diff --git a/.config/suppress.json b/.config/suppress.json new file mode 100644 index 00000000000..9be220b291e --- /dev/null +++ b/.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/.config/tsaoptions.json b/.config/tsaoptions.json new file mode 100644 index 00000000000..786ef4331a2 --- /dev/null +++ b/.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/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index af18c5ffe6f..c849a9f78e5 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -3,13 +3,14 @@ # Licensed under the MIT License. See https://go.microsoft.com/fwlink/?linkid=2090316 for license information. #------------------------------------------------------------------------------------------------------------- -FROM mcr.microsoft.com/powershell/test-deps:ubuntu-18.04 +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 diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index c7b3de62eef..eded2d1bdec 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -1,16 +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", + "name": ".NET Core 6.0, including pwsh (Ubuntu 18.04)", + "dockerFile": "Dockerfile", - // Uncomment the next line to run commands after the container is created. - "postCreateCommand": "cd src/powershell-unix && dotnet restore", + "workspaceMount": "source=${localWorkspaceFolder},target=/PowerShell,type=bind", + "workspaceFolder": "/PowerShell", - "extensions": [ - "ms-azure-devops.azure-pipelines", - "ms-dotnettools.csharp", - "ms-vscode.powershell", - "DavidAnson.vscode-markdownlint", - "vitaliymaz.vscode-svg-previewer" - ] + // 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/.devcontainer/fedora30/Dockerfile b/.devcontainer/fedora30/Dockerfile deleted file mode 100644 index ae8d15ebd54..00000000000 --- a/.devcontainer/fedora30/Dockerfile +++ /dev/null @@ -1,10 +0,0 @@ -#------------------------------------------------------------------------------------------------------------- -# 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:preview-fedora-30 - -# Configure apt and install packages -RUN dnf install -y git procps wget findutils \ - && dnf clean all diff --git a/.devcontainer/fedora30/devcontainer.json b/.devcontainer/fedora30/devcontainer.json deleted file mode 100644 index d9ef8ef5312..00000000000 --- a/.devcontainer/fedora30/devcontainer.json +++ /dev/null @@ -1,16 +0,0 @@ -// See https://aka.ms/vscode-remote/devcontainer.json for format details. -{ - "name": "Fedora 30", - "dockerFile": "Dockerfile", - - // Uncomment the next line to run commands after the container is created. - "postCreateCommand": "pwsh -c 'import-module ./build.psm1;start-psbootstrap'", - - "extensions": [ - "ms-azure-devops.azure-pipelines", - "ms-dotnettools.csharp", - "ms-vscode.powershell", - "DavidAnson.vscode-markdownlint", - "vitaliymaz.vscode-svg-previewer" - ] -} diff --git a/.editorconfig b/.editorconfig index 74496fb9a7c..57d2f6c6c3e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,6 +1,6 @@ # EditorConfig is awesome: https://EditorConfig.org # .NET coding convention settings for EditorConfig -# https://docs.microsoft.com/visualstudio/ide/editorconfig-code-style-settings-reference +# 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 @@ -21,6 +21,7 @@ indent_size = 4 # Shell scripts [*.sh] +end_of_line = lf indent_size = 4 # Xml project files @@ -43,6 +44,9 @@ indent_size = 2 [*.{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 @@ -99,6 +103,8 @@ 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 @@ -113,6 +119,17 @@ 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] diff --git a/.gitattributes b/.gitattributes index 10790ce3949..c9033dc798a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,5 +2,6 @@ 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/.github/CODEOWNERS b/.github/CODEOWNERS index 26e01101693..14569b81924 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,75 +3,66 @@ # 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: Portability -# @JamesWTruher - # Area: Security -# @TravisEz13 @PaulHigin -src/System.Management.Automation/security/wldpNativeMethods.cs @TravisEz13 @PaulHigin - -# Area: Documentation -.github/ @joeyaiello @TravisEz13 +src/System.Management.Automation/security/wldpNativeMethods.cs @TravisEz13 @seeminglyscience -# Area: Test -# @JamesWTruher @TravisEz13 @adityapatwardhan - -# Area: Cmdlets Core -# @JamesWTruher @SteveL-MSFT @anmenaga +# 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 +# src/Microsoft.PowerShell.Commands.Management/ @daxian-dbw @adityapatwardhan # Area: Utility Cmdlets -src/Microsoft.PowerShell.Commands.Utility/ @JamesWTruher @PaulHigin +# src/Microsoft.PowerShell.Commands.Utility/ # Area: Console -src/Microsoft.PowerShell.ConsoleHost/ @daxian-dbw @anmenaga @TylerLeonhardt - -# Area: Demos -demos/ @joeyaiello @SteveL-MSFT @HemantMahawar +# src/Microsoft.PowerShell.ConsoleHost/ @daxian-dbw # Area: DSC -src/System.Management.Automation/DscSupport @TravisEz13 @SteveL-MSFT +# 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/ @PaulHigin +# src/System.Management.Automation/engine/debugger/ # Area: Help -src/System.Management.Automation/help @adityapatwardhan +src/System.Management.Automation/help @adityapatwardhan @daxian-dbw # Area: Intellisense # @daxian-dbw # Area: Language -src/System.Management.Automation/engine/parser @daxian-dbw +src/System.Management.Automation/engine/parser @daxian-dbw @seeminglyscience # Area: Providers -src/System.Management.Automation/namespaces @anmenaga +# src/System.Management.Automation/namespaces # Area: Remoting -src/System.Management.Automation/engine/remoting @PaulHigin +src/System.Management.Automation/engine/remoting @daxian-dbw @TravisEz13 # Areas: Build # Must be last -*.config @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin -*.props @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin -*.yml @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin -*.csproj @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin -build.* @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin -tools/ @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin -docker/ @daxian-dbw @TravisEz13 @adityapatwardhan @anmenaga @PaulHigin +*.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 diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index d6d78e52fb7..35eab8c9b5b 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -1,47 +1,24 @@ # Contributing to PowerShell -We welcome and appreciate contributions from the community. -There are many ways to become involved with PowerShell: -including filing issues, -joining in design conversations, -writing and improving documentation, -and contributing to the code. -Please read the rest of this document to ensure a smooth contribution process. - -## Intro to Git and GitHub - -* Make sure you have a [GitHub account](https://github.com/signup/free). -* Learning Git: - * GitHub Help: [Good Resources for Learning Git and GitHub][good-git-resources] - * [Git Basics](../docs/git/basics.md): install and getting started -* [GitHub Flow Guide](https://guides.github.com/introduction/flow/): - step-by-step instructions of GitHub Flow - -## Quick Start Checklist +We welcome and appreciate contributions from the community! -* Review the [Contributor License Agreement][CLA] requirement. -* Get familiar with the [PowerShell repository](../docs/git). +There are many ways to become involved with PowerShell including: -## Contributing to Issues +- [Contributing to Documentation](#contributing-to-documentation) +- [Contributing to Issues](#contributing-to-issues) +- [Contributing to Code](#contributing-to-code) -* Review [Issue Management][issue-management]. -* Check if the issue you are going to file already exists in our [GitHub issues][open-issue]. -* 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. -* If the issue is marked as [`Up-for-Grabs`][up-for-grabs], - the PowerShell Maintainers are looking for help with the issue. -* 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. +Please read the rest of this document to ensure a smooth contribution process. ## Contributing to Documentation -### Contributing to documentation related to PowerShell +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://github.com/MicrosoftDocs/PowerShell-Docs/blob/staging/CONTRIBUTING.md). +Please see the [Contributor Guide in `MicrosoftDocs/PowerShell-Docs`](https://aka.ms/PSDocsContributor). -#### Quick steps if you're changing an existing cmdlet +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: @@ -52,70 +29,68 @@ if you don't have it - `Install-Module PlatyPS`. 1. Clone the [`MicrosoftDocs/PowerShell-Docs`](https://github.com/MicrosoftDocs/PowerShell-Docs) -repo if you don't already have it. +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 +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 ` +`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 repo with the changes that +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. -### Contributing to documentation related to maintaining or contributing to the PowerShell project +### 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 repo. +* Otherwise, these issues should be treated like any other issue in this repository. -#### Spellchecking documentation +### Spell checking documentation Documentation is spellchecked. We use the -[markdown-spellcheck](https://github.com/lukeapage/node-markdown-spellcheck) command line tool, -which can be run in interactive mode to correct typos or add words to the ignore list -(`.spelling` at the repository root). +[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 spellchecker, follow these steps: +To run the spell checker, follow these steps: * install [Node.js](https://nodejs.org/en/) (v10 or up) -* install [markdown-spellcheck](https://github.com/lukeapage/node-markdown-spellcheck) by - `npm install -g markdown-spellcheck` (v0.11.0 or up) -* run `mdspell "**/*.md" --ignore-numbers --ignore-acronyms --en-us` -* if the `.spelling` file is updated, commit and push it +* 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 +### Checking links in documentation Documentation is link-checked. We make use of the -markdown-link-check command line tool, +`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 +* install `markdown-link-check` by `npm install -g markdown-link-check@3.8.5` * run `find . \*.md -exec markdown-link-check {} \;` -## Contributing to Code - -### Code Editor - -You should use the multi-platform [Visual Studio Code (VS Code)][use-vscode-editor]. - -### Building and testing - -#### Building PowerShell - -Please see [Building PowerShell](../README.md#building-the-repository). - -#### Testing PowerShell +## Contributing to Issues -Please see PowerShell [Testing Guidelines - Running Tests Outside of CI][running-tests-outside-of-ci] on how to test your build locally. +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 @@ -136,6 +111,59 @@ Additional references: * 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 @@ -160,7 +188,7 @@ Additional references: 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-related-to-powershell). + 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. @@ -168,21 +196,21 @@ Additional references: 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 change logs, + 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". + * 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 code base + 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", + * 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], @@ -190,10 +218,10 @@ Additional references: 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-related-to-powershell) for more info.) + (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 `.h`, `.cpp`, and `.cs` files use the copyright header with empty line after it: + * For `.cs` files use the copyright header with empty line after it: ```c# // Copyright (c) Microsoft Corporation. @@ -201,7 +229,7 @@ Additional references: ``` - * For `.ps1` and `.psm1` files use the copyright header with empty line after it: + * For `.ps1` and `.psm1` files use the copyright header with empty line after it: ```powershell # Copyright (c) Microsoft Corporation. @@ -233,21 +261,13 @@ Additional references: * 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 spellchecking and link checking for markdown files. If there is any false-positive, - [run the spellchecker command line tool in interactive mode](#spellchecking-documentation) +* 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. -* Our packaging test may not pass and ask you to update `files.wxs` file if you add/remove/update nuget package references or add/remove assert files. - - You could update the file manually in accordance with messages in the test log file. Or you can use automatically generated file. To get the file you should build the msi package locally: - ```powershell - Import-Module .\build.psm1 - Start-PSBuild -Clean -CrossGen -PSModuleRestore -Runtime win7-x64 -Configuration Release -ReleaseTag - Import-Module .\tools\packaging - Start-PSPackage -Type msi -ReleaseTag -WindowsRuntime 'win7-x64' -SkipReleaseChecks - ``` - - Last command will report where new file is located. + 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 @@ -265,7 +285,7 @@ Additional references: #### Pull Request - Roles and Responsibilities -1. The PR *author* is responsible for moving the PR forward to get it Approved. +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. @@ -278,7 +298,7 @@ Additional references: - `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]. + 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. @@ -297,9 +317,9 @@ In these cases: - 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 code base or a design change), *assignee* will simply close the 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 +### Making Breaking Changes When you make code changes, please pay attention to these that can affect the [Public Contract][breaking-changes-contract]. @@ -308,12 +328,12 @@ 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 +### 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 +### Common Engineering Practices Other than the guidelines for [coding][coding-guidelines], the [RFC process][rfc-process] for design, @@ -365,7 +385,7 @@ is also appropriate, as is using Markdown syntax. Before you invest a large amount of time, file an issue and start a discussion with the community. -## Contributor License Agreement (CLA) +### 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. @@ -379,11 +399,17 @@ 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`. -[testing-guidelines]: ../docs/testing-guidelines/testing-guidelines.md +## 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 -[governance]: ../docs/community/governance.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/ @@ -395,10 +421,11 @@ Once you sign a CLA, all your existing and future pull requests will have the st [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://docs.microsoft.com/dotnet/core/tutorials/with-visual-studio-code +[use-vscode-editor]: https://learn.microsoft.com/dotnet/core/tutorials/with-visual-studio-code [repository-maintainer]: ../docs/community/governance.md#repository-maintainers -[area-expert]: ../docs/community/governance.md#area-experts +[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/.github/ISSUE_TEMPLATE/Bug_Report.md b/.github/ISSUE_TEMPLATE/Bug_Report.md deleted file mode 100644 index b8c8dabe08a..00000000000 --- a/.github/ISSUE_TEMPLATE/Bug_Report.md +++ /dev/null @@ -1,47 +0,0 @@ ---- -name: Bug report 🐛 -about: Report errors or unexpected behavior 🤔 -title: "My bug report" -labels: Needs-Triage -assignees: '' - ---- - - -## Steps to reproduce - -```powershell - -``` - -## Expected behavior - -```none - -``` - -## Actual behavior - -```none - -``` - -## Environment data - - - -```none - -``` diff --git a/.github/ISSUE_TEMPLATE/Bug_Report.yaml b/.github/ISSUE_TEMPLATE/Bug_Report.yaml new file mode 100644 index 00000000000..03fcf444e88 --- /dev/null +++ b/.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/.github/ISSUE_TEMPLATE/Distribution_Request.md b/.github/ISSUE_TEMPLATE/Distribution_Request.md deleted file mode 100644 index b104df6a1be..00000000000 --- a/.github/ISSUE_TEMPLATE/Distribution_Request.md +++ /dev/null @@ -1,39 +0,0 @@ ---- -name: Distribution Support Request -about: Requests support for a new distribution -title: "Distribution Support Request" -labels: Distribution-Request, Needs-Triage -assignees: '' - ---- - -## Details of the Distribution - -- Name of the Distribution: -- Version of the Distribution: -- Package Types - - [ ] Deb - - [ ] RPM - - [ ] Tar.gz - - Snap - Please file issue in https://github.com/powershell/powershell-snap. This issues type is unrelated to snap packages with a distribution neutral. -- Processor Architecture (One per request): -- The following is a requirement for supporting a distribution **without exception.** - - [ ] The version and architecture of the Distribution is [supported by .NET Core](https://github.com/dotnet/core/blob/master/release-notes/5.0/5.0-supported-os.md#linux). -- The following are requirements for supporting a distribution. - Please write a justification for any exception where these criteria are not met and - the PowerShell committee will review the request. - - [ ] The version of the Distribution is supported for at least one year. - - [ ] The version of the Distribution is not an [interim release](https://ubuntu.com/about/release-cycle) or equivalent. - -## Progress - -- [ ] An issues has been filed to create a Docker image in https://github.com/powershell/powershell-docker - -### For PowerShell Team **ONLY** - -- [ ] Docker image created -- [ ] Docker image published -- [ ] Distribution tested -- [ ] Update `packages.microsoft.com` deployment -- [ ] [Lifecycle](https://github.com/MicrosoftDocs/PowerShell-Docs/blob/staging/reference/docs-conceptual/PowerShell-Support-Lifecycle.md) updated -- [ ] Documentation Updated diff --git a/.github/ISSUE_TEMPLATE/Feature_Request.md b/.github/ISSUE_TEMPLATE/Feature_Request.md deleted file mode 100644 index 4ae10eb6e40..00000000000 --- a/.github/ISSUE_TEMPLATE/Feature_Request.md +++ /dev/null @@ -1,23 +0,0 @@ ---- -name: Feature Request/Idea 🚀 -about: Suggest a new feature or improvement (this does not mean you have to implement it) -title: "Feature Request" -labels: Issue-Enhancement, Needs-Triage -assignees: '' - ---- - -## Summary of the new feature/enhancement - - - -## Proposed technical implementation details (optional) - - diff --git a/.github/ISSUE_TEMPLATE/Feature_Request.yaml b/.github/ISSUE_TEMPLATE/Feature_Request.yaml new file mode 100644 index 00000000000..c8e4cec3c4d --- /dev/null +++ b/.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/.github/ISSUE_TEMPLATE/Microsoft_Update_Issue.yaml b/.github/ISSUE_TEMPLATE/Microsoft_Update_Issue.yaml new file mode 100644 index 00000000000..ce3de7ae848 --- /dev/null +++ b/.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/.github/ISSUE_TEMPLATE/Release_Process.md b/.github/ISSUE_TEMPLATE/Release_Process.md deleted file mode 100644 index 0f93a4bbb70..00000000000 --- a/.github/ISSUE_TEMPLATE/Release_Process.md +++ /dev/null @@ -1,43 +0,0 @@ ---- -name: Release Process -about: Maintainers Only - Release Process -title: "Release Process for v6.x.x" -labels: Issue-Meta, Needs-Triage -assignees: '' - ---- - - - -## Checklist - -- [ ] Verify that `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. diff --git a/.github/ISSUE_TEMPLATE/Release_Process.yaml b/.github/ISSUE_TEMPLATE/Release_Process.yaml new file mode 100644 index 00000000000..7e8d6282db1 --- /dev/null +++ b/.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/.github/ISSUE_TEMPLATE/WG_member_request.yaml b/.github/ISSUE_TEMPLATE/WG_member_request.yaml new file mode 100644 index 00000000000..1d7f0e9ba53 --- /dev/null +++ b/.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/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml index 4e050986fa5..973921cb24a 100644 --- a/.github/ISSUE_TEMPLATE/config.yml +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -1,11 +1,11 @@ blank_issues_enabled: false contact_links: - name: Windows PowerShell - url: https://windowsserver.uservoice.com/forums/301869-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 + url: https://github.com/MicrosoftDocs/PowerShell-Docs/issues/new/choose about: Please open issues on documentation for PowerShell here. diff --git a/.github/Images/Codespaces.png b/.github/Images/Codespaces.png new file mode 100644 index 00000000000..f37792f5c9f Binary files /dev/null and b/.github/Images/Codespaces.png differ diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index b64343410f7..27089847987 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,35 +11,21 @@ ## 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 + - 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 and is not [Work in Progress](https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md#pull-request---work-in-progress). - - If the PR is work in progress, please add the prefix `WIP:` or `[ WIP ]` to the beginning of the title (the `WIP` bot will keep its status check at `Pending` while the prefix is present) and remove the prefix when the PR is ready. +- [ ] 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/staging/reference/6/Microsoft.PowerShell.Core/About/about_Experimental_Features.md) - - [ ] Experimental feature name(s): + - [ ] 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: + - [ ] 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) -- **Tooling** - - [ ] I have considered the user experience from a tooling perspective and don't believe tooling will be impacted. - - **OR** - - [ ] I have considered the user experience from a tooling perspective and opened an issue in the relevant tool repository. This may include: - - [ ] Impact on [PowerShell Editor Services](https://github.com/PowerShell/PowerShellEditorServices) which is used in the [PowerShell extension](https://github.com/PowerShell/vscode-powershell) for VSCode - (which runs in a different PS Host). - - [ ] Issue filed: - - [ ] Impact on Completions (both in the console and in editors) - one of PowerShell's most powerful features. - - [ ] Issue filed: - - [ ] Impact on [PSScriptAnalyzer](https://github.com/PowerShell/PSScriptAnalyzer) (which provides linting & formatting in the editor extensions). - - [ ] Issue filed: - - [ ] Impact on [EditorSyntax](https://github.com/PowerShell/EditorSyntax) (which provides syntax highlighting with in VSCode, GitHub, and many other editors). - - [ ] Issue filed: + - [ ] 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/.github/SECURITY.md b/.github/SECURITY.md index 10633f0d6d1..797f7003851 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -1,12 +1,39 @@ -# Security Vulnerabilities + -Security issues are treated very seriously and will, by default, -takes precedence over other considerations including usability, performance, -etc... Best effort will be used to mitigate side effects of a security -change, but PowerShell must be secure by default. +## Security -## Reporting a security vulnerability +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 that there is a security vulnerability in PowerShell, -it **must** be reported to [secure@microsoft.com](https://technet.microsoft.com/security/ff852094.aspx) to allow for [Coordinated Vulnerability Disclosure](https://technet.microsoft.com/security/dn467923). -**Only** file an issue, if [secure@microsoft.com](https://www.microsoft.com/en-us/msrc/faqs-report-an-issue?rtc=1) has confirmed filing an issue is appropriate. +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/.github/SUPPORT.md b/.github/SUPPORT.md index a34d36186ed..6acedb28d27 100644 --- a/.github/SUPPORT.md +++ b/.github/SUPPORT.md @@ -5,9 +5,9 @@ If you do not see your problem captured, please file a [new issue][] and follow 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://docs.microsoft.com/powershell/scripting/powershell-support-lifecycle +[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://docs.microsoft.com/powershell/scripting/whats-new/known-issues-ps6 +[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/.github/action-filters.yml b/.github/action-filters.yml new file mode 100644 index 00000000000..9a61bc1947b --- /dev/null +++ b/.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/.github/actions/build/ci/action.yml b/.github/actions/build/ci/action.yml new file mode 100644 index 00000000000..65331fb3185 --- /dev/null +++ b/.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/.github/actions/infrastructure/get-changed-files/README.md b/.github/actions/infrastructure/get-changed-files/README.md new file mode 100644 index 00000000000..277b28c0674 --- /dev/null +++ b/.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/.github/actions/infrastructure/get-changed-files/action.yml b/.github/actions/infrastructure/get-changed-files/action.yml new file mode 100644 index 00000000000..56605fed8c9 --- /dev/null +++ b/.github/actions/infrastructure/get-changed-files/action.yml @@ -0,0 +1,130 @@ +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 }} + files_path: + description: 'Path to temp file containing the JSON array of changed file paths' + value: ${{ steps.get-files.outputs.files_path }} + 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`); + + // Write files to a temp file to avoid exceeding ARG_MAX for large PRs + const fs = require('fs'); + const path = require('path'); + const tempDir = process.env.RUNNER_TEMP || '/tmp'; + const tempFile = path.join(tempDir, 'changed-files.json'); + fs.writeFileSync(tempFile, JSON.stringify(changedFiles)); + console.log(`File list written to ${tempFile}`); + + core.setOutput('files', JSON.stringify(changedFiles)); + core.setOutput('files_path', tempFile); + core.setOutput('count', changedFiles.length); + +branding: + icon: 'file-text' + color: 'blue' diff --git a/.github/actions/infrastructure/markdownlinks/Parse-MarkdownLink.ps1 b/.github/actions/infrastructure/markdownlinks/Parse-MarkdownLink.ps1 new file mode 100644 index 00000000000..a56d696eb6e --- /dev/null +++ b/.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/.github/actions/infrastructure/markdownlinks/README.md b/.github/actions/infrastructure/markdownlinks/README.md new file mode 100644 index 00000000000..e566ec2bcc3 --- /dev/null +++ b/.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/.github/actions/infrastructure/markdownlinks/Verify-MarkdownLinks.ps1 b/.github/actions/infrastructure/markdownlinks/Verify-MarkdownLinks.ps1 new file mode 100644 index 00000000000..f50ab1590b9 --- /dev/null +++ b/.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/.github/actions/infrastructure/markdownlinks/action.yml b/.github/actions/infrastructure/markdownlinks/action.yml new file mode 100644 index 00000000000..a97bacfca47 --- /dev/null +++ b/.github/actions/infrastructure/markdownlinks/action.yml @@ -0,0 +1,114 @@ +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_PATH: ${{ steps.changed-files.outputs.files_path }} + run: | + Write-Host "Starting markdown link verification..." -ForegroundColor Cyan + + # Read changed markdown files from temp file to avoid ARG_MAX limits with large PRs + $changedFilesPath = $env:CHANGED_FILES_PATH + if ($changedFilesPath -and (Test-Path $changedFilesPath)) { + $changedFiles = @(Get-Content $changedFilesPath -Raw | ConvertFrom-Json) + } else { + $changedFiles = @() + } + + 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/.github/actions/infrastructure/merge-conflict-checker/README.md b/.github/actions/infrastructure/merge-conflict-checker/README.md new file mode 100644 index 00000000000..b53d6f99964 --- /dev/null +++ b/.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/.github/actions/infrastructure/merge-conflict-checker/action.yml b/.github/actions/infrastructure/merge-conflict-checker/action.yml new file mode 100644 index 00000000000..af76641628e --- /dev/null +++ b/.github/actions/infrastructure/merge-conflict-checker/action.yml @@ -0,0 +1,40 @@ +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_PATH: ${{ steps.changed-files.outputs.files_path }} + run: | + # Read changed files from temp file to avoid ARG_MAX limits with large PRs + $changedFilesPath = $env:CHANGED_FILES_PATH + if ($changedFilesPath -and (Test-Path $changedFilesPath)) { + $changedFiles = @(Get-Content $changedFilesPath -Raw | ConvertFrom-Json) + } else { + $changedFiles = @() + } + + # 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/.github/actions/infrastructure/path-filters/action.yml b/.github/actions/infrastructure/path-filters/action.yml new file mode 100644 index 00000000000..b50384f698d --- /dev/null +++ b/.github/actions/infrastructure/path-filters/action.yml @@ -0,0 +1,144 @@ +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_PATH: ${{ steps.get-files.outputs.files_path }} + 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; + } + + // Read files from temp file to avoid ARG_MAX limits with large PRs + const fs = require('fs'); + const filesPath = process.env.FILES_PATH; + let files = []; + if (filesPath && fs.existsSync(filesPath)) { + files = JSON.parse(fs.readFileSync(filesPath, 'utf8')); + } else { + console.log('Warning: files_path not found, no files to analyze'); + } + + // 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/.github/actions/test/linux-packaging/action.yml b/.github/actions/test/linux-packaging/action.yml new file mode 100644 index 00000000000..ce37a38c8b7 --- /dev/null +++ b/.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/.github/actions/test/nix/action.yml b/.github/actions/test/nix/action.yml new file mode 100644 index 00000000000..ab30e0d9ce6 --- /dev/null +++ b/.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/.github/actions/test/process-pester-results/action.yml b/.github/actions/test/process-pester-results/action.yml new file mode 100644 index 00000000000..44f2037626f --- /dev/null +++ b/.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/.github/actions/test/process-pester-results/process-pester-results.ps1 b/.github/actions/test/process-pester-results/process-pester-results.ps1 new file mode 100644 index 00000000000..5804bec9a94 --- /dev/null +++ b/.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/.github/actions/test/windows/action.yml b/.github/actions/test/windows/action.yml new file mode 100644 index 00000000000..ddc5da4d664 --- /dev/null +++ b/.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/.github/agents/SplitADOPipelines.agent.md b/.github/agents/SplitADOPipelines.agent.md new file mode 100644 index 00000000000..9454670061f --- /dev/null +++ b/.github/agents/SplitADOPipelines.agent.md @@ -0,0 +1,180 @@ +--- +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. + +## Template Reference Convention (MUST follow) + +All `- template:` references to files **inside this repo** must use the **absolute** form anchored at the repo root, with the `@self` suffix: + +```yaml +- template: /.pipelines/templates//.yml@self +``` + +Do **not** use relative paths such as `templates/...`, `../templates/...`, or bare filenames. Rationale: + +- Absolute paths resolve identically regardless of where the referring file lives, so moving a pipeline file between directories (for example, into `.pipelines/NonOfficial/`) does not silently break includes. +- Relative paths are resolved by Azure DevOps against the directory of the referring file, which has caused real outages in this repo when a relative include was composed into a nonexistent nested path like `.pipelines/templates/stages/.pipelines/templates/...`. +- The majority of existing includes already use the absolute form; keeping new work consistent reduces review burden. + +The only acceptable non-absolute references are to external repositories resolved via the `resources.repositories` block, for example `v2/OneBranch.Official.CrossPlat.yml@onebranchTemplates`. + +## Refactoring Steps + +### Step 1: Extract Shared Templates + +For each pipeline file that uses the toggle switch pattern (e.g., `PowerShell-Packages-Official.yml`): + +1. Create the `.pipelines/templates/variables` and `.pipelines/templates/stages` directories if they don't exist +2. Extract the **variables section** into `.pipelines/templates/variables/PowerShell-Packages-Variables.yml` +3. Extract the **stages section** into `.pipelines/templates/stages/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-Official.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: /.pipelines/templates/variables/PowerShell-Packages-Variables.yml@self + ``` +5. Replace the `stages:` section with a template reference: + ```yaml + stages: + - template: /.pipelines/templates/stages/PowerShell-Packages-Stages.yml@self + ``` + +### 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: /.pipelines/templates/variables/PowerShell-Packages-Variables.yml@self + + stages: + - template: /.pipelines/templates/stages/PowerShell-Packages-Stages.yml@self + ``` + +**Note**: Always use **absolute** template paths of the form `/.pipelines/templates/...@self`. Do not use relative paths like `templates/...` or `../templates/...`. Absolute paths are anchored at the repo root and resolve consistently from any referring file, preventing breakage when files are moved between directories. + +### 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-Official.yml`): + +```yaml +stages: + - template: /.pipelines/templates/stages/PowerShell-Packages-Stages.yml@self + parameters: + ob_release_environment: Production +``` + +#### NonOfficial Pipeline Configuration + +In the NonOfficial pipeline (e.g., `.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml`): + +```yaml +stages: + - template: /.pipelines/templates/stages/PowerShell-Packages-Stages.yml@self + parameters: + ob_release_environment: Test +``` + +#### Update Stages Template to Accept Parameter + +The extracted stages template (e.g., `.pipelines/templates/stages/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/.github/chatmodes/cherry-pick-commits.chatmode.md b/.github/chatmodes/cherry-pick-commits.chatmode.md new file mode 100644 index 00000000000..826ab11d56c --- /dev/null +++ b/.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/.github/dependabot.yml b/.github/dependabot.yml index 38a493b7f36..45d2e8fe928 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,53 +1,32 @@ version: 2 updates: - - package-ecosystem: "nuget" + - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" labels: - "CL-BuildPackaging" - ignore: - - dependency-name: "System.*" - - dependency-name: "Microsoft.Win32.Registry.AccessControl" - - dependency-name: "Microsoft.Windows.Compatibility" - - package-ecosystem: "nuget" - directory: "/tools/packaging/projects/reference/Microsoft.PowerShell.Commands.Utility" - schedule: - interval: "daily" - labels: - - "CL-BuildPackaging" - ignore: - - dependency-name: "System.*" - - dependency-name: "Microsoft.Win32.Registry.AccessControl" - - dependency-name: "Microsoft.Windows.Compatibility" - - - package-ecosystem: "nuget" - directory: "/tools/packaging/projects/reference/System.Management.Automation" + - package-ecosystem: "github-actions" + directory: "/" + target-branch: "release/*" schedule: interval: "daily" labels: - "CL-BuildPackaging" - ignore: - - dependency-name: "System.*" - - dependency-name: "Microsoft.Win32.Registry.AccessControl" - - dependency-name: "Microsoft.Windows.Compatibility" - - package-ecosystem: "nuget" - directory: "/test/tools/Modules" + - package-ecosystem: "docker" + directory: / schedule: - interval: "daily" + interval: daily labels: - "CL-BuildPackaging" - ignore: - - dependency-name: "System.*" - - dependency-name: "Microsoft.Win32.Registry.AccessControl" - - dependency-name: "Microsoft.Windows.Compatibility" - - package-ecosystem: "nuget" - directory: "/src/Modules" + - package-ecosystem: "docker" + directory: "/" + target-branch: "release/*" schedule: - interval: "daily" + interval: daily labels: - "CL-BuildPackaging" diff --git a/.github/instructions/build-and-packaging-steps.instructions.md b/.github/instructions/build-and-packaging-steps.instructions.md new file mode 100644 index 00000000000..934b1539593 --- /dev/null +++ b/.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/.github/instructions/build-checkout-prerequisites.instructions.md b/.github/instructions/build-checkout-prerequisites.instructions.md new file mode 100644 index 00000000000..717aa6faa36 --- /dev/null +++ b/.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/.github/instructions/build-configuration-guide.instructions.md b/.github/instructions/build-configuration-guide.instructions.md new file mode 100644 index 00000000000..d0384f4f307 --- /dev/null +++ b/.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/.github/instructions/code-review-branch-strategy.instructions.md b/.github/instructions/code-review-branch-strategy.instructions.md new file mode 100644 index 00000000000..191a677b912 --- /dev/null +++ b/.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/.github/instructions/instruction-file-format.instructions.md b/.github/instructions/instruction-file-format.instructions.md new file mode 100644 index 00000000000..7c4e0bdd13d --- /dev/null +++ b/.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/.github/instructions/log-grouping-guidelines.instructions.md b/.github/instructions/log-grouping-guidelines.instructions.md new file mode 100644 index 00000000000..ff845db4e4b --- /dev/null +++ b/.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/.github/instructions/onebranch-condition-syntax.instructions.md b/.github/instructions/onebranch-condition-syntax.instructions.md new file mode 100644 index 00000000000..19bf331d9c3 --- /dev/null +++ b/.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/.github/instructions/onebranch-restore-phase-pattern.instructions.md b/.github/instructions/onebranch-restore-phase-pattern.instructions.md new file mode 100644 index 00000000000..0945bb47c0b --- /dev/null +++ b/.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/.github/instructions/onebranch-signing-configuration.instructions.md b/.github/instructions/onebranch-signing-configuration.instructions.md new file mode 100644 index 00000000000..747fcaffdd6 --- /dev/null +++ b/.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/.github/instructions/pester-set-itresult-pattern.instructions.md b/.github/instructions/pester-set-itresult-pattern.instructions.md new file mode 100644 index 00000000000..33a73ca081d --- /dev/null +++ b/.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/.github/instructions/pester-test-status-and-working-meaning.instructions.md b/.github/instructions/pester-test-status-and-working-meaning.instructions.md new file mode 100644 index 00000000000..d2b28a05f18 --- /dev/null +++ b/.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/.github/instructions/powershell-automatic-variables.instructions.md b/.github/instructions/powershell-automatic-variables.instructions.md new file mode 100644 index 00000000000..5015847f41f --- /dev/null +++ b/.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/.github/instructions/powershell-module-organization.instructions.md b/.github/instructions/powershell-module-organization.instructions.md new file mode 100644 index 00000000000..9cdba06c364 --- /dev/null +++ b/.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/.github/instructions/powershell-parameter-naming.instructions.md b/.github/instructions/powershell-parameter-naming.instructions.md new file mode 100644 index 00000000000..155fd1a85c3 --- /dev/null +++ b/.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/.github/instructions/publishing-pester-result.instructions.md b/.github/instructions/publishing-pester-result.instructions.md new file mode 100644 index 00000000000..49010e65a99 --- /dev/null +++ b/.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/.github/instructions/script-module-file-format.instructions.md b/.github/instructions/script-module-file-format.instructions.md new file mode 100644 index 00000000000..922e0d4aa31 --- /dev/null +++ b/.github/instructions/script-module-file-format.instructions.md @@ -0,0 +1,27 @@ +--- +applyTo: + - "**/*.ps1" + - "**/*.psm1" +--- + +# Script and Module File Format + +These instructions define required file-level formatting for PowerShell scripts and module files in this repository. + +## Copyright Header + +If a change adds a new `.ps1` file or `.psm1` file or touches an existing one, the file should start with the copyright and license header and have an empty line after it, as shown in the example below: + +```powershell +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +``` + +Do not place blank lines, comments, or code before this header. + +## Requirements + +- Add the copyright header when creating a new `.ps1` or `.psm1` file. +- Preserve the header when editing an existing `.ps1` or `.psm1` file. +- If an existing `.ps1` or `.psm1` file is missing the header, only modify that file to add the header if a change touches that file. Do not make a change to add the header if the file is not being modified. diff --git a/.github/instructions/start-native-execution.instructions.md b/.github/instructions/start-native-execution.instructions.md new file mode 100644 index 00000000000..347e496b3bf --- /dev/null +++ b/.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/.github/instructions/start-psbuild-basics.instructions.md b/.github/instructions/start-psbuild-basics.instructions.md new file mode 100644 index 00000000000..18a0026eb2d --- /dev/null +++ b/.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/.github/instructions/troubleshooting-builds.instructions.md b/.github/instructions/troubleshooting-builds.instructions.md new file mode 100644 index 00000000000..e9b60cb8c80 --- /dev/null +++ b/.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/.github/policies/IssueManagement.CloseResolutions.yml b/.github/policies/IssueManagement.CloseResolutions.yml new file mode 100644 index 00000000000..23ab9422e1a --- /dev/null +++ b/.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/.github/policies/IssueManagement.ResolveStale.yml b/.github/policies/IssueManagement.ResolveStale.yml new file mode 100644 index 00000000000..fd254715ea9 --- /dev/null +++ b/.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/.github/policies/PRManagement.yml b/.github/policies/PRManagement.yml new file mode 100644 index 00000000000..9deaf0262bb --- /dev/null +++ b/.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/.github/policies/labelAdded.approvedLowRisk.yml b/.github/policies/labelAdded.approvedLowRisk.yml new file mode 100644 index 00000000000..bdeea5265a0 --- /dev/null +++ b/.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/.github/policies/labelAdded.clBuildPackaging.addBackportConsider.yml b/.github/policies/labelAdded.clBuildPackaging.addBackportConsider.yml new file mode 100644 index 00000000000..78edc18cb1a --- /dev/null +++ b/.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/.github/prompts/backport-pr-to-release-branch.prompt.md b/.github/prompts/backport-pr-to-release-branch.prompt.md new file mode 100644 index 00000000000..32bff10bd5e --- /dev/null +++ b/.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/.github/prquantifier.yaml b/.github/prquantifier.yaml new file mode 100644 index 00000000000..ea891ba4988 --- /dev/null +++ b/.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/.github/skills/analyze-pester-failures/SKILL.md b/.github/skills/analyze-pester-failures/SKILL.md new file mode 100644 index 00000000000..ec1b0fe82ec --- /dev/null +++ b/.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/.github/skills/analyze-pester-failures/references/stack-trace-parsing.md b/.github/skills/analyze-pester-failures/references/stack-trace-parsing.md new file mode 100644 index 00000000000..707f45560a9 --- /dev/null +++ b/.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/.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 b/.github/skills/analyze-pester-failures/scripts/analyze-pr-test-failures.ps1 new file mode 100644 index 00000000000..12486596071 --- /dev/null +++ b/.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/.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 b/.github/workflows/GHWorkflowHelper/GHWorkflowHelper.psm1 new file mode 100644 index 00000000000..f0524ce6f23 --- /dev/null +++ b/.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/.github/workflows/analyze-reusable.yml b/.github/workflows/analyze-reusable.yml new file mode 100644 index 00000000000..3ef564eba90 --- /dev/null +++ b/.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@68bde559dea0fdcac2102bfdf6230c5f70eb485e # 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@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v3.29.5 diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index a3719e2d90f..00000000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,62 +0,0 @@ -name: "CodeQL" - -on: - push: - branches: [master] - pull_request: - # The branches below must be a subset of the branches above - branches: [master] - -defaults: - run: - shell: pwsh - -env: - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-16.04 - - 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@v2 - with: - fetch-depth: '0' - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - 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: | - Get-ChildItem -Path env: - name: Capture Environment - - - run: | - Import-Module .\tools\ci.psm1 - Invoke-CIInstall -SkipUser - name: Bootstrap - - - run: | - Import-Module .\tools\ci.psm1 - Invoke-CIBuild - name: Build - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/copilot-setup-steps.yml b/.github/workflows/copilot-setup-steps.yml new file mode 100644 index 00000000000..d78e745a4a9 --- /dev/null +++ b/.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/.github/workflows/daily.yml b/.github/workflows/daily.yml deleted file mode 100644 index 1535fced837..00000000000 --- a/.github/workflows/daily.yml +++ /dev/null @@ -1,56 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT license. - -name: PowerShell Daily -on: - workflow_dispatch: - schedule: - # At 13:00 UTC every day. - - cron: '0 13 * * *' - -defaults: - run: - shell: pwsh - -env: - DOTNET_CLI_TELEMETRY_OPTOUT: 1 - POWERSHELL_TELEMETRY_OPTOUT: 1 - -jobs: - update-dotnet-preview: - name: Update .NET preview - timeout-minutes: 15 - runs-on: windows-latest - if: github.repository == 'PowerShell/PowerShell' - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Sync tags - run: | - git fetch --prune --unshallow --tags - - name: Execute Update .NET script - run: | - $currentVersion = (Get-Content .\global.json | ConvertFrom-Json).sdk.version - Write-Verbose "OLD_VERSION=$currentVersion" -Verbose - "OLD_VERSION=$currentVersion" | Out-File $env:GITHUB_ENV -Append - - ./tools/UpdateDotnetRuntime.ps1 -UpdateMSIPackaging - $newVersion = (Get-Content .\global.json | ConvertFrom-Json).sdk.version - Write-Verbose "NEW_VERSION=$newVersion" -Verbose - "NEW_VERSION=$newVersion" | Out-File $env:GITHUB_ENV -Append - - if ($currentVersion -ne $newVersion) { - Write-Verbose "CREATE_PR=true" -Verbose - "CREATE_PR=true" | Out-File $env:GITHUB_ENV -Append - } - - name: Create Pull Request - uses: peter-evans/create-pull-request@v2 - id: cpr - if: env.CREATE_PR == 'true' - with: - commit-message: "Update .NET SDK version from `${{ env.OLD_VERSION }}` to `${{ env.NEW_VERSION }}`" - title: "Update .NET SDK version from `${{ env.OLD_VERSION }}` to `${{ env.NEW_VERSION }}`" - base: master - branch: dotnet_update - - diff --git a/.github/workflows/dependency-review.yml b/.github/workflows/dependency-review.yml new file mode 100644 index 00000000000..84f0b03fa32 --- /dev/null +++ b/.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@a1d282b36b6f3519aa1f3fc636f609c47dddb294 # v5.0.0 diff --git a/.github/workflows/labels.yml b/.github/workflows/labels.yml new file mode 100644 index 00000000000..27ceac59bbd --- /dev/null +++ b/.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/.github/workflows/linux-ci.yml b/.github/workflows/linux-ci.yml new file mode 100644 index 00000000000..3277b8a0c17 --- /dev/null +++ b/.github/workflows/linux-ci.yml @@ -0,0 +1,264 @@ +name: Linux-CI + +run-name: "${{ github.ref_name }} - ${{ github.run_number }}" + +on: + workflow_dispatch: + + push: + branches: + - master + - release/** + - github-mirror + - "servicing-*" + paths: + - "**" + - "*" + - ".globalconfig" + - "!.github/ISSUE_TEMPLATE/**" + - "!.dependabot/config.yml" + - "!.pipelines/**" + - "!test/perf/**" + pull_request: + branches: + - master + - release/** + - github-mirror + - "servicing-*" + - "*-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/.github/workflows/macos-ci.yml b/.github/workflows/macos-ci.yml new file mode 100644 index 00000000000..f89ce8caa83 --- /dev/null +++ b/.github/workflows/macos-ci.yml @@ -0,0 +1,250 @@ +name: macOS-CI + +run-name: "${{ github.ref_name }} - ${{ github.run_number }}" + +on: + push: + branches: + - master + - release/** + - github-mirror + - "servicing-*" + paths: + - "**" + - "*" + - ".globalconfig" + - "!.github/ISSUE_TEMPLATE/**" + - "!.dependabot/config.yml" + - "!.pipelines/**" + - "!test/perf/**" + pull_request: + branches: + - master + - release/** + - github-mirror + - "servicing-*" + - "*-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/.github/workflows/markdown-link/config.json b/.github/workflows/markdown-link/config.json new file mode 100644 index 00000000000..87d65922a91 --- /dev/null +++ b/.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/.github/workflows/scorecards.yml b/.github/workflows/scorecards.yml new file mode 100644 index 00000000000..935c8ff93bb --- /dev/null +++ b/.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@68bde559dea0fdcac2102bfdf6230c5f70eb485e # v3.29.5 + with: + sarif_file: results.sarif diff --git a/.github/workflows/verify-markdown-links.yml b/.github/workflows/verify-markdown-links.yml new file mode 100644 index 00000000000..19da648a959 --- /dev/null +++ b/.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/.github/workflows/windows-ci.yml b/.github/workflows/windows-ci.yml new file mode 100644 index 00000000000..42347d2e12f --- /dev/null +++ b/.github/workflows/windows-ci.yml @@ -0,0 +1,196 @@ +name: Windows-CI +on: + workflow_dispatch: + push: + branches: + - master + - release/** + - github-mirror + - "servicing-*" + paths: + - "**" + - "*" + - ".globalconfig" + - "!.vsts-ci/misc-analysis.yml" + - "!.github/ISSUE_TEMPLATE/**" + - "!.dependabot/config.yml" + - "!test/perf/**" + - "!.pipelines/**" + pull_request: + branches: + - master + - release/** + - github-mirror + - "servicing-*" + - "*-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/.github/workflows/windows-packaging-reusable.yml b/.github/workflows/windows-packaging-reusable.yml new file mode 100644 index 00000000000..8d0255d4443 --- /dev/null +++ b/.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/.github/workflows/xunit-tests.yml b/.github/workflows/xunit-tests.yml new file mode 100644 index 00000000000..c643917edd0 --- /dev/null +++ b/.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/.gitignore b/.gitignore index fb19bcffa77..48556cf1b8c 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ project.lock.json # dotnet cli install/uninstall scripts dotnet-install.ps1 dotnet-install.sh +dotnet-install.sh.* dotnet-uninstall-pkgs.sh dotnet-uninstall-debian-packages.sh @@ -82,6 +83,9 @@ TestsResults*.xml ParallelXUnitResults.xml xUnitResults.xml +# Attack Surface Analyzer results +asa-results/ + # Resharper settings PowerShell.sln.DotSettings.user *.msp @@ -89,3 +93,34 @@ 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/.globalconfig b/.globalconfig index e5cb35160fb..e0dd4ccb9e5 100644 --- a/.globalconfig +++ b/.globalconfig @@ -1,1554 +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 +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 +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 +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 -dotnet_diagnostic.CA1043.severity = none +# 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 = private, internal +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 -dotnet_diagnostic.CA1067.severity = suggestion +# # 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 -dotnet_diagnostic.CA1200.severity = silent +# 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 -dotnet_diagnostic.CA1401.severity = suggestion +# 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 -dotnet_diagnostic.CA1812.severity = none +# 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 +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 -dotnet_diagnostic.CA2243.severity = none +# 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 +# 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 -dotnet_diagnostic.IDE0019.severity = silent +# 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 -dotnet_diagnostic.IDE0029.severity = silent +# https://learn.microsoft.com/dotnet/fundamentals/code-analysis/style-rules/ide0029 +dotnet_diagnostic.IDE0029.severity = warning # IDE0030: UseCoalesceExpressionForNullable -dotnet_diagnostic.IDE0030.severity = silent +# 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 -dotnet_diagnostic.IDE0044.severity = silent +# 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 -dotnet_diagnostic.IDE0049.severity = silent +# 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 -# IDE0067: DisposeObjectsBeforeLosingScope -dotnet_diagnostic.IDE0067.severity = silent - -# IDE0068: UseRecommendedDisposePattern -dotnet_diagnostic.IDE0068.severity = silent - -# IDE0069: DisposableFieldsShouldBeDisposed -dotnet_diagnostic.IDE0069.severity = silent - # IDE0070: UseSystemHashCode -dotnet_diagnostic.IDE0070.severity = silent +# 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 -dotnet_diagnostic.IDE0080.severity = silent +# 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 -dotnet_diagnostic.SA1001.severity = none +# 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 -dotnet_diagnostic.SA1008.severity = none +# 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 -dotnet_diagnostic.SA1206.severity = none +# 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/.mailmap b/.mailmap new file mode 100644 index 00000000000..0bc786ac445 --- /dev/null +++ b/.mailmap @@ -0,0 +1 @@ +Andy Jordan diff --git a/.markdownlintignore b/.markdownlintignore new file mode 100644 index 00000000000..1d3c5b1ac92 --- /dev/null +++ b/.markdownlintignore @@ -0,0 +1 @@ +.github/SECURITY.md diff --git a/.pipelines/EV2Specs/ServiceGroupRoot/RolloutSpec.json b/.pipelines/EV2Specs/ServiceGroupRoot/RolloutSpec.json new file mode 100644 index 00000000000..9ed971068cc --- /dev/null +++ b/.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/.pipelines/EV2Specs/ServiceGroupRoot/ScopeBindings.json b/.pipelines/EV2Specs/ServiceGroupRoot/ScopeBindings.json new file mode 100644 index 00000000000..c3a98555867 --- /dev/null +++ b/.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/.pipelines/EV2Specs/ServiceGroupRoot/ServiceModel.json b/.pipelines/EV2Specs/ServiceGroupRoot/ServiceModel.json new file mode 100644 index 00000000000..ce974fe69e5 --- /dev/null +++ b/.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/.pipelines/EV2Specs/ServiceGroupRoot/Shell/Run/Run.ps1 b/.pipelines/EV2Specs/ServiceGroupRoot/Shell/Run/Run.ps1 new file mode 100644 index 00000000000..6797ff94575 --- /dev/null +++ b/.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/.pipelines/EV2Specs/ServiceGroupRoot/UploadLinux.Rollout.json b/.pipelines/EV2Specs/ServiceGroupRoot/UploadLinux.Rollout.json new file mode 100644 index 00000000000..d7c75c2e216 --- /dev/null +++ b/.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/.pipelines/EV2Specs/ServiceGroupRoot/buildVer.txt b/.pipelines/EV2Specs/ServiceGroupRoot/buildVer.txt new file mode 100644 index 00000000000..7dea76edb3d --- /dev/null +++ b/.pipelines/EV2Specs/ServiceGroupRoot/buildVer.txt @@ -0,0 +1 @@ +1.0.1 diff --git a/.pipelines/MSIXBundle-vPack-Official.yml b/.pipelines/MSIXBundle-vPack-Official.yml new file mode 100644 index 00000000000..2461d3cd310 --- /dev/null +++ b/.pipelines/MSIXBundle-vPack-Official.yml @@ -0,0 +1,414 @@ +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" + } + 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 + + $metadata = Get-Content "$repoRoot\tools\metadata.json" -Raw | ConvertFrom-Json + Write-Verbose -Verbose "metadata:" + $metadata | Out-String | Write-Verbose -Verbose + + $publishLTS = $metadata.LTSRelease.PublishToChannels + $publishStable = $metadata.StableRelease.PublishToChannels + + Write-Verbose -Verbose "Publish LTS: $publishLTS" + Write-Verbose -Verbose "Publish Stable: $publishStable" + + if (-not $publishLTS -and -not $publishStable) { + throw "metadata.json indicates no channels to publish to." + } + + ## 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:$publishLTS + + if ($publishLTS -and $publishStable) { + $enabledChannels = "LTS,Stable" + Write-Verbose -Verbose "Publish to both LTS and Stable channels. Building additional Stable MSIX." + Start-PSPackage -Type msix -SkipReleaseChecks -WindowsRuntime $runtime -ReleaseTag $(ReleaseTagVar) -PackageBinPath $signedFilesPath + } + + $msixPkgNameFilter = "PowerShell*.msix" + $msixPkgFile = Get-ChildItem -Path $repoRoot -Filter $msixPkgNameFilter -Recurse -File | ForEach-Object FullName + Write-Verbose -Verbose "Unsigned msix package(s): $msixPkgFile" + + $pkgDir = '$(ob_outputDirectory)\pkgs' + $null = New-Item -ItemType Directory -Path $pkgDir -Force + Copy-Item -Path $msixPkgFile -Destination $pkgDir -Force -Verbose + + if (-not $enabledChannels) { + $enabledChannels = $publishLTS ? 'LTS' : ($publishStable ? 'Stable' : 'None') + } + + ## Create an output variable for the enabled channels so that downstream stages can use it. + $vstsCommandString = "vso[task.setvariable variable=EnabledChannels;isOutput=true]$enabledChannels" + Write-Host ("sending " + $vstsCommandString) + Write-Host "##$vstsCommandString" + name: BuildMSIXPackage + displayName: 'Build MSIX Package (Unsigned)' + + ### END OF Packaging ### + + - pwsh: | + Get-ChildItem -Path '$(ob_outputDirectory)\pkgs' -Recurse + displayName: 'List Unsigned Package' + + - pwsh: | + $signedFilesPath = '$(ob_outputDirectory)\Signed-$(Runtime)' + Remove-Item -Path $signedFilesPath -Recurse -Force -Verbose + displayName: 'Remove Signed-$(Runtime) folder' + + - stage: Pack_MSIXBundle_And_Sign + displayName: 'Pack and sign MSIXBundle' + dependsOn: [Build_MSIX_Package] + + variables: + EnabledChannels: $[ stageDependencies.Build_MSIX_Package.Build.outputs['x64.BuildMSIXPackage.EnabledChannels'] ] + + jobs: + - template: /.pipelines/templates/create-msixbundle-vpack.yml@self + parameters: + Channel: 'LTS' + createVPack: ${{ parameters.createVPack }} + + - template: /.pipelines/templates/create-msixbundle-vpack.yml@self + parameters: + Channel: 'Stable' + createVPack: ${{ parameters.createVPack }} + + - 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/.pipelines/NonOfficial/PowerShell-Coordinated_Packages-NonOfficial.yml b/.pipelines/NonOfficial/PowerShell-Coordinated_Packages-NonOfficial.yml new file mode 100644 index 00000000000..2ffa0b94513 --- /dev/null +++ b/.pipelines/NonOfficial/PowerShell-Coordinated_Packages-NonOfficial.yml @@ -0,0 +1,123 @@ +trigger: none + +parameters: + - name: InternalSDKBlobURL + displayName: URL to the blob having internal .NET SDK + type: string + default: ' ' + - name: EarlyAccessFeed + displayName: Early Access Feed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - 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: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + +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 }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + +extends: + template: v2/OneBranch.NonOfficial.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: /.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 + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} diff --git a/.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml b/.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml new file mode 100644 index 00000000000..29d209df7bb --- /dev/null +++ b/.pipelines/NonOfficial/PowerShell-Packages-NonOfficial.yml @@ -0,0 +1,122 @@ +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: IsEarlyAccess + type: boolean + default: false + - name: EarlyAccessFeed + displayName: Early Access Feed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + +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 }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + +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 + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} diff --git a/.pipelines/NonOfficial/PowerShell-Release-Azure-NonOfficial.yml b/.pipelines/NonOfficial/PowerShell-Release-Azure-NonOfficial.yml new file mode 100644 index 00000000000..b0bb4d79b39 --- /dev/null +++ b/.pipelines/NonOfficial/PowerShell-Release-Azure-NonOfficial.yml @@ -0,0 +1,82 @@ +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: $(Build.SourcesDirectory)\.config\tsaoptions.json + stages: + - template: /.pipelines/templates/release-prep-for-ev2.yml@self + parameters: + skipPublish: ${{ parameters.skipPublish }} + + # NonOfficial: run the publish stage to verify templateContext artifact download, + # but skip the actual Ev2 push to PMC. + - template: /.pipelines/templates/release-publish-pmc.yml@self + parameters: + releaseEnvironment: Test + stagePrefix: Test + skipEv2Push: true diff --git a/.pipelines/NonOfficial/PowerShell-Release-NonOfficial.yml b/.pipelines/NonOfficial/PowerShell-Release-NonOfficial.yml new file mode 100644 index 00000000000..fb1c5af40e2 --- /dev/null +++ b/.pipelines/NonOfficial/PowerShell-Release-NonOfficial.yml @@ -0,0 +1,128 @@ +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: EarlyAccessFeed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + +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 }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} diff --git a/.pipelines/NonOfficial/PowerShell-vPack-NonOfficial.yml b/.pipelines/NonOfficial/PowerShell-vPack-NonOfficial.yml new file mode 100644 index 00000000000..071db02cff8 --- /dev/null +++ b/.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/.pipelines/PowerShell-Coordinated_Packages-Official.yml b/.pipelines/PowerShell-Coordinated_Packages-Official.yml new file mode 100644 index 00000000000..6d41528af66 --- /dev/null +++ b/.pipelines/PowerShell-Coordinated_Packages-Official.yml @@ -0,0 +1,124 @@ +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: IsEarlyAccess + type: boolean + default: false + - name: EarlyAccessFeed + displayName: Early Access Feed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + +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 }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + +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 + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + diff --git a/.pipelines/PowerShell-Packages-Official.yml b/.pipelines/PowerShell-Packages-Official.yml new file mode 100644 index 00000000000..7cade8188a0 --- /dev/null +++ b/.pipelines/PowerShell-Packages-Official.yml @@ -0,0 +1,123 @@ +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: IsEarlyAccess + type: boolean + default: false + - name: EarlyAccessFeed + displayName: Early Access Feed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + +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 }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + +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 + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + diff --git a/.pipelines/PowerShell-Release-Official-Azure.yml b/.pipelines/PowerShell-Release-Official-Azure.yml new file mode 100644 index 00000000000..b5f57438925 --- /dev/null +++ b/.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: $(Build.SourcesDirectory)\.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/.pipelines/PowerShell-Release-Official.yml b/.pipelines/PowerShell-Release-Official.yml new file mode 100644 index 00000000000..0f403b6e7d3 --- /dev/null +++ b/.pipelines/PowerShell-Release-Official.yml @@ -0,0 +1,124 @@ +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: EarlyAccessFeed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + +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 }} + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} diff --git a/.pipelines/PowerShell-vPack-Official.yml b/.pipelines/PowerShell-vPack-Official.yml new file mode 100644 index 00000000000..13087fbbf65 --- /dev/null +++ b/.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/.pipelines/apiscan-gen-notice.yml b/.pipelines/apiscan-gen-notice.yml new file mode 100644 index 00000000000..df5ebaac091 --- /dev/null +++ b/.pipelines/apiscan-gen-notice.yml @@ -0,0 +1,111 @@ +# 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 + +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: [] diff --git a/.pipelines/store/PDP/PDP-Media/en-US/.gitkeep b/.pipelines/store/PDP/PDP-Media/en-US/.gitkeep new file mode 100644 index 00000000000..e69de29bb2d diff --git a/.pipelines/store/PDP/PDP/en-US/PDP.xml b/.pipelines/store/PDP/PDP/en-US/PDP.xml new file mode 100644 index 00000000000..ce36a3677f7 --- /dev/null +++ b/.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/.pipelines/store/SBConfig.json b/.pipelines/store/SBConfig.json new file mode 100644 index 00000000000..a52d60b045f --- /dev/null +++ b/.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/.pipelines/templates/SetVersionVariables.yml b/.pipelines/templates/SetVersionVariables.yml new file mode 100644 index 00000000000..30ed1704022 --- /dev/null +++ b/.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/.pipelines/templates/approvalJob.yml b/.pipelines/templates/approvalJob.yml new file mode 100644 index 00000000000..ac3b8bc2ab2 --- /dev/null +++ b/.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/.pipelines/templates/channelSelection.yml b/.pipelines/templates/channelSelection.yml new file mode 100644 index 00000000000..d6ddb53256e --- /dev/null +++ b/.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/.pipelines/templates/checkAzureContainer.yml b/.pipelines/templates/checkAzureContainer.yml new file mode 100644 index 00000000000..3e383d2c572 --- /dev/null +++ b/.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/.pipelines/templates/cloneToOfficialPath.yml b/.pipelines/templates/cloneToOfficialPath.yml new file mode 100644 index 00000000000..b060c713683 --- /dev/null +++ b/.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/.pipelines/templates/compliance/apiscan.yml b/.pipelines/templates/compliance/apiscan.yml new file mode 100644 index 00000000000..b5a15699026 --- /dev/null +++ b/.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/.pipelines/templates/compliance/generateNotice.yml b/.pipelines/templates/compliance/generateNotice.yml new file mode 100644 index 00000000000..aec44b9b8f6 --- /dev/null +++ b/.pipelines/templates/compliance/generateNotice.yml @@ -0,0 +1,112 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +parameters: + - name: parentJobs + type: jobList + +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' + + - 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/.pipelines/templates/create-msixbundle-vpack.yml b/.pipelines/templates/create-msixbundle-vpack.yml new file mode 100644 index 00000000000..df46523675f --- /dev/null +++ b/.pipelines/templates/create-msixbundle-vpack.yml @@ -0,0 +1,178 @@ +parameters: + - name: Channel + type: string + - name: createVPack + type: boolean + +jobs: +- job: Bundle_${{ parameters.Channel }} + condition: contains(variables['EnabledChannels'], '${{ parameters.Channel }}') + pool: + type: windows + + variables: + ArtifactPlatform: 'windows' + Channel: ${{ parameters.Channel }} + ob_outputDirectory: '$(BUILD.SOURCESDIRECTORY)\out' + ob_artifactBaseName: 'drop_pack_$(Channel)' + ob_createvpack_enabled: ${{ parameters.createVPack }} + ob_createvpack_packagename: 'PowerShell7-$(Channel).Store.app' + ob_createvpack_owneralias: 'dongbow' + ob_createvpack_description: 'VPack for the PowerShell 7 Store Application ($(Channel))' + 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 + + $channel = '$(Channel)' + if ($channel -eq 'LTS') { + Write-Verbose -Verbose "LTS channel. Remove Stable MSIX packages" + $stablePkgs = Get-ChildItem -Path "$(Build.ArtifactStagingDirectory)\downloads\*.msix" -Recurse | + Where-Object { $_.FullName -notlike '*-LTS-*.msix' } | ForEach-Object FullName + + if ($stablePkgs) { + Remove-Item -Path $stablePkgs -Force -Verbose -ErrorAction Stop + } else { + Write-Verbose -Verbose "No Stable MSIX package was found." + } + } + else { + Write-Verbose -Verbose "Stable channel. Remove LTS MSIX packages" + $ltsPkgs = Get-ChildItem -Path "$(Build.ArtifactStagingDirectory)\downloads\*.msix" -Recurse | + Where-Object { $_.FullName -like '*-LTS-*.msix' } | ForEach-Object FullName + + if ($ltsPkgs) { + Remove-Item -Path $ltsPkgs -Force -Verbose -ErrorAction Stop + } else { + Write-Verbose -Verbose "No LTS MSIX package was found." + } + } + + $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 + } + + $channel = '$(Channel)' + $targetFileName = if ($channel -eq 'LTS') { + 'Microsoft.PowerShell-LTS_8wekyb3d8bbwe.msixbundle' + } else { + 'Microsoft.PowerShell_8wekyb3d8bbwe.msixbundle' + } + $targetPath = Join-Path '$(ob_outputDirectory)' $targetFileName + 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 enabled: $(ob_createvpack_enabled)" -Verbose + Write-Verbose "VPack Name: $(ob_createvpack_packagename)" -Verbose + 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 diff --git a/.pipelines/templates/downloadDotnetEarlyAccess.yml b/.pipelines/templates/downloadDotnetEarlyAccess.yml new file mode 100644 index 00000000000..387b3130ac2 --- /dev/null +++ b/.pipelines/templates/downloadDotnetEarlyAccess.yml @@ -0,0 +1,61 @@ +parameters: +- name: DotnetRuntimeVersion + type: string +- name: DotnetSdkVersion + type: string + +jobs: +- job: download_dotnet_early_access + displayName: Download DotNet Early Access + variables: + - group: dotnet-early-access + - name: DOTNET_RUNTIME_VERSION + value: ${{ parameters.DotnetRuntimeVersion }} + - name: DOTNET_SDK_VERSION + value: ${{ parameters.DotnetSdkVersion }} + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/pkgs' + - name: destinationPath + value: '$(ob_outputDirectory)' + + pool: + name: PowerShell1ES + type: windows + isCustom: true + demands: + - ImageOverride -equals PSMMS2019-Secure + + steps: + - checkout: self + clean: true + + - pwsh: | + Get-ChildItem Env: | Out-String -Width 9999 -Stream | Write-Verbose -Verbose + displayName: Capture environment + + - task: AzurePowerShell@5 + inputs: + azureSubscription: powershell-net-early-access + azurePowerShellVersion: LatestVersion + ScriptType: InlineScript + pwsh: true + inline: | + $DOTNET_PRIVATE_SAS = Get-AzKeyVaultSecret -VaultName $env:DOTNET_AZ_KV_NAME -Name $env:DOTNET_AZ_SECRET_NAME -AsPlainText + + Write-Verbose -Message "DOTNET_PRIVATE_SAS acquired" -Verbose + + Import-Module "$env:BUILD_SOURCESDIRECTORY/build.psm1" -Force + + if (-not (Test-Path '$(destinationPath)')) + { + New-Item -ItemType Directory -Path '$(destinationPath)' -Force -Verbose | Out-Null + } + + Get-DotnetEarlyAccess -DestinationPath '$(destinationPath)' -Architecture all -DOTNET_PRIVATE_SAS $DOTNET_PRIVATE_SAS + + Get-ChildItem -Path '$(destinationPath)' -Recurse | ForEach-Object { + Write-Verbose -verbose "Uploading $($_.FullName) to 'dotnet-packages'" + Write-Host "##vso[artifact.upload containerfolder=dotnet-packages;artifactname=dotnet-packages]$($_.FullName)" + } + + displayName: 'Download DotNet Early Access' diff --git a/.pipelines/templates/insert-nuget-config-azfeed.yml b/.pipelines/templates/insert-nuget-config-azfeed.yml new file mode 100644 index 00000000000..b3edc587bfe --- /dev/null +++ b/.pipelines/templates/insert-nuget-config-azfeed.yml @@ -0,0 +1,114 @@ +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 + + $earlyAccess = $env:ISEARLYACCESS -eq 'true' + + Write-Verbose -Verbose "Is Early access: $earlyAccess" + + if (-not $earlyAccess) + { + Write-Verbose -Verbose "Running: Switch-PSNugetConfig -Source Private -UserName '$(AzDevopsFeedUserNameKVPAT)' -ClearTextPAT '$(powershellPackageReadPat)'" + Switch-PSNugetConfig -Source Private -UserName '$(AzDevopsFeedUserNameKVPAT)' -ClearTextPAT '$(powershellPackageReadPat)' + } + else + { + Write-Verbose -Verbose "Running: Switch-PSNugetConfig -Source EarlyAccess" + Switch-PSNugetConfig -Source EarlyAccess + } + + 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 }} + +- task: AzureCLI@2 + inputs: + azureSubscription: powershell-net-early-access + scriptType: pscore + scriptLocation: inlineScript + inlineScript: | + Write-Verbose -Verbose "Getting an Azure DevOps access token" + # Microsoft's well-known Entra resource ID for the Azure DevOps token audience. + $azureDevOpsResourceUrl = '499b84ac-1321-427f-aa17-267ca6975798' + $azt = az account get-access-token --resource $azureDevOpsResourceUrl --query accessToken --output tsv + if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($azt)) { + throw "Failed to get an Azure DevOps access token." + } + + Write-Host "##vso[task.setsecret]$azt" + Write-Verbose -Verbose "Setting up Azure Artifacts Credential Provider token" + + $earlyAccessFeed = '$(EARLY_ACCESS_FEED)' + $ADORepoUri = switch ($earlyAccessFeed) { + 'net8' { 'https://pkgs.dev.azure.com/powershell-rel/PowerShell/_packaging/powershell-net-8-early-access/nuget/v3/index.json' } + 'net9' { 'https://pkgs.dev.azure.com/powershell-rel/PowerShell/_packaging/powershell-net-9-early-access/nuget/v3/index.json' } + 'net10' { 'https://pkgs.dev.azure.com/powershell-rel/PowerShell/_packaging/powershell-net-10-early-access/nuget/v3/index.json' } + default { throw "Unknown early access feed URL: $earlyAccessFeed" } + } + $galleryRepoUri = 'https://www.powershellgallery.com/api/v2' + + Write-Verbose -Verbose "ADORepoUri == $ADORepoUri" + + if ([string]::IsNullOrEmpty($ADORepoUri) -eq $false) + { + $endpointCredsObj = @{ endpointCredentials = @( + @{ endpoint = $ADORepoUri; password = $azt } + )} + $VSS_NUGET_EXTERNAL_FEED_ENDPOINTS = $endpointCredsObj | ConvertTo-Json -Compress + + Write-Verbose -Verbose "Setting VSS_NUGET_EXTERNAL_FEED_ENDPOINTS environment variable" + + Write-Host "##vso[task.setvariable variable=VSS_NUGET_EXTERNAL_FEED_ENDPOINTS;issecret=true]$VSS_NUGET_EXTERNAL_FEED_ENDPOINTS" + } + else + { + Write-Verbose -Verbose "EARLY_ACCESS_FEED_URL is not set" + } + displayName: 'Setup Azure Artifacts Credential Provider secret' + condition: eq(variables['ISEARLYACCESS'], 'true') + env: + 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/.pipelines/templates/install-dotnet.yml b/.pipelines/templates/install-dotnet.yml new file mode 100644 index 00000000000..15f1c170458 --- /dev/null +++ b/.pipelines/templates/install-dotnet.yml @@ -0,0 +1,100 @@ +parameters: +- name: ob_restore_phase + type: boolean + default: true +- name: architecture + type: string + default: 'win-x64' + values: + - 'win-x64' + - 'win-x86' + - 'win-arm64' + - 'linux-x64' + - 'linux-arm64' + - 'linux-musl-x64' + - 'linux-musl-arm64' + - 'osx-x64' + - 'osx-arm64' + +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) + condition: and(ne(variables['ISEARLYACCESS'], 'true'), ne(variables['ISEARLYACCESS'], 'True')) + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} + + - task: DownloadPipelineArtifact@2 + displayName: "Download dotnet-packages artifact" + condition: eq(variables['ISEARLYACCESS'], 'true') + inputs: + artifactName: 'dotnet-packages' + targetPath: '$(Pipeline.Workspace)/dotnet-packages' + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} + - pwsh: | + $arch = '${{ parameters.architecture }}' + $sdkFilePattern = "dotnet-sdk-*-${arch}.*" + + if (-not (Test-Path '$(Pipeline.Workspace)/dotnet-packages')) { + New-Item -Path '$(Pipeline.Workspace)/dotnet-packages' -ItemType Directory -Force -Verbose | Out-Null + } + + $filePath = Get-ChildItem '$(Pipeline.Workspace)/dotnet-packages' -Recurse -File | Where-Object { $_.Name -like $sdkFilePattern } | Select-Object -First 1 -ExpandProperty FullName + + if (-not $filePath) { + Get-ChildItem -Path '$(Pipeline.Workspace)/dotnet-packages' -Recurse + throw "SDK file matching pattern $sdkFilePattern not found in $(Pipeline.Workspace)/dotnet-packages" + } + + $dotnetLocation = if ($IsWindows) { "$env:LocalAppData\Microsoft\dotnet" } else { "$env:HOME/.dotnet" } + + if (-not (Test-Path $dotnetLocation)) { + New-Item -ItemType Directory -Path $dotnetLocation -Force -Verbose | Out-Null + } + + Write-Verbose -Verbose "Extracting SDK from $filePath to $dotnetLocation" + + if ($filePath -match '\.(tar\.gz|tgz)$') { + & tar -xzf $filePath -C $dotnetLocation + if ($LASTEXITCODE -ne 0) { + throw "Failed to extract $filePath with tar (exit code $LASTEXITCODE)" + } + } elseif ($filePath -match '\.zip$') { + Expand-Archive -Path $filePath -DestinationPath $dotnetLocation -Force + } else { + throw "Unsupported SDK archive format: $filePath" + } + + Write-Verbose -Verbose "Expand dotnet package complete." + + $dotnetExe = if ($IsWindows) { + "$dotnetLocation\dotnet.exe" + } else { + "$dotnetLocation/dotnet" + } + + if (-not (Test-Path $dotnetExe)) { + throw "dotnet executable not found at $dotnetExe" + } + + Get-ChildItem -Path $dotnetLocation -Recurse + + & $dotnetExe --info + workingDirectory: $(RepoRoot) + displayName: Install dotnet early access + condition: eq(variables['ISEARLYACCESS'], 'true') + env: + ob_restore_phase: ${{ parameters.ob_restore_phase }} diff --git a/.pipelines/templates/linux-package-build.yml b/.pipelines/templates/linux-package-build.yml new file mode 100644 index 00000000000..50836219a3a --- /dev/null +++ b/.pipelines/templates/linux-package-build.yml @@ -0,0 +1,221 @@ +parameters: + unsignedDrop: 'drop_linux_build_linux_x64' + signedDrop: 'drop_linux_sign_linux_x64' + packageType: deb + jobName: 'deb' + dotnetArch: 'linux-x64' + +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 + - group: certificate_logical_to_actual + - 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 + # PGP signing profile selection: Mariner (Azure Linux) packages ship through + # a different distribution channel and must be signed with the Mariner release + # key; all other Linux packages use the standard PowerShell Linux key. Both + # key codes come from the `certificate_logical_to_actual` variable group. + - ${{ if startsWith(parameters.jobName, 'mariner') }}: + - name: SigningProfile + value: $(pgp_release_cert_id) + - ${{ else }}: + - name: SigningProfile + value: $(pgp_linux_cert_id) + + 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 + parameters: + architecture: ${{ parameters.dotnetArch }} + + - 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' } + 'deb-arm64' { 'Signed-linux-arm64', '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-x64' { 'Signed-linux-x64', 'powershell*.tar.gz' } + 'min-size-arm64' { 'Signed-linux-arm64', '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 -and ($packageType -like 'deb*' -or $packageType -like 'rpm*')) { + 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 + + if ($pkgPath -like '*.tar.gz') { + $entry = & tar -tzvf $pkgPath | Where-Object { $_ -match '\spwsh$' } | Select-Object -First 1 + if ($entry -notmatch '^-..x') { + throw "pwsh is not executable in $pkgPath : $entry" + } + } + 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/.pipelines/templates/linux.yml b/.pipelines/templates/linux.yml new file mode 100644 index 00000000000..b8d6005c843 --- /dev/null +++ b/.pipelines/templates/linux.yml @@ -0,0 +1,200 @@ +parameters: + Runtime: 'linux-x64' + BuildConfiguration: 'release' + JobName: 'build_linux' + dotnetArch: 'linux-x64' + +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 + parameters: + architecture: ${{ parameters.dotnetArch }} + + - 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/.pipelines/templates/mac-package-build.yml b/.pipelines/templates/mac-package-build.yml new file mode 100644 index 00000000000..89dab90aa04 --- /dev/null +++ b/.pipelines/templates/mac-package-build.yml @@ -0,0 +1,296 @@ +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 + - group: certificate_logical_to_actual + - 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: | + $signedDir = "$(Pipeline.Workspace)/CoOrdinatedBuildPipeline/drop_macos_sign_${{ parameters.buildArchitecture }}/Signed-${{ parameters.buildArchitecture }}" + Get-ChildItem $signedDir -Recurse -Include 'pwsh', '*.dylib' | ForEach-Object { + codesign --verify --deep --strict --verbose=4 $_.FullName + if ($LASTEXITCODE -ne 0) { throw "codesign verification failed for $($_.FullName)" } + } + displayName: 'Verify Apple codesign on signed binaries' + + - 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 + $entry = & tar -tzvf $file | Where-Object { $_ -match '\spwsh$' } | Select-Object -First 1 + if ($entry -notmatch '^-..x') { + throw "pwsh is not executable in $file : $entry" + } + Write-Verbose -verbose "Uploading $file to macos-pkgs" + Write-Host "##vso[artifact.upload containerfolder=macos-pkgs;artifactname=macos-pkgs]$file" + } + + $packageInfo = Get-MacOSPackageIdentifierInfo -Version '$(Version)' -LTS:$LTS + Write-Verbose -Verbose "BundleId: $($packageInfo.PackageIdentifier)" + Write-Host "##vso[task.setvariable variable=BundleId;isOutput=true]$($packageInfo.PackageIdentifier)" + + displayName: 'Package ${{ parameters.buildArchitecture}}' + name: packageStep + 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: + - group: certificate_logical_to_actual + - 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 }} + - name: BundleId + value: $[ dependencies.package_macOS_${{ parameters.buildArchitecture }}.outputs['packageStep.BundleId'] ] + + 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": "$(apple_cert_id)", + "OperationCode": "MacAppDeveloperSign", + "ToolName": "sign", + "ToolVersion": "1.0", + "Parameters": { + "Hardening": "--options=runtime" + } + } + ] + + - task: onebranch.pipeline.signing@1 + displayName: 'OneBranch Notarize Package' + inputs: + command: 'sign' + files_to_sign: '**/*-osx-*.zip' + search_root: '$(Pipeline.Workspace)' + inline_operation: | + [ + { + "KeyCode": "$(apple_cert_id)", + "OperationCode": "MacAppNotarize", + "ToolName": "sign", + "ToolVersion": "1.0", + "Parameters": { + "BundleId": "$(BundleId)" + } + } + ] + timeoutInMinutes: 120 + + - pwsh: | + $signedPkg = Get-ChildItem -Path $(Pipeline.Workspace) -Filter "*osx*.zip" -File + + if (-not (Test-Path $(ob_outputDirectory))) { + $null = New-Item -Path $(ob_outputDirectory) -ItemType Directory + } + + $expandDir = "$(Pipeline.Workspace)/pkgExpand" + $null = New-Item -Path $expandDir -ItemType Directory -Force + + $signedPkg | ForEach-Object { + Write-Verbose -Verbose "Signed package zip: $_" + Expand-Archive -Path $_ -DestinationPath $expandDir -Verbose + } + + # ESRP's signing pipeline nests the PKG inside a '.zip.unzipped' subfolder + $pkgFile = Get-ChildItem -Path $expandDir -Filter '*.pkg' -Recurse -File + if (-not $pkgFile) { + throw "Package not found in: $signedPkg" + } + + $pkgFile | ForEach-Object { + Move-Item -Path $_ -Destination $(ob_outputDirectory) -Verbose + } + + Write-Verbose -Verbose "Expanded pkg file:" + Get-ChildItem -Path $(ob_outputDirectory) | Write-Verbose -Verbose + displayName: Expand signed file diff --git a/.pipelines/templates/mac.yml b/.pipelines/templates/mac.yml new file mode 100644 index 00000000000..623f6b5ffaf --- /dev/null +++ b/.pipelines/templates/mac.yml @@ -0,0 +1,209 @@ +parameters: + buildArchitecture: 'x64' + dotnetArch: 'osx-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 + parameters: + architecture: ${{ parameters.dotnetArch }} + + - 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 + + $entitlements = "$(PowerShellRoot)/assets/macos-entitlements.plist" + $pwshBin = "$(OB_OUTPUTDIRECTORY)/pwsh" + Write-Verbose -Verbose "Applying entitlements to $pwshBin" + codesign --sign - --force --options runtime --entitlements $entitlements $pwshBin + if ($LASTEXITCODE -ne 0) { + throw "codesign failed with exit code $LASTEXITCODE" + } + + # 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) + + # Apple-sign the Mach-O binaries inside the signed output. + - pwsh: | + $signedDir = "$(ob_outputDirectory)/Signed-$(Runtime)" + $zipFile = "$(Pipeline.Workspace)/macho-$(BuildArchitecture).zip" + Compress-Archive -Path "$signedDir/*" -DestinationPath $zipFile -Force + displayName: Compress signed folder for Apple signing + + - task: onebranch.pipeline.signing@1 + displayName: Apple CodeSign Mach-O binaries + inputs: + command: 'sign' + files_to_sign: 'macho-$(BuildArchitecture).zip' + search_root: '$(Pipeline.Workspace)' + inline_operation: | + [ + { + "KeyCode": "$(apple_cert_id)", + "OperationCode": "MacAppDeveloperSign", + "ToolName": "sign", + "ToolVersion": "1.0", + "Parameters": { + "Hardening": "--options=runtime" + } + } + ] + + - pwsh: | + $signedDir = "$(ob_outputDirectory)/Signed-$(Runtime)" + $zipFile = "$(Pipeline.Workspace)/macho-$(BuildArchitecture).zip" + Expand-Archive -Path $zipFile -DestinationPath $signedDir -Force -Verbose + displayName: Expand Apple-signed Mach-O binaries into signed output + + - pwsh: | + $signedDir = "$(ob_outputDirectory)/Signed-$(Runtime)" + $expected = 'Developer ID Application: Microsoft Corporation' + $missing = @() + Get-ChildItem $signedDir -Recurse -Include 'pwsh', '*.dylib' | ForEach-Object { + $bytes = [System.IO.File]::ReadAllBytes($_.FullName) + $text = [System.Text.Encoding]::Latin1.GetString($bytes) + if (-not $text.Contains($expected)) { + $missing += $_.FullName + Write-Host "##[error]Missing '$expected' signature in $($_.FullName)" + } else { + Write-Host "OK: $($_.FullName)" + } + } + if ($missing.Count -gt 0) { + throw "ESRP did not apply a Developer ID signature to $($missing.Count) file(s): $($missing -join ', ')" + } + displayName: 'Verify Developer ID signature on Mach-O binaries' + + - template: /.pipelines/templates/step/finalize.yml@self diff --git a/.pipelines/templates/nupkg.yml b/.pipelines/templates/nupkg.yml new file mode 100644 index 00000000000..043c0b1f75c --- /dev/null +++ b/.pipelines/templates/nupkg.yml @@ -0,0 +1,299 @@ +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 + - group: certificate_logical_to_actual + + 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: '$(nuget_cert_id)' + 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: '$(nuget_cert_id)' + 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/.pipelines/templates/obp-file-signing.yml b/.pipelines/templates/obp-file-signing.yml new file mode 100644 index 00000000000..cbe44ad0018 --- /dev/null +++ b/.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/.pipelines/templates/package-create-msix.yml b/.pipelines/templates/package-create-msix.yml new file mode 100644 index 00000000000..97d2f4fc46a --- /dev/null +++ b/.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/.pipelines/templates/package-store-package.yml b/.pipelines/templates/package-store-package.yml new file mode 100644 index 00000000000..4ee2098332e --- /dev/null +++ b/.pipelines/templates/package-store-package.yml @@ -0,0 +1,259 @@ +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 { $null } + + if (-not $currentChannel) { + Write-Host "##[warning]No release channel selected (LTS/Stable/Preview all false). Skipping Store package creation." + Write-Host "##vso[task.setvariable variable=SkipStorePublish]true" + # Set channel flags so any downstream conditioned tasks evaluate to skip. + Write-Host "##vso[task.setvariable variable=LTS]false" + Write-Host "##vso[task.setvariable variable=STABLE]false" + Write-Host "##vso[task.setvariable variable=PREVIEW]false" + # Ensure the output directory exists so downstream artifact publishing does not fail. + $outputDirectory = "$(ob_outputDirectory)" + if (-not (Test-Path -LiteralPath $outputDirectory)) { + New-Item -ItemType Directory -Path $outputDirectory -Force | Out-Null + } + return + } + + Write-Host "##vso[task.setvariable variable=SkipStorePublish]false" + + $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' + condition: and(succeeded(), ne(variables['SkipStorePublish'], 'true')) diff --git a/.pipelines/templates/packaging/windows/package.yml b/.pipelines/templates/packaging/windows/package.yml new file mode 100644 index 00000000000..cb178e03fa4 --- /dev/null +++ b/.pipelines/templates/packaging/windows/package.yml @@ -0,0 +1,231 @@ +parameters: + runtime: x64 + dotnetArch: 'win-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: ${{ not(contains(parameters.runtime, 'minsize')) }} + + - download: CoOrdinatedBuildPipeline + artifact: drop_windows_build_windows_${{ parameters.runtime }} + displayName: Download minsize signed artifacts + condition: ${{ contains(parameters.runtime, 'minsize') }} + + - pwsh: | + Write-Verbose -Verbose "signed artifacts" + Get-ChildItem "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline" -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 + architecture: ${{ parameters.dotnetArch }} + + - 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' } + 'x64_minsize' { 'Signed-win7-x64' } + 'arm64_minsize' { 'Signed-win-arm64' } + } + + 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 ($runtime.Contains('minsize')) { + "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_${runtime}\$signedFolder" + "$(Pipeline.Workspace)\CoOrdinatedBuildPipeline\drop_windows_build_windows_${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' } + 'x64_minsize' { 'win7-x64' } + 'arm64_minsize' { 'win-arm64' } + } + + $packageTypes = switch ($runtime) { + 'x64' { @('zip', 'msix') } + 'x86' { @('zip', 'msix') } + 'arm64' { @('zip', 'msix') } + 'fxdependent' { 'fxdependent' } + 'fxdependentWinDesktop' { 'fxdependent-win-desktop' } + 'x64_minsize' { 'min-size-x64' } + 'arm64_minsize' { 'min-size-arm64' } + } + + 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' } + 'x64_minsize' { 'min-size-x64' } + 'arm64_minsize' { 'min-size-arm64' } + } + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + if ($packageTypes -contains 'zip' -or $packageTypes -like 'fxdependent*' -or $packageTypes -like 'min-size*') { + $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/.pipelines/templates/packaging/windows/sign.yml b/.pipelines/templates/packaging/windows/sign.yml new file mode 100644 index 00000000000..8481f93c964 --- /dev/null +++ b/.pipelines/templates/packaging/windows/sign.yml @@ -0,0 +1,118 @@ +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' } + 'x64_minsize' { 'min-size-x64' } + 'arm64_minsize' { 'min-size-arm64' } + } + + if (-not (Test-Path $(ob_outputDirectory))) { + New-Item -ItemType Directory -Path $(ob_outputDirectory) -Force + } + + if ($packageTypes -contains 'zip' -or $packageTypes -like 'fxdependent*' -or $packageTypes -like 'min-size*') { + $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/.pipelines/templates/rebuild-branch-check.yml b/.pipelines/templates/rebuild-branch-check.yml new file mode 100644 index 00000000000..a4b546a0dc6 --- /dev/null +++ b/.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/.pipelines/templates/release-MSIX-Publish.yml b/.pipelines/templates/release-MSIX-Publish.yml new file mode 100644 index 00000000000..a68755725ce --- /dev/null +++ b/.pipelines/templates/release-MSIX-Publish.yml @@ -0,0 +1,142 @@ +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 + condition: or(eq(variables['LTS'], 'true'), eq(variables['STABLE'], 'true'), eq(variables['PREVIEW'], 'true')) + 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 + condition: or(eq(variables['LTS'], 'true'), eq(variables['STABLE'], 'true'), eq(variables['PREVIEW'], 'true')) + 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 { $null } + + if (-not $currentChannel) { + Write-Host "##[warning]No release channel selected (LTS/Stable/Preview all false). Skipping Store publish." + return + } + + # 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/.pipelines/templates/release-MakeBlobPublic.yml b/.pipelines/templates/release-MakeBlobPublic.yml new file mode 100644 index 00000000000..758298202a1 --- /dev/null +++ b/.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/.pipelines/templates/release-Nuget.yml b/.pipelines/templates/release-Nuget.yml new file mode 100644 index 00000000000..c6ffb67e6a4 --- /dev/null +++ b/.pipelines/templates/release-Nuget.yml @@ -0,0 +1,59 @@ +parameters: + - name: skipPublish + type: boolean + +jobs: +- 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/.pipelines/templates/release-SetReleaseTagandContainerName.yml b/.pipelines/templates/release-SetReleaseTagandContainerName.yml new file mode 100644 index 00000000000..d40551353d2 --- /dev/null +++ b/.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/.pipelines/templates/release-SetTagAndChangelog.yml b/.pipelines/templates/release-SetTagAndChangelog.yml new file mode 100644 index 00000000000..b33e652b3c7 --- /dev/null +++ b/.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/.pipelines/templates/release-github.yml b/.pipelines/templates/release-github.yml new file mode 100644 index 00000000000..424367fbf21 --- /dev/null +++ b/.pipelines/templates/release-github.yml @@ -0,0 +1,173 @@ +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) + + if ($headingStartLines.Count -eq 0) { + throw "No release heading matching '$headingPattern' found in $filePath" + } + + $startLine = $headingStartLines[0] + if ($headingStartLines.Count -ge 2) { + $endLine = $headingStartLines[1] - 1 + } else { + # Only one release heading present; take through end of file. + $endLine = $changelog.Count + } + + $clContent = $changelog | Select-Object -Skip ($startLine-1) -First ($endLine - $startLine + 1) | 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)' diff --git a/.pipelines/templates/release-prep-for-ev2.yml b/.pipelines/templates/release-prep-for-ev2.yml new file mode 100644 index 00000000000..ec6ea5ec1e9 --- /dev/null +++ b/.pipelines/templates/release-prep-for-ev2.yml @@ -0,0 +1,220 @@ +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 + templateContext: + inputs: + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_linux_package_deb + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_linux_package_deb_arm64 + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_linux_package_rpm + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_linux_package_mariner_x64 + - input: pipelineArtifact + pipeline: PSPackagesOfficial + artifactName: drop_linux_package_mariner_arm64 + 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 + - name: ob_sdl_tsa_configFile + value: $(Build.SourcesDirectory)/PowerShell/.config/tsaoptions.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: | + 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 + + - pwsh: | + Write-Verbose -Verbose "Copy ESRP signed .deb and .rpm packages" + # templateContext.inputs places the PSPackagesOfficial pipelineArtifact files + # directly under $(Pipeline.Workspace), not in per-artifact subfolders. + $downloadedPipelineFolder = '$(Pipeline.Workspace)' + $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 -File | Where-Object { $_.Extension -in '.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/.pipelines/templates/release-publish-pmc.yml b/.pipelines/templates/release-publish-pmc.yml new file mode 100644 index 00000000000..dc7fc8534e3 --- /dev/null +++ b/.pipelines/templates/release-publish-pmc.yml @@ -0,0 +1,56 @@ +parameters: +- name: releaseEnvironment + type: string + default: Production + values: + - Production + - PPE + - Test +- name: approvalServiceEnvironment + type: string + default: Production + values: + - Production + - PPE + - Test +# OneBranch requires the stage name to be prefixed with the release environment. +# Official uses 'Prod' for Production; NonProd validators require '' (e.g. 'Test', 'PPE'). +- name: stagePrefix + type: string + default: Prod +# When true, the Ev2 push step is skipped. Useful for NonOfficial dry-runs that +# only want to validate artifact download via templateContext.inputs. +- name: skipEv2Push + type: boolean + default: false + +stages: +- stage: ${{ parameters.stagePrefix }}_Release + displayName: 'Deploy packages to PMC with EV2' + dependsOn: + - PrepForEV2 + variables: + - name: ob_release_environment + value: ${{ parameters.releaseEnvironment }} + - name: repoRoot + value: $(Build.SourcesDirectory) + jobs: + - job: ${{ parameters.stagePrefix }}_ReleaseJob + displayName: Publish to PMC + pool: + type: release + templateContext: + inputs: + - input: pipelineArtifact + artifactName: drop_PrepForEV2_CopyEv2FilesToArtifact + + steps: + - ${{ if not(parameters.skipEv2Push) }}: + - task: vsrm-ev2.vss-services-ev2.adm-release-task.ExpressV2Internal@1 + displayName: 'Ev2: Push to PMC' + inputs: + UseServerMonitorTask: true + EndpointProviderType: ApprovalService + ApprovalServiceEnvironment: ${{ parameters.approvalServiceEnvironment }} + ServiceRootPath: '$(Pipeline.Workspace)/EV2Specs/ServiceGroupRoot' + RolloutSpecPath: '$(Pipeline.Workspace)/EV2Specs/ServiceGroupRoot/RolloutSpec.json' diff --git a/.pipelines/templates/release-symbols.yml b/.pipelines/templates/release-symbols.yml new file mode 100644 index 00000000000..a628f4d7127 --- /dev/null +++ b/.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/.pipelines/templates/release-upload-buildinfo.yml b/.pipelines/templates/release-upload-buildinfo.yml new file mode 100644 index 00000000000..9e3d6a6accb --- /dev/null +++ b/.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/.pipelines/templates/release-validate-fxdpackages.yml b/.pipelines/templates/release-validate-fxdpackages.yml new file mode 100644 index 00000000000..3e8169df19c --- /dev/null +++ b/.pipelines/templates/release-validate-fxdpackages.yml @@ -0,0 +1,137 @@ +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 + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + - name: dotnetArch + type: string + default: 'win-x64' + +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 }} + - name: ISEARLYACCESS + value: ${{ parameters.IsEarlyAccess }} + + 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 + parameters: + architecture: ${{ parameters.dotnetArch }} + ob_restore_phase: false + + - 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/.pipelines/templates/release-validate-globaltools.yml b/.pipelines/templates/release-validate-globaltools.yml new file mode 100644 index 00000000000..1c784f5e76c --- /dev/null +++ b/.pipelines/templates/release-validate-globaltools.yml @@ -0,0 +1,155 @@ +parameters: + - name: jobName + type: string + default: "" + - name: displayName + type: string + default: "" + - name: jobtype + type: string + default: "windows" + - name: globalToolExeName + type: string + default: 'pwsh.exe' + - name: globalToolPackageName + type: string + default: 'PowerShell.Windows.x64' + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + - name: dotnetArch + type: string + default: 'win-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 + - name: ISEARLYACCESS + value: ${{ parameters.IsEarlyAccess }} + + 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 + parameters: + architecture: ${{ parameters.dotnetArch }} + ob_restore_phase: false + + - 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/.pipelines/templates/release-validate-packagenames.yml b/.pipelines/templates/release-validate-packagenames.yml new file mode 100644 index 00000000000..5953366ffd7 --- /dev/null +++ b/.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|arm64)\.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/.pipelines/templates/release-validate-sdk.yml b/.pipelines/templates/release-validate-sdk.yml new file mode 100644 index 00000000000..2cbefd94e98 --- /dev/null +++ b/.pipelines/templates/release-validate-sdk.yml @@ -0,0 +1,150 @@ +parameters: + - name: jobName + type: string + default: "" + - name: displayName + type: string + default: "" + - name: poolName + type: string + default: "windows" + - name: imageName + type: string + default: 'none' + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + - name: dotnetArch + type: string + default: 'win-x64' + - name: EarlyAccessFeed + type: string + default: 'net10' + +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 + - name: ISEARLYACCESS + value: ${{ parameters.IsEarlyAccess }} + - name: EARLY_ACCESS_FEED + value: ${{ parameters.EarlyAccessFeed }} + + steps: + - checkout: self + clean: true + lfs: false + + - template: /.pipelines/templates/SetVersionVariables.yml@self + parameters: + ReleaseTagVar: $(ReleaseTagVar) + + - 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 + parameters: + ob_restore_phase: false + architecture: ${{ parameters.dotnetArch }} + + - template: /.pipelines/templates/insert-nuget-config-azfeed.yml@self + + - pwsh: | + $repoRoot = "$(Build.SourcesDirectory)" + + Import-Module "$repoRoot/build.psm1" -Force -Verbose + Start-PSBootstrap -Scenario Dotnet + + $env:DOTNET_NOLOGO=1 + + $isEarlyAccess = '$(ISEARLYACCESS)' + + $ADORepoUri = if ($isEarlyAccess -eq 'True') + { + $earlyAccessFeed = '$(EARLY_ACCESS_FEED)' + switch ($earlyAccessFeed) { + 'net8' { 'https://pkgs.dev.azure.com/powershell-rel/PowerShell/_packaging/powershell-net-8-early-access/nuget/v3/index.json' } + 'net9' { 'https://pkgs.dev.azure.com/powershell-rel/PowerShell/_packaging/powershell-net-9-early-access/nuget/v3/index.json' } + 'net10' { 'https://pkgs.dev.azure.com/powershell-rel/PowerShell/_packaging/powershell-net-10-early-access/nuget/v3/index.json' } + default { throw "Unknown early access feed URL: $earlyAccessFeed" } + } + } + else { + "https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet9/nuget/v3/index.json" + } + + Write-Verbose -Verbose "ADO Repo URI: $ADORepoUri" + + $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/.pipelines/templates/set-reporoot.yml b/.pipelines/templates/set-reporoot.yml new file mode 100644 index 00000000000..af7983afaa1 --- /dev/null +++ b/.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/.pipelines/templates/shouldSign.yml b/.pipelines/templates/shouldSign.yml new file mode 100644 index 00000000000..f3701acbc97 --- /dev/null +++ b/.pipelines/templates/shouldSign.yml @@ -0,0 +1,30 @@ +parameters: +- name: ob_restore_phase + type: boolean + default: true + +steps: +- powershell: | + $shouldSign = $true + $authenticodeCert = '$(authenticode_cert_id)' + $msixCert = '$(authenticode_cert_id)' + if($env:IS_DAILY -eq 'true') + { + $authenticodeCert = '$(authenticode_test_cert_id)' + } + 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/.pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml b/.pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml new file mode 100644 index 00000000000..e6629c1d5ad --- /dev/null +++ b/.pipelines/templates/stages/PowerShell-Coordinated_Packages-Stages.yml @@ -0,0 +1,242 @@ +parameters: + - name: RUN_WINDOWS + type: boolean + default: true + - name: RUN_TEST_AND_RELEASE + type: boolean + default: true + - name: OfficialBuild + type: boolean + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + - name: EarlyAccessFeed + type: string + default: 'net10' + +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 + - name: IsEarlyAccess + value: ${{ parameters.IsEarlyAccess }} + + 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 + + - ${{ if eq(parameters.IsEarlyAccess, true) }}: + - template: /.pipelines/templates/downloadDotnetEarlyAccess.yml@self + parameters: + DotnetRuntimeVersion: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DotnetSdkVersion: ${{ parameters.DOTNET_SDK_VERSION }} + +- stage: macos + displayName: macOS - build and sign + dependsOn: ['prep'] + variables: + - name: ps_official_build + value: ${{ parameters.OfficialBuild }} + - name: IsEarlyAccess + value: ${{ parameters.IsEarlyAccess }} + 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 }} + - name: IsEarlyAccess + value: ${{ parameters.IsEarlyAccess }} + 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-arm64' + JobName: 'linux_arm64_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 }} + - name: IsEarlyAccess + value: ${{ parameters.IsEarlyAccess }} + 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: arm64 + BuildConfiguration: minSize + JobName: build_windows_arm64_minSize_release + - template: /.pipelines/templates/windows-hosted-build.yml@self + parameters: + Architecture: x86 + JobName: build_windows_x86_release + dotnetArch: 'win-x86' + - 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/.pipelines/templates/stages/PowerShell-Packages-Stages.yml b/.pipelines/templates/stages/PowerShell-Packages-Stages.yml new file mode 100644 index 00000000000..2c84885e445 --- /dev/null +++ b/.pipelines/templates/stages/PowerShell-Packages-Stages.yml @@ -0,0 +1,247 @@ +parameters: + - name: OfficialBuild + type: boolean + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + - name: EarlyAccessFeed + type: string + default: 'net10' + +stages: +- stage: prep + displayName: 'Prep BuildInfo+Az' + jobs: + - template: /.pipelines/templates/checkAzureContainer.yml@self + +- stage: EarlyDotnet + displayName: 'Early .NET Setup' + dependsOn: [] + condition: always() + + jobs: + - ${{ if eq(parameters.IsEarlyAccess, true) }}: + - template: /.pipelines/templates/downloadDotnetEarlyAccess.yml@self + parameters: + DotnetRuntimeVersion: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DotnetSdkVersion: ${{ parameters.DOTNET_SDK_VERSION }} + - ${{ else }}: + - job: skip_early_dotnet + displayName: 'Skip early access .NET setup' + pool: + type: windows + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + steps: + - pwsh: Write-Host 'IsEarlyAccess is false; skipping early access .NET setup.' +- stage: mac_package + displayName: 'macOS Pkg+Sign' + dependsOn: [EarlyDotnet] + 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: [EarlyDotnet] + 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: x64_minsize + + - template: /.pipelines/templates/packaging/windows/package.yml@self + parameters: + runtime: arm64_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: x64_minsize + + - template: /.pipelines/templates/packaging/windows/sign.yml@self + parameters: + runtime: arm64_minsize + +- stage: linux_package + displayName: 'Linux Pkg+Sign' + dependsOn: [EarlyDotnet] + 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_arm64' + signedDrop: 'drop_linux_sign_linux_arm64' + packageType: deb-arm64 + jobName: deb_arm64 + + - 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 + + - 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 + + - 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-x64 + jobName: minSize_x64 + + - template: /.pipelines/templates/linux-package-build.yml@self + parameters: + unsignedDrop: 'drop_linux_build_linux_arm64_minSize' + signedDrop: 'drop_linux_sign_linux_arm64_minSize' + packageType: min-size-arm64 + jobName: minSize_arm64 + +- stage: nupkg + displayName: 'NuGet Pkg+Sign' + dependsOn: [EarlyDotnet] + jobs: + - template: /.pipelines/templates/nupkg.yml@self + +- stage: msixbundle + displayName: 'MSIX Bundle+Sign' + dependsOn: [EarlyDotnet, 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: [EarlyDotnet, 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/.pipelines/templates/stages/PowerShell-Release-Stages.yml b/.pipelines/templates/stages/PowerShell-Release-Stages.yml new file mode 100644 index 00000000000..d922b224b97 --- /dev/null +++ b/.pipelines/templates/stages/PowerShell-Release-Stages.yml @@ -0,0 +1,398 @@ +parameters: + - name: releaseEnvironment + type: string + - name: SkipPublish + type: boolean + - name: SkipPSInfraInstallers + type: boolean + - name: skipMSIXPublish + type: boolean + - name: IsEarlyAccess + type: boolean + default: false + - name: DOTNET_RUNTIME_VERSION + displayName: Runtime version of early access build + type: string + default: ' ' + - name: DOTNET_SDK_VERSION + displayName: SDK version of early access build + type: string + default: ' ' + - name: EarlyAccessFeed + type: string + default: 'net10' + +stages: +- stage: setReleaseTagAndChangelog + displayName: 'Set Release Tag and Upload Changelog' + jobs: + - template: /.pipelines/templates/release-SetTagAndChangelog.yml@self + +- stage: downloadDotnetEarlyAccess + displayName: 'Download Early release .NET' + jobs: + - ${{ if eq(parameters.IsEarlyAccess, true) }}: + - template: /.pipelines/templates/downloadDotnetEarlyAccess.yml@self + parameters: + DotnetRuntimeVersion: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DotnetSdkVersion: ${{ parameters.DOTNET_SDK_VERSION }} + - ${{ else }}: + - job: skip_download_dotnet_early_access + displayName: 'Skip early access .NET download' + pool: + type: windows + variables: + - name: ob_outputDirectory + value: '$(Build.ArtifactStagingDirectory)/ONEBRANCH_ARTIFACT' + steps: + - pwsh: Write-Host 'IsEarlyAccess is false; skipping early access .NET download.' +- stage: validateSdk + displayName: 'Validate SDK' + dependsOn: [downloadDotnetEarlyAccess] + jobs: + - template: /.pipelines/templates/release-validate-sdk.yml@self + parameters: + jobName: "windowsSDK" + displayName: "Windows SDK Validation" + imageName: PSMMS2019-Secure + poolName: $(windowsPool) + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + EarlyAccessFeed: ${{ parameters.EarlyAccessFeed }} + dotnetArch: 'win-x64' + + - template: /.pipelines/templates/release-validate-sdk.yml@self + parameters: + jobName: "MacOSSDK" + displayName: "MacOS SDK Validation" + imageName: macOS-latest + poolName: Azure Pipelines + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'osx-x64' + + - template: /.pipelines/templates/release-validate-sdk.yml@self + parameters: + jobName: "LinuxSDK" + displayName: "Linux SDK Validation" + imageName: PSMMSUbuntu22.04-Secure + poolName: $(ubuntuPool) + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'linux-x64' + +- stage: gbltool + displayName: 'Validate Global tools' + dependsOn: [downloadDotnetEarlyAccess] + jobs: + - template: /.pipelines/templates/release-validate-globaltools.yml@self + parameters: + jobName: "WindowsGlobalTools" + displayName: "Windows Global Tools Validation" + jobtype: windows + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'win-x64' + + - template: /.pipelines/templates/release-validate-globaltools.yml@self + parameters: + jobName: "LinuxGlobalTools" + displayName: "Linux Global Tools Validation" + jobtype: linux + globalToolExeName: 'pwsh' + globalToolPackageName: 'PowerShell.Linux.x64' + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'linux-x64' + +- stage: fxdpackages + displayName: 'Validate FXD Packages' + dependsOn: [downloadDotnetEarlyAccess] + 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' + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'win-x64' + + - 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' + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'win-x64' + + - 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' + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'linux-x64' + + - 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 + IsEarlyAccess: ${{ parameters.IsEarlyAccess }} + DOTNET_RUNTIME_VERSION: ${{ parameters.DOTNET_RUNTIME_VERSION }} + DOTNET_SDK_VERSION: ${{ parameters.DOTNET_SDK_VERSION }} + dotnetArch: 'linux-arm64' + +- stage: ManualValidation + dependsOn: [] + displayName: Manual Validation + jobs: + - 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: PublishGitHubRelease + displayName: Publish GitHub + dependsOn: + - setReleaseTagAndChangelog + - UpdateChangeLog + variables: + ob_release_environment: ${{ parameters.releaseEnvironment }} + jobs: + - template: /.pipelines/templates/release-github.yml@self + parameters: + skipPublish: ${{ parameters.SkipPublish }} + +- stage: PushGitTagAndMakeDraftPublic + displayName: Push Git Tag and Make Draft Public + dependsOn: PublishGitHubRelease + 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: PublishNugetRelease + displayName: Publish Nuget Release + dependsOn: + - setReleaseTagAndChangelog + - PushGitTagAndMakeDraftPublic + - UpdateChangeLog + variables: + ob_release_environment: ${{ parameters.releaseEnvironment }} + jobs: + - template: /.pipelines/templates/release-Nuget.yml@self + parameters: + skipPublish: ${{ parameters.SkipPublish }} + +- 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/.pipelines/templates/stages/PowerShell-vPack-Stages.yml b/.pipelines/templates/stages/PowerShell-vPack-Stages.yml new file mode 100644 index 00000000000..01a83a5b161 --- /dev/null +++ b/.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/.pipelines/templates/step/finalize.yml b/.pipelines/templates/step/finalize.yml new file mode 100644 index 00000000000..78e0341c829 --- /dev/null +++ b/.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/.pipelines/templates/testartifacts.yml b/.pipelines/templates/testartifacts.yml new file mode 100644 index 00000000000..ffcb58aa96f --- /dev/null +++ b/.pipelines/templates/testartifacts.yml @@ -0,0 +1,138 @@ +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 + parameters: + architecture: 'win-x64' + + - 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 + parameters: + architecture: 'linux-x64' + + - 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/.pipelines/templates/uploadToAzure.yml b/.pipelines/templates/uploadToAzure.yml new file mode 100644 index 00000000000..45ed7c1fd3f --- /dev/null +++ b/.pipelines/templates/uploadToAzure.yml @@ -0,0 +1,449 @@ +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_deb_arm64 + itemPattern: '**/*.deb' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download deb arm64 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_x64 + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux minSize x64 package + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_linux_package_minSize_arm64 + itemPattern: '**/*.tar.gz' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download linux minSize arm64 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_x64_minsize + itemPattern: '**/*.zip' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows x64 minsize packages + + - task: DownloadPipelineArtifact@2 + inputs: + buildType: 'current' + artifact: drop_windows_package_package_win_arm64_minsize + itemPattern: '**/*.zip' + targetPath: '$(Build.ArtifactStagingDirectory)/downloads' + displayName: Download windows arm64 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/.pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml b/.pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml new file mode 100644 index 00000000000..d87334aef44 --- /dev/null +++ b/.pipelines/templates/variables/PowerShell-Coordinated_Packages-Variables.yml @@ -0,0 +1,81 @@ +parameters: + - name: InternalSDKBlobURL + type: string + default: ' ' + - name: EarlyAccessFeed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - 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 + - name: IsEarlyAccess + 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 + - name: EARLY_ACCESS_FEED + value: ${{ parameters.EarlyAccessFeed }} + - name: IsEarlyAccess + value: ${{ parameters.IsEarlyAccess }} diff --git a/.pipelines/templates/variables/PowerShell-Packages-Variables.yml b/.pipelines/templates/variables/PowerShell-Packages-Variables.yml new file mode 100644 index 00000000000..a9849a14252 --- /dev/null +++ b/.pipelines/templates/variables/PowerShell-Packages-Variables.yml @@ -0,0 +1,64 @@ +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 + - name: EarlyAccessFeed + type: string + default: 'net10' + values: + - 'net8' + - 'net9' + - 'net10' + - name: IsEarlyAccess + 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 }} + - name: EARLY_ACCESS_FEED + value: ${{ parameters.EarlyAccessFeed }} + - name: IsEarlyAccess + value: ${{ parameters.IsEarlyAccess }} diff --git a/.pipelines/templates/variables/PowerShell-Release-Azure-Variables.yml b/.pipelines/templates/variables/PowerShell-Release-Azure-Variables.yml new file mode 100644 index 00000000000..3b47e5eff2b --- /dev/null +++ b/.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/.pipelines/templates/variables/PowerShell-Release-Variables.yml b/.pipelines/templates/variables/PowerShell-Release-Variables.yml new file mode 100644 index 00000000000..930c559eafe --- /dev/null +++ b/.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/.pipelines/templates/variables/PowerShell-vPack-Variables.yml b/.pipelines/templates/variables/PowerShell-vPack-Variables.yml new file mode 100644 index 00000000000..7f00a5e0e2a --- /dev/null +++ b/.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/.pipelines/templates/variables/release-shared.yml b/.pipelines/templates/variables/release-shared.yml new file mode 100644 index 00000000000..70d3dd2df97 --- /dev/null +++ b/.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/.pipelines/templates/windows-hosted-build.yml b/.pipelines/templates/windows-hosted-build.yml new file mode 100644 index 00000000000..a89b8cd567d --- /dev/null +++ b/.pipelines/templates/windows-hosted-build.yml @@ -0,0 +1,324 @@ +parameters: + Architecture: 'x64' + BuildConfiguration: 'release' + JobName: 'build_windows' + dotnetArch: 'win-x64' + +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 + parameters: + architecture: ${{ parameters.dotnetArch }} + + - 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: '$(nuget_cert_id)' + 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/.poshchan/settings.json b/.poshchan/settings.json deleted file mode 100644 index 21ad0f08b48..00000000000 --- a/.poshchan/settings.json +++ /dev/null @@ -1,58 +0,0 @@ -{ - "version": "0.1", - "azdevops": { - "build_targets": { - "static": "PowerShell-CI-static-analysis", - "windows": "PowerShell-CI-Windows", - "macos": "PowerShell-CI-macOS", - "linux": "PowerShell-CI-Linux", - "ssh": "PowerShell-CI-SSH", - "all": [ - "PowerShell-CI-static-analysis", - "PowerShell-CI-Windows", - "PowerShell-CI-macOS", - "PowerShell-CI-Linux", - "PowerShell-CI-SSH" - ] - }, - "authorized_users": [ - "adityapatwardhan", - "anmenaga", - "bergmeister", - "daxian-dbw", - "iSazonov", - "JamesWTruher", - "KirkMunro", - "PaulHigin", - "rjmholt", - "SteveL-MSFT", - "TravisEz13", - "TylerLeonhardt", - "vexx32" - ] - }, - "failures": { - "authorized_users": [ - "adityapatwardhan", - "anmenaga", - "bergmeister", - "daxian-dbw", - "IISResetMe", - "iSazonov", - "JamesWTruher", - "KirkMunro", - "kwkam", - "PaulHigin", - "powercode", - "rjmholt", - "rkeithhill", - "SteveL-MSFT", - "TravisEz13", - "TylerLeonhardt", - "vexx32" - ] - }, - "reminders": { - "authorized_users": "*" - } -} diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 00000000000..222861c3415 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,4 @@ +{ + "tabWidth": 2, + "useTabs": false +} diff --git a/.spelling b/.spelling index 42a757b509d..cc711f0aa5a 100644 --- a/.spelling +++ b/.spelling @@ -8,13 +8,18 @@ 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 @@ -27,6 +32,8 @@ adityapatwardhan ADOPTERS.md aetos382 aiello +Aishat452 +al-cheb alepauly alexandair alexjordan6 @@ -45,6 +52,7 @@ alpha.9 alternatestream alvarodelvalle amd64 +ananya26-vishnoi andschwa anmenaga api @@ -53,23 +61,29 @@ 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 @@ -81,40 +95,57 @@ 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 @@ -132,10 +163,14 @@ CodeFormatter codeowner codepage commanddiscovery +CommandInvocationIntrinsics commandsearch CommandSearcher comobject +Compiler.cs composability +computerinfo +ComRuntimeHelpers.cs config connect-pssession consolehost @@ -163,6 +198,8 @@ CorePsAssemblyLoadContext.cs coveralls.exe coveralls.io. coveralls.net +CreateFile +CreateFileW credssp cron crontab @@ -176,9 +213,11 @@ ctrl CurrentCulture CustomShellCommands.cs DamirAinullin +DarylGraves darquewarrior darwinjs DateTime +DateTime.UnixEpoch daxian-dbw dayofweek dchristian3188 @@ -214,23 +253,28 @@ displaydataquery Distribution_Request.md distro distros +dkaszews dll +DllImport dlls dlwyatt dockerbasedbuild dockerfile dockerfiles -docs.microsoft.com +learn.microsoft.com doctordns don'ts dongbo dotcover dotnet dotnetcore +dotnetmetadata.json DotnetRutimeMetadata.json +DotnetRuntimeMetadata.json dottedscopes downlevel dropdown +dwtaber e.g. ebook ebooks @@ -254,6 +298,7 @@ ergo3114 errorrecord etl eugenesmlv +EventLogLogProvider excludeversion exe executables @@ -265,25 +310,32 @@ 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 @@ -292,6 +344,7 @@ functionprovider FunctionTable fxdependent gabrielsroka +GAC_Arm64 gamified gc.regions.xml Generic.SortedList @@ -332,32 +385,40 @@ 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 @@ -365,6 +426,7 @@ httpbin's https hubuk hvitved +i3arnon i.e. ico idera @@ -382,7 +444,10 @@ includeide includeusername informationrecord initializers +InitialSessionState.cs +InlineAsTypeCheck install-packageprovider +IntelliSense interactivetesting interop interoperation @@ -391,6 +456,7 @@ invoke-cimmethod Invoke-DSCResource invoke-restmethod invoke-wsmanaction +InvokeRestMethodCommand.Common iot isazonov iscore @@ -410,19 +476,24 @@ 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 @@ -443,7 +514,9 @@ launch.json ldspits lee303 Leonhardt +Libera.Chat libicu +LibraryImport libpsl libpsl-native libunwind8 @@ -459,18 +532,25 @@ 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 @@ -479,14 +559,19 @@ 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 @@ -501,14 +586,19 @@ 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 @@ -524,11 +614,15 @@ mwrock myget namedpipe nameof +NameObscurerTelemetryInitializer namespace nano nanoserver +NativeCommandProcessor.cs +NativeCultureResolver nativeexecution net5.0 +net10.0 netcoreapp5.0 netip.ps1. netstandard.dll @@ -554,7 +648,10 @@ new-winevent new-wsmaninstance new-wsmansessionoption NextTurn +ngharo +Newtonsoft.Json NJsonSchema +nohwnd NoMoreFood non-22 non-cim @@ -586,6 +683,7 @@ openssh openssl opensuse oss +OutputType p1 packagemanagement PackageVersion @@ -593,8 +691,11 @@ parameshbabu parameterbinderbase parameterbindercontroller parameterbinding +ParenExpression ParseError.ToString +Path.Join pathresolution +PathResolvedToMultiple patochun patwardhan paulhigin @@ -603,7 +704,11 @@ payette perf perfview perfview.exe +peter-evans petseral +PingPathCommand.cs +pinvoke +pinvokes plaintext pluggable pluralsight @@ -624,12 +729,15 @@ 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 @@ -637,6 +745,7 @@ prepend preprocessor preview.1 preview.2 +preview.2.22153.17 preview.3 preview.4 preview.5 @@ -645,18 +754,26 @@ 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 @@ -675,8 +792,10 @@ PSGalleryModules psm1 psobject psobjects +psoptions.json psproxyjobs psreadline +psresourceget psrp.windows psscriptanalyzer pssessionconfiguration @@ -690,13 +809,19 @@ 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 @@ -706,11 +831,13 @@ readme.md readonly ReadyToRun rebase +rebase.yml rebasing receive-pssession recurse reddit redhat +redirections redistributable redistributables register-argumentcompleter @@ -721,6 +848,8 @@ register-packagesource register-psrepository registryprovider relationlink +releaseTools.psm1 +RemoteSessionNamedPipe remotesigned remoting remove-ciminstance @@ -758,13 +887,17 @@ rkitover robo210 ronn rpalo +rpolley +runas runspace runspaceinit runspaces runtime runtimes +Ryan-Hutchison-USAF SA1026CodeMustNotContainSpaceAfterNewKeywordInImplicitlyTypedArrayAllocation Saancreed +SafeRegistryHandle sample-dotnet1 sample-dotnet2 sarithsutha @@ -778,6 +911,7 @@ scriptblock securestring seemethere select-xml +SemanticChecks semver serverless sessionid @@ -800,6 +934,7 @@ set-wsmaninstance set-wsmanquickconfig sethvs setversionvariables +sha256 ShaydeNofziger shellexecute shouldbeerrorid @@ -808,6 +943,7 @@ Shriram0908 silijon simonwahlin singleline +sles15 smes snapcraft snapin @@ -825,6 +961,7 @@ start-codecoveragerun start-pspester stdin stevel-msft +StevenLiekens stevend811 stknohg strawgate @@ -834,6 +971,7 @@ string.split stringbuilder stuntguy3000 StyleCop +subfolder submodule submodules sudo @@ -851,6 +989,7 @@ System.IO.Packaging System.InvalidOperationException system.manage system.management.automation +System.Management.Automation.utils systemd SytzeAndr tabcompletion @@ -861,6 +1000,7 @@ TargetFramework test-modulemanifest test-pssessionconfigurationfile test-scriptfileinfo +tar.gz test.ps1 test.txt. Tests.ps1 @@ -868,6 +1008,7 @@ test1.txt test2.txt testcase testdrive +TestPathCommand.cs tests.zip tgz theflyingcorpse @@ -894,7 +1035,10 @@ toolset tracesource travisez13 travisty +trossr32 truher +TSAUpload +turbedi TValue tylerleonhardt typecataloggen @@ -903,9 +1047,11 @@ typegen typematch t_ ubuntu +ubuntu22.04 uint un-versioned unicode +UnixSocket unregister-event unregister-packagesource unregister-psrepository @@ -913,12 +1059,15 @@ unregister-pssessionconfiguration unregistering untracked unvalidated +UpdateDotnetRuntime.ps1 update-formatdata update-modulemanifest update-scriptfileinfo update-typedata uri +urizen-source urls +UseMU userdata uservoice utf-8 @@ -933,6 +1082,7 @@ v0.4.0 v0.5.0 v0.6.0 v141 +v2 v3 v4 v5 @@ -955,11 +1105,23 @@ 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 @@ -971,6 +1133,8 @@ walkthrough webcmdlets weblistener webrequest +webrequestpscmdlet.common.cs +webresponseobject.common weltner wesholton84 wget @@ -981,11 +1145,16 @@ wildcards win32 win32-openssh win7 +win8 windos +windows.json windowspsmodulepath windowsversion winrm wix +wmentha +WNetGetConnection +WNetAddConnection2 worrenb wpr wprui.exe @@ -1008,8 +1177,10 @@ yecril71pl yml youtube Youssef1313 +Yulv-git zackjknight ComInterop +ryneandal runtime#33060 vexx32 perf @@ -1038,6 +1209,7 @@ unvalidated Geweldig mjanko5 v7.0.0 +v7.0.10 renehernandez ece-jacob-scott st0le @@ -1055,6 +1227,126 @@ 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 @@ -1094,6 +1386,7 @@ weltkante kilasuit tnieto88 Orca88 +OrderBy centreboard romero126 Greg-Smulko @@ -1123,7 +1416,9 @@ Francisco-Gamino adamdriscoll analytics deserialized +string.Join string.Split +StringSplitOptions.TrimEntries Dictionary.TryAdd Environment.NewLine ParseError.ToString @@ -1146,6 +1441,35 @@ 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 @@ -1197,7 +1521,9 @@ ini package.json jcotton42 RPMs - - CHANGELOG/preview.md +PSDesiredStateConfiguration +dotnet5 + - CHANGELOG/7.2.md Gimly jborean93 mkswd @@ -1291,9 +1617,141 @@ 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/.vsts-ci/install-ps.yml b/.vsts-ci/install-ps.yml index 72f42551162..7190e228578 100644 --- a/.vsts-ci/install-ps.yml +++ b/.vsts-ci/install-ps.yml @@ -9,13 +9,8 @@ trigger: - feature* paths: include: - - /tools/install-powershell.sh - - /tools/installpsh-amazonlinux.sh - - /tools/installpsh-debian.sh - - /tools/installpsh-osx.sh - - /tools/installpsh-redhat.sh - - /tools/installpsh-suse.sh - - /tools/install-powershell.ps1 + - /tools/install-powershell.* + - /tools/installpsh-*.sh - /.vsts-ci/install-ps.yml pr: branches: @@ -26,11 +21,7 @@ pr: paths: include: - /tools/install-powershell.sh - - /tools/installpsh-amazonlinux.sh - - /tools/installpsh-debian.sh - - /tools/installpsh-osx.sh - - /tools/installpsh-redhat.sh - - /tools/installpsh-suse.sh + - /tools/installpsh-*.sh - /tools/install-powershell.ps1 - /.vsts-ci/install-ps.yml @@ -48,7 +39,19 @@ phases: jobName: InstallPowerShellUbuntu pool: ubuntu-latest verification: | - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"6.2.0") + 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)" } @@ -60,7 +63,7 @@ phases: 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]"6.2.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } @@ -72,7 +75,7 @@ phases: 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]"6.2.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } @@ -105,7 +108,7 @@ phases: jobName: InstallPowerShellMacOS pool: macOS-latest verification: | - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"6.2.0") + 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)" @@ -124,7 +127,7 @@ phases: pool: ubuntu-latest verification: | Write-Verbose $PSVersionTable.PSVersion -verbose - if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.0.0") + if ([Version]"$($PSVersionTable.PSVersion.Major).$($PSVersionTable.PSVersion.Minor).$($PSVersionTable.PSVersion.Patch)" -lt [version]"7.3.0") { throw "powershell was not upgraded: $($PSVersionTable.PSVersion)" } diff --git a/.vsts-ci/linux-daily.yml b/.vsts-ci/linux-daily.yml index 6ab1832dfd9..10effadd1e3 100644 --- a/.vsts-ci/linux-daily.yml +++ b/.vsts-ci/linux-daily.yml @@ -18,23 +18,14 @@ pr: branches: include: - master - - release* - - feature* paths: include: - - '*' - exclude: - - tools/releaseBuild/* - - tools/releaseBuild/azureDevOps/templates/* - - /.vsts-ci/misc-analysis.yml - - /.github/ISSUE_TEMPLATE/* - - /.dependabot/config.yml + - .vsts-ci/linux-daily.yml variables: DOTNET_CLI_TELEMETRY_OPTOUT: 1 POWERSHELL_TELEMETRY_OPTOUT: 1 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + DOTNET_NOLOGO: 1 __SuppressAnsiEscapeSequences: 1 resources: @@ -47,7 +38,7 @@ stages: jobs: - template: templates/ci-build.yml parameters: - pool: ubuntu-16.04 + pool: ubuntu-20.04 jobName: linux_build displayName: linux Build @@ -55,13 +46,14 @@ stages: displayName: Test for Linux jobs: - job: linux_test + timeoutInMinutes: 90 pool: - vmImage: ubuntu-16.04 + vmImage: ubuntu-20.04 displayName: Linux Test steps: - pwsh: | - Get-ChildItem -Path env: + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose displayName: Capture Environment condition: succeededOrFailed() @@ -149,7 +141,7 @@ stages: - job: CodeCovTestPackage displayName: CodeCoverage and Test Packages pool: - vmImage: ubuntu-16.04 + vmImage: ubuntu-20.04 steps: - pwsh: | Import-Module .\tools\ci.psm1 diff --git a/.vsts-ci/linux-internal.yml b/.vsts-ci/linux-internal.yml new file mode 100644 index 00000000000..b90ab0d9eb4 --- /dev/null +++ b/.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/.vsts-ci/linux.yml b/.vsts-ci/linux.yml index be7de6d8fc5..5d9dc663e1c 100644 --- a/.vsts-ci/linux.yml +++ b/.vsts-ci/linux.yml @@ -1,3 +1,12 @@ +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 @@ -11,9 +20,12 @@ trigger: include: - '*' exclude: - - /.vsts-ci/misc-analysis.yml - - /.github/ISSUE_TEMPLATE/* - - /.dependabot/config.yml + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - .pipelines/* + - test/perf/* pr: branches: include: @@ -22,83 +34,46 @@ pr: - feature* paths: include: - - '*' - exclude: - - test/common/markdown/* - - tools/releaseBuild/* - - tools/releaseBuild/azureDevOps/templates/* - - .vsts-ci/misc-analysis.yml - - .github/ISSUE_TEMPLATE/* - - .dependabot/config.yml - - .vsts-ci/windows.yml - - .vsts-ci/windows/* + - .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 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + DOTNET_NOLOGO: 1 __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none resources: -- repo: self - clean: true + repositories: + - repository: Docker + type: github + endpoint: PowerShell + name: PowerShell/PowerShell-Docker + ref: master stages: -- stage: BuildLinux +- stage: BuildLinuxStage displayName: Build for Linux jobs: - template: templates/ci-build.yml parameters: - pool: ubuntu-16.04 + pool: ubuntu-latest jobName: linux_build displayName: linux Build -- stage: TestLinux - displayName: Test for Linux +- stage: PackageLinux + displayName: Package Linux + dependsOn: ["BuildLinuxStage"] jobs: - - template: templates/nix-test.yml + - template: linux/templates/packaging.yml parameters: - name: Linux - pool: ubuntu-16.04 - purpose: UnelevatedPesterTests - tagSet: CI - - - template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: ElevatedPesterTests - tagSet: CI - - - template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: UnelevatedPesterTests - tagSet: Others - - - template: templates/nix-test.yml - parameters: - name: Linux - pool: ubuntu-16.04 - purpose: ElevatedPesterTests - tagSet: Others - - - template: templates/verify-xunit.yml - parameters: - pool: ubuntu-16.04 - -- 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-16.04 - steps: - - pwsh: | - Import-Module .\tools\ci.psm1 - New-CodeCoverageAndTestPackage - displayName: CodeCoverage and Test Package + pool: ubuntu-latest diff --git a/.vsts-ci/linux/templates/packaging.yml b/.vsts-ci/linux/templates/packaging.yml new file mode 100644 index 00000000000..8f77b8e24a0 --- /dev/null +++ b/.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/.vsts-ci/mac.yml b/.vsts-ci/mac.yml index 5f487275bf2..678ded65259 100644 --- a/.vsts-ci/mac.yml +++ b/.vsts-ci/mac.yml @@ -11,10 +11,13 @@ trigger: include: - '*' exclude: - - /tools/releaseBuild/**/* - - /.vsts-ci/misc-analysis.yml - - /.github/ISSUE_TEMPLATE/* - - /.dependabot/config.yml + - tools/releaseBuild/**/* + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - .pipelines/* + - test/perf/* pr: branches: include: @@ -25,23 +28,31 @@ pr: include: - '*' exclude: - - test/common/markdown/* - - .vsts-ci/misc-analysis.yml - - .github/ISSUE_TEMPLATE/* - .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/* - - /.vsts-ci/windows.yml - - /.vsts-ci/windows/* + - README.md + - .spelling + - .pipelines/* variables: DOTNET_CLI_TELEMETRY_OPTOUT: 1 POWERSHELL_TELEMETRY_OPTOUT: 1 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + DOTNET_NOLOGO: 1 # Turn off Homebrew analytics HOMEBREW_NO_ANALYTICS: 1 __SuppressAnsiEscapeSequences: 1 + nugetMultiFeedWarnLevel: none resources: - repo: self @@ -84,20 +95,20 @@ stages: parameters: pool: macOS-latest -- stage: CodeCovTestPackage - displayName: CodeCoverage and Test Packages - dependsOn: [] # by specifying an empty array, this stage doesn't depend on the stage before it +- stage: PackageMac + dependsOn: ['BuildMac'] + displayName: Package macOS (bootstrap only) jobs: - - job: CodeCovTestPackage - displayName: CodeCoverage and Test Packages - pool: - vmImage: macOS-latest - steps: - - pwsh: | - # Remove old .NET SDKs - if (Test-Path -Path $HOME/.dotnet) { - Remove-Item $HOME/.dotnet -Recurse -Force - } - Import-Module .\tools\ci.psm1 - New-CodeCoverageAndTestPackage - displayName: CodeCoverage and Test Package + - 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/.vsts-ci/misc-analysis.yml b/.vsts-ci/misc-analysis.yml deleted file mode 100644 index 8c81c604270..00000000000 --- a/.vsts-ci/misc-analysis.yml +++ /dev/null @@ -1,109 +0,0 @@ -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* - -pr: - branches: - include: - - master - - release* - - feature* - -resources: - repositories: - - repository: ComplianceRepo - type: github - endpoint: PowerShell - name: PowerShell/compliance - ref: master - -variables: - - name: repoFolder - value: PowerShell - -jobs: -- job: CI_Compliance - displayName: CI Compliance - - pool: - vmImage: windows-latest - - variables: - - name: repoPath - value: $(Agent.BuildDirectory)\$(repoFolder) - - steps: - - checkout: self - clean: true - path: $(repoFolder) - - - checkout: ComplianceRepo - - - template: ci-compliance.yml@ComplianceRepo - -- job: Linux_CI - displayName: Markdown and Common Tests - - pool: - vmImage: ubuntu-16.04 - - variables: - - name: repoPath - value: $(Agent.BuildDirectory)/$(repoFolder) - - steps: - - checkout: self - clean: true - path: $(repoFolder) - - - checkout: ComplianceRepo - - - powershell: | - Get-ChildItem -Path env: - displayName: Capture Environment - condition: succeededOrFailed() - - - powershell: | - Install-module Pester -Scope CurrentUser -Force -MaximumVersion 4.99 - displayName: Install Pester - condition: succeededOrFailed() - - - bash: | - curl -o- --progress-bar -L https://yarnpkg.com/install.sh | bash - displayName: Bootstrap Yarn - condition: succeededOrFailed() - - - bash: | - sudo yarn global add markdown-spellcheck@0.11.0 - displayName: Install mdspell - condition: succeededOrFailed() - - - bash: | - mdspell '**/*.md' '!**/Pester/**/*.md' --ignore-numbers --ignore-acronyms --report --en-us; - displayName: Test Spelling in Markdown - condition: succeededOrFailed() - workingDirectory: '$(repoPath)' - - - ${{ if not(contains(variables['SYSTEM.COLLECTIONURI'],'mscodehub')) }}: - - pwsh: | - Import-module ./build.psm1 - $path = Join-Path -Path $pwd -ChildPath './commonTestResults.xml' - $results = invoke-pester -Script ./test/common -OutputFile $path -OutputFormat NUnitXml -PassThru - Write-Host "##vso[results.publish type=NUnit;mergeResults=true;runTitle=Common Tests;publishRunAttachments=true;resultFiles=$path;]" - if($results.TotalCount -eq 0 -or $results.FailedCount -gt 0) - { - throw "Markdown tests failed" - } - displayName: Run Common Tests - condition: succeededOrFailed() - workingDirectory: '$(repoPath)' - - - template: dailyBuildCompliance.yml@ComplianceRepo - parameters: - sourceScanPath: '$(repoPath)' diff --git a/.vsts-ci/misc-analysis/generateMarkdownMatrix.yml b/.vsts-ci/misc-analysis/generateMarkdownMatrix.yml new file mode 100644 index 00000000000..56a43accd55 --- /dev/null +++ b/.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/.vsts-ci/psresourceget-acr.yml b/.vsts-ci/psresourceget-acr.yml new file mode 100644 index 00000000000..225e2699533 --- /dev/null +++ b/.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/.vsts-ci/sshremoting-tests.yml b/.vsts-ci/sshremoting-tests.yml index 016f3bfddca..72c5710016b 100644 --- a/.vsts-ci/sshremoting-tests.yml +++ b/.vsts-ci/sshremoting-tests.yml @@ -23,23 +23,34 @@ pr: - '/test/SSHRemoting/*' variables: - DOTNET_CLI_TELEMETRY_OPTOUT: 1 - POWERSHELL_TELEMETRY_OPTOUT: 1 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 - __SuppressAnsiEscapeSequences: 1 + - 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: + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose displayName: Capture Environment condition: succeededOrFailed() diff --git a/.vsts-ci/templates/ci-build.yml b/.vsts-ci/templates/ci-build.yml index 9dc43bc8ebf..5ec458c3c5a 100644 --- a/.vsts-ci/templates/ci-build.yml +++ b/.vsts-ci/templates/ci-build.yml @@ -1,47 +1,84 @@ parameters: - pool: 'vs2017-win2016' - jobName: 'win_build' - displayName: Windows Build + - 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: - vmImage: ${{ parameters.pool }} + ${{ if eq( parameters.PoolType, 'AzDoHosted') }}: + vmImage: ${{ parameters.pool }} + ${{ else }}: + name: ${{ parameters.pool }} + demands: + - ImageOverride -equals ${{ parameters.imageName }} displayName: ${{ parameters.displayName }} steps: - powershell: | - Get-ChildItem -Path env: + [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() - - powershell: Write-Host "##vso[build.updatebuildnumber]$env:BUILD_SOURCEBRANCHNAME-$env:BUILD_SOURCEVERSION-$((get-date).ToString("yyyyMMddhhmmss"))" + - 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 + - ${{ if ne(variables['UseAzDevOpsFeed'], '') }}: + - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml - - pwsh: | - if (Test-Path -Path $HOME/.dotnet) { - Remove-Item $HOME/.dotnet -Recurse -Force - } - displayName: Remove Old .NET SDKs - condition: succeededOrFailed() + - 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() - - powershell: | + - pwsh: | Import-Module .\tools\ci.psm1 Invoke-CIBuild displayName: Build condition: succeeded() - - powershell: | + - pwsh: | Import-Module .\tools\ci.psm1 Restore-PSOptions Invoke-CIxUnit -SkipFailing diff --git a/.vsts-ci/templates/credscan.yml b/.vsts-ci/templates/credscan.yml index f6ed5b8fd23..60094ff3d77 100644 --- a/.vsts-ci/templates/credscan.yml +++ b/.vsts-ci/templates/credscan.yml @@ -1,12 +1,12 @@ parameters: - pool: 'Hosted VS2017' + pool: 'windows-latest' jobName: 'credscan' displayName: Secret Scan jobs: - job: ${{ parameters.jobName }} pool: - name: ${{ parameters.pool }} + vmImage: ${{ parameters.pool }} displayName: ${{ parameters.displayName }} diff --git a/.vsts-ci/templates/install-ps-phase.yml b/.vsts-ci/templates/install-ps-phase.yml index f521cda0444..4e650273264 100644 --- a/.vsts-ci/templates/install-ps-phase.yml +++ b/.vsts-ci/templates/install-ps-phase.yml @@ -22,7 +22,7 @@ jobs: steps: - pwsh: | - Get-ChildItem -Path env: + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose displayName: Capture Environment condition: succeededOrFailed() diff --git a/.vsts-ci/templates/nanoserver.yml b/.vsts-ci/templates/nanoserver.yml deleted file mode 100644 index c989d01c2f8..00000000000 --- a/.vsts-ci/templates/nanoserver.yml +++ /dev/null @@ -1,61 +0,0 @@ -parameters: - vmImage: 'windows-2019' - jobName: 'Nanoserver_Tests' - continueOnError: false - -jobs: - -- job: ${{ parameters.jobName }} - variables: - scriptName: ${{ parameters.scriptName }} - - pool: - vmImage: ${{ parameters.vmImage }} - - displayName: ${{ parameters.jobName }} - - steps: - - script: | - set - 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: | - Install-module Pester -Scope CurrentUser -Force -MaximumVersion 4.99 - displayName: 'Install Pester' - continueOnError: true - - - pwsh: | - Import-Module .\tools\ci.psm1 - Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' - $options = (Get-PSOptions) - $path = split-path -path $options.Output - Write-Verbose "Path: '$path'" -Verbose - $rootPath = split-Path -path $path - Expand-Archive -Path '$(System.ArtifactsDirectory)\build\build.zip' -DestinationPath $rootPath -Force - Invoke-Pester -Path ./test/nanoserver -OutputFormat NUnitXml -OutputFile ./test-nanoserver.xml - displayName: Test - condition: succeeded() - - - task: PublishTestResults@2 - condition: succeededOrFailed() - displayName: Publish Nanoserver Test Results **\test*.xml - inputs: - testRunner: NUnit - testResultsFiles: '**\test*.xml' - testRunTitle: nanoserver - mergeTestResults: true - failTaskOnFailedTests: true diff --git a/.vsts-ci/templates/nix-test.yml b/.vsts-ci/templates/nix-test.yml index 6a1b6e6f9de..214ae14b2c6 100644 --- a/.vsts-ci/templates/nix-test.yml +++ b/.vsts-ci/templates/nix-test.yml @@ -1,78 +1,25 @@ parameters: pool: 'macOS-latest' - parentJobs: [] purpose: '' tagSet: 'CI' name: 'mac' jobs: - job: ${{ parameters.name }}_test_${{ parameters.purpose }}_${{ parameters.tagSet }} - dependsOn: - ${{ parameters.parentJobs }} + pool: vmImage: ${{ parameters.pool }} displayName: ${{ parameters.name }} Test - ${{ parameters.purpose }} - ${{ parameters.tagSet }} 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: | - if (Test-Path -Path $HOME/.dotnet) { - Remove-Item $HOME/.dotnet -Recurse -Force - } - displayName: Remove Old .NET SDKs - condition: succeededOrFailed() - - - 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 }}' - displayName: Test - condition: succeeded() + - 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/.vsts-ci/templates/test/nix-container-test.yml b/.vsts-ci/templates/test/nix-container-test.yml new file mode 100644 index 00000000000..37c60a4c53b --- /dev/null +++ b/.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/.vsts-ci/templates/test/nix-test-steps.yml b/.vsts-ci/templates/test/nix-test-steps.yml new file mode 100644 index 00000000000..f15d59ea73a --- /dev/null +++ b/.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/.vsts-ci/templates/verify-xunit.yml b/.vsts-ci/templates/verify-xunit.yml index 9e09584d5c3..b43cb9339f9 100644 --- a/.vsts-ci/templates/verify-xunit.yml +++ b/.vsts-ci/templates/verify-xunit.yml @@ -1,6 +1,6 @@ parameters: parentJobs: [] - pool: 'vs2017-win2016' + pool: 'windows-latest' jobName: 'xunit_verify' jobs: @@ -19,12 +19,12 @@ jobs: xunit/**/* downloadPath: '$(System.ArtifactsDirectory)' - - powershell: | + - pwsh: | dir "$(System.ArtifactsDirectory)\*" -Recurse displayName: 'Capture artifacts directory' continueOnError: true - - powershell: | + - pwsh: | Import-Module .\tools\ci.psm1 $xUnitTestResultsFile = "$(System.ArtifactsDirectory)\xunit\xUnitTestResults.xml" diff --git a/.vsts-ci/templates/windows-test.yml b/.vsts-ci/templates/windows-test.yml deleted file mode 100644 index b021e45f000..00000000000 --- a/.vsts-ci/templates/windows-test.yml +++ /dev/null @@ -1,62 +0,0 @@ -parameters: - pool: 'Hosted VS2017' - parentJobs: [] - purpose: '' - tagSet: 'CI' - -jobs: -- job: win_test_${{ parameters.purpose }}_${{ parameters.tagSet }} - dependsOn: - ${{ parameters.parentJobs }} - pool: - name: ${{ parameters.pool }} - - displayName: Windows Test - ${{ parameters.purpose }} - ${{ parameters.tagSet }} - - 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 - - # must be run frow Windows PowerShell - - powershell: | - # 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: | - 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 - Invoke-CITest -Purpose '${{ parameters.purpose }}' -TagSet '${{ parameters.tagSet }}' - displayName: Test - condition: succeeded() diff --git a/.vsts-ci/windows-arm64.yml b/.vsts-ci/windows-arm64.yml new file mode 100644 index 00000000000..1c4bc2ee8af --- /dev/null +++ b/.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/.vsts-ci/windows-daily.yml b/.vsts-ci/windows-daily.yml deleted file mode 100644 index f15d0926d1d..00000000000 --- a/.vsts-ci/windows-daily.yml +++ /dev/null @@ -1,178 +0,0 @@ -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 - - release* - - feature* - paths: - include: - - '*' - exclude: - - /.vsts-ci/misc-analysis.yml - - /.github/ISSUE_TEMPLATE/* - - /.dependabot/config.yml - -variables: - GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" - DOTNET_CLI_TELEMETRY_OPTOUT: 1 - POWERSHELL_TELEMETRY_OPTOUT: 1 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 - __SuppressAnsiEscapeSequences: 1 - -resources: -- repo: self - clean: true - -stages: -- stage: BuildWin - displayName: Build for Windows - jobs: - - template: templates/ci-build.yml - -- stage: TestWin - displayName: Test for Windows - variables: - - group: CLR-CAP - jobs: - - job: win_test - pool: - vmImage: vs2017-win2016 - displayName: Windows Test - timeoutInMinutes: 90 - - steps: - - pwsh: | - Get-ChildItem -Path env: - 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: | - $capRootDir = Join-Path ([System.IO.Path]::GetTempPath()) "CAP" - $capUtilDir = Join-Path $capRootDir "Utils" - - if (Test-Path $capRootDir) { Remove-Item $capRootDir -Recurse -Force } - New-Item $capUtilDir -ItemType Directory > $null - - $capZipFile = Join-Path $capRootDir "cap.zip" - Invoke-WebRequest -Uri https://pscoretestdata.blob.core.windows.net/dotnet-cap/windows.zip -OutFile $capZipFile - Unblock-File -Path $capZipFile - Expand-Archive -Path $capZipFile -DestinationPath $capUtilDir -Force - - Write-Host "=== Capture CAP Util Directory ===" - Get-ChildItem $capUtilDir -Recurse - - Write-Host "##vso[task.setvariable variable=CapRootDir]$capRootDir" - Write-Host "##vso[task.setvariable variable=CapUtilDir]$capUtilDir" - displayName: 'Download CAP package' - condition: succeededOrFailed() - - # must be run frow Windows PowerShell - - powershell: | - # 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 - - Import-Module .\tools\ci.psm1 - Invoke-CIInstall - displayName: Bootstrap - condition: succeededOrFailed() - - - pwsh: | - Import-Module .\build.psm1 - Restore-PSOptions -PSOptionsPath '$(System.ArtifactsDirectory)\build\psoptions.json' - $path = Split-Path -Parent (Get-PSOutput -Options (Get-PSOptions)) - $rootPath = Split-Path -Path $path - Expand-Archive -Path '$(System.ArtifactsDirectory)\build\build.zip' -DestinationPath $rootPath -Force - displayName: 'Unzip Build' - condition: succeeded() - - - pwsh: | - Import-Module $(CapUtilDir)\CAPService.psm1 - $dataDir = Start-TraceCollection -RootDir $(CapRootDir) - Write-Host "##vso[task.setvariable variable=CapDataDir]$dataDir" - displayName: 'Start CLR Trace Collection' - 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() - - - pwsh: | - $capDataDir = '$(CapDataDir)' - $capModuleFile = '$(CapUtilDir)\CAPService.psm1' - - if ((Test-Path $capModuleFile) -and (Test-Path $capDataDir)) { - Import-Module $capModuleFile - Stop-TraceCollection -DataDir $capDataDir -RepoRoot $pwd -IngressToken '$(CapIngressToken)' - } - displayName: 'Upload CLR Trace' - condition: always() diff --git a/.vsts-ci/windows.yml b/.vsts-ci/windows.yml index bdaa015832e..4171d09643d 100644 --- a/.vsts-ci/windows.yml +++ b/.vsts-ci/windows.yml @@ -11,9 +11,12 @@ trigger: include: - '*' exclude: - - /.vsts-ci/misc-analysis.yml - - /.github/ISSUE_TEMPLATE/* - - /.dependabot/config.yml + - .vsts-ci/misc-analysis.yml + - .github/ISSUE_TEMPLATE/* + - .github/workflows/* + - .dependabot/config.yml + - test/perf/* + - .pipelines/* pr: branches: include: @@ -22,22 +25,27 @@ pr: - feature* paths: include: - - '*' + - .vsts-ci/templates/* + - .vsts-ci/windows.yml + - '*.props' + - build.psm1 + - src/* + - test/* + - tools/buildCommon/* + - tools/ci.psm1 + - tools/WindowsCI.psm1 exclude: - - .vsts-ci/misc-analysis.yml - - .github/ISSUE_TEMPLATE/* - - .dependabot/config.yml - - tools/releaseBuild/* - - tools/releaseBuild/azureDevOps/templates/* - test/common/markdown/* + - test/perf/* variables: GIT_CONFIG_PARAMETERS: "'core.autocrlf=false'" DOTNET_CLI_TELEMETRY_OPTOUT: 1 POWERSHELL_TELEMETRY_OPTOUT: 1 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - DOTNET_SKIP_FIRST_TIME_EXPERIENCE: 1 + DOTNET_NOLOGO: 1 __SuppressAnsiEscapeSequences: 1 + NugetSecurityAnalysisWarningLevel: none + nugetMultiFeedWarnLevel: none resources: - repo: self diff --git a/.vsts-ci/windows/templates/windows-packaging.yml b/.vsts-ci/windows/templates/windows-packaging.yml index 19d2be32618..d23b745c30f 100644 --- a/.vsts-ci/windows/templates/windows-packaging.yml +++ b/.vsts-ci/windows/templates/windows-packaging.yml @@ -1,35 +1,111 @@ parameters: - pool: 'Hosted VS2017' - jobName: 'win_packaging' - architecture: 'x64' - channel: 'preview' - parentJobs: [] + - 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 }} - dependsOn: - ${{ parameters.parentJobs }} + + variables: + - name: repoFolder + value: PowerShell + - name: repoPath + value: $(Agent.BuildDirectory)\$(repoFolder) + - name: complianceRepoFolder + value: compliance + - name: complianceRepoPath + value: $(Agent.BuildDirectory)\$(complianceRepoFolder) + pool: - name: ${{ parameters.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: + Get-ChildItem -Path env: | Out-String -width 9999 -Stream | write-Verbose -Verbose displayName: Capture environment condition: succeededOrFailed() - - template: /tools/releaseBuild/azureDevOps/templates/insert-nuget-config-azfeed.yml + - 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 win7-${{ parameters.architecture }} -channel ${{ parameters.channel }} - displayName: Build and Test Package + Invoke-CIFinish -Runtime ${{ parameters.runtimePrefix }}-${{ parameters.architecture }} -channel ${{ parameters.channel }} -Stage Package + displayName: Package and Test + workingDirectory: $(repoPath) diff --git a/.vsts-ci/windows/windows-packaging.yml b/.vsts-ci/windows/windows-packaging.yml index f471196d963..6b73ca05723 100644 --- a/.vsts-ci/windows/windows-packaging.yml +++ b/.vsts-ci/windows/windows-packaging.yml @@ -27,32 +27,18 @@ pr: - release* - feature* paths: - # file extension filters are not supported when this was written. - # This really should be /src/**/*.csproj include: - - .vsts-ci/windows/* + - .vsts-ci/windows/*.yml - assets/wix/* - build.psm1 - global.json - nuget.config - PowerShell.Common.props - - src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj - - src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj - - src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj - - src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj - - src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj - - src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj - - src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj - - src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj - - src/Microsoft.PowerShell.MarkdownRender/Microsoft.PowerShell.MarkdownRender.csproj - - src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj - - src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj - - src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj - - src/Microsoft.WSMan.Runtime/Microsoft.WSMan.Runtime.csproj - - src/Modules/PSGalleryModules.csproj - - src/powershell-win-core/powershell-win-core.csproj + - src/*.csproj + - test/packaging/windows/* - tools/ci.psm1 - tools/packaging/* + - tools/wix/* variables: - name: GIT_CONFIG_PARAMETERS @@ -61,16 +47,24 @@ variables: value: 1 - name: POWERSHELL_TELEMETRY_OPTOUT value: 1 - # Avoid expensive initialization of dotnet cli, see: https://donovanbrown.com/post/Stop-wasting-time-during-NET-Core-builds - - name: DOTNET_SKIP_FIRST_TIME_EXPERIENCE + - name: DOTNET_NOLOGO value: 1 - name: __SuppressAnsiEscapeSequences value: 1 - group: fakeNugetKey + - name: SBOMGenerator_Formats + value: spdx:2.2 + - name: nugetMultiFeedWarnLevel + value: none resources: -- repo: self - clean: true + repositories: + - repository: ComplianceRepo + type: github + endpoint: PowerShell + name: PowerShell/compliance + ref: master + stages: - stage: PackagingWin displayName: Packaging for Windows @@ -86,3 +80,8 @@ stages: parameters: channel: preview architecture: x86 + - template: templates/windows-packaging.yml + parameters: + channel: preview + architecture: arm64 + runtimePrefix: win diff --git a/ADOPTERS.md b/ADOPTERS.md index 110f56d16e6..d7d1bdd82ce 100644 --- a/ADOPTERS.md +++ b/ADOPTERS.md @@ -10,28 +10,28 @@ Example entry: ``` --> -This is a list of adopters of using PowerShell in production or in their products (in alphabetical order): +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 batteries-included browser-based PowerShell environment used by Azure administrators to manage their environment. +* [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://docs.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 in 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 to manage function apps and service plans in the cloud. - For more information about Functions, please visit [functions overview](https://docs.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 websites, 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. + 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://devolutions.net/powershell-universal) is a unified platform for PowerShell automation. It provides script execution, scheduling, APIs and interactive web-based dashboards. +* [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://docs.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. - 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://docs.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 used by customers of GitHub Actions include PowerShell out of the box. +* [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. -* [Windows 10 IoT Core](https://docs.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. +* [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/Analyzers.props b/Analyzers.props index 14b63bff789..6f906496c73 100644 --- a/Analyzers.props +++ b/Analyzers.props @@ -1,5 +1,6 @@ - + + diff --git a/CHANGELOG/6.0.md b/CHANGELOG/6.0.md index b5993b5be30..52db53afabf 100644 --- a/CHANGELOG/6.0.md +++ b/CHANGELOG/6.0.md @@ -104,7 +104,7 @@ 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 hang and add context exception for remaining instances (#5595) +- 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 @@ -766,9 +766,8 @@ For more information on this, we invite you to read [this blog post explaining P ### 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), -on [the .NET blog](https://devblogs.microsoft.com/dotnet/introducing-net-standard/), -and [on GitHub](https://github.com/dotnet/standard/blob/master/docs/faq.md). +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! @@ -781,7 +780,7 @@ Many modules and cmdlets that didn't work in the past may now work on .NET Core, 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/X-Rejected/RFC0015-PowerShell-StartupConfig.md). +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. diff --git a/CHANGELOG/6.1.md b/CHANGELOG/6.1.md index f8e12f47001..59cf2842d78 100644 --- a/CHANGELOG/6.1.md +++ b/CHANGELOG/6.1.md @@ -428,7 +428,7 @@ - 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) -- Blacklist `System.Windows.Forms` from loading to prevent a crash (#6822) +- 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!) diff --git a/CHANGELOG/6.2.md b/CHANGELOG/6.2.md index 06ad8f41482..bf54f978eba 100644 --- a/CHANGELOG/6.2.md +++ b/CHANGELOG/6.2.md @@ -844,7 +844,7 @@ ### Documentation and Help Content -- Replace ambiguous `hang` term (#7902, #7931) (Thanks @iSazonov!) +- 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!) diff --git a/CHANGELOG/7.0.md b/CHANGELOG/7.0.md index af21d0bd957..e054b34cfc9 100644 --- a/CHANGELOG/7.0.md +++ b/CHANGELOG/7.0.md @@ -1,5 +1,241 @@ # 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 @@ -130,6 +366,8 @@ Bump .NET SDK to version 3.1.405 +[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 @@ -308,7 +546,7 @@ Move to .NET Core 3.1.202 SDK and update packages. - 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 key exchange hang with `SecureString` for the `OutOfProc` transports (#11380, #11406) +- 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 @@ -1168,7 +1406,6 @@ Move to .NET Core 3.1.202 SDK and update packages. - 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 diff --git a/CHANGELOG/7.1.md b/CHANGELOG/7.1.md index 86b7a478c30..eba1998e29c 100644 --- a/CHANGELOG/7.1.md +++ b/CHANGELOG/7.1.md @@ -1,5 +1,140 @@ # 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 diff --git a/CHANGELOG/7.2.md b/CHANGELOG/7.2.md new file mode 100644 index 00000000000..c9bde27a841 --- /dev/null +++ b/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/CHANGELOG/7.3.md b/CHANGELOG/7.3.md new file mode 100644 index 00000000000..25da137b1c2 --- /dev/null +++ b/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/CHANGELOG/7.4.md b/CHANGELOG/7.4.md new file mode 100644 index 00000000000..a503e7ceb6c --- /dev/null +++ b/CHANGELOG/7.4.md @@ -0,0 +1,1769 @@ +# 7.4 Changelog + +## [7.4.18] + +### Engine Updates and Fixes + +- Merged PR 40624: Validate CAB path before expansion + +### Tests + +- Update CI workflow to also target servicing-* branches (#27649) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 8.0.423

+ +
+ +
    +
  • Update branch for release (#27690)
  • +
  • Avoid calling credential provider for public feed for Wix (#27664)
  • +
  • Separate NuGet publish into its own stage after pushing the git tag (#27648)
  • +
+ +
+ +[7.4.18]: https://github.com/PowerShell/PowerShell/compare/v7.4.17...v7.4.18 + +## [7.4.17] + +### Code Cleanup + +
+ +
    +
  • Remove the unused Publish-NugetToMyGet command from packaging module (#27574)
  • +
+ +
+ +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 8.0.422

+ +
+ +
    +
  • Update branch for release (#27580)
  • +
  • Skip Store Publish when No Channel Selected (#27571)
  • +
  • Verify Apple codesign immediately after ESRP signing (#27540)
  • +
  • Remove unused step that clones Internal-PowerShellTeam-Tools repo in PMC publish pipeline (#27497)
  • +
+ +
+ +[7.4.17]: https://github.com/PowerShell/PowerShell/compare/v7.4.16...v7.4.17 + +## [7.4.16] + +### Engine Updates and Fixes + +- Fix checks for local user config file paths (#27454) + +### General Cmdlet Updates and Fixes + +- Update PowerShell telemetry to respect the diagnostics and feedback setting on Windows (#27430) +- Fix Out-GridView by replacing use of obsolete BinaryFormatter with custom implementation (#27426) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 8.0.421

+ +
+ +
    +
  • Update branch for release (#27475)
  • +
  • Add the windowsTargetName for .NET 8 (#27473)
  • +
  • Update the MSIXBundle-VPack pipeline to create VPack for both LTS and Stable channel packages (#27470)
  • +
  • Exclude .exe packages from publishing to GitHub (#27458)
  • +
  • Update Microsoft.PowerShell.Native to the latest GA version (#27448)
  • +
  • Externalize findMissingNotices target framework selection with ordered Windows fallback (#27427)
  • +
  • Correct Variable Template Reference in NonOfficial Pipeline Templates (#27428)
  • +
  • Fix *nix permissions and use certificate_logical_to_actual (#27452)
  • +
  • Remove package verification from the notice pipeline (#27429)
  • +
  • Add appLicensing capability to Appx manifest (#27449)
  • +
  • Add macOS binary code signing and package notarization (#27431)
  • +
  • Download PMC Packages through TemplateContext (#27330)
  • +
  • PMC release: Use slash instead of back-slash for Linux container (#27322)
  • +
+ +
+ +[7.4.16]: https://github.com/PowerShell/PowerShell/compare/v7.4.15...v7.4.16 + +## [7.4.15] + +### General Cmdlet Updates and Fixes + +- Delay update notification for one week to ensure all packages become available (#27229) +- Close pipe client handles after creating the child ssh process (#27139) + +### Tests + +- Fix the `PSNativeCommandArgumentPassing` test (#27146) + +### Build and Packaging Improvements + +
+ + + +

Update .NET SDK to 8.0.420

+ +
+ +
    +
  • Fix the container image for vPack, MSIX vPack and Package pipelines (#27018)
  • +
  • Update branch for release (#27279)
  • +
  • Fix package pipeline by adding in PDP-Media directory (#27255)
  • +
  • Pin ready-to-merge.yml reusable workflow to commit SHA (#27247)
  • +
  • [StepSecurity] ci: Harden GitHub Actions tags (#27244)
  • +
  • Build, package, and create VPack for the PowerShell-LTS store package within the same msixbundle-vpack pipeline (#27242)
  • +
  • Change the display name of PowerShell-LTS package to PowerShell LTS (#27232)
  • +
  • [StepSecurity] ci: Harden GitHub Actions tokens (#27231)
  • +
  • Redo windows image fix to use latest image (#27230)
  • +
  • Separate Store Package Creation, Skip Polling for Store Publish, Clean up PDP-Media (#27228)
  • +
  • Add comment-based help documentation to build.psm1 functions (#27227)
  • +
  • Fix a preview detection test for the packaging script (#27226)
  • +
  • Update the PhoneProductId to be the official LTS id used by Store (#27169)
  • +
  • Select New MSIX Package Name (#27173)
  • +
  • Publish .msixbundle package as a VPack (#27187)
  • +
  • Bump github/codeql-action from 4.32.4 to 4.35.1 (#27143) (#27171) (#27175)
  • +
  • release-upload-buildinfo: replace version-comparison channel gating with metadata flags (#27147)
  • +
  • Create infrastructure to create two msixs and msixbundles for LTS and Stable (#27145)
  • +
  • Move _GetDependencies MSBuild target from dynamic generation in build.psm1 into Microsoft.PowerShell.SDK.csproj (#27144)
  • +
  • Bump actions/dependency-review-action from 4.8.3 to 4.9.0 (#27142)
  • +
  • Bump actions/upload-artifact from 6 to 7 (#27141)
  • +
  • Separate Official and NonOfficial templates for ADO pipelines (#27140)
  • +
  • Mirror .NET/runtime ICU version range in PowerShell (#27138)
  • +
+ +
+ +[7.4.15]: https://github.com/PowerShell/PowerShell/compare/v7.4.14...v7.4.15 + +## [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/CHANGELOG/7.5.md b/CHANGELOG/7.5.md new file mode 100644 index 00000000000..95577e024e6 --- /dev/null +++ b/CHANGELOG/7.5.md @@ -0,0 +1,1061 @@ +# 7.5 Changelog + +## [7.5.9] + +### Engine Updates and Fixes + +- Merged PR 40624: Validate CAB path before expansion + +### Tests + +- Update CI workflow to also target servicing-* branches (#27651) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.316

+ +
+ +
    +
  • Update branch for release (#27682)
  • +
  • Avoid calling credential provider for public feed for Wix (#27665)
  • +
  • Separate NuGet publish into its own stage after pushing the git tag (#27650)
  • +
+ +
+ +[7.5.9]: https://github.com/PowerShell/PowerShell/compare/v7.5.8...v7.5.9 + +## [7.5.8] + +### Code Cleanup + +
+ + + +

Update to .NET SDK 9.0.315

+ +
+ +
    +
  • Remove the unused Publish-NugetToMyGet command from packaging module (#27575)
  • +
+ +
+ +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.315

+ +
+ +
    +
  • Update branch for release (#27581)
  • +
  • Skip Store Publish when No Channel Selected (#27572)
  • +
  • Verify Apple codesign immediately after ESRP signing (#27541)
  • +
  • Remove unused step that clones Internal-PowerShellTeam-Tools repo in PMC publish pipeline (#27498)
  • +
+ +
+ +[7.5.8]: https://github.com/PowerShell/PowerShell/compare/v7.5.7...v7.5.8 + +## [7.5.7] + +### Engine Updates and Fixes + +- Fix checks for local user config file paths (#27479) + +### General Cmdlet Updates and Fixes + +- Update PowerShell telemetry to respect the diagnostics and feedback setting on Windows (#27472) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.314

+ +
+ +
    +
  • Update branch for release (#27480)
  • +
  • Fix *nix permissions and use certificate_logical_to_actual (#27468)
  • +
  • Add the windowsTargetName for .NET 9 (#27474)
  • +
  • Add macOS binary code signing and package notarization (#27467)
  • +
  • Add appLicensing capability to Appx manifest (#27466)
  • +
  • Update Microsoft.PowerShell.Native to the latest GA version (#27465)
  • +
  • Update the MSIXBundle-VPack pipeline to create VPack for both LTS and Stable channel packages (#27464)
  • +
  • Remove package verification from the notice pipeline (#27463)
  • +
  • Correct Variable Template Reference in NonOfficial Pipeline Templates (#27462)
  • +
  • Externalize findMissingNotices target framework selection with ordered Windows fallback (#27461)
  • +
  • Exclude .exe packages from publishing to GitHub (#27460)
  • +
  • Download PMC Packages through TemplateContext (#27335)
  • +
  • Flip Stable PublishToChannel false for v7.5.X (#27333)
  • +
  • PMC release: Use slash instead of back-slash for Linux container (#27318)
  • +
+ +
+ +[7.5.7]: https://github.com/PowerShell/PowerShell/compare/v7.5.6...v7.5.7 + +## [7.5.6] + +### General Cmdlet Updates and Fixes + +- Delay update notification for one week to ensure all packages become available (#27220) + +### Tests + +- Fix the `PSNativeCommandArgumentPassing` test (#27166) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 9.0.313

+ +
+ +
    +
  • Update branch for the v7.5.6 release (#27268)
  • +
  • Fix package pipeline by adding in PDP-Media directory (#27256)
  • +
  • Pin ready-to-merge.yml reusable workflow to commit SHA (#27246)
  • +
  • [StepSecurity] ci: Harden GitHub Actions tags (#27239)
  • +
  • Build, package, and create VPack for the PowerShell-LTS store package within the same msixbundle-vpack pipeline (#27240)
  • +
  • Add comment-based help documentation to build.psm1 functions (#27221)
  • +
  • Separate store package creation, skip polling for store publish, clean up PDP-Media (#27225)
  • +
  • [StepSecurity] ci: Harden GitHub Actions tokens (#27224)
  • +
  • Change the display name of "PowerShell-LTS" package to "PowerShell LTS" (#27223)
  • +
  • Redo windows image fix to use latest image (#27222)
  • +
  • Bump github/codeql-action from 4.32.4 to 4.35.1 (#27159) (#27170) (#27174)
  • +
  • Select new MSIX package name (#27172)
  • +
  • Update the PhoneProductId to be the official LTS id used by Store (#27168)
  • +
  • release-upload-buildinfo: replace version-comparison channel gating with metadata flags (#27167)
  • +
  • Create infrastructure to create two msixs and msixbundles for LTS and Stable (#27165)
  • +
  • Move _GetDependencies MSBuild target from dynamic generation in build.psm1 into Microsoft.PowerShell.SDK.csproj (#27164)
  • +
  • Create Linux LTS deb/rpm packages for LTS releases (#27163)
  • +
  • Fix the container image for vPack, MSIX vPack and Package pipelines (#27161)
  • +
  • Create LTS pkg and non-LTS pkg for macOS for LTS releases (#27162)
  • +
  • Bump actions/dependency-review-action from 4.8.3 to 4.9.0 (#27158)
  • +
  • Bump actions/upload-artifact from 6 to 7 (#27157)
  • +
  • Separate "Official" and "NonOfficial" templates for ADO pipelines (#27155)
  • +
+ +
+ +[7.5.6]: https://github.com/PowerShell/PowerShell/compare/v7.5.5...v7.5.6 + +## [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/CHANGELOG/7.6.md b/CHANGELOG/7.6.md new file mode 100644 index 00000000000..ee6be496e8e --- /dev/null +++ b/CHANGELOG/7.6.md @@ -0,0 +1,943 @@ +# 7.6 Changelog + +## [7.6.4] + +### Engine Updates and Fixes + +- Merged PR 40624: Validate CAB path before expansion + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 10.0.302

+ +
+ +
    +
  • Update branch for release (#27685)
  • +
  • Avoid calling credential provider for public feed for Wix (#27666)
  • +
  • Separate NuGet publish into its own stage after pushing the git tag (#27652)
  • +
  • PMC: Download deb_arm artifact to ensure package is available for PMC publish flow (#27653)
  • +
+ +
+ +[7.6.4]: https://github.com/PowerShell/PowerShell/compare/v7.6.3...v7.6.4 + +## [7.6.3] + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 10.0.301

+ +
+ +
    +
  • Remove the unused Publish-NugetToMyGet command from packaging module (#27576)
  • +
  • Verify Apple codesign immediately after ESRP signing (#27542)
  • +
  • Remove unused step to clone Internal-PowerShellTeam-Tools repo in PMC publish pipeline (#27496)
  • +
+ +
+ +[7.6.3]: https://github.com/PowerShell/PowerShell/compare/v7.6.2...v7.6.3 + +## [7.6.2] + +### Engine Updates and Fixes + +- Enable usage in AppContainers (#27423) +- Fix checks for local user config file paths (#27432) + +### General Cmdlet Updates and Fixes + +- Update PowerShell telemetry to respect the diagnostics and feedback setting on Windows (#27438) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 10.0.300

+ +
+ +
    +
  • Update branch for release (#27446)
  • +
  • Fix *nix permissions and use certificate_logical_to_actual (#27439)
  • +
  • Specify linux-arm64 runtime if package type is deb-arm64 in packaging.psm1 (#27440)
  • +
  • Remove mariner2.0 from PMC mapping (#27422)
  • +
  • Remove package verification from the notice pipeline (#27425)
  • +
  • Update the MSIXBundle-VPack pipeline to create VPack for both LTS and Stable channel packages (#27435)
  • +
  • Update Microsoft.PowerShell.Native to the latest GA version (#27436)
  • +
  • Create PowerShell package for arm debian distribution (#27433)
  • +
  • Add macOS binary code signing and package notarization (#27434)
  • +
  • Externalize findMissingNotices target framework selection with ordered Windows fallback (#27424)
  • +
  • Add appLicensing capability to Appx manifest (#27437)
  • +
  • Download PMC Packages through TemplateContext (#27331)
  • +
  • PMC release: Use slash instead of back-slash for Linux container (#27319)
  • +
  • Correct Variable Template Reference in NonOfficial Pipeline Templates (#27317)
  • +
+ +
+ +[7.6.2]: https://github.com/PowerShell/PowerShell/compare/v7.6.1...v7.6.2 + +## [7.6.1] + +### General Cmdlet Updates and Fixes + +- Delay update notification for one week to ensure all packages become available (#27215) + +### Tests + +- Fix the `PSNativeCommandArgumentPassing` test (#27179) + +### Build and Packaging Improvements + +
+ + + +

Update to .NET SDK 10.0.202

+ +
+ +
    +
  • Fix PMC Repo URL for RHEL10 (#27061) (#27062)
  • +
  • Update branch for release (#27287)
  • +
  • Fix package pipeline by adding in PDP-Media directory (#27257)
  • +
  • Pin ready-to-merge.yml reusable workflow to commit SHA (#27245)
  • +
  • [StepSecurity] ci: Harden GitHub Actions tags (#27236)
  • +
  • Build, package, and create VPack for the PowerShell-LTS store package within the same msixbundle-vpack pipeline (#27237)
  • +
  • Change the display name of PowerShell-LTS package to PowerShell LTS (#27219)
  • +
  • [StepSecurity] ci: Harden GitHub Actions tokens (#27218)
  • +
  • Redo windows image fix to use latest image (#27217)
  • +
  • Add comment-based help documentation to build.psm1 functions (#27216)
  • +
  • Separate Store Package Creation, Skip Polling for Store Publish, Clean up PDP-Media (#27214)
  • +
  • Bump github/codeql-action from 4.34.1 to 4.35.1 (#27184)
  • +
  • Bump github/codeql-action from 4.32.6 to 4.34.1 (#27182)
  • +
  • Select New MSIX Package Name (#27183)
  • +
  • Update the PhoneProductId to be the official LTS id used by Store (#27181)
  • +
  • release-upload-buildinfo: replace version-comparison channel gating with metadata flags (#27180)
  • +
  • Move _GetDependencies MSBuild target from dynamic generation in build.psm1 into Microsoft.PowerShell.SDK.csproj (#27177)
  • +
  • Separate Official and NonOfficial templates for ADO pipelines (#27176)
  • +
+ +
+ +[7.6.1]: https://github.com/PowerShell/PowerShell/compare/v7.6.0...v7.6.1 + +## [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/CHANGELOG/README.md b/CHANGELOG/README.md index 83efcb0fed5..2b022e75735 100644 --- a/CHANGELOG/README.md +++ b/CHANGELOG/README.md @@ -1,8 +1,13 @@ # Changelogs -* [Current preview changelog](preview.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) +- [Current preview changelog](preview.md) +- [7.6 changelog](7.6.md) +- [7.5 changelog](7.5.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/CHANGELOG/preview.md b/CHANGELOG/preview.md index a4ad0c67431..d5b6ee1fc15 100644 --- a/CHANGELOG/preview.md +++ b/CHANGELOG/preview.md @@ -1,118 +1,70 @@ -# Current preview release +# Preview Changelog -## [7.2.0-preview.4] - 2021-03-16 +## [7.7.0-preview.3] -### Breaking Changes - -- Fix `Get-Date -UFormat` `%G` and `%g` behavior (#14555) (Thanks @brianary!) - -### Engine Updates and Fixes +### General Cmdlet Updates and Fixes -- Update engine script signature validation to match `Get-AuthenticodeSignature` logic (#14849) -- Avoid array allocations from `GetDirectories` and `GetFiles` (#14327) (Thanks @xtqqczze!) +- Change `New-Guid` to generate UUID v7 by default (#27033) (Thanks @SufficientDaikon!) +- Fix progress bar rendering with double-width unicode characters (#26185) (Thanks @yotsuda!) -### General Cmdlet Updates and Fixes +### Code Cleanup -- 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) +- Remove the unused `Publish-NugetToMyGet` command from packaging module (#27403) ### Tools -- Update `dependabot` configuration to V2 format (#14882) -- Add tooling issue slots in PR template (#14697) +- Remove `-Daily` from `install-powershell.ps1` since it no longer exists (#25124) ### Tests -- Move misplaced test file to tests directory (#14908) (Thanks @MarianoAlipi!) -- Refactor MSI CI (#14753) +- Update CI workflow to also target servicing-* branches (#27612) ### Build and Packaging Improvements
-Update .NET to version 6.0.100-preview.2.21155.3 + +

Update to .NET SDK 11.0.100-preview.6

+
    -
  • 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)
  • +
  • Update metadata.json for v7.7.0-preview.2 release (#27537)
  • +
  • [master] Update branch for release (#27683)
  • +
  • Avoid calling credential provider for public feed for Wix (#27663)
  • +
  • Produce min-size package for arm64 architecture (#27646)
  • +
  • Separate NuGet publish into its own stage after pushing the git tag (#27611)
  • +
  • PMC: Download deb_arm artifact to ensure package is available for PMC publish flow (#27635)
  • +
  • [master] Update branch for release (#27582)
  • +
  • Add PMC mappings for debian12 arm64 and debian13 arm64 (#27491)
  • +
  • Skip Store Publish when No Channel Selected (#27334)
### Documentation and Help Content -- Update `README.md` and `metadata.json` for upcoming releases (#14755) -- Merge 7.1.3 and 7.0.6 Change log 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 +- Add links to changelogs for versions 7.5 and 7.6 (#27080) (Thanks @behradbhrmi!) +- Update metadata.json for servicing releases (#27609) +- Bring Changelogs to Master Branch v7.4.17, v7.5.8, v7.6.3 (#27608) +- Update PowerShell Universal information. (#27550) (Thanks @adamdriscoll!) -## [7.2.0-preview.3] - 2021-02-11 - -### Breaking Changes +[7.7.0-preview.3]: https://github.com/PowerShell/PowerShell/compare/v7.7.0-preview.2...v7.7.0-preview.3 -- Fix `Get-Date -UFormat %u` behavior to comply with ISO 8601 (#14549) (Thanks @brianary!) +## [7.7.0-preview.2] ### 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!) +- Update `MaxVisitCount` and `MaxHashtableKeyCount` if `VisitorSafeValueContext` indicates `SkipLimitCheck` is true (#27306) +- Enable usage in AppContainers (#27266) ### 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!) +- Handle empty-string and null-value results returned from custom argument completer more properly (#27398) +- Add missing resource strings for `Get-WinEvent` (#27397) (Thanks @MartinGC94!) +- Improve `Get-WinEvent -ListLog` exception handling (#27395) (Thanks @MartinGC94!) +- Update PowerShell telemetry to respect the diagnostics and feedback setting on Windows (#27328) ### Code Cleanup @@ -121,273 +73,124 @@ Update .NET to version 6.0.100-preview.2.21155.3

We thank the following contributors!

-

@xtqqczze, @powercode

+

@xtqqczze

    -
  • 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!)
  • +
  • Remove eager initialization of _startupScripts to enable lazy thread-safe initialization (#25767) (Thanks @xtqqczze!)
  • +
  • Fix IDE0049 in System.Management.Automation [Part 4] (#27380) (Thanks @xtqqczze!)
  • +
  • Fix IDE0049 in System.Management.Automation [Part 3] (#27379) (Thanks @xtqqczze!)
  • +
  • Fix IDE0049 in System.Management.Automation [Part 2] (#27378) (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) +- Add an instruction file to ensure the Copyright header is present at the start of script and module files (#27408) ### 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 repo (#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

+

Update to .NET SDK 11.0.100-preview.4

    -
  • 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!)
  • +
  • Update branch to use the .NET 11 SDK 11.0.100-preview.4 (#27504)
  • +
  • Update metadata.json for the servicing releases (#27488)
  • +
  • Update CHANGELOG for v7.4.16, v7.5.7, and v7.6.2 releases (#27494)
  • +
  • Remove unused step that clones Internal-PowerShellTeam-Tools repo in PMC publish pipeline (#27495)
  • +
  • Update Microsoft.PowerShell.PSResourceGet version to 1.3.0-preview1 (#27487)
  • +
  • Verify Apple codesign immediately after ESRP signing (#27486) (Thanks @andyleejordan!)
  • +
  • Add appLicensing capability to Appx manifest to allow it to run without acquiring a Store license (#27412)
  • +
  • Bump actions/dependency-review-action from 4.9.0 to 5.0.0 (#27411)
  • +
  • Bump github/codeql-action from 4.35.3 to 4.35.4 (#27404)
  • +
  • Specify linux-arm64 runtime if package type is deb-arm64 in packaging.psm1 (#27401)
  • +
  • Bump github/codeql-action from 4.35.1 to 4.35.3 (#27394)
  • +
  • Update Microsoft.PowerShell.Native to the latest GA version (#27400)
  • +
  • Update the MSIXBundle-VPack pipeline to create VPack for both LTS and Stable channel packages (#27384)
  • +
  • Create PowerShell package for arm debian distribution (#26925)
  • +
  • Merge release/v7.7.0-preview.1 into master (#27374)
  • +
  • Update metadata.json for the new servicing and preview releases (#27307)
  • +
  • Fix changelog grab failure when only one header exists. (#27371)
  • +
  • Remove mariner2.0 from PMC mapping (#27068)
  • +
  • Download PMC Packages through TemplateContext (#27326)
  • +
  • Correct Variable Template Reference in NonOfficial Pipeline Templates (#27275)
  • +
  • PMC release: Use slash instead of back-slash for Linux container (#27315)
-### 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 +### Documentation and Help Content -
+- Update `README.md` to call out `PowerShell.Core.Instrumentation` needs to be in sync between `PowerShell` and `PowerShell-Native` repos (#27399) +- Update changelog for the v7.5.6 release (#27320) +- Update CHANGELOG for v7.4.15 (#27314) +- Update Changelog for release v7.6.1 (#27304) -
    -
  • 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)
  • -
+[7.7.0-preview.2]: https://github.com/PowerShell/PowerShell/compare/v7.7.0-preview.1...v7.7.0-preview.2 -
+## [7.7.0-preview.1] -### 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 +### Breaking Changes -## [7.2.0-preview.1] - 2020-11-17 +- Add `ValidateNotNullOrEmpty` attribute to the `-Property` of `Format-Table/List/Custom` (#26552) +- Fix to use accurate message for validating a string argument is not null and not an empty string (#26668) +- Correct handling of explicit `-[Operator]:$false` parameter values in `Where-Object` (#26485) (Thanks @yotsuda!) ### Engine Updates and Fixes -- Change the default fallback encoding for `GetEncoding` in `Start-Transcript` to be `UTF8` without a BOM (#13732) (Thanks @Gimly!) +- Update `MaxVisitCount` and `MaxHashtableKeyCount` if `VisitorSafeValueContext` indicates `SkipLimitCheck` is true +(#27308) +- Enable usage in AppContainers (#27305) +- Delay update notification for one week to ensure all packages become available (#27095) +- Fix up default value for parameters with the `in` modifier (#26785) (Thanks @jborean93!) +- Fix `WSManInstance` COM interface with `ResourceURI` (#26692) (Thanks @jborean93!) +- Refactor the module path construction code to make it more robust and easier to maintain (#26565) +- Fix checks for local user config file paths (#26269) ### 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) +- Add verbose message to `Get-Service` when properties cannot be returned (#27109) (Thanks @reabr!) +- Fix `Remove-Item` confirmation message to use provider path instead (#27123) (Thanks @scuzqy!) +- PSStyle: validate background index against `BackgroundColorMap` (#27106) (Thanks @cuiweixie!) +- Update PowerShell Profile DSC resource manifests to allow null for content (#26929) +- Add `SubjectAlternativeName` property to the `Signature` object returned from `Get-AuthenticodeSignature` (#26252) +- Mark `-NoTypeInformation` as obsolete no-op and evaluate `-IncludeTypeInformation` on by value on Csv cmdlets (#26719) (Thanks @yotsuda!) +- Support `TargetObject` position in `ParserErrors` (#26649) (Thanks @jborean93!) +- Fix the CLR internal error and null ref exception when running `show-command` with PowerShell API (#26669) +- Fix `Test-Json` false positive errors when using `oneOf` or `anyOf` in schema (#26618) (Thanks @yotsuda!) +- Add `ToRegex` method to `WildcardPattern` class (#26515) (Thanks @yotsuda!) +- Add `-ExcludeProperty` parameter to `Format-*` cmdlets (#26514) (Thanks @yotsuda!) +- Fix NOTES section formatting in comment-based help (#26512) (Thanks @yotsuda!) +- Disable AMSI content logging in release (#26235) (Thanks @xtqqczze!) +- Add tab completion for `$PSBoundParameters.Keys` switch cases and access patterns (#26483) (Thanks @yotsuda!) +- Fix formatting to properly handle the `Reset` VT sequences that appear in the middle of a string (#26424) +- Add `-Extension` parameter to `Join-Path` cmdlet (#26482) (Thanks @yotsuda!) +- Make `Export-Csv` `-Append` and `-NoHeader` mutually exclusive (#26472) (Thanks @yotsuda!) +- Respect `-Qualifier/-NoQualifier/-Leaf/-IsAbsolute:$false` in `Split-Path` (#26474) (Thanks @yotsuda!) +- Respect `-UseWindowsPowerShell:$false` in `New-PSSession` (#26469) (Thanks @yotsuda!) +- Respect `-Repeat/-MtuSize/-Traceroute:$false` in `Test-Connection` (#26479) (Thanks @yotsuda!) +- Fix `Invoke-RestMethod` to support read-only files in multipart form data (#26454) (Thanks @yotsuda!) +- Respect `-ListAvailable:$false` in `Get-TimeZone` (#26463) (Thanks @yotsuda!) +- Respect `-Shuffle:$false` in `Get-SecureRandom` (#26460) (Thanks @yotsuda!) +- Respect `-Shuffle:$false` in `Get-Random` (#26457) (Thanks @yotsuda!) +- DSC v3 resource for Powershell Profile (#26157) +- Make the experimental feature `PSFeedbackProvider` stable (#26343) +- Make some experimental features stable (#26348) +- Add `PSApplicationOutputEncoding` variable (#21219) (Thanks @jborean93!) +- Dynamically evaluate width of `LastWriteTime` for formatting output on Unix (#24624) (Thanks @MathiasMagnus!) +- Handle null reference exception in CsvCommands.cs: `ConvertPSObjectToCSV` (#26144) (Thanks @mikkas456!) +- Improve `ValidateLength` error message consistency and refactor validation tests (#25806) (Thanks @jorgeasaurus!) +- Correct handling of explicit `-Since:$false` parameter value in `Get-Uptime` (#26141) (Thanks @logiclrd!) +- Add property and event for debug attach (#25788) (Thanks @jborean93!) +- Fix memory leak in `GetFileShares` (#25896) (Thanks @xtqqczze!) +- Correct handling of explicit `-Empty:$false` parameter value in `New-Guid` (#26140) (Thanks @logiclrd!) ### Code Cleanup @@ -396,57 +199,81 @@ Update .NET to version 6.0.100-preview.2.21155.3

We thank the following contributors!

-

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

+

@xtqqczze, @yotsuda, @ThioJoe, @rwp0, @amritanand-py

    -
  • 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!)
  • +
  • Fix IDisposable implementation in sealed classes (#26215) (Thanks @xtqqczze!)
  • +
  • Enable CA1852: Seal internal types (#25890) (Thanks @xtqqczze!)
  • +
  • Remove obsolete CA2006 rule suppression (#25939) (Thanks @xtqqczze!)
  • +
  • Use consistent indentation in the file HelpersCommon.psm1 (#26608)
  • +
  • Centralize ExcludeProperty filter application in ViewGenerator base class (#26574) (Thanks @yotsuda!)
  • +
  • Refactor IsComputerNameValid character validation (#26274) (Thanks @xtqqczze!)
  • +
  • Remove obsolete test/docker/networktest directory (#26388)
  • +
  • Avoid regex for exact word matching in DscClassCache (#26306) (Thanks @xtqqczze!)
  • +
  • Enable analyzers: Use char overload (#26301) (Thanks @xtqqczze!)
  • +
  • Enable CA1200: Avoid using cref tags with a prefix (#26298) (Thanks @xtqqczze!)
  • +
  • Remove unused timeout variable from RemoteHyperVTests class (#26297) (Thanks @xtqqczze!)
  • +
  • Enable CA2022: Avoid inexact read with Stream.Read (#25814) (Thanks @xtqqczze!)
  • +
  • Fix a few simple typos in comments and string outputs (#25805) (Thanks @ThioJoe!)
  • +
  • Remove unused Azure Devops windows CI workflows (#26245)
  • +
  • Fix CA1837: Use Environment.ProcessId (#26242) (Thanks @xtqqczze!)
  • +
  • Enable IDE0080: RemoveConfusingSuppressionForIsExpression (#26206) (Thanks @xtqqczze!)
  • +
  • Remove redundant CharSet from StructLayout attributes. Part 1 (#26216) (Thanks @xtqqczze!)
  • +
  • Fix IDE0083: UseNotPattern (#26213) (Thanks @xtqqczze!)
  • +
  • Fix IDE0049 for string in System.Management.Automation (#25921) (Thanks @xtqqczze!)
  • +
  • Fix IDE0049 for object in System.Management.Automation. Part 1 (#25923) (Thanks @xtqqczze!)
  • +
  • Replace stackallocs with collection expressions (#25803) (Thanks @xtqqczze!)
  • +
  • Capitalize Windows in PSNativeWindowsTildeExpansion experimental feature description (#25266) (Thanks @rwp0!)
  • +
  • Fix SA1028: Code should not contain trailing whitespace. Part 1. (#26203) (Thanks @xtqqczze!)
  • +
  • Fix IDE0083: UseNotPattern (#26209) (Thanks @xtqqczze!)
  • +
  • Fix CA1852: Seal internal types. Part 1 (#26205) (Thanks @xtqqczze!)
  • +
  • Enable IDE0019: InlineAsTypeCheck (#25920) (Thanks @xtqqczze!)
  • +
  • Fix mismatched indentation in .config/suppress.json (#26192) (Thanks @xtqqczze!)
  • +
  • Replace custom method with File.ReadAllText() in ScriptAnalysis.cs (#26060) (Thanks @amritanand-py!)
  • +
  • Avoid possible multiple enumerations in ImportModuleCommand.IsPs1xmlFileHelper_IsPresentInEntries (#26104) (Thanks @xtqqczze!)
  • +
  • Enable SA1206: Declaration keywords should follow order (#24973) (Thanks @xtqqczze!)
  • +
  • Disable IDE0049: PreferBuiltInOrFrameworkType (#26094) (Thanks @xtqqczze!)
  • +
  • Enable CA1853: Unnecessary call to Dictionary.ContainsKey(key) (#26106) (Thanks @xtqqczze!)
  • +
  • Enable CA1860: Avoid using Enumerable.Any() extension method (#26109) (Thanks @xtqqczze!)
  • +
  • Enable CA1858: Use StartsWith instead of IndexOf (#26107) (Thanks @xtqqczze!)
  • +
  • Add CodeQL suppressions for NativeCommandProcessor (#26729)
### Tools -- Enable `CodeQL` Security scanning (#13894) -- Add global `AnalyzerConfig` with default configuration (#13835) (Thanks @xtqqczze!) +- Add GitOps policy to auto-label backport candidates when CL-BuildPackaging is added (#26881) +- Add Pester CI Analysis Skill (#26806) +- Delete unused winget release script (#26683) +- Improve error message from `Start-NativeExecution` (#26500) (Thanks @logiclrd!) +- Add default CODEOWNERS entry for maintainers (#26660) +- Add Attack Surface Analyzer Script (#26379) +- Add merge conflict marker detection to linux-ci workflow and refactor existing actions to use reusable get-changed-files action (#26350) +- Add reusable get-changed-files action and refactor existing actions (#26355) +- Refactor analyze job to reusable workflow and enable on Windows CI (#26322) +- Create github copilot setup workflow (#26285) +- Update dependabot.yml to monitor release/* branches (#26251) + +### Tests + +- Fix the `PSNativeCommandArgumentPassing` test (#27057) +- Fix `Import-Module.Tests.ps1` to handle Arm32 platform (#26862) +- Add comprehensive PowerShell class tests for `ConvertTo-Json` (#26769) (Thanks @yotsuda!) +- Add comprehensive `PSCustomObject` tests for `ConvertTo-Json` (#26743) (Thanks @yotsuda!) +- Add GitHub Actions annotations for Pester test failures (#26789) +- Add comprehensive depth and multilevel composition tests for `ConvertTo-Json` (#26744) (Thanks @yotsuda!) +- Add comprehensive array and dictionary tests for `ConvertTo-Json` (#26742) (Thanks @yotsuda!) +- Add comprehensive scalar type tests for `ConvertTo-Json` (#26736) (Thanks @yotsuda!) +- Fix the fuzzy test (#26402) +- Add Fuzz Tests (#26384) +- Fix merge conflict checker for empty file lists and filter *.cs files (#26365) +- Fix linux_packaging job being skipped when only packaging files change (#26315) +- Use `[initialsessionstate]` type accelerator (#25912) (Thanks @xtqqczze!) +- Add markdown link verification for PRs (#26219) +- Check for `GetWindowPlacement` success (#26122) (Thanks @xtqqczze!) ### Build and Packaging Improvements @@ -455,36 +282,106 @@ Update .NET to version 6.0.100-preview.2.21155.3

We thank the following contributors!

-

@mkswd, @xtqqczze

+

@powercode, @kasperk81, @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 repo (#13714)
  • -
  • Bump Markdig.Signed to 0.22.0 (#13741)
  • -
  • Use new release script for Linux packages (#13705)
  • +
  • Update branch for release (#27291)
  • +
  • Remove package verification from the notice pipeline (#27289)
  • +
  • Remove MSI from publishing pipeline (#27213)
  • +
  • Externalize findMissingNotices target framework selection with ordered Windows fallback (#27269)
  • +
  • Fix the package pipeline by adding in PDP-Media directory (#27254)
  • +
  • Bump actions/checkout from 4 to 6.0.2 (#27206)
  • +
  • Build, package, and create VPack for the PowerShell-LTS store package within the same msixbundle-vpack pipeline (#150) (#27209)
  • +
  • Pin ready-to-merge.yml reusable workflow to commit SHA (#27204)
  • +
  • Change the display name of PowerShell-LTS MSIX package to "PowerShell LTS" (#27203)
  • +
  • [StepSecurity] ci: Harden GitHub Actions (#27201)
  • +
  • [StepSecurity] ci: Harden GitHub Actions (#27202)
  • +
  • Redo windows image fix to use latest image (#27198)
  • +
  • Separate Store Package Creation, Skip Polling for Store Publish, Clean up PDP-Media (#27024)
  • +
  • Revert "Fetch latest ICU release version dynamically" (#27127)
  • +
  • Update package references and move to .NET SDK 11.0-preview.2 (#27117)
  • +
  • Add comment-based help documentation to build.psm1 functions (#27122) (Thanks @powercode!)
  • +
  • Bump github/codeql-action from 3.30.3 to 4.35.1 (#27120)
  • +
  • Select New MSIX Package Name (#27096)
  • +
  • Separate Official and NonOfficial templates for ADO pipelines (#26897)
  • +
  • Update the PhoneProductId to be the official LTS id used by Store (#27077)
  • +
  • release-upload-buildinfo: replace version-comparison channel gating with metadata flags (#27074)
  • +
  • Update build to create two msix's and msixbundles for LTS and Stable (#27056)
  • +
  • Update metadata.json for the v7.6.0 release (#27054)
  • +
  • Move _GetDependencies MSBuild target from dynamic generation in build.psm1 into Microsoft.PowerShell.SDK.csproj (#27052)
  • +
  • Fix PMC repo URL for RHEL10 (#27059)
  • +
  • Create Linux LTS deb/rpm packages for LTS releases (#27049)
  • +
  • Create LTS pkg and non-LTS pkg for macOS for LTS releases (#27039)
  • +
  • Fix the container image for vPack, MSIX vPack and Package pipelines (#27015)
  • +
  • Update Microsoft.PowerShell.PSResourceGet version to 1.2.0 (#27003)
  • +
  • Fix ConvertFrom-ClearlyDefinedCoordinates to handle API object coordinates (#26893)
  • +
  • Bump actions/upload-artifact from 4 to 7 (#26914)
  • +
  • Bump actions/dependency-review-action from 4.7.3 to 4.9.0 (#26938)
  • + +
  • Hardcode Official templates (#26928)
  • +
  • Add PMC packages for debian13 and rhel10 (#26912)
  • +
  • Split TPN manifest and Component Governance manifest (#26891)
  • +
  • Add version in description and pass store task on failure (#26885)
  • +
  • Correct the package name for .deb and .rpm packages (#26877)
  • +
  • Fix a preview detection test for the packaging script (#26882)
  • +
  • Exclude .exe packages from publishing to GitHub (#26859)
  • +
  • Update metadata.json for v7.6.0-rc.1 (#26856)
  • +
  • Fetch latest ICU release version dynamically (#26827) (Thanks @kasperk81!)
  • +
  • Update LangVersion to preview (#26214) (Thanks @xtqqczze!)
  • +
  • Update to .NET 11 SDK and update dependencies (#26783)
  • +
  • Update outdated package references (#26771)
  • +
  • Create es-metadata (#26759)
  • +
  • Add policy to restrict the Approved-LowRisk label (#26728)
  • +
  • Move PowerShell build to depend on .NET SDK 10.0.102 (#26697)
  • +
  • Update metadata.json to update the Latest attribute with a better name (#26380)
  • +
  • Update outdated package references (#26656)
  • +
  • Bring release changes from the v7.6.0-preview.6 release branch (#26627)
  • +
  • Update build to use .NET SDK 10.0.100 (#26448)
  • +
  • Update the macos package name for preview releases to match the previous pattern (#26429)
  • +
  • Fix condition syntax for StoreBroker package tasks in MSIX pipeline (#26427)
  • +
  • Fix template path for rebuild branch check in package.yml (#26425)
  • +
  • Update the WCF packages to the latest version that is compatible with v4.10.3 (#26406)
  • +
  • Add rebuild branch support with conditional MSIX signing (#26415)
  • +
  • Optimize/split windows package signing (#26403)
  • +
  • Improve ADO package build and validation across platforms (#26398)
  • +
  • Update outdated test package references (#26368)
  • +
  • Delete this way of collecting feedback (#26364)
  • +
  • Update the Microsoft.PowerShell.Native package version (#26347)
  • +
  • Add log grouping to build.psm1 for collapsible GitHub Actions logs (#26326)
  • +
  • Bump actions/setup-dotnet from 4 to 5 (#26327)
  • +
  • Update SDK to 10.0.100-rc.2.25502.107 (#26305)
  • +
  • Replace fpm with dpkg-deb for DEB package generation (#26281)
  • +
  • Replace fpm with native macOS packaging tools (pkgbuild/productbuild) (#26268)
  • +
  • Separate Store Automation Service Endpoints, Resolve AppID (#26210)
  • +
  • Update concurrency groups to prevent merge runs and pull request runs from canceling each other (#26257)
  • +
  • Update release tags to version 7.5.4 and 7.4.13 (#26258)
  • +
  • Update outdated package references (#26148)
  • +
  • Refactor: Centralize xUnit tests into reusable workflow and remove legacy verification (#26243)
  • +
  • Convert Azure DevOps Linux Packaging pipeline to GitHub Actions workflow (#26225)
  • +
  • Update vPack name (#26090)
  • +
  • Update metadata.json for v7.6.0-preview.5 release (#26158)
  • +
  • Bump ossf/scorecard-action from 2.4.2 to 2.4.3 (#26128)
### 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 +- Check in `7.6.md` after v7.6.0 release (#27063) +- Update changelog for release v7.5.5 (#27014) +- Add 7.4.14 changelog (#26998) +- Update `SECURITY.md` to remove email reporting option (#26653) +- Update changelog for the release v7.6.0-preview.6 (#26597) +- Explain the parameter `-UseNuGetOrg` in build documentation (#26507) (Thanks @logiclrd!) +- Update backport prompt (#26392) +- Add a backport prompt for copilot (#26383) +- Update `linux.md` documentation to reflect current CI build configuration (#26255) +- Add GitHub Copilot instruction files for PowerShell CI build system (#26253) +- Add documentation for publishing Pester test results in GitHub Actions (#26254) +- Remove Gitter from README (#26200) (Thanks @xtqqczze!) +- Remove nightly build status section from README.md (#26227) (Thanks @xtqqczze!) +- Update changelog for v7.5.4 and v7.4.13 (#26202) + +[7.7.0-preview.1]: https://github.com/PowerShell/PowerShell/compare/v7.6.0-rc.1...v7.7.0-preview.1 diff --git a/CHANGELOG/v7.7/dependencychanges.json b/CHANGELOG/v7.7/dependencychanges.json new file mode 100644 index 00000000000..b1360988cd2 --- /dev/null +++ b/CHANGELOG/v7.7/dependencychanges.json @@ -0,0 +1,54 @@ +[ + { + "ChangeType": "NonSecurity", + "Branch": "master", + "PackageId": ".NET SDK", + "FromVersion": "11.0.100-preview.2.26159.112", + "ToVersion": "11.0.100-preview.3.26207.106", + "VulnerabilityId": [], + "Severity": [], + "VulnerableRanges": [], + "AdvisoryUrls": [], + "Justification": "Updated .NET SDK. Building with the latest SDK is required.", + "TimestampUtc": "2026-04-17T17:16:15.7099916Z" + }, + { + "ChangeType": "NonSecurity", + "Branch": "master", + "PackageId": ".NET SDK", + "FromVersion": "11.0.100-preview.3.26207.106", + "ToVersion": "11.0.100-preview.4.26230.115", + "VulnerabilityId": [], + "Severity": [], + "VulnerableRanges": [], + "AdvisoryUrls": [], + "Justification": "Updated .NET SDK. Building with the latest SDK is required.", + "TimestampUtc": "2026-05-22T18:15:20.6826051Z" + }, + { + "ChangeType": "NonSecurity", + "Branch": "master", + "PackageId": ".NET SDK", + "FromVersion": "11.0.100-preview.4.26230.115", + "ToVersion": "11.0.100-preview.5.26302.115", + "VulnerabilityId": [], + "Severity": [], + "VulnerableRanges": [], + "AdvisoryUrls": [], + "Justification": "Updated .NET SDK. Building with the latest SDK is required.", + "TimestampUtc": "2026-06-09T19:43:07.2603946Z" + }, + { + "ChangeType": "NonSecurity", + "Branch": "master", + "PackageId": ".NET SDK", + "FromVersion": "11.0.100-preview.5.26302.115", + "ToVersion": "11.0.100-preview.6.26359.118", + "VulnerabilityId": [], + "Severity": [], + "VulnerableRanges": [], + "AdvisoryUrls": [], + "Justification": "Updated .NET SDK. Building with the latest SDK is required.", + "TimestampUtc": "2026-07-14T22:06:54.5097290Z" + } +] diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index 90768d1293e..686e5e7a090 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,8 +1,10 @@ -# Code of Conduct +# Microsoft Open Source Code of Conduct -This project has adopted the [Microsoft Open Source Code of Conduct][conduct-code]. -For more information see the [Code of Conduct FAQ][conduct-FAQ] or contact [opencode@microsoft.com][conduct-email] with any additional questions or comments. +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). -[conduct-code]: https://opensource.microsoft.com/codeofconduct/ -[conduct-FAQ]: https://opensource.microsoft.com/codeofconduct/faq/ -[conduct-email]: mailto:opencode@microsoft.com +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/DotnetRuntimeMetadata.json b/DotnetRuntimeMetadata.json index c1f96b55956..6cdee4d1ed1 100644 --- a/DotnetRuntimeMetadata.json +++ b/DotnetRuntimeMetadata.json @@ -1,11 +1,15 @@ { "sdk": { - "channel": "release/6.0.1xx-preview2", - "packageVersionPattern": "6.0.0-preview.2", - "sdkImageVersion": "6.0.100", - "nextChannel": "6.0.1xx-preview2/daily" + "channel": "9.0.1xx-preview6", + "quality": "daily", + "qualityFallback": "preview", + "packageVersionPattern": "9.0.0-preview.6", + "sdkImageVersion": "11.0.100-preview.6.26359.118", + "nextChannel": "9.0.0-preview.7", + "azureFeed": "", + "sdkImageOverride": "" }, - "internalfeed" : { - "url": null + "internalfeed": { + "url": "" } } diff --git a/Localize/LocProject.json b/Localize/LocProject.json new file mode 100644 index 00000000000..453d67c3f5a --- /dev/null +++ b/Localize/LocProject.json @@ -0,0 +1,759 @@ +{ + "Projects": [ + { + "LanguageSet": "VS_Main_Languages", + "LocItems": [ + { + "SourceFile": "src\\System.Management.Automation\\resources\\Authenticode.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\AuthorizationManagerBase.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\AutomationExceptions.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CatalogStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CimInstanceTypeAdapterResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CmdletizationCoreResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CommandBaseStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ConsoleInfoErrorStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CoreClrStubResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\Credential.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CredentialAttributeStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\CredUI.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\DebuggerStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\DescriptionsStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\DiscoveryExceptions.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\EnumExpressionEvaluatorStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ErrorCategoryStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ErrorPackage.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\EtwLoggingStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\EventingResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\EventResource.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ExperimentalFeatureStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ExtendedTypeSystem.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\FileSystemProviderStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\FormatAndOut_format_xxx.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\FormatAndOut_MshParameter.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\FormatAndOut_out_xxx.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\FormatAndOutXmlLoadingStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\GetErrorText.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\HelpDisplayStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\HelpErrors.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\HistoryStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\HostInterfaceExceptionsStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\InternalCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\InternalHostStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\InternalHostUserInterfaceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\Logging.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\Metadata.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\MiniShellErrors.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\Modules.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\MshHostRawUserInterfaceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\MshSignature.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\MshSnapInCmdletResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\MshSnapinInfo.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\NativeCP.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ParameterBinderStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ParserStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PathUtilsStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PipelineStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PowerShellStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ProgressRecordStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ProviderBaseSecurity.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\ProxyCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PSCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PSConfigurationStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PSDataBufferStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PSListModifierStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\PSStyleStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\RegistryProviderStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\RemotingErrorIdStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\RunspaceInit.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\RunspacePoolStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\RunspaceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\SecuritySupportStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\Serialization.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\SessionStateProviderBaseStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\SessionStateStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\StringDecoratedStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\SubsystemStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\SuggestionStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\TabCompletionStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\TransactionStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\TypesXmlStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\VerbDescriptionStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\System.Management.Automation\\resources\\WildcardPatternStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\System.Management.Automation\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.Infrastructure.CimCmdlets\\resources\\CimCmdletStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.Infrastructure.CimCmdlets\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\public.GraphicalHostResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\public.HelpWindowResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\public.InvariantResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\public.ShowCommandResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\public.UICultureResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.Management.UI.Internal\\resources\\public.XamlLocalizableResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.Management.UI.Internal\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Diagnostics\\resources\\GetEventResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Diagnostics\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ClearRecycleBinResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ClipboardResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\CmdletizationResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ComputerInfoResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ComputerResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\HotFixResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\NavigationResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ProcessCommandHelpResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ProcessResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\ServiceResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\TestConnectionResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\TestPathResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Management\\resources\\TimeZoneResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Management\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\AddMember.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\AddTypeStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\AliasCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\ConvertFromStringData.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\ConvertHTMLStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\ConvertMarkdownStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\CsvCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\Debugger.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\EventingStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\FormatAndOut_out_gridview.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\GetFormatDataStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\GetMember.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\GetRandomCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\GetUptimeStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\HostStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\HttpCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\ImplicitRemotingStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\ImportLocalizedDataStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\MatchStringStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\MeasureObjectStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\NewObjectStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\OutPrinterDisplayStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\SelectObjectStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\SendMailMessageStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\SortObjectStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\StartSleepStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\TestJsonCmdletStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\TraceCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\UnblockFileStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\UpdateDataStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\UpdateListStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\UtilityCommonStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\VariableCommandStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\WebCmdletStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\WriteErrorStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\WriteProgressResourceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Commands.Utility\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\CommandLineParameterParserStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ConsoleControlStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ConsoleHostRawUserInterfaceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ConsoleHostStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ConsoleHostUserInterfaceSecurityResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ConsoleHostUserInterfaceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ManagedEntranceStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\ProgressNodeStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\TranscriptStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.ConsoleHost\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.CoreCLR.Eventing\\resources\\DotNetEventingStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.CoreCLR.Eventing\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\CertificateCommands.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\CertificateProviderStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\CmsCommands.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\ExecutionPolicyCommands.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\SecureStringCommands.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\SignatureCommands.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.PowerShell.Security\\resources\\UtilsStrings.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.PowerShell.Security\\resources\\" + }, + { + "SourceFile": "src\\Microsoft.WSMan.Management\\resources\\WsManResources.resx", + "CopyOption": "LangIDOnPathAndName", + "OutputPath": "src\\Microsoft.WSMan.Management\\resources\\" + } + ] + } + ] +} diff --git a/PowerShell.Common.props b/PowerShell.Common.props index 38cd13e007d..82c0cd9cdfe 100644 --- a/PowerShell.Common.props +++ b/PowerShell.Common.props @@ -49,13 +49,20 @@ $([System.Text.RegularExpressions.Regex]::Match($(ReleaseTag), $(RegexReleaseTag)).Groups[6].Value) 100 + + 500 $([MSBuild]::Add($(ReleaseTagSemVersionPart), $(RCIncrementValue))) $(ReleaseTag) $(ReleaseTagVersionPart).$(ReleaseTagSemVersionPart) - $(ReleaseTagVersionPart) + $(ReleaseTagVersionPart).$(GAIncrementValue) + + $(PSCoreFileVersion) + $([System.Version]::Parse($(PSCoreFileVersion)).Major).$([System.Version]::Parse($(PSCoreFileVersion)).Minor).0.$([System.Version]::Parse($(PSCoreFileVersion)).Revision) @@ -82,7 +89,7 @@ --> $(PSCoreFileVersion) @@ -102,6 +109,9 @@ + + + @@ -164,33 +176,54 @@ portable + + + + EnvironmentVariable;Global + false + false + + + + + Global + + + + + true + true + + + + AppLocal + + + + + true + true + + true + portable - - + + true full - - - - false - portable - - - - - - portable - - strict diff --git a/PowerShell.sln b/PowerShell.sln index 224d27ab3fc..4938316281d 100644 --- a/PowerShell.sln +++ b/PowerShell.sln @@ -31,6 +31,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "powershell-unix", "src\powe 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 # diff --git a/README.md b/README.md index b469018e5d0..a7b31c475f8 100644 --- a/README.md +++ b/README.md @@ -1,155 +1,50 @@ # ![logo][] PowerShell Welcome to the PowerShell GitHub Community! -PowerShell Core is a cross-platform (Windows, Linux, and macOS) automation and configuration tool/framework that works well with your existing tools and is optimized +[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. +It includes a command-line shell, an associated scripting language, and a framework for processing cmdlets. -[logo]: https://raw.githubusercontent.com/PowerShell/PowerShell/master/assets/ps_black_64.svg?sanitize=true +[logo]: assets/ps_black_64.svg?sanitize=true -## Windows PowerShell vs. PowerShell Core +## Windows PowerShell vs. PowerShell 7+ -Although this repository started as a fork of the Windows PowerShell code base, changes made in this repository do not make their way back to Windows PowerShell 5.1 automatically. -This also means that [issues tracked here][issues] are only for PowerShell Core 6 and higher. -Windows PowerShell specific issues should be opened on [UserVoice][]. +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 -[UserVoice]: https://windowsserver.uservoice.com/forums/301869-powershell +[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 would like to learn more, we recommend reviewing the [getting started][] documentation. +If you are new to PowerShell and want to learn more, we recommend reviewing the [getting started][] documentation. -[getting started]: https://github.com/PowerShell/PowerShell/tree/master/docs/learning-powershell +[getting started]: https://learn.microsoft.com/powershell/scripting/learn/more-powershell-learning ## Get PowerShell -You can download and install a PowerShell package for any of the following platforms. - -| Supported Platform | Download (LTS) | Downloads (stable) | Downloads (preview) | How to Install | -| -------------------------------------------| ------------------------| ------------------------| ----------------------| ------------------------------| -| [Windows (x64)][corefx-win] | [.msi][lts-windows-64] | [.msi][rl-windows-64] | [.msi][pv-windows-64] | [Instructions][in-windows] | -| [Windows (x86)][corefx-win] | [.msi][lts-windows-86] | [.msi][rl-windows-86] | [.msi][pv-windows-86] | [Instructions][in-windows] | -| [Ubuntu 20.04][corefx-linux] | | [.deb][rl-ubuntu20] | [.deb][pv-ubuntu20] | [Instructions][in-ubuntu20] | -| [Ubuntu 18.04][corefx-linux] | [.deb][lts-ubuntu18] | [.deb][rl-ubuntu18] | [.deb][pv-ubuntu18] | [Instructions][in-ubuntu18] | -| [Ubuntu 16.04][corefx-linux] | [.deb][lts-ubuntu16] | [.deb][rl-ubuntu16] | [.deb][pv-ubuntu16] | [Instructions][in-ubuntu16] | -| [Debian 9][corefx-linux] | [.deb][lts-debian9] | [.deb][rl-debian9] | [.deb][pv-debian9] | [Instructions][in-deb9] | -| [Debian 10][corefx-linux] | [.deb][lts-debian10] | [.deb][rl-debian10] | [.deb][pv-debian10] | [Instructions][in-deb9] | -| [Debian 11][corefx-linux] | | [.deb][rl-debian11] | [.deb][pv-debian11] | | -| [CentOS 7][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-centos] | -| [CentOS 8][corefx-linux] | [.rpm][lts-centos8] | [.rpm][rl-centos8] | [.rpm][pv-centos8] | | -| [Red Hat Enterprise Linux 7][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-rhel7] | -| [openSUSE 42.3][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-opensuse] | -| [Fedora 30][corefx-linux] | [.rpm][lts-centos] | [.rpm][rl-centos] | [.rpm][pv-centos] | [Instructions][in-fedora] | -| [macOS 10.13+][corefx-macos] | [.pkg][lts-macos] | [.pkg][rl-macos] | [.pkg][pv-macos] | [Instructions][in-macos] | -| Docker | | | | [Instructions][in-docker] | - -You can download and install a PowerShell package for any of the following platforms, **which are supported by the community.** - -| Platform | Downloads (stable) | Downloads (preview) | How to Install | -| -------------------------| ------------------------| ----------------------------- | ------------------------------| -| Arch Linux | | | [Instructions][in-archlinux] | -| Kali Linux | [.deb][rl-ubuntu16] | [.deb][pv-ubuntu16] | [Instructions][in-kali] | -| Many Linux distributions | [Snapcraft][rl-snap] | [Snapcraft][pv-snap] | | - -You can also download the PowerShell binary archives for Windows, macOS and Linux. - -| Platform | Downloads (stable) | Downloads (preview) | How to Install | -| ---------------| --------------------------------------------------- | ------------------------------------------------| -----------------------------------------------| -| Windows | [32-bit][rl-winx86-zip]/[64-bit][rl-winx64-zip] | [32-bit][pv-winx86-zip]/[64-bit][pv-winx64-zip] | [Instructions][in-windows-zip] | -| macOS | [64-bit][rl-macos-tar] | [64-bit][pv-macos-tar] | [Instructions][in-tar-macos] | -| Linux | [64-bit][rl-linux-tar] | [64-bit][pv-linux-tar] | [Instructions][in-tar-linux] | -| Windows (Arm) | [64-bit][rl-winarm64] (preview) | [64-bit][pv-winarm64] | [Instructions][in-arm] | -| Raspbian (Arm) | [32-bit][rl-arm32]/[64-bit][rl-arm64] | [32-bit][pv-arm32]/[64-bit][pv-arm64] | [Instructions][in-raspbian] | - -[lts-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/PowerShell-7.0.6-win-x86.msi -[lts-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/PowerShell-7.0.6-win-x64.msi -[lts-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.ubuntu.18.04_amd64.deb -[lts-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.ubuntu.16.04_amd64.deb -[lts-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.debian.9_amd64.deb -[lts-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts_7.0.6-1.debian.10_amd64.deb -[lts-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts-7.0.6-1.rhel.7.x86_64.rpm -[lts-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts-7.0.6-1.centos.8.x86_64.rpm -[lts-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.0.6/powershell-lts-7.0.6-osx-x64.pkg - -[rl-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x64.msi -[rl-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x86.msi -[rl-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.ubuntu.20.04_amd64.deb -[rl-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.ubuntu.18.04_amd64.deb -[rl-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.ubuntu.16.04_amd64.deb -[rl-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.9_amd64.deb -[rl-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.10_amd64.deb -[rl-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell_7.1.3-1.debian.11_amd64.deb -[rl-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-1.rhel.7.x86_64.rpm -[rl-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-1.centos.8.x86_64.rpm -[rl-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-osx-x64.pkg -[rl-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-arm64.zip -[rl-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x86.zip -[rl-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/PowerShell-7.1.3-win-x64.zip -[rl-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-osx-x64.tar.gz -[rl-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-x64.tar.gz -[rl-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-arm32.tar.gz -[rl-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.1.3/powershell-7.1.3-linux-arm64.tar.gz -[rl-snap]: https://snapcraft.io/powershell - -[pv-windows-64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/PowerShell-7.2.0-preview.4-win-x64.msi -[pv-windows-86]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/PowerShell-7.2.0-preview.4-win-x86.msi -[pv-ubuntu20]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview_7.2.0-preview.4-1.ubuntu.20.04_amd64.deb -[pv-ubuntu18]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview_7.2.0-preview.4-1.ubuntu.18.04_amd64.deb -[pv-ubuntu16]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview_7.2.0-preview.4-1.ubuntu.16.04_amd64.deb -[pv-debian9]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview_7.2.0-preview.4-1.debian.9_amd64.deb -[pv-debian10]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview_7.2.0-preview.4-1.debian.10_amd64.deb -[pv-debian11]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview_7.2.0-preview.4-1.debian.11_amd64.deb -[pv-centos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview-7.2.0_preview.4-1.rhel.7.x86_64.rpm -[pv-centos8]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-preview-7.2.0_preview.4-1.centos.8.x86_64.rpm -[pv-macos]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-7.2.0-preview.4-osx-x64.pkg -[pv-winarm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/PowerShell-7.2.0-preview.4-win-arm64.zip -[pv-winx86-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/PowerShell-7.2.0-preview.4-win-x86.zip -[pv-winx64-zip]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/PowerShell-7.2.0-preview.4-win-x64.zip -[pv-macos-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-7.2.0-preview.4-osx-x64.tar.gz -[pv-linux-tar]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-7.2.0-preview.4-linux-x64.tar.gz -[pv-arm32]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-7.2.0-preview.4-linux-arm32.tar.gz -[pv-arm64]: https://github.com/PowerShell/PowerShell/releases/download/v7.2.0-preview.4/powershell-7.2.0-preview.4-linux-arm64.tar.gz -[pv-snap]: https://snapcraft.io/powershell-preview - -[in-windows]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows -[in-ubuntu16]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1604 -[in-ubuntu18]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-1804 -[in-ubuntu20]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#ubuntu-2004 -[in-deb9]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-9 -[in-deb10]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#debian-10 -[in-centos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#centos-7 -[in-rhel7]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#red-hat-enterprise-linux-rhel-7 -[in-opensuse]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#opensuse -[in-fedora]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#fedora -[in-archlinux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#arch-linux -[in-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos -[in-docker]: https://github.com/PowerShell/PowerShell-Docker -[in-kali]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#kali -[in-windows-zip]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows#zip -[in-tar-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#binary-archives -[in-tar-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos#binary-archives -[in-raspbian]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux#raspbian -[in-arm]: https://docs.microsoft.com/powershell/scripting/install/powershell-core-on-arm -[corefx-win]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#windows -[corefx-linux]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#linux -[corefx-macos]:https://github.com/dotnet/core/blob/master/release-notes/3.0/3.0-supported-os.md#macos - -To install a specific version, visit [releases](https://github.com/PowerShell/PowerShell/releases). +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/psgithubbi) with visualizations for community contributions and project status using PowerShell, Azure, and PowerBI. +[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/en/free-pro-team@latest/discussions/quickstart) is a feature to enable fluid and open discussions within the community +[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 the discussions. +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. @@ -159,73 +54,49 @@ Create or join a [discussion](https://github.com/PowerShell/PowerShell/discussio Want to chat with other members of the PowerShell community? -We have a Gitter Room which you can join below. +There are dozens of topic-specific channels on our community-driven PowerShell Virtual User Group, which you can join on: -[![Join the chat](https://img.shields.io/static/v1.svg?label=chat&message=on%20gitter&color=informational&logo=gitter)](https://gitter.im/PowerShell/PowerShell?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) +* [Discord](https://discord.gg/PowerShell) +* [IRC](https://web.libera.chat/#powershell) on Libera.Chat +* [Slack](https://aka.ms/psslack) -There is also the community-driven PowerShell Virtual User Group, which you can join on: +## Developing and Contributing -* [Slack](https://aka.ms/psslack) -* [Discord](https://aka.ms/psdiscord) +Want to contribute to PowerShell? Please start with the [Contribution Guide][] to learn how to develop and contribute. -## Add-ons and libraries +If you are developing .NET Core C# applications targeting PowerShell Core, [check out our FAQ][] to learn more about the PowerShell SDK NuGet package. -[Awesome PowerShell](https://github.com/janikvonrotz/awesome-powershell) has a great curated list of add-ons and resources. +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 the Repository +## Building PowerShell | Linux | Windows | macOS | |--------------------------|----------------------------|------------------------| | [Instructions][bd-linux] | [Instructions][bd-windows] | [Instructions][bd-macOS] | -If you have any problems building, please consult the developer [FAQ][]. - -### Build status of nightly builds - -| Azure CI (Windows) | Azure CI (Linux) | Azure CI (macOS) | Code Coverage Status | CodeFactor Grade | -|:-----------------------------------------|:-----------------------------------------------|:-----------------------------------------------|:-------------------------|:-------------------------| -| [![windows-nightly-image][]][windows-nightly-site] | [![linux-nightly-image][]][linux-nightly-site] | [![macOS-nightly-image][]][macos-nightly-site] | [![cc-image][]][cc-site] | [![cf-image][]][cf-site] | - -[bd-linux]: https://github.com/PowerShell/PowerShell/tree/master/docs/building/linux.md -[bd-windows]: https://github.com/PowerShell/PowerShell/tree/master/docs/building/windows-core.md -[bd-macOS]: https://github.com/PowerShell/PowerShell/tree/master/docs/building/macos.md +If you have any problems building PowerShell, please start by consulting the developer [FAQ]. -[FAQ]: https://github.com/PowerShell/PowerShell/tree/master/docs/FAQ.md - -[windows-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=32 -[linux-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=23 -[macos-nightly-site]: https://powershell.visualstudio.com/PowerShell/_build?definitionId=24 -[windows-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-Windows-daily -[linux-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-linux-daily?branchName=master -[macOS-nightly-image]: https://powershell.visualstudio.com/PowerShell/_apis/build/status/PowerShell-CI-macos-daily?branchName=master -[cc-site]: https://codecov.io/gh/PowerShell/PowerShell -[cc-image]: https://codecov.io/gh/PowerShell/PowerShell/branch/master/graph/badge.svg -[cf-site]: https://www.codefactor.io/repository/github/powershell/powershell -[cf-image]: https://www.codefactor.io/repository/github/powershell/powershell/badge +[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 just clone the repository: +You can clone the repository: ```sh git clone https://github.com/PowerShell/PowerShell.git ``` -See [working with the PowerShell repository](https://github.com/PowerShell/PowerShell/tree/master/docs/git) for more information. - -## Developing and Contributing - -Please see the [Contribution Guide][] for how to develop and contribute. -If you are developing .NET Core C# applications targeting PowerShell Core, please [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]: https://github.com/PowerShell/PowerShell/blob/master/.github/CONTRIBUTING.md -[check out our FAQ]: https://github.com/PowerShell/PowerShell/tree/master/docs/FAQ.md#where-do-i-get-the-powershell-core-sdk-package +For more information, see [working with the PowerShell repository](https://github.com/PowerShell/PowerShell/tree/master/docs/git). ## Support -For support, please see the [Support Section][]. +For support, see the [Support Section][]. [Support Section]: https://github.com/PowerShell/PowerShell/tree/master/.github/SUPPORT.md @@ -235,31 +106,30 @@ PowerShell is licensed under the [MIT license][]. [MIT license]: https://github.com/PowerShell/PowerShell/tree/master/LICENSE.txt -### Windows Docker Files and Images +### Docker Containers -License: By requesting and using the Container OS Image for Windows containers, you acknowledge, understand, and consent to the Supplemental License Terms available on Docker Hub: +> [!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. -- [Windows Server Core](https://hub.docker.com/r/microsoft/windowsservercore/) -- [Nano Server](https://hub.docker.com/r/microsoft/nanoserver/) +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 -By default, PowerShell collects the OS description and the version of PowerShell (equivalent to `$PSVersionTable.OS` and `$PSVersionTable.GitCommitId`) using [Application Insights](https://azure.microsoft.com/services/application-insights/). -To opt-out of sending telemetry, create an environment variable called `POWERSHELL_TELEMETRY_OPTOUT` set to a value of `1` before starting PowerShell from the installed location. -The telemetry we collect falls under the [Microsoft Privacy Statement](https://privacy.microsoft.com/privacystatement/). +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 [here][]. +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 -[here]: https://github.com/PowerShell/PowerShell/blob/master/docs/community/governance.md +## [Code of Conduct](CODE_OF_CONDUCT.md) -## [Code of Conduct][conduct-md] +Please see our [Code of Conduct](CODE_OF_CONDUCT.md) before participating in this project. -This project has adopted the [Microsoft Open Source Code of Conduct][conduct-code]. -For more information see the [Code of Conduct FAQ][conduct-FAQ] or contact [opencode@microsoft.com][conduct-email] with any additional questions or comments. +## [Security Policy](.github/SECURITY.md) -[conduct-code]: https://opensource.microsoft.com/codeofconduct/ -[conduct-FAQ]: https://opensource.microsoft.com/codeofconduct/faq/ -[conduct-email]: mailto:opencode@microsoft.com -[conduct-md]: https://github.com/PowerShell/PowerShell/tree/master/CODE_OF_CONDUCT.md +For any security issues, please see our [Security Policy](.github/SECURITY.md). diff --git a/Settings.StyleCop b/Settings.StyleCop index 7fa179ee02e..e10c02bdd12 100644 --- a/Settings.StyleCop +++ b/Settings.StyleCop @@ -162,6 +162,7 @@ op my sb + vt diff --git a/ThirdPartyNotices.txt b/ThirdPartyNotices.txt index 06747f655ca..4d033a0f682 100644 --- a/ThirdPartyNotices.txt +++ b/ThirdPartyNotices.txt @@ -15,251 +15,429 @@ 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.45.0 - BSD-2-Clause + + + +Copyright (c) . All rights reserved. -Microsoft.CodeAnalysis.Common 3.3.1 - Apache-2.0 -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -Apache License + 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -Version 2.0, January 2004 + 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. -http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND 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. - 1. Definitions. +--------------------------------------------------------- - +--------------------------------------------------------- - "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. +Humanizer.Core 2.14.1 - MIT - - "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. +Copyright .NET Foundation and Contributors +Copyright (c) .NET Foundation and Contributors - +MIT License - "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. +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: - "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. +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. - "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. +--------------------------------------------------------- - +--------------------------------------------------------- - "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. +Json.More.Net 2.1.1 - MIT - - "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). +Copyright (c) .NET Foundation and Contributors - +MIT License - "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. +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: - "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." +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. - "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. +--------------------------------------------------------- - 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. +--------------------------------------------------------- - 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +JsonPointer.Net 5.3.1 - MIT - (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and - (b) You must cause any modified files to carry prominent notices stating that You changed the files; and +Copyright (c) .NET Foundation and Contributors - (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +MIT License - (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +Copyright (c) .NET Foundation and Contributors - You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this 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: - 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. - 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. +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. - 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. - 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. +--------------------------------------------------------- - 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS +--------------------------------------------------------- -APPENDIX: How to apply the Apache License to your work. +JsonSchema.Net 7.4.0 - MIT -To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. -Copyright [yyyy] [name of copyright owner] +Copyright (c) .NET Foundation and Contributors -Licensed under the Apache License, Version 2.0 (the "License"); +MIT License -you may not use this file except in compliance with the License. +Copyright (c) .NET Foundation and Contributors -You may obtain a copy of the License at +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: -http://www.apache.org/licenses/LICENSE-2.0 +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -Unless required by applicable law or agreed to in writing, 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. -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. +Microsoft.ApplicationInsights 2.23.0 - MIT -------------------------------------------------------------------- -------------------------------------------------------------------- +(c) Microsoft Corporation -Microsoft.CodeAnalysis.CSharp 3.3.1 - Apache-2.0 -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. -Copyright (c) Microsoft Corporation. -9Copyright (c) Microsoft Corporation. -ACopyright (c) Microsoft Corporation. -BCopyright (c) Microsoft Corporation. -CCopyright (c) Microsoft Corporation. -DCopyright (c) Microsoft Corporation. -OCopyright (c) Microsoft Corporation. -Copyright (c) Microsoft Corporation. Alle Rechte +MIT License -Apache License +Copyright (c) -Version 2.0, January 2004 +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: -http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - 1. Definitions. +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. - +--------------------------------------------------------- - "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. +--------------------------------------------------------- - +Microsoft.Bcl.AsyncInterfaces 10.0.3 - MIT - "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - +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-2024 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) 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 - "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. +MIT License - +Copyright (c) - "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this 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. - "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. +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. - +--------------------------------------------------------- - "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. +--------------------------------------------------------- - +Microsoft.CodeAnalysis.Common 5.0.0 - MIT - "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - +(c) Microsoft Corporation +Copyright (c) .NET Foundation and Contributors - "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. +MIT License - +Copyright (c) - "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." +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. - "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. +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. - 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. +--------------------------------------------------------- - 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. +--------------------------------------------------------- - 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: +Microsoft.CodeAnalysis.CSharp 5.0.0 - MIT - (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and - (b) You must cause any modified files to carry prominent notices stating that You changed the files; and +(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 - (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and +MIT License - (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. +Copyright (c) - You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this 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: - 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. +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. - 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. +--------------------------------------------------------- - 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. +--------------------------------------------------------- - 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS +Microsoft.Extensions.ObjectPool 10.0.3 - MIT -APPENDIX: How to apply the Apache License to your work. -To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. +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) -Copyright [yyyy] [name of copyright owner] +MIT License -Licensed under the Apache License, Version 2.0 (the "License"); +Copyright (c) -you may not use this file except in compliance with the 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: -You may obtain a copy of the License at +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -http://www.apache.org/licenses/LICENSE-2.0 +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. -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. +Microsoft.PowerShell.MarkdownRender 7.2.1 - MIT -See the License for the specific language governing permissions and -limitations under the License. +(c) Microsoft Corporation +(c) Microsoft Corporation. PowerShell's Markdown Rendering project PowerShell Markdown Renderer -------------------------------------------------------------------- +MIT License -------------------------------------------------------------------- +Copyright (c) -Markdig.Signed 0.17.1 - BSD-2-Clause -(c) 2008 VeriSign, Inc. +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: -Copyright (c) . All rights reserved. +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +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. - 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. +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.ApplicationInsights 2.11.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. +--------------------------------------------------------- + +Microsoft.Win32.Registry.AccessControl 10.0.3 - 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-2024 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) 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 MIT License @@ -271,66 +449,88 @@ The above copyright notice and this permission notice shall be included in all c 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.NETCore.Platforms 3.0.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +Microsoft.Win32.SystemEvents 10.0.3 - 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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -Microsoft.PowerShell.Native 7.0.0-preview.2 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) by P.J. Plauger +(c) Microsoft Corporation MIT License @@ -342,220 +542,325 @@ The above copyright notice and this permission notice shall be included in all c 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 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. +Newtonsoft.Json 13.0.4 - MIT + + +Copyright James Newton-King 2008 Copyright (c) 2007 James Newton-King -Copyright (c) 1991-2017 Unicode, Inc. -Copyright (c) 2013-2017, Alfred Klomp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2005-2007, Nick Galbreath -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2016-2017, Matthieu Darbois -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) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +Copyright (c) James Newton-King 2008 +Copyright James Newton-King 2008 Json.NET The MIT License (MIT) -Copyright (c) .NET Foundation and Contributors - -All rights reserved. +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: +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. +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 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +runtime.android-arm.runtime.native.System.IO.Ports 10.0.3 - 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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -Microsoft.Win32.SystemEvents 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -Microsoft.Windows.Compatibility 3.0.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -Namotion.Reflection 1.0.7 - MIT -(c) 2008 VeriSign, Inc. +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-2024 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) 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 MIT License @@ -567,47 +872,69 @@ The above copyright notice and this permission notice shall be included in all c 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 12.0.2 - MIT -(c) 2008 VeriSign, Inc. -Copyright James Newton-King 2008 -Copyright (c) 2007 James Newton-King -Copyright (c) James Newton-King 2008 +runtime.linux-arm.runtime.native.System.IO.Ports 10.0.3 - MIT -The MIT License (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 - -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. - - -------------------------------------------------------------------- - -------------------------------------------------------------------- - -NJsonSchema 10.0.27 - MIT -(c) 2008 VeriSign, Inc. -Copyright Rico Suter, 2018 -Copyright (c) Rico Suter, 2018 -Copyright Rico Suter, 2018 4JSON Schema +Copyright (c) 1991-2024 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) 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 MIT License @@ -619,442 +946,691 @@ The above copyright notice and this permission notice shall be included in all c 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 4.6.0-rc2.19462.14 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +runtime.linux-arm64.runtime.native.System.IO.Ports 10.0.3 - 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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -runtime.linux-arm64.runtime.native.System.IO.Ports 4.6.0-rc2.19462.14 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -runtime.linux-x64.runtime.native.System.IO.Ports 4.6.0-rc2.19462.14 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -runtime.native.System.Data.SqlClient.sni 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -runtime.native.System.IO.Ports 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -runtime.osx-x64.runtime.native.System.IO.Ports 4.6.0-rc2.19462.14 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.CodeDom 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Collections.Immutable 1.5.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. +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. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 1991-2017 Unicode, Inc. -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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-2024 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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.ComponentModel.Composition 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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) 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 + +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. + +--------------------------------------------------------- + +--------------------------------------------------------- + +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) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers The MIT License (MIT) @@ -1081,734 +1657,1071 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------- +--------------------------------------------------------- -------------------------------------------------------------------- +--------------------------------------------------------- + +runtime.native.System.IO.Ports 10.0.3 - MIT -System.ComponentModel.Composition.Registration 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. + +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Configuration.ConfigurationManager 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Data.DataSetExtensions 4.5.0 - 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-2024 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) 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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Data.Odbc 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Data.OleDb 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Data.SqlClient 4.7.0 - MIT -2008 SQL Server 2012 -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Diagnostics.EventLog 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Diagnostics.PerformanceCounter 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.DirectoryServices 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.DirectoryServices.AccountManagement 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.DirectoryServices.Protocols 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Drawing.Common 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.IO.FileSystem.AccessControl 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.IO.Packaging 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.IO.Pipes.AccessControl 4.5.1 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 1991-2017 Unicode, Inc. -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) .NET Foundation Contributors +(c) Microsoft Corporation +Copyright (c) Sven Groot (Ookii.org) 2009 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) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS The MIT License (MIT) @@ -1834,487 +2747,756 @@ 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 10.0.3 - MIT -System.IO.Ports 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. + +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Management 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Memory 4.5.3 - MIT -(c) 2008 VeriSign, Inc. +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. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 1991-2017 Unicode, Inc. -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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-2024 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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Net.Http.WinHttpHandler 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS - -The MIT License (MIT) - -Copyright (c) .NET Foundation and Contributors - -All rights reserved. +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 -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: +MIT License -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Copyright (c) -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. +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.6.0 - MIT -(c) 2008 VeriSign, Inc. -(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) +System.Reflection.Context 10.0.3 - MIT -Copyright (c) .NET Foundation and Contributors -All rights reserved. +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-2024 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) 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 -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: +MIT License -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +Copyright (c) -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. +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 10.0.3 - MIT -System.Reflection.Context 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. + +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Reflection.DispatchProxy 4.5.0 - 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-2024 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) 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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Reflection.Emit 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Reflection.Emit.ILGeneration 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.Reflection.Emit.Lightweight 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.652802 - MIT -------------------------------------------------------------------- -System.Reflection.Metadata 1.6.0 - 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) @@ -2341,32 +3523,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------- +--------------------------------------------------------- -------------------------------------------------------------------- +--------------------------------------------------------- -System.Runtime.Caching 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 2007 James Newton-King -Copyright (c) 1991-2017 Unicode, Inc. -Copyright (c) 2013-2017, Alfred Klomp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2005-2007, Nick Galbreath -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2016-2017, Matthieu Darbois -Copyright (c) .NET Foundation Contributors +System.ServiceModel.NetFramingBase 10.0.652802 - MIT + + +(c) Microsoft Corporation 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) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) Provided The MIT License (MIT) @@ -2393,15 +3559,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------- +--------------------------------------------------------- -------------------------------------------------------------------- +--------------------------------------------------------- + +System.ServiceModel.NetTcp 10.0.652802 - MIT -System.ServiceModel.Duplex 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. + +(c) Microsoft Corporation Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) Provided The MIT License (MIT) @@ -2428,15 +3595,16 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------- +--------------------------------------------------------- -------------------------------------------------------------------- +--------------------------------------------------------- + +System.ServiceModel.Primitives 10.0.652802 - MIT -System.ServiceModel.Http 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. + +(c) Microsoft Corporation Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) Provided The MIT License (MIT) @@ -2463,85 +3631,238 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------- +--------------------------------------------------------- + +--------------------------------------------------------- + +System.ServiceModel.Syndication 10.0.3 - 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-2024 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) 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 + +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.ServiceProcess.ServiceController 10.0.3 - MIT -------------------------------------------------------------------- -System.ServiceModel.NetTcp 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) +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-2024 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) 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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 10.0.3 - MIT -------------------------------------------------------------------- -System.ServiceModel.Primitives 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) +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-2024 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) 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) +MIT License -Copyright (c) .NET Foundation and Contributors +Copyright (c) -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: -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 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. -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 -------------------------------------------------------------------- -System.ServiceModel.Security 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. +(c) Microsoft Corporation Copyright (c) .NET Foundation and Contributors -Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) +Copyright (c) 2000-2014 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) Provided The MIT License (MIT) @@ -2568,38 +3889,96 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------- +--------------------------------------------------------- -------------------------------------------------------------------- +--------------------------------------------------------- + +System.Windows.Extensions 10.0.3 - MIT -System.Threading.AccessControl 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. + +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. -(c) 1997-2005 Sean Eron Anderson. +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-2017 Unicode, Inc. +Copyright (c) 1991-2024 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 -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. +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 -Copyright (c) .NET Foundation and Contributors +(c) 1995-2024 Jean-loup Gailly and Mark Adler +Copyright (c) 2020 Mara Bos +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) 1995-2017 Jean-loup Gailly and Mark Adler Copyright (c) 2015 Xamarin, Inc (http://www.xamarin.com) -Copyright (c) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +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) +MIT License -Copyright (c) .NET Foundation and Contributors +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. + +--------------------------------------------------------- -All rights reserved. + +------------------------------------------------------------------- + +------------------------------------------------------------------- + +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 @@ -2608,47 +3987,75 @@ 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 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. +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. -System.Threading.Tasks.Extensions 4.5.3 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 1991-2017 Unicode, Inc. -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -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) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +MIT License -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: -Copyright (c) .NET Foundation and Contributors +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 +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 @@ -2657,7 +4064,7 @@ 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 +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 @@ -2665,40 +4072,16 @@ 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 -System.Windows.Extensions 4.6.0 - MIT -(c) 2008 VeriSign, Inc. -(c) Microsoft Corporation. -Copyright (c) .NET Foundation. -Copyright (c) 2011, Google Inc. -(c) 1997-2005 Sean Eron Anderson. -Copyright (c) 2007 James Newton-King -Copyright (c) 1991-2017 Unicode, Inc. -Copyright (c) 2013-2017, Alfred Klomp -Copyright (c) 2015-2017, Wojciech Mula -Copyright (c) 2005-2007, Nick Galbreath -Portions (c) International Organization -Copyright (c) 2015 The Chromium Authors. -Copyright (c) 2004-2006 Intel Corporation -Copyright (c) 2016-2017, Matthieu Darbois -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) 2009, 2010, 2013-2016 by the Brotli Authors. -Copyright (c) YEAR W3C(r) (MIT, ERCIM, Keio, Beihang). Disclaimers THIS WORK IS PROVIDED AS +All rights reserved. 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 @@ -2717,18 +4100,11 @@ 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 - - --------------------------------------------- File: PSReadLine --------------------------------------------- -https://github.com/lzybkr/PSReadLine +https://github.com/PowerShell/PSReadLine Copyright (c) 2013, Jason Shirk @@ -2756,35 +4132,16 @@ 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. ----------------------------------------------- -File: Hashtables from ConvertFrom-json ----------------------------------------------- - -https://stackoverflow.com/questions/22002748/hashtables-from-convertfrom-json-have-different-type-from-powershells-built-in-h - -Copyright (c) 2015 Dave Wyatt. All rights reserved. - -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. - ------------------------------------------------- -PackageManagement +ThreadJob ------------------------------------------------- -Copyright (c) Microsoft Corporation -All rights reserved. +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 +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 @@ -2793,7 +4150,7 @@ 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 +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 @@ -2801,34 +4158,3 @@ 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. - -------------------------------------------------------------------- diff --git a/assets/AppImageThirdPartyNotices.txt b/assets/AppImageThirdPartyNotices.txt deleted file mode 100644 index d492e7c3b53..00000000000 --- a/assets/AppImageThirdPartyNotices.txt +++ /dev/null @@ -1,506 +0,0 @@ -------------------------------------------- START OF THIRD PARTY NOTICE ----------------------------------------- - - This file is based on or incorporates material from the projects listed below (Third Party IP). The original copyright notice and the license under which Microsoft received such Third Party IP, are set forth below. Such licenses and notices are provided for informational purposes only. Microsoft licenses the Third Party IP to you under the licensing terms for the Microsoft product. Microsoft reserves all other rights not expressly granted under this agreement, whether by implication, estoppel or otherwise. - - - - -Copyright (c) 1991-2016 Unicode, Inc. All rights reserved. -Distributed under the Terms of Use in http://www.unicode.org/copyright.html - -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Unicode data files and any associated documentation -(the "Data Files") or Unicode software and any associated documentation -(the "Software") to deal in the Data Files or Software -without restriction, including without limitation the rights to use, -copy, modify, merge, publish, distribute, and/or sell copies of -the Data Files or Software, and to permit persons to whom the Data Files -or Software are furnished to do so, provided that either -(a) this copyright and permission notice appear with all copies -of the Data Files or Software, or -(b) this copyright and permission notice appear in associated -Documentation. - -THE DATA FILES AND SOFTWARE ARE 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 OF THIRD PARTY RIGHTS. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS -NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL -DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, -DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER -TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THE DATA FILES OR SOFTWARE. - -Except as contained in this notice, the name of a copyright holder -shall not be used in advertising or otherwise to promote the sale, -use or other dealings in these Data Files or Software without prior -written authorization of the copyright holder. - ---------------------- - -Third-Party Software Licenses - -This section contains third-party software notices and/or additional -terms for licensed third-party software components included within ICU -libraries. - -1. ICU License - ICU 1.8.1 to ICU 57.1 - -COPYRIGHT AND PERMISSION NOTICE - -Copyright (c) 1995-2016 International Business Machines Corporation and others -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, and/or sell copies of the Software, and to permit persons -to whom the Software is furnished to do so, provided that the above -copyright notice(s) and this permission notice appear in all copies of -the Software and that both the above copyright notice(s) and this -permission notice appear in supporting documentation. - -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 -OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR -HOLDERS INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY -SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER -RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF -CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN -CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - -Except as contained in this notice, the name of a copyright holder -shall not be used in advertising or otherwise to promote the sale, use -or other dealings in this Software without prior written authorization -of the copyright holder. - -All trademarks and registered trademarks mentioned herein are the -property of their respective owners. - -2. Chinese/Japanese Word Break Dictionary Data (cjdict.txt) - - # The Google Chrome software developed by Google is licensed under - # the BSD license. Other software included in this distribution is - # provided under other licenses, as set forth below. - # - # The BSD License - # https://opensource.org/licenses/bsd-license.php - # Copyright (C) 2006-2008, Google Inc. - # - # All rights reserved. - # - # Redistribution and use in source and binary forms, with or without - # modification, are permitted provided that the following conditions are met: - # - # Redistributions of source code must retain the above copyright notice, - # this list of conditions and the following disclaimer. - # 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. - # Neither the name of Google Inc. nor the names of its - # contributors may be used to endorse or promote products derived from - # this software without specific prior written permission. - # - # - # 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. - # - # - # The word list in cjdict.txt are generated by combining three word lists - # listed below with further processing for compound word breaking. The - # frequency is generated with an iterative training against Google web - # corpora. - # - # * Libtabe (Chinese) - # - https://sourceforge.net/project/?group_id=1519 - # - Its license terms and conditions are shown below. - # - # * IPADIC (Japanese) - # - http://chasen.aist-nara.ac.jp/chasen/distribution.html - # - Its license terms and conditions are shown below. - # - # ---------COPYING.libtabe ---- BEGIN-------------------- - # - # /* - # * Copyrighy (c) 1999 TaBE Project. - # * Copyright (c) 1999 Pai-Hsiang Hsiao. - # * All rights reserved. - # * - # * Redistribution and use in source and binary forms, with or without - # * modification, are permitted provided that the following conditions - # * are met: - # * - # * . Redistributions of source code must retain the above copyright - # * notice, this list of conditions and the following disclaimer. - # * . 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. - # * . Neither the name of the TaBE Project nor the names of its - # * contributors may be used to endorse or promote products derived - # * from this software without specific prior written permission. - # * - # * 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 - # * REGENTS 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. - # */ - # - # /* - # * Copyright (c) 1999 Computer Systems and Communication Lab, - # * Institute of Information Science, Academia - # * Sinica. All rights reserved. - # * - # * Redistribution and use in source and binary forms, with or without - # * modification, are permitted provided that the following conditions - # * are met: - # * - # * . Redistributions of source code must retain the above copyright - # * notice, this list of conditions and the following disclaimer. - # * . 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. - # * . Neither the name of the Computer Systems and Communication Lab - # * nor the names of its contributors may be used to endorse or - # * promote products derived from this software without specific - # * prior written permission. - # * - # * 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 - # * REGENTS 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. - # */ - # - # Copyright 1996 Chih-Hao Tsai @ Beckman Institute, - # University of Illinois - # c-tsai4@uiuc.edu http://casper.beckman.uiuc.edu/~c-tsai4 - # - # ---------------COPYING.libtabe-----END-------------------------------- - # - # - # ---------------COPYING.ipadic-----BEGIN------------------------------- - # - # Copyright 2000, 2001, 2002, 2003 Nara Institute of Science - # and Technology. All Rights Reserved. - # - # Use, reproduction, and distribution of this software is permitted. - # Any copy of this software, whether in its original form or modified, - # must include both the above copyright notice and the following - # paragraphs. - # - # Nara Institute of Science and Technology (NAIST), - # the copyright holders, disclaims all warranties with regard to this - # software, including all implied warranties of merchantability and - # fitness, in no event shall NAIST be liable for - # any special, indirect or consequential damages or any damages - # whatsoever resulting from loss of use, data or profits, whether in an - # action of contract, negligence or other tortuous action, arising out - # of or in connection with the use or performance of this software. - # - # A large portion of the dictionary entries - # originate from ICOT Free Software. The following conditions for ICOT - # Free Software applies to the current dictionary as well. - # - # Each User may also freely distribute the Program, whether in its - # original form or modified, to any third party or parties, PROVIDED - # that the provisions of Section 3 ("NO WARRANTY") will ALWAYS appear - # on, or be attached to, the Program, which is distributed substantially - # in the same form as set out herein and that such intended - # distribution, if actually made, will neither violate or otherwise - # contravene any of the laws and regulations of the countries having - # jurisdiction over the User or the intended distribution itself. - # - # NO WARRANTY - # - # The program was produced on an experimental basis in the course of the - # research and development conducted during the project and is provided - # to users as so produced on an experimental basis. Accordingly, the - # program is provided without any warranty whatsoever, whether express, - # implied, statutory or otherwise. The term "warranty" used herein - # includes, but is not limited to, any warranty of the quality, - # performance, merchantability and fitness for a particular purpose of - # the program and the nonexistence of any infringement or violation of - # any right of any third party. - # - # Each user of the program will agree and understand, and be deemed to - # have agreed and understood, that there is no warranty whatsoever for - # the program and, accordingly, the entire risk arising from or - # otherwise connected with the program is assumed by the user. - # - # Therefore, neither ICOT, the copyright holder, or any other - # organization that participated in or was otherwise related to the - # development of the program and their respective officials, directors, - # officers and other employees shall be held liable for any and all - # damages, including, without limitation, general, special, incidental - # and consequential damages, arising out of or otherwise in connection - # with the use or inability to use the program or any product, material - # or result produced or otherwise obtained by using the program, - # regardless of whether they have been advised of, or otherwise had - # knowledge of, the possibility of such damages at any time during the - # project or thereafter. Each user will be deemed to have agreed to the - # foregoing by his or her commencement of use of the program. The term - # "use" as used herein includes, but is not limited to, the use, - # modification, copying and distribution of the program and the - # production of secondary products from the program. - # - # In the case where the program, whether in its original form or - # modified, was distributed or delivered to or received by a user from - # any person, organization or entity other than ICOT, unless it makes or - # grants independently of ICOT any specific warranty to the user in - # writing, such person, organization or entity, will also be exempted - # from and not be held liable to the user for any such damages as noted - # above as far as the program is concerned. - # - # ---------------COPYING.ipadic-----END---------------------------------- - -3. Lao Word Break Dictionary Data (laodict.txt) - - # Copyright (c) 2013 International Business Machines Corporation - # and others. All Rights Reserved. - # - # Project: https://code.google.com/p/lao-dictionary/ - # Dictionary: http://lao-dictionary.googlecode.com/git/Lao-Dictionary.txt - # License: http://lao-dictionary.googlecode.com/git/Lao-Dictionary-LICENSE.txt - # (copied below) - # - # This file is derived from the above dictionary, with slight - # modifications. - # ---------------------------------------------------------------------- - # Copyright (C) 2013 Brian Eugene Wilson, Robert Martin Campbell. - # All rights reserved. - # - # Redistribution and use in source and binary forms, with or without - # modification, - # are permitted provided that the following conditions are met: - # - # - # Redistributions of source code must retain the above copyright notice, this - # list of conditions and the following disclaimer. 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. - # -------------------------------------------------------------------------- - -4. Burmese Word Break Dictionary Data (burmesedict.txt) - - # Copyright (c) 2014 International Business Machines Corporation - # and others. All Rights Reserved. - # - # This list is part of a project hosted at: - # github.com/kanyawtech/myanmar-karen-word-lists - # - # -------------------------------------------------------------------------- - # Copyright (c) 2013, LeRoy Benjamin Sharon - # All rights reserved. - # - # Redistribution and use in source and binary forms, with or without - # modification, are permitted provided that the following conditions - # are met: Redistributions of source code must retain the above - # copyright notice, this list of conditions and the following - # disclaimer. 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. - # - # Neither the name Myanmar Karen Word Lists, nor the names of its - # contributors may be used to endorse or promote products derived - # from this software without specific prior written permission. - # - # 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. - # -------------------------------------------------------------------------- - -5. Time Zone Database - - ICU uses the public domain data and code derived from Time Zone -Database for its time zone support. The ownership of the TZ database -is explained in BCP 175: Procedure for Maintaining the Time Zone -Database section 7. - - # 7. Database Ownership - # - # The TZ database itself is not an IETF Contribution or an IETF - # document. Rather it is a pre-existing and regularly updated work - # that is in the public domain, and is intended to remain in the - # public domain. Therefore, BCPs 78 [RFC5378] and 79 [RFC3979] do - # not apply to the TZ Database or contributions that individuals make - # to it. Should any claims be made and substantiated against the TZ - # Database, the organization that is providing the IANA - # Considerations defined in this RFC, under the memorandum of - # understanding with the IETF, currently ICANN, may act in accordance - # with all competent court orders. No ownership claims will be made - # by ICANN or the IETF Trust on the database or the code. Any person - # making a contribution to the database or code waives all rights to - # future claims in that contribution or in the TZ Database. - - -8. liblzma - -XZ Utils Licensing -================== - - Different licenses apply to different files in this package. Here - is a rough summary of which licenses apply to which parts of this - package (but check the individual files to be sure!): - - - liblzma is in the public domain. - - - xz, xzdec, and lzmadec command line tools are in the public - domain unless GNU getopt_long had to be compiled and linked - in from the lib directory. The getopt_long code is under - GNU LGPLv2.1+. - - - The scripts to grep, diff, and view compressed files have been - adapted from gzip. These scripts and their documentation are - under GNU GPLv2+. - - - All the documentation in the doc directory and most of the - XZ Utils specific documentation files in other directories - are in the public domain. - - - Translated messages are in the public domain. - - - The build system contains public domain files, and files that - are under GNU GPLv2+ or GNU GPLv3+. None of these files end up - in the binaries being built. - - - Test files and test code in the tests directory, and debugging - utilities in the debug directory are in the public domain. - - - The extra directory may contain public domain files, and files - that are under various free software licenses. - - You can do whatever you want with the files that have been put into - the public domain. If you find public domain legally problematic, - take the previous sentence as a license grant. If you still find - the lack of copyright legally problematic, you have too many - lawyers. - - As usual, this software is provided "as is", without any warranty. - - If you copy significant amounts of public domain code from XZ Utils - into your project, acknowledging this somewhere in your software is - polite (especially if it is proprietary, non-free software), but - naturally it is not legally required. Here is an example of a good - notice to put into "about box" or into documentation: - - This software includes code from XZ Utils . - - The following license texts are included in the following files: - - COPYING.LGPLv2.1: GNU Lesser General Public License version 2.1 - - COPYING.GPLv2: GNU General Public License version 2 - - COPYING.GPLv3: GNU General Public License version 3 - - Note that the toolchain (compiler, linker etc.) may add some code - pieces that are copyrighted. Thus, it is possible that e.g. liblzma - binary wouldn't actually be in the public domain in its entirety - even though it contains no copyrighted code from the XZ Utils source - package. - - If you have questions, don't hesitate to ask the author(s) for more - information. - - -BSD License - -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - -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. - -9. libunwind - -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. - -Provided for Informational Purposes Only - -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. - - - - ------------------------------------------------ END OF THIRD PARTY NOTICE ------------------------------------------ diff --git a/assets/AppxManifest.xml b/assets/AppxManifest.xml index 83df8c31b41..9faaec64995 100644 --- a/assets/AppxManifest.xml +++ b/assets/AppxManifest.xml @@ -20,11 +20,24 @@ - + - + + + + + + + + + + + + + + @@ -43,7 +56,11 @@ + + + + diff --git a/assets/additionalAttributions.txt b/assets/additionalAttributions.txt index d244bad6877..6676ca99cf5 100644 --- a/assets/additionalAttributions.txt +++ b/assets/additionalAttributions.txt @@ -1,46 +1,42 @@ -## Used to generate a new TPN -## Copy this into the additional attributions fields -## Copy everything below here, but do not include this line ---------------------------------------------- -File: PSReadLine ---------------------------------------------- +------------------------------------------------------------------- -https://github.com/lzybkr/PSReadLine +------------------------------------------------------------------- -Copyright (c) 2013, Jason Shirk +Additional - -All rights reserved. +------------------------------------------------- +Microsoft.PowerShell.Archive +------------------------------------------------- -BSD License +Copyright (c) 2016 Microsoft Corporation. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: +The MIT License (MIT) -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. +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: -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. +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. ----------------------------------------------- -File: Hashtables from ConvertFrom-json ----------------------------------------------- +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. -https://stackoverflow.com/questions/22002748/hashtables-from-convertfrom-json-have-different-type-from-powershells-built-in-h +------------------------------------------------- +Microsoft.Management.Infrastructure.Runtime.Unix +Microsoft.Management.Infrastructure +------------------------------------------------- -Copyright (c) 2015 Dave Wyatt. All rights reserved. +Copyright (c) Microsoft Corporation All rights reserved. @@ -52,6 +48,36 @@ The above copyright notice and this permission notice shall be included in all c 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 ------------------------------------------------- @@ -79,32 +105,88 @@ 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 ----------------------------------------------------------- +------------------------------------------------- +PowerShellGet +------------------------------------------------- -Copyright (c) .NET Foundation. All rights reserved. +Copyright (c) Microsoft Corporation -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 +All rights reserved. -https://www.apache.org/licenses/LICENSE-2.0 +The MIT License (MIT) -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. +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/assets/macos-entitlements.plist b/assets/macos-entitlements.plist new file mode 100644 index 00000000000..9d534f4f4bf --- /dev/null +++ b/assets/macos-entitlements.plist @@ -0,0 +1,14 @@ + + + + + com.apple.security.cs.allow-jit + + com.apple.security.cs.allow-unsigned-executable-memory + + com.apple.security.cs.allow-dyld-environment-variables + + com.apple.security.cs.disable-library-validation + + + diff --git a/assets/manpage/pwsh.1 b/assets/manpage/pwsh.1 new file mode 100644 index 00000000000..14c191241a9 --- /dev/null +++ b/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/assets/manpage/pwsh.1.ronn b/assets/manpage/pwsh.1.ronn new file mode 100644 index 00000000000..98320cc60c8 --- /dev/null +++ b/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/docs/community/process_diagram.vsdx b/docs/community/process_diagram.vsdx new file mode 100644 index 00000000000..014c28fa43d Binary files /dev/null and b/docs/community/process_diagram.vsdx differ diff --git a/docs/community/working-group-definitions.md b/docs/community/working-group-definitions.md new file mode 100644 index 00000000000..277fc37f789 --- /dev/null +++ b/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/docs/community/working-group.md b/docs/community/working-group.md new file mode 100644 index 00000000000..8b9caea2857 --- /dev/null +++ b/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/docs/debugging/README.md b/docs/debugging/README.md index 1b13924b854..6e1acaaef59 100644 --- a/docs/debugging/README.md +++ b/docs/debugging/README.md @@ -41,7 +41,7 @@ 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://docs.microsoft.com/dotnet/core/tutorials/with-visual-studio-code#debug +[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 diff --git a/docs/dev-process/coding-guidelines.md b/docs/dev-process/coding-guidelines.md index 389981c3f7b..ef0f671c1a0 100644 --- a/docs/dev-process/coding-guidelines.md +++ b/docs/dev-process/coding-guidelines.md @@ -86,9 +86,15 @@ We also run the [.NET code formatter tool](https://github.com/dotnet/codeformatt * Make sure the added/updated comments are meaningful, accurate and easy to understand. -* Public members must use [doc comments](https://docs.microsoft.com/dotnet/csharp/programming-guide/xmldoc/). +### 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. @@ -183,16 +189,16 @@ See [CODEOWNERS](../../.github/CODEOWNERS) for more information about the area e * 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://docs.microsoft.com/dotnet/standard/design-guidelines/index) - Naming, Design and Usage guidelines including: - * [Arrays](https://docs.microsoft.com/dotnet/standard/design-guidelines/arrays) - * [Collections](https://docs.microsoft.com/dotnet/standard/design-guidelines/guidelines-for-collections) - * [Exceptions](https://docs.microsoft.com/dotnet/standard/design-guidelines/exceptions) - * [Best Practices for Developing World-Ready Applications](https://docs.microsoft.com/dotnet/standard/globalization-localization/best-practices-for-developing-world-ready-apps) - Unicode, Culture, Encoding and Localization. - * [Best Practices for Exceptions](https://docs.microsoft.com/dotnet/standard/exceptions/best-practices-for-exceptions) - * [Best Practices for Using Strings in .NET](https://docs.microsoft.com/dotnet/standard/base-types/best-practices-strings) - * [Best Practices for Regular Expressions in .NET](https://docs.microsoft.com/dotnet/standard/base-types/best-practices) - * [Serialization Guidelines](https://docs.microsoft.com/dotnet/standard/serialization/serialization-guidelines) - * [Managed Threading Best Practices](https://docs.microsoft.com/dotnet/standard/threading/managed-threading-best-practices) + * [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 diff --git a/docs/git/README.md b/docs/git/README.md index 817e4930f6c..46b5eee4c62 100644 --- a/docs/git/README.md +++ b/docs/git/README.md @@ -13,9 +13,9 @@ git clone https://github.com/PowerShell/PowerShell.git --branch=master * 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." + * "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 @@ -23,12 +23,12 @@ git clone https://github.com/PowerShell/PowerShell.git --branch=master It could be unstable. * Send your pull requests to **master**. -### Sync your local repo +### 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 repo +# 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 @@ -42,11 +42,9 @@ git rebase origin/master 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 few links here: +We are leaving a few links here: -[Git pretty flowchart](http://justinhileman.info/article/git-pretty/): what to do, when your local repo became a mess. - -[Linus]:https://wincent.com/wiki/git_rebase%3A_you're_doing_it_wrong +[Linus]:https://web.archive.org/web/20230522041845/https://wincent.com/wiki/git_rebase%3A_you're_doing_it_wrong ## Tags @@ -57,12 +55,12 @@ you will find it via **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 repo to a [DETACHED HEAD][HEAD] state. +**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), +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 diff --git a/docs/git/basics.md b/docs/git/basics.md index a8a9bacf046..aa7629cf746 100644 --- a/docs/git/basics.md +++ b/docs/git/basics.md @@ -40,11 +40,6 @@ changes, and issue a pull request. [Hello World]: https://guides.github.com/activities/hello-world/ -#### Katacoda - -Learn basic Git scenarios in the browser with interactive labs. -[Git lessons on katacoda](https://www.katacoda.com/courses/git/). - #### Githug [Githug](https://github.com/Gazler/githug) is a great gamified way to diff --git a/docs/host-powershell/README.md b/docs/host-powershell/README.md index 3d96855b413..174f986dfa4 100644 --- a/docs/host-powershell/README.md +++ b/docs/host-powershell/README.md @@ -41,7 +41,7 @@ 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://docs.microsoft.com/dotnet/api/system.management.automation.powershellassemblyloadcontextinitializer.setpowershellassemblyloadcontext). +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/docs/host-powershell/sample/NuGet.config b/docs/host-powershell/sample/NuGet.config deleted file mode 100644 index b3ce3cb82a5..00000000000 --- a/docs/host-powershell/sample/NuGet.config +++ /dev/null @@ -1,10 +0,0 @@ - - - - - - - - - - diff --git a/docs/host-powershell/sample/NuGet.config.md b/docs/host-powershell/sample/NuGet.config.md new file mode 100644 index 00000000000..bf2b4c3f688 --- /dev/null +++ b/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/docs/learning-powershell/README.md b/docs/learning-powershell/README.md deleted file mode 100644 index 0dbbc5b8576..00000000000 --- a/docs/learning-powershell/README.md +++ /dev/null @@ -1,127 +0,0 @@ -# Learning PowerShell - -Whether you're a Developer, a DevOps or an IT Professional, this doc will help you getting started with PowerShell. -In this document we'll cover the following: -installing PowerShell, samples walkthrough, PowerShell editor, debugger, testing tools and a map book for experienced bash users to get started with PowerShell faster. - -The exercises in this document are intended to give you a solid foundation in how to use PowerShell. -You won't be a PowerShell guru at the end of reading this material but you will be well on your way with the right set of knowledge to start using PowerShell. - -If you have 30 minutes now, let’s try it. - -## Installing PowerShell - -First you need to set up your computer working environment if you have not done so. -Choose the platform below and follow the instructions. -At the end of this exercise, you should be able to launch the PowerShell session. - -- Get PowerShell by installing package - * [PowerShell on Linux][inst-linux] - * [PowerShell on macOS][inst-macos] - * [PowerShell on Windows][inst-win] - - For this tutorial, you do not need to install PowerShell if you are running on Windows. - You can launch PowerShell console by pressing Windows key, typing PowerShell, and clicking on Windows PowerShell. - However if you want to try out the latest PowerShell, follow the [PowerShell on Windows][inst-win]. - -- Alternatively you can get the PowerShell by [building it][build-powershell] - -[build-powershell]:../../README.md#building-the-repository -[inst-linux]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-linux -[inst-win]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-windows -[inst-macos]: https://docs.microsoft.com/powershell/scripting/install/installing-powershell-core-on-macos - -## Getting Started with PowerShell - -PowerShell commands follow a Verb-Noun semantic with a set of parameters. -It's easy to learn and use PowerShell. -For example, `Get-Process` will display all the running processes on your system. -Let's walk through with a few examples from the [PowerShell Beginner's Guide](powershell-beginners-guide.md). - -Now you have learned the basics of PowerShell. -Please continue reading if you want to do some development work in PowerShell. - -### PowerShell Editor - -In this section, you will create a PowerShell script using a text editor. -You can use your favorite editor to write scripts. -We use Visual Studio Code (VS Code) which works on Windows, Linux, and macOS. -Click on the following link to create your first PowerShell script. - -- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode) - -### PowerShell Debugger - -Debugging can help you find bugs and fix problems in your PowerShell scripts. -Click on the link below to learn more about debugging: - -- [Using Visual Studio Code (VS Code)](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode#debugging-with-visual-studio-code) -- [PowerShell Command-line Debugging][cli-debugging] - -[cli-debugging]:./debugging-from-commandline.md - -### PowerShell Testing - -We recommend using Pester testing tool which is initiated by the PowerShell Community for writing test cases. -To use the tool please read [Pester Guides](https://github.com/pester/Pester) and [Writing Pester Tests Guidelines](https://github.com/PowerShell/PowerShell/blob/master/docs/testing-guidelines/WritingPesterTests.md). - -### Map Book for Experienced Bash users - -The table below lists the usage of some basic commands to help you get started on PowerShell faster. -Note that all bash commands should continue working on PowerShell session. - -| Bash | PowerShell | Description -|:--------------------------------|:----------------------------------------|:--------------------- -| ls | dir, Get-ChildItem | List files and folders -| tree | dir -Recurse, Get-ChildItem -Recurse | List all files and folders -| cd | cd, Set-Location | Change directory -| pwd | pwd, $pwd, Get-Location | Show working directory -| clear, Ctrl+L, reset | cls, clear | Clear screen -| mkdir | New-Item -ItemType Directory | Create a new folder -| touch test.txt | New-Item -Path test.txt | Create a new empty file -| cat test1.txt test2.txt | Get-Content test1.txt, test2.txt | Display files contents -| cp ./source.txt ./dest/dest.txt | Copy-Item source.txt dest/dest.txt | Copy a file -| cp -r ./source ./dest | Copy-Item ./source ./dest -Recurse | Recursively copy from one folder to another -| mv ./source.txt ./dest/dest.txt | Move-Item ./source.txt ./dest/dest.txt | Move a file to other folder -| rm test.txt | Remove-Item test.txt | Delete a file -| rm -r <folderName> | Remove-Item <folderName> -Recurse | Delete a folder -| find -name build* | Get-ChildItem build* -Recurse | Find a file or folder starting with 'build' -| grep -Rin "sometext" --include="*.cs" |Get-ChildItem -Recurse -Filter *.cs
\| Select-String -Pattern "sometext" | Recursively case-insensitive search for text in files -| curl https://github.com | Invoke-RestMethod https://github.com | Transfer data to or from the web - -### Recommended Training and Reading - -- Microsoft Virtual Academy: [Getting Started with PowerShell][getstarted-with-powershell] -- [Why Learn PowerShell][why-learn-powershell] by Ed Wilson -- PowerShell Web Docs: [Basic cookbooks][basic-cookbooks] -- [The Guide to Learning PowerShell][ebook-from-Idera] by Tobias Weltner -- [PowerShell-related Videos][channel9-learn-powershell] on Channel 9 -- [PowerShell Quick Reference Guides][quick-reference] by PowerShellMagazine.com -- [Learn PowerShell Video Library][idera-learn-powershell] from Idera -- [PowerShell 5 How-To Videos][script-guy-how-to] by Ed Wilson -- [PowerShell Documentation](https://docs.microsoft.com/powershell) -- [Interactive learning with PSKoans](https://aka.ms/pskoans) - -### Commercial Resources - -- [Windows PowerShell in Action][in-action] by [Bruce Payette](https://github.com/brucepay) -- [Introduction to PowerShell][powershell-intro] from Pluralsight -- [PowerShell Training and Tutorials][lynda-training] from Lynda.com -- [Learn Windows PowerShell in a Month of Lunches][learn-win-powershell] by Don Jones and Jeffrey Hicks -- [Learn PowerShell in a Month of Lunches][learn-powershell] by Travis Plunk (@TravisEz13), - Tyler Leonhardt (@tylerleonhardt), Don Jones, and Jeffery Hicks - -[in-action]: https://www.amazon.com/Windows-PowerShell-Action-Second-Payette/dp/1935182137 -[powershell-intro]: https://www.pluralsight.com/courses/powershell-intro -[lynda-training]: https://www.lynda.com/PowerShell-training-tutorials/5779-0.html -[learn-win-powershell]: https://www.amazon.com/Learn-Windows-PowerShell-Month-Lunches/dp/1617294160 -[learn-powershell]: https://www.manning.com/books/learn-powershell-in-a-month-of-lunches - -[getstarted-with-powershell]: https://channel9.msdn.com/Series/GetStartedPowerShell3 -[why-learn-powershell]: https://blogs.technet.microsoft.com/heyscriptingguy/2014/10/18/weekend-scripter-why-learn-powershell/ -[ebook-from-Idera]:https://www.idera.com/resourcecentral/whitepapers/powershell-ebook -[channel9-learn-powershell]: https://channel9.msdn.com/Search?term=powershell#ch9Search -[idera-learn-powershell]: https://community.idera.com/database-tools/powershell/video_library/ -[quick-reference]: https://www.powershellmagazine.com/2014/04/24/windows-powershell-4-0-and-other-quick-reference-guides/ -[script-guy-how-to]:https://blogs.technet.microsoft.com/tommypatterson/2015/09/04/ed-wilsons-powershell5-videos-now-on-channel9-2/ -[basic-cookbooks]:https://docs.microsoft.com/powershell/scripting/samples/sample-scripts-for-administration diff --git a/docs/learning-powershell/create-powershell-scripts.md b/docs/learning-powershell/create-powershell-scripts.md deleted file mode 100644 index 5f93eb97ab3..00000000000 --- a/docs/learning-powershell/create-powershell-scripts.md +++ /dev/null @@ -1,65 +0,0 @@ -# How to Create and Run PowerShell Scripts - -You can combine a series of commands in a text file and save it with the file extension '.ps1', and the file will become a PowerShell script. -This would begin by opening your favorite text editor and pasting in the following example. - -```powershell -# Script to return current IPv4 addresses on a Linux or MacOS host -$ipInfo = ifconfig | Select-String 'inet' -$ipInfo = [regex]::matches($ipInfo,"addr:\b(?:\d{1,3}\.){3}\d{1,3}\b") | ForEach-Object value -foreach ($ip in $ipInfo) -{ - $ip.Replace('addr:','') -} -``` - -Then save the file to something memorable, such as .\NetIP.ps1. -In the future when you need to get the IP addresses for the node, you can simplify this task by executing the script. - -```powershell -.\NetIP.ps1 -10.0.0.1 -127.0.0.1 -``` - -You can accomplish this same task on Windows. - -```powershell -# One line script to return current IPv4 addresses on a Windows host -Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'} | ForEach-Object IPAddress -``` - -As before, save the file as .\NetIP.ps1 and execute within a PowerShell environment. -Note: If you are using Windows, make sure you set the PowerShell's execution policy to "RemoteSigned" in this case. -See [Running PowerShell Scripts Is as Easy as 1-2-3][run-ps] for more details. - -```powershell -NetIP.ps1 -127.0.0.1 -10.0.0.1 -``` - -## Creating a script that can accomplish the same task on multiple operating systems - -If you would like to author one script that will return the IP address across Linux, MacOS, or Windows, you could accomplish this using an IF statement. - -```powershell -# Script to return current IPv4 addresses for Linux, MacOS, or Windows -$IP = if ($IsLinux -or $IsMacOS) -{ - $ipInfo = ifconfig | Select-String 'inet' - $ipInfo = [regex]::matches($ipInfo,"addr:\b(?:\d{1,3}\.){3}\d{1,3}\b") | ForEach-Object value - foreach ($ip in $ipInfo) { - $ip.Replace('addr:','') - } -} -else -{ - Get-NetIPAddress | Where-Object {$_.AddressFamily -eq 'IPv4'} | ForEach-Object IPAddress -} - -# Remove loopback address from output regardless of platform -$IP | Where-Object {$_ -ne '127.0.0.1'} -``` - -[run-ps]:https://www.itprotoday.com/powershell/running-powershell-scripts-easy-1-2-3 diff --git a/docs/learning-powershell/debugging-from-commandline.md b/docs/learning-powershell/debugging-from-commandline.md deleted file mode 100644 index 1aaab218256..00000000000 --- a/docs/learning-powershell/debugging-from-commandline.md +++ /dev/null @@ -1,173 +0,0 @@ -# Debugging in PowerShell Command-line - -As we know, we can debug PowerShell code via GUI tools like [Visual Studio Code](https://docs.microsoft.com/powershell/scripting/dev-cross-plat/vscode/using-vscode#debugging-with-visual-studio-code). In addition, we can -directly perform debugging within the PowerShell command-line session by using the PowerShell debugger cmdlets. This document demonstrates how to use the cmdlets for the PowerShell command-line debugging. We will cover the following topics: -setting a debug breakpoint on a line of code and on a variable. - -Let's use the following code snippet as our sample script. - -```powershell -# Convert Fahrenheit to Celsius -function ConvertFahrenheitToCelsius([double] $fahrenheit) -{ -$celsius = $fahrenheit - 32 -$celsius = $celsius / 1.8 -$celsius -} - -$fahrenheit = Read-Host 'Input a temperature in Fahrenheit' -$result =[int](ConvertFahrenheitToCelsius($fahrenheit)) -Write-Host "$result Celsius" -``` - -## Setting a Breakpoint on a Line - -- Open a [PowerShell editor](README.md#powershell-editor) -- Save the above code snippet to a file. For example, "test.ps1" -- Go to your command-line PowerShell -- Clear existing breakpoints if any - -```powershell - PS /home/jen/debug>Get-PSBreakpoint | Remove-PSBreakpoint -``` - -- Use **Set-PSBreakpoint** cmdlet to set a debug breakpoint. In this case, we will set it to line 5 - -```powershell -PS /home/jen/debug>Set-PSBreakpoint -Line 5 -Script ./test.ps1 - -ID Script Line Command Variable Action --- ------ ---- ------- -------- ------ - 0 test.ps1 5 -``` - -- Run the script "test.ps1". As we have set a breakpoint, it is expected the program will break into the debugger at the line 5. - -```powershell - -PS /home/jen/debug> ./test.ps1 -Input a temperature in Fahrenheit: 80 -Hit Line breakpoint on '/home/jen/debug/test.ps1:5' - -At /home/jen/debug/test.ps1:5 char:1 -+ $celsius = $celsius / 1.8 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> -``` - -- The PowerShell prompt now has the prefix **[DBG]:** as you may have noticed. This means - we have entered into the debug mode. To watch the variables like $celsius, simply type **$celsius** as below. -- To exit from the debugging, type **q** -- To get help for the debugging commands, simply type **?**. The following is an example of debugging output. - -```PowerShell -[DBG]: PS /home/jen/debug>> $celsius -48 -[DBG]: PS /home/jen/debug>> $fahrenheit -80 -[DBG]: PS /home/jen/debug>> ? - - s, stepInto Single step (step into functions, scripts, etc.) - v, stepOver Step to next statement (step over functions, scripts, etc.) - o, stepOut Step out of the current function, script, etc. - - c, continue Continue operation - q, quit Stop operation and exit the debugger - d, detach Continue operation and detach the debugger. - - k, Get-PSCallStack Display call stack - - l, list List source code for the current script. - Use "list" to start from the current line, "list " - to start from line , and "list " to list - lines starting from line - - Repeat last command if it was stepInto, stepOver or list - - ?, h displays this help message. - - -For instructions about how to customize your debugger prompt, type "help about_prompt". - -[DBG]: PS /home/jen/debug>> s -At PS /home/jen/debug/test.ps1:6 char:1 -+ $celsius -+ ~~~~~~~~ -[DBG]: PS /home/jen/debug>> $celsius -26.6666666666667 -[DBG]: PS /home/jen/debug>> $fahrenheit -80 - -[DBG]: PS /home/jen/debug>> q -PS /home/jen/debug> - -``` - -## Setting a Breakpoint on a Variable -- Clear existing breakpoints if there are any - -```powershell - PS /home/jen/debug>Get-PSBreakpoint | Remove-PSBreakpoint - ``` - -- Use **Set-PSBreakpoint** cmdlet to set a debug breakpoint. In this case, we set it to line 5 - -```powershell - - PS /home/jen/debug>Set-PSBreakpoint -Variable "celsius" -Mode write -Script ./test.ps1 - -``` - -- Run the script "test.ps1" - - Once hit the debug breakpoint, we can type **l** to list the source code that debugger is currently executing. As we can see line 3 has an asterisk at the front, meaning that's the line the program is currently executing and broke into the debugger as illustrated below. -- Type **q** to exit from the debugging mode. The following is an example of debugging output. - -```powershell -./test.ps1 -Input a temperature in Fahrenheit: 80 -Hit Variable breakpoint on '/home/jen/debug/test.ps1:$celsius' (Write access) - -At /home/jen/debug/test.ps1:3 char:1 -+ $celsius = $fahrenheit - 32 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> l - - - 1: function ConvertFahrenheitToCelsius([double] $fahrenheit) - 2: { - 3:* $celsius = $fahrenheit - 32 - 4: $celsius = $celsius / 1.8 - 5: $celsius - 6: } - 7: - 8: $fahrenheit = Read-Host 'Input a temperature in Fahrenheit' - 9: $result =[int](ConvertFahrenheitToCelsius($fahrenheit)) - 10: Write-Host "$result Celsius" - - -[DBG]: PS /home/jen/debug>> $celsius -48 -[DBG]: PS /home/jen/debug>> v -At /home/jen/debug/test.ps1:4 char:1 -+ $celsius = $celsius / 1.8 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> v -Hit Variable breakpoint on '/home/jen/debug/test.ps1:$celsius' (Write access) - -At /home/jen/debug/test.ps1:4 char:1 -+ $celsius = $celsius / 1.8 -+ ~~~~~~~~~~~~~~~~~~~~~~~~~ -[DBG]: PS /home/jen/debug>> $celsius -26.6666666666667 -[DBG]: PS /home/jen/debug>> q -PS /home/jen/debug> - -``` - -Now you know the basics of the PowerShell debugging from PowerShell command-line. For further learning, read the following articles. - -## More Reading - -- [about_Debuggers](https://docs.microsoft.com/powershell/module/microsoft.powershell.core/about/about_debuggers) -- [PowerShell Debugging](https://blogs.technet.microsoft.com/heyscriptingguy/tag/debugging/) diff --git a/docs/learning-powershell/powershell-beginners-guide.md b/docs/learning-powershell/powershell-beginners-guide.md deleted file mode 100644 index 2017b191066..00000000000 --- a/docs/learning-powershell/powershell-beginners-guide.md +++ /dev/null @@ -1,339 +0,0 @@ -# PowerShell Beginner’s Guide - -If you are new to PowerShell, this document will walk you through a few examples to give you some basic ideas of PowerShell. -We recommend that you open a PowerShell console/session and type along with the instructions in this document to get most out of this exercise. - -## Launch PowerShell Console/Session - -First you need to launch a PowerShell session by following the [Installing PowerShell Guide](./README.md#installing-powershell). - -## Getting Familiar with PowerShell Commands - -In this section, you will learn how to - -- create a file, delete a file and change file directory -- discover what version of PowerShell you are currently using -- exit a PowerShell session -- get help if you needed -- find syntax of PowerShell cmdlets -- and more - -As mentioned above, PowerShell commands are designed to have Verb-Noun structure, for instance `Get-Process`, `Set-Location`, `Clear-Host`, etc. -Let’s exercise some of the basic PowerShell commands, also known as **cmdlets**. - -Please note that we will use the PowerShell prompt sign **PS />** as it appears on Linux in the following examples. -It is shown as `PS C:\>` on Windows. - -1. `Get-Process`: Gets the processes that are running on the local computer or a remote computer. - - By default, you will get data back similar to the following: - - ```powershell - PS /> Get-Process - - Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName - ------- ------ ----- ----- ------ -- ----------- - - - - 1 0.012 12 bash - - - - 21 20.220 449 powershell - - - - 11 61.630 8620 code - - - - 74 403.150 1209 firefox - - … - ``` - - Only interested in the instance of Firefox process that is running on your computer? - - Try this: - - ```powershell - PS /> Get-Process -Name firefox - - Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName - ------- ------ ----- ----- ------ -- ----------- - - - - 74 403.150 1209 firefox - - ``` - - Want to get back more than one process? - Then just specify process names and separate them with commas. - - ```powershell - PS /> Get-Process -Name firefox, powershell - Handles NPM(K) PM(K) WS(K) CPU(s) Id ProcessName - ------- ------ ----- ----- ------ -- ----------- - - - - 74 403.150 1209 firefox - - - - 21 20.220 449 powershell - - ``` - -1. `Clear-Host`: Clears the display in the host program. - - ```powershell - PS /> Get-Process - PS /> Clear-Host - ``` - - Type too much just for clearing the screen? - - Here is how the alias can help. - -1. `Get-Alias`: Gets the aliases for the current session. - - ```powershell - Get-Alias - - CommandType Name - ----------- ---- - … - - Alias cd -> Set-Location - Alias cls -> Clear-Host - Alias clear -> Clear-Host - Alias copy -> Copy-Item - Alias dir -> Get-ChildItem - Alias gc -> Get-Content - Alias gmo -> Get-Module - Alias ri -> Remove-Item - Alias type -> Get-Content - … - ``` - - As you can see `cls` or `clear` is an alias of `Clear-Host`. - - Now try it: - - ```powershell - PS /> Get-Process - PS /> cls - ``` - -1. `cd -> Set-Location`: Sets the current working location to a specified location. - - ```powershell - PS /> Set-Location /home - PS /home> - ``` - -1. `dir -> Get-ChildItem`: Gets the items and child items in one or more specified locations. - - ```powershell - # Get all files under the current directory: - PS /> Get-ChildItem - - # Get all files under the current directory as well as its subdirectories: - PS /> cd $home - PS /home/jen> dir -Recurse - - # List all files with "txt" file extension. - PS /> cd $home - PS /home/jen> dir –Path *.txt -Recurse - ``` - -1. `New-Item`: Creates a new item. - - ```powershell - # An empty file is created if you type the following: - PS /home/jen> New-Item -Path ./test.txt - - - Directory: /home/jen - - - Mode LastWriteTime Length Name - ---- ------------- ------ ---- - -a---- 7/7/2016 7:17 PM 0 test.txt - ``` - - You can use the `-Value` parameter to add some data to your file. - - For example, the following command adds the phrase `Hello world!` as a file content to the `test.txt`. - - Because the test.txt file exists already, we use `-Force` parameter to replace the existing content. - - ```powershell - PS /home/jen> New-Item -Path ./test.txt -Value "Hello world!" -Force - - Directory: /home/jen - - - Mode LastWriteTime Length Name - ---- ------------- ------ ---- - -a---- 7/7/2016 7:19 PM 24 test.txt - - ``` - - There are other ways to add some data to a file. - - For example, you can use `Set-Content` to set the file contents: - - ```powershell - PS /home/jen>Set-Content -Path ./test.txt -Value "Hello world again!" - ``` - - Or simply use `>` as below: - - ```powershell - # create an empty file - "" > test.txt - - # set "Hello world!" as content of test.txt file - "Hello world!!!" > test.txt - - ``` - - The pound sign `#` above is used for comments in PowerShell. - -1. `type -> Get-Content`: Gets the content of the item at the specified location. - - ```powershell - PS /home/jen> Get-Content -Path ./test.txt - PS /home/jen> type -Path ./test.txt - - Hello world again! - ``` - -1. `del -> Remove-Item`: Deletes the specified items. - - This cmdlet will delete the file `/home/jen/test.txt`: - - ```powershell - PS /home/jen> Remove-Item ./test.txt - ``` - -1. `$PSVersionTable`: Displays the version of PowerShell you are currently using. - - Type `$PSVersionTable` in your PowerShell session, you will see something like below. - "PSVersion" indicates the PowerShell version that you are using. - - ```powershell - Name Value - ---- ----- - PSVersion 6.0.0-alpha - PSEdition Core - PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} - BuildVersion 3.0.0.0 - GitCommitId v6.0.0-alpha.12 - CLRVersion - WSManStackVersion 3.0 - PSRemotingProtocolVersion 2.3 - SerializationVersion 1.1.0.1 - - ``` - -1. `Exit`: To exit the PowerShell session, type `exit`. - - ```powershell - exit - ``` - -## Need Help? - -The most important command in PowerShell is possibly the `Get-Help`, which allows you to quickly learn PowerShell without having to search around the internet. - -The `Get-Help` cmdlet also shows you how PowerShell commands work with examples. - -It shows the syntax and other technical information of the `Get-Process` cmdlet. - -```powershell -PS /> Get-Help -Name Get-Process -``` - -It displays the examples how to use the `Get-Process` cmdlet. - -```powershell -PS />Get-Help -Name Get-Process -Examples -``` - -If you use **-Full** parameter, for example, `Get-Help -Name Get-Process -Full`, it will display more technical information. - -## Discover Commands Available on Your System - -You want to discover what PowerShell cmdlets available on your system? Just run `Get-Command` as below: - -```powershell -PS /> Get-Command -``` - -If you want to know whether a particular cmdlet exists on your system, you can do something like below: - -```powershell -PS /> Get-Command Get-Process -``` - -If you want to know the syntax of `Get-Process` cmdlet, type: - -```powershell -PS /> Get-Command Get-Process -Syntax -``` - -If you want to know how to use the `Get-Process`, type: - -```powershell -PS /> Get-Help Get-Process -Example -``` - -## PowerShell Pipeline `|` - -Sometimes when you run Get-ChildItem or "dir", you want to get a list of files and folders in a descending order. -To achieve that, type: - -```powershell -PS /home/jen> dir | Sort-Object -Descending -``` - -Say you want to get the largest file in a directory - -```powershell -PS /home/jen> dir | Sort-Object -Property Length -Descending | Select-Object -First 1 - - - Directory: /home/jen - - -Mode LastWriteTime Length Name ----- ------------- ------ ---- --a---- 5/16/2016 1:15 PM 32972 test.log - -``` - -## How to Create and Run PowerShell scripts - -You can use Visual Studio Code or your favorite editor to create a PowerShell script and save it with a `.ps1` file extension. -For more details, see [Create and Run PowerShell Script Guide][create-run-script] - -## Recommended Training and Reading - -- Video: [Get Started with PowerShell][remoting] from Channel9 -- [eBooks from PowerShell.org](https://leanpub.com/u/devopscollective) -- [eBooks List][ebook-list] by Martin Schvartzman -- [Tutorial from MVP][tutorial] -- Script Guy blog: [The best way to Learn PowerShell][to-learn] -- [Understanding PowerShell Module][ps-module] -- [How and When to Create PowerShell Module][create-ps-module] by Adam Bertram -- Video: [PowerShell Remoting in Depth][in-depth] from Channel9 -- [PowerShell Basics: Remote Management][remote-mgmt] from ITPro -- [Running Remote Commands][remote-commands] from PowerShell Web Docs -- [Samples for Writing a PowerShell Script Module][examples-ps-module] -- [Writing a PowerShell module in C#][writing-ps-module] -- [Examples of Cmdlets Code][sample-code] - -## Commercial Resources - -- [Windows PowerShell in Action][in-action] by Bruce Payette -- [Windows PowerShell Cookbook][cookbook] by Lee Holmes - -[in-action]: https://www.amazon.com/Windows-PowerShell-Action-Bruce-Payette/dp/1633430294 -[cookbook]: http://shop.oreilly.com/product/9780596801519.do -[ebook-list]: https://martin77s.wordpress.com/2014/05/26/free-powershell-ebooks/ -[tutorial]: https://www.computerperformance.co.uk/powershell/index-13/ -[to-learn]:https://blogs.technet.microsoft.com/heyscriptingguy/2015/01/04/weekend-scripter-the-best-ways-to-learn-powershell/ -[ps-module]:https://docs.microsoft.com/powershell/scripting/developer/module/understanding-a-windows-powershell-module -[create-ps-module]:https://www.business.com/articles/powershell-modules/ -[remoting]:https://channel9.msdn.com/Series/GetStartedPowerShell3/06 -[in-depth]: https://channel9.msdn.com/events/MMS/2012/SV-B406 -[remote-mgmt]:https://www.itprotoday.com/powershell/powershell-basics-remote-management -[remote-commands]:https://docs.microsoft.com/powershell/scripting/learn/remoting/running-remote-commands -[examples-ps-module]:https://docs.microsoft.com/powershell/scripting/developer/module/how-to-write-a-powershell-script-module -[writing-ps-module]:https://www.powershellmagazine.com/2014/03/18/writing-a-powershell-module-in-c-part-1-the-basics/ -[sample-code]:https://docs.microsoft.com/powershell/scripting/developer/cmdlet/examples-of-cmdlet-code -[create-run-script]:./create-powershell-scripts.md diff --git a/docs/learning-powershell/working-with-powershell-objects.md b/docs/learning-powershell/working-with-powershell-objects.md deleted file mode 100644 index ab127483cfe..00000000000 --- a/docs/learning-powershell/working-with-powershell-objects.md +++ /dev/null @@ -1,125 +0,0 @@ -# Working with PowerShell Objects - -When cmdlets are executed in PowerShell, the output is an Object, as opposed to only returning text. -This provides the ability to store information as properties. -As a result, handling large amounts of data and getting only specific properties is a trivial task. - -As a simple example, the following function retrieves information about storage Devices on a Linux or MacOS operating system platform. -This is accomplished by parsing the output of an existing command, *parted -l* in administrative context, and creating an object from the raw text by using the *New-Object* cmdlet. - -```powershell -function Get-DiskInfo -{ - $disks = sudo parted -l | Select-String "Disk /dev/sd*" -Context 1,0 - $diskinfo = @() - foreach ($disk in $disks) { - $diskline1 = $disk.ToString().Split("`n")[0].ToString().Replace(' Model: ','') - $diskline2 = $disk.ToString().Split("`n")[1].ToString().Replace('> Disk ','') - $i = New-Object psobject -Property @{'Friendly Name' = $diskline1; Device=$diskline2.Split(': ')[0]; 'Total Size'=$diskline2.Split(':')[1]} - $diskinfo += $i - } - $diskinfo -} -``` - -Execute the function and store the results as a variable. -Now retrieve the value of the variable. -The results are formatted as a table with the default view. - -*Note: in this example, the disks are virtual disks in a Microsoft Azure virtual machine.* - -```powershell -PS /home/psuser> $d = Get-DiskInfo -[sudo] password for psuser: -PS /home/psuser> $d - -Friendly Name Total Size Device -------------- ---------- ------ -Msft Virtual Disk (scsi) 31.5GB /dev/sda -Msft Virtual Disk (scsi) 145GB /dev/sdb - -``` - -Passing the variable down the pipeline to *Get-Member* reveals available methods and properties. -This is because the value of *$d* is not just text output. -The value is actually an array of .Net objects with methods and properties. -The properties include Device, Friendly Name, and Total Size. - -```powershell -PS /home/psuser> $d | Get-Member - - - TypeName: System.Management.Automation.PSCustomObject - -Name MemberType Definition ----- ---------- ---------- -Equals Method bool Equals(System.Object obj) -GetHashCode Method int GetHashCode() -GetType Method type GetType() -ToString Method string ToString() -Device NoteProperty string Device=/dev/sda -Friendly Name NoteProperty string Friendly Name=Msft Virtual Disk (scsi) -Total Size NoteProperty string Total Size= 31.5GB -``` - -To confirm, we can call the GetType() method interactively from the console. - -```powershell -PS /home/psuser> $d.GetType() - -IsPublic IsSerial Name BaseType --------- -------- ---- -------- -True True Object[] System.Array -``` - -To index in to the array and return only specific objects, use the square brackets. - -```powershell -PS /home/psuser> $d[0] - -Friendly Name Total Size Device -------------- ---------- ------ -Msft Virtual Disk (scsi) 31.5GB /dev/sda - -PS /home/psuser> $d[0].GetType() - -IsPublic IsSerial Name BaseType --------- -------- ---- -------- -True False PSCustomObject System.Object -``` - -To return a specific property, the property name can be called interactively from the console. - -```powershell -PS /home/psuser> $d.Device -/dev/sda -/dev/sdb -``` - -To output a view of the information other than default, such as a view with only specific properties selected, pass the value to the *Select-Object* cmdlet. - -```powershell -PS /home/psuser> $d | Select-Object Device, 'Total Size' - -Device Total Size ------- ---------- -/dev/sda 31.5GB -/dev/sdb 145GB -``` - -Finally, the example below demonstrates use of the *ForEach-Object* cmdlet to iterate through the array and manipulate the value of a specific property of each object. -In this case the Total Size property, which was given in Gigabytes, is changed to Megabytes. -Alternatively, index in to a position in the array as shown below in the third example. - -```powershell -PS /home/psuser> $d | ForEach-Object 'Total Size' - 31.5GB - 145GB - -PS /home/psuser> $d | ForEach-Object {$_.'Total Size' / 1MB} -32256 -148480 - -PS /home/psuser> $d[1].'Total Size' / 1MB -148480 -``` diff --git a/docs/maintainers/README.md b/docs/maintainers/README.md index 0c28e2cc9de..ebba4b02258 100644 --- a/docs/maintainers/README.md +++ b/docs/maintainers/README.md @@ -6,8 +6,8 @@ One of their primary responsibilities is merging pull requests after all require 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://www.thinkful.com/learn/github-pull-request-tutorial/) -1. Assign labels, milestones, and people to [issues](https://guides.github.com/features/issues/) and [pull requests](https://www.thinkful.com/learn/github-pull-request-tutorial/) +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 @@ -15,7 +15,6 @@ They have [write access](https://docs.github.com/en/free-pro-team@latest/github/ - [Repository Maintainer Responsibilities](#repository-maintainer-responsibilities) - [Issue Management Process](#issue-management-process) - [Pull Request Workflow](#pull-request-workflow) - - [Abandoned Pull Requests](#abandoned-pull-requests) - [Becoming a Repository Maintainer](#becoming-a-repository-maintainer) ## Current Repository Maintainers @@ -33,7 +32,7 @@ They have [write access](https://docs.github.com/en/free-pro-team@latest/github/ -- Andy Schwartzmeyer ([andschwa](https://github.com/andschwa)) +- 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)) @@ -44,6 +43,7 @@ Repository Maintainers enable rapid contributions while maintaining a high level 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 @@ -96,10 +96,11 @@ At any point in time, the existing Repository Maintainers can unanimously nomina 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. +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/docs/maintainers/issue-management.md b/docs/maintainers/issue-management.md index 4021d44c82a..0cc8eb00e37 100644 --- a/docs/maintainers/issue-management.md +++ b/docs/maintainers/issue-management.md @@ -7,6 +7,8 @@ first follow the [vulnerability issue reporting policy](../../.github/SECURITY.m ## 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. @@ -37,32 +39,35 @@ When an issue is resolved, the following labels are used to describe the resolut ### Feature areas -These labels describe what feature area of PowerShell that an issue affects: +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-Build`: build issues +* `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-Console`: the console experience -* `Area-Debugging`: debugging PowerShell script -* `Area-Demo`: a demo or sample * `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-Engine`: core PowerShell engine, interpreter, runtime -* `Area-HelpSystem`: anything related to the help infrastructure and formatting of help -* `Area-Intellisense`: tab completion -* `Area-Language`: parser, language semantics -* `Area-OMI`: OMI -* `Area-PackageManagement`: PackageManagement related issues -* `Area-Performance`: a performance issue -* `Area-Portability`: anything affecting script portability * `Area-PowerShellGet`: PowerShellGet related issues -* `Area-Providers`: PowerShell providers such as FileSystem, Certificates, Registry, etc... -* `Area-PSReadline`: PSReadline related issues -* `Area-Remoting`: PSRP issues with any transport layer -* `Area-Security`: security related areas such as [JEA](https://github.com/powershell/JEA) * `Area-SideBySide`: side by side support -* `Area-Test`: issues in a test or in test infrastructure +* `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 diff --git a/docs/maintainers/releasing.md b/docs/maintainers/releasing.md index e3ac1998f77..ccb4e5529d7 100644 --- a/docs/maintainers/releasing.md +++ b/docs/maintainers/releasing.md @@ -21,20 +21,15 @@ This is to help track the release preparation work. - Sign the MSI packages and DEB/RPM packages. - Install and verify the packages. 1. Update documentation, scripts and Dockerfiles - - Summarize the change log for the release. It should be reviewed by PM(s) to make it more user-friendly. - - Update [CHANGELOG.md](../../CHANGELOG.md) with the finalized change log draft. + - 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. 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. Trigger the release docker builds for Linux and Windows container images. - - Linux: push a branch named `docker` to `powershell/powershell` repository to trigger the build at [powershell docker hub](https://hub.docker.com/r/microsoft/powershell/builds/). - Delete the `docker` branch once the builds succeed. - - Windows: queue a new build in `PowerShell Windows Docker Build` on VSTS. -1. Verify the generated docker container images. 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, @@ -62,26 +57,29 @@ It **requires** that PowerShell Core has been built via `Start-PSBuild` from the #### Windows -The `Start-PSPackage` function delegates to `New-MSIPackage` which creates a Windows Installer Package of PowerShell. +`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`. -It uses the Windows Installer XML Toolset (WiX) to generate a MSI package, -which copies the output of the published PowerShell files to a version-specific folder in Program Files, -and installs a shortcut in the Start Menu. -It can be uninstalled through `Programs and Features`. - Note that PowerShell is always self-contained, thus using it does not require installing it. -The output of `Start-PSBuild` includes a `powershell.exe` executable which can simply be launched. +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`. -It relies on the [Effing Package Management][fpm] project, -which makes building packages for any (non-Windows) platform a breeze. -Similarly, the PowerShell man-page is generated from the Markdown-like file + +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 both these tools. +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 @@ -104,7 +102,7 @@ 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 pre-release version). +(and is the prerelease version). On macOS, the prefix is `/usr/local`, instead of `/opt/microsoft` because it is derived from BSD. @@ -136,7 +134,7 @@ Without `-Name` specified, the primary `powershell` package will instead be created. [fpm]: https://github.com/jordansissel/fpm -[man]: ../../assets/pwsh.1.ronn +[man]: ../../assets/manpage/pwsh.1.ronn [ronn]: https://github.com/rtomayko/ronn ### Build and Packaging Examples @@ -167,13 +165,13 @@ Start-PSBuild -Clean -CrossGen -PSModuleRestore -Runtime win7-x64 -Configuration ```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 msi -ReleaseTag v6.0.0-beta.1 -WindowsRuntime 'win7-x64' 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 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]. @@ -190,7 +188,7 @@ 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 change logs as the message. +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'. @@ -215,30 +213,10 @@ There are 2 homebrew formulas: main and preview. Update it on stable releases. -1. Make sure that you have [homebrew cask](https://caskroom.github.io/). -1. `brew update` -1. `cd /usr/local/Homebrew/Library/Taps/caskroom/homebrew-cask/Casks` -1. Edit `./powershell.rb`, reference [file history](https://github.com/vors/homebrew-cask/commits/master/Casks/powershell.rb) for the guidelines: - 1. Update `version` - 1. Update `sha256` to the checksum of produced `.pkg` (note lower-case string for the consistent style) - 1. Update `checkpoint` value. To do that run `brew cask _appcast_checkpoint --calculate 'https://github.com/PowerShell/PowerShell/releases.atom'` -1. `brew cask style --fix ./powershell.rb`, make sure there are no errors -1. `brew cask audit --download ./powershell.rb`, make sure there are no errors -1. `brew cask upgrade powershell`, make sure that powershell was updates successfully -1. Commit your changes, send a PR to [homebrew-cask](https://github.com/caskroom/homebrew-cask) +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. Add [homebrew cask versions](https://github.com/Homebrew/homebrew-cask-versions): `brew tap homebrew/cask-versions` -1. `brew update` -1. `cd /usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask-versions/Casks` -1. Edit `./powershell-preview.rb`: - 1. Update `version` - 1. Update `sha256` to the checksum of produced `.pkg` (note lower-case string for the consistent style) - 1. Update `checkpoint` value. To do that run `brew cask _appcast_checkpoint --calculate 'https://github.com/PowerShell/PowerShell/releases.atom'` -1. `brew cask style --fix ./powershell-preview.rb`, make sure there are no errors -1. `brew cask audit --download ./powershell-preview.rb`, make sure there are no errors -1. `brew cask upgrade powershell-preview`, make sure that powershell was updates successfully -1. Commit your changes, send a PR to [homebrew-cask-versions](https://github.com/Homebrew/homebrew-cask-versions) +1. Wait for a PR to show up in https://github.com/powershell/homebrew-tap, review and merge it. diff --git a/docs/testing-guidelines/CodeCoverageAnalysis.md b/docs/testing-guidelines/CodeCoverageAnalysis.md deleted file mode 100644 index bee669ea747..00000000000 --- a/docs/testing-guidelines/CodeCoverageAnalysis.md +++ /dev/null @@ -1,109 +0,0 @@ -# Code coverage analysis for commit [de5f69c](https://codecov.io/gh/PowerShell/PowerShell/tree/de5f69cf942a85839c907f11a29cf9c09f9de8b4/src) - -Code coverage runs are enabled on daily Windows builds for PowerShell Core 6. -The results of the latest build are available at [codecov.io](https://codecov.io/gh/PowerShell/PowerShell) - -The goal of this analysis is to find the hot spots of missing coverage. -The metrics used for selection of these hot spots were: # missing lines and likelihood of code path usage. - -## Coverage Status - -The following table shows the status for the above commit, dated 2018-11-28 - -| Assembly | Hit % | -| -------- |:-----:| -| Microsoft.Management.Infrastructure.CimCmdlets | 48.18% | -| Microsoft.PowerShell.Commands.Diagnostics | 47.58% | -| Microsoft.PowerShell.Commands.Management | 61.06% | -| Microsoft.PowerShell.Commands.Utility | 70.76% | -| Microsoft.PowerShell.ConsoleHost | 46.39% | -| Microsoft.PowerShell.CoreCLR.Eventing | 37.84% | -| Microsoft.PowerShell.MarkdownRender | 70.68% | -| Microsoft.PowerShell.Security | 49.36% | -| Microsoft.WSMan.Management | 62.36% | -| System.Management.Automation | 63.35% | -| Microsoft.WSMan.Runtime/WSManSessionOption.cs | 100.00% | -| powershell/Program.cs | 100.00% | - -## Hot Spots with missing coverage - -### Microsoft.PowerShell.Commands.Management - -- [ ] Add tests for *-Item cmdlets. Especially for literal paths and error cases. [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Lots of resource strings not covered. Will probably get covered when coverage is added for error cases. [#4148](https://github.com/PowerShell/PowerShell/issues/4148) - -### Microsoft.PowerShell.Commands.Utility - -- [ ] Add tests for Debug-Runspace [#4153](https://github.com/PowerShell/PowerShell/issues/4153) - -### Microsoft.PowerShell.ConsoleHost - -- [ ] Various options, DebugHandler and hosting modes like server, namedpipe etc. [#4155](https://github.com/PowerShell/PowerShell/issues/4155) - -### Microsoft.PowerShell.CoreCLR.Eventing - -- [ ] Add tests for ETW events. [#4156](https://github.com/PowerShell/PowerShell/issues/4156) - -### Microsoft.PowerShell.Security - -- [ ] Add tests for *-Acl cmdlets. [#4157](https://github.com/PowerShell/PowerShell/issues/4157) -- [ ] Add tests for *-AuthenticodeSignature cmdlets. [#4157](https://github.com/PowerShell/PowerShell/issues/4157) -- [ ] Add coverage to various utility methods under src/Microsoft.PowerShell.Security/security/Utils.cs [#4157](https://github.com/PowerShell/PowerShell/issues/4157) - -### Microsoft.WSMan.Management - -- [ ] Add tests for WSMan provider [#4158](https://github.com/PowerShell/PowerShell/issues/4158) -- [ ] Add tests for WSMan cmdlets [#4158](https://github.com/PowerShell/PowerShell/issues/4158) -- [ ] Add tests for CredSSP [#4158](https://github.com/PowerShell/PowerShell/issues/4158) - -### System.Management.Automation - -#### CoreCLR - -- [ ] Lots of non-windows code can be ifdef'ed out. [#3565](https://github.com/PowerShell/PowerShell/issues/3565) - -#### Engine - -- [ ] Add tests for Tab Completion of various types of input. [#4160](https://github.com/PowerShell/PowerShell/issues/4160) -- [ ] Add tests for debugging PS Jobs. [#4153](https://github.com/PowerShell/PowerShell/issues/4153) -- [ ] Remove Snapin code from CommandDiscovery. [#4118](https://github.com/PowerShell/PowerShell/issues/4118) -- [ ] Add tests SessionStateItem, SessionStateContainer error cases, dynamic parameters. Coverage possibly added by *-Item, *-ChildItem error case tests. [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add more tests using PSCredential [#4165](https://github.com/PowerShell/PowerShell/issues/4165) - -#### Remoting - -- [ ] Can PSProxyJobs be removed as it is for Workflows? -- [ ] Add more tests for PS Jobs. [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add more tests using -ThrottleLimit [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add tests for Register-PSSessionConfiguration [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add tests for Connect/Disconnect session [#4166](https://github.com/PowerShell/PowerShell/issues/4166) -- [ ] Add more tests for Start-Job's various options [#4166](https://github.com/PowerShell/PowerShell/issues/4166) - -#### Security - -- [ ] Add more tests under various ExecutionPolicy modes. [#4168](https://github.com/PowerShell/PowerShell/issues/4168) - -#### Utils - -- [ ] Add more error case test to improve coverage of src/System.Management.Automation/utils [#4169](https://github.com/PowerShell/PowerShell/issues/4169) - -#### Providers - -##### FileSystemProvider - -- [ ] Add tests for Mapped Network Drive [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for *-Item alternate stream [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for Get-ChildItem -path "file" [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for Rename-Item for a directory [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for Copy-Item over remote session [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for various error conditions [#4148](https://github.com/PowerShell/PowerShell/issues/4148) - -##### RegistryProvider - -- [ ] Add tests for *-Item [#4148](https://github.com/PowerShell/PowerShell/issues/4148) -- [ ] Add tests for *-Acl [#4157](https://github.com/PowerShell/PowerShell/issues/4157) -- [ ] Add tests for error conditions [#4148](https://github.com/PowerShell/PowerShell/issues/4148) - -##### FunctionProvider - -- [ ] Add *-Item tests [#4148](https://github.com/PowerShell/PowerShell/issues/4148) diff --git a/dsc/pwsh.profile.dsc.resource.json b/dsc/pwsh.profile.dsc.resource.json new file mode 100644 index 00000000000..aa5f5c29eee --- /dev/null +++ b/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/dsc/pwsh.profile.resource.ps1 b/dsc/pwsh.profile.resource.ps1 new file mode 100644 index 00000000000..ad9cfa4a63a --- /dev/null +++ b/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/es-metadata.yml b/es-metadata.yml new file mode 100644 index 00000000000..24da115c114 --- /dev/null +++ b/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/experimental-feature-linux.json b/experimental-feature-linux.json new file mode 100644 index 00000000000..31f7b965a5b --- /dev/null +++ b/experimental-feature-linux.json @@ -0,0 +1,9 @@ +[ + "PSFeedbackProvider", + "PSLoadAssemblyFromNativeCode", + "PSNativeWindowsTildeExpansion", + "PSProfileDSCResource", + "PSSerializeJSONLongEnumAsNumber", + "PSRedirectToVariable", + "PSSubsystemPluginModel" +] diff --git a/experimental-feature-windows.json b/experimental-feature-windows.json new file mode 100644 index 00000000000..31f7b965a5b --- /dev/null +++ b/experimental-feature-windows.json @@ -0,0 +1,9 @@ +[ + "PSFeedbackProvider", + "PSLoadAssemblyFromNativeCode", + "PSNativeWindowsTildeExpansion", + "PSProfileDSCResource", + "PSSerializeJSONLongEnumAsNumber", + "PSRedirectToVariable", + "PSSubsystemPluginModel" +] diff --git a/global.json b/global.json index 2c34319a232..be4bdb6275d 100644 --- a/global.json +++ b/global.json @@ -1,5 +1,5 @@ { "sdk": { - "version": "6.0.100-preview.2.21155.3" + "version": "11.0.100-preview.6.26359.118" } } diff --git a/nuget.config b/nuget.config index a8ed27bf99e..388a65572dd 100644 --- a/nuget.config +++ b/nuget.config @@ -2,8 +2,7 @@ - - + diff --git a/src/GlobalTools/PowerShell.Windows.x64/PowerShell.Windows.x64.csproj b/src/GlobalTools/PowerShell.Windows.x64/PowerShell.Windows.x64.csproj new file mode 100644 index 00000000000..8449c58ebb0 --- /dev/null +++ b/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/src/GlobalTools/PowerShell.Windows.x64/Powershell_64.png b/src/GlobalTools/PowerShell.Windows.x64/Powershell_64.png new file mode 100644 index 00000000000..2a656ffc3c8 Binary files /dev/null and b/src/GlobalTools/PowerShell.Windows.x64/Powershell_64.png differ diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs index 49f39c8c019..e794fd929d1 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimAsyncOperation.cs @@ -206,10 +206,7 @@ protected void AddCimSessionProxy(CimSessionProxy sessionproxy) { lock (cimSessionProxyCacheLock) { - if (this.cimSessionProxyCache == null) - { - this.cimSessionProxyCache = new List(); - } + this.cimSessionProxyCache ??= new List(); if (!this.cimSessionProxyCache.Contains(sessionproxy)) { @@ -347,16 +344,14 @@ protected virtual void SubscribeToCimSessionProxyEvent(CimSessionProxy proxy) /// protected object GetBaseObject(object value) { - PSObject psObject = value as PSObject; - if (psObject == null) + if (value is not PSObject psObject) { return value; } else { object baseObject = psObject.BaseObject; - var arrayObject = baseObject as object[]; - if (arrayObject == null) + if (baseObject is not object[] arrayObject) { return baseObject; } @@ -383,11 +378,10 @@ protected object GetBaseObject(object value) /// The object. protected object GetReferenceOrReferenceArrayObject(object value, ref CimType referenceType) { - PSReference cimReference = value as PSReference; - if (cimReference != null) + if (value is PSReference cimReference) { object baseObject = GetBaseObject(cimReference.Value); - if (!(baseObject is CimInstance cimInstance)) + if (baseObject is not CimInstance cimInstance) { return null; } @@ -397,8 +391,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re } else { - object[] cimReferenceArray = value as object[]; - if (cimReferenceArray == null) + if (value is not object[] cimReferenceArray) { return null; } @@ -410,7 +403,7 @@ protected object GetReferenceOrReferenceArrayObject(object value, ref CimType re CimInstance[] cimInstanceArray = new CimInstance[cimReferenceArray.Length]; for (int i = 0; i < cimReferenceArray.Length; i++) { - if (!(cimReferenceArray[i] is PSReference tempCimReference)) + if (cimReferenceArray[i] is not PSReference tempCimReference) { return null; } @@ -531,10 +524,7 @@ private void Cleanup() } this.moreActionEvent.Dispose(); - if (this.ackedEvent != null) - { - this.ackedEvent.Dispose(); - } + this.ackedEvent?.Dispose(); DebugHelper.WriteLog("Cleanup complete.", 2); } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs index e3e487a9533..4702e47e2f2 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimBaseAction.cs @@ -168,10 +168,7 @@ protected virtual void Dispose(bool disposing) if (disposing) { // Dispose managed resources. - if (this.completeEvent != null) - { - this.completeEvent.Dispose(); - } + this.completeEvent?.Dispose(); } // Call the appropriate methods to clean up diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs index 059f58a97b2..89f7478b513 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimCommandBase.cs @@ -57,7 +57,7 @@ internal class ParameterSetEntry /// Initializes a new instance of the class. /// /// - internal ParameterSetEntry(UInt32 mandatoryParameterCount) + internal ParameterSetEntry(uint mandatoryParameterCount) { this.MandatoryParameterCount = mandatoryParameterCount; this.IsDefaultParameterSet = false; @@ -80,7 +80,7 @@ internal ParameterSetEntry(ParameterSetEntry toClone) /// /// /// - internal ParameterSetEntry(UInt32 mandatoryParameterCount, bool isDefault) + internal ParameterSetEntry(uint mandatoryParameterCount, bool isDefault) { this.MandatoryParameterCount = mandatoryParameterCount; this.IsDefaultParameterSet = isDefault; @@ -104,7 +104,7 @@ internal void reset() /// /// Property MandatoryParameterCount /// - internal UInt32 MandatoryParameterCount { get; } = 0; + internal uint MandatoryParameterCount { get; } = 0; /// /// Property IsValueSet @@ -119,12 +119,12 @@ internal void reset() /// /// Property SetMandatoryParameterCount /// - internal UInt32 SetMandatoryParameterCount { get; set; } = 0; + internal uint SetMandatoryParameterCount { get; set; } = 0; /// /// Property SetMandatoryParameterCountAtBeginProcess /// - internal UInt32 SetMandatoryParameterCountAtBeginProcess { get; set; } = 0; + internal uint SetMandatoryParameterCountAtBeginProcess { get; set; } = 0; } /// @@ -390,10 +390,7 @@ internal string GetParameterSet() } // Looking for default parameter set - if (boundParameterSetName == null) - { - boundParameterSetName = defaultParameterSetName; - } + boundParameterSetName ??= defaultParameterSetName; // throw if still can not find the parameter set name if (boundParameterSetName == null) @@ -473,10 +470,7 @@ internal void SetParameter(object value, string parameterName) return; } - if (this.parameterBinder != null) - { - this.parameterBinder.SetParameter(parameterName, this.AtBeginProcess); - } + this.parameterBinder?.SetParameter(parameterName, this.AtBeginProcess); } #endregion @@ -579,10 +573,7 @@ protected void Dispose(bool disposing) protected virtual void DisposeInternal() { // Dispose managed resources. - if (this.operation != null) - { - this.operation.Dispose(); - } + this.operation?.Dispose(); } #endregion @@ -672,6 +663,7 @@ internal virtual CmdletOperationBase CmdletOperation /// Throw terminating error /// /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] internal void ThrowTerminatingError(Exception exception, string operation) { ErrorRecord errorRecord = new(exception, operation, ErrorCategory.InvalidOperation, this); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs index 386482f11c5..c775325094b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetCimClass.cs @@ -97,7 +97,7 @@ public void GetCimClass(GetCimClassCommand cmdlet) { List proxys = new(); string nameSpace = ConstValue.GetNamespace(cmdlet.Namespace); - string className = (cmdlet.ClassName == null) ? @"*" : cmdlet.ClassName; + string className = cmdlet.ClassName ?? @"*"; CimGetCimClassContext context = new( cmdlet.ClassName, cmdlet.MethodName, @@ -165,6 +165,7 @@ private static void SetSessionProxyProperties( GetCimClassCommand cmdlet) { proxy.OperationTimeout = cmdlet.OperationTimeoutSec; + proxy.Amended = cmdlet.Amended; } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs index 25400514401..371b06d9356 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimGetInstance.cs @@ -284,8 +284,7 @@ protected static string GetQuery(CimBaseCommand cmdlet) internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); - GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmdlet is GetCimInstanceCommand cmd) { if (cmd.QueryDialect != null || cmd.SelectProperties != null || cmd.Filter != null) { @@ -299,8 +298,7 @@ internal static bool IsClassNameQuerySet(CimBaseCommand cmdlet) protected static string CreateQuery(CimBaseCommand cmdlet) { DebugHelper.WriteLogEx(); - GetCimInstanceCommand cmd = cmdlet as GetCimInstanceCommand; - if (cmd != null) + if (cmdlet is GetCimInstanceCommand cmd) { StringBuilder propertyList = new(); if (cmd.SelectProperties == null) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs index 0c847265cfe..899e67495cc 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimIndicationWatcher.cs @@ -153,7 +153,7 @@ public CimIndicationWatcher( string theNamespace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); computerName = ConstValue.GetComputerName(computerName); @@ -173,7 +173,7 @@ public CimIndicationWatcher( string theNamespace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { ValidationHelper.ValidateNoNullorWhiteSpaceArgument(queryExpression, queryExpressionParameterName); ValidationHelper.ValidateNoNullArgument(cimSession, cimSessionParameterName); @@ -192,7 +192,7 @@ private void Initialize( string theNameSpace, string theQueryDialect, string theQueryExpression, - UInt32 theOperationTimeout) + uint theOperationTimeout) { enableRaisingEvents = false; status = Status.Default; @@ -221,14 +221,11 @@ private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs a if (temp != null) { // raise the event - CimSubscriptionResultEventArgs resultArgs = args as CimSubscriptionResultEventArgs; - if (resultArgs != null) + if (args is CimSubscriptionResultEventArgs resultArgs) temp(this, new CimIndicationEventInstanceEventArgs(resultArgs.Result)); - else + else if (args is CimSubscriptionExceptionEventArgs exceptionArgs) { - CimSubscriptionExceptionEventArgs exceptionArgs = args as CimSubscriptionExceptionEventArgs; - if (exceptionArgs != null) - temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); + temp(this, new CimIndicationEventExceptionEventArgs(exceptionArgs.Exception)); } } } @@ -242,7 +239,7 @@ private void NewSubscriptionResultHandler(object src, CimSubscriptionEventArgs a /// If set EnableRaisingEvents to false, which will be ignored /// /// - [BrowsableAttribute(false)] + [Browsable(false)] public bool EnableRaisingEvents { get @@ -378,7 +375,7 @@ internal void SetCmdlet(Cmdlet cmdlet) private string nameSpace; private string queryDialect; private string queryExpression; - private UInt32 operationTimeout; + private uint operationTimeout; #endregion #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs index d7436fc0ec8..beb3e551d33 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimNewCimInstance.cs @@ -179,15 +179,14 @@ internal void GetCimInstance(CimInstance cimInstance, XOperationContextBase cont { DebugHelper.WriteLogEx(); - CimNewCimInstanceContext newCimInstanceContext = context as CimNewCimInstanceContext; - if (newCimInstanceContext == null) + if (context is not CimNewCimInstanceContext newCimInstanceContext) { DebugHelper.WriteLog("Invalid (null) CimNewCimInstanceContext", 1); return; } CimSessionProxy proxy = CreateCimSessionProxy(newCimInstanceContext.Proxy); - string nameSpace = (cimInstance.CimSystemProperties.Namespace == null) ? newCimInstanceContext.Namespace : cimInstance.CimSystemProperties.Namespace; + string nameSpace = cimInstance.CimSystemProperties.Namespace ?? newCimInstanceContext.Namespace; proxy.GetInstanceAsync(nameSpace, cimInstance); } @@ -295,8 +294,7 @@ private CimInstance CreateCimInstance( DebugHelper.WriteLog("Create and add new property to ciminstance: name = {0}; value = {1}; flags = {2}", 5, propertyName, propertyValue, flag); - PSReference cimReference = propertyValue as PSReference; - if (cimReference != null) + if (propertyValue is PSReference cimReference) { CimProperty newProperty = CimProperty.Create(propertyName, GetBaseObject(cimReference.Value), CimType.Reference, flag); cimInstance.CimInstanceProperties.Add(newProperty); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs index e0fbb1aa095..692a5f123e8 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimRegisterCimIndication.cs @@ -123,7 +123,7 @@ public void RegisterCimIndication( string nameSpace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); this.TargetComputerName = computerName; @@ -146,13 +146,11 @@ public void RegisterCimIndication( string nameSpace, string queryDialect, string queryExpression, - UInt32 operationTimeout) + uint operationTimeout) { DebugHelper.WriteLogEx("queryDialect = '{0}'; queryExpression = '{1}'", 0, queryDialect, queryExpression); - if (cimSession == null) - { - throw new ArgumentNullException(string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, @"cimSession")); - } + + ArgumentNullException.ThrowIfNull(cimSession, string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.NullArgument, nameof(cimSession))); this.TargetComputerName = cimSession.ComputerName; CimSessionProxy proxy = CreateSessionProxy(cimSession, operationTimeout); @@ -198,8 +196,7 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio } // NOTES: should move after this.Disposed, but need to log the exception - CimWriteError cimWriteError = actionArgs.Action as CimWriteError; - if (cimWriteError != null) + if (actionArgs.Action is CimWriteError cimWriteError) { this.Exception = cimWriteError.Exception; if (!this.ackedEvent.IsSet) @@ -221,11 +218,9 @@ private void CimIndicationHandler(object cimSession, CmdletActionEventArgs actio DebugHelper.WriteLog("Got an exception: {0}", 2, Exception); } - CimWriteResultObject cimWriteResultObject = actionArgs.Action as CimWriteResultObject; - if (cimWriteResultObject != null) + if (actionArgs.Action is CimWriteResultObject cimWriteResultObject) { - CimSubscriptionResult result = cimWriteResultObject.Result as CimSubscriptionResult; - if (result != null) + if (cimWriteResultObject.Result is CimSubscriptionResult result) { EventHandler temp = this.OnNewSubscriptionResult; if (temp != null) @@ -317,7 +312,7 @@ internal string TargetComputerName /// private CimSessionProxy CreateSessionProxy( string computerName, - UInt32 timeout) + uint timeout) { CimSessionProxy proxy = CreateCimSessionProxy(computerName); proxy.OperationTimeout = timeout; @@ -332,7 +327,7 @@ private CimSessionProxy CreateSessionProxy( /// private CimSessionProxy CreateSessionProxy( CimSession session, - UInt32 timeout) + uint timeout) { CimSessionProxy proxy = CreateCimSessionProxy(session); proxy.OperationTimeout = timeout; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs index c27c7493ddb..389c45c8314 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimResultObserver.cs @@ -419,8 +419,7 @@ public override void OnNext(CimMethodResultBase value) string resultObjectPSType = null; PSObject resultObject = null; - CimMethodResult methodResult = value as CimMethodResult; - if (methodResult != null) + if (value is CimMethodResult methodResult) { resultObjectPSType = PSTypeCimMethodResult; resultObject = new PSObject(); @@ -431,8 +430,7 @@ public override void OnNext(CimMethodResultBase value) } else { - CimMethodStreamedResult methodStreamedResult = value as CimMethodStreamedResult; - if (methodStreamedResult != null) + if (value is CimMethodStreamedResult methodStreamedResult) { resultObjectPSType = PSTypeCimMethodStreamedResult; resultObject = new PSObject(); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs index 28d530ed6a3..b8ebc9adaef 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionOperations.cs @@ -535,9 +535,8 @@ internal IEnumerable QuerySession( { if (this.curCimSessionsById.ContainsKey(id)) { - if (!sessionIds.Contains(id)) + if (sessionIds.Add(id)) { - sessionIds.Add(id); sessions.Add(this.curCimSessionsById[id].GetPSObject()); } } @@ -951,7 +950,7 @@ internal void AddSessionToCache(CimSession cimSession, XOperationContextBase con CimTestCimSessionContext testCimSessionContext = context as CimTestCimSessionContext; uint sessionId = this.sessionState.GenerateSessionId(); string originalSessionName = testCimSessionContext.CimSessionWrapper.Name; - string sessionName = (originalSessionName != null) ? originalSessionName : string.Format(CultureInfo.CurrentUICulture, @"{0}{1}", CimSessionState.CimSessionClassName, sessionId); + string sessionName = originalSessionName ?? string.Create(CultureInfo.CurrentUICulture, $"{CimSessionState.CimSessionClassName}{sessionId}"); // detach CimSession from the proxy object CimSession createdCimSession = testCimSessionContext.Proxy.Detach(); diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs index dfbfe090ddc..5cdc168ae24 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimSessionProxy.cs @@ -539,14 +539,34 @@ private void CreateSetSession( #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 UInt32 OperationTimeout + public uint OperationTimeout { get { - return (UInt32)this.OperationOptions.Timeout.TotalSeconds; + return (uint)this.OperationOptions.Timeout.TotalSeconds; } set @@ -666,9 +686,9 @@ private void InitOption(CimOperationOptions operOptions) { this.OperationOptions = new CimOperationOptions(operOptions); } - else if (this.OperationOptions == null) + else { - this.OperationOptions = new CimOperationOptions(); + this.OperationOptions ??= new CimOperationOptions(); } this.EnableMethodResultStreaming = true; @@ -821,7 +841,7 @@ private void FireOperationDeletedEvent( /// /// /// - internal void WriteMessage(UInt32 channel, string message) + internal void WriteMessage(uint channel, string message) { DebugHelper.WriteLogEx("Channel = {0} message = {1}", 0, channel, message); try @@ -855,7 +875,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi parameters.Append(','); } - parameters.Append(string.Format(CultureInfo.CurrentUICulture, @"'{0}' = {1}", key, parameterList[key])); + parameters.Append(CultureInfo.CurrentUICulture, $@"'{key}' = {parameterList[key]}"); } } @@ -863,7 +883,7 @@ internal void WriteOperationStartMessage(string operation, Hashtable parameterLi CimCmdletStrings.CimOperationStart, operation, (parameters.Length == 0) ? "null" : parameters.ToString()); - WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationStartMessage); + WriteMessage((uint)CimWriteMessageChannel.Verbose, operationStartMessage); } /// @@ -878,7 +898,7 @@ internal void WriteOperationCompleteMessage(string operation) string operationCompleteMessage = string.Format(CultureInfo.CurrentUICulture, CimCmdletStrings.CimOperationCompleted, operation); - WriteMessage((UInt32)CimWriteMessageChannel.Verbose, operationCompleteMessage); + WriteMessage((uint)CimWriteMessageChannel.Verbose, operationCompleteMessage); } /// @@ -894,8 +914,8 @@ internal void WriteOperationCompleteMessage(string operation) public void WriteProgress(string activity, string currentOperation, string statusDescription, - UInt32 percentageCompleted, - UInt32 secondsRemaining) + uint percentageCompleted, + uint secondsRemaining) { DebugHelper.WriteLogEx("activity:{0}; currentOperation:{1}; percentageCompleted:{2}; secondsRemaining:{3}", 0, activity, currentOperation, percentageCompleted, secondsRemaining); @@ -1212,7 +1232,7 @@ public void EnumerateInstancesAsync(string namespaceName, string className) this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateInstancesAsync(namespaceName, className, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimInstanceAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1294,7 +1314,7 @@ public void EnumerateClassesAsync(string namespaceName, string className) this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncMultipleResults asyncResult = this.CimSession.EnumerateClassesAsync(namespaceName, className, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1314,7 +1334,7 @@ public void GetClassAsync(string namespaceName, string className) this.operationParameters.Add(@"className", className); this.WriteOperationStartMessage(this.operationName, this.operationParameters); CimAsyncResult asyncResult = this.CimSession.GetClassAsync(namespaceName, className, this.OperationOptions); - string errorSource = string.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimClassAsync(asyncResult, new CimResultContext(errorSource)); } @@ -1368,7 +1388,7 @@ public void InvokeMethodAsync( 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.Format(CultureInfo.CurrentUICulture, "{0}:{1}", namespaceName, className); + string errorSource = string.Create(CultureInfo.CurrentUICulture, $"{namespaceName}:{className}"); ConsumeCimInvokeMethodResultAsync(asyncResult, className, methodName, new CimResultContext(errorSource)); } @@ -1473,7 +1493,7 @@ protected virtual void PostOperationDeleteEvent(OperationEventArgs args) /// 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 constuctor. + /// if it is created by constructor. /// internal CimSession CimSession { get; private set; } @@ -1879,7 +1899,7 @@ private CimSession CreateCimSessionByComputerName(string computerName) /// /// internal static CimSessionOptions CreateCimSessionOption(string computerName, - UInt32 timeout, CimCredential credential) + uint timeout, CimCredential credential) { DebugHelper.WriteLogEx(); @@ -2021,7 +2041,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) } CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject; - if (!(writeResultObject.Result is CimClass cimClass)) + if (writeResultObject.Result is not CimClass cimClass) { return true; } @@ -2134,12 +2154,11 @@ internal class CimSessionProxyNewCimInstance : CimSessionProxy /// /// Initializes a new instance of the class. - /// + /// /// /// Create by given computer name. /// Then create wrapper object. /// - /// public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance operation) : base(computerName) { @@ -2149,6 +2168,7 @@ public CimSessionProxyNewCimInstance(string computerName, CimNewCimInstance oper /// /// Initializes a new instance of the class. /// + /// /// /// Create by given computer name /// and session options. @@ -2180,7 +2200,7 @@ protected override bool PreNewActionEvent(CmdletActionEventArgs args) } CimWriteResultObject writeResultObject = args.Action as CimWriteResultObject; - if (!(writeResultObject.Result is CimInstance cimInstance)) + if (writeResultObject.Result is not CimInstance cimInstance) { return true; } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs index d3ae3419fa4..f1ebe911603 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteError.cs @@ -39,14 +39,12 @@ internal static ErrorRecord ErrorRecordFromAnyException( { Debug.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(context, cimException, cimResultContext); } - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { return InitializeErrorRecord(context, exception: inner, diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs index cf927617235..f4b244b97f9 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteMessage.cs @@ -26,7 +26,7 @@ internal sealed class CimWriteMessage : CimBaseAction #region Properties - internal UInt32 Channel { get; } + internal uint Channel { get; } internal string Message { get; } @@ -35,7 +35,7 @@ internal sealed class CimWriteMessage : CimBaseAction /// /// Initializes a new instance of the class. /// - public CimWriteMessage(UInt32 channel, + public CimWriteMessage(uint channel, string message) { this.Channel = channel; diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs index 8e5632215a0..b99407ccc81 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CimWriteProgress.cs @@ -40,8 +40,8 @@ public CimWriteProgress( int theActivityID, string theCurrentOperation, string theStatusDescription, - UInt32 thePercentageCompleted, - UInt32 theSecondsRemaining) + uint thePercentageCompleted, + uint theSecondsRemaining) { this.Activity = theActivity; this.ActivityID = theActivityID; @@ -112,12 +112,12 @@ public override void Execute(CmdletOperationBase cmdlet) /// /// Gets the percentage completed of the given activity. /// - internal UInt32 PercentageCompleted { get; } + internal uint PercentageCompleted { get; } /// /// Gets the number of seconds remaining for the given activity. /// - internal UInt32 SecondsRemaining { get; } + internal uint SecondsRemaining { get; } #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs index 3c49b1dcbb8..bd1a2751622 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/CmdletOperation.cs @@ -65,6 +65,7 @@ public virtual bool ShouldProcess(string verboseDescription, string verboseWarni return cmdlet.ShouldProcess(verboseDescription, verboseWarning, caption, out shouldProcessReason); } + [System.Diagnostics.CodeAnalysis.DoesNotReturn] public virtual void ThrowTerminatingError(ErrorRecord errorRecord) { cmdlet.ThrowTerminatingError(errorRecord); @@ -115,6 +116,7 @@ public virtual void WriteWarning(string text) /// Throw terminating error /// /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] internal void ThrowTerminatingError(Exception exception, string operation) { ErrorRecord errorRecord = new(exception, operation, ErrorCategory.InvalidOperation, this); @@ -230,8 +232,7 @@ public override void WriteObject(object sendToPipeline, XOperationContextBase co if (sendToPipeline is CimInstance) { - CimSetCimInstanceContext setContext = context as CimSetCimInstanceContext; - if (setContext != null) + if (context is CimSetCimInstanceContext setContext) { if (string.Equals(setContext.ParameterSetName, CimBaseCommand.QueryComputerSet, StringComparison.OrdinalIgnoreCase) || string.Equals(setContext.ParameterSetName, CimBaseCommand.QuerySessionSet, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs index ea592b40b90..6c4d0c94d2b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimAssociatedInstanceCommand.cs @@ -110,7 +110,7 @@ public CimInstance InputObject /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// @@ -232,8 +232,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimGetAssociatedInstance operation = this.GetOperationAgent(); - if (operation != null) - operation.ProcessRemainActions(this.CmdletOperation); + operation?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs index d4ab679f0a7..1bededc485f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimClassCommand.cs @@ -43,6 +43,12 @@ public GetCimClassCommand() #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". @@ -79,7 +85,7 @@ public GetCimClassCommand() /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "Session". @@ -196,10 +202,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimGetCimClass cimGetCimClass = this.GetOperationAgent(); - if (cimGetCimClass != null) - { - cimGetCimClass.ProcessRemainActions(this.CmdletOperation); - } + cimGetCimClass?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs index cc4de5e84e9..65eeae8e450 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimInstanceCommand.cs @@ -260,7 +260,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". @@ -491,10 +491,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimGetInstance cimGetInstance = this.GetOperationAgent(); - if (cimGetInstance != null) - { - cimGetInstance.ProcessRemainActions(this.CmdletOperation); - } + cimGetInstance?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs index a402d58d0d3..3289b6c86c0 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/GetCimSessionCommand.cs @@ -81,7 +81,7 @@ public string[] ComputerName ValueFromPipelineByPropertyName = true, ParameterSetName = SessionIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt32[] Id + public uint[] Id { get { @@ -95,7 +95,7 @@ public UInt32[] Id } } - private UInt32[] id; + private uint[] id; /// /// The following is the definition of the input parameter "InstanceID". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs index f920094ae15..e3bc6f293b6 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/InvokeCimMethodCommand.cs @@ -373,7 +373,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } #endregion @@ -408,10 +408,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimInvokeCimMethod cimInvokeMethod = this.GetOperationAgent(); - if (cimInvokeMethod != null) - { - cimInvokeMethod.ProcessRemainActions(this.CmdletOperation); - } + cimInvokeMethod?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj b/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj index 582858a592b..f5388782d9c 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Microsoft.Management.Infrastructure.CimCmdlets.csproj @@ -10,4 +10,9 @@ + + + $(RootNamespace).resources.%(Filename) + + diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs index b43b1e275d7..5843f25a26b 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimInstanceCommand.cs @@ -223,7 +223,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// @@ -377,10 +377,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimNewCimInstance cimNewCimInstance = this.GetOperationAgent(); - if (cimNewCimInstance != null) - { - cimNewCimInstance.ProcessRemainActions(this.CmdletOperation); - } + cimNewCimInstance?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs index 2d1a91f5c0e..8b8e36cf829 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionCommand.cs @@ -54,7 +54,7 @@ public PasswordAuthenticationMechanism Authentication /// The default is the current user. /// [Parameter(Position = 1, ParameterSetName = CredentialParameterSet)] - [Credential()] + [Credential] public PSCredential Credential { get; set; } /// @@ -104,7 +104,7 @@ public PasswordAuthenticationMechanism Authentication /// [Alias(AliasOT)] [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 OperationTimeoutSec + public uint OperationTimeoutSec { get { @@ -118,7 +118,7 @@ public UInt32 OperationTimeoutSec } } - private UInt32 operationTimeout; + private uint operationTimeout; internal bool operationTimeoutSet = false; /// @@ -136,7 +136,7 @@ public UInt32 OperationTimeoutSec /// This is specificly for wsman protocol. /// [Parameter(ValueFromPipelineByPropertyName = true)] - public UInt32 Port + public uint Port { get { @@ -150,7 +150,7 @@ public UInt32 Port } } - private UInt32 port; + private uint port; private bool portSet = false; /// @@ -234,8 +234,7 @@ internal void BuildSessionOptions(out CimSessionOptions outputOptions, out CimCr outputCredential = null; if (options != null) { - DComSessionOptions dcomOptions = options as DComSessionOptions; - if (dcomOptions != null) + if (options is DComSessionOptions dcomOptions) { bool conflict = false; string parameterName = string.Empty; @@ -334,10 +333,7 @@ protected override void DisposeInternal() base.DisposeInternal(); // Dispose managed resources. - if (this.cimNewSession != null) - { - this.cimNewSession.Dispose(); - } + this.cimNewSession?.Dispose(); } #endregion } diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs index 0b62b79d96c..54956a9805a 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/NewCimSessionOptionCommand.cs @@ -231,7 +231,7 @@ public Uri HttpPrefix /// [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = WSManParameterSet)] - public UInt32 MaxEnvelopeSizeKB + public uint MaxEnvelopeSizeKB { get { @@ -246,7 +246,7 @@ public UInt32 MaxEnvelopeSizeKB } } - private UInt32 maxenvelopesizekb; + private uint maxenvelopesizekb; private bool maxenvelopesizekbSet = false; /// @@ -299,7 +299,7 @@ public string ProxyCertificateThumbprint /// Ps Credential used by the proxy server when required by the server. /// [Parameter(ParameterSetName = WSManParameterSet)] - [Credential()] + [Credential] public PSCredential ProxyCredential { get diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs index 246a95f37e3..b314691e41f 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RegisterCimIndicationCommand.cs @@ -124,7 +124,7 @@ public string QueryDialect /// [Alias(CimBaseCommand.AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "Session". @@ -205,7 +205,7 @@ protected override object GetSourceObject() case CimBaseCommand.ClassNameComputerSet: // validate the classname this.CheckArgument(); - tempQueryExpression = string.Format(CultureInfo.CurrentCulture, "Select * from {0}", this.ClassName); + tempQueryExpression = string.Create(CultureInfo.CurrentCulture, $"Select * from {this.ClassName}"); break; } @@ -227,10 +227,7 @@ protected override object GetSourceObject() break; } - if (watcher != null) - { - watcher.SetCmdlet(this); - } + watcher?.SetCmdlet(this); return watcher; } @@ -275,10 +272,7 @@ private static void newSubscriber_Unsubscribed( DebugHelper.WriteLogEx(); CimIndicationWatcher watcher = sender as CimIndicationWatcher; - if (watcher != null) - { - watcher.Stop(); - } + watcher?.Stop(); } #region private members diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs index c3f1230020c..5ac8d129367 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimInstanceCommand.cs @@ -154,7 +154,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". @@ -276,10 +276,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimRemoveCimInstance cimRemoveInstance = this.GetOperationAgent(); - if (cimRemoveInstance != null) - { - cimRemoveInstance.ProcessRemainActions(this.CmdletOperation); - } + cimRemoveInstance?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs index 53937e57354..2f1a5ad026e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/RemoveCimSessionCommand.cs @@ -108,7 +108,7 @@ public string[] ComputerName ValueFromPipelineByPropertyName = true, ParameterSetName = SessionIdSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt32[] Id + public uint[] Id { get { @@ -122,7 +122,7 @@ public UInt32[] Id } } - private UInt32[] id; + private uint[] id; /// /// The following is the definition of the input parameter "InstanceId". diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs index 25b3113e452..d190e5fafba 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/SetCimInstanceCommand.cs @@ -151,7 +151,7 @@ public string Namespace /// [Alias(AliasOT)] [Parameter] - public UInt32 OperationTimeoutSec { get; set; } + public uint OperationTimeoutSec { get; set; } /// /// The following is the definition of the input parameter "InputObject". @@ -325,10 +325,7 @@ protected override void ProcessRecord() protected override void EndProcessing() { CimSetCimInstance cimSetCimInstance = this.GetOperationAgent(); - if (cimSetCimInstance != null) - { - cimSetCimInstance.ProcessRemainActions(this.CmdletOperation); - } + cimSetCimInstance?.ProcessRemainActions(this.CmdletOperation); } #endregion diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs index bab5c092894..adcab254231 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/Utils.cs @@ -88,7 +88,7 @@ internal static bool IsDefaultComputerName(string computerName) /// internal static IEnumerable GetComputerNames(IEnumerable computerNames) { - return (computerNames == null) ? NullComputerNames : computerNames; + return computerNames ?? NullComputerNames; } /// @@ -110,7 +110,7 @@ internal static string GetComputerName(string computerName) /// internal static string GetNamespace(string nameSpace) { - return (nameSpace == null) ? DefaultNameSpace : nameSpace; + return nameSpace ?? DefaultNameSpace; } /// @@ -122,7 +122,7 @@ internal static string GetNamespace(string nameSpace) /// internal static string GetQueryDialectWithDefault(string queryDialect) { - return (queryDialect == null) ? DefaultQueryDialect : queryDialect; + return queryDialect ?? DefaultQueryDialect; } } @@ -199,18 +199,8 @@ internal static string GetSourceCodeInformation(bool withFileName, int depth) { StackTrace trace = new(); StackFrame frame = trace.GetFrame(depth); - // if (withFileName) - // { - // return string.Format(CultureInfo.CurrentUICulture, "{0}#{1}:{2}:", frame.GetFileName()., frame.GetFileLineNumber(), frame.GetMethod().Name); - // } - // else - // { - // return string.Format(CultureInfo.CurrentUICulture, "{0}:", frame.GetMethod()); - // } - - return string.Format(CultureInfo.CurrentUICulture, "{0}::{1} ", - frame.GetMethod().DeclaringType.Name, - frame.GetMethod().Name); + + return string.Create(CultureInfo.CurrentUICulture, $"{frame.GetMethod().DeclaringType.Name}::{frame.GetMethod().Name} "); } #endregion @@ -371,10 +361,7 @@ internal static class ValidationHelper /// public static void ValidateNoNullArgument(object obj, string argumentName) { - if (obj == null) - { - throw new ArgumentNullException(argumentName); - } + ArgumentNullException.ThrowIfNull(obj, argumentName); } /// diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx index d479d28b5bf..bf75344781e 100644 --- a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/CimCmdletStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/cs/CimCmdletStrings.cs.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/cs/CimCmdletStrings.cs.resx new file mode 100644 index 00000000000..9364b782c69 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/cs/CimCmdletStrings.cs.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 + + + Operace{0} byla dokončena. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Vytvořit CimInstance + + + Odstranit CimInstance + + + Vytvořit výčet přidružených instancí CimInstances + + + Výčet CimClasses + + + Výčet CimInstances + + + Získat CimClass + + + Získat CimInstance + + + Vyvolat CimMethod + + + Upravit CimInstance + + + Dotaz na CimInstances + + + Přihlásit k odběru CimIndication + + + Proveďte operaci {0} s následujícími parametry: {1}. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Parametr {0} nelze použít společně s parametrem {1}. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Nepodařilo se najít objekt CimSession s hodnotou {0} = {1}. + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + V zadané třídě {0} se nepodařilo najít následující vlastnosti: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Nepodařilo se změnit vlastnost {0} objektu {1}, která je jen pro čtení. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Popis stavu platby + N/A + + + Operaci nelze provést, protože cesta se zástupnými znaky {0} nebyla přeložena na soubor. + {0} is a placeholder for a path + + + Typ ověřování {0} není bez přihlašovacích údajů platný. Bez přihlašovacích údajů jsou povoleny pouze následující typy ověřování: {1}, {2}, {3} nebo {4}. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Ve třídě {1} se nepodařilo najít metodu {0}. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Ve třídě {2} se nepodařilo najít parametr {0} v metodě {1}. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Neplatná operace. Aktuální rutina již má vytvořenou operaci. + N/A + + + Argument {0} obsahuje znaky, které nejsou v parametru {1} povoleny. Zadejte platný argument a pak příkaz spusťte znovu. + {0} stand for argument value, {1} stand for parameter name. + + + Operaci nelze provést, protože cesta byla přeložena na více než jeden soubor. Tento příkaz nemůže pracovat s více soubory. + + + Argument {0} nemůže mít hodnotu null. + N/A + + + Objekt proxy CimSession již provádí operaci. + N/A + + + Soubor nejde otevřít, protože aktuální poskytovatel ({0}) nemůže otevřít soubor. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Do vstupního objektu {1} nelze přidat vlastnost {0}. Schéma třídy neobsahuje tuto vlastnost. + {0} stand for property name, {1} stand for cim instance path. + + + Název sady parametrů se nepodařilo přeložit. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/de/CimCmdletStrings.de.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/de/CimCmdletStrings.de.resx new file mode 100644 index 00000000000..1f3d389d78d --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/de/CimCmdletStrings.de.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 + + + Der Vorgang „{0}“ wurde abgeschlossen. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + CimInstance erstellen + + + CimInstance löschen + + + Zugeordnete CimInstances auflisten + + + CimClasses auflisten + + + CimInstances auflisten + + + CimClass abrufen + + + CimInstance abrufen + + + CimMethod aufrufen + + + CimInstance ändern + + + CimInstances abfragen + + + CimIndication abonnieren + + + Führen Sie den Vorgang „{0}“ mit den folgenden Parametern aus: „{1}“. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Der Parameter „{0}“ kann nicht mit dem Parameter „{1}“ verwendet werden. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + CimSession mit der angegebenen {0} = {1} wurde nicht gefunden. + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Die folgenden Eigenschaften konnten in der angegebenen Klasse „{0}“ nicht gefunden werden: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Die schreibgeschützte Eigenschaft „{0}“ des Objekts „{1}“ konnte nicht geändert werden. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Standardstatusbeschreibung + N/A + + + Der Vorgang kann nicht ausgeführt werden, da der Wildcardpfad „{0}“ nicht in eine Datei aufgelöst wurde. + {0} is a placeholder for a path + + + Der Authentifizierungstyp „{0}“ ist ohne Anmeldeinformationen ungültig. Ohne Anmeldeinformationen sind nur die folgenden Authentifizierungstypen zulässig: „{1}“, „{2}“, „{3}“ oder „{4}“. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Die Methode „{0}“ konnte in der Klasse „{1}“ nicht gefunden werden. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Der Parameter „{0}“ konnte in der Methode „{1}“ der Klasse „{2}“ nicht gefunden werden. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Ungültige Operation. Für das aktuelle Cmdlet wurde bereits ein Vorgang erstellt. + N/A + + + Das Argument „{0}“ enthält Zeichen, die im Parameter „{1}“ nicht zulässig sind. Geben Sie ein gültiges Argument an, und wiederholen Sie dann den Befehl. + {0} stand for argument value, {1} stand for parameter name. + + + Der Vorgang kann nicht ausgeführt werden, da der Pfad in mehrere Dateien aufgelöst wurde. Dieser Befehl kann nicht für mehrere Dateien verwendet werden. + + + Das Argument „{0}“ darf nicht NULL sein. + N/A + + + Für das CimSession-Proxyobjekt wird bereits ein Vorgang ausgeführt. + N/A + + + Die Datei kann nicht geöffnet werden, da der aktuelle Anbieter ({0}) keine Datei öffnen kann. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Die Eigenschaft „{0}“ kann dem Eingabeobjekt „{1}“ nicht hinzugefügt werden. Das Klassenschema enthält diese Eigenschaft nicht. + {0} stand for property name, {1} stand for cim instance path. + + + Der Name des Parametersatzes kann nicht aufgelöst werden. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/es/CimCmdletStrings.es.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/es/CimCmdletStrings.es.resx new file mode 100644 index 00000000000..ca57243da14 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/es/CimCmdletStrings.es.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 + + + Operación "{0}" completada. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Creación de CimInstance + + + Eliminar CimInstance + + + Enumerar CimInstances asociadas + + + Enumerar CimClasses + + + Enumerar CimInstances + + + Obtener CimClass + + + Obtener CimInstance + + + Invocar CimMethod + + + Modificar CimInstance + + + Instancias CimInstances de consulta + + + Suscribir CimIndication + + + Realice la operación "{0}" con los siguientes parámetros, "{1}". + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + El parámetro "{0}" no se puede usar con el parámetro "{1}". + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + No se pudo encontrar CimSession con el especificado {0} = {1} + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + No se encontraron las siguientes propiedades en la clase dada {0}: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + No se pudo modificar la propiedad de solo lectura "{0}" del objeto "{1}". + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Descripción del estado predeterminado. + N/A + + + No se puede realizar la operación porque la ruta de acceso comodín {0} no se resolvió en un archivo. + {0} is a placeholder for a path + + + El tipo de autenticación "{0}" no es válido sin credenciales. Solo se permiten los siguientes tipos de autenticación sin credenciales, "{1}", "{2}", "{3}" o "{4}". + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + No se encuentra el método "{0}" en la clase "{1}". + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + No se encuentra el parámetro "{0}" en el método "{1}" de la clase "{2}". + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Operación no válida. El cmdlet actual ya tiene una operación creada. + N/A + + + El argumento "{0}" contiene caracteres no permitidos en el parámetro "{1}". Proporcione un argumento que sea válido e intente el comando de nuevo. + {0} stand for argument value, {1} stand for parameter name. + + + No se puede realizar la operación porque la ruta de acceso se resolvió en más de un archivo. Este comando no puede funcionar en varios archivos. + + + El argumento "{0}" no puede ser null. + N/A + + + El objeto proxy CimSession ya tiene una operación en curso. + N/A + + + No se puede abrir el archivo porque el proveedor actual ({0}) no puede abrir un archivo. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + No se puede agregar la propiedad "{0}" al objeto de entrada "{1}". El esquema de clase no contiene la propiedad. + {0} stand for property name, {1} stand for cim instance path. + + + No se puede resolver el nombre del conjunto de parámetros. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/fr/CimCmdletStrings.fr.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/fr/CimCmdletStrings.fr.resx new file mode 100644 index 00000000000..9021d746b99 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/fr/CimCmdletStrings.fr.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 + + + L’opération « {0} » est effectuée. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Créer une CimInstance + + + Supprimer une CimInstance + + + Énumérer les CimInstances associées + + + Énumérer les CimClasses + + + Énumérer les CimInstances + + + Obtenir CimClass + + + Obtenir CimInstance + + + Appeler CimMethod + + + Modify CimInstance + + + Interroger les CimInstances + + + S’abonner à une CimIndication + + + Exécutez l’opération « {0} » avec les paramètres suivants : « {1} ». + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Le paramètre « {0} » ne peut pas être utilisé avec le paramètre « {1} ». + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Nous ne pouvons pas trouver CimSession avec le {0} = {1} donné + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Nous n’avons pas pu trouver les propriétés suivantes dans la classe donnée {0} : {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Nous n’avons pas pu modifier la propriété en lecture seule « {0} » de l’objet « {1} ». + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Description de l’état par défaut. + N/A + + + Nous ne pouvons pas effectuer l’opération, car le chemin d’accès contenant des caractères génériques {0} n’a pas été résolu en un fichier. + {0} is a placeholder for a path + + + Le type d’authentification « {0} » n’est pas valide sans informations d’identification. Seuls les types d’authentification suivants sont autorisés sans informations d’identification : « {1} », « {2} », « {3} » ou « {4} ». + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Nous ne pouvons pas trouver la méthode « {0} » dans la classe « {1} ». + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Nous ne pouvons pas trouver le paramètre « {0} » dans la méthode « {1} » de la classe « {2} ». + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Opération non valide. Une opération a déjà été créée pour la cmdlet actuelle. + N/A + + + L’argument « {0} » contient des caractères qui ne sont pas autorisés dans le paramètre « {1} ». Indiquez un argument valide, puis réexécutez la commande. + {0} stand for argument value, {1} stand for parameter name. + + + Nous ne pouvons pas effectuer l’opération, car le chemin d’accès a été résolu en plusieurs fichiers. Cette commande ne peut pas s’exécuter sur plusieurs fichiers. + + + L’argument « {0} » ne peut pas avoir une valeur nulle. + N/A + + + Un objet proxy CimSession a déjà une opération en cours. + N/A + + + Nous ne pouvons ouvrir aucun fichier, car le fournisseur actuel ({0}) ne peut pas les ouvrir. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Nous ne pouvons pas ajouter la propriété « {0} » à l’objet d’entrée « {1} ». Le schéma de classe ne contient pas la propriété. + {0} stand for property name, {1} stand for cim instance path. + + + Nous ne pouvons pas résoudre le nom du jeu de paramètres. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/it/CimCmdletStrings.it.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/it/CimCmdletStrings.it.resx new file mode 100644 index 00000000000..68dd86419d8 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/it/CimCmdletStrings.it.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 + + + Operazione ''{0}'' completata. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Crea CimInstance + + + Eliminare CimInstance + + + Enumerare CimInstance associate + + + Enumerare CimClasses + + + Enumera CimInstances + + + Ottenere CimClass + + + Ottenere CimInstance + + + Richiama CimMethod + + + Modifica CimInstance + + + Chiedi a CimInstances + + + Sottoscrivi CimIndication + + + Eseguire l'operazione ''{0}'' con i parametri seguenti, ''{1}''. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Non è possibile utilizzare il parametro ''{0}'' con il parametro ''{1}''. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Non è possibile trovare CimSession con il {0} specificato = {1} + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Non è possibile trovare le proprietà seguenti nella classe specificata {0}: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Non è possibile modificare la proprietà di sola lettura ''{0}'' dell'oggetto ''{1}''. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Descrizione dello stato predefinito. + N/A + + + Non è possibile eseguire l'operazione perché il percorso con caratteri jolly {0} non si è risolto in un file. + {0} is a placeholder for a path + + + Il tipo di autenticazione ''{0}'' non è valido senza credenziali. Sono consentiti solo i tipi di autenticazione seguenti senza credenziali, ''{1}'', ''{2}'', ''{3}'' o ''{4}''. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Non è possibile trovare il metodo ''{0}'' nella classe ''{1}''. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Non è possibile trovare il parametro ''{0}'' nel metodo ''{1}'' della classe ''{2}''. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Operazione non valida. Per il cmdlet corrente è già stata creata un'operazione. + N/A + + + L'argomento ''{0}'' contiene caratteri non consentiti nel parametro ''{1}''. Specificare un argomento valido, quindi riprovare. + {0} stand for argument value, {1} stand for parameter name. + + + Non è possibile eseguire l'operazione perché il percorso è stato risolto in più di un file. Questo comando non può operare su più file. + + + L'argomento ''{0}'' non può essere Null. + N/A + + + L'oggetto proxy CimSession ha già un'operazione in corso. + N/A + + + Non è possibile aprire il file perché il provider corrente ({0}) non riesce ad aprire un file. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Non è possibile aggiungere la proprietà ''{0}'' all'oggetto di input ''{1}''. Lo schema della classe non contiene la proprietà. + {0} stand for property name, {1} stand for cim instance path. + + + Non è possibile risolvere il nome del set di parametri. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ja/CimCmdletStrings.ja.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ja/CimCmdletStrings.ja.resx new file mode 100644 index 00000000000..dd4d67f9285 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ja/CimCmdletStrings.ja.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 + + + 操作 '{0}' が完了しました。 + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + CimInstance の作成 + + + CimInstance の削除 + + + 関連付けられた CimInstance の列挙 + + + CimClasses の列挙 + + + CimInstance の列挙 + + + CimClass の取得 + + + CimInstance の取得 + + + CimMethod の呼び出し + + + CimInstance の変更 + + + CimInstance に対してクエリを実行 + + + CimIndication のサブスクライブ + + + 次のパラメーターを使用して操作 '{0}' を実行します: '{1}'。 + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + パラメーター '{0}' は、パラメーター '{1}' と共に使用することはできません。 + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + 指定された {0} = {1} の CimSession が見つかりませんでした + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + 指定されたクラス {0} に次のプロパティが見つかりませんでした: {1}。 + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + オブジェクト '{1}' の読み取り専用プロパティ '{0}' を変更できませんでした。 + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + 既定の状態の説明。 + N/A + + + ワイルドカード パス {0} がファイルに解決されなかったため、操作を実行できません。 + {0} is a placeholder for a path + + + 認証の種類 '{0}' は、資格情報がないと無効です。資格情報なしで使用できるのは次の認証の種類のみです: '{1}'、'{2}'、'{3}'、または '{4}'。 + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + クラス '{1}' にメソッド '{0}' が見つかりません。 + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + クラス '{2}' のメソッド '{1}' にパラメーター '{0}' が見つかりません。 + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + 無効な操作です。現在のコマンドレットには、既に操作が作成されています。 + N/A + + + 引数 '{0}' には、パラメーター '{1}' で使用できない文字が含まれています。有効な引数を指定して、コマンドを再試行してください。 + {0} stand for argument value, {1} stand for parameter name. + + + パスが複数のファイルに解決されたため、操作を実行できません。このコマンドは、複数のファイルに対して操作することはできません。 + + + 引数 '{0}' を null 値にすることはできません。 + N/A + + + CimSession プロキシ オブジェクトでは、既に操作が処理中です。 + N/A + + + 現在のプロバイダー ({0}) がファイルを開くことができないため、ファイルを開けません。 + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + プロパティ '{0}' を入力オブジェクト '{1}' に追加できません。クラス スキーマにプロパティが含まれていません。 + {0} stand for property name, {1} stand for cim instance path. + + + パラメーター セット名を解決できません。 + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ko/CimCmdletStrings.ko.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ko/CimCmdletStrings.ko.resx new file mode 100644 index 00000000000..5e7dd502a91 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ko/CimCmdletStrings.ko.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 + + + 작업 '{0}'이(가) 완료되었습니다. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + CimInstance 만들기 + + + CimInstance 삭제 + + + 연결된 CimInstances 열거 + + + CimClasses 열거 + + + CimInstance 열거 + + + CimClass 가져오기 + + + CimInstance 가져오기 + + + CimMethod 호출 + + + Modify CimInstance + + + CimInstance 쿼리 + + + CimIndication 구독 + + + 다음 매개 변수를 사용하여 작업 '{0}'을(를) 수행합니다. '{1}'. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + 매개 변수 '{0}'은(는) 매개 변수 '{1}'과(와) 함께 사용할 수 없습니다. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + 지정된 {0} = {1} 값의 CimSession을 찾을 수 없습니다. + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + 지정된 클래스 {0}에서 다음 속성을 찾을 수 없습니다. {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + 개체 '{1}'의 읽기 전용 속성 '{0}'을(를) 수정할 수 없습니다. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + 기본 상태 설명입니다. + N/A + + + 와일드카드 경로 {0}이(가) 파일로 확인되지 않아 작업을 수행할 수 없습니다. + {0} is a placeholder for a path + + + 자격 증명이 없으면 '{0}' 인증 유형을 사용할 수 없습니다. 자격 증명 없이 사용할 수 있는 인증 유형은 '{1}', '{2}', '{3}' 또는 '{4}'뿐입니다. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + '{1}' 클래스에서 메서드 '{0}'을(를) 찾을 수 없습니다. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + 클래스 '{2}'의 메서드 '{1}'에서 매개 변수 '{0}'을(를) 찾을 수 없습니다. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + 작업이 잘못되었습니다. 현재 cmdlet에 이미 작업이 만들어져 있습니다. + N/A + + + 인수 '{0}'에 매개 변수 '{1}'에 허용되지 않는 문자가 포함되어 있습니다. 올바른 인수를 제공한 후 명령을 다시 시도하세요. + {0} stand for argument value, {1} stand for parameter name. + + + 경로가 두 개 이상의 파일로 확인되어 작업을 수행할 수 없습니다. 이 명령은 여러 파일에 사용할 수 없습니다. + + + '{0}' 인수는 null일 수 없습니다. + N/A + + + CimSession 프록시 개체에 이미 진행 중인 작업이 있습니다. + N/A + + + 현재 공급자({0})는 파일을 열 수 없으므로 파일을 열 수 없습니다. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + 입력 개체 '{1}'에 속성 '{0}'을(를) 추가할 수 없습니다. 클래스 스키마에 해당 속성이 없습니다. + {0} stand for property name, {1} stand for cim instance path. + + + 매개 변수 집합 이름을 확인할 수 없습니다. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/pl/CimCmdletStrings.pl.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/pl/CimCmdletStrings.pl.resx new file mode 100644 index 00000000000..5dfaca26616 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/pl/CimCmdletStrings.pl.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 + + + Operacja „{0}” została ukończona. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Utwórz wystąpienie CimInstances + + + Usuń CimInstance + + + Wyliczanie skojarzonych elementów CimInstances + + + Wylicz klasy typu CimClasses + + + Wyliczanie elementów CimInstance + + + Pobierz CimClass + + + Pobierz CimInstance + + + Wywołaj metodę CimMethod + + + Modyfikacja obiektu CimInstance + + + Zapytanie do tabeli CimInstances + + + Subskrybuj element CimIndication + + + Wykonaj operację „{0}” z następującymi parametrami: „{1}”. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Parametru „{0}” nie można użyć z parametrem „{1}”. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Nie można odnaleźć elementu CimSession o podanym parametrze {0} = {1} + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Nie można odnaleźć następujących właściwości z danej klasy {0}: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Nie można zmodyfikować właściwości tylko do odczytu „{0}” obiektu „{1}”. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Opis domyślnego statusu. + N/A + + + Nie można wykonać operacji, ponieważ ścieżka {0} symbolu wieloznacznego nie została rozpoznana jako plik. + {0} is a placeholder for a path + + + Typ uwierzytelniania „{0}” jest nieprawidłowy bez poświadczeń. Tylko następujący typ uwierzytelniania jest dozwolony bez poświadczeń, „{1}”, „{2}”, „{3}” lub „{4}”. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Nie można odnaleźć metody „{0}” w klasie „{1}”. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Nie można odnaleźć parametru „{0}” w metodzie „{1}” klasy „{2}”. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Nieprawidłowa operacja. Bieżące polecenie cmdlet ma już utworzoną operację. + N/A + + + Argument „{0}” zawiera znaki niedozwolone w parametrze „{1}”. Podaj prawidłowy argument, a następnie spróbuj ponownie wykonać polecenie. + {0} stand for argument value, {1} stand for parameter name. + + + Nie można wykonać operacji, ponieważ ścieżka wskazuje na więcej niż jeden plik. To polecenie nie może działać na wielu plikach. + + + Argument „{0}” nie może być null. + N/A + + + W obiekcie proxy CimSession już trwa operacja. + N/A + + + Nie można otworzyć pliku, ponieważ bieżący dostawca ({0}) nie może otworzyć pliku. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Nie można dodać właściwości „{0}” do obiektu wejściowego „{1}”. Schemat klasy nie zawiera właściwości. + {0} stand for property name, {1} stand for cim instance path. + + + Nie można rozpoznać nazwy zestawu parametrów. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/pt-BR/CimCmdletStrings.pt-BR.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/pt-BR/CimCmdletStrings.pt-BR.resx new file mode 100644 index 00000000000..e0f73fc33ed --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/pt-BR/CimCmdletStrings.pt-BR.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ru/CimCmdletStrings.ru.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ru/CimCmdletStrings.ru.resx new file mode 100644 index 00000000000..71f388880e6 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/ru/CimCmdletStrings.ru.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 + + + Операция "{0}" завершена. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + Создать CimInstance + + + Удалить CimInstance + + + Перечислить связанные CimInstances + + + Перечислить CimClasses + + + Перечислить CimInstances + + + Get CimClass + + + Get CimInstance + + + Вызвать CimMethod + + + Изменить CimInstance + + + Запрос CimInstances + + + Подписаться на CimIndication + + + Выполните операцию "{0}" со следующими параметрами: "{1}". + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + Параметр "{0}" нельзя использовать с параметром "{1}". + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Не удалось найти CimSession с заданным условием {0} = {1} + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Не удалось найти следующие свойства в указанном классе {0}: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + Не удалось изменить доступное только для чтения свойство "{0}" объекта "{1}". + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Описание статуса по умолчанию. + N/A + + + Не удается выполнить операцию, так как путь с подстановочными знаками {0} не сопоставлен с файлом. + {0} is a placeholder for a path + + + Тип проверки подлинности "{0}" недействителен без учетных данных. Без указания учетных данных допускаются только следующие типы проверки подлинности: "{1}", "{2}", "{3}" или "{4}". + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + Не удается найти метод "{0}" в классе "{1}". + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + Не удается найти параметр "{0}" в методе "{1}" класса "{2}". + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Недействительная операция. Для текущего командлета уже создана операция. + N/A + + + Аргумент "{0}" содержит символы, недопустимые в параметре "{1}". Укажите допустимый аргумент, а затем повторите выполнение команды. + {0} stand for argument value, {1} stand for parameter name. + + + Операция не может быть выполнена, так как путь указывает более чем на один файл. Эта команда не может выполняться с несколькими файлами. + + + Аргумент "{0}" не может иметь значение "null". + N/A + + + Для объекта-прокси CimSession уже выполняется операция. + N/A + + + Не удалось открыть файл, поскольку текущий поставщик ({0}) не может открывать файлы. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Не удается добавить свойство "{0}" во входной объект "{1}". Схема класса не содержит это свойство. + {0} stand for property name, {1} stand for cim instance path. + + + Не удалось сопоставить имя набора параметров. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/tr/CimCmdletStrings.tr.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/tr/CimCmdletStrings.tr.resx new file mode 100644 index 00000000000..2b055be79dd --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/tr/CimCmdletStrings.tr.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 + + + İşlem '{0}' tamamlandı. + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + CimInstance Oluştur + + + CimInstance'ı Sil + + + İlişkili CimInstance'ları Numaralandır + + + CimClass'ları Numaralandır + + + CimInstance'ları Numaralandır + + + CimClass'ı Al + + + CimInstance'ı Al + + + CimMethod Çağır + + + CimInstance'ı Değiştir + + + CimInstance'ları Sorgula + + + CimIndication'a Abone Ol + + + '{0}' işlemini aşağıdaki parametrelerle gerçekleştirin: '{1}'. + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + '{0}' parametresi, '{1}' parametresiyle kullanılamaz. + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + Verilen {0} = {1} için CimSession bulunamadı + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + Verilen {0} sınıfında aşağıdaki özellikler bulunamadı: {1}. + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + '{1}' nesnesinin salt okunur özelliği '{0}' değiştirilemedi. + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + Varsayılan durum açıklaması. + N/A + + + Joker karakter yolu {0} bir dosyaya çözümlenemediği için işlem gerçekleştirilemiyor. + {0} is a placeholder for a path + + + Kimlik bilgisi olmadan '{0}' kimlik doğrulama türü geçersizdir. Kimlik bilgisi olmadan yalnızca '{1}', '{2}', '{3}' veya '{4}' kimlik doğrulama türlerine izin verilir. + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + '{1}' sınıfında '{0}' yöntemi bulunamadı. + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + '{2}' sınıfının '{1}' yönteminde '{0}' parametresi bulunamadı. + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + Geçersiz işlem. Geçerli cmdlet için zaten bir işlem oluşturulmuş. + N/A + + + '{0}' bağımsız değişkeni, '{1}' parametresinde izin verilmeyen karakterler içeriyor. Geçerli bir bağımsız değişken girin ve sonra komutu yeniden deneyin. + {0} stand for argument value, {1} stand for parameter name. + + + Yol birden fazla dosyaya çözümlendiği için işlem gerçekleştirilemiyor. Bu komut birden fazla dosya üzerinde çalışamaz. + + + Bağımsız değişken '{0}' null olamaz. + N/A + + + CimSession ara sunucu nesnesinde zaten devam eden bir işlem var. + N/A + + + Geçerli sağlayıcı ({0}) bir dosya açamadığı için dosya açılamıyor. + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + Giriş nesnesi '{1}' için '{0}' özelliği eklenemedi. Sınıf şeması özelliği içermiyor. + {0} stand for property name, {1} stand for cim instance path. + + + Parametre kümesi adı çözümlenemedi. + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/zh-Hans/CimCmdletStrings.zh-Hans.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/zh-Hans/CimCmdletStrings.zh-Hans.resx new file mode 100644 index 00000000000..4173f291648 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/zh-Hans/CimCmdletStrings.zh-Hans.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 + + + 操作 '{0}' 完成。 + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + 创建 CimInstance + + + 删除 CimInstance + + + 枚举关联的 CimInstances + + + 枚举 CimClass + + + 枚举 CimInstance + + + 获取 CimClass + + + 获取 CimInstance + + + 调用 CimMethod + + + 修改 CimInstance + + + 查询 CimInstance + + + 订阅 CimIndication + + + 使用以下参数执行操作 '{0}','{1}'。 + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + 参数“{0}”不能与参数“{1}”一起使用。 + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + 找不到具有给定 {0} = {1}的 CimSession + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + 无法从给定类 {0}中找到以下属性: {1}。 + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + 无法修改对象 '{0}' 的只读属性 '{1}'。 + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + 默认状态说明。 + N/A + + + 无法执行操作,因为通配符路径 {0} 未解析为文件。 + {0} is a placeholder for a path + + + 如果没有凭据,身份验证类型 '{0}' 无效。没有凭据时,仅允许以下身份验证类型:'{1}'、'{2}'、'{3}' 或 '{4}'。 + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + 无法在类“{0}”中找到方法“{1}”。 + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + 在类 '{0}' 的方法 '{1}' 中找不到参数 '{2}'。 + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + 无效的操作。当前 cmdlet 已有正在创建的操作。 + N/A + + + 参数 '{0}' 包含参数 '{1}' 中不允许的字符。提供有效的参数,然后重试该命令。 + {0} stand for argument value, {1} stand for parameter name. + + + 无法执行操作,因为路径解析为多个文件。此命令无法对多个文件执行操作。 + + + 参数 “{0}” 不能为 null。 + N/A + + + CimSession 代理对象已在执行操作。 + N/A + + + 无法打开文件,因为当前提供程序({0})无法打开文件。 + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + 无法将属性 '{0}' 添加到输入对象 '{1}'。类架构不包含该属性。 + {0} stand for property name, {1} stand for cim instance path. + + + 无法解析参数集名称。 + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/zh-Hant/CimCmdletStrings.zh-Hant.resx b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/zh-Hant/CimCmdletStrings.zh-Hant.resx new file mode 100644 index 00000000000..b64c67afe21 --- /dev/null +++ b/src/Microsoft.Management.Infrastructure.CimCmdlets/resources/zh-Hant/CimCmdletStrings.zh-Hant.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 + + + 已完成作業 '{0}'。 + {0} is a placeholder for operation name. (i.e, GetCimInstance) + + + 建立 CimInstance + + + 刪除 CimInstance + + + 列舉關聯的 CimInstances + + + 列舉 CimClasses + + + 列舉 CimInstances + + + 取得 CimClass + + + 取得 CimInstance + + + 叫用 CimMethod + + + 修改 CimInstance + + + 查詢 CimInstances + + + 訂閱 CimIndication + + + 使用下列參數執行作業 '{0}': '{1}'。 + {0} is a placeholder for operation name; {1} is a placeholder for parameters value + + + 參數 '{0}' 不可搭配參數 '{1}' 使用。 + {0} is a placeholder for parameter name; {1} is a placeholder for another parameter name; + + + 找不到具有指定 {0} = {1} 的 CimSession + {0} is a placeholder for property name; {1} is a placeholder for property value. + + + 在指定的類別 {0} 中找不到下列屬性: {1}。 + {0} is a placeholder for class name; {1} is a placeholder for list of property names. + + + 無法修改物件 '{1}' 的唯讀屬性 '{0}'。 + {0} is a placeholder for propertyname; {1} is a placeholder for object string. + + + 預設狀態描述。 + N/A + + + 因為萬用字元路徑 {0} 未解析為檔案,所以無法執行作業。 + {0} is a placeholder for a path + + + 沒有認證時,驗證類型 '{0}' 無效。僅以下驗證類型允許在沒有認證的情況下使用: '{1}'、'{2}'、'{3}' 或 '{4}'。 + {0} is a placeholder for authentication type. {1}-{4} are placeholders for authentication types. + + + 在類別 '{1}' 中找不到方法 '{0}'。 + {0} is a placeholder for method name. {1} is a placeholders for class name. + + + 在類別 '{2}' 的方法 '{1}' 中找不到參數 '{0}'。 + {0} is a placeholder for parameter name; {1} is a placeholder for method name; {2} is a placeholder for class name. + + + 作業無效。目前的 Cmdlet 已建立作業。 + N/A + + + 引數 '{0}' 包含參數 '{1}' 中不允許的字元。請提供有效類型的引數,然後再次嘗試執行命令。 + {0} stand for argument value, {1} stand for parameter name. + + + 因為路徑已解析為多個檔案,所以無法執行作業。此命令無法針對多個檔案執行。 + + + 引數 '{0}' 不可為 null。 + N/A + + + CimSession Proxy 物件已有進行中的作業。 + N/A + + + 因為目前的提供者 ({0}) 無法開啟檔案,所以無法開啟檔案。 + {0} is a placeholder for PowerShell filesystem-like provider name (i.e. registry provider) + + + 無法將屬性 '{0}' 新增至輸入物件 '{1}'。類別結構描述不包含屬性。 + {0} stand for property name, {1} stand for cim instance path. + + + 無法解析參數集名稱。 + N/A + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/.globalconfig b/src/Microsoft.Management.UI.Internal/.globalconfig deleted file mode 100644 index fdb956e8529..00000000000 --- a/src/Microsoft.Management.UI.Internal/.globalconfig +++ /dev/null @@ -1,3 +0,0 @@ -is_global = true - -dotnet_analyzer_diagnostic.severity = none diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs index 1d4bcacd893..fdb81a6d416 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpParagraphBuilder.cs @@ -147,7 +147,7 @@ private static PSPropertyInfo GetProperty(PSObject psObj, string propertyName) /// /// PSObject that contains another PSObject as a property. /// Property name that contains the PSObject. - /// Property name in thye inner 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) { @@ -276,7 +276,7 @@ private static string AddIndent(string str, string indentString) foreach (string line in lines) { // Indentation is not localized - returnValue.AppendFormat("{0}{1}\r\n", indentString, line); + returnValue.Append($"{indentString}{line}\r\n"); } if (returnValue.Length > 2) @@ -369,7 +369,7 @@ private void AddSyntax(bool setting, string sectionTitle) continue; } - string commandStart = string.Format(CultureInfo.CurrentCulture, "{0} ", commandName); + string commandStart = string.Create(CultureInfo.CurrentCulture, $"{commandName} "); this.AddText(HelpParagraphBuilder.AddIndent(commandStart), false); foreach (object parameterObj in parameterObjs) @@ -389,7 +389,7 @@ private void AddSyntax(bool setting, string sectionTitle) continue; } - string parameterType = parameterValue == null ? string.Empty : string.Format(CultureInfo.CurrentCulture, "<{0}>", parameterValue); + string parameterType = parameterValue == null ? string.Empty : string.Create(CultureInfo.CurrentCulture, $"<{parameterValue}>"); string parameterOptionalOpenBrace, parameterOptionalCloseBrace; @@ -607,7 +607,7 @@ private void AddMembers(bool setting, string sectionTitle) description = GetPropertyString(propertyTypeObject, "description"); } - memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}\r\n", propertyType, name); + memberText = string.Create(CultureInfo.CurrentCulture, $" [{propertyType}] {name}\r\n"); } } else if (string.Equals("method", type, StringComparison.OrdinalIgnoreCase)) @@ -690,14 +690,14 @@ private static void FormatMethodData(PSObject member, string name, out string me { parameterType = GetPropertyString(parameterTypeData, "name"); - // If there is no type for the paramter, we expect it is System.Object + // If there is no type for the parameter, we expect it is System.Object if (string.IsNullOrEmpty(parameterType)) { parameterType = "object"; } } - string paramString = string.Format(CultureInfo.CurrentCulture, "[{0}] ${1},", parameterType, parameterName); + string paramString = string.Create(CultureInfo.CurrentCulture, $"[{parameterType}] ${parameterName},"); parameterText.Append(paramString); } @@ -709,7 +709,7 @@ private static void FormatMethodData(PSObject member, string name, out string me } } - memberText = string.Format(CultureInfo.CurrentCulture, " [{0}] {1}({2})\r\n", returnType, name, parameterText); + memberText = string.Create(CultureInfo.CurrentCulture, $" [{returnType}] {name}({parameterText})\r\n"); } /// diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs index 7cbe4b0c74e..7ab8681fef4 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/HelpViewModel.cs @@ -268,7 +268,7 @@ private void SetMatchesLabel() } /// - /// Called internally to notify when a proiperty changed. + /// Called internally to notify when a property changed. /// /// Property name. private void OnNotifyPropertyChanged(string propertyName) diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs index 822e4c05026..77b1b5c966f 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphBuilder.cs @@ -12,8 +12,8 @@ namespace Microsoft.Management.UI.Internal { /// /// Builds a paragraph based on Text + Bold + Highlight information. - /// Bold are the segments of thexct that should be bold, and Highlight are - /// the segments of thext that should be highlighted (like search results). + /// 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 { @@ -43,10 +43,7 @@ internal class ParagraphBuilder : INotifyPropertyChanged /// Paragraph we will be adding lines to in BuildParagraph. internal ParagraphBuilder(Paragraph paragraph) { - if (paragraph == null) - { - throw new ArgumentNullException("paragraph"); - } + ArgumentNullException.ThrowIfNull(paragraph); this.paragraph = paragraph; this.boldSpans = new List(); @@ -80,12 +77,12 @@ internal Paragraph 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 simultaneouslly: + /// 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 highlighed are. + /// characters that should be bold and/or highlighted are. /// internal void BuildParagraph() { @@ -128,7 +125,7 @@ internal void BuildParagraph() } /// - /// Highlights all ocurrences of . + /// Highlights all occurrences of . /// This is called after all calls to AddText have been made. /// /// Search string. @@ -185,10 +182,7 @@ internal void HighlightAllInstancesOf(string search, bool caseSensitive, bool wh /// True if the text should be bold. internal void AddText(string str, bool bold) { - if (str == null) - { - throw new ArgumentNullException("str"); - } + ArgumentNullException.ThrowIfNull(str); if (str.Length == 0) { @@ -240,16 +234,16 @@ private static void AddInline(Paragraph currentParagraph, bool currentBold, bool } /// - /// This is an auxiliar method in BuildParagraph to move the current bold or highlighed spans + /// This is an auxiliar method in BuildParagraph to move the current bold or highlighted spans /// according to the - /// The current bold and higlighed span should be ending ahead of the current position. + /// The current bold and highlighted span should be ending ahead of the current position. /// Moves and to the - /// propper span in according to the + /// proper span in according to the /// This is an auxiliar method in BuildParagraph. /// /// Current index within . /// Current span within . - /// Caracter position. This comes from a position within this.textBuilder. + /// 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) { @@ -270,7 +264,7 @@ private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? c } // there is no span ending ahead of current position, so - // we set the current span to null to prevent unecessary comparisons against the currentSpan + // we set the current span to null to prevent unnecessary comparisons against the currentSpan currentSpan = null; } @@ -282,21 +276,14 @@ private static void MoveSpanToPosition(ref int currentSpanIndex, ref TextSpan? c /// Highlight length. private void AddHighlight(int start, int length) { - if (start < 0) - { - throw new ArgumentOutOfRangeException("start"); - } - - if (start + length > this.textBuilder.Length) - { - throw new ArgumentOutOfRangeException("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 proiperty changed. + /// Called internally to notify when a property changed. /// /// Property name. private void OnNotifyPropertyChanged(string propertyName) @@ -309,7 +296,7 @@ private void OnNotifyPropertyChanged(string propertyName) } /// - /// A text span used to mark bold and highlighed segments. + /// A text span used to mark bold and highlighted segments. /// internal struct TextSpan { @@ -330,15 +317,8 @@ internal struct TextSpan /// Index of the last character in the span. internal TextSpan(int start, int length) { - if (start < 0) - { - throw new ArgumentOutOfRangeException("start"); - } - - if (length < 1) - { - throw new ArgumentOutOfRangeException("length"); - } + ArgumentOutOfRangeException.ThrowIfNegative(start); + ArgumentOutOfRangeException.ThrowIfLessThan(length, 1); this.start = start; this.end = start + length - 1; diff --git a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs index e71a27bac8b..c8b9907751d 100644 --- a/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs +++ b/src/Microsoft.Management.UI.Internal/HelpWindow/ParagraphSearcher.cs @@ -43,8 +43,8 @@ internal ParagraphSearcher() /// The next highlight starting at the . internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPosition) { - Debug.Assert(caretPosition != null, "a caret position is allways valid"); - Debug.Assert(caretPosition.Parent != null && caretPosition.Parent is Run, "a caret PArent is allways a valid Run"); + 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; @@ -56,10 +56,10 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi } // 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 begining of the file + // 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 allways set the caret to the end of the highlight + // 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 @@ -78,7 +78,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi if (currentRun == null) { - // if we could not find a next highlight wrap arround + // if we could not find a next highlight wraparound currentRun = ParagraphSearcher.GetFirstOrLastRun(caretRun, forward); currentRun = ParagraphSearcher.GetNextMatch(currentRun, forward); } @@ -86,7 +86,7 @@ internal Run MoveAndHighlightNextNextMatch(bool forward, TextPointer caretPositi this.currentHighlightedMatch = currentRun; if (this.currentHighlightedMatch != null) { - // restore the curent highligthed background to current highlighted + // restore the curent highlighted background to current highlighted this.currentHighlightedMatch.Background = ParagraphSearcher.CurrentHighlightBrush; } @@ -202,10 +202,10 @@ private static Paragraph GetParagraph(Run run) } /// - /// Returns true if the run is the fiorst run of the paragraph. + /// Returns true if the run is the first run of the paragraph. /// /// Run to check. - /// True if the run is the fiorst run of the paragraph. + /// True if the run is the first run of the paragraph. private static bool IsFirstRun(Run run) { Paragraph paragraph = GetParagraph(run); @@ -221,7 +221,7 @@ private static bool IsFirstRun(Run run) /// 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 allways valid"); + Debug.Assert(caretRun != null, "a caret run is always valid"); Paragraph paragraph = GetParagraph(caretRun); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs index cf65462c3b4..f75555b1da4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DataRoutedEventArgs.cs @@ -11,7 +11,7 @@ namespace Microsoft.Management.UI.Internal { /// /// Routed event args which provide the ability to attach an - /// arbitrary peice of data. + /// arbitrary piece of data. /// /// There are no restrictions on type T. [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs index 76e3206f1f5..3a2768b17b0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/DismissiblePopup.Generated.cs @@ -11,7 +11,7 @@ namespace Microsoft.Management.UI.Internal { /// - /// A popup which child controls can signal to be dimissed. + /// 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. diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs index dff537f00bb..27c45ef288b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IntegralConverter.cs @@ -31,10 +31,7 @@ public class IntegralConverter : IMultiValueConverter /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs index 55b57d76a3f..efefb08bae9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/InverseBooleanConverter.cs @@ -22,10 +22,7 @@ public class InverseBooleanConverter : IValueConverter /// The inverted boolean value. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); var boolValue = (bool)value; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs index 83cd762198f..dbd806a64d6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/IsEqualConverter.cs @@ -31,10 +31,7 @@ public class IsEqualConverter : IMultiValueConverter /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs index 90684f3f6cc..386b33996c1 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/KeyboardHelp.cs @@ -106,10 +106,10 @@ public static FocusNavigationDirection GetNavigationDirection(DependencyObject e /// /// Determines if the control key is pressed. /// - /// True if a control is is pressed. + /// True if a control is pressed. public static bool IsControlPressed() { - if (ModifierKeys.Control == (Keyboard.Modifiers & ModifierKeys.Control)) + if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control) { return true; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs index 469ed5aec77..24ff69bc35b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ListOrganizerItem.cs @@ -153,7 +153,7 @@ private void RevertTextAndChangeFromEditToDisplayMode() private void ChangeFromEditToDisplayMode() { // NOTE : This is to resolve a race condition where clicking - // on the rename button causes the the edit box to change and + // on the rename button causes the edit box to change and // then have re-toggle. DependencyObject d = Mouse.DirectlyOver as DependencyObject; if (d == null || !(this.renameButton.IsAncestorOf(d) && Mouse.LeftButton == MouseButtonState.Pressed)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs index 7734bc4903c..99f08931aa4 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ReadOnlyObservableAsyncCollection.cs @@ -44,7 +44,7 @@ public ReadOnlyObservableAsyncCollection(IList list) /// Occurs when the collection changes, either by adding or removing an item. /// /// - /// see + /// see /// public event NotifyCollectionChangedEventHandler CollectionChanged; @@ -52,7 +52,7 @@ public ReadOnlyObservableAsyncCollection(IList list) /// Occurs when a property changes. /// /// - /// see + /// see /// public event PropertyChangedEventHandler PropertyChanged; #endregion Events diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs index b994bb1a29a..ea5f91adc87 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/ScalableImage.cs @@ -75,7 +75,7 @@ protected override void OnRender(DrawingContext drawingContext) } /// - /// Override of . + /// Override of . /// Make this control to respect the ClipToBounds attribute value. /// /// An instance of used for calculating an additional clip. diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs index be8cc841757..b1a82c0d079 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StateDescriptor.cs @@ -12,7 +12,6 @@ namespace Microsoft.Management.UI.Internal /// Base proxy class for other classes which wish to have save and restore functionality. /// /// There are no restrictions on T. - [Serializable] [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class StateDescriptor { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs index a2e2b144ad6..d8cf0b253aa 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/StringFormatConverter.cs @@ -23,10 +23,7 @@ public class StringFormatConverter : IValueConverter /// The formatted string. public object Convert(object value, Type targetType, Object parameter, CultureInfo culture) { - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); string str = (string)value; string formatString = (string)parameter; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs index c6bcfcb1737..9cc60c8411c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/Utilities.cs @@ -83,10 +83,7 @@ public static class Utilities /// The specified value is a null reference. public static bool AreAllItemsOfType(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); foreach (object item in items) { @@ -108,10 +105,7 @@ public static bool AreAllItemsOfType(IEnumerable items) /// The specified value is a null reference. public static T Find(this IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); foreach (object item in items) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs index 85a7d00a61f..868e9a9b25b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/VisualToAncestorDataConverter.cs @@ -27,15 +27,9 @@ public class VisualToAncestorDataConverter : IValueConverter /// The specified value is a null reference. public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); Type dataType = (Type)parameter; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs index cc18509092f..d005dd909ee 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WeakEventListener.cs @@ -20,10 +20,7 @@ internal class WeakEventListener : IWeakEventListener where TEventAr /// The handler for the event. public WeakEventListener(EventHandler handler) { - if (handler == null) - { - throw new ArgumentNullException("handler"); - } + ArgumentNullException.ThrowIfNull(handler); this.realHander = handler; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs index 23ff80d9974..628723b089a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/Common/WpfHelp.cs @@ -153,10 +153,7 @@ public bool IsEmpty /// The specified value does not have a parent that supports removal. public static void RemoveFromParent(FrameworkElement element) { - if (element == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(element); // If the element has already been detached, do nothing \\ if (element.Parent == null) @@ -215,15 +212,9 @@ public static void RemoveFromParent(FrameworkElement element) /// The specified value does not have a parent that supports removal. public static void AddChild(FrameworkElement parent, FrameworkElement element) { - if (element == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(element); - if (parent == null) - { - throw new ArgumentNullException("element"); - } + ArgumentNullException.ThrowIfNull(parent, nameof(element)); ContentControl parentContentControl = parent as ContentControl; @@ -310,10 +301,8 @@ public static List FindVisualChildren(DependencyObject obj) where T : DependencyObject { Debug.Assert(obj != null, "obj is null"); - if (obj == null) - { - throw new ArgumentNullException("obj"); - } + + ArgumentNullException.ThrowIfNull(obj); List childrenOfType = new List(); @@ -348,10 +337,7 @@ public static List FindVisualChildren(DependencyObject obj) public static T FindVisualAncestorData(this DependencyObject obj) where T : class { - if (obj == null) - { - throw new ArgumentNullException("obj"); - } + ArgumentNullException.ThrowIfNull(obj); FrameworkElement parent = obj.FindVisualAncestor(); @@ -381,10 +367,7 @@ public static T FindVisualAncestorData(this DependencyObject obj) /// The specified value is a null reference. public static T FindVisualAncestor(this DependencyObject @object) where T : class { - if (@object == null) - { - throw new ArgumentNullException("object"); - } + ArgumentNullException.ThrowIfNull(@object, nameof(@object)); DependencyObject parent = VisualTreeHelper.GetParent(@object); @@ -413,10 +396,7 @@ public static T FindVisualAncestor(this DependencyObject @object) where T : c /// The specified value is a null reference. public static bool TryExecute(this RoutedCommand command, object parameter, IInputElement target) { - if (command == null) - { - throw new ArgumentNullException("command"); - } + ArgumentNullException.ThrowIfNull(command); if (command.CanExecute(parameter, target)) { @@ -437,15 +417,8 @@ public static bool TryExecute(this RoutedCommand command, object parameter, IInp /// The reference to the child, or null if the template part wasn't found. public static T GetOptionalTemplateChild(Control templateParent, string childName) where T : FrameworkElement { - if (templateParent == null) - { - throw new ArgumentNullException("templateParent"); - } - - if (string.IsNullOrEmpty(childName)) - { - throw new ArgumentNullException("childName"); - } + ArgumentNullException.ThrowIfNull(templateParent); + ArgumentException.ThrowIfNullOrEmpty(childName); object templatePart = templateParent.Template.FindName(childName, templateParent); T item = templatePart as T; @@ -566,10 +539,7 @@ public static RoutedPropertyChangedEventArgs CreateRoutedPropertyChangedEvent /// The specified index is not valid for the specified collection. public static void ChangeIndex(ItemCollection items, object item, int newIndex) { - if (items == null) - { - throw new ArgumentNullException("items"); - } + ArgumentNullException.ThrowIfNull(items); if (!items.Contains(item)) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs index 4cdf51f63f6..c371a6391b5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/CommonControls/ResizerGripThicknessConverter.cs @@ -38,10 +38,7 @@ public ResizerGripThicknessConverter() /// A converted value. If the method returns nullNothingnullptra null reference (Nothing in Visual Basic), the valid null value is used. public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (object.ReferenceEquals(values[0], DependencyProperty.UnsetValue) || object.ReferenceEquals(values[1], DependencyProperty.UnsetValue)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs index bd5faf32d63..cd5e40a8bd9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/DefaultFilterRuleCustomizationFactory.cs @@ -36,10 +36,7 @@ public override IPropertyValueGetter PropertyValueGetter set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.propertyValueGetter = value; } @@ -106,15 +103,9 @@ public override ICollection CreateDefaultFilterRulesForPropertyValue /// public override void TransferValues(FilterRule oldRule, FilterRule newRule) { - if (oldRule == null) - { - throw new ArgumentNullException("oldRule"); - } + ArgumentNullException.ThrowIfNull(oldRule); - if (newRule == null) - { - throw new ArgumentNullException("newRule"); - } + ArgumentNullException.ThrowIfNull(newRule); if (this.TryTransferValuesAsSingleValueComparableValueFilterRule(oldRule, newRule)) { @@ -130,10 +121,7 @@ public override void TransferValues(FilterRule oldRule, FilterRule newRule) /// public override void ClearValues(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); if (this.TryClearValueFromSingleValueComparableValueFilterRule(rule)) { @@ -163,10 +151,7 @@ public override void ClearValues(FilterRule rule) /// public override string GetErrorMessageForInvalidValue(string value, Type typeToParseTo) { - if (typeToParseTo == null) - { - throw new ArgumentNullException("typeToParseTo"); - } + ArgumentNullException.ThrowIfNull(typeToParseTo); bool isNumericType = typeToParseTo == typeof(byte) || typeToParseTo == typeof(sbyte) @@ -222,10 +207,7 @@ private object GetValueFromValidatingValue(FilterRule rule, string propertyName) Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Type ruleType = rule.GetType(); @@ -241,10 +223,7 @@ private void SetValueOnValidatingValue(FilterRule rule, string propertyName, obj Debug.Assert(rule != null && !string.IsNullOrEmpty(propertyName), "rule and propertyname are not null"); // NOTE: This isn't needed but OACR is complaining - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); Type ruleType = rule.GetType(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs index 2b33153a983..cf885d813c5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterEvaluator.cs @@ -9,7 +9,7 @@ namespace Microsoft.Management.UI.Internal { /// - /// The FilterEvaluator class is responsible for allowing the registeration of + /// The FilterEvaluator class is responsible for allowing the registration of /// the FilterExpressionProviders and producing a FilterExpression composed of /// the FilterExpression returned from the providers. /// @@ -145,10 +145,7 @@ public FilterExpressionNode FilterExpression /// public void AddFilterExpressionProvider(IFilterExpressionProvider provider) { - if (provider == null) - { - throw new ArgumentNullException("provider"); - } + ArgumentNullException.ThrowIfNull(provider); this.filterExpressionProviders.Add(provider); provider.FilterExpressionChanged += this.FilterProvider_FilterExpressionChanged; @@ -162,10 +159,7 @@ public void AddFilterExpressionProvider(IFilterExpressionProvider provider) /// public void RemoveFilterExpressionProvider(IFilterExpressionProvider provider) { - if (provider == null) - { - throw new ArgumentNullException("provider"); - } + ArgumentNullException.ThrowIfNull(provider); this.filterExpressionProviders.Remove(provider); provider.FilterExpressionChanged -= this.FilterProvider_FilterExpressionChanged; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs index b7a26757b21..77460f61fc9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExceptionEventArgs.cs @@ -32,10 +32,7 @@ public Exception Exception /// public FilterExceptionEventArgs(Exception exception) { - if (exception == null) - { - throw new ArgumentNullException("exception"); - } + ArgumentNullException.ThrowIfNull(exception); this.Exception = exception; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs index f255973dce8..0227362bf28 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionAndOperatorNode.cs @@ -52,10 +52,7 @@ public FilterExpressionAndOperatorNode() /// public FilterExpressionAndOperatorNode(IEnumerable children) { - if (children == null) - { - throw new ArgumentNullException("children"); - } + ArgumentNullException.ThrowIfNull(children); this.children.AddRange(children); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs index f6bfd17377b..3161dc30283 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOperandNode.cs @@ -38,10 +38,7 @@ public FilterRule Rule /// public FilterExpressionOperandNode(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.Rule = rule; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs index 201316a433e..ff92e42cf2d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterExpressionNodes/FilterExpressionOrOperatorNode.cs @@ -52,10 +52,7 @@ public FilterExpressionOrOperatorNode() /// public FilterExpressionOrOperatorNode(IEnumerable children) { - if (children == null) - { - throw new ArgumentNullException("children"); - } + ArgumentNullException.ThrowIfNull(children); this.children.AddRange(children); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs index 75019cdbf5d..b61c9933aef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRuleCustomizationFactory.cs @@ -32,10 +32,7 @@ public static FilterRuleCustomizationFactory FactoryInstance set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); factoryInstance = value; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs index e75cd59f17a..8362a035156 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/ComparableValueFilterRule.cs @@ -12,10 +12,26 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class ComparableValueFilterRule : FilterRule where T : IComparable { + /// + /// Initializes a new instance of the class. + /// + protected ComparableValueFilterRule() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + protected ComparableValueFilterRule(ComparableValueFilterRule source) + : base(source) + { + this.DefaultNullValueEvaluation = source.DefaultNullValueEvaluation; + } + #region Properties /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs index ea74ee062f9..c5d4f36fe55 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/DoesNotEqualFilterRule.cs @@ -12,12 +12,11 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class DoesNotEqualFilterRule : EqualsFilterRule where T : IComparable { /// - /// Initializes a new instance of the DoesNotEqualFilterRule class. + /// Initializes a new instance of the class. /// public DoesNotEqualFilterRule() { @@ -25,6 +24,15 @@ public DoesNotEqualFilterRule() this.DefaultNullValueEvaluation = true; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public DoesNotEqualFilterRule(DoesNotEqualFilterRule source) + : base(source) + { + } + /// /// Determines if item is not equal to Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs index 5f21f57292b..34a1ecb722d 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/EqualsFilterRule.cs @@ -13,18 +13,26 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class EqualsFilterRule : SingleValueComparableValueFilterRule where T : IComparable { /// - /// Initializes a new instance of the EqualsFilterRule class. + /// Initializes a new instance of the class. /// public EqualsFilterRule() { this.DisplayName = UICultureResources.FilterRule_Equals; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public EqualsFilterRule(EqualsFilterRule source) + : base(source) + { + } + /// /// Determines if item is equal to Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs index 1c2fc523e86..f18c89addf9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRule.cs @@ -8,9 +8,8 @@ namespace Microsoft.Management.UI.Internal /// /// The base class for all filtering rules. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public abstract class FilterRule : IEvaluate + public abstract class FilterRule : IEvaluate, IDeepCloneable { /// /// Gets a value indicating whether the FilterRule can be @@ -34,15 +33,26 @@ public string DisplayName } /// - /// Initializes a new instance of the FilterRule class. + /// Initializes a new instance of the class. /// protected FilterRule() { - // HACK : Is there a way to statically enforce this? No... not ISerializable... - if (!this.GetType().IsSerializable) - { - throw new InvalidOperationException("FilterRules must be serializable."); - } + } + + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + protected FilterRule(FilterRule source) + { + ArgumentNullException.ThrowIfNull(source); + this.DisplayName = source.DisplayName; + } + + /// + public object DeepClone() + { + return Activator.CreateInstance(this.GetType(), new object[] { this }); } /// @@ -58,7 +68,6 @@ protected FilterRule() /// /// Occurs when the values of this rule changes. /// - [field: NonSerialized] public event EventHandler EvaluationResultInvalidated; /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs index 1ccc3d1d227..4a3f8dc2975 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/FilterRuleExtensions.cs @@ -2,10 +2,6 @@ // Licensed under the MIT License. using System; -using System.Diagnostics; -using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; namespace Microsoft.Management.UI.Internal { @@ -27,34 +23,8 @@ public static class FilterRuleExtensions /// public static FilterRule DeepCopy(this FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } - - Debug.Assert(rule.GetType().IsSerializable, "rule is serializable"); - - BinaryFormatter formatter = new BinaryFormatter(null, new StreamingContext(StreamingContextStates.Clone)); - MemoryStream ms = new MemoryStream(); - - FilterRule copy = null; - try - { -#pragma warning disable SYSLIB0011 - formatter.Serialize(ms, rule); -#pragma warning restore SYSLIB0011 - - ms.Position = 0; -#pragma warning disable SYSLIB0011 - copy = (FilterRule)formatter.Deserialize(ms); -#pragma warning restore SYSLIB0011 - } - finally - { - ms.Close(); - } - - return copy; + ArgumentNullException.ThrowIfNull(rule); + return (FilterRule)rule.DeepClone(); } } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs index b54508157a6..f51093510ec 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsBetweenFilterRule.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsBetweenFilterRule : ComparableValueFilterRule where T : IComparable { @@ -56,7 +55,7 @@ public ValidatingValue EndValue #region Ctor /// - /// Initializes a new instance of the IsBetweenFilterRule class. + /// Initializes a new instance of the class. /// public IsBetweenFilterRule() { @@ -69,6 +68,20 @@ public IsBetweenFilterRule() this.EndValue.PropertyChanged += this.Value_PropertyChanged; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public IsBetweenFilterRule(IsBetweenFilterRule source) + : base(source) + { + this.StartValue = (ValidatingValue)source.StartValue.DeepClone(); + this.StartValue.PropertyChanged += this.Value_PropertyChanged; + + this.EndValue = (ValidatingValue)source.EndValue.DeepClone(); + this.EndValue.PropertyChanged += this.Value_PropertyChanged; + } + #endregion Ctor #region Public Methods @@ -108,13 +121,6 @@ private void Value_PropertyChanged(object sender, PropertyChangedEventArgs e) } } - [OnDeserialized] - private void Initialize(StreamingContext context) - { - this.StartValue.PropertyChanged += this.Value_PropertyChanged; - this.EndValue.PropertyChanged += this.Value_PropertyChanged; - } - #endregion Value Change Handlers } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs index 8e8b91087ef..71bb7e23e7c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsEmptyFilterRule.cs @@ -9,18 +9,26 @@ namespace Microsoft.Management.UI.Internal /// The IsEmptyFilterRule evaluates an item to determine whether it /// is empty or not. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsEmptyFilterRule : FilterRule { /// - /// Initializes a new instance of the IsEmptyFilterRule class. + /// Initializes a new instance of the class. /// public IsEmptyFilterRule() { this.DisplayName = UICultureResources.FilterRule_IsEmpty; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public IsEmptyFilterRule(IsEmptyFilterRule source) + : base(source) + { + } + /// /// Gets a values indicating whether the supplied item is empty. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs index bd9af169e82..6c7d16f312a 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsGreaterThanFilterRule.cs @@ -13,18 +13,26 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsGreaterThanFilterRule : SingleValueComparableValueFilterRule where T : IComparable { /// - /// Initializes a new instance of the IsGreaterThanFilterRule class. + /// Initializes a new instance of the class. /// public IsGreaterThanFilterRule() { this.DisplayName = UICultureResources.FilterRule_GreaterThanOrEqual; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public IsGreaterThanFilterRule(IsGreaterThanFilterRule source) + : base(source) + { + } + /// /// Determines if item is greater than Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs index db3bc01f810..e1dc3268cc5 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsLessThanFilterRule.cs @@ -13,18 +13,26 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsLessThanFilterRule : SingleValueComparableValueFilterRule where T : IComparable { /// - /// Initializes a new instance of the IsLessThanFilterRule class. + /// Initializes a new instance of the class. /// public IsLessThanFilterRule() { this.DisplayName = UICultureResources.FilterRule_LessThanOrEqual; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public IsLessThanFilterRule(IsLessThanFilterRule source) + : base(source) + { + } + /// /// Determines if item is less than Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs index c9bfc7519a0..711caee9874 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyFilterRule.cs @@ -9,18 +9,26 @@ namespace Microsoft.Management.UI.Internal /// The IsNotEmptyFilterRule evaluates an item to determine whether it /// is empty or not. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsNotEmptyFilterRule : IsEmptyFilterRule { /// - /// Initializes a new instance of the IsNotEmptyFilterRule class. + /// Initializes a new instance of the class. /// public IsNotEmptyFilterRule() { this.DisplayName = UICultureResources.FilterRule_IsNotEmpty; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public IsNotEmptyFilterRule(IsNotEmptyFilterRule source) + : base(source) + { + } + /// /// Gets a values indicating whether the supplied item is not empty. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs index 924ffc02af8..cb6eacaaff3 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/IsNotEmptyValidationRule.cs @@ -8,7 +8,6 @@ namespace Microsoft.Management.UI.Internal /// /// The IsNotEmptyValidationRule checks a value to see if a value is not empty. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class IsNotEmptyValidationRule : DataErrorInfoValidationRule { @@ -51,6 +50,14 @@ public override DataErrorInfoValidationResult Validate(object value, System.Glob } } + /// + public override object DeepClone() + { + // Instance is stateless. + // return this; + return new IsNotEmptyValidationRule(); + } + #endregion Public Methods internal static bool IsStringNotEmpty(string value) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs index c29715419ce..8c32530be8c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertiesTextContainsFilterRule.cs @@ -11,7 +11,6 @@ namespace Microsoft.Management.UI.Internal /// /// Represents a filter rule that searches for text within properties on an object. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class PropertiesTextContainsFilterRule : TextFilterRule { @@ -29,6 +28,17 @@ public PropertiesTextContainsFilterRule() this.EvaluationResultInvalidated += this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public PropertiesTextContainsFilterRule(PropertiesTextContainsFilterRule source) + : base(source) + { + this.PropertyNames = new List(source.PropertyNames); + this.EvaluationResultInvalidated += this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated; + } + /// /// Gets a collection of the names of properties to search in. /// @@ -120,11 +130,5 @@ private void PropertiesTextContainsFilterRule_EvaluationResultInvalidated(object { this.OnEvaluationResultInvalidated(); } - - [OnDeserialized] - private void Initialize(StreamingContext context) - { - this.EvaluationResultInvalidated += this.PropertiesTextContainsFilterRule_EvaluationResultInvalidated; - } } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs index e8927c74826..09c732970b0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/PropertyValueSelectorFilterRule.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class PropertyValueSelectorFilterRule : SelectorFilterRule where T : IComparable { @@ -66,21 +65,6 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl /// public PropertyValueSelectorFilterRule(string propertyName, string propertyDisplayName, IEnumerable rules) { - if (string.IsNullOrEmpty(propertyName)) - { - throw new ArgumentNullException("propertyName"); - } - - if (string.IsNullOrEmpty(propertyDisplayName)) - { - throw new ArgumentNullException("propertyDisplayName"); - } - - if (rules == null) - { - throw new ArgumentNullException("rules"); - } - this.PropertyName = propertyName; this.DisplayName = propertyDisplayName; @@ -97,6 +81,17 @@ public PropertyValueSelectorFilterRule(string propertyName, string propertyDispl this.AvailableRules.DisplayNameConverter = new FilterRuleToDisplayNameConverter(); } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public PropertyValueSelectorFilterRule(PropertyValueSelectorFilterRule source) + : base(source) + { + this.PropertyName = source.PropertyName; + this.AvailableRules.DisplayNameConverter = new FilterRuleToDisplayNameConverter(); + } + #endregion Ctor #region Public Methods diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs index c67b1c993e5..d1627ee2281 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SelectorFilterRule.cs @@ -9,7 +9,6 @@ namespace Microsoft.Management.UI.Internal /// /// The SelectorFilterRule represents a rule composed of other rules. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class SelectorFilterRule : FilterRule { @@ -40,7 +39,7 @@ public ValidatingSelectorValue AvailableRules #region Ctor /// - /// Creates a new SelectorFilterRule instance. + /// Initializes a new instance of the class. /// public SelectorFilterRule() { @@ -48,6 +47,18 @@ public SelectorFilterRule() this.AvailableRules.SelectedValueChanged += this.AvailableRules_SelectedValueChanged; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public SelectorFilterRule(SelectorFilterRule source) + : base(source) + { + this.AvailableRules = (ValidatingSelectorValue)source.AvailableRules.DeepClone(); + this.AvailableRules.SelectedValueChanged += this.AvailableRules_SelectedValueChanged; + this.AvailableRules.SelectedValue.EvaluationResultInvalidated += this.SelectedValue_EvaluationResultInvalidated; + } + #endregion Ctor #region Public Methods @@ -86,8 +97,8 @@ protected void OnSelectedValueChanged(FilterRule oldValue, FilterRule newValue) FilterRuleCustomizationFactory.FactoryInstance.TransferValues(oldValue, newValue); FilterRuleCustomizationFactory.FactoryInstance.ClearValues(oldValue); - newValue.EvaluationResultInvalidated += this.SelectedValue_EvaluationResultInvalidated; oldValue.EvaluationResultInvalidated -= this.SelectedValue_EvaluationResultInvalidated; + newValue.EvaluationResultInvalidated += this.SelectedValue_EvaluationResultInvalidated; this.NotifyEvaluationResultInvalidated(); } @@ -101,13 +112,6 @@ private void SelectedValue_EvaluationResultInvalidated(object sender, EventArgs #region Private Methods - [OnDeserialized] - private void Initialize(StreamingContext context) - { - this.AvailableRules.SelectedValueChanged += this.AvailableRules_SelectedValueChanged; - this.AvailableRules.SelectedValue.EvaluationResultInvalidated += this.SelectedValue_EvaluationResultInvalidated; - } - private void AvailableRules_SelectedValueChanged(object sender, PropertyChangedEventArgs e) { this.OnSelectedValueChanged(e.OldValue, e.NewValue); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs index 5aaabe58bfb..b26531943fc 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/SingleValueComparableValueFilterRule.cs @@ -12,7 +12,6 @@ namespace Microsoft.Management.UI.Internal /// that take a single input and evaluate against IComparable values. /// /// The generic parameter. - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class SingleValueComparableValueFilterRule : ComparableValueFilterRule where T : IComparable { @@ -44,7 +43,7 @@ public override bool IsValid #region Ctor /// - /// Initializes a new instance of the SingleValueComparableValueFilterRule class. + /// Initializes a new instance of the class. /// protected SingleValueComparableValueFilterRule() { @@ -52,6 +51,17 @@ protected SingleValueComparableValueFilterRule() this.Value.PropertyChanged += this.Value_PropertyChanged; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + protected SingleValueComparableValueFilterRule(SingleValueComparableValueFilterRule source) + : base(source) + { + this.Value = (ValidatingValue)source.Value.DeepClone(); + this.Value.PropertyChanged += this.Value_PropertyChanged; + } + #endregion Ctor private void Value_PropertyChanged(object sender, PropertyChangedEventArgs e) @@ -61,11 +71,5 @@ private void Value_PropertyChanged(object sender, PropertyChangedEventArgs e) this.NotifyEvaluationResultInvalidated(); } } - - [OnDeserialized] - private void Initialize(StreamingContext context) - { - this.Value.PropertyChanged += this.Value_PropertyChanged; - } } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs index 9186827c5f5..beb4a29d23f 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextContainsFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextContainsFilterRule class evaluates a string item to /// check if it is contains the rule's value within it. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextContainsFilterRule : TextFilterRule { @@ -18,13 +17,22 @@ public class TextContainsFilterRule : TextFilterRule private static readonly string TextContainsWordsRegexPattern = WordBoundaryRegexPattern + TextContainsCharactersRegexPattern + WordBoundaryRegexPattern; /// - /// Initializes a new instance of the TextContainsFilterRule class. + /// Initializes a new instance of the class. /// public TextContainsFilterRule() { this.DisplayName = UICultureResources.FilterRule_Contains; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public TextContainsFilterRule(TextContainsFilterRule source) + : base(source) + { + } + /// /// Determines if Value is contained within data. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs index dcfeabff4c4..2cdbf1efcef 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotContainFilterRule.cs @@ -9,12 +9,11 @@ namespace Microsoft.Management.UI.Internal /// The TextDoesNotContainFilterRule class evaluates a string item to /// check if it is does not contain the rule's value within it. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextDoesNotContainFilterRule : TextContainsFilterRule { /// - /// Initializes a new instance of the TextDoesNotContainFilterRule class. + /// Initializes a new instance of the class. /// public TextDoesNotContainFilterRule() { @@ -22,6 +21,15 @@ public TextDoesNotContainFilterRule() this.DefaultNullValueEvaluation = true; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public TextDoesNotContainFilterRule(TextDoesNotContainFilterRule source) + : base(source) + { + } + /// /// Determines if Value is not contained within data. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs index 3666b17c2de..e74b371a7a6 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextDoesNotEqualFilterRule.cs @@ -9,12 +9,11 @@ namespace Microsoft.Management.UI.Internal /// The TextDoesNotEqualFilterRule class evaluates a string item to /// check if it is not equal to the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextDoesNotEqualFilterRule : TextEqualsFilterRule { /// - /// Initializes a new instance of the TextDoesNotEqualFilterRule class. + /// Initializes a new instance of the class. /// public TextDoesNotEqualFilterRule() { @@ -22,6 +21,15 @@ public TextDoesNotEqualFilterRule() this.DefaultNullValueEvaluation = true; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public TextDoesNotEqualFilterRule(TextDoesNotEqualFilterRule source) + : base(source) + { + } + /// /// Determines if data is not equal to Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs index 45a9dd85386..d7f7e05c4b8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEndsWithFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextEndsWithFilterRule class evaluates a string item to /// check if it ends with the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextEndsWithFilterRule : TextFilterRule { @@ -18,13 +17,22 @@ public class TextEndsWithFilterRule : TextFilterRule private static readonly string TextEndsWithWordsRegexPattern = WordBoundaryRegexPattern + TextEndsWithCharactersRegexPattern; /// - /// Initializes a new instance of the TextEndsWithFilterRule class. + /// Initializes a new instance of the class. /// public TextEndsWithFilterRule() { this.DisplayName = UICultureResources.FilterRule_TextEndsWith; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public TextEndsWithFilterRule(TextEndsWithFilterRule source) + : base(source) + { + } + /// /// Determines if data ends with Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs index 6401506bf1d..a357575c6ab 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextEqualsFilterRule.cs @@ -10,20 +10,28 @@ namespace Microsoft.Management.UI.Internal /// The TextEqualsFilterRule class evaluates a string item to /// check if it is equal to the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextEqualsFilterRule : TextFilterRule { private static readonly string TextEqualsCharactersRegexPattern = "^{0}$"; /// - /// Initializes a new instance of the TextEqualsFilterRule class. + /// Initializes a new instance of the class. /// public TextEqualsFilterRule() { this.DisplayName = UICultureResources.FilterRule_Equals; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public TextEqualsFilterRule(TextEqualsFilterRule source) + : base(source) + { + } + /// /// Determines if data is equal to Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs index 3440935889f..eacbcb8d256 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextFilterRule.cs @@ -13,7 +13,6 @@ namespace Microsoft.Management.UI.Internal /// The TextFilterRule class supports derived rules by offering services for /// evaluating string operations. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public abstract class TextFilterRule : SingleValueComparableValueFilterRule { @@ -62,7 +61,7 @@ public bool CultureInvariant } /// - /// Initializes a new instance of the TextFilterRule class. + /// Initializes a new instance of the class. /// protected TextFilterRule() { @@ -70,6 +69,17 @@ protected TextFilterRule() this.CultureInvariant = false; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + protected TextFilterRule(TextFilterRule source) + : base(source) + { + this.IgnoreCase = source.IgnoreCase; + this.CultureInvariant = source.CultureInvariant; + } + /// /// Gets the current value and determines whether it should be evaluated as an exact match. /// @@ -101,15 +111,9 @@ protected internal string GetParsedValue(out bool evaluateAsExactMatch) /// The specified value is a null reference. protected internal string GetRegexPattern(string pattern, string exactMatchPattern) { - if (pattern == null) - { - throw new ArgumentNullException("pattern"); - } + ArgumentNullException.ThrowIfNull(pattern); - if (exactMatchPattern == null) - { - throw new ArgumentNullException("exactMatchPattern"); - } + ArgumentNullException.ThrowIfNull(exactMatchPattern); Debug.Assert(this.IsValid, "is valid"); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs index 8cfdc7960d8..98eac2b9a41 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/FilterRules/TextStartsWithFilterRule.cs @@ -10,7 +10,6 @@ namespace Microsoft.Management.UI.Internal /// The TextStartsWithFilterRule class evaluates a string item to /// check if it starts with the rule's value. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class TextStartsWithFilterRule : TextFilterRule { @@ -18,13 +17,22 @@ public class TextStartsWithFilterRule : TextFilterRule private static readonly string TextStartsWithWordsRegexPattern = TextStartsWithCharactersRegexPattern + WordBoundaryRegexPattern; /// - /// Initializes a new instance of the TextStartsWithFilterRule class. + /// Initializes a new instance of the class. /// public TextStartsWithFilterRule() { this.DisplayName = UICultureResources.FilterRule_TextStartsWith; } + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public TextStartsWithFilterRule(TextStartsWithFilterRule source) + : base(source) + { + } + /// /// Determines if data starts with Value. /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IDeepCloneable.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IDeepCloneable.cs new file mode 100644 index 00000000000..841a2424b51 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IDeepCloneable.cs @@ -0,0 +1,17 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace Microsoft.Management.UI.Internal +{ + /// + /// Defines a generalized method for creating a deep copy of an instance. + /// + internal interface IDeepCloneable + { + /// + /// Creates a deep copy of the current instance. + /// + /// A new object that is a deep copy of the current instance. + object DeepClone(); + } +} diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs index f83f6b377aa..161f14d4537 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/IEvaluate.cs @@ -13,7 +13,7 @@ public interface IEvaluate { /// /// Gets a values indicating whether the supplied item has meet the - /// criteria rule specificed by the rule. + /// criteria rule specified by the rule. /// /// /// The item to evaluate. diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs index ed5389668e6..0fed0c42e65 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingSelectorValue.cs @@ -15,10 +15,40 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ValidatingSelectorValue : ValidatingValueBase { + /// + /// Initializes a new instance of the class. + /// + public ValidatingSelectorValue() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public ValidatingSelectorValue(ValidatingSelectorValue source) + : base(source) + { + availableValues.EnsureCapacity(source.availableValues.Count); + if (typeof(IDeepCloneable).IsAssignableFrom(typeof(T))) + { + foreach (var value in source.availableValues) + { + availableValues.Add((T)((IDeepCloneable)value).DeepClone()); + } + } + else + { + availableValues.AddRange(source.availableValues); + } + + selectedIndex = source.selectedIndex; + displayNameConverter = source.displayNameConverter; + } + #region Properties #region Consts @@ -130,11 +160,6 @@ public IValueConverter DisplayNameConverter set { - if (value != null && !value.GetType().IsSerializable) - { - throw new ArgumentException("The DisplayNameConverter must be serializable.", "value"); - } - this.displayNameConverter = value; } } @@ -148,13 +173,18 @@ public IValueConverter DisplayNameConverter /// /// Notifies listeners that the selected value has changed. /// - [field: NonSerialized] public event EventHandler> SelectedValueChanged; #endregion Events #region Public Methods + /// + public override object DeepClone() + { + return new ValidatingSelectorValue(this); + } + #region Validate /// @@ -187,7 +217,7 @@ protected override DataErrorInfoValidationResult Validate(string columnName) { if (!columnName.Equals(SelectedIndexPropertyName, StringComparison.CurrentCulture)) { - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "{0} is not a valid column name.", columnName), "columnName"); + throw new ArgumentException(string.Create(CultureInfo.CurrentCulture, $"{columnName} is not a valid column name."), "columnName"); } if (!this.IsIndexWithinBounds(this.SelectedIndex)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs index cf9c553f6b4..437cb3be50e 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValue.cs @@ -14,10 +14,26 @@ namespace Microsoft.Management.UI.Internal /// /// The generic parameter. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ValidatingValue : ValidatingValueBase { + /// + /// Initializes a new instance of the class. + /// + public ValidatingValue() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + public ValidatingValue(ValidatingValue source) + : base(source) + { + value = source.Value is IDeepCloneable deepClone ? deepClone.DeepClone() : source.Value; + } + #region Properties #region Value @@ -50,6 +66,12 @@ public object Value #region Public Methods + /// + public override object DeepClone() + { + return new ValidatingValue(this); + } + /// /// Gets the raw value cast/transformed into /// type T. @@ -165,10 +187,7 @@ private bool TryGetCastValue(object rawValue, out T castValue) { castValue = default(T); - if (rawValue == null) - { - throw new ArgumentNullException("rawValue"); - } + ArgumentNullException.ThrowIfNull(rawValue); if (typeof(T).IsEnum) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs index f3959685349..a4ffb1af77c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidatingValueBase.cs @@ -14,10 +14,30 @@ namespace Microsoft.Management.UI.Internal /// The ValidatingValueBase class provides basic services for base /// classes to support validation via the IDataErrorInfo interface. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public abstract class ValidatingValueBase : IDataErrorInfo, INotifyPropertyChanged + public abstract class ValidatingValueBase : IDataErrorInfo, INotifyPropertyChanged, IDeepCloneable { + /// + /// Initializes a new instance of the class. + /// + protected ValidatingValueBase() + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The source to initialize from. + protected ValidatingValueBase(ValidatingValueBase source) + { + ArgumentNullException.ThrowIfNull(source); + validationRules.EnsureCapacity(source.validationRules.Count); + foreach (var rule in source.validationRules) + { + validationRules.Add((DataErrorInfoValidationRule)rule.DeepClone()); + } + } + #region Properties #region ValidationRules @@ -26,7 +46,6 @@ public abstract class ValidatingValueBase : IDataErrorInfo, INotifyPropertyChang private ReadOnlyCollection readonlyValidationRules; private bool isValidationRulesCollectionDirty = true; - [field: NonSerialized] private DataErrorInfoValidationResult cachedValidationResult; /// @@ -82,10 +101,7 @@ public string this[string columnName] { get { - if (string.IsNullOrEmpty(columnName)) - { - throw new ArgumentNullException("columnName"); - } + ArgumentException.ThrowIfNullOrEmpty(columnName); this.UpdateValidationResult(columnName); return this.GetValidationResult().ErrorMessage; @@ -123,7 +139,6 @@ public string Error /// /// The listeners attached to this event are not serialized. /// - [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; #endregion PropertyChanged @@ -132,6 +147,9 @@ public string Error #region Public Methods + /// + public abstract object DeepClone(); + #region AddValidationRule /// @@ -140,10 +158,7 @@ public string Error /// The validation rule to add. public void AddValidationRule(DataErrorInfoValidationRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.validationRules.Add(rule); @@ -161,10 +176,7 @@ public void AddValidationRule(DataErrorInfoValidationRule rule) /// The rule to remove. public void RemoveValidationRule(DataErrorInfoValidationRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.validationRules.Remove(rule); @@ -223,7 +235,7 @@ internal DataErrorInfoValidationResult EvaluateValidationRules(object value, Sys DataErrorInfoValidationResult result = rule.Validate(value, cultureInfo); if (result == null) { - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "DataErrorInfoValidationResult not returned by ValidationRule: {0}", rule.ToString())); + throw new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"DataErrorInfoValidationResult not returned by ValidationRule: {rule}")); } if (!result.IsValid) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs index 9b4a2b23d0d..a92916c0717 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterCore/ValidationRules/DataErrorInfoValidationRule.cs @@ -8,9 +8,8 @@ namespace Microsoft.Management.UI.Internal /// /// Provides a way to create a custom rule in order to check the validity of user input. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public abstract class DataErrorInfoValidationRule + public abstract class DataErrorInfoValidationRule : IDeepCloneable { /// /// When overridden in a derived class, performs validation checks on a value. @@ -25,5 +24,8 @@ public abstract class DataErrorInfoValidationRule /// A DataErrorInfoValidationResult object. /// public abstract DataErrorInfoValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo); + + /// + public abstract object DeepClone(); } } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs index bcc9a01a92c..c3bb4042d53 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanel.cs @@ -154,15 +154,9 @@ public FilterRulePanel() /// public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTemplate) { - if (type == null) - { - throw new ArgumentNullException("type"); - } + ArgumentNullException.ThrowIfNull(type); - if (dataTemplate == null) - { - throw new ArgumentNullException("dataTemplate"); - } + ArgumentNullException.ThrowIfNull(dataTemplate); this.filterRuleTemplateSelector.TemplateDictionary.Add(new KeyValuePair(type, dataTemplate)); } @@ -176,10 +170,7 @@ public void AddFilterRulePanelItemContentTemplate(Type type, DataTemplate dataTe /// public void RemoveFilterRulePanelItemContentTemplate(Type type) { - if (type == null) - { - throw new ArgumentNullException("type"); - } + ArgumentNullException.ThrowIfNull(type); this.filterRuleTemplateSelector.TemplateDictionary.Remove(type); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs index dcec5022d98..68c22de5af9 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelController.cs @@ -88,10 +88,7 @@ public FilterRulePanelController() /// public void AddFilterRulePanelItem(FilterRulePanelItem item) { - if (item == null) - { - throw new ArgumentNullException("item"); - } + ArgumentNullException.ThrowIfNull(item); int insertionIndex = this.GetInsertionIndex(item); this.filterRulePanelItems.Insert(insertionIndex, item); @@ -116,10 +113,7 @@ private void Rule_EvaluationResultInvalidated(object sender, EventArgs e) /// public void RemoveFilterRulePanelItem(FilterRulePanelItem item) { - if (item == null) - { - throw new ArgumentNullException("item"); - } + ArgumentNullException.ThrowIfNull(item); item.Rule.EvaluationResultInvalidated -= this.Rule_EvaluationResultInvalidated; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs index a1a873cdbc7..ee6b124562c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItem.cs @@ -25,7 +25,7 @@ public FilterRule Rule } /// - /// Gets a string that indentifies which group this + /// Gets a string that identifies which group this /// item belongs to. /// public string GroupId @@ -79,15 +79,8 @@ protected internal set /// public FilterRulePanelItem(FilterRule rule, string groupId) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } - - if (string.IsNullOrEmpty(groupId)) - { - throw new ArgumentNullException("groupId"); - } + ArgumentNullException.ThrowIfNull(rule); + ArgumentException.ThrowIfNullOrEmpty(groupId); this.Rule = rule; this.GroupId = groupId; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs index fc40c3c5768..0381ef0e63c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleTemplateSelector.cs @@ -26,7 +26,7 @@ public IDictionary TemplateDictionary } /// - /// Selects a template based upon the type of the item and and the + /// Selects a template based upon the type of the item and the /// corresponding template that is registered in the TemplateDictionary. /// /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs index 07a4ed58f8b..972c19080e0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRuleToDisplayNameConverter.cs @@ -11,7 +11,6 @@ namespace Microsoft.Management.UI.Internal /// The FilterRuleToDisplayNameConverter is responsible for converting /// a FilterRule value to its DisplayName. /// - [Serializable] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class FilterRuleToDisplayNameConverter : IValueConverter { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs index 0017f2a4340..1295b933d5b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/InputFieldBackgroundTextConverter.cs @@ -11,7 +11,7 @@ namespace Microsoft.Management.UI.Internal { /// - /// The InputFieldBackgroundTextConverter is responsible for determing the + /// The InputFieldBackgroundTextConverter is responsible for determining the /// correct background text to display for a particular type of data. /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] @@ -40,10 +40,7 @@ public class InputFieldBackgroundTextConverter : IValueConverter /// public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); Type inputType = null; if (this.IsOfTypeValidatingValue(value)) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs index 25830150939..b3345a10cf2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchBox.cs @@ -86,10 +86,7 @@ public SearchTextParser Parser set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.parser = value; } @@ -118,10 +115,7 @@ partial void OnClearTextExecutedImplementation(ExecutedRoutedEventArgs e) /// The specified value is a null reference. protected static FilterExpressionNode ConvertToFilterExpression(ICollection searchBoxItems) { - if (searchBoxItems == null) - { - throw new ArgumentNullException("searchBoxItems"); - } + ArgumentNullException.ThrowIfNull(searchBoxItems); if (searchBoxItems.Count == 0) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs index 5fa5e3e7703..10843087587 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParseResult.cs @@ -18,10 +18,7 @@ public class SearchTextParseResult /// The specified value is a null reference. public SearchTextParseResult(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.FilterRule = rule; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs index 04ba32ece6d..2e0ac74e076 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/SearchTextParser.cs @@ -45,10 +45,7 @@ public TextFilterRule FullTextRule public bool TryAddSearchableRule(SelectorFilterRule selectorRule) where T : TextFilterRule { - if (selectorRule == null) - { - throw new ArgumentNullException("selectorRule"); - } + ArgumentNullException.ThrowIfNull(selectorRule); T textRule = selectorRule.AvailableRules.AvailableValues.Find(); @@ -193,25 +190,21 @@ protected class SearchableRule /// The specified value is a null reference. public SearchableRule(string uniqueId, SelectorFilterRule selectorFilterRule, TextFilterRule childRule) { - if (uniqueId == null) - { - throw new ArgumentNullException("uniqueId"); - } + ArgumentNullException.ThrowIfNull(uniqueId); - if (selectorFilterRule == null) - { - throw new ArgumentNullException("selectorFilterRule"); - } + ArgumentNullException.ThrowIfNull(selectorFilterRule); - if (childRule == null) - { - throw new ArgumentNullException("childRule"); - } + ArgumentNullException.ThrowIfNull(childRule); this.UniqueId = uniqueId; this.selectorFilterRule = selectorFilterRule; this.childRule = childRule; - this.Pattern = string.Format(CultureInfo.InvariantCulture, "(?<{0}>){1}\\s*:\\s*{2}", uniqueId, Regex.Escape(selectorFilterRule.DisplayName), SearchTextParser.ValuePattern); + this.Pattern = string.Format( + CultureInfo.InvariantCulture, + "(?<{0}>){1}\\s*:\\s*{2}", + uniqueId, + Regex.Escape(selectorFilterRule.DisplayName), + SearchTextParser.ValuePattern); } /// @@ -240,10 +233,7 @@ public string Pattern /// The specified value is a null reference. public SelectorFilterRule GetRuleWithValueSet(string value) { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); SelectorFilterRule selectorRule = (SelectorFilterRule)this.selectorFilterRule.DeepCopy(); selectorRule.AvailableRules.SelectedIndex = this.selectorFilterRule.AvailableRules.AvailableValues.IndexOf(this.childRule); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs index e8708b92a15..010fbbeef75 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/ValidatingSelectorValueToDisplayNameConverter.cs @@ -38,10 +38,7 @@ public class ValidatingSelectorValueToDisplayNameConverter : IMultiValueConverte /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null) - { - throw new ArgumentNullException("values"); - } + ArgumentNullException.ThrowIfNull(values); if (values.Length != 2) { diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs index 470a7670860..05151330ea2 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ColumnPicker.xaml.cs @@ -59,15 +59,9 @@ internal ColumnPicker( ICollection availableColumns) : this() { - if (columns == null) - { - throw new ArgumentNullException("columns"); - } + ArgumentNullException.ThrowIfNull(columns); - if (availableColumns == null) - { - throw new ArgumentNullException("availableColumns"); - } + ArgumentNullException.ThrowIfNull(availableColumns); // Add visible columns to Selected list, preserving order // Note that availableColumns is not necessarily in the order diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs index cf85d79ae36..2d590904097 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/DefaultStringConverter.cs @@ -62,7 +62,9 @@ public string DefaultValue /// public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture) { - if (values == null || values.Length != 1) + ArgumentNullException.ThrowIfNull(values); + + if (values.Length != 1) { throw new ArgumentNullException("values"); } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs index 73222cae639..2761dcf36da 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/InnerListGridView.cs @@ -45,10 +45,7 @@ public InnerListGridView() /// The specified value is a null reference. internal InnerListGridView(ObservableCollection availableColumns) { - if (availableColumns == null) - { - throw new ArgumentNullException("availableColumns"); - } + ArgumentNullException.ThrowIfNull(availableColumns); // Setting the AvailableColumns property won't trigger CollectionChanged, so we have to do it manually \\ this.AvailableColumns = availableColumns; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs index 03c7acdf008..aa945a1d90c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/Innerlist.cs @@ -93,7 +93,7 @@ public InnerList() /// /// Gets ItemsSource instead. - /// Does not support adding to Items. + /// Does not support adding to Items. /// [Browsable(false)] public new ItemCollection Items @@ -191,10 +191,7 @@ public void RefreshColumns() /// The specified value is a null reference. public void ApplySort(InnerListColumn column, bool shouldScrollIntoView) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); // NOTE : By setting the column here, it will be used // later to set the sorted column when the UI state @@ -296,7 +293,7 @@ protected override void OnItemsSourceChanged(System.Collections.IEnumerable oldV this.itemsSourceIsEmpty = this.ItemsSource != null && this.ItemsSource.GetEnumerator().MoveNext() == false; - // A view can be created if there is data to auto-generate columns, or columns are added programatically \\ + // A view can be created if there is data to auto-generate columns, or columns are added programmatically \\ bool canCreateView = (this.ItemsSource != null) && (this.itemsSourceIsEmpty == false || this.AutoGenerateColumns == false); @@ -355,7 +352,7 @@ protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); - if ((Key.Left == e.Key || Key.Right == e.Key) && + if ((e.Key == Key.Left || e.Key == Key.Right) && Keyboard.Modifiers == ModifierKeys.None) { // If pressing Left or Right on a column header, move the focus \\ @@ -388,8 +385,8 @@ private static void InnerList_OnViewChanged(DependencyObject obj, DependencyProp throw new NotSupportedException(string.Format( CultureInfo.InvariantCulture, InvariantResources.ViewSetWithType, - typeof(GridView).Name, - typeof(InnerListGridView).Name)); + nameof(GridView), + nameof(InnerListGridView))); } ((InnerList)obj).innerGrid = innerGrid; @@ -405,7 +402,7 @@ private static NotSupportedException GetItemsException() string.Format( CultureInfo.InvariantCulture, InvariantResources.NotSupportAddingToItems, - typeof(InnerList).Name, + nameof(InnerList), ItemsControl.ItemsSourceProperty.Name)); } #endregion static private methods @@ -599,7 +596,7 @@ private string GetClipboardTextLineForSelectedItem(object value) propertyValue = string.Empty; } - entryText.AppendFormat(CultureInfo.CurrentCulture, "{0}\t", propertyValue); + entryText.Append(CultureInfo.CurrentCulture, $"{propertyValue}\t"); } return entryText.ToString(); diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs index 841175c97da..bbfd3d8603c 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ManagementListStateDescriptor.cs @@ -15,7 +15,6 @@ namespace Microsoft.Management.UI.Internal /// /// Allows the state of the ManagementList to be saved and restored. /// - [Serializable] [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public class ManagementListStateDescriptor : StateDescriptor { @@ -63,10 +62,7 @@ public ManagementListStateDescriptor(string name) /// public override void SaveState(ManagementList subject) { - if (subject == null) - { - throw new ArgumentNullException("subject"); - } + ArgumentNullException.ThrowIfNull(subject); this.SaveColumns(subject); this.SaveSortOrder(subject); @@ -100,10 +96,7 @@ public override void RestoreState(ManagementList subject) /// public void RestoreState(ManagementList subject, bool applyRestoredFilter) { - if (subject == null) - { - throw new ArgumentNullException("subject"); - } + ArgumentNullException.ThrowIfNull(subject); // Clear the sort, otherwise restoring columns and filters may trigger extra sorting \\ subject.List.ClearSort(); @@ -142,7 +135,7 @@ private static bool VerifyColumnsSavable(ManagementList subject, RetryActionCall /// /// Target ManagementList. /// RetryActionAfterLoaded callback method. - /// True iff columns restorable. + /// True if-and-only-if columns are restorable. /// /// ManagementList.AutoGenerateColumns not supported. /// @@ -471,7 +464,6 @@ private static void SetColumnWidth(GridViewColumn ilc, double width) #region Helper Classes - [Serializable] internal class ColumnStateDescriptor { private int index; @@ -516,7 +508,6 @@ public double Width } } - [Serializable] internal class RuleStateDescriptor { /// diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs index 61a1a71938c..2e9326cd909 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/PropertyValueGetter.cs @@ -48,10 +48,7 @@ public virtual bool TryGetPropertyValue(string propertyName, object value, out o throw new ArgumentException("propertyName is empty", "propertyName"); } - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); PropertyDescriptor descriptor = this.GetPropertyDescriptor(propertyName, value); if (descriptor == null) diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs index c69cd8e0c08..22741a7031b 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/ViewGroupToStringConverter.cs @@ -35,7 +35,7 @@ public object Convert(object value, Type targetType, object parameter, System.Gl } string name = (!string.IsNullOrEmpty(cvg.Name.ToString())) ? cvg.Name.ToString() : UICultureResources.GroupTitleNone; - string display = string.Format(CultureInfo.CurrentCulture, "{0} ({1})", name, cvg.ItemCount); + string display = string.Create(CultureInfo.CurrentCulture, $"{name} ({cvg.ItemCount})"); return display; } diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs index 9f91f2b74e8..965a66239d0 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/innerlistcolumn.cs @@ -68,10 +68,7 @@ public InnerListColumn(UIPropertyGroupDescription dataDescription, bool isVisibl /// Whether the column should create a default binding using the specified data's property. public InnerListColumn(UIPropertyGroupDescription dataDescription, bool isVisible, bool createDefaultBinding) { - if (dataDescription == null) - { - throw new ArgumentNullException("dataDescription"); - } + ArgumentNullException.ThrowIfNull(dataDescription); GridViewColumnHeader header = new GridViewColumnHeader(); header.Content = dataDescription.DisplayContent; diff --git a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs index 7c36244e0f1..4ac51c702d8 100644 --- a/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs +++ b/src/Microsoft.Management.UI.Internal/ManagementList/ManagementList/managementlist.cs @@ -50,10 +50,7 @@ public IStateDescriptorFactory SavedViewFactory set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); this.savedViewFactory = value; } @@ -177,10 +174,7 @@ private void Evaluator_PropertyChanged(object sender, PropertyChangedEventArgs e /// The specified value is a null reference. public void AddColumn(InnerListColumn column) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); this.AddColumn(column, this.IsFilterShown); } @@ -193,10 +187,7 @@ public void AddColumn(InnerListColumn column) /// The specified value is a null reference. public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) { - if (column == null) - { - throw new ArgumentNullException("column"); - } + ArgumentNullException.ThrowIfNull(column); this.List.Columns.Add(column); @@ -229,10 +220,7 @@ public void AddColumn(InnerListColumn column, bool addDefaultFilterRules) /// The specified value is a null reference. public void AddRule(FilterRule rule) { - if (rule == null) - { - throw new ArgumentNullException("rule"); - } + ArgumentNullException.ThrowIfNull(rule); this.AddFilterRulePicker.ShortcutFilterRules.Add(new AddFilterRulePickerItem(new FilterRulePanelItem(rule, rule.DisplayName))); } diff --git a/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj b/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj index 72eb8d6572f..6db4395d720 100644 --- a/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj +++ b/src/Microsoft.Management.UI.Internal/Microsoft.PowerShell.GraphicalHost.csproj @@ -5,13 +5,11 @@ $(NoWarn);CS1570 Microsoft.Management.UI.Internal Microsoft.PowerShell.GraphicalHost - True + false Windows - 7.0 - - - - $(DefineConstants);CORECLR + 8.0 + true + True @@ -33,4 +31,10 @@ + + + + $(RootNamespace).resources.%(Filename) + + diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs index 54dcf1896ff..f57d5dfda51 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/MultipleSelectionControl.xaml.cs @@ -43,7 +43,7 @@ private void ButtonBrowse_Click(object sender, RoutedEventArgs e) foreach (object selectedItem in multipleSelectionDialog.listboxParameter.SelectedItems) { - newComboText.AppendFormat(CultureInfo.InvariantCulture, "{0},", selectedItem.ToString()); + newComboText.Append(CultureInfo.InvariantCulture, $"{selectedItem},"); } if (newComboText.Length > 1) diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs index 08f9df29337..6efef65eec6 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ParameterSetControl.xaml.cs @@ -94,7 +94,7 @@ private static CheckBox CreateCheckBox(ParameterViewModel parameterViewModel, in //// Add AutomationProperties.AutomationId for Ui Automation test. checkBox.SetValue( System.Windows.Automation.AutomationProperties.AutomationIdProperty, - string.Format(CultureInfo.CurrentCulture, "chk{0}", parameterViewModel.Name)); + string.Create(CultureInfo.CurrentCulture, $"chk{parameterViewModel.Name}")); checkBox.SetValue( System.Windows.Automation.AutomationProperties.NameProperty, @@ -124,10 +124,7 @@ private static ComboBox CreateComboBoxControl(ParameterViewModel parameterViewMo Binding selectedItemBinding = new Binding("Value"); comboBox.SetBinding(ComboBox.SelectedItemProperty, selectedItemBinding); - string automationId = string.Format( - CultureInfo.CurrentCulture, - "combox{0}", - parameterViewModel.Name); + string automationId = string.Create(CultureInfo.CurrentCulture, $"combox{parameterViewModel.Name}"); //// Add AutomationProperties.AutomationId for Ui Automation test. comboBox.SetValue( @@ -164,7 +161,7 @@ private static MultipleSelectionControl CreateMultiSelectComboControl(ParameterV multiControls.comboxParameter.SetBinding(ComboBox.TextProperty, valueBinding); // Add AutomationProperties.AutomationId for Ui Automation test. - multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Format("combox{0}", parameterViewModel.Name)); + multiControls.SetValue(System.Windows.Automation.AutomationProperties.AutomationIdProperty, string.Create(CultureInfo.CurrentCulture, $"combox{parameterViewModel.Name}")); multiControls.comboxParameter.SetValue( System.Windows.Automation.AutomationProperties.NameProperty, @@ -206,7 +203,7 @@ private static TextBox CreateTextBoxControl(ParameterViewModel parameterViewMode //// Add AutomationProperties.AutomationId for UI Automation test. textBox.SetValue( System.Windows.Automation.AutomationProperties.AutomationIdProperty, - string.Format(CultureInfo.CurrentCulture, "txt{0}", parameterViewModel.Name)); + string.Create(CultureInfo.CurrentCulture, $"txt{parameterViewModel.Name}")); textBox.SetValue( System.Windows.Automation.AutomationProperties.NameProperty, @@ -366,7 +363,7 @@ private void AddControlToMainGrid(UIElement uiControl) } /// - /// Creates a Lable control and add it to MainGrid. + /// Creates a Label control and add it to MainGrid. /// /// DataContext object. /// Row number. @@ -397,7 +394,7 @@ private Label CreateLabel(ParameterViewModel parameterViewModel, int rowNumber) //// Add AutomationProperties.AutomationId for Ui Automation test. label.SetValue( System.Windows.Automation.AutomationProperties.AutomationIdProperty, - string.Format(CultureInfo.CurrentCulture, "lbl{0}", parameterViewModel.Name)); + string.Create(CultureInfo.CurrentCulture, $"lbl{parameterViewModel.Name}")); return label; } diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs index 440eb329f39..4bdaa32fd9f 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/Controls/ShowModuleControl.xaml.cs @@ -47,8 +47,8 @@ public Window Owner /// 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 it happend to be over as the list got resized. + /// 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 diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs index 34159c8f837..04fc95e4223 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/AllModulesViewModel.cs @@ -79,7 +79,9 @@ public class AllModulesViewModel : INotifyPropertyChanged /// Commands to show. public AllModulesViewModel(Dictionary importedModules, IEnumerable commands) { - if (commands == null || !commands.GetEnumerator().MoveNext()) + ArgumentNullException.ThrowIfNull(commands); + + if (!commands.GetEnumerator().MoveNext()) { throw new ArgumentNullException("commands"); } @@ -95,10 +97,7 @@ public AllModulesViewModel(Dictionary importedMod /// True not to show common parameters. public AllModulesViewModel(Dictionary importedModules, IEnumerable commands, bool noCommonParameter) { - if (commands == null) - { - throw new ArgumentNullException("commands"); - } + ArgumentNullException.ThrowIfNull(commands); this.Initialization(importedModules, commands, noCommonParameter); } @@ -530,7 +529,7 @@ private void Initialization(Dictionary importedMo return; } - // If there are more modules, create an additional module to agregate all commands + // 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); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs index e5eb1be800d..cfa2798963c 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/CommandViewModel.cs @@ -431,19 +431,19 @@ public string GetScript() if (commandName.Contains(' ')) { - builder.AppendFormat("& \"{0}\"", commandName); + builder.Append($"& \"{commandName}\""); } else { builder.Append(commandName); } - builder.Append(" "); + builder.Append(' '); if (this.SelectedParameterSet != null) { builder.Append(this.SelectedParameterSet.GetScript()); - builder.Append(" "); + builder.Append(' '); } if (this.CommonParameters != null) @@ -457,7 +457,7 @@ public string GetScript() } /// - /// Showing help information for current actived cmdlet. + /// Showing help information for current active cmdlet. /// public void OpenHelpWindow() { @@ -465,7 +465,7 @@ public void OpenHelpWindow() } /// - /// Determins whether current command name and a specifed ParameterSetName have same name. + /// Determines whether current command name and a specified ParameterSetName have same name. /// /// The name of ShareParameterSet. /// Return true is ShareParameterSet. Else return false. @@ -490,10 +490,7 @@ internal static bool IsSharedParameterSetName(string name) /// The CommandViewModel corresponding to commandInfo. internal static CommandViewModel GetCommandViewModel(ModuleViewModel module, ShowCommandCommandInfo commandInfo, bool noCommonParameters) { - if (commandInfo == null) - { - throw new ArgumentNullException("commandInfo"); - } + ArgumentNullException.ThrowIfNull(commandInfo); CommandViewModel returnValue = new CommandViewModel(); returnValue.commandInfo = commandInfo; diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs index 38925e458a9..950dbe93758 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ModuleViewModel.cs @@ -67,10 +67,7 @@ public class ModuleViewModel : INotifyPropertyChanged /// All loaded modules. public ModuleViewModel(string name, Dictionary importedModules) { - if (name == null) - { - throw new ArgumentNullException("name"); - } + ArgumentNullException.ThrowIfNull(name); this.name = name; this.commands = new List(); @@ -373,7 +370,7 @@ internal void RefreshFilteredCommands(string filter) } /// - /// Callled in response to a GUI event that requires the command to be run. + /// Called in response to a GUI event that requires the command to be run. /// internal void OnRunSelectedCommand() { diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs index 756f58c62c8..b4f42dd78a2 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterSetViewModel.cs @@ -39,21 +39,15 @@ public class ParameterSetViewModel : INotifyPropertyChanged /// Initializes a new instance of the ParameterSetViewModel class. /// /// The name of the parameterSet. - /// The array parametes 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) { - if (name == null) - { - throw new ArgumentNullException("name"); - } + ArgumentNullException.ThrowIfNull(name); - if (parameters == null) - { - throw new ArgumentNullException("parameters"); - } + ArgumentNullException.ThrowIfNull(parameters); parameters.Sort(Compare); @@ -144,7 +138,7 @@ public string GetScript() { if (((bool?)parameter.Value) == true) { - builder.AppendFormat("-{0} ", parameter.Name); + builder.Append($"-{parameter.Name} "); } continue; @@ -172,7 +166,7 @@ public string GetScript() parameterValueString = ParameterSetViewModel.GetDelimitedParameter(parameterValueString, "(", ")"); } - builder.AppendFormat("-{0} {1} ", parameter.Name, parameterValueString); + builder.Append($"-{parameter.Name} {parameterValueString} "); } return builder.ToString().Trim(); @@ -232,12 +226,12 @@ internal static int Compare(ParameterViewModel source, ParameterViewModel target #endregion /// - /// Gets the delimited poarameter if it needs delimitation and is not delimited. + /// Gets the delimited parameter if it needs delimitation and is not delimited. /// /// Value needing delimitation. /// Open delimitation. /// Close delimitation. - /// The delimited poarameter if it needs delimitation and is not delimited. + /// 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(); diff --git a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs index 2c6931eb08e..93227df87a1 100644 --- a/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs +++ b/src/Microsoft.Management.UI.Internal/ShowCommand/ViewModel/ParameterViewModel.cs @@ -48,15 +48,9 @@ public class ParameterViewModel : INotifyPropertyChanged /// The name of the parameter set this parameter is in. public ParameterViewModel(ShowCommandParameterInfo parameter, string parameterSetName) { - if (parameter == null) - { - throw new ArgumentNullException("parameter"); - } + ArgumentNullException.ThrowIfNull(parameter); - if (parameterSetName == null) - { - throw new ArgumentNullException("parameterSetName"); - } + ArgumentNullException.ThrowIfNull(parameterSetName); this.parameter = parameter; this.parameterSetName = parameterSetName; @@ -165,7 +159,7 @@ public string NameCheckLabel string returnValue = this.Parameter.Name; if (this.Parameter.IsMandatory) { - returnValue = string.Format(CultureInfo.CurrentUICulture, "{0}{1}", returnValue, ShowCommandResources.MandatoryLabelSegment); + returnValue = string.Create(CultureInfo.CurrentUICulture, $"{returnValue}{ShowCommandResources.MandatoryLabelSegment}"); } return returnValue; diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs index efed820e71c..e0b036a93d0 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/HelpWindowHelper.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Commands.Internal { /// - /// Implements thw WPF window part of the the ShowWindow option of get-help. + /// Implements the WPF window part of the ShowWindow option of get-help. /// internal static class HelpWindowHelper { diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs index 85ecd95a36f..81621624992 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/OutGridView.cs @@ -6,6 +6,7 @@ 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; @@ -213,7 +214,7 @@ private void ZoomEventHandlerPlus(object sender, ExecutedRoutedEventArgs e) if (this.zoomLevel < ZOOM_MAX) { - this.zoomLevel = this.zoomLevel + ZOOM_INCREMENT; + this.zoomLevel += ZOOM_INCREMENT; Grid g = this.gridViewWindow.Content as Grid; if (g != null) @@ -232,7 +233,7 @@ private void ZoomEventHandlerMinus(object sender, ExecutedRoutedEventArgs e) { if (this.zoomLevel >= ZOOM_MIN) { - this.zoomLevel = this.zoomLevel - ZOOM_INCREMENT; + this.zoomLevel -= ZOOM_INCREMENT; Grid g = this.gridViewWindow.Content as Grid; if (g != null) { @@ -496,6 +497,16 @@ private void AddItem(PSObject value) { 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) diff --git a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs index 5d401fc94c6..10690b65dc7 100644 --- a/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs +++ b/src/Microsoft.Management.UI.Internal/commandHelpers/ShowCommandHelper.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell.Commands.ShowCommandInternal { /// - /// Implements thw WPF window part of the show-command cmdlet. + /// Implements the WPF window part of the show-command cmdlet. /// internal class ShowCommandHelper : IDisposable { @@ -289,7 +289,7 @@ private ShowCommandHelper() } /// - /// Finalizes an instance of the ShowCommandHelper class. + /// Finalizes an instance of the class. /// ~ShowCommandHelper() { @@ -489,37 +489,6 @@ private static string GetSerializedCommandScript() @"Remove-Item -Path 'function:\PSGetSerializedShowCommandInfo' -Force"); } - /// - /// Gets the command to be run to in order to import a module and refresh the command data. - /// - /// Module we want to import. - /// 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 in order to import a module and refresh the command data. - internal static string GetImportModuleCommand(string module, bool isRemoteRunspace = false, bool isFirstChance = true) - { - string scriptBase = "Import-Module " + ShowCommandHelper.SingleQuote(module); - - if (isRemoteRunspace) - { - if (isFirstChance) - { - scriptBase += ";@(Get-Command " + ShowCommandHelper.CommandTypeSegment + @" -ShowCommandInfo )"; - } - else - { - scriptBase += GetSerializedCommandScript(); - } - } - else - { - scriptBase += ";@(Get-Command " + ShowCommandHelper.CommandTypeSegment + ")"; - } - - scriptBase += ShowCommandHelper.GetGetModuleSuffix(); - return scriptBase; - } - /// /// Gets the command to be run in order to show help for a command. /// @@ -672,7 +641,7 @@ internal static AllModulesViewModel GetNewAllModulesViewModel(AllModulesViewMode /// /// Gets an error message to be displayed when failed to import a module. /// - /// Command belongiong to the module to import. + /// 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. @@ -710,7 +679,8 @@ internal static string SingleQuote(string str) /// The host window, if it is present or null if it is not. internal static Window GetHostWindow(PSCmdlet cmdlet) { - PSPropertyInfo windowProperty = cmdlet.Host.PrivateData.Properties["Window"]; + // 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; @@ -750,7 +720,7 @@ private static object GetPropertyValue(Type type, object obj, string propertyNam try { - return property.GetValue(obj, new object[] { }); + return property.GetValue(obj, Array.Empty()); } catch (ArgumentException) { @@ -794,7 +764,7 @@ private static bool SetPropertyValue(Type type, object obj, string propertyName, try { - property.SetValue(obj, value, new object[] { }); + property.SetValue(obj, value, Array.Empty()); } catch (ArgumentException) { @@ -1000,7 +970,7 @@ private void ImportModuleDone(Dictionary imported { this.window.Dispatcher.Invoke( new SendOrPostCallback( - delegate (object ignored) + delegate(object ignored) { this.allModulesViewModel = ShowCommandHelper.GetNewAllModulesViewModel( this.allModulesViewModel, @@ -1050,7 +1020,7 @@ private void DisplayHelp(Collection getHelpResults) { this.window.Dispatcher.Invoke( new SendOrPostCallback( - delegate (object ignored) + delegate(object ignored) { HelpWindow help = new HelpWindow(getHelpResults[0]); help.Owner = this.window; @@ -1200,7 +1170,7 @@ private void Buttons_CopyClick(object sender, RoutedEventArgs e) } /// - /// Sets a succesfull dialog result and then closes the window. + /// Sets a successful dialog result and then closes the window. /// /// Event sender. /// Event arguments. diff --git a/src/Microsoft.Management.UI.Internal/resources/cs/public.GraphicalHostResources.cs.resx b/src/Microsoft.Management.UI.Internal/resources/cs/public.GraphicalHostResources.cs.resx new file mode 100644 index 00000000000..f20a07dffa2 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/cs/public.GraphicalHostResources.cs.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 + + + Objekt OutGridViewWindow + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/cs/public.HelpWindowResources.cs.resx b/src/Microsoft.Management.UI.Internal/resources/cs/public.HelpWindowResources.cs.resx new file mode 100644 index 00000000000..1180fb67e66 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/cs/public.HelpWindowResources.cs.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 + + + Zrušit + + + Rozlišovat malá a velká písmena + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Popis + + + Příklady + + + _Najít: + + + Oddíly nápovědy + + + Nápověda pro {0} + + + Vstupy + + + {0} {1} + + + Metody + + + _Další + + + Nenašly se žádné shody + + + Poznámky + + + OK + + + 1 shoda + + + Výstupy + + + Jsou podporovány zástupné znaky? + + + Výchozí hodnota + + + Přijmout vstup z kanálu? + + + Pozice? + + + Požadováno? + + + Parametry + + + _Předchozí + + + Vlastnosti + + + RelatedLinks + + + Poznámky + + + Možnosti hledání + + + Nastavení + + + Počet shod: {0} + + + Synopse + + + Syntaxe + + + Nápověda pro {0} + {0} is the name of a cmdlet + + + Celá slova + + + {0} % + + + Přiblížit + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/cs/public.InvariantResources.cs.resx b/src/Microsoft.Management.UI.Internal/resources/cs/public.InvariantResources.cs.resx new file mode 100644 index 00000000000..b92bfb0c515 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/cs/public.InvariantResources.cs.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} nelze upravovat přímo. Místo toho použijte {1}. + + + Sloupce + + + {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} nepodporuje přidávání do kolekce Položky. Místo toho použijte {1}. + + + Pokud je pro zobrazení nastavena hodnota {0}, musí mít typ {1}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/cs/public.ShowCommandResources.cs.resx b/src/Microsoft.Management.UI.Internal/resources/cs/public.ShowCommandResources.cs.resx new file mode 100644 index 00000000000..26185942412 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/cs/public.ShowCommandResources.cs.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 + + + Zrušit + + + Ko_pírovat + + + _Spustit + + + Vše + + + Moduly: + + + ? + + + Nápověda + + + Společné parametry + + + Chyby + + + Parametry pro {0}: + + + Název: {0} +Modul: {1} ({2}) + + + Při spuštění příkazu došlo k následujícím chybám: +{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 + + + Název: + + + OK + + + ... + + + Název příkazu + + + Moduly + + + <Žádný název modulu> + + + Vyberte více hodnot pro {0}. + + + Může přijímat hodnotu z kanálu + + + Společné pro všechny sady parametrů + + + Povinné + + + Volitelné + + + Pozice: {0} + + + Typ: {0} + + + Importováno + + + Nenaimportováno + + + Zobrazit podrobnosti + + + Nepodařilo se naimportovat modul požadovaný příkazem {0}. Název modulu: {1} Chybová zpráva: „{2}“. + + + Chcete-li importovat modul {0} a jeho rutiny, včetně {1}, klikněte na {2}. + + + Zobrazit příkaz – chyba + + + Počkejte prosím... + + + Aktualizovat + + + Neexistují žádné parametry. + + + Po použití {0} kliknutím zobrazte nové příkazy. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/cs/public.UICultureResources.cs.resx b/src/Microsoft.Management.UI.Internal/resources/cs/public.UICultureResources.cs.resx new file mode 100644 index 00000000000..72b57dbb88e --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/cs/public.UICultureResources.cs.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 + + + Vybrat sloupce... + + + (žádné) + The group title for items within a column whose value is empty/null. + + + Hodnota musí být typu {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. + + + Aktuální výběr je prázdný. + The error validation string to present to the user when they have selected a value out of bounds. + + + obsahuje + A filter rule that indicates a field must contain the specified value. + + + neobsahuje + A filter rule that indicates a field must not contain the specified value. + + + nerovná se + A filter rule that indicates a field must not equal the specified value. + + + rovná se + A filter rule that indicates a field must equal the specified value. + + + je větší než nebo rovno + A filter rule that indicates a field must be greater than or equal to the specified value. + + + je mezi + A filter rule that indicates a field must be between the specified values. + + + nic neobsahuje + A filter rule that indicates a field must be empty. + + + něco obsahuje + A filter rule that indicates a field must not be empty. + + + je menší než nebo rovno + A filter rule that indicates a field must be less than or equal to the specified value. + + + má na konci + A filter rule that indicates a field must end with the specified value. + + + má na začátku + A filter rule that indicates a field must start with the specified value. + + + Zpět + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Vpřed + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + Hodnotou musí být platné datum v následujícím formátu: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + Hodnota musí být platné číslo. + + + Hledat + 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+plus na numerické klávesnici + + + Ctrl+Shift+plus na numerické klávesnici + + + Ctrl+plus + + + Ctrl+Shift+plus + + + Ctrl+minus na numerické klávesnici + + + Ctrl+Shift+minus na numerické klávesnici + + + Ctrl+minus + + + Ctrl+Shift+minus + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/cs/public.XamlLocalizableResources.cs.resx b/src/Microsoft.Management.UI.Internal/resources/cs/public.XamlLocalizableResources.cs.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/cs/public.XamlLocalizableResources.cs.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/de/public.GraphicalHostResources.de.resx b/src/Microsoft.Management.UI.Internal/resources/de/public.GraphicalHostResources.de.resx new file mode 100644 index 00000000000..40ad8cc06da --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/de/public.GraphicalHostResources.de.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-Objekt + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/de/public.HelpWindowResources.de.resx b/src/Microsoft.Management.UI.Internal/resources/de/public.HelpWindowResources.de.resx new file mode 100644 index 00000000000..cf8c6838186 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/de/public.HelpWindowResources.de.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 + + + Abbrechen + + + Groß-/Kleinschreibung beachten + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Beschreibung + + + Beispiele + + + _Suchen: + + + Hilfeabschnitte + + + Hilfe zu {0} + + + Eingaben + + + {0} {1} + + + Methoden + + + _Weiter + + + Keine Übereinstimmungen gefunden + + + Notizen + + + OK + + + 1 Übereinstimmung + + + Ausgaben + + + Platzhalterzeichen akzeptieren? + + + Standardwert + + + Pipelineeingabe akzeptieren? + + + Position? + + + Erforderlich? + + + Parameter + + + _Zurück + + + Eigenschaften + + + RelatedLinks + + + Hinweise + + + Suchoptionen + + + Einstellungen + + + {0} Übereinstimmungen + + + Synopsis + + + Syntax + + + Hilfe für {0} + {0} is the name of a cmdlet + + + Ganzes Wort + + + {0} % + + + Zoom + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/de/public.InvariantResources.de.resx b/src/Microsoft.Management.UI.Internal/resources/de/public.InvariantResources.de.resx new file mode 100644 index 00000000000..bf746936812 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/de/public.InvariantResources.de.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. + + + Spalten + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/de/public.ShowCommandResources.de.resx b/src/Microsoft.Management.UI.Internal/resources/de/public.ShowCommandResources.de.resx new file mode 100644 index 00000000000..6886d07fa11 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/de/public.ShowCommandResources.de.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 + + + Abbrechen + + + Ko_pieren + + + _Ausführen + + + Alle + + + Module: + + + ? + + + Hilfe + + + Allgemeine Parameter + + + Fehler + + + Parameter für „{0}“: + + + Name: {0} +Modul: {1} ({2}) + + + Beim Ausführen des Befehls sind die folgenden Fehler aufgetreten: +{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 + + + ... + + + Befehlsname + + + Module + + + <No module name> + + + Mehrere Werte für „{0}“ auswählen + + + Kann einen Wert aus der Pipeline empfangen + + + Für alle Parametersätze gemeinsam + + + Obligatorisch + + + Optional + + + Position: {0} + + + Typ: {0} + + + Importiert + + + Nicht importiert + + + Details anzeigen + + + Fehler beim Importieren des für den Befehl „{0}“ erforderlichen Moduls. Modulname: „{1}“. Fehlermeldung: „{2}“. + + + Klicken Sie auf „{2}“, um das Modul „{0}“ und seine Cmdlets, einschließlich „{1}“, zu importieren. + + + Befehl anzeigen – Fehler + + + Bitte warten... + + + Aktualisieren + + + Es gibt keine Parameter. + + + Klicken Sie nach der Verwendung von „{0}“ darauf, um die neuen Befehle anzuzeigen. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/de/public.UICultureResources.de.resx b/src/Microsoft.Management.UI.Internal/resources/de/public.UICultureResources.de.resx new file mode 100644 index 00000000000..b7a01e57d48 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/de/public.UICultureResources.de.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 + + + Spalten auswählen... + + + (keine) + The group title for items within a column whose value is empty/null. + + + Der Wert muss vom Typ „{0}“ sein. + 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. + + + Die aktuelle Auswahl ist leer. + The error validation string to present to the user when they have selected a value out of bounds. + + + enthält + A filter rule that indicates a field must contain the specified value. + + + enthält nicht + A filter rule that indicates a field must not contain the specified value. + + + ungleich + A filter rule that indicates a field must not equal the specified value. + + + gleich + A filter rule that indicates a field must equal the specified value. + + + ist größer als oder gleich + A filter rule that indicates a field must be greater than or equal to the specified value. + + + zwischen + A filter rule that indicates a field must be between the specified values. + + + ist leer + A filter rule that indicates a field must be empty. + + + nicht leer + A filter rule that indicates a field must not be empty. + + + ist kleiner als oder gleich + A filter rule that indicates a field must be less than or equal to the specified value. + + + endet mit + A filter rule that indicates a field must end with the specified value. + + + beginnt mit + A filter rule that indicates a field must start with the specified value. + + + Zurück + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Vorwärts + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + Bei dem Wert muss es sich um ein gültiges Datum im folgenden Format handeln: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + Der Wert muss eine gültige Zahl sein. + + + Suchen + 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. + + + STRG+Hinzufügen + + + STRG+UMSCHALT+Hinzufügen + + + STRG+Plus + + + STRG+UMSCHALT+Plus + + + STRG+Subtrahieren + + + STRG+UMSCHALT+Subtrahieren + + + STRG+Minus + + + STRG+UMSCHALT+Minus + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/de/public.XamlLocalizableResources.de.resx b/src/Microsoft.Management.UI.Internal/resources/de/public.XamlLocalizableResources.de.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/de/public.XamlLocalizableResources.de.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/es/public.GraphicalHostResources.es.resx b/src/Microsoft.Management.UI.Internal/resources/es/public.GraphicalHostResources.es.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/es/public.GraphicalHostResources.es.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/es/public.HelpWindowResources.es.resx b/src/Microsoft.Management.UI.Internal/resources/es/public.HelpWindowResources.es.resx new file mode 100644 index 00000000000..f1f02a1c0ee --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/es/public.HelpWindowResources.es.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 + + + Cancelar + + + Coincidir mayúsculas y minúsculas + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Descripción + + + Ejemplos + + + _Buscar: + + + Secciones de ayuda + + + {0} Ayuda + + + Entradas + + + {0} {1} + + + Métodos + + + _Siguiente + + + No se encontraron coincidencias + + + Notas + + + Aceptar + + + 1 coincidencia + + + Salidas + + + ¿Aceptar caracteres comodín? + + + Valor predeterminado + + + ¿Aceptar la entrada de la canalización? + + + ¿Posición? + + + ¿Obligatorio? + + + Parámetros + + + _Anterior + + + Propiedades + + + RelatedLinks + + + Comentarios + + + Opciones de búsqueda + + + Configuración + + + {0} coincidencias + + + Sinopsis + + + Sintaxis + + + Ayuda para {0} + {0} is the name of a cmdlet + + + Palabra completa + + + {0} % + + + Zoom + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/es/public.InvariantResources.es.resx b/src/Microsoft.Management.UI.Internal/resources/es/public.InvariantResources.es.resx new file mode 100644 index 00000000000..08c41b65379 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/es/public.InvariantResources.es.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. + + + Columnas + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/es/public.ShowCommandResources.es.resx b/src/Microsoft.Management.UI.Internal/resources/es/public.ShowCommandResources.es.resx new file mode 100644 index 00000000000..c6f53aea89f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/es/public.ShowCommandResources.es.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 + + + Cancelar + + + Co_piar + + + _Run + + + Todas + + + Módulos: + + + ? + + + Ayuda + + + Parámetros comunes + + + Errores + + + Parámetros para "{0}": + + + Nombre: {0} +Módulo: {1} ({2}) + + + Se produjeron los siguientes errores al ejecutar el comando: +{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 + + + Nombre: + + + Aceptar + + + ... + + + Nombre de comando + + + Módulos + + + <No hay nombre de módulo> + + + Seleccionar varios valores para "{0}" + + + Puede recibir valor de la canalización + + + Común a todos los conjuntos de parámetros + + + Obligatorio + + + Opcional + + + Posición: {0} + + + Tipo: {0} + + + Importado + + + Sin importar + + + Mostrar detalles + + + No se pudo importar el módulo requerido por el comando "{0}". Nombre del módulo: "{1}". Mensaje de error: "{2}". + + + Para importar el módulo "{0}" y sus cmdlets, incluido "{1}", haga clic en {2}. + + + Mostrar comando: error + + + Espere... + + + Actualizar + + + No hay ningún parámetro. + + + Haga clic después de usar "{0}" para ver los nuevos comandos + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/es/public.UICultureResources.es.resx b/src/Microsoft.Management.UI.Internal/resources/es/public.UICultureResources.es.resx new file mode 100644 index 00000000000..dd68aeee157 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/es/public.UICultureResources.es.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 + + + Seleccionar columnas... + + + (ninguno) + The group title for items within a column whose value is empty/null. + + + El valor debe ser de tipo {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. + + + La selección actual está vacía. + The error validation string to present to the user when they have selected a value out of bounds. + + + contiene + A filter rule that indicates a field must contain the specified value. + + + no contiene + A filter rule that indicates a field must not contain the specified value. + + + no es igual que + A filter rule that indicates a field must not equal the specified value. + + + es igual a + A filter rule that indicates a field must equal the specified value. + + + es mayor o igual que + A filter rule that indicates a field must be greater than or equal to the specified value. + + + está entre + A filter rule that indicates a field must be between the specified values. + + + está vacío + A filter rule that indicates a field must be empty. + + + no está vacío + A filter rule that indicates a field must not be empty. + + + es menor o igual que + A filter rule that indicates a field must be less than or equal to the specified value. + + + termina en + A filter rule that indicates a field must end with the specified value. + + + comienza con + A filter rule that indicates a field must start with the specified value. + + + Atrás + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Reenviar + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + El valor debe ser una fecha válida con el formato siguiente: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + El valor debe ser un número válido. + + + Buscar + 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+Agregar + + + Ctrl+Mayús+Agregar + + + Ctrl+Plus + + + Ctrl+Mayús+Más + + + Ctrl+Restar + + + Ctrl+Mayús+Restar + + + Ctrl+Menos + + + Ctrl+Mayús+Menos + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/es/public.XamlLocalizableResources.es.resx b/src/Microsoft.Management.UI.Internal/resources/es/public.XamlLocalizableResources.es.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/es/public.XamlLocalizableResources.es.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/fr/public.GraphicalHostResources.fr.resx b/src/Microsoft.Management.UI.Internal/resources/fr/public.GraphicalHostResources.fr.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/fr/public.GraphicalHostResources.fr.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/fr/public.HelpWindowResources.fr.resx b/src/Microsoft.Management.UI.Internal/resources/fr/public.HelpWindowResources.fr.resx new file mode 100644 index 00000000000..90db56069d2 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/fr/public.HelpWindowResources.fr.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 + + + Annuler + + + Respecter la casse + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Description + + + Exemples + + + _Rechercher : + + + Sections d’aide + + + Aide de {0} + + + Entrées + + + {0} {1} + + + Méthodes + + + _Suivant + + + Aucune correspondance n’a été trouvée + + + Notes + + + OK + + + 1 correspondance + + + Sorties + + + Accepter les caractères génériques ? + + + Valeur par défaut + + + Accepter l'entrée de pipeline ? + + + Position ? + + + Obligatoire ? + + + Paramètres + + + _Précédent + + + Propriétés + + + RelatedLinks + + + Remarques + + + Options de recherche + + + Paramètres + + + {0} correspondances + + + Synopsis + + + Syntaxe + + + Aide pour {0} + {0} is the name of a cmdlet + + + Mot entier + + + {0} % + + + Zoom + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/fr/public.InvariantResources.fr.resx b/src/Microsoft.Management.UI.Internal/resources/fr/public.InvariantResources.fr.resx new file mode 100644 index 00000000000..b4ec0361fdf --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/fr/public.InvariantResources.fr.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. + + + Colonnes + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/fr/public.ShowCommandResources.fr.resx b/src/Microsoft.Management.UI.Internal/resources/fr/public.ShowCommandResources.fr.resx new file mode 100644 index 00000000000..1e55539465b --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/fr/public.ShowCommandResources.fr.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 + + + Annuler + + + Co_pier + + + _Run + + + Tout + + + Modules : + + +  ? + + + Aide + + + Paramètres communs + + + Erreurs + + + Paramètres pour « {0} » : + + + Nom : {0} +Module : {1} ({2}) + + + Les erreurs suivantes se sont produites lors de l’exécution de la commande : +{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 + + + Nom : + + + OK + + + ... + + + Nom de commande + + + Modules + + + <No module name> + + + Sélectionnez plusieurs valeurs pour « {0} » + + + Peut recevoir une valeur du pipeline + + + Commun à tous les jeux de paramètres + + + Obligatoire + + + Facultatif + + + Position : {0} + + + Type : {0} + + + Importé + + + Non importé + + + Afficher les détails + + + Nous ne pouvons pas importer le module requis par la commande « {0} ». Nom du module : « {1} ». Message d’erreur : « {2} ». + + + Pour importer le module « {0} » et ses cmdlets, y compris « {1} », cliquez {2}. + + + Commande « Show » – Erreur + + + Patientez... + + + Actualiser + + + Il n’existe aucun paramètre. + + + Cliquez après avoir utilisé « {0} » pour afficher les nouvelles commandes + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/fr/public.UICultureResources.fr.resx b/src/Microsoft.Management.UI.Internal/resources/fr/public.UICultureResources.fr.resx new file mode 100644 index 00000000000..a9e702b472c --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/fr/public.UICultureResources.fr.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 + + + Sélectionner des colonnes... + + + (aucun) + The group title for items within a column whose value is empty/null. + + + La valeur doit être de 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. + + + La sélection actuelle est vide. + The error validation string to present to the user when they have selected a value out of bounds. + + + contient + A filter rule that indicates a field must contain the specified value. + + + ne contient pas + A filter rule that indicates a field must not contain the specified value. + + + n’est pas égal à + A filter rule that indicates a field must not equal the specified value. + + + est égal à + A filter rule that indicates a field must equal the specified value. + + + est supérieur ou égal à + A filter rule that indicates a field must be greater than or equal to the specified value. + + + est compris entre + A filter rule that indicates a field must be between the specified values. + + + est vide + A filter rule that indicates a field must be empty. + + + n’est pas vide + A filter rule that indicates a field must not be empty. + + + est inférieur ou égal à + A filter rule that indicates a field must be less than or equal to the specified value. + + + se termine par + A filter rule that indicates a field must end with the specified value. + + + commence par + A filter rule that indicates a field must start with the specified value. + + + Retour + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Transférer + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + La valeur doit être une date valide au format suivant : {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + La valeur doit être un nombre valide. + + + Rechercher + 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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/fr/public.XamlLocalizableResources.fr.resx b/src/Microsoft.Management.UI.Internal/resources/fr/public.XamlLocalizableResources.fr.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/fr/public.XamlLocalizableResources.fr.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/it/public.GraphicalHostResources.it.resx b/src/Microsoft.Management.UI.Internal/resources/it/public.GraphicalHostResources.it.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/it/public.GraphicalHostResources.it.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/it/public.HelpWindowResources.it.resx b/src/Microsoft.Management.UI.Internal/resources/it/public.HelpWindowResources.it.resx new file mode 100644 index 00000000000..6a1d26784f4 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/it/public.HelpWindowResources.it.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 + + + Annulla + + + Corrispondenza maiuscole/minuscole + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Descrizione + + + Esempi + + + _Trova: + + + Sezioni della Guida + + + Guida di {0} + + + Input + + + {0} {1} + + + Metodi + + + _Avanti + + + Nessuna corrispondenza trovata + + + Note + + + OK + + + 1 corrispondenza + + + Output + + + Accettare caratteri jolly? + + + Valore predefinito + + + Accettare input da pipeline? + + + Posizione? + + + Obbligatorio? + + + Parametri + + + _Precedente + + + Proprietà + + + Collegamenti correlati + + + Note + + + Opzioni di ricerca + + + Impostazioni + + + {0} corrispondenze + + + Sinossi + + + Sintassi + + + Guida per {0} + {0} is the name of a cmdlet + + + Parola intera + + + {0}% + + + Zoom + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/it/public.InvariantResources.it.resx b/src/Microsoft.Management.UI.Internal/resources/it/public.InvariantResources.it.resx new file mode 100644 index 00000000000..3f4c8ff8b9f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/it/public.InvariantResources.it.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 + + + Non è possibile modificare direttamente {0}. Utilizzare invece {1}. + + + Colonne + + + {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} non supporta l'aggiunta alla raccolta di elementi. Utilizzare invece {1}. + + + Se la visualizzazione è impostata su {0}, il tipo deve essere {1}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/it/public.ShowCommandResources.it.resx b/src/Microsoft.Management.UI.Internal/resources/it/public.ShowCommandResources.it.resx new file mode 100644 index 00000000000..25c2e57944c --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/it/public.ShowCommandResources.it.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 + + + Annulla + + + Co_pia + + + _Esegui + + + Tutto + + + Moduli: + + + ? + + + Guida + + + Parametri comuni + + + Errori + + + Parametri per "{0}": + + + Nome: {0} +Modulo: {1} ({2}) + + + Durante l'esecuzione del comando si sono verificati gli errori seguenti: +{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 + + + Nome: + + + OK + + + ... + + + Nome comando + + + Moduli + + + <No module name> + + + Selezionare più valori per "{0}" + + + Può ricevere un valore dalla pipeline + + + Comune a tutti i set di parametri + + + Obbligatorio + + + Facoltativo + + + Posizione: {0} + + + Tipo: {0} + + + Importazione eseguita + + + Importazione non eseguita + + + Mostra dettagli + + + Importazione del modulo richiesto dal comando "{0}" non riuscita. Nome modulo: "{1}". Messaggio di errore: "{2}". + + + Per importare il modulo "{0}" e i relativi cmdlet, incluso "{1}", fare clic su {2}. + + + Mostra comando - Errore + + + Attendere... + + + Aggiorna + + + Non sono disponibili parametri. + + + Fare clic dopo aver usato "{0}" per vedere i nuovi comandi + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/it/public.UICultureResources.it.resx b/src/Microsoft.Management.UI.Internal/resources/it/public.UICultureResources.it.resx new file mode 100644 index 00000000000..774c8488f12 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/it/public.UICultureResources.it.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 + + + Seleziona colonne... + + + (nessuno) + The group title for items within a column whose value is empty/null. + + + Il valore deve essere di tipo {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. + + + La selezione corrente è vuota. + The error validation string to present to the user when they have selected a value out of bounds. + + + contiene + A filter rule that indicates a field must contain the specified value. + + + non contiene + A filter rule that indicates a field must not contain the specified value. + + + non uguale a + A filter rule that indicates a field must not equal the specified value. + + + uguale a + A filter rule that indicates a field must equal the specified value. + + + è maggiore o uguale a + A filter rule that indicates a field must be greater than or equal to the specified value. + + + è compreso tra + A filter rule that indicates a field must be between the specified values. + + + è vuoto + A filter rule that indicates a field must be empty. + + + non è vuoto + A filter rule that indicates a field must not be empty. + + + è minore o uguale a + A filter rule that indicates a field must be less than or equal to the specified value. + + + termina con + A filter rule that indicates a field must end with the specified value. + + + inizia con + A filter rule that indicates a field must start with the specified value. + + + Indietro + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Inoltra + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + Il valore deve essere una data valida nel formato seguente: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + Il valore deve essere un numero valido. + + + Cerca + 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+Aggiungi + + + Ctrl+MAIUSC+Aggiungi + + + Ctrl+Plus + + + Ctrl+MAIUSC+segno più + + + Ctrl+Sottrai + + + Ctrl+MAIUSC+Sottrai + + + Ctrl+segno meno + + + Ctrl+MAIUSC+segno meno + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/it/public.XamlLocalizableResources.it.resx b/src/Microsoft.Management.UI.Internal/resources/it/public.XamlLocalizableResources.it.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/it/public.XamlLocalizableResources.it.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ja/public.GraphicalHostResources.ja.resx b/src/Microsoft.Management.UI.Internal/resources/ja/public.GraphicalHostResources.ja.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ja/public.GraphicalHostResources.ja.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ja/public.HelpWindowResources.ja.resx b/src/Microsoft.Management.UI.Internal/resources/ja/public.HelpWindowResources.ja.resx new file mode 100644 index 00000000000..2d0a492d9ed --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ja/public.HelpWindowResources.ja.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 + + + キャンセル + + + 大文字と小文字を区別 + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + 説明 + + + + + + 検索(_F): + + + ヘルプ セクション + + + {0} ヘルプ + + + 入力 + + + {0} {1} + + + メソッド + + + 次へ(_N) + + + 一致するものが見つかりません + + + 注意 + + + OK + + + 1 件の一致 + + + 出力 + + + ワイルドカード文字の受け入れ? + + + 既定値 + + + パイプライン入力の受け入れ? + + + 位置? + + + 必須? + + + パラメーター + + + 前へ(_P) + + + プロパティ + + + RelatedLinks + + + 注釈 + + + 検索オプション + + + 設定 + + + {0} 件の一致 + + + 概要 + + + 構文 + + + {0} のヘルプ + {0} is the name of a cmdlet + + + 単語全体 + + + {0}% + + + ズーム + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ja/public.InvariantResources.ja.resx b/src/Microsoft.Management.UI.Internal/resources/ja/public.InvariantResources.ja.resx new file mode 100644 index 00000000000..93e3e359006 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ja/public.InvariantResources.ja.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} を直接変更することはできません。代わりに {1} を使用してください。 + + + + + + {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} は項目コレクションへの追加をサポートしていません。代わりに {1} を使用してください。 + + + If View is set to a {0}, it should have the type {1}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ja/public.ShowCommandResources.ja.resx b/src/Microsoft.Management.UI.Internal/resources/ja/public.ShowCommandResources.ja.resx new file mode 100644 index 00000000000..77db4bbd2db --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ja/public.ShowCommandResources.ja.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 + + + キャンセル + + + コピー(_P) + + + 実行(_R) + + + すべて + + + モジュール: + + + ? + + + ヘルプ + + + 共通パラメーター + + + エラー + + + "{0}" のパラメーター + + + 名前: {0} +モジュール: {1} ({2}) + + + コマンドの実行中に次のエラーが発生しました: +{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 + + + 名前: + + + OK + + + ... + + + コマンド名 + + + モジュール + + + <No module name> + + + "{0}" に複数の値を選択する + + + パイプラインから値を受け取ることができます + + + すべてのパラメーター セットに共通 + + + 必須 + + + オプション + + + 位置: {0} + + + 型: {0} + + + インポート済み + + + インポートされていません + + + 詳細を表示する + + + コマンド "{0}" で必要なモジュールをインポートできませんでした。モジュール名: "{1}"。エラー メッセージ: "{2}"。 + + + "{0}" モジュールとそのコマンドレット ("{1}" を含む) をインポートするには、[{2}] をクリックします。 + + + コマンドの表示 - エラー + + + お待ちください... + + + 最新の情報に更新 + + + パラメーターはありません。 + + + "{0}" を使用した後にクリックすると、新しいコマンドが表示されます + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ja/public.UICultureResources.ja.resx b/src/Microsoft.Management.UI.Internal/resources/ja/public.UICultureResources.ja.resx new file mode 100644 index 00000000000..08766cc91a2 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ja/public.UICultureResources.ja.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 + + + 列の選択... + + + (なし) + The group title for items within a column whose value is empty/null. + + + 値は、型 {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 error validation string to present to the user when they have selected a value out of bounds. + + + 次の値を含む + A filter rule that indicates a field must contain the specified value. + + + 次の値を含まない + A filter rule that indicates a field must not contain the specified value. + + + 次の値と等しくない + A filter rule that indicates a field must not equal the specified value. + + + 次の値と等しい + A filter rule that indicates a field must equal the specified value. + + + 次の値以上 + A filter rule that indicates a field must be greater than or equal to the specified value. + + + が次の範囲: + A filter rule that indicates a field must be between the specified values. + + + が空である + A filter rule that indicates a field must be empty. + + + が空ではない + A filter rule that indicates a field must not be empty. + + + 次の値以下 + A filter rule that indicates a field must be less than or equal to the specified value. + + + 次の値で終わる + A filter rule that indicates a field must end with the specified value. + + + 次の値で始まる + A filter rule that indicates a field must start with the specified value. + + + 戻る + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + 転送 + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + この値は、次の形式の有効な日付でなければなりません: {0}。 + {0} will be filled in with the culture appropriate ShortDatePattern + + + この値には有効な数値を指定してください。 + + + 検索 + 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 + プラス + + + CTRL + SHIFT + P + + + Ctrl + 減算 + + + Ctrl + Shift + 減算 + + + Ctrl + マイナス + + + Ctrl + Shift + マイナス + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ja/public.XamlLocalizableResources.ja.resx b/src/Microsoft.Management.UI.Internal/resources/ja/public.XamlLocalizableResources.ja.resx new file mode 100644 index 00000000000..b23115e35d8 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ja/public.XamlLocalizableResources.ja.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. + + + この列を検索 + 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 + + + クリックして検索クエリを保存 + + + 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 + + + 選択した列を、表示する列のリストに移動します + + + 選択した列を、表示しない列のリストに移動します + + + この列は削除できません。 + + + リストには、少なくとも 1 つの列を常に表示する必要があります。 + + + Selected columns + + + この列を検索 + + + Expand + + + クリックすると、フィルター条件がすべて消去されます。 + + + クリックすると、検索条件を追加できます。 + + + クリックすると、検索条件の表示が展開されます。 + + + 現在、保存されているクエリはありません。 + + + 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. + + + フィルター ウィンドウの展開/折りたたみ + 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. + + + クリックすると、保存されている検索クエリが表示されます。 + + + 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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ko/public.GraphicalHostResources.ko.resx b/src/Microsoft.Management.UI.Internal/resources/ko/public.GraphicalHostResources.ko.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ko/public.GraphicalHostResources.ko.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ko/public.HelpWindowResources.ko.resx b/src/Microsoft.Management.UI.Internal/resources/ko/public.HelpWindowResources.ko.resx new file mode 100644 index 00000000000..79b3226cfc2 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ko/public.HelpWindowResources.ko.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 + + + 취소 + + + 대/소문자 일치 + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + 설명 + + + 예시 + + + 찾기(_F): + + + 도움말 섹션 + + + {0} 도움말 + + + 입력 + + + {0} {1} + + + 방법 + + + 다음(_N) + + + 일치하는 항목을 찾을 수 없음 + + + 메모 + + + 확인 + + + 1개 일치 + + + 출력 + + + 와일드카드 문자 허용 + + + 기본값 + + + 파이프라인 입력 허용 + + + 위치 + + + 필수인가요? + + + 매개 변수 + + + 이전(_P) + + + 속성 + + + RelatedLinks + + + 설명 + + + 검색 옵션 + + + 설정 + + + {0}개가 일치합니다. + + + 시놉시스 + + + 구문 + + + {0}에 대한 도움말 + {0} is the name of a cmdlet + + + 단어 단위로 + + + {0}% + + + 확대/축소 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ko/public.InvariantResources.ko.resx b/src/Microsoft.Management.UI.Internal/resources/ko/public.InvariantResources.ko.resx new file mode 100644 index 00000000000..c6030c4a8cc --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ko/public.InvariantResources.ko.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}은(는) 직접 수정할 수 없습니다. 대신 {1}을(를) 사용하세요. + + + + + + {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}은(는) 항목 컬렉션에 대한 추가를 지원하지 않습니다. 대신 {1}을(를) 사용하세요. + + + 보기가 {0}(으)로 설정된 경우 {1} 유형이어야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ko/public.ShowCommandResources.ko.resx b/src/Microsoft.Management.UI.Internal/resources/ko/public.ShowCommandResources.ko.resx new file mode 100644 index 00000000000..c619c4f1906 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ko/public.ShowCommandResources.ko.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 + + + 취소 + + + Co_py + + + _Run + + + 모두 + + + 모듈: + + + ? + + + 도움말 + + + 공통 매개 변수 + + + 오류 + + + "{0}"에 대한 매개 변수: + + + 이름: {0} +모듈: {1} ({2}) + + + 명령을 실행하는 동안 다음 오류가 발생했습니다. +{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 + + + 이름: + + + 확인 + + + ... + + + 명령 이름 + + + 모듈 + + + <모듈 이름 없음> + + + "{0}"에 대해 여러 값을 선택합니다. + + + 파이프라인에서 값을 받을 수 있음 + + + 모든 매개 변수 집합에 공통 + + + 필수 + + + 선택 사항 + + + 위치: {0} + + + 형식: {0} + + + 가져옴 + + + 가져오지 않음 + + + 세부 정보 표시 + + + 명령 "{0}"에 필요한 모듈을 가져오지 못했습니다. 모듈 이름: "{1}". 오류 메시지: "{2}". + + + "{0}" 모듈과 "{1}"을(를) 포함한 해당 cmdlet을 가져오려면 {2}을(를) 클릭합니다. + + + 명령 표시 - 오류 + + + 기다려 주세요... + + + 새로 고침 + + + 매개 변수가 없습니다. + + + 새 명령을 보려면 “{0}”을(를) 사용한 후 클릭하세요. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ko/public.UICultureResources.ko.resx b/src/Microsoft.Management.UI.Internal/resources/ko/public.UICultureResources.ko.resx new file mode 100644 index 00000000000..1e1f252871f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ko/public.UICultureResources.ko.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 + + + 열 선택... + + + (없음) + The group title for items within a column whose value is empty/null. + + + 값은 {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 error validation string to present to the user when they have selected a value out of bounds. + + + 포함 + A filter rule that indicates a field must contain the specified value. + + + 다음 값을 포함하지 않음 + A filter rule that indicates a field must not contain the specified value. + + + 다음 값과 같지 않음 + A filter rule that indicates a field must not equal the specified value. + + + 같음 + A filter rule that indicates a field must equal the specified value. + + + 크거나 같음 + A filter rule that indicates a field must be greater than or equal to the specified value. + + + 다음 범위에 속함 + A filter rule that indicates a field must be between the specified values. + + + 비어 있음 + A filter rule that indicates a field must be empty. + + + 비어 있지 않음 + A filter rule that indicates a field must not be empty. + + + 작거나 같음 + A filter rule that indicates a field must be less than or equal to the specified value. + + + 다음 값으로 끝남 + A filter rule that indicates a field must end with the specified value. + + + 다음 값으로 시작 + A filter rule that indicates a field must start with the specified value. + + + 뒤로 + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + 전달 + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + 값은 {0} 형식의 유효한 날짜여야 합니다. + {0} will be filled in with the culture appropriate ShortDatePattern + + + 값은 올바른 숫자여야 합니다. + + + 검색 + 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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ko/public.XamlLocalizableResources.ko.resx b/src/Microsoft.Management.UI.Internal/resources/ko/public.XamlLocalizableResources.ko.resx new file mode 100644 index 00000000000..db87b4b364b --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ko/public.XamlLocalizableResources.ko.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 + + + 사용 가능한 열 + + + 추가 + + + 제거 + + + 선택한 열 + + + 뒤로 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 전달 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 이 열에서 찾기 + Background text shown in the search box. + + + 펼치기 + + + 이름 + + + 새 쿼리 + + + 작업 + This is the title string for the Task Pane. + + + 작업 + AutomationProperties.Name of a SeparatedList. + + + 확정되지 않은 진행률 아이콘 + + + 조건 추가 + + + 기존 쿼리를 덮어쓰거나 다른 이름을 입력하여 새 쿼리를 저장하세요. 각 쿼리는 조건, 정렬, 열 사용자 지정으로 구성됩니다. + + + 확인 + + + 취소 + + + 검색 쿼리를 저장하려면 클릭하십시오. + + + 사용 가능한 열 + + + >> + 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 + + + 위로 이동 + + + 아래로 이동 + + + 확인 + + + 취소 + + + 열 선택 + + + 선택한 열을 표시되는 열 목록으로 이동 + + + 선택한 열을 숨겨진 열 목록으로 이동 + + + 이 열은 제거할 수 없습니다. + + + 목록에 열을 하나 이상 표시해야 합니다. + + + 선택한 열 + + + 이 열에서 찾기 + + + 펼치기 + + + 모든 필터 조건을 지우려면 클릭하십시오. + + + 검색 조건을 추가하려면 클릭하십시오. + + + 검색 조건을 확장하려면 클릭하십시오. + + + 저장된 쿼리가 현재 없습니다. + + + 쿼리 + + + 삭제 + + + 이름 바꾸기 + + + {0} 규칙 + The text representation of a rule in the filter panel, displayed to accessibility clients. {0} will be the name of the rule. + + + 추가 + + + 취소 + + + 필터 조건 추가 + + + + The name for text input fields + + + <Empty> + + + 규칙 + The name of the panel which contains the filter rules + + + 삭제 + + + 쿼리 + + + 쿼리 + + + 검색 + + + ({0}/{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. + + + 검색 중... + 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. + + + 필터 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 필터 + + + 바로 가기 규칙 + The name used to indicate custom filter rules which are specific to a particular application. + + + 열 규칙 + The name used to indicate filter rules that are based upon the properties of the items in the list. + + + 문자 모양 정렬 + + + 문자 모양 정렬 + + + 접기 + + + 접기 + + + 오름차순 정렬 + The text used for the accessible ItemStatus property when a column is sorted ascending. + + + 내림차순 정렬 + The text used for the accessible ItemStatus property when a column is sorted descending. + + + 접기 + + + 펼치기 + + + 검색 + + + 취소 + + + 모두 선택 취소 + + + 모두 선택 취소 + + + 검색 텍스트 지우기 + + + 작업 + + + 검색 + The accessible name of the Search button in the filter panel. + + + 취소 + The accessible name of the Stop Search button in the filter panel. + + + 필터 창 확장 또는 축소 + The accessible name of the button that expands/collapses the filter panel. + + + 필터 + The background text of the list's search box when filtering is immediate. + + + 저장된 검색 쿼리를 표시하려면 클릭하십시오. + + + 필터가 적용되었습니다. + + + + 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. + + + + 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. + + + 또는 + 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. + + + 일치 항목이 없습니다. + The text displayed in the ManagementList when the filter has been applied but matching items were found. + + + 접기 + + + 펼치기 + + + 하위 항목 표시 + + + 하위 항목 표시 + + + {0}: {1} + The format string used for the ManagementList title when query has been applied. For example, "Users: My Fancy Query" + + + 취소 + + + 확인 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pl/public.GraphicalHostResources.pl.resx b/src/Microsoft.Management.UI.Internal/resources/pl/public.GraphicalHostResources.pl.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pl/public.GraphicalHostResources.pl.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pl/public.HelpWindowResources.pl.resx b/src/Microsoft.Management.UI.Internal/resources/pl/public.HelpWindowResources.pl.resx new file mode 100644 index 00000000000..1547b229bac --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pl/public.HelpWindowResources.pl.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 + + + Anuluj + + + Dopasuj wielkość liter + + + Typowe parametry + Name of a group of parameters common to all cmdlets + + + Opis + + + Przykłady + + + _Znajdź: + + + Sekcje Pomocy + + + {0} — Pomoc + + + Dane wejściowe + + + {0} {1} + + + Metody + + + _Dalej + + + Nie znaleziono dopasowań + + + Notatki + + + OK + + + 1 dopasowanie + + + Dane wyjściowe + + + Akceptować symbole wieloznaczne? + + + Wartość domyślna + + + Zaakceptować dane wejściowe potoku? + + + Lokalizacja? + + + Wymagany? + + + Parametry + + + _Wstecz + + + Właściwości + + + RelatedLinks + + + Uwagi + + + Opcje wyszukiwania + + + Ustawienia + + + {0} dopasowań + + + Synopsis + + + Składnia + + + Pomoc dotycząca {0} + {0} is the name of a cmdlet + + + Całe słowo + + + {0}% + + + Powiększanie + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pl/public.InvariantResources.pl.resx b/src/Microsoft.Management.UI.Internal/resources/pl/public.InvariantResources.pl.resx new file mode 100644 index 00000000000..e1c8b515ac0 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pl/public.InvariantResources.pl.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. + + + Kolumny + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pl/public.ShowCommandResources.pl.resx b/src/Microsoft.Management.UI.Internal/resources/pl/public.ShowCommandResources.pl.resx new file mode 100644 index 00000000000..73ffe7a6bd1 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pl/public.ShowCommandResources.pl.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 + + + Anuluj + + + Ko_piuj + + + _Uruchom + + + Wszystko + + + Moduły: + + + ? + + + Pomoc + + + Typowe parametry + + + Błędy + + + Parametry dla „{0}”: + + + Nazwa: {0} +Moduł: {1} ({2}) + + + Podczas uruchamiania polecenia wystąpiły następujące błędy: +{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 + + + Nazwa: + + + OK + + + ... + + + Nazwa polecenia + + + Moduły + + + <No module name> + + + Wybierz wiele wartości dla „{0}” + + + Może odbierać wartość z potoku + + + Wspólne dla wszystkich zestawów parametrów + + + Obowiązkowe + + + Opcjonalne + + + Pozycja: {0} + + + Typ: {0} + + + Zaimportowano + + + Nie zaimportowano + + + Pokaż szczegóły + + + Nie można zaimportować modułu wymaganego przez polecenie „{0}”. Nazwa modułu: „{1}”. Komunikat o błędzie: „{2}”. + + + Aby zaimportować moduł „{0}” i jego polecenia cmdlet, w tym „{1}”, kliknij pozycję {2}. + + + Pokaż polecenie – błąd + + + Czekaj... + + + Odśwież + + + Brak parametrów. + + + Kliknij po użyciu znaku „{0}”, aby wyświetlić nowe polecenia + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pl/public.UICultureResources.pl.resx b/src/Microsoft.Management.UI.Internal/resources/pl/public.UICultureResources.pl.resx new file mode 100644 index 00000000000..aa97338c019 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pl/public.UICultureResources.pl.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 + + + Wybierz kolumny… + + + (brak) + The group title for items within a column whose value is empty/null. + + + Wartość powinna być typem {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. + + + Bieżące zaznaczenie jest puste. + The error validation string to present to the user when they have selected a value out of bounds. + + + zawiera + A filter rule that indicates a field must contain the specified value. + + + nie zawiera + A filter rule that indicates a field must not contain the specified value. + + + nie równa się + A filter rule that indicates a field must not equal the specified value. + + + równa się + A filter rule that indicates a field must equal the specified value. + + + jest większe lub równe + A filter rule that indicates a field must be greater than or equal to the specified value. + + + jest pomiędzy + A filter rule that indicates a field must be between the specified values. + + + jest puste + A filter rule that indicates a field must be empty. + + + nie jest puste + A filter rule that indicates a field must not be empty. + + + jest mniejsze lub równe + A filter rule that indicates a field must be less than or equal to the specified value. + + + kończy się + A filter rule that indicates a field must end with the specified value. + + + rozpoczyna się + A filter rule that indicates a field must start with the specified value. + + + Do tyłu + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Do przodu + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + Wartość musi być prawidłową datą w następującym formacie: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + Wartość musi być prawidłową liczbą. + + + Wyszukaj + 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+Dodaj + + + Ctrl + Shift + Dodaj + + + Ctrl+Plus + + + Ctrl+Shift+Plus + + + Ctrl+Odejmowanie + + + Ctrl+Shift+Odejmowanie + + + Ctrl+Minus + + + Ctrl+Shift+Minus + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pl/public.XamlLocalizableResources.pl.resx b/src/Microsoft.Management.UI.Internal/resources/pl/public.XamlLocalizableResources.pl.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pl/public.XamlLocalizableResources.pl.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.GraphicalHostResources.pt-BR.resx b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.GraphicalHostResources.pt-BR.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.GraphicalHostResources.pt-BR.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.HelpWindowResources.pt-BR.resx b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.HelpWindowResources.pt-BR.resx new file mode 100644 index 00000000000..4c48e227f00 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.HelpWindowResources.pt-BR.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 + + + Cancelar + + + Match Case + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Descrição + + + 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 + + + Propriedades + + + RelatedLinks + + + Remarks + + + Search Options + + + Configurações + + + {0} matches + + + Synopsis + + + Syntax + + + Help for {0} + {0} is the name of a cmdlet + + + Whole Word + + + {0}% + + + Zoom + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.InvariantResources.pt-BR.resx b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.InvariantResources.pt-BR.resx new file mode 100644 index 00000000000..9c174b642fa --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.InvariantResources.pt-BR.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. + + + Colunas + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.ShowCommandResources.pt-BR.resx b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.ShowCommandResources.pt-BR.resx new file mode 100644 index 00000000000..626f0b31264 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.ShowCommandResources.pt-BR.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 + + + Todos + + + 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 + + + Obrigatório + + + Opcional + + + 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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.UICultureResources.pt-BR.resx b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.UICultureResources.pt-BR.resx new file mode 100644 index 00000000000..5dacc74283f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.UICultureResources.pt-BR.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 + + + Selecionar Colunas... + + + (nenhum) + The group title for items within a column whose value is empty/null. + + + O valor deve ser do tipo {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. + + + A seleção atual está vazia. + The error validation string to present to the user when they have selected a value out of bounds. + + + contém + A filter rule that indicates a field must contain the specified value. + + + não contém + A filter rule that indicates a field must not contain the specified value. + + + não é igual a + A filter rule that indicates a field must not equal the specified value. + + + é igual a + A filter rule that indicates a field must equal the specified value. + + + é maior que ou igual a + A filter rule that indicates a field must be greater than or equal to the specified value. + + + está entre + A filter rule that indicates a field must be between the specified values. + + + está vazio + A filter rule that indicates a field must be empty. + + + não está vazio + A filter rule that indicates a field must not be empty. + + + é menor que ou igual a + A filter rule that indicates a field must be less than or equal to the specified value. + + + termina com + A filter rule that indicates a field must end with the specified value. + + + começa com + A filter rule that indicates a field must start with the specified value. + + + Voltar + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Encaminhar + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + O valor deve ser uma data válida no seguinte formato: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + O valor deve ser um número válido. + + + Pesquisa + 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+Adicionar + + + Ctrl+Shift+Adicionar + + + Ctrl+Mais + + + Ctrl+Shift+Mais + + + Ctrl+Subtrair + + + Ctrl+Shift+Subtrair + + + Ctrl+Menos + + + Ctrl+Shift+Menos + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.XamlLocalizableResources.pt-BR.resx b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.XamlLocalizableResources.pt-BR.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/pt-BR/public.XamlLocalizableResources.pt-BR.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx b/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx index 0a86d51a82e..d4b7082b36b 100644 --- a/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx +++ b/src/Microsoft.Management.UI.Internal/resources/public.GraphicalHostResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx b/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx index 3bcab7bfb8a..1a6065ff769 100644 --- a/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx +++ b/src/Microsoft.Management.UI.Internal/resources/public.HelpWindowResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx b/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx index 62924692a43..64c8e33ccde 100644 --- a/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx +++ b/src/Microsoft.Management.UI.Internal/resources/public.InvariantResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx b/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx index 5853a0a3c01..dcb5aa9e44b 100644 --- a/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx +++ b/src/Microsoft.Management.UI.Internal/resources/public.ShowCommandResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx b/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx index 7f5730b3f86..de8b07134e2 100644 --- a/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx +++ b/src/Microsoft.Management.UI.Internal/resources/public.UICultureResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx b/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx index caff99962fd..f49fe3d90bf 100644 --- a/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx +++ b/src/Microsoft.Management.UI.Internal/resources/public.XamlLocalizableResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.Management.UI.Internal/resources/ru/public.GraphicalHostResources.ru.resx b/src/Microsoft.Management.UI.Internal/resources/ru/public.GraphicalHostResources.ru.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ru/public.GraphicalHostResources.ru.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ru/public.HelpWindowResources.ru.resx b/src/Microsoft.Management.UI.Internal/resources/ru/public.HelpWindowResources.ru.resx new file mode 100644 index 00000000000..9f47bf3eb63 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ru/public.HelpWindowResources.ru.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 + + + Отмена + + + Учитывать регистр + + + Общие параметры + Name of a group of parameters common to all cmdlets + + + Описание + + + Примеры + + + _Найти: + + + Разделы справки + + + {0}: справка + + + Входные данные + + + {0} {1} + + + Методы + + + _Далее + + + Совпадений не найдено + + + Заметки + + + ОК + + + 1 совпадение + + + Выходные данные + + + Принимать символы-шаблоны? + + + Значение по умолчанию + + + Принимать входные данные конвейера? + + + Позиция? + + + Обязательно? + + + Параметры + + + _Назад + + + Свойства + + + RelatedLinks + + + Примечания + + + Параметры поиска + + + Параметры + + + Совпадения: {0} + + + Описание + + + Синтаксис + + + Справка для {0} + {0} is the name of a cmdlet + + + Слово целиком + + + {0} % + + + Масштаб + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ru/public.InvariantResources.ru.resx b/src/Microsoft.Management.UI.Internal/resources/ru/public.InvariantResources.ru.resx new file mode 100644 index 00000000000..a14bccf0c61 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ru/public.InvariantResources.ru.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. + + + Столбцы + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ru/public.ShowCommandResources.ru.resx b/src/Microsoft.Management.UI.Internal/resources/ru/public.ShowCommandResources.ru.resx new file mode 100644 index 00000000000..bfc96767399 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ru/public.ShowCommandResources.ru.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 + + + Отменить + + + Ко_пировать + + + _Выполнить + + + Все + + + Модули: + + + ? + + + Справка + + + Общие параметры + + + Ошибки + + + Параметры для {0}: + + + Имя: {0} +Модуль: {1} ({2}) + + + При выполнении команды произошли следующие ошибки: +{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 + + + Имя: + + + ОК + + + ... + + + Имя команды + + + Модули + + + <Нет имени модуля> + + + Выберите несколько значений для {0} + + + Может принимать значение из конвейера + + + Общие для всех наборов параметров + + + Обязательно + + + Необязательно + + + Позиция: {0} + + + Тип: {0} + + + Импортировано + + + Не импортируется + + + Показать сведения + + + Не удалось импортировать модуль, необходимый для команды {0}. Имя модуля: {1}. Сообщение об ошибке: {2}. + + + Чтобы импортировать модуль {0} и его командлеты, включая {1}, щелкните {2}. + + + Показать команду — ошибка + + + Подождите... + + + Обновить + + + Параметров нет. + + + Щелкните после использования {0}, чтобы увидеть новые команды + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ru/public.UICultureResources.ru.resx b/src/Microsoft.Management.UI.Internal/resources/ru/public.UICultureResources.ru.resx new file mode 100644 index 00000000000..2c2f98e9143 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ru/public.UICultureResources.ru.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 + + + Выберите столбцы… + + + (нет) + The group title for items within a column whose value is empty/null. + + + Значение должно принадлежать типу {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 error validation string to present to the user when they have selected a value out of bounds. + + + содержит + A filter rule that indicates a field must contain the specified value. + + + не содержит + A filter rule that indicates a field must not contain the specified value. + + + не равно + A filter rule that indicates a field must not equal the specified value. + + + равно + A filter rule that indicates a field must equal the specified value. + + + больше или равно + A filter rule that indicates a field must be greater than or equal to the specified value. + + + между + A filter rule that indicates a field must be between the specified values. + + + пусто + A filter rule that indicates a field must be empty. + + + не пусто + A filter rule that indicates a field must not be empty. + + + меньше или равно + A filter rule that indicates a field must be less than or equal to the specified value. + + + заканчивается на + A filter rule that indicates a field must end with the specified value. + + + начинается с + A filter rule that indicates a field must start with the specified value. + + + Назад + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + Переадресовать + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + Значением должна быть допустимая дата в следующем формате: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + Значение должно быть допустимым числом. + + + Поиск + 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+ДОБАВИТЬ + + + CTRL+SHIFT+A + + + CTRL+ПЛЮС + + + CTRL+SHIFT+ПЛЮС + + + CTRL+ВЫЧЕСТЬ + + + CTRL+SHIFT+ВЫЧЕСТЬ + + + CTRL+МИНУС + + + CTRL + SHIFT + МИНУС + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/ru/public.XamlLocalizableResources.ru.resx b/src/Microsoft.Management.UI.Internal/resources/ru/public.XamlLocalizableResources.ru.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/ru/public.XamlLocalizableResources.ru.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/tr/public.GraphicalHostResources.tr.resx b/src/Microsoft.Management.UI.Internal/resources/tr/public.GraphicalHostResources.tr.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/tr/public.GraphicalHostResources.tr.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/tr/public.HelpWindowResources.tr.resx b/src/Microsoft.Management.UI.Internal/resources/tr/public.HelpWindowResources.tr.resx new file mode 100644 index 00000000000..918505d0751 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/tr/public.HelpWindowResources.tr.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 + + + İptal + + + Büyük/Küçük Harf Eşleştirin + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + Açıklama + + + Örnekler + + + _Bul: + + + Yardım bölümleri + + + {0} Yardım + + + Girişler + + + {0} {1} + + + Metotlar + + + _İleri + + + Eşleşme bulunamadı + + + Notlar + + + Tamam + + + 1 eşleşme + + + Çıkışlar + + + Joker karakterler kabul edilsin mi? + + + Varsayılan değer + + + Ardışık düzen girişi kabul edilsin mi? + + + Konum? + + + Gerekli mi? + + + Parametreler + + + _Önceki + + + Özellikler + + + İlgili Bağlantılar + + + Açıklamalar + + + Arama Seçenekleri + + + Ayarlar + + + {0} eşleşme. + + + Özet + + + Söz Dizimi + + + + {0} yardımı + {0} is the name of a cmdlet + + + Tüm Sözcük + + + %{0} + + + Zoom + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/tr/public.InvariantResources.tr.resx b/src/Microsoft.Management.UI.Internal/resources/tr/public.InvariantResources.tr.resx new file mode 100644 index 00000000000..f6b61cb6b86 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/tr/public.InvariantResources.tr.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. + + + Sütunlar + + + {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}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/tr/public.ShowCommandResources.tr.resx b/src/Microsoft.Management.UI.Internal/resources/tr/public.ShowCommandResources.tr.resx new file mode 100644 index 00000000000..2834b96490f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/tr/public.ShowCommandResources.tr.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 + + + İptal + + + Kop_yala + + + _Çalıştır + + + Tümü + + + Modüller: + + + ? + + + Yardım + + + Ortak Parametreler + + + Hatalar + + + "{0}" parametreleri: + + + Ad: {0} +Modül: {1} ({2}) + + + Komut çalıştırılırken aşağıdaki hatalar oluştu: +{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 + + + Ad: + + + Tamam + + + ... + + + Komut Adı + + + Modüller + + + <Modül adı yok> + + + "{0}" için birden çok değer seçin + + + İşlem hattından değer alabilir + + + Tüm parametre kümeleri için ortak + + + Zorunlu + + + İsteğe bağlı + + + Konum: {0} + + + Tür: {0} + + + İçeri aktarıldı + + + İçeri Aktarılmadı + + + Ayrıntıları Göster + + + "{0}" komutu için gereken modül içeri aktarılamadı. Modül adı: "{1}". Hata iletisi: "{2}". + + + "{0}" modülünü ve "{1}" dahil cmdlet'lerini içeri aktarmak için {2} seçeneğine tıklayın. + + + Komutu Göster - Hata + + + Lütfen Bekleyin... + + + Yenile + + + Parametre yok. + + + Yeni komutları görmek için "{0}" kullandıktan sonra tıklayın + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/tr/public.UICultureResources.tr.resx b/src/Microsoft.Management.UI.Internal/resources/tr/public.UICultureResources.tr.resx new file mode 100644 index 00000000000..24d7a72fcaf --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/tr/public.UICultureResources.tr.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 + + + Sütunları seç... + + + (hiçbiri) + The group title for items within a column whose value is empty/null. + + + Değer {0} Türünde olmalıdır. + 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. + + + Geçerli seçim boş. + The error validation string to present to the user when they have selected a value out of bounds. + + + içerir + A filter rule that indicates a field must contain the specified value. + + + içermez + A filter rule that indicates a field must not contain the specified value. + + + eşit değildir + A filter rule that indicates a field must not equal the specified value. + + + eşittir + A filter rule that indicates a field must equal the specified value. + + + şundan büyüktür veya şuna eşittir: + A filter rule that indicates a field must be greater than or equal to the specified value. + + + arasında + A filter rule that indicates a field must be between the specified values. + + + boş + A filter rule that indicates a field must be empty. + + + boş değil + A filter rule that indicates a field must not be empty. + + + şundan küçüktür veya şuna eşittir: + A filter rule that indicates a field must be less than or equal to the specified value. + + + ile biter + A filter rule that indicates a field must end with the specified value. + + + ile başlar + A filter rule that indicates a field must start with the specified value. + + + Geri + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + İlet + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + Değerin şu biçimde geçerli bir tarih olması gerekir: {0}. + {0} will be filled in with the culture appropriate ShortDatePattern + + + Değerin geçerli bir sayı olması gerekir. + + + Arama + 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+Ekle + + + Ctrl+Shift+Ekle + + + Ctrl+Artı + + + Ctrl+Shift+Artı + + + Ctrl+Çıkar + + + Ctrl+Shift+Çıkar + + + Ctrl+Eksi + + + Ctrl+Shift+Eksi + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/tr/public.XamlLocalizableResources.tr.resx b/src/Microsoft.Management.UI.Internal/resources/tr/public.XamlLocalizableResources.tr.resx new file mode 100644 index 00000000000..2231ee4929a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/tr/public.XamlLocalizableResources.tr.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.GraphicalHostResources.zh-Hans.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.GraphicalHostResources.zh-Hans.resx new file mode 100644 index 00000000000..50295450d9a --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.GraphicalHostResources.zh-Hans.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 对象 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.HelpWindowResources.zh-Hans.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.HelpWindowResources.zh-Hans.resx new file mode 100644 index 00000000000..87597dd0e8f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.HelpWindowResources.zh-Hans.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 + + + 取消 + + + 区分大小写 + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + 说明 + + + 示例 + + + 查找(_F): + + + 帮助部分 + + + {0} 帮助 + + + 输入 + + + {0} {1} + + + 方法 + + + 下一步(_N) + + + 找不到匹配项 + + + 备注 + + + 确定 + + + 1 个匹配项 + + + 输出 + + + 接受通配符? + + + 默认值 + + + 接受管道输入? + + + 位置? + + + 必需? + + + 参数 + + + 上一步(_P) + + + 属性 + + + RelatedLinks + + + 备注 + + + 搜索选项 + + + 设置 + + + {0} 个匹配项 + + + 摘要 + + + 语法 + + + {0}的帮助 + {0} is the name of a cmdlet + + + 全字匹配 + + + {0}% + + + 放大 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.InvariantResources.zh-Hans.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.InvariantResources.zh-Hans.resx new file mode 100644 index 00000000000..ba5290cebca --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.InvariantResources.zh-Hans.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},请改用 {1}。 + + + + + + {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} 不支持添加到项目集合,请改用 {1}。 + + + If View is set to a {0}, it should have the type {1}. + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.ShowCommandResources.zh-Hans.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.ShowCommandResources.zh-Hans.resx new file mode 100644 index 00000000000..519214001ba --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.ShowCommandResources.zh-Hans.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 + + + 取消 + + + 复制(_P) + + + 运行(_R) + + + 全部 + + + 模块: + + + ? + + + 帮助 + + + 通用参数 + + + 错误 + + + "{0}" 的参数: + + + 名称: {0} +模块: {1} ({2}) + + + 运行命令时出现以下错误: +{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 + + + 名称: + + + 确定 + + + ... + + + 命令名称 + + + 模块 + + + <没有模块名称> + + + 为 "{0}" 选择多个值 + + + 可以从管道接收值 + + + 对所有参数集通用 + + + 强制 + + + 可选 + + + 位置: {0} + + + 类型: {0} + + + 已导入 + + + 未导入 + + + 显示详细信息 + + + 未能导入命令 "{0}" 所需的模块。模块名称: "{1}"。错误消息:“{2}”。 + + + 若要导入 "{0}" 模块及其 cmdlet (包括 "{1}"),请单击 {2}。 + + + 显示命令 - 错误 + + + 请稍候... + + + 刷新 + + + 没有参数。 + + + 使用 "{0}" 后单击可查看新命令 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.UICultureResources.zh-Hans.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.UICultureResources.zh-Hans.resx new file mode 100644 index 00000000000..5989d363c2f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.UICultureResources.zh-Hans.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 + + + 选择列... + + + (无) + The group title for items within a column whose value is empty/null. + + + 值应为类型 {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 error validation string to present to the user when they have selected a value out of bounds. + + + 包含 + A filter rule that indicates a field must contain the specified value. + + + 不包含 + A filter rule that indicates a field must not contain the specified value. + + + 不等于 + A filter rule that indicates a field must not equal the specified value. + + + 等于 + A filter rule that indicates a field must equal the specified value. + + + 大于或等于 + A filter rule that indicates a field must be greater than or equal to the specified value. + + + 介于 + A filter rule that indicates a field must be between the specified values. + + + 为空 + A filter rule that indicates a field must be empty. + + + 不为空 + A filter rule that indicates a field must not be empty. + + + 小于或等于 + A filter rule that indicates a field must be less than or equal to the specified value. + + + 结尾为 + A filter rule that indicates a field must end with the specified value. + + + 开头为 + A filter rule that indicates a field must start with the specified value. + + + 返回 + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + 前进 + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + 该值必须是以下格式的有效日期: {0}。 + {0} will be filled in with the culture appropriate ShortDatePattern + + + 该值必须是有效数字。 + + + 搜索 + 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+小键盘加号 + + + Ctrl+Shift+小键盘加号 + + + Ctrl+主键盘加号 + + + Ctrl+Shift+主键盘加号 + + + Ctrl+小键盘减号 + + + Ctrl+Shift+小键盘减号 + + + Ctrl+主键盘减号 + + + Ctrl+Shift+主键盘减号 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.XamlLocalizableResources.zh-Hans.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.XamlLocalizableResources.zh-Hans.resx new file mode 100644 index 00000000000..c6f05733025 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hans/public.XamlLocalizableResources.zh-Hans.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 + + + 可用列 + + + 添加 + + + 移除 + + + 所选列 + + + 返回 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 前进 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 在此列中查找 + Background text shown in the search box. + + + 展开 + + + 名称 + + + 新查询 + + + 任务 + This is the title string for the Task Pane. + + + 任务 + AutomationProperties.Name of a SeparatedList. + + + 未定进度图标 + + + 添加条件 + + + 覆盖现有查询,或键入其他名称以保存新查询。每个查询都由条件、排序和列自定义项组成。 + + + 确定 + + + 取消 + + + 单击以保存搜索查询 + + + 可用列 + + + >> + 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 + + + 上移 + + + 下移 + + + 确定 + + + 取消 + + + 选择列 + + + 将选定列移到可视列的列表中 + + + 将选定列移到隐藏列的列表中 + + + 此列可能无法删除。 + + + 此列表必须始终显示至少一列。 + + + 所选列 + + + 在此列中查找 + + + 展开 + + + 单击以清除所有筛选条件。 + + + 单击以添加搜索条件。 + + + 单击以展开搜索条件。 + + + 当前没有保存的查询。 + + + 查询 + + + 删除 + + + 重命名 + + + “{0}”规则 + The text representation of a rule in the filter panel, displayed to accessibility clients. {0} will be the name of the rule. + + + 添加 + + + 取消 + + + 添加筛选器条件 + + + + The name for text input fields + + + <Empty> + + + 规则 + The name of the panel which contains the filter rules + + + 删除 + + + 查询 + + + 查询 + + + 搜索 + + + (第 {0} 个,共 {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. + + + 正在搜索... + 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. + + + 筛选器 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 筛选器 + + + 快捷方式规则 + The name used to indicate custom filter rules which are specific to a particular application. + + + 列规则 + The name used to indicate filter rules that are based upon the properties of the items in the list. + + + 排序字形 + + + 排序字形 + + + 折叠 + + + 折叠 + + + 已按升序排序 + The text used for the accessible ItemStatus property when a column is sorted ascending. + + + 已按降序排序 + The text used for the accessible ItemStatus property when a column is sorted descending. + + + 折叠 + + + 展开 + + + 搜索 + + + 取消 + + + 全部清除 + + + 全部清除 + + + 清除搜索文本 + + + 任务 + + + 搜索 + The accessible name of the Search button in the filter panel. + + + 取消 + The accessible name of the Stop Search button in the filter panel. + + + 展开或折叠筛选器面板 + The accessible name of the button that expands/collapses the filter panel. + + + 筛选器 + The background text of the list's search box when filtering is immediate. + + + 单击以显示已保存的搜索查询。 + + + 已应用筛选器。 + + + + 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. + + + + 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. + + + + 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. + + + 未找到匹配项。 + The text displayed in the ManagementList when the filter has been applied but matching items were found. + + + 折叠 + + + 展开 + + + 显示子项 + + + 显示子项 + + + {0}: {1} + The format string used for the ManagementList title when query has been applied. For example, "Users: My Fancy Query" + + + 取消 + + + 确定 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.GraphicalHostResources.zh-Hant.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.GraphicalHostResources.zh-Hant.resx new file mode 100644 index 00000000000..2d6df859c89 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.GraphicalHostResources.zh-Hant.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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.HelpWindowResources.zh-Hant.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.HelpWindowResources.zh-Hant.resx new file mode 100644 index 00000000000..2d5789a5b0d --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.HelpWindowResources.zh-Hant.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 + + + 取消 + + + 區分大小寫 + + + CommonParameters + Name of a group of parameters common to all cmdlets + + + 描述 + + + 範例 + + + 尋找(_F): + + + 說明區段 + + + {0} 說明 + + + 輸入 + + + {0} {1} + + + 方法 + + + 下一步(_N) + + + 找不到相符的項目 + + + 備註 + + + 確定 + + + 1 個相符項目 + + + 輸出 + + + 接受萬用字元? + + + 預設值 + + + 接受管線輸入? + + + 位置? + + + 是否為必要? + + + 參數 + + + 上一步(_P) + + + 屬性 + + + RelatedLinks + + + 備註 + + + 搜尋選項 + + + 設定 + + + {0} 個相符項目 + + + 概要 + + + 語法 + + + {0} 的說明 + {0} is the name of a cmdlet + + + 全字拼寫須相符 + + + {0}% + + + 縮放 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.InvariantResources.zh-Hant.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.InvariantResources.zh-Hant.resx new file mode 100644 index 00000000000..e7005b49d57 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.InvariantResources.zh-Hant.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},請改為使用 {1}。 + + + 資料行 + + + {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} 不支援新增至項目集合,請改為使用 {1}。 + + + 若將檢視設為 {0},則應該有類型 {1}。 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.ShowCommandResources.zh-Hant.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.ShowCommandResources.zh-Hant.resx new file mode 100644 index 00000000000..64961a1451b --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.ShowCommandResources.zh-Hant.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 + + + 取消 + + + 複製(_P) + + + 執行(_R) + + + 全部 + + + 模組: + + + + + + 說明 + + + 一般參數 + + + 錯誤 + + + "{0}" 的參數: + + + 名稱: {0} +模組: {1} ({2}) + + + 執行命令時發生下列錯誤: +{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 + + + 名稱: + + + 確定 + + + ... + + + 命令名稱 + + + 模組 + + + <無模組名稱> + + + 選取 “{0}” 的多個值 + + + 可從管線接收值 + + + 通用於所有參數集合 + + + 強制 + + + 選擇性 + + + 位置: {0} + + + 類型: {0} + + + 已匯入 + + + 尚未匯入 + + + 顯示詳細資料 + + + 無法匯入命令 “{0}” 所需的模組。模組名稱: "{1}"。錯誤訊息: "{2}"。 + + + 若要匯入 “{0}” 模組及其 Cmdlet (包括"{1}"),請按一下 {2}。 + + + 顯示命令 - 錯誤 + + + 請稍候... + + + 重新整理 + + + 沒有參數。 + + + 在使用 "{0}" 來查看新命令之後按一下 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.UICultureResources.zh-Hant.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.UICultureResources.zh-Hant.resx new file mode 100644 index 00000000000..9f92a52d0b4 --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.UICultureResources.zh-Hant.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 + + + 選取資料行... + + + (無) + The group title for items within a column whose value is empty/null. + + + 值的類型必須是 {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 error validation string to present to the user when they have selected a value out of bounds. + + + 包含 + A filter rule that indicates a field must contain the specified value. + + + 不包含 + A filter rule that indicates a field must not contain the specified value. + + + 不等於 + A filter rule that indicates a field must not equal the specified value. + + + 等於 + A filter rule that indicates a field must equal the specified value. + + + 大於或等於 + A filter rule that indicates a field must be greater than or equal to the specified value. + + + 介於 + A filter rule that indicates a field must be between the specified values. + + + 為空白 + A filter rule that indicates a field must be empty. + + + 並非空白 + A filter rule that indicates a field must not be empty. + + + 小於或等於 + A filter rule that indicates a field must be less than or equal to the specified value. + + + 結尾為 + A filter rule that indicates a field must end with the specified value. + + + 開頭為 + A filter rule that indicates a field must start with the specified value. + + + 返回 + The text representing the tool tip and help text for the Back Button in the Back Forward History control when the button is disabled + + + 下一步 + The text representing the tool tip and help text for the Forward Button in the Back Forward History control when the button is disabled + + + 此值必須是下列格式的有效日期: {0}。 + {0} will be filled in with the culture appropriate ShortDatePattern + + + 值必須為有效的數字。 + + + 搜尋 + 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 + + \ No newline at end of file diff --git a/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.XamlLocalizableResources.zh-Hant.resx b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.XamlLocalizableResources.zh-Hant.resx new file mode 100644 index 00000000000..ded9075794f --- /dev/null +++ b/src/Microsoft.Management.UI.Internal/resources/zh-Hant/public.XamlLocalizableResources.zh-Hant.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 + + + 可用的資料行 + + + 新增 + + + 移除 + + + 選取的資料行 + + + 返回 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 向前 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 在此資料行中尋找 + Background text shown in the search box. + + + 展開 + + + 名稱 + + + 新查詢 + + + 工作 + This is the title string for the Task Pane. + + + 工作 + AutomationProperties.Name of a SeparatedList. + + + 不確定的進度圖示 + + + 新增準則 + + + 覆寫現有查詢,或輸入其他名稱以儲存新查詢。每個查詢需包含準則、排序及欄自訂。 + + + 確定 + + + 取消 + + + 按一下以儲存搜尋查詢 + + + 可用的資料行 + + + >> + 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 + + + 上移 + + + 下移 + + + 確定 + + + 取消 + + + 選取資料行 + + + 將選取的欄移到可見欄清單 + + + 將選取的資料行移到隱藏欄清單 + + + 此資料行不可移除。 + + + 清單必須永遠顯示至少一個資料行。 + + + 選取的資料行 + + + 在此資料行中尋找 + + + 展開 + + + 按一下以清除所有的篩選器條件。 + + + 按一下以新增搜尋準則。 + + + 按一下以展開搜尋準則。 + + + 目前沒有儲存的查詢。 + + + 查詢 + + + 刪除 + + + 重新命名 + + + {0} 項規則 + The text representation of a rule in the filter panel, displayed to accessibility clients. {0} will be the name of the rule. + + + 新增 + + + 取消 + + + 新增篩選準則 + + + + The name for text input fields + + + <空白> + + + 規則 + The name of the panel which contains the filter rules + + + 刪除 + + + 查詢 + + + 查詢 + + + 搜尋 + + + ({1} 之 {0}) + 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. + + + 正在搜尋... + 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. + + + 篩選 + Localizable AutomationName for control that is used by accessibility screen readers. + + + 篩選 + + + 快速鍵規則 + The name used to indicate custom filter rules which are specific to a particular application. + + + 資料行規則 + The name used to indicate filter rules that are based upon the properties of the items in the list. + + + 排序字符 + + + 排序字符 + + + 摺疊 + + + 摺疊 + + + 已遞增排序 + The text used for the accessible ItemStatus property when a column is sorted ascending. + + + 已遞減排序 + The text used for the accessible ItemStatus property when a column is sorted descending. + + + 摺疊 + + + 展開 + + + 搜尋 + + + 取消 + + + 全部清除 + + + 全部清除 + + + 清除搜尋文字 + + + 工作 + + + 搜尋 + The accessible name of the Search button in the filter panel. + + + 取消 + The accessible name of the Stop Search button in the filter panel. + + + 展開或摺疊篩選面板 + The accessible name of the button that expands/collapses the filter panel. + + + 篩選 + The background text of the list's search box when filtering is immediate. + + + 按一下以顯示儲存的搜尋查詢。 + + + 已套用篩選。 + + + + 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. + + + + 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. + + + + 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. + + + 找不到相符項目。 + The text displayed in the ManagementList when the filter has been applied but matching items were found. + + + 摺疊 + + + 展開 + + + 顯示子系 + + + 顯示子系 + + + {0}: {1} + The format string used for the ManagementList title when query has been applied. For example, "Users: My Fancy Query" + + + 取消 + + + 確定 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs index fb788b4d26c..dfe046ec8ca 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/CommonUtils.cs @@ -40,12 +40,12 @@ uint dwFlags [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) + public static uint FormatMessageFromModule(uint lastError, string moduleName, out string msg) { Debug.Assert(!string.IsNullOrEmpty(moduleName)); uint formatError = 0; - msg = String.Empty; + msg = string.Empty; IntPtr moduleHandle = LoadLibraryEx(moduleName, IntPtr.Zero, LOAD_LIBRARY_AS_DATAFILE); if (moduleHandle == IntPtr.Zero) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs deleted file mode 100644 index 5d57816c0e7..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CoreCLR/Stubs.cs +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#if CORECLR - -namespace System.Diagnostics -{ - /// - /// Indicates whether the performance counter category can have multiple instances. - /// - /// 1 - public enum PerformanceCounterCategoryType - { - /// - /// The instance functionality for the performance counter category is unknown. - /// - Unknown = -1, - - /// - /// The performance counter category can have only a single instance. - /// - SingleInstance, - - /// - /// The performance counter category can have multiple instances. - /// - MultiInstance - } - - /// - /// Specifies the formula used to calculate the - /// method for a instance. - /// - /// 2 - public enum PerformanceCounterType - { - /// - /// An instantaneous counter that shows the most recently observed value. - /// Used, for example, to maintain a simple count of items or operations. - /// - NumberOfItems32 = 65536, - - /// - /// An instantaneous counter that shows the most recently observed value. - /// Used, for example, to maintain a simple count of a very large number - /// of items or operations. It is the same as NumberOfItems32 except that - /// it uses larger fields to accommodate larger values. - /// - NumberOfItems64 = 65792, - - /// - /// An instantaneous counter that shows the most recently observed value - /// in hexadecimal format. Used, for example, to maintain a simple count - /// of items or operations. - NumberOfItemsHEX32 = 0, - - /// - /// An instantaneous counter that shows the most recently observed value. - /// Used, for example, to maintain a simple count of a very large number - /// of items or operations. It is the same as NumberOfItemsHEX32 except - /// that it uses larger fields to accommodate larger values. - /// - NumberOfItemsHEX64 = 256, - - /// - /// A difference counter that shows the average number of operations completed - /// during each second of the sample interval. Counters of this type measure - /// time in ticks of the system clock. - RateOfCountsPerSecond32 = 272696320, - - /// - /// A difference counter that shows the average number of operations completed - /// during each second of the sample interval. Counters of this type measure - /// time in ticks of the system clock. This counter type is the same as the - /// RateOfCountsPerSecond32 type, but it uses larger fields to accommodate - /// larger values to track a high-volume number of items or operations per - /// second, such as a byte-transmission rate. - /// - RateOfCountsPerSecond64 = 272696576, - - /// - /// An average counter designed to monitor the average length of a queue - /// to a resource over time. It shows the difference between the queue - /// lengths observed during the last two sample intervals divided by the - /// duration of the interval. This type of counter is typically used to - /// track the number of items that are queued or waiting. - /// - CountPerTimeInterval32 = 4523008, - - /// - /// An average counter that monitors the average length of a queue to a - /// resource over time. Counters of this type display the difference - /// between the queue lengths observed during the last two sample intervals, - /// divided by the duration of the interval. This counter type is the same - /// as CountPerTimeInterval32 except that it uses larger fields to - /// accommodate larger values. This type of counter is typically used - /// to track a high-volume or very large number of items that are queued or waiting. - /// - CountPerTimeInterval64 = 4523264, - - /// - /// An instantaneous percentage counter that shows the ratio of a subset - /// to its set as a percentage. For example, it compares the number of bytes - /// in use on a disk to the total number of bytes on the disk. - /// Counters of this type display the current percentage only, not an average - /// over time. - /// - RawFraction = 537003008, - - /// - /// A base counter that stores the denominator of a counter that presents a - /// general arithmetic fraction. Check that this value is greater than zero - /// before using it as the denominator in a RawFraction value calculation. - /// - RawBase = 1073939459, - - /// - /// An average counter that measures the time it takes, on average, to - /// complete a process or operation. Counters of this type display a - /// ratio of the total elapsed time of the sample interval to the number - /// of processes or operations completed during that time. This counter - /// type measures time in ticks of the system clock. - /// - AverageTimer32 = 805438464, - - /// - /// A base counter that is used in the calculation of time or count averages, - /// such as AverageTimer32 and AverageCount64. Stores the denominator for - /// calculating a counter to present "time per operation" or "count per operation". - /// - AverageBase = 1073939458, - - /// - /// An average counter that shows how many items are processed, on average, - /// during an operation. Counters of this type display a ratio of the items - /// processed to the number of operations completed. The ratio is calculated - /// by comparing the number of items processed during the last interval to - /// the number of operations completed during the last interval. - /// - AverageCount64 = 1073874176, - - /// - /// A percentage counter that shows the average ratio of hits to all - /// operations during the last two sample intervals. - /// - SampleFraction = 549585920, - - /// - /// An average counter that shows the average number of operations completed - /// in one second. When a counter of this type samples the data, each sampling - /// interrupt returns one or zero. The counter data is the number of ones that - /// were sampled. It measures time in units of ticks of the system performance timer. - /// - SampleCounter = 4260864, - - /// - /// A base counter that stores the number of sampling interrupts taken - /// and is used as a denominator in the sampling fraction. The sampling - /// fraction is the number of samples that were 1 (or true) for a sample - /// interrupt. Check that this value is greater than zero before using - /// it as the denominator in a calculation of SampleFraction. - /// - SampleBase = 1073939457, - - /// - /// A percentage counter that shows the average time that a component is - /// active as a percentage of the total sample time. - /// - CounterTimer = 541132032, - - /// - /// A percentage counter that displays the average percentage of active - /// time observed during sample interval. The value of these counters is - /// calculated by monitoring the percentage of time that the service was - /// inactive and then subtracting that value from 100 percent. - /// - CounterTimerInverse = 557909248, - - /// A percentage counter that shows the active time of a component - /// as a percentage of the total elapsed time of the sample interval. - /// It measures time in units of 100 nanoseconds (ns). Counters of this - /// type are designed to measure the activity of one component at a time. - /// - Timer100Ns = 542180608, - - /// - /// A percentage counter that shows the average percentage of active time - /// observed during the sample interval. - /// - Timer100NsInverse = 558957824, - - /// - /// A difference timer that shows the total time between when the component - /// or process started and the time when this value is calculated. - /// - ElapsedTime = 807666944, - - /// - /// A percentage counter that displays the active time of one or more - /// components as a percentage of the total time of the sample interval. - /// Because the numerator records the active time of components operating - /// simultaneously, the resulting percentage can exceed 100 percent. - /// - CounterMultiTimer = 574686464, - - /// - /// A percentage counter that shows the active time of one or more components - /// as a percentage of the total time of the sample interval. It derives - /// the active time by measuring the time that the components were not - /// active and subtracting the result from 100 percent by the number of - /// objects monitored. - /// - CounterMultiTimerInverse = 591463680, - - /// - /// A percentage counter that shows the active time of one or more components - /// as a percentage of the total time of the sample interval. It measures - /// time in 100 nanosecond (ns) units. - CounterMultiTimer100Ns = 575735040, - - /// - /// A percentage counter that shows the active time of one or more components - /// as a percentage of the total time of the sample interval. Counters of - /// this type measure time in 100 nanosecond (ns) units. They derive the - /// active time by measuring the time that the components were not active - /// and subtracting the result from multiplying 100 percent by the number - /// of objects monitored. - CounterMultiTimer100NsInverse = 592512256, - - /// - /// A base counter that indicates the number of items sampled. It is used - /// as the denominator in the calculations to get an average among the - /// items sampled when taking timings of multiple, but similar items. - /// Used with CounterMultiTimer, CounterMultiTimerInverse, CounterMultiTimer100Ns, - /// and CounterMultiTimer100NsInverse. - CounterMultiBase = 1107494144, - - /// - /// A difference counter that shows the change in the measured attribute - /// between the two most recent sample intervals. - /// - CounterDelta32 = 4195328, - - /// - /// A difference counter that shows the change in the measured attribute - /// between the two most recent sample intervals. It is the same as the - /// CounterDelta32 counter type except that is uses larger fields to - /// accomodate larger values. - CounterDelta64 = 4195584 - } -} -#endif diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs deleted file mode 100644 index cbebb9b4557..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/CounterFileInfo.cs +++ /dev/null @@ -1,57 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs deleted file mode 100644 index 9385e55909f..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ExportCounterCommand.cs +++ /dev/null @@ -1,383 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs index 4a6941cc13f..0122ad1941f 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetCounterCommand.cs @@ -248,7 +248,7 @@ protected override void ProcessRecord() break; default: - Debug.Fail(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + Debug.Fail(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); break; } } @@ -587,13 +587,14 @@ private List CombineMachinesAndCounterPaths() { foreach (string machine in ComputerName) { + string slashBeforePath = path.Length > 0 && path[0] == '\\' ? string.Empty : "\\"; if (machine.StartsWith("\\\\", StringComparison.OrdinalIgnoreCase)) { - retColl.Add(machine + "\\" + path); + retColl.Add(machine + slashBeforePath + path); } else { - retColl.Add("\\\\" + machine + "\\" + path); + retColl.Add("\\\\" + machine + slashBeforePath + path); } } } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs index 1a74da73d1c..0ce68a31d73 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventCommand.cs @@ -23,6 +23,9 @@ 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 { @@ -144,8 +147,8 @@ public sealed class GetWinEventCommand : PSCmdlet ValueFromPipelineByPropertyName = false, HelpMessageBaseName = "GetEventResources", HelpMessageResourceId = "MaxEventsParamHelp")] - [ValidateRange((Int64)1, Int64.MaxValue)] - public Int64 MaxEvents { get; set; } = -1; + [ValidateRange((long)1, long.MaxValue)] + public long MaxEvents { get; set; } = -1; /// /// ComputerName parameter. @@ -222,10 +225,6 @@ public sealed class GetWinEventCommand : PSCmdlet ValueFromPipelineByPropertyName = false, ParameterSetName = "XmlQuerySet", HelpMessageBaseName = "GetEventResources")] - [SuppressMessage("Microsoft.Design", "CA1059:MembersShouldNotExposeCertainConcreteTypes", - Scope = "member", - Target = "Microsoft.PowerShell.Commands.GetEvent.FilterXml", - Justification = "An XmlDocument is required here because that is the type Powershell supports")] public XmlDocument FilterXml { get; set; } /// @@ -393,7 +392,7 @@ protected override void ProcessRecord() break; default: - WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); break; } } @@ -489,7 +488,7 @@ private void ProcessGetProvider() foreach (string log in _providersByLogMap.Keys) { logQuery = new EventLogQuery(log, PathType.LogName, AddProviderPredicatesToFilter(_providersByLogMap[log])); - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Log {0} will be queried", log)); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Log {log} will be queried")); } } @@ -519,9 +518,11 @@ private void ProcessListLog() || (wildLogPattern.IsMatch(logName))) { + EventLogConfiguration logObj; + EventLogInformation logInfoObj; try { - EventLogConfiguration logObj = new(logName, eventLogSession); + logObj = new EventLogConfiguration(logName, eventLogSession); // // Skip direct channels matching the wildcard unless -Force is present. @@ -534,19 +535,25 @@ private void ProcessListLog() continue; } - EventLogInformation logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); - - PSObject outputObj = new(logObj); + bMatchFound = true; + logInfoObj = eventLogSession.GetLogInformation(logName, PathType.LogName); + } + catch (UnauthorizedAccessException exc) + { + string exceptionMsg = string.Format(CultureInfo.InvariantCulture, GetEventResources.LogInfoNoAccess, logName); + var newExc = new UnauthorizedAccessException(exceptionMsg, exc); - 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)); + string recommendationMsg = GetEventResources.SuggestElevation; + var eRecord = new ErrorRecord(newExc, "LogInfoNoAccess", ErrorCategory.PermissionDenied, logName) + { + ErrorDetails = new ErrorDetails(string.Empty) + { + RecommendedAction = recommendationMsg + } + }; - WriteObject(outputObj); - bMatchFound = true; + WriteError(eRecord); + continue; } catch (Exception exc) { @@ -557,6 +564,16 @@ private void ProcessListLog() WriteError(new ErrorRecord(outerExc, "LogInfoUnavailable", ErrorCategory.NotSpecified, null)); continue; } + + 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); } } @@ -677,7 +694,7 @@ private void ProcessFile() foreach (string resolvedPath in resolvedPaths) { _resolvedPaths.Add(resolvedPath); - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found file {0}", resolvedPath)); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found file {resolvedPath}")); } } @@ -777,7 +794,7 @@ private void ReadEvents(EventLogQuery logQuery) { using (EventLogReader readerObj = new(logQuery)) { - Int64 numEvents = 0; + long numEvents = 0; EventRecord evtObj = null; while (true) @@ -905,7 +922,7 @@ private string BuildStructuredQuery(EventLogSession eventLogSession) break; default: - WriteDebug(string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", ParameterSetName)); + WriteDebug(string.Create(CultureInfo.InvariantCulture, $"Invalid parameter set name: {ParameterSetName}")); break; } @@ -1184,8 +1201,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession // // Build xpath for // - Hashtable suppresshash = hash[hashkey_supress_lc] as Hashtable; - if (suppresshash != null) + if (hash[hashkey_supress_lc] is Hashtable suppresshash) { xpathStringSuppress = BuildXPathFromHashTable(suppresshash); } @@ -1252,8 +1268,7 @@ private string BuildStructuredQueryFromHashTable(EventLogSession eventLogSession private static string HandleEventIdHashValue(object value) { StringBuilder ret = new(); - Array idsArray = value as Array; - if (idsArray != null) + if (value is Array idsArray) { ret.Append('('); for (int i = 0; i < idsArray.Length; i++) @@ -1282,8 +1297,7 @@ private static string HandleEventIdHashValue(object value) private static string HandleLevelHashValue(object value) { StringBuilder ret = new(); - Array levelsArray = value as Array; - if (levelsArray != null) + if (value is Array levelsArray) { ret.Append('('); for (int i = 0; i < levelsArray.Length; i++) @@ -1311,11 +1325,10 @@ private static string HandleLevelHashValue(object value) // private string HandleKeywordHashValue(object value) { - Int64 keywordsMask = 0; - Int64 keywordLong = 0; + long keywordsMask = 0; + long keywordLong = 0; - Array keywordArray = value as Array; - if (keywordArray != null) + if (value is Array keywordArray) { foreach (object keyword in keywordArray) { @@ -1470,8 +1483,7 @@ private string HandleEndTimeHashValue(object value, Hashtable hash) private static string HandleDataHashValue(object value) { StringBuilder ret = new(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1501,8 +1513,7 @@ private static string HandleDataHashValue(object value) private static string HandleNamedDataHashValue(string key, object value) { StringBuilder ret = new(); - Array dataArray = value as Array; - if (dataArray != null) + if (value is Array dataArray) { ret.Append('('); for (int i = 0; i < dataArray.Length; i++) @@ -1609,7 +1620,7 @@ private bool ValidateLogName(string logName, EventLogSession eventLogSession) // Returns true and keyLong ref if successful. // Writes an error and returns false if keyString cannot be converted. // - private bool KeywordStringToInt64(string keyString, ref Int64 keyLong) + private bool KeywordStringToInt64(string keyString, ref long keyLong) { try { @@ -1749,8 +1760,7 @@ private void CheckHashTablesForNullValues() } else { - Array eltArray = value as Array; - if (eltArray != null) + if (value is Array eltArray) { foreach (object elt in eltArray) { @@ -2044,7 +2054,7 @@ private void FindProvidersByLogForWildcardPatterns(EventLogSession eventLogSessi || (wildProvPattern.IsMatch(provName))) { - WriteVerbose(string.Format(CultureInfo.InvariantCulture, "Found matching provider: {0}", provName)); + WriteVerbose(string.Create(CultureInfo.InvariantCulture, $"Found matching provider: {provName}")); AddLogsForProviderToInternalMap(eventLogSession, provName); bMatched = true; } diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs deleted file mode 100644 index df3835d9e18..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/GetEventSnapin.cs +++ /dev/null @@ -1,109 +0,0 @@ -// 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 mshsnapin. - /// - public override string[] Types - { - get - { - return _types; - } - } - - private string[] _types = new string[] { "getevent.types.ps1xml" }; - - /// - /// Get format files to be used for this mshsnapin. - /// - public override string[] Formats - { - get - { - return _formats; - } - } - - private string[] _formats = new string[] { "Event.format.ps1xml" }; - } -} diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs deleted file mode 100644 index d571df34084..00000000000 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/ImportCounterCommand.cs +++ /dev/null @@ -1,682 +0,0 @@ -// 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, string.Format(CultureInfo.InvariantCulture, "Invalid parameter set name: {0}", 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/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj index 02e3b785509..d936a3a52d3 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/Microsoft.PowerShell.Commands.Diagnostics.csproj @@ -8,17 +8,7 @@ - - - - $(DefineConstants);CORECLR - - - - - - - + @@ -32,4 +22,9 @@ + + + $(RootNamespace).resources.%(Filename) + + diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs index cb74c292a3e..cdddba939f3 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/NewWinEventCommand.cs @@ -317,14 +317,13 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (_providerMetadata != null) - _providerMetadata.Dispose(); + _providerMetadata?.Dispose(); base.EndProcessing(); } } - internal class EventWriteException : Exception + internal sealed class EventWriteException : Exception { internal EventWriteException(string msg, Exception innerException) : base(msg, innerException) diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs index 97eff22db0d..6f5d8f6e5ec 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/PdhHelper.cs @@ -190,7 +190,7 @@ internal struct CounterHandleNInstance public string InstanceName; } - internal class PdhHelper : IDisposable + internal sealed class PdhHelper : IDisposable { [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct PDH_COUNTER_PATH_ELEMENTS @@ -267,28 +267,65 @@ private struct PDH_TIME_INFO // We only need dwType and lDefaultScale fields from this structure. // We access those fields directly. The struct is here for reference only. // - [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] - private struct PDH_COUNTER_INFO + [StructLayout(LayoutKind.Sequential)] + private unsafe struct PDH_COUNTER_INFO { - [FieldOffset(0)] public UInt32 dwLength; - [FieldOffset(4)] public UInt32 dwType; - [FieldOffset(8)] public UInt32 CVersion; - [FieldOffset(12)] public UInt32 CStatus; - [FieldOffset(16)] public UInt32 lScale; - [FieldOffset(20)] public UInt32 lDefaultScale; - [FieldOffset(24)] public IntPtr dwUserData; - [FieldOffset(32)] public IntPtr dwQueryUserData; - [FieldOffset(40)] public string szFullPath; - - [FieldOffset(48)] public string szMachineName; - [FieldOffset(56)] public string szObjectName; - [FieldOffset(64)] public string szInstanceName; - [FieldOffset(72)] public string szParentInstance; - [FieldOffset(80)] public UInt32 dwInstanceIndex; - [FieldOffset(88)] public string szCounterName; - - [FieldOffset(96)] public string szExplainText; - [FieldOffset(104)] public IntPtr DataBuffer; + 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)] @@ -476,8 +513,8 @@ private static uint GetCounterInfoPlus(IntPtr hCounter, out UInt32 counterType, 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.dwType; - defaultScale = pdhCounterInfo.lDefaultScale; + counterType = pdhCounterInfo.Type; + defaultScale = (uint)pdhCounterInfo.DefaultScale; } } finally diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx index f8f41ecc2f5..3a5781e9408 100644 --- a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/GetEventResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -255,6 +255,12 @@ The defined template is following: To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + Cannot retrieve event message text. @@ -285,4 +291,25 @@ The defined template is following: Log count ({0}) is exceeded Windows Event Log API limit ({1}). Adjust filter to return less log names. + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/cs/GetEventResources.cs.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/cs/GetEventResources.cs.resx new file mode 100644 index 00000000000..7bf8f659e88 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/cs/GetEventResources.cs.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}. + + + Časové razítko + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/de/GetEventResources.de.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/de/GetEventResources.de.resx new file mode 100644 index 00000000000..751256c9525 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/de/GetEventResources.de.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}. + + + Zeitstempel + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/es/GetEventResources.es.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/es/GetEventResources.es.resx new file mode 100644 index 00000000000..32ea7f7aaac --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/es/GetEventResources.es.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El archivo {0} no tiene la extensión esperada. Especifique solo archivos .blg, .csv o .tsv cuando use el parámetro Path. + + + Error en la llamada API del contador de rendimiento interno. Error: {0:x8}. + + + Debe especificar al menos un par clave-valor Log, Provider o Path. + + + No hay un proveedor de eventos en el equipo {0} que coincida con "{1}". + + + Se encontró un valor null en la clave de {0} tabla hash. No se permiten valores null. + + + Consulta estructurada construida: +{0}. + + + El proveedor {0} escribe eventos en el registro {1}. + + + El valor del parámetro StartTime debe ser menor que el valor del parámetro EndTime. + + + No hay ningún registro de eventos en el equipo {0} que coincida con "{1}". + + + Microsoft + + + El parámetro Circular se omitirá a menos que también se especifique el parámetro MaxSize. + + + No se puede abrir el {0} archivo para escribir. + + + Se especificó un valor "{0}" no válido para la palabra clave. + + + El contador de rendimiento {0} no se puede exportar al archivo {1} porque no formaba parte del primer conjunto de muestras. + + + No se encontraron eventos que coincidan con los criterios de selección especificados. + + + Error en los valores predeterminados de este comando. Error: {0:x8}. + + + No puede importar diferentes tipos de archivos de registro de rendimiento en el mismo comando. Especifique solo un tipo de archivo en el parámetro Path. + + + La ruta de acceso {0} no parece ser una ruta de acceso válida de archivo de registro. Especifique una ruta de acceso del sistema de archivos válida. + + + Debe especificarse un id. de evento válido. + + + No se pudo recuperar información sobre el proveedor {0}. Error: {1}. + + + El registro de eventos {0} solo se puede leer en orden cronológico ascendente porque es un registro analítico o de depuración. Para ver eventos del registro de eventos {0}, use el parámetro Oldest en el comando. + + + La siguiente ruta de acceso de destino de exportación es ambigua: {0}. + + + La ruta del contador de rendimiento {0} no es válida. + + + Los datos de uno de los ejemplos de contadores de rendimiento no son válidos. Vea la propiedad Status de cada objeto PerformanceCounterSample para asegurarse de que contiene datos válidos. + + + La carga proporcionada no coincide con la plantilla definida para el id. de evento {0}. +La plantilla definida es la siguiente: +{1} + + + No se encuentra ningún conjunto de contadores de rendimiento en el equipo {0} que coincida con lo siguiente: {1}. + + + No se encontraron rutas de acceso de contador válidas en los archivos. + + + No se puede crear el archivo {0}. Compruebe que la ruta de acceso es válida. + + + No se encontró ningún conjunto de contadores de rendimiento en el equipo {0}: error {1:x8}. Compruebe que el equipo {0} existe, que es detectable y que dispone de suficientes privilegios para ver los datos del contador de rendimiento en ese equipo. + + + No se puede escribir el evento porque no hay eventos definidos con el id {0} para el proveedor {1}. Corrija el id. de evento e inténtelo de nuevo. + + + El par clave-valor del contexto {0} no es un SID ni un nombre de cuenta NT válidos. + + + No se puede escribir el evento porque la versión {0} especificada para el evento {1} no está definida para el proveedor {2}. Corrija la versión e inténtelo de nuevo. + + + No puede importar más de 32 archivos de registro de contadores .blg en cada comando. + + + Los proveedores especificados no escriben eventos en el registro {0}. Este registro se omitirá. + + + El siguiente valor no tiene un formato de identificador de seguridad (SID) válido: {0}. Escriba un SID válido, como S-1-5-32-544. + + + No se encontró ningún proveedor con el nombre {0}. + + + No se puede recuperar información sobre el conjunto de contadores de rendimiento {0} porque se denegó el acceso. + + + No se puede escribir el evento porque se han definido varios eventos con id {0} para el proveedor {1}. Proporcione una versión para el evento e inténtelo de nuevo. + + + El archivo de registro de eventos {0} solo se puede leer en orden cronológico ascendente porque es un archivo .etl o .evt. Para ver eventos del registro de eventos {0}, use el parámetro Oldest en el comando. + + + Se debe especificar el nombre del proveedor. + + + El archivo {0} no parece ser un archivo de registro válido. Especifique solo los archivos .evtx, .etl o .evt como valores del parámetro Path. + + + La ruta de acceso del contador de rendimiento {0} no es válida o no está presente en los siguientes archivos: {1}. + + + Marca de tiempo + + + El siguiente valor no tiene un formato DateTime válido: {0}. + + + Para acceder al registro "{0}", inicie PowerShell con permisos de usuario elevados. Error: {1} + + + Acceso denegado para el registro: "{0}". + + + Inicie PowerShell con derechos de usuario elevados. + + + No se puede recuperar el texto del mensaje de evento. + + + El archivo {0} ya existe. Para sobrescribir este archivo, use el parámetro Force en el comando Export-Counter. + + + Los parámetros Continuous y MaxSamples no se pueden usar en el mismo comando. + + + Este cmdlet solo se puede ejecutar en Microsoft Windows 7 y versiones posteriores. + + + Este complemento de PowerShell contiene cmdlets de Windows Eventing y del contador de rendimiento. + + + No se encuentra ningún conjunto de contadores de rendimiento en los {0} archivos que coincidan con lo siguiente: {1}. + + + Los proveedores especificados no escriben eventos en ninguno de los registros especificados. + + + Valores cocinados + + + No puede importar más de un archivo de contador de rendimiento separado por comas (.csv) o por tabulaciones (.tsv) en cada comando. + + + El número de registros ({0}) supera el límite de la API de registro de eventos de Windows ({1}). Ajuste el filtro para devolver menos nombres de registro. + + + Especifica los registros de eventos. Se permiten los caracteres comodín. + + + Especifica los registros de eventos de los que este cmdlet obtiene eventos. Se permiten los caracteres comodín. + + + Especifica los proveedores de registro de eventos que obtiene este cmdlet. + + + Especifica los proveedores de registro de eventos de los que este cmdlet obtiene eventos. + + + Especifica la ruta de acceso a los archivos de registro de eventos de los que este cmdlet obtiene eventos. + + + Especifica el número máximo de eventos que se devuelven. + + + Especifica el nombre del equipo del que este cmdlet obtiene datos. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/fr/GetEventResources.fr.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/fr/GetEventResources.fr.resx new file mode 100644 index 00000000000..0c557379a56 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/fr/GetEventResources.fr.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Le fichier {0} n’a pas l’extension de nom de fichier attendue. Spécifiez uniquement des fichiers .blg, .csv ou .tsv lorsque vous utilisez le paramètre Path (Chemin d’accès). + + + Échec de l’appel d’API du compteur de performances interne. Erreur : {0:x8}. + + + Vous devez spécifier au moins une paire clé-valeur de journal, de fournisseur ou de chemin d’accès. + + + Aucun fournisseur d’événements sur l’ordinateur {0} ne correspond à « {1} ». + + + Une valeur nulle a été rencontrée dans la clé de la table de hachage {0}. Les valeurs nulles ne sont pas autorisées. + + + Requête structurée construite : +{0}. + + + Le fournisseur {0} écrit des événements dans le journal {1}. + + + La valeur du paramètre StartTime doit être inférieure à celle du paramètre EndTime. + + + Aucun journal des événements sur l’ordinateur {0} ne correspond à « {1} ». + + + Microsoft + + + Le paramètre Circular (Circulaire) sera ignoré, sauf si le paramètre MaxSize est également spécifié. + + + Impossible d’ouvrir le fichier {0} pour l’écriture. + + + Valeur non valide « {0} » spécifiée pour le mot clé. + + + Le compteur de performances {0} ne peut pas être exporté vers le fichier {1}, car il ne faisait pas partie du premier jeu d’échantillons. + + + Aucun événement correspondant aux critères de sélection spécifiés n’a été trouvé. + + + Les valeurs par défaut de cette commande ont échoué. Erreur : {0:x8}. + + + Vous ne pouvez pas importer différents types de fichiers journaux de performances dans la même commande. Spécifiez un seul type de fichier dans le paramètre Path. + + + Le chemin d’accès {0} ne semble pas être un chemin d’accès de fichier journal valide. Spécifiez un chemin d’accès de système de fichiers valide. + + + Un ID d’événement valide doit être spécifié. + + + Nous n’avons pas pu récupérer les informations sur le fournisseur {0}. Erreur : {1}. + + + Le journal des événements {0} ne peut être lu que dans l’ordre chronologique direct, car c’est un journal analytique ou de débogage. Pour afficher les événements depuis le journal des événements {0}, utilisez le paramètre Oldest (Plus ancien) dans la commande. + + + Le chemin de destination d’exportation suivant est ambigu : {0}. + + + Le chemin d’accès au compteur de performances {0} n’est pas valide. + + + Les données de l’un des échantillons de compteur de performances ne sont pas valides. Affichez la propriété Status (Statut) de chaque objet PerformanceCounterSample pour vérifier que des données valides s’y trouvent. + + + La charge utile fournie ne correspond pas au modèle qui a été défini pour l’ID d’événement {0}. +Le modèle défini est le suivant : +{1} + + + Impossible de trouver des jeux de compteurs de performances dans l’ordinateur {0} qui correspond à ce qui suit : {1}. + + + Aucun chemin d’accès de compteur valide n’a été trouvé dans les fichiers. + + + Impossible de créer le fichier {0}. Vérifiez que le chemin d'accès est valide. + + + Nous n’avons pas pu trouver de jeux de compteurs de performances sur l’ordinateur {0} : erreur {1:x8}. Vérifiez que l’ordinateur {0} existe, qu’il est détectable et que vous disposez de privilèges suffisants pour afficher les données de compteurs de performances sur cet ordinateur. + + + Impossible d’écrire un événement, car aucun événement n’est défini avec l’ID {0} pour le fournisseur {1}. Veuillez corriger l’événement, puis réessayer. + + + La paire clé-valeur du contexte {0} n’est pas SID ou un nom de compte NT valide. + + + Impossible d’écrire l’événement, car la version {0} spécifiée pour l’événement {1} n’est pas définie pour le fournisseur {2}. Veuillez corriger la version, puis réessayer. + + + Vous ne pouvez pas importer plus de 32 fichiers journaux de compteurs .blg dans chaque commande. + + + Les fournisseurs spécifiés n’écrivent pas d’événements dans le journal {0}. Ce journal va être ignoré. + + + La valeur suivante n’est pas dans un format d’ID de sécurité (SID) valide : {0}. Entrez un SID valide, tel que S-1-5-32-544. + + + Aucun fournisseur n’a été trouvé avec le nom {0}. + + + Impossible de récupérer des informations sur le jeu de compteurs de performances {0}, car l’accès a été refusé. + + + Impossible d’écrire l’événement, car plusieurs événements avec l’ID {0} ont été définis pour le fournisseur {1}. Veuillez fournir une version pour l’événement, puis réessayer. + + + Le fichier journal des événements {0} ne peut être lu que dans l’ordre chronologique direct, car c’est un fichier .etl ou .evt. Pour afficher les événements depuis le journal des événements {0}, utilisez le paramètre Oldest (Plus ancien) dans la commande. + + + Le nom de fournisseur doit être spécifié. + + + Le fichier {0} ne semble pas être un fichier journal valide. Spécifiez uniquement des fichiers .evtx, .etl ou .evt comme valeurs du paramètre Path. + + + Le chemin d’accès au compteur de performances {0} n’est pas valide ou n’est pas présent dans les fichiers suivants : {1}. + + + Horodateur + + + La valeur suivante n’est pas dans un format DateTime valide : {0}. + + + Pour accéder au journal « {0} », démarrez PowerShell avec des droits de l’utilisateur élevés. Erreur : {1} + + + Accès refusé au journal : « {0} ». + + + Lancez PowerShell avec des droits de l’utilisateur élevés. + + + Impossible de récupérer le texte du message d’événement. + + + Le fichier {0} existe déjà. Pour remplacer ce fichier, utilisez le paramètre Force dans la commande Export-Counter. + + + Les paramètres Continuous et MaxSamples ne peuvent pas être utilisés dans la même commande. + + + Cette cmdlet ne peut être exécutée que sur Microsoft Windows 7 et les versions ultérieures. + + + Ce composant logiciel enfichable PowerShell contient les cmdlets d’événements Windows Eventing et de compteur de performances. + + + Impossible de trouver des jeux de compteurs de performances dans les fichiers {0} qui correspondent à ce qui suit : {1}. + + + Les fournisseurs spécifiés n’écrivent aucun événement dans aucun des journaux spécifiés. + + + Valeurs préparées + + + Vous ne pouvez pas importer plus d’un fichier de compteur de performances séparé par des virgules (.csv) ou par des tabulations (.tsv) dans chaque commande. + + + Le nombre de journaux ({0}) a dépassé la limite de l’API Journal des événements Windows ({1}). Ajustez le filtre pour renvoyer moins de noms de journaux. + + + Spécifie les journaux des événements. Les caractères génériques sont autorisés. + + + Spécifie les journaux des événements depuis lesquels cette cmdlet obtient des événements. Les caractères génériques sont autorisés. + + + Spécifie les fournisseurs de journaux des événements que cette cmdlet obtient. + + + Spécifie les fournisseurs de journaux des événements depuis lesquels cette cmdlet obtient des événements. + + + Spécifie le chemin d’accès aux fichiers journaux des événements depuis lesquels cette cmdlet obtient des événements. + + + Spécifie le nombre maximal d'événements renvoyés. + + + Spécifie le nom de l’ordinateur depuis lequel cette cmdlet obtient des données. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/it/GetEventResources.it.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/it/GetEventResources.it.resx new file mode 100644 index 00000000000..afe084e8a85 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/it/GetEventResources.it.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ja/GetEventResources.ja.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ja/GetEventResources.ja.resx new file mode 100644 index 00000000000..7f634a5a42d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ja/GetEventResources.ja.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}. + + + タイムスタンプ + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ko/GetEventResources.ko.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ko/GetEventResources.ko.resx new file mode 100644 index 00000000000..e4d08c3b4b2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ko/GetEventResources.ko.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} 파일에 필요한 파일 이름 확장명이 없습니다. Path 매개 변수를 사용할 때는 .blg, .csv 또는 .tsv 파일만 지정하세요. + + + 내부 성능 카운터 API 호출에 실패했습니다. 오류: {0:x8}. + + + 하나 이상의 Log, Provider 또는 Path 키-값 쌍을 지정해야 합니다. + + + {0} 컴퓨터에 "{1}"와(과) 일치하는 이벤트 공급자가 없습니다. + + + {0} 해시 테이블 키에 null 값이 있습니다. null 값은 허용되지 않습니다. + + + 다음 구조화된 쿼리를 생성했습니다. +{0}. + + + {0} 공급자는 {1} 로그에 이벤트를 씁니다. + + + StartTime 매개 변수 값은 EndTime 매개 변수 값보다 작아야 합니다. + + + {0} 컴퓨터에 "{1}"와(과) 일치하는 이벤트 로그가 없습니다. + + + Microsoft + + + MaxSize 매개 변수도 지정하지 않으면 Circular 매개 변수는 무시됩니다. + + + 쓰기용으로 {0} 파일을 열 수 없습니다. + + + 키워드에 대해 값 '{0}'이(가) 잘못 지정되었습니다. + + + 첫 번째 샘플 집합의 일부가 아니므로 {0} 성능 카운터를 {1} 파일로 내보낼 수 없습니다. + + + 지정한 선택 조건과 일치하는 이벤트를 찾을 수 없습니다. + + + 이 명령의 기본값을 적용하지 못했습니다. 오류: {0:x8}. + + + 같은 명령에서 서로 다른 형식의 성능 로그 파일을 가져올 수 없습니다. Path 매개 변수에는 한 가지 형식의 파일만 지정하세요. + + + {0} 경로가 올바른 로그 파일 경로가 아닌 것 같습니다. 올바른 파일 시스템 경로를 지정하세요. + + + 유효한 이벤트 ID를 지정해야 합니다. + + + {0} 제공자에 대한 정보를 검색할 수 없습니다. 오류: {1}. + + + {0} 이벤트 로그는 분석 또는 디버그 로그이므로 앞으로의 시간 순서로만 읽을 수 있습니다. {0} 이벤트 로그의 이벤트를 보려면 명령에서 Oldest 매개 변수를 사용하세요. + + + 다음 내보내기 대상 경로가 모호합니다. {0} + + + {0} 성능 카운터 경로가 유효하지 않습니다. + + + 성능 카운터 샘플 중 하나의 데이터가 올바르지 않습니다. 각 PerformanceCounterSample 개체의 Status 속성을 열어 유효한 데이터가 포함되어 있는지 확인하세요. + + + 제공된 페이로드가 이벤트 ID {0}에 대해 정의된 템플릿과 일치하지 않습니다. +정의된 템플릿은 다음과 같습니다. +{1} + + + {0} 컴퓨터에서 다음과 일치하는 성능 카운터 집합을 찾을 수 없습니다. {1}. + + + 파일에서 유효한 카운터 경로를 찾을 수 없습니다. + + + {0} 파일을 만들 수 없습니다. 경로가 올바른지 확인하세요. + + + {0} 컴퓨터에서 성능 카운터 집합을 찾을 수 없습니다. 오류 {1:x8}. {0} 컴퓨터가 있는지, 검색 가능한지, 그리고 해당 컴퓨터에서 성능 카운터 데이터를 볼 수 있는 권한이 충분한지 확인하세요. + + + 공급자 {1}에 대해 ID {0}(으)로 정의된 이벤트가 없으므로 이벤트를 쓸 수 없습니다. 오류를 수정하고 다시 시도하세요. + + + {0} Context 키-값이 올바른 SID 또는 NT 계정 이름이 아닙니다. + + + 이벤트 {1}에 대해 지정한 버전 {0}이(가) 공급자 {2}에 대해 정의되어 있지 않아 이벤트를 쓸 수 없습니다. 버전을 수정하고 다시 시도하세요. + + + 각 명령에서 .blg 카운터 로그 파일을 32개 이상 가져올 수 없습니다. + + + 지정된 공급자는 {0} 로그에 이벤트를 쓰지 않습니다. 이 로그는 무시됩니다. + + + 다음 값은 유효한 보안 식별자(SID) 형식이 아닙니다. {0} 유효한 SID를 입력하세요(예: S-1-5-32-544). + + + 이름이 {0}인 공급자를 찾을 수 없습니다. + + + 액세스가 거부되어 {0} 성능 카운터 집합에 대한 정보를 검색할 수 없습니다. + + + 공급자 {0}에 대해 ID {1}이(가) 여러 개 정의되어 있어 이벤트를 쓸 수 없습니다. 이벤트의 버전을 지정한 후 다시 시도하세요. + + + {0} 이벤트 로그 파일은 .etl 또는 .evt 파일이므로 앞으로의 시간 순서로만 읽을 수 있습니다. {0} 이벤트 로그의 이벤트를 보려면 명령에서 Oldest 매개 변수를 사용하세요. + + + 제공자 이름을 지정해야 합니다. + + + {0} 파일이 올바른 로그 파일이 아닌 것 같습니다. Path 매개 변수 값으로는 .evtx, .etl 또는 .evt 파일만 지정하세요. + + + {0} 성능 카운터 경로가 유효하지 않거나 다음 파일에 없습니다. {1}. + + + 타임스탬프 + + + 다음 값은 올바른 DateTime 형식이 아닙니다. {0}. + + + '{0}' 로그에 액세스하려면 상승된 사용자 권한으로 PowerShell을 시작하세요. 오류: {1} + + + 로그 액세스가 거부됨: {0} + + + 상승된 사용자 권한으로 PowerShell을 시작합니다. + + + 이벤트 메시지 텍스트를 검색할 수 없습니다. + + + {0} 파일이 이미 있습니다. 이 파일을 덮어쓰려면 Export-Counter 명령에서 Force 매개 변수를 사용하세요. + + + Continuous 매개 변수와 MaxSamples 매개 변수는 같은 명령에서 함께 사용할 수 없습니다. + + + 이 cmdlet은 Microsoft Windows 7 이상에서만 실행할 수 있습니다. + + + 이 PowerShell 스냅인에는 Windows 이벤트 및 성능 카운터 cmdlet이 포함되어 있습니다. + + + {0} 파일에서 다음과 일치하는 성능 카운터 집합을 찾을 수 없습니다. {1} + + + 지정된 공급자는 지정된 로그에 이벤트를 쓰지 않습니다. + + + 가공된 값 + + + 각 명령에서 쉼표로 구분된(.csv) 또는 탭으로 구분된(.tsv) 성능 카운터 파일을 두 개 이상 가져올 수 없습니다. + + + 로그 수({0})가 Windows 이벤트 로그 API 제한({1})을 초과했습니다. 더 적은 로그 이름을 반환하도록 필터를 조정하세요. + + + 이벤트 로그를 지정합니다. 와일드카드를 사용할 수 있습니다. + + + 이 cmdlet이 이벤트를 가져오는 이벤트 로그를 지정합니다. 와일드카드를 사용할 수 있습니다. + + + 이 cmdlet이 가져오는 이벤트 로그 공급자를 지정합니다. + + + 이 cmdlet이 이벤트를 가져오는 이벤트 로그 공급자를 지정합니다. + + + 이 cmdlet이 이벤트를 가져오는 이벤트 로그 파일의 경로를 지정합니다. + + + 반환되는 최대 이벤트 수를 지정합니다. + + + 이 cmdlet이 데이터를 가져오는 컴퓨터의 이름을 지정합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/pl/GetEventResources.pl.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/pl/GetEventResources.pl.resx new file mode 100644 index 00000000000..5e906cc9575 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/pl/GetEventResources.pl.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}. + + + Znacznik czasu + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/pt-BR/GetEventResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/pt-BR/GetEventResources.pt-BR.resx new file mode 100644 index 00000000000..d82932ed822 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/pt-BR/GetEventResources.pt-BR.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + O arquivo {0} não tem a extensão de nome de arquivo esperada. Especifique somente arquivos .blg, .csv ou .tsv ao usar o parâmetro Path. + + + Falha na chamada à API interna do contador de desempenho. Erro: {0:x8}. + + + Você deve especificar pelo menos um par chave-valor de Log, Provedor ou Caminho. + + + Não há um provedor de eventos no computador {0} que corresponda a "{1}". + + + Um valor nulo foi encontrado na chave da tabela de hash {0}. Valores nulos não são permitidos. + + + Consulta estruturada construída: +{0}. + + + O provedor {0} grava eventos no log {1}. + + + O valor do parâmetro StartTime deve ser menor que o valor do parâmetro EndTime. + + + Não há um log de eventos no computador {0} que corresponda a "{1}". + + + Microsoft + + + O parâmetro Circular será ignorado, a menos que o parâmetro MaxSize também seja especificado. + + + Não é possível abrir o arquivo {0} para gravação. + + + Valor inválido '{0}' especificado para palavra-chave. + + + O contador de desempenho {0} não pode ser exportado para o arquivo {1} porque não fazia parte do primeiro conjunto de amostras. + + + Não foram encontrados eventos que correspondam aos critérios de seleção especificados. + + + Os valores padrão para este comando falharam. Erro: {0:x8}. + + + Não é possível importar diferentes tipos de arquivos de log de desempenho no mesmo comando. Especifique apenas um tipo de arquivo no parâmetro Path. + + + O {0} caminho não parece ser um caminho do arquivo de log válido. Especifique um caminho válido no sistema de arquivos. + + + Uma ID de Evento válida deve ser especificada. + + + Não foi possível recuperar informações sobre o provedor {0}. Erro: {1}. + + + O log de eventos {0} pode ser lido somente na ordem cronológica direta porque é um log analítico ou de depuração. Para ver os eventos do log de eventos {0}, use o parâmetro Oldest no comando. + + + O seguinte caminho de destino da exportação é ambíguo: {0}. + + + O caminho do contador de desempenho {0} não é válido. + + + Os dados em uma das amostras do contador de desempenho não são válidos. Exiba a propriedade Status de cada objeto PerformanceCounterSample para verificar se ela contém dados válidos. + + + O conteúdo fornecido não corresponde ao modelo definido para a ID do evento {0}. +O modelo definido é o seguinte: +{1} + + + Não é possível encontrar nenhum conjunto de contadores de desempenho no computador {0} que corresponda ao seguinte: {1}. + + + Nenhum caminho de contador válido foi encontrado nos arquivos. + + + Não é possível criar o arquivo {0}. Verifique se o caminho é válido. + + + Não foi possível encontrar nenhum conjunto de contadores de desempenho no computador {0}: erro {1:x8}. Verifique se o {0} computador existente, se é detectável e se você tem privilégios suficientes para exibir dados do contador de desempenho nesse computador. + + + O evento não pode ser gravado porque não há eventos definidos com a ID {0} para o provedor {1}. Corrija a ID do evento e tente novamente. + + + O par chave-valor Context {0} não é um SID ou um nome de conta NT válido. + + + O evento não pode ser gravado porque a versão especificada {0} para o evento {1} não está definida para o provedor {2}. Corrija a versão e tente novamente. + + + Não é possível importar mais de 32 arquivos de log do contador .blg em cada comando. + + + Os provedores especificados não gravam eventos no log {0}. Este log será ignorado. + + + O valor a seguir não está em um formato SID (identificador de segurança) válido: {0}. Insira um SID válido, como S-1-5-32-544. + + + Nenhum provedor encontrado com o nome {0}. + + + Não é possível recuperar informações sobre o conjunto de contadores de desempenho {0} porque o acesso foi negado. + + + O evento não pode ser gravado porque vários eventos com a ID {0} foram definidos para o provedor {1}. Forneça uma versão para o evento e tente novamente. + + + O arquivo de log de eventos {0} pode ser lido somente na ordem cronológica direta porque é um arquivo .etl ou .evt. Para ver os eventos do log de eventos {0}, use o parâmetro Oldest no comando. + + + O nome do provedor deve ser especificado. + + + O arquivo {0} não parece ser um arquivo de log válido. Especifique somente arquivos .evtx, .etl ou .evt como valores do parâmetro Path. + + + O caminho do contador de desempenho {0} não é válido ou não está presente nos seguintes arquivos: {1}. + + + Carimbo de data/hora + + + O valor a seguir não está em um formato DateTime válido: {0}. + + + Para acessar o log '{0}' inicie o PowerShell com direitos de usuário elevados. Erro: {1} + + + Acesso negado ao log: '{0}'. + + + Inicie o PowerShell com direitos de usuário elevados. + + + Não foi possível recuperar o texto da mensagem de evento. + + + O arquivo {0} já existe. Para substituí-lo, use o parâmetro Force no comando Export-Counter. + + + Os parâmetros Continuous e MaxSamples não podem ser usados no mesmo comando. + + + Este cmdlet pode ser executado somente no Microsoft Windows 7 ou posterior. + + + Este snap-in do PowerShell contém cmdlets do Contador de Desempenho e Eventos do Windows. + + + Não é possível encontrar nenhum conjunto de contadores de desempenho nos arquivos {0} que corresponda ao seguinte: {1}. + + + Os provedores especificados não gravam eventos em nenhum dos logs especificados. + + + Valores preparados + + + Não é possível importar mais de um arquivo de contador de desempenho separado por vírgula (.csv) ou por tabulação (.tsv) em cada comando. + + + A contagem de logs ({0}) excede o limite da API do Log de Eventos do Windows ({1}). Ajuste o filtro para retornar menos nomes de log. + + + Especifica os logs de evento. Caracteres curinga são permitidos. + + + Especifica os logs de eventos dos quais este cmdlet obtém eventos. Caracteres curinga são permitidos. + + + Especifica os provedores de log de eventos que esse cmdlet obtém. + + + Especifica os provedores de log de eventos dos quais este cmdlet obtém eventos. + + + Especifica o caminho para os arquivos de log de eventos dos quais este cmdlet obtém eventos. + + + Especifica o número máximo de eventos retornados. + + + Especifica o nome do computador do qual este cmdlet obtém dados. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ru/GetEventResources.ru.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ru/GetEventResources.ru.resx new file mode 100644 index 00000000000..3edc75ebda4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/ru/GetEventResources.ru.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}. + + + Метка времени + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/tr/GetEventResources.tr.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/tr/GetEventResources.tr.resx new file mode 100644 index 00000000000..0ba635ba01c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/tr/GetEventResources.tr.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}. + + + Zaman damgası + + + The following value is not in a valid DateTime format: {0}. + + + To access the '{0}' log start PowerShell with elevated user rights. Error: {1} + + + Access denied for log: '{0}'. + + + Launch PowerShell with elevated user rights. + + + 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. + + + Specifies the event logs. Wildcards are permitted. + + + Specifies the event logs that this cmdlet gets events from. Wildcards are permitted. + + + Specifies the event log providers that this cmdlet gets. + + + Specifies the event log providers from which this cmdlet gets events. + + + Specifies the path to the event log files that this cmdlet gets events from. + + + Specifies the maximum number of events that are returned. + + + Specifies the name of the computer from which this cmdlet gets data. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/zh-Hans/GetEventResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/zh-Hans/GetEventResources.zh-Hans.resx new file mode 100644 index 00000000000..e8c57d8c770 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/zh-Hans/GetEventResources.zh-Hans.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} 文件没有预期的文件扩展名。使用 Path 参数时,只能指定 .blg、.csv 或 .tsv 文件。 + + + 内部性能计数器 API 调用失败。错误: {0:x8}。 + + + 你必须至少指定一个 Log、Provider 或 Path 键值对。 + + + {0} 计算机上没有与“{1}”匹配的事件提供程序。 + + + 在 {0} 哈希表键中遇到 null 值。不允许 null 值。 + + + 构造的结构化查询: +{0}。 + + + {0} 提供程序会将事件写入 {1} 日志。 + + + StartTime 参数的值必须小于 EndTime 参数的值。 + + + {0} 计算机上没有与“{1}”匹配的事件日志。 + + + Microsoft + + + 除非同时指定 MaxSize 参数,否则将忽略 Circular 参数。 + + + 无法打开 {0} 文件进行写入。 + + + 为关键字指定的值 "{0}" 无效。 + + + 无法将 {0} 性能计数器导出到 {1} 文件,因为它不属于第一个样本集。 + + + 找不到与指定的选择条件匹配的事件。 + + + 此命令的默认值失败。错误: {0:x8}。 + + + 不能在同一命令中导入不同类型的性能日志文件。 请在 Path 参数中只指定一种类型的文件。 + + + {0} 路径似乎不是有效的日志文件路径。请指定有效的文件系统路径。 + + + 必须指定有效的事件 ID。 + + + 无法检索 {0} 提供程序的有关信息。错误: {1}。 + + + {0} 事件日志是分析日志或调试日志,因此只能按时间正序读取。若要查看 {0} 事件日志中的事件,请在命令中使用 Oldest 参数。 + + + 以下导出目标路径不明确: {0}。 + + + {0} 性能计数器路径无效。 + + + 其中一个性能计数器样本中的数据无效。请查看每个 PerformanceCounterSample 对象的 Status 属性,以确保其中包含有效数据。 + + + 提供的有效负载与为事件 ID {0} 定义的模板不匹配。 +定义的模板如下: +{1} + + + 在 {0} 文件中找不到任何与以下内容匹配的性能计数器集: {1}。 + + + 在文件中未找到有效的计数器路径。 + + + 无法创建 {0} 文件。请确保该路径有效。 + + + 在 {0} 计算机上找不到任何性能计数器集: 错误 {1:x8}。请验证 {0} 计算机是否存在、是否可发现,以及你是否有足够的权限查看该计算机上的性能计数器数据。 + + + 无法写入事件,因为没有为提供程序 {0} 定义 ID 为 {1} 的事件。 请更正事件 ID,然后重试。 + + + {0} 上下文键值不是有效的 SID 或 NT 帐户名。 + + + 无法写入事件,因为没有为提供程序“{2}”定义事件“{1}”的指定版本 {0}。 请更正版本,然后重试。 + + + 每个命令中不能导入超过 32 个 .blg 计数器日志文件。 + + + 指定的提供程序不会将事件写入 {0} 日志。将忽略此日志。 + + + 以下值不是有效的安全标识符(SID)格式: {0}。请输入有效的 SID,例如 S-1-5-32-544。 + + + 未找到名为“{0}”的提供程序。 + + + 无法检索有关 {0} 性能计数器集的信息,因为访问被拒绝。 + + + 无法写入事件,因为为提供程序 {1} 定义了多个 ID 为 {0} 的事件。 请为该事件提供版本,然后重试。 + + + {0} 事件日志文件是分 .etl 日志或 .evt 日志,因此只能按时间正序读取。若要查看 {0} 事件日志中的事件,请在命令中使用 Oldest 参数。 + + + 必须指定提供程序名称。 + + + {0} 文件似乎不是有效的日志文件。仅将 .evtx、.etl 或 .evt 文件指定为 Path 参数的值。 + + + {0} 性能计数器路径无效,或在以下文件中不存在: {1}。 + + + 时间戳 + + + 以下值的日期/时间格式无效: {0}。 + + + 若要访问“{0}”日志,请以提升的用户权限启动 PowerShell。 错误: {1} + + + 拒绝访问文件: {0}。 + + + 以提升的用户权限启动 PowerShell。 + + + 无法检索事件消息文本。 + + + {0} 文件已存在。若要覆盖此文件,请在 Export-Counter 命令中使用 Force 参数。 + + + Continuous 参数和 MaxSamples 参数不能用在同一命令中。 + + + 此 cmdlet 只能在 Microsoft Windows 7 及更高版本上运行。 + + + 此 PowerShell 管理单元包含 Windows 事件和性能计数器 cmdlet。 + + + 在 {0} 文件中找不到任何与以下内容匹配的性能计数器集: {1}。 + + + 指定的提供程序不会将事件写入任何指定的日志。 + + + 计算值 + + + 每个命令中不能导入多个以逗号分隔的(.csv)或以制表符分隔的(.tsv)性能计数器文件。 + + + 日志计数({0})超出了 Windows 事件日志 API 限制({1})。请调整筛选器,以返回更少的日志名称。 + + + 指定事件日志。允许使用通配符。 + + + 指定此 cmdlet 从中获取事件的事件日志。允许使用通配符。 + + + 指定此 cmdlet 获取的事件日志提供程序。 + + + 指定此 cmdlet 从中获取事件的事件日志提供程序。 + + + 指定此 cmdlet 从中获取事件的事件日志文件路径。 + + + 指定要返回的最大事件数。 + + + 指定此 cmdlet 从中获取数据的计算机名称。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Diagnostics/resources/zh-Hant/GetEventResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/zh-Hant/GetEventResources.zh-Hant.resx new file mode 100644 index 00000000000..f887a829d37 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Diagnostics/resources/zh-Hant/GetEventResources.zh-Hant.resx @@ -0,0 +1,315 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} 檔案沒有預期的副檔名。使用 Path 參數時,只能指定 .blg、.csv 或 .tsv 檔案。 + + + 內部效能計數器 API 呼叫失敗。錯誤: {0:x8}。 + + + 您必須指定至少一個 Log、Provider 或 Path 機碼值組。 + + + {0} 電腦上沒有符合 "{1}" 的事件提供者。 + + + 在 {0} 雜湊表索引鍵中遇到 null 值。不允許 Null 值。 + + + 建構的結構化查詢: +{0}。 + + + {0} 提供者會將事件寫入 {1} 記錄。 + + + StartTime 參數的值必須小於 EndTime 參數的值。 + + + {0} 電腦上沒有符合 "{1}" 的事件記錄。 + + + Microsoft + + + 除非同時指定 MaxSize 參數,否則會忽略 Circular 參數。 + + + 無法開啟 {0} 檔案以寫入。 + + + 為關鍵字指定的值 '{0}' 無效。 + + + 無法將 {0} 效能計數器匯出至 {1} 檔案,因為它不是第一個樣本集的一部分。 + + + 找不到符合指定選取準則的事件。 + + + 此命令的預設值失敗。錯誤: {0:x8}。 + + + 您無法在同一個命令中匯入不同類型的效能記錄檔。 請在 Path 參數中只指定一種檔案類型。 + + + {0} 路徑似乎不是有效的記錄檔路徑。請指定有效的檔案系統路徑。 + + + 必須指定有效的事件識別碼。 + + + 無法擷取關於 {0} 提供者的資訊。錯誤: {1}。 + + + {0} 事件記錄檔只能依時間順序向前讀取,因為它是分析或偵錯記錄檔。若要查看 {0} 事件記錄檔中的事件,請在命令中使用 Oldest 參數。 + + + 下列匯出目的地路徑不明確: {0}。 + + + {0} 效能計數器路徑無效。 + + + 其中一個效能計數器範例中的資料無效。請檢視每個 PerformanceCounterSample 物件的 Status 屬性,以確定其中包含有效資料。 + + + 提供的承載與為事件識別碼 {0} 定義的範本不符。 +定義的範本如下: +{1} + + + 在 {0} 個電腦中找不到任何符合下列條件的效能計數器組: {1}。 + + + 在檔案中找不到有效的計數器路徑。 + + + 無法建立 {0} 檔案。請確認路徑有效。 + + + 在 {0} 電腦上找不到任何效能計數器組: 錯誤 {1:x8}。請確認 {0} 電腦存在、可探索,而且您有足夠的權限檢視該電腦上的效能計數器資料。 + + + 無法寫入事件,因為提供者 {1} 沒有以識別碼 {0} 定義事件。 請更正事件識別碼後再試一次。 + + + {0} 內容機碼值不是有效的 SID 或 NT 帳戶名稱。 + + + 無法寫入事件,因為未為提供者 {2} 定義事件 {1} 的指定版本 {0}。 請更正版本後再試一次。 + + + 您無法在每個命令中匯入超過 32 個 .blg 計數器記錄檔。 + + + 指定的提供者不會將事件寫入 {0} 記錄。將忽略此記錄。 + + + 下列值不是有效的安全性識別碼 (SID) 格式: {0}。請輸入有效的 SID,例如 S-1-5-32-544。 + + + 找不到名稱為 {0} 的提供者。 + + + 無法擷取 {0} 效能計數器組的相關資訊,因為存取被拒。 + + + 無法寫入事件,因為已為提供者 {1} 定義多個識別碼為 {0} 的事件。 請為事件提供版本,然後再試一次。 + + + {0} 事件記錄檔只能依時間順序向前讀取,因為它是 .etl 或 .evt 檔案。若要查看 {0} 事件記錄檔中的事件,請在命令中使用 Oldest 參數。 + + + 必須指定提供者名稱。 + + + {0} 檔案似乎不是有效的記錄檔。使用 Path 參數時,只指定 .evtx、.etl 或 .evt 檔案做為值。 + + + {0} 效能計數器路徑無效,或不存在於下列檔案中: {1}。 + + + 時間戳記 + + + 下列值不是有效的日期/時間格式: {0}。 + + + 若要存取 '{0}' 記錄,請使用提升的使用者權限啟動 PowerShell。 錯誤: {1} + + + 存取記錄遭拒: '{0}'。 + + + 以較高的使用者權限啟動 PowerShell。 + + + 無法擷取事件訊息文字。 + + + {0} 檔案已存在。若要覆寫此檔案,請使用 Export-Counter 命令中的 Force 參數。 + + + Continuous 參數和 MaxSamples 參數不能在同一個命令中使用。 + + + 此 Cmdlet 只能在 Microsoft Windows 7 及更新版本上執行。 + + + 此 PowerShell 嵌入式管理單元包含 Windows 事件與效能計數器 Cmdlet。 + + + 在 {0} 個檔案中找不到任何符合下列條件的效能計數器組: {1}。 + + + 指定的提供者不會將事件寫入任何指定的記錄。 + + + 已處理的值 + + + 您無法在每個命令中匯入多個逗號分隔的 (.csv) 或 Tab 分隔的 (.tsv) 效能計數器檔案。 + + + 記錄數量 ({0}) 已超過 Windows Event Log API 限制 ({1})。請調整篩選條件,以傳回較少的記錄名稱。 + + + 指定事件記錄檔。允許使用萬用字元。 + + + 指定此 Cmdlet 從中取得事件的事件記錄。允許使用萬用字元。 + + + 指定此 Cmdlet 取得的事件記錄提供者。 + + + 指定此 Cmdlet 取得事件的事件記錄提供者。 + + + 指定此 Cmdlet 從中取得事件的事件記錄檔路徑。 + + + 指定傳回的事件數上限。 + + + 指定此 Cmdlet 取得資料的來源電腦名稱。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj index 31e6536380f..306ca16e7a8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj +++ b/src/Microsoft.PowerShell.Commands.Management/Microsoft.PowerShell.Commands.Management.csproj @@ -10,44 +10,14 @@ - - $(DefineConstants);CORECLR - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + - - + + $(RootNamespace).resources.%(Filename) + - diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs index fb6b638b9df..3e26b2e2e98 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/SessionBasedWrapper.cs @@ -82,11 +82,7 @@ protected TSession[] Session set { - if (value == null) - { - throw new ArgumentNullException("value"); - } - + ArgumentNullException.ThrowIfNull(value); _session = value; _sessionWasSpecified = true; } @@ -495,8 +491,7 @@ private IEnumerable GetSessionsToActAgainst(QueryBuilder queryBuilder) return this.Session; } - var sessionBoundQueryBuilder = queryBuilder as ISessionBoundQueryBuilder; - if (sessionBoundQueryBuilder != null) + if (queryBuilder is ISessionBoundQueryBuilder sessionBoundQueryBuilder) { TSession sessionOfTheQueryBuilder = sessionBoundQueryBuilder.GetTargetSession(); if (sessionOfTheQueryBuilder != null) @@ -582,8 +577,9 @@ private TSession GetImpliedSession() /// if successful method invocations should emit downstream the being operated on. public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocationInfo methodInvocationInfo, bool passThru) { - if (objectInstance == null) throw new ArgumentNullException(nameof(objectInstance)); - if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + ArgumentNullException.ThrowIfNull(objectInstance); + + ArgumentNullException.ThrowIfNull(methodInvocationInfo); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(objectInstance)) { @@ -608,7 +604,7 @@ public override void ProcessRecord(TObjectInstance objectInstance, MethodInvocat /// Method invocation details. public override void ProcessRecord(MethodInvocationInfo methodInvocationInfo) { - if (methodInvocationInfo == null) throw new ArgumentNullException(nameof(methodInvocationInfo)); + ArgumentNullException.ThrowIfNull(methodInvocationInfo); foreach (TSession sessionForJob in this.GetSessionsToActAgainst(methodInvocationInfo)) { @@ -688,10 +684,7 @@ public override void EndProcessing() public override void StopProcessing() { Job jobToStop = _parentJob; - if (jobToStop != null) - { - jobToStop.StopJob(); - } + jobToStop?.StopJob(); base.StopProcessing(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs index 808ca1a4de9..935cc960c6c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CimJobException.cs @@ -15,7 +15,6 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Represents an error during execution of a CIM job. /// - [Serializable] public class CimJobException : SystemException, IContainsErrorRecord { #region Standard constructors and methods required for all exceptions @@ -50,32 +49,12 @@ public CimJobException(string message, Exception inner) : base(message, inner) /// /// 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) : base(info, context) + StreamingContext context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - _errorRecord = (ErrorRecord)info.GetValue("errorRecord", typeof(ErrorRecord)); - } - - /// - /// Sets the SerializationInfo with information about the exception. - /// - /// The that holds the serialized object data about the exception being thrown. - /// The that contains contextual information about the source or destination. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("errorRecord", _errorRecord); + throw new NotSupportedException(); } #endregion @@ -104,16 +83,14 @@ internal static CimJobException CreateFromAnyException( Dbg.Assert(jobContext != null, "Caller should verify jobContext != null"); Dbg.Assert(inner != null, "Caller should verify inner != null"); - CimException cimException = inner as CimException; - if (cimException != null) + if (inner is CimException cimException) { return CreateFromCimException(jobDescription, jobContext, cimException); } string message = BuildErrorMessage(jobDescription, jobContext, inner.Message); CimJobException cimJobException = new(message, inner); - var containsErrorRecord = inner as IContainsErrorRecord; - if (containsErrorRecord != null) + if (inner is IContainsErrorRecord containsErrorRecord) { cimJobException.InitializeErrorRecord( jobContext, @@ -362,8 +339,7 @@ internal bool IsTerminatingError { get { - var cimException = this.InnerException as CimException; - if ((cimException == null) || (cimException.ErrorData == null)) + if ((this.InnerException is not CimException cimException) || (cimException.ErrorData == null)) { return false; } @@ -374,7 +350,7 @@ internal bool IsTerminatingError return false; } - UInt16 perceivedSeverityValue = (UInt16)perceivedSeverityProperty.Value; + ushort perceivedSeverityValue = (ushort)perceivedSeverityProperty.Value; if (perceivedSeverityValue != 7) { /* from CIM Schema: Interop\CIM_Error.mof: diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs index d8a1bdd44ea..eb594dd4eea 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/CreateInstanceJob.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job wrapping invocation of a CreateInstance intrinsic CIM method. /// - internal class CreateInstanceJob : PropertySettingJob + internal sealed class CreateInstanceJob : PropertySettingJob { private CimInstance _resultFromCreateInstance; private CimInstance _resultFromGetInstance; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs index 327fb83affa..0432c6c9a8f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/DeleteInstanceJob.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job wrapping invocation of a DeleteInstance intrinsic CIM method. /// - internal class DeleteInstanceJob : MethodInvocationJobBase + internal sealed class DeleteInstanceJob : MethodInvocationJobBase { private readonly CimInstance _objectToDelete; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs index bd024b7d76a..569740d0d1b 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/EnumerateAssociatedInstancesJob.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job that handles executing a WQL (in the future CQL?) query on a remote CIM server. /// - internal class EnumerateAssociatedInstancesJob : QueryJobBase + internal sealed class EnumerateAssociatedInstancesJob : QueryJobBase { private readonly CimInstance _associatedObject; private readonly string _associationName; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs index 1194da4ab0f..9eaac2b3d7f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ExtrinsicMethodInvocationJob.cs @@ -66,8 +66,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m methodParameter.Value = dotNetValue; cmdletOutput.Add(methodParameter.Name, methodParameter); - var cimInstances = dotNetValue as CimInstance[]; - if (cimInstances != null) + if (dotNetValue is CimInstance[] cimInstances) { foreach (var instance in cimInstances) { @@ -75,8 +74,7 @@ private void ProcessOutParameter(CimMethodResult methodResult, MethodParameter m } } - var cimInstance = dotNetValue as CimInstance; - if (cimInstance != null) + if (dotNetValue is CimInstance cimInstance) { CimCmdletAdapter.AssociateSessionOfOriginWithInstance(cimInstance, this.JobContext.Session); } @@ -105,7 +103,7 @@ private void OnNext(CimMethodResult methodResult) if (cmdletOutput.Count == 1) { - var singleOutputParameter = cmdletOutput.Values.Single(); + var singleOutputParameter = cmdletOutput.Values.First(); if (singleOutputParameter.Value == null) { return; @@ -191,15 +189,13 @@ public override void OnNext(CimMethodResultBase item) this.ExceptionSafeWrapper( delegate { - var methodResult = item as CimMethodResult; - if (methodResult != null) + if (item is CimMethodResult methodResult) { this.OnNext(methodResult); return; } - var streamedResult = item as CimMethodStreamedResult; - if (streamedResult != null) + if (item is CimMethodStreamedResult streamedResult) { this.OnNext(streamedResult); return; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs index cd1eb78d81c..06a45933522 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/InstanceMethodInvocationJob.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job wrapping invocation of an extrinsic CIM method. /// - internal class InstanceMethodInvocationJob : ExtrinsicMethodInvocationJob + internal sealed class InstanceMethodInvocationJob : ExtrinsicMethodInvocationJob { private readonly CimInstance _targetInstance; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs index eb636b4a759..84b13b82097 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/MethodInvocationJobBase.cs @@ -66,8 +66,8 @@ private IEnumerable GetMethodInputParametersCore(Func GetMethodInputParameters() { - var allMethodParameters = this.GetMethodInputParametersCore(p => !p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); - var methodParametersWithInputValue = allMethodParameters.Where(p => p.IsValuePresent); + var allMethodParameters = this.GetMethodInputParametersCore(static p => !p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); + var methodParametersWithInputValue = allMethodParameters.Where(static p => p.IsValuePresent); return methodParametersWithInputValue; } @@ -81,7 +81,7 @@ internal override CimCustomOptionsDictionary CalculateJobSpecificCustomOptions() IDictionary result = new Dictionary(StringComparer.OrdinalIgnoreCase); IEnumerable customOptions = this - .GetMethodInputParametersCore(p => p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); + .GetMethodInputParametersCore(static p => p.Name.StartsWith(CustomOperationOptionPrefix, StringComparison.OrdinalIgnoreCase)); foreach (MethodParameter customOption in customOptions) { if (customOption.Value == null) @@ -104,7 +104,7 @@ internal IEnumerable GetMethodOutputParameters() } var outParameters = allParameters_plus_returnValue - .Where(p => ((p.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error)) != 0)); + .Where(static p => ((p.Bindings & (MethodParameterBindings.Out | MethodParameterBindings.Error)) != 0)); return outParameters; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs index f0d07fc201d..869002a55f4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/ModifyInstanceJob.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job wrapping invocation of a ModifyInstance intrinsic CIM method. /// - internal class ModifyInstanceJob : PropertySettingJob + internal sealed class ModifyInstanceJob : PropertySettingJob { private CimInstance _resultFromModifyInstance; private bool _resultFromModifyInstanceHasBeenPassedThru; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs index 7c7a82ee9ca..7bd2bd17531 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/QueryJob.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job that handles executing a WQL (in the future CQL?) query on a remote CIM server. /// - internal class QueryInstancesJob : QueryJobBase + internal sealed class QueryInstancesJob : QueryJobBase { private readonly string _wqlQuery; private readonly bool _useEnumerateInstances; diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs index 5a25206fe94..3bc376ab3d5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/StaticMethodInvocationJob.cs @@ -11,7 +11,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Job wrapping invocation of a static CIM method. /// - internal class StaticMethodInvocationJob : ExtrinsicMethodInvocationJob + internal sealed class StaticMethodInvocationJob : ExtrinsicMethodInvocationJob { internal StaticMethodInvocationJob(CimJobContext jobContext, MethodInvocationInfo methodInvocationInfo) : base(jobContext, false /* passThru */, jobContext.CmdletizationClassName, methodInvocationInfo) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs index 515e19f895c..6b716fa5501 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/TerminatingErrorTracker.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// Tracks (per-session) terminating errors in a given cmdlet invocation. /// - internal class TerminatingErrorTracker + internal sealed class TerminatingErrorTracker { #region Getting tracker for a given cmdlet invocation @@ -53,8 +53,7 @@ private static int GetNumberOfSessions(InvocationInfo invocationInfo) int maxNumberOfSessionsIndicatedByCimInstanceArguments = 1; foreach (object cmdletArgument in invocationInfo.BoundParameters.Values) { - CimInstance[] array = cmdletArgument as CimInstance[]; - if (array != null) + if (cmdletArgument is CimInstance[] array) { int numberOfSessionsAssociatedWithArgument = array .Select(CimCmdletAdapter.GetSessionOfOriginFromCimInstance) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs index 6dc65424f50..6bd2bee7fee 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimChildJobBase.cs @@ -84,7 +84,7 @@ private enum WsManErrorCode : uint private static bool IsWsManQuotaReached(Exception exception) { - if (!(exception is CimException cimException)) + if (exception is not CimException cimException) { return false; } @@ -111,7 +111,7 @@ private static bool IsWsManQuotaReached(Exception exception) return false; } - WsManErrorCode wsManErrorCode = (WsManErrorCode)(UInt32)(errorCodeProperty.Value); + 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: @@ -315,10 +315,7 @@ internal override void StartJob() this.ExceptionSafeWrapper(delegate { IObservable observable = this.GetCimOperation(); - if (observable != null) - { - observable.Subscribe(this); - } + observable?.Subscribe(this); }); }); } @@ -423,11 +420,11 @@ internal CimOperationOptions CreateOperationOptions() (_jobContext.WarningActionPreference == ActionPreference.Ignore) ) && (!_jobContext.IsRunningInBackground)) { - operationOptions.DisableChannel((UInt32)MessageChannel.Warning); + operationOptions.DisableChannel((uint)MessageChannel.Warning); } else { - operationOptions.EnableChannel((UInt32)MessageChannel.Warning); + operationOptions.EnableChannel((uint)MessageChannel.Warning); } if (( @@ -435,11 +432,11 @@ internal CimOperationOptions CreateOperationOptions() (_jobContext.VerboseActionPreference == ActionPreference.Ignore) ) && (!_jobContext.IsRunningInBackground)) { - operationOptions.DisableChannel((UInt32)MessageChannel.Verbose); + operationOptions.DisableChannel((uint)MessageChannel.Verbose); } else { - operationOptions.EnableChannel((UInt32)MessageChannel.Verbose); + operationOptions.EnableChannel((uint)MessageChannel.Verbose); } if (( @@ -447,11 +444,11 @@ internal CimOperationOptions CreateOperationOptions() (_jobContext.DebugActionPreference == ActionPreference.Ignore) ) && (!_jobContext.IsRunningInBackground)) { - operationOptions.DisableChannel((UInt32)MessageChannel.Debug); + operationOptions.DisableChannel((uint)MessageChannel.Debug); } else { - operationOptions.EnableChannel((UInt32)MessageChannel.Debug); + operationOptions.EnableChannel((uint)MessageChannel.Debug); } switch (this.JobContext.ShouldProcessOptimization) @@ -522,10 +519,7 @@ internal CimOperationOptions CreateOperationOptions() } CimCustomOptionsDictionary jobSpecificCustomOptions = this.GetJobSpecificCustomOptions(); - if (jobSpecificCustomOptions != null) - { - jobSpecificCustomOptions.Apply(operationOptions, CimSensitiveValueConverter); - } + jobSpecificCustomOptions?.Apply(operationOptions, CimSensitiveValueConverter); return operationOptions; } @@ -629,8 +623,7 @@ internal void ReportJobFailure(IContainsErrorRecord exception) } else { - CimJobException cje = exception as CimJobException; - if ((cje != null) && (cje.IsTerminatingError)) + if ((exception is CimJobException cje) && (cje.IsTerminatingError)) { terminatingErrorTracker.MarkSessionAsTerminated(this.JobContext.Session, out sessionWasAlreadyTerminated); isThisTerminatingError = true; @@ -763,7 +756,7 @@ internal void FinishProgressReporting() #region Handling extended semantics callbacks - private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, UInt32 percentageCompleted, UInt32 secondsRemaining) + private void WriteProgressCallback(string activity, string currentOperation, string statusDescription, uint percentageCompleted, uint secondsRemaining) { if (string.IsNullOrEmpty(activity)) { @@ -775,28 +768,28 @@ private void WriteProgressCallback(string activity, string currentOperation, str statusDescription = this.StatusMessage; } - Int32 signedSecondsRemaining; - if (secondsRemaining == UInt32.MaxValue) + int signedSecondsRemaining; + if (secondsRemaining == uint.MaxValue) { signedSecondsRemaining = -1; } - else if (secondsRemaining <= Int32.MaxValue) + else if (secondsRemaining <= int.MaxValue) { - signedSecondsRemaining = (Int32)secondsRemaining; + signedSecondsRemaining = (int)secondsRemaining; } else { - signedSecondsRemaining = Int32.MaxValue; + signedSecondsRemaining = int.MaxValue; } - Int32 signedPercentageComplete; - if (percentageCompleted == UInt32.MaxValue) + int signedPercentageComplete; + if (percentageCompleted == uint.MaxValue) { signedPercentageComplete = -1; } else if (percentageCompleted <= 100) { - signedPercentageComplete = (Int32)percentageCompleted; + signedPercentageComplete = (int)percentageCompleted; } else { @@ -825,7 +818,7 @@ private enum MessageChannel Debug = 2, } - private void WriteMessageCallback(UInt32 channel, string message) + private void WriteMessageCallback(uint channel, string message) { this.ExceptionSafeWrapper( delegate @@ -1009,7 +1002,7 @@ private CimResponseType PromptUserCallback(string message, CimPromptType promptT internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) { PSObject pso = PSObject.AsPSObject(cimInstance); - if (!(pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty)) + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is not PSPropertyInfo psShowComputerNameProperty) { return false; } @@ -1019,8 +1012,7 @@ internal static bool IsShowComputerNameMarkerPresent(CimInstance cimInstance) internal static void AddShowComputerNameMarker(PSObject pso) { - PSPropertyInfo psShowComputerNameProperty = pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] as PSPropertyInfo; - if (psShowComputerNameProperty != null) + if (pso.InstanceMembers[RemotingConstants.ShowComputerNameNoteProperty] is PSPropertyInfo psShowComputerNameProperty) { psShowComputerNameProperty.Value = true; } @@ -1053,10 +1045,7 @@ internal override void WriteObject(object outputObject) if (this.JobContext.ShowComputerName) { - if (pso == null) - { - pso = PSObject.AsPSObject(outputObject); - } + pso ??= PSObject.AsPSObject(outputObject); AddShowComputerNameMarker(pso); if (cimInstance == null) diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs index c334ff29601..8a4e4272561 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletDefinitionContext.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { - internal class CimCmdletDefinitionContext + internal sealed class CimCmdletDefinitionContext { internal CimCmdletDefinitionContext( string cmdletizationClassName, diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs index c876184c141..3bee74526fc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimCmdletInvocationContext.cs @@ -10,7 +10,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { - internal class CimCmdletInvocationContext + internal sealed class CimCmdletInvocationContext { internal CimCmdletInvocationContext( CimCmdletDefinitionContext cmdletDefinitionContext, diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs index 91500758a06..da075286c34 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimConverter.cs @@ -24,9 +24,9 @@ namespace Microsoft.PowerShell.Cim { - internal class CimSensitiveValueConverter : IDisposable + internal sealed class CimSensitiveValueConverter : IDisposable { - private class SensitiveString : IDisposable + private sealed class SensitiveString : IDisposable { private GCHandle _gcHandle; private string _string; @@ -50,15 +50,9 @@ internal SensitiveString(int numberOfCharacters) private unsafe void Copy(char* source, int offset, int charsToCopy) { - if ((offset < 0) || (offset >= _string.Length)) - { - throw new ArgumentOutOfRangeException(nameof(offset)); - } - - if (offset + charsToCopy > _string.Length) - { - throw new ArgumentOutOfRangeException(nameof(charsToCopy)); - } + ArgumentOutOfRangeException.ThrowIfNegative(offset); + ArgumentOutOfRangeException.ThrowIfGreaterThanOrEqual(offset, _string.Length); + ArgumentOutOfRangeException.ThrowIfGreaterThan(offset + charsToCopy, _string.Length, nameof(charsToCopy)); fixed (char* target = _string) { @@ -352,7 +346,7 @@ internal static object ConvertFromDotNetToCim(object dotNetObject) /// The only kind of exception this method can throw. internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDotNetType) { - if (expectedDotNetType == null) { throw new ArgumentNullException(nameof(expectedDotNetType)); } + ArgumentNullException.ThrowIfNull(expectedDotNetType); if (cimObject == null) { @@ -431,7 +425,9 @@ internal static object ConvertFromCimToDotNet(object cimObject, Type expectedDot 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 }); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs index 5f01d472554..27d48ccab9a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimJobContext.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { - internal class CimJobContext + internal sealed class CimJobContext { internal CimJobContext( CimCmdletInvocationContext cmdletInvocationContext, diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs index 1445ed17a14..34c708b5f4c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimOperationOptionsHelper.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim { - internal class CimCustomOptionsDictionary + internal sealed class CimCustomOptionsDictionary { private readonly IDictionary _dict; private readonly object _dictModificationLock = new(); diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs index a6f5b9616b9..f08c2ab3c11 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimQuery.cs @@ -18,7 +18,7 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// /// CimQuery supports building of queries against CIM object model. /// - internal class CimQuery : QueryBuilder, ISessionBoundQueryBuilder + internal sealed class CimQuery : QueryBuilder, ISessionBoundQueryBuilder { private readonly StringBuilder _wqlCondition; @@ -177,7 +177,7 @@ private static string GetMatchCondition(string propertyName, IEnumerable propert .Select(propertyValue => wildcardsEnabled ? GetMatchConditionForLikeOperator(propertyName, propertyValue) : GetMatchConditionForEqualityOperator(propertyName, propertyValue)) - .Where(individualCondition => !string.IsNullOrWhiteSpace(individualCondition)) + .Where(static individualCondition => !string.IsNullOrWhiteSpace(individualCondition)) .ToList(); if (individualConditions.Count == 0) { @@ -196,7 +196,7 @@ private static string GetMatchCondition(string propertyName, IEnumerable propert /// Property name to query on. /// Property values to accept in the query. /// - /// if should be treated as a containing a wildcard pattern; + /// if should be treated as a containing a wildcard pattern; /// otherwise. /// /// @@ -219,7 +219,7 @@ public override void FilterByProperty(string propertyName, IEnumerable allowedPr /// Property name to query on. /// Property values to reject in the query. /// - /// if should be treated as a containing a wildcard pattern; + /// if should be treated as a containing a wildcard pattern; /// otherwise. /// /// @@ -314,15 +314,8 @@ public override void FilterByAssociatedInstance(object associatedInstance, strin /// public override void AddQueryOption(string optionName, object optionValue) { - if (string.IsNullOrEmpty(optionName)) - { - throw new ArgumentNullException(nameof(optionName)); - } - - if (optionValue == null) - { - throw new ArgumentNullException(nameof(optionValue)); - } + ArgumentException.ThrowIfNullOrEmpty(optionName); + ArgumentNullException.ThrowIfNull(optionValue); this.queryOptions[optionName] = optionValue; } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs index 7052b16c768..472046b192f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/cimWrapper.cs @@ -107,15 +107,12 @@ internal CimCmdletDefinitionContext CmdletDefinitionContext { get { - if (_cmdletDefinitionContext == null) - { - _cmdletDefinitionContext = new CimCmdletDefinitionContext( - this.ClassName, - this.ClassVersion, - this.ModuleVersion, - this.Cmdlet.CommandInfo.CommandMetadata.SupportsShouldProcess, - this.PrivateData); - } + _cmdletDefinitionContext ??= new CimCmdletDefinitionContext( + this.ClassName, + this.ClassVersion, + this.ModuleVersion, + this.Cmdlet.CommandInfo.CommandMetadata.SupportsShouldProcess, + this.PrivateData); return _cmdletDefinitionContext; } @@ -171,7 +168,7 @@ private CimJobContext CreateJobContext(CimSession session, object targetObject) /// object that performs a query against the wrapped object model. internal override StartableJob CreateQueryJob(CimSession session, QueryBuilder baseQuery) { - if (!(baseQuery is CimQuery query)) + if (baseQuery is not CimQuery query) { throw new ArgumentNullException(nameof(baseQuery)); } diff --git a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs index 39d1a5bc441..c1a8552db8c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs +++ b/src/Microsoft.PowerShell.Commands.Management/cimSupport/cmdletization/cim/clientSideQuery.cs @@ -20,9 +20,9 @@ namespace Microsoft.PowerShell.Cmdletization.Cim /// 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 class ClientSideQuery : QueryBuilder + internal sealed class ClientSideQuery : QueryBuilder { - internal class NotFoundError + internal sealed class NotFoundError { public NotFoundError() { @@ -36,8 +36,7 @@ public NotFoundError(string propertyName, object propertyValue, bool wildcardsEn if (wildcardsEnabled) { - var propertyValueAsString = propertyValue as string; - if ((propertyValueAsString != null) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) + if ((propertyValue is string propertyValueAsString) && (WildcardPattern.ContainsWildcardCharacters(propertyValueAsString))) { this.ErrorMessageGenerator = (queryDescription, className) => GetErrorMessageForNotFound_ForWildcard(this.PropertyName, this.PropertyValue, className); @@ -181,7 +180,7 @@ protected override bool IsMatchCore(CimInstance cimInstance) } } - private class CimInstanceRegularFilter : CimInstancePropertyBasedFilter + private sealed class CimInstanceRegularFilter : CimInstancePropertyBasedFilter { public CimInstanceRegularFilter(string propertyName, IEnumerable allowedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) { @@ -202,7 +201,7 @@ public CimInstanceRegularFilter(string propertyName, IEnumerable allowedProperty if (valueBehaviors.Count == 1) { - this.BehaviorOnNoMatch = valueBehaviors.Single(); + this.BehaviorOnNoMatch = valueBehaviors.First(); } else { @@ -223,7 +222,7 @@ public override bool ShouldReportErrorOnNoMatches_IfMultipleFilters() case BehaviorOnNoMatch.Default: default: return this.PropertyValueFilters - .Any(f => !f.HadMatch && f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors); + .Any(static f => !f.HadMatch && f.BehaviorOnNoMatch == BehaviorOnNoMatch.ReportErrors); } } @@ -247,7 +246,7 @@ public override IEnumerable GetNotFoundErrors_IfThisIsTheOnlyFilt } } - private class CimInstanceExcludeFilter : CimInstancePropertyBasedFilter + private sealed class CimInstanceExcludeFilter : CimInstancePropertyBasedFilter { public CimInstanceExcludeFilter(string propertyName, IEnumerable excludedPropertyValues, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) { @@ -272,7 +271,7 @@ public CimInstanceExcludeFilter(string propertyName, IEnumerable excludedPropert } } - private class CimInstanceMinFilter : CimInstancePropertyBasedFilter + private sealed class CimInstanceMinFilter : CimInstancePropertyBasedFilter { public CimInstanceMinFilter(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) { @@ -293,7 +292,7 @@ public CimInstanceMinFilter(string propertyName, object minPropertyValue, Behavi } } - private class CimInstanceMaxFilter : CimInstancePropertyBasedFilter + private sealed class CimInstanceMaxFilter : CimInstancePropertyBasedFilter { public CimInstanceMaxFilter(string propertyName, object minPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) { @@ -314,7 +313,7 @@ public CimInstanceMaxFilter(string propertyName, object minPropertyValue, Behavi } } - private class CimInstanceAssociationFilter : CimInstanceFilterBase + private sealed class CimInstanceAssociationFilter : CimInstanceFilterBase { public CimInstanceAssociationFilter(BehaviorOnNoMatch behaviorOnNoMatch) { @@ -466,8 +465,7 @@ protected override BehaviorOnNoMatch GetDefaultBehaviorWhenNoMatchesFound(object } else { - string expectedPropertyValueAsString = cimTypedExpectedPropertyValue as string; - if (expectedPropertyValueAsString != null && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) + if (cimTypedExpectedPropertyValue is string expectedPropertyValueAsString && WildcardPattern.ContainsWildcardCharacters(expectedPropertyValueAsString)) { return BehaviorOnNoMatch.SilentlyContinue; } @@ -504,8 +502,7 @@ private static bool NonWildcardEqual(string propertyName, object actualPropertyV actualPropertyValue = actualPropertyValue.ToString(); } - var expectedPropertyValueAsString = expectedPropertyValue as string; - if (expectedPropertyValueAsString != null) + if (expectedPropertyValue is string expectedPropertyValueAsString) { var actualPropertyValueAsString = (string)actualPropertyValue; return actualPropertyValueAsString.Equals(expectedPropertyValueAsString, StringComparison.OrdinalIgnoreCase); @@ -533,7 +530,7 @@ private static bool WildcardEqual(string propertyName, object actualPropertyValu } } - internal class PropertyValueExcludeFilter : PropertyValueRegularFilter + internal sealed class PropertyValueExcludeFilter : PropertyValueRegularFilter { public PropertyValueExcludeFilter(string propertyName, object expectedPropertyValue, bool wildcardsEnabled, BehaviorOnNoMatch behaviorOnNoMatch) : base(propertyName, expectedPropertyValue, wildcardsEnabled, behaviorOnNoMatch) @@ -551,7 +548,7 @@ protected override bool IsMatchingValue(object actualPropertyValue) } } - internal class PropertyValueMinFilter : PropertyValueFilter + internal sealed class PropertyValueMinFilter : PropertyValueFilter { public PropertyValueMinFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) : base(propertyName, expectedPropertyValue, behaviorOnNoMatch) @@ -572,7 +569,7 @@ private static bool ActualValueGreaterThanOrEqualToExpectedValue(string property { try { - if (!(expectedPropertyValue is IComparable expectedComparable)) + if (expectedPropertyValue is not IComparable expectedComparable) { return false; } @@ -586,7 +583,7 @@ private static bool ActualValueGreaterThanOrEqualToExpectedValue(string property } } - internal class PropertyValueMaxFilter : PropertyValueFilter + internal sealed class PropertyValueMaxFilter : PropertyValueFilter { public PropertyValueMaxFilter(string propertyName, object expectedPropertyValue, BehaviorOnNoMatch behaviorOnNoMatch) : base(propertyName, expectedPropertyValue, behaviorOnNoMatch) @@ -607,7 +604,7 @@ private static bool ActualValueLessThanOrEqualToExpectedValue(string propertyNam { try { - if (!(actualPropertyValue is IComparable actualComparable)) + if (actualPropertyValue is not IComparable actualComparable) { return false; } @@ -656,7 +653,7 @@ internal IEnumerable GenerateNotFoundErrors() return Enumerable.Empty(); } - if (_filters.All(f => !f.ShouldReportErrorOnNoMatches_IfMultipleFilters())) + if (_filters.All(static f => !f.ShouldReportErrorOnNoMatches_IfMultipleFilters())) { return Enumerable.Empty(); } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs index 1b10bbfe7ab..3f3f617097a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CIMHelper.cs @@ -9,8 +9,6 @@ namespace Microsoft.PowerShell.Commands { - using Extensions; - internal static class CIMHelper { internal static class ClassNames @@ -79,8 +77,7 @@ internal static string WqlQueryAll(string from) /// internal static T GetFirst(CimSession session, string nameSpace, string wmiClassName) where T : class, new() { - if (string.IsNullOrEmpty(wmiClassName)) - throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName)); + ArgumentException.ThrowIfNullOrEmpty(wmiClassName); try { @@ -132,8 +129,7 @@ internal static string WqlQueryAll(string from) /// internal static T[] GetAll(CimSession session, string nameSpace, string wmiClassName) where T : class, new() { - if (string.IsNullOrEmpty(wmiClassName)) - throw new ArgumentException("String argument may not be null or empty", nameof(wmiClassName)); + ArgumentException.ThrowIfNullOrEmpty(wmiClassName); var rv = new List(); @@ -239,11 +235,6 @@ internal static string EscapePath(string path) return string.Join(@"\\", path.Split('\\')); } } -} - -namespace Extensions -{ - using Microsoft.PowerShell.Commands; internal static class CIMExtensions { @@ -319,12 +310,12 @@ internal static CimInstance QueryFirstInstance(this CimSession session, string q internal static T[] GetAll(this CimSession session, string wmiClassName) where T : class, new() { - return Microsoft.PowerShell.Commands.CIMHelper.GetAll(session, wmiClassName); + return 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); + return CIMHelper.GetAll(session, wmiNamespace, wmiClassName); } } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs index 78be89b90da..bc4e44220dd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearRecycleBinCommand.cs @@ -41,7 +41,7 @@ public string[] DriveLetter /// /// Property that sets force parameter. This will allow to clear the recyclebin. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get @@ -237,7 +237,7 @@ private void EmptyRecycleBin(string drivePath) } } - internal static class NativeMethod + internal static partial class NativeMethod { // Internal code to SHEmptyRecycleBin internal enum RecycleFlags : uint @@ -247,8 +247,8 @@ internal enum RecycleFlags : uint SHERB_NOSOUND = 0x00000004 } - [DllImport("Shell32.dll", CharSet = CharSet.Unicode)] - internal static extern uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); + [LibraryImport("Shell32.dll", StringMarshalling = StringMarshalling.Utf16, EntryPoint = "SHEmptyRecycleBinW")] + internal static partial uint SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath, RecycleFlags dwFlags); } } #endif diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs index 5ce64350fbd..77e1b497b95 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Clipboard.cs @@ -8,7 +8,7 @@ namespace Microsoft.PowerShell.Commands.Internal { - internal static class Clipboard + internal static partial class Clipboard { private static bool? _clipboardSupported; @@ -19,7 +19,8 @@ internal static class Clipboard private static string StartProcess( string tool, string args, - string stdin = "") + string stdin = "", + bool readStdout = true) { ProcessStartInfo startInfo = new(); startInfo.UseShellExecute = false; @@ -28,7 +29,7 @@ private static string StartProcess( startInfo.RedirectStandardError = true; startInfo.FileName = tool; startInfo.Arguments = args; - string stdout; + string stdout = string.Empty; using (Process process = new()) { @@ -43,15 +44,15 @@ private static string StartProcess( return string.Empty; } - if (!string.IsNullOrEmpty(stdin)) + process.StandardInput.Write(stdin); + process.StandardInput.Close(); + + if (readStdout) { - process.StandardInput.Write(stdin); - process.StandardInput.Close(); + stdout = process.StandardOutput.ReadToEnd(); } - stdout = process.StandardOutput.ReadToEnd(); process.WaitForExit(250); - _clipboardSupported = process.ExitCode == 0; } @@ -93,11 +94,6 @@ public static string GetText() public static void SetText(string text) { - if (string.IsNullOrEmpty(text)) - { - return; - } - if (_clipboardSupported == false) { _internalClipboard = text; @@ -114,7 +110,14 @@ public static void SetText(string text) else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { tool = "xclip"; - args = "-selection clipboard -in"; + if (string.IsNullOrEmpty(text)) + { + args = "-selection clipboard /dev/null"; + } + else + { + args = "-selection clipboard -in"; + } } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { @@ -126,7 +129,7 @@ public static void SetText(string text) return; } - StartProcess(tool, args, text); + StartProcess(tool, args, text, readStdout: false); if (_clipboardSupported == false) { _internalClipboard = text; @@ -154,46 +157,46 @@ public static void SetRtf(string plainText, string rtfText) private const uint GMEM_ZEROINIT = 0x0040; private const uint GHND = GMEM_MOVEABLE | GMEM_ZEROINIT; - [DllImport("kernel32.dll")] - private static extern IntPtr GlobalAlloc(uint flags, UIntPtr dwBytes); + [LibraryImport("kernel32.dll")] + private static partial IntPtr GlobalAlloc(uint flags, UIntPtr dwBytes); - [DllImport("kernel32.dll")] - private static extern IntPtr GlobalFree(IntPtr hMem); + [LibraryImport("kernel32.dll")] + private static partial IntPtr GlobalFree(IntPtr hMem); - [DllImport("kernel32.dll")] - private static extern IntPtr GlobalLock(IntPtr hMem); + [LibraryImport("kernel32.dll")] + private static partial IntPtr GlobalLock(IntPtr hMem); - [DllImport("kernel32.dll")] + [LibraryImport("kernel32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GlobalUnlock(IntPtr hMem); + private static partial bool GlobalUnlock(IntPtr hMem); - [DllImport("kernel32.dll", ExactSpelling = true, EntryPoint = "RtlMoveMemory", SetLastError = true)] - private static extern void CopyMemory(IntPtr dest, IntPtr src, uint count); + [LibraryImport("kernel32.dll", EntryPoint = "RtlMoveMemory")] + private static partial void CopyMemory(IntPtr dest, IntPtr src, uint count); - [DllImport("user32.dll", SetLastError = false)] + [LibraryImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool IsClipboardFormatAvailable(uint format); + private static partial bool IsClipboardFormatAvailable(uint format); - [DllImport("user32.dll", SetLastError = true)] + [LibraryImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool OpenClipboard(IntPtr hWndNewOwner); + private static partial bool OpenClipboard(IntPtr hWndNewOwner); - [DllImport("user32.dll", SetLastError = true)] + [LibraryImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool CloseClipboard(); + private static partial bool CloseClipboard(); - [DllImport("user32.dll", SetLastError = true)] + [LibraryImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool EmptyClipboard(); + private static partial bool EmptyClipboard(); - [DllImport("user32.dll", SetLastError = true)] - private static extern IntPtr GetClipboardData(uint format); + [LibraryImport("user32.dll")] + private static partial IntPtr GetClipboardData(uint format); - [DllImport("user32.dll")] - private static extern IntPtr SetClipboardData(uint format, IntPtr data); + [LibraryImport("user32.dll")] + private static partial IntPtr SetClipboardData(uint format, IntPtr data); - [DllImport("user32.dll", SetLastError = true)] - private static extern uint RegisterClipboardFormat(string lpszFormat); + [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; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs index bdeef0dd7a0..79b1c862bfd 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/CombinePathCommand.cs @@ -32,7 +32,8 @@ public class JoinPathCommand : CoreCommandWithCredentialsBase [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true)] [AllowNull] [AllowEmptyString] - public string ChildPath { get; set; } + [AllowEmptyCollection] + public string[] ChildPath { get; set; } /// /// Gets or sets additional childPaths to the command. @@ -50,6 +51,21 @@ public class JoinPathCommand : CoreCommandWithCredentialsBase [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 @@ -64,7 +80,15 @@ protected override void ProcessRecord() Path != null, "Since Path is a mandatory parameter, paths should never be null"); - string combinedChildPath = ChildPath; + 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) @@ -119,6 +143,12 @@ protected override void ProcessRecord() 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) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs deleted file mode 100644 index 6f93119c999..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/CommitTransactionCommand.cs +++ /dev/null @@ -1,31 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs index 61b5fe4487d..ea8c111531c 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Computer.cs @@ -24,10 +24,6 @@ using Microsoft.Win32; using Dbg = System.Management.Automation; -// FxCop suppressions for resource strings: -[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "ComputerResources.resources", MessageId = "unjoined")] -[module: SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", Scope = "resource", Target = "ComputerResources.resources", MessageId = "UpTime")] - namespace Microsoft.PowerShell.Commands { #region Restart-Computer @@ -35,7 +31,6 @@ namespace Microsoft.PowerShell.Commands /// /// This exception is thrown when the timeout expires before a computer finishes restarting. /// - [Serializable] public sealed class RestartComputerTimeoutException : RuntimeException { /// @@ -87,50 +82,6 @@ public RestartComputerTimeoutException(string message) : base(message) { } /// An exception that led to this exception. /// public RestartComputerTimeoutException(string message, Exception innerException) : base(message, innerException) { } - - #region Serialization - /// - /// Serialization constructor for class RestartComputerTimeoutException. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - private RestartComputerTimeoutException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - ComputerName = info.GetString("ComputerName"); - Timeout = info.GetInt32("Timeout"); - } - - /// - /// Serializes the RestartComputerTimeoutException. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ComputerName", ComputerName); - info.AddValue("Timeout", Timeout); - } - #endregion Serialization } /// @@ -275,12 +226,12 @@ public WaitForServiceTypes For /// The specific time interval (in second) to wait between network pings or service queries. /// [Parameter(ParameterSetName = DefaultParameterSet)] - [ValidateRange(1, Int16.MaxValue)] - public Int16 Delay + [ValidateRange(1, short.MaxValue)] + public short Delay { get { - return (Int16)_delay; + return (short)_delay; } set @@ -306,7 +257,7 @@ public Int16 Delay ComputerName = $computerName ScriptBlock = { $true } - SessionOption = NewPSSessionOption -NoMachineProfile + SessionOption = New-PSSessionOption -NoMachineProfile ErrorAction = 'SilentlyContinue' } @@ -393,17 +344,10 @@ public void Dispose(bool disposing) { if (disposing) { - if (_timer != null) - { - _timer.Dispose(); - } - + _timer?.Dispose(); _waitHandler.Dispose(); _cancel.Dispose(); - if (_powershell != null) - { - _powershell.Dispose(); - } + _powershell?.Dispose(); } } @@ -522,7 +466,7 @@ private void OnTimedEvent(object s) } } - private class ComputerInfo + private sealed class ComputerInfo { internal string LastBootUpTime; internal bool RebootComplete; @@ -540,7 +484,10 @@ private List TestRestartStageUsingWsman(IEnumerable computerName { try { - if (token.IsCancellationRequested) { break; } + if (token.IsCancellationRequested) + { + break; + } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, isLocalHost: false, this, token)) { @@ -682,7 +629,10 @@ internal static List TestWmiConnectionUsingWsman(List computerNa { try { - if (token.IsCancellationRequested) { break; } + if (token.IsCancellationRequested) + { + break; + } using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, credential, wsmanAuthentication, isLocalHost: false, cmdlet, token)) { @@ -798,7 +748,7 @@ protected override void BeginProcessing() if (Wait) { - _activityId = (new Random()).Next(); + _activityId = Random.Shared.Next(); if (_timeout == -1 || _timeout >= int.MaxValue / 1000) { _timeoutInMilliseconds = int.MaxValue; @@ -837,7 +787,10 @@ protected override void ProcessRecord() ValidateComputerNames(); object[] flags = new object[] { 2, 0 }; - if (Force) flags[0] = forcedReboot; + if (Force) + { + flags[0] = forcedReboot; + } if (ParameterSetName.Equals(DefaultParameterSet, StringComparison.OrdinalIgnoreCase)) { @@ -912,14 +865,18 @@ protected override void ProcessRecord() while (true) { - int loopCount = actualDelay * 4; // (delay * 1000)/250ms + // (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 (_exit) + { + break; + } } if (first) @@ -939,7 +896,10 @@ protected override void ProcessRecord() // 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 (_exit) + { + break; + } if (restartStageTestList.Count > 0) { @@ -955,7 +915,10 @@ protected override void ProcessRecord() } // Test WMI service - if (_exit) { break; } + if (_exit) + { + break; + } if (wmiTestList.Count > 0) { @@ -973,10 +936,16 @@ protected override void ProcessRecord() } } - if (isForWmi) { break; } + if (isForWmi) + { + break; + } // Test WinRM service - if (_exit) { break; } + if (_exit) + { + break; + } if (winrmTestList.Count > 0) { @@ -1001,16 +970,25 @@ protected override void ProcessRecord() loopCount--; _waitHandler.Wait(250); - if (_exit) { break; } + if (_exit) + { + break; + } } } } } - if (isForWinRm) { break; } + if (isForWinRm) + { + break; + } // Test PowerShell - if (_exit) { break; } + if (_exit) + { + break; + } if (psTestList.Count > 0) { @@ -1026,7 +1004,10 @@ protected override void ProcessRecord() } while (false); // if time is up or Ctrl+c is typed, break out - if (_exit) { break; } + if (_exit) + { + break; + } // Check if the restart completes switch (_waitFor) @@ -1070,18 +1051,38 @@ protected override void ProcessRecord() // The timeout expires. Write out timeout error messages for the computers that haven't finished restarting do { - if (restartStageTestList.Count > 0) { WriteOutTimeoutError(restartStageTestList); } + if (restartStageTestList.Count > 0) + { + WriteOutTimeoutError(restartStageTestList); + } + + if (wmiTestList.Count > 0) + { + WriteOutTimeoutError(wmiTestList); + } - if (wmiTestList.Count > 0) { WriteOutTimeoutError(wmiTestList); } // Wait for WMI. All computers that finished restarting are put in "winrmTestList" - if (isForWmi) { break; } + if (isForWmi) + { + break; + } // Wait for WinRM. All computers that finished restarting are put in "psTestList" - if (winrmTestList.Count > 0) { WriteOutTimeoutError(winrmTestList); } + if (winrmTestList.Count > 0) + { + WriteOutTimeoutError(winrmTestList); + } - if (isForWinRm) { break; } + if (isForWinRm) + { + break; + } + + if (psTestList.Count > 0) + { + WriteOutTimeoutError(psTestList); + } - if (psTestList.Count > 0) { WriteOutTimeoutError(psTestList); } // Wait for PowerShell. All computers that finished restarting are put in "allDoneList" } while (false); } @@ -1098,10 +1099,7 @@ protected override void StopProcessing() _cancel.Cancel(); _waitHandler.Set(); - if (_timer != null) - { - _timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); - } + _timer?.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite); if (_powershell != null) { @@ -1231,7 +1229,10 @@ private void ProcessWSManProtocol(object[] flags) string strLocal = string.Empty; bool isLocalHost = false; - if (_cancel.Token.IsCancellationRequested) { break; } + if (_cancel.Token.IsCancellationRequested) + { + break; + } if ((computer.Equals("localhost", StringComparison.OrdinalIgnoreCase)) || (computer.Equals(".", StringComparison.OrdinalIgnoreCase))) { @@ -1278,6 +1279,7 @@ private void ProcessWSManProtocol(object[] flags) /// [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 @@ -1585,7 +1587,10 @@ private void DoRenameComputerWsman(string computer, string computerName, string protected override void ProcessRecord() { string targetComputer = ValidateComputerName(); - if (targetComputer == null) return; + if (targetComputer == null) + { + return; + } bool isLocalhost = targetComputer.Equals("localhost", StringComparison.OrdinalIgnoreCase); if (isLocalhost) @@ -1605,7 +1610,10 @@ protected override void ProcessRecord() /// protected override void EndProcessing() { - if (!_containsLocalHost) return; + if (!_containsLocalHost) + { + return; + } DoRenameComputerAction("localhost", _newNameForLocalHost, true); } @@ -2011,54 +2019,24 @@ internal static void WriteNonTerminatingError(int errorcode, PSCmdlet cmdlet, st /// internal static bool IsComputerNameValid(string computerName) { - bool allDigits = true; + bool hasAsciiLetterOrHyphen = false; if (computerName.Length >= 64) return false; foreach (char t in computerName) { - if (t >= 'A' && t <= 'Z' || - t >= 'a' && t <= 'z') - { - allDigits = false; - continue; - } - else if (t >= '0' && t <= '9') - { - continue; - } - else if (t == '-') + if (char.IsAsciiLetter(t) || t is '-') { - allDigits = false; - continue; + hasAsciiLetterOrHyphen = true; } - else + else if (!char.IsAsciiDigit(t)) { return false; } } - return !allDigits; - } - - /// - /// System Restore APIs are not supported on the ARM platform. Skip the system restore operation is necessary. - /// - /// - /// - internal static bool SkipSystemRestoreOperationForARMPlatform(PSCmdlet cmdlet) - { - bool retValue = false; - if (PsUtils.IsRunningOnProcessorArchitectureARM()) - { - var ex = new InvalidOperationException(ComputerResources.SystemRestoreNotSupported); - var er = new ErrorRecord(ex, "SystemRestoreNotSupported", ErrorCategory.InvalidOperation, null); - cmdlet.WriteError(er); - retValue = true; - } - - return retValue; + return hasAsciiLetterOrHyphen; } /// @@ -2230,8 +2208,7 @@ internal static string ValidateComputerName( bool isIPAddress = false; try { - IPAddress unused; - isIPAddress = IPAddress.TryParse(nameToCheck, out unused); + isIPAddress = IPAddress.TryParse(nameToCheck, out _); } catch (Exception) { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs index fb01823790f..22092116330 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ComputerUnix.cs @@ -5,10 +5,13 @@ 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 @@ -36,13 +39,13 @@ protected override void BeginProcessing() { string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal); ErrorRecord error = new ErrorRecord( - new InvalidOperationException(errMsg), "Command Failed", ErrorCategory.OperationStopped, "localhost"); + new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost"); WriteError(error); } return; } - RunCommand("/sbin/shutdown", "-r now"); + RunShutdown("-r now"); } #endregion "Overrides" } @@ -67,7 +70,7 @@ public sealed class StopComputerCommand : CommandLineCmdletBase protected override void BeginProcessing() { var args = "-P now"; - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + if (Platform.IsMacOS) { args = "now"; } @@ -78,13 +81,13 @@ protected override void BeginProcessing() { string errMsg = StringUtil.Format("Command returned 0x{0:X}", retVal); ErrorRecord error = new ErrorRecord( - new InvalidOperationException(errMsg), "Command Failed", ErrorCategory.OperationStopped, "localhost"); + new InvalidOperationException(errMsg), "CommandFailed", ErrorCategory.OperationStopped, "localhost"); WriteError(error); } return; } - RunCommand("/sbin/shutdown", args); + RunShutdown(args); } #endregion "Overrides" } @@ -95,7 +98,7 @@ protected override void BeginProcessing() public class CommandLineCmdletBase : PSCmdlet, IDisposable { #region Private Members - private Process _process = null; + private Process? _process = null; #endregion #region "IDisposable Members" @@ -150,22 +153,52 @@ protected override void StopProcessing() #region "Internals" + private static string? shutdownPath; + /// - /// Run a command. + /// Run shutdown command. /// - protected void RunCommand(String command, String args) { + 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 = "/sbin/shutdown", + 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 } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs index 0c990292b58..e7b3ada4ebb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ContentCommandBase.cs @@ -244,7 +244,7 @@ internal void WriteContentObject(object content, long readCount, PathInfo pathIn /// as they get written to the pipeline. An instance of this cache class is /// only valid for a single path. /// - internal class ContentPathsCache + internal sealed class ContentPathsCache { /// /// Constructs a content cache item. @@ -377,10 +377,7 @@ internal void CloseContent(List contentHolders, bool disposing) { try { - if (holder.Writer != null) - { - holder.Writer.Close(); - } + holder.Writer?.Close(); } catch (Exception e) // Catch-all OK. 3rd party callout { @@ -414,10 +411,7 @@ internal void CloseContent(List contentHolders, bool disposing) try { - if (holder.Reader != null) - { - holder.Reader.Close(); - } + holder.Reader?.Close(); } catch (Exception e) // Catch-all OK. 3rd party callout { diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs deleted file mode 100644 index fffb36d2979..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ControlPanelItemCommand.cs +++ /dev/null @@ -1,762 +0,0 @@ -// 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("\\", StringComparison.OrdinalIgnoreCase) + 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/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs index c32d0f2aa67..33796b23378 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ConvertPathCommand.cs @@ -55,6 +55,16 @@ public string[] LiteralPath } } + /// + /// Gets or sets the force property. + /// + [Parameter] + public override SwitchParameter Force + { + get => base.Force; + set => base.Force = value; + } + #endregion Parameters #region parameter data diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs deleted file mode 100644 index 45c484744fa..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Eventlog.cs +++ /dev/null @@ -1,1452 +0,0 @@ -// 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 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/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs index d99ece1fb81..c049370e4b4 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetChildrenCommand.cs @@ -122,7 +122,7 @@ public override string[] Exclude /// Gets or sets the recurse switch. /// [Parameter] - [Alias("s")] + [Alias("s", "r")] public SwitchParameter Recurse { get diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs index dd878bd72ce..a2b7f03ce70 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetClipboardCommand.cs @@ -2,8 +2,10 @@ // 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 @@ -34,6 +36,13 @@ public SwitchParameter Raw } } + /// + /// 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; /// @@ -68,11 +77,40 @@ private List GetClipboardContentAsText() } else { - string[] splitSymbol = { Environment.NewLine }; - result.AddRange(textContent.Split(splitSymbol, StringSplitOptions.None)); + 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/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs index 4c8a95dddeb..65d57194f5d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetComputerInfoCommand.cs @@ -17,8 +17,6 @@ namespace Microsoft.PowerShell.Commands { - using Extensions; - #region GetComputerInfoCommand cmdlet implementation /// /// The Get-ComputerInfo cmdlet gathers and reports information @@ -31,7 +29,7 @@ namespace Microsoft.PowerShell.Commands public class GetComputerInfoCommand : PSCmdlet { #region Inner Types - private class OSInfoGroup + private sealed class OSInfoGroup { public WmiOperatingSystem os; public HotFix[] hotFixes; @@ -41,7 +39,7 @@ private class OSInfoGroup public RegWinNtCurrentVersion regCurVer; } - private class SystemInfoGroup + private sealed class SystemInfoGroup { public WmiBaseBoard baseboard; public WmiBios bios; @@ -50,7 +48,7 @@ private class SystemInfoGroup public NetworkAdapter[] networkAdapters; } - private class HyperVInfo + private sealed class HyperVInfo { public bool? Present; public bool? VMMonitorModeExtensions; @@ -59,13 +57,13 @@ private class HyperVInfo public bool? DataExecutionPreventionAvailable; } - private class DeviceGuardInfo + private sealed class DeviceGuardInfo { public DeviceGuardSmartStatus status; public DeviceGuard deviceGuard; } - private class MiscInfoGroup + private sealed class MiscInfoGroup { public ulong? physicallyInstalledMemory; public string timeZone; @@ -248,7 +246,7 @@ private static string GetHalVersion(CimSession session, string systemDirectory) try { var halPath = CIMHelper.EscapePath(System.IO.Path.Combine(systemDirectory, "hal.dll")); - var query = string.Format("SELECT * FROM CIM_DataFile Where Name='{0}'", halPath); + var query = string.Create(CultureInfo.InvariantCulture, $"SELECT * FROM CIM_DataFile Where Name='{halPath}'"); var instance = session.QueryFirstInstance(query); if (instance != null) @@ -1125,16 +1123,13 @@ internal static string GetLocaleName(string locale) // 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 (UInt32.TryParse(locale, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint localeNum)) + if (uint.TryParse(locale, NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint localeNum)) { culture = CultureInfo.GetCultureInfo((int)localeNum); } - if (culture == null) - { - // If TryParse failed we'll try using the original string as culture name - culture = CultureInfo.GetCultureInfo(locale); - } + // If TryParse failed we'll try using the original string as culture name + culture ??= CultureInfo.GetCultureInfo(locale); } catch (Exception) { @@ -1193,7 +1188,7 @@ internal static class EnumConverter where T : struct, IConvertible /// /// /// A Nullable enum object. If the value - /// is convertable to a valid enum value, the returned object's + /// is convertible to a valid enum value, the returned object's /// value will contain the converted value, otherwise the returned /// object will be null. /// @@ -1231,11 +1226,11 @@ internal static class EnumConverter where T : struct, IConvertible internal static class RegistryInfo { - public static Dictionary GetServerLevels() + public static Dictionary GetServerLevels() { const string keyPath = @"Software\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels"; - var rv = new Dictionary(); + var rv = new Dictionary(); using (var key = Registry.LocalMachine.OpenSubKey(keyPath)) { @@ -1338,7 +1333,7 @@ protected static string GetLanguageName(uint? lcid) #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 class WmiBaseBoard + internal sealed class WmiBaseBoard { public string Caption; public string[] ConfigOptions; @@ -1371,9 +1366,9 @@ internal class WmiBaseBoard } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiBios : WmiClassBase + internal sealed class WmiBios : WmiClassBase { - public UInt16[] BiosCharacteristics; + public ushort[] BiosCharacteristics; public string[] BIOSVersion; public string BuildNumber; public string Caption; @@ -1406,7 +1401,7 @@ internal class WmiBios : WmiClassBase } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiComputerSystem + internal sealed class WmiComputerSystem { public ushort? AdminPasswordStatus; public bool? AutomaticManagedPagefile; @@ -1416,11 +1411,11 @@ internal class WmiComputerSystem public ushort? BootOptionOnWatchDog; public bool? BootROMSupported; public string BootupState; - public UInt16[] BootStatus; + public ushort[] BootStatus; public string Caption; public ushort? ChassisBootupState; public string ChassisSKUNumber; - public Int16? CurrentTimeZone; + public short? CurrentTimeZone; public bool? DaylightInEffect; public string Description; public string DNSHostName; @@ -1442,10 +1437,10 @@ internal class WmiComputerSystem public uint? NumberOfProcessors; public string[] OEMStringArray; public bool? PartOfDomain; - public Int64? PauseAfterReset; + public long? PauseAfterReset; public ushort? PCSystemType; public ushort? PCSystemTypeEx; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public ushort? PowerOnPasswordStatus; public ushort? PowerState; @@ -1453,8 +1448,8 @@ internal class WmiComputerSystem public string PrimaryOwnerContact; public string PrimaryOwnerName; public ushort? ResetCapability; - public Int16? ResetCount; - public Int16? ResetLimit; + public short? ResetCount; + public short? ResetLimit; public string[] Roles; public string Status; public string[] SupportContactDescription; @@ -1489,14 +1484,14 @@ public PowerManagementCapabilities[] GetPowerManagementCapabilities() } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiDeviceGuard + internal sealed class WmiDeviceGuard { - public UInt32[] AvailableSecurityProperties; + public uint[] AvailableSecurityProperties; public uint? CodeIntegrityPolicyEnforcementStatus; public uint? UsermodeCodeIntegrityPolicyEnforcementStatus; - public UInt32[] RequiredSecurityProperties; - public UInt32[] SecurityServicesConfigured; - public UInt32[] SecurityServicesRunning; + public uint[] RequiredSecurityProperties; + public uint[] SecurityServicesConfigured; + public uint[] SecurityServicesRunning; public uint? VirtualizationBasedSecurityStatus; public DeviceGuard AsOutputType @@ -1564,7 +1559,7 @@ public DeviceGuard AsOutputType } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiKeyboard + internal sealed class WmiKeyboard { public ushort? Availability; public string Caption; @@ -1582,7 +1577,7 @@ internal class WmiKeyboard public ushort? NumberOfFunctionKeys; public ushort? Password; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public string Status; public ushort? StatusInfo; @@ -1591,14 +1586,14 @@ internal class WmiKeyboard } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WMiLogicalMemory + 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 class WmiMsftNetAdapter + internal sealed class WmiMsftNetAdapter { public string Caption; public string Description; @@ -1613,7 +1608,7 @@ internal class WmiMsftNetAdapter public string ErrorDescription; public uint? LastErrorCode; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public ushort? StatusInfo; public string SystemCreationClassName; @@ -1680,13 +1675,13 @@ internal class WmiMsftNetAdapter public string PnPDeviceID; public string DriverProvider; public string ComponentID; - public UInt32[] LowerLayerInterfaceIndices; - public UInt32[] HigherLayerInterfaceIndices; + public uint[] LowerLayerInterfaceIndices; + public uint[] HigherLayerInterfaceIndices; public bool? AdminLocked; } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiNetworkAdapter + internal sealed class WmiNetworkAdapter { public string AdapterType; public ushort? AdapterTypeID; @@ -1717,7 +1712,7 @@ internal class WmiNetworkAdapter public string PermanentAddress; public bool? PhysicalAdapter; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public string ProductName; public string ServiceName; @@ -1730,7 +1725,7 @@ internal class WmiNetworkAdapter } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiNetworkAdapterConfiguration + internal sealed class WmiNetworkAdapterConfiguration { public bool? ArpAlwaysSourceRoute; public bool? ArpUseEtherSNAP; @@ -1753,7 +1748,7 @@ internal class WmiNetworkAdapterConfiguration public bool? DomainDNSRegistrationEnabled; public uint? ForwardBufferMemory; public bool? FullDNSRegistrationEnabled; - public UInt16[] GatewayCostMetric; + public ushort[] GatewayCostMetric; public byte? IGMPLevel; public uint? Index; public uint? InterfaceIndex; @@ -1769,7 +1764,7 @@ internal class WmiNetworkAdapterConfiguration public bool? IPUseZeroBroadcast; public string IPXAddress; public bool? IPXEnabled; - public UInt32[] IPXFrameType; + public uint[] IPXFrameType; public uint? IPXMediaType; public string[] IPXNetworkNumber; public string IPXVirtualNetNumber; @@ -1796,7 +1791,7 @@ internal class WmiNetworkAdapterConfiguration } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiOperatingSystem : WmiClassBase + internal sealed class WmiOperatingSystem : WmiClassBase { #region Fields public string BootDevice; @@ -1807,7 +1802,7 @@ internal class WmiOperatingSystem : WmiClassBase public string CountryCode; public string CSDVersion; public string CSName; - public Int16? CurrentTimeZone; + public short? CurrentTimeZone; public bool? DataExecutionPrevention_Available; public bool? DataExecutionPrevention_32BitApplications; public bool? DataExecutionPrevention_Drivers; @@ -1893,8 +1888,8 @@ private static OSProductSuite[] MakeProductSuites(uint? suiteMask) var mask = suiteMask.Value; var list = new List(); - foreach (OSProductSuite suite in Enum.GetValues(typeof(OSProductSuite))) - if ((mask & (UInt32)suite) != 0) + foreach (OSProductSuite suite in Enum.GetValues()) + if ((mask & (uint)suite) != 0) list.Add(suite); return list.ToArray(); @@ -1903,7 +1898,7 @@ private static OSProductSuite[] MakeProductSuites(uint? suiteMask) } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiPageFileUsage + internal sealed class WmiPageFileUsage { public uint? AllocatedBaseSize; public string Caption; @@ -1917,7 +1912,7 @@ internal class WmiPageFileUsage } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "Class is instantiated directly from a CIM instance")] - internal class WmiProcessor + internal sealed class WmiProcessor { public ushort? AddressWidth; public ushort? Architecture; @@ -1954,7 +1949,7 @@ internal class WmiProcessor public string OtherFamilyDescription; public string PartNumber; public string PNPDeviceID; - public UInt16[] PowerManagementCapabilities; + public ushort[] PowerManagementCapabilities; public bool? PowerManagementSupported; public string ProcessorId; public ushort? ProcessorType; @@ -1980,7 +1975,7 @@ internal class WmiProcessor #endregion Intermediate WMI classes #region Other Intermediate classes - internal class RegWinNtCurrentVersion + internal sealed class RegWinNtCurrentVersion { public string BuildLabEx; public string CurrentVersion; @@ -2282,7 +2277,7 @@ public class ComputerInfo /// the System Management BIOS Reference Specification. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt16[] BiosCharacteristics { get; internal set; } + public ushort[] BiosCharacteristics { get; internal set; } /// /// Array of the complete system BIOS information. In many computers @@ -2320,12 +2315,12 @@ public class ComputerInfo /// /// Major version of the embedded controller firmware. /// - public Int16? BiosEmbeddedControllerMajorVersion { get; internal set; } + public short? BiosEmbeddedControllerMajorVersion { get; internal set; } /// /// Minor version of the embedded controller firmware. /// - public Int16? BiosEmbeddedControllerMinorVersion { get; internal set; } + public short? BiosEmbeddedControllerMinorVersion { get; internal set; } /// /// Firmware type of the local computer. @@ -2496,7 +2491,7 @@ public class ComputerInfo /// Status and Additional Data fields that identify the boot status. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public UInt16[] CsBootStatus { get; internal set; } + public ushort[] CsBootStatus { get; internal set; } /// /// System is started. Fail-safe boot bypasses the user startup files—also called SafeBoot. @@ -2524,7 +2519,7 @@ public class ComputerInfo /// Amount of time the unitary computer system is offset from Coordinated /// Universal Time (UTC). /// - public Int16? CsCurrentTimeZone { get; internal set; } + public short? CsCurrentTimeZone { get; internal set; } /// /// If True, the daylight savings mode is ON. @@ -2675,7 +2670,7 @@ public class ComputerInfo /// and automatic system reset. A value of –1 (minus one) indicates that /// the pause value is unknown. /// - public Int64? CsPauseAfterReset { get; internal set; } + public long? CsPauseAfterReset { get; internal set; } /// /// Type of the computer in use, such as laptop, desktop, or tablet. @@ -2743,13 +2738,13 @@ public class ComputerInfo /// Number of automatic resets since the last reset. /// A value of –1 (minus one) indicates that the count is unknown. /// - public Int16? CsResetCount { get; internal set; } + 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 Int16? CsResetLimit { get; internal set; } + public short? CsResetLimit { get; internal set; } /// /// Array that specifies the roles of a system in the information @@ -2909,7 +2904,7 @@ public class ComputerInfo /// Number, in minutes, an operating system is offset from Greenwich /// mean time (GMT). The number is positive, negative, or zero. /// - public Int16? OsCurrentTimeZone { get; internal set; } + public short? OsCurrentTimeZone { get; internal set; } /// /// Language identifier used by the operating system. @@ -3058,7 +3053,7 @@ public class ComputerInfo public ulong? OsFreeSpaceInPagingFiles { get; internal set; } /// - /// Array of fiel paths to the operating system's paging files. + /// Array of file paths to the operating system's paging files. /// [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] OsPagingFiles { get; internal set; } @@ -3328,9 +3323,9 @@ public enum AdminPasswordStatus [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 - // + // + // This value is reserved + // // Reserved = 0, /// @@ -3687,7 +3682,22 @@ public enum DeviceGuardHardwareSecure /// /// Secure Memory Overwrite. /// - SecureMemoryOverwrite = 4 + SecureMemoryOverwrite = 4, + + /// + /// UEFI Code Readonly. + /// + UEFICodeReadonly = 5, + + /// + /// SMM Security Mitigations 1.0. + /// + SMMSecurityMitigations = 6, + + /// + /// Mode Based Execution Control. + /// + ModeBasedExecutionControl = 7 } /// @@ -5086,7 +5096,7 @@ public enum SoftwareElementState #endregion Output components #region Native - internal static class Native + internal static partial class Native { private static class PInvokeDllNames { @@ -5099,24 +5109,24 @@ private static class PInvokeDllNames public const uint POWER_PLATFORM_ROLE_V1 = 0x1; public const uint POWER_PLATFORM_ROLE_V2 = 0x2; - public const UInt32 S_OK = 0; + 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. - [DllImport(PInvokeDllNames.PowerDeterminePlatformRoleExDllName, EntryPoint = "PowerDeterminePlatformRoleEx", CharSet = CharSet.Ansi)] - public static extern uint PowerDeterminePlatformRoleEx(uint version); + [LibraryImport(PInvokeDllNames.PowerDeterminePlatformRoleExDllName, EntryPoint = "PowerDeterminePlatformRoleEx")] + public static partial uint PowerDeterminePlatformRoleEx(uint version); /// /// Retrieve the amount of RAM physically installed in the computer. /// /// /// - [DllImport(PInvokeDllNames.GetPhysicallyInstalledSystemMemoryDllName, SetLastError = true)] + [LibraryImport(PInvokeDllNames.GetPhysicallyInstalledSystemMemoryDllName)] [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool GetPhysicallyInstalledSystemMemory(out ulong MemoryInKilobytes); + public static partial bool GetPhysicallyInstalledSystemMemory(out ulong MemoryInKilobytes); /// /// Retrieve the firmware type of the local computer. @@ -5126,9 +5136,9 @@ private static class PInvokeDllNames /// the resultant firmware type /// /// - [DllImport(PInvokeDllNames.GetFirmwareTypeDllName, SetLastError = true)] + [LibraryImport(PInvokeDllNames.GetFirmwareTypeDllName)] [return: MarshalAs(UnmanagedType.Bool)] - public static extern bool GetFirmwareType(out FirmwareType firmwareType); + public static partial bool GetFirmwareType(out FirmwareType firmwareType); /// /// Gets the data specified for the passed in property name from the @@ -5137,8 +5147,8 @@ private static class PInvokeDllNames /// Name of the licensing property to get. /// Out parameter for the value. /// An hresult indicating success or failure. - [DllImport("slc.dll", CharSet = CharSet.Unicode)] - internal static extern int SLGetWindowsInformationDWORD(string licenseProperty, out int propertyValue); + [LibraryImport("slc.dll", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int SLGetWindowsInformationDWORD(string licenseProperty, out int propertyValue); } #endregion Native } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs index f689695fc38..a9d8772a5fc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetContentCommand.cs @@ -31,48 +31,20 @@ public class GetContentCommand : ContentCommandBase public long ReadCount { get; set; } = 1; /// - /// The number of content items to retrieve. By default this - /// value is -1 which means read all the content. + /// The number of content items to retrieve. /// [Parameter(ValueFromPipelineByPropertyName = true)] + [ValidateRange(0, long.MaxValue)] [Alias("First", "Head")] - public long TotalCount - { - get - { - return _totalCount; - } - - set - { - _totalCount = value; - _totalCountSpecified = true; - } - } - - private bool _totalCountSpecified = false; + 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 - { - return _backCount; - } - - set - { - _backCount = value; - _tailSpecified = true; - } - } - - private int _backCount = -1; - private bool _tailSpecified = false; + public int Tail { get; set; } = -1; /// /// A virtual method for retrieving the dynamic parameters for a cmdlet. Derived cmdlets @@ -98,15 +70,6 @@ internal override object GetDynamicParameters(CmdletProviderContext context) #endregion Parameters - #region parameter data - - /// - /// The number of content items to retrieve. - /// - private long _totalCount = -1; - - #endregion parameter data - #region Command code /// @@ -116,7 +79,7 @@ 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 (_totalCountSpecified && _tailSpecified) + if (TotalCount != -1 && Tail != -1) { string errMsg = StringUtil.Format(SessionStateStrings.GetContent_TailAndHeadCannotCoexist, "TotalCount", "Tail"); ErrorRecord error = new(new InvalidOperationException(errMsg), "TailAndHeadCannotCoexist", ErrorCategory.InvalidOperation, null); @@ -141,11 +104,9 @@ protected override void ProcessRecord() { long countRead = 0; - Dbg.Diagnostics.Assert( - holder.Reader != null, - "All holders should have a reader assigned"); + Dbg.Diagnostics.Assert(holder.Reader != null, "All holders should have a reader assigned"); - if (_tailSpecified && holder.Reader is not FileSystemContentReaderWriter) + if (Tail != -1 && holder.Reader is not FileSystemContentReaderWriter) { string errMsg = SessionStateStrings.GetContent_TailNotSupported; ErrorRecord error = new(new InvalidOperationException(errMsg), "TailNotSupported", ErrorCategory.InvalidOperation, Tail); @@ -153,7 +114,7 @@ protected override void ProcessRecord() continue; } - // If Tail is negative, we are supposed to read all content out. This is same + // 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. @@ -197,72 +158,61 @@ protected override void ProcessRecord() } } - if (TotalCount != 0) + IList results = null; + + do { - IList results = null; + long countToRead = ReadCount; - do + // 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)) { - long countToRead = ReadCount; + countToRead = TotalCount - countRead; + } - // 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 + 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); - if ((TotalCount > 0) && (countToRead == 0 || (TotalCount - countToRead < countRead))) - { - countToRead = TotalCount - countRead; - } + // Log a provider health event + MshLog.LogProviderHealthEvent(this.Context, holder.PathInfo.Provider.Name, providerException, Severity.Warning); + WriteError(new ErrorRecord(providerException.ErrorRecord, providerException)); - try - { - results = holder.Reader.Read(countToRead); - } - catch (Exception e) // Catch-all OK. 3rd party callout + break; + } + + if (results != null && results.Count > 0) + { + countRead += results.Count; + if (ReadCount == 1) { - 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; + // Write out the content as a single object + WriteContentObject(results[0], countRead, holder.PathInfo, currentContext); } - - if (results != null && results.Count > 0) + else { - 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); - } + // Write out the content as an array of objects + WriteContentObject(results, countRead, holder.PathInfo, currentContext); } - } while (results != null && results.Count > 0 && ((TotalCount < 0) || countRead < TotalCount)); - } + } + } while (results != null && results.Count > 0 && (TotalCount == -1 || countRead < TotalCount)); } } finally { - // close all the content readers + // Close all the content readers CloseContent(contentStreams, false); @@ -277,14 +227,14 @@ protected override void ProcessRecord() /// /// /// - /// true if no error occured + /// 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"); - var tailResultQueue = new Queue(); + Queue tailResultQueue = new(); IList results = null; ErrorRecord error = null; @@ -327,7 +277,10 @@ private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext foreach (object entry in results) { if (tailResultQueue.Count == Tail) + { tailResultQueue.Dequeue(); + } + tailResultQueue.Enqueue(entry); } } @@ -349,21 +302,25 @@ private bool ScanForwardsForTail(in ContentHolder holder, CmdletProviderContext { // 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) { - var outputList = new List((int)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); } - int remainder = tailResultQueue.Count; - if (remainder > 0) + if (tailResultQueue.Count > 0) { // Write out the content as an array of objects WriteContentObject(tailResultQueue.ToArray(), count, holder.PathInfo, currentContext); diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs deleted file mode 100644 index 484ddb96680..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetTransactionCommand.cs +++ /dev/null @@ -1,26 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs deleted file mode 100644 index f460b2c4957..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/GetWMIObjectCommand.cs +++ /dev/null @@ -1,441 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs index d6768a1315e..d0f15346396 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Hotfix.cs @@ -169,10 +169,7 @@ protected override void ProcessRecord() /// protected override void StopProcessing() { - if (_searchProcess != null) - { - _searchProcess.Dispose(); - } + _searchProcess?.Dispose(); } #endregion Overrides @@ -209,29 +206,11 @@ private bool FilterMatch(ManagementObject obj) #region "IDisposable Members" /// - /// Dispose Method. + /// Release all resources. /// 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) - { - if (_searchProcess != null) - { - _searchProcess.Dispose(); - } - } + _searchProcess?.Dispose(); } #endregion "IDisposable Members" diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs deleted file mode 100644 index df0c5775ca1..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/InvokeWMIMethodCommand.cs +++ /dev/null @@ -1,318 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/JobProcessCollection.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/JobProcessCollection.cs new file mode 100644 index 00000000000..78560543939 --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs index fb90ec1c502..a40cae64b9f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/MovePropertyCommand.cs @@ -61,10 +61,7 @@ public string[] Name set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _property = value; } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs index 23aa621266d..6ab8f1d652d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Navigation.cs @@ -25,7 +25,7 @@ public abstract class CoreCommandBase : PSCmdlet, IDynamicParameters /// An instance of the PSTraceSource class used for trace output /// using "NavigationCommands" as the category. /// - [Dbg.TraceSourceAttribute("NavigationCommands", "The namespace navigation tracer")] + [Dbg.TraceSource("NavigationCommands", "The namespace navigation tracer")] internal static readonly Dbg.PSTraceSource tracer = Dbg.PSTraceSource.GetTracer("NavigationCommands", "The namespace navigation tracer"); #endregion Tracer @@ -283,7 +283,7 @@ public class CoreCommandWithCredentialsBase : CoreCommandBase /// Gets or sets the credential parameter. /// [Parameter(ValueFromPipelineByPropertyName = true)] - [Credential()] + [Credential] public PSCredential Credential { get; set; } #endregion Parameters @@ -618,7 +618,7 @@ protected override void ProcessRecord() break; default: - Dbg.Diagnostics.Assert(false, string.Format(System.Globalization.CultureInfo.InvariantCulture, "One of the predefined parameter sets should have been specified, instead we got: {0}", ParameterSetName)); + 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; } } @@ -1075,7 +1075,7 @@ protected override void ProcessRecord() #region NewPSDriveCommand /// - /// Mounts a drive in the Monad namespace. + /// 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")] @@ -1129,6 +1129,7 @@ public string Description /// Gets or sets the scope identifier for the drive being created. /// [Parameter(ValueFromPipelineByPropertyName = true)] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } #if !UNIX @@ -1477,7 +1478,7 @@ internal List GetMatchingDrives( #region RemovePSDriveCommand /// - /// Removes a drive that is mounted in the Monad namespace. + /// 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")] @@ -1533,6 +1534,7 @@ public string[] PSProvider /// global scope until a drive of the given name is found to remove. /// [Parameter(ValueFromPipelineByPropertyName = true)] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } /// @@ -1653,7 +1655,7 @@ protected override void ProcessRecord() #region GetPSDriveCommand /// - /// Gets a specified or listing of drives that are mounted in the Monad + /// 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")] @@ -1701,6 +1703,7 @@ public string[] LiteralName /// Gets or sets the scope parameter to the command. /// [Parameter(ValueFromPipelineByPropertyName = true)] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } /// @@ -2699,7 +2702,7 @@ protected override void ProcessRecord() try { System.IO.DirectoryInfo di = new(providerPath); - if (di != null && (di.Attributes & System.IO.FileAttributes.ReparsePoint) != 0) + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(di)) { shouldRecurse = false; treatAsFile = true; @@ -2715,7 +2718,7 @@ protected override void ProcessRecord() { // Get the localized prompt string - string prompt = StringUtil.Format(NavigationResources.RemoveItemWithChildren, resolvedPath.Path); + 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 @@ -4128,7 +4131,7 @@ public class GetPSProviderCommand : CoreCommandBase /// Gets or sets the provider that will be removed. /// [Parameter(Position = 0, ValueFromPipelineByPropertyName = true)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string[] PSProvider { get => _provider; diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs index b2b9e6c1a85..fb134ce7a11 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/NewPropertyCommand.cs @@ -1,7 +1,11 @@ // 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 { @@ -63,6 +67,9 @@ public string[] LiteralPath /// [Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Type")] +#if !UNIX + [ArgumentCompleter(typeof(PropertyTypeArgumentCompleter))] +#endif public string PropertyType { get; set; } /// @@ -175,4 +182,114 @@ protected override void ProcessRecord() #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/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs index d56a20faba0..ca616301ebb 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ParsePathCommand.cs @@ -12,8 +12,8 @@ namespace Microsoft.PowerShell.Commands { /// - /// A command to resolve MSH paths containing glob characters to - /// MSH paths that match the glob strings. + /// 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, @@ -105,7 +105,7 @@ public string[] LiteralPath /// /// If true the qualifier of the path will be returned. /// The qualifier is the drive or provider that is qualifying - /// the MSH path. + /// the PowerShell path. /// [Parameter(ParameterSetName = qualifierSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] public SwitchParameter Qualifier { get; set; } @@ -116,7 +116,7 @@ public string[] LiteralPath /// /// If true the qualifier of the path will be returned. /// The qualifier is the drive or provider that is qualifying - /// the MSH path. + /// the PowerShell path. /// [Parameter(ParameterSetName = noQualifierSet, Mandatory = true, ValueFromPipelineByPropertyName = true)] public SwitchParameter NoQualifier { get; set; } @@ -289,137 +289,125 @@ protected override void ProcessRecord() { string result = null; - switch (ParameterSetName) + // Check switch parameters in order of specificity + if (IsAbsolute) { - case isAbsoluteSet: - string ignored; - bool isPathAbsolute = - SessionState.Path.IsPSAbsolute(pathsToParse[index], out ignored); + string ignored; + bool isPathAbsolute = + SessionState.Path.IsPSAbsolute(pathsToParse[index], out ignored); - WriteObject(isPathAbsolute); - continue; + WriteObject(isPathAbsolute); + continue; + } + else if (Qualifier) + { + int separatorIndex = pathsToParse[index].IndexOf(':'); - case qualifierSet: - 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 (separatorIndex < 0) - { - FormatException e = - new( - StringUtil.Format(NavigationResources.ParsePathFormatError, pathsToParse[index])); - WriteError( - new ErrorRecord( - e, - "ParsePathFormatError", // RENAME - ErrorCategory.InvalidArgument, - pathsToParse[index])); - continue; - } - else + if (SessionState.Path.IsProviderQualified(pathsToParse[index])) { - // 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); - } - } + // The plus 2 is for the length of the provider separator + // which is "::" - break; - - case parentSet: - case literalPathSet: - try - { result = - SessionState.Path.ParseParent( - pathsToParse[index], - string.Empty, - CmdletProviderContext, - true); + pathsToParse[index].Substring( + 0, + separatorIndex + 2); } - 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; - } - - break; - - case leafSet: - case leafBaseSet: - case extensionSet: - try + else { - // default handles leafSet 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); - } + pathsToParse[index].Substring( + 0, + separatorIndex + 1); } - catch (PSNotSupportedException) + } + } + else if (Leaf || LeafBase || Extension) + { + try + { + result = + SessionState.Path.ParseChildName( + pathsToParse[index], + CmdletProviderContext, + true); + if (LeafBase) { - // 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]; + result = System.IO.Path.GetFileNameWithoutExtension(result); } - catch (DriveNotFoundException driveNotFound) + else if (Extension) { - WriteError( - new ErrorRecord( - driveNotFound.ErrorRecord, - driveNotFound)); - continue; - } - catch (ProviderNotFoundException providerNotFound) - { - WriteError( - new ErrorRecord( - providerNotFound.ErrorRecord, - providerNotFound)); - continue; + result = System.IO.Path.GetExtension(result); } - - break; - - case noQualifierSet: - result = RemoveQualifier(pathsToParse[index]); - break; - - default: - Dbg.Diagnostics.Assert( - false, - "Only a known parameter set should be called"); - break; + } + 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) diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs deleted file mode 100644 index 9bebcd076ca..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/PingPathCommand.cs +++ /dev/null @@ -1,250 +0,0 @@ -// 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 (this.PathType == TestPathType.Any && !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 (path == null) - { - WriteError(new ErrorRecord( - new ArgumentNullException(TestPathResources.PathIsNullOrEmptyCollection), - "NullPathNotPermitted", - ErrorCategory.InvalidArgument, - Path)); - continue; - } - - if (string.IsNullOrWhiteSpace(path)) - { - WriteObject(result); - continue; - } - - try - { - if (IsValid) - { - result = SessionState.Path.IsValid(path, currentContext); - } - else - { - if (this.PathType == TestPathType.Container) - { - result = InvokeProvider.Item.IsContainer(path, currentContext); - } - else if (this.PathType == TestPathType.Leaf) - { - result = - InvokeProvider.Item.Exists(path, currentContext) && - !InvokeProvider.Item.IsContainer(path, currentContext); - } - else - { - result = InvokeProvider.Item.Exists(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/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs index 6656dcc549b..91efda12263 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Process.cs @@ -4,6 +4,7 @@ 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 @@ -11,18 +12,16 @@ 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; using System.Security.Principal; using System.Text; using System.Threading; using Microsoft.Management.Infrastructure; using Microsoft.PowerShell.Commands.Internal; using Microsoft.Win32.SafeHandles; -using DWORD = System.UInt32; -using FileNakedHandle = System.IntPtr; namespace Microsoft.PowerShell.Commands { @@ -266,30 +265,17 @@ private void RetrieveProcessesByInput() } /// - /// Retrieve the master list of all processes. + /// 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 - { - get - { - if (_allProcesses == null) - { - List processes = new(); - processes.AddRange(Process.GetProcesses()); - _allProcesses = processes.ToArray(); - } + internal Process[] AllProcesses => _allProcesses ??= Process.GetProcesses(); - return _allProcesses; - } - } - - private Process[] _allProcesses = null; + private Process[] _allProcesses; /// /// Add to , @@ -532,27 +518,20 @@ public override Process[] InputObject [Parameter(ParameterSetName = NameWithUserNameParameterSet, Mandatory = true)] [Parameter(ParameterSetName = IdWithUserNameParameterSet, Mandatory = true)] [Parameter(ParameterSetName = InputObjectWithUserNameParameterSet, Mandatory = true)] - public SwitchParameter IncludeUserName - { - get { return _includeUserName; } - - set { _includeUserName = value; } - } - - private bool _includeUserName = false; + 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)] @@ -564,20 +543,6 @@ public SwitchParameter IncludeUserName #region Overrides - /// - /// Check the elevation mode if IncludeUserName is specified. - /// - protected override void BeginProcessing() - { - // The parameter 'IncludeUserName' requires administrator privilege - if (IncludeUserName.IsPresent && !Utils.IsAdministrator()) - { - var ex = new InvalidOperationException(ProcessResources.IncludeUserNameRequiresElevation); - var er = new ErrorRecord(ex, "IncludeUserNameRequiresElevation", ErrorCategory.InvalidOperation, null); - ThrowTerminatingError(er); - } - } - /// /// Write the process objects. /// @@ -653,6 +618,10 @@ protected override void ProcessRecord() WriteNonTerminatingError(process, ex, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); } } + catch (PipelineStoppedException) + { + throw; + } catch (Exception exception) { WriteNonTerminatingError(process, exception, ProcessResources.CouldNotEnumerateModules, "CouldNotEnumerateModules", ErrorCategory.PermissionDenied); @@ -662,7 +631,7 @@ protected override void ProcessRecord() { try { - ProcessModule mainModule = PsUtils.GetMainModule(process); + ProcessModule mainModule = process.MainModule; if (mainModule != null) { WriteObject(mainModule.FileVersionInfo, true); @@ -682,7 +651,7 @@ protected override void ProcessRecord() { if (exception.HResult == 299) { - WriteObject(PsUtils.GetMainModule(process).FileVersionInfo, true); + WriteObject(process.MainModule?.FileVersionInfo, true); } else { @@ -701,7 +670,7 @@ protected override void ProcessRecord() } else { - WriteObject(IncludeUserName.IsPresent ? AddUserNameToProcess(process) : (object)process); + WriteObject(IncludeUserName.IsPresent ? AddUserNameToProcess(process) : process); } } } @@ -752,56 +721,46 @@ private static string RetrieveProcessUserName(Process process) try { - do + int error; + if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) { - int error; - if (!Win32Native.OpenProcessToken(process.Handle, TOKEN_QUERY, out processTokenHandler)) { break; } + 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)) + // 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) { - error = Marshal.GetLastWin32Error(); - if (error == Win32Native.ERROR_INSUFFICIENT_BUFFER) - { - Marshal.FreeHGlobal(tokenUserInfo); - tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); + Marshal.FreeHGlobal(tokenUserInfo); + tokenUserInfo = Marshal.AllocHGlobal(tokenInfoLength); - if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { break; } - } - else + if (!Win32Native.GetTokenInformation(processTokenHandler, Win32Native.TOKEN_INFORMATION_CLASS.TokenUser, tokenUserInfo, tokenInfoLength, out tokenInfoLength)) { - break; + return null; } } - - var tokenUser = Marshal.PtrToStructure(tokenUserInfo); - - // Max username is defined as UNLEN = 256 in lmcons.h - // Max domainname is defined as DNLEN = CNLEN = 15 in lmcons.h - // The buffer length must be +1, last position is for a null string terminator. - int userNameLength = 257; - int domainNameLength = 16; -#pragma warning disable CA2014 - Span userNameStr = stackalloc char[userNameLength]; - Span domainNameStr = stackalloc char[domainNameLength]; -#pragma warning restore CA2014 - Win32Native.SID_NAME_USE accountType; - - // userNameLength and domainNameLength will be set to actual lengths. - if (!Win32Native.LookupAccountSid(null, tokenUser.User.Sid, userNameStr, ref userNameLength, domainNameStr, ref domainNameLength, out accountType)) + else { - break; + return null; } + } - userName = string.Concat(domainNameStr.Slice(0, domainNameLength), "\\", userNameStr.Slice(0, userNameLength)); - } while (false); + 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. @@ -826,7 +785,6 @@ private static string RetrieveProcessUserName(Process process) Win32Native.CloseHandle(processTokenHandler); } } - #endif return userName; } @@ -840,6 +798,7 @@ private static string RetrieveProcessUserName(Process process) /// 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 @@ -914,6 +873,18 @@ public int Timeout } } + /// + /// 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; @@ -945,12 +916,9 @@ public void Dispose() // Handle Exited event and display process information. private void myProcess_Exited(object sender, System.EventArgs e) { - if (System.Threading.Interlocked.Decrement(ref _numberOfProcessesToWaitFor) == 0) + if (Any || (Interlocked.Decrement(ref _numberOfProcessesToWaitFor) == 0)) { - if (_waitHandle != null) - { - _waitHandle.Set(); - } + _waitHandle?.Set(); } } @@ -1000,7 +968,12 @@ protected override void EndProcessing() { try { - if (!process.HasExited) + // 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; @@ -1016,11 +989,12 @@ protected override void EndProcessing() } } + bool hasTimedOut = false; if (_numberOfProcessesToWaitFor > 0) { if (_timeOutSpecified) { - _waitHandle.WaitOne(_timeout * 1000); + hasTimedOut = !_waitHandle.WaitOne(_timeout * 1000); } else { @@ -1028,34 +1002,37 @@ protected override void EndProcessing() } } - foreach (Process process in _processList) + if (hasTimedOut || (!Any && _numberOfProcessesToWaitFor > 0)) { - try + foreach (Process process in _processList) { - if (!process.HasExited) + try { - string message = StringUtil.Format(ProcessResources.ProcessNotTerminated, new object[] { process.ProcessName, process.Id }); - ErrorRecord errorRecord = new(new TimeoutException(message), "ProcessNotTerminated", ErrorCategory.CloseError, process); - WriteError(errorRecord); + 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); } - } - catch (Win32Exception exception) - { - WriteNonTerminatingError(process, exception, ProcessResources.ProcessIsNotTerminated, "ProcessNotTerminated", ErrorCategory.CloseError); } } + + if (PassThru) + { + WriteObject(_processList, enumerateCollection: true); + } } /// /// StopProcessing. /// - protected override void StopProcessing() - { - if (_waitHandle != null) - { - _waitHandle.Set(); - } - } + protected override void StopProcessing() => _waitHandle?.Set(); + #endregion Overrides } @@ -1188,7 +1165,10 @@ protected override void ProcessRecord() SafeGetProcessName(process), SafeGetProcessId(process)); - if (!ShouldProcess(targetString)) { continue; } + if (!ShouldProcess(targetString)) + { + continue; + } try { @@ -1346,7 +1326,10 @@ private bool IsProcessOwnedByCurrentUser(Process process) } finally { - if (ph != IntPtr.Zero) { Win32Native.CloseHandle(ph); } + if (ph != IntPtr.Zero) + { + Win32Native.CloseHandle(ph); + } } return false; @@ -1506,7 +1489,10 @@ protected override void ProcessRecord() SafeGetProcessName(process), SafeGetProcessId(process)); - if (!ShouldProcess(targetMessage)) { continue; } + if (!ShouldProcess(targetMessage)) + { + continue; + } // Sometimes Idle process has processid zero,so handle that because we cannot attach debugger to it. if (process.Id == 0) @@ -1521,7 +1507,10 @@ protected override void ProcessRecord() { // 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; } + if (process.HasExited) + { + continue; + } } catch (NotSupportedException ex) { @@ -1572,8 +1561,7 @@ private void AttachDebuggerToProcess(Process process) } catch (CimException e) { - string message = e.Message; - if (!string.IsNullOrEmpty(message)) { message = message.Trim(); } + string message = e.Message?.Trim(); var errorRecord = new ErrorRecord( new InvalidOperationException(StringUtil.Format(ProcessResources.DebuggerError, message)), @@ -1589,16 +1577,17 @@ private void AttachDebuggerToProcess(Process process) /// private static string MapReturnCodeToErrorMessage(int returnCode) { - string errorMessage = string.Empty; - switch (returnCode) + string errorMessage = returnCode switch { - case 2: errorMessage = ProcessResources.AttachDebuggerReturnCode2; break; - case 3: errorMessage = ProcessResources.AttachDebuggerReturnCode3; break; - case 8: errorMessage = ProcessResources.AttachDebuggerReturnCode8; break; - case 9: errorMessage = ProcessResources.AttachDebuggerReturnCode9; break; - case 21: errorMessage = ProcessResources.AttachDebuggerReturnCode21; break; - default: Diagnostics.Assert(false, "Unreachable code."); break; - } + 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; } @@ -1614,7 +1603,7 @@ private static string MapReturnCodeToErrorMessage(int returnCode) [OutputType(typeof(Process))] public sealed class StartProcessCommand : PSCmdlet, IDisposable { - private ManualResetEvent _waithandle = null; + private readonly CancellationTokenSource _cancellationTokenSource = new(); private bool _isDefaultSetParameterSpecified = false; #region Parameters @@ -1687,7 +1676,7 @@ public SwitchParameter LoadUserProfile private SwitchParameter _loaduserprofile = SwitchParameter.Present; /// - /// Starts process in a new window. + /// Starts process in the current console window. /// [Parameter(ParameterSetName = "Default")] [Alias("nnw")] @@ -1787,6 +1776,7 @@ public string RedirectStandardOutput /// [Parameter(ParameterSetName = "UseShellExecute")] [ValidateNotNullOrEmpty] + [ArgumentCompleter(typeof(VerbArgumentCompleter))] public string Verb { get; set; } /// @@ -1837,6 +1827,26 @@ public SwitchParameter UseNewEnvironment 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 @@ -1893,6 +1903,7 @@ protected override void BeginProcessing() } 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 @@ -1925,8 +1936,12 @@ protected override void BeginProcessing() } else { - // Working Directory not specified -> Assign Current Path. - startInfo.WorkingDirectory = PathUtils.ResolveFilePath(this.SessionState.Path.CurrentFileSystemLocation.Path, this, isLiteralPath: true); + // 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")) @@ -1939,13 +1954,20 @@ protected override void BeginProcessing() if (_UseNewEnvironment) { startInfo.EnvironmentVariables.Clear(); - LoadEnvironmentVariable(startInfo, Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); - LoadEnvironmentVariable(startInfo, Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); + LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.Machine)); + LoadEnvironmentVariable(startInfo, System.Environment.GetEnvironmentVariables(EnvironmentVariableTarget.User)); + } + + if (_environment != null) + { + LoadEnvironmentVariable(startInfo, _environment); } startInfo.WindowStyle = _windowstyle; - if (_nonewwindow) + // 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; } @@ -2025,15 +2047,89 @@ protected override void BeginProcessing() } else if (ParameterSetName.Equals("UseShellExecute")) { - if (Verb != null) { startInfo.Verb = Verb; } + if (Verb != null) + { + startInfo.Verb = Verb; + } startInfo.WindowStyle = _windowstyle; } string targetMessage = StringUtil.Format(ProcessResources.StartProcessTarget, startInfo.FileName, startInfo.Arguments.Trim()); - if (!ShouldProcess(targetMessage)) { return; } + if (!ShouldProcess(targetMessage)) + { + return; + } - Process process = Start(startInfo); + 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) { @@ -2056,23 +2152,20 @@ protected override void BeginProcessing() if (!process.HasExited) { #if UNIX - process.WaitForExit(); + process.WaitForExitAsync(_cancellationTokenSource.Token).GetAwaiter().GetResult(); #else - _waithandle = new ManualResetEvent(false); - - // Create and start the job object - ProcessCollection jobObject = new(); - if (jobObject.AssignProcessToJobObject(process)) + // 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.WaitOne(_waithandle); + jobObject.WaitForExit(_cancellationTokenSource.Token); } - else if (!process.HasExited) + else { // WinBlue: 27537 Start-Process -Wait doesn't work in a remote session on Windows 7 or lower. - process.Exited += myProcess_Exited; - process.EnableRaisingEvents = true; - process.WaitForExit(); + // 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 } @@ -2088,51 +2181,27 @@ protected override void BeginProcessing() /// /// Implements ^c, after creating a process. /// - protected override void StopProcessing() - { - if (_waithandle != null) - { - _waithandle.Set(); - } - } + protected override void StopProcessing() => _cancellationTokenSource.Cancel(); #endregion #region IDisposable Overrides /// - /// Dispose WaitHandle used to honor -Wait parameter. + /// Release all resources. /// + /// + /// Dispose WaitHandle used to honor -Wait parameter. + /// public void Dispose() { - Dispose(true); - System.GC.SuppressFinalize(this); - } - - private void Dispose(bool isDisposing) - { - if (_waithandle != null) - { - _waithandle.Dispose(); - _waithandle = null; - } + _cancellationTokenSource.Dispose(); } #endregion #region Private Methods - /// - /// When Process exits the wait handle is set. - /// - private void myProcess_Exited(object sender, System.EventArgs e) - { - if (_waithandle != null) - { - _waithandle.Set(); - } - } - private string ResolveFilePath(string path) { string filepath = PathUtils.ResolveFilePath(path, this); @@ -2149,50 +2218,22 @@ private static void LoadEnvironmentVariable(ProcessStartInfo startinfo, IDiction processEnvironment.Remove(entry.Key.ToString()); } - if (entry.Key.ToString().Equals("PATH")) + if (entry.Value != null) { - processEnvironment.Add(entry.Key.ToString(), Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.Machine) + ";" + Environment.GetEnvironmentVariable(entry.Key.ToString(), EnvironmentVariableTarget.User)); - } - else - { - processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); - } - } - } - - private Process Start(ProcessStartInfo startInfo) - { - Process process = null; - if (startInfo.UseShellExecute) - { - process = StartWithShellExecute(startInfo); - } - else - { + if (entry.Key.ToString().Equals("PATH")) + { #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); - } + processEnvironment.Add(entry.Key.ToString(), entry.Value.ToString()); #else - process = StartWithCreateProcess(startInfo); + 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()); + } + } } - - return process; } #if UNIX @@ -2230,15 +2271,8 @@ private void StreamClosing() { Thread.Sleep(1000); - if (_outputWriter != null) - { - _outputWriter.Dispose(); - } - - if (_errorWriter != null) - { - _errorWriter.Dispose(); - } + _outputWriter?.Dispose(); + _errorWriter?.Dispose(); } private void SetupInputOutputRedirection(Process p) @@ -2299,28 +2333,22 @@ private void WriteToStandardInput(Process p) writer.Dispose(); } #else - private SafeFileHandle GetSafeFileHandleForRedirection(string RedirectionPath, uint dwCreationDisposition) - { - System.IntPtr hFileHandle = System.IntPtr.Zero; - ProcessNativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes = new(); - - hFileHandle = ProcessNativeMethods.CreateFileW(RedirectionPath, - ProcessNativeMethods.GENERIC_READ | ProcessNativeMethods.GENERIC_WRITE, - ProcessNativeMethods.FILE_SHARE_WRITE | ProcessNativeMethods.FILE_SHARE_READ, - lpSecurityAttributes, - dwCreationDisposition, - ProcessNativeMethods.FILE_ATTRIBUTE_NORMAL, - System.IntPtr.Zero); - if (hFileHandle == System.IntPtr.Zero) - { - int error = Marshal.GetLastWin32Error(); - Win32Exception win32ex = new(error); + + 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); } - SafeFileHandle sf = new(hFileHandle, true); return sf; } @@ -2376,16 +2404,31 @@ private static byte[] ConvertEnvVarsToByteArray(StringDictionary sd) 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, ProcessNativeMethods.OPEN_EXISTING); + lpStartupInfo.hStdInput = GetSafeFileHandleForRedirection(_redirectstandardinput, FileMode.Open); } - else + else if (startinfo.CreateNoWindow) { - lpStartupInfo.hStdInput = new SafeFileHandle(ProcessNativeMethods.GetStdHandle(-10), false); + lpStartupInfo.hStdInput = new SafeFileHandle( + ProcessNativeMethods.GetStdHandle(-10), + ownsHandle: false); } // RedirectionStandardOutput @@ -2393,11 +2436,13 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods { startinfo.RedirectStandardOutput = true; _redirectstandardoutput = ResolveFilePath(_redirectstandardoutput); - lpStartupInfo.hStdOutput = GetSafeFileHandleForRedirection(_redirectstandardoutput, ProcessNativeMethods.CREATE_ALWAYS); + lpStartupInfo.hStdOutput = GetSafeFileHandleForRedirection(_redirectstandardoutput, FileMode.Create); } - else + else if (startinfo.CreateNoWindow) { - lpStartupInfo.hStdOutput = new SafeFileHandle(ProcessNativeMethods.GetStdHandle(-11), false); + lpStartupInfo.hStdOutput = new SafeFileHandle( + ProcessNativeMethods.GetStdHandle(-11), + ownsHandle: false); } // RedirectionStandardError @@ -2405,15 +2450,20 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods { startinfo.RedirectStandardError = true; _redirectstandarderror = ResolveFilePath(_redirectstandarderror); - lpStartupInfo.hStdError = GetSafeFileHandleForRedirection(_redirectstandarderror, ProcessNativeMethods.CREATE_ALWAYS); + lpStartupInfo.hStdError = GetSafeFileHandleForRedirection(_redirectstandarderror, FileMode.Create); } - else + else if (startinfo.CreateNoWindow) { - lpStartupInfo.hStdError = new SafeFileHandle(ProcessNativeMethods.GetStdHandle(-12), false); + lpStartupInfo.hStdError = new SafeFileHandle( + ProcessNativeMethods.GetStdHandle(-12), + ownsHandle: false); } - // STARTF_USESTDHANDLES - lpStartupInfo.dwFlags = 0x100; + if (hasRedirection) + { + // Set STARTF_USESTDHANDLES only if there is redirection. + lpStartupInfo.dwFlags = 0x100; + } if (startinfo.CreateNoWindow) { @@ -2457,10 +2507,10 @@ private void SetStartupInfo(ProcessStartInfo startinfo, ref ProcessNativeMethods /// /// This method will be used on all windows platforms, both full desktop and headless SKUs. /// - private Process StartWithCreateProcess(ProcessStartInfo startinfo) + private ProcessInformation StartWithCreateProcess(ProcessStartInfo startinfo) { ProcessNativeMethods.STARTUPINFO lpStartupInfo = new(); - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); + ProcessNativeMethods.PROCESS_INFORMATION lpProcessInformation = new(); int error = 0; GCHandle pinnedEnvironmentBlock = new(); IntPtr AddressOfEnvironmentBlock = IntPtr.Zero; @@ -2507,7 +2557,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) 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, lpProcessInformation); + flag = ProcessNativeMethods.CreateProcessWithLogonW(startinfo.UserName, startinfo.Domain, password, logonFlags, null, cmdLine, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); if (!flag) { error = Marshal.GetLastWin32Error(); @@ -2563,7 +2613,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) ProcessNativeMethods.SECURITY_ATTRIBUTES lpProcessAttributes = new(); ProcessNativeMethods.SECURITY_ATTRIBUTES lpThreadAttributes = new(); - flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, lpProcessInformation); + flag = ProcessNativeMethods.CreateProcess(null, cmdLine, lpProcessAttributes, lpThreadAttributes, true, creationFlags, AddressOfEnvironmentBlock, startinfo.WorkingDirectory, lpStartupInfo, ref lpProcessInformation); if (!flag) { error = Marshal.GetLastWin32Error(); @@ -2576,11 +2626,7 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) Label_03AE: - // At this point, we should have a suspended process. Get the .Net Process object, resume the process, and return. - Process result = Process.GetProcessById(lpProcessInformation.dwProcessId); - ProcessNativeMethods.ResumeThread(lpProcessInformation.hThread); - - return result; + return new ProcessInformation(lpProcessInformation); } finally { @@ -2594,7 +2640,6 @@ private Process StartWithCreateProcess(ProcessStartInfo startinfo) } lpStartupInfo.Dispose(); - lpProcessInformation.Dispose(); } } #endif @@ -2621,122 +2666,120 @@ private Process StartWithShellExecute(ProcessStartInfo startInfo) #endregion } -#if !UNIX /// - /// ProcessCollection 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. + /// Provides argument completion for Verb parameter. /// - internal class ProcessCollection + public class VerbArgumentCompleter : IArgumentCompleter { /// - /// 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 readonly Microsoft.PowerShell.Commands.SafeJobHandle _jobObjectHandle; - - /// - /// ProcessCollection constructor. + /// Returns completion results for verb parameter. /// - internal ProcessCollection() + /// 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) { - IntPtr jobObjectHandleIntPtr = NativeMethods.CreateJobObject(IntPtr.Zero, null); - _jobObjectHandle = new SafeJobHandle(jobObjectHandleIntPtr); - } + // -Verb is not supported on non-Windows platforms as well as Windows headless SKUs + if (!Platform.IsWindowsDesktop) + { + return Array.Empty(); + } - /// - /// Start API assigns the process to the JobObject and starts monitoring - /// the child processes hosted by the process created by Start-Process cmdlet. - /// - internal bool AssignProcessToJobObject(Process process) - { - // Add the process to the job object - bool result = NativeMethods.AssignProcessToJobObject(_jobObjectHandle, process.Handle); - return result; - } + // Completion: Start-Process -FilePath -Verb + if (commandName.Equals("Start-Process", StringComparison.OrdinalIgnoreCase) + && fakeBoundParameters.Contains("FilePath")) + { + string filePath = fakeBoundParameters["FilePath"].ToString(); - /// - /// Checks to see if the JobObject is empty (has no assigned processes). - /// If job is empty the auto reset event supplied as input would be set. - /// - internal void CheckJobStatus(object stateInfo) - { - ManualResetEvent emptyJobAutoEvent = (ManualResetEvent)stateInfo; - int dwSize = 0; - const int JOB_OBJECT_BASIC_PROCESS_ID_LIST = 3; - JOBOBJECT_BASIC_PROCESS_ID_LIST JobList = new(); + // Complete file verbs if extension exists + if (Path.HasExtension(filePath)) + { + return CompleteFileVerbs(wordToComplete, filePath); + } - dwSize = Marshal.SizeOf(JobList); - if (NativeMethods.QueryInformationJobObject(_jobObjectHandle, - JOB_OBJECT_BASIC_PROCESS_ID_LIST, - ref JobList, dwSize, IntPtr.Zero)) - { - if (JobList.NumberOfAssignedProcess == 0) + // 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) { - emptyJobAutoEvent.Set(); + return CompleteFileVerbs(wordToComplete, filePath: commands[0].Source); } } + + return Array.Empty(); } /// - /// WaitOne blocks the current thread until the current instance receives a signal, using - /// a System.TimeSpan to measure the time interval and specifying whether to - /// exit the synchronization domain before the wait. + /// Completes file verbs. /// - /// - /// WaitHandle to use for waiting on the job object. - /// - internal void WaitOne(ManualResetEvent waitHandleToUse) - { - TimerCallback jobObjectStatusCb = this.CheckJobStatus; - using (Timer stateTimer = new(jobObjectStatusCb, waitHandleToUse, 0, 1000)) - { - waitHandleToUse.WaitOne(); - } - } + /// 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 /// - /// JOBOBJECT_BASIC_PROCESS_ID_LIST Contains the process identifier list for a job object. - /// If the job is nested, the process identifier list consists of all - /// processes associated with the job and its child jobs. + /// 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. /// - [StructLayout(LayoutKind.Sequential)] - internal struct JOBOBJECT_BASIC_PROCESS_ID_LIST + internal sealed class ProcessInformation : IDisposable { - /// - /// The number of process identifiers to be stored in ProcessIdList. - /// - public uint NumberOfAssignedProcess; + public SafeProcessHandle Process { get; } - /// - /// The number of process identifiers returned in the ProcessIdList buffer. - /// If this number is less than NumberOfAssignedProcesses, increase - /// the size of the buffer to accommodate the complete list. - /// - public uint NumberOfProcessIdsInList; + public SafeProcessHandle Thread { get; } - /// - /// A variable-length array of process identifiers returned by this call. - /// Array elements 0 through NumberOfProcessIdsInList minus 1 - /// contain valid process identifiers. - /// - public IntPtr ProcessIdList; + 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 { - // Fields - internal static readonly UInt32 GENERIC_READ = 0x80000000; - internal static readonly UInt32 GENERIC_WRITE = 0x40000000; - internal static readonly UInt32 FILE_ATTRIBUTE_NORMAL = 0x80000000; - internal static readonly UInt32 CREATE_ALWAYS = 2; - internal static readonly UInt32 FILE_SHARE_WRITE = 0x00000002; - internal static readonly UInt32 FILE_SHARE_READ = 0x00000001; - internal static readonly UInt32 OF_READWRITE = 0x00000002; - internal static readonly UInt32 OPEN_EXISTING = 3; - - // Methods - [DllImport(PinvokeDllNames.GetStdHandleDllName, SetLastError = true)] public static extern IntPtr GetStdHandle(int whichHandle); @@ -2752,7 +2795,7 @@ internal static extern bool CreateProcessWithLogonW(string userName, IntPtr environmentBlock, [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, STARTUPINFO lpStartupInfo, - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation); + ref PROCESS_INFORMATION lpProcessInformation); [DllImport(PinvokeDllNames.CreateProcessDllName, CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] @@ -2765,22 +2808,11 @@ public static extern bool CreateProcess([MarshalAs(UnmanagedType.LPWStr)] string IntPtr lpEnvironment, [MarshalAs(UnmanagedType.LPWStr)] string lpCurrentDirectory, STARTUPINFO lpStartupInfo, - SafeNativeMethods.PROCESS_INFORMATION lpProcessInformation); + ref PROCESS_INFORMATION lpProcessInformation); [DllImport(PinvokeDllNames.ResumeThreadDllName, CharSet = CharSet.Unicode, SetLastError = true)] public static extern uint ResumeThread(IntPtr threadHandle); - [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] - public static extern FileNakedHandle CreateFileW( - [In, MarshalAs(UnmanagedType.LPWStr)] string lpFileName, - DWORD dwDesiredAccess, - DWORD dwShareMode, - ProcessNativeMethods.SECURITY_ATTRIBUTES lpSecurityAttributes, - DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, - System.IntPtr hTemplateFile - ); - [DllImport("userenv.dll", CharSet = CharSet.Unicode, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit); @@ -2797,7 +2829,16 @@ internal enum LogonFlags } [StructLayout(LayoutKind.Sequential)] - internal class SECURITY_ATTRIBUTES + 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; @@ -2835,7 +2876,7 @@ protected override bool ReleaseHandle() } [StructLayout(LayoutKind.Sequential)] - internal class STARTUPINFO + internal sealed class STARTUPINFO { public int cb; public IntPtr lpReserved; @@ -2898,72 +2939,6 @@ public void Dispose() } } } - - internal static class SafeNativeMethods - { - [DllImport(PinvokeDllNames.CloseHandleDllName, SetLastError = true, ExactSpelling = true)] - public static extern bool CloseHandle(IntPtr handle); - - [StructLayout(LayoutKind.Sequential)] - internal class PROCESS_INFORMATION - { - public IntPtr hProcess; - public IntPtr hThread; - public int dwProcessId; - public int dwThreadId; - - public PROCESS_INFORMATION() - { - this.hProcess = IntPtr.Zero; - this.hThread = IntPtr.Zero; - } - - /// - /// Dispose. - /// - public void Dispose() - { - Dispose(true); - } - - /// - /// Dispose. - /// - /// - private void Dispose(bool disposing) - { - if (disposing) - { - if (this.hProcess != IntPtr.Zero) - { - CloseHandle(this.hProcess); - this.hProcess = IntPtr.Zero; - } - - if (this.hThread != IntPtr.Zero) - { - CloseHandle(this.hThread); - this.hThread = IntPtr.Zero; - } - } - } - } - } - - [SuppressUnmanagedCodeSecurity] - internal sealed class SafeJobHandle : SafeHandleZeroOrMinusOneIsInvalid - { - internal SafeJobHandle(IntPtr jobHandle) - : base(true) - { - base.SetHandle(jobHandle); - } - - protected override bool ReleaseHandle() - { - return SafeNativeMethods.CloseHandle(base.handle); - } - } #endif #endregion @@ -2971,7 +2946,6 @@ protected override bool ReleaseHandle() /// /// Non-terminating errors occurring in the process noun commands. /// - [Serializable] public class ProcessCommandException : SystemException { #region ctors @@ -3011,29 +2985,14 @@ public ProcessCommandException(string message, Exception innerException) /// /// /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ProcessCommandException( SerializationInfo info, StreamingContext context) - : base(info, context) { - _processName = info.GetString("ProcessName"); + throw new NotSupportedException(); } - /// - /// Serializer. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData( - SerializationInfo info, - StreamingContext context) - { - base.GetObjectData(info, context); - if (info == null) - throw new ArgumentNullException(nameof(info)); - - info.AddValue("ProcessName", _processName); - } #endregion Serialization #region Properties diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs deleted file mode 100644 index 0a4d9c6cb34..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RegisterWMIEventCommand.cs +++ /dev/null @@ -1,194 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs deleted file mode 100644 index cce50ea1563..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RemoveWMIObjectCommand.cs +++ /dev/null @@ -1,183 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs index fcc9aef195f..d0f5fecf495 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/ResolvePathCommand.cs @@ -8,8 +8,8 @@ namespace Microsoft.PowerShell.Commands { /// - /// A command to resolve MSH paths containing glob characters to - /// MSH paths that match the glob strings. + /// 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")] @@ -59,7 +59,8 @@ public string[] LiteralPath /// Gets or sets the value that determines if the resolved path should /// be resolved to its relative version. /// - [Parameter()] + [Parameter(ParameterSetName = "Path")] + [Parameter(ParameterSetName = "LiteralPath")] public SwitchParameter Relative { get @@ -75,6 +76,33 @@ public SwitchParameter Relative 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 @@ -84,12 +112,68 @@ public SwitchParameter Relative /// private string[] _paths; + private PSDriveInfo _relativeDrive; + private string _relativeBasePath; + #endregion parameter data #region Command code /// - /// Resolves the path containing glob characters to the MSH paths that it + /// 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() @@ -99,25 +183,53 @@ protected override void ProcessRecord() Collection result = null; try { - result = SessionState.Path.GetResolvedPSPathFromPSPath(path, CmdletProviderContext); + 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 != SessionState.Path.CurrentLocation.Drive && - SessionState.Path.CurrentLocation.Drive != null && - !currentPath.ProviderPath.StartsWith( - SessionState.Path.CurrentLocation.Drive.Root, StringComparison.OrdinalIgnoreCase)) + if (currentPath.Drive != _relativeDrive && + _relativeDrive != null && + !currentPath.ProviderPath.StartsWith(_relativeDrive.Root, StringComparison.OrdinalIgnoreCase)) { WriteObject(currentPath.Path, enumerateCollection: false); continue; } - string adjustedPath = SessionState.Path.NormalizeRelativePath(currentPath.Path, - SessionState.Path.CurrentLocation.ProviderPath); + 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) && @@ -126,6 +238,9 @@ protected override void ProcessRecord() adjustedPath = SessionState.Path.Combine(".", adjustedPath); } + leafIndex = adjustedPath.LastIndexOf(currentPath.Provider.ItemSeparator); + adjustedBaseCache = adjustedPath.AsSpan(0, leafIndex + 1); + WriteObject(adjustedPath, enumerateCollection: false); } } diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs deleted file mode 100644 index 297dd5269a9..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/RollbackTransactionCommand.cs +++ /dev/null @@ -1,31 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs index 82210f627ce..a00f9583d6a 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/Service.cs @@ -103,7 +103,7 @@ internal void WriteNonTerminatingError( string message = StringUtil.Format(errorMessage, serviceName, displayName, - (innerException == null) ? string.Empty : innerException.Message); + (innerException == null) ? category.ToString() : innerException.Message); var exception = new ServiceCommandException(message, innerException); exception.ServiceName = serviceName; @@ -610,146 +610,197 @@ public string[] Name /// protected override void ProcessRecord() { - foreach (ServiceController service in MatchingServices()) + nint scManagerHandle = nint.Zero; + if (!DependentServices && !RequiredServices) { - if (!DependentServices.IsPresent && !RequiredServices.IsPresent) - { - WriteObject(AddProperties(service)); + // 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); } - else + } + + try + { + foreach (ServiceController service in MatchingServices()) { - if (DependentServices.IsPresent) + if (!DependentServices.IsPresent && !RequiredServices.IsPresent) { - foreach (ServiceController dependantserv in service.DependentServices) + WriteObject(AddProperties(scManagerHandle, service)); + } + else + { + if (DependentServices.IsPresent) { - WriteObject(dependantserv); + foreach (ServiceController dependantserv in service.DependentServices) + { + WriteObject(dependantserv); + } } - } - if (RequiredServices.IsPresent) - { - foreach (ServiceController servicedependedon in service.ServicesDependedOn) + if (RequiredServices.IsPresent) { - WriteObject(servicedependedon); + 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(ServiceController service) + private PSObject AddProperties(nint scManagerHandle, ServiceController service) { - NakedWin32Handle hScManager = IntPtr.Zero; - NakedWin32Handle hService = IntPtr.Zero; - int lastError = 0; - PSObject serviceAsPSObj = PSObject.AsPSObject(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 { - hScManager = NativeMethods.OpenSCManagerW( - lpMachineName: service.MachineName, - lpDatabaseName: null, - dwDesiredAccess: NativeMethods.SC_MANAGER_CONNECT - ); - if (hScManager == IntPtr.Zero) - { - lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new(lastError); - WriteNonTerminatingError( - service, - exception, - "FailToOpenServiceControlManager", - ServiceResources.FailToOpenServiceControlManager, - ErrorCategory.PermissionDenied); - } - + // We don't use service.ServiceHandle as that requests + // SERVICE_ALL_ACCESS when we only need SERVICE_QUERY_CONFIG. hService = NativeMethods.OpenServiceW( - hScManager, + scManagerHandle, service.ServiceName, NativeMethods.SERVICE_QUERY_CONFIG ); - if (hService == IntPtr.Zero) + if (hService != nint.Zero) { - lastError = Marshal.GetLastWin32Error(); - Win32Exception exception = new(lastError); - WriteNonTerminatingError( - service, - exception, - "CouldNotGetServiceInfo", - ServiceResources.CouldNotGetServiceInfo, - ErrorCategory.PermissionDenied); - } - - NativeMethods.SERVICE_DESCRIPTIONW description = new(); - bool querySuccessful = NativeMethods.QueryServiceConfig2(hService, NativeMethods.SERVICE_CONFIG_DESCRIPTION, out description); - - NativeMethods.SERVICE_DELAYED_AUTO_START_INFO autostartInfo = new(); - querySuccessful = querySuccessful && NativeMethods.QueryServiceConfig2(hService, NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO, out autostartInfo); + if (NativeMethods.QueryServiceConfig2( + hService, + NativeMethods.SERVICE_CONFIG_DESCRIPTION, + out NativeMethods.SERVICE_DESCRIPTIONW descriptionInfo)) + { + description = descriptionInfo.lpDescription; + } + else + { + WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_DESCRIPTIONW)); + } - NativeMethods.QUERY_SERVICE_CONFIG serviceInfo = new(); - querySuccessful = querySuccessful && NativeMethods.QueryServiceConfig(hService, out serviceInfo); + 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 (!querySuccessful) + 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 { - WriteNonTerminatingError( - service: service, - innerException: null, - errorId: "CouldNotGetServiceInfo", - errorMessage: ServiceResources.CouldNotGetServiceInfo, - category: ErrorCategory.PermissionDenied - ); + // handle when OpenServiceW itself fails: + WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_QUERY_CONFIG)); } - - PSProperty noteProperty = new("UserName", serviceInfo.lpServiceStartName); - serviceAsPSObj.Properties.Add(noteProperty, true); - serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#UserName"); - - noteProperty = new PSProperty("Description", description.lpDescription); - serviceAsPSObj.Properties.Add(noteProperty, true); - serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#Description"); - - noteProperty = new PSProperty("DelayedAutoStart", autostartInfo.fDelayedAutostart); - serviceAsPSObj.Properties.Add(noteProperty, true); - serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#DelayedAutoStart"); - - noteProperty = new PSProperty("BinaryPathName", serviceInfo.lpBinaryPathName); - serviceAsPSObj.Properties.Add(noteProperty, true); - serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#BinaryPathName"); - - noteProperty = new PSProperty("StartupType", NativeMethods.GetServiceStartupType(service.StartType, autostartInfo.fDelayedAutostart)); - serviceAsPSObj.Properties.Add(noteProperty, true); - serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#StartupType"); } finally { if (hService != IntPtr.Zero) { bool succeeded = NativeMethods.CloseServiceHandle(hService); - if (!succeeded) - { - Diagnostics.Assert(lastError != 0, "ErrorCode not success"); - } - } - - if (hScManager != IntPtr.Zero) - { - bool succeeded = NativeMethods.CloseServiceHandle(hScManager); - if (!succeeded) - { - Diagnostics.Assert(lastError != 0, "ErrorCode not success"); - } + 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 @@ -888,7 +939,7 @@ internal bool DoWaitForStatus( /// This will start the service. /// /// Service to start. - /// True iff the service was started. + /// True if-and-only-if the service was started. internal bool DoStartService(ServiceController serviceController) { Exception exception = null; @@ -903,8 +954,7 @@ internal bool DoStartService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING) { exception = e; @@ -945,7 +995,7 @@ internal bool DoStartService(ServiceController serviceController) /// Service to stop. /// Stop dependent services. /// - /// True iff the service was stopped. + /// 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 @@ -1020,9 +1070,7 @@ internal List DoStopService(ServiceController serviceControll } catch (InvalidOperationException e) { - Win32Exception eInner = - e.InnerException as Win32Exception; - if (eInner == null + if (e.InnerException is not Win32Exception eInner || eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { exception = e; @@ -1078,7 +1126,7 @@ internal List DoStopService(ServiceController serviceControll /// private static bool HaveAllDependentServicesStopped(ServiceController[] dependentServices) { - return Array.TrueForAll(dependentServices, service => service.Status == ServiceControllerStatus.Stopped); + return Array.TrueForAll(dependentServices, static service => service.Status == ServiceControllerStatus.Stopped); } /// @@ -1097,7 +1145,7 @@ internal void RemoveNotStoppedServices(List services) /// This will pause the service. /// /// Service to pause. - /// True iff the service was paused. + /// True if-and-only-if the service was paused. internal bool DoPauseService(ServiceController serviceController) { Exception exception = null; @@ -1117,8 +1165,7 @@ internal bool DoPauseService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { serviceNotRunning = true; @@ -1178,7 +1225,7 @@ internal bool DoPauseService(ServiceController serviceController) /// This will resume the service. /// /// Service to resume. - /// True iff the service was resumed. + /// True if-and-only-if the service was resumed. internal bool DoResumeService(ServiceController serviceController) { Exception exception = null; @@ -1198,8 +1245,7 @@ internal bool DoResumeService(ServiceController serviceController) } catch (InvalidOperationException e) { - Win32Exception eInner = e.InnerException as Win32Exception; - if (eInner != null + if (e.InnerException is Win32Exception eInner && eInner.NativeErrorCode == NativeMethods.ERROR_SERVICE_NOT_ACTIVE) { serviceNotRunning = true; @@ -1680,7 +1726,6 @@ public string Status #region Overrides /// /// - [ArchitectureSensitive] protected override void ProcessRecord() { ServiceController service = null; @@ -1756,10 +1801,14 @@ protected override void ProcessRecord() return; } + var access = NativeMethods.SERVICE_CHANGE_CONFIG; + if (!string.IsNullOrEmpty(SecurityDescriptorSddl)) + access |= NativeMethods.WRITE_DAC | NativeMethods.WRITE_OWNER; + hService = NativeMethods.OpenServiceW( hScManager, Name, - NativeMethods.SERVICE_CHANGE_CONFIG | NativeMethods.WRITE_DAC | NativeMethods.WRITE_OWNER + access ); if (hService == IntPtr.Zero) @@ -2111,7 +2160,6 @@ public string[] DependsOn /// /// Create the service. /// - [ArchitectureSensitive] protected override void BeginProcessing() { ServiceController service = null; @@ -2353,7 +2401,7 @@ protected override void BeginProcessing() /// /// This class implements the Remove-Service command. /// - [Cmdlet(VerbsCommon.Remove, "Service", SupportsShouldProcess = true, DefaultParameterSetName = "Name")] + [Cmdlet(VerbsCommon.Remove, "Service", SupportsShouldProcess = true, DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2248980")] public class RemoveServiceCommand : ServiceBaseCommand { #region Parameters @@ -2380,7 +2428,6 @@ public class RemoveServiceCommand : ServiceBaseCommand /// /// Remove the service. /// - [ArchitectureSensitive] protected override void ProcessRecord() { ServiceController service = null; @@ -2523,7 +2570,6 @@ protected override void ProcessRecord() /// /// Non-terminating errors occurring in the service noun commands. /// - [Serializable] public class ServiceCommandException : SystemException { #region ctors @@ -2565,31 +2611,12 @@ public ServiceCommandException(string message, Exception innerException) /// /// /// 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) - : base(info, context) { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - _serviceName = info.GetString("ServiceName"); + throw new NotSupportedException(); } - /// - /// Serializer. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - base.GetObjectData(info, context); - info.AddValue("ServiceName", _serviceName); - } #endregion Serialization #region Properties @@ -2761,69 +2788,6 @@ bool SetServiceObjectSecurity( byte[] lpSecurityDescriptor ); - /// - /// CreateJobObject API creates or opens a job object. - /// - /// - /// A pointer to a SECURITY_ATTRIBUTES structure that specifies the security descriptor for the - /// job object and determines whether child processes can inherit the returned handle. - /// If lpJobAttributes is NULL, the job object gets a default security descriptor - /// and the handle cannot be inherited. - /// - /// - /// The name of the job. - /// - /// - /// If the function succeeds, the return value is a handle to the job object. - /// If the object existed before the function call, the function - /// returns a handle to the existing job object. - /// - [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName); - - /// - /// AssignProcessToJobObject API is used to assign a process to an existing job object. - /// - /// - /// A handle to the job object to which the process will be associated. - /// - /// - /// A handle to the process to associate with the job object. - /// - /// If the function succeeds, the return value is nonzero. - /// If the function fails, the return value is zero. - /// - [DllImport("Kernel32.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool AssignProcessToJobObject(SafeHandle hJob, IntPtr hProcess); - - /// - /// Retrieves job state information from the job object. - /// - /// - /// A handle to the job whose information is being queried. - /// - /// - /// The information class for the limits to be queried. - /// - /// - /// The limit or job state information. - /// - /// - /// The count of the job information being queried, in bytes. - /// - /// - /// A pointer to a variable that receives the length of - /// data written to the structure pointed to by the lpJobObjectInfo parameter. - /// - /// If the function succeeds, the return value is nonzero. - /// If the function fails, the return value is zero. - /// - [DllImport("Kernel32.dll", EntryPoint = "QueryInformationJobObject", SetLastError = true, CharSet = CharSet.Unicode)] - public static extern bool QueryInformationJobObject(SafeHandle hJob, int JobObjectInfoClass, - ref JOBOBJECT_BASIC_PROCESS_ID_LIST lpJobObjectInfo, - int cbJobObjectLength, IntPtr lpReturnLength); - internal static bool QueryServiceConfig(NakedWin32Handle hService, out NativeMethods.QUERY_SERVICE_CONFIG configStructure) { IntPtr lpBuffer = IntPtr.Zero; @@ -2960,20 +2924,20 @@ internal static ServiceStartupType GetServiceStartupType(ServiceStartMode startM #endregion NativeMethods #region ServiceStartupType - /// - ///Enum for usage with StartupType. Automatic, Manual and Disabled index matched from System.ServiceProcess.ServiceStartMode - /// + /// + /// Enum for usage with StartupType. Automatic, Manual and Disabled index matched from System.ServiceProcess.ServiceStartMode + /// public enum ServiceStartupType { - ///Invalid service + /// Invalid service InvalidValue = -1, - ///Automatic service + /// Automatic service Automatic = 2, - ///Manual service + /// Manual service Manual = 3, - ///Disabled service + /// Disabled service Disabled = 4, - ///Automatic (Delayed Start) service + /// Automatic (Delayed Start) service AutomaticDelayedStart = 10 } #endregion ServiceStartupType diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs index b53ffeb01b3..49ab5d768f6 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetClipboardCommand.cs @@ -17,6 +17,7 @@ namespace Microsoft.PowerShell.Commands /// [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(); @@ -37,6 +38,19 @@ public class SetClipboardCommand : PSCmdlet [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. /// @@ -53,6 +67,11 @@ protected override void ProcessRecord() if (Value != null) { _contentList.AddRange(Value); + + if (PassThru) + { + WriteObject(Value); + } } } @@ -117,8 +136,28 @@ private void SetClipboardContent(List contentList, bool append) if (ShouldProcess(setClipboardShouldProcessTarget, "Set-Clipboard")) { - Clipboard.SetText(content.ToString()); + 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/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs deleted file mode 100644 index 4b2deac8bef..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/SetWMIInstanceCommand.cs +++ /dev/null @@ -1,186 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs deleted file mode 100644 index 4f5c239cc64..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/StartTransactionCommand.cs +++ /dev/null @@ -1,110 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs index e6b33142457..2a4a453f8f7 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestConnectionCommand.cs @@ -27,6 +27,7 @@ namespace Microsoft.PowerShell.Commands [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 @@ -55,7 +56,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable #region Private Fields - private static byte[]? s_DefaultSendBuffer; + private static readonly byte[] s_DefaultSendBuffer = Array.Empty(); private readonly CancellationTokenSource _dnsLookupCancel = new(); @@ -134,6 +135,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// The default (from Windows) is 4 times. /// [Parameter(ParameterSetName = DefaultPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] [ValidateRange(ValidateRangeKind.Positive)] public int Count { get; set; } = 4; @@ -143,6 +145,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// [Parameter(ParameterSetName = DefaultPingParameterSet)] [Parameter(ParameterSetName = RepeatPingParameterSet)] + [Parameter(ParameterSetName = TcpPortParameterSet)] [ValidateRange(ValidateRangeKind.Positive)] public int Delay { get; set; } = 1; @@ -169,6 +172,7 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// 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; } @@ -180,6 +184,13 @@ public class TestConnectionCommand : PSCmdlet, IDisposable [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. @@ -227,14 +238,17 @@ public class TestConnectionCommand : PSCmdlet, IDisposable /// /// BeginProcessing implementation for TestConnectionCommand. + /// Sets Count for different types of tests unless specified explicitly. /// protected override void BeginProcessing() { - switch (ParameterSetName) + if (Repeat) { - case RepeatPingParameterSet: - Count = int.MaxValue; - break; + Count = int.MaxValue; + } + else if (ParameterSetName == TcpPortParameterSet) + { + SetCountForTcpTest(); } } @@ -250,21 +264,22 @@ protected override void ProcessRecord() foreach (var targetName in TargetName) { - switch (ParameterSetName) + if (MtuSize) + { + ProcessMTUSize(targetName); + } + else if (Traceroute) + { + ProcessTraceroute(targetName); + } + else if (ParameterSetName == TcpPortParameterSet) + { + ProcessConnectionByTCPPort(targetName); + } + else { - case DefaultPingParameterSet: - case RepeatPingParameterSet: - ProcessPing(targetName); - break; - case MtuSizeDetectParameterSet: - ProcessMTUSize(targetName); - break; - case TraceRouteParameterSet: - ProcessTraceroute(targetName); - break; - case TcpPortParameterSet: - ProcessConnectionByTCPPort(targetName); - break; + // None of the switch parameters are true: handle default ping or -Repeat + ProcessPing(targetName); } } } @@ -281,6 +296,18 @@ protected override void StopProcessing() #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)) @@ -293,42 +320,80 @@ private void ProcessConnectionByTCPPort(string targetNameOrAddress) return; } - TcpClient client = new(); + int timeoutMilliseconds = TimeoutSeconds * 1000; + int delayMilliseconds = Delay * 1000; - try + for (var i = 1; i <= Count; i++) { - Task connectionTask = client.ConnectAsync(targetAddress, TcpPort); - string targetString = targetAddress.ToString(); + long latency = 0; + SocketError status = SocketError.SocketError; + + Stopwatch stopwatch = new Stopwatch(); - for (var i = 1; i <= TimeoutSeconds; i++) + using var client = new TcpClient(); + + try { - Task timeoutTask = Task.Delay(millisecondsDelay: 1000); - Task.WhenAny(connectionTask, timeoutTask).Result.Wait(); + stopwatch.Start(); - if (timeoutTask.Status == TaskStatus.Faulted || timeoutTask.Status == TaskStatus.Canceled) + if (client.ConnectAsync(targetAddress, TcpPort).Wait(timeoutMilliseconds, _dnsLookupCancel.Token)) { - // Waiting is interrupted by Ctrl-C. - WriteObject(false); - return; + latency = stopwatch.ElapsedMilliseconds; + status = SocketError.Success; } - - if (connectionTask.Status == TaskStatus.RanToCompletion) + else { - WriteObject(true); - return; + status = SocketError.TimedOut; } } - } - catch - { - // Silently ignore connection errors. - } - finally - { - client.Close(); - } + 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 + )); + } - WriteObject(false); + if (i < Count) + { + Task.Delay(delayMilliseconds).Wait(_dnsLookupCancel.Token); + } + } } #endregion ConnectionTest @@ -419,7 +484,10 @@ private void ProcessTraceroute(string targetNameOrAddress) reply.Status == IPStatus.Success ? reply.RoundtripTime : timer.ElapsedMilliseconds, - buffer.Length, + + // 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, @@ -497,6 +565,8 @@ private void ProcessMTUSize(string targetNameOrAddress) int LowMTUSize = targetAddress.AddressFamily == AddressFamily.InterNetworkV6 ? 1280 : 68; int timeout = TimeoutSeconds * 1000; + PingReply? timeoutReply = null; + try { PingOptions pingOptions = new(MaxHops, true); @@ -517,6 +587,7 @@ private void ProcessMTUSize(string targetNameOrAddress) if (reply.Status == IPStatus.PacketTooBig || reply.Status == IPStatus.TimedOut) { HighMTUSize = CurrentMTUSize; + timeoutReply = reply; retry = 1; } else if (reply.Status == IPStatus.Success) @@ -575,11 +646,32 @@ private void ProcessMTUSize(string targetNameOrAddress) } else { - WriteObject(new PingMtuStatus( - Source, - resolvedTargetName, - replyResult ?? throw new ArgumentNullException(nameof(replyResult)), - CurrentMTUSize)); + 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)); + } + } } @@ -640,7 +732,7 @@ private void ProcessPing(string targetNameOrAddress) resolvedTargetName, reply, reply.RoundtripTime, - buffer.Length, + buffer.Length == 0 ? DefaultSendBufferSize : buffer.Length, pingNum: (uint)i)); } @@ -795,7 +887,7 @@ private IPHostEntry GetCancellableHostEntry(string targetNameOrAddress) // Creates and fills a send buffer. This follows the ping.exe and CoreFX model. private static byte[] GetSendBuffer(int bufferSize) { - if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer != null) + if (bufferSize == DefaultSendBufferSize) { return s_DefaultSendBuffer; } @@ -807,11 +899,6 @@ private static byte[] GetSendBuffer(int bufferSize) sendBuffer[i] = (byte)((int)'a' + i % 23); } - if (bufferSize == DefaultSendBufferSize && s_DefaultSendBuffer == null) - { - s_DefaultSendBuffer = sendBuffer; - } - return sendBuffer; } @@ -875,6 +962,75 @@ private PingReply SendCancellablePing( } } + /// + /// 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. /// diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TestPathCommand.cs new file mode 100644 index 00000000000..50765c0e0ae --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs index 69e8860f3ab..22a50e41176 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/TimeZoneCommands.cs @@ -17,6 +17,7 @@ namespace Microsoft.PowerShell.Commands /// [Cmdlet(VerbsCommon.Get, "TimeZone", DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096904")] + [OutputType(typeof(TimeZoneInfo))] [Alias("gtz")] public class GetTimeZoneCommand : PSCmdlet { @@ -53,7 +54,7 @@ protected override void ProcessRecord() // make sure we've got the latest time zone settings TimeZoneInfo.ClearCachedData(); - if (this.ParameterSetName.Equals("ListAvailable", StringComparison.OrdinalIgnoreCase)) + if (ListAvailable) { // output the list of all available time zones WriteObject(TimeZoneInfo.GetSystemTimeZones(), true); @@ -121,6 +122,7 @@ protected override void ProcessRecord() SupportsShouldProcess = true, DefaultParameterSetName = "Name", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097056")] + [OutputType(typeof(TimeZoneInfo))] [Alias("stz")] public class SetTimeZoneCommand : PSCmdlet { @@ -159,7 +161,7 @@ public class SetTimeZoneCommand : PSCmdlet #endregion Parameters /// - /// Implementation of the ProcessRecord method for Get-TimeZone. + /// 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() diff --git a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs deleted file mode 100644 index 056cf60265b..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/UseTransactionCommand.cs +++ /dev/null @@ -1,94 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs deleted file mode 100644 index eed6efff76a..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WMIHelper.cs +++ /dev/null @@ -1,2083 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs deleted file mode 100644 index 547b121c571..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WebServiceProxy.cs +++ /dev/null @@ -1,491 +0,0 @@ -// 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/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs index 25ecd672c4c..a2a6387e9da 100644 --- a/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Management/commands/management/WriteContentCommandBase.cs @@ -95,10 +95,7 @@ protected override void ProcessRecord() // Initialize the content - if (_content == null) - { - _content = Array.Empty(); - } + _content ??= Array.Empty(); if (_pipingPaths) { diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx index d74321e46ff..9811798e3f8 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ClearRecycleBinResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx index 9e6cbd55cc1..4b25f91f36e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ClipboardResources.resx @@ -1,103 +1,63 @@ - - - - + + + + + + - - - - - - - - - - - - - - - - - - - - - + + + + + + + - - - - 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 - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 string '{0}' to the clipboard. diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx index 15bfadffe7b..1c931c700bc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/CmdletizationResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx index 8a562f462d4..c8865458286 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ComputerInfoResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx index 63a671c0248..23fa6c4b68d 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ComputerResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -387,4 +387,7 @@ The {0} parameter is not supported for CoreCLR. + + The required native command 'shutdown' was not found. + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx deleted file mode 100644 index 077beaa117f..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ControlPanelResources.resx +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx deleted file mode 100644 index cee97f4adae..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/EventlogResources.resx +++ /dev/null @@ -1,180 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx index a058ae71a11..c878f64a50f 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/HotFixResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx deleted file mode 100644 index 73de4f80a24..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ManagementMshSnapInResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx index 6bec473c213..3c2675f900e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/NavigationResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx index fa4ae71963a..d75296bacf3 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ProcessCommandHelpResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx index 65513e55f5f..1b9e9b21c25 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ProcessResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -189,6 +189,9 @@ 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. @@ -204,9 +207,6 @@ Parameters "{0}" and "{1}" cannot be specified at the same time. - - The 'IncludeUserName' parameter requires elevated user rights. Try running the command again in a session that has been opened with elevated user rights (that is, Run as Administrator). - Cannot debug process "{0} ({1})" because of the following error: {2} diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx index 3792ce8db99..1184748d98e 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ServiceResources.resx @@ -1,17 +1,17 @@ - - - + + @@ -159,9 +159,6 @@ Service '{1} ({0})' cannot be configured due to the following error: {2} - - Service '{1} ({0})' cannot be queried due to the following error: {2} - Service '{1} ({0})' description cannot be configured due to the following error: {2} @@ -211,9 +208,12 @@ Service '{1} ({0})' resume failed. - Failed to configure the service '{1} ({0})' due to the following error: {2}. Run PowerShell as admin and run your command again. + 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/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx index ddd4ba8f815..da6e540b9bc 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/TestConnectionResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx index c60c4318a64..c14a57076b5 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/TestPathResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx index f474785fd22..01594e592a1 100644 --- a/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx +++ b/src/Microsoft.PowerShell.Commands.Management/resources/TimeZoneResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx deleted file mode 100644 index 9d92573d86d..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/TransactionResources.resx +++ /dev/null @@ -1,123 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx deleted file mode 100644 index 91d57c51902..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/WebServiceResources.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx b/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx deleted file mode 100644 index 47f736405ea..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/resources/WmiResources.resx +++ /dev/null @@ -1,138 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Management/resources/cs/ClearRecycleBinResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ClearRecycleBinResources.cs.resx new file mode 100644 index 00000000000..4f7ab0ca493 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ClearRecycleBinResources.cs.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 + + + Veškerý obsah Koše + + + Veškerý obsah Koše pro jednotku {0} + + + Vyprazdňování Koše + + + pro jednotku {0} + + + pro všechny jednotky + + + Jednotku nelze najít. Jednotka s názvem {0} neexistuje. Spuštěním rutiny {1} zobrazíte dostupné pevné jednotky v systému. + + + Neplatný vstup Podporovány jsou následující formáty: {0}, {1} nebo {2}. + + + Jednotka s názvem {0} není pevná jednotka a nepodporuje Koš. Spuštěním rutiny {1} zobrazíte dostupné pevné jednotky v systému. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/ClipboardResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ClipboardResources.cs.resx new file mode 100644 index 00000000000..15ad2078786 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ClipboardResources.cs.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nastavte řetězec {0} do schránky. + + + Připojte řetězec {0} ke schránce. + + + Nastavte soubor {0} do schránky. + + + Připojte soubor {0} ke schránce. + + + Nastavte soubory ({0}) do schránky. + + + Připojte soubory ({0}) do schránky. + + + Schránka neobsahuje žádný obsah nebo formát obsahu není kompatibilní. Nastavte vstupní objekt do schránky. + + + Schránka byla vymazána. + + + TextFormatType lze kombinovat pouze s formátem Text. + + + Hodnotu Raw lze kombinovat pouze s formátem Text nebo FileDropList. + + + Html lze kombinovat pouze s formátem Html Text. + + + Na této platformě je podporován pouze formát Text. + + + Schránka není na této platformě podporována. + + + Přepínač -AsHtml není na této platformě podporován. + + + Parametr -TextFormatType podporuje na této platformě pouze hodnotu Text. + + + Parametr -Path není na této platformě podporován. + + + Parametr -LiteralPath není na této platformě podporován. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/CmdletizationResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/CmdletizationResources.cs.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/CmdletizationResources.cs.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/ComputerInfoResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ComputerInfoResources.cs.resx new file mode 100644 index 00000000000..aa8e8ec437a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ComputerInfoResources.cs.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 + + + Načítají se informace o operačním systému. + + + Načítají se informace o aktualizacích instalovatelných bez restartování. + + + Načítají se informace o registru. + + + Načítají se informace o systému BIOS. + + + Načítají se informace o základní desce. + + + Načítají se informace o počítači. + + + Načítají se informace o procesoru. + + + Načítají se informace o síťovém adaptéru. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/ComputerResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ComputerResources.cs.resx new file mode 100644 index 00000000000..d5a2e9c1c4f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ComputerResources.cs.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 + + + Tato funkce není v tomto operačním systému podporována. + + + Nelze povolit jednotku {0}. + + + Příkaz nemůže zapnout infrastrukturu obnovení počítače na zadaném počítači, protože zadaná jednotka není platná. Zadejte do parametru Drive platnou jednotku a zkuste to znovu. + + + Do seznamu jednotek zahrňte systémovou jednotku. + + + Příkaz nemůže vypnout infrastrukturu obnovení počítače, protože zadaná jednotka není platná. Zadejte do parametru Drive platnou jednotku a zkuste to znovu. + + + Příkaz nemůže zakázat obnovení systému na jednotce {0} . Tuto operaci nemůžete provést, protože k tomu nemáte dostatečná oprávnění. + + + Služba SystemRestore je zakázaná. + + + Infrastruktura obnovení systému nemůže vytvořit bod obnovení. + + + Poslední pokus o obnovení počítače se nezdařil. + + + Počítač byl obnoven do zadaného bodu obnovení. + + + Poslední pokus o obnovení počítače byl přerušen. + + + Příkaz nemůže najít bod obnovení {0}. Ověřte pořadové číslo {0} a potom příkaz spusťte znovu. + + + {0} ({1}) + + + Restartování počítače {0} se nezdařilo s následující chybovou zprávou: {1}. + + + Tento příkaz nelze spustit na cílovém počítači ({1}) kvůli následující chybě: {0}. {2} + + + Počítač {0} se nepodařilo zastavit. Chybová zpráva: {1}. + + + Příkaz nemůže obnovit počítač, protože {0} není nastaven jako platný bod obnovení. Zadejte platný bod obnovení do parametru RestorePoint a zkuste to znovu. + + + Změny se projeví po restartování počítače {1}. + + + Po opuštění domény budete muset znát heslo místního účtu správce, abyste se mohli přihlásit k tomuto počítači. Chcete pokračovat? + + + Následující název počítače není platný: {0}. Ujistěte se, že název počítače není delší než 255 znaků, neobsahuje dvě nebo více po sobě jdoucích teček, nezačíná tečkou, neobsahuje pouze číselné znaky a neobsahuje žádný z následujících znaků: +{{|}}~[\]^:;<=>?@!"#$%^`()+/, + + + Doména v názvu počítače {0} není platná. Ujistěte se, že doména existuje a že název je platný název domény. + + + Hodnota zadaná pro parametr NewComputerName je stejná jako hodnota parametru ComputerName. Zadejte pro parametr NewComputerName jinou hodnotu. + + + Heslo zabezpečeného kanálu mezi {0} a {1} bylo resetováno. + + + Tento příkaz nelze spustit kvůli následující chybě: Službu nelze spustit, protože je zakázaná nebo nemá povolená přidružená zařízení. + + + Vytváří se bod obnovení systému... + + + Vytváří se bod obnovení systému... {0} % dokončeno. + + + Dokončeno. + + + Zkuste použít níže uvedené možnosti a spusťte příkaz znovu. +1. Ověřte, zda je cílový počítač ({0}) spuštěn. +2. Zadejte úplný název cílového počítače ({0}). + + + Restartování počítače {0} se nezdařilo. Oprávnění přístupu {1} nelze pro volající proces povolit. + + + Povolte {0} a restartujte počítač. + + + Přístupová práva k místnímu vypnutí + + + Přístupová práva ke vzdálenému vypnutí + + + Nelze čekat na restart místního počítače. Při zadání parametru Wait se místní počítač ignoruje. + + + Parametry Timeout, For a Delay jsou platné pouze tehdy, když je zadán parametr Wait. + + + Restartují se počítače... + + + Restartování počítače {0} + + + Dokončeno: {0}/{1} + + + Ověřuje se, zda se počítač restartoval... + + + Čeká se na připojení PowerShellu... + + + Čeká se na zahájení restartování... + + + Čeká se na připojení WinRM... + + + Čeká se na připojení rozhraní WMI... + + + Restartování je dokončeno + + + Kombinované typy služeb se v současné době nepodporují. + + + Název počítače {0} nelze přeložit s následující výjimkou: {1}. + + + Počet nových názvů neodpovídá počtu cílových počítačů. + + + Přeskočit počítač {0} s novým názvem {1}, protože nový název není platný. Zadaný nový název počítače nemá správný formát. Standardní názvy mohou obsahovat písmena (a-z, A-Z), číslice (0-9) a spojovníky (-), ale ne mezery ani tečky (.). Název nesmí být tvořen pouze číslicemi a nesmí být delší než 63 znaků. + + + Přeskočit počítač {0} s novým názvem {1}, protože nový název je stejný jako aktuální název. + + + Počítač {0} nelze odebrat, protože není v doméně. + + + Počítač {0} se nepodařilo připojit k pracovní skupině {1}. Chybová zpráva: {2}. + + + Počítače nelze odebrat z domény, protože místní síť není dostupná. + + + Přejmenování počítače {0} na {1} se nezdařilo kvůli následující výjimce: {2}. + + + Připojit k doméně {0} + + + Připojit k pracovní skupině {0} + + + Počítač {0} nelze přidat do domény {1}, protože už je její součástí. + + + Počítač {0} nelze přidat do pracovní skupiny {1}, protože už je její součástí. + + + Počítač {0} byl úspěšně připojen k pracovní skupině {1}, ale nepodařilo se ho přejmenovat na {2}. Chybová zpráva: {3}. + + + Počítač {0} byl úspěšně odpojen od domény {1}, ale nepodařilo se ho připojit k pracovní skupině {2}. Chybová zpráva: {3}. + + + Počítač {0} se nepodařilo odpojit od domény {1}. Chybová zpráva: {2}. + + + K počítači {0} se nepodařilo navázat připojení WMI. Chybová zpráva: {1} + + + Počítači {0} se nepodařilo připojit k doméně {1} z aktuální pracovní skupiny {2} s následující chybovou zprávou: {3}. + + + Počítač {0} byl úspěšně odpojen od domény {1}, ale nepodařilo se ho připojit k nové doméně {2}. Chybová zpráva: {3}. + + + Počítač {0} byl úspěšně připojen k nové doméně {1}, ale nepodařilo se ho přejmenovat na {2}. Chybová zpráva: {3}. + + + Příznak {0} je platný pouze v případě, že je zadán příznak {1}. + + + Nelze přejmenovat více počítačů. Parametr -NewName je platný pouze v případě, že je zadán jeden počítač. + + + Účet místního počítače v doméně {0} se nepodařilo najít. + + + Účet počítače pro místní počítač se nepodařilo najít na řadiči domény {0}. + + + Informace o doméně místního počítače nelze získat kvůli následující výjimce: {0}. + + + Heslo zabezpečeného kanálu pro účet počítače v doméně nelze resetovat. Operace se nezdařila s následujícím výjimkou: {0}. + + + Resetování hesla zabezpečeného kanálu pro místní počítač se nezdařilo s následující chybovou zprávou: {0}. + + + K resetování hesla zabezpečeného kanálu na místním počítači jsou vyžadována oprávnění správce. Přístup byl odepřen. + + + Heslo zabezpečeného kanálu pro účet místního počítače nelze resetovat. Místní počítač momentálně není součástí domény. + + + Název počítače NetBIOS je omezen na 15 bajtů, což v tomto případě představuje 15 znaků. Název pro rozhraní NetBIOS bude zkrácen na {0}, což může způsobit konflikty při překladu názvů rozhraní NetBIOS. Chcete pokračovat? + + + Název pro rozhraní NetBIOS bude zkrácen. + + + Zadaný název serveru {0} nelze přeložit. + + + Nový bod obnovení systému nelze vytvořit, protože již byl vytvořen během posledních {0} minut. Frekvenci vytváření bodů obnovení lze změnit vytvořením hodnoty DWORD SystemRestorePointCreationFrequency v klíči registru HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore. Hodnota tohoto klíče registru určuje požadovaný časový interval (v minutách) mezi vytvořením dvou bodů obnovení. Výchozí hodnota je 1440 minut (24 hodin). + + + Objekt WMI Win32_OperatingSystem nelze načíst. + + + Počítač {0} je přeskočen. Nepodařilo se načíst hodnotu LastBootUpTime prostřednictvím služby WMI. Chybová zpráva: {1}. + + + Zabezpečený kanál pro místní počítač nelze ověřit. Operace se nezdařila s následujícím výjimkou: {0}. + + + Pokus o opravu zabezpečeného kanálu mezi místním počítačem a doménou {0} se nezdařil. + + + Zabezpečený kanál mezi místním počítačem a doménou {0} byl úspěšně opraven. + + + Zabezpečený kanál mezi místním počítačem a doménou {0} je v pořádku. + + + Zabezpečený kanál mezi místním počítačem a doménou {0} je poškozen. + + + Nelze ověřit heslo zabezpečeného kanálu pro místní počítač. Místní počítač momentálně není součástí domény. + + + Operaci nelze provést, protože rozhraní API pro obnovení systému nejsou na platformě Advanced RISC Machine (ARM) podporována. + + + Restartování počítače nebylo dokončeno v zadaném časovém limitu. + + + Časový interval pro vytvoření bodu obnovení nelze ověřit. Nepodařilo se načíst poslední bod obnovení. Chybová zpráva: {0}. + + + Sada parametrů AsJob není podporována. + + + Parametr {0} se pro CoreCLR nepodporuje. + + + Požadovaný nativní příkaz shutdown nebyl nalezen. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/HotFixResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/HotFixResources.cs.resx new file mode 100644 index 00000000000..2489f912017 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/HotFixResources.cs.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 + + + V počítači {0} nelze najít požadovanou opravu hotfix. Ověřte vstup a spusťte příkaz znovu. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/NavigationResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/NavigationResources.cs.resx new file mode 100644 index 00000000000..223f5410b6c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/NavigationResources.cs.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 + + + Zadaná cesta je kontejner, který má podřízené položky. Chcete odstranit tento kontejner a jeho podřízené položky? + + + Chcete odstranit zadanou položku? + + + Nelze kopírovat, protože zadaný cíl již existuje. Chcete přepsat existující obsah? + + + Nová jednotka + + + Název: {0} Zprostředkovatel: {1} Kořen: {2} + + + Odebrat jednotku + + + Název: {0} Zprostředkovatel: {1} Kořen: {2} + + + Jednotku {0} nelze odebrat, protože se používá. + + + Položka v {0} má podřízené položky a parametr Recurse nebyl zadán. Pokud budete pokračovat, odeberou se spolu s položkou všechny podřízené položky. Opravdu chcete pokračovat? + + + Položku {0} nelze odebrat, protože se používá. + + + Objekt v zadané cestě {0} neexistuje nebo byl filtrován pomocí parametru -Include nebo -Exclude. + + + Nastavit obsah + + + Cesta: {0} + + + Přidat obsah + + + Cesta: {0} + + + Položku nelze přesunout, protože položka {0} neexistuje. + + + Položku nelze přesunout, protože položka v {0} je používána. + + + Nelze přejmenovat, protože položka {0} neexistuje. + + + Položku {0} nelze přejmenovat, protože se používá. + + + Cestu nelze analyzovat, protože cesta {0} nemá zadán kvalifikátor. + + + Začít + + + Vrátit zpět + + + Potvrdit + + + Aktuální transakce + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/ProcessCommandHelpResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ProcessCommandHelpResources.cs.resx new file mode 100644 index 00000000000..e619e61392f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ProcessCommandHelpResources.cs.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 + + + Vypíše aktuálně spuštěné procesy. + + + +-Id id +[int[]] +[vstup z kanálu je povolen] +Čárkami oddělený seznam identifikátorů procesů určujících procesy, které se mají získat + +-ProcessName název +[string[]] +[vstup z kanálu je povolen] +Čárkami oddělený seznam názvů procesů určujících procesy, které se mají získat + +-Exclude název +[ArrayList] +Čárkami oddělený seznam názvů procesů, které mají být z výstupu vyloučeny. + +--- +Příkaz vypíše procesy z místního počítače a vrátí objekty System.Diagnostics.Process. Příkaz zapisuje objekt procesu do výstupního kanálu po jednom. Příkaz přijímá z příkazového řádku parametry, jako jsou ID (identifikátor procesu) nebo ProcessName (název procesu). Příkaz vrátí odpovídající objekt System.Diagnostics.Process pro zadané parametry ID nebo ProcessName. + + + Možnost Vyloučit funguje pouze pro název procesu. + + + Vrátí všechny spuštěné procesy. + + + Vrátí všechny procesy s názvy začínajícími na svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/ProcessResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ProcessResources.cs.resx new file mode 100644 index 00000000000..f22605b5b5b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ProcessResources.cs.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} + + + Uživatel nemá přístup k požadovaným informacím. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/ServiceResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ServiceResources.cs.resx new file mode 100644 index 00000000000..91c82bc2195 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/ServiceResources.cs.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}) + + + Nenašla se žádná služba s názvem služby {0}. + + + Nenašla se žádná služba se zobrazovaným názvem {1}. + + + Službu {1} ({0}) nejde zastavit, protože na ní závisí jiné služby. Službu jde zastavit jen v případě, že je nastavený příznak Force. + + + Službu {1} ({0}) nejde zastavit, protože na ní závisí jiné služby. + + + Službu {1} ({0}) nejde zastavit kvůli následující chybě: {2} + + + Službu {1} ({0}) nejde spustit kvůli následující chybě: {2} + + + Službu {1} ({0}) nejde pozastavit kvůli následující chybě: {2} + + + Službu {1} ({0}) nejde pozastavit, protože nepodporuje pozastavení ani obnovení. + + + Službu {1} ({0}) nejde pozastavit, protože není spuštěná. + + + Službu {1} ({0}) nejde obnovit kvůli následující chybě: {2} + + + Službu {1} ({0}) nejde obnovit, protože nepodporuje pozastavení ani obnovení. + + + Službu {1} ({0}) nejde obnovit, protože není spuštěná. + + + Službu {1} ({0}) nejde nakonfigurovat kvůli následující chybě: {2} + + + Popis služby {1} ({0}) nejde nastavit kvůli následující chybě: {2} + + + U služby {1} ({0}) nejde nastavit automatické spuštění (zpožděné spuštění) kvůli následující chybě: {2} + + + Popisovač zabezpečení služby {0} nejde nastavit kvůli následující chybě: {1} + + + Službu {1} ({0}) nejde vytvořit kvůli následující chybě: {2} + + + Služba {1} ({0}) byla vytvořena, ale její popis nejde nastavit kvůli následující chybě: {2} + + + Služba {1} ({0}) byla vytvořena, ale její typ spuštění StartupType Automatic (Delayed Start) se nepovedlo nastavit kvůli následující chybě: {2} + + + Službu {1} ({0}) nejde odebrat kvůli následující chybě: {2} + + + K závislým službám služby {1} ({0}) nejde získat přístup + + + Čeká se na spuštění služby {1} ({0})... + + + Čeká se na zastavení služby {1} ({0})... + + + Čeká se na pozastavení služby {1} ({0})... + + + Čeká se na obnovení služby {1} ({0})... + + + Službu {1} ({0}) se nepovedlo spustit. + + + Zastavení služby {1} ({0}) se nepovedlo. + + + Pozastavení služby {1} ({0}) se nepovedlo. + + + Obnovení služby {1} ({0}) se nepovedlo. + + + SCManager se nepovedlo otevřít kvůli následující chybě: {0}. Spusťte PowerShell jako správce a potom příkaz spusťte znovu. + + + Typ spuštění {0} není v {1} podporovaný. + + + Vlastnost {1} se u služby {0} nepovedlo načíst: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/TestConnectionResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/TestConnectionResources.cs.resx new file mode 100644 index 00000000000..65fec512efa --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/TestConnectionResources.cs.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 + + + Testování připojení k počítači {0} se nezdařilo: {1} + + + Nelze přeložit název cíle. + + + Cílová adresa IPv4/IPv6 chybí. + + + Nelze dokončit traceroute k cíli „{0}“: Počet přeskoků potřebných k dosažení hostitele překračuje hodnotu MaxHops ({1}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/TestPathResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/TestPathResources.cs.resx new file mode 100644 index 00000000000..8aa59d87333 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/TestPathResources.cs.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 + + + Zadaný argument Path měl hodnotu null nebo představoval prázdnou kolekci. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/cs/TimeZoneResources.cs.resx b/src/Microsoft.PowerShell.Commands.Management/resources/cs/TimeZoneResources.cs.resx new file mode 100644 index 00000000000..83302e57f20 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/cs/TimeZoneResources.cs.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 + + + Místní časové pásmo nelze nastavit, protože název {0} se překládá na více položek. + + + Název časového pásma {0} nebyl v místním počítači nalezen. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ClearRecycleBinResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ClearRecycleBinResources.de.resx new file mode 100644 index 00000000000..acebb930da1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ClearRecycleBinResources.de.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 + + + Alle Inhalte des Papierkorbs + + + Der gesamte Inhalt der Papierkorb für das Laufwerk „{0}“ + + + Papierkorb wird gelöscht + + + für das Laufwerk „{0}“ + + + für alle Laufwerke + + + Laufwerk wurde nicht gefunden. Ein Laufwerk mit dem Namen „{0}“ ist nicht vorhanden. Führen Sie das cmdlet „{1}“ aus, um die verfügbaren Festplattenlaufwerke im System anzuzeigen. + + + Die Eingabe ist ungültig. Die folgenden Formate werden unterstützt: „{0}“, „{1}“ oder „{2}“. + + + Das Laufwerk mit dem Namen „{0}“ ist kein Festplattenlaufwerk und unterstützt die Papierkorb nicht. Führen Sie das cmdlet „{1}“ aus, um die verfügbaren Festplattenlaufwerke im System anzuzeigen. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ClipboardResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ClipboardResources.de.resx new file mode 100644 index 00000000000..4d717d9f91b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ClipboardResources.de.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Zeichenfolge „{0}“ in die Zwischenablage festlegen. + + + Zeichenfolge „{0}“ an die Zwischenablage anhängen. + + + Legen Sie die Datei „{0}“ in der Zwischenablage fest. + + + Hängen Sie die Datei „{0}“ an die Zwischenablage an. + + + Legen Sie {0} Dateien in der Zwischenablage fest. + + + Fügen Sie {0} Dateien an die Zwischenablage an. + + + In der Zwischenablage sind keine Inhalte vorhanden, oder das Inhaltsformat ist nicht kompatibel. Legen Sie das Eingabeobjekt auf die Zwischenablage fest. + + + Die Zwischenablage wurde gelöscht. + + + TextFormatType kann nur mit dem Textformat kombiniert werden. + + + Raw kann nur mit dem Text- oder FileDropList-Format kombiniert werden. + + + HTML kann nur mit dem HTML-Textformat kombiniert werden. + + + Auf dieser Plattform wird nur das Textformat unterstützt. + + + Die Zwischenablage wird auf dieser Plattform nicht unterstützt. + + + Der Schalter „-AsHtml“ wird auf dieser Plattform nicht unterstützt. + + + Der Parameter „-TextFormatType“ unterstützt nur „Text“ auf dieser Plattform. + + + Der Parameter „-Path“ wird auf dieser Plattform nicht unterstützt. + + + Der Parameter -LiteralPath wird auf dieser Plattform nicht unterstützt. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/CmdletizationResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/CmdletizationResources.de.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/CmdletizationResources.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ComputerInfoResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ComputerInfoResources.de.resx new file mode 100644 index 00000000000..bbf97b78caf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ComputerInfoResources.de.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 + + + Informationen zum Betriebssystem werden geladen + + + Hotpatchinformationen werden geladen + + + Registrierungsinformationen werden geladen + + + BIOS-Informationen werden geladen + + + Hauptplatineninformationen werden geladen + + + Computerinformationen werden geladen + + + Prozessorinformationen werden geladen + + + Informationen zum Netzwerkadapter werden geladen + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ComputerResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ComputerResources.de.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ComputerResources.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/HotFixResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/HotFixResources.de.resx new file mode 100644 index 00000000000..0acf66f51bf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/HotFixResources.de.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 + + + Der angeforderte Hotfix wurde auf dem Computer „{0}“ nicht gefunden. Überprüfen Sie die Eingabe, und führen Sie den Befehl erneut aus. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/NavigationResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/NavigationResources.de.resx new file mode 100644 index 00000000000..7e763e49448 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/NavigationResources.de.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 + + + Der angegebene Pfad ist ein Container mit untergeordneten Elementen. Möchten Sie diesen Container und seine untergeordneten Elemente löschen? + + + Möchten Sie das angegebene Element löschen? + + + Kann nicht kopiert werden, da das angegebene Ziel bereits vorhanden ist. Möchten Sie den vorhandenen Inhalt überschreiben? + + + Neues Laufwerk + + + Name: {0} Anbieter: {1} Stamm: {2} + + + Laufwerk entfernen + + + Name: {0} Anbieter: {1} Stamm: {2} + + + Das Laufwerk „{0}“ kann nicht entfernt werden, da es verwendet wird. + + + Das Element hat {0} untergeordnete Elemente und der Recurse-Parameter wurde nicht angegeben. Wenn Sie fortfahren, werden alle untergeordneten Elemente mit dem Element entfernt. Sind Sie sicher, dass Sie den Vorgang fortsetzen? + + + Das Element unter „{0}“ kann nicht entfernt werden, da es verwendet wird. + + + Ein Objekt am angegebenen Pfad {0} ist nicht vorhanden oder wurde mit dem -Include- oder -Exclude-Parameter gefiltert. + + + Inhalt festlegen + + + Pfad: {0} + + + Inhalt hinzufügen + + + Pfad: {0} + + + Das Element kann nicht verschoben werden, da das Element unter „{0}“ nicht vorhanden ist. + + + Das Element kann nicht verschoben werden, da das Element unter „{0}“ verwendet wird. + + + Kann nicht umbenannt werden, da das Element unter „{0}“ nicht vorhanden ist. + + + Das Element kann nicht unter „{0}“ umbenannt werden, da es verwendet wird. + + + Der Pfad kann nicht analysiert werden, da für den Pfad „{0}“ kein Qualifizierer angegeben ist. + + + Beginn + + + Rollback + + + Committen + + + Aktuelle Transaktion + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ProcessCommandHelpResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ProcessCommandHelpResources.de.resx new file mode 100644 index 00000000000..db935ef5512 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ProcessCommandHelpResources.de.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 + + + Listet Prozesse auf, die derzeit ausgeführt werden. + + + +-Id id +[int[]] +[Pipelineeingabe zulässig] +Durch Kommata getrennte Liste von Prozessbezeichnern, die die abzurufenden Prozesse angeben + +-ProcessName-Name +[Zeichenfolge[]] +[Pipelineeingabe zulässig] +Durch Kommata getrennte Liste von Prozessnamen, die die abzurufenden Prozesse angeben + +-Name ausschließen +[ArrayList] +Durch Kommata getrennte Liste von Prozessnamen, die von der Ausgabe ausgeschlossen werden sollen. + +--- +Der Befehl listet Prozesse vom lokalen Computer auf und gibt System.Diagnostics.Process-Objekt(e) aus. Der Befehl schreibt das Prozessobjekt einzeln in die Ausgabepipeline. Der Befehl akzeptiert Parameter wie ID (Prozessbezeichner) oder Prozessname über die Befehlszeile. Der Befehl gibt den entsprechenden system.diagnostics.process-Wert für die angegebenen ID- oder ProcessName-Parameter zurück. + + + „Ausschließen“ funktioniert nur für den Prozessnamen. + + + Gibt alle laufenden Prozesse zurück. + + + Gibt alle Prozesse mit Namen zurück, die mit svc beginnen. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ProcessResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ProcessResources.de.resx new file mode 100644 index 00000000000..e6c243359d0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ProcessResources.de.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 + + + Es wurde kein Prozess mit dem Namen „{0}“ gefunden. Überprüfen Sie den Prozessnamen, und rufen Sie das Cmdlet erneut auf. + + + Es wurde kein Prozess mit dem Namen „{0}“ gefunden. Führen Sie den Befehl mit -Id aus, um nach der ID der Prozesse zu suchen. + + + Dieser Befehl kann nicht ausgeführt werden, da der Debugger nicht an den Prozess „{0} ({1})“ angefügt werden kann. Geben Sie einen anderen Prozess an, und führen Sie den Befehl aus. + + + Es wurde kein Prozess mit der Prozess-ID „{1}“ gefunden. + + + Der Prozess „{0} ({1})“ kann aufgrund des folgenden Fehlers nicht beendet werden: {2} + + + {0} ({1}) + + + {0} {1} + + + Die Module des Prozesses „{0}“ können nicht aufgelistet werden. + + + Die Dateiversionsinformationen des Prozesses „{0}“ können nicht aufgezählt werden. + + + Die Module und die Dateiversionsinformationen des Prozesses „{0}“ können nicht aufgezählt werden. + + + Möchten Sie den Stop-Process-Vorgang für das folgende Element ausführen: {0}({1})? + + + Der angegebene Pfad ist keine gültige win32-Anwendung. Wiederholen Sie den Vorgang mit UseShellExecute. + + + Dieser Befehl hat den Vorgang von „{0} ({1})“ aufgrund des folgenden Fehlers beendet: {2}. + + + Dieser Befehl kann nicht ausgeführt werden, da Umleitungsparameter nicht zusammen mit dem Parameter UseShellExecute verwendet werden können. + + + Ausnahme beim Abrufen von „Modules“ oder „FileVersion“: „This feature is not supported for remote computers.“. + + + Dieser Befehl kann den Debugger nicht an den Prozess anfügen, da „{0}“ kein Standarddebugger verfügbar ist. + + + Dieser Befehl hat den Vorgang beendet, da er nicht auf den Prozess „System Idle“ (System im Leerlauf) warten kann. Geben Sie einen anderen Prozess an, und führen Sie den Befehl erneut aus. + + + Dieser Befehl hat den Vorgang beendet, da er nicht auf sich selbst warten kann. Geben Sie einen anderen Prozess an, und führen Sie den Befehl erneut aus. + + + Dieser Befehl hat den Vorgang beendet, da der Prozess „{0} ({1})“ nicht innerhalb der angegebenen Zeitüberschreitung beendet wurde. + + + Dieser Befehl kann aufgrund des folgenden Fehlers nicht ausgeführt werden: {0} + + + Dieser Befehl kann nicht ausgeführt werden, da die Eingabe „{0}“ keine gültige Anwendung ist. Geben Sie eine gültige Anwendung an, und führen Sie den Befehl erneut aus. + + + Dieser Befehl kann nicht ausgeführt werden, da der Parameter „{0}“ einen ungültigen Wert hat oder nicht mit diesem Befehl verwendet werden kann. Geben Sie eine gültige Eingabe ein, und führen Sie den Befehl erneut aus. + + + Dieser Befehl kann nicht ausgeführt werden, da „{0}“ und „{1}“ identisch sind. Geben Sie unterschiedliche Eingaben an, und führen Sie den Befehl erneut aus. + + + Dieser Befehl kann nicht vollständig ausgeführt werden, da das System nicht alle erforderlichen Informationen finden kann. + + + Beim Abrufen des neuen Prozesshandles ist ein Fehler aufgetreten: „{0}“. Das ausgegebene Process-Objekt verfügt möglicherweise über einige Eigenschaften und Methoden, die nicht ordnungsgemäß funktionieren. + + + Dieser Befehl kann aufgrund des Fehlers 1783 nicht ausgeführt werden. Eine mögliche Ursache für diesen Fehler ist die Verwendung des nicht vorhandenen Benutzers „{0}“. Geben Sie einen gültigen Benutzer an, und führen Sie den Befehl erneut aus. + + + Fehler beim Hinzufügen von „{0}“ zum Netzwerk: {1} + + + Fehler beim Entfernen von „{0}“ aus dem Netzwerk: {1} + + + Fehler beim Umbenennen von „{0}“: {1} + + + Die Parameter „{0}“ und „{1}“ können nicht gleichzeitig festgelegt werden. + + + Der Prozess „{0} ({1})“ kann aufgrund des folgenden Fehlers nicht debuggen werden: {2} + + + Der Benutzer besitzt keinen Zugriff auf die angeforderten Informationen. + + + Der angegebene Parameter ist ungültig. + + + Der Benutzer verfügt nicht über ausreichende Berechtigungen. + + + Unbekannter Fehler. + + + Der angegebene Pfad ist nicht vorhanden. + + + Der Parameter „{0}“ wird für das Cmdlet „{1}“ in dieser Windows-Edition nicht unterstützt. + + + Der Parameter „{0}“ wird für das Cmdlet „{1}“ in dieser PowerShell-Edition nicht unterstützt. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/ServiceResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/ServiceResources.de.resx new file mode 100644 index 00000000000..01824eb79fa --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/ServiceResources.de.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}) + + + Es wurde kein Dienst mit dem Dienstnamen „{0}“ gefunden. + + + Es wurde kein Dienst mit dem Anzeigenamen „{1}“ gefunden. + + + Der Dienst „{1} ({0})“ kann nicht beendet werden, da er abhängige Dienste aufweist. Er kann nur beendet werden, wenn das Force-Flag festgelegt ist. + + + Der Dienst „{1} ({0})“ kann nicht beendet werden, da er abhängige Dienste aufweist. + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht beendet werden: {2} + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht gestartet werden: {2} + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht angehalten werden: {2} + + + Der Dienst „{1} ({0})“ kann nicht angehalten werden, da der Dienst das Anhalten oder Fortsetzen nicht unterstützt. + + + Der Dienst „{1} ({0})“ kann nicht angehalten werden, da er derzeit nicht ausgeführt wird. + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht fortgesetzt werden: {2} + + + Der Dienst „{1} ({0})“ kann nicht fortgesetzt werden, da der Dienst das Anhalten oder Fortsetzen nicht unterstützt. + + + Der Dienst „{1} ({0})“ kann nicht fortgesetzt werden, da er derzeit nicht ausgeführt wird. + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht konfiguriert werden: {2} + + + Die Beschreibung des Diensts „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht konfiguriert werden: {2} + + + Für den Dienst „{1} ({0})“ kann „Automatisch (verzögerter Start)“ aufgrund des folgenden Fehlers nicht konfiguriert werden: {2} + + + Der Sicherheitsdeskriptor des Diensts „{0}“ kann aufgrund des folgenden Fehlers nicht konfiguriert werden: {1} + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht erstellt werden: {2} + + + Der Dienst „{1} ({0})“ wurde erstellt, aber seine Beschreibung kann aufgrund des folgenden Fehlers nicht konfiguriert werden: {2} + + + Der Dienst „{1} ({0})“ wurde erstellt, aber der Starttyp „Automatisch (verzögerter Start)“ konnte aufgrund des folgenden Fehlers nicht konfiguriert werden: {2} + + + Der Dienst „{1} ({0})“ kann aufgrund des folgenden Fehlers nicht entfernt werden: {2} + + + Auf die abhängigen Dienste von „{1} ({0})“ kann nicht zugegriffen werden + + + Es wird auf das Starten des Diensts „{1} ({0})“ gewartet... + + + Es wird auf das Beenden des Diensts „{1} ({0})“ gewartet... + + + Es wird auf das Anhalten des Diensts „{1} ({0})“ gewartet... + + + Es wird auf das Fortsetzen des Diensts „{1} ({0})“ gewartet... + + + Fehler beim Starten des Diensts „{1} ({0})“. + + + Fehler beim Beenden des Diensts „{1} ({0})“. + + + Fehler beim Anhalten des Diensts „{1} ({0})“. + + + Fehler beim Fortsetzen des Diensts „{1} ({0})“. + + + SCManager konnte aufgrund des folgenden Fehlers nicht geöffnet werden: {0}. Führen Sie PowerShell als Administrator aus, und führen Sie den Befehl erneut aus. + + + Der Starttyp „{0}“ wird von „{1}“ nicht unterstützt. + + + Die Eigenschaft „{1}“ für den Dienst „{0}“ konnte nicht abgerufen werden: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/TestConnectionResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/TestConnectionResources.de.resx new file mode 100644 index 00000000000..72191589598 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/TestConnectionResources.de.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 + + + Verbindung zum Computer „{0}“ konnte nicht getestet werden: {1} + + + Der Zielname kann nicht aufgelöst werden. + + + Die Ziel-IPv4-/IPv6-Adresse fehlt. + + + Der Traceroute-Vorgang zum Ziel „{0}“ kann nicht abgeschlossen werden: Die Anzahl der erforderlichen Hops zum Erreichen des Hosts überschreitet MaxHops ({1}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/TestPathResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/TestPathResources.de.resx new file mode 100644 index 00000000000..6fed3545078 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/TestPathResources.de.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 + + + Das angegebene Path-Argument war Null oder eine leere Auflistung. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/de/TimeZoneResources.de.resx b/src/Microsoft.PowerShell.Commands.Management/resources/de/TimeZoneResources.de.resx new file mode 100644 index 00000000000..2788e83d3cf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/de/TimeZoneResources.de.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 + + + Die lokale Zeitzone kann nicht festgelegt werden, da der Name „{0}“ mehreren Einträgen entspricht. + + + Der Zeitzonenname „{0}“ wurde auf dem lokalen Computer nicht gefunden. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ClearRecycleBinResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ClearRecycleBinResources.es.resx new file mode 100644 index 00000000000..33d86a8b2b9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ClearRecycleBinResources.es.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 + + + Todo el contenido de la papelera de reciclaje + + + Todo el contenido de la papelera de reciclaje de la unidad "{0}" + + + Borrando papelera de reciclaje + + + para la unidad "{0}" + + + en todas las unidades. + + + No se encuentra la unidad. No existe una unidad con el nombre '{0}'. Ejecute el cmdlet "{1}" para ver las unidades fijas disponibles en el sistema. + + + Entrada no válida. Se admiten los formatos siguientes: '{0}', '{1}' o '{2}'. + + + La unidad con el nombre '{0}' no es una unidad fija y no admite el papelera de reciclaje. Ejecute el cmdlet "{1}" para ver las unidades fijas disponibles en el sistema. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ClipboardResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ClipboardResources.es.resx new file mode 100644 index 00000000000..c319969cf54 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ClipboardResources.es.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Establezca la cadena "{0}" en el Portapapeles. + + + Anexe la cadena "{0}" en el Portapapeles. + + + Establezca el archivo "{0}" en el Portapapeles. + + + Anexar el archivo "{0}" al Portapapeles. + + + Establezca {0} archivos en el Portapapeles. + + + Anexe {0} archivos en el Portapapeles. + + + No hay contenido en Portapapeles o el formato del contenido no es compatible. Establece el objeto de entrada en el Portapapeles. + + + Se ha borrado el Portapapeles. + + + TextFormatType solo se puede combinar con el formato Text. + + + Raw solo se puede combinar con los formatos Text o FileDropList. + + + HTML solo se puede combinar con el formato HTML Text. + + + En esta plataforma solo se admite el formato Text. + + + El Portapapeles no se admite en esta plataforma. + + + El modificador '-AsHtml' no se admite en esta plataforma. + + + El parámetro "-TextFormatType" solo admite "Text" en esta plataforma. + + + El parámetro "-Path" no se admite en esta plataforma. + + + El parámetro "-LiteralPath" no se admite en esta plataforma. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/CmdletizationResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/CmdletizationResources.es.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/CmdletizationResources.es.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ComputerInfoResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ComputerInfoResources.es.resx new file mode 100644 index 00000000000..522b61cb43a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ComputerInfoResources.es.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 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ComputerResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ComputerResources.es.resx new file mode 100644 index 00000000000..f74f3ec280f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ComputerResources.es.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 + + + Esta funcionalidad no se admite en este sistema operativo. + + + No se pudo habilitar la unidad {0}. + + + El comando no puede activar la infraestructura del equipo de restauración en el equipo especificado porque la unidad proporcionada no es válida. Escriba una unidad válida en el parámetro Drive e inténtelo de nuevo. + + + Incluir unidad del sistema en la lista de unidades. + + + El comando no puede desactivar la infraestructura del equipo de restauración porque la unidad proporcionada no es válida. Escriba una unidad válida en el parámetro Drive e inténtelo de nuevo. + + + El comando no puede desactivar Restaurar sistema en la unidad {0}. Es posible que no tenga permisos suficientes para realizar esta operación. + + + El servicio SystemRestore está deshabilitado. + + + La infraestructura de restauración del sistema no puede crear un punto de restauración. + + + Error en el último intento de restaurar el equipo. + + + El equipo se restauró al punto de restauración especificado. + + + Se interrumpió el último intento de restaurar el equipo. + + + El comando no encuentra el punto de restauración "{0}". Compruebe el número de secuencia "{0}" e intente el comando de nuevo. + + + {0} ({1}) + + + No se pudo reiniciar el equipo {0} con el siguiente mensaje de error: {1}. + + + Este comando no se puede ejecutar en el equipo de destino ("{1}") debido al siguiente error: {0}.{2} + + + No se pudo detener el equipo {0} con el siguiente mensaje de error: {1}. + + + El comando no puede restaurar el equipo porque "{0}" no se ha establecido como punto de restauración válido. Escriba un punto de restauración válido en el parámetro RestorePoint e inténtelo de nuevo. + + + Los cambios surtirán efecto después de reiniciar el equipo {1}. + + + Después de abandonar el dominio, deberá conocer la contraseña de la cuenta de administrador local para iniciar sesión en este equipo. ¿Desea continuar? + + + El siguiente nombre de equipo no es válido: {0}. Asegúrese de que el nombre del equipo no tenga más de 255 caracteres, que no contenga dos o más puntos consecutivos, que no comience con un punto, que no contenga solo caracteres numéricos y que no contenga ninguno de los siguientes caracteres: +{{|}}~[\]^:; <=>?@!" #$%^`()+/, + + + El dominio del nombre de equipo "{0}" no es válido. Asegúrese de que el dominio existe y de que el nombre es un nombre de dominio válido. + + + El valor especificado para el parámetro NewComputerName es el mismo que el valor del parámetro ComputerName. Proporcione un valor diferente para el parámetro NewComputerName. + + + "Se restableció la contraseña del canal seguro entre "{0}" y "{1}". + + + Este comando no se puede ejecutar debido al siguiente error: no se puede iniciar el servicio porque está deshabilitado o no tiene dispositivos habilitados asociados. + + + Creando un punto de restauración del sistema... + + + Creando un punto de restauración del sistema... {0}% completado. + + + Completado. + + + Pruebe las opciones siguientes y vuelva a ejecutar el comando. +1. Compruebe que el equipo de destino (''{0}") se está ejecutando. +2. Especifique el nombre completo del equipo de destino (''{0}"). + + + No se pudo reiniciar el equipo {0}. No se pueden habilitar derechos {1} de acceso para el proceso de llamada. + + + Habilite la {0} y reinicie el equipo. + + + Derechos de acceso de apagado local + + + Derechos de acceso de apagado remoto + + + No se puede esperar a que se reinicie el equipo local. El equipo local se omite cuando se especifica el parámetro Wait. + + + Los parámetros Timeout, For y Delay solo son válidos cuando se especifica el parámetro Wait. + + + Reiniciando equipos... + + + Reiniciando el equipo {0} + + + Completado: {0}/{1}. + + + Comprobando que se ha reiniciado el equipo... + + + Esperando la conectividad de PowerShell... + + + Esperando a que comience el reinicio... + + + Esperando la conectividad de WinRM... + + + Esperando conectividad WMI... + + + Se completó el reinicio + + + Los tipos de servicio combinados no se admiten por ahora. + + + El nombre del equipo {0} no se puede resolver con la excepción: {1}. + + + El número de nombres nuevos no es igual al número de equipos de destino. + + + Omita el equipo "{0}" con el nuevo nombre v{1}" porque el nuevo nombre no es válido. El nuevo nombre de equipo especificado no tiene el formato correcto. Los nombres estándar pueden contener letras (a-z, A-Z), números (0-9) y guiones (-), pero sin espacios ni puntos (.). El nombre no puede constar por completo de dígitos y no puede tener más de 63 caracteres. + + + Omita el equipo "{0}" con el nuevo nombre "{1}" porque el nuevo nombre es el mismo que el nombre actual. + + + No se puede quitar el equipo "{0}" porque no está en un dominio. + + + No se pudo unir el equipo "{0}" al grupo de trabajo "{1}" con el siguiente mensaje de error: {2} + + + No se pueden quitar equipos del dominio porque la red local está inactiva. + + + No se pudo cambiar el nombre del equipo "{0}" a "{1}" debido a la siguiente excepción: {2}. + + + Unirse al dominio "{0}" + + + Unirse al grupo de trabajo "{0}" + + + No se puede agregar el equipo "{0}" al dominio "{1}" porque ya está en ese dominio. + + + No se puede agregar el equipo "{0}" al grupo de trabajo "{1}" porque ya está en ese grupo de trabajo. + + + El equipo "{0}" se unió correctamente al grupo de trabajo "{1}", pero no se pudo cambiar el nombre a "{2}" con el siguiente mensaje de error: {3}. + + + El equipo "{0}" se desinstaló correctamente del dominio ''{1}", pero no pudo unirse al grupo de trabajo "{2}" con el siguiente mensaje de error: {3}. + + + No se pudo quitar el equipo "{0}" del dominio "{1}" con el siguiente mensaje de error: {2}. + + + No se puede establecer la conexión WMI con el equipo "{0}" con el siguiente mensaje de error: {1}. + + + El equipo "{0}" no pudo unirse al dominio '"{1}" desde su grupo de trabajo actual "{2}" con el siguiente mensaje de error: {3}. + + + El equipo "{0}" se desinstaló correctamente del dominio ''{1}", pero no pudo unirse al nuevo dominio "{2}" con el siguiente mensaje de error: {3}. + + + El equipo "{0}" se unió correctamente al nuevo dominio ''{1}", pero al cambiar su nombre a "{2}" se produjo el siguiente mensaje de error: {3}. + + + La marca "{0}" solo es válida si se especifica la marca ''{1}". + + + No se puede cambiar el nombre de varios equipos. El parámetro NewName solo es válido si se especifica un único equipo. + + + No se encuentra la cuenta de equipo del equipo local en el dominio {0}. + + + No se encuentra la cuenta de equipo del equipo local desde el controlador de dominio {0}. + + + No se puede obtener información de dominio sobre el equipo local debido a la siguiente excepción: {0}. + + + No se puede restablecer la contraseña del canal seguro para la cuenta de equipo en el dominio. Error en la operación con la siguiente excepción: {0}. + + + Error al restablecer la contraseña del canal seguro para el equipo local con el siguiente mensaje de error: {0}. + + + Se requieren derechos de administrador para restablecer la contraseña del canal seguro en el equipo local. Acceso denegado. + + + No se puede restablecer la contraseña del canal seguro para la cuenta del equipo local. El equipo local no forma parte actualmente de un dominio. + + + El nombre NetBIOS del equipo está limitado a 15 bytes, que en este caso son 15 caracteres. El nombre NetBIOS se acortará a "{0}", lo que puede provocar conflictos en la resolución de nombres NetBIOS. ¿Desea continuar? + + + El nombre NetBIOS se truncará. + + + No se puede resolver el nombre de servidor especificado {0}. + + + No se puede crear un nuevo punto de restauración del sistema porque ya se ha creado uno en los últimos {0} minutos. La frecuencia de creación de puntos de restauración se puede cambiar creando el valor DWORD 'SystemRestorePointCreationFrequency' en la clave del Registro 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore'. El valor de esta clave del Registro indica el intervalo de tiempo necesario (en minutos) entre dos creaciones de puntos de restauración. El valor predeterminado es 1440 minutos (24 horas). + + + No se puede recuperar el objeto WMI Win32_OperatingSystem. + + + Se omite el equipo {0}. No se pudo recuperar su LastBootUpTime a través del servicio WMI con el siguiente mensaje de error: {1}. + + + No se puede comprobar el canal seguro para el equipo local. Error en la operación con la siguiente excepción: {0}. + + + Error al intentar reparar el canal seguro entre el equipo local y el dominio {0}. + + + El canal seguro entre el equipo local y el dominio {0} se reparó correctamente. + + + El canal seguro entre el equipo local y el dominio {0} está en buen estado. + + + El canal seguro entre el equipo local y el dominio {0} está roto. + + + No se puede comprobar la contraseña del canal seguro para el equipo local. El equipo local no forma parte actualmente de un dominio. + + + No se puede realizar la operación porque las API de restauración del sistema no se admiten en la plataforma Advanced RISC Machine (ARM). + + + El equipo no finalizó el reinicio dentro del período de tiempo de espera especificado. + + + No se puede validar el intervalo de tiempo para la creación de puntos de restauración. No se pudo recuperar el último punto de restauración con el siguiente mensaje de error: {0}. + + + No se admite el conjunto de parámetros AsJob. + + + El parámetro {0} no es compatible con CoreCLR. + + + No se encontró el comando nativo necesario "shutdown". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/HotFixResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/HotFixResources.es.resx new file mode 100644 index 00000000000..eeef8ff6a37 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/HotFixResources.es.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 + + + No se encuentra la revisión solicitada en el equipo ''{0}. Compruebe la entrada y vuelva a ejecutar el comando. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/NavigationResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/NavigationResources.es.resx new file mode 100644 index 00000000000..11f281978c9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/NavigationResources.es.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 + + + La ruta de acceso especificada es un contenedor que tiene elementos secundarios. ¿Desea eliminar este contenedor y sus elementos secundarios? + + + ¿Desea eliminar el elemento especificado? + + + No se puede copiar porque el destino especificado ya existe. ¿Desea sobrescribir el contenido existente? + + + Nueva unidad + + + Nombre: {0} Proveedor: {1} Raíz: {2} + + + Quitar unidad + + + Nombre: {0} Proveedor: {1} Raíz: {2} + + + No se puede quitar la unidad "{0}" porque está en uso. + + + El elemento en {0} tiene elementos secundarios y no se especificó el parámetro Recurse. Si continúa, se quitarán todos los elementos secundarios con el elemento. ¿Está seguro de que quiere continuar? + + + No se puede quitar el elemento en "{0}" porque está en uso. + + + Un objeto en la ruta de acceso especificada {0} no existe, o se ha filtrado mediante el parámetro -Include o -Exclude. + + + Establecer contenido + + + Ruta de acceso: {0} + + + Agregar contenido + + + Ruta de acceso: {0} + + + No se puede mover el elemento porque el elemento de "{0}" no existe. + + + No se puede mover el elemento porque el elemento en "{0}" está en uso. + + + No se puede cambiar el nombre porque el elemento en "{0}" no existe. + + + No se puede cambiar el nombre del elemento en "{0}" porque está en uso. + + + No se puede analizar la ruta de acceso porque la ruta de acceso "{0}" no tiene especificado un calificador. + + + Comenzar + + + Reversión + + + Confirmar + + + Transacción actual + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ProcessCommandHelpResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ProcessCommandHelpResources.es.resx new file mode 100644 index 00000000000..9c8ec651897 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ProcessCommandHelpResources.es.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 + + + Enumera los procesos que se están ejecutando actualmente. + + + +Id. -Id +[int[]] +[se permite entrada por canalización] +Lista separada por comas de identificadores de proceso que especifican los procesos que se van a obtener + +Nombre -ProcessName +[string[]] +[se permite entrada por canalización] +Lista separada por comas de nombres de proceso que especifican los procesos que se van a obtener + +Nombre -Exclude +[ArrayList] +Lista separada por comas de nombres de procesos que se excluirán de la salida. + +--- +El comando enumera los procesos del equipo local y devuelve objetos System.Diagnostics.Process. El comando escribe el objeto de proceso en la canalización de salida uno a uno. El comando toma parámetros como id. (identificador de proceso) o nombre de proceso desde la línea de comandos. El comando devuelve el system.diagnostics.process correspondiente para los parámetros id. o ProcessName proporcionados. + + + La exclusión solo funciona para el nombre del proceso. + + + Devuelve todos los procesos en ejecución. + + + Devuelve todos los procesos cuyos nombres empiezan por svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ProcessResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ProcessResources.es.resx new file mode 100644 index 00000000000..49286f06c70 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ProcessResources.es.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 + + + No se encuentra un proceso con el nombre "{0}". Compruebe el nombre del proceso y vuelva a llamar al cmdlet. + + + No se encuentra un proceso con el nombre "{0}". Intente ejecutar con -Id para buscar por id. de procesos. + + + Este comando no se puede ejecutar porque el depurador no se puede asociar al proceso "{0} ({1})". Especifique otro proceso y ejecute el comando. + + + No se encuentra ningún proceso con el identificador de proceso {1}. + + + No se puede detener el proceso "{0} ({1})" debido al siguiente error: {2} + + + {0} ({1}) + + + {0} {1} + + + No se pueden enumerar los módulos del proceso "{0}". + + + No se puede enumerar la información de versión del archivo del proceso "{0}". + + + No se pueden enumerar los módulos ni la información de versión del archivo del proceso "{0}". + + + ¿Está seguro de que desea realizar la operación Stop-Process en el siguiente elemento: {0}({1})? + + + La ruta de acceso especificada no es una aplicación win32 válida. Vuelva a intentarlo con UseShellExecute. + + + Este comando detuvo la operación de "{0} ({1})" debido al siguiente error: {2}. + + + No se puede ejecutar este comando porque no se pueden usar parámetros de redirección con el parámetro UseShellExecute + + + Excepción al obtener "Modules" o "FileVersion": "Esta característica no se admite para equipos remotos". + + + Este comando no puede asociar el depurador al proceso porque {0} no hay ningún depurador predeterminado disponible. + + + Este comando detuvo la operación porque no puede esperar en el proceso "Inactiva del sistema". Especifique otro proceso y vuelva a ejecutar el comando. + + + Este comando detuvo la operación porque no puede esperar por sí mismo. Especifique otro proceso y vuelva a ejecutar el comando. + + + Este comando detuvo la operación porque el proceso "{0} ({1})" no se detuvo en el tiempo de espera especificado. + + + Este comando no se puede ejecutar debido al error: {0} + + + No se puede ejecutar este comando porque la entrada "{0}" no es una aplicación válida. Proporcione una aplicación válida y vuelva a ejecutar el comando. + + + Este comando no se puede ejecutar porque el parámetro "{0}" tiene un valor que no es válido o no se puede usar con este comando. Proporcione una entrada válida y vuelva a ejecutar el comando. + + + No se puede ejecutar este comando porque "{0}" y "{1}" son iguales. Proporcione entradas diferentes y vuelva a ejecutar el comando. + + + Este comando no se puede ejecutar completamente porque el sistema no encuentra toda la información necesaria. + + + No se pudo recuperar el nuevo identificador de proceso: "{0}". El objeto Process generado puede tener algunas propiedades y métodos que no funcionan correctamente. + + + Este comando no se puede ejecutar debido al error 1783. La posible causa de este error puede ser el uso de un usuario no existente "{0}". Proporcione un usuario válido y vuelva a ejecutar el comando. + + + Error al agregar "{0}" a la red: {1} + + + Error al quitar "{0}" de la red: {1} + + + Error al cambiar el nombre de "{0}": {1} + + + Los parámetros "{0}" y "{1}" no se pueden especificar al mismo tiempo. + + + No se puede depurar el proceso "{0} ({1})" debido al siguiente error: {2} + + + El usuario no tiene acceso a la información pedida. + + + El parámetro especificado no es válido. + + + El usuario no tiene privilegios suficientes. + + + Error desconocido. + + + La ruta especificada no existe. + + + El parámetro "{0}" no es compatible con el cmdlet "{1}" en esta edición de Windows. + + + El parámetro "{0}" no es compatible con el cmdlet "{1}" en esta edición de PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/ServiceResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/ServiceResources.es.resx new file mode 100644 index 00000000000..d796ec09df5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/ServiceResources.es.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}) + + + No se encuentra ningún servicio con el nombre de servicio "{0}". + + + No se encuentra ningún servicio con el nombre para mostrar "{1}". + + + No se puede detener el servicio "{1} ({0})" porque tiene servicios dependientes. Solo se puede detener si se establece la marca Force. + + + No se puede detener el servicio "{1} ({0})" porque tiene servicios dependientes. + + + El servicio "{1} ({0})" no se puede detener debido al siguiente error: {2} + + + No se puede iniciar el servicio "{1} ({0})" debido al siguiente error: {2} + + + El servicio "{1} ({0})" no se puede suspender debido al siguiente error: {2} + + + El servicio "{1} ({0})" no se puede suspender porque el servicio no admite que se suspenda o reanude. + + + El servicio "{1} ({0})" no se puede suspender porque no se está ejecutando actualmente. + + + No se puede reanudar el servicio "{1} ({0})" debido al siguiente error: {2} + + + El servicio "{1} ({0})" no se puede reanudar porque el servicio no admite que se suspenda o reanude. + + + El servicio "{1} ({0})" no se puede reanudar porque no se está ejecutando actualmente. + + + El servicio "{1} ({0})" no se puede configurar debido al siguiente error: {2} + + + No se puede configurar la descripción del servicio "{1} ({0})" debido al siguiente error: {2} + + + El servicio "{1} ({0})" automático (inicio retrasado) no se puede configurar debido al siguiente error: {2} + + + No se puede configurar el descriptor de seguridad del servicio "{0}" debido al siguiente error: {1} + + + No se puede crear el servicio "{1} ({0})" debido al siguiente error: {2} + + + Se creó el servicio "{1} ({0})", pero su descripción no se puede configurar debido al siguiente error: {2} + + + Se creó el servicio "{1} ({0})", pero no se pudo configurar StartupType "Automático (inicio retrasado)" debido al siguiente error: {2} + + + No se puede quitar el servicio "{1} ({0})" debido al siguiente error: {2} + + + 'No se puede acceder a los servicios dependientes de "{1} ({0})" + + + Esperando a que se inicie el servicio "{1} ({0})"... + + + Esperando a que el servicio "{1} ({0})" se detenga... + + + Esperando a que el servicio "{1} ({0})" se suspenda... + + + Esperando a que se reanude el servicio "{1} ({0})"... + + + No se pudo iniciar el servicio "{1} ({0})". + + + Error al detener el servicio "{1} ({0})". + + + Error al suspender el servicio "{1} ({0})". + + + Error al reanudar el servicio "{1} ({0})". + + + No se pudo abrir SCManager debido al siguiente error: {0}. Ejecute PowerShell como administrador y vuelva a ejecutar el comando. + + + El tipo de inicio "{0}" no es compatible con {1}. + + + No se pudo recuperar la propiedad "{1}" para el servicio "{0}": {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/TestConnectionResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/TestConnectionResources.es.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/TestConnectionResources.es.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/TestPathResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/TestPathResources.es.resx new file mode 100644 index 00000000000..93969b61234 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/TestPathResources.es.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 + + + El argumento Path proporcionado era nulo o una colección vacía. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/es/TimeZoneResources.es.resx b/src/Microsoft.PowerShell.Commands.Management/resources/es/TimeZoneResources.es.resx new file mode 100644 index 00000000000..3c3a3d5fdd6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/es/TimeZoneResources.es.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 + + + No se puede establecer la zona horaria local porque el nombre "{0}" se resuelve en varias entradas. + + + No se encontró el nombre de zona horaria "{0}" en el equipo local. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ClearRecycleBinResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ClearRecycleBinResources.fr.resx new file mode 100644 index 00000000000..1e4c3e85da9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ClearRecycleBinResources.fr.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 + + + Tous les éléments de la Corbeille + + + Tout le contenu de la Corbeille du lecteur « {0} » + + + Effacement Corbeille + + + pour le lecteur « {0} » + + + pour tous les disques + + + Nous ne pouvons pas trouver le lecteur. Aucun lecteur nommé « {0} » n’existe. Exécutez l’applet de commande « {1} » pour voir les lecteurs fixes disponibles sur le système. + + + Entrée non valide. Les formats suivants sont pris en charge : « {0} », « {1} » ou « {2} ». + + + Le lecteur nommé « {0} » n’est pas un lecteur fixe et ne prend pas en charge la Corbeille. Exécutez l’applet de commande « {1} » pour voir les lecteurs fixes disponibles sur le système. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ClipboardResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ClipboardResources.fr.resx new file mode 100644 index 00000000000..7c9418f2bc2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ClipboardResources.fr.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Définissez la chaîne « {0} » au Presse-papiers. + + + Ajoutez la chaîne « {0} » au Presse-papiers. + + + Définissez le fichier « {0} » au Presse-papiers. + + + Ajoutez le fichier « {0} » au Presse-papiers. + + + Définissez {0} fichiers au Presse-papiers. + + + Ajoutez {0} fichiers au Presse-papiers. + + + Aucun contenu n’est présent dans le Presse-papiers ou le format du contenu n’est pas compatible. Définissez l’objet d’entrée sur le Presse-papiers. + + + Le Presse-papiers a été vidé. + + + TextFormatType ne peut être combiné qu’avec le format Text. + + + Raw ne peut être combiné qu’avec le format Text ou FileDropList. + + + Le format HTML ne peut être combiné qu’avec le format de texte HTML. + + + Seul le format texte est pris en charge sur cette plateforme. + + + Le Presse-papiers n’est pas pris en charge sur cette plateforme. + + + Le commutateur « -AsHtml » n’est pas pris en charge sur cette plateforme. + + + Le paramètre « -TextFormatType » prend en charge uniquement « Text » sur cette plateforme. + + + Le paramètre « -Path » n’est pas pris en charge sur cette plateforme. + + + Le paramètre « -LiteralPath » n’est pas pris en charge sur cette plateforme. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/CmdletizationResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/CmdletizationResources.fr.resx new file mode 100644 index 00000000000..26074da4143 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/CmdletizationResources.fr.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 + + + Impossible de trouver la classe {0} sur le serveur CIM {1}. Vérifiez la valeur de l’attribut XML ClassName dans le fichier XML de définition de la cmdlet, puis réessayez. Exemple de nom de classe valide : 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". + + + + Méthode CIM {1} sur l’objet CIM {0} + {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 + + + Nous n’avons pas pu exécuter {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 + + + Exécution de l’opération suivante : {0}. + {0} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + Les cmdlets CIM ne prennent pas en charge le paramètre {0} avec le paramètre AsJob. Supprimez l’un de ces paramètres, puis réessayez. + {StrContains="AsJob"} +{0} is a placeholder for 'WhatIf' or 'Confirm' cmdlet parameters + + + Requête CIM pour les instances de la classe {0} sur le serveur CIM {1} : {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". + + + La méthode CIM a retourné le code d’erreur suivant : {0} + {0} is a placeholder for an error code returned from a CIM method. Example: 123 + + + La méthode CIM {2} exposée par la classe {0} sur le serveur CIM {1} + {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 + + + Type intrinsèque CIM + + + Littéral WQL + + + Impossible de trouver le paramètre de sortie {2} de la méthode {1} de l’objet CIM {0}. Vérifiez la valeur de l’attribut ParameterName dans le fichier XML de définition de la cmdlet, puis réessayez. + {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. + + + + Aucun objet {1} correspondant trouvé par {0}. Vérifiez les paramètres de la requête, puis réessayez. + + + Aucun objet {2} trouvé avec la propriété « {0} » égale à « {1} ». Vérifiez la valeur de la propriété, puis réessayez. + + + Le type de la propriété {0} ({1}) ne correspond pas au type CIM ({2}) associé au type déclaré dans le fichier XML de définition de la cmdlet. + + + Requête CIM pour énumérer les instances associées de la classe {0} sur le serveur CIM {1} + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + Requête CIM pour énumérer les instances de la classe {0} sur le serveur CIM {1}, associées à l’instance suivante : {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]". + + + La commande {0} ne peut pas se terminer, car le serveur {1} est actuellement occupé. La commande reprendra automatiquement dans {2:f2} secondes. + {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 + + + Impossible de se connecter au serveur VMM. {0} + {0} is a placeholder for a more detailed error message. + + + La cmdlet ne prend pas entièrement en charge l’action Inquire (Demander) pour les messages de débogage. L’opération de la cmdlet se poursuivra pendant la requête. Sélectionnez une autre préférence d’action à l’aide du commutateur -Debug ou de la variable $DebugPreference, puis réessayez. + {StrContains="Debug"} {StrContains="DebugPreference"} {StrContains="Inquire"} + + + La cmdlet ne prend pas entièrement en charge l’action Inquire (Demander) pour les avertissements. L’opération de la cmdlet se poursuivra pendant la requête. Sélectionnez une préférence d’action différente à l’aide du paramètre -WarningAction ou de la variable $WarningPreference, puis réessayez. + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Inquire"} + + + La cmdlet ne prend pas entièrement en charge l’action Stop (Arrêter) pour les avertissements. L’opération de la cmdlet sera interrompue avec un retard. Sélectionnez une préférence d’action différente à l’aide du paramètre -WarningAction ou de la variable $WarningPreference, puis réessayez. + {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} : une CimSession vers le serveur CIM utilise le protocole DCOM, qui ne prend pas en charge le commutateur {1}. + {0} is a placeholder for a name of a computer +{1} is a placeholder for 'Confirm' or 'WhatIf' + + + Aucun objet {2} trouvé avec la propriété « {0} » correspondant à « {1} ». Vérifiez la valeur de la propriété, puis réessayez. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ComputerInfoResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ComputerInfoResources.fr.resx new file mode 100644 index 00000000000..522b61cb43a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ComputerInfoResources.fr.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 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ComputerResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ComputerResources.fr.resx new file mode 100644 index 00000000000..cbf81b15382 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ComputerResources.fr.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 + + + Cette fonctionnalité n’est pas prise en charge sur ce système d’exploitation. + + + Impossible d'activer le lecteur {0}. + + + La commande ne peut pas désactiver l’infrastructure de restauration de l’ordinateur spécifié, car le lecteur fourni n’est pas valide. Entrez un lecteur valide dans le paramètre Drive (Lecteur), puis réessayez. + + + Incluez le lecteur système dans la liste des lecteurs. + + + La commande ne peut pas désactiver l’infrastructure de restauration de l’ordinateur, car le lecteur fourni n’est pas valide. Entrez un lecteur valide dans le paramètre Drive (Lecteur), puis réessayez. + + + La commande ne peut pas désactiver la restauration du système sur le lecteur {0}. Vous n'avez peut-être pas les autorisations suffisantes pour effectuer cette opération. + + + Le service SystemRestore (restauration du système) est désactivé. + + + L’infrastructure de restauration du système ne peut pas créer de point de restauration. + + + La dernière tentative de restauration de l’ordinateur a échoué. + + + L’ordinateur a été restauré au point de restauration spécifié. + + + La dernière tentative de restauration de l’ordinateur a été interrompue. + + + La commande ne peut pas localiser le point de restauration « {0} ». Vérifiez le numéro de séquence « {0} », puis réessayez la commande. + + + {0} ({1}) + + + Nous n’avons pas pu redémarrer l’ordinateur {0} avec le message d’erreur suivant : {1}. + + + Impossible d’exécuter cette commande sur l’ordinateur cible (« {1} ») en raison de l’erreur suivante : {0}.{2} + + + Nous n’avons pas pu arrêter l’ordinateur {0} avec le message d’erreur suivant : {1}. + + + La commande ne peut pas restaurer l’ordinateur, car « {0} » n’a pas été défini comme point de restauration valide. Entrez un point de restauration valide dans le paramètre RestorePoint, puis réessayez. + + + Ces modifications seront prises en compte une fois l’ordinateur {1} redémarré. + + + Après avoir quitté le domaine, vous devrez connaître le mot de passe du compte administrateur local pour ouvrir une session sur cet ordinateur. Voulez-vous vraiment continuer ? + + + Le nom de dossier suivant n'est pas valide : {0}. Vérifiez que le nom d’ordinateur ne dépasse pas 255 caractères, qu’il ne contient pas deux points consécutifs ou plus, qu’il ne commence pas par un point, qu’il ne contient que des caractères numériques et qu’il ne contient aucun des caractères suivants : +{{|}}~[\]^:;<=>?@!"#$%^`()+/, + + + Le domaine dans le nom d’ordinateur « {0} » n’est pas valide. Vérifiez que le domaine existe et que le nom est un nom de domaine valide. + + + La valeur spécifiée pour le paramètre NewComputerName est identique à celle du paramètre ComputerName. Fournissez une autre valeur pour le paramètre NewComputerName. + + + « Le mot de passe du canal sécurisé entre « {0} » et « {1} » a été réinitialisé. » + + + Impossible d’exécuter cette commande en raison de l’erreur suivante : le service ne peut pas être démarré, car il est désactivé ou ne dispose d’aucun appareil activé associé. + + + Création d'un point de restauration du système ... + + + Création d’un point de restauration système... {0} % terminés. + + + Terminé. + + + Essayez les options ci-dessous, puis réexécutez la commande. +1. Vérifiez que l’ordinateur cible (« {0} ») est en fonctionnement. +2. Spécifiez le nom complet de l’ordinateur cible (« {0} »). + + + Nous n’avons pas pu redémarrer l'ordinateur {0}. Impossible d’activer les droits d’accès {1} pour le processus appelant. + + + Activez le {0}, puis redémarrez l’ordinateur. + + + Droits d’accès à l’arrêt local + + + Droits d’accès à l’arrêt à distance + + + Impossible d’attendre le redémarrage de l’ordinateur local. L’ordinateur local est ignoré lorsque le paramètre Wait (Patienter) est spécifié. + + + Les paramètres Timeout (Délai d’expiration), For (Pour) et Delay (Retard) ne sont valides que lorsque le paramètre Wait (Patienter) est spécifié. + + + Redémarrage des ordinateurs... + + + Redémarrage de l’ordinateur {0} + + + Terminé : {0}/{1}. + + + Vérification du redémarrage de l’ordinateur... + + + En attente de la connectivité PowerShell... + + + En attente du début du redémarrage... + + + En attente de la connectivité WinRM... + + + En attente de la connectivité WMI... + + + Le redémarrage est terminé + + + Les types de services combinés ne sont pas pris en charge pour le moment. + + + Impossible de résoudre le nom d’ordinateur {0} avec l’exception : {1}. + + + Le nombre de nouveaux noms n’est pas égal au nombre d’ordinateurs cibles. + + + Ignorez l’ordinateur « {0} » avec le nouveau nom « {1} », car le nouveau nom n’est pas valide. Le nouveau nom d’ordinateur entré n’est pas correctement mis en forme. Les noms Standard peuvent contenir des lettres (a-z, A-Z), des chiffres (0-9) et des traits d’union (-), mais ni espaces ni points (.). Le nom ne peut pas être composé uniquement de chiffres et ne peut pas dépasser 63 caractères. + + + Ignorez l’ordinateur « {0} » avec le nouveau nom « {1} », car ce nouveau nom est identique au nom actuel. + + + Impossible de supprimer l’ordinateur « {0} », car il ne se trouve pas dans un domaine. + + + Nous n’avons pas pu joindre l’ordinateur « {0} » au groupe de travail « {1} » avec le message d’erreur suivant : {2} + + + Impossible de supprimer les ordinateurs du domaine, car le réseau local est hors service. + + + Impossible de renommer l’ordinateur « {0} » en « {1} » en raison de l’exception suivante : {2}. + + + Rejoindre le domaine « {0} » + + + Rejoindre le groupe de travail « {0} » + + + Impossible d’ajouter l’ordinateur « {0} » au domaine « {1} », car il figure déjà dans ce domaine. + + + Impossible d’ajouter l’ordinateur « {0} » au groupe de travail « {1} », car il figure déjà dans ce groupe de travail. + + + L’ordinateur « {0} » a correctement rejoint le groupe de travail « {1} », mais n’a pas pu être renommé en « {2} » avec le message d’erreur suivant : {3}. + + + L’ordinateur « {0} » a été correctement dissocié du domaine « {1} », mais n’a pas pu rejoindre le groupe de travail « {2} » avec le message d’erreur suivant : {3}. + + + Nous n’avons pas pu dissocier l’ordinateur « {0} » du domaine « {1} » avec le message d’erreur suivant : {2}. + + + Impossible d’établir la connexion WMI à l’ordinateur « {0} » avec le message d’erreur suivant : {1}. + + + L’ordinateur « {0} » n’a pas pu joindre le domaine « {1} » depuis son groupe de travail actuel « {2} » et a reçu le message d’erreur suivant : {3}. + + + L’ordinateur « {0} » a été correctement dissocié du domaine « {1} », mais n’a pas pu rejoindre le nouveau domaine de travail « {2} » avec le message d’erreur suivant : {3}. + + + L’ordinateur « {0} » a été correctement joint au nouveau domaine « {1} », mais nous n’avons pas pu le renommer en « {2} » avec le message d’erreur suivant : {3}. + + + L’indicateur « {0} » n’est valide que si l’indicateur « {1} » est spécifié. + + + Impossible de renommer plusieurs ordinateurs. Le paramètre NewName n’est valide que si un seul ordinateur est spécifié. + + + Impossible de trouver le compte d’ordinateur de l’ordinateur local dans le domaine {0}. + + + Impossible de trouver le compte d’ordinateur de l’ordinateur local depuis le contrôleur de domaine {0}. + + + Impossible d’obtenir les informations sur le domaine de l’ordinateur local en raison de l’exception suivante : {0}. + + + Impossible de réinitialiser le mot de passe du canal sécurisé pour le compte d’ordinateur dans le domaine. Échec de l'opération avec l'exception suivante : {0}. + + + Nous n’avons pas pu réinitialiser le mot de passe du canal sécurisé pour l’ordinateur local avec le message d’erreur suivant : {0}. + + + Des droits d’administrateur sont requis pour réinitialiser le mot de passe du canal sécurisé sur l’ordinateur local. L'accès est refusé. + + + Impossible de réinitialiser le mot de passe du canal sécurisé de l’ordinateur local. L’ordinateur local ne fait actuellement pas partie d’un domaine. + + + Le nom NetBIOS de l’ordinateur est limité à 15 octets, soit 15 caractères dans ce cas. Le nom NetBIOS sera raccourci en « {0} », ce qui peut provoquer des conflits lors de la résolution de noms NetBIOS. Voulez-vous vraiment continuer ? + + + Le nom NetBIOS sera tronqué. + + + Le nom du serveur spécifié {0} ne peut pas être résolu. + + + Impossible de créer un nouveau point de restauration système, car un point de restauration a déjà été créé au cours des {0} dernières minutes. Vous pouvez modifier la fréquence de création des points de restauration en créant la valeur DWORD « SystemRestorePointCreationFrequency » sous la clé de Registre « HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore ». La valeur de cette clé de Registre indique l’intervalle de temps nécessaire (en minutes) entre la création de deux points de restauration. La valeur par défaut est 1 440 minutes (24 heures). + + + L’objet WMI Win32_OperatingSystem ne peut pas être récupéré. + + + L’ordinateur {0} est ignoré. Nous ne pouvons pas récupérer sa dernière heure de démarrage LastBootUpTime via le service WMI avec le message d’erreur suivant : {1}. + + + Impossible de vérifier le canal sécurisé de l’ordinateur local. Échec de l'opération avec l'exception suivante : {0}. + + + La tentative de réparation du canal sécurisé entre l’ordinateur local et le domaine {0} a échoué. + + + Le canal sécurisé entre l’ordinateur local et le domaine {0} a été réparé avec succès. + + + Le canal sécurisé entre l’ordinateur local et le domaine {0} est en bon état. + + + Le canal sécurisé entre l’ordinateur local et le domaine {0} est détruit. + + + Impossible de vérifier le mot de passe du canal sécurisé de l’ordinateur local. L’ordinateur local ne fait actuellement pas partie d’un domaine. + + + Impossible d’effectuer l’opération, car les API de restauration système ne sont pas prises en charge sur la plateforme Advanced RISC Machine (ARM). + + + L’ordinateur n’a pas fini son redémarrage dans le délai imparti. + + + Impossible de valider l’intervalle de temps pour la création du point de restauration. Nous n’avons pas pu récupérer le dernier point de restauration avec le message d’erreur suivant : {0}. + + + Le jeu de paramètres AsJob n’est pas pris en charge. + + + Le paramètre « {0} » n’est pas pris en charge pour CoreCLR. + + + La commande native requise « shutdown » n’a pas été trouvée. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/HotFixResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/HotFixResources.fr.resx new file mode 100644 index 00000000000..ef9011638db --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/HotFixResources.fr.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 + + + Nous ne pouvons pas trouver le correctif logiciel demandé sur l’ordinateur « {0} ». Vérifiez l’entrée et réexécutez la commande. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/NavigationResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/NavigationResources.fr.resx new file mode 100644 index 00000000000..6e874892f77 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/NavigationResources.fr.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 + + + Le chemin spécifié est un conteneur qui contient des éléments enfants. Voulez-vous supprimer ce conteneur et ses éléments enfants ? + + + Voulez-vous supprimer l’élément spécifié ? + + + Nous ne pouvons pas copier, car la destination spécifiée existe déjà. Voulez-vous remplacer le contenu existant ? + + + Nouveau lecteur + + + Nom : {0} Fournisseur : {1} Racine : {2} + + + Supprimer le lecteur + + + Nom : {0} Fournisseur : {1} Racine : {2} + + + Nous ne pouvons pas supprimer le lecteur « {0} », car il est en cours d’utilisation. + + + L’élément à {0} a des enfants et le paramètre Recurse n’a pas été spécifié. Si vous continuez, tous les enfants seront supprimés avec l’élément. Voulez-vous vraiment continuer ? + + + Nous ne pouvons pas déplacer l’élément à « {0} », car il est en cours d’utilisation. + + + Un objet ne se trouve pas au chemin d’accès spécifié {0} ou a été filtré par le paramètre -Include ou -Exclude. + + + Définir le contenu + + + Chemin d’accès : {0} + + + Ajouter du contenu + + + Chemin d’accès : {0} + + + Nous ne pouvons pas déplacer l’élément, car l’élément à « {0} » n’existe pas. + + + Nous ne pouvons pas déplacer l’élément, car l’élément à « {0} » est en cours d’utilisation. + + + Nous ne pouvons pas renommer, car l’élément à « {0} » n’existe pas. + + + Nous ne pouvons pas renommer l’élément à « {0} », car il est en cours d’utilisation. + + + Nous ne pouvons pas analyser le chemin d’accès, car aucun qualificateur n’est spécifié pour le chemin « {0} ». + + + Commencer + + + Restauration + + + Valider + + + Transaction à jour + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ProcessCommandHelpResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ProcessCommandHelpResources.fr.resx new file mode 100644 index 00000000000..125ac713408 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ProcessCommandHelpResources.fr.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 + + + Répertorie les processus en cours d’exécution. + + + +-Id id +[int[]] +[pipeline input allowed] +Liste séparée par des virgules des identifiants de processus qui spécifient les processus à obtenir + +-ProcessName name +[string[]] +[pipeline input allowed] +Liste séparée par des virgules des noms de processus qui spécifient les processus à obtenir + +-Exclure le nom +[ArrayList] +Liste séparée par des virgules des noms de processus à exclure de la sortie. + +--- +La commande énumère les processus de l’ordinateur local et renvoie un ou plusieurs objets System.Diagnostics.Process. La commande écrit l’objet de processus dans le pipeline de sortie un à la fois. La commande accepte des paramètres comme ID (identifiant de processus) ou Process Name depuis la ligne de commande. La commande retourne System.Diagnostics.Process correspondant pour les paramètres ID ou ProcessName fournis. + + + L’exclusion ne s’applique qu’au nom du processus. + + + Retourne tous les processus en cours d’exécution. + + + Renvoie tous les processus dont le nom commence par svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ProcessResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ProcessResources.fr.resx new file mode 100644 index 00000000000..8bd5fe1369d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ProcessResources.fr.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} + + + L'utilisateur n'a pas accès aux informations demandées. + + + The specified parameter is not valid. + + + The user does not have sufficient privilege. + + + Unknown failure. + + + Le chemin d’accès spécifié n’existe pas. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/ServiceResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ServiceResources.fr.resx new file mode 100644 index 00000000000..443f73dcdda --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/ServiceResources.fr.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}) + + + Nous ne pouvons pas trouver un service avec le nom de service « {0} ». + + + Nous ne pouvons pas trouver un service avec le nom d’affichage « {1} ». + + + Nouss ne pouvons pas arrêter le service « {1} ({0}) », car il a des services dépendants. Il ne peut être arrêté que si l’indicateur Force est défini. + + + Nouss ne pouvons pas arrêter le service « {1} ({0}) », car il a des services dépendants. + + + Nous ne pouvons pas arrêter le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas démarrer le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas mettre en pause le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas mettre en pause le service « {1} ({0}) », car il ne prend pas en charge l’interruption ou la reprise. + + + Nous ne pouvons pas interrompre le service « {1} ({0}) », car il n’est pas en cours d’exécution. + + + Nous ne pouvons pas reprendre le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas reprendre le service « {1} ({0}) », car il ne prend pas en charge l’interruption ou la reprise. + + + Nous ne pouvons pas reprendre le service « {1} ({0}) », car il n’est pas en cours d’exécution. + + + Nous ne pouvons pas configurer le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas configurer la description du service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas configurer le service « {1} ({0}) » avec le démarrage automatique (démarrage différé) en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas configurer le descripteur de sécurité du service « {0} » en raison de l’erreur suivante : {1} + + + Nous ne pouvons pas créer le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + Le service « {1} ({0}) » a été créé, mais sa description ne peut pas être configurée en raison de l’erreur suivante : {2} + + + Le service « {1} ({0}) » a été créé, mais son type de démarrage « Automatic (Delayed Start) » n’a pas pu être configuré en raison de l’erreur suivante : {2} + + + Nous ne pouvons pas supprimer le service « {1} ({0}) » en raison de l’erreur suivante : {2} + + + « Nous ne pouvons pas accéder aux services dépendants de « {1} ({0}) » + + + Attente de le début du service. « {1} ({0}) »... + + + Attente de l’arrêt du service. « {1} ({0}) »... + + + Attente de la mise en pause du service. « {1} ({0}) »... + + + Attente de la reprise du service. « {1} ({0}) »... + + + Échec du démarrage du service « {1} ({0}) ». + + + Échec d’arrêt du service « {1} ({0}) ». + + + L’interruption du service « {1} ({0}) » a échoué. + + + La reprise du service « {1} ({0}) » a échoué. + + + Échec de l’ouverture de SCManager en raison de l’erreur suivante : {0}. Exécutez PowerShell en tant qu’administrateur(-trice), puis relancez votre commande. + + + Le type de démarrage « {0} » n’est pas pris en charge par {1}. + + + Nous n’avons pas pu récupérer la propriété « {1} » pour le service « {0} » : {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/TestConnectionResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/TestConnectionResources.fr.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/TestConnectionResources.fr.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/TestPathResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/TestPathResources.fr.resx new file mode 100644 index 00000000000..6587c518bcc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/TestPathResources.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/fr/TimeZoneResources.fr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/fr/TimeZoneResources.fr.resx new file mode 100644 index 00000000000..fc8a77291f3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/fr/TimeZoneResources.fr.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 + + + Nous ne pouvons pas définir le fuseau horaire local, car le nom « {0} » correspond à plusieurs entrées. + + + Le nom de fuseau horaire « {0} » est introuvable sur l’ordinateur local. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ClearRecycleBinResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ClearRecycleBinResources.it.resx new file mode 100644 index 00000000000..f1dfe2a454d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ClearRecycleBinResources.it.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 + + + Tutto il contenuto del cestino + + + Tutto il contenuto del cestino per l'unità "{0}" + + + Svuotamento del cestino + + + per l'unità "{0}" + + + per tutte le unità + + + Impossibile trovare l'unità. L'unità con il nome "{0}" non esiste. Eseguire il cmdlet "{1}" per visualizzare le unità fisse disponibili nel sistema. + + + Input non valido. Sono supportati i seguenti formati: "{0}", "{1}" o "{2}". + + + L'unità con il nome "{0}" non è un'unità fissa e non supporta il cestino. Eseguire il cmdlet "{1}" per visualizzare le unità fisse disponibili nel sistema. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ClipboardResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ClipboardResources.it.resx new file mode 100644 index 00000000000..b965d42aaea --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ClipboardResources.it.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impostare la stringa '{0}' negli Appunti. + + + Accodare la stringa '{0}' negli Appunti. + + + Impostare il file '{0}' negli Appunti. + + + Accodare il file '{0}' negli Appunti. + + + Impostare i file {0} negli Appunti. + + + Accodare i file {0} negli Appunti. + + + Non è presente alcun contenuto negli Appunti oppure il formato del contenuto non è compatibile. Impostare l'oggetto di input negli Appunti. + + + Gli Appunti sono stati cancellati. + + + TextFormatType può essere combinato solo con il formato Testo. + + + È possibile combinare Raw solo con il formato Testo o FileDropList. + + + È possibile combinare HTML solo con il formato testo HTML. + + + Questa piattaforma supporta solo il formato Testo. + + + Gli Appunti non sono supportati in questa piattaforma. + + + L'opzione '-AsHtml' non è supportata in questa piattaforma. + + + Il parametro '-TextFormatType' supporta solo 'Text' in questa piattaforma. + + + Il parametro '-Path' non è supportato in questa piattaforma. + + + Il parametro '-LiteralPath' non è supportato in questa piattaforma. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/CmdletizationResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/CmdletizationResources.it.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/CmdletizationResources.it.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ComputerInfoResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ComputerInfoResources.it.resx new file mode 100644 index 00000000000..f1dbd0c1c97 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ComputerInfoResources.it.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 + + + Caricamento delle informazioni sul sistema operativo + + + Caricamento delle informazioni sulla hot-patch + + + Caricamento delle informazioni sul Registro di sistema in coro + + + Caricamento delle informazioni sul BIOS + + + Caricamento delle informazioni sulla scheda madre + + + Caricamento delle informazioni sul computer + + + Caricamento delle informazioni sul processore + + + Caricamento delle informazioni della scheda di rete + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ComputerResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ComputerResources.it.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ComputerResources.it.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/HotFixResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/HotFixResources.it.resx new file mode 100644 index 00000000000..fd527f6f7e0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/HotFixResources.it.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 + + + Non è possibile trovare l'hotfix richiesto nel computer ''{0}''. Verificare l'input ed eseguire di nuovo il comando. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/NavigationResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/NavigationResources.it.resx new file mode 100644 index 00000000000..a375a7224e8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/NavigationResources.it.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 + + + Il percorso specificato è un contenitore che contiene elementi figlio. Eliminare il contenitore e i relativi elementi figlio? + + + Eliminare l'elemento specificato? + + + Non è possibile copiare perché la destinazione specificata esiste già. Sovrascrivere il contenuto esistente? + + + Nuova unità + + + Nome: {0} Provider: {1} Radice: {2} + + + Rimuovi unità + + + Nome: {0} Provider: {1} Radice: {2} + + + Non è possibile rimuovere l'unità '{0}' perché è in uso. + + + L'elemento in {0} contiene elementi figlio e il parametro Recurse non è stato specificato. Se si continua, tutti gli elementi figlio verranno rimossi insieme all'elemento. Continuare? + + + Non è possibile rimuovere l'elemento in '{0}' perché è in uso. + + + Un oggetto nel percorso specificato {0} non esiste o è stato filtrato in base al parametro -Include o -Exclude. + + + Imposta contenuto + + + Percorso: {0} + + + Aggiungi contenuto + + + Percorso: {0} + + + Non è possibile spostare l'elemento perché l'elemento in '{0}' non esiste. + + + Non è possibile spostare l'elemento perché l'elemento in '{0}' è in uso. + + + Non è possibile rinominare perché l'elemento in '{0}' non esiste. + + + Non è possibile rinominare l'elemento in '{0}' perché è in uso. + + + Non è possibile analizzare il percorso perché il qualificatore del percorso '{0}' non è specificato. + + + Inizia + + + Ripristino dello stato precedente + + + Commit + + + Transazione corrente + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ProcessCommandHelpResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ProcessCommandHelpResources.it.resx new file mode 100644 index 00000000000..fce17ad4b7f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ProcessCommandHelpResources.it.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 + + + Elenca i processi attualmente in esecuzione. + + + +-Id id +[int[]] +[input pipeline consentito] +Elenco delimitato da virgole di identificatori di processo che specifica i processi da ottenere + +-nome ProcessName +[string[]] +[input pipeline consentito] +Elenco delimitato da virgole di nomi di processo che specifica i processi da ottenere + +-Escludi nome +[ArrayList] +Elenco delimitato da virgole di nomi di processo da escludere dall'output. + +--- +Il comando enumera i processi dal computer locale e restituisce uno o più oggetti System.Diagnostics.Process. Il comando scrive l'oggetto processo nella pipeline di output uno alla volta. Il comando accetta parametri come ID (identificatore di processo) o nome processo dalla riga di comando. Il comando restituisce il corrispondente System.Diagnostics.Process per i parametri ID o ProcessName forniti. + + + L'esclusione funziona solo per il nome del processo. + + + Restituisce tutti i processi in esecuzione. + + + Restituisce tutti i processi con nomi che iniziano con svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ProcessResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ProcessResources.it.resx new file mode 100644 index 00000000000..8e4cfceaca2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ProcessResources.it.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 + + + Non è possibile trovare un processo denominato "{0}". Verificare il nome del processo e chiamare di nuovo il cmdlet. + + + Non è possibile trovare un processo denominato "{0}". Provare a eseguire con -Id per cercare in base all'ID dei processi. + + + Non è possibile eseguire questo comando perché il debugger non può essere collegato al processo "{0} ({1})". Specificare un altro processo ed eseguire il comando. + + + Non è possibile trovare un processo con l'identificatore del processo {1}. + + + Non è possibile arrestare il processo "{0} ({1})" a causa dell'errore seguente: {2} + + + {0} ({1}) + + + {0} {1} + + + Non è possibile enumerare i moduli del processo "{0}". + + + Non è possibile enumerare le informazioni sulla versione del file del processo "{0}". + + + Non è possibile enumerare i moduli e le informazioni sulla versione del file del processo "{0}". + + + Eseguire l'operazione Stop-Process sull'elemento seguente: {0}({1})? + + + Il percorso specificato non è un'applicazione win32 valida. Riprovare con UseShellExecute. + + + Questo comando ha interrotto l'esecuzione di "{0} ({1})" a causa dell'errore seguente: {2}. + + + Questo comando non può essere eseguito perché non è possibile usare i parametri di reindirizzamento con il parametro UseShellExecute + + + Eccezione durante il recupero di "Modules" o "FileVersion": "Questa funzionalità non è supportata per i computer remoti". + + + Questo comando non può collegare il debugger al processo a causa di {0} perché non è disponibile alcun debugger predefinito. + + + Questo comando ha interrotto l'esecuzione perché non può attendere il processo 'System Idle'. Specificare un altro processo ed eseguire di nuovo il comando. + + + Questo comando ha interrotto l'esecuzione perché non può attendere se stesso. Specificare un altro processo ed eseguire di nuovo il comando. + + + Questo comando ha interrotto l'esecuzione perché il processo "{0} ({1})" non è arrestato nel timeout specificato. + + + Non è possibile eseguire questo comando a causa dell'errore: {0} + + + Non è possibile eseguire questo comando perché l'input "{0}" non è un'applicazione valida. Specificare un'applicazione valida ed eseguire di nuovo il comando. + + + Non è possibile eseguire questo comando perché il parametro "{0}" ha un valore non valido o non può essere usato con questo comando. Specificare un input valido ed eseguire di nuovo il comando. + + + Non è possibile eseguire questo comando perché "{0}" e "{1}" sono uguali. Assegnare input diversi ed eseguire di nuovo il comando. + + + Non è possibile eseguire completamente questo comando perché il sistema non è in grado di trovare tutte le informazioni necessarie. + + + Non è possibile recuperare il nuovo handle di processo: "{0}". È possibile che alcune proprietà e metodi dell'oggetto Process restituito non funzionino correttamente. + + + Questo comando non può essere eseguito a causa dell'errore 1783. Una possibile causa dell'errore può essere l'uso di un utente inesistente "{0}". Specificare un utente valido ed eseguire di nuovo il comando. + + + Errore durante l'aggiunta di '{0}' alla rete: {1} + + + Errore durante la rimozione di '{0}' dalla rete: {1} + + + Errore durante la ridenominazione di '{0}': {1} + + + Non è possibile specificare "{0}" e "{1}" contemporaneamente. + + + Non è possibile eseguire il debug del processo "{0} ({1})" a causa dell'errore seguente: {2} + + + L'utente non ha accesso alle informazioni richieste. + + + Il parametro specificato non è valido. + + + L'utente non dispone di privilegi sufficienti. + + + Errore sconosciuto. + + + Il percorso specificato non esiste. + + + Il parametro '{0}' non è supportato per il cmdlet '{1}' in questa edizione di Windows. + + + Il parametro '{0}' non è supportato per il cmdlet '{1}' in questa edizione di PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/ServiceResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/ServiceResources.it.resx new file mode 100644 index 00000000000..07b15d79c99 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/ServiceResources.it.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}) + + + Non è possibile trovare un servizio con nome del servizio '{0}'. + + + Non è possibile trovare un servizio con nome visualizzato '{1}'. + + + Non è possibile arrestare il servizio '{1} ({0})' perché ha servizi dipendenti. È possibile arrestarlo solo se è impostato il flag Force. + + + Non è possibile arrestare il servizio '{1} ({0})' perché ha servizi dipendenti. + + + Non è possibile arrestare il servizio '{1} ({0})' a causa del seguente errore: {2} + + + Non è possibile avviare il servizio '{1} ({0})' a causa del seguente errore: {2} + + + Non è possibile sospendere il servizio '{1} ({0})' a causa del seguente errore: {2} + + + Non è possibile sospendere il servizio '{1} ({0})' perché il servizio non supporta la sospensione o la ripresa. + + + Il servizio '{1} ({0})' non può essere sospeso perché non è attualmente in esecuzione. + + + Non è possibile riprendere il servizio '{1} ({0})' a causa del seguente errore: {2} + + + Non è possibile riprendere il servizio '{1} ({0})' perché il servizio non supporta la sospensione o la ripresa. + + + Non è possibile riprendere il servizio '{1} ({0})' perché non è attualmente in esecuzione. + + + Non è possibile configurare il servizio '{1} ({0})' a causa del seguente errore: {2} + + + Non è possibile configurare la descrizione del servizio '{1} ({0})' a causa del seguente errore: {2} + + + Non è possibile configurare il servizio '{1} ({0})' come automatico (avvio ritardato) a causa del seguente errore: {2} + + + Non è possibile configurare il descrittore di sicurezza del servizio '{0}' a causa del seguente errore: {1} + + + Non è possibile creare il servizio '{1} ({0})' a causa del seguente errore: {2} + + + Il servizio '{1} ({0})' è stato creato, ma non è possibile configurarne la descrizione a causa del seguente errore: {2} + + + Il servizio '{1} ({0})' è stato creato, ma non è stato possibile configurare il tipo di avvio 'Automatico (avvio ritardato)' a causa del seguente errore: {2} + + + Non è possibile rimuovere il servizio '{1} ({0})' a causa del seguente errore: {2} + + + 'Non è possibile accedere ai servizi dipendenti di '{1} ({0})' + + + In attesa dell'avvio del servizio '{1} ({0})'... + + + Attesa per l'interruzione del servizio '{1} ({0})'... + + + Attesa per l'interruzione del servizio '{1} ({0})... + + + Attesa della ripresa del servizio '{1} ({0})'... + + + Non è stato possibile avviare il servizio '{1} ({0})'. + + + L'interruzione del servizio '{1} ({0})' non è riuscita. + + + Sospensione del servizio '{1} ({0})' non riuscita. + + + Ripresa del servizio '{1} ({0})' non riuscita. + + + Non è possibile aprire SCManager a causa del seguente errore: {0}. Eseguire PowerShell come amministratore e riprovare il comando. + + + Il tipo di avvio '{0}' non è supportato da {1}. + + + Non è possibile recuperare la proprietà '{1}' per il servizio '{0}': {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/TestConnectionResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/TestConnectionResources.it.resx new file mode 100644 index 00000000000..8ef0a0063d3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/TestConnectionResources.it.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 + + + Il test della connessione al computer '{0}' non è riuscito: {1} + + + Non è possibile risolvere il nome della destinazione. + + + Indirizzo IPv4/IPv6 di destinazione assente. + + + Non è possibile completare il traceroute alla destinazione '{0}': il numero di hop necessari per raggiungere l'host supera il valore MaxHops ({1}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/TestPathResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/TestPathResources.it.resx new file mode 100644 index 00000000000..79f9e01c3e8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/TestPathResources.it.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 + + + L'argomento Path specificato era null o una raccolta vuota. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/it/TimeZoneResources.it.resx b/src/Microsoft.PowerShell.Commands.Management/resources/it/TimeZoneResources.it.resx new file mode 100644 index 00000000000..a4fbc3eb2ea --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/it/TimeZoneResources.it.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 + + + Non è possibile impostare il fuso orario locale perché il nome "{0}" corrisponde a più voci. + + + Il nome del fuso orario "{0}" non è stato trovato nel computer locale. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ClearRecycleBinResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ClearRecycleBinResources.ja.resx new file mode 100644 index 00000000000..d0f2e835aa5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ClearRecycleBinResources.ja.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 + + + ごみ箱のすべての内容 + + + '{0}' ドライブのごみ箱のすべての内容 + + + ごみ箱を空にしています + + + '{0}' ドライブ + + + すべてのドライブ + + + ドライブが見つかりません。'{0}' という名前のドライブは存在しません。'{1}' コマンドレットを実行して、システムで使用可能な固定ドライブを確認してください。 + + + 入力が無効です。次の形式がサポートされています: '{0}'、'{1}' または '{2}'。 + + + '{0}' という名前のドライブは固定ドライブではなく、ごみ箱をサポートしていません。'{1}' コマンドレットを実行して、システムで使用可能な固定ドライブを確認してください。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ClipboardResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ClipboardResources.ja.resx new file mode 100644 index 00000000000..6eccdb7dd0d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ClipboardResources.ja.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 文字列 '{0}' をクリップボードに設定します。 + + + 文字列 '{0}' をクリップボードにアペンドします。 + + + ファイル '{0}' をクリップボードに設定します。 + + + ファイル '{0}' をクリップボードに追加します。 + + + {0} ファイルをクリップボードに設定します。 + + + {0} ファイルをクリップボードにアペンドします。 + + + クリップボードにコンテンツがないか、コンテンツ形式に互換性がありません。入力オブジェクトをクリップボードに設定します。 + + + クリップボードがクリアされました。 + + + TextFormatType はテキスト形式とのみ組み合わせることができます。 + + + Raw は Text 形式または FileDropList 形式でのみ組み合わせることができます。 + + + HTML は HTML テキスト形式とのみ組み合わせることができます。 + + + このプラットフォームでは、テキスト形式のみがサポートされています。 + + + クリップボードは、このプラットフォームではサポートされていません。 + + + '-AsHtml' スイッチは、このプラットフォームではサポートされていません。 + + + '-TextFormatType' パラメーターは、このプラットフォームで 'Text' のみをサポートします。 + + + '-Path' パラメーターは、このプラットフォームではサポートされていません。 + + + '-LiteralPath' パラメーターは、このプラットフォームではサポートされていません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/CmdletizationResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/CmdletizationResources.ja.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/CmdletizationResources.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ComputerInfoResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ComputerInfoResources.ja.resx new file mode 100644 index 00000000000..d665c09ae3d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ComputerInfoResources.ja.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 + + + オペレーティング システム情報を読み込んでいます + + + ホットパッチ情報を読み込んでいます + + + レジストリ情報を読み込んでいます + + + BIOS 情報を読み込んでいます + + + マザーボード情報を読み込んでいます + + + コンピューター情報を読み込んでいます + + + プロセッサ情報を読み込んでいます + + + ネットワーク アダプターの情報を読み込んでいます + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ComputerResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ComputerResources.ja.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ComputerResources.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/HotFixResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/HotFixResources.ja.resx new file mode 100644 index 00000000000..d6bd6a75bef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/HotFixResources.ja.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 + + + '{0}' コンピューターに要求された修正プログラムが見つかりません。入力を確認し、コマンドをもう一度実行してください。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/NavigationResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/NavigationResources.ja.resx new file mode 100644 index 00000000000..304bda6d9e0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/NavigationResources.ja.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 + + + 指定されたパスは、子アイテムを持つコンテナーです。このコンテナーとその子アイテムを削除しますか? + + + 指定したアイテムを削除しますか? + + + 指定されたコピー先が既に存在するため、コピーできません。既存の内容を上書きしますか? + + + 新しいドライブ + + + 名前: {0} プロバイダー: {1} ルート: {2} + + + ドライブの削除 + + + 名前: {0} プロバイダー: {1} ルート: {2} + + + ドライブ '{0}' は使用中のため、削除できません。 + + + {0} のアイテムに子があり、Recurse パラメーターが指定されていません。続行すると、すべての子がアイテムと共に削除されます。続行しますか? + + + '{0}' にあるアイテムは使用中のため、削除できません。 + + + 指定されたパス {0} にあるオブジェクトが存在しないか、-Include パラメーターまたは -Exclude パラメーターによってフィルター処理されています。 + + + Set-Content + + + パス: {0} + + + コンテンツの追加 + + + パス: {0} + + + '{0}' のアイテムが存在しないため、アイテムを移動できません。 + + + '{0}' のアイテムが使用中のため、アイテムを移動できません。 + + + '{0}' の項目が存在しないため、名前を変更できません。 + + + '{0}' のアイテムは使用中のため、名前を変更できません。 + + + パス '{0}' に修飾子が指定されていないため、パスを解析できません。 + + + 開始 + + + ロールバック + + + コミット + + + 現在のトランザクション + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ProcessCommandHelpResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ProcessCommandHelpResources.ja.resx new file mode 100644 index 00000000000..6efea01c88c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ProcessCommandHelpResources.ja.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 + + + 現在実行中のプロセスを一覧表示します。 + + + +-Id id +[int[]] +[パイプライン入力が許可されました] +取得するプロセスを指定するプロセス識別子のコンマ区切りの一覧 + +-ProcessName 名 +[string[]] +[パイプライン入力が許可されました] +取得するプロセスを指定するプロセス名のコンマ区切りの一覧 + +-除外名 +[ArrayList] +出力から除外するプロセス名のコンマ区切りリスト。 + +--- +このコマンドは、ローカル コンピューターからプロセスを列挙し、System.Diagnostics.Process オブジェクトを出力します。このコマンドは、プロセス オブジェクトを出力パイプラインに一度に 1 つずつ書き込みます。このコマンドは、コマンド ラインから ID (プロセス識別子) またはプロセス名などのパラメーターを受け取ります。このコマンドは、指定された ID または ProcessName パラメーターに対応する system.diagnostics.process を返します。 + + + 除外は、プロセス名に対してのみ機能します。 + + + 実行中のすべてのプロセスを返します。 + + + svc で始まる名前を持つすべてのプロセスを返します。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ProcessResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ProcessResources.ja.resx new file mode 100644 index 00000000000..adf19a3eecb --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ProcessResources.ja.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 + + + "{0}" という名前のプロセスが見つかりません。プロセス名を確認し、コマンドレットをもう一度呼び出してください。 + + + "{0}" という名前のプロセスが見つかりません。プロセスの ID で検索するには、-Id を指定して実行してみてください。 + + + デバッガーをプロセス "{0} ({1})" にアタッチできないため、このコマンドを実行できません。別のプロセスを指定して、コマンドを実行してください。 + + + プロセス識別子が {1} のプロセスが見つかりません。 + + + 次のエラーにより、プロセス "{0} ({1})" を停止できません: {2} + + + {0} ({1}) + + + {0} {1} + + + "{0}" プロセスのモジュールを列挙できません。 + + + "{0}" プロセスのファイル バージョン情報を列挙できません。 + + + "{0}" プロセスのモジュールとファイル バージョン情報を列挙できません。 + + + 次の項目に対して Stop-Process 操作を実行しますか: {0}({1})? + + + 指定されたパスは、有効な win32 アプリケーションではありません。UseShellExecute を使用して、もう一度お試しください。 + + + このコマンドは、次のエラーにより、"{0} ({1})" の操作を停止しました: {2}。 + + + Redirection パラメーターは UseShellExecute パラメーターと共に使用できないため、このコマンドを実行できません + + + "Modules" または "FileVersion" の取得で例外が発生しました: "この機能はリモート コンピューターではサポートされていません。"。 + + + 既定のデバッガーがないため、{0} により、このコマンドはデバッガーをプロセスにアタッチできません。 + + + このコマンドは、'システム アイドル' 状態のプロセスで待機できないため、操作を停止しました。別のプロセスを指定して、コマンドをもう一度実行してください。 + + + このコマンドは、それ自体を待機できないため、操作を停止しました。別のプロセスを指定して、コマンドをもう一度実行してください。 + + + このコマンドは、指定されたタイムアウト時間内にプロセス "{0} ({1})" が停止しなかったため、操作を停止しました。 + + + 次のエラーにより、このコマンドを実行できません: {0} + + + 入力 "{0}" が有効なアプリケーションではないため、このコマンドを実行できません。 有効なアプリケーションを指定して、コマンドをもう一度実行してください。 + + + パラメーター "{0}" の値が無効であるか、このコマンドでは使用できないため、このコマンドを実行できません。有効な入力を指定して、コマンドをもう一度実行してください。 + + + "{0}" と "{1}" が同じであるため、このコマンドを実行できません。異なる入力を指定して、コマンドをもう一度実行してください。 + + + システムが必要なすべての情報を見つけられないため、このコマンドを完全に実行できません。 + + + 新しいプロセス ハンドルを取得できませんでした: "{0}"。出力された Process オブジェクトには、正しく動作しないプロパティやメソッドが含まれている可能性があります。 + + + エラー 1783 のため、このコマンドを実行できません。このエラーの原因として、存在しないユーザー "{0}" の使用が考えられます。有効なユーザーを指定して、コマンドをもう一度実行してください。 + + + ネットワークへの '{0}' の追加でエラーが発生しました: {1} + + + ネットワークからの '{0}' の削除でエラーが発生しました: {1} + + + '{0}' の名前の変更でエラーが発生しました: {1} + + + パラメーター "{0}" と "{1}" を同時に指定することはできません。 + + + 次のエラーにより、プロセス "{0} ({1})" をデバッグできません: {2} + + + ユーザーには、要求された情報へのアクセス権がありません。 + + + 指定されたパラメーターは無効です。 + + + ユーザーには十分な権限がありません。 + + + 不明なエラーです。 + + + 指定されたパスが存在しない。 + + + パラメーター '{0}' は、このエディションの Windows のコマンドレット '{1}' ではサポートされていません。 + + + パラメーター '{0}' は、このエディションの PowerShell のコマンドレット '{1}' ではサポートされていません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/ServiceResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ServiceResources.ja.resx new file mode 100644 index 00000000000..a710545577f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/ServiceResources.ja.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}) + + + サービス名 '{0}' のサービスは見つかりません。 + + + 表示名 '{1}' のサービスは見つかりません。 + + + サービス '{1} ({0})' には依存サービスがあるため、停止できません。Force フラグが設定されている場合にのみ停止できます。 + + + サービス '{1} ({0})' には依存サービスがあるため、停止できません。 + + + 次のエラーのため、サービス '{1} ({0})' を停止できません: {2} + + + 次のエラーのため、サービス '{1} ({0})' を開始できません: {2} + + + 次のエラーのため、サービス '{1} ({0})' を中断できません: {2} + + + サービス '{1} ({0})' は中断または再開がサポートされていないため、中断できません。 + + + サービス '{1} ({0})' は現在実行されていないため、中断できません。 + + + 次のエラーのため、サービス '{1} ({0})' を再開できません: {2} + + + サービス '{1} ({0})' は中断または再開がサポートされていないため、再開できません。 + + + サービス '{1} ({0})' は現在実行されていないため、再開できません。 + + + 次のエラーのため、サービス '{1} ({0})' を構成できません: {2} + + + 次のエラーのため、サービス '{1} ({0})' の説明を構成できません: {2} + + + 次のエラーのため、サービス '{1} ({0})' を自動 (遅延開始) に構成できません: {2} + + + 次のエラーのため、サービス '{0}' のセキュリティ記述子を構成できません: {1} + + + 次のエラーのため、サービス '{1} ({0})' を作成できません: {2} + + + サービス '{1} ({0})' が作成されましたが、次のエラーのため説明を構成できません: {2} + + + サービス '{1} ({0})' が作成されましたが、次のエラーが発生したため、その StartupType 'Automatic (Delayed Start)' を構成できませんでした: {2} + + + 次のエラーのため、サービス '{1} ({0})' を削除できません: {2} + + + サービス '{1} ({0})' の依存サービスにアクセスできません + + + サービス '{1} ({0})' の開始を待機しています... + + + サービス '{1} ({0})' の停止を待機しています... + + + サービス '{1} ({0})' の中断を待機しています... + + + サービス '{1} ({0})' の再開を待機しています... + + + サービス '{1} ({0})' を開始できませんでした。 + + + サービス '{1} ({0})' の停止に失敗しました。 + + + サービス '{1} ({0})' の中断に失敗しました。 + + + サービス '{1} ({0})' を再開できませんでした。 + + + 次のエラーが発生したため、SCManager を開けませんでした: {0}。PowerShell を管理者として実行し、コマンドをもう一度実行してください。 + + + スタートアップの種類 '{0}' は {1} ではサポートされていません。 + + + サービス '{0}' のプロパティ '{1}' を取得できませんでした: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/TestConnectionResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/TestConnectionResources.ja.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/TestConnectionResources.ja.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/TestPathResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/TestPathResources.ja.resx new file mode 100644 index 00000000000..c5abbb45288 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/TestPathResources.ja.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 + + + 指定された Path 引数が null 値または空のコレクションでした。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ja/TimeZoneResources.ja.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ja/TimeZoneResources.ja.resx new file mode 100644 index 00000000000..6e82e493b96 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ja/TimeZoneResources.ja.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 + + + 名前 '{0}' は複数のエントリに解決されるため、ローカル タイム ゾーンを設定できません。 + + + ローカル コンピューターにタイム ゾーン名 '{0}' が見つかりませんでした。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ClearRecycleBinResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ClearRecycleBinResources.ko.resx new file mode 100644 index 00000000000..009e32045e8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ClearRecycleBinResources.ko.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 + + + 휴지통에 있는 모든 항목 + + + '{0}' 드라이브의 휴지통에 있는 모든 내용 + + + 휴지통 지우는 중 + + + '{0}' 드라이브용 + + + 모든 드라이브에 대해 + + + 드라이브를 찾을 수 없습니다. 이름이 '{0}'인 드라이브가 없습니다. '{1}' cmdlet을 실행하여 시스템에서 사용 가능한 고정 드라이브를 확인하세요. + + + 유효하지 않은 입력입니다. 지원되는 형식은 '{0}', '{1}' 또는 '{2}'입니다. + + + '{0}' 드라이브는 Fixed 드라이브가 아니므로 휴지통을 지원하지 않습니다. '{1}' cmdlet을 실행하여 시스템에서 사용 가능한 고정 드라이브를 확인하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ClipboardResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ClipboardResources.ko.resx new file mode 100644 index 00000000000..569f0b1ca7d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ClipboardResources.ko.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{0}' 문자열을 클립보드로 설정합니다. + + + '{0}' 문자열을 클립보드에 추가합니다. + + + '{0}' 파일을 클립보드로 설정합니다. + + + '{0}' 파일을 클립보드에 추가합니다. + + + {0} 파일을 클립보드로 설정합니다. + + + {0} 파일을 클립보드에 추가합니다. + + + 클립보드에 콘텐츠가 없거나 콘텐츠 형식이 호환되지 않습니다. 입력 개체를 클립보드에 설정하세요. + + + 클립보드를 지웠습니다. + + + TextFormatType은 텍스트 형식과만 함께 사용할 수 있습니다. + + + Raw는 텍스트 또는 FileDropList 형식과만 함께 사용할 수 있습니다. + + + HTML은 HTML 텍스트 형식과만 함께 사용할 수 있습니다. + + + 이 플랫폼에서는 텍스트 형식만 지원됩니다. + + + 클립보드는 이 플랫폼에서 지원되지 않습니다. + + + 이 플랫폼에서는 '-AsHtml' 스위치를 지원하지 않습니다. + + + 이 플랫폼에서는 '-TextFormatType' 매개 변수가 'Text'만 지원합니다. + + + '-Path' 매개 변수는 이 플랫폼에서 지원되지 않습니다. + + + '-LiteralPath' 매개 변수는 이 플랫폼에서 지원되지 않습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/CmdletizationResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/CmdletizationResources.ko.resx new file mode 100644 index 00000000000..a929461bb75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/CmdletizationResources.ko.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 + + + {1} CIM 서버에서 {0} 클래스를 찾을 수 없습니다. Cmdlet Definition XML에서 ClassName xml 특성의 값을 확인하고 다시 시도하세요. 유효한 클래스 이름 예: 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". + + + + {0}CIM 개체의 CIM 메서드 {1} + {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 + + + {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 + + + 다음 작업을 실행하는 중입니다. {0} + {0} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + CIM cmdlet은 {0} 매개 변수와 AsJob 매개 변수를 함께 지원하지 않습니다. 이 매개 변수들 중 하나를 제거하고 다시 시도하세요. + {StrContains="AsJob"} +{0} is a placeholder for 'WhatIf' or 'Confirm' cmdlet parameters + + + {1} CIM 서버의 {0} 클래스 인스턴스에 대한 CIM 쿼리: {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". + + + CIM 메서드가 다음 오류 코드를 반환했습니다. {0} + {0} is a placeholder for an error code returned from a CIM method. Example: 123 + + + {1} CIM 서버의 {0} 클래스에서 노출하는 {2} CIM 메서드 + {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 내장 형식 + + + WQL 리터럴 + + + {0} CIM 개체의 {1} 메서드에 대한 {2} 출력 매개 변수를 찾을 수 없습니다. Cmdlet Definition XML에서 ParameterName 특성의 값을 확인하고 다시 시도하세요. + {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. + + + + {0}을(를) 통해 일치하는 {1} 개체를 찾을 수 없습니다. 쿼리 매개 변수를 확인하고 다시 시도하세요. + + + 속성 '{0}'이(가) '{1}'와(과) 같은 {2} 개체를 찾을 수 없습니다. 속성 값을 확인하고 다시 시도하세요. + + + Cmdlet Definition XML에 선언된 형식과 연결된 CIM 형식({2})이 {0} 속성({1})의 형식과 일치하지 않습니다. + + + {1} CIM 서버의 {0} 클래스에 대한 연결된 인스턴스를 열거하는 CIM 쿼리 + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + 다음 인스턴스와 연결된{1} CIM 서버의 {0} 클래스 인스턴스를 열거하는 CIM 쿼리입니다. {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]". + + + {1} 서버가 현재 사용 중이므로 {0} 명령을 완료할 수 없습니다. 명령은 {2:f2}초 후에 자동으로 다시 시작됩니다. + {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 + + + CIM 서버에 연결할 수 없습니다. {0} + {0} is a placeholder for a more detailed error message. + + + cmdlet은 디버그 메시지에 대한 Inquire 동작을 완전히 지원하지 않습니다. 프롬프트 중에도 cmdlet 작업은 계속됩니다. -Debug 스위치 또는 $DebugPreference 변수를 통해 다른 동작 기본 설정을 선택하고 다시 시도하세요. + {StrContains="Debug"} {StrContains="DebugPreference"} {StrContains="Inquire"} + + + cmdlet은 경고에 대한 Inquire 동작을 완전히 지원하지 않습니다. 프롬프트 중에도 cmdlet 작업은 계속됩니다. -WarningAction 매개 변수 또는 $WarningPreference 변수를 통해 다른 동작 기본 설정을 선택하고 다시 시도하세요. + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Inquire"} + + + cmdlet은 경고에 대한 Stop 동작을 완전히 지원하지 않습니다. cmdlet 작업은 지연 후 중지됩니다. -WarningAction 매개 변수 또는 $WarningPreference 변수를 통해 다른 동작 기본 설정을 선택하고 다시 시도하세요. + {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}: CimSession이 CIM 서버에 연결할 때 DCOM 프로토콜을 사용합니다. 이 프로토콜은 {1} 스위치를 지원하지 않습니다. + {0} is a placeholder for a name of a computer +{1} is a placeholder for 'Confirm' or 'WhatIf' + + + 속성 '{0}'이(가) '{1}'와(과) 일치하는 {2} 개체를 찾을 수 없습니다. 속성 값을 확인하고 다시 시도하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ComputerInfoResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ComputerInfoResources.ko.resx new file mode 100644 index 00000000000..3d9e341728e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ComputerInfoResources.ko.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 + + + 운영 체제 정보를 로드하는 중 + + + 핫패치 정보를 로드하는 중 + + + 레지스트리 정보를 로드하는 중 + + + BIOS 정보를 로드하는 중 + + + 마더보드 정보를 로드하는 중 + + + 컴퓨터 정보를 로드하는 중 + + + 프로세서 정보를 로드하는 중 + + + 네트워크 어댑터 정보를 로드하는 중 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ComputerResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ComputerResources.ko.resx new file mode 100644 index 00000000000..3869d32efda --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ComputerResources.ko.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 + + + 이 기능은 이 운영 체제에서 지원되지 않습니다. + + + {0} 드라이브를 사용하도록 설정할 수 없습니다. + + + 제공된 드라이브가 올바르지 않으므로 명령을 사용하여 지정한 컴퓨터의 복원 컴퓨터 인프라를 켤 수 없습니다. Drive 매개 변수에 올바른 드라이브를 입력한 후 다시 시도하세요. + + + 드라이브 목록에 시스템 드라이브를 포함합니다. + + + 제공된 드라이브가 올바르지 않으므로 명령을 사용하여 복원 컴퓨터 인프라를 끌 수 없습니다. Drive 매개 변수에 올바른 드라이브를 입력한 후 다시 시도하세요. + + + 명령을 사용하여 {0} 드라이브에서 시스템 복원을 사용하지 않도록 설정할 수 없습니다. 이 작업을 수행할 수 있는 권한이 없을 수 있습니다. + + + SystemRestore 서비스가 사용하지 않도록 설정되어 있습니다. + + + 시스템 복원 인프라에서 복원 지점을 만들 수 없습니다. + + + 컴퓨터를 복원하려는 마지막 시도가 실패했습니다. + + + 컴퓨터가 지정된 복원 지점으로 복원되었습니다. + + + 컴퓨터를 복원하려는 마지막 시도가 중단되었습니다. + + + 명령에서 "{0}" 복원 지점을 찾을 수 없습니다. "{0}" 시퀀스 번호를 확인한 다음 명령을 다시 시도하세요. + + + {0}({1}) + + + 다음 오류 메시지로 인해 컴퓨터 {0}을(를) 다시 시작하지 못했습니다. {1}. + + + 다음 오류로 인해 대상 컴퓨터('{1}')에서 이 명령을 실행할 수 없습니다. {0}.{2} + + + 다음 오류 메시지로 인해 컴퓨터 {0}을(를) 중지하지 못했습니다. {1}. + + + "{0}"이(가) 올바른 복원 지점으로 설정되지 않았으므로 명령을 사용하여 컴퓨터를 복원할 수 없습니다. RestorePoint 매개 변수에 유효한 복원 지점을 입력한 후 다시 시도하세요. + + + 변경 내용은 {1} 컴퓨터를 다시 시작한 후에 적용됩니다. + + + 도메인에서 나간 후 이 컴퓨터에 로그온하려면 로컬 관리자 계정의 암호를 알아야 합니다. 계속하시겠습니까? + + + 다음 컴퓨터 이름이 잘못되었습니다. {0}. 컴퓨터 이름이 255자를 초과하지 않고, 마침표가 두 개 이상 연속으로 포함되지 않으며, 마침표로 시작하지 않고, 숫자만으로 구성되지 않으며, 다음 문자 중 어느 것도 포함하지 않도록 합니다. +{{|}}~[\]^:;<=>?@!"#$%^`()+/, + + + 컴퓨터 이름 '{0}'의 도메인이 잘못되었습니다. 도메인이 있고 이름이 올바른 도메인 이름인지 확인합니다. + + + NewComputerName 매개 변수에 지정한 값이 ComputerName 매개 변수의 값과 같습니다. NewComputerName 매개 변수에 다른 값을 제공하세요. + + + "'{0}' 및 '{1}' 사이의 보안 채널의 암호가 다시 설정되었습니다." + + + 다음 오류로 인해 이 명령을 실행할 수 없습니다. 서비스가 사용하지 않도록 설정되어 있거나, 해당 서비스에 연결된 사용하도록 설정된 장치가 없기 때문에 서비스를 시작할 수 없습니다. + + + 시스템 복원 지점을 만드는 중... + + + 시스템 복원 지점을 만드는 중... {0}% 완료. + + + 완료되었습니다. + + + 아래 옵션을 시도하고 명령을 다시 실행하세요. +1. 대상 컴퓨터('{0}')가 실행 중인지 확인합니다. +2. 대상 컴퓨터('{0}')의 전체 컴퓨터 이름을 지정합니다. + + + {0} 컴퓨터를 다시 시작하지 못했습니다. 호출 프로세스에 액세스 권한 {1}을(를) 사용하도록 설정할 수 없습니다. + + + {0}을(를) 사용하도록 설정하고 컴퓨터를 다시 시작합니다. + + + 로컬 종료 액세스 권한 + + + 원격 종료 액세스 권한 + + + 로컬 컴퓨터가 다시 시작될 때까지 기다릴 수 없습니다. Wait 매개 변수를 지정하면 로컬 컴퓨터가 무시됩니다. + + + 매개 변수 Timeout, For 및 Delay는 Wait 매개 변수가 지정된 경우에만 유효합니다. + + + 컴퓨터를 다시 시작하는 중... + + + {0} 컴퓨터를 다시 시작하는 중 + + + 완료됨: {0}/{1}. + + + 컴퓨터가 다시 시작되었는지 확인하는 중... + + + PowerShell 연결을 기다리는 중... + + + 다시 시작이 시작되기를 기다리는 중... + + + WinRM 연결을 기다리는 중... + + + WMI 연결을 기다리는 중... + + + 다시 시작이 완료되었습니다. + + + 지금은 결합된 서비스 유형이 지원되지 않습니다. + + + 다음 예외로 인해 컴퓨터 이름 {0}을(를) 확인할 수 없습니다. {1}. + + + 새 이름의 수가 대상 컴퓨터의 수와 같지 않습니다. + + + 새 이름이 잘못되었으므로 새 이름이 '{1}'인 '{0}' 컴퓨터를 건너뜁니다. 입력한 새 컴퓨터 이름의 형식이 잘못되었습니다. 표준 이름에는 문자(a-z, A-Z), 숫자(0-9) 및 하이픈(-)을 포함할 수 있지만 공백이나 마침표(.)는 포함할 수 없습니다. 이름은 전체가 숫자만으로 구성될 수는 없으며 63자를 초과할 수 없습니다. + + + 새 이름이 현재 이름과 동일하기 때문에 새 이름이 '{1}'인 '{0}' 컴퓨터를 건너뜁니다. + + + '{0}' 컴퓨터가 도메인에 없으므로 제거할 수 없습니다. + + + 다음 오류 메시지로 인해 '{0}' 컴퓨터를 작업 그룹 '{1}'에 조인하지 못했습니다. {2} + + + 로컬 네트워크가 다운되어 도메인에서 컴퓨터를 제거할 수 없습니다. + + + 다음 예외로 인해 '{0}' 컴퓨터의 이름을 '{1}'(으)로 바꾸지 못했습니다. {2}. + + + 도메인 '{0}'에 조인 + + + 작업 그룹 '{0}'에 조인 + + + '{0}' 컴퓨터가 이미 도메인 '{1}'에 있으므로 해당 도메인에 추가할 수 없습니다. + + + 컴퓨터 '{0}'이(가) 이미 작업 그룹 '{1}'에 있으므로 해당 작업 그룹에 추가할 수 없습니다. + + + '{0}' 컴퓨터가 작업 그룹 '{1}'에 조인했지만 다음 오류 메시지로 인해 '{2}'(으)로 이름을 바꿀 수 없습니다. {3}. + + + '{0}' 컴퓨터가 도메인 '{1}'에서 조인이 해제되었지만 다음 오류 메시지로 인해 작업 그룹 '{2}'에 조인하지 못했습니다. {3}. + + + 다음 오류 메시지로 인해 도메인 '{1}'에서 '{0}' 컴퓨터의 조인을 해제하지 못했습니다. {2}. + + + 다음 오류 메시지로 인해 '{0}' 컴퓨터에 대한 WMI 연결을 설정할 수 없습니다. {1}. + + + 다음 오류 메시지로 인해 '{0}' 컴퓨터가 현재 작업 그룹 '{2}'에서 도메인 '{1}'에 조인하지 못했습니다. {3}. + + + '{0}' 컴퓨터가 도메인 '{1}'에서 조인이 해제되었지만 다음 오류 메시지로 인해 새 도메인 '{2}'에 조인하지 못했습니다. {3}. + + + 컴퓨터 '{0}'이(가) 새 도메인 '{1}'에 조인되었지만 다음 오류 메시지로 인해 '{2}'(으)로 이름을 변경하지 못했습니다. {3}. + + + '{0}' 플래그는 '{1}' 플래그가 지정된 경우에만 유효합니다. + + + 여러 대의 컴퓨터 이름을 바꿀 수 없습니다. NewName 매개 변수는 단일 컴퓨터가 지정된 경우에만 유효합니다. + + + 도메인 {0}에서 로컬 컴퓨터의 컴퓨터 계정을 찾을 수 없습니다. + + + {0} 도메인 컨트롤러에서 로컬 컴퓨터의 컴퓨터 계정을 찾을 수 없습니다. + + + 다음 예외로 인해 로컬 컴퓨터에 대한 도메인 정보를 가져올 수 없습니다. {0}. + + + 도메인의 컴퓨터 계정에 대한 보안 채널 암호를 다시 설정할 수 없습니다. 다음 예외로 인해 작업이 실패했습니다. {0}. + + + 다음 오류 메시지로 인해 로컬 컴퓨터의 보안 채널 암호를 다시 설정하지 못했습니다. {0}. + + + 로컬 컴퓨터에서 보안 채널 암호를 다시 설정하려면 관리자 권한이 필요합니다. 액세스가 거부되었습니다. + + + 로컬 컴퓨터 계정의 보안 채널 암호를 다시 설정할 수 없습니다. 로컬 컴퓨터가 현재 도메인의 일부가 아닙니다. + + + 컴퓨터의 NetBIOS 이름은 15바이트(이 경우 15자)로 제한됩니다. NetBIOS 이름은 "{0}"(으)로 단축되므로 NetBIOS 이름 확인에서 충돌이 발생할 수 있습니다. 계속하시겠습니까? + + + NetBIOS 이름이 잘립니다. + + + 지정한 서버 이름 {0}을(를) 확인할 수 없습니다. + + + 지난 {0}분 내에 이미 만들어졌으므로 새 시스템 복원 지점을 만들 수 없습니다. 레지스트리 키 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore' 아래에 DWORD 값 'SystemRestorePointCreationFrequency'를 만들어 복원 지점 만들기 빈도를 변경할 수 있습니다. 이 레지스트리 키의 값은 두 복원 지점 생성 사이에 필요한 시간 간격(분)을 나타냅니다. 기본값은 1440분(24시간)입니다. + + + Win32_OperatingSystem WMI 개체를 검색할 수 없습니다. + + + {0} 컴퓨터는 건너뜁니다. 다음 오류 메시지와 함께 WMI 서비스를 통해 LastBootUpTime을 검색하지 못했습니다. {1}. + + + 로컬 컴퓨터에 대한 보안 채널을 확인할 수 없습니다. 다음 예외로 인해 작업이 실패했습니다. {0}. + + + 로컬 컴퓨터와 도메인 {0} 간의 보안 채널을 복구하려는 시도가 실패했습니다. + + + 로컬 컴퓨터와 도메인 {0} 간의 보안 채널을 복구했습니다. + + + 로컬 컴퓨터와 도메인 {0} 간의 보안 채널이 양호한 상태입니다. + + + 로컬 컴퓨터와 도메인 {0} 간의 보안 채널이 손상되었습니다. + + + 로컬 컴퓨터의 보안 채널 암호를 확인할 수 없습니다. 로컬 컴퓨터가 현재 도메인의 일부가 아닙니다. + + + ARM(Advanced RISC Machine) 플랫폼에서 시스템 복원 API가 지원되지 않으므로 작업을 수행할 수 없습니다. + + + 컴퓨터가 지정된 제한 시간 내에 다시 시작을 완료하지 못했습니다. + + + 복원 지점 만들기에 대한 시간 간격의 유효성을 검사할 수 없습니다. 다음 오류 메시지로 인해 마지막 복원 지점을 검색하지 못했습니다. {0}. + + + AsJob 매개 변수 집합은 지원되지 않습니다. + + + CoreCLR에서는 {0} 매개 변수가 지원되지 않습니다. + + + 필요한 네이티브 명령 'shutdown'을 찾을 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/HotFixResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/HotFixResources.ko.resx new file mode 100644 index 00000000000..4578269e0f0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/HotFixResources.ko.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 + + + '{0}' 컴퓨터에서 요청한 핫픽스를 찾을 수 없습니다. 입력을 확인한 다음 명령을 다시 실행하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/NavigationResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/NavigationResources.ko.resx new file mode 100644 index 00000000000..9d7fbed85d4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/NavigationResources.ko.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 + + + 지정한 경로는 자식 항목이 있는 컨테이너입니다. 이 컨테이너와 해당 자식 항목을 삭제하시겠습니까? + + + 지정한 항목을 삭제하시겠습니까? + + + 지정한 대상이 이미 있으므로 복사할 수 없습니다. 기존 콘텐츠를 덮어쓰시겠습니까? + + + 새 드라이브 + + + 이름: {0} 공급자: {1} 루트: {2} + + + 드라이브 제거 + + + 이름: {0} 공급자: {1} 루트: {2} + + + 드라이브 '{0}'이(가) 사용 중이므로 제거할 수 없습니다. + + + 항목 {0}에 자식 항목이 있으며 Recurse 매개 변수가 지정되지 않았습니다. 계속하면 모든 자식 항목이 항목과 함께 제거됩니다. 계속하시겠습니까? + + + 항목 '{0}'이(가) 사용 중이므로 제거할 수 없습니다. + + + 지정한 경로의 개체 {0}이(가) 없거나 -Include 또는 -Exclude 매개 변수로 필터링되었습니다. + + + 콘텐츠 설정 + + + 경로: {0} + + + 콘텐츠 추가 + + + 경로: {0} + + + 항목 '{0}'이(가) 없으므로 항목을 이동할 수 없습니다. + + + 항목 '{0}'이(가) 사용 중이므로 항목을 이동할 수 없습니다. + + + 항목 '{0}'이(가) 없어서 이름을 바꿀 수 없습니다. + + + 항목 '{0}'이(가) 사용 중이므로 이름을 바꿀 수 없습니다. + + + 경로 '{0}'에 한정자가 지정되지 않았으므로 경로를 구문 분석할 수 없습니다. + + + 시작 + + + 롤백 + + + 커밋 + + + 현재 트랜잭션 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ProcessCommandHelpResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ProcessCommandHelpResources.ko.resx new file mode 100644 index 00000000000..ea4f0235b4b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ProcessCommandHelpResources.ko.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 + + + 현재 실행 중인 프로세스를 나열합니다. + + + +-Id id +[int[]] +[pipeline input allowed] +가져올 프로세스를 지정하는 프로세스 식별자의 쉼표로 구분된 목록 + +-ProcessName name +[string[]] +[pipeline input allowed] +가져올 프로세스를 지정하는 프로세스 이름의 쉼표로 구분된 목록 + +-Exclude name +[ArrayList] +출력에서 제외할 프로세스 이름의 쉼표로 구분된 목록입니다. + +--- +이 명령은 로컬 컴퓨터의 프로세스를 열거하고 System.Diagnostics.Process 개체를 출력합니다. 이 명령은 프로세스 개체를 출력 파이프라인으로 하나씩 보냅니다. 이 명령은 명령줄에서 ID(프로세스 식별자) 또는 프로세스 이름 같은 매개 변수를 사용합니다. 이 명령은 지정한 ID 또는 ProcessName 매개 변수에 해당하는 system.diagnostics.process를 반환합니다. + + + 제외는 프로세스 이름에 대해서만 작동합니다. + + + 실행 중인 모든 프로세스를 반환합니다. + + + svc로 시작하는 이름의 모든 프로세스를 반환합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ProcessResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ProcessResources.ko.resx new file mode 100644 index 00000000000..06b1a9cf489 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ProcessResources.ko.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 + + + "{0}" 이름의 프로세스를 찾을 수 없습니다. 프로세스 이름을 확인한 다음 cmdlet을 다시 호출하세요. + + + "{0}" 이름의 프로세스를 찾을 수 없습니다. 프로세스 ID로 검색하려면 -Id를 사용해 보세요. + + + 디버거를 "{0} ({1})" 프로세스에 연결할 수 없어서 이 명령을 실행할 수 없습니다. 다른 프로세스를 지정한 다음 명령을 다시 실행하세요. + + + 프로세스 식별자가 {1}인 프로세스를 찾을 수 없습니다. + + + 다음 오류로 인해 "{0} ({1})" 프로세스를 중지할 수 없습니다. {2} + + + {0}({1}) + + + {0} {1} + + + "{0}" 프로세스의 모듈을 열거할 수 없습니다. + + + "{0}" 프로세스의 파일 버전 정보를 열거할 수 없습니다. + + + "{0}" 프로세스의 모듈 및 파일 버전 정보를 열거할 수 없습니다. + + + {0}({1}) 항목에 대해 Stop-Process 작업을 수행하시겠습니까? + + + 지정한 경로는 올바른 Win32 응용 프로그램이 아닙니다. UseShellExecute를 사용하여 다시 시도하세요. + + + 다음 오류로 인해 이 명령이 "{0} ({1})" 작업을 중지했습니다. {2} + + + Redirection 매개 변수는 UseShellExecute 매개 변수와 함께 사용할 수 없어서 이 명령을 실행할 수 없습니다. + + + "Modules" 또는 "FileVersion"을 가져오는 중 예외가 발생했습니다. "이 기능은 원격 컴퓨터에서 지원되지 않습니다." + + + 기본 디버거를 사용할 수 없어서 이 명령은 {0} 때문에 프로세스에 디버거를 연결할 수 없습니다. + + + "시스템 유휴 상태" 프로세스를 기다릴 수 없어서 이 명령이 중지되었습니다. 다른 프로세스를 지정하고 명령을 다시 실행하세요. + + + 자기 자신은 기다릴 수 없어서 이 명령이 중지되었습니다. 다른 프로세스를 지정하고 명령을 다시 실행하세요. + + + "{0} ({1})" 프로세스가 지정된 제한 시간 안에 중지되지 않아서 이 명령이 중지되었습니다. + + + 오류 때문에 이 명령을 실행할 수 없습니다. {0} + + + 입력한 "{0}"이(가) 올바른 응용 프로그램이 아니므로 이 명령을 실행할 수 없습니다. 올바른 응용 프로그램을 지정한 다음 명령을 다시 실행하세요. + + + 매개 변수 "{0}"에 올바르지 않은 값이 있거나 이 명령과 함께 사용할 수 없어서 이 명령을 실행할 수 없습니다. 올바른 입력을 제공한 다음 명령을 다시 실행하세요. + + + "{0}"과(와) "{1}"이(가) 같아서 이 명령을 실행할 수 없습니다. 다른 입력을 제공한 다음 명령을 다시 실행하세요. + + + 이 명령은 필요한 정보를 모두 찾을 수 없어서 완전히 실행할 수 없습니다. + + + 새 프로세스 핸들을 가져오지 못했습니다. "{0}". 출력된 Process 개체의 일부 속성과 메서드는 제대로 작동하지 않을 수 있습니다. + + + 오류 1783 때문에 이 명령을 실행할 수 없습니다. 이 오류의 원인은 존재하지 않는 사용자 "{0}"을(를) 사용하는 것일 수 있습니다. 올바른 사용자를 지정하고 명령을 다시 실행하세요. + + + 네트워크에 '{0}'을(를) 추가하는 동안 오류가 발생했습니다. {1} + + + 네트워크에서 '{0}'을(를) 제거하는 동안 오류가 발생했습니다. {1} + + + ‘{0}’의 이름을 바꾸는 동안 오류 발생: {1} + + + 매개 변수 "{0}" 및 "{1}"을(를) 동시에 지정할 수 없습니다. + + + 다음 오류로 인해 "{0} ({1})" 프로세스를 디버그할 수 없습니다. {2} + + + 사용자는 요청한 정보에 대한 액세스 권한이 없습니다. + + + 지정한 매개 변수가 잘못되었습니다. + + + 사용자에게 권한이 충분하지 않습니다. + + + 알 수 없는 오류가 발생했습니다. + + + 지정한 경로가 없습니다. + + + '{0}' 매개 변수는 이 Windows 버전의 cmdlet '{1}'에서 지원되지 않습니다. + + + '{0}' 매개 변수는 이 PowerShell 버전의 cmdlet '{1}'에서 지원되지 않습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/ServiceResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ServiceResources.ko.resx new file mode 100644 index 00000000000..0a90db7b1e7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/ServiceResources.ko.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}) + + + 서비스 이름이 '{0}'인 서비스를 찾을 수 없습니다. + + + 표시 이름이 '{1}'인 서비스를 찾을 수 없습니다. + + + 종속 서비스가 있으므로 서비스 '{1}({0})'을(를) 중지할 수 없습니다. Force 플래그가 설정된 경우에만 중지할 수 있습니다. + + + 종속 서비스가 있으므로 서비스 '{1}({0})'을(를) 중지할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 중지할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 시작할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 일시 중단할 수 없습니다. + + + 서비스 '{1}({0})'은(는) 일시 중단이나 다시 시작을 지원하지 않으므로 일시 중단할 수 없습니다. + + + 서비스 '{1}({0})'이(가) 현재 실행 중이 아니므로 일시 중단할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 다시 시작할 수 없습니다. + + + 서비스 '{1}({0})'은(는) 일시 중단이나 재개를 지원하지 않으므로 다시 시작할 수 없습니다. + + + 서비스 '{1}({0})'이(가) 현재 실행 중이 아니므로 다시 시작할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 구성할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})' 설명을 구성할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'의 자동(지연된 시작)을 구성할 수 없습니다. + + + {1} 오류로 인해 서비스 '{0}' 보안 설명자를 구성할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 만들 수 없습니다. + + + 서비스 '{1}({0})'이(가) 만들어졌지만 {2} 오류로 인해 설명을 구성할 수 없습니다. + + + 서비스 '{1}({0})'이(가) 만들어졌지만 {2} 오류로 인해 StartupType '자동(지연된 시작)'을 구성할 수 없습니다. + + + {2} 오류로 인해 서비스 '{1}({0})'을(를) 제거할 수 없습니다. + + + ''{1}({0})'의 종속 서비스에 액세스할 수 없습니다. + + + 서비스 '{1}({0})'이(가) 시작되기를 기다리는 중... + + + 서비스 '{1}({0})'이(가) 중지되기를 기다리는 중... + + + 서비스 '{1}({0})'이(가) 일시 중단되기를 기다리는 중... + + + 서비스 '{1}({0})'이(가) 다시 시작되기를 기다리는 중... + + + '{1}({0})' 서비스를 시작하지 못했습니다. + + + 서비스 '{1}({0})'을(를) 중지하지 못했습니다. + + + 서비스 '{1}({0})'을(를) 일시 중단하지 못했습니다. + + + 서비스 '{1}({0})'을(를) 다시 시작하지 못했습니다. + + + {0} 오류로 인해 SCManager를 열 수 없습니다. PowerShell을 관리자 권한으로 실행한 다음 명령을 다시 실행하세요. + + + 시작 유형 '{0}'은(는) {1}에서 지원되지 않습니다. + + + 서비스 '{0}'의 속성 '{1}'을(를) 검색할 수 없음: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/TestConnectionResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/TestConnectionResources.ko.resx new file mode 100644 index 00000000000..9fb8c73ae77 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/TestConnectionResources.ko.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 + + + 컴퓨터 '{0}'에 대한 연결 테스트에 실패했습니다. {1} + + + 대상 이름을 확인할 수 없습니다. + + + 대상 IPv4/IPv6 주소가 없습니다. + + + 대상 '{0}'에 대한 경로 추적을 완료할 수 없습니다. 호스트에 도달하는 데 필요한 홉 수가 MaxHops({1})를 초과합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/TestPathResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/TestPathResources.ko.resx new file mode 100644 index 00000000000..daf71928900 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/TestPathResources.ko.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 + + + 제공된 Path 인수는 null이거나 비어 있는 컬렉션입니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ko/TimeZoneResources.ko.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ko/TimeZoneResources.ko.resx new file mode 100644 index 00000000000..ca093b6f03f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ko/TimeZoneResources.ko.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 + + + 이름 '{0}'이(가) 여러 항목으로 확인되므로 로컬 표준 시간대를 설정할 수 없습니다. + + + 로컬 컴퓨터에서 '{0}' 표준 시간대 이름을 찾을 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ClearRecycleBinResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ClearRecycleBinResources.pl.resx new file mode 100644 index 00000000000..3efd0592ed4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ClearRecycleBinResources.pl.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 + + + Cała zawartość kosza + + + Cała zawartość kosza w przypadku dysku „{0}” + + + Czyszczenie kosza + + + W przypadku dysku „{0}” + + + w przypadku wszystkich dysków + + + Nie można odnaleźć dysku. Dysk o nazwie „{0}” nie istnieje. Uruchom polecenie cmdlet „{1}”, aby wyświetlić dostępne dyski stałe w systemie. + + + Nieprawidłowe dane wejściowe. Obsługiwane są następujące formaty: „{0}”, „{1}” lub „{2}”. + + + Dysk o nazwie „{0}” nie jest dyskiem stałym i nie obsługuje kosza. Uruchom polecenie cmdlet „{1}”, aby wyświetlić dostępne dyski stałe w systemie. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ClipboardResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ClipboardResources.pl.resx new file mode 100644 index 00000000000..ecced3ff668 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ClipboardResources.pl.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ustaw ciąg „{0}” do schowka. + + + Dołącz ciąg „{0}” do schowka. + + + Ustaw plik „{0}” do schowka. + + + Dołącz plik „{0}” do schowka. + + + Ustaw pliki ({0}) w schowku. + + + Dołącz pliki ({0}) do schowka. + + + W Schowku nie ma zawartości lub format zawartości jest niezgodny. Ustaw obiekt wejściowy na Schowek. + + + Schowek został wyczyszczony. + + + Typ TextFormatType można łączyć tylko z formatem Text. + + + Nieprzetworzone można łączyć tylko z formatem Text lub FileDropList. + + + Kod HTML można łączyć tylko z formatem tekstu HTML. + + + Na tej platformie jest obsługiwany tylko format tekstu. + + + Schowek nie jest obsługiwany na tej platformie. + + + Przełącznik „-AsHtml” nie jest obsługiwany na tej platformie. + + + Parametr „-TextFormatType” obsługuje tylko element „Text” na tej platformie. + + + Parametr „-Path” nie jest obsługiwany na tej platformie. + + + Parametr „-LiteralPath” nie jest obsługiwany na tej platformie. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/CmdletizationResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/CmdletizationResources.pl.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/CmdletizationResources.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ComputerInfoResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ComputerInfoResources.pl.resx new file mode 100644 index 00000000000..2bc714027c5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ComputerInfoResources.pl.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 + + + Ładowanie informacji o systemie operacyjnym + + + Ładowanie informacji o poprawkach na gorąco + + + Ładowanie informacji rejestru + + + Ładowanie informacji o systemie BIOS + + + Ładowanie informacji o płycie głównej + + + Ładowanie informacji o komputerze + + + Ładowanie informacji o procesorze + + + Ładowanie informacji o karcie sieciowej + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ComputerResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ComputerResources.pl.resx new file mode 100644 index 00000000000..cd19bd3a865 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ComputerResources.pl.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 + + + Ta funkcja nie jest obsługiwana w tym systemie operacyjnym. + + + Nie można włączyć dysku {0}. + + + Polecenie nie może włączyć infrastruktury przywracania komputera na wskazanym komputerze, ponieważ podany dysk jest nieprawidłowy. Wprowadź prawidłowy dysk w parametrze Drive, a następnie spróbuj ponownie. + + + Uwzględnij dysk systemowy na liście dysków. + + + Polecenie nie może wyłączyć infrastruktury przywracania komputera, ponieważ podany dysk jest nieprawidłowy. Wprowadź prawidłowy dysk w parametrze Drive, a następnie spróbuj ponownie. + + + Polecenie nie może wyłączyć przywracania systemu na dysku {0}. Być może nie masz wystarczających uprawnień do wykonania tej operacji. + + + Usługa SystemRestore jest wyłączona. + + + Infrastruktura przywracania systemu nie może utworzyć punktu przywracania. + + + Ostatnia próba przywrócenia komputera zakończyła się niepowodzeniem. + + + Komputer został przywrócony do określonego punktu przywracania. + + + Ostatnia próba przywrócenia komputera została przerwana. + + + Polecenie nie może odnaleźć punktu przywracania „{0}”. Sprawdź numer sekwencyjny „{0}”, a następnie spróbuj ponownie uruchomić polecenie. + + + {0} ({1}) + + + Nie można ponownie uruchomić komputera {0}. Komunikat o błędzie: {1}. + + + Nie można uruchomić tego polecenia na komputerze docelowym („{1}”) z powodu następującego błędu: {0}.{2} + + + Nie można zatrzymać komputera {0}. Komunikat o błędzie: {1}. + + + Polecenie nie może przywrócić komputera, ponieważ element „{0}” nie został ustawiony jako prawidłowy punkt przywracania. Wprowadź prawidłowy punkt przywracania w parametrze RestorePoint, a następnie spróbuj ponownie. + + + Zmiany zaczną obowiązywać po ponownym uruchomieniu komputera {1}. + + + Po opuszczeniu domeny trzeba będzie znać hasło konta administratora lokalnego, aby zalogować się na tym komputerze. Chcesz kontynuować? + + + Następująca nazwa komputera jest nieprawidłowa: {0}. Upewnij się, że nazwa komputera nie jest dłuższa niż 255 znaków, nie zawiera dwóch lub więcej kropek następujących po sobie, nie zaczyna się od kropki, nie składa się wyłącznie ze znaków numerycznych i nie zawiera żadnego z następujących znaków: +{{|}}~[\]^:;<=>?@!"#$%^`()+/, + + + Domena w nazwie komputera „{0}” jest nieprawidłowa. Upewnij się, że domena istnieje i że jej nazwa jest prawidłową nazwą domeny. + + + Wartość określona dla parametru NewComputerName jest taka sama, jak wartość parametru ComputerName. Podaj inną wartość dla parametru NewComputerName. + + + „Hasło bezpiecznego kanału między „{0}” i „{1}: zostało zresetowane.” + + + Nie można uruchomić tego polecenia z powodu następującego błędu: nie można uruchomić usługi, ponieważ jest wyłączona lub nie ma włączonych skojarzonych z nią urządzeń. + + + Trwa tworzenie punktu przywracania systemu ... + + + Trwa tworzenie punktu przywracania systemu... Ukończono {0}%. + + + Ukończono. + + + Wypróbuj poniższe opcje i uruchom polecenie ponownie. +1. Sprawdź, czy komputer docelowy („{0}”) jest uruchomiony. +2. Określ pełną nazwę komputera docelowego („{0}”). + + + Nie można ponownie uruchomić komputera {0}. Nie można włączyć uprawnień dostępu {1} dla procesu wywołującego. + + + Włącz {0} i uruchom ponownie komputer. + + + Uprawnienia dostępu do lokalnego zamykania + + + Uprawnienia dostępu do zdalnego zamykania + + + Nie można czekać na ponowne uruchomienie komputera lokalnego. Komputer lokalny jest ignorowany, gdy określony jest parametr Wait. + + + Parametry Timeout, For i Delay są prawidłowe tylko wtedy, gdy określono parametr Wait. + + + Trwa ponowne uruchamianie komputerów... + + + Ponowne uruchamianie komputera {0} + + + Ukończono: {0}/{1}. + + + Trwa weryfikowanie, czy komputer został uruchomiony ponownie... + + + Trwa oczekiwanie na łączność z programem PowerShell... + + + Trwa oczekiwanie na ponowne uruchomienie... + + + Trwa oczekiwanie na połączenie z usługą WinRM... + + + Trwa oczekiwanie na połączenie z usługą WMI... + + + Ponowne uruchamianie zakończone + + + Połączone typy usług nie są obecnie obsługiwane. + + + Nie można rozpoznać nazwy komputera {0} z powodu wyjątku: {1}. + + + Liczba nowych nazw nie jest równa liczbie komputerów docelowych. + + + Pomiń komputer „{0}” z nową nazwą „{1}”, ponieważ nowa nazwa jest nieprawidłowa. Wprowadzona nowa nazwa komputera nie ma prawidłowego formatu. Nazwy standardowe mogą zawierać litery (a-z, A-Z), cyfry (0-9) i łączniki (-), ale nie mogą zawierać spacji ani kropek (.). Nazwa nie może składać się wyłącznie z cyfr i nie może być dłuższa niż 63 znaki. + + + Pomiń komputer „{0}” o nowej nazwie „{1}”, ponieważ nowa nazwa jest taka sama jak bieżąca. + + + Nie można usunąć komputera „{0}”, ponieważ nie znajduje się on w domenie. + + + Nie można przyłączyć komputera „{0}” do grupy roboczej „{1}”. Komunikat o błędzie: {2} + + + Nie można usunąć komputerów z domeny, ponieważ sieć lokalna nie działa. + + + Nie można zmienić nazwy komputera „{0}” na „{1}” z powodu następującego wyjątku: {2}. + + + Dołącz do domeny „{0}” + + + Dołącz do grupy roboczej „{0}” + + + Nie można dodać komputera „{0}” do domeny „{1}”, ponieważ komputer już się w niej znajduje. + + + Nie można dodać komputera „{0}” do grupy roboczej „{1}”, ponieważ komputer już do niej należy. + + + Komputer „{0}” został z powodzeniem przyłączony do grupy roboczej „{1}”, ale nie można zmienić jego nazwy na „{2}”. Komunikat o błędzie: {3}. + + + Komputer „{0}” został za powodzeniem odłączony od domeny „{1}”, ale nie można przyłączyć go do grupy roboczej „{2}”. Komunikat o błędzie: {3}. + + + Nie można odłączyć komputera „{0}” od domeny „{1}” z powodu następującego komunikatu o błędzie: {2}. + + + Nie można nawiązać połączenia WMI z komputerem „{0}”. Komunikat o błędzie: {1}. + + + Komputer „{0}” nie może dołączyć do domeny „{1}” z bieżącej grupy roboczej „{2}”. Komunikat o błędzie: {3}. + + + Komputer „{0}” został z powodzeniem odłączony od domeny „{1}”, ale nie można go przyłączyć do nowej domeny „{2}”, a wyświetlony został następujący komunikat o błędzie: {3}. + + + Komputer „{0}” został z powodzeniem przyłączony do nowej domeny „{1}”, ale zmiana jego nazwy na „{2}” zakończyła się niepowodzeniem. Komunikat o błędzie: {3}. + + + Flaga „{0}” jest prawidłowa tylko wtedy, gdy określono flagę „{1}”. + + + Nie można zmienić nazwy wielu komputerów. Parametr NewName jest prawidłowy tylko wtedy, gdy określono jeden komputer. + + + Nie można odnaleźć konta komputera dla komputera lokalnego w domenie {0}. + + + Nie można odnaleźć konta komputera dla komputera lokalnego z kontrolera domeny {0}. + + + Nie można uzyskać informacji o domenie dla komputera lokalnego z powodu następującego wyjątku: {0}. + + + Nie można zresetować hasła bezpiecznego kanału dla konta komputera w domenie. Operacja zakończyła się niepowodzeniem z następującym wyjątkiem: {0}. + + + Resetowanie hasła bezpiecznego kanału dla komputera lokalnego zakończyło się niepowodzeniem. Komunikat o błędzie: {0}. + + + Do zresetowania hasła bezpiecznego kanału na komputerze lokalnym są wymagane uprawnienia administratora. Odmowa dostępu. + + + Nie można zresetować hasła bezpiecznego kanału dla konta komputera lokalnego. Komputer lokalny nie jest obecnie częścią domeny. + + + Nazwa NetBIOS komputera jest ograniczona do 15 bajtów, co w tym przypadku oznacza 15 znaków. Nazwa NetBIOS zostanie skrócona do „{0}”, co może powodować konflikty związane z rozpoznawaniem nazw NetBIOS. Chcesz kontynuować? + + + Nazwa NetBIOS zostanie obcięta. + + + Nie można rozwiązać podanej nazwy serwera {0}. + + + Nie można utworzyć nowego punktu przywracania systemu, ponieważ taki punkt został już utworzony w ciągu ostatnich minut {0}. Częstotliwość tworzenia punktów przywracania można zmienić, tworząc wartość DWORD „SystemRestorePointCreationFrequency” w kluczu rejestru „HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore”. Wartość tego klucza rejestru określa wymagany interwał czasu w minutach między dwoma punktami przywracania. Wartość domyślna wynosi 1440 minut (24 godziny). + + + Nie można pobrać obiektu WMI Win32_OperatingSystem. + + + Komputer {0} jest pomijany. Nie można pobrać wartości LastBootUpTime za pośrednictwem usługi WMI przy użyciu następującego komunikatu o błędzie: {1}. + + + Nie można zweryfikować bezpiecznego kanału dla komputera lokalnego. Operacja zakończyła się niepowodzeniem z następującym wyjątkiem: {0}. + + + Próba naprawienia bezpiecznego kanału między komputerem lokalnym a domeną {0} zakończyła się niepowodzeniem. + + + Bezpieczny kanał między komputerem lokalnym a domeną {0} został z powodzeniem naprawiony. + + + Bezpieczny kanał pomiędzy komputerem lokalnym a domeną {0} jest w dobrym stanie. + + + Bezpieczny kanał pomiędzy komputerem lokalnym a domeną {0} jest uszkodzony. + + + Nie można zweryfikować hasła bezpiecznego kanału dla komputera lokalnego. Komputer lokalny nie jest obecnie częścią domeny. + + + Nie można wykonać operacji, ponieważ interfejsy API przywracania systemu nie są obsługiwane na platformie ARM (Advanced RISC Machine). + + + Komputer nie został ponownie uruchomiony w określonym czasie. + + + Nie można sprawdzić interwału czasu tworzenia punktu przywracania. Nie można pobrać ostatniego punktu przywracania. Komunikat o błędzie: {0}. + + + Zestaw parametrów AsJob nie jest obsługiwany. + + + Parametr {0} nie jest obsługiwany w przypadku środowiska CoreCLR. + + + Nie znaleziono wymaganego polecenia natywnego „shutdown”. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/HotFixResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/HotFixResources.pl.resx new file mode 100644 index 00000000000..7c8caab1353 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/HotFixResources.pl.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 + + + Nie można odnaleźć żądanej poprawki na komputerze „{0}”. Sprawdź dane wejściowe i ponownie uruchom polecenie. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/NavigationResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/NavigationResources.pl.resx new file mode 100644 index 00000000000..a738ff5621f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/NavigationResources.pl.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 + + + Określona ścieżka jest kontenerem zawierającym elementy podrzędne. Czy chcesz usunąć ten kontener i jego elementy podrzędne? + + + Czy chcesz usunąć określony element? + + + Nie można skopiować, ponieważ określone miejsce docelowe już istnieje. Czy chcesz zastąpić istniejącą zawartość? + + + Nowy dysk + + + Nazwa: {0} Dostawca: {1} Katalog główny: {2} + + + Usuń dysk + + + Nazwa: {0} Dostawca: {1} Katalog główny: {2} + + + Nie można usunąć dysku „{0}”, ponieważ jest używany. + + + Element {0} ma elementy podrzędne, a parametr Recurse nie został określony. Jeśli będziesz kontynuować, wszystkie elementy podrzędne zostaną usunięte wraz z elementem. Czy na pewno chcesz kontynuować? + + + Nie można usunąć elementu w lokalizacji „{0}”, ponieważ jest on używany. + + + Obiekt w określonej ścieżce {0} nie istnieje lub został przefiltrowany za pomocą parametru -Include lub -Exclude. + + + Ustaw zawartość + + + Ścieżka: {0} + + + Dodaj zawartość + + + Ścieżka: {0} + + + Nie można przenieść elementu, ponieważ element w lokalizacji „{0}” nie istnieje. + + + Nie można przenieść elementu, ponieważ element w „{0}” jest w użyciu. + + + Nie można zmienić nazwy, ponieważ element w lokalizacji „{0}” nie istnieje. + + + Nie można zmienić nazwy elementu w „{0}”, ponieważ jest on używany. + + + Nie można przeanalizować ścieżki, ponieważ ścieżka „{0}” nie ma określonego kwalifikatora. + + + Początek + + + Wycofaj + + + Zatwierdź + + + Bieżąca transakcja + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ProcessCommandHelpResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ProcessCommandHelpResources.pl.resx new file mode 100644 index 00000000000..8f507d59b76 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ProcessCommandHelpResources.pl.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 + + + Wyświetla listę aktualnie uruchomionych procesów. + + + +-Id id +[int[]] +[pipeline input allowed] +Rozdzielana przecinkami lista identyfikatorów procesów określających procesy do pobrania + +Nazwa -ProcessName +[string[]] +[pipeline input allowed] +Rozdzielana przecinkami lista nazw procesów określających procesy do pobrania + +-Wyklucz nazwę +[ArrayList] +Rozdzielana przecinkami lista nazw procesów do wykluczenia z danych wyjściowych. + +--- +Polecenie wylicza procesy z komputera lokalnego i generuje obiekty System.Diagnostics.Process. Polecenie zapisuje obiekt procesu do potoku wyjściowego pojedynczo. Polecenie pobiera parametry, takie jak identyfikator (identyfikator procesu) lub nazwa procesu z wiersza polecenia. Polecenie zwraca odpowiedni element system.diagnostics.process dla podanego identyfikatora lub parametrów ProcessName. + + + Wykluczenie działa tylko dla nazwy procesu. + + + Zwraca wszystkie uruchomione procesy. + + + Zwraca wszystkie procesy o nazwach rozpoczynających się od svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ProcessResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ProcessResources.pl.resx new file mode 100644 index 00000000000..fbe5fd2f5e3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ProcessResources.pl.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 + + + Nie można odnaleźć procesu o nazwie „{0}”. Sprawdź nazwę procesu i ponownie wywołaj polecenie cmdlet. + + + Nie można odnaleźć procesu o nazwie „{0}”. Spróbuj uruchomić polecenie z identyfikatorem -Id, aby wyszukać według identyfikatora procesów. + + + Nie można uruchomić tego polecenia, ponieważ nie można dołączyć debugera do procesu „{0} ({1})”. Określ inny proces i uruchom polecenie. + + + Nie można odnaleźć procesu o identyfikatorze procesu {1}. + + + Nie można zatrzymać procesu „{0} ({1})” z powodu następującego błędu: {2} + + + {0} ({1}) + + + {0} {1} + + + Nie można wyliczyć modułów procesu „{0}”. + + + Nie można wyliczyć informacji o wersji pliku procesu „{0}”. + + + Nie można wyliczyć modułów i informacji o wersji pliku procesu „{0}”. + + + Czy na pewno chcesz wykonać operację zatrzymania procesu na następującym elemencie: {0}({1})? + + + Określona ścieżka nie jest prawidłową aplikacją win32. Spróbuj ponownie za pomocą polecenia UseShellExecute. + + + To polecenie zatrzymało operację „{0} ({1})” z powodu następującego błędu: {2}. + + + Nie można uruchomić tego polecenia, ponieważ parametrów przekierowania nie można używać z parametrem UseShellExecute + + + Wystąpił błąd podczas pobierania elementów „Modules” lub „FileVersion”: „Ta funkcja nie jest obsługiwana na komputerach zdalnych.”. + + + To polecenie nie może dołączyć debugera do procesu z powodu {0} braku dostępnego debugera domyślnego. + + + To polecenie przerwało działanie, ponieważ nie może oczekiwać na zakończenie procesu bezczynności systemu. Określ inny proces i ponownie uruchom polecenie. + + + To polecenie zatrzymało operację, ponieważ nie może czekać na siebie. Określ inny proces i ponownie uruchom polecenie. + + + To polecenie zatrzymało operację, ponieważ proces „{0} ({1})” nie został zatrzymany w określonym przekroczeniem limitu czasu. + + + Nie można uruchomić tego polecenia z powodu błędu: {0} + + + Nie można uruchomić tego polecenia, ponieważ dane wejściowe „{0}” nie są prawidłową aplikacją. Podaj prawidłową aplikację i ponownie uruchom polecenie. + + + Nie można uruchomić tego polecenia, ponieważ parametr „{0}” ma nieprawidłową wartość lub nie może być używany z tym poleceniem. Podaj prawidłowe dane wejściowe i ponownie uruchom polecenie. + + + Nie można uruchomić tego polecenia, ponieważ „{0}” i „{1}” są takie same. Podaj różne dane wejściowe i ponownie uruchom polecenie. + + + To polecenie nie może zostać w pełni wykonane, ponieważ system nie może znaleźć wszystkich wymaganych informacji. + + + Nie można pobrać nowego dojścia procesu: „{0}”. Wyjściowy obiekt Process może mieć pewne właściwości i metody, które nie działają prawidłowo. + + + Nie można uruchomić tego polecenia z powodu błędu 1783. Możliwą przyczyną tego błędu może być użycie nieistniejącego użytkownika „{0}”. Podaj prawidłowego użytkownika i ponownie uruchom polecenie. + + + Błąd podczas dodawania elementu „{0}” do sieci: {1} + + + Błąd podczas usuwania elementu „{0}” z sieci: {1} + + + Błąd podczas zmieniania nazwy „{0}”: {1} + + + Nie można jednocześnie podać parametrów „{0}” i „{1}”. + + + Nie można przeprowadzić debugowania procesu „{0} ({1})” z powodu następującego błędu: {2} + + + Użytkownik nie ma dostępu do żądanych informacji. + + + Określona nazwa parametru jest nieprawidłowa. + + + Użytkownik nie ma wystarczających uprawnień. + + + Nieznany błąd. + + + Podana ścieżka nie istnieje. + + + Parametr „{0}” nie jest obsługiwany przez polecenie cmdlet „{1}” w tej wersji systemu Windows. + + + Parametr „{0}” nie jest obsługiwany dla polecenia cmdlet „{1}” w tej wersji programu PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/ServiceResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ServiceResources.pl.resx new file mode 100644 index 00000000000..70532713564 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/ServiceResources.pl.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}) + + + Nie można odnaleźć żadnej usługi o nazwie „{0}”. + + + Nie można odnaleźć żadnej usługi o nazwie wyświetlanej „{1}”. + + + Nie można zatrzymać usługi „{1} ({0})”, ponieważ ma ona usługi zależne. Można ją zatrzymać tylko wtedy, gdy flaga Wymuś jest ustawiona. + + + Nie można zatrzymać usługi „{1} ({0})”, ponieważ ma ona usługi zależne. + + + Nie można zatrzymać usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Nie można uruchomić usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Nie można wstrzymać usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Nie można wstrzymać usługi „{1} ({0})”, ponieważ usługa nie obsługuje wstrzymania ani wznowienia. + + + Nie można wstrzymać usługi „{1} ({0})”, ponieważ nie jest ona obecnie uruchomiona. + + + Nie można wznowić usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Nie można wznowić usługi „{1} ({0})”, ponieważ usługa nie obsługuje wstrzymania ani wznowienia. + + + Nie można wznowić usługi „{1} ({0})”, ponieważ nie jest ona obecnie uruchomiona. + + + Nie można skonfigurować usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Nie można skonfigurować opisu usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Nie można skonfigurować automatycznej usługi „{1} ({0})” (opóźnione uruchomienie) z powodu następującego błędu: {2} + + + Nie można skonfigurować deskryptora zabezpieczeń usługi „{0}” z powodu następującego błędu: {1} + + + Nie można utworzyć usługi „{1} ({0})” z powodu następującego błędu: {2} + + + Utworzono usługę „{1} ({0})”, ale jej opisu nie można skonfigurować z powodu następującego błędu: {2} + + + Utworzono usługę „{1} ({0})”, ale nie można skonfigurować jej elementu StartupType „Automatic (Delayed Start)” z powodu następującego błędu: {2} + + + Nie można usunąć usługi „{1} ({0})” z powodu następującego błędu: {2} + + + 'Nie można uzyskać dostępu do usług zależnych „{1} ({0})” + + + Trwa oczekiwanie na uruchomienie usługi „{1} ({0})”... + + + Trwa oczekiwanie na zatrzymanie usługi „{1} ({0})”... + + + Trwa oczekiwanie na wstrzymanie usługi „{1} ({0})”... + + + Trwa oczekiwanie na wznowienie usługi {1} ({0})... + + + Nie można uruchomić usługi „{1} ({0})”. + + + Zatrzymanie usługi „{1} ({0})” nie powiodło się. + + + Wstrzymanie usługi „{1} ({0})” nie powiodło się. + + + Wznowienie usługi „{1} ({0})” nie powiodło się. + + + Nie można otworzyć programu SCManager z powodu następującego błędu: {0} Uruchom program PowerShell jako administrator i ponownie uruchom polecenie. + + + Typ uruchomienia „{0}” nie jest obsługiwany przez {1}. + + + Nie można pobrać właściwości „{1}” dla usługi „{0}”: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/TestConnectionResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/TestConnectionResources.pl.resx new file mode 100644 index 00000000000..706a2b2a7ba --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/TestConnectionResources.pl.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 + + + Testowanie połączenia z komputerem „{0}” nie powiodło się: {1} + + + Nie można rozpoznać nazwy docelowej. + + + Brak adresu docelowego IPv4/IPv6. + + + Nie można ukończyć traceroute do hosta docelowego „{0}”: liczba przeskoków potrzebnych do osiągnięcia hosta przekracza wartość MaxHops ({1}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/TestPathResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/TestPathResources.pl.resx new file mode 100644 index 00000000000..d83b9a6a9ec --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/TestPathResources.pl.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 + + + Podany argument Path ma wartość null lub jest pustą kolekcją. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pl/TimeZoneResources.pl.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pl/TimeZoneResources.pl.resx new file mode 100644 index 00000000000..16364606ae5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pl/TimeZoneResources.pl.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 + + + Nie można ustawić lokalnej strefy czasowej, ponieważ nazwa „{0}” wskazuje na wiele wpisów. + + + Nie znaleziono nazwy strefy czasowej „{0}” na komputerze lokalnym. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ClearRecycleBinResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ClearRecycleBinResources.pt-BR.resx new file mode 100644 index 00000000000..8b1e4e60ca9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ClearRecycleBinResources.pt-BR.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 + + + Todo o conteúdo da Lixeira + + + Todo o conteúdo da Lixeira da unidade '{0}' + + + Limpando a Lixeira + + + para a unidade '{0}' + + + para todas as unidades + + + Não é possível localizar a unidade. Não existe uma unidade com o nome '{0}'. Execute o cmdlet '{1}' para ver as unidades fixas disponíveis no sistema. + + + Entrada inválida. Há suporte para os seguintes formatos: '{0}', '{1}' ou '{2}'. + + + A unidade com o nome '{0}' não é uma unidade fixa e não dá suporte à Lixeira. Execute o cmdlet '{1}' para ver as unidades fixas disponíveis no sistema. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ClipboardResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ClipboardResources.pt-BR.resx new file mode 100644 index 00000000000..9b1784cb8e9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ClipboardResources.pt-BR.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Definir a cadeia '{0}' na área de transferência. + + + Acrescentar a cadeia '{0}' à área de transferência. + + + Definir o arquivo '{0}' na área de transferência. + + + Acrescentar o arquivo '{0}' à área de transferência. + + + Definir {0} arquivos na área de transferência. + + + Acrescentar {0} arquivos à área de transferência. + + + Não há conteúdo na Área de Transferência ou o formato do conteúdo não é compatível. Definir o objeto de entrada como Área de Transferência. + + + A Área de Transferência foi limpa. + + + TextFormatType só pode ser combinado com o formato Texto. + + + Raw só pode ser combinado com o formato Texto ou FileDropList. + + + Html só pode ser combinado com o formato Texto Html. + + + Somente o formato Texto tem suporte nesta plataforma. + + + A área de transferência não tem suporte nesta plataforma. + + + O parâmetro '-AsHtml' não tem suporte nesta plataforma. + + + O parâmetro '-TextFormatType' só dá suporte a 'Texto' nesta plataforma. + + + O parâmetro '-Path' não tem suporte nesta plataforma. + + + O parâmetro '-LiteralPath' não tem suporte nesta plataforma. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/CmdletizationResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/CmdletizationResources.pt-BR.resx new file mode 100644 index 00000000000..8227b2beaec --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/CmdletizationResources.pt-BR.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 + + + Não é possível encontrar a classe {0} no servidor CIM {1}. Verifique o valor do atributo xml ClassName no XML de Definição de Cmdlet e tente novamente. Exemplo de nome de classe válido: 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". + + + + Método CIM {1} no objeto CIM {0} + {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 + + + Falha ao executar {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 + + + Executando a seguinte operação: {0}. + {0} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + Os cmdlets CIM não oferecem suporte ao parâmetro {0} junto com o parâmetro AsJob. Remova um desses parâmetros e tente novamente. + {StrContains="AsJob"} +{0} is a placeholder for 'WhatIf' or 'Confirm' cmdlet parameters + + + Consulta CIM para instâncias da classe {0} no servidor CIM {1}: {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". + + + O método CIM retornou o seguinte código de erro: {0} + {0} is a placeholder for an error code returned from a CIM method. Example: 123 + + + O método CIM {2} exposto pela classe {0} no servidor CIM {1} + {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 + + + Tipo intrínseco CIM + + + Literal WQL + + + Não é possível localizar o parâmetro de saída {2} do método {1} do objeto CIM {0}. Verifique o valor do atributo ParameterName no XML de Definição do Cmdlet e tente novamente. + {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. + + + + Nenhum objeto {1} correspondente encontrado por {0}. Verifique os parâmetros de consulta e tente novamente. + + + Nenhum {2} encontrado com a propriedade '{0}' igual a '{1}'. Verifique o valor da propriedade e tente novamente. + + + O tipo da propriedade {0} ({1}) não corresponde ao tipo CIM ({2}) associado ao tipo declarado no XML de Definição do Cmdlet. + + + Consulta CIM para enumerar a instância associada da classe {0} no servidor CIM {1} + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + Consulta CIM para enumerar instâncias da classe {0} no servidor CIM {1}, que estão associadas à seguinte instância: {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]". + + + O comando {0} não pode ser concluído, porque o servidor {1} está ocupado no momento. O comando será retomado automaticamente em {2:f2} segundos. + {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 + + + Não é possível conectar ao servidor CIM. {0} + {0} is a placeholder for a more detailed error message. + + + O cmdlet não oferece suporte total à ação Inquire para mensagens de depuração. A operação do cmdlet continuará durante o prompt. Selecione uma preferência de ação diferente usando a opção -Debug ou a variável $DebugPreference e tente novamente. + {StrContains="Debug"} {StrContains="DebugPreference"} {StrContains="Inquire"} + + + O cmdlet não dá suporte total à ação Inquire para avisos. A operação do cmdlet continuará durante o prompt. Selecione uma preferência de ação diferente usando o parâmetro -WarningAction ou a variável $WarningPreference e tente novamente. + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Inquire"} + + + O cmdlet não oferece suporte total à ação Stop para avisos. A operação do cmdlet será interrompida com um atraso. Selecione uma preferência de ação diferente usando o parâmetro -WarningAction ou a variável $WarningPreference e tente novamente. + {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}: uma CimSession para o servidor CIM usa o protocolo DCOM, que não oferece suporte à opção {1} . + {0} is a placeholder for a name of a computer +{1} is a placeholder for 'Confirm' or 'WhatIf' + + + Nenhum objeto {2} encontrado com a propriedade '{0}' correspondente a '{1}'. Verifique o valor da propriedade e tente novamente. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ComputerInfoResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ComputerInfoResources.pt-BR.resx new file mode 100644 index 00000000000..522b61cb43a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ComputerInfoResources.pt-BR.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 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ComputerResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ComputerResources.pt-BR.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ComputerResources.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/HotFixResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/HotFixResources.pt-BR.resx new file mode 100644 index 00000000000..3c6a66af83f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/HotFixResources.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/NavigationResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/NavigationResources.pt-BR.resx new file mode 100644 index 00000000000..dc048a70495 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/NavigationResources.pt-BR.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 + + + O caminho especificado é um contêiner que tem itens filho. Deseja excluir este contêiner e seus itens filho? + + + Deseja excluir o item especificado? + + + Não é possível copiar porque o destino especificado já existe. Deseja substituir o conteúdo existente? + + + Nova unidade + + + Nome: {0} Provedor: {1} Raiz: {2} + + + Remover Unidade + + + Nome: {0} Provedor: {1} Raiz: {2} + + + Não é possível remover a unidade '{0}' porque ela está em uso. + + + O item em {0} tem filhos e o parâmetro Recurse não foi especificado. Se você continuar, todos os filhos serão removidos com o item. Tem certeza de que deseja continuar? + + + Não é possível remover o item em '{0}' porque ele está em uso. + + + Um objeto no caminho especificado {0} não existe ou foi filtrado pelo parâmetro -Include ou -Exclude. + + + Definir Conteúdo + + + Caminho: {0} + + + Adicionar Conteúdo + + + Caminho: {0} + + + Não é possível mover o item porque o item em '{0}' não existe. + + + Não é possível mover o item porque o item em '{0}' está em uso. + + + Não é possível renomear porque o item em '{0}' não existe. + + + Não é possível renomear o item em '{0}' porque ele está em uso. + + + Não é possível analisar o caminho porque o caminho '{0}' não tem um qualificador especificado. + + + Iniciar + + + Reversão + + + Confirmar + + + Transação atual + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ProcessCommandHelpResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ProcessCommandHelpResources.pt-BR.resx new file mode 100644 index 00000000000..d1e2e53a9cd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ProcessCommandHelpResources.pt-BR.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 + + + Lista os processos em execução no momento. + + + +-Id id +[int[]] +[entrada de pipeline permitida] +Lista separada por vírgulas de identificadores de processo que especificam os processos a serem obtidos + +-ProcessName nome +[string[]] +[entrada de pipeline permitida] +Lista separada por vírgulas de nomes de processo que especificam os processos a serem obtidos + +-Exclude name +[ArrayList] +Lista separada por vírgulas de nomes de processo a serem excluídos da saída. + +--- +O comando enumera processos no computador local e produz objetos System.Diagnostics.Process. O comando grava o objeto de processo no pipeline de saída, um de cada vez. O comando aceita parâmetros como ID (Identificador de Processo) ou Nome do Processo na linha de comando. O comando retorna o system.diagnostics.process correspondente para os parâmetros ID ou ProcessName fornecidos. + + + Excluir funciona somente para nome de processo. + + + Retorna todos os processos em execução. + + + Retorna todos os processos com nomes que começam com svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ProcessResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ProcessResources.pt-BR.resx new file mode 100644 index 00000000000..d2b97ac1074 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ProcessResources.pt-BR.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 + + + Não é possível localizar um processo com o nome "{0}". Verifique o nome do processo e chame o cmdlet novamente. + + + Não é possível localizar um processo com o nome "{0}". Tente executar com -Id para pesquisar processos por ID. + + + Este comando não pode ser executado porque o depurador não pode ser anexado ao processo "{0} ({1})". Especifique outro processo e execute o comando. + + + Não é possível localizar um processo com o identificador de processo {1}. + + + Não é possível interromper o processo "{0} ({1})" devido ao seguinte erro: {2} + + + {0} ({1}) + + + {0} {1} + + + Não é possível enumerar os módulos do processo "{0}". + + + Não é possível enumerar as informações de versão de arquivo do processo "{0}". + + + Não é possível enumerar os módulos e as informações de versão do arquivo do processo "{0}" . + + + Tem certeza de que deseja executar a operação Stop-Process no seguinte item: {0}({1})? + + + O caminho especificado não é um aplicativo win32 válido. Tente novamente com o UseShellExecute. + + + Este comando interrompeu a operação de "{0} ({1})" devido ao seguinte erro: {2}. + + + Este comando não pode ser executado porque os parâmetros Redirection não podem ser usados com o parâmetro UseShellExecute + + + Exceção ao obter "Modules" ou "FileVersion": "Este recurso não tem suporte para computadores remotos.". + + + Este comando não pode anexar o depurador ao processo devido a {0} porque nenhum depurador padrão está disponível. + + + Este comando interrompeu a operação porque não pode aguardar o processo 'System Idle'. Especifique outro processo e execute o comando novamente. + + + Este comando interrompeu a operação porque não pode aguardar por si mesmo. Especifique outro processo e execute o comando novamente. + + + Este comando interrompeu a operação porque o processo "{0} ({1})" não foi encerrado no tempo limite especificado. + + + Este comando não pode ser executado devido ao erro: {0} + + + Este comando não pode ser executado porque a entrada "{0}" não é um Aplicativo válido. Forneça um aplicativo válido e execute o comando novamente. + + + Este comando não pode ser executado porque o parâmetro "{0}" tem um valor inválido ou não pode ser usado com este comando. Forneça uma entrada válida e execute o comando novamente. + + + Este comando não pode ser executado porque "{0}" e "{1}" são iguais. Forneça entradas diferentes e execute o comando novamente. + + + Este comando não pode ser executado completamente porque o sistema não consegue encontrar todas as informações necessárias. + + + Falha ao recuperar o novo identificador do processo: "{0}". O objeto Process gerado pode ter algumas propriedades e métodos que não funcionam corretamente. + + + Este comando não pode ser executado devido ao erro 1783. A possível causa desse erro pode ser o uso de um usuário inexistente "{0}". Forneça um usuário válido e execute o comando novamente. + + + Erro ao adicionar '{0}' à rede: {1} + + + Erro ao remover '{0}' da rede: {1} + + + Erro ao renomear '{0}': {1} + + + Os parâmetros "{0}" e "{1}" não podem ser especificados ao mesmo tempo. + + + Não é possível depurar o processo "{0} ({1})" devido ao seguinte erro: {2} + + + O usuário não tem acesso às informações solicitadas. + + + O parâmetro especificado não é válido. + + + O usuário não tem privilégios suficientes. + + + Falha desconhecida. + + + O caminho especificado não existe. + + + Não há suporte para o parâmetro '{0}' no cmdlet '{1}' nesta edição do Windows. + + + O parâmetro '{0}' não tem suporte para o cmdlet '{1}' nesta edição do PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ServiceResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ServiceResources.pt-BR.resx new file mode 100644 index 00000000000..bc44ebbdfad --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/ServiceResources.pt-BR.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}) + + + Não é possível localizar nenhum serviço com o nome de serviço '{0}'. + + + Não é possível localizar nenhum serviço com o nome de exibição '{1}'. + + + Não é possível interromper o serviço '{1} ({0})' porque ele tem serviços dependentes. Ele só poderá ser interrompido se o sinalizador Force estiver definido. + + + Não é possível interromper o serviço '{1} ({0})' porque ele tem serviços dependentes. + + + O serviço '{1} ({0})' não pode ser interrompido devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' não pode ser iniciado devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' não pode ser suspenso devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' não pode ser suspenso porque o serviço não oferece suporte à suspensão ou à retomada. + + + O serviço '{1} ({0})' não pode ser suspenso porque não está em execução no momento. + + + O serviço '{1} ({0})' não pode ser retomado devido ao seguinte erro: {2} + + + Não é possível retomar o serviço '{1} ({0})' porque ele não oferece suporte à suspensão ou à retomada. + + + O serviço '{1} ({0})' não pode ser retomado porque não está em execução no momento. + + + O serviço '{1} ({0})' não pode ser configurado devido ao seguinte erro: {2} + + + A descrição do serviço '{1} ({0})' não pode ser configurada devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' automático (início atrasado) não pode ser configurado devido ao seguinte erro: {2} + + + Não é possível configurar o descritor de segurança do serviço '{0}' devido ao seguinte erro: {1} + + + O serviço '{1} ({0})' não pode ser criado devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' foi criado, mas sua descrição não pode ser configurada devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' foi criado, mas seu StartupType 'Automatic (Início Atrasado)' não pôde ser configurado devido ao seguinte erro: {2} + + + O serviço '{1} ({0})' não pode ser removido devido ao seguinte erro: {2} + + + 'Não é possível acessar os serviços dependentes de '{1} ({0})' + + + Aguardando o serviço '{1} ({0})' iniciar... + + + Aguardando o serviço '{1} ({0})' ser interrompido... + + + Aguardando a suspensão{1} ({0})' do serviço... + + + Aguardando o serviço '{1} ({0})' ser retomado... + + + Falha ao iniciar o serviço '{1} ({0})'. + + + Falha ao parar o serviço '{1} ({0})'. + + + Falha ao suspender o serviço '{1} ({0})'. + + + Falha ao retomar o serviço '{1} ({0})'. + + + Falha ao abrir o SCManager devido ao seguinte erro: {0}. Execute o PowerShell como administrador e execute o comando novamente. + + + O tipo de inicialização '{0}' não tem suporte do {1}. + + + Não foi possível recuperar a propriedade '{1}' para o serviço '{0}': {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TestConnectionResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TestConnectionResources.pt-BR.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TestConnectionResources.pt-BR.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TestPathResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TestPathResources.pt-BR.resx new file mode 100644 index 00000000000..6587c518bcc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TestPathResources.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TimeZoneResources.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TimeZoneResources.pt-BR.resx new file mode 100644 index 00000000000..eb9de86b5ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/pt-BR/TimeZoneResources.pt-BR.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 + + + Não é possível definir o fuso horário local porque o nome '{0}' resolve para várias entradas. + + + O nome do fuso horário '{0}' não foi encontrado no computador local. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ClearRecycleBinResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ClearRecycleBinResources.ru.resx new file mode 100644 index 00000000000..35bbad73d6a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ClearRecycleBinResources.ru.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 + + + Все содержимое корзины + + + Все содержимое корзины для диска {0} + + + Очистка корзины + + + для диска {0} + + + для всех дисков + + + Не удается найти диск. Диск с именем {0} не существует. Запустите командлет {1}, чтобы просмотреть доступные в системе фиксированные диски. + + + Недопустимые входные данные. Поддерживаются следующие форматы: {0}, {1} или {2}. + + + Диск с именем {0} не является фиксированным диском и не поддерживает корзину. Запустите командлет {1}, чтобы просмотреть доступные в системе фиксированные диски. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ClipboardResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ClipboardResources.ru.resx new file mode 100644 index 00000000000..59bf0775854 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ClipboardResources.ru.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Установить строку "{0}" в буфер обмена. + + + Добавить строку "{0}" в буфер обмена. + + + Установить файл "{0}" в буфер обмена. + + + Добавить файл "{0}" в буфер обмена. + + + Установите файлы {0} в буфер обмена. + + + Добавлять файлы ({0}) в буфер обмена. + + + В буфере обмена нет содержимого, или формат содержимого несовместим. Установите входной объект в буфер обмена. + + + Буфер обмена очищен. + + + TextFormatType можно объединить только с текстовым форматом. + + + Необработанные файлы можно сочетать только с текстовым форматом или форматом FileDropList. + + + HTML можно сочетать только с текстовым HTML-форматом. + + + На этой платформе поддерживается только текстовый формат. + + + Буфер обмена не поддерживается на этой платформе. + + + Переключатель "-AsHtml" не поддерживается на этой платформе. + + + Параметр "-TextFormatType" поддерживает только текст на этой платформе. + + + Параметр "-Path" не поддерживается на этой платформе. + + + Параметр "-LiteralPath" не поддерживается на этой платформе. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/CmdletizationResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/CmdletizationResources.ru.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/CmdletizationResources.ru.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ComputerInfoResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ComputerInfoResources.ru.resx new file mode 100644 index 00000000000..522b61cb43a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ComputerInfoResources.ru.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 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ComputerResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ComputerResources.ru.resx new file mode 100644 index 00000000000..d7176c4e99a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ComputerResources.ru.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 + + + Данная функциональность не поддерживается в этой операционной системе. + + + Не удалось включить диск {0} . + + + Команда не может включить инфраструктуру восстановления компьютера на указанном компьютере, поскольку предоставленный диск недействителен. Введите действительный диск в поле "Диск", а затем повторите попытку. + + + Включите системный диск в список дисков. + + + Команда не может отключить инфраструктуру восстановления компьютера, поскольку предоставленный диск недействителен. Введите действительный диск в поле "Диск", а затем повторите попытку. + + + Команда не может отключить восстановление системы на {0} диске . Возможно, у вас недостаточно прав для выполнения этой операции. + + + Служба восстановления системы отключена. + + + Инфраструктура восстановления системы не может создать точку восстановления. + + + Последняя попытка восстановления компьютера не удалась. + + + Компьютер восстановлен до указанной точки восстановления. + + + Последняя попытка восстановления компьютера была прервана. + + + Команда не может найти точку восстановления " {0} ". Проверьте порядковый номер " {0} ", а затем повторите команду. + + + {0} ( {1} ) + + + Не удалось перезагрузить компьютер {0} со следующим сообщением об ошибке: {1} . + + + Эту команду невозможно выполнить на целевом компьютере (' {1} ') из-за следующей ошибки: {0} . {2} + + + Не удалось остановить компьютер {0} со следующим сообщением об ошибке: {1} . + + + Команда не может восстановить компьютер, поскольку " {0} " не был установлен в качестве допустимой точки восстановления. Введите действительную точку восстановления в параметре RestorePoint, а затем повторите попытку. + + + Изменения вступят в силу после перезагрузки компьютера {1} . + + + После выхода из домена вам потребуется знать пароль локальной учетной записи администратора для входа на этот компьютер. Вы хотите продолжить? + + + Следующее имя компьютера недействительно: {0} . Убедитесь, что имя компьютера не длиннее 255 символов, не содержит двух или более последовательных точек, не начинается с точки, не содержит только цифр и не содержит следующих символов: +{{|}} ~[\]^:;<=>?@!"#$%^`()+/, + + + Домен в имени компьютера ' {0} ' недействителен. Убедитесь, что домен существует и что имя является допустимым доменным именем. + + + Значение, указанное для параметра NewComputerName, совпадает со значением параметра ComputerName. Укажите другое значение для параметра NewComputerName. + + + "Пароль защищенного канала между ' {0} ' и ' {1} ' был сброшен". + + + Выполнение этой команды невозможно из-за следующей ошибки: служба не может быть запущена, поскольку она отключена или к ней не подключены включенные устройства. + + + Создание точки восстановления системы... + + + Создание точки восстановления системы... {0} % Завершено. + + + Выполнено. + + + Попробуйте следующие варианты и снова выполните команду. +1. Убедитесь, что целевой компьютер (' {0} ') запущен. +2. Укажите полное имя целевого компьютера (' {0} '). + + + Не удалось перезагрузить компьютер {0} . Права доступа {1} не могут быть предоставлены вызывающему процессу. + + + Включите {0} и перезагрузите компьютер. + + + Права доступа к локальному завершению работы + + + Права доступа для удаленного завершения работы + + + Не могу дождаться перезагрузки локального компьютера. При указании параметра Wait локальный компьютер игнорируется. + + + Параметры Timeout, For и Delay действительны только при указании параметра Wait. + + + Перезагрузка компьютеров... + + + Перезагрузка компьютера {0} + + + Завершено: {0} / {1} . + + + Проверка перезагрузки компьютера... + + + Ожидание подключения PowerShell... + + + Ожидание начала перезапуска... + + + Ожидание подключения WinRM... + + + Ожидание подключения WMI... + + + Перезагрузка завершена. + + + В настоящее время комбинированные типы услуг не поддерживаются. + + + Имя компьютера {0} не может быть разрешено, исключение: {1} . + + + Количество новых имен не равно количеству целевых компьютеров. + + + Пропустить компьютер ' {0} ' с новым именем ' {1} ', поскольку новое имя недействительно. Введенное новое имя компьютера имеет неправильный формат. Стандартные имена могут содержать буквы (az, AZ), цифры (0-9) и дефисы (-), но не пробелы и точки (.). Имя не может состоять исключительно из цифр и не может быть длиннее 63 символов. + + + Пропустить компьютер ' {0} ' с новым именем ' {1} ', поскольку новое имя совпадает с текущим именем. + + + Невозможно удалить компьютер ' {0} ', поскольку он не входит в домен. + + + Не удалось подключить компьютер ' {0} ' к рабочей группе ' {1} ' со следующим сообщением об ошибке: {2} + + + Невозможно удалить компьютер(ы) из домена, поскольку локальная сеть недоступна. + + + Не удалось переименовать компьютер ' {0} ' в ' {1} ' из-за следующего исключения: {2} . + + + Присоединиться к домену ' {0} ' + + + Присоединиться к рабочей группе ' {0} ' + + + Невозможно добавить компьютер ' {0} ' в домен ' {1} ', поскольку он уже находится в этом домене. + + + Невозможно добавить компьютер ' {0} ' в рабочую группу ' {1} ', поскольку он уже находится в этой рабочей группе. + + + Компьютер ' {0} ' успешно присоединился к рабочей группе ' {1} ', но не смог быть переименован в ' {2} ' со следующим сообщением об ошибке: ' {3} '. + + + Компьютер " {0} " был успешно отсоединен от домена " {1} ", но не смог присоединиться к рабочей группе " {2} " со следующим сообщением об ошибке: "{3}" . + + + Не удалось отсоединить компьютер ' {0} ' от домена ' {1} ' со следующим сообщением об ошибке: {2} . + + + Не удается установить WMI-соединение с компьютером ' {0} ' со следующим сообщением об ошибке: {1} . + + + Компьютер ' {0} ' не смог присоединиться к домену ' {1} ' из текущей рабочей группы ' {2} ' со следующим сообщением об ошибке: {3} . + + + Компьютер ' {0} ' успешно отсоединился от домена ' {1} ', но не смог присоединиться к новому домену ' {2} ' со следующим сообщением об ошибке: {3} . + + + Компьютер ' {0} ' успешно подключен к новому домену ' {1} ', но переименование его в ' {2} ' завершилось с ошибкой: {3} . + + + Флаг ' {0} ' действителен только в том случае, если указан флаг ' {1} '. + + + Невозможно переименовать несколько компьютеров. Параметр NewName действителен только в том случае, если указан один компьютер. + + + Не удается найти учетную запись компьютера для локального компьютера в домене {0} . + + + Не удается найти учетную запись компьютера для локального компьютера на контроллере домена {0} . + + + Невозможно получить информацию о домене локального компьютера из-за следующего исключения: {0} . + + + Не удается сбросить пароль защищенного канала для учетной записи компьютера в домене. Операция завершилась с ошибкой: {0} . + + + Сброс пароля защищенного канала для локального компьютера завершился с ошибкой: {0} . + + + Для сброса пароля защищенного канала на локальном компьютере требуются права администратора. Доступ запрещен. + + + Не удается сбросить пароль защищенного канала для учетной записи локального компьютера. Локальный компьютер в данный момент не входит в домен. + + + Имя компьютера в NetBIOS ограничено 15 байтами, что в данном случае составляет 15 символов. Имя NetBIOS будет сокращено до " {0} ", что может вызвать конфликты при разрешении имен NetBIOS. Вы хотите продолжить? + + + Имя NetBIOS будет усечено. + + + Указанное имя сервера {0} не может быть разрешено. + + + Создать новую точку восстановления системы невозможно, поскольку она уже была создана в течение последних {0} минут. Частоту создания точек восстановления можно изменить, создав значение DWORD 'SystemRestorePointCreationFrequency' в разделе реестра 'HKLM\Software\Microsoft\Windows NT\CurrentVersion\SystemRestore'. Значение этого ключа реестра указывает необходимый временной интервал (в минутах) между созданием двух точек восстановления. Значение по умолчанию — 1440 минут (24 часа). + + + Не удается получить объект WMI Win32_OperatingSystem. + + + Компьютер {0} пропускается. Не удалось получить LastBootUpTime через службу WMI со следующим сообщением об ошибке: {1} . + + + Не удается проверить защищенный канал для локального компьютера. Операция завершилась с ошибкой: {0} . + + + Попытка восстановить защищенный канал между локальным компьютером и доменом {0} не удалась. + + + Защищенный канал между локальным компьютером и доменом {0} был успешно восстановлен. + + + Защищенный канал связи между локальным компьютером и доменом {0} находится в хорошем состоянии. + + + Защищенный канал связи между локальным компьютером и доменом {0} разорван. + + + Не удается проверить пароль защищенного канала для локального компьютера. Локальный компьютер в данный момент не входит в домен. + + + Данная операция не может быть выполнена, поскольку API-интерфейсы восстановления системы не поддерживаются на платформе Advanced RISC Machine (ARM). + + + Компьютер не завершил перезагрузку в течение указанного периода времени. + + + Не удается подтвердить временной интервал для создания точки восстановления. Не удалось восстановить последнюю точку восстановления со следующим сообщением об ошибке: {0} . + + + Набор параметров AsJob не поддерживается. + + + {0} Параметр не поддерживается для CoreCLR. + + + Необходимая встроенная команда 'shutdown' не найдена. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/HotFixResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/HotFixResources.ru.resx new file mode 100644 index 00000000000..98f349a8ec4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/HotFixResources.ru.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 + + + Не удалось найти запрошенное исправление на компьютере "{0}". Проверьте введенные данные и запустите команду еще раз. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/NavigationResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/NavigationResources.ru.resx new file mode 100644 index 00000000000..bcc0d0b3658 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/NavigationResources.ru.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 + + + Указанный путь является контейнером с дочерними элементами. Вы хотите удалить этот контейнер и его дочерние элементы? + + + Удалить указанный элемент? + + + Не удается скопировать, так как указанное назначение уже существует. Перезаписать существующее содержимое? + + + Новый диск + + + Имя: {0} Поставщик: {1} Корень: {2} + + + Удалить диск + + + Имя: {0} Поставщик: {1} Корень: {2} + + + Не удается удалить диск {0}, так как он используется. + + + Элемент в {0} имеет дочерние элементы, а параметр Recurse не указан. Если продолжить, все дочерние элементы будут удалены вместе с элементом. Действительно продолжить? + + + Не удается удалить элемент в {0}, так как он используется. + + + Объект по указанному пути {0} не существует или был отфильтрован с помощью параметра -Include или -Exclude. + + + Настройка содержимого + + + Путь: {0} + + + Добавить содержимое + + + Путь: {0} + + + Не удается переместить элемент, так как элемент в {0} не существует. + + + Не удается переместить элемент, так как элемент в {0} используется. + + + Не удается переименовать, так как элемент в {0} не существует. + + + Не удается переименовать элемент в {0}, так как он используется. + + + Не удается проанализировать путь, так как у пути {0} не указан квалификатор. + + + Начало + + + Откат + + + Зафиксировать + + + Текущая транзакция + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ProcessCommandHelpResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ProcessCommandHelpResources.ru.resx new file mode 100644 index 00000000000..25f5aa87254 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ProcessCommandHelpResources.ru.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 + + + Отображает список процессов, запущенных в данный момент. + + + +ИД: -Id +[int[]] +[входные данные конвейера разрешены] +Список идентификаторов процессов, разделенных запятыми, указывает, какие процессы нужно получить + +Имя -ProcessName +[string[]] +[входные данные конвейера разрешены] +Список имен процессов, разделенных запятыми, указывает, какие процессы нужно получить + +Имя -Exclude +[ArrayList] +Список имен процессов, разделенных запятыми, которые нужно исключить из вывода. + +--- +Команда перечисляет процессы на локальном компьютере и выводит объекты System.Diagnostics.Process. Команда записывает объекты процесса в выходной конвейер по одному. Команда принимает из командной строки такие параметры, как ID(Идентификатор процесса) или Имя процесса. Команда возвращает соответствующий System.Diagnostics.Process для указанных параметров ID или ProcessName. + + + Исключение применяется только к имени процесса. + + + Возвращает все запущенные процессы. + + + Возвращает все процессы, имена которых начинаются с svc. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ProcessResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ProcessResources.ru.resx new file mode 100644 index 00000000000..9d77a6ddca1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ProcessResources.ru.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 + + + Не удается найти процесс "{0}". Проверьте имя процесса и вызовите командлет еще раз. + + + Не удается найти процесс "{0}". Попробуйте запустить команду с параметром -Id для поиска по идентификатору процесса. + + + Эту команду нельзя выполнить, так как отладчик не может быть присоединен к процессу "{0} ({1})". Укажите другой процесс и выполните команду. + + + Не удается найти процесс с идентификатором {1}. + + + Невозможно остановить процесс "{0} ({1})" из-за следующей ошибки: {2} + + + {0} ({1}) + + + {0} {1} + + + Не удается перечислить модули процесса "{0}". + + + Не удается получить сведения о версии файла для процесса "{0}". + + + Не удается получить сведения о модулях и версии файла для процесса "{0}". + + + Действительно выполнить операцию Stop-Process для следующего элемента: {0}({1})? + + + Указанный путь не является действительным приложением win32. Повторите попытку, используя UseShellExecute. + + + Эта команда остановила операцию "{0} ({1})" из-за следующей ошибки: {2}. + + + Эту команду нельзя выполнить, так как параметры перенаправления нельзя использовать с параметром UseShellExecute + + + Исключение при получении "Modules" или "FileVersion": "Эта функция не поддерживается для удаленных компьютеров.". + + + Эта команда не может присоединить отладчик к процессу из-за {0}, так как отладчик по умолчанию недоступен. + + + Эта команда остановила операцию, так как не может ожидать процесса "Бездействие системы". Укажите другой процесс и выполните команду еще раз. + + + Эта команда остановила операцию, так как не может ожидать саму себя. Укажите другой процесс и выполните команду еще раз. + + + Эта команда остановила операцию, так как процесс "{0} ({1})" не был остановлен в течение указанного времени ожидания. + + + Не удается выполнить эту команду из-за ошибки: {0} + + + Эту команду нельзя выполнить, так как введенное значение "{0}" не является допустимым приложением. Укажите допустимое приложение и выполните команду еще раз. + + + Эту команду нельзя выполнить, так как параметр "{0}" имеет недопустимое значение или не может использоваться с этой командой. Укажите допустимые входные данные и выполните команду еще раз. + + + Эту команду нельзя выполнить, так как "{0}" и "{1}" совпадают. Укажите разные входные данные и выполните команду еще раз. + + + Эту команду невозможно выполнить полностью, так как системе не удается найти всю необходимую информацию. + + + Не удалось получить новый дескриптор процесса: "{0}". У выведенного объекта Process некоторые свойства и методы могут работать неправильно. + + + Эту команду нельзя выполнить из-за ошибки 1783. Возможная причина этой ошибки — использование несуществующего пользователя "{0}". Укажите допустимого пользователя и выполните команду еще раз. + + + Ошибка при добавлении "{0}" в сеть: {1} + + + Ошибка при удалении "{0}" из сети: {1} + + + Ошибка при переименовании "{0}": {1} + + + Параметры "{0}" и "{1}" нельзя задать одновременно. + + + Невозможно отладить процесс "{0} ({1})" из-за следующей ошибки: {2} + + + У пользователя нет доступа к запрошенной информации. + + + Указан недопустимый параметр. + + + У пользователя недостаточно прав. + + + Неизвестный сбой. + + + Указанный путь не существует. + + + Параметр "{0}" не поддерживается для командлета "{1}" в этом выпуске Windows. + + + Параметр "{0}" не поддерживается для командлета "{1}" в этом выпуске PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/ServiceResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ServiceResources.ru.resx new file mode 100644 index 00000000000..9bc8d3d391f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/ServiceResources.ru.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}) + + + Не удается найти службу с именем {0}. + + + Не удается найти службу с отображаемым именем {1}. + + + Не удается остановить службу {1} ({0}), так как от нее зависят другие службы. Ее можно остановить, только если установлен флаг Force. + + + Не удается остановить службу {1} ({0}), так как от нее зависят другие службы. + + + Невозможно остановить службу {1} ({0}) из-за следующей ошибки: {2} + + + Невозможно запустить службу {1} ({0}) из-за следующей ошибки: {2} + + + Невозможно приостановить службу {1} ({0}) из-за следующей ошибки: {2} + + + Не удается приостановить службу {1} ({0}), так как служба не поддерживает приостановку или возобновление. + + + Службу {1} ({0}) нельзя приостановить, так как она сейчас не запущена. + + + Невозможно возобновить работу службы {1} ({0}) из-за следующей ошибки: {2} + + + Не удается возобновить службу {1} ({0}), так как служба не поддерживает приостановку или возобновление. + + + Работу службы {1} ({0}) нельзя возобновить, так как она сейчас не запущена. + + + Невозможно настроить службу {1} ({0}) из-за следующей ошибки: {2} + + + Невозможно настроить описание службы {1} ({0}) из-за следующей ошибки: {2} + + + Не удается настроить автоматический отложенный запуск ля службы {1} ({0}) из-за следующей ошибки: {2} + + + Не удалось настроить дескриптор безопасности службы {0} из-за следующей ошибки: {1} + + + Невозможно создать службу {1} ({0}) из-за следующей ошибки: {2} + + + Служба {1} ({0}) создана, но не удалось настроить ее описание из-за следующей ошибки: {2} + + + Служба {1} ({0}) создана, но не удалось настроить тип запуска "Автоматически (отложенный запуск)" из-за следующей ошибки: {2} + + + Невозможно удалить службу {1} ({0}) из-за следующей ошибки: {2} + + + Не удается получить доступ к зависимым службам {1} ({0}) + + + Ожидание запуска службы {1} ({0})… + + + Ожидание остановки службы {1} ({0})… + + + Ожидание приостановки службы {1} ({0})… + + + Ожидание возобновления службы {1} ({0})... + + + Не удалось запустить службу {1} ({0}). + + + Не удалось остановить службу {1} ({0}). + + + Не удалось приостановить службу {1} ({0}). + + + Не удалось возобновить работу службы {1} ({0}). + + + Не удалось открыть SCManager из-за следующей ошибки: {0}. Запустите PowerShell от имени администратора и повторите команду. + + + Тип запуска {0} не поддерживается {1}. + + + Не удалось получить свойство {1} для службы {0}: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/TestConnectionResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/TestConnectionResources.ru.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/TestConnectionResources.ru.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/TestPathResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/TestPathResources.ru.resx new file mode 100644 index 00000000000..21a1e1eebfe --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/TestPathResources.ru.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 + + + Указанный аргумент Path имеет значение null или представляет собой пустую коллекцию. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/ru/TimeZoneResources.ru.resx b/src/Microsoft.PowerShell.Commands.Management/resources/ru/TimeZoneResources.ru.resx new file mode 100644 index 00000000000..a5b4ef3662d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/ru/TimeZoneResources.ru.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 + + + Невозможно задать локальный часовой пояс, так как имя {0} соответствует нескольким записям. + + + Имя часового пояса {0} не найдено на локальном компьютере. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ClearRecycleBinResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ClearRecycleBinResources.tr.resx new file mode 100644 index 00000000000..621b26b07a6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ClearRecycleBinResources.tr.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 + + + Geri Dönüşüm Kutusu’ndaki tüm içerikler + + + '{0}' sürücüsündeki Geri Dönüşüm Kutusu'nun tüm içeriği + + + Geri Dönüşüm Kutusu'nu Boşaltılıyor + + + '{0}' sürücüsü için + + + tüm sürücüler için + + + Sürücü bulunamıyor. '{0}' adlı bir sürücü yok. Sistemde bulunan Sabit sürücüleri görmek için lütfen '{1}' cmdlet'ini çalıştırın. + + + Geçersiz giriş. Aşağıdaki biçimler desteklenmektedir: '{0}', '{1}' veya '{2}'. + + + '{0}' adlı sürücü, Sabit sürücü değildir ve Geri Dönüşüm Kutusu'nu desteklemez. Sistemde bulunan Sabit sürücüleri görmek için lütfen '{1}' cmdlet'ini çalıştırın. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ClipboardResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ClipboardResources.tr.resx new file mode 100644 index 00000000000..f9ea4816390 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ClipboardResources.tr.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{0}' dizesini panoya ayarlayın. + + + '{0}' dizesini panoya ekleyin. + + + '{0}' dosyasını panoya ayarlayın. + + + '{0}' dosyasını panoya ekleyin. + + + {0} dosyayı panoya ayarlayın. + + + {0} dosyayı panoya ekleyin. + + + Panoda içerik yok ya da içeriğin biçimi uyumlu değil. Giriş nesnesini Panoya ayarlayın. + + + Pano temizlendi. + + + TextFormatType yalnızca Text biçimiyle birleştirilebilir. + + + Raw yalnızca Text veya FileDropList biçimiyle birleştirilebilir. + + + Html yalnızca Html Text biçimiyle birleştirilebilir. + + + Bu platformda yalnızca Text biçimi desteklenir. + + + Pano bu platformda desteklenmiyor. + + + '-AsHtml' anahtarı bu platformda desteklenmiyor. + + + '-TextFormatType' parametresi bu platformda yalnızca 'Text' biçimini destekler. + + + '-Path' parametresi bu platformda desteklenmiyor. + + + '-LiteralPath' parametresi bu platformda desteklenmiyor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/CmdletizationResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/CmdletizationResources.tr.resx new file mode 100644 index 00000000000..360c91b56b9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/CmdletizationResources.tr.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 + + + {1} CIM sunucusunda {0} sınıfı bulunamadı. Cmdlet Definition XML'deki ClassName xml özniteliğinin değerini doğrulayın ve yeniden deneyin. Geçerli sınıf adı örneği: 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". + + + + {0} CIM nesnesinde {1} CIM yöntemi + {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 + + + {1} çalıştırılamadı. {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 + + + Aşağıdaki işlem çalıştırılıyor: {0}. + {0} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + CIM cmdlet'leri AsJob parametresiyle birlikte {0} parametresini desteklemiyor. Bu parametrelerden birini kaldırın ve yeniden deneyin. + {StrContains="AsJob"} +{0} is a placeholder for 'WhatIf' or 'Confirm' cmdlet parameters + + + {1} CIM sunucusundaki {0} sınıfının örneklerine yönelik CIM sorgusu: {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". + + + CIM yöntemi şu hata kodunu döndürdü: {0} + {0} is a placeholder for an error code returned from a CIM method. Example: 123 + + + {1} CIM sunucusundaki {0} sınıfı tarafından kullanıma sunulan {2} CIM yöntemi + {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 dahili türü + + + WQL değişmez değeri + + + {0} CIM nesnesinin {2} yöntemindeki {1} çıkış parametresi bulunamıyor. Cmdlet Definition XML'deki ParameterName özniteliğinin değerini doğrulayın ve yeniden deneyin. + {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. + + + + {0}, eşleşen {1} nesnesi bulamadı. Sorgu parametrelerini doğrulayın ve yeniden deneyin. + + + '{1}' değerine eşit olan '{0}' özelliğine sahip hiçbir {2} nesnesi bulunamadı. Özelliğin değerini doğrulayın ve yeniden deneyin. + + + {0} özelliğinin türü ({1}), Cmdlet Definition XML'de bildirilen türle ilişkilendirilmiş CIM türüyle ({2}) eşleşmiyor. + + + {1} CIM sunucusunda {0} sınıfının ilişkili örneğini numaralandırmaya yönelik CIM sorgusu + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + {1} CIM sunucusunda yer alan ve {2} örneğiyle ilişkilendirilen {0} sınıfının örneklerini numaralandırmaya yönelik CIM sorgusu + {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]". + + + {1} sunucusu şu anda meşgul olduğundan {0} komutu tamamlanamıyor. Komut {2:f2} saniye içinde otomatik olarak sürdürülecek. + {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 + + + CIM sunucusuna bağlanamıyor. {0} + {0} is a placeholder for a more detailed error message. + + + Cmdlet, hata ayıklama iletileri için Inquire eylemini tam olarak desteklemiyor. İstem sırasında cmdlet işlemi devam edecek. -Debug anahtarı veya $DebugPreference değişkeni yoluyla farklı bir eylem tercihi yapın ve yeniden deneyin. + {StrContains="Debug"} {StrContains="DebugPreference"} {StrContains="Inquire"} + + + Cmdlet, uyarılar için Inquire eylemini tam olarak desteklemiyor. İstem sırasında cmdlet işlemi devam edecek. -WarningAction parametresi ya da $WarningPreference değişkeni aracılığıyla farklı bir eylem tercihi belirtin ve yeniden deneyin. + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Inquire"} + + + Bu cmdlet, uyarılar için Stop eylemini tam olarak desteklemiyor. Cmdlet işlemi bir gecikmeyle durdurulacak. -WarningAction parametresi ya da $WarningPreference değişkeni aracılığıyla farklı bir eylem tercihi belirtin ve yeniden deneyin. + {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}: CIM sunucusundaki bir CimSession, {1} anahtarını desteklemeyen DCOM protokolünü kullanıyor. + {0} is a placeholder for a name of a computer +{1} is a placeholder for 'Confirm' or 'WhatIf' + + + '{1}' ile eşleşen '{0}' özelliğine sahip hiçbir {2} nesnesi bulunamadı. Özelliğin değerini doğrulayın ve yeniden deneyin. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ComputerInfoResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ComputerInfoResources.tr.resx new file mode 100644 index 00000000000..dd72ff0ebe6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ComputerInfoResources.tr.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 + + + İşletim sistemi bilgileri yükleniyor + + + Çalışırken yama uygulama bilgileri yükleniyor + + + Kayıt defteri bilgileri yükleniyor + + + BIOS bilgileri yükleniyor + + + Anakart bilgileri yükleniyor + + + Bilgisayar bilgileri yükleniyor + + + İşlemci bilgileri yükleniyor + + + Ağ bağdaştırıcısı bilgileri yükleniyor + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ComputerResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ComputerResources.tr.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ComputerResources.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/HotFixResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/HotFixResources.tr.resx new file mode 100644 index 00000000000..8957136c16d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/HotFixResources.tr.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 + + + İstenen hotfix'i '{0}' bilgisayarında bulamıyor. Girişi doğrulayın ve komutu yeniden çalıştırın. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/NavigationResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/NavigationResources.tr.resx new file mode 100644 index 00000000000..54cd02c830b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/NavigationResources.tr.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 + + + Belirtilen yol, alt öğeleri olan bir kapsayıcıdır. Bu kapsayıcıyı ve alt öğelerini silmek istiyor musunuz? + + + Belirtilen öğeyi silmek istiyor musunuz? + + + Belirtilen hedef zaten var olduğu için kopyalanamıyor. Var olan içeriğin üzerine yazmak istiyor musunuz? + + + Yeni sürücü + + + Ad: {0} Sağlayıcı: {1} Kök: {2} + + + Sürücüyü kaldır + + + Ad: {0} Sağlayıcı: {1} Kök: {2} + + + ‘{0}' sürücüsü kullanımda olduğu için kaldırılamıyor. + + + {0} konumundaki öğenin alt öğeleri var ve Recurse parametresi belirtilmedi. Devam ederseniz, tüm çocuklar öğe ile birlikte kaldırılacaktır. Devam etmek istediğinizden emin misiniz? + + + ‘{0}' konumundaki öğe kullanımda olduğu için kaldırılamıyor. + + + Belirtilen {0} yolundaki nesne yok veya -Include ya da -Exclude parametresi tarafından filtrelenmiş. + + + İçerik Ayarla + + + Yol: {0} + + + İçerik Ekle + + + Yol: {0} + + + ‘{0}' konumundaki öğe bulunamadığı için öğe taşınamıyor. + + + ‘{0}' konumundaki öğe kullanımda olduğu için öğe taşınamıyor. + + + Belirtilen konumdaki '{0}' öğesi yeniden adlandırılamıyor çünkü bu öğe yok. + + + ‘{0}' konumundaki öğe kullanımda olduğu için yeniden adlandırılamıyor. + + + ‘{0}' yolu bir niteleyici belirtilmediği için ayrıştırılamıyor. + + + Başlat + + + Geri alma + + + İşle + + + Geçerli işlem + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ProcessCommandHelpResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ProcessCommandHelpResources.tr.resx new file mode 100644 index 00000000000..59607b3dba9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ProcessCommandHelpResources.tr.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 + + + O anda çalışan işlemleri listeler. + + + +-Id kimliği +[int[]] +[pipeline input allowed] +Alınacak işlemleri belirten işlem kimliklerinin virgülle ayrılmış listesi + +-ProcessName adı +[string[]] +[pipeline input allowed] +Alınacak işlemleri belirten işlem kimliklerinin virgülle ayrılmış listesi + +-Exclude adı +[ArrayList] +Çıkıştan hariç tutulacak işlem adlarının virgülle ayrılmış listesi. + +--- +Komut, yerel bilgisayardaki işlemleri listeler ve System.Diagnostics.Process nesnelerini çıktı olarak verir. Komut, işlem nesnelerini çıktı işlem hattına teker teker yazar. Komut, komut satırından ID (İşlem Kimliği) ya da Process Name gibi parametreleri alır. Komut, sağlanan ID veya ProcessName parametreleri için ilgili system.diagnostics.process nesnesini döndürür. + + + Hariç tutma yalnızca işlem adı için çalışır. + + + Tüm çalışan işlemleri döndürür. + + + Adları svc ile başlayan tüm işlemleri döndürür. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ProcessResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ProcessResources.tr.resx new file mode 100644 index 00000000000..fc9a1c466ee --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ProcessResources.tr.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 + + + "{0}" adlı bir işlem bulunamıyor. İşlem adını doğrulayın ve cmdlet'i yeniden çağırın. + + + "{0}" adlı bir işlem bulunamıyor. İşlemleri kimliğe göre aramak için -Id ile çalıştırmayı deneyin. + + + Hata ayıklayıcısı "{0} ({1})" işlemine eklenemediğinden bu komut çalıştırılamıyor. Başka bir işlem belirtin ve komutunuzu çalıştırın. + + + {1} işlem tanımlayıcısına sahip bir işlem bulunamadı. + + + Şu hata nedeniyle "{0} ({1})" işlemi durdurulamıyor: {2} + + + {0} ({1}) + + + {0} {1} + + + "{0}" işleminin modülleri numaralandırılamıyor. + + + "{0}" işleminin dosya sürümü bilgileri numaralandırılamıyor. + + + "{0}" işleminin modülleri ve dosya sürümü bilgileri numaralandırılamıyor. + + + {0}({1}) öğesinde Stop-Process işlemini gerçekleştirmek istediğinizden emin misiniz? + + + Belirtilen yol geçerli bir win32 uygulaması değil. UseShellExecute ile yeniden deneyin. + + + Şu hata nedeniyle bu komut "{0} ({1})" operasyonunu durdurdu: {2}. + + + Redirection parametreleri UseShellExecute parametresiyle kullanılamadığından bu komut çalıştırılamıyor + + + "Modules" veya "FileVersion" alınırken özel durum oluştu: "Uzak bilgisayarlar için bu özellik desteklenmiyor.". + + + Varsayılan hata ayıklayıcı bulunmadığından, bu komut {0} nedeniyle hata ayıklayıcıyı işleme ekleyemiyor. + + + Bu komut 'Sistem Boşta' işleminde bekleyemediği için operasyonu durdurdu. Başka bir işlem belirtin ve komutunuzu yeniden çalıştırın. + + + Bu komut kendi çalışmasını bekleyemediği için operasyonu durdurdu. Başka bir işlem belirtin ve komutunuzu yeniden çalıştırın. + + + "{0} ({1})" işlemi belirtilen zaman aşımında durdurulamadığı için bu komut operasyonu durdurdu. + + + Bu komut şu hata nedeniyle çalıştırılamıyor: {0} + + + "{0}" girişi geçerli bir Uygulama olmadığından bu komut çalıştırılamıyor. Geçerli bir uygulama belirtin ve komutunuzu yeniden çalıştırın. + + + "{0}" parametresinin değeri geçerli olmadığından veya bu komutla kullanılamadığından, bu komut çalıştırılamıyor. Geçerli bir giriş sağlayın ve komutunuzu yeniden çalıştırın. + + + "{0}" ve "{1}" aynı olduğundan bu komut çalıştırılamıyor. Farklı girişler sağlayın ve komutunuzu yeniden çalıştırın. + + + Sistem gerekli bilgilerin tümünü bulamadığı için bu komut tamamen çalıştırılamıyor. + + + Yeni işlem tanıtıcısı alınamadı: "{0}". Çıktısı alınan Process nesnesinin bazı özellikleri ve yöntemleri düzgün çalışmıyor olabilir. + + + Bu komut 1783 hatası nedeniyle çalıştırılamıyor. Bu hatanın olası nedeni, mevcut olmayan "{0}" kullanıcısının kullanılması olabilir. Lütfen geçerli bir kullanıcı belirtin ve komutunuzu yeniden çalıştırın. + + + Ağa '{0}' eklenirken hata oluştu: {1} + + + '{0}' ağdan kaldırılırken hata oluştu: {1} + + + '{0}' yeniden adlandırılırken hata oluştu: {1} + + + "{0}" ve "{1}" parametreleri aynı anda belirtilemez. + + + Şu hata nedeniyle "{0} ({1})" işleminde hata ayıklaması yapılamıyor: {2} + + + Kullanıcının istenen bilgilere erişimi yok. + + + Belirtilen parametre geçerli değil. + + + Kullanıcının yeterli ayrıcalığı yok. + + + Bilinmeyen hata. + + + Belirtilen yol yok. + + + '{0}' parametresi, Windows'un bu sürümünde '{1}' cmdlet'inde desteklenmiyor. + + + '{0}' parametresi, PowerShell'in bu sürümünde '{1}' cmdlet'inde desteklenmiyor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/ServiceResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ServiceResources.tr.resx new file mode 100644 index 00000000000..9cc7f1d41e7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/ServiceResources.tr.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}) + + + ‘{0}' hizmet adıyla hiçbir hizmet bulunamadı. + + + Görünen adı '{1}' olan hiçbir hizmet bulunamadı. + + + Bağımlı hizmetleri olduğu için '{1} ({0})' hizmeti durdurulamıyor. Force bayrağı ayarlanmışsa yalnızca durdurulabilir. + + + Bağımlı hizmetleri olduğu için '{1} ({0})' hizmeti durdurulamıyor. + + + ‘{1} ({0})' hizmeti aşağıdaki hata nedeniyle durdurulamıyor: {2} + + + ‘{1} ({0})' hizmeti aşağıdaki hata nedeniyle başlatılamıyor: {2} + + + ‘{1} ({0})' hizmeti aşağıdaki hata nedeniyle askıya alınamıyor: {2} + + + ‘{1} ({0})' hizmeti, hizmet askıya alınmayı veya sürdürülmeyi desteklemediği için askıya alınamıyor. + + + ‘{1} ({0})' hizmeti şu anda çalışmadığı için duraklatılamaz. + + + Aşağıdaki hata nedeniyle '{1} ({0})' hizmeti sürdürülemiyor: {2} + + + ‘{1} ({0})' hizmeti, hizmet askıya alınmayı veya sürdürülmeyi desteklemediği için sürdürülemiyor. + + + ‘{1} ({0})' hizmeti şu anda çalışmadığı için sürdürülemiyor. + + + ‘{1} ({0})' hizmeti aşağıdaki hata nedeniyle yapılandırılamıyor: {2} + + + ‘{1} ({0})' hizmetinin açıklaması aşağıdaki hata nedeniyle yapılandırılamıyor: {2} + + + ‘{1} ({0})' hizmeti otomatik (gecikmeli başlatma) aşağıdaki hata nedeniyle yapılandırılamıyor: {2} + + + ‘{0}' hizmetinin güvenlik tanımlayıcısı aşağıdaki hata nedeniyle yapılandırılamıyor: {1} + + + ‘{1} ({0})' hizmeti aşağıdaki hata nedeniyle oluşturulamıyor: {2} + + + ‘{1} ({0})' hizmeti oluşturuldu, ancak açıklaması aşağıdaki hata nedeniyle yapılandırılamıyor: {2} + + + ‘{1} ({0})' hizmeti oluşturuldu, ancak 'Automatic (Delayed Start)' Startuptype'ı aşağıdaki hata nedeniyle yapılandırılamadı: {2} + + + ‘{1} ({0})' hizmeti aşağıdaki hata nedeniyle kaldırılamıyor: {2} + + + ‘{1} ({0})' hizmetinin bağımlı hizmetlerine erişilemiyor + + + ‘{1} ({0})' hizmetinin başlatılması bekleniyor... + + + Bekliyor: '{1} ({0})' hizmetinin durdurulması... + + + ‘{1} ({0})' hizmetinin askıya alınması bekleniyor... + + + ‘{1} ({0})' hizmetinin sürdürülmesi bekleniyor... + + + ‘{1} ({0})' hizmeti başlatılamadı. + + + ‘{1} ({0})' hizmeti durdurma başarısız. + + + ‘{1} ({0})' hizmeti askıya alma başarısız. + + + ‘{1} ({0})' hizmeti sürdürme başarısız. + + + Aşağıdaki hata nedeniyle SCManager açılamadı: {0}. Windows PowerShell'i yönetici olarak çalıştırın ve komutunuzu yeniden çalıştırın. + + + ‘{0}' önyükleme türü {1} tarafından desteklenmiyor. + + + ‘{1}' özelliği '{0}' hizmeti için alınamadı: {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/TestConnectionResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/TestConnectionResources.tr.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/TestConnectionResources.tr.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/TestPathResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/TestPathResources.tr.resx new file mode 100644 index 00000000000..6587c518bcc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/TestPathResources.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/tr/TimeZoneResources.tr.resx b/src/Microsoft.PowerShell.Commands.Management/resources/tr/TimeZoneResources.tr.resx new file mode 100644 index 00000000000..efdb3278968 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/tr/TimeZoneResources.tr.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 + + + Adı '{0}' birden çok girdiye çözümlendiği için yerel saat dilimi ayarlanamıyor. + + + Yerel bilgisayarda '{0}' saat dilimi adı bulunamadı. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ClearRecycleBinResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ClearRecycleBinResources.zh-Hans.resx new file mode 100644 index 00000000000..ee1eb3b15e3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ClearRecycleBinResources.zh-Hans.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 + + + 回收站的所有内容 + + + “{0}”驱动器回收站的所有内容 + + + 正在清除回收站 + + + 对于“{0}”驱动器 + + + 对于所有驱动器 + + + 找不到驱动器。名为“{0}”的驱动器不存在。请运行“{1}”cmdlet 以查看系统中可用的固定驱动器。 + + + 输入无效。支持以下文件格式:“{0}”、“{1}”或“{2}”。 + + + 名为“{0}”的驱动器不是固定驱动器,不支持回收站。请运行“{1}”cmdlet 以查看系统中可用的固定驱动器。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ClipboardResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ClipboardResources.zh-Hans.resx new file mode 100644 index 00000000000..4ed9d404583 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ClipboardResources.zh-Hans.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 将字符串 '{0}' 放入剪贴板。 + + + 将字符串 '{0}' 追加到剪贴板。 + + + 将文件“{0}”放入剪贴板。 + + + 将文件“{0}”追加到剪贴板。 + + + 将 {0} 个文件放入剪贴板。 + + + 将 {0} 个文件追加到剪贴板。 + + + 剪贴板中没有内容,或内容格式不兼容。请将输入对象放入剪贴板。 + + + 已清除剪贴板。 + + + TextFormatType 只能与 Text 格式组合使用。 + + + Raw 只能与 Text 或 FileDropList 格式组合使用。 + + + Html 只能与 Html Text 格式组合使用。 + + + 此平台仅支持 Text 格式。 + + + 此平台不支持剪贴板。 + + + 此平台不支持 '-AsHtml' 开关。 + + + '-TextFormatType' 参数在此平台上仅支持 'Text'。 + + + 此平台不支持 '-Path' 参数。 + + + 此平台上不支持 '-LiteralPath' 参数。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/CmdletizationResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/CmdletizationResources.zh-Hans.resx new file mode 100644 index 00000000000..e94a8901bd9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/CmdletizationResources.zh-Hans.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 + + + 在 {1} CIM 服务器上找不到 {0} 类。 请验证 Cmdlet Definition XML 中 ClassName 属性的值,然后重试。有效的类名示例: 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 方法 {1} 位于 {0} CIM 对象上 + {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 + + + 未能运行 {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 + + + 正在运行以下操作: {0}。 + {0} is a placeholder for a description of CIM operation. This most likely comes from CimJob_MethodDescription or CimJob_QueryDescription + + + CIM cmdlet 不支持 {0} 参数和 AsJob 参数同时使用。 请删除其中一个参数,然后重试。 + {StrContains="AsJob"} +{0} is a placeholder for 'WhatIf' or 'Confirm' cmdlet parameters + + + 用于获取位于 {1} CIM 服务器上 {0} 类实例的 CIM 查询: {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". + + + CIM 方法返回了以下错误代码: {0} + {0} is a placeholder for an error code returned from a CIM method. Example: 123 + + + 位于 {1} CIM 服务器上、由 {0} 类公开的 {2} CIM 方法 + {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 内在类型 + + + WQL 字面量 + + + 找不到 {0} CIM 对象的 {1} 方法的 {2} 输出参数。 请验证 Cmdlet Definition XML 中 ParameterName 属性的值,然后重试。 + {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. + + + + {0} 未找到匹配的 {1} 对象。请验证查询参数,然后重试。 + + + 找不到属性“{0}”与“{1}”等效的“{2}”对象。 请验证属性值,然后重试。 + + + Cmdlet Definition XML 中声明的类型所对应的 CIM 类型({2})与 {1} 属性({0})的类型不匹配。 + + + 用于枚举位于 {1} CIM 服务器上 {0} 类关联实例的 CIM 查询 + {0} is a placeholder for a name of a CIM class. Example: "Win32_Process". +{1} is a placeholder for a server name. Example: "localhost". + + + 用于枚举位于 {1} CIM 服务器上、与以下实例关联的 {0} 类实例的 CIM 查询: {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]". + + + 无法完成 {0} 命令,因为 {1} 服务器当前正忙。 该命令将在 {2:f2} 秒后自动恢复。 + {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 + + + 无法连接到 CIM 服务器。{0} + {0} is a placeholder for a more detailed error message. + + + cmdlet 不完全支持调试消息的 Inquire 操作。 提示期间,cmdlet 操作将继续。 请通过 -Debug 开关或 $DebugPreference 变量选择其他操作首选项,然后重试。 + {StrContains="Debug"} {StrContains="DebugPreference"} {StrContains="Inquire"} + + + cmdlet 不完全支持警报的 Inquire 操作。 提示期间,cmdlet 操作将继续。 请通过 -WarningAction 参数或 $WarningPreference 变量选择其他操作首选项,然后重试。 + {StrContains="WarningAction"} {StrContains="WarningPreference"} {StrContains="Inquire"} + + + cmdlet 不完全支持警报的 Stop 操作。 cmdlet 操作将延迟停止。 请通过 -WarningAction 参数或 $WarningPreference 变量选择其他操作首选项,然后重试。 + {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}: 连接到 CIM 服务器的 CimSession 使用 DCOM 协议,该协议不支持“{1}”开关。 + {0} is a placeholder for a name of a computer +{1} is a placeholder for 'Confirm' or 'WhatIf' + + + 找不到属性“{0}”与“{1}”匹配的“{2}”对象。 请验证属性值,然后重试。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ComputerInfoResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ComputerInfoResources.zh-Hans.resx new file mode 100644 index 00000000000..522b61cb43a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ComputerInfoResources.zh-Hans.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 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ComputerResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ComputerResources.zh-Hans.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ComputerResources.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/HotFixResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/HotFixResources.zh-Hans.resx new file mode 100644 index 00000000000..222ea0b01ff --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/HotFixResources.zh-Hans.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 + + + 在“{0}”计算机上找不到请求的修补程序。验证输入并再次运行该命令。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/NavigationResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/NavigationResources.zh-Hans.resx new file mode 100644 index 00000000000..312e3ab559a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/NavigationResources.zh-Hans.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 + + + 指定的路径是一个包含子项的容器。是否要删除此容器及其子项? + + + 是否要删除指定项? + + + 无法复制,因为指定的目标已存在。是否要覆盖现有内容? + + + 新驱动器 + + + 名称: {0} 提供程序: {1} 根目录: {2} + + + 移除驱动器 + + + 名称: {0} 提供程序: {1} 根目录: {2} + + + 无法移除驱动器“{0}”,因为它正在使用中。 + + + {0} 处的项具有子项,并且未指定 Recurse 参数。如果继续,所有子项都将随该项一起移除。是否确定要继续? + + + 无法移除“{0}”处的项,因为它正在使用中。 + + + 指定路径 {0} 处的对象不存在,或者已被 -Include 或 -Exclude 参数筛选。 + + + 设置内容 + + + 路径: {0} + + + 添加内容 + + + 路径: {0} + + + 无法移动项,因为“{0}”处的项不存在。 + + + 无法移动项,因为“{0}”处的项正在使用中。 + + + 无法重命名,因为“{0}”处的项不存在。 + + + 无法重命名“{0}”处的项,因为它正在使用中。 + + + 无法解析路径,因为路径“{0}”未指定限定符。 + + + 开始 + + + 回滚 + + + 提交 + + + 当前事务 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ProcessCommandHelpResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ProcessCommandHelpResources.zh-Hans.resx new file mode 100644 index 00000000000..22e570ecf07 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ProcessCommandHelpResources.zh-Hans.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 + + + 列出当前正在运行的进程。 + + + +-Id id +[int[]] +[pipeline input allowed] +以逗号分隔的进程标识符列表,用于指定要获取的进程 + +-ProcessName 名称 +[string[]] +[pipeline input allowed] +以逗号分隔的进程名称列表,用于指定要获取的进程 + +-排除名称 +[ArrayList] +要从输出中排除的进程名称的逗号分隔列表。 + +--- +该命令枚举本地计算机上的进程,并输出 System.Diagnostics.Process 对象。该命令一次将一个进程对象写入输出管道。该命令从命令行获取 ID (进程标识符)或进程名称等参数。该命令返回与所提供的 ID 或 ProcessName 参数对应的 system.diagnostics.process。 + + + 排除仅适用于进程名称。 + + + 返回所有正在运行的进程。 + + + 返回所有名称以 svc. 开头的进程。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ProcessResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ProcessResources.zh-Hans.resx new file mode 100644 index 00000000000..2788b2a2542 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ProcessResources.zh-Hans.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 + + + 找不到名为“{0}”的进程。验证进程名称,然后再次调用该 cmdlet。 + + + 找不到名为“{0}”的进程。尝试使用 -Id 运行以按进程 ID 进行搜索。 + + + 无法运行此命令,因为无法将调试器附加到进程“{0} ({1})”。指定其他进程,然后运行命令。 + + + 找不到进程标识符为 {1} 的进程。 + + + 由于以下错误,无法停止进程“{0} ({1})”: {2} + + + {0} ({1}) + + + {0} {1} + + + 无法枚举“{0}”进程的模块。 + + + 无法枚举“{0}”进程的文件版本信息。 + + + 无法枚举“{0}”进程的模块和文件版本信息。 + + + 是否确实要对以下项执行停止进程操作: {0}({1})? + + + 指定的路径不是有效的 win32 应用程序。请使用 UseShellExecute 重试。 + + + 由于以下错误,此命令已停止“{0} ({1})”的操作: {2}。 + + + 无法运行此命令,因为 Redirection 参数不能与 UseShellExecute 参数一起使用 + + + 获取 "Modules" 或 "FileVersion" 时出现异常:“远程计算机不支持此功能。”。 + + + 此命令由于 {0} 无法将调试程序附加到进程,因为没有可用的默认调试程序。 + + + 此命令已停止操作,因为它无法等待“系统空闲”进程。指定其他进程,然后再次运行命令。 + + + 此命令已停止操作,因为它无法等待其自身。指定其他进程,然后再次运行命令。 + + + 此命令已停止操作,因为进程“{0} ({1})”未在指定的超时内停止。 + + + 由于以下错误,无法运行此命令: {0} + + + 无法运行此命令,因为输入“{0}”不是有效的应用程序。 提供有效的应用程序,然后再次运行命令。 + + + 无法运行此命令,因为参数“{0}”的值无效或无法与此命令一起使用。提供有效的输入,然后再次运行命令。 + + + 无法运行此命令,因为“{0}”和“{1}”相同。提供不同的输入并再次运行命令。 + + + 无法完整运行此命令,因为系统找不到所需的所有信息。 + + + 未能检索新的进程句柄:“{0}”。输出的 Process 对象可能具有一些无法正常工作的属性和方法。 + + + 由于错误 1783,无法运行此命令。此错误的可能原因可能是使用了不存在的用户“{0}”。请提供有效的用户,然后再次运行命令。 + + + 将“{0}”添加到网络时出错: {1} + + + 从网络中移除“{0}”时出错: {1} + + + 重命名“{0}”时出错: {1} + + + 不能同时指定参数“{0}”和“{1}”。 + + + 由于以下错误,无法调试进程“{0} ({1})”: {2} + + + 用户无权访问请求的信息。 + + + 指定的参数无效。 + + + 用户权限不足。 + + + 未知故障。 + + + 指定的路径不存在。 + + + 此版本 Windows 上的 cmdlet“{1}”不支持参数“{0}”。 + + + 此版本 PowerShell 上的 cmdlet“{1}”不支持参数“{0}”。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ServiceResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ServiceResources.zh-Hans.resx new file mode 100644 index 00000000000..5947a8d3126 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/ServiceResources.zh-Hans.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}) + + + 找不到任何服务名称为 '{0}' 的服务。 + + + 找不到任何显示名称为 '{1}' 的服务。 + + + 无法停止服务 '{1} ({0})',因为它具有依赖服务。只有设置强制标志时才能停止它。 + + + 无法停止服务 '{1} ({0})',因为它具有依赖服务。 + + + 由于以下错误,无法停止服务 '{1} ({0})': {2} + + + 由于以下错误,无法启动服务 '{1} ({0})': {2} + + + 由于以下错误,无法暂停服务 '{1} ({0})': {2} + + + 无法暂停服务 '{1} ({0})',因为该服务不支持暂停或恢复。 + + + 无法暂停服务 '{1} ({0})',因为它当前未运行。 + + + 由于以下错误,无法恢复服务 '{1} ({0})': {2} + + + 无法恢复服务 '{1} ({0})',因为该服务不支持暂停或恢复。 + + + 无法恢复服务 '{1} ({0})',因为它当前未运行。 + + + 由于以下错误,无法配置服务 '{1} ({0})': {2} + + + 由于以下错误,无法配置服务 '{1} ({0})' 的说明: {2} + + + 由于以下错误,无法配置服务 '{1} ({0})' 自动(延迟启动): {2} + + + 由于以下错误,无法配置服务 '{0}' 的安全描述符: {1} + + + 由于以下错误,无法创建服务 '{1} ({0})': {2} + + + 已创建服务 '{1} ({0})',但由于以下错误,无法配置其说明: {2} + + + 已创建服务 '{1} ({0})',但由于以下错误,无法配置其 StartupType“自动(延迟启动)”: {2} + + + 由于以下错误,无法移除服务 '{1} ({0})': {2} + + + '无法访问 '{1} ({0})' 的依赖服务 + + + 正在等待服务 '{1} ({0})' 启动... + + + 正在等待服务 '{1} ({0})' 停止... + + + 正在等待服务 '{1} ({0})' 暂停... + + + 正在等待服务 '{1} ({0})' 恢复... + + + 未能启动服务 '{1} ({0})'。 + + + 服务 '{1} ({0})' 停止失败。 + + + 服务 '{1} ({0})' 暂停失败。 + + + 服务 '{1} ({0})' 恢复失败。 + + + 由于以下错误,未能打开 SCManager: {0}。请以管理员身份运行 PowerShell,然后再次运行你的命令。 + + + 启动类型 '{0}' 不受 {1} 支持。 + + + 无法检索服务 '{0}' 的属性 '{1}': {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TestConnectionResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TestConnectionResources.zh-Hans.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TestConnectionResources.zh-Hans.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TestPathResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TestPathResources.zh-Hans.resx new file mode 100644 index 00000000000..21185978b44 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TestPathResources.zh-Hans.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 + + + 提供的 Path 参数为 null 或为空集合。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TimeZoneResources.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TimeZoneResources.zh-Hans.resx new file mode 100644 index 00000000000..e8c913c1372 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hans/TimeZoneResources.zh-Hans.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 + + + 无法设置本地时区,因为名称 '{0}' 解析为多个条目。 + + + 在本地计算机上找不到时区名称 '{0}'。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ClearRecycleBinResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ClearRecycleBinResources.zh-Hant.resx new file mode 100644 index 00000000000..906277c6f06 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ClearRecycleBinResources.zh-Hant.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 + + + 資源回收筒中的所有內容 + + + '{0}' 磁碟機之資源回收筒中的所有內容 + + + 正在清理資源回收筒 + + + '{0}' 磁碟機 + + + 所有磁碟機 + + + 找不到磁碟機。沒有名為 '{0}' 的磁碟機。請執行 '{1}' Cmdlet,以查看系統中可用的固定磁碟機。 + + + 輸入無效。支援下列格式: '{0}'、'{1}' 或 '{2}'。 + + + 名稱為 '{0}' 的磁碟機不是固定磁碟機,而且不支援資源回收筒。請執行 '{1}' Cmdlet,以查看系統中可用的固定磁碟機。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ClipboardResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ClipboardResources.zh-Hant.resx new file mode 100644 index 00000000000..ac99a2866b9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ClipboardResources.zh-Hant.resx @@ -0,0 +1,112 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 將字串 '{0}' 設定為剪貼簿。 + + + 將字串 '{0}' 附加至剪貼簿。 + + + 將檔案 '{0}' 設定為剪貼簿。 + + + 將檔案 '{0}' 附加至剪貼簿。 + + + 將 {0} 檔案設定為剪貼簿。 + + + 將 {0} 檔案附加至剪貼簿。 + + + 剪貼簿中沒有任何內容,或內容格式不相容。將輸入物件設定為剪貼簿。 + + + 剪貼簿已清除。 + + + TextFormatType 只能與文字格式結合。 + + + Raw 只能與文字或 FileDropList 格式結合。 + + + Html 只能與 Html 文字格式結合。 + + + 此平台僅支援文字格式。 + + + 此平台不支援剪貼簿。 + + + 此平台不支援 '-AsHtml' 參數。 + + + '-TextformatType' 參數僅在此平台上支援 'Text'。 + + + 此平台不支援 '-Path' 參數。 + + + 此平台不支援 '-LiteralPath' 參數。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/CmdletizationResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/CmdletizationResources.zh-Hant.resx new file mode 100644 index 00000000000..b97467043ef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/CmdletizationResources.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ComputerInfoResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ComputerInfoResources.zh-Hant.resx new file mode 100644 index 00000000000..522b61cb43a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ComputerInfoResources.zh-Hant.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 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ComputerResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ComputerResources.zh-Hant.resx new file mode 100644 index 00000000000..0891a9bdd1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ComputerResources.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/HotFixResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/HotFixResources.zh-Hant.resx new file mode 100644 index 00000000000..d79c1b010d6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/HotFixResources.zh-Hant.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 + + + 在 '{0}' 電腦上找不到要求的 Hotfix。驗證輸入,然後再次執行命令。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/NavigationResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/NavigationResources.zh-Hant.resx new file mode 100644 index 00000000000..b0c84402a49 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/NavigationResources.zh-Hant.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 + + + 指定的路徑是含有子項目的容器。您要刪除此容器及其子項目嗎? + + + 是否要刪除指定的項目? + + + 無法複製,因為指定的目的地已經存在。要覆蓋目前的內容嗎? + + + 新增磁碟機 + + + 名稱: {0} 提供者: {1} 根: {2} + + + 移除磁碟機 + + + 名稱: {0} 提供者: {1} 根: {2} + + + 無法移除磁碟機 '{0}',因為它正在使用中。 + + + 位於 {0} 的項目具有子項目,且未指定 Recurse 參數。如果繼續,所有子項目都會隨項目一起移除。確定要繼續嗎? + + + 無法移除位於 '{0}' 的項目,因為該項目正在使用中。 + + + 位於指定路徑 {0} 的物件不存在,或已經 -Include 或 -Exclude 參數篩選。 + + + 設定內容 + + + 路徑: {0} + + + 新增內容 + + + 路徑: {0} + + + 無法移動項目,因為位於 '{0}' 的項目並不存在。 + + + 無法移動項目,因為位於 '{0}' 的項目正在使用中。 + + + 無法重新命名,因為位於 '{0}' 的項目不存在。 + + + 無法重新命名位於 '{0}' 的項目,因為該項目正在使用中。 + + + 無法剖析路徑,因為路徑 '{0}' 未指定限定詞。 + + + 開始 + + + 復原 + + + 提交 + + + 目前的交易 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ProcessCommandHelpResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ProcessCommandHelpResources.zh-Hant.resx new file mode 100644 index 00000000000..e6e0fbdd429 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ProcessCommandHelpResources.zh-Hant.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 + + + 列出目前正在執行的處理序。 + + + +-Id 識別碼 +[int[]] +[pipeline input allowed] +以逗號分隔的處理序識別碼清單,指定要取得的處理序 + +-ProcessName 名稱 +[string[]] +[pipeline input allowed] +以逗號分隔的處理序名稱清單,指定要取得的處理序 + +-Exclude 名稱 +[ArrayList] +以逗號分隔的清單,列出要從輸出中排除的處理序名稱。 + +--- +此命令會列舉本機電腦上的處理序,並輸出 System.Diagnostics.Process 物件。此命令會一次將一個處理序物件寫入輸出管線。此命令會從命令列接受 ID (處理序識別碼) 或 Process Name 等參數。此命令會針對所提供的 ID 或 ProcessName 參數,傳回對應的 system.diagnostics.process。 + + + 排除僅適用於處理序名稱。 + + + 傳回所有執行中的處理序。 + + + 傳回名稱以 svc 開頭的所有處理序。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ProcessResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ProcessResources.zh-Hant.resx new file mode 100644 index 00000000000..46e1f1dc936 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ProcessResources.zh-Hant.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 + + + 找不到名稱為 "{0}" 的處理序。請確認處理序名稱,然後再次呼叫 Cmdlet。 + + + 找不到名稱為 "{0}" 的處理序。請嘗試使用 -Id 依處理序識別碼搜尋。 + + + 因為無法將偵錯工具附加到處理序 "{0} ({1})",所以無法執行此命令。請指定其他處理序,然後執行命令。 + + + 找不到處理序識別碼為 {1} 的處理序。 + + + 因為發生下列錯誤,無法停止處理序 "{0} ({1})": {2} + + + {0} ({1}) + + + {0} {1} + + + 無法列舉 "{0}" 處理序的模組。 + + + 無法列舉 "{0}" 處理序的檔案版本資訊。 + + + 無法列舉 "{0}" 處理序的模組和檔案版本資訊。 + + + 您確定要在下列項目上執行 Stop-Process 作業嗎: {0}({1})? + + + 指定的路徑不是有效的 Win32 應用程式。請改用 UseShellExecute 再試一次。 + + + 因為發生下列錯誤,所以此命令已停止 "{0} ({1})" 的作業: {2}。 + + + 因為 Redirection 參數無法與 UseShellExecute 參數搭配使用,所以無法執行此命令 + + + 取得 "Modules" 或 "FileVersion" 時發生例外狀況: [此功能不支援遠端電腦。]。 + + + 因為沒有可用的預設偵錯工具,所以此命令因 {0} 無法將偵錯工具附加至處理序。 + + + 因為此命令無法等候 'System Idle' 處理序,所以已停止作業。請指定其他處理序,然後再次執行命令。 + + + 因為此命令無法等候自己完成,所以已停止作業。請指定其他處理序,然後再次執行命令。 + + + 因為處理序 "{0} ({1})" 未在指定的逾時時間內停止,所以此命令已停止作業。 + + + 因為發生錯誤,所以無法執行此命令: {0} + + + 因為輸入 "{0}" 不是有效的應用程式,所以無法執行此命令。 請提供有效的應用程式,然後再次執行命令。 + + + 因為參數 "{0}" 的值無效,或無法與此命令搭配使用,所以無法執行此命令。請提供有效的輸入,然後再次執行命令。 + + + 因為 "{0}" 和 "{1}" 相同,所以無法執行此命令。請提供不同的輸入,然後再次執行命令。 + + + 因為系統找不到所有必要的資訊,所以此命令無法完整執行。 + + + 無法擷取新的處理序控制代碼: "{0}"。輸出的 Process 物件可能有一些屬性和方法無法正常運作。 + + + 因為發生錯誤 1783,所以無法執行此命令。此錯誤的可能原因是使用了不存在的使用者 "{0}"。請提供有效的使用者,然後再次執行命令。 + + + 將 '{0}' 新增至網路時發生錯誤: {1} + + + 從網路移除 '{0}' 時發生錯誤: {1} + + + 重新命名 '{0}' 時發生錯誤: {1} + + + 不可同時指定參數 "{0}" 和 "{1}"。 + + + 因為發生下列錯誤,所以無法對處理序 "{0} ({1})" 進行偵錯: {2} + + + 使用者沒有要求之資訊的存取權。 + + + 指定的參數無效。 + + + 使用者沒有足夠的權限。 + + + 未知失敗。 + + + 指定的路徑不存在。 + + + 此版本的 Windows 不支援 cmdlet '{1}' 的參數 '{0}'。 + + + 此版本的 PowerShell 不支援 cmdlet '{1}' 的參數 '{0}'。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ServiceResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ServiceResources.zh-Hant.resx new file mode 100644 index 00000000000..13e1e1d7889 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/ServiceResources.zh-Hant.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}) + + + 找不到任何服務名稱為 '{0}' 的服務。 + + + 找不到任何顯示名稱為 '{1}' 的服務。 + + + 無法停止服務 '{1} ({0})',因為該服務具有相依式服務。只有在設定 Force 旗標時,才能停止該服務。 + + + 無法停止服務 '{1} ({0})',因為該服務具有相依式服務。 + + + 由於下列錯誤,無法停止服務 '{1} ({0})': {2} + + + 由於下列錯誤,無法啟動服務 '{1} ({0})': {2} + + + 由於下列錯誤,無法暫止服務 '{1} ({0})': {2} + + + 無法暫止服務 '{1} ({0})',因為該服務不支援暫止或繼續。 + + + 無法暫止服務 '{1} ({0})',因為該服務目前未執行。 + + + 由於下列錯誤,無法繼續服務 '{1} ({0})': {2} + + + 無法繼續服務 '{1} ({0})',因為該服務不支援暫止或繼續。 + + + 無法繼續服務 '{1} ({0})',因為該服務目前未執行。 + + + 由於下列錯誤,無法設定服務 '{1} ({0})': {2} + + + 由於下列錯誤,無法設定服務 '{1} ({0})' 的描述: {2} + + + 由於下列錯誤,無法將服務 '{1} ({0})' 設定為自動 (延遲啟動): {2} + + + 由於下列錯誤,無法設定服務 '{0}' 的安全性描述元: {1} + + + 由於下列錯誤,無法建立服務 '{1} ({0})': {2} + + + 已建立服務 '{1} ({0})',但由於下列錯誤,無法設定其描述: {2} + + + 已建立服務 '{1} ({0})',但由於下列錯誤,無法將其 StartupType 設定為 [自動 (延遲啟動)]: {2} + + + 由於下列錯誤,無法移除服務 '{1} ({0})': {2} + + + '無法存取 '{1} ({0})' 的相依式服務' + + + 正在等候服務 '{1} ({0})' 啟動... + + + 正在等候服務 '{1} ({0})' 停止... + + + 正在等候服務 '{1} ({0})' 暫止... + + + 正在等候服務 '{1} ({0})' 繼續... + + + 無法啟動服務 '{1} ({0})。 + + + 服務 '{1} ({0})' 停止失敗。 + + + 服務 '{1} ({0})' 暫止失敗。 + + + 服務 '{1} ({0})' 繼續失敗。 + + + 由於下列錯誤,無法開啟 SCManager: {0}。以系統管理員身分執行 PowerShell,然後再次執行您的命令。 + + + {1} 不支援啟動類型 '{0}'。 + + + 無法擷取服務 '{0}' 的屬性 '{1}': {2} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TestConnectionResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TestConnectionResources.zh-Hant.resx new file mode 100644 index 00000000000..8f01dca03fd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TestConnectionResources.zh-Hant.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}). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TestPathResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TestPathResources.zh-Hant.resx new file mode 100644 index 00000000000..b3e6ba950d4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TestPathResources.zh-Hant.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 + + + 提供的 Path 引數是 Null 或空的集合。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TimeZoneResources.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TimeZoneResources.zh-Hant.resx new file mode 100644 index 00000000000..31a2cdfca31 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Management/resources/zh-Hant/TimeZoneResources.zh-Hant.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 + + + 無法設定本機時區,因為名稱 '{0}' 解析為多個項目。 + + + 在本機電腦上找不到時區名稱 '{0}'。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs deleted file mode 100644 index 0b0239053ea..00000000000 --- a/src/Microsoft.PowerShell.Commands.Management/singleshell/installer/MshManagementMshSnapin.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.ComponentModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell -{ - /// - /// MshManagementMshSnapin (or MshManagementMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad management mshsnapin. - /// - /// 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 mshsnapin. - /// - public override string Name - { - get - { - return RegistryStrings.ManagementMshSnapinName; - } - } - - /// - /// Get the default vendor string for this mshsnapin. - /// - 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 mshsnapin. - /// - 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/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj index e923f6aa810..9a7249ee575 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj +++ b/src/Microsoft.PowerShell.Commands.Utility/Microsoft.PowerShell.Commands.Utility.csproj @@ -8,33 +8,19 @@ - + + - - $(DefineConstants);CORECLR - - - - - - - - - - - - - - + + + - - - - + + $(RootNamespace).resources.%(Filename) + - diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs index efb035b7785..4c7601e883f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddMember.cs @@ -147,8 +147,8 @@ public SwitchParameter PassThru /// The name of the new NoteProperty member. /// [Parameter(Mandatory = true, Position = 0, ParameterSetName = NotePropertySingleMemberSet)] - [ValidateNotePropertyNameAttribute()] - [NotePropertyTransformationAttribute()] + [ValidateNotePropertyName] + [NotePropertyTransformation] [ValidateNotNullOrEmpty] public string NotePropertyName { @@ -524,7 +524,10 @@ private void UpdateTypeNames() // Respect the type shortcut Type type; string typeNameInUse = _typeName; - if (LanguagePrimitives.TryConvertTo(_typeName, out type)) { typeNameInUse = type.FullName; } + if (LanguagePrimitives.TryConvertTo(_typeName, out type)) + { + typeNameInUse = type.FullName; + } _inputObject.TypeNames.Insert(0, typeNameInUse); } @@ -557,9 +560,8 @@ private sealed class ValidateNotePropertyNameAttribute : ValidateArgumentsAttrib { protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { - string notePropertyName = arguments as string; PSMemberTypes memberType; - if (notePropertyName != null && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) + if (arguments is string notePropertyName && LanguagePrimitives.TryConvertTo(notePropertyName, out memberType)) { switch (memberType) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs index b86cadc1eff..7dc0a9c3556 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/AddType.cs @@ -11,7 +11,9 @@ 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; @@ -108,7 +110,7 @@ public string[] MemberDefinition if (value != null) { - _sourceCode = string.Join("\n", value); + _sourceCode = string.Join('\n', value); } } } @@ -127,7 +129,7 @@ public string[] MemberDefinition /// Any using statements required by the auto-generated type. /// [Parameter(ParameterSetName = FromMemberParameterSetName)] - [ValidateNotNull()] + [ValidateNotNull] [Alias("Using")] public string[] UsingNamespace { get; set; } = Array.Empty(); @@ -299,7 +301,10 @@ public string[] ReferencedAssemblies set { - if (value != null) { _referencedAssemblies = value; } + if (value != null) + { + _referencedAssemblies = value; + } } } @@ -400,7 +405,7 @@ public string OutputAssembly /// /// Flag to pass the resulting types along. /// - [Parameter()] + [Parameter] public SwitchParameter PassThru { get; set; } /// @@ -549,15 +554,26 @@ private string GetUsingSet(Language language) /// protected override void BeginProcessing() { - // Prevent code compilation in ConstrainedLanguage mode - if (SessionState.LanguageMode == PSLanguageMode.ConstrainedLanguage) + // 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)) { - ThrowTerminatingError( - new ErrorRecord( - new PSNotSupportedException(AddTypeStrings.CannotDefineNewType), - nameof(AddTypeStrings.CannotDefineNewType), - ErrorCategory.PermissionDenied, - targetObject: null)); + 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 @@ -646,8 +662,8 @@ protected override void EndProcessing() // 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 HashSet s_sourceTypesCache = new(); - private static readonly Dictionary s_sourceAssemblyCache = new(); + private static readonly ConcurrentDictionary s_sourceTypesCache = new(); + private static readonly ConcurrentDictionary s_sourceAssemblyCache = new(); private static readonly string s_defaultSdkDirectory = Utils.DefaultPowerShellAppBase; @@ -668,6 +684,7 @@ private void LoadAssemblies(IEnumerable 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) @@ -682,11 +699,10 @@ private void LoadAssemblies(IEnumerable assemblies) /// private static IEnumerable InitDefaultRefAssemblies() { - // Define number of reference assemblies distributed with PowerShell. - const int maxPowershellRefAssemblies = 160; - - const int capacity = maxPowershellRefAssemblies + 1; - var defaultRefAssemblies = new List(capacity); + // 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)) { @@ -696,11 +712,6 @@ private static IEnumerable InitDefaultRefAssemblies // Add System.Management.Automation.dll defaultRefAssemblies.Add(MetadataReference.CreateFromFile(typeof(PSObject).Assembly.Location)); - // We want to avoid reallocating the internal array, so we assert if the list capacity has increased. - Diagnostics.Assert( - defaultRefAssemblies.Capacity <= capacity, - $"defaultRefAssemblies was resized because of insufficient initial capacity! A capacity of {defaultRefAssemblies.Count} is required."); - return defaultRefAssemblies; } @@ -869,7 +880,10 @@ private IEnumerable GetPortableExecutableReferences var tempReferences = new List(s_autoReferencedAssemblies.Value); foreach (string assembly in ReferencedAssemblies) { - if (string.IsNullOrWhiteSpace(assembly)) { continue; } + if (string.IsNullOrWhiteSpace(assembly)) + { + continue; + } string resolvedAssemblyPath = ResolveAssemblyName(assembly, true); @@ -894,7 +908,14 @@ private IEnumerable GetPortableExecutableReferences private void WriteTypes(Assembly assembly) { - WriteObject(assembly.GetTypes(), true); + 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 @@ -952,7 +973,7 @@ private CompilationOptions GetDefaultCompilationOptions() } } - private bool isSourceCodeUpdated(List syntaxTrees, out Assembly assembly) + private bool IsSourceCodeUpdated(List syntaxTrees, out Assembly assembly) { Diagnostics.Assert(syntaxTrees.Count != 0, "syntaxTrees should contains a source code."); @@ -1037,7 +1058,7 @@ private void SourceCodeProcessing() { // 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)) + if (IsSourceCodeUpdated(syntaxTrees, out Assembly assembly)) { CompileToAssembly(syntaxTrees, compilationOptions, emitOptions); } @@ -1107,7 +1128,7 @@ private void CheckDuplicateTypes(Compilation compilation, out ConcurrentBag DuplicateSymbols = new(); public readonly ConcurrentBag UniqueSymbols = new(); @@ -1127,7 +1148,7 @@ public override void VisitNamedType(INamedTypeSymbol symbol) // It is namespace-fully-qualified name var symbolFullName = symbol.ToString(); - if (s_sourceTypesCache.TryGetValue(symbolFullName, out _)) + if (s_sourceTypesCache.ContainsKey(symbolFullName)) { DuplicateSymbols.Add(symbolFullName); } @@ -1142,13 +1163,13 @@ private static void CacheNewTypes(ConcurrentBag newTypes) { foreach (var typeName in newTypes) { - s_sourceTypesCache.Add(typeName); + s_sourceTypesCache.TryAdd(typeName, null); } } private void CacheAssembly(Assembly assembly) { - s_sourceAssemblyCache.Add(_syntaxTreesHash, assembly); + s_sourceAssemblyCache.TryAdd(_syntaxTreesHash, assembly); } private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOptions) @@ -1167,8 +1188,6 @@ private void DoEmitAndLoadAssembly(Compilation compilation, EmitOptions emitOpti if (emitResult.Success) { - // TODO: We could use Assembly.LoadFromStream() in future. - // See https://github.com/dotnet/corefx/issues/26994 ms.Seek(0, SeekOrigin.Begin); Assembly assembly = AssemblyLoadContext.Default.LoadFromStream(ms); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs index 83f78ce77a2..54a5b07cf5d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Compare-Object.cs @@ -32,8 +32,8 @@ public sealed class CompareObjectCommand : ObjectCmdletBase /// /// [Parameter] - [ValidateRange(0, Int32.MaxValue)] - public int SyncWindow { get; set; } = Int32.MaxValue; + [ValidateRange(0, int.MaxValue)] + public int SyncWindow { get; set; } = int.MaxValue; /// /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs index 22c1e5ef46b..48bda12cd8a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-SddlString.cs @@ -70,7 +70,7 @@ private static List GetApplicableAccessRights(int accessMask, AccessRigh } else { - foreach (AccessRightTypeNames member in Enum.GetValues(typeof(AccessRightTypeNames))) + foreach (AccessRightTypeNames member in Enum.GetValues()) { typesToExamine.Add(GetRealAccessRightType(member)); } @@ -81,9 +81,8 @@ private static List GetApplicableAccessRights(int accessMask, AccessRigh foreach (string memberName in Enum.GetNames(accessRightType)) { int memberValue = (int)Enum.Parse(accessRightType, memberName); - if (!foundAccessRightValues.Contains(memberValue)) + if (foundAccessRightValues.Add(memberValue)) { - foundAccessRightValues.Add(memberValue); if ((accessMask & memberValue) == memberValue) { foundAccessRightNames.Add(memberName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs index 16bb4be012d..9272e85c05d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertFrom-StringData.cs @@ -55,16 +55,14 @@ protected override void ProcessRecord() return; } - string[] lines = _stringData.Split('\n'); + string[] lines = _stringData.Split('\n', StringSplitOptions.TrimEntries); foreach (string line in lines) { - string s = line.Trim(); - - if (string.IsNullOrEmpty(s) || s[0] == '#') + if (string.IsNullOrEmpty(line) || line[0] == '#') continue; - int index = s.IndexOf(Delimiter); + int index = line.IndexOf(Delimiter); if (index <= 0) { throw PSTraceSource.NewInvalidOperationException( @@ -72,7 +70,7 @@ protected override void ProcessRecord() line); } - string name = s.Substring(0, index); + string name = line.Substring(0, index); name = name.Trim(); if (result.ContainsKey(name)) @@ -83,7 +81,7 @@ protected override void ProcessRecord() name); } - string value = s.Substring(index + 1); + string value = line.Substring(index + 1); value = value.Trim(); value = Regex.Unescape(value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs index e72fc825e7c..41dd159a3ba 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ConvertTo-Html.cs @@ -19,6 +19,7 @@ namespace Microsoft.PowerShell.Commands /// [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 { @@ -320,7 +321,7 @@ internal static class ConvertHTMLParameterDefinitionKeys /// /// This allows for @{e='foo';label='bar';alignment='center';width='20'}. /// - internal class ConvertHTMLExpressionParameterDefinition : CommandParameterDefinition + internal sealed class ConvertHTMLExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { @@ -343,10 +344,7 @@ private List ProcessParameter(object[] properties) TerminatingErrorContext invocationContext = new(this); ParameterProcessor processor = new(new ConvertHTMLExpressionParameterDefinition()); - if (properties == null) - { - properties = new object[] { "*" }; - } + properties ??= new object[] { "*" }; return processor.ProcessParameters(properties, invocationContext); } @@ -504,9 +502,8 @@ protected override void BeginProcessing() MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; string Message = StringUtil.Format(ConvertHTMLStrings.MetaPropertyNotFound, s, _meta[s]); WarningRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -555,16 +552,14 @@ private void WriteColumns(List mshParams) foreach (MshParameter p in mshParams) { COLTag.Append(" /// This class is used to parse CSV text. /// - internal class CSVHelper + internal sealed class CSVHelper { internal CSVHelper(char delimiter) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs index cbd9d4c36b4..cb455417531 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CsvCommands.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; @@ -31,9 +32,9 @@ public abstract class BaseCsvWritingCommand : PSCmdlet [ValidateNotNull] public char Delimiter { get; set; } - /// - ///Culture switch for csv conversion - /// + /// + /// Culture switch for csv conversion + /// [Parameter(ParameterSetName = "UseCulture")] public SwitchParameter UseCulture { get; set; } @@ -44,17 +45,19 @@ public abstract class BaseCsvWritingCommand : PSCmdlet public abstract PSObject InputObject { get; set; } /// - /// IncludeTypeInformation : The #TYPE line should be generated. Default is false. Cannot specify with NoTypeInformation. + /// IncludeTypeInformation : The #TYPE line should be generated. Default is false. /// [Parameter] [Alias("ITI")] public SwitchParameter IncludeTypeInformation { get; set; } /// - /// NoTypeInformation : The #TYPE line should not be generated. Default is true. Cannot specify with IncludeTypeInformation. + /// 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; /// @@ -71,6 +74,12 @@ public abstract class BaseCsvWritingCommand : PSCmdlet [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 /// @@ -113,18 +122,6 @@ protected override void BeginProcessing() this.ThrowTerminatingError(errorRecord); } - if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation)) && this.MyInvocation.BoundParameters.ContainsKey(nameof(NoTypeInformation))) - { - InvalidOperationException exception = new(CsvCommandStrings.CannotSpecifyIncludeTypeInformationAndNoTypeInformation); - ErrorRecord errorRecord = new(exception, "CannotSpecifyIncludeTypeInformationAndNoTypeInformation", ErrorCategory.InvalidData, null); - this.ThrowTerminatingError(errorRecord); - } - - if (this.MyInvocation.BoundParameters.ContainsKey(nameof(IncludeTypeInformation))) - { - NoTypeInformation = !IncludeTypeInformation; - } - Delimiter = ImportExportCSVHelper.SetDelimiter(this, ParameterSetName, Delimiter, UseCulture); } } @@ -211,8 +208,8 @@ public string LiteralPath /// Gets or sets encoding optional flag. /// [Parameter] - [ArgumentToEncodingTransformationAttribute] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -228,7 +225,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Gets or sets property that sets append parameter. @@ -263,6 +260,14 @@ protected override void BeginProcessing() 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) { @@ -300,9 +305,9 @@ protected override void ProcessRecord() } // write headers (row1: typename + row2: column names) - if (!_isActuallyAppending) + if (!_isActuallyAppending && !NoHeader.IsPresent) { - if (NoTypeInformation == false) + if (IncludeTypeInformation) { WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); } @@ -313,7 +318,6 @@ protected override void ProcessRecord() string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); WriteCsvLine(csv); - _sw.Flush(); } /// @@ -415,7 +419,6 @@ private void CleanUp() { if (_sw != null) { - _sw.Flush(); _sw.Dispose(); _sw = null; } @@ -428,10 +431,7 @@ private void CleanUp() _readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } - if (_helper != null) - { - _helper.Dispose(); - } + _helper?.Dispose(); } private void ReconcilePreexistingPropertyNames() @@ -588,9 +588,9 @@ public string[] LiteralPath [ValidateNotNull] public SwitchParameter UseCulture { get; set; } - /// + /// /// Gets or sets header property to customize the names. - /// + /// [Parameter(Mandatory = false)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] @@ -600,8 +600,8 @@ public string[] LiteralPath /// Gets or sets encoding optional flag. /// [Parameter] - [ArgumentToEncodingTransformationAttribute] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -617,7 +617,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Avoid writing out duplicate warning messages when there are one or more unspecified names. @@ -729,22 +729,30 @@ protected override void ProcessRecord() if (_propertyNames == null) { _propertyNames = ExportCsvHelper.BuildPropertyNames(InputObject, _propertyNames); - if (NoTypeInformation == false) + + if (!NoHeader.IsPresent) { - WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); - } + if (IncludeTypeInformation) + { + WriteCsvLine(ExportCsvHelper.GetTypeString(InputObject)); + } - // Write property information - string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); - if (!properties.Equals(string.Empty)) - WriteCsvLine(properties); + // Write property information + string properties = _helper.ConvertPropertyNamesCSV(_propertyNames); + if (!properties.Equals(string.Empty)) + { + WriteCsvLine(properties); + } + } } string csv = _helper.ConvertPSObjectToCSV(InputObject, _propertyNames); - // write to the console + // Write to the output stream if (csv != string.Empty) + { WriteCsvLine(csv); + } } #endregion Overrides @@ -783,9 +791,9 @@ public sealed class ConvertFromCsvCommand : PSCmdlet [ValidateNotNullOrEmpty] public char Delimiter { get; set; } - /// - ///Culture switch for csv conversion - /// + /// + /// Culture switch for csv conversion + /// [Parameter(ParameterSetName = "UseCulture", Mandatory = true)] [ValidateNotNull] [ValidateNotNullOrEmpty] @@ -800,9 +808,9 @@ public sealed class ConvertFromCsvCommand : PSCmdlet [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSObject[] InputObject { get; set; } - /// + /// /// Gets or sets header property to customize the names. - /// + /// [Parameter(Mandatory = false)] [ValidateNotNull] [ValidateNotNullOrEmpty] @@ -875,7 +883,7 @@ protected override void ProcessRecord() /// /// Helper class for Export-Csv and ConvertTo-Csv. /// - internal class ExportCsvHelper : IDisposable + internal sealed class ExportCsvHelper : IDisposable { private readonly char _delimiter; private readonly BaseCsvWritingCommand.QuoteKind _quoteKind; @@ -908,16 +916,36 @@ internal static IList BuildPropertyNames(PSObject source, IList throw new InvalidOperationException(CsvCommandStrings.BuildPropertyNamesMethodShouldBeCalledOnlyOncePerCmdletInstance); } - // serialize only Extended and Adapted properties.. - PSMemberInfoCollection srcPropertiesToSearch = - new PSMemberInfoIntegratingCollection( + 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 | PSMemberViewTypes.Adapted)); + PSObject.GetPropertyCollection(PSMemberViewTypes.Extended)); - propertyNames = new Collection(); - foreach (PSPropertyInfo prop in srcPropertiesToSearch) + foreach (var prop in propertiesToSearch) + { + propertyNames.Add(prop.Name); + } + } + else { - propertyNames.Add(prop.Name); + // 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; @@ -929,10 +957,7 @@ internal static IList BuildPropertyNames(PSObject source, IList /// Converted string. internal string ConvertPropertyNamesCSV(IList propertyNames) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); _outputString.Clear(); bool first = true; @@ -967,7 +992,8 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) AppendStringWithEscapeAlways(_outputString, propertyName); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (propertyName.Contains(_delimiter)) + + if (propertyName.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1) { AppendStringWithEscapeAlways(_outputString, propertyName); } @@ -995,10 +1021,7 @@ internal string ConvertPropertyNamesCSV(IList propertyNames) /// internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyNames) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); _outputString.Clear(); bool first = true; @@ -1014,11 +1037,26 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN _outputString.Append(_delimiter); } - // If property is not present, assume value is null and skip it. - if (mshObject.Properties[propertyName] is PSPropertyInfo property) + string value = null; + if (mshObject.BaseObject is IDictionary dictionary) { - var value = GetToStringValueForProperty(property); + 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 _)) @@ -1038,7 +1076,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN AppendStringWithEscapeAlways(_outputString, value); break; case BaseCsvWritingCommand.QuoteKind.AsNeeded: - if (value != null && value.Contains(_delimiter)) + if (value != null && value.AsSpan().IndexOfAny(_delimiter, '\n', '"') != -1) { AppendStringWithEscapeAlways(_outputString, value); } @@ -1069,10 +1107,7 @@ internal string ConvertPSObjectToCSV(PSObject mshObject, IList propertyN /// ToString() value. internal static string GetToStringValueForProperty(PSPropertyInfo property) { - if (property == null) - { - throw new ArgumentNullException(nameof(property)); - } + ArgumentNullException.ThrowIfNull(property); string value = null; try @@ -1122,7 +1157,7 @@ internal static string GetTypeString(PSObject source) temp = temp.Substring(4); } - type = string.Format(System.Globalization.CultureInfo.InvariantCulture, "#TYPE {0}", temp); + type = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"#TYPE {temp}"); } return type; @@ -1187,7 +1222,7 @@ public void Dispose() /// /// Helper class to import single CSV file. /// - internal class ImportCsvHelper + internal sealed class ImportCsvHelper { #region constructor @@ -1234,15 +1269,8 @@ internal class ImportCsvHelper internal ImportCsvHelper(PSCmdlet cmdlet, char delimiter, IList header, string typeName, StreamReader streamReader) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } - - if (streamReader == null) - { - throw new ArgumentNullException(nameof(streamReader)); - } + ArgumentNullException.ThrowIfNull(cmdlet); + ArgumentNullException.ThrowIfNull(streamReader); _cmdlet = cmdlet; _delimiter = delimiter; @@ -1389,11 +1417,7 @@ private static void ValidatePropertyNames(IList names) { if (!string.IsNullOrEmpty(currentHeader)) { - if (!headers.Contains(currentHeader)) - { - headers.Add(currentHeader); - } - else + if (!headers.Add(currentHeader)) { // throw a terminating error as there are duplicate headers in the input. string memberAlreadyPresentMsg = diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs index 6ad8b02a558..6d224d29007 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/CustomSerialization.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation /// /// This class provides functionality for serializing a PSObject. /// - internal class CustomSerialization + internal sealed class CustomSerialization { #region constructor /// @@ -170,10 +170,7 @@ internal void DoneAsStream() internal void Stop() { CustomInternalSerializer serializer = _serializer; - if (serializer != null) - { - serializer.Stop(); - } + serializer?.Stop(); } #endregion @@ -182,8 +179,7 @@ internal void Stop() /// /// This internal helper class provides methods for serializing mshObject. /// - internal class - CustomInternalSerializer + internal sealed class CustomInternalSerializer { #region constructor @@ -341,8 +337,7 @@ private bool HandlePrimitiveKnownTypePSObject(object source, string property, in Dbg.Assert(source != null, "caller should validate the parameter"); bool sourceHandled = false; - PSObject moSource = source as PSObject; - if (moSource != null && !moSource.ImmediateBaseObjectIsEmpty) + if (source is PSObject moSource && !moSource.ImmediateBaseObjectIsEmpty) { // Check if baseObject is primitive known type object baseObject = moSource.ImmediateBaseObject; @@ -709,7 +704,7 @@ private void WriteMemberInfoCollection( continue; } - if (!(info is PSPropertyInfo property)) + if (info is not PSPropertyInfo property) { continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs index aa370c12ba1..756afff13de 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/DebugRunspaceCommand.cs @@ -103,7 +103,6 @@ public Guid InstanceId /// /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target. /// - [Experimental("Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", ExperimentAction.Show)] [Parameter] public SwitchParameter BreakAll { get; set; } @@ -237,10 +236,7 @@ protected override void StopProcessing() // Unblock the data collection. PSDataCollection debugCollection = _debugBlockingCollection; - if (debugCollection != null) - { - debugCollection.Complete(); - } + debugCollection?.Complete(); // Unblock any new command wait. _newRunningScriptEvent.Set(); @@ -269,12 +265,24 @@ private void WaitAndReceiveRunspaceOutput() // 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; } + if (!_debugging) + { + return; + } AddDataEventHandlers(); @@ -308,6 +316,7 @@ private void WaitAndReceiveRunspaceOutput() { _runspace.AvailabilityChanged -= HandleRunspaceAvailabilityChanged; _debugger.NestedDebuggingCancelledEvent -= HandleDebuggerNestedDebuggingCancelledEvent; + _runspace.IsRemoteDebuggerAttached = false; _debugger.StopDebugRunspace(_runspace); _newRunningScriptEvent.Dispose(); } @@ -335,9 +344,8 @@ private void HostWriteLine(string line) private void AddDataEventHandlers() { // Create new collection objects. - if (_debugBlockingCollection != null) { _debugBlockingCollection.Dispose(); } - - if (_debugAccumulateCollection != null) { _debugAccumulateCollection.Dispose(); } + _debugBlockingCollection?.Dispose(); + _debugAccumulateCollection?.Dispose(); _debugBlockingCollection = new PSDataCollection(); _debugBlockingCollection.BlockingEnumerator = true; @@ -409,8 +417,7 @@ private void RemoveDataEventHandlers() private void HandleRunspaceAvailabilityChanged(object sender, RunspaceAvailabilityEventArgs e) { // Ignore nested commands. - LocalRunspace localRunspace = sender as LocalRunspace; - if (localRunspace != null) + if (sender is LocalRunspace localRunspace) { var basePowerShell = localRunspace.GetCurrentBasePowerShell(); if ((basePowerShell != null) && (basePowerShell.IsNested)) @@ -440,8 +447,7 @@ private void HandleDebuggerNestedDebuggingCancelledEvent(object sender, EventArg private void HandlePipelineOutputDataReady(object sender, EventArgs e) { - PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Output); } @@ -449,8 +455,7 @@ private void HandlePipelineOutputDataReady(object sender, EventArgs e) private void HandlePipelineErrorDataReady(object sender, EventArgs e) { - PipelineReader reader = sender as PipelineReader; - if (reader != null && reader.IsOpen) + if (sender is PipelineReader reader && reader.IsOpen) { WritePipelineCollection(reader.NonBlockingRead(), PSStreamObjectType.Error); } @@ -508,7 +513,10 @@ private void HandlePowerShellPStreamItem(PSStreamObject streamItem) private void AddToDebugBlockingCollection(PSStreamObject streamItem) { - if (!_debugBlockingCollection.IsOpen) { return; } + if (!_debugBlockingCollection.IsOpen) + { + return; + } if (streamItem != null) { @@ -537,8 +545,7 @@ 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) { - LocalRunspace localRunspace = runspace as LocalRunspace; - if ((localRunspace != null) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) + if ((runspace is LocalRunspace localRunspace) && (localRunspace.ExecutionContext != null) && (localRunspace.ExecutionContext.EngineHostInterface != null)) { try { @@ -551,8 +558,7 @@ private void EnableHostDebugger(Runspace runspace, bool enabled) private static void SetLocalMode(System.Management.Automation.Debugger debugger, bool localMode) { - ServerRemoteDebugger remoteDebugger = debugger as ServerRemoteDebugger; - if (remoteDebugger != null) + if (debugger is ServerRemoteDebugger remoteDebugger) { remoteDebugger.LocalDebugMode = localMode; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs index c37d83ecf84..47b83c78770 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/EnableDisableRunspaceDebugCommand.cs @@ -59,7 +59,10 @@ public sealed class PSRunspaceDebug /// Runspace local Id. public PSRunspaceDebug(bool enabled, bool breakAll, string runspaceName, int runspaceId) { - if (string.IsNullOrEmpty(runspaceName)) { throw new PSArgumentNullException(nameof(runspaceName)); } + if (string.IsNullOrEmpty(runspaceName)) + { + throw new PSArgumentNullException(nameof(runspaceName)); + } this.Enabled = enabled; this.BreakAll = breakAll; @@ -115,7 +118,7 @@ public abstract class CommonRunspaceCommandBase : PSCmdlet /// [Parameter(Position = 0, ParameterSetName = CommonRunspaceCommandBase.RunspaceNameParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] RunspaceName { @@ -131,7 +134,7 @@ public string[] RunspaceName ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = CommonRunspaceCommandBase.RunspaceParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public Runspace[] Runspace { @@ -145,7 +148,7 @@ public Runspace[] Runspace [Parameter(Position = 0, Mandatory = true, ParameterSetName = CommonRunspaceCommandBase.RunspaceIdParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] RunspaceId { @@ -158,7 +161,7 @@ public int[] RunspaceId [Parameter(Position = 0, Mandatory = true, ParameterSetName = CommonRunspaceCommandBase.RunspaceInstanceIdParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public System.Guid[] RunspaceInstanceId { @@ -170,7 +173,7 @@ public System.Guid[] RunspaceInstanceId /// Gets or Sets the ProcessName for which runspace debugging has to be enabled or disabled. /// [Parameter(Position = 0, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string ProcessName { get; @@ -181,7 +184,7 @@ public string ProcessName /// Gets or Sets the AppDomain Names for which runspace debugging has to be enabled or disabled. /// [Parameter(Position = 1, ParameterSetName = CommonRunspaceCommandBase.ProcessNameParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Scope = "member", Target = "Microsoft.PowerShell.Commands.CommonRunspaceCommandBase.#AppDomainName")] public string[] AppDomainName @@ -275,10 +278,7 @@ protected void SetDebugPreferenceHelper(string processName, string[] appDomainNa { if (!string.IsNullOrEmpty(currentAppDomainName)) { - if (appDomainNames == null) - { - appDomainNames = new List(); - } + appDomainNames ??= new List(); appDomainNames.Add(currentAppDomainName.ToLowerInvariant()); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs index e01d8c28e0c..d6f2c661ad0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ExportAliasCommand.cs @@ -21,7 +21,7 @@ public enum ExportAliasFormat Csv, /// - /// Aliases will be exported as an MSH script. + /// Aliases will be exported as a script. /// Script } @@ -117,7 +117,7 @@ public SwitchParameter PassThru /// /// Property that sets append parameter. /// - [Parameter()] + [Parameter] public SwitchParameter Append { get @@ -136,7 +136,7 @@ public SwitchParameter Append /// /// Property that sets force parameter. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get @@ -155,7 +155,7 @@ public SwitchParameter Force /// /// Property that prevents file overwrite. /// - [Parameter()] + [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { @@ -184,6 +184,7 @@ public SwitchParameter NoClobber /// which scope the aliases are retrieved from. /// [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } #endregion Parameters @@ -291,8 +292,7 @@ protected override void EndProcessing() line = GetAliasLine(alias, "set-alias -Name:\"{0}\" -Value:\"{1}\" -Description:\"{2}\" -Option:\"{3}\""); } - if (writer != null) - writer.WriteLine(line); + writer?.WriteLine(line); if (PassThru) { @@ -302,8 +302,7 @@ protected override void EndProcessing() } finally { - if (writer != null) - writer.Dispose(); + writer?.Dispose(); // reset the read-only attribute if (readOnlyFileInfo != null) readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs index a42462737ea..65efee78a28 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ColumnInfo.cs @@ -48,7 +48,7 @@ internal Type GetValueType(PSObject liveObject, out object columnValue) /// The source string limited in the number of lines. internal static object LimitString(object src) { - if (!(src is string srcString)) + if (src is not string srcString) { return src; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs index e905f5d64b6..4d0c8af875c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ExpressionColumnInfo.cs @@ -6,7 +6,7 @@ namespace Microsoft.PowerShell.Commands { - internal class ExpressionColumnInfo : ColumnInfo + internal sealed class ExpressionColumnInfo : ColumnInfo { private readonly PSPropertyExpression _expression; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs index d811ce32303..4f4e84a1569 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/HeaderInfo.cs @@ -7,7 +7,7 @@ namespace Microsoft.PowerShell.Commands { - internal class HeaderInfo + internal sealed class HeaderInfo { private readonly List _columns = new(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs index 3db37f3528e..4ec5e2240fa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OriginalColumnInfo.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands { - internal class OriginalColumnInfo : ColumnInfo + internal sealed class OriginalColumnInfo : ColumnInfo { private readonly string _liveObjectPropertyName; private readonly OutGridViewCommand _parentCmdlet; @@ -33,15 +33,13 @@ internal override object GetValue(PSObject liveObject) // The live object has the liveObjectPropertyName property. object liveObjectValue = propertyInfo.Value; - ICollection collectionValue = liveObjectValue as ICollection; - if (collectionValue != null) + if (liveObjectValue is ICollection collectionValue) { liveObjectValue = _parentCmdlet.ConvertToString(PSObjectHelper.AsPSObject(propertyInfo.Value)); } else { - PSObject psObjectValue = liveObjectValue as PSObject; - if (psObjectValue != null) + 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) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs index e606e58e9e4..574ca39426d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutGridViewCommand.cs @@ -145,7 +145,7 @@ protected override void EndProcessing() // The pipeline will be blocked while we don't return if (this.Wait || this.OutputMode != OutputModeOption.None) { - _windowProxy.BlockUntillClosed(); + _windowProxy.BlockUntilClosed(); } // Output selected items to pipeline. @@ -180,8 +180,7 @@ protected override void ProcessRecord() return; } - IDictionary dictionary = InputObject.BaseObject as IDictionary; - if (dictionary != null) + if (InputObject.BaseObject is IDictionary dictionary) { // Dictionaries should be enumerated through because the pipeline does not enumerate through them. foreach (DictionaryEntry entry in dictionary) @@ -324,7 +323,7 @@ internal static GridHeader ConstructGridHeader(PSObject input, OutGridViewComman internal abstract void ProcessInputObject(PSObject input); } - internal class ScalarTypeHeader : GridHeader + internal sealed class ScalarTypeHeader : GridHeader { private readonly Type _originalScalarType; @@ -350,7 +349,7 @@ internal override void ProcessInputObject(PSObject input) } } - internal class NonscalarTypeHeader : GridHeader + internal sealed class NonscalarTypeHeader : GridHeader { private readonly AppliesTo _appliesTo = null; @@ -454,7 +453,7 @@ internal override void ProcessInputObject(PSObject input) } } - internal class HeteroTypeHeader : GridHeader + internal sealed class HeteroTypeHeader : GridHeader { internal HeteroTypeHeader(OutGridViewCommand parentCmd, PSObject input) : base(parentCmd) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs index 3f22caf1e7b..ef9b0528c75 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/OutWindowProxy.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Commands { - internal class OutWindowProxy : IDisposable + internal sealed class OutWindowProxy : IDisposable { private const string OutGridViewWindowClassName = "Microsoft.Management.UI.Internal.OutGridViewWindow"; private const string OriginalTypePropertyName = "OriginalType"; @@ -58,20 +58,11 @@ internal OutWindowProxy(string title, OutputModeOption outPutMode, OutGridViewCo /// An array of types to add. internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] types) { - if (propertyNames == null) - { - throw new ArgumentNullException(nameof(propertyNames)); - } + ArgumentNullException.ThrowIfNull(propertyNames); - if (displayNames == null) - { - throw new ArgumentNullException(nameof(displayNames)); - } + ArgumentNullException.ThrowIfNull(displayNames); - if (types == null) - { - throw new ArgumentNullException(nameof(types)); - } + ArgumentNullException.ThrowIfNull(types); try { @@ -80,8 +71,7 @@ internal void AddColumns(string[] propertyNames, string[] displayNames, Type[] t catch (TargetInvocationException ex) { // Verify if this is an error loading the System.Core dll. - FileNotFoundException fileNotFoundEx = ex.InnerException as FileNotFoundException; - if (fileNotFoundEx != null && fileNotFoundEx.FileName.Contains("System.Core")) + if (ex.InnerException is FileNotFoundException fileNotFoundEx && fileNotFoundEx.FileName.Contains("System.Core")) { _parentCmdlet.ThrowTerminatingError( new ErrorRecord(new InvalidOperationException( @@ -177,10 +167,7 @@ private void AddExtraProperties(PSObject staleObject, PSObject liveObject) /// internal void AddItem(PSObject livePSObject) { - if (livePSObject == null) - { - throw new ArgumentNullException(nameof(livePSObject)); - } + ArgumentNullException.ThrowIfNull(livePSObject); if (_headerInfo == null) { @@ -203,10 +190,7 @@ internal void AddItem(PSObject livePSObject) /// internal void AddHeteroViewItem(PSObject livePSObject) { - if (livePSObject == null) - { - throw new ArgumentNullException(nameof(livePSObject)); - } + ArgumentNullException.ThrowIfNull(livePSObject); if (_headerInfo == null) { @@ -230,13 +214,7 @@ internal void ShowWindow() } } - internal void BlockUntillClosed() - { - if (_closedEvent != null) - { - _closedEvent.WaitOne(); - } - } + internal void BlockUntilClosed() => _closedEvent?.WaitOne(); /// /// Implements IDisposable logic. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs index 77f80c269a3..38cc9668856 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/ScalarTypeColumnInfo.cs @@ -6,7 +6,7 @@ namespace Microsoft.PowerShell.Commands { - internal class ScalarTypeColumnInfo : ColumnInfo + internal sealed class ScalarTypeColumnInfo : ColumnInfo { private readonly Type _type; @@ -29,7 +29,7 @@ internal override object GetValue(PSObject liveObject) } } - internal class TypeNameColumnInfo : ColumnInfo + internal sealed class TypeNameColumnInfo : ColumnInfo { internal TypeNameColumnInfo(string staleObjectPropertyName, string displayName) : base(staleObjectPropertyName, displayName) @@ -43,7 +43,7 @@ internal override object GetValue(PSObject liveObject) } } - internal class ToStringColumnInfo : ColumnInfo + internal sealed class ToStringColumnInfo : ColumnInfo { private readonly OutGridViewCommand _parentCmdlet; @@ -60,7 +60,7 @@ internal override object GetValue(PSObject liveObject) } } - internal class IndexColumnInfo : ColumnInfo + internal sealed class IndexColumnInfo : ColumnInfo { private int _index = 0; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs index 216d9121d54..e152bb7c973 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/OutGridView/TableView.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.Commands { - internal class TableView + internal sealed class TableView { private PSPropertyExpressionFactory _expressionFactory; private TypeInfoDataBase _typeInfoDatabase; @@ -69,14 +69,10 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { - if (displayName == null) - { - // Database does not provide a label(DisplayName) for the current property, use the expression value instead. - displayName = fpt.expression.expressionValue; - } + // 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) { @@ -101,8 +97,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, TableControlBody tableBod } else { - TextToken tt = token as TextToken; - if (tt != null) + if (token is TextToken tt) { displayName = _typeInfoDatabase.displayResourceManagerCache.GetTextTokenString(tt); columnInfo = new OriginalColumnInfo(tt.text, displayName, tt.text, parentCmdlet); @@ -170,10 +165,7 @@ internal HeaderInfo GenerateHeaderInfo(PSObject input, OutGridViewCommand parent propertyName = (string)key; } - if (propertyName == null) - { - propertyName = association.ResolvedExpression.ToString(); - } + propertyName ??= association.ResolvedExpression.ToString(); ColumnInfo columnInfo = new OriginalColumnInfo(propertyName, propertyName, propertyName, parentCmdlet); @@ -233,10 +225,7 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition == null) - { - matchingRowDefinition = match.BestMatch as TableRowDefinition; - } + matchingRowDefinition ??= match.BestMatch as TableRowDefinition; if (matchingRowDefinition == null) { @@ -254,10 +243,7 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition == null) - { - matchingRowDefinition = match.BestMatch as TableRowDefinition; - } + matchingRowDefinition ??= match.BestMatch as TableRowDefinition; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs index 70967aa897b..16d4325f68a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/GetFormatDataCommand.cs @@ -4,7 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; +using System.Globalization; using System.Management.Automation; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; @@ -85,7 +85,7 @@ private static Dictionary> GetTypeGroupMap(IEnumerable typeReference.name).ToList(); + var typesInGroup = typeGroup.typeReferenceList.ConvertAll(static typeReference => typeReference.name); typeGroupMap.Add(typeGroup.name, typesInGroup); } } @@ -98,7 +98,7 @@ private static Dictionary> GetTypeGroupMap(IEnumerable protected override void ProcessRecord() { - // Remoting detection: + // 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, @@ -130,6 +130,7 @@ protected override void ProcessRecord() foreach (ViewDefinition definition in viewdefinitions) { + this.WriteVerbose(string.Format(CultureInfo.CurrentCulture, GetFormatDataStrings.ProcessViewDefinition, definition.name)); if (definition.isHelpFormatter) continue; @@ -140,22 +141,19 @@ protected override void ProcessRecord() PSControl control; - var tableControlBody = definition.mainControl as TableControlBody; - if (tableControlBody != null) + if (definition.mainControl is TableControlBody tableControlBody) { control = new TableControl(tableControlBody, definition); } else { - var listControlBody = definition.mainControl as ListControlBody; - if (listControlBody != null) + if (definition.mainControl is ListControlBody listControlBody) { control = new ListControl(listControlBody, definition); } else { - var wideControlBody = definition.mainControl as WideControlBody; - if (wideControlBody != null) + if (definition.mainControl is WideControlBody wideControlBody) { control = new WideControl(wideControlBody, definition); if (writeOldWay) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs index 3ccbe942829..c07539aa25a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/common/WriteFormatDataCommand.cs @@ -81,7 +81,7 @@ public string LiteralPath /// /// Force writing a file. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get @@ -98,7 +98,7 @@ public SwitchParameter Force /// /// Do not overwrite file if exists. /// - [Parameter()] + [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { @@ -118,7 +118,7 @@ public SwitchParameter NoClobber /// /// Include scriptblocks for export. /// - [Parameter()] + [Parameter] public SwitchParameter IncludeScriptBlock { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs index 091903f011a..7e9dab8a203 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-hex/Format-Hex.cs @@ -24,7 +24,7 @@ public sealed class FormatHex : PSCmdlet private const int BUFFERSIZE = 16; /// - /// For cases where a homogenous collection of bytes or other items are directly piped in, we collect all the + /// 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(); @@ -37,7 +37,7 @@ public sealed class FormatHex : PSCmdlet private bool _groupInput = true; /// - /// Keep track of prior input types to determine if we're given a heterogenous collection. + /// Keep track of prior input types to determine if we're given a heterogeneous collection. /// private Type _lastInputType; @@ -47,14 +47,14 @@ public sealed class FormatHex : PSCmdlet /// Gets or sets the path of file(s) to process. /// [Parameter(Mandatory = true, Position = 0, ParameterSetName = "Path")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string[] Path { get; set; } /// /// Gets or sets the literal path of file to process. /// [Parameter(Mandatory = true, ParameterSetName = "LiteralPath")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [Alias("PSPath", "LP")] public string[] LiteralPath { get; set; } @@ -68,8 +68,8 @@ public sealed class FormatHex : PSCmdlet /// Gets or sets the type of character encoding for InputObject. /// [Parameter(ParameterSetName = "ByInputObject")] - [ArgumentToEncodingTransformationAttribute()] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -85,7 +85,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Gets or sets count of bytes to read from the input stream. @@ -391,7 +391,6 @@ private byte[] ConvertToBytes(object inputObject) byte[] result = null; int elements = 1; bool isArray = false; - bool isBool = false; bool isEnum = false; if (baseType.IsArray) { @@ -424,11 +423,6 @@ private byte[] ConvertToBytes(object inputObject) _lastInputType = baseType; } - if (baseType == typeof(bool)) - { - isBool = true; - } - var elementSize = Marshal.SizeOf(baseType); result = new byte[elementSize * elements]; if (!isArray) @@ -450,11 +444,6 @@ private byte[] ConvertToBytes(object inputObject) { toBytes = Convert.ChangeType(obj, baseType); } - else if (isBool) - { - // bool is 1 byte apparently - toBytes = Convert.ToByte(obj); - } else { toBytes = obj; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs index 7237cd46834..182ea53e258 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-list/Format-List.cs @@ -8,9 +8,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-table command. + /// 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 { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs index 9e064ba37db..693a799c809 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-object/Format-Object.cs @@ -8,9 +8,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-custom command. It just calls the formatting engine on complex shape. + /// 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 { /// @@ -31,6 +32,7 @@ public FormatCustomCommand() /// will be determined using property sets, etc. /// [Parameter(Position = 0)] + [ValidateNotNullOrEmpty] public object[] Property { get { return _props; } @@ -40,10 +42,16 @@ public object[] Property private object[] _props; + /// + /// Gets or sets the properties to exclude from formatting. + /// + [Parameter] + public string[] ExcludeProperty { get; set; } + /// /// /// - [ValidateRangeAttribute(1, int.MaxValue)] + [ValidateRange(1, int.MaxValue)] [Parameter] public int Depth { @@ -60,6 +68,18 @@ 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()); @@ -67,15 +87,17 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() parameters.mshParameterList = processor.ProcessParameters(_props, invocationContext); } - if (!string.IsNullOrEmpty(this.View)) + if (ExcludeProperty is not null) { - // we have a view command line switch - if (parameters.mshParameterList.Count != 0) + parameters.excludePropertyFilter = new PSPropertyExpressionFilter(ExcludeProperty); + + // ExcludeProperty implies -Property * for better UX + if (_props is null || _props.Length == 0) { - ReportCannotSpecifyViewAndProperty(); + ParameterProcessor processor = new(new FormatObjectParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); + parameters.mshParameterList = processor.ProcessParameters(new object[] { "*" }, invocationContext); } - - parameters.viewName = this.View; } parameters.groupByParameter = this.ProcessGroupByParameter(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs index e831981568e..a9e35fcdbc3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-table/Format-Table.cs @@ -8,9 +8,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-table command. + /// 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 { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs index 8d80462c12f..c6aef5c20be 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/format-wide/Format-Wide.cs @@ -10,9 +10,10 @@ namespace Microsoft.PowerShell.Commands { /// - /// Implementation for the format-table command. + /// 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 { /// @@ -41,23 +42,19 @@ public object Property private object _prop; /// - /// Optional, non positional parameter. + /// 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 - { - if (_autosize.HasValue) - return _autosize.Value; - return false; - } - - set - { - _autosize = value; - } + get => _autosize.GetValueOrDefault(); + set => _autosize = value; } private bool? _autosize = null; @@ -67,20 +64,11 @@ public SwitchParameter AutoSize /// /// [Parameter] - [ValidateRangeAttribute(1, int.MaxValue)] + [ValidateRange(1, int.MaxValue)] public int Column { - get - { - if (_column.HasValue) - return _column.Value; - return -1; - } - - set - { - _column = value; - } + get => _column.GetValueOrDefault(-1); + set => _column = value; } private int? _column = null; @@ -91,6 +79,18 @@ 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()); @@ -98,34 +98,33 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() parameters.mshParameterList = processor.ProcessParameters(new object[] { _prop }, invocationContext); } - if (!string.IsNullOrEmpty(this.View)) + if (ExcludeProperty is not null) { - // we have a view command line switch - if (parameters.mshParameterList.Count != 0) + parameters.excludePropertyFilter = new PSPropertyExpressionFilter(ExcludeProperty); + + // ExcludeProperty implies -Property * for better UX + if (_prop is null) { - ReportCannotSpecifyViewAndProperty(); + ParameterProcessor processor = new(new FormatWideParameterDefinition()); + TerminatingErrorContext invocationContext = new(this); + parameters.mshParameterList = processor.ProcessParameters(new object[] { "*" }, invocationContext); } - - parameters.viewName = this.View; } // we cannot specify -column and -autosize, they are mutually exclusive - if (_autosize.HasValue && _column.HasValue) + if (AutoSize && _column.HasValue) { - if (_autosize.Value) - { - // the user specified -autosize:true AND a column number - string msg = StringUtil.Format(FormatAndOut_format_xxx.CannotSpecifyAutosizeAndColumnsError); + // 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 errorRecord = new( + new InvalidDataException(), + "FormatCannotSpecifyAutosizeAndColumns", + ErrorCategory.InvalidArgument, + null); - errorRecord.ErrorDetails = new ErrorDetails(msg); - this.ThrowTerminatingError(errorRecord); - } + errorRecord.ErrorDetails = new ErrorDetails(msg); + this.ThrowTerminatingError(errorRecord); } parameters.groupByParameter = this.ProcessGroupByParameter(); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs index 2fbdb73dc9c..e585fc1ce08 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-file/Out-File.cs @@ -74,8 +74,8 @@ public string LiteralPath /// Encoding optional flag. /// [Parameter(Position = 1)] - [ArgumentToEncodingTransformationAttribute()] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -91,12 +91,12 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Property that sets append parameter. /// - [Parameter()] + [Parameter] public SwitchParameter Append { get { return _append; } @@ -109,7 +109,7 @@ public SwitchParameter Append /// /// Property that sets force parameter. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get { return _force; } @@ -122,7 +122,7 @@ public SwitchParameter Force /// /// Property that prevents file overwrite. /// - [Parameter()] + [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { @@ -136,7 +136,7 @@ public SwitchParameter NoClobber /// /// Optional, number of columns to use when writing to device. /// - [ValidateRangeAttribute(2, int.MaxValue)] + [ValidateRange(2, int.MaxValue)] [Parameter] public int Width { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs index cbd19a17f4f..94f3fe6a50e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-printer/PrinterLineOutput.cs @@ -5,6 +5,8 @@ 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 { @@ -62,11 +64,25 @@ internal override int RowNumber internal override void WriteLine(string s) { CheckStopProcessing(); - // delegate the action to the helper, - // that will properly break the string into - // screen lines - _writeLineHelper.WriteLine(s, this.ColumnNumber); + + // 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 /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs index 512bf1048e0..0f485bec06a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/FormatAndOutput/out-string/Out-String.cs @@ -34,7 +34,7 @@ public SwitchParameter Stream /// /// Optional, number of columns to use when writing to device. /// - [ValidateRangeAttribute(2, int.MaxValue)] + [ValidateRange(2, int.MaxValue)] [Parameter] public int Width { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs index 053f99f897d..3af01087ad7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-Error.cs @@ -12,7 +12,7 @@ namespace Microsoft.PowerShell.Commands /// Class for Get-Error implementation. /// [Cmdlet(VerbsCommon.Get, "Error", - HelpUri = "https://docs.microsoft.com/powershell/module/microsoft.powershell.utility/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 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs index 469e18926d8..c675a0f6dc1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Get-PSBreakpoint.cs @@ -16,8 +16,7 @@ public enum BreakpointType /// Breakpoint on a line within a script Line, - /// - /// Breakpoint on a variable + /// Breakpoint on a variable Variable, /// Breakpoint on a command @@ -107,7 +106,7 @@ protected override void ProcessRecord() breakpoints = Filter( breakpoints, Id, - (Breakpoint breakpoint, int id) => breakpoint.Id == id); + static (Breakpoint breakpoint, int id) => breakpoint.Id == id); } else if (ParameterSetName.Equals(CommandParameterSetName, StringComparison.OrdinalIgnoreCase)) { @@ -116,7 +115,7 @@ protected override void ProcessRecord() Command, (Breakpoint breakpoint, string command) => { - if (!(breakpoint is CommandBreakpoint commandBreakpoint)) + if (breakpoint is not CommandBreakpoint commandBreakpoint) { return false; } @@ -131,7 +130,7 @@ protected override void ProcessRecord() Variable, (Breakpoint breakpoint, string variable) => { - if (!(breakpoint is VariableBreakpoint variableBreakpoint)) + if (breakpoint is not VariableBreakpoint variableBreakpoint) { return false; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs index fee8b3ab27c..7b93b555c5c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetAliasCommand.cs @@ -51,6 +51,7 @@ public string[] Exclude /// which scope the aliases are retrieved from. /// [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } /// @@ -181,7 +182,7 @@ private void WriteMatches(string value, string parametersetname) } results.Sort( - (AliasInfo left, AliasInfo right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)); + static (AliasInfo left, AliasInfo right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)); foreach (AliasInfo alias in results) { this.WriteObject(alias); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs index 40e0bbeefd7..6717cc7196b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetDateCommand.cs @@ -78,7 +78,7 @@ public long UnixTimeSeconds /// Allows the user to override the year. /// [Parameter] - [ValidateRangeAttribute(1, 9999)] + [ValidateRange(1, 9999)] public int Year { get @@ -100,7 +100,7 @@ public int Year /// Allows the user to override the month. /// [Parameter] - [ValidateRangeAttribute(1, 12)] + [ValidateRange(1, 12)] public int Month { get @@ -122,7 +122,7 @@ public int Month /// Allows the user to override the day. /// [Parameter] - [ValidateRangeAttribute(1, 31)] + [ValidateRange(1, 31)] public int Day { get @@ -144,7 +144,7 @@ public int Day /// Allows the user to override the hour. /// [Parameter] - [ValidateRangeAttribute(0, 23)] + [ValidateRange(0, 23)] public int Hour { get @@ -166,7 +166,7 @@ public int Hour /// Allows the user to override the minute. /// [Parameter] - [ValidateRangeAttribute(0, 59)] + [ValidateRange(0, 59)] public int Minute { get @@ -188,7 +188,7 @@ public int Minute /// Allows the user to override the second. /// [Parameter] - [ValidateRangeAttribute(0, 59)] + [ValidateRange(0, 59)] public int Second { get @@ -210,7 +210,7 @@ public int Second /// Allows the user to override the millisecond. /// [Parameter] - [ValidateRangeAttribute(0, 999)] + [ValidateRange(0, 999)] public int Millisecond { get @@ -376,8 +376,6 @@ protected override void ProcessRecord() } } - private static readonly DateTime s_epoch = new(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); - /// /// This is more an implementation of the UNIX strftime. /// @@ -501,7 +499,7 @@ private string UFormatDateString(DateTime dateTime) break; case 's': - sb.Append(StringUtil.Format("{0:0}", dateTime.ToUniversalTime().Subtract(s_epoch).TotalSeconds)); + sb.Append(StringUtil.Format("{0:0}", dateTime.ToUniversalTime().Subtract(DateTime.UnixEpoch).TotalSeconds)); break; case 'T': diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs index 42360983c4e..f4ab18ac75a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventCommand.cs @@ -20,7 +20,7 @@ public class GetEventCommand : PSCmdlet /// An identifier for this event subscription. /// [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "BySource")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string SourceIdentifier { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs index b3bd99b7bdf..f95c708fa50 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetEventSubscriberCommand.cs @@ -20,7 +20,7 @@ public class GetEventSubscriberCommand : PSCmdlet /// An identifier for this event subscription. /// [Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ParameterSetName = "BySource")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string SourceIdentifier { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs index 40ea1d187d5..6f4b2f53cef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetHash.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics; using System.IO; using System.Management.Automation; using System.Security.Cryptography; @@ -68,15 +69,6 @@ public string[] LiteralPath [Parameter(Mandatory = true, ParameterSetName = StreamParameterSet, Position = 0)] public Stream InputStream { get; set; } - /// - /// BeginProcessing() override. - /// This is for hash function init. - /// - protected override void BeginProcessing() - { - InitHasher(Algorithm); - } - /// /// ProcessRecord() override. /// This is for paths collecting from pipe. @@ -133,6 +125,26 @@ protected override void ProcessRecord() } } + 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. @@ -141,12 +153,9 @@ protected override void EndProcessing() { if (ParameterSetName == StreamParameterSet) { - byte[] bytehash = null; - string hash = null; + byte[] bytehash = ComputeHash(InputStream); - bytehash = hasher.ComputeHash(InputStream); - - hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); + string hash = Convert.ToHexString(bytehash); WriteHashResult(Algorithm, hash, string.Empty); } } @@ -159,7 +168,6 @@ protected override void EndProcessing() /// Boolean value indicating whether the hash calculation succeeded or failed. private bool ComputeFileHash(string path, out string hash) { - byte[] bytehash = null; Stream openfilestream = null; hash = null; @@ -167,9 +175,9 @@ private bool ComputeFileHash(string path, out string hash) try { openfilestream = File.OpenRead(path); + byte[] bytehash = ComputeHash(openfilestream); - bytehash = hasher.ComputeHash(openfilestream); - hash = BitConverter.ToString(bytehash).Replace("-", string.Empty); + hash = Convert.ToHexString(bytehash); } catch (FileNotFoundException ex) { @@ -259,11 +267,6 @@ public string Algorithm private string _Algorithm = HashAlgorithmNames.SHA256; - /// - /// Hash algorithm is used. - /// - protected HashAlgorithm hasher; - /// /// Hash algorithm names. /// @@ -275,40 +278,6 @@ internal static class HashAlgorithmNames public const string SHA384 = "SHA384"; public const string SHA512 = "SHA512"; } - - /// - /// Init a hash algorithm. - /// - protected void InitHasher(string Algorithm) - { - try - { - switch (Algorithm) - { - case HashAlgorithmNames.SHA1: - hasher = SHA1.Create(); - break; - case HashAlgorithmNames.SHA256: - hasher = SHA256.Create(); - break; - case HashAlgorithmNames.SHA384: - hasher = SHA384.Create(); - break; - case HashAlgorithmNames.SHA512: - hasher = SHA512.Create(); - break; - case HashAlgorithmNames.MD5: - hasher = MD5.Create(); - break; - } - } - catch - { - // Seems it will never throw! Remove? - Exception exc = new NotSupportedException(UtilityCommonStrings.AlgorithmTypeNotSupported); - ThrowTerminatingError(new ErrorRecord(exc, "AlgorithmTypeNotSupported", ErrorCategory.NotImplemented, null)); - } - } } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs index 2fd9a499012..0b11af84200 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetMember.cs @@ -230,8 +230,7 @@ protected override void ProcessRecord() { if (!Force) { - PSMethod memberAsPSMethod = member as PSMethod; - if ((memberAsPSMethod != null) && (memberAsPSMethod.IsSpecial)) + if ((member is PSMethod memberAsPSMethod) && (memberAsPSMethod.IsSpecial)) { continue; } @@ -249,7 +248,7 @@ protected override void ProcessRecord() } } - private class MemberComparer : System.Collections.Generic.IComparer + private sealed class MemberComparer : System.Collections.Generic.IComparer { public int Compare(MemberDefinition first, MemberDefinition second) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs index 7d02713d801..c77c25c5f4f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommand.cs @@ -1,199 +1,18 @@ // 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.Security.Cryptography; -using System.Threading; - -using Debug = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands { /// - /// This class implements get-random cmdlet. + /// This class implements `Get-Random` cmdlet. /// - /// - [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommand.RandomNumberParameterSet, + [Cmdlet(VerbsCommon.Get, "Random", DefaultParameterSetName = GetRandomCommandBase.RandomNumberParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097016", RemotingCapability = RemotingCapability.None)] - [OutputType(typeof(Int32), typeof(Int64), typeof(double))] - public class GetRandomCommand : PSCmdlet + [OutputType(typeof(int), typeof(long), typeof(double))] + public sealed class GetRandomCommand : GetRandomCommandBase { - #region Parameter set handling - - private 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 == GetRandomCommand.RandomListItemParameterSet - || ParameterSetName == GetRandomCommand.ShuffleParameterSet) - { - _effectiveParameterSet = MyParameterSet.RandomListItem; - } - else if (ParameterSetName.Equals(GetRandomCommand.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 runspaces 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 - { - GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); - GetRandomCommand.s_runspaceGeneratorMap.Remove(((Runspace)sender).InstanceId); - } - finally - { - GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); - } - - break; - } - } - - private PolymorphicRandomNumberGenerator _generator; - - /// - /// Gets and sets generator associated with the current runspace. - /// - private PolymorphicRandomNumberGenerator Generator - { - get - { - if (_generator == null) - { - Guid runspaceId = Context.CurrentRunspace.InstanceId; - - bool needToInitialize = false; - try - { - GetRandomCommand.s_runspaceGeneratorMapLock.EnterReadLock(); - needToInitialize = !GetRandomCommand.s_runspaceGeneratorMap.TryGetValue(runspaceId, out _generator); - } - finally - { - GetRandomCommand.s_runspaceGeneratorMapLock.ExitReadLock(); - } - - if (needToInitialize) - { - Generator = new PolymorphicRandomNumberGenerator(); - } - } - - return _generator; - } - - set - { - _generator = value; - Runspace myRunspace = Context.CurrentRunspace; - - try - { - GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); - if (!GetRandomCommand.s_runspaceGeneratorMap.ContainsKey(myRunspace.InstanceId)) - { - // make sure we won't leave the generator around after runspace exits - myRunspace.StateChanged += CurrentRunspace_StateChanged; - } - - GetRandomCommand.s_runspaceGeneratorMap[myRunspace.InstanceId] = _generator; - } - finally - { - GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); - } - } - } - - #endregion - - #region Common parameters - /// /// Seed used to reinitialize random numbers generator. /// @@ -201,194 +20,6 @@ private PolymorphicRandomNumberGenerator Generator [ValidateNotNull] public int? SetSeed { get; set; } - #endregion Common parameters - - #region Parameters for RandomNumberParameterSet - - /// - /// Maximum number to generate. - /// - [Parameter(ParameterSetName = RandomNumberParameterSet, Position = 0)] - public object Maximum { get; set; } - - /// - /// 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 Int64) - { - 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; - - /// - /// 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; } - - /// - /// 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. - /// - /// - /// - /// - private Int64 GetRandomInt64(Int64 minValue, Int64 maxValue) - { - // Randomly generate eight bytes and convert the byte array to UInt64 - var buffer = new byte[sizeof(UInt64)]; - UInt64 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. - UInt64 uint64Diff = (UInt64)bigIntegerDiff; - - // Calculate the number of bits to represent the diff in type UInt64 - int bitsToRepresentDiff = 0; - UInt64 diffCopy = uint64Diff; - for (; diffCopy != 0; bitsToRepresentDiff++) - { - diffCopy >>= 1; - } - // Get the mask for the number of bits - UInt64 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 (Int64)randomNumber; - } - /// /// This method implements the BeginProcessing method for get-random command. /// @@ -399,335 +30,7 @@ protected override void BeginProcessing() Generator = new PolymorphicRandomNumberGenerator(SetSeed.Value); } - if (EffectiveParameterSet == MyParameterSet.RandomNumber) - { - object maxOperand = ProcessOperand(Maximum); - object minOperand = ProcessOperand(Minimum); - - if (IsInt(maxOperand) && IsInt(minOperand)) - { - int minValue = minOperand != null ? (int)minOperand : 0; - int maxValue = maxOperand != null ? (int)maxOperand : int.MaxValue; - - if (minValue >= maxValue) - { - ThrowMinGreaterThanOrEqualMax(minValue, maxValue); - } - - for (int i = 0; i < Count; i++) - { - int randomNumber = Generator.Next(minValue, maxValue); - Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); - Debug.Assert(randomNumber < maxValue, "random number < upper bound"); - - WriteObject(randomNumber); - } - } - else if ((IsInt64(maxOperand) || IsInt(maxOperand)) && (IsInt64(minOperand) || IsInt(minOperand))) - { - Int64 minValue = minOperand != null ? ((minOperand is Int64) ? (Int64)minOperand : (int)minOperand) : 0; - Int64 maxValue = maxOperand != null ? ((maxOperand is Int64) ? (Int64)maxOperand : (int)maxOperand) : Int64.MaxValue; - - if (minValue >= maxValue) - { - ThrowMinGreaterThanOrEqualMax(minValue, maxValue); - } - - for (int i = 0; i < Count; i++) - { - Int64 randomNumber = GetRandomInt64(minValue, maxValue); - Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); - Debug.Assert(randomNumber < maxValue, "random number < upper bound"); - - WriteObject(randomNumber); - } - } - else - { - double minValue = (minOperand is double) ? (double)minOperand : ConvertToDouble(Minimum, 0.0); - double maxValue = (maxOperand is double) ? (double)maxOperand : ConvertToDouble(Maximum, double.MaxValue); - - if (minValue >= maxValue) - { - ThrowMinGreaterThanOrEqualMax(minValue, maxValue); - } - - for (int i = 0; i < Count; i++) - { - double randomNumber = GetRandomDouble(minValue, maxValue); - Debug.Assert(minValue <= randomNumber, "lower bound <= random number"); - Debug.Assert(randomNumber < maxValue, "random number < upper bound"); - - WriteObject(randomNumber); - } - } - } - else if (EffectiveParameterSet == MyParameterSet.RandomListItem) - { - _chosenListItems = new List(); - _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 get-random command. - /// - protected override void ProcessRecord() - { - if (EffectiveParameterSet == MyParameterSet.RandomListItem) - { - if (ParameterSetName == ShuffleParameterSet) - { - // 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 get-random command. - /// - 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 class PolymorphicRandomNumberGenerator - { - /// - /// Initializes a new instance of the class. - /// - public PolymorphicRandomNumberGenerator() - { - _cryptographicGenerator = RandomNumberGenerator.Create(); - _pseudoGenerator = null; - } - - 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 / Int32.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 == Int32.MaxValue); - - if (randomNumber < 0) - { - randomNumber += Int32.MaxValue; - } - - return randomNumber; - } - - /// - /// Returns a random integer that is within a specified range. - /// - /// The exclusive upper bound of the random number returned. - /// - 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. - /// - 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)Int32.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 . - /// - /// - private double InternalSampleLargeRange() - { - double randomNumber; - - do - { - randomNumber = InternalSample(); - } while (randomNumber == Int32.MaxValue); - - randomNumber += Int32.MaxValue; - return randomNumber; + base.BeginProcessing(); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetRandomCommandBase.cs new file mode 100644 index 00000000000..8e50b1cf5a9 --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetSecureRandomCommand.cs new file mode 100644 index 00000000000..e0ea7e68dbf --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs index b43a870dccb..09bc78d9693 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUnique.cs @@ -50,6 +50,13 @@ public SwitchParameter OnType } private bool _onType = false; + + /// + /// Gets or sets case insensitive switch for string comparison. + /// + [Parameter] + public SwitchParameter CaseInsensitive { get; set; } + #endregion Parameters #region Overrides @@ -72,15 +79,12 @@ protected override void ProcessRecord() else if (AsString) { string inputString = InputObject.ToString(); - if (_lastObjectAsString == null) - { - _lastObjectAsString = _lastObject.ToString(); - } + _lastObjectAsString ??= _lastObject.ToString(); if (string.Equals( inputString, _lastObjectAsString, - StringComparison.CurrentCulture)) + CaseInsensitive.IsPresent ? StringComparison.CurrentCultureIgnoreCase : StringComparison.CurrentCulture)) { isUnique = false; } @@ -91,13 +95,10 @@ protected override void ProcessRecord() } else // compare as objects { - if (_comparer == null) - { - _comparer = new ObjectCommandComparer( - true, // ascending (doesn't matter) - CultureInfo.CurrentCulture, - true); // case-sensitive - } + _comparer ??= new ObjectCommandComparer( + ascending: true, + CultureInfo.CurrentCulture, + caseSensitive: !CaseInsensitive.IsPresent); isUnique = (_comparer.Compare(InputObject, _lastObject) != 0); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs index e8dcfbe254a..c21165301e2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetUptime.cs @@ -36,16 +36,15 @@ protected override void ProcessRecord() { TimeSpan uptime = TimeSpan.FromSeconds(Stopwatch.GetTimestamp() / Stopwatch.Frequency); - switch (ParameterSetName) + if (Since) { - case TimespanParameterSet: - // return TimeSpan of time since the system started up - WriteObject(uptime); - break; - case SinceParameterSet: - // return Datetime when the system started up - WriteObject(DateTime.Now.Subtract(uptime)); - break; + // 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 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs index 1ec93b0f1d7..61a0fe1a390 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/GetVerbCommand.cs @@ -1,10 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System; -using System.Collections.ObjectModel; using System.Management.Automation; -using System.Reflection; +using static System.Management.Automation.Verbs; namespace Microsoft.PowerShell.Commands { @@ -19,6 +17,7 @@ public class GetVerbCommand : Cmdlet /// Optional Verb filter. /// [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, Position = 0)] + [ArgumentCompleter(typeof(VerbArgumentCompleter))] public string[] Verb { get; set; @@ -39,45 +38,9 @@ public string[] Group /// protected override void ProcessRecord() { - Type[] verbTypes = new Type[] { typeof(VerbsCommon), typeof(VerbsCommunications), typeof(VerbsData), - typeof(VerbsDiagnostic), typeof(VerbsLifecycle), typeof(VerbsOther), typeof(VerbsSecurity) }; - - Collection matchingVerbs = SessionStateUtilities.CreateWildcardsFromStrings( - this.Verb, - WildcardOptions.IgnoreCase - ); - - foreach (Type type in verbTypes) + foreach (VerbInfo verb in FilterByVerbsAndGroups(Verb, Group)) { - string groupName = type.Name.Substring(5); - if (this.Group != null) - { - if (!SessionStateUtilities.CollectionContainsValue(this.Group, groupName, StringComparer.OrdinalIgnoreCase)) - { - continue; - } - } - - foreach (FieldInfo field in type.GetFields()) - { - if (field.IsLiteral) - { - if (this.Verb != null) - { - if (!SessionStateUtilities.MatchesAnyWildcardPattern(field.Name, matchingVerbs, false)) - { - continue; - } - } - - VerbInfo verb = new(); - verb.Verb = field.Name; - verb.AliasPrefix = VerbAliasPrefixes.GetVerbAliasPrefix(field.Name); - verb.Group = groupName; - verb.Description = VerbDescriptions.GetVerbDescription(field.Name); - WriteObject(verb); - } - } + WriteObject(verb); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs index d63ff694281..1f527258939 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Group-Object.cs @@ -153,7 +153,7 @@ private static string BuildName(List propValues) foreach (object item in propertyValueItems) { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", item.ToString()); + sb.Append(CultureInfo.CurrentCulture, $"{item}, "); } sb = sb.Length > length ? sb.Remove(sb.Length - 2, 2) : sb; @@ -161,7 +161,7 @@ private static string BuildName(List propValues) } else { - sb.AppendFormat(CultureInfo.InvariantCulture, "{0}, ", propValuePropertyValue.ToString()); + sb.Append(CultureInfo.CurrentCulture, $"{propValuePropertyValue}, "); } } } @@ -392,10 +392,7 @@ protected override void ProcessRecord() if (!_hasProcessedFirstInputObject) { - if (Property == null) - { - Property = OrderByProperty.GetDefaultKeyPropertySet(InputObject); - } + Property ??= OrderByProperty.GetDefaultKeyPropertySet(InputObject); _orderByProperty.ProcessExpressionParameter(this, Property); @@ -443,7 +440,7 @@ private void UpdateOrderPropertyTypeInfo(List curren { if (_propertyTypesCandidate == null) { - _propertyTypesCandidate = currentEntryOrderValues.Select(c => PSObject.Base(c.PropertyValue)?.GetType()).ToArray(); + _propertyTypesCandidate = currentEntryOrderValues.Select(static c => PSObject.Base(c.PropertyValue)?.GetType()).ToArray(); return; } @@ -491,7 +488,7 @@ protected override void EndProcessing() { // using OrderBy to get stable sort. // fast path when we only have the same object types to group - foreach (var entry in _entriesToOrder.OrderBy(e => e, _orderByPropertyComparer)) + foreach (var entry in _entriesToOrder.Order(_orderByPropertyComparer)) { DoOrderedGrouping(entry, NoElement, _groups, _tupleToGroupInfoMappingDictionary, _orderByPropertyComparer); if (Stopping) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs index d772258227b..d01d144caca 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImplicitRemotingCommands.cs @@ -73,8 +73,8 @@ public SwitchParameter Force /// Encoding optional flag. /// [Parameter] - [ArgumentToEncodingTransformationAttribute()] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -90,7 +90,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; #endregion Parameters @@ -443,10 +443,7 @@ public string[] Module set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _PSSnapins = value; _commandParameterSpecified = true; @@ -729,8 +726,7 @@ private ErrorRecord GetErrorFromRemoteCommand(string commandName, RuntimeExcepti // // handle recognized types of exceptions first // - RemoteException remoteException = runtimeException as RemoteException; - if ((remoteException != null) && (remoteException.SerializedRemoteException != null)) + if ((runtimeException is RemoteException remoteException) && (remoteException.SerializedRemoteException != null)) { if (Deserializer.IsInstanceOfType(remoteException.SerializedRemoteException, typeof(CommandNotFoundException))) { @@ -1044,10 +1040,7 @@ private List RehydrateList(string commandName, PSObject deserializedObject private List RehydrateList(string commandName, object deserializedList, Func itemRehydrator) { - if (itemRehydrator == null) - { - itemRehydrator = (PSObject pso) => ConvertTo(commandName, pso); - } + itemRehydrator ??= (PSObject pso) => ConvertTo(commandName, pso); List result = null; @@ -1068,17 +1061,14 @@ private List RehydrateList(string commandName, object deserializedList, Fu private Dictionary RehydrateDictionary( string commandName, - PSObject deserializedObject, + PSObject deserializedObject, string propertyName, Func valueRehydrator) { Dbg.Assert(deserializedObject != null, "deserializedObject parameter != null"); Dbg.Assert(!string.IsNullOrEmpty(propertyName), "propertyName parameter != null"); - if (valueRehydrator == null) - { - valueRehydrator = (PSObject pso) => ConvertTo(commandName, pso); - } + valueRehydrator ??= (PSObject pso) => ConvertTo(commandName, pso); Dictionary result = new(); PSPropertyInfo deserializedDictionaryProperty = deserializedObject.Properties[propertyName]; @@ -1310,13 +1300,23 @@ private ParameterMetadata RehydrateParameterMetadata(PSObject deserializedParame parameterType); } - private static bool IsProxyForCmdlet(Dictionary parameters) + 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 - foreach (string commonParameterName in Cmdlet.CommonParameters) + // 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; @@ -1584,8 +1584,7 @@ private PowerShell BuildPowerShellForGetFormatData() powerShell.AddParameter("TypeName", this.FormatTypeName); // For remote PS version 5.1 and greater, we need to include the new -PowerShellVersion parameter - RemoteRunspace remoteRunspace = Session.Runspace as RemoteRunspace; - if ((remoteRunspace != null) && (remoteRunspace.ServerVersion != null) && + if ((Session.Runspace is RemoteRunspace remoteRunspace) && (remoteRunspace.ServerVersion != null) && (remoteRunspace.ServerVersion >= new Version(5, 1))) { powerShell.AddParameter("PowerShellVersion", PSVersionInfo.PSVersion); @@ -1706,7 +1705,7 @@ private void HandleHostCallReceived(object sender, RemoteDataEventArgs GetRemoteCommandMetadata(out Dictionary alias2resolvedCommandName) { bool isReleaseCandidateBackcompatibilityMode = - this.Session.Runspace.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; + this.Session.Runspace.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersion_2_0; alias2resolvedCommandName = new Dictionary(StringComparer.OrdinalIgnoreCase); if ((this.CommandName == null) || (this.CommandName.Length == 0) || @@ -1917,7 +1916,7 @@ internal List GenerateProxyModule( #endregion } - internal class ImplicitRemotingCodeGenerator + internal sealed class ImplicitRemotingCodeGenerator { internal static readonly Version VersionOfScriptWriter = new(1, 0); @@ -1951,20 +1950,17 @@ internal ImplicitRemotingCodeGenerator( /// Connection URI associated with the remote runspace. private string GetConnectionString() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo connectionInfo) { return connectionInfo.ConnectionUri.ToString(); } - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return vmConnectionInfo.ComputerName; } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return containerConnectionInfo.ComputerName; } @@ -2024,7 +2020,6 @@ private static void GenerateSectionSeparator(TextWriter writer) PrivateData = @{{ ImplicitRemoting = $true - ImplicitSessionId = '{4}' }} }} "; @@ -2043,8 +2038,7 @@ private void GenerateManifest(TextWriter writer, string psm1fileName, string for CodeGeneration.EscapeSingleQuotedStringContent(_moduleGuid.ToString()), CodeGeneration.EscapeSingleQuotedStringContent(StringUtil.Format(ImplicitRemotingStrings.ProxyModuleDescription, this.GetConnectionString())), CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(psm1fileName)), - CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(formatPs1xmlFileName)), - _remoteRunspaceInfo.InstanceId); + CodeGeneration.EscapeSingleQuotedStringContent(Path.GetFileName(formatPs1xmlFileName))); } #endregion @@ -2111,7 +2105,9 @@ private void GenerateModuleHeader(TextWriter 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 - string versionOfScriptGenerator = "[" + typeof(ExportPSSessionCommand).AssemblyQualifiedName + "]" + "::VersionOfScriptGenerator"; + Type type = typeof(ExportPSSessionCommand); + string asmName = type.Assembly.GetName().Name; + string versionOfScriptGenerator = $"[{type.FullName}, {asmName}]::VersionOfScriptGenerator"; GenerateTopComment(writer); writer.Write( HeaderTemplate, @@ -2253,64 +2249,68 @@ private string GenerateNewPSSessionOption() { StringBuilder result = new("& $script:NewPSSessionOption "); - RunspaceConnectionInfo runspaceConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as RunspaceConnectionInfo; - if (runspaceConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is RunspaceConnectionInfo runspaceConnectionInfo) { - result.AppendFormat(null, "-Culture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())); - result.AppendFormat(null, "-UICulture '{0}' ", CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())); + result.Append(null, $"-Culture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.Culture.ToString())}' "); + result.Append(null, $"-UICulture '{CodeGeneration.EscapeSingleQuotedStringContent(runspaceConnectionInfo.UICulture.ToString())}' "); - result.AppendFormat(null, "-CancelTimeOut {0} ", runspaceConnectionInfo.CancelTimeout); - result.AppendFormat(null, "-IdleTimeOut {0} ", runspaceConnectionInfo.IdleTimeout); - result.AppendFormat(null, "-OpenTimeOut {0} ", runspaceConnectionInfo.OpenTimeout); - result.AppendFormat(null, "-OperationTimeOut {0} ", runspaceConnectionInfo.OperationTimeout); + result.Append(null, $"-CancelTimeOut {runspaceConnectionInfo.CancelTimeout} "); + result.Append(null, $"-IdleTimeOut {runspaceConnectionInfo.IdleTimeout} "); + result.Append(null, $"-OpenTimeOut {runspaceConnectionInfo.OpenTimeout} "); + result.Append(null, $"-OperationTimeOut {runspaceConnectionInfo.OperationTimeout} "); } - WSManConnectionInfo wsmanConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (wsmanConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo) { - if (!wsmanConnectionInfo.UseCompression) { result.Append("-NoCompression "); } + if (!wsmanConnectionInfo.UseCompression) + { + result.Append("-NoCompression "); + } - if (wsmanConnectionInfo.NoEncryption) { result.Append("-NoEncryption "); } + if (wsmanConnectionInfo.NoEncryption) + { + result.Append("-NoEncryption "); + } - if (wsmanConnectionInfo.NoMachineProfile) { result.Append("-NoMachineProfile "); } + if (wsmanConnectionInfo.NoMachineProfile) + { + result.Append("-NoMachineProfile "); + } - if (wsmanConnectionInfo.UseUTF16) { result.Append("-UseUTF16 "); } + if (wsmanConnectionInfo.UseUTF16) + { + result.Append("-UseUTF16 "); + } - if (wsmanConnectionInfo.SkipCACheck) { result.Append("-SkipCACheck "); } + if (wsmanConnectionInfo.SkipCACheck) + { + result.Append("-SkipCACheck "); + } - if (wsmanConnectionInfo.SkipCNCheck) { result.Append("-SkipCNCheck "); } + if (wsmanConnectionInfo.SkipCNCheck) + { + result.Append("-SkipCNCheck "); + } - if (wsmanConnectionInfo.SkipRevocationCheck) { result.Append("-SkipRevocationCheck "); } + if (wsmanConnectionInfo.SkipRevocationCheck) + { + result.Append("-SkipRevocationCheck "); + } if (wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.HasValue) { - result.AppendFormat( - CultureInfo.InvariantCulture, - "-MaximumReceivedDataSizePerCommand {0} ", - wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value); + result.Append(CultureInfo.InvariantCulture, $"-MaximumReceivedDataSizePerCommand {wsmanConnectionInfo.MaximumReceivedDataSizePerCommand.Value} "); } if (wsmanConnectionInfo.MaximumReceivedObjectSize.HasValue) { - result.AppendFormat( - CultureInfo.InvariantCulture, - "-MaximumReceivedObjectSize {0} ", - wsmanConnectionInfo.MaximumReceivedObjectSize.Value); + result.Append(CultureInfo.InvariantCulture, $"-MaximumReceivedObjectSize {wsmanConnectionInfo.MaximumReceivedObjectSize.Value} "); } - result.AppendFormat( - CultureInfo.InvariantCulture, - "-MaximumRedirection {0} ", - wsmanConnectionInfo.MaximumConnectionRedirectionCount); + result.Append(CultureInfo.InvariantCulture, $"-MaximumRedirection {wsmanConnectionInfo.MaximumConnectionRedirectionCount} "); - result.AppendFormat( - CultureInfo.InvariantCulture, - "-ProxyAccessType {0} ", - wsmanConnectionInfo.ProxyAccessType.ToString()); - result.AppendFormat( - CultureInfo.InvariantCulture, - "-ProxyAuthentication {0} ", - wsmanConnectionInfo.ProxyAuthentication.ToString()); + result.Append(CultureInfo.InvariantCulture, $"-ProxyAccessType {wsmanConnectionInfo.ProxyAccessType} "); + result.Append(CultureInfo.InvariantCulture, $"-ProxyAuthentication {wsmanConnectionInfo.ProxyAuthentication} "); result.Append(this.GenerateProxyCredentialParameter(wsmanConnectionInfo)); } @@ -2525,8 +2525,7 @@ private string GenerateReimportingOfModules() private string GenerateNewRunspaceExpression() { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { string vmConfigurationName = vmConnectionInfo.ConfigurationName; return string.Format( @@ -2538,8 +2537,7 @@ private string GenerateNewRunspaceExpression() } else { - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { string containerConfigurationName = containerConnectionInfo.ContainerProc.ConfigurationName; return string.Format( @@ -2581,19 +2579,16 @@ private string GenerateNewRunspaceExpression() /// private string GenerateConnectionStringForNewRunspace() { - WSManConnectionInfo connectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as WSManConnectionInfo; - if (connectionInfo == null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo connectionInfo) { - VMConnectionInfo vmConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as VMConnectionInfo; - if (vmConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is VMConnectionInfo vmConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, VMIdParameterTemplate, CodeGeneration.EscapeSingleQuotedStringContent(vmConnectionInfo.VMGuid.ToString())); } - ContainerConnectionInfo containerConnectionInfo = _remoteRunspaceInfo.Runspace.ConnectionInfo as ContainerConnectionInfo; - if (containerConnectionInfo != null) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is ContainerConnectionInfo containerConnectionInfo) { return string.Format(CultureInfo.InvariantCulture, ContainerIdParameterTemplate, @@ -2613,21 +2608,19 @@ private string GenerateConnectionStringForNewRunspace() CodeGeneration.EscapeSingleQuotedStringContent(connectionInfo.AppName), connectionInfo.UseDefaultWSManPort ? string.Empty : - string.Format(CultureInfo.InvariantCulture, - "-Port {0} ", connectionInfo.Port), + string.Create(CultureInfo.InvariantCulture, $"-Port {connectionInfo.Port} "), isSSLSpecified ? "-useSSL" : string.Empty); } else { - return string.Format(CultureInfo.InvariantCulture, - "-connectionUri '{0}'", - CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString())); + string connectionString = CodeGeneration.EscapeSingleQuotedStringContent(GetConnectionString()); + return string.Create(CultureInfo.InvariantCulture, $"-connectionUri '{connectionString}'"); } } private string GenerateAllowRedirectionParameter() { - if (!(_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo)) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo wsmanConnectionInfo) { return string.Empty; } @@ -2653,7 +2646,7 @@ private string GenerateAuthenticationMechanismParameter() return string.Empty; } - if (!(_remoteRunspaceInfo.Runspace.ConnectionInfo is WSManConnectionInfo wsmanConnectionInfo)) + if (_remoteRunspaceInfo.Runspace.ConnectionInfo is not WSManConnectionInfo wsmanConnectionInfo) { return string.Empty; } @@ -2749,7 +2742,7 @@ function Get-PSImplicitRemotingClientSideParameters $clientSideParameters = @{} - $parametersToLeaveRemote = 'ErrorAction', 'WarningAction', 'InformationAction' + $parametersToLeaveRemote = 'ErrorAction', 'WarningAction', 'InformationAction', 'ProgressAction' Modify-PSImplicitRemotingParameters $clientSideParameters $PSBoundParameters 'AsJob' if ($proxyForCmdlet) @@ -2825,13 +2818,14 @@ private void GenerateHelperFunctions(TextWriter writer) $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 }} ` - }} + $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) @@ -3059,10 +3053,7 @@ internal List GenerateProxyModule( FileShare.None); using (TextWriter writer = new StreamWriter(psm1, encoding)) { - if (listOfCommandMetadata == null) - { - listOfCommandMetadata = new List(); - } + listOfCommandMetadata ??= new List(); GenerateModuleHeader(writer); GenerateHelperFunctions(writer); @@ -3080,10 +3071,7 @@ internal List GenerateProxyModule( FileShare.None); using (TextWriter writer = new StreamWriter(formatPs1xml, encoding)) { - if (listOfFormatData == null) - { - listOfFormatData = new List(); - } + listOfFormatData ??= new List(); GenerateFormatFile(writer, listOfFormatData); formatPs1xml.SetLength(formatPs1xml.Position); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs index 53ab8d32c2f..c4e423ffd1d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Import-LocalizedData.cs @@ -2,11 +2,13 @@ // 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 { @@ -146,9 +148,9 @@ protected override void ProcessRecord() } // Prevent additional commands in ConstrainedLanguage mode - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + if (_setSupportedCommand && Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if (_setSupportedCommand) + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) { NotSupportedException nse = PSTraceSource.NewNotSupportedException( @@ -156,6 +158,13 @@ protected override void ProcessRecord() 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); @@ -282,7 +291,7 @@ private string GetFilePath() fileName = Path.GetFileNameWithoutExtension(fileName); - CultureInfo culture = null; + CultureInfo culture; if (_uiculture == null) { culture = CultureInfo.CurrentUICulture; @@ -299,19 +308,33 @@ private string GetFilePath() } } - CultureInfo currentCulture = 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"; - while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name)) + foreach (CultureInfo cultureToTest in cultureList) { - filePath = Path.Combine(dir, currentCulture.Name, fullFileName); - - if (File.Exists(filePath)) + CultureInfo currentCulture = cultureToTest; + while (currentCulture != null && !string.IsNullOrEmpty(currentCulture.Name)) { - return filePath; - } + filePath = Path.Combine(dir, currentCulture.Name, fullFileName); - currentCulture = currentCulture.Parent; + if (File.Exists(filePath)) + { + return filePath; + } + + currentCulture = currentCulture.Parent; + } } filePath = Path.Combine(dir, fullFileName); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs index 4252a1623d6..657d00b4fc5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportAliasCommand.cs @@ -55,6 +55,7 @@ public string LiteralPath /// [Parameter] [ValidateNotNullOrEmpty] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } /// @@ -296,7 +297,7 @@ private Collection GetAliasesFromFile(bool isLiteralPath) { CSVHelper csvHelper = new(','); - Int64 lineNumber = 0; + long lineNumber = 0; string line = null; while ((line = reader.ReadLine()) != null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs index 53dc461dfb2..5661df24fa9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ImportPowerShellDataFile.cs @@ -42,7 +42,6 @@ public string[] LiteralPath /// /// Gets or sets switch that determines if built-in limits are applied to the data. /// - [Experimental("Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck", ExperimentAction.Show)] [Parameter] public SwitchParameter SkipLimitCheck { get; set; } @@ -65,7 +64,7 @@ protected override void ProcessRecord() } else { - var data = ast.Find(a => a is HashtableAst, false); + var data = ast.Find(static a => a is HashtableAst, false); if (data != null) { WriteObject(data.SafeGetValue(SkipLimitCheck)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs index d51f20f8704..acbffeb66f4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/InvokeExpressionCommand.cs @@ -4,6 +4,7 @@ using System; using System.Management.Automation; using System.Management.Automation.Internal; +using System.Management.Automation.Security; namespace Microsoft.PowerShell.Commands { @@ -43,6 +44,16 @@ protected override void ProcessRecord() 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, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs index 16243fcf6ae..80a04b07f17 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Join-String.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation; @@ -40,7 +41,7 @@ public sealed class JoinStringCommand : PSCmdlet /// Gets or sets the delimiter to join the output with. /// [Parameter(Position = 1)] - [ArgumentCompleter(typeof(JoinItemCompleter))] + [ArgumentCompleter(typeof(SeparatorArgumentCompleter))] [AllowEmptyString] public string Separator { @@ -78,7 +79,7 @@ public string Separator /// Gets or sets a format string that is applied to each input object. /// [Parameter(ParameterSetName = "Format")] - [ArgumentCompleter(typeof(JoinItemCompleter))] + [ArgumentCompleter(typeof(FormatStringArgumentCompleter))] public string FormatString { get; set; } /// @@ -159,75 +160,115 @@ protected override void EndProcessing() } } - internal class JoinItemCompleter : IArgumentCompleter + /// + /// 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) - { - switch (parameterName) - { - case "Separator": return CompleteSeparator(wordToComplete); - case "FormatString": return CompleteFormatString(wordToComplete); - } - - return null; - } - - private static IEnumerable CompleteFormatString(string wordToComplete) - { - var res = new List(); - void AddMatching(string completionText) - { - if (completionText.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) - { - res.Add(new CompletionResult(completionText)); - } - } - - AddMatching("'[{0}]'"); - AddMatching("'{0:N2}'"); - AddMatching("\"`r`n `${0}\""); - AddMatching("\"`r`n [string] `${0}\""); - - return res; - } - - private IEnumerable CompleteSeparator(string wordToComplete) - { - var res = new List(10); - - void AddMatching(string completionText, string listText, string toolTip) - { - if (completionText.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) - { - res.Add(new CompletionResult(completionText, listText, CompletionResultType.ParameterValue, toolTip)); - } - } - - AddMatching("', '", "Comma-Space", "', ' - Comma-Space"); - AddMatching("';'", "Semi-Colon", "';' - Semi-Colon "); - AddMatching("'; '", "Semi-Colon-Space", "'; ' - Semi-Colon-Space"); - AddMatching($"\"{NewLineText}\"", "Newline", $"{NewLineText} - Newline"); - AddMatching("','", "Comma", "',' - Comma"); - AddMatching("'-'", "Dash", "'-' - Dash"); - AddMatching("' '", "Space", "' ' - Space"); - return res; - } + => CompletionHelpers.GetMatchingResults( + wordToComplete, + possibleCompletionValues: s_separatorValues, + displayInfoMapper: SeparatorDisplayInfoMapper, + resultType: CompletionResultType.ParameterValue); + } - public string NewLineText + /// + /// 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) { - get - { + "[{0}]", + "{0:N2}", #if UNIX - return "`n"; + "`n `${0}", + "`n [string] `${0}", #else - return "`r`n"; + "`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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/JsonSchemaReferenceResolutionException.cs new file mode 100644 index 00000000000..7c2a7ac65f4 --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs index 6271e6f57b6..262fd44b30f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/MatchString.cs @@ -80,7 +80,7 @@ public class MatchInfo /// Gets or sets the number of the matching line. /// /// The number of the matching line. - public int LineNumber { get; set; } + public ulong LineNumber { get; set; } /// /// Gets or sets the text of the matching line. @@ -127,11 +127,11 @@ public MatchInfo(IReadOnlyList matchIndexes, IReadOnlyList matchLength /// /// 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 { @@ -150,10 +150,10 @@ public 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 { @@ -182,11 +182,11 @@ public string Path /// /// 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) @@ -232,12 +232,12 @@ public string RelativePath(string directory) /// /// 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() { @@ -277,7 +277,7 @@ private string ToString(string directory, string line) // Otherwise, render the full context. List lines = new(Context.DisplayPreContext.Length + Context.DisplayPostContext.Length + 1); - int displayLineNumber = this.LineNumber - Context.DisplayPreContext.Length; + ulong displayLineNumber = this.LineNumber - (ulong)Context.DisplayPreContext.Length; foreach (string contextLine in Context.DisplayPreContext) { lines.Add(FormatLine(contextLine, displayLineNumber++, displayPath, ContextPrefix)); @@ -315,8 +315,8 @@ public string ToEmphasizedString(string directory) /// The matched line with matched text inverted. private string EmphasizeLine() { - string invertColorsVT100 = VTUtility.GetEscapeSequence(VTUtility.VT.Inverse); - string resetVT100 = VTUtility.GetEscapeSequence(VTUtility.VT.Reset); + 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; @@ -356,7 +356,7 @@ private string EmphasizeLine() /// The file path, formatted for display. /// The match prefix. /// The formatted line as a string. - private string FormatLine(string lineStr, int displayLineNumber, string displayPath, string prefix) + private string FormatLine(string lineStr, ulong displayLineNumber, string displayPath, string prefix) { return _pathSet ? StringUtil.Format(MatchFormat, prefix, displayPath, displayLineNumber, lineStr) @@ -410,7 +410,7 @@ public sealed class SelectStringCommand : PSCmdlet /// A generic circular buffer. /// /// The type of items that are buffered. - private class CircularBuffer : ICollection + private sealed class CircularBuffer : ICollection { // Ring of items private readonly T[] _items; @@ -428,10 +428,7 @@ private class CircularBuffer : ICollection /// If is negative. public CircularBuffer(int capacity) { - if (capacity < 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfNegative(capacity); _items = new T[capacity]; Clear(); @@ -532,15 +529,8 @@ public bool Contains(T item) public void CopyTo(T[] array, int arrayIndex) { - if (array == null) - { - throw new ArgumentNullException(nameof(array)); - } - - if (arrayIndex < 0) - { - throw new ArgumentOutOfRangeException(nameof(arrayIndex)); - } + ArgumentNullException.ThrowIfNull(array); + ArgumentOutOfRangeException.ThrowIfNegative(arrayIndex); if (Count > (array.Length - arrayIndex)) { @@ -627,7 +617,7 @@ private interface IContextTracker /// /// A state machine to track display context for each match. /// - private class DisplayContextTracker : IContextTracker + private sealed class DisplayContextTracker : IContextTracker { private enum ContextState { @@ -784,12 +774,12 @@ private void Reset() /// and other matching lines (since they will appear /// as their own match entries.). /// - private class LogicalContextTracker : IContextTracker + private sealed class LogicalContextTracker : IContextTracker { // A union: string | MatchInfo. Needed since // context lines could be either proper matches // or non-matching lines. - private class ContextEntry + private sealed class ContextEntry { public readonly string Line; public readonly MatchInfo Match; @@ -989,7 +979,7 @@ private string[] CopyContext(int startIndex, int length) /// /// A class to track both logical and display contexts. /// - private class ContextTracker : IContextTracker + private sealed class ContextTracker : IContextTracker { private readonly IContextTracker _displayTracker; private readonly IContextTracker _logicalTracker; @@ -1058,7 +1048,7 @@ private void UpdateQueue() /// /// ContextTracker that does not work for the case when pre- and post context is 0. /// - private class NoContextTracker : IContextTracker + private sealed class NoContextTracker : IContextTracker { private readonly IList _matches = new List(1); @@ -1346,8 +1336,8 @@ public string[] Exclude /// Gets or sets the text encoding to process each file as. /// [Parameter] - [ArgumentToEncodingTransformationAttribute()] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -1363,7 +1353,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Gets or sets the number of context lines to collect. If set to a @@ -1376,7 +1366,7 @@ public Encoding Encoding [Parameter] [ValidateNotNullOrEmpty] [ValidateCount(1, 2)] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public new int[] Context { get => _context; @@ -1427,7 +1417,7 @@ private IContextTracker GetContextTracker() => (Raw || (_preContext == 0 && _pos /// private bool _doneProcessing; - private int _inputRecordNumber; + private ulong _inputRecordNumber; /// /// Read command line parameters. @@ -1605,7 +1595,7 @@ private bool ProcessFile(string filename) using (StreamReader sr = new(fs, Encoding)) { string line; - int lineNo = 0; + ulong lineNo = 0; // Read and display lines from the file until the end of // the file is reached. @@ -1996,7 +1986,7 @@ private void WarnFilterContext() /// /// Magic class that works around the limitations on ToString() for FileInfo. /// - private class FileinfoToStringAttribute : ArgumentTransformationAttribute + private sealed class FileinfoToStringAttribute : ArgumentTransformationAttribute { public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs index 452e8bfe09c..1e741758270 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Measure-Object.cs @@ -160,7 +160,7 @@ public sealed class MeasureObjectCommand : PSCmdlet /// Keys are strings. Keys are compared with OrdinalIgnoreCase. /// /// Value type. - private class MeasureObjectDictionary : Dictionary + private sealed class MeasureObjectDictionary : Dictionary where TValue : new() { /// @@ -200,7 +200,7 @@ public TValue EnsureEntry(string key) /// what mode we're in. /// [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses")] - private class Statistics + private sealed class Statistics { // Common properties internal int count = 0; @@ -561,8 +561,7 @@ private void AnalyzeObjectProperties(PSObject inObj) /// The value to analyze. private void AnalyzeValue(string propertyName, object objValue) { - if (propertyName == null) - propertyName = thisObject; + propertyName ??= thisObject; Statistics stat = _statistics.EnsureEntry(propertyName); @@ -792,9 +791,9 @@ 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("Property"), + PSTraceSource.NewArgumentException(propertyName), errorId, - ErrorCategory.InvalidArgument, + ErrorCategory.ObjectNotFound, null); errorRecord.ErrorDetails = new ErrorDetails( this, "MeasureObjectStrings", "PropertyNotFound", propertyName); @@ -820,9 +819,12 @@ protected override void EndProcessing() Statistics stat = _statistics[propertyName]; if (stat.count == 0 && Property != null) { - // Why are there two different ids for this error? - string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; - WritePropertyNotFoundError(propertyName, errorId); + if (Context.IsStrictVersion(2)) + { + string errorId = (IsMeasuringGeneric) ? "GenericMeasurePropertyNotFound" : "TextMeasurePropertyNotFound"; + WritePropertyNotFoundError(propertyName, errorId); + } + continue; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs index 90ef2ca4376..0ea312f2963 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/New-Object.cs @@ -187,18 +187,30 @@ protected override void BeginProcessing() targetObject: null)); } - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) - { - if (!CoreTypes.Contains(type)) - { - ThrowTerminatingError( - new ErrorRecord( - new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateTypeConstrainedLanguage", ErrorCategory.PermissionDenied, 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 @@ -212,8 +224,7 @@ protected override void BeginProcessing() ErrorCategory.PermissionDenied, targetObject: null)); } - - break; + break; } // WinRT does not support creating instances of attribute & delegate WinRT types. @@ -238,7 +249,7 @@ protected override void BeginProcessing() WriteObject(_newObject); return; } - else if (type.GetTypeInfo().IsValueType) + else if (type.IsValueType) { // This is for default parameterless struct ctor which is not returned by // Type.GetConstructor(System.Type.EmptyTypes). @@ -301,21 +312,31 @@ protected override void BeginProcessing() bool isAllowed = false; // If it's a system-wide lockdown, we may allow additional COM types - if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); + if (systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) { - if ((result >= 0) && - SystemPolicy.IsClassInApprovedList(_comObjectClsId)) - { - isAllowed = true; - } + isAllowed = (result >= 0) && SystemPolicy.IsClassInApprovedList(_comObjectClsId); } if (!isAllowed) { - ThrowTerminatingError( - new ErrorRecord( - new PSNotSupportedException(NewObjectStrings.CannotCreateTypeConstrainedLanguage), "CannotCreateComTypeConstrainedLanguage", ErrorCategory.PermissionDenied, null)); - return; + 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); } } @@ -351,12 +372,12 @@ protected override void BeginProcessing() #if !UNIX #region Com - private object SafeCreateInstance(Type t, object[] args) + private object SafeCreateInstance(Type t) { object result = null; try { - result = Activator.CreateInstance(t, args); + result = Activator.CreateInstance(t); } // Does not catch InvalidComObjectException because ComObject is obtained from GetTypeFromProgID catch (ArgumentException e) @@ -416,7 +437,7 @@ private object SafeCreateInstance(Type t, object[] args) return result; } - private class ComCreateInfo + private sealed class ComCreateInfo { public object objectCreated; public bool success; @@ -430,13 +451,10 @@ private void STAComCreateThreadProc(object createstruct) ComCreateInfo info = (ComCreateInfo)createstruct; try { - Type type = null; - PSArgumentException mshArgE = null; - - type = Type.GetTypeFromCLSID(_comObjectClsId); + Type type = Type.GetTypeFromCLSID(_comObjectClsId); if (type == null) { - mshArgE = PSTraceSource.NewArgumentException( + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( "ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); @@ -446,7 +464,7 @@ private void STAComCreateThreadProc(object createstruct) return; } - info.objectCreated = SafeCreateInstance(type, ArgumentList); + info.objectCreated = SafeCreateInstance(type); info.success = true; } catch (Exception e) @@ -458,20 +476,25 @@ private void STAComCreateThreadProc(object createstruct) private object CreateComObject() { - Type type = null; - PSArgumentException mshArgE = null; - try { - type = Marshal.GetTypeFromCLSID(_comObjectClsId); + Type type = Marshal.GetTypeFromCLSID(_comObjectClsId); if (type == null) { - mshArgE = PSTraceSource.NewArgumentException("ComObject", NewObjectStrings.CannotLoadComObjectType, ComObject); + PSArgumentException mshArgE = PSTraceSource.NewArgumentException( + "ComObject", + NewObjectStrings.CannotLoadComObjectType, + ComObject); + ThrowTerminatingError( - new ErrorRecord(mshArgE, "CannotLoadComObjectType", ErrorCategory.InvalidType, null)); + new ErrorRecord( + mshArgE, + "CannotLoadComObjectType", + ErrorCategory.InvalidType, + targetObject: null)); } - return SafeCreateInstance(type, ArgumentList); + return SafeCreateInstance(type); } catch (COMException e) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs index 34c95a116f3..1e46241b2d8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewEventCommand.cs @@ -121,7 +121,10 @@ protected override void EndProcessing() } object messageSender = null; - if (_sender != null) { messageSender = _sender.BaseObject; } + if (_sender != null) + { + messageSender = _sender.BaseObject; + } // And then generate the event WriteObject(Events.GenerateEvent(_sourceIdentifier, messageSender, baseEventArgs, _messageData, true, false)); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs index 537d86c24ec..d1d41b312f7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewGuidCommand.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Management.Automation; @@ -9,16 +11,48 @@ namespace Microsoft.PowerShell.Commands /// /// The implementation of the "new-guid" cmdlet. /// - [Cmdlet(VerbsCommon.New, "Guid", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097130")] + [Cmdlet(VerbsCommon.New, "Guid", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097130")] [OutputType(typeof(Guid))] - public class NewGuidCommand : Cmdlet + public class NewGuidCommand : PSCmdlet { /// - /// Returns a guid. + /// Gets or sets a value indicating that the cmdlet should return a Guid structure whose value is all zeros. /// - protected override void EndProcessing() + [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() { - WriteObject(Guid.NewGuid()); + 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.CreateVersion7(); + } + + WriteObject(guid); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs index 53c39250763..a5d784da9bb 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/NewTimeSpanCommand.cs @@ -88,6 +88,12 @@ public DateTime End [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 @@ -119,7 +125,7 @@ protected override void ProcessRecord() break; case "Time": - result = new TimeSpan(Days, Hours, Minutes, Seconds); + result = new TimeSpan(Days, Hours, Minutes, Seconds, Milliseconds); break; default: diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs index 39986943c99..13b0234a02b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ObjectCommandComparer.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell.Commands /// isExistingProperty is needed to distinguish whether a property exists and its value is null or /// the property does not exist at all. /// - internal class ObjectCommandPropertyValue + internal sealed class ObjectCommandPropertyValue { private ObjectCommandPropertyValue() { } @@ -77,7 +77,7 @@ internal CultureInfo Culture /// True if both the objects are same or else returns false. public override bool Equals(object inputObject) { - if (!(inputObject is ObjectCommandPropertyValue objectCommandPropertyValueObject)) + if (inputObject is not ObjectCommandPropertyValue objectCommandPropertyValueObject) { return false; } @@ -136,7 +136,7 @@ public override int GetHashCode() /// /// ObjectCommandComparer class. /// - internal class ObjectCommandComparer : IComparer + internal sealed class ObjectCommandComparer : IComparer { /// /// Initializes a new instance of the class. @@ -190,7 +190,7 @@ internal int Compare(ObjectCommandPropertyValue first, ObjectCommandPropertyValu /// /// /// 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 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs index 40f06e58eca..596bbcaafc6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/OrderObjectBase.cs @@ -24,7 +24,7 @@ internal static class SortObjectParameterDefinitionKeys /// /// - internal class SortObjectExpressionParameterDefinition : CommandParameterDefinition + internal sealed class SortObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { @@ -36,7 +36,7 @@ protected override void SetEntries() /// /// - internal class GroupObjectExpressionParameterDefinition : CommandParameterDefinition + internal sealed class GroupObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { @@ -259,10 +259,7 @@ internal void ProcessExpressionParameter( } else { - if (_unExpandedParametersWithWildCardPattern == null) - { - _unExpandedParametersWithWildCardPattern = new List(); - } + _unExpandedParametersWithWildCardPattern ??= new List(); _unExpandedParametersWithWildCardPattern.Add(unexpandedParameter); } @@ -361,7 +358,7 @@ internal static string[] GetDefaultKeyPropertySet(PSObject mshObj) return null; } - if (!(standardNames.Members["DefaultKeyPropertySet"] is PSPropertySet defaultKeys)) + if (standardNames.Members["DefaultKeyPropertySet"] is not PSPropertySet defaultKeys) { return null; } @@ -633,7 +630,7 @@ internal sealed class OrderByPropertyEntry internal bool comparable = false; } - internal class OrderByPropertyComparer : IComparer + internal sealed class OrderByPropertyComparer : IComparer { internal OrderByPropertyComparer(bool[] ascending, CultureInfo cultureInfo, bool caseSensitive) { @@ -702,7 +699,7 @@ internal static OrderByPropertyComparer CreateComparer(List + internal sealed class IndexedOrderByPropertyComparer : IComparer { internal IndexedOrderByPropertyComparer(OrderByPropertyComparer orderByPropertyComparer) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs index bc01f341861..61d7236977d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/PSBreakpointCommandBase.cs @@ -16,7 +16,6 @@ public abstract class PSBreakpointCommandBase : PSCmdlet /// /// Gets or sets the runspace where the breakpoints will be used. /// - [Experimental("Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", ExperimentAction.Show)] [Parameter] [ValidateNotNull] [Runspace] @@ -31,10 +30,7 @@ public abstract class PSBreakpointCommandBase : PSCmdlet /// protected override void BeginProcessing() { - if (Runspace == null) - { - Runspace = Context.CurrentRunspace; - } + Runspace ??= Context.CurrentRunspace; } #endregion overrides diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs index 7cec08e1b10..15c48efd847 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/RemoveAliasCommand.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands /// /// The implementation of the "Remove-Alias" cmdlet. /// - [Cmdlet(VerbsCommon.Remove, "Alias", DefaultParameterSetName = "Default", HelpUri = "")] + [Cmdlet(VerbsCommon.Remove, "Alias", DefaultParameterSetName = "Default", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2097127")] [Alias("ral")] public class RemoveAliasCommand : PSCmdlet { @@ -25,6 +25,7 @@ public class RemoveAliasCommand : PSCmdlet /// The scope parameter for the command determines which scope the alias is removed from. /// [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs index efdd82d79de..e0b0bff07c5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Select-Object.cs @@ -12,51 +12,7 @@ namespace Microsoft.PowerShell.Commands { - /// - /// Helper class to do wildcard matching on PSPropertyExpressions. - /// - internal sealed class PSPropertyExpressionFilter - { - /// - /// Initializes a new instance of the class - /// with the specified array of patterns. - /// - /// Array of pattern strings to use. - internal PSPropertyExpressionFilter(string[] wildcardPatternsStrings) - { - if (wildcardPatternsStrings == null) - { - throw new ArgumentNullException(nameof(wildcardPatternsStrings)); - } - - _wildcardPatterns = new WildcardPattern[wildcardPatternsStrings.Length]; - for (int k = 0; k < wildcardPatternsStrings.Length; k++) - { - _wildcardPatterns[k] = WildcardPattern.Get(wildcardPatternsStrings[k], WildcardOptions.IgnoreCase); - } - } - - /// - /// Try to match the expression against the array of wildcard patterns. - /// The first match shortcircuits the search. - /// - /// PSPropertyExpression to test against. - /// True if there is a match, else false. - internal bool IsMatch(PSPropertyExpression expression) - { - for (int k = 0; k < _wildcardPatterns.Length; k++) - { - if (_wildcardPatterns[k].IsMatch(expression.ToString())) - return true; - } - - return false; - } - - private readonly WildcardPattern[] _wildcardPatterns; - } - - internal class SelectObjectExpressionParameterDefinition : CommandParameterDefinition + internal sealed class SelectObjectExpressionParameterDefinition : CommandParameterDefinition { protected override void SetEntries() { @@ -113,6 +69,13 @@ public SwitchParameter Unique 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; } + /// /// /// @@ -147,10 +110,11 @@ public int First private bool _firstOrLastSpecified; /// - /// Skips the specified number of items from top when used with First, from end when used with Last. + /// 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; } @@ -174,7 +138,7 @@ public int First /// /// [Parameter(ParameterSetName = "IndexParameter")] - [ValidateRangeAttribute(0, int.MaxValue)] + [ValidateRange(0, int.MaxValue)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] Index { @@ -197,7 +161,7 @@ public int[] Index /// /// [Parameter(ParameterSetName = "SkipIndexParameter")] - [ValidateRangeAttribute(0, int.MaxValue)] + [ValidateRange(0, int.MaxValue)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] SkipIndex { @@ -223,7 +187,7 @@ public int[] SkipIndex private SelectObjectQueue _selectObjectQueue; - private class SelectObjectQueue : Queue + private sealed class SelectObjectQueue : Queue { internal SelectObjectQueue(int first, int last, int skip, int skipLast, bool firstOrLastSpecified) { @@ -324,7 +288,7 @@ public PSObject StreamingDequeue() private PSPropertyExpressionFilter _exclusionFilter; - private class UniquePSObjectHelper + private sealed class UniquePSObjectHelper { internal UniquePSObjectHelper(PSObject o, int notePropertyCount) { @@ -437,7 +401,11 @@ private void ProcessParameter(MshParameter p, PSObject inputObject, List tempExprResults = resolvedName.GetValues(inputObject); - if (tempExprResults == null) continue; + if (tempExprResults == null) + { + continue; + } + foreach (PSPropertyExpressionResult mshExpRes in tempExprResults) { expressionResults.Add(mshExpRes); @@ -528,7 +496,10 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, if (r.Exception == null) { // ignore the property value if it's null - if (r.Result == null) { return; } + if (r.Result == null) + { + return; + } System.Collections.IEnumerable results = LanguagePrimitives.GetEnumerable(r.Result); if (results == null) @@ -548,7 +519,10 @@ private void ProcessExpandParameter(MshParameter p, PSObject inputObject, foreach (object expandedValue in results) { // ignore the element if it's null - if (expandedValue == null) { continue; } + if (expandedValue == null) + { + continue; + } // add NoteProperties if there is any // If expandedValue is a base object, we don't want to associate the NoteProperty @@ -624,7 +598,11 @@ private void FilteredWriteObject(PSObject obj, List addedNotePro bool isObjUnique = true; foreach (UniquePSObjectHelper uniqueObj in _uniques) { - ObjectCommandComparer comparer = new(true, CultureInfo.CurrentCulture, true); + ObjectCommandComparer comparer = new( + ascending: true, + CultureInfo.CurrentCulture, + caseSensitive: !CaseInsensitive.IsPresent); + if ((comparer.Compare(obj.BaseObject, uniqueObj.WrittenObject.BaseObject) == 0) && (uniqueObj.NotePropertyCount == addedNoteProperties.Count)) { @@ -847,7 +825,7 @@ protected override void EndProcessing() [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 class SelectObjectException : SystemException + internal sealed class SelectObjectException : SystemException { internal ErrorRecord ErrorRecord { get; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs index 975fd68ebfa..2598d953496 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Send-MailMessage.cs @@ -61,8 +61,8 @@ public sealed class SendMailMessage : PSCmdlet [Parameter(ValueFromPipelineByPropertyName = true)] [Alias("BE")] [ValidateNotNullOrEmpty] - [ArgumentEncodingCompletionsAttribute] - [ArgumentToEncodingTransformationAttribute] + [ArgumentEncodingCompletions] + [ArgumentToEncodingTransformation] public Encoding Encoding { get @@ -165,7 +165,7 @@ public Encoding Encoding /// Value must be greater than zero. /// [Parameter(ValueFromPipelineByPropertyName = true)] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public int Port { get; set; } #endregion diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs index 77b0dce3470..5dfe40fa9d4 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/SetDateCommand.cs @@ -48,7 +48,6 @@ public sealed class SetDateCommand : PSCmdlet /// /// Set the date. /// - [ArchitectureSensitive] protected override void ProcessRecord() { DateTime dateToUse; @@ -71,31 +70,44 @@ protected override void ProcessRecord() if (ShouldProcess(dateToUse.ToString())) { #if UNIX - if (!Platform.NonWindowsSetDate(dateToUse)) + // 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 = (UInt16)dateToUse.Year; - systemTime.Month = (UInt16)dateToUse.Month; - systemTime.Day = (UInt16)dateToUse.Day; - systemTime.Hour = (UInt16)dateToUse.Hour; - systemTime.Minute = (UInt16)dateToUse.Minute; - systemTime.Second = (UInt16)dateToUse.Second; - systemTime.Milliseconds = (UInt16)dateToUse.Millisecond; + 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 (!NativeMethods.SetLocalTime(ref systemTime)) + if (Dbg.Internal.InternalTestHooks.SetDate) { - throw new Win32Exception(Marshal.GetLastWin32Error()); + WriteObject(systemTime); } - - // MSDN says to call this twice to account for changes - // between DST - if (!NativeMethods.SetLocalTime(ref systemTime)) + else { - throw new Win32Exception(Marshal.GetLastWin32Error()); + 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 @@ -106,7 +118,11 @@ protected override void ProcessRecord() PSNoteProperty note = new("DisplayHint", DisplayHint); outputObj.Properties.Add(note); - WriteObject(outputObj); + // 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 @@ -118,14 +134,14 @@ internal static class NativeMethods [StructLayout(LayoutKind.Sequential)] public 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; + 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)] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs index 330716af151..60b05807d48 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommand.cs @@ -75,14 +75,14 @@ public class ShowCommandCommand : PSCmdlet, IDisposable /// Gets or sets the Width. /// [Parameter] - [ValidateRange(300, Int32.MaxValue)] + [ValidateRange(300, int.MaxValue)] public double Height { get; set; } /// /// Gets or sets the Width. /// [Parameter] - [ValidateRange(300, Int32.MaxValue)] + [ValidateRange(300, int.MaxValue)] public double Width { get; set; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs index e3de5cac296..e2ba41fb3fc 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandCommandInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandCommandInfo /// public ShowCommandCommandInfo(CommandInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.ModuleName = other.ModuleName; @@ -39,7 +36,7 @@ public ShowCommandCommandInfo(CommandInfo other) { this.ParameterSets = other.ParameterSets - .Select(x => new ShowCommandParameterSetInfo(x)) + .Select(static x => new ShowCommandParameterSetInfo(x)) .ToList() .AsReadOnly(); } @@ -71,10 +68,7 @@ public ShowCommandCommandInfo(CommandInfo other) /// public ShowCommandCommandInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.ModuleName = other.Members["ModuleName"].Value as string; @@ -92,7 +86,7 @@ public ShowCommandCommandInfo(PSObject other) 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(x => new ShowCommandParameterSetInfo(x)).ToList().AsReadOnly(); + this.ParameterSets = GetObjectEnumerable(parameterSets).Cast().Select(static x => new ShowCommandParameterSetInfo(x)).ToList().AsReadOnly(); if (other.Members["Module"]?.Value is PSObject) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs index b12cc5651f4..f31bc93525d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandModuleInfo.cs @@ -20,10 +20,7 @@ public class ShowCommandModuleInfo /// public ShowCommandModuleInfo(PSModuleInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; } @@ -37,10 +34,7 @@ public ShowCommandModuleInfo(PSModuleInfo other) /// public ShowCommandModuleInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs index 04a74b4fc45..9bf79c5bd76 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterInfo.cs @@ -22,10 +22,7 @@ public class ShowCommandParameterInfo /// public ShowCommandParameterInfo(CommandParameterInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.IsMandatory = other.IsMandatory; @@ -33,7 +30,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) this.ParameterType = new ShowCommandParameterType(other.ParameterType); this.Position = other.Position; - var validateSetAttribute = other.Attributes.Where(x => typeof(ValidateSetAttribute).IsAssignableFrom(x.GetType())).Cast().LastOrDefault(); + var validateSetAttribute = other.Attributes.Where(static x => typeof(ValidateSetAttribute).IsAssignableFrom(x.GetType())).Cast().LastOrDefault(); if (validateSetAttribute != null) { this.HasParameterSet = true; @@ -50,10 +47,7 @@ public ShowCommandParameterInfo(CommandParameterInfo other) /// public ShowCommandParameterInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Members["Name"].Value as string; this.IsMandatory = (bool)(other.Members["IsMandatory"].Value); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs index fb25e2e4745..c5ec1c74c08 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterSetInfo.cs @@ -22,14 +22,11 @@ public class ShowCommandParameterSetInfo /// public ShowCommandParameterSetInfo(CommandParameterSetInfo other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.Name = other.Name; this.IsDefault = other.IsDefault; - this.Parameters = other.Parameters.Select(x => new ShowCommandParameterInfo(x)).ToArray(); + this.Parameters = other.Parameters.Select(static x => new ShowCommandParameterInfo(x)).ToArray(); } /// @@ -41,15 +38,12 @@ public ShowCommandParameterSetInfo(CommandParameterSetInfo other) /// public ShowCommandParameterSetInfo(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(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(x => new ShowCommandParameterInfo(x)).ToArray(); + this.Parameters = ShowCommandCommandInfo.GetObjectEnumerable(parameters).Cast().Select(static x => new ShowCommandParameterInfo(x)).ToArray(); } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs index 1daf0350dbc..01da285a1d7 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandParameterType.cs @@ -21,10 +21,7 @@ public class ShowCommandParameterType /// public ShowCommandParameterType(Type other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.FullName = other.FullName; if (other.IsEnum) @@ -51,10 +48,7 @@ public ShowCommandParameterType(Type other) /// public ShowCommandParameterType(PSObject other) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); this.IsEnum = (bool)(other.Members["IsEnum"].Value); this.FullName = other.Members["FullName"].Value as string; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs index a8a9c8f194d..ab8909bb590 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowCommand/ShowCommandProxy.cs @@ -16,7 +16,7 @@ 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 class ShowCommandProxy + internal sealed class ShowCommandProxy { private const string ShowCommandHelperName = "Microsoft.PowerShell.Commands.ShowCommandInternal.ShowCommandHelper"; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs index 63ee15f6f59..3f40ec3439e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/ShowMarkdownCommand.cs @@ -224,10 +224,7 @@ private void ProcessMarkdownInfo(MarkdownInfo markdownInfo) /// protected override void EndProcessing() { - if (_powerShell != null) - { - _powerShell.Dispose(); - } + _powerShell?.Dispose(); } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs index 06f5ebfffad..365a669c186 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Sort-Object.cs @@ -147,7 +147,7 @@ private int Heapify(List dataToSort, OrderByPropertyCompar // 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 < dataToSort.Count - discardedDuplicates; dataIndex++) + 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 @@ -157,20 +157,19 @@ private int Heapify(List dataToSort, OrderByPropertyCompar } // If we're doing a unique sort and the entry is not unique, discard the duplicate entry - if (Unique && !uniqueSet.Add(dataToSort[dataIndex])) + if (Unique && !uniqueSet.Add(dataToSort[dataIndex + discardedDuplicates])) { discardedDuplicates++; - if (dataIndex != dataToSort.Count - discardedDuplicates) - { - // When discarding duplicates, replace them with an item at the end of the list and - // adjust our counter so that we check the item we just swapped in next - dataToSort[dataIndex] = dataToSort[dataToSort.Count - discardedDuplicates]; - dataIndex--; - } - + 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) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs index a57d635f3eb..839a0b7c051 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/StartSleepCommand.cs @@ -44,17 +44,26 @@ public void Dispose() /// [Parameter(Position = 0, Mandatory = true, ParameterSetName = "Seconds", ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] - [ValidateRangeAttribute(0.0, (double)(int.MaxValue / 1000))] + [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)] - [ValidateRangeAttribute(0, int.MaxValue)] + [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 @@ -82,10 +91,7 @@ private void Sleep(int milliSecondsToSleep) } } - if (_waitHandle != null) - { - _waitHandle.WaitOne(milliSecondsToSleep, true); - } + _waitHandle?.WaitOne(milliSecondsToSleep, true); } /// @@ -105,6 +111,26 @@ protected override void ProcessRecord() 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; @@ -121,10 +147,7 @@ protected override void StopProcessing() lock (_syncObject) { _stopping = true; - if (_waitHandle != null) - { - _waitHandle.Set(); - } + _waitHandle?.Set(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs index 78ca964d408..4a0f4831299 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Tee-Object.cs @@ -3,6 +3,7 @@ using System; using System.Management.Automation; +using System.Text; using Microsoft.PowerShell.Commands.Internal.Format; @@ -72,6 +73,16 @@ public SwitchParameter Append 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. /// @@ -95,12 +106,14 @@ protected override void BeginProcessing() _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 { @@ -127,12 +140,15 @@ protected override void EndProcessing() _commandWrapper.ShutDown(); } - private void Dispose(bool isDisposing) + /// + /// Release all resources. + /// + public void Dispose() { if (!_alreadyDisposed) { _alreadyDisposed = true; - if (isDisposing && _commandWrapper != null) + if (_commandWrapper != null) { _commandWrapper.Dispose(); _commandWrapper = null; @@ -140,15 +156,6 @@ private void Dispose(bool isDisposing) } } - /// - /// Dispose method in IDisposable. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - #region private private CommandWrapper _commandWrapper; private bool _alreadyDisposed; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs index c8ba1e7ea48..909cbff3c8f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/TestJsonCommand.cs @@ -4,30 +4,83 @@ using System; using System.Globalization; using System.IO; +using System.Linq; using System.Management.Automation; -using System.Reflection; -using System.Runtime.ExceptionServices; +using System.Net.Http; using System.Security; -using Newtonsoft.Json.Linq; -using NJsonSchema; +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 = ParameterAttribute.AllParameterSets, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096609")] + [Cmdlet(VerbsDiagnostic.Test, "Json", DefaultParameterSetName = JsonStringParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096609")] + [OutputType(typeof(bool))] public class TestJsonCommand : PSCmdlet { - private const string SchemaFileParameterSet = "SchemaFile"; - private const string SchemaStringParameterSet = "SchemaString"; + #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)] + [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. @@ -36,46 +89,82 @@ public class TestJsonCommand : PSCmdlet /// 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, ParameterSetName = SchemaStringParameterSet)] + [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 containg schema to validate the JSON string against. + /// Gets or sets path to the file containing schema to validate the JSON string against. /// This is optional parameter. /// - [Parameter(Position = 1, ParameterSetName = SchemaFileParameterSet)] + [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; } - private JsonSchema _jschema; - /// - /// Process all exceptions in the AggregateException. - /// Unwrap TargetInvocationException if any and - /// rethrow inner exception without losing the stack trace. + /// Gets or sets JSON document options. /// - /// AggregateException to be unwrapped. - /// Return value is unreachable since we always rethrow. - private static bool UnwrapException(Exception e) - { - if (e.InnerException != null && e is TargetInvocationException) - { - ExceptionDispatchInfo.Capture(e.InnerException).Throw(); - } - else - { - ExceptionDispatchInfo.Capture(e).Throw(); - } + [Parameter] + [ValidateNotNullOrEmpty] + [ValidateSet(IgnoreCommentsOption, AllowTrailingCommasOption)] + public string[] Options { get; set; } = Array.Empty(); - return true; - } + #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 @@ -84,13 +173,12 @@ protected override void BeginProcessing() { try { - _jschema = JsonSchema.FromJsonAsync(Schema).Result; + _jschema = JsonSchema.FromText(Schema); } - catch (AggregateException ae) + catch (JsonException e) { - // Even if only one exception is thrown, it is still wrapped in an AggregateException exception - // https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/exception-handling-task-parallel-library - ae.Handle(UnwrapException); + Exception exception = new(TestJsonCmdletStrings.InvalidJsonSchema, e); + WriteError(new ErrorRecord(exception, "InvalidJsonSchema", ErrorCategory.InvalidData, Schema)); } } else if (SchemaFile != null) @@ -98,17 +186,18 @@ protected override void BeginProcessing() try { resolvedpath = Context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(SchemaFile); - _jschema = JsonSchema.FromFileAsync(resolvedpath).Result; + _jschema = JsonSchema.FromFile(resolvedpath); } - catch (AggregateException ae) + catch (JsonException e) { - ae.Handle(UnwrapException); + 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://docs.microsoft.com/en-us/dotnet/standard/io/handling-io-errors + // https://learn.microsoft.com/dotnet/standard/io/handling-io-errors e is IOException || e is UnauthorizedAccessException || e is NotSupportedException || @@ -128,6 +217,14 @@ e is SecurityException 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) + }; } /// @@ -135,31 +232,53 @@ e is SecurityException /// protected override void ProcessRecord() { - JObject parsedJson = null; 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 { - parsedJson = JObject.Parse(Json); + + var parsedJson = JsonNode.Parse(jsonToParse, nodeOptions: null, _documentOptions); if (_jschema != null) { - var errorMessages = _jschema.Validate(parsedJson); - if (errorMessages != null && errorMessages.Count != 0) + EvaluationResults evaluationResults = _jschema.Evaluate(parsedJson, new EvaluationOptions { OutputFormat = OutputFormat.Hierarchical }); + result = evaluationResults.IsValid; + if (!result) { - result = false; - - Exception exception = new(TestJsonCmdletStrings.InvalidJsonAgainstSchema); - - foreach (var message in errorMessages) - { - ErrorRecord errorRecord = new(exception, "InvalidJsonAgainstSchema", ErrorCategory.InvalidData, null); - errorRecord.ErrorDetails = new ErrorDetails(message.ToString()); - WriteError(errorRecord); - } + 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; @@ -170,5 +289,47 @@ protected override void ProcessRecord() 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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs index 5c297ed86d5..6633a66f96f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnblockFile.cs @@ -137,7 +137,7 @@ protected override void ProcessRecord() } } #else - if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + if (Platform.IsLinux) { string errorMessage = UnblockFileStrings.LinuxNotSupported; Exception e = new PlatformNotSupportedException(errorMessage); diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs index f0f87eb9f66..cf65a1f73b3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UnregisterEventCommand.cs @@ -47,7 +47,7 @@ public string SourceIdentifier /// /// Flag that determines if we should include subscriptions used to support other subscriptions. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get; set; } #endregion parameters diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs index 5850eaca7db..99507d0461b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-List.cs @@ -26,7 +26,7 @@ public class UpdateListCommand : PSCmdlet /// Objects to add to the list. /// [Parameter(ParameterSetName = "AddRemoveSet")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public object[] Add { get; set; } @@ -35,7 +35,7 @@ public class UpdateListCommand : PSCmdlet /// Objects to be removed from the list. /// [Parameter(ParameterSetName = "AddRemoveSet")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public object[] Remove { get; set; } @@ -44,7 +44,7 @@ public class UpdateListCommand : PSCmdlet /// Objects in this list replace the objects in the target list. /// [Parameter(Mandatory = true, ParameterSetName = "ReplaceSet")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays", Justification = "Cmdlets use arrays for parameters.")] public object[] Replace { get; set; } @@ -55,7 +55,7 @@ public class UpdateListCommand : PSCmdlet // [Parameter(ValueFromPipeline = true, ParameterSetName = "AddRemoveSet")] // [Parameter(ValueFromPipeline = true, ParameterSetName = "ReplaceSet")] [Parameter(ValueFromPipeline = true)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public PSObject InputObject { get; set; } /// @@ -65,7 +65,7 @@ public class UpdateListCommand : PSCmdlet // [Parameter(Position = 0, ParameterSetName = "AddRemoveSet")] // [Parameter(Position = 0, ParameterSetName = "ReplaceSet")] [Parameter(Position = 0)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string Property { get; set; } private PSListModifier _listModifier; @@ -83,10 +83,7 @@ protected override void ProcessRecord() } else { - if (_listModifier == null) - { - _listModifier = CreatePSListModifier(); - } + _listModifier ??= CreatePSListModifier(); PSMemberInfo memberInfo = InputObject.Members[Property]; if (memberInfo != null) diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs index d137524629d..b73d8570040 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Update-TypeData.cs @@ -260,7 +260,7 @@ public string[] PropertySerializationSet /// The type name we want to update on. /// [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = DynamicTypeSet)] - [ArgumentToTypeNameTransformationAttribute()] + [ArgumentToTypeNameTransformation] [ValidateNotNullOrEmpty] public string TypeName { @@ -792,9 +792,8 @@ private void ProcessTypeFiles() if (ShouldProcess(formattedTarget, action)) { - if (!fullFileNameHash.Contains(resolvedPath)) + if (fullFileNameHash.Add(resolvedPath)) { - fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(prependPathTotal[i])); } } @@ -806,9 +805,8 @@ private void ProcessTypeFiles() if (entry.FileName != null) { string resolvedPath = ModuleCmdletBase.ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; - if (!fullFileNameHash.Contains(resolvedPath)) + if (fullFileNameHash.Add(resolvedPath)) { - fullFileNameHash.Add(resolvedPath); newTypes.Add(entry); } } @@ -825,9 +823,8 @@ private void ProcessTypeFiles() if (ShouldProcess(formattedTarget, action)) { - if (!fullFileNameHash.Contains(resolvedPath)) + if (fullFileNameHash.Add(resolvedPath)) { - fullFileNameHash.Add(resolvedPath); newTypes.Add(new SessionStateTypeEntry(appendPathTotalItem)); } } @@ -849,8 +846,7 @@ private void ProcessTypeFiles() } else if (sste.FileName != null) { - bool unused; - Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out unused); + Context.TypeTable.Update(sste.FileName, sste.FileName, errors, Context.AuthorizationManager, Context.InitialSessionState.Host, out _); } else { @@ -972,9 +968,8 @@ protected override void ProcessRecord() if (ShouldProcess(formattedTarget, action)) { - if (!fullFileNameHash.Contains(appendPathTotalItem)) + if (fullFileNameHash.Add(appendPathTotalItem)) { - fullFileNameHash.Add(appendPathTotalItem); newFormats.Add(new SessionStateFormatEntry(appendPathTotalItem)); } } @@ -1056,7 +1051,7 @@ public class RemoveTypeDataCommand : PSCmdlet /// The target type to remove. /// [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = RemoveTypeSet)] - [ArgumentToTypeNameTransformationAttribute()] + [ArgumentToTypeNameTransformation] [ValidateNotNullOrEmpty] public string TypeName { @@ -1118,7 +1113,10 @@ protected override void ProcessRecord() string removeFileTarget = UpdateDataStrings.UpdateTarget; Collection typeFileTotal = UpdateData.Glob(_typeFiles, "TypePathException", this); - if (typeFileTotal.Count == 0) { return; } + 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() @@ -1130,7 +1128,10 @@ protected override void ProcessRecord() for (int index = 0; index < Context.InitialSessionState.Types.Count; index++) { string fileName = Context.InitialSessionState.Types[index].FileName; - if (fileName == null) { continue; } + 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 @@ -1161,10 +1162,7 @@ protected override void ProcessRecord() indicesToRemove.Sort(); for (int i = indicesToRemove.Count - 1; i >= 0; i--) { - if (Context.InitialSessionState != null) - { - Context.InitialSessionState.Types.RemoveItem(indicesToRemove[i]); - } + Context.InitialSessionState?.Types.RemoveItem(indicesToRemove[i]); } try @@ -1337,7 +1335,6 @@ protected override void ProcessRecord() ValidateTypeName(); Dictionary alltypes = Context.TypeTable.GetAllTypeData(); - Collection typedefs = new(); foreach (string type in alltypes.Keys) { @@ -1345,17 +1342,11 @@ protected override void ProcessRecord() { if (pattern.IsMatch(type)) { - typedefs.Add(alltypes[type]); + WriteObject(alltypes[type]); break; } } } - - // write out all the available type definitions - foreach (TypeData typedef in typedefs) - { - WriteObject(typedef); - } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs index 69b89e928ce..1e3cc038750 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/UtilityCommon.cs @@ -78,15 +78,10 @@ public static class UtilityResources public static string FileReadError { get { return UtilityCommonStrings.FileReadError; } } /// - /// The resource string used to indicate 'PATH:' in the formating header. + /// The resource string used to indicate 'PATH:' in the formatting header. /// public static string FormatHexPathPrefix { get { return UtilityCommonStrings.FormatHexPathPrefix; } } - /// - /// Error message to indicate that requested algorithm is not supported on the target platform. - /// - public static string AlgorithmTypeNotSupported { get { return UtilityCommonStrings.AlgorithmTypeNotSupported; } } - /// /// The file '{0}' could not be parsed as a PowerShell Data File. /// @@ -188,11 +183,11 @@ public ByteCollection(byte[] 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 UInt32 Offset + public uint Offset { get { - return (UInt32)Offset64; + return (uint)Offset64; } private set @@ -204,7 +199,7 @@ private set /// /// Gets the Offset address to be used while displaying the bytes in the collection. /// - public UInt64 Offset64 { get; private set; } + public ulong Offset64 { get; private set; } /// /// Gets underlying bytes stored in the collection. @@ -220,7 +215,7 @@ private set /// /// Gets the hexadecimal representation of the value. /// - public string HexOffset { get => string.Format(CultureInfo.CurrentCulture, "{0:X16}", Offset64); } + public string HexOffset => string.Create(CultureInfo.CurrentCulture, $"{Offset64:X16}"); /// /// Gets the type of the input objects used to create the . diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs index 20f8f847475..a41b284f568 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Var.cs @@ -22,6 +22,7 @@ public abstract class VariableCommandBase : PSCmdlet /// [Parameter] [ValidateNotNullOrEmpty] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } #endregion parameters @@ -38,10 +39,7 @@ protected string[] IncludeFilters set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _include = value; } @@ -61,10 +59,7 @@ protected string[] ExcludeFilters set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _exclude = value; } @@ -258,10 +253,7 @@ public string[] Name set { - if (value == null) - { - value = new string[] { "*" }; - } + value ??= new string[] { "*" }; _name = value; } @@ -336,7 +328,7 @@ protected override void ProcessRecord() GetMatchingVariables(varName, Scope, out wasFiltered, /*quiet*/ false); matchingVariables.Sort( - (PSVariable left, PSVariable right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)); + static (PSVariable left, PSVariable right) => StringComparer.CurrentCultureIgnoreCase.Compare(left.Name, right.Name)); bool matchFound = false; foreach (PSVariable matchingVariable in matchingVariables) @@ -374,6 +366,7 @@ protected override void ProcessRecord() /// [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 @@ -700,6 +693,12 @@ public SwitchParameter PassThru 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 @@ -718,6 +717,33 @@ protected override void BeginProcessing() { _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); + } + } + } } /// @@ -733,6 +759,16 @@ protected override void ProcessRecord() { if (_nameIsFormalParameter && _valueIsFormalParameter) { + if (Append) + { + if (Value != AutomationNull.Value) + { + _valueList ??= new List(); + + _valueList.Add(Value); + } + } + return; } @@ -740,10 +776,7 @@ protected override void ProcessRecord() { if (Value != AutomationNull.Value) { - if (_valueList == null) - { - _valueList = new List(); - } + _valueList ??= new List(); _valueList.Add(Value); } @@ -766,7 +799,14 @@ protected override void EndProcessing() { if (_valueIsFormalParameter) { - SetVariable(Name, Value); + if (Append) + { + SetVariable(Name, _valueList); + } + else + { + SetVariable(Name, Value); + } } else { @@ -870,10 +910,7 @@ private void SetVariable(string[] varNames, object varValue) newVarValue, newOptions); - if (Description == null) - { - Description = string.Empty; - } + Description ??= string.Empty; varToSet.Description = Description; @@ -1102,10 +1139,7 @@ protected override void ProcessRecord() // Removal of variables only happens in the local scope if the // scope wasn't explicitly specified by the user. - if (Scope == null) - { - Scope = "local"; - } + Scope ??= "local"; foreach (string varName in Name) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs index 70ac9e4ae95..3c4336f07d0 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WaitEventCommand.cs @@ -42,7 +42,7 @@ public string SourceIdentifier /// [Parameter] [Alias("TimeoutSec")] - [ValidateRangeAttribute(-1, Int32.MaxValue)] + [ValidateRange(-1, int.MaxValue)] public int Timeout { get diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs index 969dd8231c8..ea650e80e67 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/BasicHtmlWebResponseObject.Common.cs @@ -1,13 +1,18 @@ // 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 { @@ -16,38 +21,27 @@ namespace Microsoft.PowerShell.Commands /// public class BasicHtmlWebResponseObject : WebResponseObject { - #region Private Fields - - private static Regex s_attribNameValueRegex; - private static Regex s_attribsRegex; - private static Regex s_imageRegex; - private static Regex s_inputFieldRegex; - private static Regex s_linkRegex; - private static Regex s_tagRegex; - - #endregion Private Fields - #region Constructors /// /// Initializes a new instance of the class. /// - /// - public BasicHtmlWebResponseObject(HttpResponseMessage response) - : this(response, null) - { } + /// 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 . /// - /// - /// - public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentStream) - : base(response, contentStream) + /// 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) { - EnsureHtmlParser(); - InitializeContent(); + InitializeContent(cancellationToken); InitializeRawContent(response); } @@ -72,9 +66,9 @@ public BasicHtmlWebResponseObject(HttpResponseMessage response, Stream contentSt /// Encoding of the response body from the Content-Type header, /// or if the encoding could not be determined. /// - public Encoding Encoding { get; private set; } + public Encoding? Encoding { get; private set; } - private WebCmdletElementCollection _inputFields; + private WebCmdletElementCollection? _inputFields; /// /// Gets the HTML input field elements parsed from . @@ -85,13 +79,11 @@ public WebCmdletElementCollection InputFields { if (_inputFields == null) { - EnsureHtmlParser(); - List parsedFields = new(); - MatchCollection fieldMatch = s_inputFieldRegex.Matches(Content); - foreach (Match field in fieldMatch) + MatchCollection fieldMatch = HtmlParser.InputFieldRegex.Matches(Content); + foreach (Match match in fieldMatch) { - parsedFields.Add(CreateHtmlObject(field.Value, "INPUT")); + parsedFields.Add(CreateHtmlObject(match.Value, "INPUT")); } _inputFields = new WebCmdletElementCollection(parsedFields); @@ -101,7 +93,7 @@ public WebCmdletElementCollection InputFields } } - private WebCmdletElementCollection _links; + private WebCmdletElementCollection? _links; /// /// Gets the HTML a link elements parsed from . @@ -112,10 +104,8 @@ public WebCmdletElementCollection Links { if (_links == null) { - EnsureHtmlParser(); - List parsedLinks = new(); - MatchCollection linkMatch = s_linkRegex.Matches(Content); + MatchCollection linkMatch = HtmlParser.LinkRegex.Matches(Content); foreach (Match link in linkMatch) { parsedLinks.Add(CreateHtmlObject(link.Value, "A")); @@ -128,7 +118,7 @@ public WebCmdletElementCollection Links } } - private WebCmdletElementCollection _images; + private WebCmdletElementCollection? _images; /// /// Gets the HTML img elements parsed from . @@ -139,10 +129,8 @@ public WebCmdletElementCollection Images { if (_images == null) { - EnsureHtmlParser(); - List parsedImages = new(); - MatchCollection imageMatch = s_imageRegex.Matches(Content); + MatchCollection imageMatch = HtmlParser.ImageRegex.Matches(Content); foreach (Match image in imageMatch) { parsedImages.Add(CreateHtmlObject(image.Value, "IMG")); @@ -162,26 +150,22 @@ public WebCmdletElementCollection Images /// /// Reads the response content from the web response. /// - protected void InitializeContent() + /// The cancellation token. + [MemberNotNull(nameof(Content))] + protected void InitializeContent(CancellationToken cancellationToken) { - string contentType = ContentHelper.GetContentType(BaseResponse); + string? contentType = ContentHelper.GetContentType(BaseResponse); if (ContentHelper.IsText(contentType)) { - Encoding encoding = null; - // fill the Content buffer - string characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); - - if (string.IsNullOrEmpty(characterSet) && ContentHelper.IsJson(contentType)) - { - characterSet = Encoding.UTF8.HeaderName; - } + // Fill the Content buffer + string? characterSet = WebResponseHelper.GetCharacterSet(BaseResponse); - this.Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out encoding); - this.Encoding = encoding; + Content = StreamHelper.DecodeStream(RawContentStream, characterSet, out Encoding encoding, perReadTimeout, cancellationToken); + Encoding = encoding; } else { - this.Content = string.Empty; + Content = string.Empty; } } @@ -197,50 +181,11 @@ private static PSObject CreateHtmlObject(string html, string tagName) return elementObject; } - private static void EnsureHtmlParser() - { - if (s_tagRegex == null) - { - s_tagRegex = new Regex(@"<\w+((\s+[^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)+\s*|\s*)/?>", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - - if (s_attribsRegex == null) - { - s_attribsRegex = new Regex(@"(?<=\s+)([^""'>/=\s\p{Cc}]+(\s*=\s*(?:"".*?""|'.*?'|[^'"">\s]+))?)", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - - if (s_attribNameValueRegex == null) - { - s_attribNameValueRegex = new Regex(@"([^""'>/=\s\p{Cc}]+)(?:\s*=\s*(?:""(.*?)""|'(.*?)'|([^'"">\s]+)))?", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - - if (s_inputFieldRegex == null) - { - s_inputFieldRegex = new Regex(@"]*(/>|>.*?)", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - - if (s_linkRegex == null) - { - s_linkRegex = new Regex(@"]*(/>|>.*?)", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - - if (s_imageRegex == null) - { - s_imageRegex = new Regex(@"]*?>", - RegexOptions.Singleline | RegexOptions.IgnoreCase | RegexOptions.Compiled); - } - } - private void InitializeRawContent(HttpResponseMessage baseResponse) { StringBuilder raw = ContentHelper.GetRawContentHeader(baseResponse); raw.Append(Content); - this.RawContent = raw.ToString(); + RawContent = raw.ToString(); } private static void ParseAttributes(string outerHtml, PSObject elementObject) @@ -250,23 +195,23 @@ private static void ParseAttributes(string outerHtml, PSObject elementObject) { // Extract just the opening tag of the HTML element (omitting the closing tag and any contents, // including contained HTML elements) - var match = s_tagRegex.Match(outerHtml); + Match match = HtmlParser.TagRegex.Match(outerHtml); // Extract all the attribute specifications within the HTML element opening tag - var attribMatches = s_attribsRegex.Matches(match.Value); + 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) - var nvMatches = s_attribNameValueRegex.Match(attribMatch.Value); + 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; + string? value = null; if (nvMatches.Groups[2].Success) { value = nvMatches.Groups[2].Value; @@ -286,5 +231,21 @@ private static void ParseAttributes(string outerHtml, PSObject elementObject) } #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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs index f16ad99d2a1..9eca5ce187a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/ContentHelper.Common.cs @@ -1,70 +1,34 @@ // 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 Constants - - // default codepage encoding for web content. See RFC 2616. - private const string _defaultCodePage = "ISO-8859-1"; - - #endregion Constants - - #region Fields - - // used to split contentType arguments - private static readonly char[] s_contentTypeParamSeparator = { ';' }; - - #endregion Fields - #region Internal Methods - internal static string GetContentType(HttpResponseMessage response) - { - // ContentType may not exist in response header. Return null if not. - return response.Content.Headers.ContentType?.MediaType; - } + // ContentType may not exist in response header. Return null if not. + internal static string? GetContentType(HttpResponseMessage response) => response.Content.Headers.ContentType?.MediaType; - internal static Encoding GetDefaultEncoding() - { - return GetEncodingOrDefault((string)null); - } + internal static string? GetContentType(HttpRequestMessage request) => request.Content?.Headers.ContentType?.MediaType; - internal static Encoding GetEncoding(HttpResponseMessage response) - { - // ContentType may not exist in response header. - string charSet = response.Content.Headers.ContentType?.CharSet; - return GetEncodingOrDefault(charSet); - } + internal static Encoding GetDefaultEncoding() => Encoding.UTF8; - internal static Encoding GetEncodingOrDefault(string characterSet) - { - // get the name of the codepage to use for response content - string codepage = (string.IsNullOrEmpty(characterSet) ? _defaultCodePage : characterSet); - Encoding encoding = null; - - try - { - encoding = Encoding.GetEncoding(codepage); - } - catch (ArgumentException) - { - // 0, default code page - encoding = Encoding.GetEncoding(0); - } - - return encoding; - } + internal static string GetFriendlyContentLength(long? length) => + length.HasValue + ? $"{length.Value.Bytes().Humanize()} ({length.Value:#,0} bytes)" + : "unknown size"; internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { @@ -75,14 +39,13 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) { int statusCode = WebResponseHelper.GetStatusCode(response); string statusDescription = WebResponseHelper.GetStatusDescription(response); - raw.AppendFormat("{0} {1} {2}", protocol, statusCode, statusDescription); - raw.AppendLine(); + raw.AppendLine($"{protocol} {statusCode} {statusDescription}"); } HttpHeaders[] headerCollections = { response.Headers, - response.Content?.Headers + response.Content.Headers }; foreach (var headerCollection in headerCollections) @@ -95,12 +58,9 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) foreach (var header in headerCollection) { // Headers may have multiple entries with different values - foreach (var headerValue in header.Value) + foreach (string headerValue in header.Value) { - raw.Append(header.Key); - raw.Append(": "); - raw.Append(headerValue); - raw.AppendLine(); + raw.AppendLine($"{header.Key}: {headerValue}"); } } } @@ -109,74 +69,55 @@ internal static StringBuilder GetRawContentHeader(HttpResponseMessage response) return raw; } - internal static bool IsJson(string contentType) - { - contentType = GetContentTypeSignature(contentType); - return CheckIsJson(contentType); - } - - internal static bool IsText(string contentType) - { - contentType = GetContentTypeSignature(contentType); - return CheckIsText(contentType); - } - - internal static bool IsXml(string contentType) - { - contentType = GetContentTypeSignature(contentType); - return CheckIsXml(contentType); - } - - #endregion Internal Methods - - #region Private Helper Methods - - private static bool CheckIsJson(string contentType) + 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 + // 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 + // 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); + || 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); + return isJson; } - private static bool CheckIsText(string contentType) + internal static bool IsText([NotNullWhen(true)] string? contentType) { if (string.IsNullOrEmpty(contentType)) + { return false; + } - // any text, xml or json types are text + // Any text, xml or json types are text bool isText = contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase) - || CheckIsXml(contentType) - || CheckIsJson(contentType); + || 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)) + using (RegistryKey? contentTypeKey = Registry.ClassesRoot.OpenSubKey(@"MIME\Database\Content Type\" + contentType)) { if (contentTypeKey != null) { - string extension = contentTypeKey.GetValue("Extension") as string; - if (extension != null) + if (contentTypeKey.GetValue("Extension") is string extension) { - using (RegistryKey extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) + using (RegistryKey? extensionKey = Registry.ClassesRoot.OpenSubKey(extension)) { if (extensionKey != null) { - string perceivedType = extensionKey.GetValue("PerceivedType") as string; - isText = (perceivedType == "text"); + string? perceivedType = extensionKey.GetValue("PerceivedType") as string; + isText = perceivedType == "text"; } } } @@ -184,32 +125,28 @@ private static bool CheckIsText(string contentType) } } - return (isText); + return isText; } - private static bool CheckIsXml(string contentType) + 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)); + 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); - isXml |= contentType.EndsWith("+xml", StringComparison.OrdinalIgnoreCase); - return (isXml); + return isXml; } - private static string GetContentTypeSignature(string contentType) - { - if (string.IsNullOrEmpty(contentType)) - return null; + internal static bool IsTextBasedContentType([NotNullWhen(true)] string? contentType) + => IsText(contentType) || IsJson(contentType) || IsXml(contentType); - string sig = contentType.Split(s_contentTypeParamSeparator, 2)[0].ToUpperInvariant(); - return (sig); - } - - #endregion Private Helper Methods + #endregion Internal Methods } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HttpVersionCompletionsAttribute.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/HttpVersionCompletionsAttribute.cs new file mode 100644 index 00000000000..903ff4d8f80 --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs index 235aaf82773..22ffaef288c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/InvokeRestMethodCommand.Common.cs @@ -1,11 +1,15 @@ // 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; @@ -13,36 +17,18 @@ namespace Microsoft.PowerShell.Commands { - public partial class InvokeRestMethodCommand + /// + /// 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 - /// - /// Gets or sets the parameter Method. - /// - [Parameter(ParameterSetName = "StandardMethod")] - [Parameter(ParameterSetName = "StandardMethodNoProxy")] - public override WebRequestMethod Method - { - get { return base.Method; } - - set { base.Method = value; } - } - - /// - /// Gets or sets the parameter CustomMethod. - /// - [Parameter(Mandatory = true, ParameterSetName = "CustomMethod")] - [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] - [Alias("CM")] - [ValidateNotNullOrEmpty] - public override string CustomMethod - { - get { return base.CustomMethod; } - - set { base.CustomMethod = value; } - } - /// /// Enable automatic following of rel links. /// @@ -50,9 +36,9 @@ public override string CustomMethod [Alias("FL")] public SwitchParameter FollowRelLink { - get { return base._followRelLink; } + get => base._followRelLink; - set { base._followRelLink = value; } + set => base._followRelLink = value; } /// @@ -60,12 +46,12 @@ public SwitchParameter FollowRelLink /// [Parameter] [Alias("ML")] - [ValidateRange(1, Int32.MaxValue)] + [ValidateRange(1, int.MaxValue)] public int MaximumFollowRelLink { - get { return base._maximumFollowRelLink; } + get => base._maximumFollowRelLink; - set { base._maximumFollowRelLink = value; } + set => base._maximumFollowRelLink = value; } /// @@ -73,18 +59,137 @@ public int MaximumFollowRelLink /// [Parameter] [Alias("RHV")] - public string ResponseHeadersVariable { get; set; } + 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; } + 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; @@ -111,7 +216,8 @@ private bool TryProcessFeedStream(Stream responseStream) if (isRssOrFeed) { XmlDocument workingDocument = new(); - // performing a Read() here to avoid rrechecking + + // Performing a Read() here to avoid rechecking // "rss" or "feed" items reader.Read(); while (!reader.EOF) @@ -122,8 +228,8 @@ private bool TryProcessFeedStream(Stream responseStream) string.Equals("Entry", reader.Name, StringComparison.OrdinalIgnoreCase)) ) { - // this one will do reader.Read() internally - XmlNode result = workingDocument.ReadNode(reader); + // This one will do reader.Read() internally + XmlNode? result = workingDocument.ReadNode(reader); WriteObject(result); } else @@ -133,7 +239,10 @@ private bool TryProcessFeedStream(Stream responseStream) } } } - catch (XmlException) { } + catch (XmlException) + { + // Catch XmlException + } finally { responseStream.Seek(0, SeekOrigin.Begin); @@ -159,14 +268,14 @@ private static XmlReaderSettings GetSecureXmlReaderSettings() return xrs; } - private static bool TryConvertToXml(string xml, out object doc, ref Exception exRef) + 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); - var xmlDoc = new XmlDocument(); + XmlDocument xmlDoc = new(); xmlDoc.PreserveWhitespace = true; xmlDoc.Load(xmlReader); @@ -178,16 +287,15 @@ private static bool TryConvertToXml(string xml, out object doc, ref Exception ex doc = null; } - return (doc != null); + return doc != null; } - private static bool TryConvertToJson(string json, out object obj, ref Exception exRef) + private static bool TryConvertToJson(string json, [NotNullWhen(true)] out object? obj, ref Exception? exRef) { bool converted = false; try { - ErrorRecord error; - obj = JsonObject.ConvertFromJson(json, out error); + obj = JsonObject.ConvertFromJson(json, out ErrorRecord error); if (obj == null) { @@ -206,19 +314,14 @@ private static bool TryConvertToJson(string json, out object obj, ref Exception converted = true; } } - catch (ArgumentException ex) - { - exRef = ex; - obj = null; - } - catch (InvalidOperationException ex) + catch (Exception ex) when (ex is ArgumentException || ex is InvalidOperationException) { exRef = ex; obj = null; } catch (JsonException ex) { - var msg = string.Format(System.Globalization.CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, ex.Message); + string msg = string.Format(System.Globalization.CultureInfo.CurrentCulture, WebCmdletStrings.JsonDeserializationFailed, ex.Message); exRef = new ArgumentException(msg, ex); obj = null; } @@ -226,7 +329,7 @@ private static bool TryConvertToJson(string json, out object obj, ref Exception return converted; } - #endregion + #endregion Helper Methods /// /// Enum for rest return type. @@ -242,7 +345,7 @@ public enum RestReturnType /// /// Json return type. /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] Json, /// @@ -251,52 +354,44 @@ public enum RestReturnType Xml, } - internal class BufferingStreamReader : Stream + internal sealed class BufferingStreamReader : Stream { - internal BufferingStreamReader(Stream baseStream) + 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 - { - get { return true; } - } + public override bool CanRead => true; - public override bool CanSeek - { - get { return true; } - } + public override bool CanSeek => true; - public override bool CanWrite - { - get { return false; } - } + public override bool CanWrite => false; public override void Flush() { _streamBuffer.SetLength(0); } - public override long Length - { - get { return _length; } - } + public override long Length => _length; private long _length; public override long Position { - get { return _streamBuffer.Position; } + get => _streamBuffer.Position; - set { _streamBuffer.Position = value; } + set => _streamBuffer.Position = value; } public override int Read(byte[] buffer, int offset, int count) @@ -304,13 +399,12 @@ 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)) + 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.Read(_copyBuffer, 0, _copyBuffer.Length); + int bytesRead = _baseStream.ReadAsync(_copyBuffer.AsMemory(), _perReadTimeout, _cancellationToken).GetAwaiter().GetResult(); if (_streamBuffer.Position < _streamBuffer.Length) { @@ -359,147 +453,4 @@ public override void Write(byte[] buffer, int offset, int count) } } } - - // TODO: Merge Partials - - /// - /// 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 partial class InvokeRestMethodCommand : WebRequestPSCmdlet - { - #region Virtual Method Overrides - - /// - /// Process the web response and output corresponding objects. - /// - /// - internal override void ProcessResponse(HttpResponseMessage response) - { - if (response == null) { throw new ArgumentNullException(nameof(response)); } - - var baseResponseStream = StreamHelper.GetResponseStream(response); - - if (ShouldWriteToPipeline) - { - using var responseStream = new BufferingStreamReader(baseResponseStream); - - // 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 - { - // determine the response type - RestReturnType returnType = CheckReturnType(response); - - // Try to get the response encoding from the ContentType header. - Encoding encoding = null; - string charSet = response.Content.Headers.ContentType?.CharSet; - if (!string.IsNullOrEmpty(charSet)) - { - // NOTE: Don't use ContentHelper.GetEncoding; it returns a - // default which bypasses checking for a meta charset value. - StreamHelper.TryGetEncoding(charSet, out encoding); - } - - if (string.IsNullOrEmpty(charSet) && returnType == RestReturnType.Json) - { - encoding = Encoding.UTF8; - } - - object obj = null; - Exception ex = null; - - string str = StreamHelper.DecodeStream(responseStream, ref encoding); - - string encodingVerboseName; - try - { - encodingVerboseName = string.IsNullOrEmpty(encoding.HeaderName) ? encoding.EncodingName : encoding.HeaderName; - } - catch (NotSupportedException) - { - encodingVerboseName = encoding.EncodingName; - } - // NOTE: Tests use this verbose output to verify the encoding. - WriteVerbose(string.Format - ( - System.Globalization.CultureInfo.InvariantCulture, - "Content encoding: {0}", - encodingVerboseName) - ); - bool convertSuccess = false; - - 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); - } - } - else if (ShouldSaveToOutFile) - { - StreamHelper.SaveStreamToFile(baseResponseStream, QualifiedOutFile, this, _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) - { - if (response == null) { throw new ArgumentNullException(nameof(response)); } - - RestReturnType rt = RestReturnType.Detect; - string contentType = ContentHelper.GetContentType(response); - if (string.IsNullOrEmpty(contentType)) - { - rt = RestReturnType.Detect; - } - else if (ContentHelper.IsJson(contentType)) - { - rt = RestReturnType.Json; - } - else if (ContentHelper.IsXml(contentType)) - { - rt = RestReturnType.Xml; - } - - return (rt); - } - - #endregion Helper Methods - } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs index 3423b912fe7..f1a455974b9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebRequestPSCmdlet.Common.cs @@ -11,11 +11,14 @@ 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; @@ -60,17 +63,17 @@ public enum WebSslProtocol /// /// No SSL protocol will be set and the system defaults will be used. /// - Default = 0, + Default = SslProtocols.None, /// - /// Specifies the TLS 1.0 security protocol. The TLS protocol is defined in IETF RFC 2246. + /// Specifies the TLS 1.0 is obsolete. Using this value now defaults to TLS 1.2. /// - Tls = SslProtocols.Tls, + Tls = SslProtocols.Tls12, /// - /// Specifies the TLS 1.1 security protocol. The TLS protocol is defined in IETF RFC 4346. + /// Specifies the TLS 1.1 is obsolete. Using this value now defaults to TLS 1.2. /// - Tls11 = SslProtocols.Tls11, + Tls11 = SslProtocols.Tls12, /// /// Specifies the TLS 1.2 security protocol. The TLS protocol is defined in IETF RFC 5246. @@ -86,8 +89,62 @@ public enum WebSslProtocol /// /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. /// - public abstract partial class WebRequestPSCmdlet : PSCmdlet + 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 @@ -105,7 +162,19 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [ValidateNotNullOrEmpty] public virtual Uri Uri { get; set; } - #endregion + #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 /// @@ -121,7 +190,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Alias("SV")] public virtual string SessionVariable { get; set; } - #endregion + #endregion Session #region Authorization and Credentials @@ -132,7 +201,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet public virtual SwitchParameter AllowUnencryptedAuthentication { get; set; } /// - /// Gets or sets the Authentication property used to determin the Authentication method for the web session. + /// 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. @@ -186,7 +255,7 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Parameter] public virtual SecureString Token { get; set; } - #endregion + #endregion Authorization and Credentials #region Headers @@ -203,11 +272,25 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet public virtual SwitchParameter DisableKeepAlive { get; set; } /// - /// Gets or sets the TimeOut property. + /// 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, Int32.MaxValue)] - public virtual int TimeoutSec { get; set; } + [ValidateRange(0, int.MaxValue)] + public virtual int OperationTimeoutSeconds { get; set; } /// /// Gets or sets the Headers property. @@ -216,39 +299,62 @@ public abstract partial class WebRequestPSCmdlet : PSCmdlet [Parameter] public virtual IDictionary Headers { get; set; } - #endregion + /// + /// 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 RedirectMax property. + /// Gets or sets the AllowInsecureRedirect property used to follow HTTP redirects from HTTPS. /// [Parameter] - [ValidateRange(0, Int32.MaxValue)] - public virtual int MaximumRedirection - { - get { return _maximumRedirection; } - - set { _maximumRedirection = value; } - } + public virtual SwitchParameter AllowInsecureRedirect { get; set; } - private int _maximumRedirection = -1; + /// + /// 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, Int32.MaxValue)] + [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, Int32.MaxValue)] + [ValidateRange(1, int.MaxValue)] public virtual int RetryIntervalSec { get; set; } = 5; - #endregion + #endregion Redirect #region Method @@ -257,14 +363,7 @@ public virtual int MaximumRedirection /// [Parameter(ParameterSetName = "StandardMethod")] [Parameter(ParameterSetName = "StandardMethodNoProxy")] - public virtual WebRequestMethod Method - { - get { return _method; } - - set { _method = value; } - } - - private WebRequestMethod _method = WebRequestMethod.Default; + public virtual WebRequestMethod Method { get; set; } = WebRequestMethod.Default; /// /// Gets or sets the CustomMethod property. @@ -273,16 +372,24 @@ public virtual WebRequestMethod Method [Parameter(Mandatory = true, ParameterSetName = "CustomMethodNoProxy")] [Alias("CM")] [ValidateNotNullOrEmpty] - public virtual string CustomMethod - { - get { return _customMethod; } - - set { _customMethod = value; } - } + public virtual string CustomMethod { get => _customMethod; set => _customMethod = value.ToUpperInvariant(); } private string _customMethod; - #endregion + /// + /// 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 @@ -293,7 +400,7 @@ public virtual string CustomMethod [Parameter(Mandatory = true, ParameterSetName = "StandardMethodNoProxy")] public virtual SwitchParameter NoProxy { get; set; } - #endregion + #endregion NoProxy #region Proxy @@ -319,7 +426,7 @@ public virtual string CustomMethod [Parameter(ParameterSetName = "CustomMethod")] public virtual SwitchParameter ProxyUseDefaultCredentials { get; set; } - #endregion + #endregion Proxy #region Input @@ -354,6 +461,7 @@ public virtual string CustomMethod /// Gets or sets the InFile property. /// [Parameter] + [ValidateNotNullOrEmpty] public virtual string InFile { get; set; } /// @@ -361,7 +469,7 @@ public virtual string CustomMethod /// private string _originalFilePath; - #endregion + #endregion Input #region Output @@ -369,6 +477,7 @@ public virtual string CustomMethod /// Gets or sets the OutFile property. /// [Parameter] + [ValidateNotNullOrEmpty] public virtual string OutFile { get; set; } /// @@ -389,142 +498,366 @@ public virtual string CustomMethod [Parameter] public virtual SwitchParameter SkipHttpErrorCheck { get; set; } - #endregion + #endregion Output #endregion Virtual Properties - #region Virtual Methods + #region Helper Properties - internal virtual void ValidateParameters() + 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() { - // sessions - if ((WebSession != null) && (SessionVariable != null)) + try { - ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, - "WebCmdletSessionConflictException"); - ThrowTerminatingError(error); + // 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); + } + } - // Authentication - if (UseDefaultCredentials && (Authentication != WebAuthenticationType.None)) + /// + /// 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.AuthenticationConflict, - "WebCmdletAuthenticationConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.SessionConflict, "WebCmdletSessionConflictException"); ThrowTerminatingError(error); } - if ((Authentication != WebAuthenticationType.None) && (Token != null) && (Credential != null)) + // Authentication + if (UseDefaultCredentials && Authentication != WebAuthenticationType.None) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, - "WebCmdletAuthenticationTokenConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationConflict, "WebCmdletAuthenticationConflictException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.Basic) && (Credential == null)) + if (Authentication != WebAuthenticationType.None && Token is not null && Credential is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, - "WebCmdletAuthenticationCredentialNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenConflict, "WebCmdletAuthenticationTokenConflictException"); ThrowTerminatingError(error); } - if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && (Token == null)) + if (Authentication == WebAuthenticationType.Basic && Credential is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, - "WebCmdletAuthenticationTokenNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationCredentialNotSupplied, "WebCmdletAuthenticationCredentialNotSuppliedException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None) && (Uri.Scheme != "https")) + if ((Authentication == WebAuthenticationType.OAuth || Authentication == WebAuthenticationType.Bearer) && Token is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, - "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AuthenticationTokenNotSupplied, "WebCmdletAuthenticationTokenNotSuppliedException"); ThrowTerminatingError(error); } - if (!AllowUnencryptedAuthentication && (Credential != null || UseDefaultCredentials) && (Uri.Scheme != "https")) + if (!AllowUnencryptedAuthentication && (Authentication != WebAuthenticationType.None || Credential is not null || UseDefaultCredentials) && Uri.Scheme != "https") { - ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, - "WebCmdletAllowUnencryptedAuthenticationRequiredException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.AllowUnencryptedAuthenticationRequired, "WebCmdletAllowUnencryptedAuthenticationRequiredException"); ThrowTerminatingError(error); } - // credentials - if (UseDefaultCredentials && (Credential != null)) + // Credentials + if (UseDefaultCredentials && Credential is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, - "WebCmdletCredentialConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.CredentialConflict, "WebCmdletCredentialConflictException"); ThrowTerminatingError(error); } // Proxy server - if (ProxyUseDefaultCredentials && (ProxyCredential != null)) + if (ProxyUseDefaultCredentials && ProxyCredential is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, - "WebCmdletProxyCredentialConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyCredentialConflict, "WebCmdletProxyCredentialConflictException"); ThrowTerminatingError(error); } - else if ((Proxy == null) && ((ProxyCredential != null) || ProxyUseDefaultCredentials)) + else if (Proxy is null && (ProxyCredential is not null || ProxyUseDefaultCredentials)) { - ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, - "WebCmdletProxyUriNotSuppliedException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.ProxyUriNotSupplied, "WebCmdletProxyUriNotSuppliedException"); ThrowTerminatingError(error); } - // request body content - if ((Body != null) && (InFile != null)) + // Request body content + if (Body is not null && InFile is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, - "WebCmdletBodyConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyConflict, "WebCmdletBodyConflictException"); ThrowTerminatingError(error); } - if ((Body != null) && (Form != null)) + if (Body is not null && Form is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, - "WebCmdletBodyFormConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.BodyFormConflict, "WebCmdletBodyFormConflictException"); ThrowTerminatingError(error); } - if ((InFile != null) && (Form != null)) + if (InFile is not null && Form is not null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, - "WebCmdletFormInFileConflictException"); + ErrorRecord error = GetValidationError(WebCmdletStrings.FormInFileConflict, "WebCmdletFormInFileConflictException"); ThrowTerminatingError(error); } - // validate InFile path - if (InFile != null) + // Validate InFile path + if (InFile is not null) { - ProviderInfo provider = null; ErrorRecord errorRecord = null; try { - Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out provider); + Collection providerPaths = GetResolvedProviderPathFromPSPath(InFile, out ProviderInfo provider); if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, - "WebCmdletInFileNotFilesystemPathException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.NotFilesystemPath, "WebCmdletInFileNotFilesystemPathException", InFile); } else { if (providerPaths.Count > 1) { - errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, - "WebCmdletInFileMultiplePathsResolvedException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.MultiplePathsResolved, "WebCmdletInFileMultiplePathsResolvedException", InFile); } else if (providerPaths.Count == 0) { - errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, - "WebCmdletInFileNoPathResolvedException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.NoPathResolved, "WebCmdletInFileNoPathResolvedException", InFile); } else { if (Directory.Exists(providerPaths[0])) { - errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, - "WebCmdletInFileNotFilePathException", InFile); + errorRecord = GetValidationError(WebCmdletStrings.DirectoryPathSpecified, "WebCmdletInFileNotFilePathException", InFile); } _originalFilePath = InFile; @@ -545,57 +878,59 @@ internal virtual void ValidateParameters() errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); } - if (errorRecord != null) + if (errorRecord is not null) { ThrowTerminatingError(errorRecord); } } - // output ?? - if (PassThru && (OutFile == null)) + // Output ?? + if (PassThru.IsPresent && OutFile is null) { - ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, - "WebCmdletOutFileMissingException", nameof(PassThru)); + ErrorRecord error = GetValidationError(WebCmdletStrings.OutFileMissing, "WebCmdletOutFileMissingException", nameof(PassThru)); ThrowTerminatingError(error); } // Resume requires OutFile. - if (Resume.IsPresent && OutFile == null) + 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.OutFileMissing, - "WebCmdletOutFileMissingException", nameof(Resume)); + ErrorRecord error = GetValidationError(WebCmdletStrings.ResumeNotFilePath, "WebCmdletResumeNotFilePathException", _qualifiedOutFile); ThrowTerminatingError(error); } } internal virtual void PrepareSession() { - // make sure we have a valid WebRequestSession object to work with - if (WebSession == null) - { - WebSession = new WebRequestSession(); - } + // Make sure we have a valid WebRequestSession object to work with + WebSession ??= new WebRequestSession(); - if (SessionVariable != null) + if (SessionVariable is not null) { - // save the session back to the PS environment if requested + // Save the session back to the PS environment if requested PSVariableIntrinsics vi = SessionState.PSVariable; vi.Set(SessionVariable, WebSession); } - // - // handle credentials - // - if (Credential != null && Authentication == WebAuthenticationType.None) + // Handle credentials + if (Credential is not null && Authentication == WebAuthenticationType.None) { - // get the relevant NetworkCredential + // Get the relevant NetworkCredential NetworkCredential netCred = Credential.GetNetworkCredential(); WebSession.Credentials = netCred; - // supplying a credential overrides the UseDefaultCredentials setting + // Supplying a credential overrides the UseDefaultCredentials setting WebSession.UseDefaultCredentials = false; } - else if ((Credential != null || Token != null) && Authentication != WebAuthenticationType.None) + else if ((Credential is not null || Token is not null) && Authentication != WebAuthenticationType.None) { ProcessAuthentication(); } @@ -604,16 +939,15 @@ internal virtual void PrepareSession() WebSession.UseDefaultCredentials = true; } - if (CertificateThumbprint != null) + if (CertificateThumbprint is not null) { - X509Store store = new(StoreName.My, StoreLocation.CurrentUser); + 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) { - CryptographicException ex = new(WebCmdletStrings.ThumbprintNotFound); - throw ex; + throw new CryptographicException(WebCmdletStrings.ThumbprintNotFound); } foreach (X509Certificate2 tbCert in tbCollection) @@ -623,36 +957,53 @@ internal virtual void PrepareSession() } } - if (Certificate != null) + if (Certificate is not null) { WebSession.AddCertificate(Certificate); } - // - // handle the user agent - // - if (UserAgent != null) + // Handle the user agent + if (UserAgent is not null) { - // store the UserAgent string + // Store the UserAgent string WebSession.UserAgent = UserAgent; } - if (Proxy != null) + // 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) { - WebProxy webProxy = new(Proxy); - webProxy.BypassProxyOnLocal = false; - if (ProxyCredential != null) + WebSession.NoProxy = true; + } + else + { + if (Proxy is not null) { - webProxy.Credentials = ProxyCredential.GetNetworkCredential(); - } - else if (ProxyUseDefaultCredentials) - { - // If both ProxyCredential and ProxyUseDefaultCredentials are passed, - // UseDefaultCredentials will overwrite the supplied credentials. - webProxy.UseDefaultCredentials = true; + 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; + } } + } - WebSession.Proxy = webProxy; + if (MyInvocation.BoundParameters.ContainsKey(nameof(SslProtocol))) + { + WebSession.SslProtocol = SslProtocol; } if (MaximumRedirection > -1) @@ -660,18 +1011,22 @@ internal virtual void PrepareSession() WebSession.MaximumRedirection = MaximumRedirection; } - // store the other supplied headers - if (Headers != null) + WebSession.UnixSocket = UnixSocket; + + WebSession.SkipCertificateCheck = SkipCertificateCheck.IsPresent; + + // Store the other supplied headers + if (Headers is not null) { foreach (string key in Headers.Keys) { - var value = Headers[key]; + 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) + // Add the header value (or overwrite it if already present). WebSession.Headers[key] = value.ToString(); } } @@ -681,407 +1036,39 @@ internal virtual void PrepareSession() { WebSession.MaximumRetryCount = MaximumRetryCount; - // only set retry interval if retry count is set. + // Only set retry interval if retry count is set. WebSession.RetryIntervalInSeconds = RetryIntervalSec; } - } - - #endregion Virtual Methods - - #region Helper Properties - - internal string QualifiedOutFile - { - get { return (QualifyFilePath(OutFile)); } - } - - internal bool ShouldSaveToOutFile - { - get { return (!string.IsNullOrEmpty(OutFile)); } - } - - internal bool ShouldWriteToPipeline - { - get { return (!ShouldSaveToOutFile || PassThru); } - } - - internal bool ShouldCheckHttpStatus - { - get { return !SkipHttpErrorCheck; } - } - - /// - /// Determines whether writing to a file should Resume and append rather than overwrite. - /// - internal bool ShouldResume - { - get { return (Resume.IsPresent && _resumeSuccess); } - } - - #endregion Helper Properties - - #region Helper Methods - 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) - IDictionary bodyAsDictionary; - LanguagePrimitives.TryConvertTo(Body, out bodyAsDictionary); - if ((bodyAsDictionary != null) - && ((IsStandardMethodSet() && (Method == WebRequestMethod.Default || Method == WebRequestMethod.Get)) - || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "GET"))) - { - UriBuilder uriBuilder = new(uri); - if (uriBuilder.Query != 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) - { - if (uri == null) { throw new ArgumentNullException(nameof(uri)); } - - if (!uri.IsAbsoluteUri) - { - uri = new Uri("http://" + uri.OriginalString); - } - - return (uri); - } - - private string QualifyFilePath(string path) - { - string resolvedFilePath = PathUtils.ResolveFilePath(filePath: path, command: this, isLiteralPath: true); - return resolvedFilePath; - } - - private static string FormatDictionary(IDictionary content) - { - if (content == null) - throw new ArgumentNullException(nameof(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 = string.Empty; - if (value != null) - { - encodedValue = WebUtility.UrlEncode(value.ToString()); - } - - bodyBuilder.AppendFormat("{0}={1}", encodedKey, encodedValue); - } - - return bodyBuilder.ToString(); - } - - private ErrorRecord GetValidationError(string msg, string errorId) - { - var ex = new ValidationMetadataException(msg); - var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return (error); - } - - private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) - { - msg = string.Format(CultureInfo.InvariantCulture, msg, args); - var ex = new ValidationMetadataException(msg); - var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); - return (error); - } - - private bool IsStandardMethodSet() - { - return (ParameterSetName == "StandardMethod" || ParameterSetName == "StandardMethodNoProxy"); - } - - private bool IsCustomMethodSet() - { - return (ParameterSetName == "CustomMethod" || ParameterSetName == "CustomMethodNoProxy"); - } - - private string GetBasicAuthorizationHeader() - { - var password = new NetworkCredential(null, Credential.Password).Password; - string unencoded = string.Format("{0}:{1}", Credential.UserName, password); - byte[] bytes = Encoding.UTF8.GetBytes(unencoded); - return string.Format("Basic {0}", Convert.ToBase64String(bytes)); - } - - private string GetBearerAuthorizationHeader() - { - return string.Format("Bearer {0}", 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.Format("Unrecognized Authentication value: {0}", Authentication)); - } - } - - #endregion Helper Methods - } - - // TODO: Merge Partials - - /// - /// 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) - { - Response = response; - } - - /// - /// HTTP error response. - /// - public HttpResponseMessage Response { get; } - } - - /// - /// Base class for Invoke-RestMethod and Invoke-WebRequest commands. - /// - public abstract partial class WebRequestPSCmdlet : PSCmdlet - { - /// - /// 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 SkipHeaderValidation property. - /// - /// - /// This property adds headers to the request's header collection without validation. - /// - [Parameter] - public virtual SwitchParameter SkipHeaderValidation { get; set; } - - #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 - - /// - /// Cancellation token source. - /// - internal CancellationTokenSource _cancelToken = null; - - /// - /// Parse Rel Links. - /// - internal bool _parseRelLink = false; - - /// - /// Automatically follow Rel Links. - /// - internal bool _followRelLink = false; - - /// - /// Automatically follow Rel Links. - /// - internal Dictionary _relationLink = null; - - /// - /// Maximum number of Rel Links to follow. - /// - internal int _maximumFollowRelLink = Int32.MaxValue; - /// - /// The remote endpoint returned a 206 status code indicating successful resume. - /// - private bool _resumeSuccess = false; - - /// - /// The current size of the local file being resumed. - /// - private long _resumeFileSize = 0; - - private HttpMethod GetHttpMethod(WebRequestMethod method) - { - switch (Method) - { - case WebRequestMethod.Default: - case WebRequestMethod.Get: - return HttpMethod.Get; - case WebRequestMethod.Head: - return HttpMethod.Head; - case WebRequestMethod.Post: - return HttpMethod.Post; - case WebRequestMethod.Put: - return HttpMethod.Put; - case WebRequestMethod.Delete: - return HttpMethod.Delete; - case WebRequestMethod.Trace: - return HttpMethod.Trace; - case WebRequestMethod.Options: - return HttpMethod.Options; - default: - // Merge and Patch - return new HttpMethod(Method.ToString().ToUpperInvariant()); - } + WebSession.ConnectionTimeout = ConvertTimeoutSecondsToTimeSpan(ConnectionTimeoutSeconds); } - #region Virtual Methods - - // NOTE: Only pass true for handleRedirect if the original request has an authorization header - // and PreserveAuthorizationOnRedirect is NOT set. internal virtual HttpClient GetHttpClient(bool handleRedirect) { - // By default the HttpClientHandler will automatically decompress GZip and Deflate content - HttpClientHandler handler = new(); - handler.CookieContainer = WebSession.Cookies; - - // set the credentials used by this request - if (WebSession.UseDefaultCredentials) - { - // the UseDefaultCredentials flag overrides other supplied credentials - handler.UseDefaultCredentials = true; - } - else if (WebSession.Credentials != null) - { - handler.Credentials = WebSession.Credentials; - } - - if (NoProxy) - { - handler.UseProxy = false; - } - else if (WebSession.Proxy != null) - { - handler.Proxy = WebSession.Proxy; - } - - if (WebSession.Certificates != null) - { - handler.ClientCertificates.AddRange(WebSession.Certificates); - } - - if (SkipCertificateCheck) - { - handler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; - handler.ClientCertificateOptions = ClientCertificateOption.Manual; - } - - // This indicates GetResponse will handle redirects. - if (handleRedirect) - { - handler.AllowAutoRedirect = false; - } - else if (WebSession.MaximumRedirection > -1) - { - if (WebSession.MaximumRedirection == 0) - { - handler.AllowAutoRedirect = false; - } - else - { - handler.MaxAutomaticRedirections = WebSession.MaximumRedirection; - } - } - - handler.SslProtocols = (SslProtocols)SslProtocol; - - HttpClient httpClient = new(handler); + HttpClient client = WebSession.GetHttpClient(handleRedirect, out bool clientWasReset); - // check timeout setting (in seconds instead of milliseconds as in HttpWebRequest) - if (TimeoutSec == 0) - { - // A zero timeout means infinite - httpClient.Timeout = TimeSpan.FromMilliseconds(Timeout.Infinite); - } - else if (TimeoutSec > 0) + if (clientWasReset) { - httpClient.Timeout = new TimeSpan(0, 0, TimeoutSec); + WriteVerbose(WebCmdletStrings.WebSessionConnectionRecreated); } - return httpClient; + return client; } internal virtual HttpRequestMessage GetRequest(Uri uri) { Uri requestUri = PrepareUri(uri); - HttpMethod httpMethod = null; - - switch (ParameterSetName) - { - case "StandardMethodNoProxy": - goto case "StandardMethod"; - case "StandardMethod": - // set the method if the parameter was provided - httpMethod = GetHttpMethod(Method); - break; - case "CustomMethodNoProxy": - goto case "CustomMethod"; - case "CustomMethod": - if (!string.IsNullOrEmpty(CustomMethod)) - { - // set the method if the parameter was provided - httpMethod = new HttpMethod(CustomMethod.ToUpperInvariant()); - } + HttpMethod httpMethod = string.IsNullOrEmpty(CustomMethod) ? GetHttpMethod(Method) : new HttpMethod(CustomMethod); - break; - } + // Create the base WebRequest object + HttpRequestMessage request = new(httpMethod, requestUri); - // create the base WebRequest object - var request = new HttpRequestMessage(httpMethod, requestUri); + if (HttpVersion is not null) + { + request.Version = HttpVersion; + } - // pull in session data + // Pull in session data if (WebSession.Headers.Count > 0) { WebSession.ContentHeaders.Clear(); @@ -1112,8 +1099,7 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } // Set 'User-Agent' if WebSession.Headers doesn't already contain it - string userAgent = null; - if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out userAgent)) + if (WebSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out string userAgent)) { WebSession.UserAgent = userAgent; } @@ -1136,10 +1122,10 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } // Set 'Transfer-Encoding' - if (TransferEncoding != null) + if (TransferEncoding is not null) { request.Headers.TransferEncodingChunked = true; - var headerValue = new TransferCodingHeaderValue(TransferEncoding); + TransferCodingHeaderValue headerValue = new(TransferEncoding); if (!request.Headers.TransferEncoding.Contains(headerValue)) { request.Headers.TransferEncoding.Add(headerValue); @@ -1150,7 +1136,8 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) // If not, create a Range to request the entire file. if (Resume.IsPresent) { - var fileInfo = new FileInfo(QualifiedOutFile); + FileInfo fileInfo = new(QualifiedOutFile); + if (fileInfo.Exists) { request.Headers.Range = new RangeHeaderValue(fileInfo.Length, null); @@ -1162,37 +1149,31 @@ internal virtual HttpRequestMessage GetRequest(Uri uri) } } - return (request); + return request; } internal virtual void FillRequestStream(HttpRequestMessage request) { - if (request == null) { throw new ArgumentNullException(nameof(request)); } + ArgumentNullException.ThrowIfNull(request); - // set the content type - if (ContentType != null) + // Set the request content type + if (ContentType is not null) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; - // request } - // ContentType == null - else if (Method == WebRequestMethod.Post || (IsCustomMethodSet() && CustomMethod.ToUpperInvariant() == "POST")) + else if (request.Method == HttpMethod.Post) { // Win8:545310 Invoke-WebRequest does not properly set MIME type for POST - string contentType = null; - WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out contentType); + WebSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out string contentType); if (string.IsNullOrEmpty(contentType)) { WebSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = "application/x-www-form-urlencoded"; } } - if (Form != null) + if (Form is not null) { - // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first - WebSession.ContentHeaders.Clear(); - - var formData = new MultipartFormDataContent(); + MultipartFormDataContent formData = new(); foreach (DictionaryEntry formEntry in Form) { // AddMultipartContent will handle PSObject unwrapping, Object type determination and enumerateing top level IEnumerables. @@ -1201,73 +1182,67 @@ internal virtual void FillRequestStream(HttpRequestMessage request) SetRequestContent(request, formData); } - // coerce body into a usable form - else if (Body != null) + else if (Body is not null) { - object content = Body; - - // make sure we're using the base object of the body, not the PSObject wrapper - PSObject psBody = Body as PSObject; - if (psBody != null) - { - content = psBody.BaseObject; - } + // 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; - if (content is FormObject form) - { - SetRequestContent(request, form.Fields); - } - else if (content is IDictionary dictionary && request.Method != HttpMethod.Get) - { - SetRequestContent(request, dictionary); - } - else if (content is XmlNode xmlNode) - { - SetRequestContent(request, xmlNode); - } - else if (content is Stream stream) - { - SetRequestContent(request, stream); - } - else if (content is byte[] bytes) - { - SetRequestContent(request, bytes); - } - else if (content is MultipartFormDataContent multipartFormDataContent) - { - WebSession.ContentHeaders.Clear(); - SetRequestContent(request, multipartFormDataContent); - } - else + switch (content) { - SetRequestContent( - request, - (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); + 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 != null) // copy InFile data + else if (InFile is not null) { + // Copy InFile data try { - // open the input file + // 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); + string msg = string.Format(CultureInfo.InvariantCulture, WebCmdletStrings.AccessDenied, _originalFilePath); + throw new UnauthorizedAccessException(msg); } } - // Add the content headers - if (request.Content == null) + // 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 (var entry in WebSession.ContentHeaders) + foreach (KeyValuePair entry in WebSession.ContentHeaders) { if (!string.IsNullOrWhiteSpace(entry.Value)) { @@ -1283,7 +1258,7 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } catch (FormatException ex) { - var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); + ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } @@ -1292,106 +1267,97 @@ internal virtual void FillRequestStream(HttpRequestMessage request) } } - // Returns true if the status code is one of the supported redirection codes. - private static bool IsRedirectCode(HttpStatusCode code) - { - int intCode = (int)code; - return - ( - (intCode >= 300 && intCode < 304) - || - intCode == 307 - ); - } - - // Returns true if the status code is a redirection code and the action requires switching from POST to GET on redirection. - // NOTE: Some of these status codes map to the same underlying value but spelling them out for completeness. - private static bool IsRedirectToGet(HttpStatusCode code) - { - return - ( - code == HttpStatusCode.Found - || - code == HttpStatusCode.Moved - || - code == HttpStatusCode.Redirect - || - code == HttpStatusCode.RedirectMethod - || - code == HttpStatusCode.SeeOther - || - code == HttpStatusCode.Ambiguous - || - code == HttpStatusCode.MultipleChoices - ); - } - - private bool ShouldRetry(HttpStatusCode code) - { - int intCode = (int)code; - - if (((intCode == 304) || (intCode >= 400 && intCode <= 599)) && WebSession.MaximumRetryCount > 0) - { - return true; - } - - return false; - } - - internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool keepAuthorization) + internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestMessage request, bool handleRedirect) { - if (client == null) { throw new ArgumentNullException(nameof(client)); } - - if (request == null) { throw new ArgumentNullException(nameof(request)); } + ArgumentNullException.ThrowIfNull(client); + ArgumentNullException.ThrowIfNull(request); // Add 1 to account for the first request. int totalRequests = WebSession.MaximumRetryCount + 1; - HttpRequestMessage req = request; + HttpRequestMessage currentRequest = request; HttpResponseMessage response = null; do { // Track the current URI being used by various requests and re-requests. - var currentUri = req.RequestUri; + Uri currentUri = currentRequest.RequestUri; _cancelToken = new CancellationTokenSource(); - response = client.SendAsync(req, HttpCompletionOption.ResponseHeadersRead, _cancelToken.Token).GetAwaiter().GetResult(); + 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 (keepAuthorization && IsRedirectCode(response.StatusCode) && response.Headers.Location != null) + } + 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 (WebSession.MaximumRedirection > 0) + // If explicit count was provided, reduce it for this redirection. + if (_maximumRedirection > 0) { - WebSession.MaximumRedirection--; + _maximumRedirection--; } - // For selected redirects that used POST, GET must be used with the - // redirected Location. - // Since GET is the default; POST only occurs when -Method POST is used. - if (Method == WebRequestMethod.Post && IsRedirectToGet(response.StatusCode)) + + // For selected redirects, GET must be used with the redirected Location. + if (RequestRequiresForceGet(response.StatusCode, currentRequest.Method) && !PreserveHttpMethodOnRedirect) { - // See https://msdn.microsoft.com/library/system.net.httpstatuscode(v=vs.110).aspx Method = WebRequestMethod.Get; + CustomMethod = string.Empty; } currentUri = new Uri(request.RequestUri, response.Headers.Location); + // Continue to handle redirection - using (client = GetHttpClient(handleRedirect: true)) - using (HttpRequestMessage redirectRequest = GetRequest(currentUri)) - { - response = GetResponse(client, redirectRequest, keepAuthorization); - } + 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)) + if (Resume.IsPresent + && response.StatusCode == HttpStatusCode.RequestedRangeNotSatisfiable + && (response.Content.Headers.ContentRange.HasLength + && response.Content.Headers.ContentRange.Length != _resumeFileSize)) { _cancelToken.Cancel(); @@ -1404,45 +1370,53 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM using (HttpRequestMessage requestWithoutRange = GetRequest(currentUri)) { FillRequestStream(requestWithoutRange); - long requestContentLength = 0; - if (requestWithoutRange.Content != null) - { - requestContentLength = requestWithoutRange.Content.Headers.ContentLength.Value; - } - string reqVerboseMsg = string.Format( - CultureInfo.CurrentCulture, - WebCmdletStrings.WebMethodInvocationVerboseMsg, - requestWithoutRange.Method, - requestWithoutRange.RequestUri, - requestContentLength); - WriteVerbose(reqVerboseMsg); - - return GetResponse(client, requestWithoutRange, keepAuthorization); + response.Dispose(); + response = GetResponse(client, requestWithoutRange, handleRedirect); } } _resumeSuccess = response.StatusCode == HttpStatusCode.PartialContent; - // When MaximumRetryCount is not specified, the totalRequests == 1. - if (totalRequests > 1 && ShouldRetry(response.StatusCode)) - { + // 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, - RetryIntervalSec, + retryIntervalInSeconds, response.StatusCode); WriteVerbose(retryMessage); _cancelToken = new CancellationTokenSource(); - Task.Delay(WebSession.RetryIntervalInSeconds * 1000, _cancelToken.Token).GetAwaiter().GetResult(); + Task.Delay(retryIntervalInSeconds * 1000, _cancelToken.Token).GetAwaiter().GetResult(); _cancelToken.Cancel(); _cancelToken = null; - req.Dispose(); - req = GetRequest(currentUri); - FillRequestStream(req); + currentRequest.Dispose(); + currentRequest = GetRequest(currentUri); + FillRequestStream(currentRequest); } totalRequests--; @@ -1454,219 +1428,329 @@ internal virtual HttpResponseMessage GetResponse(HttpClient client, HttpRequestM internal virtual void UpdateSession(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); } - #endregion Virtual Methods - #region Overrides + #region Helper Methods +#nullable enable + internal static TimeSpan ConvertTimeoutSecondsToTimeSpan(int timeout) => timeout > 0 ? TimeSpan.FromSeconds(timeout) : Timeout.InfiniteTimeSpan; - /// - /// The main execution method for cmdlets derived from WebRequestPSCmdlet. - /// - protected override void ProcessRecord() + private void WriteWebRequestVerboseInfo(HttpRequestMessage request) { try { - // Set cmdlet context for write progress - ValidateParameters(); - PrepareSession(); + // Typical Basic Example: 'WebRequest: v1.1 POST https://httpstat.us/200 with query length 6' + StringBuilder verboseBuilder = new(128); - // if the request contains an authorization header and PreserveAuthorizationOnRedirect is not set, - // it needs to be stripped on the first redirect. - bool keepAuthorization = WebSession != null - && - WebSession.Headers != null - && - PreserveAuthorizationOnRedirect.IsPresent - && - WebSession.Headers.ContainsKey(HttpKnownHeaderNames.Authorization); - - using (HttpClient client = GetHttpClient(keepAuthorization)) + // "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 }) { - int followedRelLink = 0; - Uri uri = Uri; - do + if (headerSet is null) { - if (followedRelLink > 0) - { - string linkVerboseMsg = string.Format(CultureInfo.CurrentCulture, - WebCmdletStrings.FollowingRelLinkVerboseMsg, - uri.AbsoluteUri); - WriteVerbose(linkVerboseMsg); - } + continue; + } - using (HttpRequestMessage request = GetRequest(uri)) - { - FillRequestStream(request); - try - { - long requestContentLength = 0; - if (request.Content != null) - requestContentLength = request.Content.Headers.ContentLength.Value; - - string reqVerboseMsg = string.Format(CultureInfo.CurrentCulture, - WebCmdletStrings.WebMethodInvocationVerboseMsg, - request.Method, - requestContentLength); - WriteVerbose(reqVerboseMsg); - - HttpResponseMessage response = GetResponse(client, request, keepAuthorization); - - string contentType = ContentHelper.GetContentType(response); - string respVerboseMsg = string.Format(CultureInfo.CurrentCulture, - WebCmdletStrings.WebResponseVerboseMsg, - response.Content.Headers.ContentLength, - contentType); - WriteVerbose(respVerboseMsg); - - 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; - } + debugBuilder.AppendLine(headerSet.ToString()); + } - 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; - StreamReader reader = null; - try - { - reader = new StreamReader(StreamHelper.GetResponseStream(response)); - // remove HTML tags making it easier to read - detailMsg = System.Text.RegularExpressions.Regex.Replace(reader.ReadToEnd(), "<[^>]*>", string.Empty); - } - catch (Exception) - { - // catch all - } - finally - { - if (reader != null) - { - reader.Dispose(); - } - } - - if (!string.IsNullOrEmpty(detailMsg)) - { - er.ErrorDetails = new ErrorDetails(detailMsg); - } + 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(); + } - ThrowTerminatingError(er); - } + 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}"); + } + } - if (_parseRelLink || _followRelLink) - { - ParseLinkHeader(response, uri); - } + 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()}"); - ProcessResponse(response); - UpdateSession(response); + string? responseContentType = ContentHelper.GetContentType(response); + if (responseContentType is not null) + { + verboseBuilder.Append($" with {responseContentType} payload"); + } - // 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 (WebSession.MaximumRedirection == 0) // Indicate "HttpClientHandler.AllowAutoRedirect == false" - { - if (response.StatusCode == HttpStatusCode.Found || - response.StatusCode == HttpStatusCode.Moved || - response.StatusCode == HttpStatusCode.MovedPermanently) - { - ErrorRecord er = new(new InvalidOperationException(), "MaximumRedirectExceeded", ErrorCategory.InvalidOperation, request); - er.ErrorDetails = new ErrorDetails(WebCmdletStrings.MaximumRedirectionCountExceeded); - WriteError(er); - } - } - } - catch (HttpRequestException ex) - { - ErrorRecord er = new(ex, "WebCmdletWebResponseException", ErrorCategory.InvalidOperation, request); - if (ex.InnerException != null) - { - er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); - } + long? responseContentLength = response.Content?.Headers?.ContentLength; + if (responseContentLength is not null) + { + verboseBuilder.Append($" with body size {ContentHelper.GetFriendlyContentLength(responseContentLength)}"); + } - ThrowTerminatingError(er); - } + 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}"); + } + } - if (_followRelLink) - { - if (!_relationLink.ContainsKey("next")) - { - return; - } + 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; + } - uri = new Uri(_relationLink["next"]); - followedRelLink++; - } - } + 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}]"); } - while (_followRelLink && (followedRelLink < _maximumFollowRelLink)); } + + WriteDebug(debugBuilder.ToString().Trim()); } - catch (CryptographicException ex) + catch (Exception ex) { - ErrorRecord er = new(ex, "WebCmdletCertificateException", ErrorCategory.SecurityError, null); - ThrowTerminatingError(er); + // 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}"); } - catch (NotSupportedException ex) + } + + 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")) { - ErrorRecord er = new(ex, "WebCmdletIEDomNotSupportedException", ErrorCategory.NotImplemented, null); - ThrowTerminatingError(er); + 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; } - /// - /// Implementing ^C, after start the BeginGetResponse. - /// - protected override void StopProcessing() + 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) { - if (_cancelToken != null) + ArgumentNullException.ThrowIfNull(content); + + StringBuilder bodyBuilder = new(); + foreach (string key in content.Keys) { - _cancelToken.Cancel(); + 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(); } - #endregion Overrides + private ErrorRecord GetValidationError(string msg, string errorId) + { + ValidationMetadataException ex = new(msg); + return new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); + } - #region Helper Methods + 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. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// 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 long SetRequestContent(HttpRequestMessage request, byte[] content) + internal void SetRequestContent(HttpRequestMessage request, byte[] content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (content == null) - return 0; - - var byteArrayContent = new ByteArrayContent(content); - request.Content = byteArrayContent; + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); - return byteArrayContent.Headers.ContentLength.Value; + request.Content = new ByteArrayContent(content); } /// @@ -1674,85 +1758,63 @@ internal long SetRequestContent(HttpRequestMessage request, byte[] content) /// /// The WebRequest who's content is to be set. /// A String object containing the content data. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// 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 long SetRequestContent(HttpRequestMessage request, string content) + internal void SetRequestContent(HttpRequestMessage request, string content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - - if (content == null) - return 0; + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); Encoding encoding = null; - if (ContentType != 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 { - var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(ContentType); + MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(contentType); if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet)) { encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet); } } - catch (FormatException ex) + catch (Exception ex) when (ex is FormatException || ex is ArgumentException) { if (!SkipHeaderValidation) { - var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); - ThrowTerminatingError(er); - } - } - catch (ArgumentException ex) - { - if (!SkipHeaderValidation) - { - var outerEx = new ValidationMetadataException(WebCmdletStrings.ContentTypeException, ex); - ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, ContentType); + ValidationMetadataException outerEx = new(WebCmdletStrings.ContentTypeException, ex); + ErrorRecord er = new(outerEx, "WebCmdletContentTypeException", ErrorCategory.InvalidArgument, contentType); ThrowTerminatingError(er); } } } byte[] bytes = StreamHelper.EncodeToBytes(content, encoding); - var byteArrayContent = new ByteArrayContent(bytes); - request.Content = byteArrayContent; - - return byteArrayContent.Headers.ContentLength.Value; + request.Content = new ByteArrayContent(bytes); } - internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) + internal void SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - - if (xmlNode == null) - return 0; + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(xmlNode); byte[] bytes = null; XmlDocument doc = xmlNode as XmlDocument; - if (doc?.FirstChild is XmlDeclaration) + if (doc?.FirstChild is XmlDeclaration decl && !string.IsNullOrEmpty(decl.Encoding)) { - XmlDeclaration decl = doc.FirstChild as XmlDeclaration; Encoding encoding = Encoding.GetEncoding(decl.Encoding); bytes = StreamHelper.EncodeToBytes(doc.OuterXml, encoding); } else { - bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml); + bytes = StreamHelper.EncodeToBytes(xmlNode.OuterXml, encoding: null); } - var byteArrayContent = new ByteArrayContent(bytes); - request.Content = byteArrayContent; - - return byteArrayContent.Headers.ContentLength.Value; + request.Content = new ByteArrayContent(bytes); } /// @@ -1760,65 +1822,51 @@ internal long SetRequestContent(HttpRequestMessage request, XmlNode xmlNode) /// /// The WebRequest who's content is to be set. /// A Stream object containing the content data. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// 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 long SetRequestContent(HttpRequestMessage request, Stream contentStream) + internal void SetRequestContent(HttpRequestMessage request, Stream contentStream) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (contentStream == null) - throw new ArgumentNullException(nameof(contentStream)); - - var streamContent = new StreamContent(contentStream); - request.Content = streamContent; + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(contentStream); - return streamContent.Headers.ContentLength.Value; + request.Content = new StreamContent(contentStream); } /// - /// Sets the ContentLength property of the request and writes the specified content to the request's RequestStream. + /// 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. - /// The number of bytes written to the requests RequestStream (and the new value of the request's ContentLength property. /// - /// Because this function sets the request's ContentLength property and writes content data into the requests's stream, + /// 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 long SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) + internal void SetRequestContent(HttpRequestMessage request, MultipartFormDataContent multipartContent) { - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(multipartContent); - if (multipartContent == null) - { - throw new ArgumentNullException(nameof(multipartContent)); - } + // Content headers will be set by MultipartFormDataContent which will throw unless we clear them first + WebSession.ContentHeaders.Clear(); request.Content = multipartContent; - - return multipartContent.Headers.ContentLength.Value; } - internal long SetRequestContent(HttpRequestMessage request, IDictionary content) + internal void SetRequestContent(HttpRequestMessage request, IDictionary content) { - if (request == null) - throw new ArgumentNullException(nameof(request)); - if (content == null) - throw new ArgumentNullException(nameof(content)); + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(content); string body = FormatDictionary(content); - return (SetRequestContent(request, body)); + SetRequestContent(request, body); } - internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUri) + internal void ParseLinkHeader(HttpResponseMessage response) { - if (_relationLink == null) + 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); @@ -1828,17 +1876,16 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr _relationLink.Clear(); } - // we only support the URL in angle brackets and `rel`, other attributes are ignored + // 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=(\"?)(?.*?)\\1[^\\w -.]?"; - IEnumerable links; - if (response.Headers.TryGetValues("Link", out links)) + const string Pattern = "<(?.*?)>;\\s*rel=(?\")?(?(?(quoted).*?|[^,;]*))(?(quoted)\")"; + if (response.Headers.TryGetValues("Link", out IEnumerable links)) { foreach (string linkHeader in links) { - foreach (string link in linkHeader.Split(',')) + MatchCollection matchCollection = Regex.Matches(linkHeader, Pattern); + foreach (Match match in matchCollection) { - Match match = Regex.Match(link, pattern); if (match.Success) { string url = match.Groups["url"].Value; @@ -1859,14 +1906,11 @@ internal void ParseLinkHeader(HttpResponseMessage response, System.Uri requestUr /// /// The Field Name to use. /// The Field Value to use. - /// The > to update. + /// The to update. /// If true, collection types in will be enumerated. If false, collections will be treated as single value. - private void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) + private static void AddMultipartContent(object fieldName, object fieldValue, MultipartFormDataContent formData, bool enumerate) { - if (formData == null) - { - throw new ArgumentNullException("formDate"); - } + 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. @@ -1902,9 +1946,9 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF // Treat the value as a collection and enumerate it if enumeration is true if (enumerate && fieldValue is IEnumerable items) { - foreach (var item in items) + foreach (object item in items) { - // Recruse, but do not enumerate the next level. IEnumerables will be treated as single values. + // Recurse, but do not enumerate the next level. IEnumerables will be treated as single values. AddMultipartContent(fieldName: fieldName, fieldValue: item, formData: formData, enumerate: false); } } @@ -1917,11 +1961,11 @@ private void AddMultipartContent(object fieldName, object fieldValue, MultipartF /// The Field Value to use for the private static StringContent GetMultipartStringContent(object fieldName, object fieldValue) { - var contentDisposition = new ContentDispositionHeaderValue("form-data"); - // .NET does not enclose field names in quotes, however, modern browsers and curl do. - contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; + ContentDispositionHeaderValue contentDisposition = new("form-data"); + contentDisposition.Name = LanguagePrimitives.ConvertTo(fieldName); - var result = new StringContent(LanguagePrimitives.ConvertTo(fieldValue)); + // 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; @@ -1934,11 +1978,10 @@ private static StringContent GetMultipartStringContent(object fieldName, object /// The to use for the private static StreamContent GetMultipartStreamContent(object fieldName, Stream stream) { - var contentDisposition = new ContentDispositionHeaderValue("form-data"); - // .NET does not enclose field names in quotes, however, modern browsers and curl do. - contentDisposition.Name = "\"" + LanguagePrimitives.ConvertTo(fieldName) + "\""; + ContentDispositionHeaderValue contentDisposition = new("form-data"); + contentDisposition.Name = LanguagePrimitives.ConvertTo(fieldName); - var result = new StreamContent(stream); + StreamContent result = new(stream); result.Headers.ContentDisposition = contentDisposition; result.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); @@ -1952,12 +1995,131 @@ private static StreamContent GetMultipartStreamContent(object fieldName, Stream /// The file to use for the private static StreamContent GetMultipartFileContent(object fieldName, FileInfo file) { - var result = GetMultipartStreamContent(fieldName: fieldName, stream: new FileStream(file.FullName, FileMode.Open)); - // .NET does not enclose field names in quotes, however, modern browsers and curl do. - result.Headers.ContentDisposition.FileName = "\"" + file.Name + "\""; + 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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs index 98e7c397e45..ace84f480f9 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/Common/WebResponseObject.Common.cs @@ -1,60 +1,41 @@ // 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 partial class WebResponseObject + public class WebResponseObject { #region Properties /// - /// Gets or protected sets the response body content. - /// - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public byte[] Content { get; protected set; } - - /// - /// Gets the response status code. + /// Gets or sets the BaseResponse property. /// - public int StatusCode - { - get { return (WebResponseHelper.GetStatusCode(BaseResponse)); } - } + public HttpResponseMessage BaseResponse { get; set; } /// - /// Gets the response status description. + /// Gets or protected sets the response body content. /// - public string StatusDescription - { - get { return (WebResponseHelper.GetStatusDescription(BaseResponse)); } - } + public byte[]? Content { get; protected set; } - private MemoryStream _rawContentStream; /// - /// Gets the response body content as a . + /// Gets the Headers property. /// - public MemoryStream RawContentStream - { - get { return (_rawContentStream); } - } + public Dictionary> Headers => _headers ??= WebResponseHelper.GetHeadersDictionary(BaseResponse); - /// - /// Gets the length (in bytes) of . - /// - public long RawContentLength - { - get { return (RawContentStream == null ? -1 : RawContentStream.Length); } - } + private Dictionary>? _headers; /// /// Gets or protected sets the full response content. @@ -62,104 +43,71 @@ public long RawContentLength /// /// Full response content, including the HTTP status line, headers, and body. /// - public string RawContent { get; protected set; } - - #endregion Properties - - #region Methods + public string? RawContent { get; protected set; } /// - /// Reads the response content from the web response. + /// Gets the length (in bytes) of . /// - private void InitializeContent() - { - this.Content = this.RawContentStream.ToArray(); - } - - private static bool IsPrintable(char c) - { - return (char.IsLetterOrDigit(c) || char.IsPunctuation(c) || char.IsSeparator(c) || char.IsSymbol(c) || char.IsWhiteSpace(c)); - } + public long RawContentLength => RawContentStream is null ? -1 : RawContentStream.Length; /// - /// Returns the string representation of this web response. + /// Gets or protected sets the response body content as a . /// - /// The string representation of this web response. - public sealed override string ToString() - { - char[] stringContent = System.Text.Encoding.ASCII.GetChars(Content); - for (int counter = 0; counter < stringContent.Length; counter++) - { - if (!IsPrintable(stringContent[counter])) - { - stringContent[counter] = '.'; - } - } - - return new string(stringContent); - } + public MemoryStream RawContentStream { get; protected set; } - #endregion Methods - } - - // TODO: Merge Partials + /// + /// Gets the RelationLink property. + /// + public Dictionary? RelationLink { get; internal set; } - /// - /// WebResponseObject. - /// - public partial class WebResponseObject - { - #region Properties + /// + /// Gets the response status code. + /// + public int StatusCode => WebResponseHelper.GetStatusCode(BaseResponse); /// - /// Gets or sets the BaseResponse property. + /// Gets the response status description. /// - public HttpResponseMessage BaseResponse { get; set; } + public string StatusDescription => WebResponseHelper.GetStatusDescription(BaseResponse); /// - /// Gets the Headers property. + /// Gets or sets the output file path. /// - public Dictionary> Headers - { - get - { - if (_headers == null) - { - _headers = WebResponseHelper.GetHeadersDictionary(BaseResponse); - } + public string? OutFile { get; internal set; } - return _headers; - } - } + #endregion Properties - private Dictionary> _headers = null; + #region Protected Fields /// - /// Gets the RelationLink property. + /// Time permitted between reads or Timeout.InfiniteTimeSpan for no timeout. /// - public Dictionary RelationLink { get; internal set; } + protected TimeSpan perReadTimeout; - #endregion + #endregion Protected Fields #region Constructors /// /// Initializes a new instance of the class. /// - /// - public WebResponseObject(HttpResponseMessage response) - : this(response, null) - { } + /// 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 . /// - /// - /// - public WebResponseObject(HttpResponseMessage response, Stream contentStream) + /// 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) { - SetResponse(response, contentStream); + this.perReadTimeout = perReadTimeout; + SetResponse(response, contentStream, cancellationToken); InitializeContent(); InitializeRawContent(response); } @@ -168,50 +116,86 @@ public WebResponseObject(HttpResponseMessage response, Stream contentStream) #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) + if (Content?.Length > 0) { - raw.Append(this.ToString()); + raw.Append(ToString()); } - this.RawContent = raw.ToString(); + RawContent = raw.ToString(); } - private void SetResponse(HttpResponseMessage response, Stream contentStream) + 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) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); BaseResponse = response; - MemoryStream ms = contentStream as MemoryStream; - if (ms != null) + if (contentStream is MemoryStream ms) { - _rawContentStream = ms; + RawContentStream = ms; } else { - Stream st = contentStream; - if (contentStream == null) - { - st = StreamHelper.GetResponseStream(response); - } + Stream st = contentStream ?? StreamHelper.GetResponseStream(response, cancellationToken); - long contentLength = response.Content.Headers.ContentLength.Value; + 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, null); + 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; } - // set the position of the content stream to the beginning - _rawContentStream.Position = 0; + + 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 + + #endregion Methods } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs index 0af97b061a9..82e1277e00c 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertFromJsonCommand.cs @@ -32,13 +32,13 @@ public class ConvertFromJsonCommand : Cmdlet /// /// Returned data structure is a Hashtable instead a CustomPSObject. /// - [Parameter()] + [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()] + [Parameter] [ValidateRange(ValidateRangeKind.Positive)] public int Depth { get; set; } = 1024; @@ -49,6 +49,12 @@ public class ConvertFromJsonCommand : Cmdlet [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 @@ -86,7 +92,7 @@ protected override void EndProcessing() catch (ArgumentException) { // The first input string does not represent a complete Json Syntax. - // Hence consider the the entire input as a single Json content. + // Hence consider the entire input as a single Json content. } if (successfullyConverted) @@ -113,7 +119,7 @@ protected override void EndProcessing() private bool ConvertFromJsonHelper(string input) { ErrorRecord error = null; - object result = JsonObject.ConvertFromJson(input, AsHashtable.IsPresent, Depth, out error); + object result = JsonObject.ConvertFromJson(input, AsHashtable.IsPresent, Depth, DateKind, out error); if (error != null) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs index d15303557eb..173d999b06d 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/ConvertToJsonCommand.cs @@ -16,7 +16,8 @@ namespace Microsoft.PowerShell.Commands /// 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)] - public class ConvertToJsonCommand : PSCmdlet + [OutputType(typeof(string))] + public class ConvertToJsonCommand : PSCmdlet, IDisposable { /// /// Gets or sets the InputObject property. @@ -27,15 +28,13 @@ public class ConvertToJsonCommand : PSCmdlet private int _depth = 2; - private const int maxDepthAllowed = 100; - private readonly CancellationTokenSource _cancellationSource = new(); /// /// Gets or sets the Depth property. /// [Parameter] - [ValidateRange(1, int.MaxValue)] + [ValidateRange(0, 100)] public int Depth { get { return _depth; } @@ -78,18 +77,25 @@ public int Depth public StringEscapeHandling EscapeHandling { get; set; } = StringEscapeHandling.Default; /// - /// Prerequisite checks. + /// 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. /// - protected override void BeginProcessing() + /// + /// Specified as true when Dispose() was called, false if this is called from the finalizer. + /// + protected virtual void Dispose(bool disposing) { - if (_depth > maxDepthAllowed) + if (disposing) { - string errorMessage = StringUtil.Format(WebCmdletStrings.ReachedMaximumDepthAllowed, maxDepthAllowed); - ThrowTerminatingError(new ErrorRecord( - new InvalidOperationException(errorMessage), - "ReachedMaximumDepthAllowed", - ErrorCategory.InvalidOperation, - null)); + _cancellationSource.Dispose(); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs index 80d07a54ddf..6571696e5bf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/HttpKnownHeaderNames.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.Generic; @@ -11,14 +13,22 @@ internal static class HttpKnownHeaderNames #region Known_HTTP_Header_Names // Known HTTP Header Names. - // List comes from corefx/System/Net/HttpKnownHeaderNames.cs + // 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"; @@ -29,6 +39,7 @@ internal static class HttpKnownHeaderNames 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"; @@ -45,6 +56,7 @@ internal static class HttpKnownHeaderNames 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"; @@ -53,6 +65,7 @@ internal static class HttpKnownHeaderNames 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"; @@ -64,45 +77,49 @@ internal static class HttpKnownHeaderNames 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 HashSet s_contentHeaderSet = null; + private static readonly HashSet s_contentHeaderSet; - internal static HashSet ContentHeaders + static HttpKnownHeaderNames() { - get - { - if (s_contentHeaderSet == null) - { - 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); - } + // Thread-safe initialization. + s_contentHeaderSet = new HashSet(StringComparer.OrdinalIgnoreCase); - return s_contentHeaderSet; - } + 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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs index dafcf3b4295..0bcafcf2964 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs @@ -1,10 +1,13 @@ // 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 { @@ -13,6 +16,7 @@ namespace Microsoft.PowerShell.Commands /// 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 @@ -22,7 +26,7 @@ public class InvokeWebRequestCommand : WebRequestPSCmdlet /// public InvokeWebRequestCommand() : base() { - this._parseRelLink = true; + _parseRelLink = true; } /// @@ -31,18 +35,27 @@ public InvokeWebRequestCommand() : base() /// internal override void ProcessResponse(HttpResponseMessage response) { - if (response == null) { throw new ArgumentNullException(nameof(response)); } + ArgumentNullException.ThrowIfNull(response); + TimeSpan perReadTimeout = ConvertTimeoutSecondsToTimeSpan(OperationTimeoutSeconds); + Stream responseStream = StreamHelper.GetResponseStream(response, _cancelToken.Token); + string outFilePath = WebResponseHelper.GetOutFilePath(response, _qualifiedOutFile); - Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) { - // creating a MemoryStream wrapper to response stream here to support IsStopping. - responseStream = new WebResponseContentMemoryStream(responseStream, StreamHelper.ChunkSize, this); - WebResponseObject ro = WebResponseObjectFactory.GetResponseObject(response, responseStream, this.Context); + // 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 + // 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; @@ -51,7 +64,11 @@ internal override void ProcessResponse(HttpResponseMessage response) if (ShouldSaveToOutFile) { - StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this, _cancelToken.Token); + 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); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs index 226a981f8a2..c8fed859771 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebProxy.cs @@ -1,69 +1,65 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Net; namespace Microsoft.PowerShell.Commands { - internal class WebProxy : IWebProxy + internal sealed class WebProxy : IWebProxy, IEquatable { - private ICredentials _credentials; + private ICredentials? _credentials; private readonly Uri _proxyAddress; internal WebProxy(Uri address) { - if (address == null) - { - throw new ArgumentNullException(nameof(address)); - } + ArgumentNullException.ThrowIfNull(address); _proxyAddress = address; } - public ICredentials Credentials + public override bool Equals(object? obj) => Equals(obj as WebProxy); + + public override int GetHashCode() => HashCode.Combine(_proxyAddress, _credentials, BypassProxyOnLocal); + + public bool Equals(WebProxy? other) { - get { return _credentials; } + if (other is null) + { + return false; + } - set { _credentials = value; } + // _proxyAddress cannot be null as it is set in the constructor + return other._credentials == _credentials + && _proxyAddress.Equals(other._proxyAddress) + && BypassProxyOnLocal == other.BypassProxyOnLocal; } - internal bool BypassProxyOnLocal + public ICredentials? Credentials { - get; set; + get => _credentials; + + set => _credentials = value; } + internal bool BypassProxyOnLocal { get; set; } + internal bool UseDefaultCredentials { - get - { - return _credentials == CredentialCache.DefaultCredentials; - } + get => _credentials == CredentialCache.DefaultCredentials; - set - { - _credentials = value ? CredentialCache.DefaultCredentials : null; - } + set => _credentials = value ? CredentialCache.DefaultCredentials : null; } public Uri GetProxy(Uri destination) { - if (destination == null) - { - throw new ArgumentNullException(nameof(destination)); - } + ArgumentNullException.ThrowIfNull(destination); - if (destination.IsLoopback) - { - return destination; - } - - return _proxyAddress; + return destination.IsLoopback ? destination : _proxyAddress; } - public bool IsBypassed(Uri host) - { - return host.IsLoopback; - } + public bool IsBypassed(Uri host) => host.IsLoopback; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs index dc2f734d6bd..377a7e56265 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseHelper.CoreClr.cs @@ -1,20 +1,19 @@ // 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) - { - string characterSet = response.Content.Headers.ContentType.CharSet; - return characterSet; - } + internal static string? GetCharacterSet(HttpResponseMessage response) => response.Content.Headers.ContentType?.CharSet; internal static Dictionary> GetHeadersDictionary(HttpResponseMessage response) { @@ -27,7 +26,7 @@ internal static Dictionary> GetHeadersDictionary(Htt // 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 != null) + if (response.Content is not null) { foreach (var entry in response.Content.Headers) { @@ -38,29 +37,24 @@ internal static Dictionary> GetHeadersDictionary(Htt return headers; } - internal static string GetProtocol(HttpResponseMessage response) + internal static string GetOutFilePath(HttpResponseMessage response, string qualifiedOutFile) { - string protocol = string.Format(CultureInfo.InvariantCulture, - "HTTP/{0}", response.Version); - return protocol; - } + // Get file name from last segment of Uri + string? lastUriSegment = System.Net.WebUtility.UrlDecode(response.RequestMessage?.RequestUri?.Segments[^1]); - internal static int GetStatusCode(HttpResponseMessage response) - { - int statusCode = (int)response.StatusCode; - return statusCode; + return Directory.Exists(qualifiedOutFile) ? Path.Join(qualifiedOutFile, lastUriSegment) : qualifiedOutFile; } - internal static string GetStatusDescription(HttpResponseMessage response) - { - string statusDescription = response.StatusCode.ToString(); - return statusDescription; - } + 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 = response.Content.Headers.ContentType?.MediaType; + string? contentType = ContentHelper.GetContentType(response); return ContentHelper.IsText(contentType); } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs deleted file mode 100644 index c4371515fe7..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/WebResponseObjectFactory.CoreClr.cs +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.IO; -using System.Management.Automation; -using System.Net.Http; - -namespace Microsoft.PowerShell.Commands -{ - internal static class WebResponseObjectFactory - { - internal static WebResponseObject GetResponseObject(HttpResponseMessage response, Stream responseStream, ExecutionContext executionContext) - { - WebResponseObject output; - if (WebResponseHelper.IsText(response)) - { - output = new BasicHtmlWebResponseObject(response, responseStream); - } - else - { - output = new WebResponseObject(response, responseStream); - } - - return (output); - } - } -} diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs index b8f7d252711..5ac4adfbb64 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObject.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections.Generic; namespace Microsoft.PowerShell.Commands @@ -11,22 +13,22 @@ namespace Microsoft.PowerShell.Commands public class FormObject { /// - /// Gets or private sets the Id property. + /// Gets the Id property. /// public string Id { get; } /// - /// Gets or private sets the Method property. + /// Gets the Method property. /// public string Method { get; } /// - /// Gets or private sets the Action property. + /// Gets the Action property. /// public string Action { get; } /// - /// Gets or private sets the Fields property. + /// Gets the Fields property. /// public Dictionary Fields { get; } @@ -46,8 +48,7 @@ public FormObject(string id, string method, string action) internal void AddField(string key, string value) { - string test; - if (key != null && !Fields.TryGetValue(key, out test)) + if (key is not null && !Fields.TryGetValue(key, out string? _)) { Fields[key] = value; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs index 9072e431cae..5f923558185 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/FormObjectCollection.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Collections.ObjectModel; @@ -16,11 +18,11 @@ public class FormObjectCollection : Collection /// /// /// - public FormObject this[string key] + public FormObject? this[string key] { get { - FormObject form = null; + FormObject? form = null; foreach (FormObject f in this) { if (string.Equals(key, f.Id, StringComparison.OrdinalIgnoreCase)) @@ -30,7 +32,7 @@ public FormObject this[string key] } } - return (form); + return form; } } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonDateKind.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonDateKind.cs new file mode 100644 index 00000000000..2fed27128a6 --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs index 9f1d2b1c8a2..6506f2bd2ce 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/JsonObject.cs @@ -8,8 +8,8 @@ using System.Globalization; using System.Management.Automation; using System.Management.Automation.Language; +using System.Numerics; using System.Reflection; -using System.Text.RegularExpressions; using System.Threading; using Newtonsoft.Json; @@ -98,7 +98,7 @@ public ConvertToJsonContext( } } - private class DuplicateMemberHashSet : HashSet + private sealed class DuplicateMemberHashSet : HashSet { public DuplicateMemberHashSet(int capacity) : base(capacity, StringComparer.OrdinalIgnoreCase) @@ -151,35 +151,68 @@ public static object ConvertFromJson(string input, bool returnHashtable, out Err /// 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) { - if (input == null) + ArgumentNullException.ThrowIfNull(input); + + DateParseHandling dateParseHandling; + DateTimeZoneHandling dateTimeZoneHandling; + switch (jsonDateKind) { - throw new ArgumentNullException(nameof(input)); + 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 { - // JsonConvert.DeserializeObject does not throw an exception when an invalid Json array is passed. - // This issue is being tracked by https://github.com/JamesNK/Newtonsoft.Json/issues/1930. - // To work around this, we need to identify when input is a Json array, and then try to parse it via JArray.Parse(). - - // If input starts with '[' (ignoring white spaces). - if (Regex.Match(input, @"^\s*\[").Success) - { - // JArray.Parse() will throw a JsonException if the array is invalid. - // This will be caught by the catch block below, and then throw an - // ArgumentException - this is done to have same behavior as the JavaScriptSerializer. - JArray.Parse(input); - - // Please note that if the Json array is valid, we don't do anything, - // we just continue the deserialization. - } - 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, @@ -255,11 +288,11 @@ private static PSObject PopulateFromJDictionary(JObject entries, DuplicateMember return null; } - // Array switch (entry.Value) { case JArray list: { + // Array var listResult = PopulateFromJArray(list, out error); if (error != null) { @@ -299,52 +332,51 @@ private static ICollection PopulateFromJArray(JArray list, out ErrorReco { error = null; var result = new object[list.Count]; + var i = 0; - for (var index = 0; index < list.Count; index++) + foreach (var element in list) { - var element = list[index]; switch (element) { case JArray subList: + // Array + result[i++] = PopulateFromJArray(subList, out error); + if (error != null) { - // Array - var listResult = PopulateFromJArray(subList, out error); - if (error != null) - { - return null; - } - - result[index] = listResult; - break; + return null; } + + break; + case JObject dic: + // Dictionary + result[i++] = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error); + if (error != null) { - // Dictionary - var dicResult = PopulateFromJDictionary(dic, new DuplicateMemberHashSet(dic.Count), out error); - if (error != null) - { - return null; - } - - result[index] = dicResult; - break; + return null; } + + break; + case JValue value: + if (value.Type != JTokenType.Comment) { - result[index] = value.Value; - break; + result[i++] = value.Value; } + + break; } } - return result; + // 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; - Hashtable result = new(entries.Count); + OrderedHashtable result = new(entries.Count); foreach (var entry in entries) { // Case sensitive duplicates should normally not occur since JsonConvert.DeserializeObject @@ -402,46 +434,44 @@ private static ICollection PopulateHashTableFromJArray(JArray list, out { error = null; var result = new object[list.Count]; + var i = 0; - for (var index = 0; index < list.Count; index++) + foreach (var element in list) { - var element = list[index]; - switch (element) { - case JArray array: + case JArray subList: + // Array + result[i++] = PopulateHashTableFromJArray(subList, out error); + if (error != null) { - // Array - var listResult = PopulateHashTableFromJArray(array, out error); - if (error != null) - { - return null; - } - - result[index] = listResult; - break; + return null; } + + break; + case JObject dic: + // Dictionary + result[i++] = PopulateHashTableFromJDictionary(dic, out error); + if (error != null) { - // Dictionary - var dicResult = PopulateHashTableFromJDictionary(dic, out error); - if (error != null) - { - return null; - } - - result[index] = dicResult; - break; + return null; } + + break; + case JValue value: + if (value.Type != JTokenType.Comment) { - result[index] = value.Value; - break; + result[i++] = value.Value; } + + break; } } - return result; + // 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 @@ -530,7 +560,8 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso || obj is Uri || obj is double || obj is float - || obj is decimal) + || obj is decimal + || obj is BigInteger) { rv = obj; } @@ -542,7 +573,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso { Type t = obj.GetType(); - if (t.IsPrimitive) + if (t.IsPrimitive || (t.IsEnum && ExperimentalFeature.IsEnabled(ExperimentalFeature.PSSerializeJSONLongEnumAsNumber))) { rv = obj; } @@ -551,7 +582,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso // 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(Int64)) || enumUnderlyingType.Equals(typeof(UInt64))) + if (enumUnderlyingType.Equals(typeof(long)) || enumUnderlyingType.Equals(typeof(ulong))) { rv = obj.ToString(); } @@ -590,15 +621,13 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso } else { - IDictionary dict = obj as IDictionary; - if (dict != null) + if (obj is IDictionary dict) { rv = ProcessDictionary(dict, currentDepth, in context); } else { - IEnumerable enumerable = obj as IEnumerable; - if (enumerable != null) + if (obj is IEnumerable enumerable) { rv = ProcessEnumerable(enumerable, currentDepth, in context); } @@ -633,7 +662,7 @@ private static object ProcessValue(object obj, int currentDepth, in ConvertToJso /// private static object AddPsProperties(object psObj, object obj, int depth, bool isPurePSObj, bool isCustomObj, in ConvertToJsonContext context) { - if (!(psObj is PSObject pso)) + if (psObj is not PSObject pso) { return obj; } @@ -645,9 +674,8 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool } bool wasDictionary = true; - IDictionary dict = obj as IDictionary; - if (dict == null) + if (obj is not IDictionary dict) { wasDictionary = false; dict = new Dictionary(); @@ -678,6 +706,12 @@ private static object AddPsProperties(object psObj, object obj, int depth, bool /// 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, diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs index 2ea29e73fa3..1a19d6b0457 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/PSUserAgent.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; using System.Globalization; using System.Management.Automation; @@ -14,112 +16,39 @@ namespace Microsoft.PowerShell.Commands /// public static class PSUserAgent { - private static string s_windowsUserAgent; + private static string? s_windowsUserAgent; - internal static string UserAgent - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) {4}", - Compatibility, PlatformName, OS, Culture, App); - return (userAgent); - } - } + // 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 - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} (compatible; MSIE 9.0; {1}; {2}; {3})", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + 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 - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) Gecko/20100401 Firefox/4.0", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + 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 - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) AppleWebKit/534.6 (KHTML, like Gecko) Chrome/7.0.500.0 Safari/534.6", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + 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 - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "Opera/9.70 ({0}; {1}; {2}) Presto/2.2.1", - PlatformName, OS, Culture); - return (userAgent); - } - } + 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 - { - get - { - // format the user-agent string from the various component parts - string userAgent = string.Format(CultureInfo.InvariantCulture, - "{0} ({1}; {2}; {3}) AppleWebKit/533.16 (KHTML, like Gecko) Version/5.0 Safari/533.16", - Compatibility, PlatformName, OS, Culture); - return (userAgent); - } - } + 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 - { - get - { - return ("Mozilla/5.0"); - } - } + internal static string Compatibility => "Mozilla/5.0"; - internal static string App - { - get - { - string app = string.Format(CultureInfo.InvariantCulture, - "PowerShell/{0}", PSVersionInfo.PSVersion); - return (app); - } - } + internal static string App => string.Create(CultureInfo.InvariantCulture, $"PowerShell/{PSVersionInfo.PSVersion}"); internal static string PlatformName { @@ -127,10 +56,10 @@ internal static string PlatformName { if (Platform.IsWindows) { - // only generate the windows user agent once - if (s_windowsUserAgent == null) + // Only generate the windows user agent once + if (s_windowsUserAgent is null) { - // find the version in the windows operating system description + // Find the version in the windows operating system description Regex pattern = new(@"\d+(\.\d+)+"); string versionText = pattern.Match(OS).Value; Version windowsPlatformversion = new(versionText); @@ -149,27 +78,15 @@ internal static string PlatformName } else { - // unknown/unsupported platform + // Unknown/unsupported platform Diagnostics.Assert(false, "Unable to determine Operating System Platform"); return string.Empty; } } } - internal static string OS - { - get - { - return RuntimeInformation.OSDescription.Trim(); - } - } + internal static string OS => RuntimeInformation.OSDescription.Trim(); - internal static string Culture - { - get - { - return (CultureInfo.CurrentCulture.Name); - } - } + internal static string Culture => CultureInfo.CurrentCulture.Name; } } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs index 43b625311b9..d24961834b6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/StreamHelper.cs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System; +using System.Buffers; using System.IO; -using System.IO.Compression; using System.Management.Automation; using System.Management.Automation.Internal; using System.Net.Http; @@ -20,70 +22,50 @@ namespace Microsoft.PowerShell.Commands /// 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 class WebResponseContentMemoryStream : MemoryStream + 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; - private readonly Cmdlet _ownerCmdlet; - #endregion + #endregion Data #region Constructors /// /// Initializes a new instance of the class. /// - /// - /// + /// Response stream. + /// Presize the memory stream. /// Owner cmdlet if any. - internal WebResponseContentMemoryStream(Stream stream, int initialCapacity, Cmdlet cmdlet) - : base(initialCapacity) + /// 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 + #endregion Constructors /// /// - public override bool CanRead - { - get - { - return true; - } - } + public override bool CanRead => true; /// /// - public override bool CanSeek - { - get - { - return true; - } - } + public override bool CanSeek => true; /// /// - public override bool CanTimeout - { - get - { - return base.CanTimeout; - } - } - - /// - /// - public override bool CanWrite - { - get - { - return true; - } - } + public override bool CanWrite => true; /// /// @@ -104,7 +86,7 @@ public override long Length /// public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { - Initialize(); + Initialize(cancellationToken); return base.CopyToAsync(destination, bufferSize, cancellationToken); } @@ -129,7 +111,7 @@ public override int Read(byte[] buffer, int offset, int count) /// public override Task ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - Initialize(); + Initialize(cancellationToken); return base.ReadAsync(buffer, offset, count, cancellationToken); } @@ -180,7 +162,7 @@ public override void Write(byte[] buffer, int offset, int count) /// public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - Initialize(); + Initialize(cancellationToken); return base.WriteAsync(buffer, offset, count, cancellationToken); } @@ -209,23 +191,39 @@ protected override void Dispose(bool disposing) base.Dispose(disposing); } - /// - /// - private void Initialize() + private void Initialize(CancellationToken cancellationToken = default) { - if (_isInitialized) { return; } + if (_isInitialized) + { + return; + } + + if (cancellationToken == default) + { + cancellationToken = _cancellationToken; + } _isInitialized = true; try { - long totalLength = 0; + long totalRead = 0; byte[] buffer = new byte[StreamHelper.ChunkSize]; ProgressRecord record = new(StreamHelper.ActivityId, WebCmdletStrings.ReadResponseProgressActivity, "statusDescriptionPlaceholder"); - for (int read = 1; read > 0; totalLength += read) + string totalDownloadSize = _contentLength is null ? "???" : Utils.DisplayHumanReadableFileSize((long)_contentLength); + for (int read = 1; read > 0; totalRead += read) { - if (_ownerCmdlet != null) + if (_ownerCmdlet is not null) { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseProgressStatus, totalLength); + 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) @@ -234,7 +232,7 @@ private void Initialize() } } - read = _originalStreamToProxy.Read(buffer, 0, buffer.Length); + read = _originalStreamToProxy.ReadAsync(buffer.AsMemory(), _perReadTimeout, cancellationToken).GetAwaiter().GetResult(); if (read > 0) { @@ -242,25 +240,103 @@ private void Initialize() } } - if (_ownerCmdlet != null) + if (_ownerCmdlet is not null) { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalLength); + record.StatusDescription = StringUtil.Format(WebCmdletStrings.ReadResponseComplete, totalRead); record.RecordType = ProgressRecordType.Completed; _ownerCmdlet.WriteProgress(record); } - // make sure the length is set appropriately - base.SetLength(totalLength); - base.Seek(0, SeekOrigin.Begin); + // Make sure the length is set appropriately + base.SetLength(totalRead); + Seek(0, SeekOrigin.Begin); } catch (Exception) { - base.Dispose(); + 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 @@ -269,46 +345,61 @@ internal static class StreamHelper internal const int ChunkSize = 10000; - // just picked a random number + // 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, CancellationToken cancellationToken) + internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, long? contentLength, TimeSpan perReadTimeout, CancellationToken cancellationToken) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } + ArgumentNullException.ThrowIfNull(cmdlet); - Task copyTask = input.CopyToAsync(output, cancellationToken); + 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 { - do + while (!copyTask.Wait(1000, cancellationToken)) { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestProgressStatus, output.Position); - cmdlet.WriteProgress(record); + record.StatusDescription = StringUtil.Format( + WebCmdletStrings.WriteRequestProgressStatus, + Utils.DisplayHumanReadableFileSize(output.Position), + totalDownloadSize); - Task.Delay(1000).Wait(cancellationToken); - } - while (!copyTask.IsCompleted && !cancellationToken.IsCancellationRequested); + if (contentLength > 0) + { + record.PercentComplete = Math.Min((int)(output.Position * 100 / (long)contentLength), 100); + } - if (copyTask.IsCompleted) - { - record.StatusDescription = StringUtil.Format(WebCmdletStrings.WriteRequestComplete, output.Position); 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); + } + } } /// @@ -318,16 +409,18 @@ internal static void WriteToStream(Stream input, Stream output, PSCmdlet cmdlet, /// 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, CancellationToken cancellationToken) + 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, cancellationToken); + WriteToStream(stream, output, cmdlet, contentLength, perReadTimeout, cancellationToken); } - private static string StreamToString(Stream stream, Encoding encoding) + private static string StreamToString(Stream stream, Encoding encoding, TimeSpan perReadTimeout, CancellationToken cancellationToken) { StringBuilder result = new(capacity: ChunkSize); Decoder decoder = encoding.GetDecoder(); @@ -338,157 +431,126 @@ private static string StreamToString(Stream stream, Encoding encoding) useBufferSize = encoding.GetMaxCharCount(10); } - char[] chars = new char[useBufferSize]; - byte[] bytes = new byte[useBufferSize * 4]; - int bytesRead = 0; - do + char[] chars = ArrayPool.Shared.Rent(useBufferSize); + byte[] bytes = ArrayPool.Shared.Rent(useBufferSize * 4); + try { - // 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.Read(bytes, 0, useBufferSize * 4); + 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; - int bytesUsed; - int charsUsed; + 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 == 0); - decoder.Convert(bytes, byteIndex, bytesRead - byteIndex, - chars, 0, useBufferSize, flush, - out bytesUsed, out 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) + while (!completed) { - break; + // 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); + while (bytesRead != 0); - return result.ToString(); + return result.ToString(); + } + finally + { + ArrayPool.Shared.Return(chars); + ArrayPool.Shared.Return(bytes); + } } - internal static string DecodeStream(Stream stream, string characterSet, out Encoding encoding) + internal static string DecodeStream(Stream stream, string? characterSet, out Encoding encoding, TimeSpan perReadTimeout, CancellationToken cancellationToken) { - try - { - encoding = Encoding.GetEncoding(characterSet); - } - catch (ArgumentException) + bool isDefaultEncoding = !TryGetEncoding(characterSet, out encoding); + + string content = StreamToString(stream, encoding, perReadTimeout, cancellationToken); + if (isDefaultEncoding) { - encoding = null; + // 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 DecodeStream(stream, ref encoding); + return content; } - internal static bool TryGetEncoding(string characterSet, out Encoding encoding) + internal static bool TryGetEncoding(string? characterSet, out Encoding encoding) { bool result = false; try { - encoding = Encoding.GetEncoding(characterSet); + encoding = Encoding.GetEncoding(characterSet!); result = true; } catch (ArgumentException) { - encoding = null; + // Use the default encoding if one wasn't provided + encoding = ContentHelper.GetDefaultEncoding(); } return result; } - private static readonly Regex s_metaexp = new( + 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.Compiled | RegexOptions.Singleline | RegexOptions.ExplicitCapture | RegexOptions.CultureInvariant | RegexOptions.IgnoreCase | RegexOptions.NonBacktracking ); - internal static string DecodeStream(Stream stream, ref Encoding encoding) - { - bool isDefaultEncoding = false; - if (encoding == null) - { - // Use the default encoding if one wasn't provided - encoding = ContentHelper.GetDefaultEncoding(); - isDefaultEncoding = true; - } - - string content = StreamToString(stream, encoding); - if (isDefaultEncoding) - { - do - { - // check for a charset attribute on the meta element to override the default. - Match match = s_metaexp.Match(content); - if (match.Success) - { - Encoding localEncoding = null; - string characterSet = match.Groups["charset"].Value; - - if (TryGetEncoding(characterSet, out localEncoding)) - { - stream.Seek(0, SeekOrigin.Begin); - content = StreamToString(stream, localEncoding); - // report the encoding used. - encoding = localEncoding; - } - } - } while (false); - } - - return content; - } + 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) { - if (encoding == null) - { - // just use the default encoding if one wasn't provided - encoding = ContentHelper.GetDefaultEncoding(); - } + // Just use the default encoding if one wasn't provided + encoding ??= ContentHelper.GetDefaultEncoding(); return encoding.GetBytes(str); } - internal static byte[] EncodeToBytes(string str) - { - return EncodeToBytes(str, null); - } - - internal static Stream GetResponseStream(HttpResponseMessage response) - { - Stream responseStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult(); - var contentEncoding = response.Content.Headers.ContentEncoding; - - // HttpClient by default will automatically decompress GZip and Deflate content. - // We keep this decompression logic here just in case. - if (contentEncoding != null && contentEncoding.Count > 0) - { - if (contentEncoding.Contains("gzip")) - { - responseStream = new GZipStream(responseStream, CompressionMode.Decompress); - } - else if (contentEncoding.Contains("deflate")) - { - responseStream = new DeflateStream(responseStream, CompressionMode.Decompress); - } - } - - return responseStream; - } + internal static Stream GetResponseStream(HttpResponseMessage response, CancellationToken cancellationToken) => response.Content.ReadAsStreamAsync(cancellationToken).GetAwaiter().GetResult(); #endregion Static Methods } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs index fada385d4ac..99326898d9f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebCmdletElementCollection.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation; @@ -12,8 +14,7 @@ namespace Microsoft.PowerShell.Commands /// public class WebCmdletElementCollection : ReadOnlyCollection { - internal WebCmdletElementCollection(IList list) - : base(list) + internal WebCmdletElementCollection(IList list) : base(list) { } @@ -22,35 +23,23 @@ internal WebCmdletElementCollection(IList list) /// /// /// Found element as PSObject. - public PSObject Find(string nameOrId) - { - // try Id first - PSObject result = FindById(nameOrId) ?? FindByName(nameOrId); - - return (result); - } + public PSObject? Find(string nameOrId) => FindById(nameOrId) ?? FindByName(nameOrId); /// /// Finds the element by id. /// /// /// Found element as PSObject. - public PSObject FindById(string id) - { - return Find(id, true); - } + public PSObject? FindById(string id) => Find(id, findById: true); /// /// Finds the element by name. /// /// /// Found element as PSObject. - public PSObject FindByName(string name) - { - return Find(name, false); - } + public PSObject? FindByName(string name) => Find(name, findById: false); - private PSObject Find(string nameOrId, bool findById) + private PSObject? Find(string nameOrId, bool findById) { foreach (PSObject candidate in this) { diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs index aa7067f1c23..9b90115a1d5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestMethod.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + namespace Microsoft.PowerShell.Commands { /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs index ae08babe17f..efee6f3240e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/WebRequestSession.cs @@ -1,18 +1,48 @@ // 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 + 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. /// @@ -27,27 +57,27 @@ public class WebRequestSession /// /// Gets or sets the Cookies property. /// - public CookieContainer Cookies { get; set; } + public CookieContainer Cookies { get => _cookies; set => SetClassVar(ref _cookies, value); } #region Credentials /// /// Gets or sets the UseDefaultCredentials property. /// - public bool UseDefaultCredentials { get; set; } + public bool UseDefaultCredentials { get => _useDefaultCredentials; set => SetStructVar(ref _useDefaultCredentials, value); } /// /// Gets or sets the Credentials property. /// - public ICredentials Credentials { get; set; } + 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; set; } + public X509CertificateCollection? Certificates { get => _certificates; set => SetClassVar(ref _certificates, value); } - #endregion + #endregion Credentials /// /// Gets or sets the UserAgent property. @@ -57,12 +87,23 @@ public class WebRequestSession /// /// Gets or sets the Proxy property. /// - public IWebProxy Proxy { get; set; } + public IWebProxy? Proxy + { + get => _proxy; + set + { + SetClassVar(ref _proxy, value); + if (_proxy is not null) + { + NoProxy = false; + } + } + } /// - /// Gets or sets the RedirectMax property. + /// Gets or sets the MaximumRedirection property. /// - public int MaximumRedirection { get; set; } + public int MaximumRedirection { get => _maximumRedirection; set => SetStructVar(ref _maximumRedirection, value); } /// /// Gets or sets the count of retries for request failures. @@ -79,23 +120,44 @@ public class WebRequestSession /// public WebRequestSession() { - // build the headers collection + // Build the headers collection Headers = new Dictionary(StringComparer.OrdinalIgnoreCase); ContentHeaders = new Dictionary(StringComparer.OrdinalIgnoreCase); - // build the cookie jar - Cookies = new CookieContainer(); + // Build the cookie jar + _cookies = new CookieContainer(); - // initialize the credential and certificate caches - UseDefaultCredentials = false; - Credentials = null; - Certificates = null; + // Initialize the credential and certificate caches + _useDefaultCredentials = false; + _credentials = null; + _certificates = null; - // setup the default UserAgent + // Setup the default UserAgent UserAgent = PSUserAgent.UserAgent; - Proxy = null; - MaximumRedirection = -1; + _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; + } + } } /// @@ -104,12 +166,150 @@ public WebRequestSession() /// The certificate to be added. internal void AddCertificate(X509Certificate certificate) { - if (Certificates == null) + 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) { - Certificates = new X509CertificateCollection(); + 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); + }; } - Certificates.Add(certificate); + 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/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs index bf907203544..d20d7d8712b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/Write.cs @@ -33,15 +33,11 @@ protected override void ProcessRecord() // 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(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { DebugRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -81,15 +77,11 @@ protected override void ProcessRecord() // 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(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { VerboseRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -129,15 +121,11 @@ protected override void ProcessRecord() // 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(). // - MshCommandRuntime mshCommandRuntime = this.CommandRuntime as MshCommandRuntime; - - if (mshCommandRuntime != null) + if (this.CommandRuntime is MshCommandRuntime mshCommandRuntime) { WarningRecord record = new(Message); - InvocationInfo invocationInfo = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - - if (invocationInfo != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo invocationInfo) { record.SetInvocationInfo(invocationInfo); } @@ -214,7 +202,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// /// ErrorRecord.Exception -- if not specified, ErrorRecord.Exception is System.Exception. /// - [Parameter(ParameterSetName = "WithException", Mandatory = true)] + [Parameter(Position = 0, ParameterSetName = "WithException", Mandatory = true)] public Exception Exception { get; set; } /// @@ -232,7 +220,7 @@ public class WriteOrThrowErrorCommand : PSCmdlet /// If Exception is specified, this is ErrorRecord.ErrorDetails.Message; /// otherwise, the Exception is System.Exception, and this is Exception.Message. /// - [Parameter(ParameterSetName = "ErrorRecord", Mandatory = true)] + [Parameter(Position = 0, ParameterSetName = "ErrorRecord", Mandatory = true)] public ErrorRecord ErrorRecord { get; set; } /// @@ -312,10 +300,7 @@ protected override void ProcessRecord() { Exception e = this.Exception; string msg = Message; - if (e == null) - { - e = new WriteErrorException(msg); - } + e ??= new WriteErrorException(msg); string errid = ErrorId; if (string.IsNullOrEmpty(errid)) @@ -339,10 +324,7 @@ protected override void ProcessRecord() string recact = RecommendedAction; if (!string.IsNullOrEmpty(recact)) { - if (errorRecord.ErrorDetails == null) - { - errorRecord.ErrorDetails = new ErrorDetails(errorRecord.ToString()); - } + errorRecord.ErrorDetails ??= new ErrorDetails(errorRecord.ToString()); errorRecord.ErrorDetails.RecommendedAction = recact; } @@ -367,8 +349,7 @@ protected override void ProcessRecord() // 2005/07/14-913791 "write-error output is confusing and misleading" // set InvocationInfo to the script not the command - InvocationInfo myInvocation = GetVariableValue(SpecialVariables.MyInvocation) as InvocationInfo; - if (myInvocation != null) + if (GetVariableValue(SpecialVariables.MyInvocation) is InvocationInfo myInvocation) { errorRecord.SetInvocationInfo(myInvocation); errorRecord.PreserveInvocationInfoOnce = true; @@ -428,7 +409,6 @@ public ThrowErrorCommand() /// when the user only specifies a string and not /// an Exception or ErrorRecord. /// - [Serializable] public class WriteErrorException : SystemException { #region ctor @@ -471,10 +451,11 @@ public WriteErrorException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected WriteErrorException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs index 82c9c9f6557..31670935fcf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteAliasCommandBase.cs @@ -61,6 +61,7 @@ public SwitchParameter PassThru /// The scope parameter for the command determines which scope the alias is set in. /// [Parameter] + [ArgumentCompleter(typeof(ScopeArgumentCompleter))] public string Scope { get; set; } /// diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs index 2d2009e56bc..48d84636ce2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteConsoleCmdlet.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Management.Automation; using System.Text; +using System.Xml; namespace Microsoft.PowerShell.Commands { @@ -51,9 +52,7 @@ private string ProcessObject(object o) { if (o != null) { - string s = o as string; - IEnumerable enumerable = null; - if (s != null) + if (o is string s) { // strings are IEnumerable, so we special case them if (s.Length > 0) @@ -61,7 +60,11 @@ private string ProcessObject(object o) return s; } } - else if ((enumerable = o as IEnumerable) != null) + else if (o is XmlNode xmlNode) + { + return xmlNode.Name; + } + else if (o is IEnumerable enumerable) { // unroll enumerables, including arrays. diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs index fe8fccb6e1a..0751954c54e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/WriteProgressCmdlet.cs @@ -17,7 +17,6 @@ public sealed class WriteProgressCommand : PSCmdlet /// [Parameter( Position = 0, - Mandatory = true, HelpMessageBaseName = HelpMessageBaseName, HelpMessageResourceId = "ActivityParameterHelpMessage")] public string Activity { get; set; } @@ -36,7 +35,7 @@ public sealed class WriteProgressCommand : PSCmdlet /// Uniquely identifies this activity for purposes of chaining subordinate activities. /// [Parameter(Position = 2)] - [ValidateRange(0, Int32.MaxValue)] + [ValidateRange(0, int.MaxValue)] public int Id { get; set; } /// @@ -62,7 +61,7 @@ public sealed class WriteProgressCommand : PSCmdlet /// Identifies the parent Id of this activity, or -1 if none. /// [Parameter] - [ValidateRange(-1, Int32.MaxValue)] + [ValidateRange(-1, int.MaxValue)] public int ParentId { get; set; } = -1; /// @@ -96,7 +95,29 @@ protected override void ProcessRecord() { - ProgressRecord pr = new(Id, Activity, Status); + 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; diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs index 8db56196a68..cc3b1f2b251 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/XmlCommands.cs @@ -111,8 +111,8 @@ public SwitchParameter NoClobber /// Encoding optional flag. /// [Parameter] - [ArgumentToEncodingTransformationAttribute()] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -128,7 +128,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; #endregion Command Line Parameters @@ -208,7 +208,10 @@ private void CreateFileStream() { Dbg.Assert(Path != null, "FileName is mandatory parameter"); - if (!ShouldProcess(Path)) return; + if (!ShouldProcess(Path)) + { + return; + } StreamWriter sw; PathUtils.MasterStreamOpen( @@ -328,13 +331,12 @@ public string[] LiteralPath private bool _disposed = false; /// - /// Public dispose method. + /// Release all resources. /// public void Dispose() { if (!_disposed) { - GC.SuppressFinalize(this); if (_helper != null) { _helper.Dispose(); @@ -439,7 +441,7 @@ protected override void BeginProcessing() } else { - WriteObject(string.Format(CultureInfo.InvariantCulture, "", Encoding.UTF8.WebName)); + WriteObject(string.Create(CultureInfo.InvariantCulture, $"")); WriteObject(""); } } @@ -453,8 +455,7 @@ protected override void ProcessRecord() { CreateMemoryStream(); - if (_serializer != null) - _serializer.SerializeAsStream(InputObject); + _serializer?.SerializeAsStream(InputObject); if (_serializer != null) { @@ -472,8 +473,7 @@ protected override void ProcessRecord() } else { - if (_serializer != null) - _serializer.Serialize(InputObject); + _serializer?.Serialize(InputObject); } } @@ -631,10 +631,90 @@ private void CleanUp() #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 class ImportXmlHelper : IDisposable + internal sealed class ImportXmlHelper : IDisposable { #region constructor @@ -763,12 +843,10 @@ internal void Import() while (!_deserializer.Done() && count < first) { object result = _deserializer.Deserialize(); - PSObject psObject = result as PSObject; - if (psObject != null) + if (result is PSObject psObject) { - ICollection c = psObject.BaseObject as ICollection; - if (c != null) + if (psObject.BaseObject is ICollection c) { foreach (object o in c) { @@ -801,19 +879,13 @@ internal void Import() } } - internal void Stop() - { - if (_deserializer != null) - { - _deserializer.Stop(); - } - } + internal void Stop() => _deserializer?.Stop(); } #region Select-Xml - /// - ///This cmdlet is used to search an xml document based on the XPath Query. - /// + /// + /// 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 diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs index b37f06b2b2f..491aaf85361 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/GetTracerCommand.cs @@ -51,7 +51,7 @@ public string[] Name protected override void ProcessRecord() { var sources = GetMatchingTraceSource(_names, true); - var result = sources.OrderBy(source => source.Name); + var result = sources.OrderBy(static source => source.Name); WriteObject(result, true); } diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs index 357e0222b6d..b7e4ed279aa 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/MshHostTraceListener.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.Commands /// This trace listener cannot be specified in the app.config file. /// It must be added through the add-tracelistener cmdlet. /// - internal class PSHostTraceListener + internal sealed class PSHostTraceListener : System.Diagnostics.TraceListener { #region TraceListener constructors and disposer diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs index a17ee0fdbef..9f8694ebd20 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/SetTracerCommand.cs @@ -99,7 +99,7 @@ public SwitchParameter Debugger } /// - /// If this parameter is specified the Msh Host trace listener will be added. + /// If this parameter is specified the PSHost trace listener will be added. /// /// [Parameter(ParameterSetName = "optionsSet")] diff --git a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs index 412f4a2d150..1eadd4934b3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs +++ b/src/Microsoft.PowerShell.Commands.Utility/commands/utility/trace/TraceExpressionCommand.cs @@ -249,13 +249,7 @@ protected override void EndProcessing() /// /// Ensures that the sub-pipeline we created gets stopped as well. /// - protected override void StopProcessing() - { - if (_pipeline != null) - { - _pipeline.Stop(); - } - } + protected override void StopProcessing() => _pipeline?.Stop(); #endregion Cmdlet code @@ -329,22 +323,15 @@ public void Dispose() /// 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 class TracePipelineWriter : PipelineWriter + internal sealed class TracePipelineWriter : PipelineWriter { internal TracePipelineWriter( TraceListenerCommandBase cmdlet, bool writeError, Collection matchingSources) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } - - if (matchingSources == null) - { - throw new ArgumentNullException(nameof(matchingSources)); - } + ArgumentNullException.ThrowIfNull(cmdlet); + ArgumentNullException.ThrowIfNull(matchingSources); _cmdlet = cmdlet; _writeError = writeError; @@ -525,8 +512,7 @@ public override int Write(object obj, bool enumerateCollection) private static ErrorRecord ConvertToErrorRecord(object obj) { ErrorRecord result = null; - PSObject mshobj = obj as PSObject; - if (mshobj != null) + if (obj is PSObject mshobj) { object baseObject = mshobj.BaseObject; if (baseObject is not PSCustomObject) @@ -535,8 +521,7 @@ private static ErrorRecord ConvertToErrorRecord(object obj) } } - ErrorRecord errorRecordResult = obj as ErrorRecord; - if (errorRecordResult != null) + if (obj is ErrorRecord errorRecordResult) { result = errorRecordResult; } diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx index cb18968d6ed..5890ed43eea 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AddMember.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx index 75ba47072d2..c0374e4d1d2 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AddTypeStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -120,27 +120,12 @@ The source code was already compiled and loaded. - - The generated type defines no public methods or properties. - - - The generated type is not public. - - - Cannot add type. The -MemberDefinition parameter is not supported for this language. - Cannot add type. The "{0}" extension is not supported. Cannot add type. Input files must all have the same file extension. - - Cannot add type. Specify only the Language or CodeDomProvider parameters. - - - Cannot add type. The assembly name {0} matches both {1} and {2}. - Cannot add type. The assembly '{0}' could not be found. @@ -153,9 +138,6 @@ Cannot add type. Compilation errors occurred. - - Cannot add type. One or more required assemblies are missing. - Cannot add type. The OutputType parameter requires that the OutputAssembly parameter be specified. @@ -168,4 +150,10 @@ 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/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx index 1c3b0e52953..b113e19818f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/AliasCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -135,12 +135,6 @@ Name: {0} Value: {1} - - Cannot export the aliases because path '{0}' referred to a '{1}' provider path. Change the Path parameter to a file system path. - - - Cannot export the aliases because path '{0}' contains wildcard characters that resolved to multiple paths. Aliases can be exported to only one file. Change the value of the Path parameter to a path that resolves to a single file. - Cannot open file {0} to export the alias. {1} diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx index 285dea7301e..10214736962 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringData.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx deleted file mode 100644 index ae0b785d645..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertFromStringResources.resx +++ /dev/null @@ -1,150 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx index f01b88d8754..e604b617997 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertHTMLStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx index d37509d0f50..692be6fe026 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertMarkdownStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -120,9 +120,6 @@ The type of the input object '{0}' is invalid. - - The file is not found: '{0}'. - Only FileSystem Provider paths are supported. The file path is not supported: '{0}'. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx deleted file mode 100644 index 9e65acdc23c..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ConvertStringResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx index 0eff0d6f84f..572e4d99e17 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/CsvCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -130,9 +130,6 @@ You must specify either the -UseQuotes or -QuoteFields parameters, but not both. - - You must specify either the -IncludeTypeInformation or -NoTypeInformation parameters, but not both. - You must specify either the -Path or -LiteralPath parameters, but not both. @@ -157,4 +154,7 @@ EOF is reached. + + You must specify either the -Append or -NoHeader parameters, but not both. + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx index 043fa4a9320..c4ab45d5b61 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/Debugger.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx index 2eff70b6267..e36c4148b01 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/EventingStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx deleted file mode 100644 index 824b56ec6bf..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/FlashExtractStrings.resx +++ /dev/null @@ -1,213 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx index e5bdb6dc12b..f5b5dd3000a 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/FormatAndOut_out_gridview.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/GetFormatDataStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/GetFormatDataStrings.resx new file mode 100644 index 00000000000..74e1db4692d --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx index a2e19681b64..054a4c873d6 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/GetMember.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx index c81839c8409..ecbdecc3464 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/GetRandomCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx index f59439da714..9450dc82028 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/GetUptimeStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx index 6172bb81951..6391b0183ea 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/HostStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -120,7 +120,4 @@ Cannot process the color because {0} is not a valid color. - - Cannot evaluate the error because a string is not specified. - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx index 78ccfb68dc1..a08843ed7c3 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/HttpCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - The command cannot run because "{0}" is empty or blank. Specify a value, and then run the command again. - This command cannot be completed due to the following error: '{0}'. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx deleted file mode 100644 index 9ba7fddb0b5..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImmutableStrings.resx +++ /dev/null @@ -1,147 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - - Object is not a array with the same initialization state as the array to compare it to. - - - Object is not a array with the same number of elements as the array to compare it to. - - - Cannot find the old value - - - Capacity was less than the current Count of elements. - - - MoveToImmutable can only be performed when Count equals Capacity. - - - Collection was modified; enumeration operation may not execute. - - - An element with the same key but a different value already exists. Key: {0} - - - This operation does not apply to an empty instance. - - - This operation cannot be performed on a default instance of ImmutableArray<T>. Consider initializing the array, or checking the ImmutableArray<T>.IsDefault property. - - diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx index 48d1fea7c34..70e00b3b7f1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ImplicitRemotingStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -129,9 +129,6 @@ Running the {0} command in a remote session returned no results. - - Cannot create temporary file for implicit remoting module. - No session has been associated with this implicit remoting module. @@ -147,15 +144,6 @@ 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 '{0}' command, because PowerShell could not verify the safety of a parameter name: '{1}'. - - - Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of a parameter set name: '{1}'. - - - Proxy creation has been skipped for the '{0}' command, because PowerShell could not verify the safety of a parameter alias name: '{1}'. - 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. @@ -204,9 +192,6 @@ Getting formatting and output information from remote session ... {0} objects received - - Generating a proxy command for '{0}' ... - Completed. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx index 8bd19d60ac3..8fc6474c99e 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ImportLocalizedDataStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -143,4 +143,10 @@ 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/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx index 2b6b80959d0..fe284f4a24b 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/MatchStringStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx index 8211114c335..47daf3c35b1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/MeasureObjectStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -120,9 +120,6 @@ The property "{0}" cannot be found in the input for any objects. - - Property "{0}" is not numeric. - Input object "{0}" is not numeric. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx index 07c2a6d8c9e..3b8b8ab2371 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/NewObjectStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -147,7 +147,16 @@ Cannot create type. Only core types are supported in {0} language mode on a policy locked down machine. - - {0} Please note that Single-Threaded Apartment is not supported in PowerShell. + + 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/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx index 0b4c01443f3..8e6fcd284b1 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/OutPrinterDisplayStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx index 02d3aad766d..621e833d092 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/SelectObjectStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx index 3f53249c1b3..8278af4b469 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/SendMailMessageStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx index 4e05f063ce1..729a027d66f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/SortObjectStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/StartSleepStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/StartSleepStrings.resx new file mode 100644 index 00000000000..32804b9e21b --- /dev/null +++ b/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/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx index ab105e47fd3..e9a19f81793 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/TestJsonCmdletStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -123,10 +123,13 @@ Cannot parse the JSON. - - The JSON is not valid with the schema. + + 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/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx index 0eb1e1e9466..1446921e129 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/TraceCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - A file listener with name '{0}' was not found. - Trace output can only be written to the file system. The path '{0}' referred to a '{1}' provider path. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx index b2af7eba67e..9c6325363cf 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UnblockFileStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx index 9d2ccaced94..feea0b90490 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateDataStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -135,9 +135,6 @@ Cannot update a member with type "{0}". Specify a different type for the MemberType parameter. - - The value of the SerializationDepth property should not be negative. - The {0} parameter is required for the type "{1}". Please specify the {0} parameter. diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx index e6b985db275..8caa94ce8d8 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UpdateListStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx index 551f0d1fcb8..3e7f0052592 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityCommonStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - There are no matching results found for {2}. - {2} has one or more exceptions that are not valid. @@ -165,13 +162,16 @@ Cannot use tag '{0}'. The 'PS' prefix is reserved. - - Algorithm '{0}' is not supported in this system. - 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/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx deleted file mode 100644 index 3bca38847db..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/UtilityMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx index bff7eee52af..51b93d480ef 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/VariableCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -123,18 +123,15 @@ Name: {0} Value: {1} + + Use a single variable rather than a collection + New variable Name: {0} Value: {1} - - Add variable - - - Name: {0} - Remove variable diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx index e3c64bd5ca3..4bc8e782b0f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WebCmdletStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -129,7 +129,7 @@ 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. @@ -159,17 +159,14 @@ Cannot convert the JSON string because a dictionary that was converted from the string contains the duplicated key '{0}'. - - 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 ConvertTo-Json and ConvertFrom-Json cmdlets require the installation of the .NET Client Profile, sometimes called the .NET extended profile. - 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. - - The converted JSON string is in bad format. + + 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. @@ -199,16 +196,16 @@ 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 completed. (Number of bytes read: {0}) + Reading web response stream completed. Bytes downloaded: {0} - Reading web response + Reading web response stream - Reading response stream... (Number of bytes read: {0}) + Downloaded: {0} of {1} - - The operation has timed out. + + 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. @@ -219,26 +216,14 @@ Web request completed. (Number of bytes processed: {0}) + + Web request cancelled. (Number of bytes processed: {0}) + Web request status - Number of bytes processed: {0} - - - The ConvertTo-Json and ConvertFrom-Json cmdlets require the 'Json.Net' module. {0} - - - The cmdlet cannot run because the 'Json.Net' module cannot be loaded. Import the module manually or set the $PSModuleAutoLoadingPreference variable to enable module auto loading. For more information, see 'get-help about_Preference_Variables'. - - - However, the 'Json.Net' module could not be loaded. For more information, run 'Import-Module Json.Net'. - - - Ensure 'Json.Net.psd1' and 'Newtonsoft.Json.dll' are available in a versioned subdirectory of '{0}'. - - - The maximum depth allowed for serialization is {0}. + Downloaded: {0} of {1} Conversion from JSON failed with error: {0} @@ -249,14 +234,11 @@ Following rel link {0} - - {0} with {1}-byte payload - The remote server indicated it could not resume downloading. The local file will be overwritten. - - received {0}-byte response of content type {1} + + Received HTTP/{0} response of content type {1} of unknown size Retrying after interval of {0} seconds. Status code for previous attempt: {1} @@ -264,4 +246,7 @@ 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/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx index 13d2058e7b2..cb913ef9dd5 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WriteErrorStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx index 9603b4deb99..919e5638e2f 100644 --- a/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/WriteProgressResourceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AddMember.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AddMember.cs.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AddMember.cs.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AddTypeStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AddTypeStrings.cs.resx new file mode 100644 index 00000000000..fae897a2605 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AddTypeStrings.cs.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 + + + Zdrojový kód již byl zkompilován a načten. + + + Typ nelze přidat. Přípona „{0}“ se nepodporuje. + + + Typ nelze přidat. Vstupní soubory musí mít stejnou příponu. + + + Typ nelze přidat. Sestavení {0} nejde najít. + + + Typ nelze přidat. Název typu {0} již existuje. + + + Nelze nastavit výstupní sestavení. Cesta {0} se nepřeložila na jeden soubor. + + + Typ nelze přidat. Došlo k chybám kompilace. + + + Typ nelze přidat. Parametr OutputType vyžaduje, aby byl zadán parametr OutputAssembly. + + + Typ nelze přidat. Definice nových typů není v tomto jazykovém režimu podporována. + + + Zadané referenční sestavení „{0}“ je zbytečné a ignoruje se. + + + Typy sestavení ConsoleApplication a WindowsApplication se v současné době nepodporují. + + + Rutina Add-Type + + + Rutina Add-Type nebude v režimu ConstrainedLanguage povolena. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AliasCommandStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AliasCommandStrings.cs.resx new file mode 100644 index 00000000000..5d925594808 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/AliasCommandStrings.cs.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 + + + Nastavit alias + + + Název: {0} Hodnota: {1} + + + Nový alias + + + Název: {0} Hodnota: {1} + + + Importovat alias + + + Název: {0} Hodnota: {1} + + + Nelze otevřít soubor {0} pro export aliasu. {1} + + + Soubor aliasu + + + Exportováno uživatelem: {0} + + + Datum a čas: {0:F} + + + Počítač: {0} + + + Alias nelze importovat, protože zadaná cesta {0} odkazuje na cestu zprostředkovatele {1}. Změňte hodnotu parametru Path na cestu systému souborů. + + + Alias nejde importovat, protože cesta {0} obsahuje zástupné znaky, které se překládají na více cest. Aliasy se dají importovat jenom z jednoho souboru. Změňte hodnotu parametru Path na cestu, která se překládá na jeden soubor. + + + Nelze otevřít soubor {0} pro import aliasu. {1} + + + Alias nelze importovat. Číslo řádku {1} v souboru {0} není správně formátovaný řádek hodnot oddělených čárkami (CSV) pro aliasy. Změňte řádek tak, aby obsahoval čtyři hodnoty oddělené čárkami. Pokud samotný text hodnoty obsahuje čárku, musí být hodnota obsažena v uvozovkách. + + + Alias nelze importovat, protože číslo řádku {1} v souboru {0} obsahuje možnost, která nebyla rozpoznána pro aliasy. Změňte soubor tak, aby obsahoval platné možnosti. + + + Tento příkaz nemůže najít odpovídající alias, protože alias s {0} {1} neexistuje. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertFromStringData.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertFromStringData.cs.resx new file mode 100644 index 00000000000..2a10c309c52 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertFromStringData.cs.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 + + + Datový řádek {0} není ve formátu name=value. + + + Datová položka {1} na řádku {0} je již definována. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertHTMLStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertHTMLStrings.cs.resx new file mode 100644 index 00000000000..1eebd695779 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertHTMLStrings.cs.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 + + + Povolené meta vlastnosti jsou content-type, default-style, application-name, author, description, generator, keywords, x-ua-compatible a viewport. Meta pár {0} a {1} nemusí fungovat správně. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertMarkdownStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertMarkdownStrings.cs.resx new file mode 100644 index 00000000000..523a392e975 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ConvertMarkdownStrings.cs.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 + + + Typ vstupního objektu {0} je neplatný. + + + Jsou podporovány pouze cesty poskytovatele FileSystem. Cesta k souboru {0} se nepodporuje. + + + Vlastnost {0} zadaného objektu má hodnotu null nebo je prázdná. + + + Neplatný název sady parametrů: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/CsvCommandStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/CsvCommandStrings.cs.resx new file mode 100644 index 00000000000..8306588baaf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/CsvCommandStrings.cs.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 + + + Obsah CSV nejde přidat do následujícího souboru: {1}. Přidávaný objekt nemá vlastnost odpovídající následujícímu sloupci: {0}. Chcete-li pokračovat i s neodpovídajícími vlastnostmi, přidejte parametr -Force a spusťte příkaz znovu. + {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. + + + + Musíte zadat parametr -UseQuotes nebo -QuoteFields, ale ne oba. + + + Musíte zadat parametr -Path nebo -LiteralPath, ale ne oba. + + + Jedno nebo více záhlaví nebylo zadaných. Místo všech chybějících záhlaví se použily výchozí názvy začínající písmenem H. + + + FileName je povinný parametr. + + + Metoda ReconcilePreexistingPropertyNames se má volat jen při přidávání. + + + Metoda ReconcilePreexistingPropertyNames se má volat jen po úspěšném načtení existujících názvů vlastností. + + + Metoda BuildPropertyNames se má u každé instance rutiny volat jen jednou. + + + Hierarchie typů nesmí obsahovat hodnoty null. + + + Bylo dosaženo konce souboru. + + + Musíte zadat parametr -Append nebo -NoHeader, ale ne oba. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/Debugger.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/Debugger.cs.resx new file mode 100644 index 00000000000..9065b98afbe --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/Debugger.cs.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 + + + Řádek nemůže být menší než 1. + + + Zarážka s ID {0} neexistuje. + + + Soubor {0} neexistuje. + + + V souboru {0} nelze nastavit zarážku. Platné jsou pouze soubory *.ps1 a *.psm1. + + + Ladění není ve vzdálených relacích podporováno. + + + Nelze nastavit zarážku. Jazykový režim této relace není kompatibilní se systémovým jazykovým režimem. + + + Zarážky nelze nastavit ve vzdálené relaci, protože aktuální hostitel nepodporuje vzdálené ladění. + + + Pomocí této rutiny nelze ladit výchozí hostitelské prostředí runspace. Chcete-li ladit výchozí prostředí runspace, použijte běžné příkazy ladění hostitele. + + + Nelze ladit prostředí runspace. Hostitel nemá ladicí program. Zkuste ladit prostředí runspace v konzole PowerShellu nebo ve Visual Studio Code, které mají integrované ladicí programy. + + + Nelze ladit prostředí runspace. Hostitel nebo jeho uživatelské rozhraní nejsou k dispozici. Ladicí program vyžaduje hostitele a uživatelské rozhraní hostitele. + + + Bylo nalezeno více než jedno prostředí runspace. Současně lze ladit pouze jedno prostředí runspace. + + + Chcete-li ukončit relaci ladění, zadejte na příkazovém řádku ladicího programu příkaz Detach, případně stiskněte Ctrl+C. + + + Příkaz nebo skript byl dokončen. + + + Laděné prostředí runspace: {0} + + + Možnosti ladění prostředí runspace {0} nelze nastavit, protože není ve stavu Opened (Otevřeno). + + + Možnosti ladění pro proces {0} se nepodařilo trvale uložit. + + + Pro prostředí runspace {0} nebyl nalezen žádný ladicí program. + + + Nebylo nalezeno žádné prostředí runspace. + + + Rutina Wait-Debugger byla volána na řádku {0} v {1}. + + + Zarážku přidruženou k jinému prostředí runspace nelze aktualizovat, protože neexistuje žádné prostředí runspace s ID instance {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/EventingStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/EventingStrings.cs.resx new file mode 100644 index 00000000000..3668e81183b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/EventingStrings.cs.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 + + + Událost s identifikátorem zdroje {0} neexistuje. + + + Událost s identifikátorem {0} neexistuje. + + + Odběr události s identifikátorem zdroje {0} neexistuje. + + + Odběr události s identifikátorem {0} neexistuje. + + + Odběr události: {0} + + + Událost „{0}“ + + + Pro nepřesměrované události musí být zadána akce. + + + Odhlásit odběr + + + Odebrat + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/FormatAndOut_out_gridview.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/FormatAndOut_out_gridview.cs.resx new file mode 100644 index 00000000000..edeed8ec053 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/FormatAndOut_out_gridview.cs.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 + + + Out-GridView nepodporuje tento formát dat. + + + Microsoft .NET Framework 4.5 byl nainstalován v době, kdy byla spuštěna jedna nebo více relací PowerShellu. Chcete-li použít rutinu {0}, zavřete všechna okna PowerShellu a potom otevřete nové okno PowerShellu. + + + Typ + + + Hodnota + + + Index + + + Příkaz s názvem {0} nebyl nalezen. + + + Byl nalezen více než jeden příkaz s názvem {0}. Spusťte {1} bez parametrů a potom zadáním {0} vyfiltrujte výsledky. + + + Do vstupní vyrovnávací paměti konzoly nelze zapisovat. + + + {0} musí být menší než {1}. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetFormatDataStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetFormatDataStrings.cs.resx new file mode 100644 index 00000000000..90c9780343a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetFormatDataStrings.cs.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 + + + Probíhá zpracování definice zobrazení {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetMember.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetMember.cs.resx new file mode 100644 index 00000000000..0ac872df5d0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetMember.cs.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 + + + Pro rutinu Get-Member musíte zadat objekt. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetRandomCommandStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetRandomCommandStrings.cs.resx new file mode 100644 index 00000000000..8a4f4972027 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetRandomCommandStrings.cs.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 + + + Hodnota maxValue musí být větší než nula. + + + Minimální hodnota ({0}) nemůže být větší nebo rovna maximální hodnotě ({1}). + + + Hodnota minValue nemůže být větší než hodnota maxValue. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetUptimeStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetUptimeStrings.cs.resx new file mode 100644 index 00000000000..fd5946bb3e5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/GetUptimeStrings.cs.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 + + + Platforma není podporována (System.Diagnostics.Stopwatch.IsHighResolution má hodnotu false). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/HostStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/HostStrings.cs.resx new file mode 100644 index 00000000000..4e2f0f729ad --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/HostStrings.cs.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 + + + Barvu nelze zpracovat, protože {0} není platná barva. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/HttpCommandStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/HttpCommandStrings.cs.resx new file mode 100644 index 00000000000..7b764b1e15e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/HttpCommandStrings.cs.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 + + + Tento příkaz nelze dokončit z důvodu následující chyby: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ImplicitRemotingStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ImplicitRemotingStrings.cs.resx new file mode 100644 index 00000000000..abf17af3591 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ImplicitRemotingStrings.cs.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 vrácená vzdáleným příkazem {0} nejsou v očekávaném formátu. + + + Rutina {0} vyžaduje ve vzdálené relaci následující příkazy: Get-Command, Get-FormatData a Select-Object. Používají se následující příkazy, ale volitelné: Get-Help a Measure-Object. Ověřte, zda vzdálená relace obsahuje požadované příkazy, a akci opakujte. + + + Spuštění příkazu {0} ve vzdálené relaci oznámilo následující chybu: {1}. + + + Spuštění příkazu {0} ve vzdálené relaci nevrátilo žádné výsledky. + + + K tomuto modulu implicitní vzdálené komunikace nebyla přidružena žádná relace. + + + Vzdálený alias {0} nelze přeložit. + + + Vytvoření proxy serveru pro příkaz {0} bylo přeskočeno, protože název neodpovídá hodnotě parametru Name. + + + Definice rozšířeného typu byla pro typ {0} vynechána, protože jeho název neodpovídá hodnotě parametru FormatTypeName. + + + Vytvoření proxy serveru pro příkaz {0} bylo přeskočeno, protože prostředí PowerShell nemohlo ověřit bezpečnost názvu příkazu. + + + Vytvoření proxy serveru bylo pro následující příkaz přeskočeno: {0}, protože by stínoval existující místní příkaz. Pokud chcete stínovat existující místní příkazy, použijte parametr AllowClobber. + + + Nebyly vytvořeny žádné proxy pro příkazy, protože všechny požadované vzdálené příkazy by stínovaly existující místní příkazy. Pokud chcete stínovat existující místní příkazy, použijte parametr AllowClobber. + + + Implicitní vzdálená komunikace pro {0} + + + Událost implicitní vzdálené komunikace (ID relace: {0}; ID obslužné rutiny události: {1}) + + + Modul implicitní vzdálené komunikace + + + vygenerováno {0} + + + od rutiny {0} + + + Vyvoláno s následujícím příkazovým řádkem: {0} + + + Volitelný parametr, který se dá použít k určení relace, na které tento modul proxy serveru funguje + + + Vytváří se nová relace pro implicitní vzdálenou komunikaci příkazu {{0}}... + + + Relace pro modul implicitní vzdálené komunikace v {{0}} + + + Vytváření modulu implicitní vzdálené komunikace... + + + Načítání informací o příkazu ze vzdálené relace... + + + Načítání informací o příkazu ze vzdálené relace... Přijaté příkazy: {0} + + + Načítají se informace o formátování a výstupu ze vzdálené relace... + + + Načítají se informace o formátování a výstupu ze vzdálené relace... Přijaté objekty: {0} + + + Dokončeno. + + + Žádost o přihlašovací údaje k PowerShellu + + + Zadejte vaše přihlašovací údaje pro {0}. + + + Zadejte přihlašovací údaje proxy serveru HTTP, které se používají pro následující připojení: {0} + + + Příkazy, které jsou k dispozici v nové vzdálené relaci, se liší od příkazů dostupných při vytvoření modulu implicitní vzdálené komunikace. Zvažte opětovné vytvoření modulu pomocí rutiny Export-PSSession. + + + Soubory nelze načíst, protože spuštěné skripty jsou v tomto systému zakázány. Zadejte platný certifikát, kterým chcete podepsat soubory. + + + Soubor {0} se nepodařilo podepsat. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ImportLocalizedDataStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ImportLocalizedDataStrings.cs.resx new file mode 100644 index 00000000000..de0933c01d8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/ImportLocalizedDataStrings.cs.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 + + + Datový soubor {0} se nenašel. + + + Parametr FileName nebyl zadaný. Parametr FileName je povinný, pokud se Import-LocalizedData nevolá ze souboru skriptu. + + + Při otevírání datového souboru {0} v PowerShellu došlo k následující chybě: +{1}. + + + Při načítání datového souboru skriptu {0} v PowerShellu došlo k následující chybě: +{1}. + + + Argument parametru FileName nesmí obsahovat cestu. + + + Datový soubor PowerShellu {0} se nenašel v adresáři {1} ani v žádném nadřazeném adresáři jazykové verze. + + + Lokalizovaná data nejde importovat. V tomto jazykovém režimu není povolená definice dalších podporovaných příkazů. + + + Název BindingVariable {0} není platný. + + + Rutina Import-LocalizedData + + + V režimu ConstrainedLanguage nebudou povolené další podporované příkazy zadané parametrem SupportedCommand. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/MatchStringStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/MatchStringStrings.cs.resx new file mode 100644 index 00000000000..e7fbe08564f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/MatchStringStrings.cs.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 + + + Soubor nejde otevřít, protože aktuální poskytovatel ({0}) neumí otevírat soubory. + + + Soubor {0} nejde přečíst: {1} + + + Možnost Context není platná při hledání výsledků předaných kanálem z výstupu Select-String. + + + Řetězec {0} není platný regulární výraz: {1} + + + Parametr -Culture musíte zadat jen společně s parametrem -SimpleMatch. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/MeasureObjectStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/MeasureObjectStrings.cs.resx new file mode 100644 index 00000000000..5da93bbc568 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/MeasureObjectStrings.cs.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 + + + Vlastnost {0} nebyla nalezena ve vstupu pro žádné objekty. + + + Vstupní objekt {0} není číselný. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/NewObjectStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/NewObjectStrings.cs.resx new file mode 100644 index 00000000000..53adb99a35e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/NewObjectStrings.cs.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 + + + Konstruktor nebyl nalezen. Nelze najít odpovídající konstruktor pro typ {0}. + + + Nelze najít typ [{0}]: Ověřte, že je načteno sestavení obsahující tento typ. + + + Nelze načíst typ modelu COM {0}. + + + Objekt zapsaný do kanálu je instancí typu {0} z primárního sestavení komponenty pro interoperabilitu. Pokud tento typ zpřístupňuje jiné členy než členy IDispatch, skripty napsané pro práci s tímto objektem nemusí fungovat, pokud není nainstalováno primární sestavení pro interoperabilitu. + + + Člen {1} nebyl pro zadaný objekt {2} nalezen. + + + Zadaná hodnota není platná nebo je vlastnost jen pro čtení. Změňte hodnotu a zkuste to znovu. + + + Vytváření instancí atributů a delegovaných typů Windows RT není podporováno. + + + Nelze vytvořit instance typu podobného ByRef {0}. PowerShell nepodporuje typy podobné ByRef. + + + Typ nelze vytvořit. V tomto jazykovém režimu se podporují jen základní typy. + + + Typ nelze vytvořit. V počítači uzamčeném zásadou jsou v jazykovém režimu {0} podporovány pouze základní typy. + + + Vytvoření typu rutiny New-Object + + + Typ {0} nebude vytvořen v režimu ConstrainedLanguage. + + + Vytvoření objektu COM rutiny New-Object + + + Objekt COM {0} nebude vytvořen v režimu ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/OutPrinterDisplayStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/OutPrinterDisplayStrings.cs.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/OutPrinterDisplayStrings.cs.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SelectObjectStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SelectObjectStrings.cs.resx new file mode 100644 index 00000000000..e23427cbe4e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SelectObjectStrings.cs.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 + + + Více výsledků nelze přejmenovat. + + + Vlastnost {0} nebyla nalezena. + + + Nelze rozbalit více vlastností. + + + Vlastnost nelze zpracovat, protože vlastnost {0} již existuje. + + + Vlastnost je prázdný blok skriptu a neposkytuje název. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SendMailMessageStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SendMailMessageStrings.cs.resx new file mode 100644 index 00000000000..34d7df9b9c3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SendMailMessageStrings.cs.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 + + + E-mail nejde odeslat, protože nebyl zadaný žádný server SMTP. Server SMTP musíte zadat pomocí parametru SmtpServer nebo proměnné $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SortObjectStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SortObjectStrings.cs.resx new file mode 100644 index 00000000000..eb75ae68c52 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/SortObjectStrings.cs.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} nelze nalézt v InputObject. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/StartSleepStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/StartSleepStrings.cs.resx new file mode 100644 index 00000000000..5d05191e8ba --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/StartSleepStrings.cs.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 + + + Hodnota parametru -Duration nesmí překročit hodnotu {0}, zadaná hodnota byla {1}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/TestJsonCmdletStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/TestJsonCmdletStrings.cs.resx new file mode 100644 index 00000000000..5d764487240 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/TestJsonCmdletStrings.cs.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 + + + Schéma JSON nejde parsovat. + + + JSON nejde parsovat. + + + JSON není platný se schématem: {0} v {1}. + + + Nelze otevřít soubor schématu JSON: {0} + + + Schéma identifikátoru URI {0} není podporováno. Povoleny jsou pouze identifikátory URI protokolu HTTP(S) a místního systému souborů. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/TraceCommandStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/TraceCommandStrings.cs.resx new file mode 100644 index 00000000000..e41f3e1c4c2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/TraceCommandStrings.cs.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 + + + Výstup trasování jde zapisovat jen do systému souborů. Cesta {0} odkazovala na cestu poskytovatele {1}. + + + Výstup trasování jde zapisovat jen do jednoho souboru. Cesta {0} se přeložila na více než jeden soubor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UnblockFileStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UnblockFileStrings.cs.resx new file mode 100644 index 00000000000..6c8706b9efd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UnblockFileStrings.cs.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 + + + Rutina nepodporuje Linux. + + + Při pokusu o odblokování souboru {0} došlo k chybě. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UpdateDataStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UpdateDataStrings.cs.resx new file mode 100644 index 00000000000..982e4931fcd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UpdateDataStrings.cs.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 + + + Soubor nelze otevřít, protože aktuálním zprostředkovatelem je {0} a tento příkaz vyžaduje soubor. + + + Soubor {0} nelze přečíst, protože nemá příponu názvu souboru {1}. + + + Aktualizovat TypeData + + + Aktualizovat FormatData + + + FileName: {0} + + + Člen typu {0} se nedá aktualizovat. Pro parametr MemberType zadejte jiný typ. + + + Parametr {0} je pro typ {1} povinný. Zadejte prosím parametr {0}. + + + Parametr {0} nesmí být pro člen typu {1} null ani prázdný řetězec. Při aktualizaci tohoto typu členu zadejte pro parametr {0} hodnotu, která není null. + + + Parametr {0} není pro člen typu {1} nutný a neměl by být zadán. Při aktualizaci tohoto typu členu nezadávejte parametr {0}. + + + Pro aktualizaci typu {0} není zadán žádný člen. + + + Název cílového typu nesmí být null, prázdný ani obsahovat pouze prázdné znaky. + + + Parametry Value a SecondValue nesmí být pro člen typu {0} současně null. Zadejte pro jeden z těchto dvou parametrů hodnotu, která není null. + + + Lze zadat pouze jeden typ členu. Zadané typy členů: {0}. Aktualizujte typ pouze s jedním typem členu. + + + Parametry MemberName, Value a SecondValue nelze zadat bez parametru MemberType. + + + Odebrat TypeData + + + Název typu, který bude odebrán: {0} + + + Typ, který chcete aktualizovat: {0} + + + Odebrat typ souboru + + + Soubor {0} není importován do aktuální relace. + + + Aktualizace dat formátu nejsou v tomto prostředí runspace povoleny. Při vytváření prostředí runspace je vlastnost DisableFormatUpdates nastavena na hodnotu True. + + + Data formátu nelze aktualizovat pomocí instance FormatTable. + + + Data typu nelze aktualizovat pomocí instance TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UpdateListStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UpdateListStrings.cs.resx new file mode 100644 index 00000000000..58f81044229 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UpdateListStrings.cs.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 + + + Vlastnost {0} se u tohoto objektu nenašla + + + Když zadáte parametr InputObject, musíte zadat také parametr Property. + + + Když zadáte parametr Property, musíte zadat také parametr InputObject. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UtilityCommonStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UtilityCommonStrings.cs.resx new file mode 100644 index 00000000000..9dff16de405 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/UtilityCommonStrings.cs.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 + + + Objekt {2} obsahuje jednu nebo více neplatných výjimek. + + + Tento příkaz nejde spustit, protože cesta k souboru {0} není platná. Zadejte platnou cestu k souboru a spusťte příkaz znovu. + + + Tento příkaz nejde spustit, protože hodnota {0} je prázdná. Zadejte CSSUri a spusťte příkaz znovu. + + + Soubor nejde otevřít, protože aktuální poskytovatel ({0}) neumí otevírat soubory. + + + Tento příkaz nejde spustit, protože hodnota předpony v parametru Namespace má hodnotu null. Zadejte platnou hodnotu předpony a spusťte příkaz znovu. + + + Objekty seskupené podle této vlastnosti nejde rozbalit, protože se opakuje klíč. Zadejte platnou hodnotu vlastnosti a zkuste to znovu. + + + Tento příkaz není v tomto operačním systému podporovaný. + + + Soubor {0} nejde přečíst: {1} + + + Vstup typu {0} nejde převést na šestnáctkovou hodnotu. Chcete-li zobrazit šestnáctkové formátování jeho řetězcové reprezentace, předejte ho před rutinou Format-Hex prostřednictvím kanálu rutině Out-String. + + + Zadaná cesta {0} není podporovaná. Tento příkaz podporuje jen cesty poskytovatele FileSystem. + + + Cesta: + + + Příkaz nejde spustit, protože parametr AsString vyžaduje zadání parametru AsHashtable. + + + Příkaz nejde spustit, protože při použití parametru AsHashTable s více než jednou vlastností je nutné přidat parametr AsString. + + + Cesta {0} se nenašla, protože neexistuje. + + + Značku {0} nejde použít. Předpona PS je rezervovaná. + + + Soubor {0} se nepovedlo analyzovat jako datový soubor PowerShellu. + + + Z daného SDDL nejde vytvořit popisovač zabezpečení kvůli následující chybě: {0} + + + Rutina Invoke-Expression + + + Blok skriptu rutiny Invoke-Expression se spustí v režimu ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/VariableCommandStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/VariableCommandStrings.cs.resx new file mode 100644 index 00000000000..3497e287da1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/VariableCommandStrings.cs.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 + + + Nastavit proměnnou + + + Název: {0} Hodnota: {1} + + + Použijte jednu proměnnou místo kolekce + + + Nová proměnná + + + Název: {0} Hodnota: {1} + + + Odebrat proměnnou + + + Název: {0} + + + Vymazat proměnnou + + + Název: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WebCmdletStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WebCmdletStrings.cs.resx new file mode 100644 index 00000000000..89eaa6df2fe --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WebCmdletStrings.cs.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 + + + Přístup k cestě {0} se zamítl. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WriteErrorStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WriteErrorStrings.cs.resx new file mode 100644 index 00000000000..5c1c39539ba --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WriteErrorStrings.cs.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 + + + Rutina Write-Error ohlásila chybu. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WriteProgressResourceStrings.cs.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WriteProgressResourceStrings.cs.resx new file mode 100644 index 00000000000..22fa2809b6b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/cs/WriteProgressResourceStrings.cs.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 popisující aktivitu, pro kterou se hlásí průběh + + + Text popisující aktuální stav aktivity, pro kterou se hlásí průběh + + + Zpracovávání + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/AddMember.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/AddMember.de.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/AddMember.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/AddTypeStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/AddTypeStrings.de.resx new file mode 100644 index 00000000000..6af9d2b3409 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/AddTypeStrings.de.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 + + + Der Quellcode wurde bereits kompiliert und geladen. + + + Der Typ kann nicht hinzugefügt werden. Die Endung „{0}“ wird nicht unterstützt. + + + Der Typ kann nicht hinzugefügt werden. Eingabedateien müssen alle die gleiche Dateiendung aufweisen. + + + Der Typ kann nicht hinzugefügt werden. Die Assembly „{0}“ wurde nicht gefunden. + + + Der Typ kann nicht hinzugefügt werden. Der Typname „{0}“ ist bereits vorhanden. + + + Die Ausgabeassembly kann nicht festgelegt werden. Der Pfad {0} wurde nicht in eine einzelne Datei aufgelöst. + + + Der Typ kann nicht hinzugefügt werden. Fehler bei der Kompilierung. + + + Der Typ kann nicht hinzugefügt werden. Der OutputType-Parameter erfordert, dass der OutputAssembly-Parameter angegeben wird. + + + Der Typ kann nicht hinzugefügt werden. Die Definition neuer Typen wird in diesem Sprachmodus nicht unterstützt. + + + Die angegebene Verweisassembly „{0}“ ist nicht erforderlich und wird ignoriert. + + + Die Assemblytypen „ConsoleApplication“ und „WindowsApplication“ werden derzeit nicht unterstützt. + + + Add-Type-Cmdlet + + + Das Add-Type-cmdlet ist im ConstrainedLanguage-Modus nicht zulässig. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/AliasCommandStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/AliasCommandStrings.de.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/AliasCommandStrings.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertFromStringData.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertFromStringData.de.resx new file mode 100644 index 00000000000..dc3ff5d1261 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertFromStringData.de.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 + + + Die Datenzeile „{0}“ weist nicht das Format „name=value“ auf. + + + Das Datenelement „{1}“ in Zeile „{0}“ ist bereits definiert. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertHTMLStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertHTMLStrings.de.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertHTMLStrings.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertMarkdownStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertMarkdownStrings.de.resx new file mode 100644 index 00000000000..f4957176502 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ConvertMarkdownStrings.de.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 + + + Der Typ des Eingabeobjekts „{0}“ ist ungültig. + + + Es werden nur FileSystem Provider-Pfade unterstützt. Der Dateipfad wird nicht unterstützt: „{0}“. + + + Die Eigenschaft {0} des angegebenen Objekts ist NULL oder leer. + + + Ungültiger Parametersatzname: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/CsvCommandStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/CsvCommandStrings.de.resx new file mode 100644 index 00000000000..b8f95b9e80a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/CsvCommandStrings.de.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 + + + CSV-Inhalt kann nicht an die folgende Datei angefügt werden: {1}. Das angefügte Objekt verfügt nicht über eine Eigenschaft, die der folgenden Spalte entspricht: {0}. Um mit nicht übereinstimmenden Eigenschaften fortzufahren, fügen Sie den -Force-Parameter hinzu, und wiederholen Sie dann den Befehl. + {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. + + + + Sie müssen entweder die Parameter -UseQuotes oder -QuoteFields angeben, aber nicht beides. + + + Sie müssen entweder die Parameter -Path oder -LiteralPath angeben, aber nicht beides. + + + Mindestens ein Header wurde nicht angegeben. Standardnamen, die mit „H“ beginnen, wurden anstelle fehlender Header verwendet. + + + FileName ist ein obligatorischer Parameter. + + + Die ReconcilePreexistingPropertyNames-Methode sollte nur beim Anfügen aufgerufen werden. + + + Die ReconcilePreexistingPropertyNames-Methode sollte nur aufgerufen werden, wenn bereits vorhandene Eigenschaftsnamen erfolgreich gelesen wurden. + + + Die BuildPropertyNames-Methode sollte nur einmal pro cmdlet-Instanz aufgerufen werden. + + + Die Typhierarchie darf keine NULL-Werte enthalten. + + + EOF ist erreicht. + + + Sie müssen entweder die Parameter -Append oder -NoHeader angeben, aber nicht beide. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/Debugger.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/Debugger.de.resx new file mode 100644 index 00000000000..f9593efbe5a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/Debugger.de.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}'. + + + Die Datei '{0}' ist nicht vorhanden. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/EventingStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/EventingStrings.de.resx new file mode 100644 index 00000000000..30f89eafe66 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/EventingStrings.de.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 + + + Das Ereignis mit dem Quellbezeichner „{0}“ ist nicht vorhanden. + + + Das Ereignis mit dem Bezeichner „{0}“ ist nicht vorhanden. + + + Das Ereignisabonnement mit dem Quellbezeichner „{0}“ ist nicht vorhanden. + + + Das Ereignisabonnement mit dem Bezeichner „{0}“ ist nicht vorhanden. + + + Ereignisabonnement „{0}“ + + + Ereignis „{0}“ + + + Für nicht weitergeleitete Ereignisse muss eine Aktion angegeben werden. + + + Abonnement kündigen + + + Entfernen + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/FormatAndOut_out_gridview.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/FormatAndOut_out_gridview.de.resx new file mode 100644 index 00000000000..4706e203e17 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/FormatAndOut_out_gridview.de.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 + + + Das Datenformat wird von Out-GridView nicht unterstützt. + + + Microsoft .NET Framework 4.5 wurde installiert, während mindestens eine PowerShell-Sitzung ausgeführt wurde. Schließen Sie zum Verwenden des {0} Cmdlets alle PowerShell-Fenster und öffnen Sie dann ein neues PowerShell-Fenster. + + + Typ + + + Wert + + + Index + + + Ein Befehl mit dem Namen „{0}“ wurde nicht gefunden. + + + Es wurden mehrere Befehle mit dem Namen „{0}“ gefunden. Starten Sie „{1}“ ohne Parameter und geben Sie dann „{0}“ ein, um die Ergebnisse zu filtern. + + + In den Konsoleneingabepuffer kann nicht geschrieben werden. + + + {0} muss kleiner als {1} sein. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetFormatDataStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetFormatDataStrings.de.resx new file mode 100644 index 00000000000..e3bfa4be97c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetFormatDataStrings.de.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 + + + Die Ansichtsdefinition „{0}“ wird verarbeitet + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetMember.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetMember.de.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetMember.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetRandomCommandStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetRandomCommandStrings.de.resx new file mode 100644 index 00000000000..3cf9f28e1a5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetRandomCommandStrings.de.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“ muss größer als Null sein. + + + Der Mindestwert ({0}) darf nicht größer oder gleich dem Höchstwert ({1}) sein. + + + „minValue“ darf nicht größer als maxValue sein. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetUptimeStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetUptimeStrings.de.resx new file mode 100644 index 00000000000..ec9afcfce05 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/GetUptimeStrings.de.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 + + + Die Plattform wird nicht unterstützt (System.Diagnostics.Stopwatch.IsHighResolution ist false). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/HostStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/HostStrings.de.resx new file mode 100644 index 00000000000..a8151e4a5cc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/HostStrings.de.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 + + + Die Farbe kann nicht verarbeitet werden, da {0} keine gültige Farbe ist. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/HttpCommandStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/HttpCommandStrings.de.resx new file mode 100644 index 00000000000..6cb7165bdae --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/HttpCommandStrings.de.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 + + + Dieser Befehl kann aufgrund des folgenden Fehlers nicht abgeschlossen werden: „{0}“. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/ImplicitRemotingStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ImplicitRemotingStrings.de.resx new file mode 100644 index 00000000000..d0b0f1b1979 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ImplicitRemotingStrings.de.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 + + + Die vom Remotebefehl {0} zurückgegebenen Daten haben nicht das erwartete Format. + + + Das Cmdlet {0} erfordert die folgenden Befehle in der Remotesitzung: Get-Command, Get-FormatData und Select-Object. Die folgenden Befehle werden verwendet, sind aber optional: Get-Help und Measure-Object. Überprüfen Sie, ob die Remotesitzung die erforderlichen Befehle enthält, und versuchen Sie es dann erneut. + + + Beim Ausführen des Befehls {0} in einer Remotesitzung wurde der folgende Fehler gemeldet: {1}. + + + Beim Ausführen des Befehls {0} in einer Remotesitzung wurden keine Ergebnisse zurückgegeben. + + + Diesem impliziten Remotingmodul wurde keine Sitzung zugeordnet. + + + Der Remotealias „{0}“ konnte nicht aufgelöst werden. + + + Die Proxyerstellung wurde für den Befehl „{0}“ übersprungen, da der Name nicht mit dem Wert des Parameters „Name“ übereinstimmte. + + + Die Definition des erweiterten Typs wurde für den Typ „{0}“ übersprungen, da sein Name nicht mit dem Wert des FormatTypeName-Parameters übereinstimmte. + + + Die Proxyerstellung wurde für den Befehl „{0}“ übersprungen, da PowerShell die Sicherheit des Befehlsnamens nicht überprüfen konnte. + + + Die Proxyerstellung wurde für den folgenden Befehl „{0}“ übersprungen, da er einen vorhandenen lokalen Befehl überschatten würde. Verwenden Sie den AllowClobber-Parameter, wenn Sie vorhandene lokale Befehle überschatten möchten. + + + Es wurden keine Befehlsproxys erstellt, da alle angeforderten Remotebefehle vorhandene lokale Befehle überschatten würden. Verwenden Sie den AllowClobber-Parameter, wenn Sie vorhandene lokale Befehle überschatten möchten. + + + Implizites Remoting für {0} + + + Implizites Remotingereignis (Sitzungs-ID: {0}; Ereignishandler-ID: {1}) + + + Implizites Remotingmodul + + + generiert am {0} + + + nach {0} Cmdlet + + + Aufruf mit der folgenden Befehlszeile: {0} + + + Optionaler Parameter, der verwendet werden kann, um die Sitzung anzugeben, in der dieses Proxymodul funktioniert + + + Eine neue Sitzung für implizites Remoting des Befehls „{{0}}“ wird erstellt ... + + + Sitzung für implizites Remotingmodul bei {{0}} + + + Implizites Remotingmodul wird erstellt ... + + + Befehlsinformationen aus Remotesitzung werden abgerufen ... + + + Befehlsinformationen aus Remotesitzung werden abgerufen ... {0} Befehle empfangen + + + Formatierungs- und Ausgabeinformationen aus Remotesitzung werden abgerufen ... + + + Formatierungs- und Ausgabeinformationen aus Remotesitzung werden abgerufen... {0} Objekte empfangen + + + Abgeschlossen. + + + PowerShell-Anmeldeinformationsanforderung + + + Geben Sie Ihre Anmeldeinformationen für {0} ein. + + + Geben Sie die HTTP-Proxyanmeldeinformationen ein, die für die folgende Verbindung verwendet werden: {0} + + + Befehle, die in der neuen Remotesitzung verfügbar sind, unterscheiden sich von denen, die beim Erstellen des impliziten Remotingmoduls verfügbar waren. Ziehen Sie in Betracht, das Modul mit dem Cmdlet Export-PSSession erneut zu erstellen. + + + Dateien können nicht geladen werden, weil das Ausführen von Skripts auf diesem System deaktiviert ist. Geben Sie ein gültiges Zertifikat an, mit dem die Dateien signiert werden sollen. + + + Die Datei {0} konnte nicht signiert werden. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/ImportLocalizedDataStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ImportLocalizedDataStrings.de.resx new file mode 100644 index 00000000000..e40ef7210f5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/ImportLocalizedDataStrings.de.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 + + + Die Datei „{0}“ wurde nicht gefunden. + + + Der FileName-Parameter wurde nicht angegeben. Der FileName-Parameter ist erforderlich, wenn „Import-LocalizedData“ nicht aus einer Skriptdatei aufgerufen wird. + + + Der folgende Fehler ist aufgetreten, während PowerShell die Datendatei „{0}“ geöffnet hat: +{1}. + + + Der folgende Fehler ist aufgetreten, während PowerShell die Skriptdatendatei „{0}“ geladen hat: +{1}. + + + Das Argument für den Parameter „FileName“ darf keinen Pfad enthalten. + + + Die PowerShell-Datendatei „{0}“ konnte weder im Verzeichnis „{1}“ noch in übergeordneten Kulturverzeichnissen gefunden werden. + + + Lokalisierte Daten können nicht importiert werden. Die Definition zusätzlicher unterstützter Befehle ist in diesem Sprachmodus nicht zulässig. + + + Der Name der BindingVariable „{0}“ ist ungültig. + + + Cmdlet „Import-LocalizedData“ + + + Zusätzliche unterstützte Befehle (über den Parameter „SupportedCommand“) sind im Modus „ConstrainedLanguage“ nicht zulässig. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/MatchStringStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/MatchStringStrings.de.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/MatchStringStrings.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/MeasureObjectStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/MeasureObjectStrings.de.resx new file mode 100644 index 00000000000..a02ad464a99 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/MeasureObjectStrings.de.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 + + + Die Eigenschaft „{0}“ kann in der Eingabe bei keinem Objekt gefunden werden. + + + Das Eingabeobjekt „{0}“ ist nicht numerisch. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/NewObjectStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/NewObjectStrings.de.resx new file mode 100644 index 00000000000..7d4cc78209a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/NewObjectStrings.de.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 + + + Es wurde kein Konstruktor gefunden. Für den Typ „{0}“ wurde kein geeigneter Konstruktor gefunden. + + + Der Typ [{0}] wurde nicht gefunden: Überprüfen Sie, ob die Assembly geladen ist, die diesen Typ enthält. + + + Der COM-Typ „{0}“ kann nicht geladen werden. + + + Das in die Pipeline geschriebene Objekt ist eine Instanz des Typs „{0}“ aus der primären Interoperabilitätsassembly der Komponente. Wenn dieser Typ andere Member als die IDispatch-Member bereitstellt, funktionieren Skripts, die für dieses Objekt geschrieben wurden, möglicherweise nicht, wenn die primäre Interoperabilitätsassembly nicht installiert ist. + + + Das Element „{1}“ wurde für das angegebene {2} -Objekt nicht gefunden. + + + Der angegebene Wert ist ungültig, oder die Eigenschaft ist schreibgeschützt. Ändern Sie den Wert, und versuchen Sie es dann erneut. + + + Das Erstellen von Instanzen von Attributen und delegierten Windows-Typen wird nicht unterstützt. + + + Es können keine Instanzen des ByRef-ähnlichen Typs „{0}“ erstellt werden. ByRef-ähnliche Typen werden in PowerShell nicht unterstützt. + + + Der Typ kann nicht erstellt werden. In diesem Sprachmodus werden nur Kerntypen unterstützt. + + + Der Typ kann nicht erstellt werden. Im {0}-Sprachmodus auf einem per Richtlinie gesperrten Computer werden nur Kerntypen unterstützt. + + + Typerstellung mit dem Cmdlet „New-Object“ + + + Der Typ „{0}“ wird im ConstrainedLanguage-Modus nicht erstellt. + + + COM-Objekterstellung mit dem New-Object-Cmdlet + + + Das COM-Objekt „{0}“ wird im ConstrainedLanguage-Modus nicht erstellt. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/OutPrinterDisplayStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/OutPrinterDisplayStrings.de.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/OutPrinterDisplayStrings.de.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/SelectObjectStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/SelectObjectStrings.de.resx new file mode 100644 index 00000000000..bdd62150f75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/SelectObjectStrings.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/SendMailMessageStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/SendMailMessageStrings.de.resx new file mode 100644 index 00000000000..795e1f8b017 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/SendMailMessageStrings.de.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 + + + Die E-Mail kann nicht gesendet werden, da kein SMTP-Server angegeben wurde. Sie müssen einen SMTP-Server angeben, indem Sie entweder den SmtpServer-Parameter oder die $PSEmailServer Variable verwenden. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/SortObjectStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/SortObjectStrings.de.resx new file mode 100644 index 00000000000..5a9d77c8078 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/SortObjectStrings.de.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}“ wurde in „InputObject“ nicht gefunden. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/StartSleepStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/StartSleepStrings.de.resx new file mode 100644 index 00000000000..b7f64978cbf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/StartSleepStrings.de.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 + + + Der Parameterwert „-Duration“ darf „{0}“ nicht überschreiten. Der angegebene Wert war „{1}“. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/TestJsonCmdletStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/TestJsonCmdletStrings.de.resx new file mode 100644 index 00000000000..03aebe59102 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/TestJsonCmdletStrings.de.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 + + + Das JSON-Schema kann nicht analysiert werden. + + + Der JSON-Code kann nicht analysiert werden. + + + Der JSON-Code ist mit dem Schema ungültig: {0} bei „{1}“ + + + Die JSON-Schemadatei kann nicht geöffnet werden: {0} + + + Das URI-Schema „{0}“ wird nicht unterstützt. Nur HTTP(S) und lokale Dateisystem-URIs sind zulässig. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/TraceCommandStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/TraceCommandStrings.de.resx new file mode 100644 index 00000000000..298837b2c29 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/TraceCommandStrings.de.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 + + + Die Ablaufverfolgungsausgabe kann nur in das Dateisystem geschrieben werden. Der Pfad „{0}“ verweist auf einen „{1}“-Anbieterpfad. + + + Die Ablaufverfolgungsausgabe kann nur in eine einzelne Datei geschrieben werden. Der Pfad „{0}“ wurde in mehr als eine Datei aufgelöst. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/UnblockFileStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UnblockFileStrings.de.resx new file mode 100644 index 00000000000..b48d9adbba4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UnblockFileStrings.de.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 + + + Linux wird vom cmdlet nicht unterstützt. + + + Fehler beim Aufheben der Blockierung von {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/UpdateDataStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UpdateDataStrings.de.resx new file mode 100644 index 00000000000..2524db1af95 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UpdateDataStrings.de.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 + + + Die Datei kann nicht geöffnet werden, da der aktuelle Anbieter „{0}“ ist, und dieser Befehl eine Datei erfordert. + + + Die Datei „{0}“ kann nicht gelesen werden, da sie nicht die Dateinamenerweiterung „{1}“ hat. + + + TypeData aktualisieren + + + FormatData aktualisieren + + + FileName: {0} + + + Ein Member vom Typ „{0}“ kann nicht aktualisiert werden. Geben Sie für den Parameter MemberType einen anderen Typ an. + + + Der {0}-Parameter ist für den Typ „{1}“ erforderlich. Geben Sie den {0}-Parameter an. + + + Der {0}-Parameter darf für einen Member vom Typ „{1}“ nicht NULL oder eine leere Zeichenfolge sein. Geben Sie beim Aktualisieren dieses Membertyps für den {0}-Parameter einen Wert ungleich NULL an. + + + Der {0}-Parameter ist für einen Member vom Typ „{1}“ nicht erforderlich und sollte nicht angegeben werden. Geben Sie den {0}-Parameter nicht an, wenn Sie diesen Membertyp aktualisieren. + + + Für die Aktualisierung des Typs „{0}“ ist kein Member angegeben. + + + Der Zieltypname darf nicht NULL oder leer sein oder nur Leerzeichen enthalten. + + + Die Value- und SecondValue-Parameter dürfen für einen Member vom Typ „{0}“ nicht beide NULL sein. Geben Sie für einen der beiden Parameter einen Wert ungleich NULL an. + + + Es kann nur ein Membertyp angegeben werden. Die angegebenen Membertypen sind: „{0}“. Aktualisieren Sie den Typ nur mit einem Membertyp. + + + Die MemberName-, Value- und SecondValue-Parameter können nicht ohne den MemberType-Parameter angegeben werden. + + + TypeData entfernen + + + Name des zu entfernenden Typs: {0} + + + Zu aktualisierender Typ: {0} + + + Typdatei entfernen + + + Die Datei „{0}“ wird nicht in die aktuelle Sitzung importiert. + + + Das Aktualisieren von Formatdaten ist in diesem Runspace nicht zulässig. Die Eigenschaft „DisableFormatUpdates“ wird beim Erstellen des Runspace auf TRUE festgelegt. + + + Die Formatdaten können nicht mithilfe einer Instanz der FormatTable aktualisiert werden. + + + Die Typdaten können nicht mithilfe einer TypeTable-Instanz aktualisiert werden. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/UpdateListStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UpdateListStrings.de.resx new file mode 100644 index 00000000000..9f0546e02e1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UpdateListStrings.de.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 + + + Die Eigenschaft „{0}“ kann in diesem Objekt nicht gefunden werden. + + + Sie müssen den Parameter Property angeben, wenn der Parameter InputObject angegeben wird. + + + Sie müssen den Parameter InputObject angeben, wenn der Parameter Property angegeben wird. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/UtilityCommonStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UtilityCommonStrings.de.resx new file mode 100644 index 00000000000..eb88c6e1706 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/UtilityCommonStrings.de.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} weist mindestens eine ungültige Ausnahme auf. + + + Dieser Befehl kann nicht ausgeführt werden, da der Dateipfad „{0}“ ungültig ist. Geben Sie einen gültigen Dateipfad an, und führen Sie dann den Befehl aus. + + + Dieser Befehl kann nicht ausgeführt werden, da „{0}“ leer oder nicht ausgefüllt ist. Geben Sie CSSUri an, und führen Sie den Befehl aus. + + + Die Datei kann nicht geöffnet werden, da der aktuelle Anbieter ({0}) keine Dateien öffnen kann. + + + Dieser Befehl kann nicht ausgeführt werden, da der Präfixwert im Namespace-Parameter Null ist. Geben Sie einen gültigen Wert für das Präfix an, und führen Sie den Befehl dann erneut aus. + + + Die nach dieser Eigenschaft gruppierten Objekte können nicht erweitert werden, da eine Schlüsselduplizierung vorliegt. Geben Sie einen gültigen Wert für die Eigenschaft an, und wiederholen Sie dann den Vorgang. + + + Der Befehl wird unter diesem Betriebssystem nicht unterstützt. + + + Die Datei „{0}“ kann nicht gelesen werden: {1} + + + Die Eingabe vom Typ „{0}“ kann nicht in hexadezimale Eingaben konvertiert werden. Um die hexadezimale Formatierung der Zeichenfolgendarstellung anzuzeigen, übergeben Sie sie an das Out-String-cmdlet, bevor Sie sie an Format-Hex weiterleiten. + + + Der angegebene Pfad „{0}“ wird nicht unterstützt. Dieser Befehl unterstützt nur die FileSystem Provider-Pfade. + + + Pfad: + + + Der Befehl kann nicht ausgeführt werden, da der AsString-Parameter erfordert, dass Sie den AsHashtable-Parameter angeben. + + + Der Befehl kann nicht ausgeführt werden, da für die Verwendung des AsHashTable-Parameters mit mehreren Eigenschaften der AsString-Parameter hinzugefügt werden muss. + + + Der Pfad "{0}" wurde nicht gefunden, da er nicht vorhanden ist. + + + Das Tag „{0}“ kann nicht verwendet werden. Das Präfix „PS“ ist reserviert. + + + Die Datei „{0}“ konnte nicht als PowerShell-Datendatei analysiert werden. + + + Aufgrund des folgenden Fehlers kann keine Sicherheitsbeschreibung aus der angegebenen SDDL erstellt werden: {0} + + + Invoke-Expression Cmdlet + + + Der Skriptblock des cmdlets „Invoke-Expression“ wird im ConstrainedLanguage-Modus ausgeführt. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/VariableCommandStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/VariableCommandStrings.de.resx new file mode 100644 index 00000000000..8d2587c1efe --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/VariableCommandStrings.de.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 + + + Variable festlegen + + + Name: {0} Wert: {1} + + + Verwenden einer einzelnen Variablen anstelle einer Auflistung + + + Neue Variable + + + Name: {0} Wert: {1} + + + Variable entfernen + + + Name: {0} + + + Variable löschen + + + Name: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/WebCmdletStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/WebCmdletStrings.de.resx new file mode 100644 index 00000000000..2e7d6752493 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/WebCmdletStrings.de.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 + + + Der Zugriff auf den Pfad "{0}" wird verweigert. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/WriteErrorStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/WriteErrorStrings.de.resx new file mode 100644 index 00000000000..1a196ff7e9d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/WriteErrorStrings.de.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 + + + „Das Cmdlet Write-Error hat einen Fehler gemeldet.“ + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/de/WriteProgressResourceStrings.de.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/de/WriteProgressResourceStrings.de.resx new file mode 100644 index 00000000000..c25dea6cf0d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/de/WriteProgressResourceStrings.de.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 zur Beschreibung der Aktivität, für die der Fortschritt gemeldet wird. + + + Text, der den aktuellen Status der Aktivität beschreibt, für die der Fortschritt gemeldet wird. + + + Wird verarbeitet + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/AddMember.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/AddMember.es.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/AddMember.es.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/AddTypeStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/AddTypeStrings.es.resx new file mode 100644 index 00000000000..cf65608761a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/AddTypeStrings.es.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 + + + El código fuente ya se compiló y cargó. + + + No se puede agregar el tipo. No se admite la extensión "{0}". + + + No se puede agregar el tipo. Todos los archivos de entrada deben tener la misma extensión de archivo. + + + No se puede agregar el tipo. No se encontró el ensamblado "{0}". + + + No se puede agregar el tipo. El nombre de tipo "{0}" ya existe. + + + No se puede establecer el ensamblado de salida. La ruta de acceso {0} no se resolvió en un solo archivo. + + + No se puede agregar el tipo. Se produjeron errores de compilación. + + + No se puede agregar el tipo. El parámetro OutputType requiere que se especifique el parámetro OutputAssembly. + + + No se puede agregar el tipo. No se admite la definición de nuevos tipos en este modo de lenguaje. + + + El ensamblado de referencia especificado "{0}" no es necesario y se omite. + + + Actualmente no se admiten los tipos de ensamblado "ConsoleApplication" y "WindowsApplication". + + + cmdlet Add-Type + + + El cmdlet Add-Type no se permitirá en el modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/AliasCommandStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/AliasCommandStrings.es.resx new file mode 100644 index 00000000000..d20895d6480 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/AliasCommandStrings.es.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 + + + Establecer alias + + + Nombre: {0} Valor: {1} + + + Nuevo alias + + + Nombre: {0} Valor: {1} + + + Importar alias + + + Nombre: {0} Valor: {1} + + + No se puede abrir el archivo {0} para exportar el alias. {1} + + + Archivo de alias + + + Exportado por : {0} + + + Fecha y hora: {0:F} + + + Equipo : {0} + + + No se puede importar el alias porque la ruta de acceso especificada "{0}" hacía referencia a una ruta de acceso de proveedor ''{1}". Cambie el valor del parámetro Path a una ruta de acceso del sistema de archivos. + + + No se puede importar el alias porque la ruta de acceso "{0}" contiene caracteres comodín que se resuelven en varias rutas de acceso. Los alias solo se pueden importar desde un archivo. Cambie el valor del parámetro Path a una ruta de acceso que se resuelva en un único archivo. + + + No se puede abrir el archivo {0} para importar el alias. {1} + + + No se puede importar un alias. El número {1} de línea del archivo "{0}" no es una línea de valores separados por comas (CSV) con el formato correcto para los alias. Cambie la línea para que contenga cuatro valores separados por comas. Si el texto del valor contiene una coma, el valor debe ir entre comillas. + + + No se puede importar el alias porque el número {1} de línea del archivo "{0}" contiene una opción que no se reconoce para los alias. Cambie el archivo para que contenga opciones válidas. + + + Este comando no puede encontrar un alias coincidente porque no existe un alias con {0} "{1}". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertFromStringData.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertFromStringData.es.resx new file mode 100644 index 00000000000..eef3a91fada --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertFromStringData.es.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 + + + La línea de datos "{0}" no está en formato "nombre=valor". + + + El elemento de datos "{1}" de la línea "{0}" ya está definido. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertHTMLStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertHTMLStrings.es.resx new file mode 100644 index 00000000000..86ede54b09d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertHTMLStrings.es.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 + + + Las propiedades de metadatos aceptadas son content-type, default-style, application-name, author, description, generator, keywords, x-ua-compatible y viewport. Es posible que el par de metadatos {0} y {1} no funcione correctamente. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertMarkdownStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertMarkdownStrings.es.resx new file mode 100644 index 00000000000..45c7b84a2b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ConvertMarkdownStrings.es.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 + + + El tipo del objeto de entrada "{0}" no es válido. + + + Solo se admiten rutas de acceso del proveedor FileSystem. No se admite la ruta de archivo: "{0}". + + + La propiedad {0} del objeto especificado está vacía o es null. + + + El nombre del conjunto de parámetros no es válido: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/CsvCommandStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/CsvCommandStrings.es.resx new file mode 100644 index 00000000000..597399f29ea --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/CsvCommandStrings.es.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 + + + No se puede anexar contenido CSV al siguiente archivo: {1}. El objeto anexado no tiene una propiedad que corresponda a la siguiente columna: {0}. Para continuar con las propiedades no coincidentes, agregue el parámetro -Force y vuelva a intentar el comando. + {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. + + + + Debe especificar los parámetros -UseQuotes o -QuoteFields, pero no ambos. + + + Debe especificar los parámetros -Path o -LiteralPath, pero no ambos. + + + No se especificaron uno o varios encabezados. Los nombres predeterminados que empiezan por "H" se han usado en lugar de los encabezados que faltan. + + + FileName es un parámetro obligatorio. + + + Solo se debe llamar al método ReconcilePreexistingPropertyNames al anexar. + + + Solo se debe llamar al método ReconcilePreexistingPropertyNames cuando los nombres de propiedad preexistente se hayan leído correctamente. + + + Solo se debe llamar al método BuildPropertyNames una vez por instancia de cmdlet. + + + La jerarquía de tipos no debe tener valores NULL. + + + Se ha alcanzado EOF. + + + Debe especificar los parámetros -Append o -NoHeader, pero no ambos. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/Debugger.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/Debugger.es.resx new file mode 100644 index 00000000000..4aad039409e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/Debugger.es.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}'. + + + El archivo '{0}' no existe. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/EventingStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/EventingStrings.es.resx new file mode 100644 index 00000000000..149e485d59c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/EventingStrings.es.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 + + + El evento con el identificador de origen "{0}" no existe. + + + El evento con el identificador "{0}" no existe. + + + La suscripción de eventos con el identificador de origen "{0}" no existe. + + + La suscripción de eventos con el identificador "{0}" no existe. + + + Suscripción de eventos "{0}" + + + Evento "{0}" + + + Se debe especificar una acción para los eventos no reenviados. + + + Cancelar suscripción + + + Quitar + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/FormatAndOut_out_gridview.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/FormatAndOut_out_gridview.es.resx new file mode 100644 index 00000000000..53215e3d3d8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/FormatAndOut_out_gridview.es.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 + + + Out-GridView no admite el formato de datos. + + + Microsoft .NET Framework 4.5 se instaló mientras se ejecutaban una o varias sesiones de PowerShell. Para usar el {0} cmdlet, cierre todas las ventanas de PowerShell y, a continuación, abra una nueva ventana de PowerShell. + + + Tipo + + + Valor + + + Índice + + + No se encontró un comando denominado ''{0}". + + + Se encontró más de un comando con el nombre "{0}". Inicie "{1}" sin parámetros y, a continuación, escriba "{0}" para filtrar los resultados. + + + No se puede escribir en el búfer de entrada de la consola. + + + {0} debe ser menor que {1}. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetFormatDataStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetFormatDataStrings.es.resx new file mode 100644 index 00000000000..b03891f2b03 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetFormatDataStrings.es.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 + + + Procesando la definición de vista "{0}" + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetMember.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetMember.es.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetMember.es.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetRandomCommandStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetRandomCommandStrings.es.resx new file mode 100644 index 00000000000..aa4f6029286 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetRandomCommandStrings.es.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" debe ser mayor que cero. + + + El valor mínimo ({0}) no puede ser mayor o igual que el valor máximo ({1}). + + + "minValue" no puede ser mayor que maxValue. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetUptimeStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetUptimeStrings.es.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/GetUptimeStrings.es.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/HostStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/HostStrings.es.resx new file mode 100644 index 00000000000..de2f8f2dc92 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/HostStrings.es.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 + + + No se puede procesar el color porque {0} no es un color válido. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/HttpCommandStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/HttpCommandStrings.es.resx new file mode 100644 index 00000000000..ec32021dfec --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/HttpCommandStrings.es.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 + + + Este comando no se puede completar debido al siguiente error: "{0}". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/ImplicitRemotingStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ImplicitRemotingStrings.es.resx new file mode 100644 index 00000000000..d1436f5640b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ImplicitRemotingStrings.es.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 + + + Los datos devueltos por el comando {0} remoto no están en el formato esperado. + + + El cmdlet {0} requiere los siguientes comandos en la sesión remota: Get-Command, Get-FormatData y Select-Object. Los siguientes comandos se usan, pero son opcionales: Get-Help y Measure-Object. Compruebe que la sesión remota incluye los comandos necesarios e inténtelo de nuevo. + + + Al ejecutar el comando {0} en una sesión remota se notificó el siguiente error: {1}. + + + La ejecución del comando {0} en una sesión remota no devolvió ningún resultado. + + + No se ha asociado ninguna sesión a este módulo de comunicación remota implícita. + + + No se pudo resolver el alias remoto "{0}". + + + Se omitió la creación del proxy para el comando "{0}" porque el nombre no coincidía con el valor del parámetro Name. + + + Se ha omitido la definición de tipo extendido para el tipo "{0}" porque su nombre no coincide con el valor del parámetro FormatTypeName. + + + Se omitió la creación del proxy para el comando "{0}" porque PowerShell no pudo comprobar la seguridad del nombre del comando. + + + Se ha omitido la creación del Proxy para el siguiente comando: "{0}", ya que se ocultaría un comando local existente. Use el parámetro AllowClobber si desea ocultar los comandos locales existentes. + + + No se ha creado ningún proxy de comando, porque todos los comandos remotos solicitados crearían sombras de los comandos locales existentes. Use el parámetro AllowClobber si desea ocultar los comandos locales existentes. + + + Comunicación remota implícita para {0} + + + Evento de comunicación remota implícita (id. de sesión: {0}; id. de controlador de eventos: {1}) + + + Módulo de comunicación remota implícita + + + generado en {0} + + + por {0} cmdlet + + + Se invoca con la siguiente línea de comandos: {0} + + + Parámetro opcional que se puede usar para especificar la sesión en la que funciona este módulo de proxy + + + Creando una nueva sesión para la comunicación remota implícita del comando "{{0}}"... + + + Sesión para el módulo de comunicación remota implícita en {{0}} + + + Creando módulo de comunicación remota implícita... + + + Obteniendo información de comandos de la sesión remota... + + + Obteniendo información de comandos de sesión remota... {0} comandos recibidos + + + Obteniendo formato e información de salida de la sesión remota... + + + Obteniendo información de formato y salida de sesión remota... {0} objetos recibidos + + + Completado. + + + Solicitud de credenciales de PowerShell + + + Escriba sus credenciales para {0}. + + + Escriba las credenciales de proxy HTTP que se usan para la siguiente conexión: {0} + + + Los comandos disponibles en la nueva sesión remota son distintos de los que estaban disponibles cuando se creó el módulo de comunicación remota implícita. Considere la posibilidad de volver a crear el módulo mediante el cmdlet Export-PSSession. + + + No se pueden cargar archivos porque la ejecución de scripts está deshabilitada en este sistema. Proporcione un certificado válido con el que firmar los archivos. + + + El archivo {0} no se pudo firmar. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/ImportLocalizedDataStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ImportLocalizedDataStrings.es.resx new file mode 100644 index 00000000000..b2e208f5178 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/ImportLocalizedDataStrings.es.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 + + + No se encuentra el archivo de datos "{0}". + + + No se especificó el parámetro FileName. El parámetro FileName es necesario cuando no se llama a Import-LocalizedData desde un archivo de script. + + + Se produjo el siguiente error mientras PowerShell abría el archivo de datos "{0}": +{1}. + + + Se produjo el siguiente error mientras PowerShell cargaba el archivo de datos de script "{0}": +{1}. + + + El argumento del parámetro FileName no debe contener una ruta de acceso. + + + No se encuentra el archivo de datos de PowerShell "{0}" en el directorio "{1}" o en ningún directorio de referencia cultural primario. + + + No se pueden importar datos localizados. No se permite la definición de comandos admitidos adicionales en este modo de lenguaje. + + + El nombre BindingVariable "{0}" no es válido. + + + Import-LocalizedData Cmdlet + + + No se permitirán comandos admitidos adicionales (a través del parámetro SupportedCommand) en el modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/MatchStringStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/MatchStringStrings.es.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/MatchStringStrings.es.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/MeasureObjectStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/MeasureObjectStrings.es.resx new file mode 100644 index 00000000000..37521c491dc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/MeasureObjectStrings.es.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 + + + No se encuentra la propiedad "{0}" en la entrada de ningún objeto. + + + El objeto de entrada "{0}" no es numérico. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/NewObjectStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/NewObjectStrings.es.resx new file mode 100644 index 00000000000..eeac5dff3ff --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/NewObjectStrings.es.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 + + + No se encontró un constructor. No se encuentra un constructor adecuado para el tipo {0}. + + + No se encuentra el tipo [{0}]: compruebe que el ensamblado que contiene este tipo está cargado. + + + No se puede cargar el tipo COM {0}. + + + El objeto escrito en la canalización es una instancia del tipo "{0}" del ensamblado principal de interoperabilidad del componente. Si este tipo expone miembros distintos de los miembros IDispatch, es posible que los scripts escritos para funcionar con este objeto no funcionen si no está instalado el ensamblado principal de interoperabilidad. + + + No se encontró el miembro "{1}" para el objeto especificado {2}. + + + El valor proporcionado no es válido o la propiedad es de solo lectura. Cambie el valor e inténtelo de nuevo. + + + No se admite la creación de instancias de atributos y tipos delegados de Windows RT. + + + No se pueden crear instancias del tipo similar a ByRef "{0}". Los tipos de tipo ByRef no se admiten en PowerShell. + + + No se puede crear el tipo. En este modo de lenguaje solo se admiten los tipos principales. + + + No se puede crear el tipo. Solo se admiten tipos principales en {0} modo de lenguaje en un equipo bloqueado por directiva. + + + Creación del tipo de cmdlet New-Object + + + El tipo "{0}" no se creará en modo ConstrainedLanguage. + + + Creación de objetos COM con el cmdlet New-Object + + + El objeto COM "{0}" no se creará en modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/OutPrinterDisplayStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/OutPrinterDisplayStrings.es.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/OutPrinterDisplayStrings.es.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/SelectObjectStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/SelectObjectStrings.es.resx new file mode 100644 index 00000000000..bdd62150f75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/SelectObjectStrings.es.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/SendMailMessageStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/SendMailMessageStrings.es.resx new file mode 100644 index 00000000000..a099c436291 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/SendMailMessageStrings.es.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 + + + No se puede enviar el correo electrónico porque no se especificó ningún servidor SMTP. Debe especificar un servidor SMTP mediante el parámetro SmtpServer o la variable $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/SortObjectStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/SortObjectStrings.es.resx new file mode 100644 index 00000000000..e47bb16e94a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/SortObjectStrings.es.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}" no se encuentra en "InputObject". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/StartSleepStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/StartSleepStrings.es.resx new file mode 100644 index 00000000000..d6dcb872922 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/StartSleepStrings.es.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 + + + El valor del parámetro "-Duration" no debe superar ''{0}". El valor proporcionado es "{1}". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/TestJsonCmdletStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/TestJsonCmdletStrings.es.resx new file mode 100644 index 00000000000..2c45d491dd2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/TestJsonCmdletStrings.es.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 + + + No se puede analizar el esquema JSON. + + + No se puede analizar el archivo JSON. + + + El JSON no es válido con el esquema: {0} en "{1}" + + + No se puede abrir el archivo de esquema JSON: {0} + + + No se admite el esquema URI "{0}". Solo se permiten HTTP(S) y URI del sistema de archivos local. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/TraceCommandStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/TraceCommandStrings.es.resx new file mode 100644 index 00000000000..5f2b76f9777 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/TraceCommandStrings.es.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 + + + La salida de seguimiento solo se puede escribir en el sistema de archivos. La ruta de acceso ''{0}'' se refiere a una ruta de proveedor de ''{1}''. + + + La salida de seguimiento solo se puede escribir en un único archivo. La ruta de acceso ''{0}'' resuelve en más de un archivo. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/UnblockFileStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UnblockFileStrings.es.resx new file mode 100644 index 00000000000..8785ba77912 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UnblockFileStrings.es.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 + + + El cmdlet no admite Linux. + + + Se produjo un error al desbloquear {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/UpdateDataStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UpdateDataStrings.es.resx new file mode 100644 index 00000000000..b3f1289174a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UpdateDataStrings.es.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 + + + No se puede abrir el archivo porque el proveedor actual es "{0}" y este comando requiere un archivo. + + + No se puede leer el archivo "{0}" porque no tiene la extensión de nombre de archivo "{1}". + + + Actualizar TypeData + + + Actualizar FormatData + + + Nombre de archivo: {0} + + + No se puede actualizar un miembro con el tipo "{0}". Especifique un tipo diferente para el parámetro MemberType. + + + El parámetro {0} es necesario para el tipo "{1}". Especifique el parámetro {0}. + + + El parámetro {0} no debe ser nulo ni una cadena vacía para un miembro de tipo "{1}". Especifique un valor distinto de NULL para el parámetro {0} al actualizar este tipo de miembro. + + + El parámetro {0} no es necesario para un miembro de tipo "{1}" y no se debe especificar. No especifique el parámetro {0} al actualizar este tipo de miembro. + + + No se especificó ningún miembro para la actualización en el tipo "{0}". + + + El nombre del tipo de destino no debe ser nulo, estar vacío ni contener solo espacios en blanco. + + + Los parámetros Value y SecondValue no deben ser nulos para un miembro de tipo "{0}". Especifique un valor distinto de NULL para uno de los dos parámetros. + + + Solo se puede especificar un tipo de miembro. Los tipos de miembro especificados son: "{0}". Actualice el tipo con un solo tipo de miembro. + + + Los parámetros MemberName, Value y SecondValue no se pueden especificar sin el parámetro MemberType. + + + Quitar TypeData + + + Nombre del tipo que se quitará: {0} + + + Escriba para actualizar: {0} + + + Quitar archivo de tipo + + + El archivo {0} no se importa en la sesión actual. + + + No se permite actualizar los datos de formato en este espacio de ejecución. La propiedad 'DisableFormatUpdates' se establece en True al crear el espacio de ejecución. + + + No se pueden actualizar los datos de formato con una instancia de FormatTable. + + + No se pueden actualizar los datos de tipo con una instancia de TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/UpdateListStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UpdateListStrings.es.resx new file mode 100644 index 00000000000..583200b3deb --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UpdateListStrings.es.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 + + + No se encuentra la propiedad "{0}" en este objeto + + + Debe especificar el parámetro Property cuando se especifique el parámetro InputObject. + + + Debe especificar el parámetro InputObject cuando se especifique el parámetro Property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/UtilityCommonStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UtilityCommonStrings.es.resx new file mode 100644 index 00000000000..1c71e7c0ab6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/UtilityCommonStrings.es.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} tiene una o varias excepciones que no son válidas. + + + No se puede ejecutar este comando porque la ruta de acceso del archivo "{0}" no es válida. Proporcione una ruta de acceso de archivo válida y, a continuación, ejecute el comando. + + + No se puede ejecutar este comando porque "{0}" está vacío o en blanco. Especifique CSSUri y, a continuación, ejecute el comando. + + + No se puede abrir el archivo porque el proveedor actual ({0}) no puede abrir archivos. + + + No se puede ejecutar este comando porque el valor de prefijo del parámetro Namespace es null. Proporcione un valor válido para el prefijo y, a continuación, vuelva a ejecutar el comando. + + + Los objetos agrupados por esta propiedad no se pueden expandir porque hay una duplicación de claves. Proporcione un valor válido para la propiedad y vuelva a intentarlo. + + + El comando no se admite en este sistema operativo. + + + No se puede leer el archivo "{0}": {1} + + + No se puede convertir la entrada de tipo "{0}" a hexadecimal. Para ver el formato hexadecimal de su representación de cadena, canalícela al cmdlet Out-String antes de canalizarla a Format-Hex. + + + No se admite la ruta de acceso especificada "{0}". Este comando solo admite las rutas de acceso del proveedor FileSystem. + + + Ruta: + + + No se puede ejecutar el comando porque el parámetro AsString requiere que especifique el parámetro AsHashtable. + + + No se puede ejecutar el comando porque, para usar el parámetro AsHashTable con más de una propiedad, debe agregar el parámetro AsString. + + + No se encuentra la ruta de acceso '{0}' porque no existe. + + + No se puede usar la etiqueta "{0}". El prefijo "PS" está reservado. + + + No se pudo analizar el archivo "{0}" como un archivo de datos de PowerShell. + + + No se puede construir un descriptor de seguridad a partir del SDDL especificado debido al siguiente error: {0} + + + Cmdlet Invoke-Expression + + + El bloque de script del cmdlet Invoke-Expression se ejecutará en modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/VariableCommandStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/VariableCommandStrings.es.resx new file mode 100644 index 00000000000..15a5ca10025 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/VariableCommandStrings.es.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 + + + Establecer variable + + + Nombre: {0} Valor: {1} + + + Usar una sola variable en lugar de una colección + + + Nueva variable + + + Nombre: {0} Valor: {1} + + + Quitar variable + + + Nombre: {0} + + + Borrar variable + + + Nombre: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/WebCmdletStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/WebCmdletStrings.es.resx new file mode 100644 index 00000000000..b5e0460fd11 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/WebCmdletStrings.es.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 + + + Se ha denegado el acceso a la ruta '{0}'. + + + El cmdlet no puede proteger los secretos de texto sin formato enviados a través de conexiones sin cifrar. Para suprimir esta advertencia y enviar secretos de texto sin formato a través de redes sin cifrar, vuelva a emitir el comando especificando el parámetro AllowUnencryptedAuthentication. + + + No se puede ejecutar el cmdlet porque se especificaron los siguientes parámetros en conflicto: Authentication y UseDefaultCredentials. La autenticación no admite credenciales predeterminadas. Especifique Authentication o UseDefaultCredentials y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque no se ha especificado el siguiente parámetro: Credential. El tipo de autenticación proporcionado requiere una credencial. Especifique la credencial y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque no se ha especificado el siguiente parámetro: Token. El tipo de autenticación proporcionado requiere un token. Especifique el token y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: Credencial y Token. Especifique credenciales o tokens y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: Body e InFile. Especifique Body o Infile y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: Body y Form. Especifique Body o Form y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: InFile y Form. Especifique InFile o Form y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque el parámetro -ContentType no es un encabezado Content-Type válido. Especifique un Content-Type válido para -ContentType y vuelva a intentarlo. Para suprimir la validación del encabezado, proporcione el parámetro -SkipHeaderValidation. + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: Credential y UseDefaultCredentials. Especifique Credential o UseDefaultCredentials y vuelva a intentarlo. + + + La ruta de acceso "{0}" se resuelve en un directorio. Especifique una ruta de acceso que incluya un nombre de archivo y, a continuación, vuelva a intentar el comando. + + + El JSON proporcionado incluye una propiedad cuyo nombre es una cadena vacía, solo se admite mediante el modificador -AsHashTable. + + + No se puede convertir la cadena JSON porque un diccionario convertido a partir de la cadena contiene la clave duplicada "{0}". + + + No se puede analizar el contenido de la respuesta porque el motor de Internet Explorer no está disponible o la configuración del primer inicio de Internet Explorer no está completa. Especifique el parámetro UseBasicParsing e inténtelo de nuevo. + + + No se puede seguir un redireccionamiento no seguro de forma predeterminada. Vuelva a emitir el comando especificando el modificador -AllowInsecureRedirect. + + + No se puede convertir la cadena JSON porque contiene claves con distintas mayúsculas y minúsculas. Use el modificador -AsHashTable en su lugar. La clave que se intentó agregar a la clave existente "{0}" era "{1}". + + + Se ha superado el número máximo de redireccionamientos. Para aumentar el número de redireccionamientos permitidos, proporcione un valor mayor al parámetro -MaximumRedirection. + + + La ruta de acceso "{0}" se puede resolver en varias rutas de acceso. + + + El tipo "{0}" no se admite para la serialización o deserialización de un diccionario. Las claves deben ser cadenas. + + + La ruta de acceso "{0}" no se puede resolver en un archivo. + + + La ruta de acceso "{0}" no es una ruta de acceso del sistema de archivos. Especifique la ruta de acceso a un archivo en el sistema de archivos. + + + No se puede ejecutar el cmdlet porque falta el parámetro siguiente: OutFile. Proporcione un valor de parámetro OutFile válido al usar el {0} parámetro y vuelva a intentarlo. + + + El archivo no se volverá a descargar porque el archivo remoto tiene el mismo tamaño que OutFile: {0} + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: ProxyCredential y ProxyUseDefaultCredentials. Especifique ProxyCredential o ProxyUseDefaultCredentials y vuelva a intentarlo. + + + No se puede ejecutar el cmdlet porque falta el siguiente parámetro: Proxy. Proporcione un URI de proxy válido para el parámetro Proxy cuando use los parámetros ProxyCredential o ProxyUseDefaultCredentials y vuelva a intentarlo. + + + Lectura del flujo de respuesta web completada. Bytes descargados: {0} + + + Leyendo secuencia de respuesta web + + + Descargado: {0} de {1} + + + El modificador Resume solo se puede usar si OutFile tiene como destino un archivo, pero se resuelve en un directorio: {0}. + + + No se puede ejecutar el cmdlet porque se han especificado los siguientes parámetros en conflicto: Session y SessionVariable. Especifique Session o SessionVariable y vuelva a intentarlo. + + + No se pueden recuperar los certificados porque la huella digital no es válida. Compruebe la huella digital y vuelva a intentarlo. + + + Solicitud web completada. (Número de bytes procesados: {0}) + + + Solicitud web cancelada. (Número de bytes procesados: {0}) + + + Estado de solicitud web + + + Descargado: {0} de {1} + + + Error en la conversión de JSON: {0} + + + El código de estado de la respuesta no indica un resultado correcto: {0} ({1}). + + + Siguiente vínculo rel {0} + + + El servidor remoto indicó que no pudo reanudar la descarga. Se sobrescribirá el archivo local. + + + Se recibió una respuesta HTTP/{0} de tipo de contenido {1} de tamaño desconocido + + + Reintentar después del intervalo de {0} segundos. Código de estado del intento anterior: {1} + + + El JSON resultante se trunca porque la serialización ha superado la profundidad establecida de {0}. + + + Las propiedades de WebSession cambiaron entre solicitudes, lo que obligó a volver a crear todas las conexiones HTTP de la sesión. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/WriteErrorStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/WriteErrorStrings.es.resx new file mode 100644 index 00000000000..6b8229bba3e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/WriteErrorStrings.es.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 + + + "El cmdlet Write-Error notificó un error". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/es/WriteProgressResourceStrings.es.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/es/WriteProgressResourceStrings.es.resx new file mode 100644 index 00000000000..dbf919975b1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/es/WriteProgressResourceStrings.es.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 + + + Texto para describir la actividad para la que se notifica el progreso. + + + Texto para describir el estado actual de la actividad sobre la que se informa del progreso. + + + Procesando + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AddMember.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AddMember.fr.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AddMember.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AddTypeStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AddTypeStrings.fr.resx new file mode 100644 index 00000000000..621a76cc8fa --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AddTypeStrings.fr.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 + + + Le code source a déjà été compilé et chargé. + + + Nous ne pouvons pas ajouter de type. L’extension « {0} » n’est pas prise en charge. + + + Nous ne pouvons pas ajouter de type. Tous les fichiers d’entrée doivent avoir la même extension de fichier. + + + Nous ne pouvons pas ajouter de type. Nous n’avons pas pu trouver l’assembly « {0} ». + + + Nous ne pouvons pas ajouter de type. Le nom de type « {0} » existe déjà. + + + Nous ne pouvons pas définir l’assembly de sortie. Le chemin d’accès {0} n’a pas été résolu en un seul fichier. + + + Nous ne pouvons pas ajouter de type. Des erreurs de compilation se sont produites. + + + Nous ne pouvons pas ajouter de type. Le paramètre OutputType nécessite que le paramètre OutputAssembly soit indiqué. + + + Nous ne pouvons pas ajouter de type. La définition de nouveaux types n’est pas prise en charge dans ce mode de langage. + + + L’assembly de référence spécifié « {0} » est inutile et ignoré. + + + Les types d’assembly « ConsoleApplication » et « WindowsApplication » ne sont actuellement pas pris en charge. + + + Cmdlet Add-Type + + + La cmdlet Add-Type ne sera pas autorisée en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AliasCommandStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AliasCommandStrings.fr.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/AliasCommandStrings.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertFromStringData.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertFromStringData.fr.resx new file mode 100644 index 00000000000..eb8e39ef728 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertFromStringData.fr.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 + + + La ligne de données « {0} » n’est pas au format « name=value ». + + + L’élément de données « {1} » dans la ligne « {0} » est déjà défini. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertHTMLStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertHTMLStrings.fr.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertHTMLStrings.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertMarkdownStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertMarkdownStrings.fr.resx new file mode 100644 index 00000000000..00962209f7a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ConvertMarkdownStrings.fr.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 + + + Le type de l’objet d’entrée « {0} » n’est pas valide. + + + Seuls les chemins du fournisseur FileSystem sont pris en charge. Le chemin d’accès au fichier n’est pas pris en charge : « {0} ». + + + La propriété {0} de l’objet donné est null ou vide. + + + Nom du jeu de paramètres non valide : {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/CsvCommandStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/CsvCommandStrings.fr.resx new file mode 100644 index 00000000000..7a6821aa7f4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/CsvCommandStrings.fr.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 + + + Impossible d’ajouter du contenu CSV au fichier suivant : {1}. L’objet ajouté n’a pas de propriété qui correspond à la colonne suivante : {0}. Pour continuer avec des propriétés incompatibles, ajoutez le paramètre -Force, puis réessayez la commande. + {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. + + + + Vous devez spécifier les paramètres -UseQuotes ou -QuoteFields, mais pas les deux. + + + Vous devez spécifier les paramètres -Path ou -LiteralPath, mais pas les deux. + + + Un ou plusieurs en-têtes n’ont pas été spécifiés. Les noms par défaut commençant par « H » ont été utilisés à la place des en-têtes manquants. + + + FileName est un paramètre obligatoire. + + + La méthode ReconcilePreexistingPropertyNames ne doit être appelée qu’en cas d’ajout. + + + La méthode ReconcilePreexistingPropertyNames doit être appelée uniquement lorsque les noms de propriété préexistants ont été lus avec succès. + + + La méthode BuildPropertyNames ne doit être appelée qu’une seule fois par instance d’applet de commande. + + + La hiérarchie des types ne doit pas comporter de valeurs nulles. + + + EOF est atteint. + + + Vous devez spécifier les paramètres -Append ou -NoHeader, mais pas les deux. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/Debugger.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/Debugger.fr.resx new file mode 100644 index 00000000000..e41e801baae --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/Debugger.fr.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 + + + La ligne ne peut pas être inférieure à 1. + + + Il n’existe aucun point d’arrêt avec l’ID « {0} ». + + + Le fichier « {0} » n'existe pas. + + + Nous ne pouvons pas définir un point d’arrêt sur le fichier « {0} ». Seuls les fichiers *.ps1 et *.psm1 sont valides. + + + Le débogage n’est pas pris en charge sur les sessions distantes. + + + Nous ne pouvons pas définir un point d’arrêt. Le mode de langage de cette session n’est pas compatible avec le mode de langage à l’échelle du système. + + + Nous ne pouvons pas définir des points d’arrêt dans la session à distance, car l’hôte actuel ne prend pas en charge le débogage distant. + + + Vous ne pouvez pas déboguer l’instance d’exécution de l’hôte par défaut en utilisant cette cmdlet. Pour déboguer l’instance d’exécution par défaut, utilisez les commandes de débogage normales à partir de l’hôte. + + + Nous ne pouvons pas déboguer l’instance d’exécution. L’hôte n’a aucun débogueur. Essayez de déboguer l’instance d’exécution dans la console PowerShell ou avec Visual Studio Code, qui ont tous deux des débogueurs intégrés. + + + Nous ne pouvons pas déboguer l’instance d’exécution. Il n’existe ni hôte ni interface utilisateur hôte. Le débogueur nécessite un hôte et une interface utilisateur hôte pour le débogage. + + + Plusieurs instance d’exécution ont été trouvées. Vous ne pouvez en déboguer qu’une seule à la fois. + + + Pour terminer le type de session de débogage, tapez la commande « Detach » à l’invite du débogueur, sinon tapez « Ctrl+C ». + + + La commande ou le script a été effectué. + + + Débogage de l’instance d’exécution : {0} + + + Nous ne pouvons pas définir les options de débogage sur l’instance d'exécution {0}, car elle n’est pas dans l’état Ouvert. + + + Nous n’avons pas pu conserver les options de débogage pour le processus {0}. + + + Aucun débogueur n’a été trouvé pour l’instance d’exécution {0}. + + + Aucune instance d’exécution n’a été trouvée. + + + Wait-Debugger a été appelé à la ligne {0} dans {1}. + + + Nous ne pouvons pas à jour un point d’arrêt associé à une autre instance d’exécution, car il n’en existe aucune avec l’ID d’instance « {0} ». + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/EventingStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/EventingStrings.fr.resx new file mode 100644 index 00000000000..ea08e6f2a4d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/EventingStrings.fr.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 + + + L’événement avec l’identificateur source '{0}' n’existe pas. + + + L’événement avec l’identificateur '{0}' n’existe pas. + + + L’abonnement aux événements avec l’identificateur source «{0}» n’existe pas. + + + L’abonnement aux événements avec l’identificateur «{0}» n’existe pas. + + + Abonnement aux événements '{0}' + + + Événement '{0}' + + + L’action doit être spécifiée pour les événements non transférés. + + + Se désabonner + + + Supprimer + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/FormatAndOut_out_gridview.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/FormatAndOut_out_gridview.fr.resx new file mode 100644 index 00000000000..c2a09dd7168 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/FormatAndOut_out_gridview.fr.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 + + + Valeur + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetFormatDataStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetFormatDataStrings.fr.resx new file mode 100644 index 00000000000..1defd23f8ad --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetFormatDataStrings.fr.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 + + + Traitement de la définition de vue « {0} » + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetMember.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetMember.fr.resx new file mode 100644 index 00000000000..5a5d70cd9ac --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetMember.fr.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 + + + Vous devez spécifier un objet pour la cmdlet Get-Member. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetRandomCommandStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetRandomCommandStrings.fr.resx new file mode 100644 index 00000000000..d89b397af4d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetRandomCommandStrings.fr.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' doit être supérieur à zéro. + + + La valeur minimale ({0}) ne peut pas être supérieure ou égale à la valeur maximale ({1}). + + + 'minValue' ne peut pas être supérieur à maxValue. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetUptimeStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetUptimeStrings.fr.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/GetUptimeStrings.fr.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/HostStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/HostStrings.fr.resx new file mode 100644 index 00000000000..c13fee13a67 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/HostStrings.fr.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 + + + Nous ne pouvons pas traiter la couleur, car {0} n’est pas une couleur valide. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/HttpCommandStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/HttpCommandStrings.fr.resx new file mode 100644 index 00000000000..cffdf9c658d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/HttpCommandStrings.fr.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 + + + Nous ne pouvons pas exécuter cette commande en raison de l’erreur suivante : « {0} ». + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ImplicitRemotingStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ImplicitRemotingStrings.fr.resx new file mode 100644 index 00000000000..d12e1061027 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ImplicitRemotingStrings.fr.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 + + + Les données renvoyées par la commande distante {0} n’ont pas le format attendu. + + + La cmdlet {0} nécessite les commandes suivantes dans la session distante : Get-Command, Get-FormatData et Select-Object. Les commandes suivantes sont utilisées, mais facultatives : Get-Help et Measure-Object. Vérifiez que la session distante inclut les commandes nécessaires, puis réessayez. + + + L’exécution de la commande {0} dans une session distante a signalé l’erreur suivante : {1}. + + + L’exécution de la commande {0} dans une session distante n’a renvoyé aucun résultat. + + + Aucune session n’a été associée à ce module de communication à distance implicite. + + + Nous n’avons pas pu résoudre l’alias distant « {0} ». + + + La création du proxy a été ignorée pour la commande « {0} », car le nom ne correspondait pas à la valeur du paramètre Name. + + + La définition de type étendue a été ignorée pour le type « {0} », car son nom ne correspondait pas à la valeur du paramètre FormatTypeName. + + + La création du proxy a été ignorée pour la commande « {0} », car PowerShell n’a pas pu vérifier la sécurité du nom de la commande. + + + La création du proxy a été ignorée pour la commande suivante : « {0} », car elle va masquer une commande locale existante. Utilisez le paramètre AllowClobber si vous souhaitez masquer des commandes locales existantes. + + + Aucun proxy de commande n’a été créé, car toutes les commandes distantes demandées vont masquer des commandes locales existantes. Utilisez le paramètre AllowClobber si vous souhaitez masquer des commandes locales existantes. + + + Module de communication à distance implicite pour {0} + + + Événement de communication à distance implicite (ID de session : {0}, ID du gestionnaire d’événements : {1}) + + + Module de communication à distance implicite + + + généré le {0} + + + par la cmdlet {0} + + + Nous l’appelons avec la ligne de commande suivante : {0} + + + Paramètre facultatif que vous pouvez utiliser pour spécifier la session sur laquelle ce module proxy fonctionne + + + Création d’une nouvelle session pour la communication à distance implicite de la commande « {{0}} » en cours... + + + Session pour le module de communication à distance implicite sur {{0}} + + + Création du module de communication à distance implicite... + + + Obtention des informations de commande à partir de la session distante en cours... + + + Obtention des informations de commande à partir de la session distante en cours... {0} commandes reçues + + + Obtention des informations de mise en forme et de sortie à partir de la session distante en cours... + + + Obtention des informations de mise en forme et de sortie à partir de la session distante en cours... {0} objets reçus + + + Terminé. + + + Requête d’informations d’identification PowerShell + + + Entrez vos informations d’identification pour {0}. + + + Entrez les informations d’identification du proxy HTTP utilisées pour la connexion suivante : {0} + + + Les commandes disponibles dans la nouvelle session distante sont différentes de celles disponibles au moment de la création du module de communication à distance implicite. Envisagez de recréer le module en utilisant la cmdlet Export-PSSession. + + + Nous ne pouvons pas charger les fichiers, car l’exécution de scripts est désactivée sur ce système. Fournissez un certificat valide avec lequel signer les fichiers. + + + Nous n’avons pas pu signer le fichier {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ImportLocalizedDataStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ImportLocalizedDataStrings.fr.resx new file mode 100644 index 00000000000..08915a13229 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/ImportLocalizedDataStrings.fr.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 + + + Le fichier de données «{0}» est introuvable. + + + Le paramètre FileName n’a pas été spécifié. Le paramètre FileName est requis lorsque Import-LocalizedData n’est pas appelé à partir d’un fichier de script. + + + L’erreur suivante s’est produite lors de l’ouverture du fichier de données «{0}» par PowerShell : +{1}. + + + L’erreur suivante s’est produite lors du chargement du fichier de données de script «{0}» par PowerShell : +{1}. + + + L’argument du paramètre FileName ne doit pas contenir de chemin d’accès. + + + Impossible de trouver le fichier de données PowerShell «{0}» dans le répertoire «{1}» ou dans les répertoires de culture parent. + + + Impossible d’importer des données localisées. La définition de commandes supplémentaires prises en charge n’est pas autorisée dans ce mode de langage. + + + Le nom BindingVariable «{0}» n’est pas valide. + + + Applet de commande Import-LocalizedData + + + Les commandes prises en charge supplémentaires (via le paramètre SupportedCommand) ne sont pas autorisées en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/MatchStringStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/MatchStringStrings.fr.resx new file mode 100644 index 00000000000..bb6c47f9be7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/MatchStringStrings.fr.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 + + + Nous ne pouvons pas ouvrir le fichier, car le fournisseur actuel ({0}) ne peut pas ouvrir de fichiers. + + + Le fichier {0} ne peut pas être lu : {1} + + + L’option « Context » n’est pas valide lors de la recherche de résultats redirigés depuis la sortie de Select-String. + + + La chaîne {0} n’est pas une expression régulière valide : {1} + + + Vous devez spécifier le paramètre -Culture uniquement avec le paramètre -SimpleMatch. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/MeasureObjectStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/MeasureObjectStrings.fr.resx new file mode 100644 index 00000000000..bde620f6ce7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/MeasureObjectStrings.fr.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 + + + La propriété « {0} » est introuvable dans l’entrée pour aucun des objets. + + + L’objet d’entrée « {0} » n’est pas numérique. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/NewObjectStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/NewObjectStrings.fr.resx new file mode 100644 index 00000000000..eb932149c9f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/NewObjectStrings.fr.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 + + + Aucun constructeur n’a été trouvé. Nous ne pouvons pas trouver un constructeur approprié pour le type {0}. + + + Type [{0}] introuvable : vérifiez que l’assembly contenant ce type est chargé. + + + Nous ne pouvons pas charger le type COM {0}. + + + L’objet écrit dans le pipeline est une instance du type « {0} » provenant de l’assembly d’interopérabilité principal du composant. Si ce type expose des membres différents de ceux de IDispatch, les scripts écrits pour fonctionner avec cet objet risquent de ne pas fonctionner si l’assembly d’interopérabilité principal n’est pas installé. + + + Le membre « {1} » est introuvable pour l’objet spécifié {2}. + + + La valeur fournie n’est pas valide ou la propriété est en lecture seule. Modifiez la valeur, puis réessayez. + + + La création d’instances de types d’attribut et de types Windows RT délégués n’est pas prise en charge. + + + Nous ne pouvons pas créer des instances du type ByRef-like « {0} ». Les types ByRef-like ne sont pas pris en charge dans PowerShell. + + + Nous ne pouvons pas créer le type. Seuls les types principaux sont pris en charge dans ce mode de langage. + + + Nous ne pouvons pas créer le type. Seuls les types principaux sont pris en charge en mode langue {0} sur un ordinateur verrouillé par stratégie. + + + Création d’un type avec l’applet de commande New-Object + + + Le type « {0} » ne sera pas créé en mode ConstrainedLanguage. + + + Création d’un objet COM avec l’applet de commande New-Object + + + L’objet COM « {0} » ne sera pas créé en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/OutPrinterDisplayStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/OutPrinterDisplayStrings.fr.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/OutPrinterDisplayStrings.fr.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SelectObjectStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SelectObjectStrings.fr.resx new file mode 100644 index 00000000000..bdd62150f75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SelectObjectStrings.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SendMailMessageStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SendMailMessageStrings.fr.resx new file mode 100644 index 00000000000..518ae60795b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SendMailMessageStrings.fr.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 + + + L’e-mail ne peut pas être envoyé car aucun serveur SMTP n’a été spécifié. Vous devez spécifier un serveur SMTP à l’aide du paramètre SmtpServer ou de la variable $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SortObjectStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SortObjectStrings.fr.resx new file mode 100644 index 00000000000..81510673266 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/SortObjectStrings.fr.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}» est introuvable dans « InputObject ». + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/StartSleepStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/StartSleepStrings.fr.resx new file mode 100644 index 00000000000..b239755bc03 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/StartSleepStrings.fr.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 + + + La valeur du paramètre « -Duration » ne doit pas dépasser «{0}», la valeur fournie était «{1}». + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/TestJsonCmdletStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/TestJsonCmdletStrings.fr.resx new file mode 100644 index 00000000000..a0f77afd986 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/TestJsonCmdletStrings.fr.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 + + + Nous ne pouvons pas analyser le schéma JSON. + + + Nous ne pouvons pas analyser le JSON. + + + Le JSON n’est pas valide avec le schéma : {0} à « {1} » + + + Nous ne pouvons pas ouvrir le fichier de schéma JSON : {0} + + + Le schéma Uri « {0} » n’est pas pris en charge. Seuls les URI HTTP(S) et du système de fichiers local sont autorisés. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/TraceCommandStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/TraceCommandStrings.fr.resx new file mode 100644 index 00000000000..31af68598ba --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/TraceCommandStrings.fr.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 + + + La sortie de trace ne peut être écrite que dans le système de fichiers. Le chemin d’accès « {0} » fait référence à un chemin d’accès de fournisseur « {1} ». + + + La sortie de trace ne peut être écrite que dans un seul fichier. Le chemin d’accès « {0} » a été résolu en plusieurs fichiers. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UnblockFileStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UnblockFileStrings.fr.resx new file mode 100644 index 00000000000..5ecd31b7e84 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UnblockFileStrings.fr.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 + + + La cmdlet ne prend pas en charge Linux. + + + Une erreur s’est produite lors du déblocage {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UpdateDataStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UpdateDataStrings.fr.resx new file mode 100644 index 00000000000..47e36801bb8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UpdateDataStrings.fr.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 + + + Impossible d’ouvrir le fichier, car le fournisseur actuel est «{0}», et cette commande nécessite un fichier. + + + Impossible de lire le fichier «{0}», car il n’a pas l’extension de nom de fichier «{1}». + + + Mettre à jour TypeData + + + Mettre à jour FormatData + + + FileName : {0} + + + Impossible de mettre à jour un membre avec le type «{0}». Spécifiez un type différent pour le paramètre MemberType. + + + Le paramètre {0} est requis pour le type «{1}». Spécifiez le paramètre {0}. + + + Le paramètre {0} ne doit pas être nul ou une chaîne vide pour un membre de type "{1}". Spécifiez une valeur non nulle pour ce paramètre {0} lors de la mise à jour de ce type de membre. + + + Le paramètre {0} n’est pas nécessaire pour un membre de type «{1}» et ne doit pas être spécifié. Ne spécifiez pas le paramètre {0} lors de la mise à jour de ce type de membre. + + + Aucun membre n’est spécifié pour la mise à jour sur le type «{0}». + + + Le nom du type cible ne doit pas être nul, vide ou ne doit pas contenir uniquement des espaces blancs. + + + Les paramètres Value et SecondValue ne doivent pas tous deux être nuls pour un membre de type "{0}". Spécifiez une valeur non nulle pour l'un des deux paramètres. + + + Un seul type de membre peut être spécifié. Les types de membres spécifiés sont : «{0}». Mettez à jour le type avec un seul type de membre. + + + Les paramètres MemberName, Value et SecondValue ne peuvent pas être spécifiés sans le paramètre MemberType. + + + Supprimer TypeData + + + Nom du type à supprimer : {0} + + + Type à mettre à jour : {0} + + + Supprimer le fichier de type + + + Le fichier {0} n’est pas importé dans la session active. + + + La mise à jour des données de format n’est pas autorisée dans cet espace d’exécution. La propriété « DisableFormatUpdates » a la valeur True lors de la création de l’instance d’exécution. + + + Impossible de mettre à jour les données de format avec une instance FormatTable. + + + Impossible de mettre à jour les données de type avec une instance TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UpdateListStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UpdateListStrings.fr.resx new file mode 100644 index 00000000000..e9b49338451 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UpdateListStrings.fr.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 + + + La propriété « {0} » est introuvable sur cet objet + + + Vous devez spécifier le paramètre Property lorsque le paramètre InputObject est spécifié. + + + Vous devez spécifier le paramètre InputObject lorsque le paramètre Property est spécifié. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UtilityCommonStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UtilityCommonStrings.fr.resx new file mode 100644 index 00000000000..313e63f7db8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/UtilityCommonStrings.fr.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} comporte une ou plusieurs exceptions non valides. + + + Nous ne pouvons pas exécuter cette commande, car le chemin d’accès au fichier « {0} » n’est pas valide. Indiquez un chemin d’accès au fichier valide, puis exécutez la commande. + + + Nous ne pouvons pas exécuter cette commande, car « {0} » est vide ou blanc. Veuillez spécifier CSSUri, puis exécutez la commande. + + + Nous ne pouvons pas ouvrir le fichier, car le fournisseur actuel ({0}) ne peut pas ouvrir de fichiers. + + + Nous ne pouvons pas exécuter cette commande, car la valeur de préfixe du paramètre Namespace est null. Fournissez une valeur valide pour le préfixe, puis exécutez de nouveau la commande. + + + Les objets regroupés par cette propriété ne peuvent pas être développés, car une clé est en double. Fournissez une valeur valide pour la propriété, puis réessayez. + + + La commande n’est pas prise en charge sur ce système d’exploitation. + + + Le fichier « {0} » ne peut pas être lu : {1} + + + Nous ne pouvons pas convertir une entrée de type « {0} » en hexadécimal. Pour afficher la mise en forme hexadécimale de sa représentation sous forme de chaîne, redirigez-la vers l’applet de commande Out-String avant de la rediriger vers Format-Hex. + + + Le chemin d’accès donné « {0} » n’est pas pris en charge. Cette commande prend en charge uniquement les chemins d’accès du fournisseur FileSystem. + + + Chemin d’accès : + + + Nous ne pouvons pas exécuter la commande, car le paramètre AsString nécessite de spécifier le paramètre AsHashtable. + + + Nous ne pouvons pas exécuter la commande, car l’utilisation du paramètre AsHashTable avec plusieurs propriétés nécessite d’ajouter le paramètre AsString. + + + Impossible de trouver le chemin d'accès « {0} », car il n'existe pas. + + + Vous ne pouvez pas utiliser la balise : « {0} ». Le préfixe « PS » est réservé. + + + Le fichier « {0} » n’a pas pu être analysé en tant que fichier de données PowerShell. + + + Nous ne pouvons pas construire un descripteur de sécurité à partir du SDDL fourni en raison de l’erreur suivante : {0} + + + Invoke-Expression Cmdlet + + + Le bloc de script de l’applet de commande Invoke-Expression s’exécutera en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/VariableCommandStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/VariableCommandStrings.fr.resx new file mode 100644 index 00000000000..ca6f484e5f6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/VariableCommandStrings.fr.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 + + + Définissez une variable + + + Nom : {0}Valeur : {1} + + + Utilisez une seule variable plutôt qu’une collection + + + Nouvelle variable + + + Nom : {0}Valeur : {1} + + + Supprimer une variable + + + Nom : {0} + + + Effacer la variable + + + Nom : {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WebCmdletStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WebCmdletStrings.fr.resx new file mode 100644 index 00000000000..004617b35fa --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WebCmdletStrings.fr.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 + + + L'accès au chemin '{0}' est refusé. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WriteErrorStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WriteErrorStrings.fr.resx new file mode 100644 index 00000000000..a66e6cfdf4f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WriteErrorStrings.fr.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 + + + « L’applet de commande Write-Error a signalé une erreur. » + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WriteProgressResourceStrings.fr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WriteProgressResourceStrings.fr.resx new file mode 100644 index 00000000000..e66cdb10022 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/fr/WriteProgressResourceStrings.fr.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 + + + Texte décrivant l’activité pour laquelle l’avancement est signalé. + + + Texte décrivant l’état actuel de l’activité pour laquelle l’avancement est signalé. + + + Traitement + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/AddMember.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/AddMember.it.resx new file mode 100644 index 00000000000..e66edc36714 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/AddMember.it.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 + + + Per aggiungere un membro, è possibile specificare un solo tipo di membro. I tipi di membro specificati sono: "{0}" + + + Non è possibile aggiungere un membro di tipo "{0}". Specificare un tipo diverso per il parametro MemberTypes. + + + Il parametro SecondValue non è necessario per un membro di tipo "{0}" e non deve essere specificato. Non specificare il parametro SecondValue quando si aggiungono membri di questo tipo. + + + Il parametro Value è obbligatorio per un membro di tipo "{0}". Specificare il parametro Value quando si aggiungono membri di questo tipo. + + + Entrambi i parametri Value e SecondValue non devono essere Null per un membro di tipo "{0}". Specificare un valore non null per uno dei due parametri. + + + Non è possibile aggiungere un membro con il nome "{0}" perché esiste già un membro con tale nome. Per sovrascrivere comunque il membro, aggiungere il parametro Force al comando. + + + Non è possibile forzare l'aggiunta del membro con nome "{0}" e tipo "{1}". Esiste già un membro con tale nome e tipo e il membro esistente non è un'estensione di istanza. + + + Il membro a cui fa riferimento questo alias non deve essere Null o vuoto. + + + Il parametro Value non deve essere Null per un membro di tipo "{0}". Specificare un valore non Null per il parametro Value quando si aggiungono membri di questo tipo. + + + Il parametro SecondValue non deve essere Null per un membro di tipo "{0}". Specificare un valore non Null per il parametro SecondValue quando si aggiungono membri di questo tipo. + + + Il parametro NotePropertyName non può accettare valori che possono essere convertiti nel tipo {0}. Per definire il nome di un membro con tali valori, utilizzare Add-Member e specificare il tipo di membro. + + + Il nome di un membro NoteProperty non deve essere Null o una stringa vuota. + + + Il parametro TypeName non deve essere Null, vuoto o contenere solo spazi vuoti. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/AddTypeStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/AddTypeStrings.it.resx new file mode 100644 index 00000000000..d254da85a24 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/AddTypeStrings.it.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 + + + Il codice sorgente è già stato compilato e caricato. + + + Non è possibile aggiungere il tipo. L'estensione "{0}" non è supportata. + + + Non è possibile aggiungere il tipo. Tutti i file di input devono avere la stessa estensione. + + + Non è possibile aggiungere il tipo. Non è possibile trovare l'assembly '{0}'. + + + Non è possibile aggiungere il tipo. Il nome del tipo '{0}' esiste già. + + + Non è possibile impostare l'assembly di output. Il percorso {0} non è stato risolto in un singolo file. + + + Non è possibile aggiungere il tipo. Si sono verificati errori di compilazione. + + + Non è possibile aggiungere il tipo. Per il parametro OutputType è necessario specificare il parametro OutputAssembly. + + + Non è possibile aggiungere il tipo. La definizione de nuovi tipi non è supportata in questa modalità di linguaggio. + + + L'assembly di riferimento '{0}' specificato non è necessario e viene ignorato. + + + Entrambi i tipi di assembly 'ConsoleApplication' e 'WindowsApplication' non sono attualmente supportati. + + + Add-Type Cmdlet + + + Il cmdlet Add-Type non sarà consentito in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/AliasCommandStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/AliasCommandStrings.it.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/AliasCommandStrings.it.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertFromStringData.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertFromStringData.it.resx new file mode 100644 index 00000000000..bfeba170a2a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertFromStringData.it.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 + + + La riga di dati "{0}" non è nel formato "nome=valore". + + + L'elemento di dati "{1}" nella riga "{0}" è già definito. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertHTMLStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertHTMLStrings.it.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertHTMLStrings.it.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertMarkdownStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertMarkdownStrings.it.resx new file mode 100644 index 00000000000..08b4e072260 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ConvertMarkdownStrings.it.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 + + + Il tipo dell'oggetto di input ''{0}'' non è valido. + + + Sono supportati solo i percorsi del provider FileSystem. Il percorso del file non è supportato: ''{0}''. + + + La proprietà {0} dell'oggetto specificato è null o vuota. + + + Nome del set di parametri non valido: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/CsvCommandStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/CsvCommandStrings.it.resx new file mode 100644 index 00000000000..c9ddadf276d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/CsvCommandStrings.it.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 + + + Non è possibile aggiungere contenuto CSV al file seguente: {1}. L'oggetto da aggiungere non dispone di una proprietà corrispondente alla colonna seguente: {0}. Per continuare nonostante le proprietà non corrispondenti, aggiungere il parametro -Force e riprovare il comando. + {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. + + + + È necessario specificare il parametro -UseQuotes o -QuoteFields, ma non entrambi. + + + È necessario specificare il parametro -Path o -LiteralPath, ma non entrambi. + + + Una o più intestazioni non sono state specificate. Sono stati usati nomi predefiniti che iniziano con "H" al posto delle intestazioni mancanti. + + + FileName è un parametro obbligatorio. + + + Il metodo ReconcilePreexistingPropertyNames deve essere chiamato solo durante l'accodamento. + + + Il metodo ReconcilePreexistingPropertyNames deve essere chiamato solo quando i nomi di proprietà preesistenti sono stati letti correttamente. + + + Il metodo BuildPropertyNames deve essere chiamato una sola volta per istanza di cmdlet. + + + La gerarchia dei tipi non deve contenere valori null. + + + EOF è stato raggiunto. + + + È necessario specificare il parametro -Append o -NoHeader, ma non entrambi. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/Debugger.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/Debugger.it.resx new file mode 100644 index 00000000000..d5dfffa76e6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/Debugger.it.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}'. + + + Il file '{0}' non esiste. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/EventingStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/EventingStrings.it.resx new file mode 100644 index 00000000000..9f53a99ad32 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/EventingStrings.it.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 + + + L'evento con identificatore di origine "{0}" non esiste. + + + L'evento con identificatore "{0}" non esiste. + + + La sottoscrizione evento con identificatore di origine"{0}" non esiste. + + + La sottoscrizione evento con identificatore"{0}" non esiste. + + + Sottoscrizione evento "{0}" + + + Evento "{0}" + + + È necessario specificare un'azione per gli eventi non inoltrati. + + + Annulla la sottoscrizione + + + Rimuovi + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/FormatAndOut_out_gridview.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/FormatAndOut_out_gridview.it.resx new file mode 100644 index 00000000000..04b57c10fbf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/FormatAndOut_out_gridview.it.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 + + + Il formato dei dati non è supportato da Out-GridView. + + + Microsoft .NET Framework 4.5 è stato installato durante l'esecuzione di una o più sessioni di PowerShell. Per usare il cmdlet {0}, chiudere tutte le finestre di PowerShell e quindi aprire una nuova finestra di PowerShell. + + + Tipo + + + Valore + + + Indice + + + Non è possibile trovare un comando denominato ''{0}''. + + + È stato trovato più di un comando denominato ''{0}''. Avviare ''{1}'' senza parametri, quindi digitare ''{0}'' per filtrare i risultati. + + + Non è possibile scrivere nel buffer di input della console. + + + {0} deve essere minore di {1}. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetFormatDataStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetFormatDataStrings.it.resx new file mode 100644 index 00000000000..c7c49b8e7de --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetFormatDataStrings.it.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 + + + Elaborazione della definizione della vista ''{0}'' + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetMember.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetMember.it.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetMember.it.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetRandomCommandStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetRandomCommandStrings.it.resx new file mode 100644 index 00000000000..ff0b5a5cd17 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetRandomCommandStrings.it.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'' deve essere maggiore di zero. + + + Il valore minimo ({0}) non può essere maggiore o uguale al valore massimo ({1}). + + + ''minValue'' non può essere maggiore di maxValue. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetUptimeStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetUptimeStrings.it.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/GetUptimeStrings.it.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/HostStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/HostStrings.it.resx new file mode 100644 index 00000000000..f9e12f33016 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/HostStrings.it.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 + + + Non è possibile elaborare il colore perché {0} non è un colore valido. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/HttpCommandStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/HttpCommandStrings.it.resx new file mode 100644 index 00000000000..4ffef6614bd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/HttpCommandStrings.it.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 + + + Non è possibile completare il comando a causa dell'errore seguente: ''{0}''. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/ImplicitRemotingStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ImplicitRemotingStrings.it.resx new file mode 100644 index 00000000000..92676a65fb6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ImplicitRemotingStrings.it.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 + + + I dati restituiti dal comando remoto {0} non sono nel formato previsto. + + + Il {0} cmdlet richiede i comandi seguenti nella sessione remota: Get-Command, Get-FormatData e Select-Object. Vengono usati i comandi seguenti, ma sono facoltativi: Get-Help e Measure-Object. Verificare che la sessione remota includa i comandi necessari, quindi riprovare. + + + Durante l'esecuzione del comando {0} in una sessione remota si è verificato l'errore seguente: {1}. + + + L'esecuzione del comando {0} in una sessione remota non ha restituito alcun risultato. + + + Nessuna sessione è stata associata a questo modulo di comunicazione remota implicita. + + + Non è possibile risolvere l'alias remoto '{0}'. + + + La creazione del proxy è stata ignorata per il comando '{0}' perché il nome non corrisponde al valore del parametro Name. + + + La definizione di tipo estesa è stata ignorata per il tipo '{0}' perché il nome non corrisponde al valore del parametro FormatTypeName. + + + La creazione del proxy è stata ignorata per il comando '{0}' perché PowerShell non è riuscito a verificare la sicurezza del nome del comando. + + + La creazione del proxy è stata ignorata per il comando seguente: '{0}', perché andrebbe a sovrapporsi a un comando locale esistente. Usare il parametro AllowClobber se si desidera nascondere i comandi locali esistenti. + + + Non è stato creato alcun proxy di comando perché tutti i comandi remoti richiesti andrebbero a sovrapporsi a comandi locali esistenti. Usare il parametro AllowClobber se si desidera nascondere i comandi locali esistenti. + + + Comunicazione remota implicita per {0} + + + Evento di comunicazione remota implicita (ID sessione: {0}; ID gestore eventi: {1}) + + + Modulo di comunicazione remota implicita + + + data di generazione: {0} + + + da {0} cmdlet + + + A tale scopo, eseguire la riga di comando seguente: {0} + + + Parametro facoltativo che può essere usato per specificare la sessione su cui opera questo modulo proxy + + + Creazione di una nuova sessione per la comunicazione remota implicita del comando "{{0}}"... + + + Sessione del modulo di comunicazione remota implicita in {{0}} + + + Creazione del modulo di comunicazione remota implicita... + + + Recupero delle informazioni sui comandi dalla sessione remota ... + + + Recupero delle informazioni sui comandi dalla sessione remota ... {0} comandi ricevuti + + + Recupero delle informazioni di formattazione e di output dalla sessione remota ... + + + Recupero delle informazioni di formattazione e di output dalla sessione remota ... {0} oggetti ricevuti + + + Completato. + + + Richiesta di credenziali di PowerShell + + + Immettere le credenziali per {0}. + + + Immettere le credenziali del proxy HTTP usate per la connessione seguente: {0} + + + I comandi disponibili nella nuova sessione remota sono diversi da quelli disponibili quando è stato creato il modulo di comunicazione remota implicita. Valutare la possibilità di creare di nuovo il modulo usando il cmdlet Export-PSSession. + + + Non è possibile caricare i file perché l'esecuzione di script è disabilitata nel sistema. Specificare un certificato valido con cui firmare i file. + + + Non è stato possibile firmare il file {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/ImportLocalizedDataStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ImportLocalizedDataStrings.it.resx new file mode 100644 index 00000000000..8d778cae89c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/ImportLocalizedDataStrings.it.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 + + + Non è possibile trovare il file di dati '{0}'. + + + Il parametro FileName non è specificato. Il parametro FileName è obbligatorio quando Import-LocalizedData non viene richiamato da un file script. + + + Si è verificato l'errore seguente durante l'apertura del file di dati '{0}' da parte di PowerShell: +{1}. + + + Si è verificato l'errore seguente durante il caricamento del file di dati script '{0}' da parte di PowerShell: +{1}. + + + L'argomento per il parametro FileName non deve contenere un percorso. + + + Non è possibile trovare il file di dati di PowerShell '{0}' nella directory '{1}' o in alcuna directory delle impostazioni cultura padre. + + + Non è possibile importare dati localizzati. La definizione di comandi aggiuntivi supportati non è consentita in questa modalità del linguaggio. + + + Il nome della BindingVariable '{0}' non è valido. + + + Import-LocalizedData Cmdlet + + + I comandi aggiuntivi supportati (tramite il parametro SupportedCommand) non sono consentiti in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/MatchStringStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/MatchStringStrings.it.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/MatchStringStrings.it.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/MeasureObjectStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/MeasureObjectStrings.it.resx new file mode 100644 index 00000000000..323e0c21271 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/MeasureObjectStrings.it.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 + + + Non è possibile trovare la proprietà "{0}" nell'input di alcun oggetto. + + + L'oggetto di input "{0}" non è numerico. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/NewObjectStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/NewObjectStrings.it.resx new file mode 100644 index 00000000000..6c50ca091bc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/NewObjectStrings.it.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 + + + Costruttore non trovato. Non è possibile trovare un costruttore appropriato per il tipo {0}. + + + Non è possibile trovare il tipo [{0}]: verificare che l'assembly contenente questo tipo sia caricato. + + + Non è possibile caricare il tipo COM {0}. + + + L'oggetto scritto nella pipeline è un'istanza del tipo "{0}" dall'assembly di interoperabilità primario del componente. Se questo tipo espone membri diversi rispetto ai membri IDispatch, gli script scritti per lavorare con questo oggetto potrebbero non funzionare se l'assembly di interoperabilità primario non è installato. + + + Non è possibile trovare il membro "{1}" per l'oggetto {2} specificato. + + + Il valore specificato non è valido o la proprietà è di sola lettura. Modificare il valore, quindi riprovare. + + + La creazione di istanze di attributi e tipi di Windows RT delegati non è supportata. + + + Non è possibile creare istanze del tipo simile a ByRef "{0}". I tipi simili a ByRef non sono supportati in PowerShell. + + + Non è possibile creare il tipo. In questa modalità linguaggio sono supportati solo i tipi di base. + + + Non è possibile creare il tipo. Solo i tipi di base sono supportati in modalità lingua {0} in un computer con criteri bloccati. + + + Creazione del tipo di cmdlet New-Object + + + Il tipo ''{0}'' non verrà creato in modalità ConstrainedLanguage. + + + Creazione di oggetti COM cmdlet New-Object + + + L'oggetto COM ''{0}'' non verrà creato in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/OutPrinterDisplayStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/OutPrinterDisplayStrings.it.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/OutPrinterDisplayStrings.it.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/SelectObjectStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/SelectObjectStrings.it.resx new file mode 100644 index 00000000000..c7ead22dbdc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/SelectObjectStrings.it.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 + + + Non è possibile rinominare più risultati. + + + Non è possibile trovare la proprietà "{0}". + + + Non è possibile espandere più proprietà. + + + La proprietà non può essere elaborata perché la proprietà "{0}" esiste già. + + + Una proprietà è un blocco di script vuoto e non fornisce un nome. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/SendMailMessageStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/SendMailMessageStrings.it.resx new file mode 100644 index 00000000000..83d2d662ddc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/SendMailMessageStrings.it.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 + + + Non è possibile inviare il messaggio e-mail perché non è stato specificato alcun server SMTP. È necessario specificare un server SMTP usando il parametro SmtpServer o la variabile $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/SortObjectStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/SortObjectStrings.it.resx new file mode 100644 index 00000000000..d2b3bdf96ad --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/SortObjectStrings.it.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": Non è possibile trovare "{0}" in "InputObject". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/StartSleepStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/StartSleepStrings.it.resx new file mode 100644 index 00000000000..b4149bedd14 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/StartSleepStrings.it.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 + + + Il valore del parametro "-Duration" non deve superare "{0}", il valore specificato era "{1}". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/TestJsonCmdletStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/TestJsonCmdletStrings.it.resx new file mode 100644 index 00000000000..180ebbf7e6f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/TestJsonCmdletStrings.it.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 è possibile analizzare lo schema JSON. + + + Non è possibile analizzare il JSON. + + + Il JSON non è valido rispetto allo schema: {0} in "{1}" + + + Non è possibile aprire il file di schema JSON: {0} + + + Lo schema URI "{0}" non è supportato. Sono consentiti solo URI HTTP(S) e del file system locale. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/TraceCommandStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/TraceCommandStrings.it.resx new file mode 100644 index 00000000000..bc95d839f91 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/TraceCommandStrings.it.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 + + + L'output di traccia può essere scritto solo nel file system. Il percorso '{0}' fa riferimento a un percorso del provider '{1}'. + + + L'output di traccia può essere scritto solo in un singolo file. Il percorso '{0}' è stato risolto in più file. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/UnblockFileStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UnblockFileStrings.it.resx new file mode 100644 index 00000000000..100877f6ab4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UnblockFileStrings.it.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 + + + Il cmdlet non supporta Linux. + + + Si è verificato un errore durante la rimozione del blocco {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/UpdateDataStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UpdateDataStrings.it.resx new file mode 100644 index 00000000000..2b9426ad0a8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UpdateDataStrings.it.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 + + + Non è possibile aprire il file perché il provider corrente è "{0}" e questo comando richiede un file. + + + Non è possibile leggere il file "{0}" perché non ha l'estensione "{1}". + + + Aggiorna TypeData + + + Aggiorna FormatData + + + FileName: {0} + + + Non è possibile aggiornare un membro con tipo "{0}". Specificare un tipo diverso per il parametro MemberType. + + + Il parametro {0} è obbligatorio per il tipo "{1}". Specificare il parametro {0}. + + + Il parametro {0} non deve essere null o una stringa vuota per un membro di tipo "{1}". Specificare un valore non null per il parametro {0} quando si aggiorna questo tipo di membro. + + + Il parametro {0} non è necessario per un membro di tipo "{1}" e non deve essere specificato. Non specificare il parametro {0} quando si aggiorna questo tipo di membro. + + + Nessun membro è specificato per l'aggiornamento sul tipo "{0}". + + + Il nome del tipo di destinazione non deve essere null, vuoto o contenere solo spazi vuoti. + + + I parametri Value e SecondValue non devono essere entrambi null per un membro di tipo "{0}". Specificare un valore non null per uno dei due parametri. + + + È possibile specificare un solo tipo di membro. I tipi di membro specificati sono: "{0}". Aggiornare il tipo con un solo tipo di membro. + + + Non è possibile specificare parametri MemberName, Value e SecondValue senza il parametro MemberType. + + + Rimuovi TypeData + + + Nome del tipo che verrà rimosso: {0} + + + Tipo da aggiornare: {0} + + + Rimuovi tipo di file + + + Il file {0} non è stato importato nella sessione corrente. + + + L'aggiornamento dei dati di formato non è consentito in questo spazio di esecuzione. La proprietà 'DisableFormatUpdates' è impostata su True durante la creazione dello spazio di esecuzione. + + + Non è possibile aggiornare i dati di formato con un'istanza di FormatTable. + + + Non è possibile aggiornare i dati del tipo con un'istanza di TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/UpdateListStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UpdateListStrings.it.resx new file mode 100644 index 00000000000..79c35ef3a6a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UpdateListStrings.it.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 + + + Non è possibile trovare la proprietà '{0}' in questo oggetto + + + È necessario specificare il parametro Property quando si specifica il parametro InputObject. + + + È necessario specificare il parametro InputObject quando si specifica il parametro Property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/UtilityCommonStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UtilityCommonStrings.it.resx new file mode 100644 index 00000000000..4463108dd8e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/UtilityCommonStrings.it.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} presenta una o più eccezioni non valide. + + + Questo comando non può essere eseguito perché il percorso del file "{0}" non è valido. Specificare un percorso di file valido e quindi eseguire il comando. + + + Questo comando non può essere eseguito perché "{0}" è vuoto o non contiene caratteri. Specificare CSSUri e quindi eseguire il comando. + + + Non è possibile aprire il file perché il provider corrente ({0}) non può aprire i file. + + + Questo comando non può essere eseguito perché il valore del prefisso nel parametro Namespace è Null. Specificare un valore valido per il prefisso e quindi eseguire di nuovo il comando. + + + Gli oggetti raggruppati in base a questa proprietà non possono essere espansi perché è presente una chiave duplicata. Specificare un valore valido per la proprietà e quindi riprovare. + + + Il comando non è supportato in questo sistema operativo. + + + Non è possibile leggere il file "{0}": {1} + + + Non è possibile convertire l'input di tipo "{0}" in esadecimale. Per visualizzare la formattazione esadecimale della relativa rappresentazione di stringa, inviarla tramite pipe al cmdlet Out-String prima di inviarla tramite pipe a Format-Hex. + + + Il percorso specificato "{0}" non è supportato. Questo comando supporta solo i percorsi del provider FileSystem. + + + Percorso: + + + Non è possibile eseguire il comando perché il parametro AsString richiede di specificare il parametro AsHashtable. + + + Non è possibile eseguire il comando perché per usare il parametro AsHashTable con più di una proprietà è necessario aggiungere il parametro AsString. + + + Non è possibile trovare il percorso '{0}' perché non esiste. + + + Non è possibile usare il tag "{0}". Il prefisso "PS" è riservato. + + + Non è possibile analizzare il file "{0}" come file di dati di PowerShell. + + + Non è possibile creare un descrittore di sicurezza dall'SDDL specificato a causa dell'errore seguente: {0} + + + Cmdlet Invoke-Expression + + + Il blocco di script del cmdlet Invoke-Expression verrà eseguito in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/VariableCommandStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/VariableCommandStrings.it.resx new file mode 100644 index 00000000000..1fbfda2431e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/VariableCommandStrings.it.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 + + + Imposta variabile + + + Nome: {0} Valore: {1} + + + Usare una singola variabile invece di una raccolta + + + Nuova variabile + + + Nome: {0} Valore: {1} + + + Rimuovi variabile + + + Nome: {0} + + + Cancella variabile + + + Nome: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/WebCmdletStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/WebCmdletStrings.it.resx new file mode 100644 index 00000000000..ded891dfa8f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/WebCmdletStrings.it.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 + + + L'accesso al percorso '{0}' è stato negato. + + + Il cmdlet non può proteggere i segreti in testo normale inviati tramite connessioni non crittografate. Per non visualizzare più questo messaggio e inviare segreti in testo normale su reti non crittografate, rieseguire il comando specificando il parametro AllowUnencryptedAuthentication. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: Authentication e UseDefaultCredentials. Authentication non supporta le credenziali predefinite. Specificare Authentication o UseDefaultCredentials, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché manca il seguente parametro: Credential. Il tipo Authentication specificato richiede una Credenziale. Specificare Credential, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché manca il seguente parametro: Token. Il tipo Authentication specificato richiede un Token. Specificare Token, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: Credential e Token. Specificare Credential o Token, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: Body e InFile. Specificare Body o InFile, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: Body e Form. Specificare Body o Form, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: InFile e Form. Specificare InFile o Form, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché il parametro -ContentType non è un'intestazione Content-Type valida. Specificare un Content-Type valido per -ContentType, quindi riprovare. Per disabilitare la convalida dell'intestazione, specificare il parametro -SkipHeaderValidation. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: Credential e UseDefaultCredentials. Specificare Credential o UseDefaultCredentials, quindi riprovare. + + + Il percorso '{0}' viene risolto come directory. Specificare un percorso che includa il nome di un file, quindi riprovare il comando. + + + Il JSON fornito include una proprietà il cui nome è una stringa vuota. Questa operazione è supportata solo con l'opzione -AsHashTable. + + + Non è possibile convertire la stringa JSON perché un dizionario convertito dalla stringa contiene la chiave duplicata '{0}'. + + + Non è possibile analizzare il contenuto della risposta perché il motore di Internet Explorer non è disponibile, oppure la configurazione del primo avvio di Internet Explorer non è completa. Specificare il parametro UseBasicParsing e riprovare. + + + Non è possibile seguire per impostazione predefinita un reindirizzamento non sicuro. Rieseguire il comando specificando l'opzione -AllowInsecureRedirect. + + + Non è possibile convertire la stringa JSON perché contiene chiavi con maiuscole e minuscole diverse. Usare invece l'opzione -AsHashTable. La chiave che si è tentato di aggiungere alla chiave esistente '{0}' era '{1}'. + + + È stato superato il numero massimo di reindirizzamenti. Per aumentare il numero di reindirizzamenti consentiti, specificare un valore più alto per il parametro -MaximumRedirection. + + + Il percorso '{0}' può essere risolto in più percorsi. + + + Il tipo '{0}' non è supportato per la serializzazione o la deserializzazione di un dizionario. Le chiavi devono essere stringhe. + + + Non è possibile risolvere il percorso '{0}' in un file. + + + Il percorso '{0}' non è un percorso del file system. Specificare il percorso di un file nel file system. + + + Non è possibile eseguire il cmdlet perché manca il seguente parametro: OutFile. Specificare un valore valido per il parametro OutFile quando si usa il parametro {0}, quindi riprovare. + + + Il file non verrà scaricato di nuovo perché il file remoto ha le stesse dimensioni di OutFile: {0} + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: ProxyCredential e ProxyUseDefaultCredentials. Specificare ProxyCredential o ProxyUseDefaultCredentials, quindi riprovare. + + + Non è possibile eseguire il cmdlet perché manca il seguente parametro: Proxy. Specificare un URI proxy valido per il parametro Proxy quando si usano i parametri ProxyCredential o ProxyUseDefaultCredentials, quindi riprovare. + + + Lettura del flusso di risposta Web completata. Byte scaricati: {0} + + + Lettura del flusso di risposta Web + + + Scaricati: {0} di {1} + + + L'opzione Riprendi può essere usata solo se OutFile punta a un file, ma viene risolto in una directory: {0}. + + + Non è possibile eseguire il cmdlet perché sono stati specificati i seguenti parametri in conflitto: Session e SessionVariable. Specificare Session o SessionVariable, quindi riprovare. + + + Non è possibile recuperare i certificati perché l'identificazione personale non è valida. Verificare l'identificazione personale e riprovare. + + + Richiesta Web completata. (Numero di byte elaborati: {0}) + + + Richiesta Web annullata. (Numero di byte elaborati: {0}) + + + Stato della richiesta Web + + + Scaricati: {0} di {1} + + + Conversione da JSON non riuscita con errore: {0} + + + Il codice di stato della risposta non indica la riuscita dell'operazione: {0} ({1}). + + + Seguendo il collegamento rel {0} + + + Il server remoto ha indicato che non è possibile riprendere il download. Il file locale verrà sovrascritto. + + + Ricevuta risposta HTTP/{0} di tipo di contenuto {1} e di dimensioni sconosciute + + + Nuovo tentativo tra {0} secondi. Codice di stato del tentativo precedente: {1} + + + Il JSON risultante viene troncato perché la serializzazione ha superato la profondità impostata di {0}. + + + Le proprietà di WebSession sono state modificate tra una richiesta e l'altra, costringendo a ricreare tutte le connessioni HTTP nella sessione. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/WriteErrorStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/WriteErrorStrings.it.resx new file mode 100644 index 00000000000..e6dcfd02ef0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/WriteErrorStrings.it.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 + + + "Il cmdlet Write-Error ha segnalato un errore". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/it/WriteProgressResourceStrings.it.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/it/WriteProgressResourceStrings.it.resx new file mode 100644 index 00000000000..848e353c1b0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/it/WriteProgressResourceStrings.it.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 + + + Testo che descrive l'attività per cui viene segnalato lo stato di avanzamento. + + + Testo che descrive lo stato corrente dell'attività per cui viene segnalato lo stato di avanzamento. + + + Elaborazione + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AddMember.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AddMember.ja.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AddMember.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AddTypeStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AddTypeStrings.ja.resx new file mode 100644 index 00000000000..57b1ecbdf30 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AddTypeStrings.ja.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 + + + ソース コードはすでにコンパイルされ、読み込まれています。 + + + 型を追加できません。"{0}" 拡張子はサポートされていません。 + + + 型を追加できません。入力ファイルはすべて同じファイル拡張子である必要があります。 + + + 型を追加できません。アセンブリ {0} が見つかりませんでした。 + + + 型を追加できません。型の名前 '{0}' は既に存在します。 + + + 出力アセンブリを設定できません。パス {0} は 1 つのファイルに解決されませんでした。 + + + 型を追加できません。コンパイル エラーが発生しました。 + + + 型を追加できません。OutputType パラメーターを指定するには、OutputAssembly パラメーターが必要です。 + + + 型を追加できません。この言語モードでは、新しい型の定義はサポートされていません。 + + + 指定された参照アセンブリ '{0}' は不要なため、無視されます。 + + + アセンブリの型 'ConsoleApplication' と 'WindowsApplication' は、どちらも現在サポートされていません。 + + + Add-Type コマンドレット + + + Add-Type コマンドレットは ConstrainedLanguage モードでは許可されません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AliasCommandStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AliasCommandStrings.ja.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/AliasCommandStrings.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertFromStringData.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertFromStringData.ja.resx new file mode 100644 index 00000000000..9c8e13242b3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertFromStringData.ja.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 + + + データ行 '{0}' は 'name=value' 形式ではありません。 + + + 行 '{0}' のデータ項目 '{1}' は既に定義されています。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertHTMLStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertHTMLStrings.ja.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertHTMLStrings.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertMarkdownStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertMarkdownStrings.ja.resx new file mode 100644 index 00000000000..0aab95b023b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ConvertMarkdownStrings.ja.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 + + + 入力オブジェクト '{0}' の型が無効です。 + + + FileSystem プロバイダー パスのみがサポートされています。ファイル パス '{0}' はサポートされていません。 + + + 指定されたオブジェクトのプロパティ {0} が null 値または空です。 + + + 無効なパラメーター セット名: {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/CsvCommandStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/CsvCommandStrings.ja.resx new file mode 100644 index 00000000000..b3ecec46d6b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/CsvCommandStrings.ja.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 + + + CSV コンテンツを次のファイルに追加できません: {1}。追加されたオブジェクトには、次の列に対応するプロパティがありません: {0}。一致しないプロパティを続行するには、-Force パラメーターを追加してから、コマンドを再試行してください。 + {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. + + + + -UseQuotes パラメーターまたは -QuoteFields パラメーターを指定する必要がありますが、両方を指定することはできません。 + + + -Path パラメーター、または -LiteralPath パラメーターのいずれかを指定する必要がありますが、両方を指定することはできません。 + + + 1 つ以上のヘッダーが指定されませんでした。不足しているヘッダーの代わりに、"H" で始まる既定の名前が使用されています。 + + + FileName は必須パラメーターです。 + + + ReconcilePreexistingPropertyNames メソッドは、追加時にのみ呼び出されます。 + + + ReconcilePreexistingPropertyNames メソッドは、既存のプロパティ名が正常に読み取られた場合にのみ呼び出されます。 + + + BuildPropertyNames メソッドは、コマンドレット インスタンスごとに 1 回だけ呼び出す必要があります。 + + + 型階層に null 値を含めてはなりません。 + + + EOF に達しました。 + + + -Append パラメーターまたは -NoHeader パラメーターを指定する必要がありますが、両方を指定することはできません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/Debugger.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/Debugger.ja.resx new file mode 100644 index 00000000000..bb3e7a77f25 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/Debugger.ja.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}'. + + + ファイル '{0}' が存在しません。 + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/EventingStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/EventingStrings.ja.resx new file mode 100644 index 00000000000..e0f5dca954a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/EventingStrings.ja.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 + + + ソース識別子 '{0}' を持つイベントは存在しません。 + + + 識別子 '{0}' を持つイベントは存在しません。 + + + ソース識別子 '{0}' を持つイベント サブスクリプションは存在しません。 + + + 識別子 '{0}' を持つイベント サブスクリプションは存在しません。 + + + イベント サブスクリプション '{0}' + + + イベント '{0}' + + + 転送されないイベントには、アクションを指定する必要があります。 + + + 受信登録の取り消し + + + 削除 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/FormatAndOut_out_gridview.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/FormatAndOut_out_gridview.ja.resx new file mode 100644 index 00000000000..a7d5abcad08 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/FormatAndOut_out_gridview.ja.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 + + + このデータ形式は Out-GridView ではサポートされていません。 + + + 1 つ以上の PowerShell セッションの実行中に、Microsoft .NET Framework 4.5 がインストールされました。{0} コマンドレットを使用するには、すべての PowerShell ウィンドウを閉じてから、新しい PowerShell ウィンドウを開いてください。 + + + + + + + + + インデックス + + + '{0}' という名前のコマンドが見つかりませんでした。 + + + '{0}' という名前のコマンドが複数見つかりました。パラメーターなしで '{1}' を開始し、'{0}' と入力して結果をフィルター処理します。 + + + コンソールの入力バッファーに書き込めません。 + + + {0} は {1} より小さくする必要があります。 + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetFormatDataStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetFormatDataStrings.ja.resx new file mode 100644 index 00000000000..5c73654c618 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetFormatDataStrings.ja.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 + + + ビュー定義 '{0}' を処理しています + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetMember.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetMember.ja.resx new file mode 100644 index 00000000000..d2a9278b2d6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetMember.ja.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 + + + Get-Member コマンドレットのオブジェクトを指定する必要があります。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetRandomCommandStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetRandomCommandStrings.ja.resx new file mode 100644 index 00000000000..e98eb114916 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetRandomCommandStrings.ja.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' は 0 よりも大きくする必要があります。 + + + 最小値 ({0}) を最大値 ({1}) 以上にすることはできません。 + + + 'minValue' を maxValue より大きくすることはできません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetUptimeStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetUptimeStrings.ja.resx new file mode 100644 index 00000000000..2a231223709 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/GetUptimeStrings.ja.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 + + + "プラットフォームはサポートされていません (System.Diagnostics.Stopwatch.IsHighResolution は false です)。" + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/HostStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/HostStrings.ja.resx new file mode 100644 index 00000000000..ed16d85df7e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/HostStrings.ja.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 + + + {0} が有効な色ではないため、色を処理できません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/HttpCommandStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/HttpCommandStrings.ja.resx new file mode 100644 index 00000000000..35bb2013d4d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/HttpCommandStrings.ja.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 + + + 次のエラーのため、このコマンドを完了できません: '{0}'。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ImplicitRemotingStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ImplicitRemotingStrings.ja.resx new file mode 100644 index 00000000000..c01bfc8fd7f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ImplicitRemotingStrings.ja.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 + + + リモート {0} コマンドによって返されるデータの形式が正しくありません。 + + + {0} コマンドレットには、リモート セッションで Get-Command、Get-FormatData、Select-Object の各コマンドが必要です。次のコマンドが使用されますが、Get-Help と Measure-Object は省略可能です。リモート セッションに必要なコマンドが含まれていることを確認してから、もう一度やり直してください。 + + + リモート セッションで {0} コマンドを実行すると、次のエラーが報告されました: {1}。 + + + リモート セッションで {0} コマンドを実行しても結果が返されませんでした。 + + + この暗黙的なリモート処理モジュールに関連付けられているセッションはありません。 + + + リモート エイリアス '{0}' を解決できませんでした。 + + + 名前が "Name" パラメーターの値と一致しなかったため、'{0}' コマンドのプロキシの作成はスキップされました。 + + + '{0}' 型の名前が FormatTypeName パラメーターの値と一致しなかったため、拡張型定義はスキップされました。 + + + PowerShell がコマンド名の安全性を確認できなかったため、'{0}' コマンドのプロキシの作成はスキップされました。 + + + 次のコマンドのプロキシの作成はスキップされました: '{0}'。これは既存のローカル コマンドをシャドウするためです。 既存のローカル コマンドをシャドウする場合は、AllowClobber パラメーターを使用します。 + + + 要求されたすべてのリモート コマンドが既存のローカル コマンドをシャドウするため、コマンド プロキシは作成されていません。 既存のローカル コマンドをシャドウする場合は、AllowClobber パラメーターを使用します。 + + + {0} の暗黙的なリモート処理 + + + 暗黙的なリモート処理イベント (セッション ID: {0}; イベント ハンドラー ID: {1}) + + + 暗黙的なリモート処理モジュール + + + {0} に生成 + + + {0} コマンドレットごと + + + 次のコマンドラインで起動されました: {0} + + + このプロキシ モジュールが動作するセッションを指定するために使用できる省略可能なパラメーター + + + "{{0}}" コマンドの暗黙的なリモート処理のための新しいセッションを作成しています... + + + {{0}} での暗黙的なリモート処理モジュールのセッション + + + 暗黙的なリモート処理モジュールを作成しています... + + + リモート セッションからコマンド情報を取得しています... + + + リモート セッションからコマンド情報を取得しています... {0} 受信したコマンド + + + リモート セッションから書式設定と出力情報を取得しています... + + + リモート セッションから書式設定と出力情報を取得しています... {0} 受信したオブジェクト + + + 完了しました。 + + + PowerShell 資格情報の要求 + + + {0} の資格情報を入力してください。 + + + 次の接続に使用する HTTP プロキシ資格情報を入力します: {0} + + + 新しいリモート セッションで使用できるコマンドは、暗黙的なリモート処理モジュールの作成時に使用できるコマンドとは異なります。 Export-PSSession コマンドレットを使用して、モジュールをもう一度作成することを検討してください。 + + + 実行中のスクリプトがこのシステムで無効になっているため、ファイルを読み込めません。ファイルの署名に使用する有効な証明書を指定します。 + + + ファイル {0} を署名できませんでした。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ImportLocalizedDataStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ImportLocalizedDataStrings.ja.resx new file mode 100644 index 00000000000..6da5c02e3a5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/ImportLocalizedDataStrings.ja.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 + + + データ ファイル '{0}' が見つかりません。 + + + FileName パラメーターが指定されませんでした。Import-LocalizedData がスクリプト ファイルから呼び出されない場合、FileName パラメーターは必須です。 + + + PowerShell がデータ ファイル '{0}' を開く際に、次のエラーが発生しました: +{1}。 + + + PowerShell が '{0}' スクリプト データ ファイルを読み込む際に、次のエラーが発生しました: +{1}。 + + + FileName パラメーターの引数にパスを含めないでください。 + + + PowerShell データ ファイル '{0}' は、ディレクトリ '{1}' またはいずれの親カルチャー ディレクトリ内にも見つかりません。 + + + ローカライズされたデータをインポートできません。追加でサポートされるコマンドの定義は、この言語モードでは許可されません。 + + + BindingVariable 名 '{0}' は無効です。 + + + Import-LocalizedData コマンドレット + + + 追加でサポートされるコマンド (SupportedCommand パラメーター経由) は、ConstrainedLanguage モードでは許可されません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/MatchStringStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/MatchStringStrings.ja.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/MatchStringStrings.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/MeasureObjectStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/MeasureObjectStrings.ja.resx new file mode 100644 index 00000000000..6541603f7d1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/MeasureObjectStrings.ja.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 + + + プロパティ "{0}" は、どのオブジェクトの入力にも見つかりません。 + + + 入力オブジェクト "{0}" は数値ではありません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/NewObjectStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/NewObjectStrings.ja.resx new file mode 100644 index 00000000000..61881a7c9a0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/NewObjectStrings.ja.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 + + + コンストラクターが見つかりませんでした。型 {0}の適切なコンストラクターが見つかりません。 + + + 型 [{0}] が見つかりません: この型を含むアセンブリが読み込まれていることを確認してください。 + + + COM 型 {0} を読み込めません。 + + + パイプラインに書き込まれるオブジェクトは、コンポーネントのプライマリ相互運用性アセンブリからの "{0}" 型のインスタンスです。この型が IDispatch メンバーとは異なるメンバーを公開している場合、プライマリ相互運用性アセンブリがインストールされていないと、このオブジェクトで動作するように書き込まれたスクリプトが機能しない可能性があります。 + + + 指定された {2} オブジェクトのメンバー "{1}" が見つかりませんでした。 + + + 指定された値が無効であるか、プロパティが読み取り専用です。値を変更して、もう一度やり直してください。 + + + 属性型と委任されたWindows RT 型のインスタンスの作成はサポートされていません。 + + + ByRef に似た "{0}" 型のインスタンスは作成できません。ByRef に似た型は、PowerShell ではサポートされていません。 + + + 型を作成できません。この言語モードでは、コア型のみがサポートされています。 + + + 型を作成できません。ポリシーがロック ダウンされたコンピューターでは、{0} 言語モードではコア型のみがサポートされています。 + + + New-Object コマンドレットの型の作成 + + + 型 '{0}' は ConstrainedLanguage モードでは作成されません。 + + + New-Object コマンドレットの COM オブジェクトの作成 + + + COM オブジェクト '{0}' は ConstrainedLanguage モードでは作成されません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/OutPrinterDisplayStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/OutPrinterDisplayStrings.ja.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/OutPrinterDisplayStrings.ja.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SelectObjectStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SelectObjectStrings.ja.resx new file mode 100644 index 00000000000..4e352433020 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SelectObjectStrings.ja.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 + + + 複数の結果の名前を変更することはできません。 + + + プロパティ "{0}" が見つかりません。 + + + 複数のプロパティを展開することはできません。 + + + プロパティ "{0}" が既に存在するため、プロパティを処理できません。 + + + プロパティは空のスクリプト ブロックであり、名前は指定されません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SendMailMessageStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SendMailMessageStrings.ja.resx new file mode 100644 index 00000000000..c8a75a17efb --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SendMailMessageStrings.ja.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 + + + SMTP サーバーが指定されていないため、メールを送信できません。SMTPServer パラメーターまたは $PSEmailServer 変数を使用して SMTP サーバーを指定する必要があります。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SortObjectStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SortObjectStrings.ja.resx new file mode 100644 index 00000000000..e1935b54a64 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/SortObjectStrings.ja.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}" が "InputObject" に見つかりません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/StartSleepStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/StartSleepStrings.ja.resx new file mode 100644 index 00000000000..2761a76dc60 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/StartSleepStrings.ja.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 + + + '-Duration' パラメーターの値は '{0}' を超えることはできません。指定された値は '{1}' でした。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/TestJsonCmdletStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/TestJsonCmdletStrings.ja.resx new file mode 100644 index 00000000000..cbd5ee99cc2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/TestJsonCmdletStrings.ja.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 + + + JSON スキーマを解析できません。 + + + JSON を解析できません。 + + + JSON は '{1}' のスキーマ {0} で無効です + + + JSON スキーマ ファイルを開けません: {0} + + + URI スキーム '{0}' はサポートされていません。HTTP(S) およびローカル ファイル システムの URI のみが許可されています。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/TraceCommandStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/TraceCommandStrings.ja.resx new file mode 100644 index 00000000000..ae06806995b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/TraceCommandStrings.ja.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 + + + トレース出力は、ファイル システムにのみ書き込むことができます。パス '{0}' は '{1}' プロバイダー パスを参照しました。 + + + トレース出力は、1 つのファイルにのみ書き込むことができます。パス '{0}' は、複数のファイルに解決されました。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UnblockFileStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UnblockFileStrings.ja.resx new file mode 100644 index 00000000000..26b55d35614 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UnblockFileStrings.ja.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 + + + このコマンドレットは Linux をサポートしていません。 + + + {0} のブロック解除中にエラーが発生しました。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UpdateDataStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UpdateDataStrings.ja.resx new file mode 100644 index 00000000000..dbd215d7ad5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UpdateDataStrings.ja.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 + + + 現在のプロバイダーが "{0}" であるため、ファイルを開けません。このコマンドにはファイルが必要です。 + + + ファイル名拡張子 "{1}" がないため、ファイル "{0}" を読み取れません。 + + + TypeData の更新 + + + FormatData の更新 + + + Filename: {0} + + + 型が "{0}" のメンバーを更新できません。MemberType パラメーターに別の型を指定します。 + + + 型 " {1} " には、{0} パラメーターが必要です。{0} パラメーターを指定してください。 + + + 型 " {1} " のメンバーに対して、{0} パラメーターを null 値または空の文字列にすることはできません。このメンバー型を更新するときに、{0} パラメーターに null 値以外の値を指定します。 + + + {0} パラメーターは、型 "{1}" のメンバーには必要ありません。指定しないでください。このメンバー型を更新するときに、{0} パラメーターを指定しないでください。 + + + 型 "{0}" の更新にメンバーが指定されていません。 + + + ターゲットの型名を null 値、空、または空白のみにすることはできません。 + + + 型 "{0}" のメンバーの Value パラメーターと SecondValue パラメーターの両方を null 値にすることはできません。2 つのパラメーターのいずれかに null 値以外の値を指定します。 + + + 指定できるメンバー型は 1 つだけです。指定されたメンバー型は "{0}" です。メンバー型を 1 つだけ使用して型を更新します。 + + + MemberType パラメーターを指定しないと、MemberName、Value、SecondValue パラメーターを指定できません。 + + + TypeData の削除 + + + 削除される型の名前: {0} + + + 更新する種類: {0} + + + 種類のファイルを削除する + + + ファイル {0} は現在のセッションにインポートされません。 + + + この実行空間では、フォーマット データの更新は許可されていません。実行空間の作成時に "DisableFormatUpdates" プロパティが True に設定されます。 + + + FormatTable インスタンスでフォーマット データを更新できません。 + + + TypeTable インスタンスで型データを更新できません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UpdateListStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UpdateListStrings.ja.resx new file mode 100644 index 00000000000..bbe003b602a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UpdateListStrings.ja.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}' がこのオブジェクトに見つかりません + + + InputObject パラメーターを指定する場合は、Property パラメーターを指定する必要があります。 + + + Property パラメーターを指定する場合は、InputObject パラメーターを指定する必要があります。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UtilityCommonStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UtilityCommonStrings.ja.resx new file mode 100644 index 00000000000..ccdd020001b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/UtilityCommonStrings.ja.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} には無効な例外が 1 つ以上あります。 + + + ファイル パス '{0}' が無効なため、このコマンドは実行できません。有効なファイル パスを指定してから、コマンドを実行してください。 + + + '{0}' が空または空白であるため、このコマンドは実行できません。CSSUri を指定してから、コマンドを実行してください。 + + + 現在のプロバイダー ({0}) ではファイルを開けないため、このファイルを開けません。 + + + Namespace パラメーターのプレフィックス値が null であるため、このコマンドは実行できません。プレフィックスに有効な値を指定してから、コマンドを再度実行してください。 + + + このプロパティでグループ化されたオブジェクトは、キーが重複しているため展開できません。プロパティに有効な値を指定してから、やり直してください。 + + + このコマンドは、このオペレーティング システムではサポートされていません。 + + + ファイル '{0}' を読み取れません: {1} + + + 型 '{0}' の入力を 16 進数に変換できません。文字列表現の 16 進数形式を表示するには、Out-String コマンドレットにパイプしてから Format-Hex にパイプしてください。 + + + 指定されたパス '{0}' はサポートされていません。このコマンドでサポートされているのは、FileSystem プロバイダーのパスのみです。 + + + パス: + + + AsString パラメーターを使用するには、AsHashtable パラメーターを指定する必要があるため、このコマンドは実行できません。 + + + 複数のプロパティで AsHashTable パラメーターを使用するには、AsString パラメーターを追加する必要があるため、このコマンドは実行できません。 + + + パス '{0}' は存在しないため、見つかりません。 + + + タグ '{0}' を使用できません。'PS' プレフィックスは予約されています。 + + + ファイル '{0}' を PowerShell データ ファイルとして解析できませんでした。 + + + 次のエラーのため、指定された SDDL からセキュリティ記述子を構築できません: {0} + + + Invoke-Expression コマンドレット + + + Invoke-Expression コマンドレットのスクリプト ブロックは ConstrainedLanguage モードで実行されます。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/VariableCommandStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/VariableCommandStrings.ja.resx new file mode 100644 index 00000000000..2c6080f0131 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/VariableCommandStrings.ja.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 + + + 変数の設定 + + + 名前: {0}、値: {1} + + + コレクションではなく単一の変数を使用する + + + 新しい変数 + + + 名前: {0}、値: {1} + + + 変数の削除 + + + 名前: {0} + + + 変数のクリア + + + 名前: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WebCmdletStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WebCmdletStrings.ja.resx new file mode 100644 index 00000000000..bed18b034cd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WebCmdletStrings.ja.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 + + + パス '{0}' へのアクセスが拒否されました。 + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WriteErrorStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WriteErrorStrings.ja.resx new file mode 100644 index 00000000000..0da25011ef0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WriteErrorStrings.ja.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 + + + "Write-Error コマンドレットでエラーが報告されました。" + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WriteProgressResourceStrings.ja.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WriteProgressResourceStrings.ja.resx new file mode 100644 index 00000000000..81bfacb2172 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ja/WriteProgressResourceStrings.ja.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 + + + 進行状況を報告するアクティビティを説明するテキスト。 + + + 進行状況が報告されているアクティビティの現在の状態を説明するテキスト。 + + + 処理中 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AddMember.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AddMember.ko.resx new file mode 100644 index 00000000000..24ebef69ddf --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AddMember.ko.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 + + + 멤버를 추가하려면 멤버 형식을 하나만 지정할 수 있습니다. 지정된 멤버 형식은 "{0}"입니다. + + + "{0}" 형식의 멤버를 추가할 수 없습니다. MemberTypes 매개 변수에 다른 형식을 지정합니다. + + + SecondValue 매개 변수는 "{0}" 형식의 멤버에 필요하지 않으며, 지정하면 안 됩니다. 이 형식의 멤버를 추가할 때는 SecondValue 매개 변수를 지정하지 마세요. + + + "{0}" 형식의 멤버에는 Value 매개 변수가 필요합니다. 이 형식의 멤버를 추가할 때는 Value 매개 변수를 지정합니다. + + + "{0}" 형식의 멤버에 대해 Value 및 SecondValue 매개 변수는 둘 다 null이면 안 됩니다. 두 매개 변수 중 하나에 null이 아닌 값을 지정합니다. + + + 이름이 "{0}"인 멤버가 이미 있으므로 해당 이름의 멤버를 추가할 수 없습니다. 그래도 멤버를 덮어쓰려면 명령에 Force 매개 변수를 추가하세요. + + + 이름이 "{0}"이고 형식이 "{1}"인 멤버를 강제로 추가할 수 없습니다. 해당 이름과 형식의 멤버가 이미 있으며, 기존 멤버는 instance 확장이 아닙니다. + + + 이 별칭이 참조하는 멤버는 null이거나 비어 있으면 안 됩니다. + + + Value 매개 변수는 "{0}" 형식의 멤버에 대해 null이면 안 됩니다. 이 형식의 멤버를 추가할 때는 Value 매개 변수에 null이 아닌 값을 지정하세요. + + + SecondValue 매개 변수는 "{0}" 형식의 멤버에 대해 null이면 안 됩니다. 이 형식의 멤버를 추가할 때는 SecondValue 매개 변수에 null이 아닌 값을 지정합니다. + + + NotePropertyName 매개 변수에는 {0} 형식으로 변환할 수 있는 값을 사용할 수 없습니다. 이러한 값으로 멤버 이름을 정의하려면 Add-Member를 사용하고 멤버 형식을 지정하세요. + + + NoteProperty 멤버의 이름은 null이거나 빈 문자열이면 안 됩니다. + + + 대상 형식 이름은 null이거나, 비어 있거나, 공백만 포함해서는 안 됩니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AddTypeStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AddTypeStrings.ko.resx new file mode 100644 index 00000000000..0263c949247 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AddTypeStrings.ko.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 + + + 소스 코드가 이미 컴파일되어 로드되었습니다. + + + 유형을 추가할 수 없습니다. "{0}" 확장은 지원되지 않습니다. + + + 유형을 추가할 수 없습니다. 입력 파일의 파일 확장명은 모두 같아야 합니다. + + + 유형을 추가할 수 없습니다. 어셈블리 '{0}'을(를) 찾을 수 없습니다. + + + 유형을 추가할 수 없습니다. 형식 이름 '{0}'이(가) 이미 있습니다. + + + 출력 어셈블리를 설정할 수 없습니다. 경로 {0}이(가) 단일 파일로 확인되지 않았습니다. + + + 유형을 추가할 수 없습니다. 컴파일 오류가 발생했습니다. + + + 유형을 추가할 수 없습니다. OutputType 매개 변수를 사용하려면 OutputAssembly 매개 변수를 지정해야 합니다. + + + 유형을 추가할 수 없습니다. 이 언어 모드에서는 새 형식 정의를 지원하지 않습니다. + + + 지정한 참조 어셈블리 '{0}'은(는) 필요하지 않으므로 무시됩니다. + + + 어셈블리 형식 'ConsoleApplication'과 'WindowsApplication'은 현재 지원되지 않습니다. + + + Add-Type cmdlet + + + ConstrainedLanguage 모드에서는 Add-Type cmdlet을 사용할 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AliasCommandStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AliasCommandStrings.ko.resx new file mode 100644 index 00000000000..f874ebb8c49 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/AliasCommandStrings.ko.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 + + + 별칭 설정 + + + 이름: {0} 값: {1} + + + 새 별칭 + + + 이름: {0} 값: {1} + + + 별칭 가져오기 + + + 이름: {0} 값: {1} + + + 별칭을 내보낼 파일 {0}을(를) 열 수 없습니다. {1} + + + 별칭 파일 + + + 내보낸 사람: {0} + + + 날짜/시간: {0:F} + + + 컴퓨터 : {0} + + + 지정한 경로 '{0}'이(가) '{1}' 공급자 경로이므로 별칭을 가져올 수 없습니다. Path 매개 변수 값을 파일 시스템 경로로 변경합니다. + + + 경로 '{0}'에 여러 경로로 해석되는 와일드카드 문자가 포함되어 있어 별칭을 가져올 수 없습니다. 별칭은 한 파일에서만 가져올 수 있습니다. Path 매개 변수 값을 하나의 파일로 확인되는 경로로 변경하세요. + + + 별칭을 가져올 파일 {0}을(를) 열 수 없습니다. {1} + + + 별칭을 가져올 수 없습니다. 파일 '{0}'의 줄 번호 {1}은(는) 별칭에 대한 올바른 형식의 CSV(쉼표로 구분된 값 파일) 줄이 아닙니다. 줄에 쉼표로 구분된 4개의 값이 들어가도록 변경하세요. 값 텍스트 자체에 쉼표가 포함된 경우에는 해당 값을 큰따옴표로 묶어야 합니다. + + + 파일 '{0}'의 줄 번호 {1}에 별칭에 대해 인식되지 않는 옵션이 포함되어 있어 별칭을 가져올 수 없습니다. 파일을 수정하여 유효한 옵션만 포함하세요. + + + '{0}' '{1}' 별칭이 없으므로 이 명령은 일치하는 별칭을 찾을 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertFromStringData.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertFromStringData.ko.resx new file mode 100644 index 00000000000..3bf72dbb488 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertFromStringData.ko.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 + + + 데이터 줄 '{0}'이(가) 'name=value' 형식이 아닙니다. + + + '{0}' 줄의 데이터 항목 '{1}'이(가) 이미 정의되어 있습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertHTMLStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertHTMLStrings.ko.resx new file mode 100644 index 00000000000..ed48423f41c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertHTMLStrings.ko.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 + + + 허용되는 메타 속성은 content-type, default-style, application-name, author, description, generator, keywords, x-ua-compatible, viewport입니다. 메타 쌍 {0} 및 {1}이(가) 제대로 작동하지 않을 수 있습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertMarkdownStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertMarkdownStrings.ko.resx new file mode 100644 index 00000000000..021ce3492c0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ConvertMarkdownStrings.ko.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 + + + 입력 개체 '{0}'의 형식이 잘못되었습니다. + + + FileSystem 공급자 경로만 지원됩니다. 파일 경로가 지원되지 않습니다. '{0}'. + + + 지정된 개체의 속성 {0}은(는) null이거나 비어 있습니다. + + + 잘못된 매개 변수 집합 이름: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/CsvCommandStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/CsvCommandStrings.ko.resx new file mode 100644 index 00000000000..a6b2723e16d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/CsvCommandStrings.ko.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 + + + CSV 콘텐츠를 {1} 파일에 추가할 수 없습니다. 추가된 개체에 {0} 열에 해당하는 속성이 없습니다. 일치하지 않는 속성을 계속하려면 -Force 매개 변수를 추가한 다음 명령을 다시 시도하세요. + {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. + + + + -UseQuotes 또는 -QuoteFields 매개 변수 중 하나만 지정해야 합니다. + + + -Path 또는 -LiteralPath 매개 변수 중 하나만 지정해야 합니다. 둘 다 지정할 수는 없습니다. + + + 하나 이상의 헤더가 지정되지 않았습니다. 누락된 헤더 대신 "H"로 시작하는 기본 이름이 사용되었습니다. + + + FileName은 필수 매개 변수입니다. + + + ReconcilePreexistingPropertyNames 메서드는 추가할 때만 호출해야 합니다. + + + ReconcilePreexistingPropertyNames 메서드는 기존 속성 이름을 성공적으로 읽은 경우에만 호출해야 합니다. + + + BuildPropertyNames 메서드는 cmdlet 인스턴스당 한 번만 호출해야 합니다. + + + 형식 계층 구조에는 null 값이 없어야 합니다. + + + EOF에 도달했습니다. + + + -Append 또는 -NoHeader 매개 변수 중 하나만 지정해야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/Debugger.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/Debugger.ko.resx new file mode 100644 index 00000000000..0f7513abb5d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/Debugger.ko.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 + + + 줄은 1보다 작을 수 없습니다. + + + ID가 '{0}'인 중단점이 없습니다. + + + 파일 '{0}'이(가) 없습니다. + + + 파일 '{0}'에 중단점을 설정할 수 없습니다. *.ps1 및 *.psm1 파일만 유효합니다. + + + 원격 세션에서는 디버깅이 지원되지 않습니다. + + + 중단점을 설정할 수 없습니다. 이 세션의 언어 모드는 시스템 전체 언어 모드와 호환되지 않습니다. + + + 원격 디버깅이 현재 호스트에서 지원되지 않으므로 원격 세션에서 중단점을 설정할 수 없습니다. + + + 이 cmdlet을 사용하여 기본 호스트 Runspace를 디버그할 수 없습니다. 기본 Runspace를 디버그하려면 호스트의 일반 디버깅 명령을 사용합니다. + + + Runspace를 디버그할 수 없습니다. 호스트에 디버거가 없습니다. PowerShell 콘솔 내에서 또는 Visual Studio Code를 사용하여 Runspace를 디버깅해 보세요. 둘 다 기본 제공 디버거가 있습니다. + + + Runspace를 디버그할 수 없습니다. 호스트 또는 호스트 UI가 없습니다. 디버거를 디버깅하려면 호스트 및 호스트 UI가 필요합니다. + + + Runspace를 두 개 이상 찾았습니다. 한 번에 하나의 Runspace만 디버깅할 수 있습니다. + + + 디버깅 세션을 종료하려면 디버거 프롬프트에서 'Detach' 명령을 입력하거나, 그렇지 않으면 'Ctrl+C'를 입력합니다. + + + 명령 또는 스크립트가 완료되었습니다. + + + Runspace 디버깅: {0} + + + Runspace {0}은(는) 열린 상태가 아니므로 디버그 옵션을 설정할 수 없습니다. + + + 프로세스 {0}에 대한 디버그 옵션을 유지하지 못했습니다. + + + Runspace {0}에 대한 디버거를 찾을 수 없습니다. + + + Runspace를 찾을 수 없습니다. + + + {1}의 줄 {0}에서 대해 Wait-Debugger가 호출되었습니다. + + + 인스턴스 ID가 '{0}'인 runspace가 없으므로 다른 runspace와 연결된 중단점을 업데이트할 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/EventingStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/EventingStrings.ko.resx new file mode 100644 index 00000000000..dd7c0d5880c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/EventingStrings.ko.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 + + + 원본 식별자가 '{0}'인 이벤트는 없습니다. + + + 식별자가 '{0}'인 이벤트는 없습니다. + + + 원본 식별자 '{0}'의 이벤트 구독이 없습니다. + + + 식별자 '{0}'의 이벤트 구독이 없습니다. + + + 이벤트 구독 '{0}' + + + ‘{0}’ 이벤트 + + + 전달되지 않는 이벤트에는 작업을 지정해야 합니다. + + + 구독 취소 + + + 제거 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/FormatAndOut_out_gridview.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/FormatAndOut_out_gridview.ko.resx new file mode 100644 index 00000000000..1d7c6521b9a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/FormatAndOut_out_gridview.ko.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 + + + Out-GridView에서 지원하지 않는 데이터 형식입니다. + + + 하나 이상의 PowerShell 세션이 실행되는 동안 Microsoft .NET Framework 4.5가 설치되었습니다. {0} cmdlet을 사용하려면 모든 PowerShell 창을 닫은 다음 새 PowerShell 창을 여세요. + + + 형식 + + + + + + 인덱스 + + + '{0}'(이)라는 이름의 명령을 찾을 수 없습니다. + + + '{0}'(이)라는 이름의 명령이 둘 이상 발견되었습니다. 매개 변수 없이 '{1}'을(를) 시작한 다음 '{0}'을(를) 입력하여 결과를 필터링하세요. + + + 콘솔 입력 버퍼에 쓸 수 없습니다. + + + {0}은(는) {1}보다 작아야 합니다. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetFormatDataStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetFormatDataStrings.ko.resx new file mode 100644 index 00000000000..a0e4a1ff3d2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetFormatDataStrings.ko.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 + + + 뷰 정의 '{0}' 처리 중 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetMember.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetMember.ko.resx new file mode 100644 index 00000000000..da4a5e4f2c7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetMember.ko.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 + + + Get-Member cmdlet에 사용할 개체를 지정해야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetRandomCommandStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetRandomCommandStrings.ko.resx new file mode 100644 index 00000000000..2799c04a347 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetRandomCommandStrings.ko.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'는 0보다 커야 합니다. + + + 최솟값({0})은 최댓값({1})보다 크거나 같을 수 없습니다. + + + 'minValue'는 maxValue보다 클 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetUptimeStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetUptimeStrings.ko.resx new file mode 100644 index 00000000000..092999e05d2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/GetUptimeStrings.ko.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 + + + 플랫폼이 지원되지 않습니다(System.Diagnostics.Stopwatch.IsHighResolution이 false임). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/HostStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/HostStrings.ko.resx new file mode 100644 index 00000000000..aade50e6e33 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/HostStrings.ko.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 + + + {0}이(가) 올바른 색이 아니므로 색을 처리할 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/HttpCommandStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/HttpCommandStrings.ko.resx new file mode 100644 index 00000000000..21069fdc3bc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/HttpCommandStrings.ko.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 + + + 다음 오류 때문에 이 명령을 완료할 수 없습니다. '{0}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ImplicitRemotingStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ImplicitRemotingStrings.ko.resx new file mode 100644 index 00000000000..fb110509908 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ImplicitRemotingStrings.ko.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 + + + 원격 {0} 명령에서 반환된 데이터가 예상 형식이 아닙니다. + + + {0} cmdlet을 사용하려면 원격 세션에 Get-Command, Get-FormatData, Select-Objec 명령이 필요합니다. Get-Help, Measure-Object 명령은 사용되지만 선택 사항입니다. 원격 세션에 필요한 명령이 포함되어 있는지 확인한 다음 다시 시도하세요. + + + 원격 세션에서 {0} 명령을 실행하는 동안 {1} 오류가 보고되었습니다. + + + 원격 세션에서 {0} 명령을 실행해도 결과가 반환되지 않았습니다. + + + 이 암시적 원격 모듈과 연결된 세션이 없습니다. + + + 원격 별칭 '{0}'을(를) 확인할 수 없습니다. + + + 이름이 Name 매개 변수의 값과 일치하지 않아 '{0}' 명령에 대한 프록시 만들기를 건너뛰었습니다. + + + '{0}' 형식은 이름이 FormatTypeName 매개 변수의 값과 일치하지 않아 해당 형식에 대한 확장 형식 정의를 건너뛰었습니다. + + + PowerShell에서 명령 이름의 안전성을 확인할 수 없어 '{0}' 명령에 대한 프록시 만들기를 건너뛰었습니다. + + + '{0}' 명령은 기존 로컬 명령과 겹치므로 프록시 만들기를 건너뛰었습니다. 기존 로컬 명령과 겹치게 하려면 AllowClobber 매개 변수를 사용하세요. + + + 요청된 모든 원격 명령이 기존 로컬 명령과 겹치므로 명령 프록시를 만들지 않았습니다. 기존 로컬 명령과 겹치게 하려면 AllowClobber 매개 변수를 사용하세요. + + + {0}에 대한 암시적 원격 + + + 암시적 원격 이벤트(세션 ID: {0}, 이벤트 처리기 ID: {1}) + + + 암시적 원격 모듈 + + + {0}에 생성됨 + + + {0} cmdlet 기준 + + + {0} 명령줄로 호출되었습니다. + + + 이 프록시 모듈이 작동할 세션을 지정하는 데 사용할 수 있는 선택적 매개 변수입니다. + + + "{{0}}" 명령의 암시적 원격 작업을 위한 새 세션을 만드는 중... + + + {{0}}의 암시적 원격 모듈 세션 + + + 암시적 원격 모듈을 만드는 중 ... + + + 원격 세션에서 명령 정보를 가져오는 중 ... + + + 원격 세션에서 명령 정보를 가져오는 중 ... {0} 명령 받음 + + + 원격 세션에서 형식 및 출력 정보를 가져오는 중... + + + 원격 세션에서 형식 및 출력 정보를 가져오는 중 ... {0} 개체 받음 + + + 완료했습니다. + + + PowerShell 자격 증명 요청 + + + {0}에 대한 자격 증명을 입력하세요. + + + {0} 연결에 사용할 HTTP 프록시 자격 증명을 입력하세요. + + + 새 원격 세션에서 사용할 수 있는 명령은 암시적 원격 모듈을 만들 때 사용할 수 있는 명령과 다릅니다. Export-PSSession cmdlet을 사용해 모듈을 다시 만드는 것이 좋습니다. + + + 이 시스템에서 스크립트 실행이 비활성화되어 파일을 로드할 수 없습니다. 파일 서명에 유효한 인증서를 제공하세요. + + + 파일 {0}을(를) 저장할 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ImportLocalizedDataStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ImportLocalizedDataStrings.ko.resx new file mode 100644 index 00000000000..8fe7e5efaa9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/ImportLocalizedDataStrings.ko.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 + + + 데이터 파일 '{0}'을(를) 찾을 수 없습니다. + + + FileName 매개 변수를 지정하지 않았습니다. Import-LocalizedData를 스크립트 파일에서 호출하지 않는 경우 FileName 매개 변수가 필요합니다. + + + PowerShell이 데이터 파일 '{0}'을(를) 여는 동안 다음 오류가 발생했습니다. +{1}. + + + PowerShell이 '{0}' 스크립트 데이터 파일을 로드하는 동안 다음 오류가 발생했습니다. +{1}. + + + FileName 매개 변수의 인수에는 경로가 포함되어서는 안 됩니다. + + + '{0}' 디렉터리 또는 상위 문화권 디렉터리에서 PowerShell 데이터 파일 '{1}'을(를) 찾을 수 없습니다. + + + 지역화된 데이터를 가져올 수 없습니다. 이 언어 모드에서는 추가 지원 명령을 정의할 수 없습니다. + + + BindingVariable 이름 '{0}'은(는) 잘못되었습니다. + + + Import-LocalizedData Cmdlet + + + ConstrainedLanguage 모드에서는 추가 지원 명령(SupportedCommand 매개 변수를 통해)이 허용되지 않습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/MatchStringStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/MatchStringStrings.ko.resx new file mode 100644 index 00000000000..238e5653002 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/MatchStringStrings.ko.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 + + + 현재 공급자({0})에서는 파일을 열 수 없으므로 파일을 열 수 없습니다. + + + {0} 파일을 읽을 수 없습니다. {1} + + + Select-String 출력에서 파이프된 결과를 검색할 때는 "Context" 옵션을 사용할 수 없습니다. + + + 문자열 {0}은(는) 올바른 정규식이 아닙니다. {1} + + + -Culture 매개 변수는 -SimpleMatch 매개 변수와 함께만 지정할 수 있습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/MeasureObjectStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/MeasureObjectStrings.ko.resx new file mode 100644 index 00000000000..e7631e8090b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/MeasureObjectStrings.ko.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 + + + 입력의 어떤 개체에서도 "{0}" 속성을 찾을 수 없습니다. + + + 입력 개체 "{0}"은(는) 숫자 형식이 아닙니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/NewObjectStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/NewObjectStrings.ko.resx new file mode 100644 index 00000000000..cb0555d9193 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/NewObjectStrings.ko.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 + + + 생성자를 찾을 수 없습니다. 형식 {0}에 적합한 생성자를 찾을 수 없습니다. + + + [{0}] 형식을 찾을 수 없습니다. 이 형식을 포함하는 어셈블리가 로드되었는지 확인하세요. + + + COM 형식을 로드할 수 없습니다. {0} + + + 파이프라인에 기록된 개체는 구성 요소의 기본 상호 운용 어셈블리에 있는 "{0}" 형식의 인스턴스입니다. 이 형식이 IDispatch 멤버와 다른 멤버를 노출하는 경우, 이 개체와 함께 작동하도록 작성된 스크립트는 기본 상호 운용 어셈블리가 설치되어 있지 않으면 제대로 작동하지 않을 수 있습니다. + + + 지정한 {2} 개체에서 멤버 "{1}"을(를) 찾을 수 없습니다. + + + 제공된 값이 올바르지 않거나 속성이 읽기 전용입니다. 값을 바꾼 다음 다시 시도하세요. + + + 특성 및 위임된 Windows RT 형식의 인스턴스를 만들 수 없습니다. + + + ByRef와 유사한 형식 "{0}"의 인스턴스를 만들 수 없습니다. PowerShell에서는 ByRef와 유사한 형식이 지원되지 않습니다. + + + 형식을 만들 수 없습니다. 이 언어 모드에서는 핵심 형식만 지원됩니다. + + + 형식을 만들 수 없습니다. 핵심 형식만 정책 잠금 컴퓨터의 {0} 언어 모드에서 지원됩니다. + + + New-Object Cmdlet 형식 만들기 + + + ConstrainedLanguage 모드에서는 '{0}' 형식이 만들어지지 않습니다. + + + New-Object Cmdlet COM 개체 만들기 + + + ConstrainedLanguage 모드에서는 COM 개체 '{0}'이(가) 만들어지지 않습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/OutPrinterDisplayStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/OutPrinterDisplayStrings.ko.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/OutPrinterDisplayStrings.ko.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SelectObjectStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SelectObjectStrings.ko.resx new file mode 100644 index 00000000000..59e0c98c463 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SelectObjectStrings.ko.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 + + + 여러 결과의 이름을 바꿀 수 없습니다. + + + 속성 "{0}"을(를) 찾을 수 없습니다. + + + 여러 속성을 확장할 수 없습니다. + + + 속성 "{0}"이(가) 이미 있어서 이 속성을 처리할 수 없습니다. + + + 이 속성은 빈 스크립트 블록이며 이름을 제공하지 않습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SendMailMessageStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SendMailMessageStrings.ko.resx new file mode 100644 index 00000000000..fc7fb61f879 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SendMailMessageStrings.ko.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 + + + SMTP 서버를 지정하지 않았기 때문에 전자 메일을 보낼 수 없습니다. SmtpServer 매개 변수 또는 $PSEmailServer 변수를 사용하여 SMTP 서버를 지정해야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SortObjectStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SortObjectStrings.ko.resx new file mode 100644 index 00000000000..cc3b9e537ac --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/SortObjectStrings.ko.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" - "InputObject"에서 "{0}"을(를) 찾을 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/StartSleepStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/StartSleepStrings.ko.resx new file mode 100644 index 00000000000..22d48356456 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/StartSleepStrings.ko.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 + + + '-Duration' 매개 변수 값은 '{0}'을(를) 초과할 수 없습니다. 입력한 값은 '{1}'입니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/TestJsonCmdletStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/TestJsonCmdletStrings.ko.resx new file mode 100644 index 00000000000..d3128bb4d71 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/TestJsonCmdletStrings.ko.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 + + + JSON 스키마를 구문 분석할 수 없습니다. + + + JSON을 구문 분석할 수 없습니다. + + + JSON이 스키마와 일치하지 않습니다. '{1}'에서 {0} + + + JSON 스키마 파일을 열 수 없습니다. {0} + + + URI 체계 '{0}'은(는) 지원되지 않습니다. HTTP(S)와 로컬 파일 시스템 URI만 허용됩니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/TraceCommandStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/TraceCommandStrings.ko.resx new file mode 100644 index 00000000000..4429323c93c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/TraceCommandStrings.ko.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 + + + 추적 출력은 파일 시스템에만 쓸 수 있습니다. 경로 '{0}'은(는) '{1}' 공급자 경로를 가리킵니다. + + + 추적 출력은 단일 파일에만 쓸 수 있습니다. 경로 '{0}'은(는) 하나 이상의 파일로 확인되었습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UnblockFileStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UnblockFileStrings.ko.resx new file mode 100644 index 00000000000..7629ea9a68f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UnblockFileStrings.ko.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 + + + 이 cmdlet은 Linux를 지원하지 않습니다. + + + {0}의 차단을 해제하는 동안 오류가 발생했습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UpdateDataStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UpdateDataStrings.ko.resx new file mode 100644 index 00000000000..73dcef211eb --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UpdateDataStrings.ko.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 + + + 현재 공급자가 "{0}"이고 이 명령에 파일이 필요하므로 파일을 열 수 없습니다. + + + 파일 이름 확장명 "{1}"이(가) 없기 때문에 "{0}" 파일을 읽을 수 없습니다. + + + TypeData 업데이트 + + + FormatData 업데이트 + + + FileName: {0} + + + 형식이 "{0}"인 멤버를 업데이트할 수 없습니다. MemberType 매개 변수에 다른 형식을 지정합니다. + + + "{1}" 형식에는{0} 매개 변수가 필요합니다. {0} 매개 변수를 지정하세요. + + + {0} 매개 변수는 null이거나 "{1}" 형식의 멤버에 대한 빈 문자열이 아니어야 합니다. 이 멤버 형식을 업데이트할 때 {0} 매개 변수에 null이 아닌 값을 지정합니다. + + + {0} 매개 변수는 "{1}" 형식의 멤버에 필요하지 않으며 지정해서는 안 됩니다. 이 멤버 형식을 업데이트할 때 {0} 매개 변수를 지정하지 마세요. + + + "{0}" 형식의 업데이트에 지정된 멤버가 없습니다. + + + 대상 형식 이름은 null이거나, 비어 있거나, 공백만 포함해서는 안 됩니다. + + + Value 및 SecondValue 매개 변수는 "{0}" 형식의 멤버에 대해 모두 null이 아니어야 합니다. 두 매개 변수 중 하나에 null이 아닌 값을 지정합니다. + + + 멤버 형식은 하나만 지정할 수 있습니다. 지정된 멤버 형식은 "{0}"입니다. 하나의 멤버 형식으로만 형식을 업데이트합니다. + + + MemberType 매개 변수 없이 MemberName, Value 및 SecondValue 매개 변수를 지정할 수 없습니다. + + + TypeData 제거 + + + 제거할 형식의 이름: {0} + + + 업데이트할 형식: {0} + + + 형식 파일 제거 + + + {0} 파일이 현재 세션으로 가져와지지 않았습니다. + + + 이 runspace에서는 형식 데이터를 업데이트할 수 없습니다. Runspace를 만들 때 'DisableFormatUpdates' 속성이 True로 설정됩니다. + + + FormatTable 인스턴스로 형식 데이터를 업데이트할 수 없습니다. + + + TypeTable 인스턴스로 형식 데이터를 업데이트할 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UpdateListStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UpdateListStrings.ko.resx new file mode 100644 index 00000000000..228aadb4a2d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UpdateListStrings.ko.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}' 속성을 찾을 수 없습니다. + + + InputObject 매개 변수를 지정하는 경우 Property 매개 변수를 지정해야 합니다. + + + Property 매개 변수를 지정하는 경우 InputObject 매개 변수를 지정해야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UtilityCommonStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UtilityCommonStrings.ko.resx new file mode 100644 index 00000000000..c36550b7564 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/UtilityCommonStrings.ko.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}에 잘못된 예외가 하나 이상 있습니다. + + + 파일 경로 '{0}'이(가) 잘못되었으므로 이 명령을 실행할 수 없습니다. 올바른 파일 경로를 제공한 다음 명령을 실행하세요. + + + '{0}'이(가) 비어 있거나 공백이므로 이 명령을 실행할 수 없습니다. CSSUri를 지정한 다음 명령을 실행하세요. + + + 현재 공급자({0})에서는 파일을 열 수 없으므로 파일을 열 수 없습니다. + + + Namespace 매개 변수의 접두사 값이 null이므로 이 명령을 실행할 수 없습니다. 접두사에 유효한 값을 지정한 다음 명령을 다시 실행하세요. + + + 이 속성으로 그룹화된 개체는 키가 중복되어 확장할 수 없습니다. 속성에 유효한 값을 지정한 다음 다시 시도하세요. + + + 이 운영 체제에서는 명령이 지원되지 않습니다. + + + '{0}' 파일을 읽을 수 없습니다. {1} + + + '{0}' 형식의 입력은 16진수로 변환할 수 없습니다. 문자열 표현의 16진수 서식을 보려면 Format-Hex에 전달하기 전에 Out-String cmdlet에 먼저 전달하세요. + + + 지정된 경로 '{0}'은(는) 지원되지 않습니다. 이 명령은 FileSystem 공급자 경로만 지원합니다. + + + 경로: + + + AsString 매개 변수를 사용하려면 AsHashtable 매개 변수를 지정해야 하므로 명령을 실행할 수 없습니다. + + + 하나 이상의 속성과 함께 AsHashTable 매개 변수를 사용하려면 AsString 매개 변수도 지정해야 하므로 명령을 실행할 수 없습니다. + + + 경로 '{0}'이(가) 없으므로 찾을 수 없습니다. + + + 태그 '{0}'을(를) 사용할 수 없습니다. 'PS' 접두사는 예약되어 있습니다. + + + '{0}' 파일을 PowerShell 데이터 파일로 구문 분석할 수 없습니다. + + + 다음 오류로 인해 제공된 SDDL에서 보안 설명자를 생성할 수 없습니다. {0} + + + Invoke-Expression Cmdlet + + + Invoke-Expression cmdlet 스크립트 블록은 ConstrainedLanguage 모드에서 실행됩니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/VariableCommandStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/VariableCommandStrings.ko.resx new file mode 100644 index 00000000000..23c5d775874 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/VariableCommandStrings.ko.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 + + + 변수 설정 + + + 이름: {0} 값: {1} + + + 컬렉션 대신 단일 변수를 사용하세요 + + + 새 변수 + + + 이름: {0} 값: {1} + + + 변수 제거 + + + 이름: {0} + + + 변수 지우기 + + + 이름: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WebCmdletStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WebCmdletStrings.ko.resx new file mode 100644 index 00000000000..fc1fe4a838a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WebCmdletStrings.ko.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 + + + '{0}' 경로에 대한 액세스가 거부되었습니다. + + + cmdlet은 암호화되지 않은 연결을 통해 전송되는 일반 텍스트 비밀을 보호할 수 없습니다. 이 경고를 표시하지 않고 암호화되지 않은 네트워크를 통해 일반 텍스트 비밀을 보내려면 AllowUnencryptedAuthentication 매개 변수를 지정하여 명령을 다시 실행하세요. + + + 충돌하는 매개 변수 Authentication 및 UseDefaultCredentials가 지정되어 cmdlet을 실행할 수 없습니다. Authentication은 기본 자격 증명을 지원하지 않습니다. Authentication 또는 UseDefaultCredentials를 지정한 후 다시 시도하세요. + + + Credential 매개 변수가 지정되지 않아 cmdlet을 실행할 수 없습니다. 지정한 Authentication 형식에는 Credential이 필요합니다. Credential을 지정한 후 다시 시도하세요. + + + Token 매개 변수가 지정되지 않아 cmdlet을 실행할 수 없습니다. 지정한 Authentication 형식에는 Token이 필요합니다. Token을 지정한 후 다시 시도하세요. + + + 충돌하는 매개 변수 Credential 및 Token이 지정되어 cmdlet을 실행할 수 없습니다. Credential 또는 Token을 지정한 후 다시 시도하세요. + + + 충돌하는 매개 변수 Body 및 InFile이 지정되어 cmdlet을 실행할 수 없습니다. Body 또는 InFile을 지정한 후 다시 시도하세요. + + + 충돌하는 매개 변수 Body 및 Form이 지정되어 cmdlet을 실행할 수 없습니다. Body 또는 Form을 지정한 후 다시 시도하세요. + + + 충돌하는 매개 변수 InFile 및 Form이 지정되어 cmdlet을 실행할 수 없습니다. InFile 또는 Form을 지정한 후 다시 시도하세요. + + + -ContentType 매개 변수가 올바른 Content-Type 헤더가 아니므로 cmdlet을 실행할 수 없습니다. -ContentType에 유효한 Content-Type을 지정한 후 다시 시도하세요. 헤더 유효성 검사를 건너뛰려면 -SkipHeaderValidation 매개 변수를 제공하세요. + + + 충돌하는 매개 변수 Credential 및 UseDefaultCredentials가 지정되어 cmdlet을 실행할 수 없습니다. Credential 또는 UseDefaultCredentials를 지정한 후 다시 시도하세요. + + + 경로 '{0}'은(는) 디렉터리로 확인됩니다. 파일 이름을 포함한 경로를 지정한 후 명령을 다시 시도하세요. + + + 제공된 JSON에 이름이 빈 문자열인 속성이 포함되어 있습니다. 이는 -AsHashTable 스위치를 사용하는 경우에만 지원됩니다. + + + 문자열에서 변환된 사전에 중복된 키 '{0}'이(가) 포함되어 있으므로 JSON 문자열을 변환할 수 없습니다. + + + 응답 콘텐츠를 구문 분석할 수 없습니다. Internet Explorer 엔진을 사용할 수 없거나 Internet Explorer의 첫 실행 구성이 완료되지 않았습니다. UseBasicParsing 매개 변수를 지정하고 다시 시도하세요. + + + 기본적으로 안전하지 않은 리디렉션은 따를 수 없습니다. -AllowInsecureRedirect 스위치를 지정하여 명령을 다시 실행하세요. + + + 대/소문자가 다른 키를 포함하므로 JSON 문자열을 변환할 수 없습니다. 대신 -AsHashTable 스위치를 사용하세요. 기존 키 '{0}'에 추가하려던 키는 '{1}'입니다. + + + 최대 리디렉션 횟수를 초과했습니다. 허용되는 리디렉션 수를 늘리려면 -MaximumRedirection 매개 변수에 더 큰 값을 지정하세요. + + + 경로 '{0}'은(는) 여러 경로로 확인될 수 있습니다. + + + '{0}' 유형은 사전의 직렬화 또는 역직렬화에 지원되지 않습니다. 키는 문자열이어야 합니다. + + + 경로 '{0}'을(를) 파일로 확인할 수 없습니다. + + + '{0}' 경로는 파일 시스템 경로가 아닙니다. 파일 시스템의 파일 경로를 지정하세요. + + + OutFile 매개 변수가 지정되지 않아 cmdlet을 실행할 수 없습니다. {0} 매개 변수를 사용할 때는 유효한 OutFile 매개 변수 값을 제공한 후 다시 시도하세요. + + + 원격 파일의 크기가 OutFile {0}와(과) 같으므로 파일이 다시 다운로드되지 않습니다. + + + 충돌하는 매개 변수 ProxyCredential 및 ProxyUseDefaultCredentials가 지정되어 cmdlet을 실행할 수 없습니다. ProxyCredential 또는 ProxyUseDefaultCredentials를 지정한 후 다시 시도하세요. + + + Proxy 매개 변수가 지정되지 않아 cmdlet을 실행할 수 없습니다. ProxyCredential 또는 ProxyUseDefaultCredentials 매개 변수를 사용할 때는 Proxy 매개 변수에 유효한 프록시 URI를 제공한 후 다시 시도하세요. + + + 웹 응답 스트림 읽기가 완료되었습니다. 다운로드된 바이트: {0} + + + 웹 응답 스트림을 읽는 중 + + + {1}개 중 {0}개를 다운로드함 + + + Resume 스위치는 OutFile이 파일을 대상으로 할 때만 사용할 수 있지만 파일이 {0} 디렉터리로 확인됩니다. + + + 충돌하는 매개 변수 Session 및 SessionVariable이 지정되어 cmdlet을 실행할 수 없습니다. Session 또는 SessionVariable을 지정한 후 다시 시도하세요. + + + 지문이 올바르지 않아 인증서를 검색할 수 없습니다. 지문을 확인한 후 다시 시도하세요. + + + 웹 요청이 완료되었습니다. (처리된 바이트 수: {0}) + + + 웹 요청이 취소되었습니다. (처리된 바이트 수: {0}) + + + 웹 요청 상태 + + + {1}개 중 {0}개를 다운로드함 + + + 다음 오류로 JSON 변환에 실패했습니다. {0} + + + 다음 응답 상태 코드가 성공을 나타내지 않습니다. {0}({1}) + + + rel 링크 {0}을(를) 따르는 중 + + + 원격 서버에서 다운로드를 다시 시작할 수 없다고 응답했습니다. 로컬 파일을 덮어씁니다. + + + 알 수 없는 크기의 콘텐츠 형식 {0}의 HTTP/{1} 응답을 받았습니다. + + + {0}초 간격 후 다시 시도합니다. 이전 시도의 상태 코드: {1} + + + 직렬화가 설정된 깊이({0})를 초과하므로 결과 JSON이 잘립니다. + + + WebSession 속성이 요청 사이에 변경되어 세션의 모든 HTTP 연결을 다시 만들어야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WriteErrorStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WriteErrorStrings.ko.resx new file mode 100644 index 00000000000..845a8797be6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WriteErrorStrings.ko.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 + + + Write-Error cmdlet에서 오류가 보고되었습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WriteProgressResourceStrings.ko.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WriteProgressResourceStrings.ko.resx new file mode 100644 index 00000000000..b1947c94de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ko/WriteProgressResourceStrings.ko.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 + + + 진행 상황이 보고되는 활동을 설명하는 텍스트입니다. + + + 진행 상황이 보고되는 활동의 현재 상태를 설명하는 텍스트입니다. + + + 처리하는 중 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AddMember.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AddMember.pl.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AddMember.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AddTypeStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AddTypeStrings.pl.resx new file mode 100644 index 00000000000..bb3193c217d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AddTypeStrings.pl.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 + + + Kod źródłowy został już skompilowany i załadowany. + + + Nie można dodać typu. Rozszerzenie „{0}” nie jest obsługiwane. + + + Nie można dodać typu. Wszystkie pliki wejściowe muszą mieć to samo rozszerzenie. + + + Nie można dodać typu. Nie można odnaleźć zestawu „{0}”. + + + Nie można dodać typu. Nazwa typu „{0}” już istnieje. + + + Nie można ustawić zestawu wyjściowego. Ścieżka {0} nie została rozpoznana jako pojedynczy plik. + + + Nie można dodać typu. Wystąpiły błędy kompilacji. + + + Nie można dodać typu. Parametr OutputType wymaga określenia parametru OutputAssembly. + + + Nie można dodać typu. Definiowanie nowych typów nie jest obsługiwane w tym trybie języka. + + + Określony zestaw odwołania „{0}” jest niepotrzebny i zostanie zignorowany. + + + Typy zestawów „ConsoleApplication” i „WindowsApplication” nie są obecnie obsługiwane. + + + Polecenie cmdlet Add-Type + + + Polecenie cmdlet Add-Type nie będzie dozwolone w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AliasCommandStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AliasCommandStrings.pl.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/AliasCommandStrings.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertFromStringData.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertFromStringData.pl.resx new file mode 100644 index 00000000000..2ff46762218 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertFromStringData.pl.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 + + + Wiersz danych „{0}” nie ma formatu „name=value”. + + + Element danych „{1}” w wierszu „{0}” jest już zdefiniowany. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertHTMLStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertHTMLStrings.pl.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertHTMLStrings.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertMarkdownStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertMarkdownStrings.pl.resx new file mode 100644 index 00000000000..d86e11f4f90 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ConvertMarkdownStrings.pl.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 + + + Typ obiektu wejściowego „{0}” jest nieprawidłowy. + + + Obsługiwane są tylko ścieżki dostawcy systemu plików. Ścieżka pliku nie jest obsługiwana: „{0}”. + + + Właściwość {0} danego obiektu ma wartość null lub jest pusta. + + + Nieprawidłowa nazwa zestawu parametrów: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/CsvCommandStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/CsvCommandStrings.pl.resx new file mode 100644 index 00000000000..235bb044226 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/CsvCommandStrings.pl.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 + + + Nie można dołączyć zawartości CSV do następującego pliku: {1}. Dołączony obiekt nie ma właściwości odpowiadającej następującej kolumnie: {0}. Aby kontynuować z niezgodnymi właściwościami, dodaj parametr -Force, a następnie ponów próbę wykonania polecenia. + {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. + + + + Należy określić parametry -UseQuotes lub -QuoteFields, ale nie oba te parametry. + + + Należy określić parametry -Path lub -LiteralPath, ale nie oba te parametry. + + + Nie określono co najmniej jednego nagłówka. Zamiast brakujących nagłówków użyto domyślnych nazw rozpoczynających się od znaku „H”. + + + FileName jest parametrem obowiązkowym. + + + Metoda ReconcilePreexistingPropertyNames powinna zostać wywołana tylko w przypadku dołączenia. + + + Metoda ReconcilePreexistingPropertyNames powinna zostać wywołana tylko wtedy, gdy istniejące wcześniej nazwy właściwości zostały pomyślnie odczytane. + + + Metoda BuildPropertyNames powinna być wywoływana tylko raz na wystąpienie polecenia cmdlet. + + + Hierarchia typów nie powinna mieć wartości null. + + + Osiągnięto EOF. + + + Należy określić parametry -Append lub -NoHeader, ale nie oba te parametry. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/Debugger.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/Debugger.pl.resx new file mode 100644 index 00000000000..c22b0885147 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/Debugger.pl.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}'. + + + Plik „{0}” nie istnieje. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/EventingStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/EventingStrings.pl.resx new file mode 100644 index 00000000000..3b6616d7166 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/EventingStrings.pl.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 + + + Zdarzenie o identyfikatorze źródła „{0}” nie istnieje. + + + Zdarzenie o identyfikatorze „{0}” nie istnieje. + + + Subskrypcja zdarzeń o identyfikatorze źródła „{0}” nie istnieje. + + + Subskrypcja zdarzeń o identyfikatorze „{0}” nie istnieje. + + + Subskrypcja zdarzenia „{0}” + + + Wydarzenie „{0}” + + + W przypadku zdarzeń nieprzekazanych należy określić działanie. + + + Anuluj subskrypcję + + + Usuń + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/FormatAndOut_out_gridview.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/FormatAndOut_out_gridview.pl.resx new file mode 100644 index 00000000000..7245234b3bc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/FormatAndOut_out_gridview.pl.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 + + + Format danych nie jest obsługiwany przez element Out-GridView. + + + Program Microsoft .NET Framework 4.5 został zainstalowany, gdy była uruchomiona co najmniej jedna sesja programu PowerShell. Aby użyć {0} polecenia cmdlet, zamknij wszystkie okna programu PowerShell, a następnie otwórz nowe okno programu PowerShell. + + + Typ + + + Wartość + + + Indeks + + + Nie znaleziono polecenia o nazwie „{0}”. + + + Znaleziono więcej niż jedno polecenie o nazwie „{0}”. Rozpocznij „{1}” bez parametrów, a następnie wpisz „{0}”, aby odfiltrować wyniki. + + + Nie można zapisać w buforze wejściowym konsoli. + + + {0} powinno być mniejsze niż {1}. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetFormatDataStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetFormatDataStrings.pl.resx new file mode 100644 index 00000000000..6706d39e83a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetFormatDataStrings.pl.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 + + + Przetwarzanie definicji widoku „{0}” + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetMember.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetMember.pl.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetMember.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetRandomCommandStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetRandomCommandStrings.pl.resx new file mode 100644 index 00000000000..cd5f6db742e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetRandomCommandStrings.pl.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 + + + Wartość „maxValue” musi być większa od zera. + + + Wartość minimalna ({0}) nie może być większa lub równa wartości maksymalnej ({1}). + + + Wartość „minValue” nie może być większa niż maxValue. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetUptimeStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetUptimeStrings.pl.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/GetUptimeStrings.pl.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/HostStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/HostStrings.pl.resx new file mode 100644 index 00000000000..ed9b9a6587e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/HostStrings.pl.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 + + + Nie można przetworzyć koloru, ponieważ {0} nie jest prawidłowym kolorem. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/HttpCommandStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/HttpCommandStrings.pl.resx new file mode 100644 index 00000000000..c1093f003f5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/HttpCommandStrings.pl.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 + + + Nie można wykonać tego polecenia z powodu następującego błędu: „{0}”. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ImplicitRemotingStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ImplicitRemotingStrings.pl.resx new file mode 100644 index 00000000000..2fd4066ea78 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ImplicitRemotingStrings.pl.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 + + + Dane zwrócone przez polecenie zdalne {0} nie mają oczekiwanego formatu. + + + Polecenie cmdlet {0} wymaga następujących poleceń w sesji zdalnej: Get-Command, Get-FormatData i Select-Object. Są używane następujące polecenia, ale opcjonalne: Get-Help i Measure-Object. Sprawdź, czy sesja zdalna zawiera wymagane polecenia, a następnie spróbuj ponownie. + + + Uruchomienie polecenia {0} w sesji zdalnej zgłosiło następujący błąd: {1}. + + + Uruchomienie polecenia {0} w sesji zdalnej nie zwróciło żadnych wyników. + + + Z tym niejawnym modułem zdalnym nie skojarzono żadnej sesji. + + + Nie można rozpoznać aliasu zdalnego „{0}”. + + + Tworzenie serwera proxy zostało pominięte dla polecenia „{0}”, ponieważ nazwa nie jest zgodna z wartością parametru Name. + + + Definicja typu rozszerzonego została pominięta dla typu „{0}”, ponieważ jego nazwa nie jest zgodna z wartością parametru FormatTypeName. + + + Tworzenie serwera proxy dla polecenia „{0}” zostało pominięte, ponieważ program PowerShell nie może zweryfikować bezpieczeństwa nazwy polecenia. + + + Tworzenie serwera proxy zostało pominięte dla następującego polecenia: „{0}”, ponieważ spowodowałoby to cieniowanie istniejącego polecenia lokalnego. Użyj parametru AllowClobber, jeśli chcesz zasłaniać istniejące polecenia lokalne. + + + Nie utworzono serwerów proxy poleceń, ponieważ wszystkie żądane polecenia zdalne będą w tle istniejących poleceń lokalnych. Użyj parametru AllowClobber, jeśli chcesz zasłaniać istniejące polecenia lokalne. + + + Niejawna komunikacja zdalna dla {0} + + + Niejawne zdarzenie komunikacji zdalnej (identyfikator sesji: {0}; identyfikator procedury obsługi zdarzeń: {1}) + + + Moduł niejawnej komunikacji zdalnej + + + wygenerowano {0} + + + według polecenia cmdlet {0} + + + Wywołano przy użyciu następującego wiersza polecenia: {0} + + + Opcjonalny parametr, którego można użyć do określenia sesji, w której działa ten moduł proxy + + + Trwa tworzenie nowej sesji na potrzeby niejawnego zdalnego sterowania poleceniem „{{0}}”... + + + Sesja modułu niejawnej komunikacji zdalnej {{0}} + + + Trwa tworzenie niejawnego modułu zdalnego... + + + Trwa pobieranie informacji o poleceniu z sesji zdalnej... + + + Trwa pobieranie informacji o poleceniu z sesji zdalnej... {0} odebrane polecenia + + + Trwa pobieranie informacji o formatowaniu i danych wyjściowych z sesji zdalnej... + + + Trwa pobieranie informacji o formatowaniu i danych wyjściowych z sesji zdalnej... odebrane obiekty ({0}) + + + Ukończono. + + + Żądanie poświadczeń programu PowerShell + + + Wprowadź swoje poświadczenia dla {0}. + + + Wprowadź poświadczenia serwera proxy HTTP, które są używane dla następującego połączenia: {0} + + + Polecenia dostępne w nowej sesji zdalnej różnią się od poleceń dostępnych podczas tworzenia niejawnego modułu komunikacji zdalnej. Rozważ ponowne utworzenie modułu korzystając z polecenia cmdlet Export-PSSession. + + + Nie można załadować plików, ponieważ uruchomione skrypty są wyłączone w tym systemie. Podaj prawidłowy certyfikat, za pomocą którego chcesz podpisać pliki. + + + Nie można zapisać pliku {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ImportLocalizedDataStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ImportLocalizedDataStrings.pl.resx new file mode 100644 index 00000000000..30e3aa58d67 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/ImportLocalizedDataStrings.pl.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 + + + Nie można odnaleźć pliku danych „{0}”. + + + Nie określono parametru FileName. Parametr FileName jest wymagany, gdy polecenie Import-LocalizedData nie jest wywoływane z pliku skryptu. + + + Podczas otwierania pliku danych „{0}” programu PowerShell wystąpił następujący błąd: +{1}. + + + Wystąpił następujący błąd podczas ładowania pliku danych skryptu „{0}” przez program PowerShell: +{1}. + + + Argument parametru FileName nie powinien zawierać ścieżki. + + + Nie można odnaleźć pliku danych programu PowerShell „{0}” w katalogu „{1}” lub w żadnym nadrzędnym katalogu kultury. + + + Nie można zaimportować zlokalizowanych danych. Definicja dodatkowych obsługiwanych poleceń jest niedozwolona w tym trybie języka. + + + Nazwa BindingVariable „{0}” jest nieprawidłowa. + + + Polecenie cmdlet Import-LocalizedData + + + Dodatkowe obsługiwane polecenia (za pośrednictwem parametru SupportedCommand) nie będą dozwolone w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/MatchStringStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/MatchStringStrings.pl.resx new file mode 100644 index 00000000000..dc5589ae963 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/MatchStringStrings.pl.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 + + + Nie można otworzyć pliku, ponieważ bieżący dostawca ({0}) nie może otwierać plików. + + + Nie można odczytać pliku {0}: {1} + + + Opcja „Context” jest niedozwolona podczas wyszukiwania wyników przesyłanych potokowo z danych wyjściowych Select-String. + + + Ciąg {0} nie jest prawidłowym wyrażeniem regularnym: {1} + + + Parametr -Culture możesz podać tylko z parametrem -SimpleMatch. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/MeasureObjectStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/MeasureObjectStrings.pl.resx new file mode 100644 index 00000000000..a6b4c39ab94 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/MeasureObjectStrings.pl.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 + + + Nie można odnaleźć właściwości „{0}” w danych wejściowych dla żadnych obiektów. + + + Obiekt wejściowy „{0}” nie jest wartością liczbową. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/NewObjectStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/NewObjectStrings.pl.resx new file mode 100644 index 00000000000..4d5839056f7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/NewObjectStrings.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/OutPrinterDisplayStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/OutPrinterDisplayStrings.pl.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/OutPrinterDisplayStrings.pl.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SelectObjectStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SelectObjectStrings.pl.resx new file mode 100644 index 00000000000..4910a20018e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SelectObjectStrings.pl.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 + + + Nie można zmienić nazwy wielu wyników. + + + Nie można odnaleźć właściwości „{0}”. + + + Nie można rozszerzyć wielu właściwości. + + + Nie można przetworzyć właściwości, ponieważ właściwość „{0}” już istnieje. + + + Właściwość jest pustym blokiem skryptu i nie zawiera nazwy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SendMailMessageStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SendMailMessageStrings.pl.resx new file mode 100644 index 00000000000..517fab076c1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SendMailMessageStrings.pl.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 + + + Nie można wysłać wiadomości e-mail, ponieważ nie określono serwera SMTP. Serwer SMTP należy określić przy użyciu parametru SmtpServer lub zmiennej $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SortObjectStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SortObjectStrings.pl.resx new file mode 100644 index 00000000000..17c3027f8a6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/SortObjectStrings.pl.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 + + + Nie można odnaleźć elementu „Sort-Object” — „{0}” w obiekcie „InputObject”. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/StartSleepStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/StartSleepStrings.pl.resx new file mode 100644 index 00000000000..a87778d0c54 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/StartSleepStrings.pl.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 + + + Wartość parametru '-Duration' nie może przekraczać „{0}”. Podana wartość wynosiła „{1}”. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/TestJsonCmdletStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/TestJsonCmdletStrings.pl.resx new file mode 100644 index 00000000000..a4bf11ee9d8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/TestJsonCmdletStrings.pl.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 + + + Nie można przeanalizować schematu JSON. + + + Nie można przeanalizować kodu JSON. + + + JSON jest nieprawidłowy względem schematu: {0} w „{1}” + + + Nie można otworzyć pliku schematu JSON: {0} + + + Schemat identyfikatora URI „{0}” nie jest obsługiwany. Dozwolone są tylko identyfikatory URI HTTP(S) i lokalnego systemu plików. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/TraceCommandStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/TraceCommandStrings.pl.resx new file mode 100644 index 00000000000..4ff5e18defc --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/TraceCommandStrings.pl.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 + + + Dane wyjściowe śledzenia można zapisywać tylko w systemie plików. Ścieżka „{0}” odwołuje się do ścieżki dostawcy „{1}”. + + + Dane wyjściowe śledzenia mogą być zapisywane tylko w pojedynczym pliku. Ścieżka „{0}” została rozpoznana jako więcej niż jeden plik. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UnblockFileStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UnblockFileStrings.pl.resx new file mode 100644 index 00000000000..c269bd82055 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UnblockFileStrings.pl.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 + + + Polecenie cmdlet nie obsługuje systemu Linux. + + + Wystąpił błąd podczas odblokowywanie {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UpdateDataStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UpdateDataStrings.pl.resx new file mode 100644 index 00000000000..124c9b4b871 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UpdateDataStrings.pl.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 + + + Nie można otworzyć pliku, ponieważ bieżący dostawca to „{0}" , a to polecenie wymaga pliku. + + + Nie można odczytać pliku „{0}”, ponieważ nie ma on rozszerzenia nazwy pliku „{1}”. + + + Update TypeData + + + Update FormatData + + + Filename: {0} + + + Nie można zaktualizować elementu członkowskiego o typie „{0}”. Określ inny typ parametru MemberType. + + + Parametr {0} jest wymagany dla typu „{1}”. Określ typ parametru {0}. + + + Parametr {0} nie powinien mieć wartości null ani być pustym ciągiem dla składowej typu „{1}”. Określ wartość inną niż null dla parametru {0} podczas aktualizowania tego typu elementu członkowskiego. + + + Parametr {0} nie jest niezbędny dla składowej typu „{1}”. Nie należy go określać. Nie określaj parametru {0} podczas aktualizowania tego typu elementu członkowskiego. + + + Nie określono elementu członkowskiego dla aktualizacji w typie „{0}”. + + + Nazwa typu docelowego nie może mieć wartości null, być pusta ani zawierać tylko białych znaków. + + + Parametry Value i SecondValue nie powinny mieć jednocześnie wartości null dla składowej typu „{0}”. Określ wartość inną niż null dla jednego z dwóch parametrów. + + + Można określić tylko jeden typ elementu członkowskiego. Określone typy składowych to: „{0}” Zaktualizuj typ przy użyciu tylko jednego typu elementu członkowskiego. + + + Nie można określić parametrów MemberName, Value i SecondValue bez parametru MemberType. + + + Remove TypeData + + + Nazwa typu, który zostanie usunięty: {0} + + + Wpisz, aby zaktualizować: {0} + + + Usuń plik typu + + + Plik {0} nie jest importowany do bieżącej sesji. + + + Aktualizowanie danych formatu jest niedozwolone w tym obszarze uruchamiania. Właściwość „DisableFormatUpdates” jest ustawiona na wartość True podczas tworzenia obszaru uruchomieniowego. + + + Nie można zaktualizować danych formatu przy użyciu wystąpienia formatTable. + + + Nie można zaktualizować danych typu przy użyciu wystąpienia elementu TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UpdateListStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UpdateListStrings.pl.resx new file mode 100644 index 00000000000..e51e7fe890f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UpdateListStrings.pl.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 + + + Nie można odnaleźć właściwości „{0}” w tym obiekcie + + + Po określeniu parametru InputObject należy określić parametr Property. + + + Po określeniu parametru Property należy określić parametr InputObject. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UtilityCommonStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UtilityCommonStrings.pl.resx new file mode 100644 index 00000000000..31bfcd9183e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/UtilityCommonStrings.pl.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} ma co najmniej jeden nieprawidłowy wyjątek. + + + Nie można uruchomić tego polecenia, ponieważ ścieżka pliku „{0}” jest nieprawidłowa. Podaj prawidłową ścieżkę pliku, a następnie uruchom polecenie. + + + Nie można uruchomić tego polecenia, ponieważ element „{0}”" jest czysty lub pusty. Określ identyfikator CSSUri, a następnie uruchom polecenie. + + + Nie można otworzyć pliku, ponieważ bieżący dostawca ({0}) nie może otwierać plików. + + + Nie można uruchomić tego polecenia, ponieważ wartość prefiksu w parametrze Namespace ma wartość null. Podaj prawidłową wartość prefiksu, a następnie ponownie uruchom polecenie. + + + Nie można rozszerzyć obiektów pogrupowanych według tej właściwości, ponieważ istnieje duplikacja klucza. Podaj prawidłową wartość właściwości, a następnie spróbuj ponownie. + + + Polecenie nie jest obsługiwane w tym systemie operacyjnym. + + + Nie można odczytać pliku {0}: {1} + + + Nie można przekonwertować danych wejściowych typu „{0}” na szesnastkowy. Aby wyświetlić formatowanie szesnastkowe reprezentacji ciągu, przekaż je do polecenia cmdlet Out-String przed przesłaniem potoku do Format-Hex. + + + Podana ścieżka „{0}” nie jest obsługiwana. To polecenie obsługuje tylko ścieżki dostawcy systemu plików. + + + Ścieżka: + + + Nie można uruchomić polecenia, ponieważ parametr AsString wymaga określenia parametru AsHashtable. + + + Nie można uruchomić polecenia, ponieważ użycie parametru AsHashTable z więcej niż jedną właściwością wymaga dodania parametru AsString. + + + Nie można odnaleźć ścieżki „{0}”, ponieważ nie istnieje. + + + Nie można użyć tagu „{0}”. Prefiks „PS” jest zarezerwowany. + + + Nie można przeanalizować pliku „{0}” jako pliku danych programu PowerShell. + + + Nie można utworzyć deskryptora zabezpieczeń z danego pliku SDDL z powodu następującego błędu: {0} + + + Polecenie cmdlet Invoke-Expression + + + Blok skryptu polecenia cmdlet Invoke-Expression zostanie uruchomiony w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/VariableCommandStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/VariableCommandStrings.pl.resx new file mode 100644 index 00000000000..072132c8206 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/VariableCommandStrings.pl.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 + + + Ustaw zmienną + + + Nazwa: {0} Wartość: {1} + + + Użyj pojedynczej zmiennej, a nie kolekcji + + + Nowa zmienna + + + Nazwa: {0} Wartość: {1} + + + Usuń zmienną + + + Nazwa: {0} + + + Wyczyść zmienną + + + Nazwa: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WebCmdletStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WebCmdletStrings.pl.resx new file mode 100644 index 00000000000..beb82618d2c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WebCmdletStrings.pl.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 + + + Odmowa dostępu do ścieżki „{0}”. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WriteErrorStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WriteErrorStrings.pl.resx new file mode 100644 index 00000000000..f2049ef43a4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WriteErrorStrings.pl.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 + + + „Polecenie Write-Error zgłosiło błąd.” + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WriteProgressResourceStrings.pl.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WriteProgressResourceStrings.pl.resx new file mode 100644 index 00000000000..fbfc044c86c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pl/WriteProgressResourceStrings.pl.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 + + + Tekst opisujący działanie, dla którego jest raportowany postęp. + + + Tekst opisujący bieżący stan działania, dla którego jest raportowany postęp. + + + Przetwarzanie + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AddMember.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AddMember.pt-BR.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AddMember.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AddTypeStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AddTypeStrings.pt-BR.resx new file mode 100644 index 00000000000..18a15a6f605 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AddTypeStrings.pt-BR.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 + + + O código-fonte já foi compilado e carregado. + + + Não é possível adicionar o tipo. A extensão "{0}" não tem suporte. + + + Não é possível adicionar o tipo. Todos os arquivos de entrada devem ter a mesma extensão. + + + Não é possível adicionar o tipo. O assembly '{0}' não foi encontrado. + + + Não é possível adicionar o tipo. O nome do tipo '{0}' já existe. + + + Não é possível definir o assembly de saída. O caminho {0} não resolveu para um único arquivo. + + + Não é possível adicionar o tipo. Ocorreram erros de compilação. + + + Não é possível adicionar o tipo. O parâmetro OutputType exige que o parâmetro OutputAssembly seja especificado. + + + Não é possível adicionar o tipo. Não há suporte para a definição de novos tipos neste modo de linguagem. + + + O assembly de referência especificado '{0}' é desnecessário e será ignorado. + + + No momento, não há suporte para os tipos de assembly 'ConsoleApplication' e 'WindowsApplication'. + + + Cmdlet Add-Type + + + O cmdlet Add-Type não será permitido no modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AliasCommandStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AliasCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/AliasCommandStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertFromStringData.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertFromStringData.pt-BR.resx new file mode 100644 index 00000000000..909d5fc4e42 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertFromStringData.pt-BR.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 + + + A linha de dados '{0}' não está no formato 'name=value'. + + + O item de dados '{1}' na linha '{0}' já está definido. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertHTMLStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertHTMLStrings.pt-BR.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertHTMLStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertMarkdownStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertMarkdownStrings.pt-BR.resx new file mode 100644 index 00000000000..214c9d12da0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ConvertMarkdownStrings.pt-BR.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 + + + O tipo do objeto de entrada '{0}' é inválido. + + + Somente caminhos do Provedor FileSystem têm suporte. Não há suporte para o caminho do arquivo: '{0}'. + + + A propriedade {0} do objeto fornecido é nula ou vazia. + + + Nome do conjunto de parâmetros inválido: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/CsvCommandStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/CsvCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..4388886a111 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/CsvCommandStrings.pt-BR.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 + + + Não é possível acrescentar conteúdo CSV ao arquivo a seguir: {1}. O objeto acrescentado não tem uma propriedade que corresponda à coluna a seguir: {0}. Para continuar com propriedades incompatíveis, adicione o parâmetro -Force e tente o comando novamente. + {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. + + + + Você deve especificar os parâmetros -UseQuotes ou -QuoteFields, mas não ambos. + + + Você deve especificar os parâmetros -Path ou -LiteralPath, mas não ambos. + + + Um ou mais cabeçalhos não foram especificados. Nomes padrão que começam com "H" foram usados no lugar de cabeçalhos ausentes. + + + FileName é um parâmetro obrigatório. + + + O método ReconcilePreexistingPropertyNames só deve ser chamado ao anexar. + + + O método ReconcilePreexistingPropertyNames só deve ser chamado quando os nomes de propriedades preexistentes tiverem sido lidos com sucesso. + + + O método BuildPropertyNames deve ser chamado apenas uma vez por instância de cmdlet. + + + A hierarquia de tipos não deve ter valores nulos. + + + O fim do arquivo foi alcançado. + + + Você deve especificar os parâmetros -Append ou -NoHeader, mas não ambos. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/Debugger.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/Debugger.pt-BR.resx new file mode 100644 index 00000000000..4711ef99002 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/Debugger.pt-BR.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}'. + + + O arquivo '{0}' não existe. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/EventingStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/EventingStrings.pt-BR.resx new file mode 100644 index 00000000000..9d7d82ed69b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/EventingStrings.pt-BR.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. + + + Cancelar assinatura + + + Remover + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/FormatAndOut_out_gridview.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/FormatAndOut_out_gridview.pt-BR.resx new file mode 100644 index 00000000000..1ded52b6cf1 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/FormatAndOut_out_gridview.pt-BR.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 + + + Valor + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetFormatDataStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetFormatDataStrings.pt-BR.resx new file mode 100644 index 00000000000..e2a6747737b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetFormatDataStrings.pt-BR.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 + + + Processando a definição de exibição '{0}' + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetMember.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetMember.pt-BR.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetMember.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetRandomCommandStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetRandomCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..b3a7965b642 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetRandomCommandStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetUptimeStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetUptimeStrings.pt-BR.resx new file mode 100644 index 00000000000..4edfcc0d071 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/GetUptimeStrings.pt-BR.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 + + + "Não há suporte para a plataforma (System.Diagnostics.Stopwatch.IsHighResolution é falso)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/HostStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/HostStrings.pt-BR.resx new file mode 100644 index 00000000000..27fb9cc6392 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/HostStrings.pt-BR.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 + + + Não é possível processar a cor porque {0} não é uma cor válida. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/HttpCommandStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/HttpCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..b49aec19359 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/HttpCommandStrings.pt-BR.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 + + + Este comando não pode ser concluído devido ao seguinte erro: '{0}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ImplicitRemotingStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ImplicitRemotingStrings.pt-BR.resx new file mode 100644 index 00000000000..2aa0346a70e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ImplicitRemotingStrings.pt-BR.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 + + + Os dados retornados pelo comando remoto {0} não estão no formato esperado. + + + O cmdlet {0} requer os seguintes comandos na sessão remota: Get-Command, Get-FormatData e Select-Object. Os comandos a seguir são usados, mas opcionais: Get-Help e Measure-Object. Verifique se a sessão remota inclui os comandos necessários e tente novamente. + + + A execução do comando {0} em uma sessão remota relatou o seguinte erro: {1}. + + + A execução do comando {0} em uma sessão remota não retornou nenhum resultado. + + + Nenhuma sessão foi associada a este módulo de comunicação remota implícita. + + + Não foi possível resolver o alias remoto '{0}'. + + + A criação de proxy foi ignorada para o comando '{0}' porque o nome não correspondia ao valor do parâmetro Name. + + + A definição de tipo estendida foi ignorada para o tipo '{0}' porque seu nome não correspondia ao valor do parâmetro FormatTypeName. + + + A criação de proxy foi ignorada para o comando '{0}', pois o PowerShell não pôde verificar a segurança do nome do comando. + + + A criação de proxy foi ignorada para o seguinte comando: '{0}', porque ele iria sombrear um comando local existente. Use o parâmetro AllowClobber se quiser sombrear os comandos locais existentes. + + + Nenhum proxy de comando foi criado, porque todos os comandos remotos solicitados sombreiam os comandos locais existentes. Use o parâmetro AllowClobber se quiser sombrear os comandos locais existentes. + + + Comunicação remota implícita para {0} + + + Evento de comunicação remota implícita (ID da sessão: {0}; ID do manipulador de eventos: {1}) + + + Módulo de comunicação remota implícita + + + Gerado em {0} + + + por cmdlet {0} + + + Executado com a seguinte linha de comando: {0} + + + Parâmetro opcional que pode ser usado para especificar a sessão na qual este módulo proxy funciona + + + Criando uma nova sessão para comunicação remota implícita do comando "{{0}}"... + + + Sessão para módulo de comunicação remota implícita em {{0}} + + + Criando módulo de comunicação remota implícita... + + + Obtendo informações de comando da sessão remota... + + + Obtendo informações de comando da sessão remota... {0} comandos recebidos + + + Obtendo informações de formatação e saída da sessão remota... + + + Obtendo informações de formatação e saída da sessão remota... {0} objetos recebidos + + + Concluído. + + + Solicitação de Credencial do PowerShell + + + Insira suas credenciais para {0}. + + + Insira as credenciais de proxy HTTP usadas para a seguinte conexão: {0} + + + Os comandos que estão disponíveis na nova sessão remota são diferentes daqueles disponíveis quando o módulo de comunicação remota implícita foi criado. Considere criar o módulo novamente usando o cmdlet Export-PSSession. + + + Não é possível carregar arquivos porque a execução de scripts está desabilitada neste sistema. Forneça um certificado válido para assinar os arquivos. + + + O arquivo {0} não pôde ser assinado. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ImportLocalizedDataStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ImportLocalizedDataStrings.pt-BR.resx new file mode 100644 index 00000000000..84827251a03 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/ImportLocalizedDataStrings.pt-BR.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 + + + Não foi possível encontrar o arquivo de dados '{0}'. + + + O parâmetro FileName não foi especificado. O parâmetro FileName é necessário quando Import-LocalizedData não é chamado de um arquivo de script. + + + Ocorreu o seguinte erro enquanto o PowerShell abria o arquivo de dados '{0}': +{1}. + + + Ocorreu o seguinte erro enquanto o PowerShell carregava o arquivo de dados do script '{0}': +{1}. + + + O argumento do parâmetro FileName não deve conter um caminho. + + + Não foi possível localizar o arquivo de dados do PowerShell '{0}' no diretório '{1}' nem em nenhum diretório de cultura pai. + + + Não é possível importar dados localizados. A definição de comandos adicionais com suporte não é permitida neste modo de linguagem. + + + O nome de BindingVariable '{0}' é inválido. + + + Cmdlet Import-LocalizedData + + + Comandos adicionais com suporte (por meio do parâmetro SupportedCommand) não serão permitidos no modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/MatchStringStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/MatchStringStrings.pt-BR.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/MatchStringStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/MeasureObjectStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/MeasureObjectStrings.pt-BR.resx new file mode 100644 index 00000000000..c32c4ccc02c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/MeasureObjectStrings.pt-BR.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 + + + A propriedade "{0}" não pode ser encontrada na entrada de nenhum objeto. + + + O objeto de entrada "{0}" não é numérico. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/NewObjectStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/NewObjectStrings.pt-BR.resx new file mode 100644 index 00000000000..4d5839056f7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/NewObjectStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/OutPrinterDisplayStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/OutPrinterDisplayStrings.pt-BR.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/OutPrinterDisplayStrings.pt-BR.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SelectObjectStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SelectObjectStrings.pt-BR.resx new file mode 100644 index 00000000000..bdd62150f75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SelectObjectStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SendMailMessageStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SendMailMessageStrings.pt-BR.resx new file mode 100644 index 00000000000..fac6ae19485 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SendMailMessageStrings.pt-BR.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 + + + O email não pode ser enviado porque nenhum servidor SMTP foi especificado. Você deve especificar um servidor SMTP usando o parâmetro SmtpServer ou a variável $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SortObjectStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SortObjectStrings.pt-BR.resx new file mode 100644 index 00000000000..7b582db9f27 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/SortObjectStrings.pt-BR.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" - não foi possível encontrar "{0}" em "InputObject". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/StartSleepStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/StartSleepStrings.pt-BR.resx new file mode 100644 index 00000000000..8a9aed4bd67 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/StartSleepStrings.pt-BR.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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/TestJsonCmdletStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/TestJsonCmdletStrings.pt-BR.resx new file mode 100644 index 00000000000..49ee964a5e7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/TestJsonCmdletStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/TraceCommandStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/TraceCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..1e184349185 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/TraceCommandStrings.pt-BR.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 + + + A saída de rastreamento só pode ser gravada no sistema de arquivos. O caminho '{0}' se refere a um caminho de provedor '{1}'. + + + A saída de rastreamento só pode ser gravada em um único arquivo. O caminho '{0}' foi resolvido para mais de um arquivo. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UnblockFileStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UnblockFileStrings.pt-BR.resx new file mode 100644 index 00000000000..dc852cc519d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UnblockFileStrings.pt-BR.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 + + + O cmdlet não dá suporte ao Linux. + + + Ocorreu um erro ao desbloquear {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UpdateDataStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UpdateDataStrings.pt-BR.resx new file mode 100644 index 00000000000..f1f6f938907 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UpdateDataStrings.pt-BR.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 + + + Não é possível abrir o arquivo porque o provedor atual é "{0}" e este comando requer um arquivo. + + + Não é possível ler o arquivo "{0}" porque ele não tem a extensão de nome de arquivo "{1}". + + + Atualizar TypeData + + + Atualizar FormatData + + + FileName: {0} + + + Não é possível atualizar um membro com o tipo "{0}". Especifique um tipo diferente para o parâmetro MemberType. + + + O parâmetro {0} é necessário para o tipo "{1}". Especifique o parâmetro {0}. + + + O parâmetro {0} não deve ser nulo ou uma cadeia de caracteres vazia para um membro do tipo "{1}". Especifique um valor não nulo para o parâmetro {0} ao atualizar esse tipo de membro. + + + O parâmetro {0} não é necessário para um membro do tipo "{1}" e não deve ser especificado. Não especifique o parâmetro {0} ao atualizar esse tipo de membro. + + + Nenhum membro foi especificado para a atualização no tipo "{0}". + + + O nome do tipo de destino não deve ser nulo, estar vazio nem conter apenas espaços em branco. + + + Os parâmetros Value e SecondValue não devem ser nulos para um membro do tipo "{0}". Especifique um valor não nulo para um dos dois parâmetros. + + + Apenas um tipo de membro pode ser especificado. Os tipos de membro especificados são: "{0}". Atualize o tipo com apenas um tipo de membro. + + + Os parâmetros MemberName, Value e SecondValue não podem ser especificados sem o parâmetro MemberType. + + + Remover TypeData + + + Nome do tipo que será removido: {0} + + + Tipo a ser atualizado: {0} + + + Remover arquivo de tipo + + + O arquivo {0} não foi importado para a sessão atual. + + + Não é permitido atualizar dados de formato neste runspace. A propriedade "DisableFormatUpdates" está definida como True ao criar o runspace. + + + Não é possível atualizar os dados de formato com uma instância de FormatTable. + + + Não é possível atualizar os dados de tipo com uma instância de TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UpdateListStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UpdateListStrings.pt-BR.resx new file mode 100644 index 00000000000..d62def347e3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UpdateListStrings.pt-BR.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 + + + Não é possível encontrar a propriedade '{0}' neste objeto + + + Você deve especificar o parâmetro Property quando o parâmetro InputObject for especificado. + + + Você deve especificar o parâmetro InputObject quando o parâmetro Property for especificado. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UtilityCommonStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UtilityCommonStrings.pt-BR.resx new file mode 100644 index 00000000000..d086ee71627 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/UtilityCommonStrings.pt-BR.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} tem uma ou mais exceções inválidas. + + + Este comando não pode ser executado porque o caminho do arquivo "{0}" é inválido. Forneça um caminho de arquivo válido e execute o comando novamente. + + + Este comando não pode ser executado porque "{0}" está vazio ou em branco. Especifique CSSUri e execute o comando novamente. + + + Não é possível abrir o arquivo porque o provedor atual ({0}) não pode abrir arquivos. + + + Este comando não pode ser executado porque o valor do prefixo no parâmetro Namespace é nulo. Forneça um valor válido para o prefixo e execute o comando novamente. + + + Os objetos agrupados por essa propriedade não podem ser expandidos porque há duplicidade de chave. Forneça um valor válido para a propriedade e tente novamente. + + + O comando não tem suporte neste sistema operacional. + + + O arquivo "{0}" não pode ser lido: {1} + + + Não é possível converter a entrada do tipo "{0}" em hexa. Para ver a formatação hexa da representação em cadeia de caracteres, passe-a para o cmdlet Out-String antes de passá-la para Format-Hex. + + + Não há suporte para o caminho "{0}" fornecido. Este comando dá suporte apenas a caminhos do provedor FileSystem. + + + Caminho: + + + O comando não pode ser executado porque o parâmetro AsString exige que você especifique o parâmetro AsHashtable. + + + O comando não pode ser executado porque usar o parâmetro AsHashTable com mais de uma propriedade exige adicionar o parâmetro AsString. + + + Não é possível localizar o caminho '{0}' porque ele não existe. + + + Não é possível usar a marca "{0}". O prefixo "PS" está reservado. + + + Não foi possível analisar o arquivo "{0}" como um arquivo de dados do PowerShell. + + + Não é possível construir um descritor de segurança a partir do SDDL fornecido devido ao seguinte erro: {0} + + + Cmdlet Invoke-Expression + + + O bloco de script do cmdlet Invoke-Expression será executado no modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/VariableCommandStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/VariableCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..caf018acdae --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/VariableCommandStrings.pt-BR.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 + + + Definir variável + + + Nome: {0} Valor: {1} + + + Use uma única variável em vez de uma coleção + + + Nova variável + + + Nome: {0} Valor: {1} + + + Remover variável + + + Nome: {0} + + + Limpar variável + + + Nome: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WebCmdletStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WebCmdletStrings.pt-BR.resx new file mode 100644 index 00000000000..bddbf13e282 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WebCmdletStrings.pt-BR.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 + + + O acesso ao caminho '{0}' foi recusado. + + + O cmdlet não pode proteger segredos de texto sem formatação enviados por conexões não criptografadas. Para suprimir esse aviso e enviar segredos de texto sem formatação em redes não criptografadas, emita novamente o comando especificando o parâmetro AllowUnencryptedAuthentication. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: Authentication e UseDefaultCredentials. Authentication não oferece suporte a Credenciais padrão. Especifique Authentication ou UseDefaultCredentials e tente novamente. + + + O cmdlet não pode ser executado porque o seguinte parâmetro não foi especificado: Credencial. O tipo de Autenticação fornecido requer uma Credencial. Especifique Credencial e tente novamente. + + + O cmdlet não pode ser executado porque o seguinte parâmetro não foi especificado: Token. O tipo de Authentication fornecido requer um Token. Especifique Token e tente novamente. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: Credencial e Token. Especifique Credential ou Token e tente novamente. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: Body e InFile. Especifique Body ou InFile e tente novamente. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: Body e Form. Especifique Body ou Form e tente novamente. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: InFile e Form. Especifique InFile ou Form e tente novamente. + + + O cmdlet não pode ser executado porque o parâmetro -ContentType não é um cabeçalho Content-Type válido. Especifique um Content-Type válido para -ContentType e tente novamente. Para suprimir a validação de cabeçalho, forneça o parâmetro -SkipHeaderValidation. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: Credential e UseDefaultCredentials. Especifique Credential ou UseDefaultCredentials e tente novamente. + + + O caminho '{0}' resolve para um diretório. Especifique um caminho incluindo um nome de arquivo e repita o comando. + + + O JSON fornecido inclui uma propriedade cujo nome é uma cadeia de caracteres vazia. Isso só tem suporte com a opção -AsHashTable. + + + Não é possível converter a cadeia de caracteres JSON porque um dicionário convertido a partir da cadeia de caracteres contém a chave duplicada '{0}'. + + + O conteúdo da resposta não pode ser analisado porque o mecanismo do Internet Explorer não está disponível ou a configuração da primeira execução do Internet Explorer não está concluída. Especifique o parâmetro UseBasicParsing e tente novamente. + + + Não é possível seguir um redirecionamento inseguro por padrão. Reenvie o comando especificando a opção -AllowInsecureRedirect. + + + Não é possível converter a cadeia de caracteres JSON porque ela contém chaves com maiúsculas e minúsculas diferentes. Em vez disso, use a opção -AsHashTable. A chave que se tentou adicionar à chave existente '{0}' foi '{1}'. + + + A contagem máxima de redirecionamentos foi excedida. Para aumentar o número de redirecionamentos permitidos, forneça um valor maior para o parâmetro -MaximumRedirection. + + + O caminho '{0}' pode ser resolvido para vários caminhos. + + + O tipo '{0}' não tem suporte para serialização ou desserialização de um dicionário. As chaves devem ser cadeias de caracteres. + + + O caminho '{0}' não pode ser resolvido para um arquivo. + + + O caminho '{0}' não é um caminho do sistema de arquivos. Especifique o caminho para um arquivo no sistema de arquivos. + + + O cmdlet não pode ser executado porque o seguinte parâmetro está ausente: OutFile. Forneça um valor válido para o parâmetro OutFile ao usar o parâmetro {0} e tente novamente. + + + O arquivo não será baixado novamente porque o arquivo remoto tem o mesmo tamanho que o OutFile: {0} + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: ProxyCredential e ProxyUseDefaultCredentials. Especifique ProxyCredential ou ProxyUseDefaultCredentials e tente novamente. + + + O cmdlet não pode ser executado porque o seguinte parâmetro está ausente: Proxy. Forneça um URI de proxy válido para o parâmetro Proxy ao usar os parâmetros ProxyCredential ou ProxyUseDefaultCredentials e tente novamente. + + + Leitura do fluxo de resposta da Web concluída. Bytes baixados: {0} + + + Lendo o fluxo de resposta da Web + + + Baixados: {0} de {1} + + + A opção Resume só pode ser usada se OutFile apontar para um arquivo, mas ela resolve para um diretório: {0}. + + + O cmdlet não pode ser executado porque os seguintes parâmetros conflitantes foram especificados: Session e SessionVariable. Especifique Session ou SessionVariable e tente novamente. + + + Não foi possível recuperar certificados porque a impressão digital não é válida. Verifique a impressão digital e tente novamente. + + + Solicitação da Web concluída. (Número de bytes processados: {0}) + + + Solicitação da Web cancelada. (Número de bytes processados: {0}) + + + Status da solicitação da Web + + + Baixados: {0} de {1} + + + Falha na conversão de JSON com o erro: {0} + + + O código de status da réplica não indica êxito: {0} ({1}). + + + Seguindo o link rel {0} + + + O servidor remoto indicou que não foi possível retomar o download. O arquivo local será substituído. + + + Resposta HTTP/{0} de tipo de conteúdo {1} de tamanho desconhecido + + + Tentando novamente após o intervalo de {0} segundos. Código de status da tentativa anterior: {1} + + + O JSON resultante está truncado porque a serialização excedeu a profundidade definida de {0}. + + + As propriedades de WebSession foram alteradas entre as solicitações, forçando a recriação de todas as conexões HTTP na sessão. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WriteErrorStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WriteErrorStrings.pt-BR.resx new file mode 100644 index 00000000000..987d37e25d8 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WriteErrorStrings.pt-BR.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 + + + "O cmdlet Write-Error relatou um erro." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WriteProgressResourceStrings.pt-BR.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WriteProgressResourceStrings.pt-BR.resx new file mode 100644 index 00000000000..53ffa3a9046 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/pt-BR/WriteProgressResourceStrings.pt-BR.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 + + + Texto para descrever a atividade cujo andamento está sendo relatado. + + + Texto para descrever o estado atual da atividade cujo andamento está sendo relatado. + + + Processando + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AddMember.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AddMember.ru.resx new file mode 100644 index 00000000000..bed50223beb --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AddMember.ru.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 + + + Чтобы добавить элемент, можно указать только один тип элемента. Указаны следующие типы элементов: {0}. + + + Не удается добавить элемент с типом {0}. Укажите другой тип для параметра MemberTypes. + + + Параметр SecondValue необязателен для типа элемента {0}, и его не следует указывать. Не указывайте параметр SecondValue при добавлении элементов этого типа. + + + Параметр Value является обязательным для элемента типа {0}. Укажите параметр Value при добавлении элементов этого типа. + + + Параметры Value и SecondValue не могут одновременно иметь значение NULL для типа элемента {0}. Укажите значение, отличное от NULL, для одного из этих параметров. + + + Не удается добавить элемент с именем {0}, так как элемент с таким именем уже существует. Чтобы перезаписать элемент, добавьте в команду параметр Force. + + + Не удается принудительно добавить элемент с именем {0} и типом {1}. Элемент с таким именем и типом уже существует, а существующий элемент не является расширением экземпляра. + + + Элемент, на который ссылается этот псевдоним, не должен быть пустым или иметь значение NULL. + + + Параметр Value не должен иметь значение NULL для элемента типа {0}. При добавлении элементов этого типа укажите для параметра Value значение, отличное от NULL. + + + Параметр SecondValue не должен иметь значение NULL для элемента типа {0}. При добавлении элементов этого типа укажите для параметра SecondValue значение, отличное от NULL. + + + Параметр NotePropertyName не может принимать значения, которые можно преобразовать в тип {0}. Чтобы задать имя элемента с такими значениями, используйте Add-Member и укажите тип элемента. + + + Имя элемента NoteProperty не должно быть пустой строкой или иметь значение NULL. + + + Параметр TypeName не может быть пустым, иметь значение NULL или содержать только пробелы. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AddTypeStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AddTypeStrings.ru.resx new file mode 100644 index 00000000000..da89c76cbfd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AddTypeStrings.ru.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 + + + Исходный код уже скомпилирован и загружен. + + + Не удается добавить тип. Расширение "{0}" не поддерживается. + + + Не удается добавить тип. Все входные файлы должны иметь одинаковое расширение. + + + Не удается добавить тип. Не удается найти сборку "{0}". + + + Не удается добавить тип. Тип "{0}" уже существует. + + + Не удается задать выходную сборку. Путь {0} не разрешен в один файл. + + + Не удается добавить тип. Произошли ошибки компиляции. + + + Не удается добавить тип. Для параметра OutputType необходимо указать параметр OutputAssembly. + + + Не удается добавить тип. Определение новых типов не поддерживается в этом языковом режиме. + + + Указанная базовая сборка "{0}" не требуется и не учитывается. + + + Типы сборок "ConsoleApplication" и "WindowsApplication" в настоящее время не поддерживаются. + + + Командлет Add-Type + + + Командлет Add-Type не будет разрешен в режиме ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AliasCommandStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AliasCommandStrings.ru.resx new file mode 100644 index 00000000000..a5efb63a3cd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/AliasCommandStrings.ru.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 + + + Установить псевдоним + + + Имя: {0}, значение: {1} + + + Новый псевдоним + + + Имя: {0}, значение: {1} + + + Импорт псевдонима + + + Имя: {0}, значение: {1} + + + Не удается открыть файл {0} для экспорта псевдонима. {1} + + + Файл псевдонима + + + Кем экспортировано: {0} + + + Дата и время: {0:F} + + + Компьютер: {0} + + + Не удается импортировать псевдоним, так как указанный путь {0} относится к пути поставщика {1}. Измените значение параметра Path на путь файловой системы. + + + Не удается импортировать псевдоним, так как путь {0} содержит подстановочные знаки, которые разрешаются в несколько путей. Псевдонимы можно импортировать только из одного файла. Измените значение параметра Path так, чтобы он указывал на один файл. + + + Не удается открыть файл {0} для импорт псевдонима. {1} + + + Не удается импортировать псевдоним. Номер строки {1} в файле {0} не является правильно отформатированной строкой CSV для псевдонимов. Измените строку так, чтобы она содержала четыре значения, разделенные запятыми. Если текст значения сам содержит запятую, значение должно быть заключено в кавычки. + + + Не удается импортировать псевдоним, так как номер строки {1} в файле {0} содержит параметр, который не распознается для псевдонимов. Измените файл, чтобы в нем были только допустимые параметры. + + + Этой команде не удается найти соответствующий псевдоним, так как псевдоним с именем {0} {1} не существует. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertFromStringData.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertFromStringData.ru.resx new file mode 100644 index 00000000000..a91cd5f45c2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertFromStringData.ru.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 + + + Строка данных "{0}" не в формате "имя=значение". + + + Элемент данных "{1}" в строке "{0}" уже определен. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertHTMLStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertHTMLStrings.ru.resx new file mode 100644 index 00000000000..9ea785251e6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertHTMLStrings.ru.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 + + + Допустимые свойства метаданных: content-type, default-style, application-name, author, description, generator, keywords, x-ua-compatible и viewport. Пара элементов метаданных: {0} и {1} может неправильно работать. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertMarkdownStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertMarkdownStrings.ru.resx new file mode 100644 index 00000000000..a40c3f186dd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ConvertMarkdownStrings.ru.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 + + + Недопустимый тип входного объекта "{0}". + + + Поддерживаются только пути поставщика файловой системы. Путь к файлу "{0}" не поддерживается. + + + Свойство {0} данного объекта равно null или пустое. + + + Недопустимое имя набора параметров: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/CsvCommandStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/CsvCommandStrings.ru.resx new file mode 100644 index 00000000000..17ee8aab73d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/CsvCommandStrings.ru.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 + + + Не удается добавить содержимое CSV в следующий файл: {1}. Добавленный объект не содержит свойства, соответствующего следующему столбцу: {0}. Чтобы продолжить работу с несовпадающими свойствами, добавьте параметр -Force и повторите команду. + {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. + + + + Необходимо указать либо параметр -UseQuotes, либо параметр -QuoteFields, но не оба. + + + Необходимо указать либо параметр -Path, либо параметр -LiteralPath, но не оба. + + + Не указан один или несколько заголовков. Вместо отсутствующих заголовков использованы имена по умолчанию, начинающиеся с "H". + + + FileName является обязательным параметром. + + + Метод ReconcilePreexistingPropertyNames следует вызывать только при добавлении. + + + Метод ReconcilePreexistingPropertyNames следует вызывать только после успешного чтения существующих имен свойств. + + + Метод BuildPropertyNames следует вызывать только один раз для каждого экземпляра командлета. + + + Иерархия типов не должна содержать значения null. + + + Достигнут конец файла. + + + Необходимо указать либо параметр -Append, либо параметр -NoHeader, но не оба. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/Debugger.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/Debugger.ru.resx new file mode 100644 index 00000000000..5b669eeed0d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/Debugger.ru.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}'. + + + Файл "{0}" не существует. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/EventingStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/EventingStrings.ru.resx new file mode 100644 index 00000000000..99aead2ad36 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/EventingStrings.ru.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 + + + Событие с идентификатором источника "{0}" не существует. + + + Событие с идентификатором "{0}" не существует. + + + Подписка на событие с идентификатором источника "{0}" не существует. + + + Подписка на событие с идентификатором "{0}" не существует. + + + Подписка на событие "{0}" + + + Событие "{0}" + + + Для событий, не переданных третьим лицам, необходимо указать необходимые действия. + + + Отменить подписку + + + Удалить + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/FormatAndOut_out_gridview.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/FormatAndOut_out_gridview.ru.resx new file mode 100644 index 00000000000..34691c8b90c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/FormatAndOut_out_gridview.ru.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 + + + Формат данных не поддерживается в Out-GridView. + + + Платформа Microsoft .NET Framework 4.5 была установлена, когда выполнялся один или несколько сеансов PowerShell. Чтобы использовать командлет {0}, закройте все окна PowerShell, а затем откройте новое окно PowerShell. + + + Тип + + + Значение + + + Индекс + + + Команда "{0}" не найдена. + + + Найдено несколько команд с именем "{0}". Запустите "{1}" без параметров, а затем введите "{0}", чтобы отфильтровать результаты. + + + Невозможно записать данные в буфер ввода консоли. + + + Значение {0} должно быть меньше {1}. + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetFormatDataStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetFormatDataStrings.ru.resx new file mode 100644 index 00000000000..2b868a467ba --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetFormatDataStrings.ru.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 + + + Определение представления обработки "{0}" + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetMember.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetMember.ru.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetMember.ru.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetRandomCommandStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetRandomCommandStrings.ru.resx new file mode 100644 index 00000000000..e9dff322d37 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetRandomCommandStrings.ru.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" должно быть больше нуля. + + + Минимальное значение ({0}) не может быть больше или равно максимальному значению ({1}). + + + "minValue" не может быть больше maxValue. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetUptimeStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetUptimeStrings.ru.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/GetUptimeStrings.ru.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/HostStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/HostStrings.ru.resx new file mode 100644 index 00000000000..c86c396e04d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/HostStrings.ru.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 + + + Невозможно обработать цвет, так как {0} не является допустимым цветом. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/HttpCommandStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/HttpCommandStrings.ru.resx new file mode 100644 index 00000000000..0d55e047d13 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/HttpCommandStrings.ru.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 + + + Не удается завершить эту команду из-за следующей ошибки: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ImplicitRemotingStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ImplicitRemotingStrings.ru.resx new file mode 100644 index 00000000000..9992a08d502 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ImplicitRemotingStrings.ru.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 + + + Данные, возвращенные удаленной командой {0}, имеют неожиданный формат. + + + Командлет {0} требует наличия следующих команд в удаленном сеансе: Get-Command, Get-FormatData и Select-Object. Следующие команды используются, но не являются обязательными: Get-Help и Measure-Object. Убедитесь, что в удаленном сеансе есть необходимые команды, а затем повторите попытку. + + + При выполнении команды {0} в удаленном сеансе возникла следующая ошибка: {1}. + + + Выполнение команды {0} в удаленном сеансе не дало результатов. + + + С этим модулем неявного удаленного взаимодействия не связан ни один сеанс. + + + Не удалось разрешить удаленный псевдоним {0}. + + + Создание прокси для команды {0} пропущено, так как имя не соответствует значению параметра Name. + + + Определение расширенного типа пропущено для типа {0}, так как его имя не соответствует значению параметра FormatTypeName. + + + Создание прокси для команды {0} пропущено, так как PowerShell не удалось проверить безопасность имени команды. + + + Создание прокси пропущено для следующей команды: {0}, так как это приведет к перекрытию существующей локальной команды. Используйте параметр AllowClobber, если хотите перекрыть существующие локальные команды. + + + Прокси для команд не созданы, так как все запрошенные удаленные команды будут перекрывать существующие локальные команды. Используйте параметр AllowClobber, если хотите перекрыть существующие локальные команды. + + + Неявное удаленное взаимодействие для {0} + + + Событие неявного удаленного взаимодействия (идентификатор сеанса: {0}; идентификатор обработчика события: {1}) + + + Модуль неявного удаленного взаимодействия + + + создано {0} + + + с помощью командлета {0} + + + Вызвано с помощью следующей командной строки: {0} + + + Необязательный параметр, который можно использовать для указания сеанса, в котором работает этот модуль прокси + + + Создание нового сеанса для неявного удаленного взаимодействия с командой {{0}}... + + + Сеанс модуля неявного удаленного взаимодействия в {{0}} + + + Создание модуля неявного удаленного взаимодействия... + + + Получение сведений о командах из удаленного сеанса... + + + Получение сведений о командах из удаленного сеанса... Получено команд: {0} + + + Получение сведений о форматировании и выходных данных из удаленного сеанса... + + + Получение сведений о форматировании и выходных данных из удаленного сеанса... Получено объектов: {0} + + + Выполнено. + + + Запрос учетных данных PowerShell + + + Введите свои учетные данные для {0}. + + + Введите учетные данные прокси-сервера HTTP, которые используются для следующего подключения: {0} + + + Команды, доступные в новом удаленном сеансе, отличаются от команд, доступных при создании модуля неявного удаленного взаимодействия. Создайте модуль еще раз с помощью командлета Export-PSSession. + + + Не удается загрузить файлы, так как выполнение сценариев отключено в этой системе. Укажите действительный сертификат, чтобы подписать файлы. + + + Не удалось подписать файл {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ImportLocalizedDataStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ImportLocalizedDataStrings.ru.resx new file mode 100644 index 00000000000..364b74f1cce --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/ImportLocalizedDataStrings.ru.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 + + + Не удается найти файл данных {0}. + + + Параметр FileName не указан. Параметр FileName обязателен, если Import-LocalizedData не вызывается из файла сценария. + + + При открытии файла данных {0} в PowerShell произошла следующая ошибка: +{1}. + + + При загрузке файла данных сценария {0} в PowerShell произошла следующая ошибка: +{1}. + + + Аргумент для параметра FileName не должен содержать путь. + + + Не удается найти файл данных PowerShell {0} в каталоге {1} или в любом родительском каталоге языка. + + + Не удается импортировать локализованные данные. В этом режиме языка нельзя определять дополнительные поддерживаемые команды. + + + Имя BindingVariable {0} недопустимо. + + + Командлет Import-LocalizedData + + + В режиме ConstrainedLanguage нельзя использовать дополнительные поддерживаемые команды через параметр SupportedCommand. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/MatchStringStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/MatchStringStrings.ru.resx new file mode 100644 index 00000000000..1c46df3a685 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/MatchStringStrings.ru.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 + + + Не удалось открыть файл, поскольку текущий поставщик ({0}) не может открывать файлы. + + + Не удается прочесть файл {0}: {1} + + + Параметр "Context" не является допустимым при поиске результатов, полученных по конвейеру из выходных данных Select-String. + + + Ошибка: строка {0} не является допустимым регулярным выражением: {1} + + + Параметр -Culture необходимо указывать только с параметром -SimpleMatch. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/MeasureObjectStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/MeasureObjectStrings.ru.resx new file mode 100644 index 00000000000..95555b6b68b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/MeasureObjectStrings.ru.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 + + + Свойство {0} не найдено во входных данных ни для одного объекта. + + + Входной объект {0} не является числом. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/NewObjectStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/NewObjectStrings.ru.resx new file mode 100644 index 00000000000..600db9d56d6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/NewObjectStrings.ru.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 + + + Конструктор не найден. Не удается найти подходящий конструктор для типа {0}. + + + Не удается найти тип [{0}]: убедитесь, что сборка, содержащая этот тип, загружена. + + + Не удается загрузить тип COM {0}. + + + Объект, записанный в конвейер, является экземпляром типа "{0}" из основной сборки взаимодействия компонента. Если этот тип предоставляет не элементы IDispatch, а другие элементы, то скрипты, написанные для работы с этим объектом, могут не работать, если основная сборка взаимодействия не установлена. + + + Элемент "{1}" не найден для указанного объекта {2}. + + + Указанное значение недопустимо, или свойство доступно только для чтения. Измените значение и повторите попытку. + + + Создание экземпляров атрибутов и делегированных типов Windows RT не поддерживается. + + + Не удается создать экземпляры подобного ByRef типа "{0}". Типы, подобные ByRef, не поддерживаются в PowerShell. + + + Не удается создать тип. В этом языковом режиме поддерживаются только основные типы. + + + Не удается создать тип. В языковом режиме {0} на компьютере, заблокированном политикой, поддерживаются только основные типы. + + + Создание типа с помощью командлета New-Object + + + Тип "{0}" не будет создан в режиме ConstrainedLanguage. + + + Создание COM-объекта с помощью командлета New-Object + + + Объект COM "{0}" не будет создан в режиме ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/OutPrinterDisplayStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/OutPrinterDisplayStrings.ru.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/OutPrinterDisplayStrings.ru.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SelectObjectStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SelectObjectStrings.ru.resx new file mode 100644 index 00000000000..b2d9f7f9d44 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SelectObjectStrings.ru.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 + + + Не удается переименовать несколько результатов. + + + Не удается найти свойство "{0}". + + + Не удается развернуть несколько свойств. + + + Не удается обработать свойство, так как свойство "{0}" уже существует. + + + Свойство является пустым блоком сценария и не предоставляет имя. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SendMailMessageStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SendMailMessageStrings.ru.resx new file mode 100644 index 00000000000..6b62243e900 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SendMailMessageStrings.ru.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 + + + Не удается отправить сообщение электронной почты, так как не указан SMTP-сервер. Укажите SMTP-сервер с помощью параметра SmtpServer или переменной $PSEmailServer. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SortObjectStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SortObjectStrings.ru.resx new file mode 100644 index 00000000000..17e34a6bd8b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/SortObjectStrings.ru.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}" не удается найти в "InputObject". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/StartSleepStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/StartSleepStrings.ru.resx new file mode 100644 index 00000000000..c1eeba0708b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/StartSleepStrings.ru.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 + + + Значение параметра "-Duration" не должно превышать {0}. Указанное значение: {1}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/TestJsonCmdletStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/TestJsonCmdletStrings.ru.resx new file mode 100644 index 00000000000..22c3665b7b9 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/TestJsonCmdletStrings.ru.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 + + + Не удалось проанализировать схему JSON. + + + Не удалось проанализировать JSON. + + + JSON не является допустимым со схемой: {0} в "{1}" + + + Не удалось открыть файл схемы JSON: {0} + + + Схема URI "{0}" не поддерживается. Разрешены только URI HTTP(S) и URI локальной файловой системы. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/TraceCommandStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/TraceCommandStrings.ru.resx new file mode 100644 index 00000000000..c2cd31ff0fa --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/TraceCommandStrings.ru.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 + + + Результаты трассировки могут быть записаны только в файловую систему. Путь "{0}" ссылается на путь поставщика "{1}". + + + Результаты трассировки можно записать только в один файл. Путь "{0}" разрешен в несколько файлов. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UnblockFileStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UnblockFileStrings.ru.resx new file mode 100644 index 00000000000..01d006d227d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UnblockFileStrings.ru.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 + + + Командлет не поддерживает Linux. + + + Произошла ошибка при снятии блокировки {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UpdateDataStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UpdateDataStrings.ru.resx new file mode 100644 index 00000000000..f9249a05c0b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UpdateDataStrings.ru.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 + + + Не удается открыть файл, так как текущий поставщик — "{0}", а для этой команды требуется файл. + + + Не удается прочитать файл "{0}", так как у него нет расширения имени файла "{1}". + + + Обновить TypeData + + + Обновить FormatData + + + FileName: {0} + + + Не удается обновить тип элемента "{0}". Укажите другой тип для параметра MemberType. + + + Параметр {0} обязателен для типа "{1}". Укажите параметр {0}. + + + Параметр {0} не может иметь значение null или быть пустой строкой для типа элемента "{1}". При обновлении этого типа элемента укажите значение, отличное от null, для параметра {0}. + + + Параметр {0} необязателен для типа элемента "{1}", и его не следует указывать. Не указывайте параметр {0} при обновлении этого типа элемента. + + + Для обновления типа "{0}" не указан элемент. + + + Имя целевого типа не может быть пустым, иметь значение null или содержать только пробелы. + + + Параметры Value и SecondValue не могут одновременно иметь значение null для типа элемента "{0}". Укажите значение, отличное от null, для одного из этих параметров. + + + Можно указать только один тип элемента. Указаны следующие типы элементов: "{0}". Обновите тип, указав только один тип элемента. + + + Параметры MemberName, Value и SecondValue не могут быть указаны без параметра MemberType. + + + Удалить TypeData + + + Имя типа, который будет удален: {0} + + + Тип для обновления: {0} + + + Удалить тип файла + + + Файл {0} не импортирован в текущий сеанс. + + + Обновление формата данных в этом пространстве выполнения не разрешено. При создании пространства выполнения для свойства "DisableFormatUpdates" задается значение True. + + + Не удается обновить формат данных с помощью экземпляра FormatTable. + + + Не удается обновить тип данных с помощью экземпляра TypeTable. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UpdateListStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UpdateListStrings.ru.resx new file mode 100644 index 00000000000..d85eb56f587 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UpdateListStrings.ru.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} не найдено в этом объекте + + + Необходимо указать параметр Property, если указан параметр InputObject. + + + Необходимо указать параметр InputObject, если указан параметр Property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UtilityCommonStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UtilityCommonStrings.ru.resx new file mode 100644 index 00000000000..989f7128b72 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/UtilityCommonStrings.ru.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} содержит одно или несколько недопустимых исключений. + + + Невозможно выполнить эту команду, поскольку путь к файлу "{0}" недопустим. Укажите допустимый путь к файлу и повторите попытку. + + + Невозможно выполнить эту команду, поскольку элемент "{0}" пуст. Укажите CSSUri, затем выполните команду. + + + Не удалось открыть файл, поскольку текущий поставщик ({0}) не может открывать файлы. + + + Невозможно выполнить эту команду, поскольку значение префикса в параметре пространства имен равно null. Укажите допустимое значение префикса, затем снова выполните эту команду. + + + Объекты, сгруппированные по этому свойству, невозможно развернуть из-за дублирования ключа. Укажите допустимое значение свойства, затем повторите попытку. + + + Команда не поддерживается в этой операционной системе. + + + Невозможно прочесть файл "{0}": {1} + + + Невозможно преобразовать входные данные типа "{0}" в шестнадцатеричный формат. Чтобы просмотреть это строковое представление в шестнадцатеричном формате, передайте его в командлет Out-String перед передачей в Format-Hex. + + + Заданный путь "{0}" не поддерживается. Эта команда поддерживает только пути поставщика FileSystem. + + + Путь: + + + Невозможно выполнить эту команду, поскольку для параметра AsString необходимо указать параметр AsHashtable. + + + Невозможно выполнить эту команду, поскольку для использования параметра AsHashTable более чем с одним свойством необходимо добавить параметр AsString. + + + не удается найти путь "{0}", поскольку он не существует. + + + Невозможно использовать тег "{0}". Префикс "PS" зарезервирован. + + + Не удалось проанализировать файл "{0}" в качестве файла данных PowerShell. + + + Не удалось создать дескриптор безопасности из заданного SDDL из-за следующей ошибки: {0} + + + Командлет Invoke-Expression + + + Блок сценария командлета Invoke-Expression будет выполняться в режиме ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/VariableCommandStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/VariableCommandStrings.ru.resx new file mode 100644 index 00000000000..9160096b901 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/VariableCommandStrings.ru.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 + + + Задать переменную + + + Имя: {0}, значение: {1} + + + Используйте одну переменную вместо коллекции + + + Новая переменная + + + Имя: {0}, значение: {1} + + + Удалить переменную + + + Имя: {0} + + + Clear-Variable + + + Имя: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WebCmdletStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WebCmdletStrings.ru.resx new file mode 100644 index 00000000000..80c8a790ac3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WebCmdletStrings.ru.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 + + + Доступ к пути "{0}" запрещен. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WriteErrorStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WriteErrorStrings.ru.resx new file mode 100644 index 00000000000..a937658804c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WriteErrorStrings.ru.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 + + + "Командлет Write-Error сообщил об ошибке." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WriteProgressResourceStrings.ru.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WriteProgressResourceStrings.ru.resx new file mode 100644 index 00000000000..9e7e063b71b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/ru/WriteProgressResourceStrings.ru.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 + + + Текст, описывающий действие, о ходе выполнения которого сообщается. + + + Текст, описывающий текущее состояние действия, о ходе выполнения которого сообщается. + + + Обработка + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AddMember.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AddMember.tr.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AddMember.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AddTypeStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AddTypeStrings.tr.resx new file mode 100644 index 00000000000..9544b2a57da --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AddTypeStrings.tr.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 + + + Kaynak kodu zaten derlenmiş ve yüklenmişti. + + + Tür eklenemiyor. “{0}" uzantısı desteklenmiyor. + + + Tür eklenemiyor. Giriş dosyalarının tümü aynı dosya adı uzantısına sahip olmalıdır. + + + Tür eklenemiyor. ‘{0}' derlemesi bulunamadı. + + + Tür eklenemiyor. ‘{0}' tür adı zaten mevcut. + + + Çıktı derlemesi ayarlanamıyor. Yol {0} tek bir dosyaya çözümlenemedi. + + + Tür eklenemiyor. Derleme hataları oluştu. + + + Tür eklenemiyor. OutputType parametresi, OutputAssembly parametresinin belirtilmesini gerektirir. + + + Tür eklenemiyor. Bu bilgisayar dili modunda yeni türlerin tanımlanması desteklenmiyor. + + + Belirtilen '{0}' başvuru bütünleştirilmiş kodu gereksizdir ve yoksayılır. + + + Hem 'ConsoleApplication' hem de 'WindowsApplication' derleme türleri şu anda desteklenmiyor. + + + Add-Type Cmdlet + + + ConstrainedLanguage modunda Add-Type cmdlet'ine izin verilmeyecek. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AliasCommandStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AliasCommandStrings.tr.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/AliasCommandStrings.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertFromStringData.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertFromStringData.tr.resx new file mode 100644 index 00000000000..b78cad7a2eb --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertFromStringData.tr.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 + + + Veri satırı "{0}" "ad=değer" biçiminde değil. + + + Satır "{0}" içindeki "{1}" veri öğesi zaten tanımlı. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertHTMLStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertHTMLStrings.tr.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertHTMLStrings.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertMarkdownStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertMarkdownStrings.tr.resx new file mode 100644 index 00000000000..c928146d006 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ConvertMarkdownStrings.tr.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 + + + Giriş nesnesinin '{0}' türü geçersiz. + + + Yalnızca FileSystem Sağlayıcısı yolları desteklenir. Dosya yolu desteklenmiyor: '{0}'. + + + Belirtilen nesnenin {0} özelliği null veya boş. + + + Geçersiz parametre kümesi adı: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/CsvCommandStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/CsvCommandStrings.tr.resx new file mode 100644 index 00000000000..cf64bd058cd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/CsvCommandStrings.tr.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 + + + CSV içeriği aşağıdaki dosyaya eklenemiyor: {1}. Eklenen nesnede, şu sütuna karşılık gelen bir özellik bulunmamaktadır: {0}. Eşleşmeyen özelliklerle devam etmek için -Force parametresini ekleyin ve ardından komutu yeniden deneyin. + {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. + + + + -UseQuotes ya da -QuoteFields parametrelerinden birini belirtmeniz gerekir; ancak ikisini birden belirtemezsiniz. + + + -Path ya da -LiteralPath parametrelerinden birini belirtmeniz gerekir; ancak ikisini birden belirtemezsiniz. + + + Bir veya daha fazla başlık belirtilmemiştir. Eksik başlıkların yerine “H” harfiyle başlayan varsayılan isimler kullanılmıştır. + + + FileName zorunlu bir parametredir. + + + ReconcilePreexistingPropertyNames yöntemi yalnızca ekleme işlemi sırasında çağrılmalıdır. + + + ReconcilePreexistingPropertyNames yöntemi, yalnızca önceden var olan özellik adları başarıyla okunduğunda çağrılmalıdır. + + + BuildPropertyNames yöntemi, her cmdlet örneği için yalnızca bir kez çağrılmalıdır. + + + Tip hiyerarşisinde null değerler bulunmamalıdır. + + + EOF'a ulaşıldı. + + + -Append ya da -NoHeader parametrelerinden birini belirtmeniz gerekir; ancak ikisini birden belirtemezsiniz. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/Debugger.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/Debugger.tr.resx new file mode 100644 index 00000000000..dfced76494e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/Debugger.tr.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}'. + + + '{0}' dosyası yok. + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/EventingStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/EventingStrings.tr.resx new file mode 100644 index 00000000000..649e3d5ad27 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/EventingStrings.tr.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 + + + Kaynak tanımlayıcısı '{0}' olan olay yok. + + + Tanımlayıcısı '{0}' olan olay yok. + + + Kaynak tanımlayıcısı '{0}' olan olay aboneliği mevcut değil. + + + Tanımlayıcısı '{0}' olan olay aboneliği yok. + + + Olay aboneliği '{0}' + + + '{0}' olayı + + + İletilmeyen olaylar için bir eylem belirtilmelidir. + + + Aboneliği kaldır + + + Kaldır + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/FormatAndOut_out_gridview.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/FormatAndOut_out_gridview.tr.resx new file mode 100644 index 00000000000..72c3903542b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/FormatAndOut_out_gridview.tr.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 + + + Değer + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetFormatDataStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetFormatDataStrings.tr.resx new file mode 100644 index 00000000000..5eb225e3d5e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetFormatDataStrings.tr.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 + + + "{0}" görünüm tanımı işleniyor + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetMember.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetMember.tr.resx new file mode 100644 index 00000000000..407f7f7cb17 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetMember.tr.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 + + + Get-Member cmdlet'i için bir nesne belirtmelisiniz. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetRandomCommandStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetRandomCommandStrings.tr.resx new file mode 100644 index 00000000000..270bf26b395 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetRandomCommandStrings.tr.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' sıfırdan büyük olmalıdır. + + + En Küçük değer ({0}), En Büyük değerden ({1}) büyük veya buna eşit olamaz. + + + 'minValue', maxValue değerinden büyük olamaz. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetUptimeStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetUptimeStrings.tr.resx new file mode 100644 index 00000000000..e486059ddc4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/GetUptimeStrings.tr.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 + + + "platform desteklenmiyor (System.Diagnostics.Stopwatch.IsHighResolution false)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/HostStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/HostStrings.tr.resx new file mode 100644 index 00000000000..ec35114917d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/HostStrings.tr.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 + + + {0} geçerli bir renk olmadığından renk işlenemiyor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/HttpCommandStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/HttpCommandStrings.tr.resx new file mode 100644 index 00000000000..e5400c55f3a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/HttpCommandStrings.tr.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 + + + Komut şu hata nedeniyle tamamlanamıyor: '{0}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ImplicitRemotingStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ImplicitRemotingStrings.tr.resx new file mode 100644 index 00000000000..80834956fd2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ImplicitRemotingStrings.tr.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 + + + Uzak {0} komutundan döndürülen veri beklenen biçimde değil. + + + {0} cmdlet, uzak oturumdaki aşağıdaki komutları gerektirir: Get-Command, get-FormatData ve Select-Object. Aşağıdaki komutlar kullanılıyor, ancak isteğe bağlıdır: Get-Help ve Measure-Object. Uzak oturumun gerekli komutları içerdiğini doğrulayın ve ardından yeniden deneyin. + + + Uzak oturumda {0} komutu çalıştırılırken aşağıdaki hata bildirildi: {1}. + + + Uzak oturumda {0} komutu çalıştırıldığında sonuç döndürülmedi. + + + Bu sanal remoting modülüyle ilişkilendirilmiş bir oturum yok. + + + Uzak diğer ad '{0}' çözümlenemedi. + + + ‘{0}' komutu için proxy oluşturma atlandı; çünkü ad, Name parametresinin değeriyle eşleşmedi. + + + Genişletilmiş tür tanımı, adının FormatTypeName parametresinin değeriyle eşleşmemesi nedeniyle '{0}' türü için atlandı. + + + ‘{0}' komutu için proxy oluşturma atlandı; çünkü Windows PowerShell komut adının güvenliğini doğrulayamadı. + + + Aşağıdaki komut için proxy oluşturulması atlandı: '{0}', çünkü mevcut bir yerel komutun üzerine gölge düşürecekti. Mevcut yerel komutların üzerine gölge düşürmek istiyorsanız AllowClobber parametresini kullanın. + + + İstenen uzak komutların tümü mevcut yerel komutların üzerine gölge düşüreceğinden, hiçbir komut proxy'si oluşturulmadı. Mevcut yerel komutların üzerine gölge düşürmek istiyorsanız AllowClobber parametresini kullanın. + + + {0} için sanal remoting + + + Sanal remoting etkinliği (oturum kimliği: {0}; olay işleyicisi kimliği: {1}) + + + Sanal remoting modülü + + + {0} tarihinde oluşturuldu + + + by {0} cmdlet + + + Aşağıdaki komut satırıyla çağrıldı: {0} + + + Bu proxy modülünün çalıştığı oturumu belirtmek için kullanılabilecek isteğe bağlı parametre + + + "{{0}}" komutu için sanal remoting amacıyla yeni bir oturum oluşturuluyor... + + + {{0}} konumundaki sanal remoting modülü oturumu + + + Sanal remoting modülü oluşturuluyor ... + + + Uzak oturumdan komut bilgileri alınıyor ... + + + Uzak oturumdan komut bilgileri alınıyor ... {0} komut alındı + + + Uzak oturumdan biçimlendirme ve çıktı bilgileri alınıyor ... + + + Uzak oturumdan biçimlendirme ve çıktı bilgileri alınıyor ... {0} nesne alındı + + + Tamamlandı. + + + Windows PowerShell Kimlik Bilgisi İsteği + + + {0} için kimlik bilgilerinizi girin. + + + Aşağıdaki bağlantı için kullanılan HTTP ara sunucu kimlik bilgilerini girin: {0} + + + Yeni uzak oturumda kullanılabilir olan komutlar, sanal remoting modülü oluşturulduğundakilerden farklıdır. Modülü yeniden oluşturmak için Export-PSSession cmdlet'ini kullanmayı düşünün. + + + Dosyalar yüklenemiyor çünkü bu sistemde betiklerin çalıştırılması devre dışı bırakılmış. Dosyaları imzalamak için geçerli bir sertifika sağlayın. + + + Dosya {0} imzalanamadı. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ImportLocalizedDataStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ImportLocalizedDataStrings.tr.resx new file mode 100644 index 00000000000..21f2527a84c --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/ImportLocalizedDataStrings.tr.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 + + + "{0}" dosyası bulunamıyor. + + + FileName parametresi belirtilmedi. Import-LocalizedData bir betik dosyasından çağrılmadığında FileName parametresi gereklidir. + + + Windows PowerShell, "{0}" veri dosyasını açarken şu hata oluştu: +{1}. + + + Windows PowerShell, "{0}" betik veri dosyasını yüklerken şu hata oluştu: +{1}. + + + FileName parametresi için belirtilen bağımsız değişken bir yol içermemelidir. + + + "{0}" Windows PowerShell veri dosyası, "{1}" dizininde veya herhangi bir üst kültür dizininde bulunamıyor. + + + Yerelleştirilmiş veriler içeri aktarılamıyor. Bu dil modunda ek desteklenen komutların tanımlanmasına izin verilmiyor. + + + BindingVariable adı '{0}' geçersiz. + + + Import-LocalizedData Cmdlet + + + Desteklenen ek komutlara (SupportedCommand parametresi aracılığıyla) ConstrainedLanguage modunda izin verilmez. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/MatchStringStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/MatchStringStrings.tr.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/MatchStringStrings.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/MeasureObjectStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/MeasureObjectStrings.tr.resx new file mode 100644 index 00000000000..7f1bcb90e56 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/MeasureObjectStrings.tr.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 + + + "{0}" özelliği, hiçbir nesne için girişte bulunamadı. + + + Giriş nesnesi "{0}" sayısal değil. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/NewObjectStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/NewObjectStrings.tr.resx new file mode 100644 index 00000000000..4aad563d70d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/NewObjectStrings.tr.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 + + + Oluşturucu bulunamadı. {0} türü için uygun bir oluşturucu bulunamadı. + + + [{0}] türü bulunamadı: Bu türü içeren derlemenin yüklü olduğunu doğrulayın. + + + {0} COM türü yüklenemiyor. + + + İşlem hattına yazılan nesne, bileşenin birincil birlikte çalışabilirlik derlemesindeki "{0}" türünün bir örneğidir. Bu tür, IDispatch üyelerinden farklı üyeleri kullanıma sunuyorsa, bu nesneyle çalışacak şekilde yazılmış betikler, birincil birlikte çalışabilirlik derlemesi yüklü değilse çalışmayabilir. + + + Belirtilen {2} nesnesi için "{1}" üyesi bulunamadı. + + + Sağlanan değer geçerli değil veya özellik salt okunur. Değeri değiştirin ve ardından yeniden deneyin. + + + Öznitelik ve temsilci Windows RT türlerinin örneklerinin oluşturulması desteklenmez. + + + ByRef benzeri "{0}" türünün örnekleri oluşturulamıyor. ByRef benzeri türler PowerShell'de desteklenmez. + + + Tür oluşturulamıyor. Bu dil modunda yalnızca çekirdek türler desteklenir. + + + Tür oluşturulamıyor. İlke tarafından kilitlenen bir makinede {0} dil modunda yalnızca çekirdek türler desteklenir. + + + New-Object Cmdlet'i Tür Oluşturma + + + '{0}' türü ConstrainedLanguage modunda oluşturulmaz. + + + New-Object Cmdlet'i COM Nesnesi Oluşturma + + + '{0}' COM nesnesi ConstrainedLanguage modunda oluşturulmaz. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/OutPrinterDisplayStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/OutPrinterDisplayStrings.tr.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/OutPrinterDisplayStrings.tr.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SelectObjectStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SelectObjectStrings.tr.resx new file mode 100644 index 00000000000..bdd62150f75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SelectObjectStrings.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SendMailMessageStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SendMailMessageStrings.tr.resx new file mode 100644 index 00000000000..a20c5a39f2d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SendMailMessageStrings.tr.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 + + + SMTP sunucusu belirtilmediğinden e-posta gönderilemiyor. SmtpServer parametresini ya da $PSEmailServer değişkenini kullanarak bir SMTP sunucusu belirtmeniz gerekir. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SortObjectStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SortObjectStrings.tr.resx new file mode 100644 index 00000000000..43e9aa96524 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/SortObjectStrings.tr.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}", "InputObject" içinde bulunamıyor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/StartSleepStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/StartSleepStrings.tr.resx new file mode 100644 index 00000000000..97abe81bf3e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/StartSleepStrings.tr.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 + + + '-Duration' parametresi değeri '{0}' değerini aşmamalıdır, sağlanan değer '{1}' idi. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/TestJsonCmdletStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/TestJsonCmdletStrings.tr.resx new file mode 100644 index 00000000000..af2c7a143e3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/TestJsonCmdletStrings.tr.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 + + + JSON şeması ayrıştırılamıyor. + + + JSON ayrıştırılamıyor. + + + JSON, '{1}' konumunda {0} şeması ile geçerli değil + + + JSON şema dosyası açılamıyor: {0} + + + '{0}' URI düzeni desteklenmiyor. Yalnızca HTTP(S) ve yerel dosya sistemi URI'lerine izin verilir. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/TraceCommandStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/TraceCommandStrings.tr.resx new file mode 100644 index 00000000000..003d8e137ed --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/TraceCommandStrings.tr.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 + + + İzleme çıktısı yalnızca dosya sistemine yazılabilir. '{0}' yolu, bir '{1}' sağlayıcısı yoluna başvurdu. + + + İzleme çıktısı yalnızca tek bir dosyaya yazılabilir. '{0}' yolu birden fazla dosyaya çözümlendi. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UnblockFileStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UnblockFileStrings.tr.resx new file mode 100644 index 00000000000..194a6e1f35f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UnblockFileStrings.tr.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 + + + Cmdlet Linux'ı desteklemiyor. + + + {0} için engelleme kaldırılırken bir hata oluştu. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UpdateDataStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UpdateDataStrings.tr.resx new file mode 100644 index 00000000000..04a250ab42f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UpdateDataStrings.tr.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 + + + Dosya açılamıyor çünkü mevcut sağlayıcı “{0}” ve bu komut bir dosya gerektiriyor. + + + “{0}” dosyası, “{1}” dosya adı uzantısına sahip olmadığı için okunamıyor. + + + TypeData'yı güncelleştir + + + FormatData'yı güncelleştir + + + Dosya Adı: {0} + + + “{0}” türündeki bir üyeyi güncelleştiremiyorum. MemberType parametresi için farklı bir tür belirtin. + + + “{1}” türü için {0} parametresi zorunludur. Lütfen {0} parametresini belirtin. + + + “{1}” türündeki bir üye için {0} parametresi null veya boş bir dize olmamalıdır. Bu üye türünü güncelleştirirken {0} parametresi için null olmayan bir değer belirtin. + + + “{1}” türündeki bir üye için {0} parametresi gerekli değildir ve belirtilmemelidir. Bu üye türünü güncelleştirirken {0} parametresini belirtmeyin. + + + “{0}” türündeki güncelleştirme için herhangi bir üye belirtilmemiştir. + + + Hedef tür adı null olmamalı, boş olmamalı veya yalnızca boşluk karakterlerinden oluşmamalıdır. + + + “{0}” türündeki bir üye için Value ve SecondValue parametrelerinin ikisi de null olmamalıdır. İki parametreden biri için null olmayan bir değer belirtin. + + + Yalnızca bir üye türü belirtilebilir. Belirtilen üye türleri şunlardır: “{0}”. Türü, yalnızca bir üye türü içerecek şekilde güncelleştirin. + + + MemberName, Value ve SecondValue parametreleri, MemberType parametresi olmadan belirtilemez. + + + TypeData'yı kaldır + + + Kaldırılacak türün adı: {0} + + + Güncelleştirmek için şunu yazın: {0} + + + Dosya türünü kaldır + + + {0} dosyası mevcut oturuma içe aktarılmamıştır. + + + Bu çalışma alanında format verilerinin güncelleştirilmesine izin verilmez. Çalışma alanı oluşturulurken ‘DisableFormatUpdates’ özelliği True olarak ayarlanır. + + + FormatTable örneği kullanılarak biçim verileri güncelleştirilemiyor. + + + TypeTable örneği ile tür verileri güncelleştirilemiyor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UpdateListStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UpdateListStrings.tr.resx new file mode 100644 index 00000000000..fb6611cb792 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UpdateListStrings.tr.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}' özelliği bu nesnede bulunamıyor + + + InputObject parametresi belirtildiğinde Property parametresini belirtmelisiniz. + + + Özellik parametresi belirtildiğinde InputObject parametresini belirtmelisiniz. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UtilityCommonStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UtilityCommonStrings.tr.resx new file mode 100644 index 00000000000..2dbcab3f4d5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/UtilityCommonStrings.tr.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} geçersiz olan bir veya daha fazla özel durum içeriyor. + + + ‘{0}' dosya yolu geçersiz olduğu için bu komut çalıştırılamaz. Lütfen geçerli bir dosya yolu sağlayın ve ardından komutu çalıştırın. + + + ‘{0}' boş veya boşluk olduğu için bu komut çalıştırılamaz. Lütfen CSSUri belirtin ve ardından komutu çalıştırın. + + + Geçerli sağlayıcı ({0}) dosyaları açamadığı için dosya açılamıyor. + + + Namespace parametresindeki önek değeri null olduğu için bu komut çalıştırılamaz. Önek için geçerli bir değer sağlayın ve ardından komutu yeniden çalıştırın. + + + Bu özellik tarafından gruplandırılan nesneler, bir anahtar çoğaltması olduğu için genişletilemez. Özellik için geçerli bir değer sağlayın ve ardından yeniden deneyin. + + + Bu komut geçerli işletim sisteminde desteklenmiyor. + + + ‘{0}' dosyası okunamıyor: {1} + + + ‘{0}' türündeki giriş onaltılığa dönüştürülemiyor. Dize gösteriminin onaltılık biçimlendirmesini görüntülemek için, Format-Hex'e göndermeden önce onu Out-String cmdlet'ine kanal oluşturun. + + + Verilen '{0}' yolu desteklenmiyor. Bu komut yalnızca FileSystem Provider yollarını destekler. + + + Yol: + + + AsString parametresi, AsHashtable parametresini belirtmenizi gerektirdiği için bu komut çalıştırılamaz. + + + AsHashTable parametresini birden fazla özellik ile kullanmak, AsString parametresinin eklenmesini gerektirdiğinden bu komut çalıştırılamaz. + + + ‘{0}' yolu bulunamadığı için bulunamıyor. + + + ‘{0}' etiketi kullanılamaz. 'PS' öneki ayrılmış. + + + ‘{0}' PowerShell Veri dosyası olarak ayrıştırılamadı. + + + Verilen hata nedeniyle güvenlik tanımlayıcısı belirtilen SDDL'den oluşturulamıyor: {0} + + + Invoke-Expression Cmdlet + + + Invoke-Expression cmdlet betik bloğu, ConstrainedLanguage modunda çalıştırılacak. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/VariableCommandStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/VariableCommandStrings.tr.resx new file mode 100644 index 00000000000..d8b7aa2c9db --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/VariableCommandStrings.tr.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 + + + Değişken ayarla + + + Ad: {0} Değer: {1} + + + Tek bir değişken kullanın, koleksiyon yerine + + + Yeni değişken + + + Ad: {0} Değer: {1} + + + Değişkeni kaldır + + + Ad: {0} + + + Değişkeni temizle + + + Ad: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WebCmdletStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WebCmdletStrings.tr.resx new file mode 100644 index 00000000000..ef580bbc142 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WebCmdletStrings.tr.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 + + + '{0}' yoluna erişim reddedildi. + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WriteErrorStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WriteErrorStrings.tr.resx new file mode 100644 index 00000000000..51d65239054 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WriteErrorStrings.tr.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 + + + "Write-Error cmdlet'i bir Hata bildirdi." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WriteProgressResourceStrings.tr.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WriteProgressResourceStrings.tr.resx new file mode 100644 index 00000000000..b2c0b402555 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/tr/WriteProgressResourceStrings.tr.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 + + + İlerlemenin bildirildiği etkinliği açıklayan metin. + + + İlerlemenin bildirildiği etkinliğin mevcut durumunu açıklayan metin. + + + İşleniyor + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AddMember.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AddMember.zh-Hans.resx new file mode 100644 index 00000000000..e7ce64965ab --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AddMember.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AddTypeStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AddTypeStrings.zh-Hans.resx new file mode 100644 index 00000000000..425a1a71764 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AddTypeStrings.zh-Hans.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 + + + 已编译并加载源代码。 + + + 无法添加类型。不支持“{0}”扩展。 + + + 无法添加类型。输入文件必须全部具有相同的文件扩展名。 + + + 无法添加类型。找不到程序集“{0}”。 + + + 无法添加类型。类型名称“{0}”已存在。 + + + 无法设置输出程序集。路径 {0} 未解析为单个文件。 + + + 无法添加类型。出现编译错误。 + + + 无法添加类型。OutputType 参数要求指定 OutputAssembly 参数。 + + + 无法添加类型。此语言模式不支持新类型的定义。 + + + 指定的引用程序集“{0}”不是必需的,并且将被忽略。 + + + 当前不支持程序集类型 'ConsoleApplication' 和 'WindowsApplication'。 + + + Add-Type Cmdlet + + + ConstrainedLanguage 模式不允许使用 Add-Type cmdlet。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AliasCommandStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AliasCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/AliasCommandStrings.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertFromStringData.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertFromStringData.zh-Hans.resx new file mode 100644 index 00000000000..5a2603d98f0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertFromStringData.zh-Hans.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 + + + 数据行“{0}”未采用 'name=value' 格式。 + + + 行“{0}”中的数据项“{1}”已被定义。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertHTMLStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertHTMLStrings.zh-Hans.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertHTMLStrings.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertMarkdownStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertMarkdownStrings.zh-Hans.resx new file mode 100644 index 00000000000..65165e5ff0b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ConvertMarkdownStrings.zh-Hans.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 + + + 输入对象 '{0}' 的类型无效。 + + + 仅支持 FileSystem 提供程序路径。不支持文件路径: '{0}'。 + + + 给定对象的属性 {0} 为 null 或为空。 + + + 无效的参数集名称: {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/CsvCommandStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/CsvCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..454fbd916b5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/CsvCommandStrings.zh-Hans.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 + + + 无法将 CSV 内容追加到以下文件: {1}。追加的对象没有对应于以下列的属性: {0}。要继续使用不匹配的属性,请添加 -Force 参数,然后重试该命令。 + {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. + + + + 必须指定 -UseQuotes 或 -QuoteFields 参数之一,但不能同时指定两者。 + + + 必须指定 -Path 或 -LiteralPath 参数之一,但不能同时指定两者。 + + + 未指定一个或多个标头。已使用以 "H" 开头的默认名称来代替任何缺失的标头。 + + + FileName 是必需参数。 + + + 只有在追加时才应调用 ReconcilePreexistingPropertyNames 方法。 + + + 只有在已成功读取预先存在的属性名称时,才应调用 ReconcilePreexistingPropertyNames 方法。 + + + 每个 cmdlet 实例只能调用一次 BuildPropertyNames 方法。 + + + 类型层次结构不应具有 null 值。 + + + 已达到 EOF。 + + + 必须指定 -Append 或 -NoHeader 参数,但不能同时指定两者。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/Debugger.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/Debugger.zh-Hans.resx new file mode 100644 index 00000000000..a8e17de0d04 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/Debugger.zh-Hans.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}'. + + + 文件“{0}”不存在。 + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/EventingStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/EventingStrings.zh-Hans.resx new file mode 100644 index 00000000000..909d1f11bfd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/EventingStrings.zh-Hans.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 + + + 源标识符为“{0}”的事件不存在。 + + + 标识符为“{0}”的事件不存在。 + + + 源标识符为“{0}”的事件订阅不存在。 + + + 标识符为“{0}”的事件订阅不存在。 + + + 事件订阅“{0}” + + + 事件“{0}” + + + 必须为非转发事件指定操作。 + + + 取消订阅 + + + 移除 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/FormatAndOut_out_gridview.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/FormatAndOut_out_gridview.zh-Hans.resx new file mode 100644 index 00000000000..fcc9f4542db --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/FormatAndOut_out_gridview.zh-Hans.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 + + + + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetFormatDataStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetFormatDataStrings.zh-Hans.resx new file mode 100644 index 00000000000..33abd5025ce --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetFormatDataStrings.zh-Hans.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 + + + 正在处理视图定义 '{0}' + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetMember.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetMember.zh-Hans.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetMember.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetRandomCommandStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetRandomCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..3986d2305d0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetRandomCommandStrings.zh-Hans.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' 必须大于零。 + + + 最小值({0})不能大于或等于最大值({1})。 + + + 'minValue' 不能大于 maxValue。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetUptimeStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetUptimeStrings.zh-Hans.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/GetUptimeStrings.zh-Hans.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/HostStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/HostStrings.zh-Hans.resx new file mode 100644 index 00000000000..262799a448d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/HostStrings.zh-Hans.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 + + + 无法处理该颜色,因为 {0} 不是有效颜色。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/HttpCommandStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/HttpCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..e8aa6480202 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/HttpCommandStrings.zh-Hans.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 + + + 由于以下错误,无法完成此命令:“{0}”。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ImplicitRemotingStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ImplicitRemotingStrings.zh-Hans.resx new file mode 100644 index 00000000000..936defa25de --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ImplicitRemotingStrings.zh-Hans.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 + + + 远程 {0} 命令返回的数据为采用预期格式。 + + + {0} cmdlet 要求远程会话中包含以下命令: Get-Command、Get-FormatData 和 Select-Object。可以使用以下命令,但它们不是必需的: Get-Help 和 Measure-Object。验证远程会话是否包含所需命令,然后重试。 + + + 在远程会话中运行 {0} 命令时报告了以下错误: {1}。 + + + 在远程会话中运行 {0} 命令未返回结果。 + + + 没有会话与此隐式远程处理模块关联。 + + + 无法解析远程别名 '{0}'。 + + + 已跳过 '{0}' 命令的代理创建,因为名称与 Name 参数的值不匹配。 + + + 已跳过 '{0}' 类型的扩展类型定义,因为其名称与 FormatTypeName 参数的值不匹配。 + + + 已跳过 '{0}' 命令的代理创建,因为 PowerShell 无法验证命令名称的安全性。 + + + 已跳过以下命令的代理创建: '{0}',因为它会遮蔽现有的本地命令。 如果要遮蔽现有本地命令,请使用 AllowClobber 参数。 + + + 未创建任何命令代理,因为请求的所有远程命令都会遮蔽现有的本地命令。 如果要遮蔽现有本地命令,请使用 AllowClobber 参数。 + + + 针对 {0} 的隐式远程处理 + + + 隐式远程处理事件(会话 ID: {0};事件处理程序 ID: {1}) + + + 隐式远程处理模块 + + + 生成时间: {0} + + + 通过 {0} cmdlet + + + 请使用以下命令行进行调用: {0} + + + 可选参数,可用于指定此代理模块在哪个会话上运行 + + + 正在为隐式远程处理 "{{0}}" 命令创建新会话... + + + 位于 {{0}} 的隐式远程处理模块会话 + + + 正在创建隐式远程处理模块... + + + 正在从远程会话获取命令信息... + + + 正在从远程会话获取命令信息... 已收到 {0} 条命令 + + + 正在从远程会话获取格式和输出信息... + + + 正在从远程会话获取格式和输出信息... 已收到 {0} 个对象 + + + 已完成。 + + + PowerShell 凭据请求 + + + 输入 {0} 的凭据。 + + + 输入用于以下连接的 HTTP 代理凭据: {0} + + + 新远程会话中可用的命令与创建隐式远程处理模块时可用的命令不同。 请考虑使用 Export-PSSession cmdlet 重新创建该模块。 + + + 无法加载文件,因为此系统上已禁用脚本运行功能。请提供用于对文件进行签名的有效证书。 + + + 无法对文件 {0} 进行签名。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ImportLocalizedDataStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ImportLocalizedDataStrings.zh-Hans.resx new file mode 100644 index 00000000000..5455a8e9ac2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/ImportLocalizedDataStrings.zh-Hans.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 + + + 找不到数据文件 '{0}'。 + + + 未指定 FileName 参数。如果不是从脚本文件调用 Import-LocalizedData,则需要 FileName 参数。 + + + PowerShell 打开数据文件 '{0}' 时发生以下错误: +{1}。 + + + PowerShell 加载 '{0}' 脚本数据文件时发生以下错误: +{1}。 + + + FileName 参数的自变量不应包含路径。 + + + 无法在目录 '{1}' 或任何父区域性目录中找到 PowerShell 数据文件 '{0}'。 + + + 无法导入本地化数据。此语言模式不允许定义其他受支持的命令。 + + + BindingVariable 名称 '{0}' 无效。 + + + Import-LocalizedData Cmdlet + + + 在 ConstrainedLanguage 模式下,不允许使用其他受支持的命令(通过 SupportedCommand 参数)。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/MatchStringStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/MatchStringStrings.zh-Hans.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/MatchStringStrings.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/MeasureObjectStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/MeasureObjectStrings.zh-Hans.resx new file mode 100644 index 00000000000..c8d4ecabd5d --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/MeasureObjectStrings.zh-Hans.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 + + + 在任何对象的输入中都找不到属性“{0}”。 + + + 输入对象“{0}”不是数值。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/NewObjectStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/NewObjectStrings.zh-Hans.resx new file mode 100644 index 00000000000..68032620ee5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/NewObjectStrings.zh-Hans.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 + + + 找不到构造函数。找不到类型 {0} 的合适的构造函数。 + + + 找不到类型 [{0}]: 请验证是否已加载包含此类型的程序集。 + + + 无法加载 COM 类型 {0}。 + + + 写入管道的对象是来自组件主互操作程序集的类型 "{0}" 的实例。如果此类型公开的成员与 IDispatch 成员不同,那么在未安装主互操作程序集时,编写以使用此对象的脚本可能无法正常工作。 + + + 未找到指定 {2} 对象的成员 "{1}"。 + + + 提供的值无效,或者该属性为只读。请更改该值,然后重试。 + + + 不支持创建属性和委托 Windows RT 类型的实例。 + + + 无法创建类似 ByRef 的类型 "{0}" 的实例。PowerShell 不支持类似 ByRef 的类型。 + + + 无法创建类型。此语言模式仅支持核心类型。 + + + 无法创建类型。在策略锁定的计算机上的 {0} 语言模式下,仅支持核心类型。 + + + New-Object Cmdlet 类型创建 + + + ConstrainedLanguage 模式下不会创建类型 "{0}"。 + + + New-Object cmdlet COM 对象创建 + + + ConstrainedLanguage 模式下不会创建 COM 对象 "{0}"。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/OutPrinterDisplayStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/OutPrinterDisplayStrings.zh-Hans.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/OutPrinterDisplayStrings.zh-Hans.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SelectObjectStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SelectObjectStrings.zh-Hans.resx new file mode 100644 index 00000000000..bdd62150f75 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SelectObjectStrings.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SendMailMessageStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SendMailMessageStrings.zh-Hans.resx new file mode 100644 index 00000000000..8cd5b19ccb4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SendMailMessageStrings.zh-Hans.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 + + + 由于未指定 SMTP 服务器,因此无法发送电子邮件。必须使用 SmtpServer 参数或 $PSEmailServer 变量指定 SMTP 服务器。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SortObjectStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SortObjectStrings.zh-Hans.resx new file mode 100644 index 00000000000..4dca6b67103 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/SortObjectStrings.zh-Hans.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 + + + 在 "InputObject" 中找不到 "Sort-Object" -“{0}”。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/StartSleepStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/StartSleepStrings.zh-Hans.resx new file mode 100644 index 00000000000..49d08be7677 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/StartSleepStrings.zh-Hans.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 + + + "-Duration" 参数值不能超过“{0}”,提供的值为“{1}”。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/TestJsonCmdletStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/TestJsonCmdletStrings.zh-Hans.resx new file mode 100644 index 00000000000..c332d90bcef --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/TestJsonCmdletStrings.zh-Hans.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 + + + 无法分析 JSON 架构。 + + + 无法分析 JSON。 + + + JSON 对位于“{1}”的架构 {0} 无效 + + + 无法打开 JSON 架构文件: {0} + + + 不支持 URI 架构“{0}”。仅允许 HTTP(S)和本地文件系统 URI。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/TraceCommandStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/TraceCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..5634ea6e8a3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/TraceCommandStrings.zh-Hans.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 + + + 只能将跟踪输出写入文件系统。路径“{0}”引用了“{1}”提供程序路径。 + + + 只能将跟踪输出写入单个文件。路径“{0}”已解析为多个文件。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UnblockFileStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UnblockFileStrings.zh-Hans.resx new file mode 100644 index 00000000000..1c1c2e7f0c0 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UnblockFileStrings.zh-Hans.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 + + + 该 cmdlet 不支持 Linux。 + + + 取消阻止 {0} 时出错。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UpdateDataStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UpdateDataStrings.zh-Hans.resx new file mode 100644 index 00000000000..52c77a16b44 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UpdateDataStrings.zh-Hans.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 + + + 无法打开文件,因为当前提供程序为“{0}”,而此命令需要一个文件。 + + + 无法读取文件“{0}”,因为它没有文件扩展名“{1}”。 + + + 更新 TypeData + + + 更新 FormatData + + + 文件名: {0} + + + 无法更新类型为“{0}”的成员。请为 MemberType 参数指定其他类型。 + + + 类型“{1}”需要 {0} 参数。请指定 {0} 参数。 + + + 对于类型为“{1}”的成员,{0} 参数不能为 null 或为空字符串。更新此成员类型时,请为 {0} 参数指定一个非 null 值。 + + + 对于类型为“{1}”的成员,{0} 参数不是必需项,因此不应指定。更新此成员类型时,请不要指定 {0} 参数。 + + + 未为类型“{0}”的更新指定任何成员。 + + + 目标类型名称不能为 null、不能为空或仅包含空格。 + + + 对于类型为“{0}”的成员,Value 和 SecondValue 参数不能同时为 null。请为这两个参数中的一个指定非 null 值。 + + + 只能指定一个成员类型。指定的成员类型为: “{0}”。仅使用一种成员类型更新类型。 + + + 如果没有 MemberType 参数,则不能指定 MemberName、Value 和 SecondValue 参数。 + + + 移除 TypeData + + + 要移除的类型名称: {0} + + + 要更新的类型: {0} + + + 移除类型文件 + + + 文件 {0} 未导入到当前会话中。 + + + 此运行空间不允许更新格式数据。创建运行空间时,"DisableFormatUpdates" 属性设置为 True。 + + + 无法使用 FormatTable 实例更新格式数据。 + + + 无法使用 TypeTable 实例更新类型数据。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UpdateListStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UpdateListStrings.zh-Hans.resx new file mode 100644 index 00000000000..98caf649e5a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UpdateListStrings.zh-Hans.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}' + + + 指定 InputObject 参数时,必须指定 Property 参数。 + + + 指定 Property 参数时,必须指定 InputObject 参数。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UtilityCommonStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UtilityCommonStrings.zh-Hans.resx new file mode 100644 index 00000000000..7c5eb07c006 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/UtilityCommonStrings.zh-Hans.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} 具有一个或多个无效的异常。 + + + 无法运行此命令,因为文件路径“{0}”无效。请提供有效的文件路径,然后运行该命令。 + + + 无法运行此命令,因为“{0}”为空或为空白。请指定 CSSUri,然后运行该命令。 + + + 无法打开文件,因为当前提供程序({0})无法打开文件。 + + + 无法运行此命令,因为 Namespace 参数中的前缀值为 null。提供前缀的有效值,然后再次运行该命令。 + + + 无法展开按此属性分组的对象,因为存在键重复。请提供属性的有效值,然后重试。 + + + 此操作系统不支持该命令。 + + + 无法读取文件“{0}”: {1} + + + 无法将“{0}”类型的输入转换为十六进制。要查看其字符串表示形式的十六进制格式,请将其通过管道传递给 Out-String cmdlet,然后再将其传递给 Format-Hex。 + + + 不支持给定的路径“{0}”。此命令仅支持 FileSystem 提供程序路径。 + + + 路径: + + + 无法运行该命令,因为 AsString 参数要求指定 AsHashtable 参数。 + + + 无法运行该命令,因为使用具有多个属性的 AsHashTable 参数需要添加 AsString 参数。 + + + 找不到路径“{0}”,因为该路径不存在。 + + + 无法使用标记“{0}”。已保留 'PS' 前缀。 + + + 无法将文件“{0}”分析为 PowerShell 数据文件。 + + + 由于以下错误,无法根据给定的 SDDL 构造安全描述符: {0} + + + Invoke-Expression Cmdlet + + + Invoke-Expression cmdlet 脚本块将在 ConstrainedLanguage 模式下运行。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/VariableCommandStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/VariableCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..b02198a2b72 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/VariableCommandStrings.zh-Hans.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 + + + 设置变量 + + + 名称: {0} 值: {1} + + + 使用单个变量而不是集合 + + + 新变量 + + + 名称: {0} 值: {1} + + + 移除变量 + + + 名称: {0} + + + 清除变量 + + + 名称: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WebCmdletStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WebCmdletStrings.zh-Hans.resx new file mode 100644 index 00000000000..d6c7a8b3e38 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WebCmdletStrings.zh-Hans.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 + + + 对路径“{0}”的访问被拒绝。 + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WriteErrorStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WriteErrorStrings.zh-Hans.resx new file mode 100644 index 00000000000..66186f9b7cd --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WriteErrorStrings.zh-Hans.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 + + + “Write-Error cmdlet 报告了错误。” + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WriteProgressResourceStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WriteProgressResourceStrings.zh-Hans.resx new file mode 100644 index 00000000000..c307454cc91 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hans/WriteProgressResourceStrings.zh-Hans.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 + + + 用于描述正在报告进度的活动的文本。 + + + 用于描述正在报告进度的活动当前状态的文本。 + + + 正在处理 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AddMember.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AddMember.zh-Hant.resx new file mode 100644 index 00000000000..bb7d9b27fe6 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AddMember.zh-Hant.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 + + + 若要新增成員,只能指定一種成員類型。指定的成員類型為: "{0}" + + + 無法新增類型為 "{0}" 的成員。請為 MemberTypes 參數指定不同的類型。 + + + 類型為 "{0}" 的成員不需要 SecondValue 參數,因此不應指定此參數。新增此類型的成員時,請勿指定 SecondValue 參數。 + + + 類型為 "{0}" 的成員需要 Value 參數。新增此類型的成員時,請指定 Value 參數。 + + + 類型為 "{0}" 的成員,其 Value 和 SecondValue 參數不應同時為 null。請為這兩個參數的其中一個指定非 null 值。 + + + 無法新增名稱為 "{0}" 的成員,因為已存在同名的成員。若仍要覆寫此成員,請將 Force 參數新增至您的命令。 + + + 無法強制新增名稱為 "{0}" 且類型為 "{1}" 的成員。已存在名稱與類型相同的成員,而且現有成員不是執行個體延伸。 + + + 此別名所參照的成員不應為 null 或空白。 + + + 類型為 "{0}" 的成員,其 Value 參數不應為 null。新增此類型的成員時,請為 Value 參數指定非 null 值。 + + + 類型為 "{0}" 的成員,其 SecondValue 參數不應為 null。新增此類型的成員時,請為 SecondValue 參數指定非 null 值。 + + + NotePropertyName 參數無法接受可轉換為類型 {0} 的值。若要使用這些值定義成員的名稱,請使用 Add-Member,並指定成員類型。 + + + NoteProperty 成員的名稱不應為 null 或空字串。 + + + TypeName 參數不應為 null、空白,或只包含空白字元。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AddTypeStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AddTypeStrings.zh-Hant.resx new file mode 100644 index 00000000000..626eb4d1332 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AddTypeStrings.zh-Hant.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 + + + 原始程式碼已經編譯並載入。 + + + 無法新增類型。不支援 "{0}" 副檔名。 + + + 無法新增類型。輸入檔案必須具有相同的副檔名。 + + + 無法新增類型。找不到組件 '{0}'。 + + + 無法新增類型。類型名稱 '{0}' 已存在。 + + + 無法設定輸出組件。路徑 {0} 無法解析為單一檔案。 + + + 無法新增類型。發生編譯錯誤。 + + + 無法新增類型。OutputType 參數需要指定 OutputAssembly 參數。 + + + 無法新增類型。此語言模式不支援定義新類型。 + + + 不需要指定的參考組件 '{0}',因此已忽略。 + + + 目前不支援 'ConsoleApplication' 和 'WindowsApplication' 這兩種組件類型。 + + + Add-Type Cmdlet + + + ConstrainedLanguage 模式不允許使用 Add-Type Cmdlet。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AliasCommandStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AliasCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..abb7afc3de7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/AliasCommandStrings.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertFromStringData.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertFromStringData.zh-Hant.resx new file mode 100644 index 00000000000..75e43519082 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertFromStringData.zh-Hant.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 + + + 資料行 '{0}' 不是 'name=value' 格式。 + + + 行 '{0}' 中的資料項目 '{1}' 已經定義。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertHTMLStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertHTMLStrings.zh-Hant.resx new file mode 100644 index 00000000000..865447e08b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertHTMLStrings.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertMarkdownStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertMarkdownStrings.zh-Hant.resx new file mode 100644 index 00000000000..ba58f067550 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ConvertMarkdownStrings.zh-Hant.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 + + + 輸入物件 '{0}' 的類型無效。 + + + 僅支援 FileSystem 提供者路徑。不支援檔案路徑: '{0}'。 + + + 指定物件的屬性 {0} 為 null 或空字串。 + + + 無效的參數集名稱: {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/CsvCommandStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/CsvCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..20c7a456c17 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/CsvCommandStrings.zh-Hant.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 + + + 無法將 CSV 內容附加至下列檔案: {1}。附加物件的屬性未對應下列資料行: {0}。若要繼續使用不相符的屬性,請新增 -Force 參數,然後重新執行命令。 + {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. + + + + 您必須指定 -UseQuotes 或 -QuoteFields 參數,但不能同時指定兩者。 + + + 您必須指定 -Path 或 -LiteralPath 參數,但不能同時指定兩者。 + + + 未指定一或多個標頭。已使用以 "H" 開頭的預設名稱取代任何遺漏的標頭。 + + + FileName 是必要參數。 + + + 只有在附加時,才應呼叫 ReconcilePreexistingPropertyNames 方法。 + + + 只有在成功讀取現有屬性名稱後,才應呼叫 ReconcilePreexistingPropertyNames 方法。 + + + 每個 Cmdlet 執行個體只能呼叫一次 BuildPropertyNames 方法。 + + + 類型階層不應有 null 值。 + + + 已達到檔案結尾。 + + + 您必須指定 -Append 或 -NoHeader 參數,但不能同時指定兩者。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/Debugger.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/Debugger.zh-Hant.resx new file mode 100644 index 00000000000..75884ad9a06 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/Debugger.zh-Hant.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}'. + + + 檔案 '{0}' 不存在。 + + + 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}'. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/EventingStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/EventingStrings.zh-Hant.resx new file mode 100644 index 00000000000..b4803546537 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/EventingStrings.zh-Hant.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 + + + 來源識別碼為 '{0}' 的事件不存在。 + + + 識別碼為 '{0}' 的事件不存在。 + + + 來源識別碼為 '{0}' 的事件訂閱不存在。 + + + 識別碼為 '{0}' 的事件訂閱不存在。 + + + 事件訂閱 '{0}' + + + 事件 '{0}' + + + 您必須為非轉送事件指定動作。 + + + 取消訂閱 + + + 移除 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/FormatAndOut_out_gridview.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/FormatAndOut_out_gridview.zh-Hant.resx new file mode 100644 index 00000000000..99088c3cf01 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/FormatAndOut_out_gridview.zh-Hant.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 + + + Out-GridView 不支援此資料格式。 + + + 在執行一或多個 PowerShell 工作階段時安裝了 Microsoft .NET Framework 4.5。若要使用 {0} Cmdlet,請關閉所有 PowerShell 視窗,然後開啟新的 PowerShell 視窗。 + + + 類型 + + + + + + 索引 + + + 找不到名為 '{0}' 的命令。 + + + 找到多個名為 '{0}' 的命令。在沒有參數的情況下啟動 '{1}',然後輸入 '{0}' 以篩選結果。 + + + 無法寫入至主控台輸入緩衝區。 + + + {0} 應小於 {1}。 + {0} is the property "Height" +{1} is the maximum allowed value for the height property. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetFormatDataStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetFormatDataStrings.zh-Hant.resx new file mode 100644 index 00000000000..f20b16fad40 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetFormatDataStrings.zh-Hant.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 + + + 正在處理檢視定義 '{0}' + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetMember.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetMember.zh-Hant.resx new file mode 100644 index 00000000000..5ad7b93b9c4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetMember.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetRandomCommandStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetRandomCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..58808001dce --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetRandomCommandStrings.zh-Hant.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' 必須大於零。 + + + Minimum 值 ({0}) 不能大於或等於 Maximum 值 ({1})。 + + + 'minValue' 不可大於 maxValue。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetUptimeStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetUptimeStrings.zh-Hant.resx new file mode 100644 index 00000000000..a9d0be9630e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/GetUptimeStrings.zh-Hant.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)." + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/HostStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/HostStrings.zh-Hant.resx new file mode 100644 index 00000000000..89b67347463 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/HostStrings.zh-Hant.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 + + + 無法處理色彩,因為 {0} 不是有效的色彩。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/HttpCommandStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/HttpCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..68a7fe3f0f7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/HttpCommandStrings.zh-Hant.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 + + + 無法完成此命令,因為發生下列錯誤: '{0}'。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ImplicitRemotingStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ImplicitRemotingStrings.zh-Hant.resx new file mode 100644 index 00000000000..77d47e6e98b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ImplicitRemotingStrings.zh-Hant.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 + + + 遠端 {0} 命令傳回的資料不是預期的格式。 + + + {0} Cmdlet 要求遠端工作階段中必須有下列命令: Get-Command、Get-FormatData 和 Select-Object。下列命令會使用,但為選用: Get-Help 和 Measure-Object。請確認遠端工作階段包含必要的命令,然後再試一次。 + + + 在遠端工作階段中執行 {0} 命令時回報下列錯誤: {1}。 + + + 在遠端工作階段中執行 {0} 命令未傳回任何結果。 + + + 沒有任何工作階段與此隱含式遠端處理模組相關聯。 + + + 無法解析遠端別名 '{0}'。 + + + 已跳過為 '{0}' 命令建立 Proxy,因為名稱與 Name 參數的值不相符。 + + + 已跳過 '{0}' 類型的延伸類型定義,因為其名稱與 FormatTypeName 參數的值不相符。 + + + 已跳過為命令 '{0}' 建立 Proxy,因為 PowerShell 無法確認命令名稱是否安全。 + + + 已跳過為下列命令建立 Proxy: '{0}',因為它會陰影現有的本機命令。 若要陰影現有的本機命令,請使用 AllowClobber 參數。 + + + 尚未建立任何命令 Proxy,因為所有要求的遠端命令都會陰影現有的本機命令。 若要陰影現有的本機命令,請使用 AllowClobber 參數。 + + + {0} 的隱含式遠端處理 + + + 隱含式遠端處理事件 (工作階段識別碼: {0}; 事件處理常式識別碼: {1}) + + + 隱含式遠端處理模組 + + + 產生於 {0} + + + 由 {0} Cmdlet + + + 已使用下列命令列叫用: {0} + + + 可用來指定此 Proxy 模組運作所在工作階段的選擇性參數 + + + 正在為 "{{0}}" 命令建立新的隱含式遠端處理工作階段... + + + 位於 {{0}} 的隱含式遠端處理模組工作階段 + + + 正在建立隱含式遠端處理模組 ... + + + 正在從遠端工作階段取得命令資訊 ... + + + 正在從遠端工作階段取得命令資訊 ... 已收到 {0} 個命令 + + + 正在從遠端工作階段取得格式化和輸出資訊 ... + + + 正在從遠端工作階段取得格式化和輸出資訊 ... 已收到 {0} 個物件 + + + 已完成。 + + + PowerShell 認證要求 + + + 請輸入 {0} 的認證。 + + + 請輸入下列連線所使用的 HTTP Proxy 認證: {0} + + + 新遠端工作階段中可用的命令與建立隱含式遠端處理模組時可用的命令不同。 請考慮使用 Export-PSSession Cmdlet 重新建立模組。 + + + 無法載入檔案,因為此系統已停用指令碼執行。請提供可用來簽署檔案的有效憑證。 + + + 無法簽署檔案 {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ImportLocalizedDataStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ImportLocalizedDataStrings.zh-Hant.resx new file mode 100644 index 00000000000..2ba0c835eb5 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/ImportLocalizedDataStrings.zh-Hant.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 + + + 找不到資料檔案 '{0}'。 + + + 未指定 FileName 參數。當未從指令碼檔呼叫 Import-LocalizedData 時,必須指定 FileName 參數。 + + + PowerShell 開啟資料檔案 '{0}' 時,發生下列錯誤: +{1}。 + + + PowerShell 載入 '{0}' 指令碼資料檔案時,發生下列錯誤: +{1}。 + + + FileName 參數的引數不應包含路徑。 + + + 在目錄 '{0}' 或任何上層文化目錄中,都找不到 PowerShell 資料檔案 '{1}'。 + + + 無法匯入當地語系化資料。此語言模式不允許定義額外支援的命令。 + + + BindingVariable 名稱 '{0}' 無效。 + + + Import-LocalizedData Cmdlet + + + 在 ConstrainedLanguage 模式中,不允許使用 SupportedCommand 參數新增其他支援的命令。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/MatchStringStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/MatchStringStrings.zh-Hant.resx new file mode 100644 index 00000000000..bc7da6005b7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/MatchStringStrings.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/MeasureObjectStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/MeasureObjectStrings.zh-Hant.resx new file mode 100644 index 00000000000..fbfdc4a21f2 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/MeasureObjectStrings.zh-Hant.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 + + + 在任何物件的輸入中,都找不到屬性 "{0}"。 + + + 輸入物件 "{0}" 不是數值。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/NewObjectStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/NewObjectStrings.zh-Hant.resx new file mode 100644 index 00000000000..4d5839056f7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/NewObjectStrings.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/OutPrinterDisplayStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/OutPrinterDisplayStrings.zh-Hant.resx new file mode 100644 index 00000000000..06b5ab3d4b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/OutPrinterDisplayStrings.zh-Hant.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"} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SelectObjectStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SelectObjectStrings.zh-Hant.resx new file mode 100644 index 00000000000..dc653ffa4d7 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SelectObjectStrings.zh-Hant.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 + + + 無法重新命名多個結果。 + + + 找不到屬性 "{0}"。 + + + 無法展開多個屬性。 + + + 無法處理屬性,因為屬性 "{0}" 已經存在。 + + + 屬性是空的指令碼區塊,且未提供名稱。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SendMailMessageStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SendMailMessageStrings.zh-Hant.resx new file mode 100644 index 00000000000..d6bfa0981df --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SendMailMessageStrings.zh-Hant.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 + + + 無法傳送電子郵件,因為未指定 SMTP 伺服器。您必須使用 SmtpServer 參數或 $PSEmailServer 變數來指定 SMTP 伺服器。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SortObjectStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SortObjectStrings.zh-Hant.resx new file mode 100644 index 00000000000..2318cabc6f4 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/SortObjectStrings.zh-Hant.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" - 無法在 "InputObject" 中找到 "{0}"。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/StartSleepStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/StartSleepStrings.zh-Hant.resx new file mode 100644 index 00000000000..8744584e66f --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/StartSleepStrings.zh-Hant.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 + + + '-Duration' 參數值不得超過 '{0}',您提供的值為 '{1}'。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/TestJsonCmdletStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/TestJsonCmdletStrings.zh-Hant.resx new file mode 100644 index 00000000000..d39c2bcae1a --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/TestJsonCmdletStrings.zh-Hant.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 + + + 無法剖析 JSON 結構描述。 + + + 無法剖析 JSON。 + + + JSON 對位於 '{1}' 的結構描述 {0} 無效 + + + 無法開啟 JSON 結構描述檔案: {0} + + + 不支援 URI 配置 '{0}'。只允許 HTTP(S) 和本機檔案系統 URI。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/TraceCommandStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/TraceCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..e771733c140 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/TraceCommandStrings.zh-Hant.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 + + + 追蹤輸出只能寫入檔案系統。路徑 '{0}' 參照 '{1}' 提供者路徑。 + + + 追蹤輸出只能寫入單一系統。路徑 '{0}' 解析成多個檔案。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UnblockFileStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UnblockFileStrings.zh-Hant.resx new file mode 100644 index 00000000000..7b6946f5d62 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UnblockFileStrings.zh-Hant.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 + + + 此 Cmdlet 不支援 Linux。 + + + 解除封鎖 {0} 時發生錯誤。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UpdateDataStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UpdateDataStrings.zh-Hant.resx new file mode 100644 index 00000000000..94dc041be87 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UpdateDataStrings.zh-Hant.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 + + + 無法開啟檔案,因為目前的提供者是 "{0}",而此命令需要檔案。 + + + 無法讀取檔案 "{0}",因為它沒有副檔名 "{1}"。 + + + 更新 TypeData + + + 更新 FormatData + + + FileName: {0} + + + 無法使用類型 "{0}" 更新成員。請為 MemberTypes 參數指定不同的類型。 + + + 類型 "{1}" 需要 {0} 參數。請指定 {0} 參數。 + + + 對於類型 "{1}" 的成員,{0} 參數不應為 null 或空字串。更新此成員類型時,請為 {0} 參數指定非 null 值。 + + + 類型 "{1}" 的成員不需要 {0} 參數,因此不應指定此參數。更新此成員類型時,請勿指定 {0} 參數。 + + + 未為類型 "{0}" 的更新指定成員。 + + + 目標類型名稱不應為 null、空白,或只包含空白字元。 + + + 類型為 "{0}" 的成員,其 Value 和 SecondValue 參數不應同時為 null。請為這兩個參數的其中一個指定非 null 值。 + + + 只能指定一種成員類型。指定的成員類型為: "{0}"。請只使用一種成員類型更新此類型。 + + + 若未指定 MemberType 參數,則無法指定 MemberName、Value 及 SecondValue 參數。 + + + 移除 TypeData + + + 將移除的類型名稱: {0} + + + 要更新的類型: {0} + + + 移除類型檔案 + + + 檔案 {0} 未匯入目前的工作階段。 + + + 此 Runspace 不允許更新格式資料。建立 Runspace 時,已將 'DisableFormatUpdates' 屬性設為 True。 + + + 無法使用 FormatTable 執行個體更新格式資料。 + + + 無法使用 TypeTable 執行個體更新類型資料。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UpdateListStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UpdateListStrings.zh-Hant.resx new file mode 100644 index 00000000000..6984c4fbfb3 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UpdateListStrings.zh-Hant.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}' + + + 當您指定 InputObject 參數時,必須指定 Property 參數。 + + + 當您指定 Property 參數時,必須指定 InputObject 參數。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UtilityCommonStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UtilityCommonStrings.zh-Hant.resx new file mode 100644 index 00000000000..ca8fe0ee44b --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/UtilityCommonStrings.zh-Hant.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} 有一或多個無效的例外狀況。 + + + 無法執行此命令,因為檔案路徑 '{0}' 無效。請提供有效的檔案路徑,然後執行命令。 + + + 無法執行此命令,因為 '{0}' 是空的或空白。請指定 CSSUri,然後執行命令。 + + + 無法開啟檔案,因為目前的提供者 ({0}) 無法開啟檔案。 + + + 無法執行此命令,因為 Namespace 參數中的前置詞值為 null。請為前置詞提供有效值,然後再次執行命令。 + + + 無法展開依此屬性分組的物件,因為索引鍵重複。請為此屬性提供有效值,然後再試一次。 + + + 此作業系統不支援這個命令。 + + + 無法讀取檔案 '{0}': {1} + + + 無法將類型為 '{0}' 的輸入轉換為十六進位。若要檢視其字串表示的十六進位格式,請先將它傳送至 Out-String Cmdlet,再傳送至 Format-Hex。 + + + 不支援指定的路徑 '{0}'。此命令僅支援 FileSystem 提供者路徑。 + + + 路徑: + + + 無法執行命令,因為 AsString 參數需要您指定 AsHashtable 參數。 + + + 無法執行命令,因為當 AsHashTable 參數搭配一個以上的屬性使用時,必須同時加入 AsString 參數。 + + + 找不到路徑 '{0}',因為它不存在。 + + + 無法使用標記 '{0}'。'PS' 前置詞是保留的。 + + + 無法將檔案 '{0}' 剖析為 PowerShell 資料檔案。 + + + 無法從指定的 SDDL 建構安全性描述元,因為發生下列錯誤: {0} + + + Invoke-Expression Cmdlet + + + Invoke-Expression Cmdlet 指令碼區塊將會以 ConstrainedLanguage 模式執行。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/VariableCommandStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/VariableCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..b422ea58e25 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/VariableCommandStrings.zh-Hant.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 + + + 設定變數 + + + 名稱: {0},值: {1} + + + 使用單一變數,而非集合 + + + 新增變數 + + + 名稱: {0},值: {1} + + + 移除變數 + + + 名稱: {0} + + + 清除變數 + + + 名稱: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WebCmdletStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WebCmdletStrings.zh-Hant.resx new file mode 100644 index 00000000000..80f45281c7e --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WebCmdletStrings.zh-Hant.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 + + + 存取路徑 '{0}' 遭拒。 + + + 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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WriteErrorStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WriteErrorStrings.zh-Hant.resx new file mode 100644 index 00000000000..22a84dd8eec --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WriteErrorStrings.zh-Hant.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 + + + 「Write-Error Cmdlet 已報告一個錯誤。」 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WriteProgressResourceStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WriteProgressResourceStrings.zh-Hant.resx new file mode 100644 index 00000000000..291b2f4df66 --- /dev/null +++ b/src/Microsoft.PowerShell.Commands.Utility/resources/zh-Hant/WriteProgressResourceStrings.zh-Hant.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 + + + 描述正在報告進度之活動的文字。 + + + 描述目前正在報告進度之活動目前狀態的文字。 + + + 正在處理 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs b/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs deleted file mode 100644 index 1c29b44c603..00000000000 --- a/src/Microsoft.PowerShell.Commands.Utility/singleshell/installer/MshUtilityMshSnapin.cs +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.ComponentModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell -{ - /// - /// MshUtilityMshSnapin (or MshUtilityMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad utility mshsnapin. - /// - /// This class will be built with monad utility dll. - /// - [RunInstaller(true)] - public sealed class PSUtilityPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSUtilityPSSnapIn() - : base() - { - } - - /// - /// Get name of this mshsnapin. - /// - public override string Name - { - get - { - return RegistryStrings.UtilityMshSnapinName; - } - } - - /// - /// Get the default vendor string for this mshsnapin. - /// - 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 mshsnapin. - /// - 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/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj b/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj index bbc8023b1da..ddb794bd1d2 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj +++ b/src/Microsoft.PowerShell.ConsoleHost/Microsoft.PowerShell.ConsoleHost.csproj @@ -10,20 +10,13 @@ - - $(DefineConstants);CORECLR - - - - - - - + + $(RootNamespace).resources.%(Filename) + - diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs index f5903ded5bc..8cc6bd8ab02 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/ComInterfaces.cs @@ -20,20 +20,20 @@ internal static class ComInterfaces [StructLayout(LayoutKind.Sequential)] internal readonly struct StartUpInfo { - public readonly UInt32 cb; + public readonly uint cb; private readonly IntPtr lpReserved; public readonly IntPtr lpDesktop; public readonly IntPtr lpTitle; - public readonly UInt32 dwX; - public readonly UInt32 dwY; - public readonly UInt32 dwXSize; - public readonly UInt32 dwYSize; - public readonly UInt32 dwXCountChars; - public readonly UInt32 dwYCountChars; - public readonly UInt32 dwFillAttribute; - public readonly UInt32 dwFlags; - public readonly UInt16 wShowWindow; - private readonly UInt16 cbReserved2; + 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; @@ -160,7 +160,7 @@ internal interface IPropertyStore HResult Commit(); } - [ComImport()] + [ComImport] [Guid("6332DEBF-87B5-4670-90C0-5E57B408A49E")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface ICustomDestinationList @@ -204,7 +204,7 @@ internal enum KnownDestinationCategory Recent } - [ComImport()] + [ComImport] [Guid("92CA9DCD-5622-4BBA-A805-5E9F541BD8C9")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] internal interface IObjectArray @@ -217,7 +217,7 @@ void GetAt( [Out(), MarshalAs(UnmanagedType.Interface)] out object ppvObject); } - [ComImport()] + [ComImport] [Guid("5632B1A4-E38A-400A-928A-D4CD63230295")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] internal interface IObjectCollection @@ -248,13 +248,13 @@ void AddFromArray( internal interface IShellLinkDataListW { [PreserveSig] - Int32 AddDataBlock(IntPtr pDataBlock); + int AddDataBlock(IntPtr pDataBlock); [PreserveSig] - Int32 CopyDataBlock(UInt32 dwSig, out IntPtr ppDataBlock); + int CopyDataBlock(uint dwSig, out IntPtr ppDataBlock); [PreserveSig] - Int32 RemoveDataBlock(UInt32 dwSig); + int RemoveDataBlock(uint dwSig); void GetFlags(out uint pdwFlags); diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs index e23f0810ea1..4789bcef06f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/HResult.cs @@ -4,18 +4,18 @@ namespace Microsoft.PowerShell { /// - /// HRESULT Wrapper - /// + /// HRESULT Wrapper + /// internal enum HResult { - /// - /// S_OK - /// + /// + /// S_OK + /// Ok = 0x0000, /// /// S_FALSE. - /// + /// False = 0x0001, /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs index 10db7912b4a..408c59c482a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropVariant.cs @@ -34,9 +34,7 @@ internal PropVariant(string value) throw new ArgumentException("PropVariantNullString", nameof(value)); } -#pragma warning disable CS0618 // Type or member is obsolete (might get deprecated in future versions _valueType = (ushort)VarEnum.VT_LPWSTR; -#pragma warning restore CS0618 // Type or member is obsolete (might get deprecated in future versions _ptr = Marshal.StringToCoTaskMemUni(value); } diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs index ecd1918492b..93346424dc5 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/PropertyKey.cs @@ -21,7 +21,7 @@ namespace Microsoft.PowerShell /// /// Property identifier (PID) /// - public Int32 PropertyId { get; } + public int PropertyId { get; } #endregion @@ -32,7 +32,7 @@ namespace Microsoft.PowerShell /// /// A unique GUID for the property. /// Property identifier (PID). - internal PropertyKey(Guid formatId, Int32 propertyId) + internal PropertyKey(Guid formatId, int propertyId) { this.FormatId = formatId; this.PropertyId = propertyId; diff --git a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs index 90c6c811bb1..5606eabd567 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/WindowsTaskbarJumpList/TaskbarJumpList.cs @@ -33,13 +33,12 @@ internal static void CreateRunAsAdministratorJumpList() { try { - TaskbarJumpList.CreateElevatedEntry(ConsoleHostStrings.RunAsAdministrator); + CreateElevatedEntry(ConsoleHostStrings.RunAsAdministrator); } - catch (Exception exception) + 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. - Debug.Fail($"Creating 'Run as Administrator' JumpList failed. {exception}"); } }); @@ -48,7 +47,7 @@ internal static void CreateRunAsAdministratorJumpList() thread.SetApartmentState(ApartmentState.STA); thread.Start(); } - catch (System.Threading.ThreadStartException) + catch (ThreadStartException) { // STA may not be supported on some platforms } @@ -117,7 +116,6 @@ private static void CreateElevatedEntry(string title) 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; - var ComSvrInterface_GUID = new Guid(@"555E2D2B-EE00-47AA-AB2B-39F953F6B339"); hResult = CoCreateInstance(ref CLSID_EnumerableObjectCollection, null, CLSCTX_INPROC, ref IID_IUnknown, out object instance); if (hResult < 0) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs index ad809b70982..0546dc527ee 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/CommandLineParameterParser.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. - #nullable enable using System; @@ -15,6 +14,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Security; using System.Text; @@ -175,6 +175,7 @@ internal static int MaxNameLength() "sta", "mta", "command", + "commandwithargs", "configurationname", "custompipename", "encodedcommand", @@ -187,6 +188,7 @@ internal static int MaxNameLength() "nologo", "noninteractive", "noprofile", + "noprofileloadtime", "outputformat", "removeworkingdirectorytrailingcharacter", "settingsfile", @@ -195,6 +197,66 @@ internal static int MaxNameLength() "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() { @@ -320,6 +382,15 @@ internal Collection Args } } + internal string? ConfigurationFile + { + get + { + AssertArgumentsParsed(); + return _configurationFile; + } + } + internal string? ConfigurationName { get @@ -403,6 +474,15 @@ internal bool ShowExtendedHelp } } + internal bool NoProfileLoadTime + { + get + { + AssertArgumentsParsed(); + return _noProfileLoadTime; + } + } + internal bool ShowVersion { get @@ -477,7 +557,7 @@ internal bool StaMode } else { - return true; + return Platform.IsStaSupported; } } } @@ -524,6 +604,33 @@ internal bool RemoveWorkingDirectoryTrailingCharacter 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 @@ -608,7 +715,8 @@ internal static string GetConfigurationNameFromGroupPolicy() return (switchKey: string.Empty, shouldBreak: false); } - if (!CharExtensions.IsDash(switchKey[0]) && switchKey[0] != '/') + char firstChar = switchKey[0]; + if (!CharExtensions.IsDash(firstChar) && firstChar != '/') { // then it's a file --argIndex; @@ -622,7 +730,7 @@ internal static string GetConfigurationNameFromGroupPolicy() switchKey = switchKey.Substring(1); // chop off the second dash so we're agnostic wrt specifying - or -- - if (!string.IsNullOrEmpty(switchKey) && CharExtensions.IsDash(switchKey[0])) + if (!string.IsNullOrEmpty(switchKey) && CharExtensions.IsDash(firstChar) && switchKey[0] == firstChar) { switchKey = switchKey.Substring(1); } @@ -640,6 +748,53 @@ internal static string NormalizeFilePath(string path) 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"); @@ -689,7 +844,6 @@ private void DisplayBanner(PSHostUserInterface hostUI, string? bannerText) if (!string.IsNullOrEmpty(bannerText)) { hostUI.WriteLine(bannerText); - hostUI.WriteLine(); } if (UpdatesNotification.CanNotifyUpdates) @@ -715,10 +869,7 @@ internal void Parse(string[] args) for (int i = 0; i < args.Length; i++) { - if (args[i] is null) - { - throw new ArgumentNullException(nameof(args), CommandLineParameterParserStrings.NullElementInArgs); - } + 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 @@ -728,10 +879,27 @@ internal void Parse(string[] args) ParseHelper(args); } + internal static bool IsFileOnlyEntryEnabled + { + get + { +#if UNIX + return false; +#else + return SystemPolicy.IsFileOnlyEntryEnabled(); +#endif + } + } + private void ParseHelper(string[] args) { if (args.Length == 0) { + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryRequired); + } + return; } @@ -755,6 +923,7 @@ private void ParseHelper(string[] args) _noInteractive = true; _skipUserInit = true; _noExit = false; + ParametersUsed |= ParameterBitmap.Version; break; } @@ -763,48 +932,120 @@ private void ParseHelper(string[] args) _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; + + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryNoExitDisabled); + break; + } } 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 (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryServerMode); + break; + } } +#if !UNIX + else if (MatchSwitch(switchKey, "v2socketservermode", "v2so")) + { + _v2SocketServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.V2SocketServerMode; + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryServerMode); + break; + } + } +#endif else if (MatchSwitch(switchKey, "servermode", "s")) { _serverMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.ServerMode; + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryServerMode); + break; + } } else if (MatchSwitch(switchKey, "namedpipeservermode", "nam")) { _namedPipeServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.NamedPipeServerMode; + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryServerMode); + break; + } } else if (MatchSwitch(switchKey, "sshservermode", "sshs")) { _sshServerMode = true; + _showBanner = false; + ParametersUsed |= ParameterBitmap.SSHServerMode; + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryServerMode); + break; + } + } + 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")) { @@ -817,6 +1058,7 @@ private void ParseHelper(string[] args) } _configurationName = args[i]; + ParametersUsed |= ParameterBitmap.ConfigurationName; } else if (MatchSwitch(switchKey, "custompipename", "cus")) { @@ -841,7 +1083,22 @@ private void ParseHelper(string[] args) 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")) { @@ -849,6 +1106,8 @@ private void ParseHelper(string[] args) { break; } + + ParametersUsed |= ParameterBitmap.Command; } else if (MatchSwitch(switchKey, "windowstyle", "w")) { @@ -875,6 +1134,8 @@ private void ParseHelper(string[] args) string.Format(CultureInfo.CurrentCulture, CommandLineParameterParserStrings.InvalidWindowStyleArgument, args[i], e.Message)); break; } + + ParametersUsed |= ParameterBitmap.WindowStyle; #endif } else if (MatchSwitch(switchKey, "file", "f")) @@ -883,6 +1144,8 @@ private void ParseHelper(string[] args) { break; } + + ParametersUsed |= ParameterBitmap.File; } #if DEBUG else if (MatchSwitch(switchKey, "isswait", "isswait")) @@ -894,14 +1157,27 @@ private void ParseHelper(string[] args) { 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")) { @@ -910,6 +1186,8 @@ private void ParseHelper(string[] args) { break; } + + ParametersUsed |= ParameterBitmap.EncodedCommand; } else if (MatchSwitch(switchKey, "encodedarguments", "encodeda") || MatchSwitch(switchKey, "ea", "ea")) { @@ -917,6 +1195,8 @@ private void ParseHelper(string[] args) { break; } + + ParametersUsed |= ParameterBitmap.EncodedArgument; } else if (MatchSwitch(switchKey, "settingsfile", "settings")) { @@ -925,10 +1205,12 @@ private void ParseHelper(string[] args) { break; } + + ParametersUsed |= ParameterBitmap.SettingsFile; } else if (MatchSwitch(switchKey, "sta", "sta")) { - if (!Platform.IsWindowsDesktop) + if (!Platform.IsWindowsDesktop || !Platform.IsStaSupported) { SetCommandLineError( CommandLineParameterParserStrings.STANotImplemented); @@ -944,6 +1226,7 @@ private void ParseHelper(string[] args) } _staMode = true; + ParametersUsed |= ParameterBitmap.STA; } else if (MatchSwitch(switchKey, "mta", "mta")) { @@ -963,6 +1246,7 @@ private void ParseHelper(string[] args) } _staMode = false; + ParametersUsed |= ParameterBitmap.MTA; } else if (MatchSwitch(switchKey, "workingdirectory", "wo") || MatchSwitch(switchKey, "wd", "wd")) { @@ -975,12 +1259,44 @@ private void ParseHelper(string[] args) } _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 { @@ -990,9 +1306,21 @@ private void ParseHelper(string[] args) { break; } + + // default to filename being the next argument. + ParametersUsed |= ParameterBitmap.File; } } + if (_error is null + && !_showVersion + && !_showHelp + && !ParametersUsed.HasFlag(ParameterBitmap.File) + && IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryRequired); + } + Dbg.Assert( ((_exitCode == ConsoleHost.ExitCodeBadCommandLineParameter) && _abortStartup) || (_exitCode == ConsoleHost.ExitCodeSuccess), @@ -1023,7 +1351,7 @@ private void SetCommandLineError(string msg, bool showHelp = false, bool showBan private void ParseFormat(string[] args, ref int i, ref Serialization.DataFormat format, string resourceStr) { StringBuilder sb = new StringBuilder(); - foreach (string s in Enum.GetNames(typeof(Serialization.DataFormat))) + foreach (string s in Enum.GetNames()) { sb.Append(s); sb.Append(Environment.NewLine); @@ -1073,15 +1401,6 @@ private void ParseExecutionPolicy(string[] args, ref int i, ref string? executio // treat -command as an argument to the script... private bool ParseFile(string[] args, ref int i, bool noexitSeen) { - // 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; - } - ++i; if (i >= args.Length) { @@ -1099,6 +1418,12 @@ static object ConvertToBoolIfPossible(string arg) // Process interactive input... if (args[i] == "-") { + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryRequired); + return false; + } + // the arg to -file is -, which is secret code for "read the commands from stdin with prompts" _explicitReadCommandsFromStdin = true; @@ -1158,58 +1483,85 @@ static object ConvertToBoolIfPossible(string arg) 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++; - string? pendingParameter = null; + CollectPSArgs(args, ref i); + } - // Accumulate the arguments to this script... - while (i < args.Length) - { - string arg = args[i]; + return true; + } - // 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) + 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) { - int offset = arg.IndexOf(':'); - if (offset >= 0) + if (offset == arg.Length - 1) { - 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))); - } + pendingParameter = arg.TrimEnd(':'); } else { - _collectedArgs.Add(new CommandParameter(arg)); + string argValue = arg.Substring(offset + 1); + string argName = arg.Substring(0, offset); + _collectedArgs.Add(new CommandParameter(argName, ConvertToBoolIfPossible(argValue))); } } else { - _collectedArgs.Add(new CommandParameter(null, arg)); + _collectedArgs.Add(new CommandParameter(arg)); } - - ++i; } - } + else + { + _collectedArgs.Add(new CommandParameter(null, arg)); + } - return true; + ++i; + } } private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEncoded) { + if (IsFileOnlyEntryEnabled) + { + SetCommandLineError(CommandLineParameterParserStrings.FileOnlyEntryRequired); + return false; + } + if (_commandLineCommand != null) { // we've already set the command, so squawk @@ -1261,23 +1613,15 @@ private bool ParseCommand(string[] args, ref int i, bool noexitSeen, bool isEnco } else { - // Collect the remaining parameters and combine them into a single command to be run. - - StringBuilder cmdLineCmdSB = new StringBuilder(); - - while (i < args.Length) + if (_commandHasArgs) { - cmdLineCmdSB.Append(args[i] + " "); - ++i; + _commandLineCommand = args[i]; } - - if (cmdLineCmdSB.Length > 0) + else { - // remove the last blank - cmdLineCmdSB.Remove(cmdLineCmdSB.Length - 1, 1); + _commandLineCommand = string.Join(' ', args, i, args.Length - i); + i = args.Length; } - - _commandLineCommand = cmdLineCmdSB.ToString(); } if (!noexitSeen && !_explicitReadCommandsFromStdin) @@ -1328,10 +1672,15 @@ private bool CollectArgs(string[] args, ref int i) } 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; @@ -1347,6 +1696,7 @@ private bool CollectArgs(string[] args, ref int i) 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; @@ -1357,6 +1707,10 @@ private bool CollectArgs(string[] args, ref int i) private string? _executionPolicy; private string? _settingsFile; private string? _workingDirectory; +#if !UNIX + private string? _token; + private DateTimeOffset? _utcTimestamp; +#endif #if !UNIX private ProcessWindowStyle? _windowStyle; diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs index a157964c637..7bda4bc5688 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleControl.cs @@ -10,9 +10,9 @@ // 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. -#pragma warning disable 1634, 1691 using System; +using System.Buffers; using System.Text; using System.Runtime.InteropServices; using System.Management.Automation; @@ -109,7 +109,7 @@ internal struct COORD public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", X, Y); + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); } } @@ -161,7 +161,7 @@ internal struct SMALL_RECT public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", Left, Top, Right, Bottom); + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}"); } } @@ -192,7 +192,7 @@ internal struct CONSOLE_CURSOR_INFO public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "Size: {0}, Visible: {1}", Size, Visible); + return string.Create(CultureInfo.InvariantCulture, $"Size: {Size}, Visible: {Visible}"); } } @@ -211,41 +211,6 @@ internal struct FONTSIGNATURE internal DWORD fsCsb1; } - [StructLayout(LayoutKind.Sequential)] - internal struct CHARSETINFO - { - // From public\sdk\inc\wingdi.h - internal uint ciCharset; // Character set value. - internal uint ciACP; // ANSI code-page identifier. - internal FONTSIGNATURE fs; - } - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct TEXTMETRIC - { - // From public\sdk\inc\wingdi.h - public int tmHeight; - public int tmAscent; - public int tmDescent; - public int tmInternalLeading; - public int tmExternalLeading; - public int tmAveCharWidth; - public int tmMaxCharWidth; - public int tmWeight; - public int tmOverhang; - public int tmDigitizedAspectX; - public int tmDigitizedAspectY; - public char tmFirstChar; - public char tmLastChar; - public char tmDefaultChar; - public char tmBreakChar; - public byte tmItalic; - public byte tmUnderlined; - public byte tmStruckOut; - public byte tmPitchAndFamily; - public byte tmCharSet; - } - #region SentInput Data Structures [StructLayout(LayoutKind.Sequential)] @@ -275,13 +240,13 @@ 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 Int32 X; + 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 Int32 Y; + 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; @@ -450,7 +415,7 @@ internal enum KeyboardFlag : uint /// True if it was successful. [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow); + internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); internal static void SetConsoleMode(ProcessWindowStyle style) { @@ -1249,8 +1214,7 @@ internal static void CheckWriteEdges( { if (firstLeftTrailingRow >= 0) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - firstLeftTrailingRow, contentsRegion.Left)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstLeftTrailingRow}, {contentsRegion.Left}]")); } } else @@ -1265,8 +1229,7 @@ internal static void CheckWriteEdges( if (leftExisting[r, 0].BufferCellType == BufferCellType.Leading ^ contents[r, contentsRegion.Left].BufferCellType == BufferCellType.Trailing) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - r, contentsRegion.Left)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Left}]")); } } } @@ -1275,8 +1238,7 @@ internal static void CheckWriteEdges( { if (firstRightLeadingRow >= 0) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - firstRightLeadingRow, contentsRegion.Right)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{firstRightLeadingRow}, {contentsRegion.Right}]")); } } else @@ -1291,8 +1253,7 @@ internal static void CheckWriteEdges( if (rightExisting[r, 0].BufferCellType == BufferCellType.Leading ^ contents[r, contentsRegion.Right].BufferCellType == BufferCellType.Leading) { - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", - r, contentsRegion.Right)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {contentsRegion.Right}]")); } } } @@ -1312,7 +1273,7 @@ private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rect contents[r, c].Character != 0) { // trailing character is not 0 - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", r, c)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]")); } if (contents[r, c].BufferCellType == BufferCellType.Leading) @@ -1327,7 +1288,7 @@ private static void CheckWriteConsoleOutputContents(BufferCell[,] contents, Rect { // for a 2 cell character, either there is no trailing BufferCell or // the trailing BufferCell's character is not 0 - throw PSTraceSource.NewArgumentException(string.Format(CultureInfo.InvariantCulture, "contents[{0}, {1}]", r, c)); + throw PSTraceSource.NewArgumentException(string.Create(CultureInfo.InvariantCulture, $"contents[{r}, {c}]")); } } } @@ -1479,9 +1440,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat bSize.X++; SMALL_RECT wRegion = writeRegion; wRegion.Right++; - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 + result = NativeMethods.WriteConsoleOutput( consoleHandle.DangerousGetHandle(), characterBuffer, @@ -1491,9 +1450,6 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat } else { - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 result = NativeMethods.WriteConsoleOutput( consoleHandle.DangerousGetHandle(), characterBuffer, @@ -1527,7 +1483,7 @@ private static void WriteConsoleOutputCJK(ConsoleHandle consoleHandle, Coordinat // 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.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + 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; } @@ -1655,7 +1611,7 @@ private static void WriteConsoleOutputPlain(ConsoleHandle consoleHandle, Coordin // 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.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + 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; } @@ -1732,10 +1688,7 @@ internal static void ReadConsoleOutput if (origin.X + (contentsRegion.Right - contentsRegion.Left) + 1 < bufferInfo.BufferSize.X && ShouldCheck(contentsRegion.Right, contents, contentsRegion)) { - if (cellArray == null) - { - cellArray = new BufferCell[cellArrayRegion.Bottom + 1, 2]; - } + cellArray ??= new BufferCell[cellArrayRegion.Bottom + 1, 2]; checkOrigin = new Coordinates(origin.X + (contentsRegion.Right - contentsRegion.Left), origin.Y); @@ -1799,9 +1752,7 @@ private static bool ReadConsoleOutputCJKSmall readRegion.Top = (short)origin.Y; readRegion.Right = (short)(origin.X + bufferSize.X - 1); readRegion.Bottom = (short)(origin.Y + bufferSize.Y - 1); - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 + bool result = NativeMethods.ReadConsoleOutput( consoleHandle.DangerousGetHandle(), characterBuffer, @@ -1985,7 +1936,7 @@ internal static void ReadConsoleOutputCJK // 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.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + 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; } @@ -2155,7 +2106,7 @@ private static void ReadConsoleOutputPlain // 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.Format(CultureInfo.InvariantCulture, "bufferSize.Y should be 1, but is {0}", bufferSize.Y)); + 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; } @@ -2270,14 +2221,13 @@ Coordinates origin c.X = (short)origin.X; c.Y = (short)origin.Y; - DWORD unused = 0; bool result = NativeMethods.FillConsoleOutputCharacter( consoleHandle.DangerousGetHandle(), character, (DWORD)numberToWrite, c, - out unused); + out _); if (!result) { int err = Marshal.GetLastWin32Error(); @@ -2324,14 +2274,13 @@ Coordinates origin c.X = (short)origin.X; c.Y = (short)origin.Y; - DWORD unused = 0; bool result = NativeMethods.FillConsoleOutputAttribute( consoleHandle.DangerousGetHandle(), attribute, (DWORD)numberToWrite, c, - out unused); + out _); if (!result) { @@ -2479,9 +2428,6 @@ internal static string GetConsoleWindowTitle() DWORD result; StringBuilder consoleTitle = new StringBuilder((int)bufferSize); - // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to - // get the error code. -#pragma warning disable 56523 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 @@ -2494,6 +2440,8 @@ internal static string GetConsoleWindowTitle() return consoleTitle.ToString(); } + private static bool s_dontsetConsoleWindowTitle; + /// /// Wraps Win32 SetConsoleTitle. /// @@ -2505,12 +2453,27 @@ internal static string GetConsoleWindowTitle() /// 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; @@ -2549,42 +2512,54 @@ internal static void WriteConsole(ConsoleHandle consoleHandle, ReadOnlySpan outBuffer; - while (cursor < output.Length) + // 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) { - ReadOnlySpan outBuffer; + outBuffer = output.Slice(cursor, MaxBufferSize); + cursor += MaxBufferSize; + WriteConsole(consoleHandle, outBuffer); + } - if (cursor + MaxBufferSize < output.Length) - { - outBuffer = output.Slice(cursor, MaxBufferSize); - cursor += MaxBufferSize; + outBuffer = output.Slice(cursor); + if (!newLine) + { + WriteConsole(consoleHandle, outBuffer); + return; + } - WriteConsole(consoleHandle, outBuffer); - } - else + 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) { - outBuffer = output.Slice(cursor); - cursor = output.Length; + rentedArray = ArrayPool.Shared.Rent(size); + buffer = rentedArray.AsSpan().Slice(0, size); + } - if (newLine) - { - var endOfLine = Environment.NewLine.AsSpan(); - var endOfLineLength = endOfLine.Length; -#pragma warning disable CA2014 - Span outBufferLine = stackalloc char[outBuffer.Length + endOfLineLength]; -#pragma warning restore CA2014 - outBuffer.CopyTo(outBufferLine); - endOfLine.CopyTo(outBufferLine.Slice(outBufferLine.Length - endOfLineLength)); - WriteConsole(consoleHandle, outBufferLine); - } - else - { - WriteConsole(consoleHandle, outBuffer); - } + outBuffer.CopyTo(buffer); + lineEnding.CopyTo(buffer.Slice(outBuffer.Length)); + WriteConsole(consoleHandle, buffer); + } + finally + { + if (rentedArray is not null) + { + ArrayPool.Shared.Return(rentedArray); } } } @@ -2654,7 +2629,7 @@ internal static void SetConsoleTextAttribute(ConsoleHandle consoleHandle, WORD a // CSI params? '#' [{}pq] // XTPUSHSGR ('{'), XTPOPSGR ('}'), or their aliases ('p' and 'q') // // Where: - // params: digit+ (';' params)? + // params: digit+ ((';' | ':') params)? // CSI: C0_CSI | C1_CSI // C0_CSI: \x001b '[' // ESC '[' // C1_CSI: \x009b @@ -2699,7 +2674,7 @@ internal static int ControlSequenceLength(string str, ref int offset) { c = str[offset++]; } - while ((offset < str.Length) && (char.IsDigit(c) || c == ';')); + while ((offset < str.Length) && (char.IsDigit(c) || (c == ';') || (c == ':'))); // Finally, handle the command characters for the specific sequences we // handle: @@ -2789,7 +2764,7 @@ internal static int LengthInBufferCells(char c) ((uint)(c - 0xffe0) <= (0xffe6 - 0xffe0))); // We can ignore these ranges because .Net strings use surrogate pairs - // for this range and we do not handle surrogage pairs. + // for this range and we do not handle surrogate pairs. // (c >= 0x20000 && c <= 0x2fffd) || // (c >= 0x30000 && c <= 0x3fffd) return 1 + (isWide ? 1 : 0); @@ -2818,40 +2793,6 @@ internal static bool IsCJKOutputCodePage(out uint codePage) #region Cursor - /// - /// Wraps Win32 SetConsoleCursorPosition. - /// - /// - /// handle for the console where cursor position is set - /// - /// - /// location to which the cursor will be set - /// - /// - /// If Win32's SetConsoleCursorPosition fails - /// - internal static void SetConsoleCursorPosition(ConsoleHandle consoleHandle, Coordinates cursorPosition) - { - Dbg.Assert(!consoleHandle.IsInvalid, "ConsoleHandle is not valid"); - Dbg.Assert(!consoleHandle.IsClosed, "ConsoleHandle is closed"); - - ConsoleControl.COORD c; - - c.X = (short)cursorPosition.X; - c.Y = (short)cursorPosition.Y; - - bool result = NativeMethods.SetConsoleCursorPosition(consoleHandle.DangerousGetHandle(), c); - - if (!result) - { - int err = Marshal.GetLastWin32Error(); - - HostException e = CreateHostException(err, "SetConsoleCursorPosition", - ErrorCategory.ResourceUnavailable, ConsoleControlStrings.SetConsoleCursorPositionExceptionTemplate); - throw e; - } - } - /// /// Wraps Win32 GetConsoleCursorInfo. /// @@ -3159,10 +3100,6 @@ out DWORD numberOfEventsRead [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetConsoleCtrlHandler(BreakHandler handlerRoutine, bool add); - [DllImport(PinvokeDllNames.SetConsoleCursorPositionDllName, SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool SetConsoleCursorPosition(NakedWin32Handle consoleOutput, COORD cursorPosition); - [DllImport(PinvokeDllNames.SetConsoleModeDllName, SetLastError = true, CharSet = CharSet.Unicode)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetConsoleMode(NakedWin32Handle consoleHandle, DWORD mode); @@ -3213,7 +3150,7 @@ ref CHAR_INFO fill ); [DllImport(PinvokeDllNames.SendInputDllName, SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern UInt32 SendInput(UInt32 inputNumbers, INPUT[] inputs, Int32 sizeOfInput); + 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)] diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs index 660e6774334..c79cf42c57a 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHost.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -#pragma warning disable 1634, 1691 - using System; using System.Collections.Generic; using System.Collections.ObjectModel; @@ -16,7 +14,10 @@ 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; @@ -53,11 +54,10 @@ internal sealed partial class ConsoleHost internal const int ExitCodeCtrlBreak = 128 + 21; // SIGBREAK internal const int ExitCodeInitFailure = 70; // Internal Software Error internal const int ExitCodeBadCommandLineParameter = 64; // Command Line Usage Error - private const uint SPI_GETSCREENREADER = 0x0046; - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, ref bool pvParam, uint fWinIni); +#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. @@ -68,6 +68,9 @@ internal sealed partial class 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. /// @@ -94,7 +97,10 @@ internal sealed partial class ConsoleHost /// 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) + internal static int Start( + string bannerText, + string helpText, + bool issProvidedExternally) { #if DEBUG if (Environment.GetEnvironmentVariable("POWERSHELL_DEBUG_STARTUP") != null) @@ -106,11 +112,29 @@ internal static int Start(string bannerText, string helpText) } #endif - // put PSHOME in front of PATH so that calling `powershell` within `powershell` always starts the same running version + // 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 + Path.PathSeparator; + 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]; + } - // to not impact startup perf, we don't remove duplicates, but we avoid adding a duplicate to the front + 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)) { @@ -124,13 +148,16 @@ internal static int Start(string bannerText, string helpText) try { string profileDir = Platform.CacheDirectory; -#if !UNIX - if (!Directory.Exists(profileDir)) + if (!string.IsNullOrEmpty(profileDir)) { - Directory.CreateDirectory(profileDir); - } +#if !UNIX + if (!Directory.Exists(profileDir)) + { + Directory.CreateDirectory(profileDir); + } #endif - ProfileOptimization.SetProfileRoot(profileDir); + ProfileOptimization.SetProfileRoot(profileDir); + } } catch { @@ -138,8 +165,6 @@ internal static int Start(string bannerText, string helpText) // improve startup performance. } - uint exitCode = ExitCodeSuccess; - Thread.CurrentThread.Name = "ConsoleHost main thread"; try @@ -164,104 +189,173 @@ internal static int Start(string bannerText, string helpText) // 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; + s_theConsoleHost.UI.WriteLine($"PowerShell {PSVersionInfo.GitCommitId}"); + return ExitCodeSuccess; } // Servermode parameter validation check. - if ((s_cpp.ServerMode && s_cpp.NamedPipeServerMode) || (s_cpp.ServerMode && s_cpp.SocketServerMode) || (s_cpp.NamedPipeServerMode && s_cpp.SocketServerMode)) + 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."); - if (s_theConsoleHost != null) - { - s_theConsoleHost.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); - } + s_theConsoleHost?.ui.WriteErrorLine(ConsoleHostStrings.ConflictingServerModeParameters); + + return ExitCodeBadCommandLineParameter; + } + if (serverModeCount is 1 && CommandLineParameterParser.IsFileOnlyEntryEnabled) + { + // User facing error message should already be written by the parser, + // so just trace and exit. + s_tracer.TraceError("Server mode cannot be specified when FileOnlyEntry policy is in place."); 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"); + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("ServerMode", s_cpp.ParametersUsedAsDouble); ProfileOptimization.StartProfile("StartupProfileData-ServerMode"); - System.Management.Automation.Remoting.Server.OutOfProcessMediator.Run(s_cpp.InitialCommand, s_cpp.WorkingDirectory); - exitCode = 0; + StdIOProcessMediator.Run( + initialCommand: s_cpp.InitialCommand, + workingDirectory: s_cpp.WorkingDirectory, + configurationName: null, + configurationFile: s_cpp.ConfigurationFile, + combineErrOutStream: false); + return ExitCodeSuccess; } - else if (s_cpp.NamedPipeServerMode) - { - ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("NamedPipe"); - ProfileOptimization.StartProfile("StartupProfileData-NamedPipeServerMode"); - System.Management.Automation.Remoting.RemoteSessionNamedPipeServer.RunServerMode( - s_cpp.ConfigurationName); - exitCode = 0; - } - else if (s_cpp.SSHServerMode) + + if (s_cpp.SSHServerMode) { - ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SSHServer"); + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SSHServer", s_cpp.ParametersUsedAsDouble); ProfileOptimization.StartProfile("StartupProfileData-SSHServerMode"); - System.Management.Automation.Remoting.Server.SSHProcessMediator.Run(s_cpp.InitialCommand); - exitCode = 0; + StdIOProcessMediator.Run( + initialCommand: s_cpp.InitialCommand, + workingDirectory: null, + configurationName: null, + configurationFile: s_cpp.ConfigurationFile, + combineErrOutStream: true); + return ExitCodeSuccess; } - else if (s_cpp.SocketServerMode) + + if (s_cpp.NamedPipeServerMode) { - ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SocketServerMode"); - ProfileOptimization.StartProfile("StartupProfileData-SocketServerMode"); - System.Management.Automation.Remoting.Server.HyperVSocketMediator.Run(s_cpp.InitialCommand, - s_cpp.ConfigurationName); - exitCode = 0; + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("NamedPipe", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-NamedPipeServerMode"); + RemoteSessionNamedPipeServer.RunServerMode( + configurationName: s_cpp.ConfigurationName); + return ExitCodeSuccess; } - else +#if !UNIX + + if (s_cpp.V2SocketServerMode) { - // Run PowerShell in normal console mode. - if (hostException != null) + if (s_cpp.Token == null) { - // Unable to create console host. - throw hostException; + s_tracer.TraceError("Token is required for V2SocketServerMode."); + s_theConsoleHost?.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, ConsoleHostStrings.MissingMandatoryParameter, "-Token", "-V2SocketServerMode")); + return ExitCodeBadCommandLineParameter; } - if (LoadPSReadline()) + if (s_cpp.UTCTimestamp == null) { - ProfileOptimization.StartProfile("StartupProfileData-Interactive"); - - if (UpdatesNotification.CanNotifyUpdates) - { - // Start a task in the background to check for the update release. - _ = UpdatesNotification.CheckForUpdates(); - } + s_tracer.TraceError("UTCTimestamp is required for V2SocketServerMode."); + s_theConsoleHost?.ui.WriteErrorLine(string.Format(CultureInfo.CurrentCulture, ConsoleHostStrings.MissingMandatoryParameter, "-UTCTimestamp", "-v2socketservermode")); + return ExitCodeBadCommandLineParameter; } - else + + 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); + + return ExitCodeSuccess; + } +#endif + + if (s_cpp.SocketServerMode) + { + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("SocketServerMode", s_cpp.ParametersUsedAsDouble); + ProfileOptimization.StartProfile("StartupProfileData-SocketServerMode"); + HyperVSocketMediator.Run( + initialCommand: s_cpp.InitialCommand, + configurationName: s_cpp.ConfigurationName); + return ExitCodeSuccess; + } + + // 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) { - ProfileOptimization.StartProfile("StartupProfileData-NonInteractive"); + // Start a task in the background to check for the update release. + _ = UpdatesNotification.CheckForUpdates(); } + } + else + { + ProfileOptimization.StartProfile("StartupProfileData-NonInteractive"); + } - s_theConsoleHost.BindBreakHandler(); - PSHost.IsStdOutputRedirected = Console.IsOutputRedirected; + s_theConsoleHost.BindBreakHandler(); + IsStdOutputRedirected = Console.IsOutputRedirected; - // Send startup telemetry for ConsoleHost startup - ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("Normal"); + // Send startup telemetry for ConsoleHost startup + ApplicationInsightsTelemetry.SendPSCoreStartupTelemetry("Normal", s_cpp.ParametersUsedAsDouble); - exitCode = s_theConsoleHost.Run(s_cpp, false); - } + return unchecked((int)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(); } - } - - unchecked - { - return (int)exitCode; +#pragma warning restore IDE0031 } } @@ -281,8 +375,8 @@ internal static void ParseCommandLine(string[] args) 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. + // 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(); } @@ -398,7 +492,7 @@ private static bool BreakIntoDebugger() /// 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; @@ -413,7 +507,7 @@ private static void SpinUpBreakHandlerThread(bool shouldEndSession) host.ShouldEndSession = shouldEndSession; } - // Creation of the tread and starting it should be an atomic operation. + // 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. @@ -464,10 +558,7 @@ private static void HandleBreak() if (runspaceRef != null) { var runspace = runspaceRef.Runspace; - if (runspace != null) - { - runspace.Close(); - } + runspace?.Close(); } } } @@ -579,12 +670,18 @@ public override PSHostUserInterface UI /// /// See base class. /// - public void PushRunspace(Runspace newRunspace) + public void PushRunspace(Runspace runspace) { - if (_runspaceRef == null) { return; } + if (_runspaceRef == null) + { + return; + } + + if (runspace is not RemoteRunspace remoteRunspace) + { + throw new ArgumentException(ConsoleHostStrings.PushRunspaceNotRemote, nameof(runspace)); + } - RemoteRunspace remoteRunspace = newRunspace as RemoteRunspace; - Dbg.Assert(remoteRunspace != null, "Expected remoteRunspace != null"); remoteRunspace.StateChanged += HandleRemoteRunspaceStateChanged; // Unsubscribe the local session debugger. @@ -714,7 +811,10 @@ public Runspace Runspace { get { - if (this.RunspaceRef == null) { return null; } + if (this.RunspaceRef == null) + { + return null; + } return this.RunspaceRef.Runspace; } @@ -729,7 +829,10 @@ internal LocalRunspace LocalRunspace return RunspaceRef.OldRunspace as LocalRunspace; } - if (RunspaceRef == null) { return null; } + if (RunspaceRef == null) + { + return null; + } return RunspaceRef.Runspace as LocalRunspace; } @@ -741,7 +844,7 @@ public class ConsoleColorProxy public ConsoleColorProxy(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException(nameof(ui)); + ArgumentNullException.ThrowIfNull(ui); _ui = ui; } @@ -934,7 +1037,11 @@ public override PSObject PrivateData { get { - if (ui == null) return null; + if (ui == null) + { + return null; + } + return _consoleColorProxy ??= PSObject.AsPSObject(new ConsoleColorProxy(ui)); } } @@ -1051,18 +1158,16 @@ public override void NotifyBeginApplication() { lock (hostGlobalLock) { - ++_beginApplicationNotifyCount; - if (_beginApplicationNotifyCount == 1) + if (++_beginApplicationNotifyCount == 1) { - // save the window title when first notified. - + // Save the window title when first notified. _savedWindowTitle = ui.RawUI.WindowTitle; #if !UNIX if (_initialConsoleMode != ConsoleControl.ConsoleModes.Unknown) { - var activeScreenBufferHandle = ConsoleControl.GetActiveScreenBufferHandle(); - _savedConsoleMode = ConsoleControl.GetMode(activeScreenBufferHandle); - ConsoleControl.SetMode(activeScreenBufferHandle, _initialConsoleMode); + var outputHandle = ConsoleControl.GetActiveScreenBufferHandle(); + _savedConsoleMode = ConsoleControl.GetMode(outputHandle); + ConsoleControl.SetMode(outputHandle, _initialConsoleMode); } #endif } @@ -1077,17 +1182,26 @@ public override void NotifyEndApplication() { lock (hostGlobalLock) { - Dbg.Assert(_beginApplicationNotifyCount > 0, "Not running an executable - NotifyBeginApplication was not called!"); - --_beginApplicationNotifyCount; - if (_beginApplicationNotifyCount == 0) + if (--_beginApplicationNotifyCount == 0) { - // restore the window title when the last application started has ended. - + // 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 } @@ -1222,15 +1336,8 @@ private void Dispose(bool isDisposingNotFinalizing) StopTranscribing(); } - if (_outputSerializer != null) - { - _outputSerializer.End(); - } - - if (_errorSerializer != null) - { - _errorSerializer.End(); - } + _outputSerializer?.End(); + _errorSerializer?.End(); if (_runspaceRef != null) { @@ -1346,14 +1453,11 @@ internal WrappedSerializer OutputSerializer { get { - if (_outputSerializer == null) - { - _outputSerializer = - new WrappedSerializer( - OutputFormat, - "Output", - Console.IsOutputRedirected ? Console.Out : ConsoleTextWriter); - } + _outputSerializer ??= + new WrappedSerializer( + OutputFormat, + "Output", + Console.IsOutputRedirected ? Console.Out : ConsoleTextWriter); return _outputSerializer; } @@ -1363,14 +1467,11 @@ internal WrappedSerializer ErrorSerializer { get { - if (_errorSerializer == null) - { - _errorSerializer = - new WrappedSerializer( - ErrorFormat, - "Error", - Console.IsErrorRedirected ? Console.Error : ConsoleTextWriter); - } + _errorSerializer ??= + new WrappedSerializer( + ErrorFormat, + "Error", + Console.IsErrorRedirected ? Console.Error : ConsoleTextWriter); return _errorSerializer; } @@ -1462,7 +1563,7 @@ private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned) // 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); + exitCode = DoRunspaceLoop(cpp.InitialCommand, cpp.SkipProfiles, cpp.Args, cpp.StaMode, cpp.ConfigurationName, cpp.ConfigurationFile); } while (false); @@ -1475,16 +1576,25 @@ private uint Run(CommandLineParameterParser cpp, bool isPrestartWarned) /// /// The process exit code to be returned by Main. /// - private uint DoRunspaceLoop(string initialCommand, bool skipProfiles, Collection initialCommandArgs, bool staMode, string configurationName) + 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, initialCommandArgs); + RunspaceCreationEventArgs args = new RunspaceCreationEventArgs(initialCommand, skipProfiles, staMode, configurationName, configurationFilePath, initialCommandArgs); CreateRunspace(args); - if (ExitCode == ExitCodeInitFailure) { break; } + if (ExitCode == ExitCodeInitFailure) + { + break; + } if (!_noExit) { @@ -1557,14 +1667,12 @@ private Exception InitializeRunspaceHelper(string command, Executor exec, Execut return e; } - private void CreateRunspace(object runspaceCreationArgs) + private void CreateRunspace(RunspaceCreationEventArgs runspaceCreationArgs) { - RunspaceCreationEventArgs args = null; try { - args = runspaceCreationArgs as RunspaceCreationEventArgs; - Dbg.Assert(args != null, "Event Arguments to CreateRunspace should not be null"); - DoCreateRunspace(args.InitialCommand, args.SkipProfiles, args.StaMode, args.ConfigurationName, args.InitialCommandArgs); + Dbg.Assert(runspaceCreationArgs != null, "Arguments to CreateRunspace should not be null."); + DoCreateRunspace(runspaceCreationArgs); } catch (ConsoleHostStartupException startupException) { @@ -1573,35 +1681,6 @@ private void CreateRunspace(object runspaceCreationArgs) } } - /// - /// Check if a screen reviewer utility is running. - /// When a screen reader is running, we don't auto-load the PSReadLine module at startup, - /// since PSReadLine is not accessibility-firendly enough as of today. - /// - private bool IsScreenReaderActive() - { - if (_screenReaderActive.HasValue) - { - return _screenReaderActive.Value; - } - - _screenReaderActive = false; - if (Platform.IsWindowsDesktop) - { - // Note: this API can detect if a third-party screen reader is active, such as NVDA, but not the in-box Windows Narrator. - // Quoted from https://docs.microsoft.com/windows/win32/api/winuser/nf-winuser-systemparametersinfoa about the - // accessibility parameter 'SPI_GETSCREENREADER': - // "Narrator, the screen reader that is included with Windows, does not set the SPI_SETSCREENREADER or SPI_GETSCREENREADER flags." - bool enabled = false; - if (SystemParametersInfo(SPI_GETSCREENREADER, 0, ref enabled, 0)) - { - _screenReaderActive = enabled; - } - } - - return _screenReaderActive.Value; - } - private static bool LoadPSReadline() { // Don't load PSReadline if: @@ -1619,19 +1698,39 @@ private static bool LoadPSReadline() /// Opens and Initializes the Host's sole Runspace. Processes the startup scripts and runs any command passed on the /// command line. /// - private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool staMode, string configurationName, Collection initialCommandArgs) + /// Runspace creation event arguments. + private void DoCreateRunspace(RunspaceCreationEventArgs args) { - Dbg.Assert(_runspaceRef == null, "runspace should be null"); + 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: - // - screen reader is active, such as NVDA, indicating non-visual access // - we're running a command/file and just exiting // - stdin is redirected by a parent process // - we're not interactive @@ -1640,28 +1739,20 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta // powershell -command "Update-Module PSReadline" // This should work just fine as long as no other instances of PowerShell are running. ReadOnlyCollection defaultImportModulesList = null; - if (LoadPSReadline()) + if (!customConfigurationProvided && LoadPSReadline()) { - if (IsScreenReaderActive()) + // Create and open Runspace with PSReadline. + defaultImportModulesList = DefaultInitialSessionState.Modules; + DefaultInitialSessionState.ImportPSModule(new[] { "PSReadLine" }); + consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState); + try { - s_theConsoleHost.UI.WriteLine(ManagedEntranceStrings.PSReadLineDisabledWhenScreenReaderIsActive); - s_theConsoleHost.UI.WriteLine(); + OpenConsoleRunspace(consoleRunspace, args.StaMode); } - else + catch (Exception) { - // Create and open Runspace with PSReadline. - defaultImportModulesList = DefaultInitialSessionState.Modules; - DefaultInitialSessionState.ImportPSModule(new[] { "PSReadLine" }); - consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState); - try - { - OpenConsoleRunspace(consoleRunspace, staMode); - } - catch (Exception) - { - consoleRunspace = null; - psReadlineFailed = true; - } + consoleRunspace = null; + psReadlineFailed = true; } } @@ -1675,7 +1766,7 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta } consoleRunspace = RunspaceFactory.CreateRunspace(this, DefaultInitialSessionState); - OpenConsoleRunspace(consoleRunspace, staMode); + OpenConsoleRunspace(consoleRunspace, args.StaMode); } Runspace.PrimaryRunspace = consoleRunspace; @@ -1707,7 +1798,7 @@ private void DoCreateRunspace(string initialCommand, bool skipProfiles, bool sta _readyForInputTimeInMS = (DateTime.Now - Process.GetCurrentProcess().StartTime).TotalMilliseconds; #endif - DoRunspaceInitialization(skipProfiles, initialCommand, configurationName, initialCommandArgs); + DoRunspaceInitialization(args); } private static void OpenConsoleRunspace(Runspace runspace, bool staMode) @@ -1724,7 +1815,7 @@ private static void OpenConsoleRunspace(Runspace runspace, bool staMode) runspace.Open(); } - private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, string configurationName, Collection initialCommandArgs) + private void DoRunspaceInitialization(RunspaceCreationEventArgs args) { if (_runspaceRef.Runspace.Debugger != null) { @@ -1759,13 +1850,13 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, } } - if (!string.IsNullOrEmpty(configurationName)) + 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(configurationName, this); + RemoteRunspace remoteRunspace = HostUtilities.CreateConfiguredRunspace(args.ConfigurationName, this); remoteRunspace.ShouldCloseOnPop = true; PushRunspace(remoteRunspace); @@ -1782,8 +1873,37 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, 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) - Utils.EnforceSystemLockDownLanguageMode(_runspaceRef.Runspace.ExecutionContext); + // 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); @@ -1800,7 +1920,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, currentUserProfile, currentUserHostSpecificProfile)); - if (!skipProfiles) + if (!args.SkipProfiles) { // Run the profiles. // Profiles are run in the following order: @@ -1818,7 +1938,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, sw.Stop(); var profileLoadTimeInMs = sw.ElapsedMilliseconds; - if (profileLoadTimeInMs > 500 && s_cpp.ShowBanner) + if (s_cpp.ShowBanner && !s_cpp.NoProfileLoadTime && profileLoadTimeInMs > 500) { Console.Error.WriteLine(ConsoleHostStrings.SlowProfileLoadingMessage, profileLoadTimeInMs); } @@ -1845,24 +1965,26 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, 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 (!Path.GetExtension(filePath).Equals(".ps1", StringComparison.OrdinalIgnoreCase)) + 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 (initialCommandArgs != null) + if (args.InitialCommandArgs != null) { // add the args passed to the command. - foreach (CommandParameter p in initialCommandArgs) + foreach (CommandParameter p in args.InitialCommandArgs) { c.Parameters.Add(p); } @@ -1919,19 +2041,19 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, ReportException(e1, exec); } } - else if (!string.IsNullOrEmpty(initialCommand)) + else if (!string.IsNullOrEmpty(args.InitialCommand)) { // Run the command passed on the command line s_tracer.WriteLine("running initial command"); - Pipeline tempPipeline = exec.CreatePipeline(initialCommand, true); + Pipeline tempPipeline = exec.CreatePipeline(args.InitialCommand, true); - if (initialCommandArgs != null) + if (args.InitialCommandArgs != null) { // add the args passed to the command. - foreach (CommandParameter p in initialCommandArgs) + foreach (CommandParameter p in args.InitialCommandArgs) { tempPipeline.Commands[0].Parameters.Add(p); } @@ -1947,7 +2069,7 @@ private void DoRunspaceInitialization(bool skipProfiles, string initialCommand, ParseError[] errors; // Detect if they're using input. If so, read from it. - Ast parsedInput = Parser.ParseInput(initialCommand, out tokens, out errors); + Ast parsedInput = Parser.ParseInput(args.InitialCommand, out tokens, out errors); if (AstSearcher.IsUsingDollarInput(parsedInput)) { executionOptions |= Executor.ExecutionOptions.ReadInputObjects; @@ -2053,9 +2175,7 @@ private void ReportException(Exception e, Executor exec) // NTRAID#Windows OS Bugs-1143621-2005/04/08-sburns - IContainsErrorRecord icer = e as IContainsErrorRecord; - - if (icer != null) + if (e is IContainsErrorRecord icer) { error = icer.ErrorRecord; } @@ -2084,7 +2204,6 @@ private void ReportException(Exception e, Executor exec) if (e1 != null) { // that didn't work. Write out the error ourselves as a last resort. - ReportExceptionFallback(e, null); } } @@ -2105,16 +2224,17 @@ private void ReportExceptionFallback(Exception e, string header) Console.Error.WriteLine(header); } - if (e == null) + if (e is null) { return; } // See if the exception has an error record attached to it... ErrorRecord er = null; - IContainsErrorRecord icer = e as IContainsErrorRecord; - if (icer != null) + if (e is IContainsErrorRecord icer) + { er = icer.ErrorRecord; + } if (e is PSRemotingTransportException) { @@ -2131,8 +2251,22 @@ private void ReportExceptionFallback(Exception e, string header) } // Add the position message for the error if it's available. - if (er != null && er.InvocationInfo != null) + 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; + } } /// @@ -2156,7 +2290,10 @@ 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; } + if ((localrunspace != null) && !localrunspace.ExecutionContext.EngineHostInterface.DebuggerEnabled) + { + return; + } _debuggerStopEventArgs = e; InputLoop baseLoop = null; @@ -2168,10 +2305,7 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) // For remote debugging block data coming from the main (not-nested) // running command. baseLoop = InputLoop.GetNonNestedLoop(); - if (baseLoop != null) - { - baseLoop.BlockCommandOutput(); - } + baseLoop?.BlockCommandOutput(); } // @@ -2216,10 +2350,7 @@ private void OnExecutionSuspended(object sender, DebuggerStopEventArgs e) finally { _debuggerStopEventArgs = null; - if (baseLoop != null) - { - baseLoop.ResumeCommandOutput(); - } + baseLoop?.ResumeCommandOutput(); } } @@ -2310,7 +2441,7 @@ private void WriteDebuggerMessage(string line) /// Neither this class' instances nor its static data is threadsafe. Caller is responsible for ensuring threadsafe /// access. /// - private class InputLoop + private sealed class InputLoop { internal static void RunNewInputLoop(ConsoleHost parent, bool isNested) { @@ -2419,25 +2550,18 @@ private void HandleRunspacePopped(object sender, EventArgs eventArgs) /// internal void Run(bool inputLoopIsNested) { - System.Management.Automation.Host.PSHostUserInterface c = _parent.UI; + PSHostUserInterface c = _parent.UI; ConsoleHostUserInterface ui = c as ConsoleHostUserInterface; Dbg.Assert(ui != null, "Host.UI should return an instance."); bool inBlockMode = false; - bool previousResponseWasEmpty = false; - StringBuilder inputBlock = new StringBuilder(); + // Use nullable so that we don't evaluate suggestions at startup. + bool? previousResponseWasEmpty = null; + var inputBlock = new StringBuilder(); while (!_parent.ShouldEndSession && !_shouldExit) { -#if !UNIX - if (ui.SupportsVirtualTerminal) - { - // need to re-enable VT mode if it was previously enabled as native commands may have turned it off - ui.TryTurnOnVtMode(); - } -#endif - try { _parent._isRunningPromptLoop = true; @@ -2450,7 +2574,6 @@ internal void Run(bool inputLoopIsNested) if (inBlockMode) { // use a special prompt that denotes block mode - prompt = ">> "; } else @@ -2461,9 +2584,9 @@ internal void Run(bool inputLoopIsNested) ui.WriteLine(); // Evaluate any suggestions - if (!previousResponseWasEmpty) + if (previousResponseWasEmpty == false) { - EvaluateSuggestions(ui); + EvaluateFeedbacks(ui); } // Then output the prompt @@ -2472,15 +2595,20 @@ internal void Run(bool inputLoopIsNested) prompt = EvaluateDebugPrompt(); } - if (prompt == null) - { - prompt = EvaluatePrompt(); - } + 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); @@ -2584,6 +2712,14 @@ e is RemoteException || } 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); @@ -2600,10 +2736,7 @@ e is RemoteException || bht = _parent._breakHandlerThread; } - if (bht != null) - { - bht.Join(); - } + bht?.Join(); // Once the pipeline has been executed, we toss any outstanding progress data and // take down the display. @@ -2631,6 +2764,7 @@ e is RemoteException || #endif } } + // NTRAID#Windows Out Of Band Releases-915506-2005/09/09 // Removed HandleUnexpectedExceptions infrastructure finally @@ -2642,8 +2776,7 @@ e is RemoteException || internal void BlockCommandOutput() { - RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (_parent.runningCmd is RemotePipeline rCmdPipeline) { rCmdPipeline.DrainIncomingData(); rCmdPipeline.SuspendIncomingData(); @@ -2656,8 +2789,7 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { - RemotePipeline rCmdPipeline = _parent.runningCmd as RemotePipeline; - if (rCmdPipeline != null) + if (_parent.runningCmd is RemotePipeline rCmdPipeline) { rCmdPipeline.ResumeIncomingData(); } @@ -2685,7 +2817,7 @@ private bool HandleErrors(Exception e, string line, bool inBlockMode, ref String } else { - // an exception ocurred when the command was executed. Tell the user about it. + // an exception occurred when the command was executed. Tell the user about it. _parent.ReportException(e, _exec); } @@ -2747,8 +2879,7 @@ private static bool IsIncompleteParseException(Exception e) } // If it is remote exception ferret out the real exception. - RemoteException remoteException = e as RemoteException; - if (remoteException == null || remoteException.ErrorRecord == null) + if (e is not RemoteException remoteException || remoteException.ErrorRecord == null) { return false; } @@ -2756,33 +2887,18 @@ private static bool IsIncompleteParseException(Exception e) return remoteException.ErrorRecord.CategoryInfo.Reason == nameof(IncompleteParseException); } - private void EvaluateSuggestions(ConsoleHostUserInterface ui) + private void EvaluateFeedbacks(ConsoleHostUserInterface ui) { // Output any training suggestions try { - List suggestions = HostUtilities.GetSuggestion(_parent.Runspace); - - if (suggestions.Count > 0) + List feedbacks = FeedbackHub.GetFeedback(_parent.Runspace); + if (feedbacks is null || feedbacks.Count is 0) { - ui.WriteLine(); + return; } - bool first = true; - foreach (string suggestion in suggestions) - { - if (!first) - ui.WriteLine(); - - ui.WriteLine(suggestion); - - first = false; - } - } - catch (TerminateException) - { - // A variable breakpoint may be hit by HostUtilities.GetSuggestion. The debugger throws TerminateExceptions to stop the execution - // of the current statement; we do not want to treat these exceptions as errors. + HostUtilities.RenderFeedback(feedbacks, ui); } catch (Exception e) { @@ -2796,8 +2912,7 @@ private void EvaluateSuggestions(ConsoleHostUserInterface ui) private string EvaluatePrompt() { - Exception unused = null; - string promptString = _promptExec.ExecuteCommandAndGetResultAsString("prompt", out unused); + string promptString = _promptExec.ExecuteCommandAndGetResultAsString("prompt", out _); if (string.IsNullOrEmpty(promptString)) { @@ -2807,8 +2922,7 @@ private string EvaluatePrompt() // Check for the pushed runspace scenario. if (_isRunspacePushed) { - RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) + if (_parent.Runspace is RemoteRunspace remoteRunspace) { promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } @@ -2842,13 +2956,9 @@ private string EvaluateDebugPrompt() PSObject prompt = output.ReadAndRemoveAt0(); string promptString = (prompt != null) ? (prompt.BaseObject as string) : null; - if (promptString != null) + if (promptString != null && _parent.Runspace is RemoteRunspace remoteRunspace) { - RemoteRunspace remoteRunspace = _parent.Runspace as RemoteRunspace; - if (remoteRunspace != null) - { - promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); - } + promptString = HostUtilities.GetRemotePrompt(remoteRunspace, promptString, _parent._inPushedConfiguredSession); } return promptString; @@ -2871,10 +2981,9 @@ private string EvaluateDebugPrompt() private static readonly Stack s_instanceStack = new Stack(); } - [Serializable] [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 class ConsoleHostStartupException : Exception + private sealed class ConsoleHostStartupException : Exception { internal ConsoleHostStartupException() @@ -2888,14 +2997,6 @@ private class ConsoleHostStartupException : Exception { } - protected - ConsoleHostStartupException( - System.Runtime.Serialization.SerializationInfo info, - System.Runtime.Serialization.StreamingContext context) - : base(info, context) - { - } - internal ConsoleHostStartupException(string message, Exception innerException) : base(message, innerException) @@ -2925,7 +3026,7 @@ private class ConsoleHostStartupException : Exception private bool _isDisposed; internal ConsoleHostUserInterface ui; - internal Lazy ConsoleIn { get; } = new Lazy(() => Console.In); + internal Lazy ConsoleIn { get; } = new Lazy(static () => Console.In); private string _savedWindowTitle = string.Empty; private readonly Version _ver = PSVersionInfo.PSVersion; @@ -2934,7 +3035,6 @@ private class ConsoleHostStartupException : Exception private bool _setShouldExitCalled; private bool _isRunningPromptLoop; private bool _wasInitialCommandEncoded; - private bool? _screenReaderActive; // 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 @@ -2984,12 +3084,14 @@ internal RunspaceCreationEventArgs( bool skipProfiles, bool staMode, string configurationName, + string configurationFilePath, Collection initialCommandArgs) { InitialCommand = initialCommand; SkipProfiles = skipProfiles; StaMode = staMode; ConfigurationName = configurationName; + ConfigurationFilePath = configurationFilePath; InitialCommandArgs = initialCommandArgs; } @@ -3001,6 +3103,8 @@ internal RunspaceCreationEventArgs( internal string ConfigurationName { get; set; } + internal string ConfigurationFilePath { get; set; } + internal Collection InitialCommandArgs { get; set; } } } // namespace diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs index 2a6ea89176d..58630f5b3c0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostRawUserInterface.cs @@ -41,23 +41,16 @@ class ConsoleHostRawUserInterface : System.Management.Automation.Host.PSHostRawU // (we may load resources which can take some time) Task.Run(() => { - WindowsIdentity identity = WindowsIdentity.GetCurrent(); - WindowsPrincipal principal = new WindowsPrincipal(identity); + var identity = WindowsIdentity.GetCurrent(); + var principal = new WindowsPrincipal(identity); if (principal.IsInRole(WindowsBuiltInRole.Administrator)) { - string prefix = ConsoleHostRawUserInterfaceStrings.WindowTitleElevatedPrefix; - - // check using Regex if the window already has Administrator: prefix - // (i.e. from the parent console process) - string titlePattern = ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate; - titlePattern = Regex.Escape(titlePattern) - .Replace(@"\{1}", ".*") - .Replace(@"\{0}", Regex.Escape(prefix)); - if (!Regex.IsMatch(this.WindowTitle, titlePattern)) + // 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)) { - this.WindowTitle = StringUtil.Format(ConsoleHostRawUserInterfaceStrings.WindowTitleTemplate, - prefix, - this.WindowTitle); + WindowTitle = string.Concat(prefix, windowTitle); } } }); @@ -85,9 +78,8 @@ public override GetBufferInfo(out bufferInfo); ConsoleColor foreground; - ConsoleColor unused; - ConsoleControl.WORDToColor(bufferInfo.Attributes, out foreground, out unused); + ConsoleControl.WORDToColor(bufferInfo.Attributes, out foreground, out _); return foreground; } @@ -135,9 +127,8 @@ public override GetBufferInfo(out bufferInfo); ConsoleColor background; - ConsoleColor unused; - ConsoleControl.WORDToColor(bufferInfo.Attributes, out unused, out background); + ConsoleControl.WORDToColor(bufferInfo.Attributes, out _, out background); return background; } @@ -190,14 +181,15 @@ public override set { - // cursor position can't be outside the buffer area - - ConsoleControl.CONSOLE_SCREEN_BUFFER_INFO bufferInfo; - - ConsoleHandle handle = GetBufferInfo(out bufferInfo); - - CheckCoordinateWithinBuffer(ref value, ref bufferInfo, "value"); - ConsoleControl.SetConsoleCursorPosition(handle, value); + 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 + } } } @@ -362,8 +354,7 @@ public override } catch (HostException e) { - Win32Exception win32exception = e.InnerException as Win32Exception; - if (win32exception != null && + if (e.InnerException is Win32Exception win32exception && win32exception.NativeErrorCode == 0x57) { throw PSTraceSource.NewArgumentOutOfRangeException("value", value, @@ -456,7 +447,7 @@ public override } // if the new size will extend past the edge of screen buffer, then move the window position to try to - // accomodate that. + // accommodate that. ConsoleControl.SMALL_RECT r = bufferInfo.WindowRect; @@ -647,8 +638,7 @@ public override { int actualNumberOfInput = ConsoleControl.ReadConsoleInput(handle, ref inputRecords); Dbg.Assert(actualNumberOfInput == 1, - string.Format(CultureInfo.InvariantCulture, "ReadConsoleInput returns {0} number of input event records", - actualNumberOfInput)); + string.Create(CultureInfo.InvariantCulture, $"ReadConsoleInput returns {actualNumberOfInput} number of input event records")); if (actualNumberOfInput == 1) { if (((ConsoleControl.InputRecordEventTypes)inputRecords[0].EventType) == @@ -1540,7 +1530,7 @@ internal struct COORD public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", X, Y); + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); } } @@ -1556,7 +1546,7 @@ internal struct SMALL_RECT public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", Left, Top, Right, Bottom); + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top},{Right},{Bottom}"); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs index 14425da82c0..f0da0d99547 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterface.cs @@ -60,11 +60,38 @@ internal ConsoleHostUserInterface(ConsoleHost parent) _parent = parent; _rawui = new ConsoleHostRawUserInterface(this); - SupportsVirtualTerminal = TryTurnOnVtMode(); + 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 TryTurnOnVtMode() + internal bool TryTurnOnVirtualTerminal() { #if UNIX return true; @@ -72,16 +99,22 @@ internal bool TryTurnOnVtMode() 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 handle = ConsoleControl.GetActiveScreenBufferHandle(); - var m = ConsoleControl.GetMode(handle); - if (ConsoleControl.NativeMethods.SetConsoleMode(handle.DangerousGetHandle(), (uint)(m | ConsoleControl.ConsoleModes.VirtualTerminal))) + 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. - m = ConsoleControl.GetMode(handle); - return (m & ConsoleControl.ConsoleModes.VirtualTerminal) != 0; + outputMode = ConsoleControl.GetMode(outputHandle); + return outputMode.HasFlag(ConsoleControl.ConsoleModes.VirtualTerminal); } } catch @@ -174,9 +207,8 @@ public override string ReadLine() HandleThrowOnReadAndPrompt(); // call our internal version such that it does not end input on a tab - ReadLineResult unused; - return ReadLine(false, string.Empty, out unused, true, true); + return ReadLine(false, string.Empty, out _, true, true); } /// @@ -223,7 +255,7 @@ public override SecureString ReadLineAsSecureString() /// 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 /// /// @@ -300,20 +332,19 @@ private object ReadLineSafe(bool isSecureString, char? printToken) 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) { - // - // read one char at a time so that we don't - // end up having a immutable string holding the - // secret in memory. - // #if UNIX ConsoleKeyInfo keyInfo = Console.ReadKey(true); #else - const int CharactersToRead = 1; -#pragma warning disable CA2014 - Span inputBuffer = stackalloc char[CharactersToRead + 1]; -#pragma warning restore CA2014 string key = ConsoleControl.ReadConsole(handle, initialContentLength: 0, inputBuffer, charactersToRead: CharactersToRead, endOnTab: false, out _); #endif @@ -547,7 +578,7 @@ private static bool shouldUnsetMode( [MethodImpl(MethodImplOptions.AggressiveInlining)] internal void WriteToConsole(char c, bool transcribeResult) { - ReadOnlySpan value = stackalloc char[1] { c }; + ReadOnlySpan value = [c]; WriteToConsole(value, transcribeResult); } @@ -678,9 +709,14 @@ private void WriteLineToConsole() /// public override void Write(string value) { - WriteImpl(value, newLine: false); + 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) @@ -702,7 +738,7 @@ private void WriteImpl(string value, bool newLine) } TextWriter writer = Console.IsOutputRedirected ? Console.Out : _parent.ConsoleTextWriter; - value = Utils.GetOutputString(value, isHost: true, SupportsVirtualTerminal, Console.IsOutputRedirected); + value = GetOutputString(value, SupportsVirtualTerminal); if (_parent.IsRunningAsync) { @@ -814,7 +850,10 @@ private void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, s /// public override void WriteLine(string value) { - this.WriteImpl(value, newLine: true); + lock (_instanceLock) + { + this.WriteImpl(value, newLine: true); + } } /// @@ -831,7 +870,10 @@ public override void WriteLine(string value) /// public override void WriteLine() { - this.WriteImpl(Environment.NewLine, newLine: false); + lock (_instanceLock) + { + this.WriteImpl(Environment.NewLine, newLine: false); + } } #region Word Wrapping @@ -931,7 +973,7 @@ internal List WrapText(string text, int maxWidthInBufferCells) int w = maxWidthInBufferCells - cellCounter; Dbg.Assert(w < e.Current.CellCount, "width remaining should be less than size of word"); - line.Append(e.Current.Text.Substring(0, w)); + line.Append(e.Current.Text.AsSpan(0, w)); l = line.ToString(); Dbg.Assert(RawUI.LengthInBufferCells(l) == maxWidthInBufferCells, "line should exactly fit"); @@ -1175,10 +1217,6 @@ internal string WrapToCurrentWindowWidth(string text) /// public override void WriteDebugLine(string message) { - // don't lock here as WriteLine is already protected. - bool unused; - message = HostUtilities.RemoveGuidFromMessage(message, out unused); - // We should write debug to error stream only if debug is redirected.) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { @@ -1186,9 +1224,9 @@ public override void WriteDebugLine(string message) } else { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { - WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Debug) + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message) + PSStyle.Instance.Reset); + WriteLine(GetFormatStyleString(FormatStyle.Debug) + StringUtil.Format(ConsoleHostUserInterfaceStrings.DebugFormatString, message) + PSStyle.Instance.Reset); } else { @@ -1236,10 +1274,6 @@ public override void WriteInformation(InformationRecord record) /// public override void WriteVerboseLine(string message) { - // don't lock here as WriteLine is already protected. - bool unused; - message = HostUtilities.RemoveGuidFromMessage(message, out unused); - // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { @@ -1247,9 +1281,9 @@ public override void WriteVerboseLine(string message) } else { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { - WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Verbose) + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message) + PSStyle.Instance.Reset); + WriteLine(GetFormatStyleString(FormatStyle.Verbose) + StringUtil.Format(ConsoleHostUserInterfaceStrings.VerboseFormatString, message) + PSStyle.Instance.Reset); } else { @@ -1280,10 +1314,6 @@ public override void WriteVerboseLine(string message) /// public override void WriteWarningLine(string message) { - // don't lock here as WriteLine is already protected. - bool unused; - message = HostUtilities.RemoveGuidFromMessage(message, out unused); - // NTRAID#Windows OS Bugs-1061752-2004/12/15-sburns should read a skin setting here...) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { @@ -1291,9 +1321,9 @@ public override void WriteWarningLine(string message) } else { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { - WriteLine(Utils.GetFormatStyleString(Utils.FormatStyle.Warning) + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message) + PSStyle.Instance.Reset); + WriteLine(GetFormatStyleString(FormatStyle.Warning) + StringUtil.Format(ConsoleHostUserInterfaceStrings.WarningFormatString, message) + PSStyle.Instance.Reset); } else { @@ -1308,24 +1338,10 @@ public override void WriteWarningLine(string message) /// /// Invoked by CommandBase.WriteProgress to display a progress record. /// - public override void WriteProgress(Int64 sourceId, ProgressRecord record) + public override void WriteProgress(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "WriteProgress called with null ProgressRecord"); - if (Console.IsOutputRedirected) - { - // Do not write progress bar when the stdout is redirected. - return; - } - - bool matchPattern; - string currentOperation = HostUtilities.RemoveIdentifierInfoFromMessage(record.CurrentOperation, out matchPattern); - if (matchPattern) - { - record = new ProgressRecord(record) { CurrentOperation = currentOperation }; - } - - // We allow only one thread at a time to update the progress state.) if (_parent.ErrorFormat == Serialization.DataFormat.XML) { PSObject obj = new PSObject(); @@ -1333,8 +1349,14 @@ public override void WriteProgress(Int64 sourceId, ProgressRecord record) 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); @@ -1363,7 +1385,7 @@ public override void WriteErrorLine(string value) { if (writer == _parent.ConsoleTextWriter) { - if (SupportsVirtualTerminal && ExperimentalFeature.IsEnabled("PSAnsiRendering")) + if (SupportsVirtualTerminal) { WriteLine(value); } @@ -1374,6 +1396,7 @@ public override void WriteErrorLine(string value) } else { + value = GetOutputString(value, SupportsVirtualTerminal); Console.Error.WriteLine(value); } } @@ -1463,7 +1486,10 @@ internal string ReadLine(bool endOnTab, string initialContent, out ReadLineResul result = ReadLineResult.endedOnEnter; // If the test hook is set, read from it. - if (s_h != null) return s_h.ReadLine(); + if (s_h != null) + { + return s_h.ReadLine(); + } string restOfLine = null; @@ -1508,14 +1534,21 @@ private string ReadLineFromFile(string initialContent) } var c = unchecked((char)inC); - if (!NoPrompt) Console.Out.Write(c); + 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'); + if (!NoPrompt) + { + Console.Out.Write('\n'); + } + consoleIn.Read(); } @@ -1882,22 +1915,24 @@ private char GetCharacterUnderCursor(Coordinates cursorPosition) #endif /// - /// Strip nulls from a string... + /// Strip nulls from a string. /// /// The string to process. - /// The string with any \0 characters removed... + /// The string with any '\0' characters removed. private static string RemoveNulls(string input) { - if (input.Contains('\0')) + if (!input.Contains('\0')) { return input; } - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(input.Length); foreach (char c in input) { if (c != '\0') + { sb.Append(c); + } } return sb.ToString(); @@ -1989,8 +2024,7 @@ internal string ReadLineWithTabCompletion(Executor exec) var completionResult = commandCompletion.GetNextResult(rlResult == ReadLineResult.endedOnTab); if (completionResult != null) { - completedInput = completionInput.Substring(0, commandCompletion.ReplacementIndex) - + completionResult.CompletionText; + completedInput = string.Concat(completionInput.AsSpan(0, commandCompletion.ReplacementIndex), completionResult.CompletionText); } else { @@ -2087,20 +2121,20 @@ private static void SendLeftArrows(int length) for (int i = 0; i < length; i++) { var down = new ConsoleControl.INPUT(); - down.Type = (UInt32)ConsoleControl.InputType.Keyboard; + down.Type = (uint)ConsoleControl.InputType.Keyboard; down.Data.Keyboard = new ConsoleControl.KeyboardInput(); - down.Data.Keyboard.Vk = (UInt16)ConsoleControl.VirtualKeyCode.Left; + 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 = (UInt32)ConsoleControl.InputType.Keyboard; + up.Type = (uint)ConsoleControl.InputType.Keyboard; up.Data.Keyboard = new ConsoleControl.KeyboardInput(); - up.Data.Keyboard.Vk = (UInt16)ConsoleControl.VirtualKeyCode.Left; + up.Data.Keyboard.Vk = (ushort)ConsoleControl.VirtualKeyCode.Left; up.Data.Keyboard.Scan = 0; - up.Data.Keyboard.Flags = (UInt32)ConsoleControl.KeyboardFlag.KeyUp; + up.Data.Keyboard.Flags = (uint)ConsoleControl.KeyboardFlag.KeyUp; up.Data.Keyboard.Time = 0; up.Data.Keyboard.ExtraInfo = IntPtr.Zero; @@ -2228,7 +2262,7 @@ internal void HandleThrowOnReadAndPrompt() private readonly ConsoleHostRawUserInterface _rawui; private readonly ConsoleHost _parent; - [TraceSourceAttribute("ConsoleHostUserInterface", "Console host's subclass of S.M.A.Host.Console")] + [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/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs index 406c36c8a00..1c9d37ea9fb 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfaceProgress.cs @@ -3,6 +3,7 @@ using System; using System.Management.Automation; +using System.Management.Automation.Host; using System.Threading; using Dbg = System.Management.Automation.Diagnostics; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell { internal partial - class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInterface + class ConsoleHostUserInterface : PSHostUserInterface { /// /// Called at the end of a prompt loop to take down any progress display that might have appeared and purge any @@ -48,7 +49,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt _pendingProgress = null; - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.UseOSCIndicator) + if (SupportsVirtualTerminal && !PSHost.IsStdOutputRedirected && PSStyle.Instance.Progress.UseOSCIndicator) { // OSC sequence to turn off progress indicator // https://github.com/microsoft/terminal/issues/6700 @@ -63,7 +64,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt /// private void - HandleIncomingProgressRecord(Int64 sourceId, ProgressRecord record) + HandleIncomingProgressRecord(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "record should not be null"); @@ -99,7 +100,7 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt { // 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 (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.UseOSCIndicator) + if (SupportsVirtualTerminal && !PSHost.IsStdOutputRedirected && PSStyle.Instance.Progress.UseOSCIndicator) { int percentComplete = record.PercentComplete; if (percentComplete < 0) @@ -114,6 +115,12 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt 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); } } @@ -132,20 +139,14 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void PreWrite() { - if (_progPane != null) - { - _progPane.Hide(); - } + _progPane?.Hide(); } private void PostWrite() { - if (_progPane != null) - { - _progPane.Show(); - } + _progPane?.Show(); } private @@ -171,20 +172,14 @@ class ConsoleHostUserInterface : System.Management.Automation.Host.PSHostUserInt void PreRead() { - if (_progPane != null) - { - _progPane.Hide(); - } + _progPane?.Hide(); } private void PostRead() { - if (_progPane != null) - { - _progPane.Show(); - } + _progPane?.Show(); } private diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs index 6d7caefec36..5895dcf2b83 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePrompt.cs @@ -140,7 +140,7 @@ public override { throw PSTraceSource.NewArgumentException(nameof(descriptions), ConsoleHostUserInterfaceStrings.NullErrorTemplate, - string.Format(CultureInfo.InvariantCulture, "descriptions[{0}]", descIndex)); + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}]")); } PSObject inputPSObject = null; @@ -152,7 +152,7 @@ public override if (string.IsNullOrEmpty(desc.ParameterAssemblyFullName)) { string paramName = - string.Format(CultureInfo.InvariantCulture, "descriptions[{0}].AssemblyFullName", descIndex); + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}].AssemblyFullName"); throw PSTraceSource.NewArgumentException(paramName, ConsoleHostUserInterfaceStrings.NullOrEmptyErrorTemplate, paramName); } @@ -190,8 +190,7 @@ public override { string msg = StringUtil.Format(ConsoleHostUserInterfaceStrings.RankZeroArrayErrorTemplate, desc.Name); ArgumentException innerException = PSTraceSource.NewArgumentException( - string.Format(CultureInfo.InvariantCulture, - "descriptions[{0}].AssemblyFullName", descIndex)); + string.Create(CultureInfo.InvariantCulture, $"descriptions[{descIndex}].AssemblyFullName")); PromptingException e = new PromptingException(msg, innerException, "ZeroRankArray", ErrorCategory.InvalidOperation); throw e; } @@ -203,8 +202,7 @@ public override while (true) { - fieldPromptList.Append( - string.Format(CultureInfo.InvariantCulture, "{0}]: ", inputList.Count)); + fieldPromptList.Append(CultureInfo.InvariantCulture, $"{inputList.Count}]: "); bool endListInput = false; object convertedObj = null; _ = PromptForSingleItem( @@ -356,7 +354,7 @@ out object convertedObj /// 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 iff the input is canceled, e.g., by Ctrl-C or Ctrl-Break. + /// 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) @@ -486,7 +484,7 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe /// !h prints out field's Quick Help, returns null /// All others tilde comments are invalid and return null /// - /// returns null iff there's nothing the caller can process. + /// returns null if-and-only-if there's nothing the caller can process. /// /// /// @@ -495,7 +493,7 @@ private PromptCommonInputErrors PromptTryConvertTo(Type fieldType, bool isFromRe private string PromptCommandMode(string input, FieldDescription desc, out bool inputDone) { Dbg.Assert(input != null && input.StartsWith(PromptCommandPrefix, StringComparison.OrdinalIgnoreCase), - string.Format(CultureInfo.InvariantCulture, "input should start with {0}", PromptCommandPrefix)); + 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); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs index 872aaa19a9c..7e3dcfd70e0 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleHostUserInterfacePromptForChoice.cs @@ -345,8 +345,7 @@ private void WriteChoicePrompt(string[,] hotkeysAndPlainLabels, defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } - defaultChoicesBuilder.Append(string.Format(CultureInfo.InvariantCulture, - "{0}{1}", prepend, defaultStr)); + defaultChoicesBuilder.Append(CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); prepend = ","; } @@ -427,7 +426,7 @@ private void ShowChoiceHelp(Collection choices, string[,] hot WriteLineToConsole( WrapToCurrentWindowWidth( - string.Format(CultureInfo.InvariantCulture, "{0} - {1}", s, choices[i].HelpMessage))); + string.Create(CultureInfo.InvariantCulture, $"{s} - {choices[i].HelpMessage}"))); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs index 11dd276a52d..ce5d5ecaef4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleShell.cs @@ -9,8 +9,8 @@ namespace Microsoft.PowerShell { /// - /// This class provides an entry point which is called by minishell's main - /// to transfer control to Msh console host implementation. + /// This class provides an entry point which is called + /// to transfer control to console host implementation. /// public static class ConsoleShell { @@ -21,7 +21,12 @@ public static class ConsoleShell /// An integer value which should be used as exit code for the process. public static int Start(string? bannerText, string? helpText, string[] args) { - return Start(InitialSessionState.CreateDefault2(), bannerText, helpText, args); + return StartImpl( + initialSessionState: InitialSessionState.CreateDefault2(), + bannerText, + helpText, + args, + issProvided: false); } /// Entry point in to ConsoleShell. Used to create a custom Powershell console application. @@ -31,6 +36,31 @@ public static int Start(string? bannerText, string? helpText, string[] args) /// 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) { @@ -45,7 +75,7 @@ public static int Start(InitialSessionState initialSessionState, string? bannerT ConsoleHost.ParseCommandLine(args); ConsoleHost.DefaultInitialSessionState = initialSessionState; - return ConsoleHost.Start(bannerText, helpText); + return ConsoleHost.Start(bannerText, helpText, issProvided); } } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs index 97a02cb7123..a82156ce1c8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ConsoleTextWriter.cs @@ -76,8 +76,8 @@ public override void Write(char c) { - ReadOnlySpan c1 = stackalloc char[1] { c }; - _ui.WriteToConsole(c1, transcribeResult: true); + ReadOnlySpan value = [c]; + _ui.WriteToConsole(value, transcribeResult: true); } public override diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs index 68df51be539..354c61fb8f3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Executor.cs @@ -13,11 +13,11 @@ namespace Microsoft.PowerShell { /// - /// Executor wraps a Pipeline instance, and provides helper methods for executing commands in that pipeline. It is used to + /// 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 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. + /// 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. @@ -44,8 +44,8 @@ internal enum ExecutionOptions /// /// /// True if the instance will be used to execute the prompt function, which will delay stopping the pipeline by some - /// milliseconds. This we prevent us from stopping the pipeline so quickly that when the user leans on the ctrl-c key - /// that the prompt "stops working" (because it is being stopped faster than it can run to completion). + /// 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) { @@ -67,7 +67,7 @@ private void OutputObjectStreamHandler(object sender, EventArgs e) PipelineReader reader = (PipelineReader)sender; - // we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be + // 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. @@ -80,7 +80,6 @@ private void OutputObjectStreamHandler(object sender, EventArgs e) } // 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 @@ -88,7 +87,7 @@ private void ErrorObjectStreamHandler(object sender, EventArgs e) PipelineReader reader = (PipelineReader)sender; - // we use NonBlockingRead instead of Read, as Read would block if the reader has no objects. While it would be + // 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. @@ -101,30 +100,26 @@ private void ErrorObjectStreamHandler(object sender, EventArgs e) } /// - /// This method handles the failure in executing pipeline asynchronously. + /// This method handles failures in executing the pipeline asynchronously. /// /// private void AsyncPipelineFailureHandler(Exception ex) { ErrorRecord er = null; - IContainsErrorRecord cer = ex as IContainsErrorRecord; - if (cer != null) + if (ex is IContainsErrorRecord cer) { er = cer.ErrorRecord; - // Exception inside the error record is ParentContainsErrorRecordException which - // doesn't have stack trace. Replace it with top level exception. + // 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); } - if (er == null) - { - er = new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); - } + er ??= new ErrorRecord(ex, "ConsoleHostAsyncPipelineFailure", ErrorCategory.NotSpecified, null); _parent.ErrorSerializer.Serialize(er); } - private class PipelineFinishedWaitHandle + private sealed class PipelineFinishedWaitHandle { internal PipelineFinishedWaitHandle(Pipeline p) { @@ -232,9 +227,9 @@ internal void ExecuteCommandAsyncHelper(Pipeline tempPipeline, out Exception exc } catch (PipelineClosedException) { - // This exception can occurs when input is closed. This can happen - // for various reasons. For ex:Command in the pipeline is invalid and - // command discovery throws exception which closes the pipeline and + // 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; } @@ -297,46 +292,30 @@ internal Pipeline CreatePipeline(string command, bool addToHistory) /// /// 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 + /// 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. + /// 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. + /// 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 + /// Options to govern the execution /// /// - /// the object stream resulting from the execution. May be null. + /// 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"); - // Experimental: - // Check for implicit remoting commands that can be batched, and execute as batched if able. - if (ExperimentalFeature.IsEnabled("PSImplicitRemotingBatching")) - { - var addOutputter = ((options & ExecutionOptions.AddOutputter) > 0); - if (addOutputter && - !_parent.RunspaceRef.IsRunspaceOverridden && - _parent.RunspaceRef.Runspace.ExecutionContext.Modules != null && - _parent.RunspaceRef.Runspace.ExecutionContext.Modules.IsImplicitRemotingModuleLoaded && - Utils.TryRunAsImplicitBatch(command, _parent.RunspaceRef.Runspace)) - { - exceptionThrown = null; - return null; - } - } - Pipeline tempPipeline = CreatePipeline(command, (options & ExecutionOptions.AddToHistory) > 0); return ExecuteCommandHelper(tempPipeline, out exceptionThrown, options); @@ -461,14 +440,14 @@ internal Collection ExecuteCommand(string command) } /// - /// 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 thru the exceptionThrown parameter. + /// 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. + /// The command to execute. May be any valid monad command. /// /// - /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null. + /// 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. /// /// @@ -502,8 +481,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception // 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. - PSObject msho = streamResults[0] as PSObject; - if (msho != null) + if (streamResults[0] is PSObject msho) result = msho.BaseObject.ToString(); else result = streamResults[0].ToString(); @@ -514,11 +492,11 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception } /// - /// Executes a command (by calling this.ExecuteCommand), and coerces the first result object to a bool. Any Exception + /// 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 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 @@ -526,22 +504,20 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception /// internal bool? ExecuteCommandAndGetResultAsBool(string command) { - Exception unused = null; - - bool? result = ExecuteCommandAndGetResultAsBool(command, out unused); + 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 thru the exceptionThrown parameter. + /// 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. + /// The command to execute. May be any valid monad command. /// /// - /// Receives the Exception thrown by the execution of the command, if any. If no exception is thrown, then set to null. + /// 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. /// /// @@ -580,7 +556,7 @@ internal string ExecuteCommandAndGetResultAsString(string command, out Exception } /// - /// Cancels execution of the current instance. If the current instance is not running, then does nothing. Called in + /// 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() @@ -605,8 +581,7 @@ private void Cancel() internal void BlockCommandOutput() { - RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) + if (_pipeline is RemotePipeline remotePipeline) { // Waits until queued data is handled. remotePipeline.DrainIncomingData(); @@ -619,15 +594,13 @@ internal void BlockCommandOutput() internal void ResumeCommandOutput() { RemotePipeline remotePipeline = _pipeline as RemotePipeline; - if (remotePipeline != null) - { - // Resumes data flow. - remotePipeline.ResumeIncomingData(); - } + + // Resumes data flow. + remotePipeline?.ResumeIncomingData(); } /// - /// Resets the instance to its post-ctor state. Does not cancel execution. + /// Resets the instance to its post-ctor state. Does not cancel execution. /// private void Reset() { @@ -643,7 +616,7 @@ private void Reset() /// handler is triggered and calls the static Cancel method. /// /// - /// The instance to make current. Null is allowed. + /// The instance to make current. Null is allowed. /// /// /// Here are some state-transition cases to illustrate the use of CurrentExecutor @@ -705,8 +678,8 @@ internal static Executor CurrentExecutor } /// - /// Cancels the execution of the current instance (the instance last passed to PushCurrentExecutor), if any. If no - /// instance is Current, then does nothing. + /// 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() { @@ -717,10 +690,7 @@ internal static void CancelCurrentExecutor() temp = s_currentExecutor; } - if (temp != null) - { - temp.Cancel(); - } + temp?.Cancel(); } // These statics are threadsafe, as there can be only one instance of ConsoleHost in a process at a time, and access diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs index 6dbc21ab242..acfdea07153 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ManagedEntrance.cs @@ -16,18 +16,18 @@ namespace Microsoft.PowerShell { /// - /// Defines an entry point from unmanaged code to managed Msh. + /// Defines an entry point from unmanaged code to PowerShell. /// public sealed class UnmanagedPSEntry { /// - /// Starts managed MSH. + /// Starts PowerShell. /// /// - /// Deprecated: Console file used to create a runspace configuration to start MSH + /// Deprecated: Console file used to create a runspace configuration to start PowerShell /// /// - /// Command line arguments to the managed MSH + /// Command line arguments to the PowerShell /// /// /// Length of the passed in argument array. @@ -39,20 +39,17 @@ public static int Start(string consoleFilePath, [MarshalAs(UnmanagedType.LPArray } /// - /// Starts managed MSH. + /// Starts PowerShell. /// /// - /// Command line arguments to the managed MSH + /// 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) { - if (args == null) - { - throw new ArgumentNullException(nameof(args)); - } + ArgumentNullException.ThrowIfNull(args); #if DEBUG if (args.Length > 0 && !string.IsNullOrEmpty(args[0]) && args[0]!.Equals("-isswait", StringComparison.OrdinalIgnoreCase)) @@ -89,14 +86,17 @@ public static int Start([MarshalAs(UnmanagedType.LPArray, ArraySubType = Unmanag int exitCode = 0; try { - var banner = string.Format( + string banner = string.Format( CultureInfo.InvariantCulture, - ManagedEntranceStrings.ShellBannerNonWindowsPowerShell, + ManagedEntranceStrings.ShellBannerPowerShell, PSVersionInfo.GitCommitId); ConsoleHost.DefaultInitialSessionState = InitialSessionState.CreateDefault2(); - exitCode = ConsoleHost.Start(banner, ManagedEntranceStrings.UsageHelp); + exitCode = ConsoleHost.Start( + bannerText: banner, + helpText: ManagedEntranceStrings.UsageHelp, + issProvidedExternally: false); } catch (HostException e) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs index 0c38f35960f..b16fb5ee147 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/PendingProgress.cs @@ -43,7 +43,7 @@ class PendingProgress /// internal void - Update(Int64 sourceId, ProgressRecord record) + Update(long sourceId, ProgressRecord record) { Dbg.Assert(record != null, "record should not be null"); @@ -119,10 +119,7 @@ class PendingProgress ProgressNode parentNode = FindNodeById(newNode.SourceId, newNode.ParentActivityId); if (parentNode != null) { - if (parentNode.Children == null) - { - parentNode.Children = new ArrayList(); - } + parentNode.Children ??= new ArrayList(); AddNode(parentNode.Children, newNode); break; @@ -265,8 +262,7 @@ class PendingProgress #endif } - private - class FindOldestNodeVisitor : NodeVisitor + private sealed class FindOldestNodeVisitor : NodeVisitor { internal override bool @@ -358,7 +354,7 @@ internal override /// private ProgressNode - FindNodeById(Int64 sourceId, int activityId) + FindNodeById(long sourceId, int activityId) { ArrayList listWhereFound = null; int indexWhereFound = -1; @@ -366,11 +362,10 @@ internal override FindNodeById(sourceId, activityId, out listWhereFound, out indexWhereFound); } - private - class FindByIdNodeVisitor : NodeVisitor + private sealed class FindByIdNodeVisitor : NodeVisitor { internal - FindByIdNodeVisitor(Int64 sourceIdToFind, int activityIdToFind) + FindByIdNodeVisitor(long sourceIdToFind, int activityIdToFind) { _sourceIdToFind = sourceIdToFind; _idToFind = activityIdToFind; @@ -404,7 +399,7 @@ internal override IndexWhereFound = -1; private readonly int _idToFind = -1; - private readonly Int64 _sourceIdToFind; + private readonly long _sourceIdToFind; } /// @@ -428,7 +423,7 @@ internal override /// private ProgressNode - FindNodeById(Int64 sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound) + FindNodeById(long sourceId, int activityId, out ArrayList listWhereFound, out int indexWhereFound) { listWhereFound = null; indexWhereFound = -1; @@ -463,9 +458,7 @@ internal override /// /// The found node, or null if no suitable node was located. /// - private - ProgressNode - FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style) + private static ProgressNode FindOldestNodeOfGivenStyle(ArrayList nodes, int oldestSoFar, ProgressNode.RenderStyle style) { if (nodes == null) { @@ -508,8 +501,7 @@ internal override return found; } - private - class AgeAndResetStyleVisitor : NodeVisitor + private sealed class AgeAndResetStyleVisitor : NodeVisitor { internal override bool @@ -579,7 +571,7 @@ internal override int invisible = 0; if (TallyHeight(rawUI, maxHeight, maxWidth) > maxHeight) { - // This will smash down nodes until the tree will fit into the alloted number of lines. If in the + // 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); @@ -637,9 +629,7 @@ internal override /// /// The PSHostRawUserInterface used to gauge string widths in the rendering. /// - private - void - RenderHelper(ArrayList strings, ArrayList nodes, int indentation, int maxWidth, PSHostRawUserInterface rawUI) + 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"); @@ -666,8 +656,7 @@ internal override } } - private - class HeightTallyer : NodeVisitor + private sealed class HeightTallyer : NodeVisitor { internal HeightTallyer(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) { @@ -728,9 +717,7 @@ private int TallyHeight(PSHostRawUserInterface rawUi, int maxHeight, int maxWidt /// /// /// - private - bool - AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style) + private static bool AllNodesHaveGivenStyle(ArrayList nodes, ProgressNode.RenderStyle style) { if (nodes == null) { @@ -855,18 +842,6 @@ internal override } // If we get all the way to here, then we've compressed all the nodes and we still don't fit. - -#if DEBUG || ASSERTIONS_TRACE - - Dbg.Assert( - nodesCompressed == CountNodes(), - "We should have compressed every node in the tree."); - Dbg.Assert( - AllNodesHaveGivenStyle(_topLevelNodes, newStyle), - "We should have compressed every node in the tree."); - -#endif - return false; } @@ -891,7 +866,7 @@ internal override /// /// The number of nodes that were made invisible during the compression. /// - /// + /// private int CompressToFit(PSHostRawUserInterface rawUi, int maxHeight, int maxWidth) @@ -953,8 +928,6 @@ internal override return nodesCompressed; } - Dbg.Assert(false, "with all nodes invisible, we should never reach this point."); - return 0; } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs index ca2694bcabc..01cbd4069c4 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressNode.cs @@ -54,7 +54,7 @@ namespace Microsoft.PowerShell /// Constructs an instance from a ProgressRecord. /// internal - ProgressNode(Int64 sourceId, ProgressRecord record) + 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"); @@ -67,7 +67,7 @@ namespace Microsoft.PowerShell this.Style = IsMinimalProgressRenderingEnabled() ? RenderStyle.Ansi - : this.Style = RenderStyle.FullPlus; + : RenderStyle.FullPlus; this.SourceId = sourceId; } @@ -111,7 +111,7 @@ namespace Microsoft.PowerShell RenderMinimal(strCollection, indentation, maxWidth, rawUI); break; case RenderStyle.Ansi: - RenderAnsi(strCollection, indentation, maxWidth); + RenderAnsi(strCollection, indentation, maxWidth, rawUI); break; case RenderStyle.Invisible: // do nothing @@ -353,7 +353,7 @@ private static void RenderFullDescription(string description, string indent, int internal static bool IsMinimalProgressRenderingEnabled() { - return ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.View == ProgressView.Minimal; + return PSStyle.Instance.Progress.View == ProgressView.Minimal; } /// @@ -368,9 +368,12 @@ internal static bool IsMinimalProgressRenderingEnabled() /// /// The maximum number of chars that the rendering is allowed to consume. /// + /// + /// The PSHostRawUserInterface used to gauge string widths in the rendering. + /// private void - RenderAnsi(ArrayList strCollection, int indentation, int maxWidth) + RenderAnsi(ArrayList strCollection, int indentation, int maxWidth, PSHostRawUserInterface rawUI) { string indent = StringUtil.Padding(indentation); string secRemain = string.Empty; @@ -387,50 +390,131 @@ internal static bool IsMinimalProgressRenderingEnabled() maxWidth = PSStyle.Instance.Progress.MaxWidth; } + // if the activity is really long, only use up to half the width + string activity; + int activityDisplayCellsWidth = rawUI.LengthInBufferCells(Activity); + if (activityDisplayCellsWidth > maxWidth / 2) + { + activity = StringUtil.TruncateToBufferCellWidth(rawUI, Activity, (maxWidth / 2) - 1) + PSObjectHelper.Ellipsis; + } + else + { + activity = Activity; + } + + activityDisplayCellsWidth = rawUI.LengthInBufferCells(activity); + // 4 is for the extra space and square brackets below and one extra space - int barWidth = maxWidth - Activity.Length - indentation - 4; + int barWidth = maxWidth - activityDisplayCellsWidth - 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); - if (StatusDescription.Length > barWidth - secRemainLength) + // Build the status description part + int maxStatusWidth = barWidth - secRemainLength; + string statusPart = RenderAnsiStatusPart(rawUI, maxStatusWidth, out int statusPartDisplayWidth); + + sb.Append(statusPart); + + // Calculate padding needed + int emptyPadLength = barWidth - statusPartDisplayWidth - secRemainLength; + if (emptyPadLength > 0) { - sb.Append(StatusDescription.Substring(0, barWidth - secRemainLength - 1)); - sb.Append(PSObjectHelper.Ellipsis); + sb.Append(' ', emptyPadLength); } - else + + sb.Append(secRemain); + + // Insert ReverseOff at the correct position for the progress bar + RenderAnsiReverseOff(sb, rawUI, statusPart, barWidth); + + strCollection.Add( + StringUtil.Format( + "{0}{1}{2} [{3}]{4}", + indent, + PSStyle.Instance.Progress.Style, + activity, + sb.ToString(), + PSStyle.Instance.Reset)); + } + + /// + /// Builds the status-description portion of the Ansi progress bar, truncating it + /// with an ellipsis when it would exceed the available status width. + /// + /// + /// The PSHostRawUserInterface used to gauge string widths. + /// + /// + /// The maximum number of buffer cells available for the status description. + /// + /// + /// On return, the width in buffer cells of the produced status part. + /// + /// The status description, possibly truncated with an ellipsis. + private string RenderAnsiStatusPart(PSHostRawUserInterface rawUI, int maxStatusWidth, out int statusPartDisplayWidth) + { + int statusDisplayWidth = rawUI.LengthInBufferCells(StatusDescription); + + if (maxStatusWidth <= 0 || statusDisplayWidth <= maxStatusWidth) { - sb.Append(StatusDescription); + statusPartDisplayWidth = statusDisplayWidth; + return StatusDescription; } - sb.Append(string.Empty.PadRight(barWidth + PSStyle.Instance.Reverse.Length - sb.Length - secRemainLength)); - sb.Append(secRemain); + int ellipsisWidth = rawUI.LengthInBufferCells(PSObjectHelper.EllipsisStr); + string statusPart = StringUtil.TruncateToBufferCellWidth(rawUI, StatusDescription, maxStatusWidth - ellipsisWidth) + PSObjectHelper.EllipsisStr; + statusPartDisplayWidth = rawUI.LengthInBufferCells(statusPart); + return statusPart; + } - if (PercentComplete > 0 && PercentComplete < 100) + /// + /// Appends the ReverseOff VT sequence to the rendered bar at the buffer-cell position + /// that corresponds to the filled portion of the progress bar, respecting character boundaries. + /// + /// The StringBuilder holding the bar contents built so far. + /// + /// The PSHostRawUserInterface used to gauge string widths. + /// + /// The status text at the start of the bar. + /// The total width of the progress bar in buffer cells. + private void RenderAnsiReverseOff(StringBuilder sb, PSHostRawUserInterface rawUI, string statusPart, int barWidth) + { + if (PercentComplete < 0 || PercentComplete >= 100 || barWidth <= 0) { - int barLength = PercentComplete * barWidth / 100; - if (barLength >= barWidth) - { - barLength = barWidth - 1; - } + sb.Append(PSStyle.Instance.ReverseOff); + return; + } + + int barLength = PercentComplete * barWidth / 100; + if (barLength >= barWidth) + { + barLength = barWidth - 1; + } + + // Calculate the string position where we need to insert ReverseOff. + // We need to find the character position that corresponds to barLength buffer cells. + int stringPos = PSStyle.Instance.Reverse.Length; + int currentCellCount = 0; + + for (int i = 0; i < statusPart.Length && currentCellCount < barLength; i++) + { + currentCellCount += rawUI.LengthInBufferCells(statusPart[i]); + stringPos++; + } - sb.Insert(barLength + PSStyle.Instance.Reverse.Length, PSStyle.Instance.ReverseOff); + // Add any padding characters. + int remainingCells = barLength - currentCellCount; + stringPos += Math.Max(0, remainingCells); + + if (stringPos < sb.Length) + { + sb.Insert(stringPos, 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)); } /// @@ -465,7 +549,7 @@ internal static bool IsMinimalProgressRenderingEnabled() /// Identifies the source of the progress record. /// internal - Int64 + long SourceId; /// diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs index f0cdadc73eb..030a359c2d8 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/ProgressPane.cs @@ -13,7 +13,7 @@ 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 { @@ -26,7 +26,7 @@ class ProgressPane internal ProgressPane(ConsoleHostUserInterface ui) { - if (ui == null) throw new ArgumentNullException(nameof(ui)); + ArgumentNullException.ThrowIfNull(ui); _ui = ui; _rawui = ui.RawUI; } @@ -37,7 +37,7 @@ class ProgressPane /// /// true if the pane is visible, false if not. /// - /// + /// internal bool IsShowing @@ -115,7 +115,7 @@ class ProgressPane // create cleared region to clear progress bar later _savedRegion = tempProgressRegion; - if (ExperimentalFeature.IsEnabled(ExperimentalFeature.PSAnsiProgressFeatureName) && PSStyle.Instance.Progress.View != ProgressView.Minimal) + if (PSStyle.Instance.Progress.View != ProgressView.Minimal) { for (int row = 0; row < rows; row++) { @@ -301,7 +301,17 @@ 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; @@ -319,7 +329,11 @@ private void WriteContent() } _rawui.CursorPosition = currentPosition; +#if UNIX Console.CursorVisible = true; +#else + Console.CursorVisible = currentCursorVisible; +#endif } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs index 4c1fb4fa4e9..5181ae63672 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/Serialization.cs @@ -189,8 +189,7 @@ class WrappedDeserializer : Serialization return null; case DataFormat.XML: - string unused; - o = _xmlDeserializer.Deserialize(out unused); + o = _xmlDeserializer.Deserialize(out _); break; case DataFormat.Text: diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs index dadc5117ab3..18725b5ddb7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StartTranscriptCmdlet.cs @@ -96,7 +96,7 @@ public SwitchParameter Append /// /// The read-only attribute will not be replaced when the transcript is done. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get @@ -115,7 +115,7 @@ public SwitchParameter Force /// /// Property that prevents file overwrite. /// - [Parameter()] + [Parameter] [Alias("NoOverwrite")] public SwitchParameter NoClobber { @@ -135,7 +135,7 @@ public SwitchParameter NoClobber /// /// Whether to include command invocation time headers between commands. /// - [Parameter()] + [Parameter] public SwitchParameter IncludeInvocationHeader { get; set; @@ -177,7 +177,7 @@ protected override void BeginProcessing() } else { - _outFilename = (string)value; + _outFilename = (string)PSObject.Base(value); } } diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs index 48b392f98e7..093f7c147dc 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/StopTranscriptCmdlet.cs @@ -10,17 +10,22 @@ namespace Microsoft.PowerShell.Commands /// /// Implements the stop-transcript cmdlet. /// - [Cmdlet(VerbsLifecycle.Stop, "Transcript", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096798")] + [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 { /// - /// Starts the transcription. + /// Stops the transcription. /// protected override void BeginProcessing() { + if (!ShouldProcess(string.Empty)) + { + return; + } + try { string outFilename = Host.UI.StopTranscribing(); diff --git a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs index 08e0ed8e1ee..eb4557c04d2 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs +++ b/src/Microsoft.PowerShell.ConsoleHost/host/msh/UpdatesNotification.cs @@ -28,6 +28,9 @@ internal static class UpdatesNotification 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', @@ -57,12 +60,12 @@ internal static class UpdatesNotification static UpdatesNotification() { s_notificationType = GetNotificationType(); - CanNotifyUpdates = s_notificationType != NotificationType.Off; + CanNotifyUpdates = s_notificationType != NotificationType.Off + && Platform.TryDeriveFromCache(PSVersionInfo.GitCommitId, out s_cacheDirectory); if (CanNotifyUpdates) { s_enumOptions = new EnumerationOptions(); - s_cacheDirectory = Path.Combine(Platform.CacheDirectory, PSVersionInfo.GitCommitId); // Build the template/pattern strings for the configured notification type. string typeNum = ((int)s_notificationType).ToString(); @@ -89,9 +92,18 @@ internal static void ShowUpdateNotification(PSHostUserInterface hostUI) if (TryParseUpdateFile( updateFilePath: out _, out SemanticVersion lastUpdateVersion, - lastUpdateDate: out _) + 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 @@ -108,7 +120,7 @@ internal static void ShowUpdateNotification(PSHostUserInterface hostUI) // We calculate how much whitespace we need to make it look nice if (hostUI.SupportsVirtualTerminal) { - // Use Warning Color + // Swaps foreground and background colors. notificationColor = "\x1B[7m"; resetColor = "\x1B[0m"; @@ -126,6 +138,7 @@ internal static void ShowUpdateNotification(PSHostUserInterface hostUI) string notificationMsg = string.Format(CultureInfo.CurrentCulture, notificationMsgTemplate, releaseTag, notificationColor, resetColor, line2Padding, line3Padding); + hostUI.WriteLine(); hostUI.WriteLine(notificationMsg); } } @@ -168,7 +181,7 @@ internal static async Task CheckForUpdates() out DateTime lastUpdateDate); DateTime today = DateTime.UtcNow; - if (parseSuccess && updateFilePath != null && (today - lastUpdateDate).TotalDays < 7) + 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. @@ -352,7 +365,7 @@ private static async Task QueryNewReleaseAsync(SemanticVersion baseline using var client = new HttpClient(); - string userAgent = string.Format(CultureInfo.InvariantCulture, "PowerShell {0}", PSVersionInfo.GitCommitId); + string userAgent = string.Create(CultureInfo.InvariantCulture, $"PowerShell {PSVersionInfo.GitCommitId}"); client.DefaultRequestHeaders.Add("User-Agent", userAgent); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); @@ -411,7 +424,7 @@ private static NotificationType GetNotificationType() private enum NotificationType { /// - /// Turn off the udpate notification. + /// Turn off the update notification. /// Off = 0, @@ -428,7 +441,7 @@ private enum NotificationType LTS = 2 } - private class Release + private sealed class Release { internal Release(string publishAt, string tagName) { diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx index ab893b91a0a..7a66c4dd828 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/CommandLineParameterParserStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -118,10 +118,7 @@ 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 or -EncodedCommand. - - - Unable to read from file '{0}'. + 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. @@ -187,7 +184,10 @@ Valid formats are: Cannot process the command because -STA and -MTA are both specified. Specify either -STA or -MTA. - Cannot process the command because -Configuration requires an argument that is a remote endpoint configuration name. Specify this argument and try again. + 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. @@ -222,4 +222,19 @@ Valid formats are: The specified arguments must not contain null elements. + + Invalid ExecutionPolicy value '{0}'. + + + An argument is required to be supplied to the '{0}' parameter. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx index f5fc6e4427a..bb2e50e949e 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleControlStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -123,12 +123,6 @@ 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 attaching to parent console. Contact Microsoft Customer Support Services. - - - The Win32 internal error "{0}" 0x{1:X} occurred while detaching from the console. 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. @@ -192,9 +186,6 @@ 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 trying to set the cursor position. Contact Microsoft Customer Support Services. - The Win32 internal error "{0}" 0x{1:X} occurred while getting cursor information. Contact Microsoft Customer Support Services. @@ -207,7 +198,4 @@ The Win32 internal error "{0}" 0x{1:X} occurred while sending keyboard input. Contact Microsoft Customer Support Services. - - The Win32 internal error "{0}" 0x{1:X} occurred while setting console font information. Contact Microsoft Customer Support Services. - diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx index bf47782fdb0..150f1cb973f 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostRawUserInterfaceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -172,9 +172,6 @@ Window title cannot be longer than {0} characters. - Administrator - - - {0}: {1} + Administrator: diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx index 7296bb30feb..f99a7627a65 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -123,18 +123,15 @@ Cannot process input loop. ExitCurrentLoop was called when no InputLoops were running. - - A nested prompt cannot be entered until the host is running at least one prompt loop. - PS> - - Execution of initialization script has failed. The shell cannot be started. - 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. @@ -152,9 +149,6 @@ PowerShell transcript end End time: {0:yyyyMMddHHmmss} ********************** - - An instance of the ConsoleHost class has already been created for this process. - Command '{0}' could not be run because some PowerShell Snap-Ins did not load. @@ -170,9 +164,6 @@ End time: {0:yyyyMMddHHmmss} {0}:{1,-3} {2} - - An error occurred while running '{0}': {1} - The current session does not support debugging; execution will continue. @@ -191,4 +182,10 @@ The current session does not support debugging; execution will continue. 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/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx index 6c383d5052f..a3b9491db36 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceSecurityResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx index 7a2f61022f5..b7d0c1f79d6 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ConsoleHostUserInterfaceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx deleted file mode 100644 index 7cfdd2f63b5..00000000000 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/HostMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx index 7b13837b294..4f5e919fbf7 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ManagedEntranceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,15 +117,20 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - PowerShell {0} -Copyright (c) Microsoft Corporation. - -https://aka.ms/powershell -Type 'help' to get help. + + PowerShell {0} + + + [Constrained Language Mode] + + + [Constrained Language AUDIT Mode : No Restrictions] - - Warning: PowerShell detected that you might be using a screen reader and has disabled PSReadLine for compatibility purposes. If you want to re-enable it, run 'Import-Module PSReadLine'. + + [No Language Mode] + + + [Restricted Language Mode] {1} A new PowerShell preview release is available: v{0} {2} @@ -149,12 +154,15 @@ Type 'help' to get help. Usage: pwsh[.exe] [-Login] [[-File] <filePath> [args]] [-Command { - | <script-block> [-args <arg-array>] | <string> [<CommandParameters>] } ] - [-ConfigurationName <string>] [-CustomPipeName <string>] - [-EncodedCommand <Base64EncodedCommand>] + [-CommandWithArgs <string> [<CommandParameters>] + [-ConfigurationName <string>] [-ConfigurationFile <filePath>] + [-CustomPipeName <string>] [-EncodedCommand <Base64EncodedCommand>] [-ExecutionPolicy <ExecutionPolicy>] [-InputFormat {Text | XML}] [-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile] - [-OutputFormat {Text | XML}] [-SettingsFile <filePath>] [-SSHServerMode] [-STA] - [-Version] [-WindowStyle <style>] [-WorkingDirectory <directoryPath>] + [-NoProfileLoadTime] [-OutputFormat {Text | XML}] + [-SettingsFile <filePath>] [-SSHServerMode] [-STA] + [-Version] [-WindowStyle <style>] + [-WorkingDirectory <directoryPath>] pwsh[.exe] -h | -Help | -? | /? @@ -283,6 +291,25 @@ All parameters are case-insensitive. (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 @@ -292,6 +319,14 @@ All parameters are case-insensitive. 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 @@ -383,18 +418,24 @@ All parameters are case-insensitive. -NoLogo | -nol - Hides the copyright banner at startup of interactive sessions. + Hides the banner text at startup of interactive sessions. -NonInteractive | -noni - Does not present an interactive prompt to the user. Any attempts to use - interactive features, like Read-Host or confirmation prompts, result in - statement-terminating errors. + 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" @@ -402,7 +443,7 @@ All parameters are case-insensitive. Example: "pwsh -o XML -c Get-Date" - When called withing a PowerShell session, you get deserialized objects as + 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. @@ -434,7 +475,7 @@ All parameters are case-insensitive. -WindowStyle | -w Sets the window style for the session. Valid values are Normal, Minimized, - Maximized and Hidden. + Maximized, and Hidden. -WorkingDirectory | -wd diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx index b4e9785add6..afaa49e90c3 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ProgressNodeStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx index c2a2826955c..e460449e060 100644 --- a/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/TranscriptStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - This host does not support transcription. - Transcript started, output file is {0} diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/CommandLineParameterParserStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/CommandLineParameterParserStrings.cs.resx new file mode 100644 index 00000000000..4e56f6dfd21 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/CommandLineParameterParserStrings.cs.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Příkaz nelze zpracovat, protože už byl zadán pomocí parametru -Command, -CommandWithArgs nebo -EncodedCommand. + + + Příkaz nelze zpracovat, protože chybí parametr. Za parametrem -Command musí následovat příkaz. + + + Nerozpoznaný parametr: {0}. + + + Parametrem -Command byla zadána hodnota -; nejsou povoleny žádné další argumenty parametru -Command. + + + Jako argument parametru -Command byla zadána hodnota -, ale standardní vstup nebyl pro tento proces přesměrován. + + + Příkaz nelze spustit, protože pro parametr OutputFormat nebyl zadán žádný argument. +Zadejte pro tento parametr jeden z následujících formátů: +{0} + + + Příkaz nelze zpracovat, protože parametr -InputFormat vyžaduje argument. Zadejte pro tento parametr platný argument formátu. +Platné formáty jsou: +{0} + + + Příkaz nelze zpracovat, protože byla zadána nesprávná hodnota parametru. {0} není platný formát. +Platné formáty jsou: +{1} + + + Příkaz nelze zpracovat, protože argumenty parametru -Command nebo -EncodedCommand už byly zadány pomocí parametru -EncodedArguments. + + + Příkaz nelze zpracovat, protože parametr -EncodedArguments vyžaduje hodnotu. Zadejte hodnotu pro parametr -EncodedArguments. + + + Příkaz nelze spustit, protože parametr -File vyžaduje cestu k souboru. Zadejte cestu pro parametr -File a potom příkaz spusťte znovu. + + + Příkaz nelze zpracovat, protože parametr -WindowStyle vyžaduje jako argument hodnotu normal, hidden, minimized nebo maximized. Zadejte jednu z těchto hodnot argumentu a zkuste to znovu. + + + Zpracování parametru -File {0} se nezdařilo: {1}. Zadejte platnou cestu pro parametr -File. + + + Zpracování parametru -WindowStyle {0} se nezdařilo: {1}. + + + Zpracování parametru -File {0} se nezdařilo, protože soubor nemá příponu .ps1. Zadejte název platného souboru skriptu PowerShellu a zkuste to znovu. + + + Argument {0} se nerozpoznal jako název souboru skriptu. Zkontrolujte pravopis názvu. Pokud jste zadali cestu, ověřte, že je správná, a zkuste to znovu. + + + Příkaz nelze zpracovat, protože hodnota zadaná pomocí parametru -EncodedArguments není správně zakódovaná. Hodnota musí být zakódovaná ve formátu Base64. + + + Příkaz nelze zpracovat, protože hodnota zadaná pomocí parametru -EncodedCommand není správně zakódovaná. Hodnota musí být zakódovaná ve formátu Base64. + + + Zásadu spouštění nelze zpracovat, protože chybí název zásady. Za parametrem -ExecutionPolicy musí následovat název zásady. + + + Příkaz nelze zpracovat, protože jsou zadány oba parametry, -STA i -MTA. Zadejte buď parametr -STA, nebo parametr -MTA. + + + Příkaz nelze zpracovat, protože parametr -ConfigurationName vyžaduje jako argument název konfigurace vzdáleného koncového bodu. Zadejte tento argument a zkuste to znovu. + + + Příkaz nelze zpracovat, protože parametr -ConfigurationFile vyžaduje jako argument cestu ke konfiguračnímu souboru relace (.pssc). Zadejte tento argument a zkuste to znovu. + + + Příkaz nelze zpracovat, protože parametr -CustomPipeName vyžaduje jako argument název kanálu, který chcete použít. Zadejte tento argument a zkuste to znovu. + + + Příkaz nelze zpracovat, protože název zadaný parametrem -CustomPipeName je příliš dlouhý. Názvy kanálů mohou mít na této platformě maximálně {0} znaků. Název vašeho kanálu {1} má {2} znaků. + + + Příkaz nelze zpracovat, protože parametr -SettingsFile vyžaduje jako argument cestu k souboru. + + + Zpracování parametru -SettingsFile {0} se nezdařilo: {1}. Zadejte platnou cestu pro parametr -SettingsFile. + + + Argument {0} předaný parametru -SettingsFile neexistuje. Jako argument parametru -SettingsFile zadejte cestu k existujícímu souboru JSON. + + + Neplatný argument {0}. Neměli jste na mysli: + + + Parametr -WindowStyle není na této platformě implementovaný. + + + Příkaz nelze zpracovat, protože parametr -WorkingDirectory vyžaduje jako argument cestu k adresáři. + + + Parametr -MTA není na této platformě podporovaný. + + + Parametr -STA není na této platformě podporovaný. + + + Zadané argumenty nesmí obsahovat elementy null. + + + Neplatná hodnota ExecutionPolicy {0}. + + + Pro parametr {0} je nutné zadat argument. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleControlStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleControlStrings.cs.resx new file mode 100644 index 00000000000..c0e4cbcc550 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleControlStrings.cs.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 + + + Při přidávání obslužné rutiny přerušení došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby podpory Microsoftu. + + + Při pokusu o odebrání obslužné rutiny přerušení došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při získávání vstupních informací o popisovači konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při načítání popisovače aktivní výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při získávání režimu konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při nastavování režimu konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při čtení znaků ze vstupní vyrovnávací paměti konzoly došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při čtení vstupních záznamů ze vstupní vyrovnávací paměti konzoly došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při čtení obsahu vstupní vyrovnávací paměti konzoly došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při získávání počtu událostí ve vstupní vyrovnávací paměti konzoly došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při vyprazdňování vstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při získávání informací o výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při nastavování velikosti výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při zápisu do výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při čtení výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při plnění výstupní vyrovnávací paměti konzoly znaky došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při plnění výstupní vyrovnávací paměti konzoly atributy došlo k vnitřní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při posouvání výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při nastavování informací o okně konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při získávání největší možné velikosti okna konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při nastavování názvu okna konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při zápisu do výstupní vyrovnávací paměti konzoly na aktuální pozici kurzoru došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při nastavování atributů znaků výstupní vyrovnávací paměti konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při získávání informací o kurzoru došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při nastavování informací o kurzoru došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na oddělení služeb zákaznické podpory společnosti Microsoft. + + + Při získávání informací o písmu konzoly došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + + Při odesílání vstupu z klávesnice došlo k interní chybě Win32 {0} 0x{1:X}. Obraťte se na služby zákaznické podpory Microsoftu. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostRawUserInterfaceStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostRawUserInterfaceStrings.cs.resx new file mode 100644 index 00000000000..9acadc5284f --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostRawUserInterfaceStrings.cs.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 + + + Operaci nelze zpracovat, protože zadané souřadnice nejsou platné. Zadejte souřadnici v oblasti {0} vyrovnávací paměti. + + + Velikost vyrovnávací paměti nelze nastavit, protože zadaná velikost je příliš velká nebo příliš malá. + + + Barvu konzoly nelze nastavit, protože zadaná hodnota není platná. Zadejte platnou barvu definovanou typem System.ConsoleColor. + + + Vlastnost CursorSize nelze zpracovat, protože zadaná velikost kurzoru není platná. + + + Nelze načíst možnosti čtení klávesy. Chcete-li číst stisknutí kláves, nastavte jednu nebo obě z následujících možností: IncludeKeyDown, IncludeKeyUp. + + + Hodnota {0} musí být větší nebo rovna {1}. + + + Zadanou pozici X okna (sloupec) nelze použít, protože přesahuje šířku vyrovnávací paměti obrazovky. Zadejte jinou pozici X, přičemž 0 představuje krajní levý sloupec vyrovnávací paměti. + + + Zadanou pozici Y okna (řádek) nelze použít, protože přesahuje výšku vyrovnávací paměti obrazovky. Zadejte jinou pozici Y, přičemž 0 představuje horní krajní řádek vyrovnávací paměti. + + + Šířka okna nemůže být menší než 1. + + + Výška okna musí být alespoň 1. + + + Okno nemůže být širší než vyrovnávací paměť obrazovky. + + + Okno nemůže být vyšší než vyrovnávací paměť obrazovky. + + + Okno nemůže být širší než {0}. + + + Okno nemůže být vyšší než {0}. + + + Šířka okna je příliš malá. + + + Výška okna je příliš malá. + + + Název okna nemůže být prázdný. + + + Název okna nemůže být delší než {0} znaků. + + + Správce: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostStrings.cs.resx new file mode 100644 index 00000000000..9aa0d08e743 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostStrings.cs.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 + + + Nelze zobrazit výzvu, protože je již spuštěno příliš mnoho vnořených výzev. + + + Vstupní smyčku nelze zpracovat. Metoda ExitCurrentLoop byla volána, když nebyly spuštěny žádné InputLoops. + + + PS> + + + Prostředí nelze spustit. Během inicializace došlo k chybě: + + + Prostředí nelze spustit. Spolu s argumentem -ConfigurationFile byl zadán objekt InitialSessionState. Obě direktivy konfigurace nelze použít současně. + + + Došlo k chybě, která nebyla správně zpracována. Další informace jsou uvedeny níže. Proces PowerShellu se ukončí. + + + ********************** +Začátek přepisu PowerShellu +Čas zahájení: {0:yyyyMMddHHmmss} +Uživatelské jméno: {1}\{2} +Počítač: {3} ({4}) +********************** + + + ********************** +Konec přepisu PowerShellu +Čas ukončení: {0:yyyyMMddHHmmss} +********************** + + + Příkaz {0} nelze spustit, protože se nenačetly některé moduly snap-in PowerShellu. + + + Příkaz {0} nebyl spuštěn, protože relace, ve které byl určen ke spuštění, byla zavřena nebo přerušena + + + Vstupujete do režimu ladění. Použijte h nebo ? pro pomoc. + + + Nalezeno: {0} + + + {0}:{1,-3} {2} + + + +Aktuální relace nepodporuje ladění. Provádění bude pokračovat. + + + + + Nelze načíst modul PSReadline. Konzola je spuštěna bez PSReadline. + + + Byl zadán více než jeden parametr režimu serveru. Parametry režimu serveru musí být použity výhradně. + + + Načítání osobních a systémových profilů trvalo {0} ms. + + + Spustit jako správce + + + PushRunspace může odeslat pouze vzdálené prostředí runspace. + + + Parametr {0} je povinný a musí být zadán při použití parametru {1}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostUserInterfaceSecurityResources.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostUserInterfaceSecurityResources.cs.resx new file mode 100644 index 00000000000..1fcc9ce638d --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostUserInterfaceSecurityResources.cs.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 + + + Uživatel: + + + Heslo uživatele {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostUserInterfaceStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostUserInterfaceStrings.cs.resx new file mode 100644 index 00000000000..3af9b7c2d4e --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ConsoleHostUserInterfaceStrings.cs.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 + + + Kolekce {0} musí obsahovat nejméně jeden prvek. + + + Nelze rozpoznat „{1}“ jako {0} z důvodu chyby přetečení. + + + Nelze rozpoznat „{1}“ jako {0} z důvodu chyby formátu. + + + „{0}“ nelze rozpoznat jako platný příkaz příkazového řádku. + + + Pro {0} není k dispozici žádná nápověda. + + + {0}: + + + Pole {0} je pole s nulovým pořadím. + + + „{0}“ musí mít alespoň jeden prvek. + + + „{0}“ musí být platný index do „{1}“ nebo -1 pro žádnou výchozí volbu. + + + „{0}“ musí být platný index do „{1}“. „{2}“ není platný index. + + + [?] Nápověda + + + Výzva byla zrušena. + + + Klávesovou zkratku nelze zpracovat, protože otazník (?) nelze použít jako klávesovou zkratku. + + + Nelze zobrazit výzvu pro „{0}“, protože typ „{1}“ nelze načíst. + + + „{0}“ nesmí být null ani prázdné. + + + „{0}“ nemůže mít hodnotu null. + + + (Nápovědu získáte zadáním !?.) + + + (výchozí hodnota je „{0}“): + + + (výchozí hodnota je „{0}“) + + + (výchozí volby jsou {0}) + + + Volba[{0}]: + + + LADIT: {0} + + + PODROBNÉ: {0} + + + UPOZORNĚNÍ: {0} + + + PowerShell je v neinteraktivním režimu. Funkce čtení a příkazového řádku není k dispozici. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ManagedEntranceStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ManagedEntranceStrings.cs.resx new file mode 100644 index 00000000000..c6cea6f3b9a --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ManagedEntranceStrings.cs.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} + + + [Režim omezeného jazyka] + + + [Režim AUDIT omezeného jazyka : Bez omezení] + + + [Režim bez jazyka] + + + [Režim omezeného jazyka] + + + {1} Je k dispozici nová verze Preview PowerShellu: v{0} {2} + {1} Upgradujte teď nebo si prohlédněte stránku verze na adrese:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Je k dispozici nová stabilní verze PowerShellu: v{0} {2} + {1} Upgradujte teď nebo si prohlédněte stránku verze na adrese:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Je k dispozici nová verze PowerShellu LTS: v{0} {2} + {1} Upgradujte teď nebo si prohlédněte stránku verze na adrese:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Použití: 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 | -? | /? + +Online nápověda PowerShellu https://aka.ms/powershell-docs + +U všech parametrů se nerozlišují velká a malá písmena. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ProgressNodeStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ProgressNodeStrings.cs.resx new file mode 100644 index 00000000000..e1c9a20b1bc --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/ProgressNodeStrings.cs.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 + + + Zbývá: {0} {1} + + + {0} aktivita se nezobrazuje... + + + Tento počet aktivit se nezobrazuje: {0}... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/cs/TranscriptStrings.cs.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/TranscriptStrings.cs.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/cs/TranscriptStrings.cs.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/CommandLineParameterParserStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/CommandLineParameterParserStrings.de.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/CommandLineParameterParserStrings.de.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleControlStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleControlStrings.de.resx new file mode 100644 index 00000000000..3439e2a21ef --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleControlStrings.de.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 + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Hinzufügen eines Unterbrechungshandlers aufgetreten. Wenden Sie sich an den Microsoft-Support Services, um Hilfe zu erhalten. + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Entfernen eines Unterbrechungshandlers aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen von Eingaben zum Konsolenhandle aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen des Handles für den aktiven Konsolenausgabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen des Konsolenmodus aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen des Konsolenmodus aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Lesen von Zeichen aus dem Konsoleneingabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Lesen von Eingabedatensätzen aus dem Konsoleneingabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Lesen des Inhalts des Konsoleneingabepuffers aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen der Anzahl der Ereignisse im Konsoleneingabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Leeren des Konsoleneingabepuffers aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen der Informationen zum Konsolenausgabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen der Größe des Konsolenausgabepuffers aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Schreiben in den Konsolenausgabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Lesen des Konsolenausgabepuffers aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Ausfüllen des Konsolenausgabepuffers mit Zeichen aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Ausfüllen des Konsolenausgabepuffers mit Attributen aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Scrollen des Konsolenausgabepuffers aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen des Konsolenfensterinformationen aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen der größten Konsolenfenstergröße aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen des Konsolenfenstertitels aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Schreiben in den Konsolenausgabepuffer an der aktuellen Cursorposition aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen von Zeichenattributen für den Konsolenausgabepuffer aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen der Cursorinformationen aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Festlegen der Cursorinformationen aufgetreten. Wenden Sie sich an Microsoft Customer Support Services. + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Abrufen der Konsolenschriftartinformationen aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + + Der interne Win32-Fehler „{0}“ 0x{1:X} ist beim Senden von Tastatureingaben aufgetreten. Wenden Sie sich an den Microsoft-Kundendienst (Customer Support Services, CSS). + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostRawUserInterfaceStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostRawUserInterfaceStrings.de.resx new file mode 100644 index 00000000000..5cc8977fbba --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostRawUserInterfaceStrings.de.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 + + + Der Vorgang kann nicht verarbeitet werden, da die angegebene Koordinate ungültig ist. Geben Sie eine Koordinate innerhalb des Pufferbereichs von {0} an. + + + Die Puffergröße kann nicht festgelegt werden, da die angegebene Größe zu groß oder zu klein ist. + + + Die Konsolenfarbe kann nicht festgelegt werden, da der angegebene Wert ungültig ist. Geben Sie eine gültige Farbe an, wie sie vom Typ System.ConsoleColor definiert wird. + + + CursorSize kann nicht verarbeitet werden, da die angegebene Cursorgröße ungültig ist. + + + Tastenoptionen können nicht gelesen werden. Legen Sie zum Lesen von Optionen eine oder beide der folgenden Optionen fest: IncludeKeyDown, IncludeKeyUp. + + + {0} muss größer als oder gleich {1} sein. + + + Die angegebene X-Position des Fensters (Spalte) kann nicht verwendet werden, da sie über die Breite des Bildschirmpuffers hinausgeht. Geben Sie eine andere X-Position an, beginnend mit 0 als der linken Spalte des Puffers. + + + Die angegebene Y-Position des Fensters (Zeile) kann nicht verwendet werden, da sie über die Höhe des Bildschirmpuffers hinausgeht. Geben Sie eine andere Y-Position an, beginnend mit 0 als oberster Zeile des Puffers. + + + Die Fensterbreite darf nicht kleiner als 1 sein. + + + Die Fensterhöhe muss mindestens 1 betragen. + + + Das Fenster darf nicht breiter als der Bildschirmpuffer sein. + + + Das Fenster darf nicht größer als der Bildschirmpuffer sein. + + + Das Fenster darf nicht breiter als {0} sein. + + + Das Fenster darf nicht höher als {0} sein. + + + Das Fenster ist zu schmal. + + + Das Fenster ist zu kurz. + + + Der Titel des Fensters darf nicht leer sein. + + + Der Titel des Fensters darf nicht länger als {0} Zeichen sein. + + + Admin: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostStrings.de.resx new file mode 100644 index 00000000000..d3bcfad86ed --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostStrings.de.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 + + + Der Prompt kann nicht angezeigt werden, da bereits zu viele verschachtelte Prompts ausgeführt werden. + + + Die Eingabeschleife kann nicht verarbeitet werden. ExitCurrentLoop wurde aufgerufen, als keine Eingabeschleifen ausgeführt wurden. + + + PS> + + + Die Shell kann nicht gestartet werden. Fehler bei der Initialisierung. + + + Die Shell kann nicht gestartet werden. Zusammen mit dem -ConfigurationFile-Argument wurde ein InitialSessionState-Objekt angegeben. Beide Konfigurationsanweisungen können nicht gleichzeitig verwendet werden. + + + Ein Fehler ist aufgetreten, der nicht ordnungsgemäß behandelt wurde. Weitere Informationen sind unten aufgeführt. Der PowerShell-Prozess wird beendet. + + + ********************** +Beginn des PowerShell-Transkripts +Startzeit: {0:yyyyMMddHHmmss} +Benutzername: {1}\{2} +Computer: {3} ({4}) +********************** + + + ********************** +Ende des PowerShell-Transkripts +Endzeit: {0:yyyyMMddHHmmss} +********************** + + + Der Befehl „{0}“ konnte nicht ausgeführt werden, da einige PowerShell-Snap-Ins nicht geladen wurden. + + + Der Befehl „{0}“ wurde nicht ausgeführt, da die Sitzung, in der er ausgeführt werden sollte, geschlossen oder unterbrochen wurde + + + Der Debugmodus wird aktiviert Verwenden Sie „h“ oder „?“, um Hilfe zu erhalten. + + + Treffer {0} + + + {0}:{1,-3} {2} + + + +Die aktuelle Sitzung unterstützt kein Debugging, die Ausführung wird fortgesetzt. + + + + + Das PSReadLine-Modul kann nicht geladen werden. Die Konsole wird ohne PSReadLine ausgeführt. + + + Es wurden mehr als ein Servermodusparameter angegeben. Servermodusparameter müssen ausschließlich verwendet werden. + + + Das Laden der persönlichen und Systemprofile dauerte {0} ms. + + + Als Administrator ausführen + + + PushRunspace kann nur einen Remoterunspace pushen. + + + Der Parameter „{0}“ ist erforderlich und muss angegeben werden, wenn der Parameter „{1}“ verwendet wird. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostUserInterfaceSecurityResources.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostUserInterfaceSecurityResources.de.resx new file mode 100644 index 00000000000..ce6ce6ae67e --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostUserInterfaceSecurityResources.de.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 + + + Benutzer: + + + Kennwort für Benutzer {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostUserInterfaceStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostUserInterfaceStrings.de.resx new file mode 100644 index 00000000000..31258136b9f --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ConsoleHostUserInterfaceStrings.de.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 + + + Die Sammlung „{0}“ muss mindestens ein Element enthalten. + + + „{1}“ kann aufgrund eines Überlauffehlers nicht als {0} erkannt werden. + + + „{1}“ kann aufgrund eines Formatfehlers nicht als {0} erkannt werden. + + + „{0}“ kann nicht als gültiger Promptbefehl erkannt werden. + + + Es ist keine Hilfe für {0} verfügbar. + + + {0}: + + + Das Feld „{0}“ ist ein Nullrangarray. + + + „{0}“ muss mindestens ein Element aufweisen. + + + „{0}“ muss ein gültiger Index in „{1}“ oder -1 sein, wenn keine Standardauswahl vorhanden ist. + + + „{0}“ muss ein gültiger Index in „{1}“ sein. „{2}“ ist kein gültiger Index. + + + [?] Hilfe + + + Der Prompt wurde abgebrochen. + + + Der Hotkey kann nicht verarbeitet werden, da ein Fragezeichen („?“) nicht als Hotkey verwendet werden kann. + + + Der Prompt für „{0}“ kann nicht angezeigt werden, da der Typ „{1}“ nicht geladen werden kann. + + + '{0}' darf nicht NULL oder leer sein. + + + „{0}“ darf nicht NULL sein. + + + (Geben Sie !? ein, um Hilfe zu erhalten.) + + + (Standard ist „{0}“): + + + (Standard ist „{0}“) + + + (Standardoptionen sind {0}) + + + Auswahl[{0}]: + + + DEBUGGEN: {0} + + + AUSFÜHRLICH: {0} + + + WARNUNG: {0} + + + PowerShell befindet sich im Nichtinteraktiv-Modus. Lese- und Promptfunktionen sind nicht verfügbar. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ManagedEntranceStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ManagedEntranceStrings.de.resx new file mode 100644 index 00000000000..4d6e339dd07 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ManagedEntranceStrings.de.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} + + + [Eingeschränkter Sprachmodus] + + + [Eingeschränkte Sprache AUDIT-Modus : Keine Einschränkungen] + + + [Kein Sprachmodus] + + + [Eingeschränkter Sprachmodus] + + + {1} Eine neue PowerShell-Vorschauversion ist verfügbar: v{0} {2} + {1} Upgraden Sie jetzt, oder besuchen Sie die Releaseseite unter:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Ein neues stabiles PowerShell-Release ist verfügbar: v{0} {2} + {1} Upgraden Sie jetzt, oder besuchen Sie die Releaseseite unter:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Ein neues PowerShell LTS-Release ist verfügbar: v{0} {2} + {1} Jetzt aktualisieren, oder besuchen Sie die Releaseseite unter:{3}{2} + {1}https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Syntax: pwsh[.exe] [-Login] [[-File] <filePath> [args]] + [-Command { - | <script-block> [-args <arg-array>] + | <string> [<CommandParameters>] } ] + [-CommandWithArgs <string> [<CommandParameters>] + [-ConfigurationName <string>] [-ConfigurationFile <filePath>] + [-CustomPipeName <Zeichenfolge>] [-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 | -? | /? + +Die PowerShell Online-Hilfe https://aka.ms/powershell-docs + +Bei allen Parametern wird die Groß-/Kleinschreibung nicht beachtet. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/ProgressNodeStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ProgressNodeStrings.de.resx new file mode 100644 index 00000000000..04cd8644b1e --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/ProgressNodeStrings.de.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} verbleibend + + + {0} Aktivität wird nicht angezeigt... + + + {0} Aktivitäten werden nicht angezeigt... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/de/TranscriptStrings.de.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/de/TranscriptStrings.de.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/de/TranscriptStrings.de.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/CommandLineParameterParserStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/CommandLineParameterParserStrings.es.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/CommandLineParameterParserStrings.es.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleControlStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleControlStrings.es.resx new file mode 100644 index 00000000000..eee42ceb98f --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleControlStrings.es.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 + + + Error interno de Win32 "{0}" 0x{1:X} al agregar un controlador de interrupción. Póngase en contacto con los servicios de Soporte técnico de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al intentar quitar un controlador de interrupción. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al obtener información sobre el identificador de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al recuperar el identificador del búfer de salida de la consola activa. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo un error interno de Win32 "{0}" 0x{1:X} al obtener el modo de consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al establecer el modo de consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al leer caracteres del búfer de entrada de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Error interno de Win32 "{0}" 0x{1:X} al leer los registros de entrada del búfer de entrada de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al leer el contenido del búfer de entrada de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al obtener el número de eventos del búfer de entrada de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al vaciar el búfer de entrada de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al obtener información del búfer de salida de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Error interno de Win32 "{0}" 0x{1:X} al establecer el tamaño del búfer de salida de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al escribir en el búfer de salida de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Error interno de Win32 "{0}" 0x{1:X} al leer el búfer de salida de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al rellenar el búfer de salida de la consola con caracteres. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al escribir en el búfer de salida de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al establecer el título de la ventana de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Error interno de Win32 "{0}" 0x{1:X} al establecer la información de la ventana de consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al obtener el tamaño máximo de la ventana de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al establecer el título de la ventana de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al escribir en el búfer de salida de la consola en la posición actual del cursor. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al escribir en el búfer de salida de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al obtener información del cursor. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al establecer la información del cursor. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al obtener información de la fuente de la consola. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + + Se produjo el error interno de Win32 "{0}" 0x{1:X} al enviar entrada de teclado. Póngase en contacto con los servicios de soporte al cliente de Microsoft. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostRawUserInterfaceStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostRawUserInterfaceStrings.es.resx new file mode 100644 index 00000000000..d3aac76c76d --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostRawUserInterfaceStrings.es.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 + + + No se puede procesar la operación porque la coordenada proporcionada no es válida. Especifique una coordenada dentro del área de búfer de {0}. + + + No se puede establecer el tamaño del búfer porque el tamaño especificado es demasiado grande o demasiado pequeño. + + + No se puede establecer el color de la consola porque el valor especificado no es válido. Especifique un color válido según lo definido por el tipo System.ConsoleColor. + + + No se puede procesar CursorSize porque el tamaño de cursor especificado no es válido. + + + No se pueden leer las opciones de clave. Para leer las opciones, establezca una o las dos opciones siguientes: IncludeKeyDown, IncludeKeyUp. + + + {0} debe ser mayor o igual que {1}. + + + No se puede usar la posición especificada de la ventana X (columna) porque se extiende más allá del ancho del búfer de pantalla. Especifique otra posición X, empezando por 0 como la columna más a la izquierda del búfer. + + + No se puede usar la posición Y (fila) de la ventana especificada porque se extiende más allá del alto del búfer de pantalla. Especifique otra posición Y, empezando por 0 como la fila más alta del búfer. + + + El ancho de la ventana no puede ser menor que 1. + + + El alto de la ventana debe ser al menos 1. + + + La ventana no puede ser más ancha que el búfer de pantalla. + + + La ventana no puede ser más alta que el búfer de pantalla. + + + La ventana no puede ser más ancha que {0}. + + + La ventana no puede ser más alta que {0}. + + + El tamaño de la ventana es demasiado estrecho. + + + El tamaño de la ventana es demasiado corto. + + + El título de la ventana no puede estar vacío. + + + El título de la ventana no puede tener más de {0} caracteres. + + + Administrador: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostStrings.es.resx new file mode 100644 index 00000000000..a27b39b07b6 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostStrings.es.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 + + + No se puede mostrar el mensaje porque ya se están ejecutando demasiados mensajes anidados. + + + No se puede procesar el bucle de entrada. Se llamó a ExitCurrentLoop cuando no se estaba ejecutando InputLoops. + + + PS> + + + No se puede iniciar el shell. Error durante la inicialización: + + + No se puede iniciar el shell. Se ha proporcionado un objeto InitialSessionState junto con un argumento -ConfigurationFile. Ambas directivas de configuración no se pueden usar al mismo tiempo. + + + Error que no se controló correctamente. A continuación se muestra información adicional. El proceso de PowerShell se cerrará. + + + ********************** +Inicio de transcripción de PowerShell +Hora de inicio: {0:yyyyMMddHHmmss} +Nombre de usuario : {1}\{2} +Máquina: {3}({4}) +********************** + + + ********************** +Fin de transcripción de PowerShell +Hora de finalización: {0:yyyyMMddHHmmss} +********************** + + + No se pudo ejecutar el comando "{0}" porque algunos complementos de PowerShell no se cargaron. + + + El comando "{0}" no se ejecutó porque la sesión en la que estaba previsto ejecutarse estaba cerrada o interrumpida + + + Entrando en modo de depuración. Usar h o ? para obtener ayuda. + + + Acierto {0} + + + {0}:{1,-3} {2} + + + +La sesión actual no admite la depuración; la ejecución continuará. + + + + + No se puede cargar el módulo PSReadline. La consola se está ejecutando sin PSReadline. + + + Se especificó más de un parámetro de modo de servidor. Los parámetros de modo de servidor deben usarse exclusivamente. + + + La carga de perfiles personales y del sistema tardó {0}ms. + + + Ejecutar como administrador + + + PushRunspace solo puede insertar un espacio de ejecución remoto. + + + El parámetro "{0}" es obligatorio y debe especificarse al usar el parámetro ''{1}". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostUserInterfaceSecurityResources.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostUserInterfaceSecurityResources.es.resx new file mode 100644 index 00000000000..1f37d095ec1 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostUserInterfaceSecurityResources.es.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 + + + Usuario: + + + Contraseña del usuario {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostUserInterfaceStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostUserInterfaceStrings.es.resx new file mode 100644 index 00000000000..f0979e4c48c --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ConsoleHostUserInterfaceStrings.es.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 + + + La colección "{0}" debe tener al menos un elemento. + + + No se puede reconocer "{1}" como debido a un {0} error de desbordamiento. + + + No se puede reconocer "{1}" debido a un {0} error de formato. + + + "{0}" no se puede reconocer como un comando prompt válido. + + + No hay ayuda disponible para {0}. + + + {0}: + + + El campo "{0}" es una matriz de rango cero. + + + "{0}" debe tener al menos un elemento. + + + "{0}" debe ser un índice válido en "{1}" o -1 para que no haya ninguna opción predeterminada. + + + "{0}" debe ser un índice válido en "{1}". "{2}" no es un índice válido. + + + Ayuda + + + Se canceló la solicitud. + + + No se puede procesar la tecla activa porque no se puede usar un signo de interrogación ("?") como tecla activa. + + + No se puede mostrar el mensaje de "{0}" porque no se puede cargar el tipo "{1}". + + + El valor de '{0}' no puede ser de tipo NULL ni estar vacío. + + + "{0}" no puede ser null. + + + (Escriba !? para obtener ayuda.) + + + (el valor predeterminado es "{0}"): + + + (el valor predeterminado es "{0}") + + + (las opciones predeterminadas son {0}) + + + Opción[{0}]: + + + DEPURACIÓN: {0} + + + DETALLADO: {0} + + + ADVERTENCIA: {0} + + + PowerShell está en modo NonInteractive. La funcionalidad de lectura y petición de mensajes no está disponible. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ManagedEntranceStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ManagedEntranceStrings.es.resx new file mode 100644 index 00000000000..9981769419d --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ManagedEntranceStrings.es.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} + + + [Modo de lenguaje restringido] + + + [Modo auditoría de lenguaje restringido: sin restricciones] + + + [Modo sin lenguaje] + + + [Modo de lenguaje restringido] + + + {1} Ya está disponible una nueva versión en versión preliminar de PowerShell: v{0} {2} + {1} Actualice ahora o consulte la página de la versión en:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Ya está disponible una nueva versión estable de PowerShell: v{0} {2} + {1} Actualice ahora o consulte la página de la versión en:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Ya está disponible una nueva versión LTS de PowerShell: v{0} {2} + {1} Actualice ahora o consulte la página de la versión en:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Uso: 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 | -? | /? + +Ayuda en pantalla de PowerShell https://aka.ms/powershell-docs + +Ningún parámetro distingue entre mayúsculas y minúsculas. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/ProgressNodeStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ProgressNodeStrings.es.resx new file mode 100644 index 00000000000..8298849cfe5 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/ProgressNodeStrings.es.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} restantes. + + + {0} actividad no mostrada... + + + {0} actividades no mostradas... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/es/TranscriptStrings.es.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/es/TranscriptStrings.es.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/es/TranscriptStrings.es.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/CommandLineParameterParserStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/CommandLineParameterParserStrings.fr.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/CommandLineParameterParserStrings.fr.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleControlStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleControlStrings.fr.resx new file mode 100644 index 00000000000..4ed58eaec53 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleControlStrings.fr.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 + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de l'ajout d'un gestionnaire d'interruption. Contactez Support Microsoft Services. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la tentative de suppression d'un gestionnaire d'interruption. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la récupération des données concernant le descripteur de console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la récupération du handle du tampon de sortie de la console active. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de l'obtention du mode console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la configuration du mode console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la lecture des caractères du tampon d'entrée de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la lecture des enregistrements d'entrée à partir du tampon d'entrée de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la lecture du contenu du tampon d'entrée de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la récupération du nombre d'événements dans la mémoire tampon d'entrée de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la vidange du tampon d'entrée de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la récupération des informations du tampon de sortie de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la définition de la taille du tampon de sortie de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de l'écriture dans le tampon de sortie de la console. Contactez le service d'assistance clientèle de Microsoft. + + + Erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la lecture du tampon de sortie de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors du remplissage du tampon de sortie de la console avec des caractères. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors du remplissage du tampon de sortie de la console avec des attributs. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors du défilement du tampon de sortie de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la définition des informations de la fenêtre de console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de l'obtention de la plus grande taille de fenêtre de console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la définition du titre de la fenêtre de console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de l'écriture dans le tampon de sortie de la console à la position actuelle du curseur. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la définition des attributs de caractères pour la mémoire tampon de sortie de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la récupération des informations du curseur. Contactez le service d'assistance clientèle de Microsoft. + + + Erreur interne Win32 "{0}" 0x{1:X} lors de la définition des informations du curseur. Contactez le support technique Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de la récupération des informations de police de la console. Contactez le service d'assistance clientèle de Microsoft. + + + L'erreur interne Win32 "{0}" 0x{1:X} s'est produite lors de l'envoi de l'entrée clavier. Contactez le service d'assistance clientèle de Microsoft. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostRawUserInterfaceStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostRawUserInterfaceStrings.fr.resx new file mode 100644 index 00000000000..a18e86eb455 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostRawUserInterfaceStrings.fr.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 + + + Nous ne pouvons pas traiter l’opération, car la coordonnée fournie n’est pas valide. Spécifiez une coordonnée dans la zone de la mémoire tampon de {0}. + + + Nous ne pouvons pas définir la taille de la mémoire tampon, car la taille spécifiée est trop grande ou trop petite. + + + Nous ne pouvons pas définir la couleur de la console, car la valeur spécifiée n’est pas valide. Indiquez une couleur valide telle que définie par le type System.ConsoleColor. + + + Nous ne pouvons pas traiter CursorSize, car la taille du curseur spécifiée n’est pas valide. + + + Nous ne pouvons pas lire les options de touche. Si vous souhaitez lire les options, définissez l’une ou les deux options suivantes : IncludeKeyDown, IncludeKeyUp. + + + {0} doit être supérieur ou égal à {1}. + + + Nous ne pouvons pas utiliser la position X (colonne) de la fenêtre spécifiée, car elle dépasse la largeur de la mémoire tampon d’écran. Indiquez une autre position X, en commençant par 0 pour la colonne la plus à gauche de la mémoire tampon. + + + Nous ne pouvons pas utiliser la position Y (ligne) de la fenêtre spécifiée, car elle dépasse la hauteur de la mémoire tampon d’écran. Indiquez une autre position Y, en commençant par 0 pour la ligne la plus haute de la mémoire tampon. + + + La largeur de la fenêtre ne peut pas être inférieure à 1. + + + La hauteur de la fenêtre doit être au moins égale à 1. + + + Une fenêtre ne peut pas être plus large que la mémoire tampon de l’écran. + + + Une fenêtre ne peut pas être plus grande que la mémoire tampon de l’écran. + + + La fenêtre ne peut pas être plus large que {0}. + + + La fenêtre ne peut pas être plus grande que {0}. + + + La taille de la fenêtre est trop étroite. + + + La taille de la fenêtre est trop courte. + + + Un titre de fenêtre ne peut pas être vide. + + + Le titre de fenêtre ne peut pas dépasser {0} caractères. + + + Administrateur : + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostStrings.fr.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostStrings.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostUserInterfaceSecurityResources.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostUserInterfaceSecurityResources.fr.resx new file mode 100644 index 00000000000..20d086475d7 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostUserInterfaceSecurityResources.fr.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}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostUserInterfaceStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostUserInterfaceStrings.fr.resx new file mode 100644 index 00000000000..ce2309bd106 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ConsoleHostUserInterfaceStrings.fr.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 + + + La collection « {0} »doit contenir au moins un élément. + + + Nous ne pouvons pas reconnaître « {1} » en tant que {0} en raison d’une erreur de dépassement. + + + Nous ne pouvons pas reconnaître « {1} » en tant que {0} en raison d’une erreur de format. + + + « {0} » ne peut pas être reconnu comme une commande d’invite valide. + + + Aucune aide n’est disponible pour {0}. + + + {0} : + + + Le champ « {0} » est un tableau de rang zéro. + + + « {0} » doit comporter au moins un élément. + + + « {0} » doit être un index valide dans « {1} » ou -1 pour aucun choix par défaut. + + + « {0} » doit être un index valide dans « {1} ». « {2} » n’est pas un index valide. + + + [?] Aide + + + La requête a été annulée. + + + Nous ne pouvons pas traiter la touche d’accès rapide, car un point d’interrogation (« ? ») ne peut pas être utilisé comme touche d’accès rapide. + + + Nous ne pouvons pas d’afficher la requête pour « {0} » car le type « {1} » ne peut pas être chargé. + + + « {0} » ne peut pas être NULL ou vide. + + + « {0} » ne peut pas avoir une valeur nulle. + + + (Tapez !? pour obtenir de l’aide.) + + + (la valeur par défaut est « {0} ») : + + + (la valeur par défaut est « {0} ») + + + (les choix par défaut sont {0}) + + + Choix[{0}] : + + + DÉBOGUER : {0} + + + DÉTAILLÉ : {0} + + + AVERTISSEMENT : {0} + + + PowerShell est en mode NonInteractive. Les fonctionnalités de lecture et de requête ne sont pas disponibles. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ManagedEntranceStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ManagedEntranceStrings.fr.resx new file mode 100644 index 00000000000..056812d80d6 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ManagedEntranceStrings.fr.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} + + + [Mode de langue contrainte] + + + [Mode AUDIT du langage contraint : Aucune restriction] + + + [Aucun mode de langue] + + + [Mode de langage restreint] + + + {1} Une nouvelle version de préversion de PowerShell est disponible : v{0} {2} + {1} Mettez à niveau maintenant ou consultez la page de publication à l’adresse suivante :{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Une nouvelle version stable de PowerShell est disponible : v{0} {2} + {1} Mettez à niveau maintenant ou consultez la page de publication à l’adresse suivante :{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Une nouvelle version LTS de PowerShell est disponible : v{0} {2} + {1} Mettez à niveau maintenant ou consultez la page de publication à l’adresse suivante :{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Utilisation : 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 | -? | /? + +Aide en ligne PowerShell https://aka.ms/powershell-docs + +Tous les paramètres ne tiennent pas compte de la casse. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ProgressNodeStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ProgressNodeStrings.fr.resx new file mode 100644 index 00000000000..609ec701175 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/ProgressNodeStrings.fr.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 + + + Il reste {0} {1}. + + + L’activité {0} n’est pas affichée... + + + Les activités {0} ne sont pas affichées... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/fr/TranscriptStrings.fr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/TranscriptStrings.fr.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/fr/TranscriptStrings.fr.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/CommandLineParameterParserStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/CommandLineParameterParserStrings.it.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/CommandLineParameterParserStrings.it.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleControlStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleControlStrings.it.resx new file mode 100644 index 00000000000..8b9c7b4bfab --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleControlStrings.it.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 + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'aggiunta di un gestore di interruzioni. Contattare il Supporto tecnico Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il tentativo di rimozione di un gestore di interruzioni. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero delle informazioni sull'handle della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero dell'handle del buffer di output della console attiva. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero della modalità console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'impostazione della modalità console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante la lettura dei caratteri dal buffer di input della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante la lettura dei record di input dal buffer di input della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante la lettura del contenuto del buffer di input della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero del numero di eventi nel buffer di input della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante lo svuotamento del buffer di input della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero delle informazioni sul buffer di output della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'impostazione delle dimensioni del buffer di output della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante la scrittura nel buffer di output della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante la lettura del buffer di output della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il riempimento del buffer di output della console con i caratteri. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il riempimento del buffer di output della console con gli attributi. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante lo scorrimento del buffer di output della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'impostazione delle informazioni sulla finestra della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero delle dimensioni massime della finestra della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'impostazione del titolo della finestra della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante la scrittura nel buffer di output della console nella posizione corrente del cursore. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'impostazione degli attributi dei caratteri per il buffer di output della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero delle informazioni sul cursore. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'impostazione delle informazioni sul cursore. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante il recupero delle informazioni sui tipi di carattere della console. Contattare il Servizio Assistenza clienti Microsoft. + + + Si è verificato l'errore interno Win32 "{0}" 0x{1:X} durante l'invio dell'input da tastiera. Contattare il Servizio Assistenza clienti Microsoft. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostRawUserInterfaceStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostRawUserInterfaceStrings.it.resx new file mode 100644 index 00000000000..130dc64b2d8 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostRawUserInterfaceStrings.it.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 + + + Non è possibile elaborare l'operazione perché la coordinata specificata non è valida. Specificare una coordinata all'interno dell'area del buffer di {0}. + + + Non è possibile impostare le dimensioni del buffer perché quelle specificate sono troppo grandi o troppo piccole. + + + Non è possibile impostare il colore della console perché il valore specificato non è valido. Specificare un colore valido come definito dal tipo System.ConsoleColor. + + + Non è possibile elaborare CursorSize perché la dimensione del cursore specificata non è valida. + + + Non è possibile leggere le opzioni dei tasti. Per leggere le opzioni, impostare uno o entrambi i seguenti valori: IncludeKeyDown, IncludeKeyUp. + + + {0} deve essere maggiore o uguale a {1}. + + + Non è possibile usare la posizione della finestra X (colonna) specificata perché si estende oltre la larghezza del buffer dello schermo. Specificare un'altra posizione X, partendo da 0 come colonna più a sinistra del buffer. + + + Non è possibile usare la posizione della finestra Y (riga) specificata perché si estende oltre la l'altezza del buffer dello schermo. Specificare un'altra posizione Y, partendo da 0 come riga più alta del buffer. + + + La larghezza della finestra non può essere minore di 1. + + + L'altezza della finestra deve essere almeno 1. + + + La finestra non può essere più larga del buffer dello schermo. + + + La finestra non può essere più alta del buffer dello schermo. + + + La finestra non può essere più larga di {0}. + + + La finestra non può essere più alta di {0}. + + + Le dimensioni della finestra sono insufficienti. + + + L'altezza della finestra è insufficiente. + + + Il titolo della finestra non può essere vuoto. + + + Il titolo della finestra non può superare i {0} caratteri. + + + Amministratore: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostStrings.it.resx new file mode 100644 index 00000000000..935395c3fb9 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostStrings.it.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 + + + Non è possibile visualizzare la richiesta perché sono già in esecuzione troppi prompt annidati. + + + Non è possibile elaborare il ciclo di input. ExitCurrentLoop è stato chiamato quando non era in esecuzione alcun InputLoops. + + + PS> + + + Non è possibile avviare la shell. Errore durante l'inizializzazione: + + + Non è possibile avviare la shell. È stato fornito un oggetto InitialSessionState insieme a un argomento -ConfigurationFile. Entrambe le direttive di configurazione non possono essere usate contemporaneamente. + + + Si è verificato un errore che non è stato gestito correttamente. Di seguito sono riportate informazioni aggiuntive. Il processo di PowerShell verrà chiuso. + + + ********************** +Avvio della trascrizione di PowerShell +Ora di inizio: {0:yyyyMMddHHmmss} +Nome utente : {1}\{2} +Computer : {3} ({4}) +********************** + + + ********************** +Fine della trascrizione di PowerShell +Ora di fine: {0:yyyyMMddHHmmss} +********************** + + + Non è possibile eseguire il comando ''{0}'' perché alcuni snap-in di PowerShell non sono stati caricati. + + + Il comando ''{0}'' non è stato eseguito perché la sessione in cui era destinata all'esecuzione è stata chiusa o interrotta + + + Attivazione della modalità di debug. Usare h o ? per assistenza. + + + Riscontri {0} + + + {0}:{1,-3} {2} + + + +La sessione corrente non supporta il debug; l'esecuzione continuerà. + + + + + Non è possibile caricare il modulo PSReadline. La console è in esecuzione senza PSReadline. + + + È stato specificato più di un parametro della modalità server. I parametri della modalità server devono essere utilizzati esclusivamente. + + + Il caricamento dei profili personali e di sistema ha richiesto {0} ms. + + + Esegui come amministratore + + + PushRunspace può eseguire il push solo di uno spazio di esecuzione remoto. + + + Il parametro ''{0}'' è obbligatorio e deve essere specificato quando si utilizza il parametro ''{1}''. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostUserInterfaceSecurityResources.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostUserInterfaceSecurityResources.it.resx new file mode 100644 index 00000000000..58f0c1b9413 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostUserInterfaceSecurityResources.it.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 + + + Utente: + + + Password per l'utente {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostUserInterfaceStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostUserInterfaceStrings.it.resx new file mode 100644 index 00000000000..d64e003b729 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ConsoleHostUserInterfaceStrings.it.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 + + + La raccolta "{0}" deve contenere almeno un elemento. + + + Non è possibile riconoscere "{1}" come {0} a causa di un errore di overflow. + + + Non è possibile riconoscere "{1}" come {0} a causa di un errore di formato. + + + "{0}" non può essere riconosciuto come comando Prompt valido. + + + Nessuna Guida è disponibile per {0}. + + + {0}: + + + Il campo "{0}" è una matrice di rango zero. + + + "{0}" deve avere almeno un elemento. + + + "{0}" deve essere un indice valido in "{1}" o -1 se non è stata scelta alcuna opzione predefinita. + + + "{0}" deve essere un indice valido in "{1}". "{2}" non è un indice valido. + + + [?] Guida + + + Il prompt è stato annullato. + + + Non è possibile elaborare il tasto di scelta rapida perché il punto interrogativo ("?") non può essere usato come tasto di scelta rapida. + + + Non è possibile visualizzare il prompt per "{0}" perché il tipo "{1}" non può essere caricato. + + + "{0}" non può essere Null o vuoto. + + + "{0}" non può essere Null. + + + (Digitare !? per la Guida). + + + (l'impostazione predefinita è ''{0}''): + + + (l'impostazione predefinita è ''{0}'') + + + (le opzioni predefinite sono {0}) + + + Opzione[{0}]: + + + DEBUG: {0} + + + DETTAGLIATO: {0} + + + AVVISO: {0} + + + PowerShell è in modalità NonInteractive. Le funzionalità Read e Prompt non sono disponibili. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ManagedEntranceStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ManagedEntranceStrings.it.resx new file mode 100644 index 00000000000..30e1026d966 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ManagedEntranceStrings.it.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} + + + [Modalità linguaggio con restrizioni] + + + [Modalità di controllo linguaggio con restrizioni: nessuna restrizione] + + + [Nessuna modalità di linguaggio] + + + [Modalità linguaggio con restrizioni] + + + {1} È disponibile una nuova versione di anteprima di PowerShell: v{0} {2} + {1} Aggiorna ora oppure consulta la pagina della versione all'indirizzo:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} È disponibile una nuova versione stabile di PowerShell: v{0} {2} + {1} Aggiorna ora oppure consulta la pagina della versione all'indirizzo:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} È disponibile una nuova versione LTS di PowerShell: v{0} {2} + {1} Aggiorna ora oppure consulta la pagina della versione all'indirizzo:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Utilizzo: 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 | -? | /? + +Guida in linea di PowerShell https://aka.ms/powershell-docs + +Tutti i parametri non fanno distinzione tra maiuscole e minuscole. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/ProgressNodeStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ProgressNodeStrings.it.resx new file mode 100644 index 00000000000..e6e9c785fc6 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/ProgressNodeStrings.it.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} rimanenti. + + + {0} attività non visualizzata... + + + {0} attività non visualizzate... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/it/TranscriptStrings.it.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/it/TranscriptStrings.it.resx new file mode 100644 index 00000000000..e809664bd64 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/it/TranscriptStrings.it.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 + + + Trascrizione avviata, il file di output è {0} + + + Trascrizione interrotta, il file di output è {0} + + + Non è possibile avviare la trascrizione a causa dell'errore: {0} + + + Il provider corrente ({0}) non può aprire un file. + + + Il file {0} è in sola lettura. Non è possibile scrivere in questo file. "Start-Transcript -Force" cancellerà l'attributo di sola lettura. + + + Non è possibile eseguire l'operazione perché il percorso è stato risolto in più di un file. Questo comando non può operare su più file. + + + Il file {0} esiste già e {1} è stato specificato. + + + Si è verificato un errore durante l'arresto della trascrizione: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/CommandLineParameterParserStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/CommandLineParameterParserStrings.ja.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/CommandLineParameterParserStrings.ja.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleControlStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleControlStrings.ja.resx new file mode 100644 index 00000000000..9d972db65ad --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleControlStrings.ja.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 + + + ブレーク ハンドラーを追加するときに、Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft サポート サービスにお問い合わせください。 + + + 中断ハンドラーを削除しようとしているときに、Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール ハンドルに関する入力を取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + アクティブなコンソール出力バッファーのハンドルの取得中に、Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール モードの取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール モードの設定中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール入力バッファーから文字を読み取り中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール入力バッファーからの入力レコードの読み取り中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール入力バッファーの内容の読み取り中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール入力バッファー内のイベント数の取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール入力バッファーのフラッシュ中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファー情報の取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファー サイズの設定中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファーへの書き込み中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファーの読み取り中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファーに文字を入力中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファーに属性を入力中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファーのスクロール中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール ウィンドウ情報の設定中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + 最大のコンソール ウィンドウ サイズの取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール ウィンドウのタイトルの設定中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + 現在のカーソル位置にあるコンソール出力バッファーへの書き込み中に、Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + コンソール出力バッファーの文字属性の設定中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + カーソル情報の取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + カーソル情報の設定中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスにお問い合わせください。 + + + 本体のフォント情報の取得中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + + キーボード入力の送信中に Win32 内部エラー "{0}" 0x{1:X} が発生しました。Microsoft カスタマー サポート サービスに連絡してください。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostRawUserInterfaceStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostRawUserInterfaceStrings.ja.resx new file mode 100644 index 00000000000..cd8946d01fa --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostRawUserInterfaceStrings.ja.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 + + + 指定された座標が無効なため、操作を処理できません。{0} のバッファー領域内の座標を指定してください。 + + + 指定されたサイズが大きすぎるか小さすぎるため、バッファー サイズを設定できません。 + + + 指定された値が無効なため、コンソールの色を設定できません。System.ConsoleColor 型で定義されている有効な色を指定してください。 + + + 指定されたカーソル サイズが無効なため、CursorSize を処理できません。 + + + キー オプションを読み取れません。オプションを読み取るには、IncludeKeyDown、IncludeKeyUp のどちらかまたは両方を設定してください。 + + + {0} は {1} 以上である必要があります。 + + + 指定した Window X (列) の位置は、画面バッファーの幅を超えているため、使用できません。バッファーの左端の列を 0 として、別の X 位置を指定してください。 + + + 指定した Window Y (行) の位置は、画面バッファーの高さを超えているため、使用できません。バッファーの一番上の行を 0 として、別の Y 位置を指定してください。 + + + ウィンドウの幅を 1 未満にすることはできません。 + + + ウィンドウの高さは 1 以上である必要があります。 + + + ウィンドウの幅は画面バッファーを超えられません。 + + + ウィンドウの高さは画面バッファーを超えられません。 + + + ウィンドウの幅は {0} 以下である必要があります。 + + + ウィンドウの高さは {0} を超えられません。 + + + ウィンドウの幅が狭すぎます。 + + + ウィンドウの高さが短すぎます。 + + + ウィンドウのタイトルを空にすることはできません。 + + + ウィンドウのタイトルを {0} 文字より長くすることはできません。 + + + 管理者: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostStrings.ja.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostStrings.ja.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostUserInterfaceSecurityResources.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostUserInterfaceSecurityResources.ja.resx new file mode 100644 index 00000000000..d5bc8352b21 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostUserInterfaceSecurityResources.ja.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 + + + ユーザー: + + + ユーザー {0} のパスワード: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostUserInterfaceStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostUserInterfaceStrings.ja.resx new file mode 100644 index 00000000000..cbf6ecc661d --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ConsoleHostUserInterfaceStrings.ja.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 + + + "{0}" コレクションには、少なくとも 1 つの要素が必要です。 + + + オーバーフロー エラーのため、"{1}" を {0} として認識できません。 + + + 形式エラーのため、"{1}" を {0} として認識できません。 + + + "{0}" は有効な Prompt コマンドとして認識できません。 + + + {0} に関するヘルプはありません。 + + + {0}: + + + フィールド "{0}" はランク 0 の配列です。 + + + "{0}" には少なくとも 1 つの要素が必要です。 + + + "{0}" は "{1}" の有効なインデックスであるか、既定の選択肢がない場合は -1 である必要があります。 + + + "{0}" は "{1}" の有効なインデックスである必要があります。"{2}" は有効なインデックスではありません。 + + + [?] ヘルプ + + + プロンプトはキャンセルされました。 + + + 疑問符 ("?") はホット キーとして使用できないため、ホット キーを処理できません。 + + + 型 "{1}" を読み込めないため、"{0}" のプロンプトを表示できません。 + + + "{0}" を NULL または空にすることはできません。 + + + "{0}" を null 値にすることはできません。 + + + (ヘルプを表示するには、!? と入力してください。) + + + (既定値は "{0}" です): + + + (既定値は "{0}" です) + + + (既定の選択肢は {0}です) + + + 選択肢[{0}]: + + + デバッグ: {0} + + + 詳細: {0} + + + 警告: {0} + + + PowerShell は NonInteractive モードです。Read と Prompt の機能は使用できません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ManagedEntranceStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ManagedEntranceStrings.ja.resx new file mode 100644 index 00000000000..55bd36508d7 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ManagedEntranceStrings.ja.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} + + + [制約付き言語モード] + + + [制約付き言語監査モード : 制限なし] + + + [言語モードなし] + + + [制限付き言語モード] + + + {1} 新しい PowerShell のプレビュー リリースが利用可能です。v{0} {2} + {1} 今すぐアップグレードするか、{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} +のリリース ページを確認してください + + + {1} 新しい PowerShell の安定リリースが利用可能です。v{0} {2} + {1} 今すぐアップグレードするか、{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} +のリリース ページを確認してください + + + {1} 新しい PowerShell LTS リリースが利用可能です。v{0} {2} + {1} 今すぐアップグレードするか、{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} +のリリース ページを確認してください + + + 使用法: 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 オンライン ヘルプ https://aka.ms/powershell-docs + +すべてのパラメーターでは大文字と小文字が区別されません。 + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ProgressNodeStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ProgressNodeStrings.ja.resx new file mode 100644 index 00000000000..23be405a44f --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/ProgressNodeStrings.ja.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} が残っています。 + + + {0} アクティビティが表示されていません... + + + {0} アクティビティが表示されていません... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ja/TranscriptStrings.ja.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/TranscriptStrings.ja.resx new file mode 100644 index 00000000000..d4abb218abc --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ja/TranscriptStrings.ja.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 + + + トランスクリプトが開始されました。出力ファイルは {0} です + + + トランスクリプトが停止しました。出力ファイルは {0} です + + + 次のエラーのため、文字起こしを開始できません: {0} + + + 現在のプロバイダー ({0}) はファイルを開けません。 + + + ファイル {0} は読み取り専用です。このファイルに書き込めません。"Start-Transcript -Force" は読み取り専用属性をクリアします。 + + + パスが複数のファイルに解決されたため、操作を実行できません。このコマンドは、複数のファイルに対して操作することはできません。 + + + ファイル {0} は既に存在し、{1} が指定されました。 + + + 文字起こしの停止中にエラーが発生しました: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/CommandLineParameterParserStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/CommandLineParameterParserStrings.ko.resx new file mode 100644 index 00000000000..318b74b70fc --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/CommandLineParameterParserStrings.ko.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + -Command, -CommandWithArgs 또는 -EncodedCommand로 명령이 이미 지정되었으므로 명령을 처리할 수 없습니다. + + + 필수 매개 변수가 없어서 명령을 처리할 수 없습니다. -Command 뒤에 명령을 지정해야 합니다. + + + 매개 변수 '{0}'을(를) 인식할 수 없습니다. + + + -Command 매개 변수로 '-'를 지정했습니다. -Command에 다른 인수는 허용되지 않습니다. + + + '-'가 -Command의 인수로 지정되었지만 이 프로세스에 대해 표준 입력이 리디렉션되지 않았습니다. + + + OutputFormat 매개 변수에 인수가 제공되지 않아 명령을 실행할 수 없습니다. +이 매개 변수에 대해 다음 형식 중 하나를 지정하세요: +{0} + + + -InputFormat 매개 변수에 인수가 필요하므로 명령을 처리할 수 없습니다. 이 매개 변수에 유효한 형식 인수를 지정하세요. +유효한 형식: +{0} + + + 매개 변수 값이 잘못되어 명령을 처리할 수 없습니다. "{0}"은(는) 유효한 형식이 아닙니다. +유효한 형식: +{1} + + + -EncodedArguments를 사용해 -Command 또는 -EncodedCommand의 인수가 이미 지정되었으므로 명령을 처리할 수 없습니다. + + + -EncodedArguments에는 값이 필요하므로 명령을 처리할 수 없습니다. -EncodedArguments 매개 변수의 값을 지정하세요. + + + File 매개 변수에 파일 경로가 필요하므로 명령을 실행할 수 없습니다. File 매개 변수의 경로를 제공한 후 명령을 다시 시도하세요. + + + -WindowStyle에는 normal, hidden, minimized 또는 maximized 인수가 필요하므로 명령을 처리할 수 없습니다. 이러한 값 중 하나를 지정한 후 다시 시도하세요. + + + -File '{0}' 처리에 실패했습니다. {1} -File 매개 변수에 올바른 경로를 지정하세요. + + + -WindowStyle '{0}'을(를) 처리하지 못했습니다: {1}. + + + 파일에 '.ps1' 확장명이 없어 -File '{0}'을(를) 처리하지 못했습니다. 유효한 PowerShell 스크립트 파일 이름을 지정한 후 다시 시도하세요. + + + '{0}' 인수가 스크립트 파일 이름으로 인식되지 않습니다. 이름의 철자를 확인하거나, 포함된 경로가 올바른지 확인한 후 다시 시도하세요. + + + -EncodedArguments로 지정된 값이 제대로 인코딩되지 않아 명령을 처리할 수 없습니다. 값이 Base64로 인코딩되어야 합니다. + + + -EncodedCommand로 지정된 값이 제대로 인코딩되지 않아 명령을 처리할 수 없습니다. 값이 Base64로 인코딩되어야 합니다. + + + 정책 이름이 없어서 실행 정책을 처리할 수 없습니다. -ExecutionPolicy 뒤에 정책 이름을 지정해야 합니다. + + + -STA와 -MTA가 둘 다 지정되어 명령을 처리할 수 없습니다. -STA 또는 -MTA 중 하나만 지정하세요. + + + -ConfigurationName에는 원격 엔드포인트 구성 이름을 나타내는 인수가 필요하므로 명령을 처리할 수 없습니다. 이 인수를 지정한 후 다시 시도하세요. + + + -ConfigurationFile에는 세션 구성(.pssc) 파일 경로를 나타내는 인수가 필요하므로 명령을 처리할 수 없습니다. 이 인수를 지정한 후 다시 시도하세요. + + + -CustomPipeName에는 사용하려고 하는 파이프 이름을 나타내는 인수가 필요하므로 명령을 처리할 수 없습니다. 이 인수를 지정한 후 다시 시도하세요. + + + 지정한 -CustomPipeName이 너무 길어 명령을 처리할 수 없습니다. 이 플랫폼의 파이프 이름은 최대 {0}자까지 가능합니다. 현재 파이프 이름 '{1}'은(는) {2}자입니다. + + + -SettingsFile에는 파일 경로를 나타내는 인수가 필요하므로 명령을 처리할 수 없습니다. + + + -SettingsFile '{0}' 처리에 실패했습니다: {1}. -SettingsFile 매개 변수에 올바른 경로를 지정하세요. + + + -SettingsFile에 전달된 인수 '{0}'이(가) 없습니다. 기존 json 파일의 경로를 -SettingsFile 매개 변수의 인수로 제공하세요. + + + '{0}' 인수는 잘못되었습니다. 다음을 의미했나요? + + + -WindowStyle 매개 변수는 이 플랫폼에서 지원되지 않습니다. + + + -WorkingDirectory에는 디렉터리 경로를 나타내는 인수가 필요하므로 명령을 처리할 수 없습니다. + + + 매개 변수 -MTA는 이 플랫폼에서 지원되지 않습니다. + + + 매개 변수 -STA는 이 플랫폼에서 지원되지 않습니다. + + + 지정한 인수에 null 요소가 있으면 안 됩니다. + + + ExecutionPolicy 값 '{0}'이(가) 잘못되었습니다. + + + '{0}' 매개 변수에 제공할 인수가 필요합니다. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleControlStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleControlStrings.ko.resx new file mode 100644 index 00000000000..c02a84e63ed --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleControlStrings.ko.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 + + + 중단 핸들러를 추가할 때 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 지원 서비스에 문의하세요. + + + 중단 핸들러를 제거하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 핸들에 대한 입력을 가져오는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 활성 콘솔 출력 버퍼의 핸들을 검색하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 모드를 가져오는 동안 Win32 내부 오류 "{0}% 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 모드를 설정하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 입력 버퍼에서 문자를 읽는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 입력 버퍼에서 입력 레코드를 읽는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 입력 버퍼의 내용을 읽는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 입력 버퍼의 이벤트 수를 가져오는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 입력 버퍼를 플러시하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 출력 버퍼 정보를 가져오는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 출력 버퍼 크기를 설정하는 동안 Win32 내부 오류 "{0}% 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 출력 버퍼에 쓰는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 입력 버퍼를 읽는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 출력 버퍼를 문자로 채우는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 출력 버퍼에 특성으로 채우는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 창 제목을 스크롤하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 모드를 설정하는 동안 Win32 내부 오류 "{0}% 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 가장 큰 콘솔 창 크기를 가져오는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 창 제목을 설정하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 현재 커서 위치에서 콘솔 출력 버퍼에 쓰는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 출력 버퍼의 문자 속성을 설정하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 커서 정보를 가져오는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 커서 정보를 설정하는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 콘솔 글꼴 정보를 가져오는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 키보드 입력을 보내는 동안 Win32 내부 오류 "{0}" 0x{1:X}이(가) 발생했습니다. Microsoft 고객 지원 서비스에 문의하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostRawUserInterfaceStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostRawUserInterfaceStrings.ko.resx new file mode 100644 index 00000000000..25fce18cc90 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostRawUserInterfaceStrings.ko.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 + + + 제공된 좌표가 올바르지 않아 작업을 처리할 수 없습니다. {0}의 버퍼 영역 안에 있는 좌표를 지정합니다. + + + 지정한 크기가 너무 크거나 너무 작아 버퍼 크기를 설정할 수 없습니다. + + + 지정한 값이 올바르지 않아 콘솔 색을 설정할 수 없습니다. System.ConsoleColor 형식에 정의된 유효한 색을 지정합니다. + + + 지정한 커서 크기가 잘못되었으므로 CursorSize를 처리할 수 없습니다. + + + 키 옵션을 읽을 수 없습니다. 옵션을 읽으려면 IncludeKeyDown, IncludeKeyUp 중 하나 또는 둘 다를 설정하세요. + + + {0}은(는) {1}보다 크거나 같아야 합니다. + + + 지정한 Window X(열) 위치는 화면 버퍼의 너비를 벗어나 사용할 수 없습니다. 버퍼의 가장 왼쪽 열을 0으로 하여 다른 X 위치를 지정합니다. + + + 지정한 Window Y(행) 위치는 화면 버퍼의 높이를 벗어나 사용할 수 없습니다. 버퍼의 맨 위 행을 0으로 하여 다른 Y 위치를 지정합니다. + + + 창 너비는 1보다 작을 수 없습니다. + + + 창 높이는 1 이상이어야 합니다. + + + 창 너비는 화면 버퍼보다 클 수 없습니다. + + + 창 높이는 화면 버퍼보다 클 수 없습니다. + + + 창 너비는 {0}보다 클 수 없습니다. + + + 창 높이는 {0}보다 클 수 없습니다. + + + 창 크기가 너무 좁습니다. + + + 창 크기가 너무 짧습니다. + + + 창 제목은 비워 둘 수 없습니다. + + + 창 제목은 {0}자보다 길 수 없습니다. + + + 관리자: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostStrings.ko.resx new file mode 100644 index 00000000000..3587a4e1398 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostStrings.ko.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 + + + 중첩 프롬프트가 너무 많이 실행 중이어서 프롬프트를 표시할 수 없습니다. + + + 입력 루프를 처리할 수 없습니다. 실행 중인 InputLoop가 없을 때 ExitCurrentLoop가 호출되었습니다. + + + PS> + + + 셸을 시작할 수 없습니다. 초기화 중에 오류가 발생했습니다: + + + 셸을 시작할 수 없습니다. InitialSessionState 개체가 -ConfigurationFile 인수와 함께 제공되었습니다. 두 구성 지시문은 동시에 사용할 수 없습니다. + + + 적절하게 처리되지 않은 오류가 발생했습니다. 자세한 내용은 아래에 표시됩니다. PowerShell 프로세스가 종료됩니다. + + + ********************** +PowerShell 기록 시작 +시작 시간: {0:yyyyMMddHHmmss} +사용자 이름 : {1}\{2} +컴퓨터 : {3} ({4}) +********************** + + + ********************** +PowerShell 기록 끝 +종료 시간: {0:yyyyMMddHHmmss} +********************** + + + 일부 PowerShell 스냅인(Snap-In)이 로드되지 않아 명령 '{0}'을(를) 실행할 수 없습니다. + + + 명령 '{0}'을(를) 실행해야 할 세션이 닫혔거나 손상되어 실행되지 않았습니다. + + + 디버그 모드로 들어갑니다. h 또는 ? 사용에 도움이 될 수 있습니다. + + + {0} 적중 + + + {0}:{1,-3} {2} + + + +현재 세션은 디버깅을 지원하지 않습니다. 실행을 계속합니다. + + + + + PSReadline 모듈을 로드할 수 없습니다. 콘솔은 PSReadline 없이 실행됩니다. + + + 서버 모드 매개 변수가 두 개 이상 지정되었습니다. 서버 모드 매개 변수는 하나만 사용해야 합니다. + + + 개인 및 시스템 프로필을 로드하는 데 {0}ms가 걸렸습니다. + + + 관리자 권한으로 실행 + + + PushRunspace는 원격 runspace만 푸시할 수 있습니다. + + + '{0}' 매개 변수는 필수이며 '{1}' 매개 변수를 사용할 때는 반드시 지정해야 합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostUserInterfaceSecurityResources.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostUserInterfaceSecurityResources.ko.resx new file mode 100644 index 00000000000..080a3222ecd --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostUserInterfaceSecurityResources.ko.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 + + + 사용자: + + + 사용자 {0}의 암호: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostUserInterfaceStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostUserInterfaceStrings.ko.resx new file mode 100644 index 00000000000..fd24433ffbf --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ConsoleHostUserInterfaceStrings.ko.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 + + + "{0}" 컬렉션에는 요소가 하나 이상 있어야 합니다. + + + 오버플로 오류로 인해 "{1}"을(를) {0}(으)로 인식할 수 없습니다. + + + 형식 오류로 인해 "{1}"을(를) {0}(으)로 인식할 수 없습니다. + + + "{0}"은(는) 유효한 Prompt 명령으로 인식할 수 없습니다. + + + {0}에 사용할 수 있는 도움말이 없습니다. + + + {0}: + + + "{0}" 필드는 0차원 배열입니다. + + + "{0}"에는 요소가 하나 이상 있어야 합니다. + + + "{0}"은(는) "{1}"의 유효한 인덱스이거나, 기본 선택 항목이 없으면 -1이어야 합니다. + + + "{0}"은(는) "{1}"의 유효한 인덱스여야 합니다. "{2}"은(는) 유효한 인덱스가 아닙니다. + + + [?] 도움말 + + + 프롬프트가 취소되었습니다. + + + 물음표("?")는 바로 가기 키로 사용할 수 없으므로 바로 가기 키를 처리할 수 없습니다. + + + "{0}"의 프롬프트를 표시할 수 없습니다. "{1}" 형식을 로드할 수 없습니다. + + + "{0}"은(는) Null이거나 비워 둘 수 없습니다. + + + “{0}”은(는) null일 수 없습니다. + + + (도움말을 보려면 !?를 입력하세요.) + + + (기본값은 "{0}"입니다.) + + + (기본값은 "{0}"입니다.) + + + (기본 선택 항목은 {0}입니다.) + + + 선택[{0}]: + + + 디버그: {0} + + + 자세한 정보: {0} + + + 경고: {0} + + + PowerShell이 NonInteractive 모드입니다. Read 및 Prompt 기능을 사용할 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ManagedEntranceStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ManagedEntranceStrings.ko.resx new file mode 100644 index 00000000000..854608e0885 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ManagedEntranceStrings.ko.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} + + + [제한된 언어 모드] + + + [제한된 언어 감사 모드: 제한 없음] + + + [언어 없음 모드] + + + [제한된 언어 모드] + + + {1} 새 PowerShell 미리 보기 릴리스(v{0} {2} + {1} )를 사용할 수 있습니다. 지금 업그레이드하거나 다음 링크에서 릴리스 페이지를 확인하세요.{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} 새 PowerShell 안정 릴리스(v{0} {2} + {1} )를 사용할 수 있습니다. 지금 업그레이드하거나 다음 링크에서 릴리스 페이지를 확인하세요.{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} 새 PowerShell LTS 릴리스(v{0} {2} + {1} )를 사용할 수 있습니다. 지금 업그레이드하거나 다음 링크에서 릴리스 페이지를 확인하세요.{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + 사용법: 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 온라인 도움말 https://aka.ms/powershell-docs + +모든 매개 변수는 대/소문자를 구분하지 않습니다. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ProgressNodeStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ProgressNodeStrings.ko.resx new file mode 100644 index 00000000000..3a835272368 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/ProgressNodeStrings.ko.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} 남음. + + + {0} 활동이 표시되지 않습니다... + + + {0} 활동이 표시되지 않습니다... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ko/TranscriptStrings.ko.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/TranscriptStrings.ko.resx new file mode 100644 index 00000000000..695477e62a2 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ko/TranscriptStrings.ko.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 + + + 대화 내용 기록이 시작되었습니다. 출력 파일은 {0}입니다. + + + 대화 내용 기록이 중지되었습니다. 출력 파일은 {0}입니다. + + + 다음 오류로 인해 대화 내용 기록을 시작할 수 없습니다. {0} + + + 현재 공급자({0})는 파일을 열 수 없습니다. + + + 파일 {0}이(가) 읽기 전용 파일입니다. 이 파일에 쓸 수 없습니다. "Start-Transcript -Force"를 사용하면 읽기 전용 특성이 해제됩니다. + + + 경로가 두 개 이상의 파일로 확인되어 작업을 수행할 수 없습니다. 이 명령은 여러 파일에 사용할 수 없습니다. + + + 파일 {0}이(가) 이미 존재하며 {1}이(가) 지정되었습니다. + + + 대화 내용 기록을 중지하는 동안 다음 오류가 발생했습니다. {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/CommandLineParameterParserStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/CommandLineParameterParserStrings.pl.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/CommandLineParameterParserStrings.pl.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleControlStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleControlStrings.pl.resx new file mode 100644 index 00000000000..749f190979e --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleControlStrings.pl.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 + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas dodawania procedury obsługi przerwania. Skontaktuj się z pomocą techniczną firmy Microsoft w celu uzyskania pomocy. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas próby usunięcia procedury obsługi przerwania. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania danych wejściowych dotyczących dojścia konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania dojścia do aktywnego buforu danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas uzyskiwania trybu konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas ustawiania trybu konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas odczytywania znaków z buforu danych wejściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas odczytywania rekordów danych wejściowych z buforu danych wejściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas odczytywania zawartości buforu danych wejściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania liczby zdarzeń w buforze danych wejściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas opróżniania buforu danych wejściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania informacji o buforze danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas ustawiania rozmiaru buforu danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas zapisywania w buforze danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny win32 „{0}” 0x{1:X} podczas odczytywania buforu danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas wypełniania buforu danych wyjściowych konsoli znakami. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas wypełniania buforu danych wyjściowych konsoli atrybutami. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas przewijania buforu danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas ustawiania informacji o oknie konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania największego rozmiaru okna konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas ustawiania tytułu okna konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas zapisywania w buforze danych wyjściowych konsoli w bieżącym położeniu kursora. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas ustawiania atrybutów znaków dla buforu danych wyjściowych konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania informacji o kursorze. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas ustawiania informacji o kursorze. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas pobierania informacji o czcionce konsoli. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Wystąpił błąd wewnętrzny Win32 „{0}” 0x{1:X} podczas wysyłania danych wejściowych klawiatury. Skontaktuj się z pomocą techniczną firmy Microsoft. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostRawUserInterfaceStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostRawUserInterfaceStrings.pl.resx new file mode 100644 index 00000000000..9ac331ca2c3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostRawUserInterfaceStrings.pl.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 + + + Nie można przetworzyć operacji, ponieważ podana współrzędna jest nieprawidłowa. Określ współrzędną znajdującą się w obszarze buforu {0}. + + + Nie można ustawić rozmiaru buforu, ponieważ określony rozmiar jest za duży lub za mały. + + + Nie można ustawić koloru konsoli, ponieważ określona wartość jest nieprawidłowa. Określ prawidłowy kolor zdefiniowany przez typ System.ConsoleColor. + + + Nie można przetworzyć elementu CursorSize, ponieważ określony rozmiar kursora jest nieprawidłowy. + + + Nie można odczytać opcji klawisza. Aby odczytać opcje, ustaw jedną lub obie z następujących wartości: IncludeKeyDown, IncludeKeyUp. + + + Wartość {0} powinna być większa lub równa {1}. + + + Nie można użyć określonej pozycji X okna (kolumny), ponieważ wykracza ona poza szerokość buforu ekranu. Określ inną pozycję X, zaczynając od 0 jako skrajnej lewej kolumny buforu. + + + Nie można użyć określonej pozycji okna Y (wiersz), ponieważ wykracza poza wysokość buforu ekranu. Określ inną pozycję Y, zaczynając od 0 jako najwyższego wiersza buforu. + + + Szerokość okna nie może być mniejsza niż 1. + + + Wysokość okna musi wynosić co najmniej 1. + + + Okno nie może być szersze niż bufor ekranu. + + + Okno nie może być wyższe niż bufor ekranu. + + + Okno nie może być szersze niż {0}. + + + Okno nie może być wyższe niż {0}. + + + Rozmiar okna jest zbyt wąski. + + + Rozmiar okna jest za mały. + + + Tytuł okna nie może być pusty. + + + Długość tytułu okna nie może przekraczać {0} znaków. + + + Administrator: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostStrings.pl.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostStrings.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostUserInterfaceSecurityResources.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostUserInterfaceSecurityResources.pl.resx new file mode 100644 index 00000000000..56fc10cb8fe --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostUserInterfaceSecurityResources.pl.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 + + + Użytkownik: + + + Hasło użytkownika {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostUserInterfaceStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostUserInterfaceStrings.pl.resx new file mode 100644 index 00000000000..c0e18ff3e83 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ConsoleHostUserInterfaceStrings.pl.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 + + + Kolekcja „{0}” musi mieć co najmniej jeden element. + + + Nie można rozpoznać „{1}” jako {0} z powodu błędu przepełnienia. + + + Nie można rozpoznać „{1}” jako {0} z powodu błędu formatu. + + + Nie można rozpoznać „{0}” jako prawidłowego polecenia Prompt. + + + Brak dostępnej pomocy dla {0}. + + + {0}: + + + Pole „{0}” jest tablicą o randze zerowej. + + + Element „{0}” powinien mieć co najmniej jeden element. + + + „{0}” musi być prawidłowym indeksem w „{1}” lub -1 w przypadku braku opcji domyślnej. + + + „{0}” musi być prawidłowym indeksem w „{1}”. „{2}” nie jest prawidłowym indeksem. + + + [?] Pomoc + + + Monit został anulowany. + + + Nie można przetworzyć klawisza skrótu, ponieważ znak zapytania ("?") nie może być użyty jako klawisz skrótu. + + + Nie można wyświetlić monitu dla „{0}”, ponieważ nie można załadować typu „{1}”. + + + Argument „{0}” nie może mieć wartości null ani nie może być pusty. + + + Wartość „{0}” nie może mieć wartości null. + + + (Aby uzyskać Pomoc, wpisz !?). + + + (wartość domyślna to „{0}”): + + + (wartość domyślna to „{0}”) + + + (domyślne opcje to {0}) + + + Wybór[{0}]: + + + DEBUGOWANIE: {0} + + + PEŁNE INFORMACJE: {0} + + + OSTRZEŻENIE: {0} + + + Program PowerShell działa w trybie nieinteraktywnym. Funkcje Read i Prompt są niedostępne. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ManagedEntranceStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ManagedEntranceStrings.pl.resx new file mode 100644 index 00000000000..baea9a4881e --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ManagedEntranceStrings.pl.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} + + + [Tryb z ograniczonym językiem] + + + [Tryb AUDYTU języka z ograniczeniami: brak ograniczeń] + + + [Brak trybu języka] + + + [Tryb języka z ograniczeniami] + + + {1} Dostępna jest nowa wersja zapoznawcza programu PowerShell: v{0} {2} + {1} Zaktualizuj teraz albo sprawdź stronę wydania pod adresem:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Dostępna jest nowa stabilna wersja programu PowerShell: v{0} {2} + {1} Zaktualizuj teraz albo sprawdź stronę wydania pod adresem:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Dostępna jest nowa wersja LTS programu PowerShell: v{0} {2} + {1} Zaktualizuj teraz albo sprawdź stronę wydania pod adresem:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Sposób użycia: 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 {Tekst | XML}] + [-Interactive] [-MTA] [-NoExit] [-NoLogo] [-NonInteractive] [-NoProfile] + [-NoProfileLoadTime] [-OutputFormat {Text | XML}] + [-SettingsFile <filePath>] [-SSHServerMode] [-STA] + [-Version] [-WindowStyle <style>] + [-WorkingDirectory <directoryPath>] + + pwsh[.exe] -h | -Help | -? | /? + +Pomoc online programu PowerShell https://aka.ms/powershell-docs + +Wszystkie parametry nie rozróżniają wielkości liter. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ProgressNodeStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ProgressNodeStrings.pl.resx new file mode 100644 index 00000000000..26f138a0486 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/ProgressNodeStrings.pl.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 + + + Pozostało {0}{1}. + + + {0} aktywność nie jest wyświetlana... + + + {0} aktywności nie są wyświetlane... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pl/TranscriptStrings.pl.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/TranscriptStrings.pl.resx new file mode 100644 index 00000000000..97c5f3e7d4b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pl/TranscriptStrings.pl.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 + + + Rozpoczęto transkrypcję, plik wyjściowy to {0} + + + Transkrypcja zatrzymana, plik wyjściowy jest {0} + + + Nie można rozpocząć transkrypcji z powodu błędu: {0} + + + Bieżący dostawca ({0}) nie może otworzyć pliku. + + + Plik {0} jest tylko do odczytu. Nie można zapisać w tym pliku. Polecenie „Start-Transcript -Force” spowoduje usunięcie atrybutu tylko do odczytu. + + + Nie można wykonać operacji, ponieważ ścieżka wskazuje na więcej niż jeden plik. To polecenie nie może działać na wielu plikach. + + + Plik {0} już istnieje i określono {1}. + + + Wystąpił błąd podczas zatrzymywania transkrypcji: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/CommandLineParameterParserStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/CommandLineParameterParserStrings.pt-BR.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/CommandLineParameterParserStrings.pt-BR.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleControlStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleControlStrings.pt-BR.resx new file mode 100644 index 00000000000..d751e265e5a --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleControlStrings.pt-BR.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 + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao adicionar um manipulador de interrupção. Entre em contato com os Serviços de Suporte da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao tentar remover um manipulador de interrupção. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter informações sobre o identificador do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao recuperar o identificador do buffer de saída do console ativo. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter o modo do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao definir o modo do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao ler caracteres do buffer de entrada do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao ler registros de entrada do buffer de entrada do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao ler o conteúdo do buffer de entrada do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter o número de eventos no buffer de entrada do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao liberar o buffer de entrada do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter informações do buffer de saída do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao definir o tamanho do buffer de saída do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao gravar no buffer de saída do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao ler o buffer de saída do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao preencher o buffer de saída do console com caracteres. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao preencher o buffer de saída do console com atributos. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao rolar o buffer de saída do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao definir as informações da janela do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter o maior tamanho da janela do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao definir o título da janela do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao gravar no buffer de saída do console na posição atual do cursor. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao definir atributos de caractere para o buffer de saída do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter informações do cursor. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao definir as informações do cursor. Entre em contato com os Serviços de Suporte ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao obter informações sobre a fonte do console. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + + O erro interno do Win32 "{0}" 0x{1:X} ocorreu ao enviar entrada de teclado. Entre em contato com os Serviços de Atendimento ao Cliente da Microsoft. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostRawUserInterfaceStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostRawUserInterfaceStrings.pt-BR.resx new file mode 100644 index 00000000000..16f445c292b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostRawUserInterfaceStrings.pt-BR.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 + + + Não é possível processar a operação porque a coordenada fornecida não é válida. Especifique uma coordenada dentro da área de buffer de {0}. + + + Não é possível definir o tamanho do buffer porque o tamanho especificado é muito grande ou muito pequeno. + + + Não é possível definir a cor do console porque o valor especificado não é válido. Especifique uma cor válida conforme definido pelo tipo System.ConsoleColor. + + + Não é possível processar CursorSize porque o tamanho do cursor especificado não é válido. + + + Não é possível ler as opções da chave. Para ler as opções, defina uma ou ambas as opções a seguir: IncludeKeyDown, IncludeKeyUp. + + + {0} deve ser maior ou igual a {1}. + + + Não é possível usar a posição da Janela X (coluna) especificada porque ela se estende além da largura do buffer de tela. Especifique outra posição X, começando com 0 como a coluna mais à esquerda do buffer. + + + Não é possível usar a posição da Janela Y (linha) especificada porque ela se estende além da altura do buffer de tela. Especifique outra posição Y, começando com 0 como a linha mais alta do buffer. + + + A largura da janela não pode ser menor que 1. + + + A altura da janela deve ser pelo menos 1. + + + A janela não pode ser maior do que o buffer da tela. + + + A janela não pode ser mais alta do que o buffer de tela. + + + A janela não pode ser maior que {0}. + + + A janela não pode ser mais alta do que {0}. + + + O tamanho da janela é muito estreito. + + + O tamanho da janela é muito curto. + + + O título da janela não pode ficar vazio. + + + O título da janela não pode ter mais de {0} caracteres. + + + Administrador: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostStrings.pt-BR.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostUserInterfaceSecurityResources.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostUserInterfaceSecurityResources.pt-BR.resx new file mode 100644 index 00000000000..21e3f6392b6 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostUserInterfaceSecurityResources.pt-BR.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 + + + Usuário: + + + Senha para usuário {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostUserInterfaceStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostUserInterfaceStrings.pt-BR.resx new file mode 100644 index 00000000000..e30569b8f53 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ConsoleHostUserInterfaceStrings.pt-BR.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 + + + A coleção "{0}" deve ter pelo menos um elemento. + + + Não é possível reconhecer "{1}" como um {0} devido a um erro de estouro. + + + Não é possível reconhecer "{1}" como um {0} devido a um erro de formato. + + + "{0}" não pode ser reconhecido como um comando de Prompt válido. + + + Não há ajuda disponível para {0}. + + + {0}: + + + O campo "{0}" é uma matriz de classificação zero. + + + "{0}" deve ter pelo menos um elemento. + + + "{0}" deve ser um índice válido em "{1}" ou -1 para nenhuma opção padrão. + + + "{0}" deve ser um índice válido em "{1}". "{2}" não é um índice válido. + + + [?] Ajuda + + + O prompt foi cancelado. + + + Não é possível processar a tecla de atalho porque um ponto de interrogação ("?") não pode ser usado como tecla de atalho. + + + Não é possível exibir o prompt para “{0}” porque o tipo “{1}” não pode ser carregado. + + + "{0}" não pode ser nulo ou vazio. + + + "{0}" não pode ser nulo. + + + (Digite !? para obter Ajuda.) + + + (o padrão é "{0}"): + + + (o padrão é "{0}") + + + (as opções padrão são {0}) + + + Escolha[{0}]: + + + DEPURAR: {0} + + + DETALHADO: {0} + + + AVISO: {0} + + + O PowerShell está no modo NonInteractive. A funcionalidade de Leitura e Prompt não está disponível. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ManagedEntranceStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ManagedEntranceStrings.pt-BR.resx new file mode 100644 index 00000000000..813d5baa47c --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ManagedEntranceStrings.pt-BR.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} + + + [Modo de Linguagem Restritiva] + + + [Modo de AUDITORIA de Linguagem Restrita: Sem Restrições] + + + [Modo sem Linguagem] + + + [Modo de Linguagem Restrita] + + + {1} Uma nova versão prévia do PowerShell está disponível: v{0} {2} + {1} Atualize agora ou confira a página da versão em:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Uma nova versão estável do PowerShell está disponível: v{0} {2} + {1} Atualize agora ou confira a página da versão em:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Uma nova versão LTS do PowerShell está disponível: v{0} {2} + {1} Atualize agora ou confira a página da versão em:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Uso: 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 | -? | /? + +Ajuda Online do PowerShell https://aka.ms/powershell-docs + +Todos os parâmetros não diferenciam maiúsculas de minúsculas. + + + + +-File | -f + + Se o valor de File for "-", será feita a leitura do texto do comando a partir da entrada padrão. + Executar "pwsh -File -" sem entrada padrão redirecionada inicia uma sessão + regular. Isso é o mesmo que não especificar o parâmetro File de forma alguma. + + Este é o parâmetro padrão quando não há parâmetros, mas há valores + presente na linha de comando. O script especificado é executado no escopo local + ("dot-sourced"), para que as funções e variáveis que o script + cria fiquem disponíveis na sessão atual. Insira o caminho do arquivo de script + e quaisquer parâmetros. File deve ser o último parâmetro no comando, porque + todos os caracteres digitados após o nome do parâmetro File são interpretados como o + caminho do arquivo de script seguido pelos parâmetros do script. + + Normalmente, os parâmetros de opção de um script são incluídos ou + omitidos. Por exemplo, o comando a seguir usa o parâmetro All do + Get-Script.ps1 arquivo de script: "-File .\Get-Script.ps1 -All" + + Em casos raros, talvez seja necessário fornecer um valor BOOLIANO para um parâmetro + de opção. Para fornecer um valor BOOLIANO para um parâmetro de opção no valor + do parâmetro FILE, use o parâmetro normalmente seguido imediatamente por + dois-pontos e pelo valor booleano, como no exemplo a seguir: + "-File .\Get-Script.ps1 -All:$False". + + Os parâmetros passados para o script são passados como cadeias de caracteres literais, após + a interpretação pelo shell atual. Por exemplo, se você estiver no cmd.exe e + quiser passar um valor de variável de ambiente, você usaria a sintaxe do + cmd.exe: "pwsh -File .\test.ps1 -TestParam %windir%" + + Em contraste, executar "pwsh -File .\test.ps1 -TestParam $env:windir" em + cmd.exe fará com que o script receba a cadeia de caracteres literal "$env:windir" + porque ela não tem um significado especial para o shell cmd.exe atual. O + O estilo de referência de variável de ambiente "$env:windir" pode ser usado dentro de um + parâmetro Command, pois lá ele é interpretado como código do PowerShell. + + Da mesma forma, se você quiser executar o mesmo comando a partir de um script de Lote, + você usaria "%~dp0" em vez de ".\" ou "$PSScriptRoot" para representar o diretório + de execução atual: "pwsh -File %~dp0test.ps1 -TestParam %windir%". Se você + usasse ".\test.ps1", o PowerShell geraria um erro porque ele não consegue + localizar o caminho literal ".\test.ps1". + + Quando o arquivo de script invocado termina com um comando de saída, o + o código de saída do processo é definido como o argumento numérico usado com o comando de saída. Em + caso de encerramento normal, o código de saída é sempre 0. + + Semelhante a -Command, quando ocorre um erro que termina o script, o código de saída + é definido como 1. No entanto, ao contrário de -Command, quando a execução é + interrompida com Ctrl-C, o código de saída é 0. + +-Command | -c + + Executa os comandos especificados (e quaisquer parâmetros) como se fossem + digitados no prompt de comando do PowerShell e, em seguida, encerrados, a menos que o parâmetro NoExit + seja especificado. + + O valor de Command pode ser "-", um bloco de script ou uma cadeia de caracteres. Se o valor + de Command for "-", o texto do comando será lido da entrada padrão. + + O parâmetro Command aceita um bloco de script para execução somente quando consegue + reconhecer o valor passado para Command como um tipo ScriptBlock. Isso só é + possível somente ao executar pwsh de outro processo que hospeda o PowerShell. O tipo ScriptBlock + pode estar contido em uma variável existente, ser retornado de uma expressão, + ou analisado pelo processo que hospeda o PowerShell como um bloco de script literal delimitado por + chaves curvas "{}", antes de ser passado para pwsh. + + pwsh -Command {Get-WinEvent -LogName security} + + No cmd.exe, não existe algo como um bloco de script (ou tipo ScriptBlock), + portanto, o valor passado para Command será sempre uma cadeia de caracteres. Você pode escrever o + bloco de script dentro da cadeia, mas, em vez de ser executado, ele + se comportará exatamente como se você o tivesse digitado em um prompt típico do PowerShell, + imprimindo o conteúdo do bloco de script de volta para você. + + Uma cadeia de caracteres passada para Command ainda é executada como script do PowerShell, portanto, + as chaves do bloco de script geralmente nem são necessárias quando + em execução a partir de cmd.exe. Para executar um bloco de script embutido definido dentro de uma + cadeia de caracteres, pode-se usar o operador de chamada &: + + pwsh -Command "& {Get-WinEvent -LogName security}" + + Se o valor de Command for uma cadeia, Command deverá ser o último parâmetro de + pwsh, pois todos os argumentos posteriores a ele são interpretados como parte do + comando a executar. + + Quando chamado de uma sessão existente do PowerShell, os resultados são + retornados ao shell pai como objetos XML desserializados, não como objetos ativos. + Para outros shells, os resultados são retornados como cadeias de caracteres. + + Se o valor de Command for "-", o texto do comando será lido da entrada + padrão. Você deve redirecionar a entrada padrão ao usar o parâmetro Command + com entrada padrão. Por exemplo: + + @' + "in" + + "olá" | + % { "$_ there" } + + "out" + '@ | powershell -NoProfile -Command - + + Este exemplo produz a seguinte saída: + + in + hi there + out + + O código de saída do processo é determinado pelo status do + comando executado no bloco de script (executado). O código de saída é 0 quando $? é $true ou 1 + quando $? é $false. Se o último comando for um programa externo ou um + Script do PowerShell que defina explicitamente um código de saída diferente de 0 ou 1, + o código de saída será convertido em 1 para o código de saída do processo. Para preservar o + código de saída específico, adicione exit $LASTEXITCODE à cadeia de caracteres do comando ou ao bloco de script. + + Da mesma forma, o valor 1 é retornado quando ocorre um erro de encerramento de script + (erro que encerra o script), como um throw ou -ErrorAction Stop, ocorre + ou quando a execução é interrompida com Ctrl-C. + +-CommandWithArgs | -cwa + + [Experimental] + Executa um comando do PowerShell com argumentos. Ao contrário de `-Command`, esse + parâmetro preenche a variável interna `$args, que pode ser usada pelo + comando. + + A primeira cadeia de caracteres é o comando e as cadeias de caracteres seguintes, separadas por espaços em branco, + são os argumentos. + + Por exemplo: + + pwsh -CommandWithArgs '$args | % { "arg: $_" }' arg1 arg2 + + Este exemplo produz a seguinte saída: + + arg: arg1 + arg: arg2 + +-ConfigurationName | -config + + Especifica um ponto de extremidade de configuração no qual o PowerShell é executado. Esse pode ser + qualquer ponto de extremidade registrado no computador local, incluindo + pontos de extremidade padrão de comunicação remota do PowerShell ou um ponto de extremidade personalizado com capacidades específicas de + função de usuário. + + Exemplo: "pwsh -ConfigurationName AdminRoles" + +-ConfigurationFile + + Especifica o caminho de um arquivo de configuração de sessão (.pssc). A configuração + contida no arquivo de configuração será aplicada à sessão do + PowerShell. + + Exemplo: "pwsh -ConfigurationFile "C:\ProgramData\PowerShell\MyConfig.pssc" + +-CustomPipeName + + Especifica o nome que será usado para um servidor IPC adicional (pipe nomeado) usado + para depuração e outras comunicações entre processos. Este oferece um + mecanismo previsível para se conectar a outras instâncias do PowerShell. + Normalmente usado com o parâmetro CustomPipeName no comando "Enter-PSHostProcess". + + Este parâmetro foi introduzido no PowerShell 6.2. + + Por exemplo: + + # Instância do PowerShell 1 + pwsh -CustomPipeName mydebugpipe + # Instância do PowerShell 2 + Enter-PSHostProcess -CustomPipeName mydebugpipe + +-EncodedCommand | -e | -ec + + Aceita uma versão do comando codificada em Base64 de um comando. Use este parâmetro para + enviar comandos ao PowerShell que exigem aspas complexas e aninhadas. O + A representação em Base64 deve ser uma cadeia de caracteres codificada em UTF-16. + + Por exemplo: + + $command = 'dir "c:\program files" ' + $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) + $encodedCommand = [Convert]::ToBase64String($bytes) + pwsh -encodedcommand $encodedCommand + +-ExecutionPolicy | -ex | -ep + + Define a política de execução padrão para a sessão atual e a salva na + variável de ambiente $env:PSExecutionPolicyPreference. Este parâmetro + não altera as políticas de execução configuradas de forma persistente. + + Este parâmetro aplica-se somente a computadores Windows. A + variável de ambiente $env:PSExecutionPolicyPreference não existe em + plataformas não Windows. + +-InputFormat | -inp | -if + + Descreve o formato dos dados enviados ao PowerShell. Os valores válidos são "Text" + (cadeias de caracteres de texto) ou "XML" (formato CLIXML serializado). + +-Interactive | -i + + Apresente um prompt interativo ao usuário. É o inverso do parâmetro + NonInteractive. + +-Login | -l + + No Linux e macOS, inicia o PowerShell como um shell de logon, usando /bin/sh para + executar perfis de logon, como /etc/profile e ~/.profile. No Windows, + este parâmetro de opçã não faz nada. + + [!IMPORTANT] Este parâmetro deve vir primeiro para iniciar o PowerShell como um shell + de logon. O parâmetro será ignorado se for passado em qualquer outra posição. + + Para configurar o pwsh como o shell de logon em sistemas operacionais semelhantes ao UNIX: + + - Verifique se o caminho absoluto completo para pwsh está listado em /etc/shells + + - Este caminho geralmente é algo como /usr/bin/pwsh no Linux ou + /usr/local/bin/pwsh no macOS + - Com alguns métodos de instalação, esta entrada é adicionada + automaticamente durante a instalação + - Se o pwsh não estiver presente em /etc/shells, use um editor para acrescentar o + caminho para pwsh na última linha. A edição exige privilégios elevados para + editar. + + - Use o utilitário chsh para definir o shell do usuário atual como pwsh: + + chsh -s /usr/bin/pwsh + + [!WARNING] No momento, não há suporte para definir pwsh como o shell de logon no + Subsistema do Windows para Linux (WSL), e tentar definir o pwsh como + shell de logon no WSL pode fazer com que não seja possível iniciar o WSL interativamente. + +-MTA + + Iniciar o PowerShell usando um multi-threaded apartment. Este parâmetro só está + disponível no Windows. + +-NoExit | -noe + + Não encerra o PowerShell após executar os comandos de inicialização. + + Exemplo: "pwsh -NoExit -Command Get-Date" + +-NoLogo | -nol + + Oculta o texto da barra de notificação na inicialização de sessões interativas. + +-NonInteractive | -noni + + Este parâmetro é usado para criar sessões que não devem exigir a entrada do usuário. + Isto é útil para scripts executados em tarefas agendadas ou pipelines de CI/CD. + Todas as tentativas de usar recursos interativos, como 'Read-Host' ou prompts de confirmação, + resultam em erros de término de instrução em vez de ficarem aguardando indefinidamente. + +-NoProfile | -nop + + Não carrega os perfis do PowerShell. + +-NoProfileLoadTime + + Oculta o texto do tempo de carregamento do perfil do PowerShell exibido na inicialização quando esse + tempo ultrapassa 500 milissegundos. + +-OutputFormat | -o | -of + + Determina como a saída do PowerShell é formatada. Os valores válidos são "Text" + (cadeias de caracteres de texto) ou "XML" (formato CLIXML serializado). + + Exemplo: "pwsh -o XML -c Get-Date" + + Quando chamado em uma sessão do PowerShell, você obtém objetos desserializados como + saída, em vez de cadeias de caracteres simples. Quando chamado de outros shells, a saída é + dados de cadeia de caracteres formatados como texto CLIXML. + +-SettingsFile | -settings + + Substitui, para a sessão, o arquivo de configurações + "powershell.config.json". Por padrão, as configurações de todo o sistema são lidas do + "powershell.config.json" no diretório "$PSHOME". + + Observe que essas configurações não são usadas pelo ponto de extremidade especificado pelo + argumento "-ConfigurationName". + + Exemplo: "pwsh -SettingsFile c:\myproject\powershell.config.json" + +-SSHServerMode | -sshs + + Usado em sshd_config para executar o PowerShell como subsistema SSH. Não se + destina a nenhum outro uso, que também não tem suporte. + +-STA + + Iniciar PowerShell usando um single-threaded apartment. Esse é o padrão. + Este parâmetro só está disponível no Windows. + +-Version | -v + + Exibe a versão do PowerShell. Os parâmetros adicionais são ignorados. + +-WindowStyle | -w + + Define o estilo da janela para a sessão. Os valores válidos são Normal, Minimized, + Maximized e Hidden. + +-WorkingDirectory | -wd + + Define o diretório de trabalho inicial executando na inicialização. Há suporte para + qualquer caminho de arquivo válido do PowerShell. + + Para iniciar o PowerShell no diretório inicial, use: pwsh -WorkingDirectory ~ + +-Help, -?, /? + + Exibe a ajuda do pwsh. Se você estiver digitando um comando pwsh no PowerShell, + preceda os parâmetros do comando com um hífen (-), não com uma barra (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ProgressNodeStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ProgressNodeStrings.pt-BR.resx new file mode 100644 index 00000000000..ac7d9c8c173 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/ProgressNodeStrings.pt-BR.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... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/TranscriptStrings.pt-BR.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/TranscriptStrings.pt-BR.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/pt-BR/TranscriptStrings.pt-BR.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/CommandLineParameterParserStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/CommandLineParameterParserStrings.ru.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/CommandLineParameterParserStrings.ru.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleControlStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleControlStrings.ru.resx new file mode 100644 index 00000000000..e5f0a066727 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleControlStrings.ru.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 + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при добавлении обработчика прерывания. Обратитесь за помощью в службу поддержки Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при попытке удалить обработчик прерывания. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении сведений о дескрипторе консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении дескриптора активного буфера вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении режима консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при настройке режима консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при чтении символов из буфера ввода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при чтении записей из буфера ввода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при чтении содержания буфера ввода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении числа событий в буфере ввода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при сбросе буфера ввода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении сведений о буфере вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при настройке размера буфера вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при записи в буфер вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при чтении буфера вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при заполнении буфера вывода консоли символами. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при заполнении буфера вывода консоли атрибутами. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при прокрутке буфера вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при настройке сведений окна консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении наибольшего окна консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при установке заголовка окна консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при записи в буфер вывода консоли в текущей позиции курсора. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при установке атрибутов символов для буфера вывода консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении сведений о курсоре. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при настройке сведений о курсоре. Обратитесь в службу поддержки Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при получении сведений о шрифте консоли. Обратитесь в службу поддержки клиентов Майкрософт. + + + Произошла внутренняя ошибка Win32 {0} 0x{1:X} при отправке ввода с клавиатуры. Обратитесь в службу поддержки клиентов Майкрософт. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostRawUserInterfaceStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostRawUserInterfaceStrings.ru.resx new file mode 100644 index 00000000000..1208a48697f --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostRawUserInterfaceStrings.ru.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 + + + Невозможно обработать операцию, так как переданная координата недопустима. Укажите координату в пределах области буфера {0}. + + + Невозможно задать размер буфера, так как указанный размер слишком велик или слишком мал. + + + Невозможно задать цвет консоли, так как указанное значение недопустимо. Укажите допустимый цвет, определенный типом System.ConsoleColor. + + + Невозможно обработать CursorSize, так как указан недопустимый размер курсора. + + + Не удается прочитать параметры клавиш. Чтобы прочитать параметры, задайте один или оба из следующих параметров: IncludeKeyDown, IncludeKeyUp. + + + Значение {0} должно быть больше или равно {1}. + + + Невозможно использовать указанную позицию окна X (столбец), так как она выходит за ширину буфера экрана. Укажите другую позицию X, начиная со значения 0 для крайнего левого столбца буфера. + + + Невозможно использовать указанную позицию окна Y (строка), так как она выходит за высоту буфера экрана. Укажите другую позицию Y, начиная со значения 0 для верхней строки буфера. + + + Ширина окна не может быть меньше 1. + + + Высота окна должна быть не менее 1. + + + Ширина окна не может превышать ширину буфера экрана. + + + Высота окна не может превышать высоту буфера экрана. + + + Ширина окна не может превышать {0}. + + + Высота окна не может превышать {0}. + + + Окно слишком узкое. + + + Окно слишком короткое. + + + Заголовок окна не может быть пустым. + + + Длина заголовка окна не должна превышать {0} символов. + + + Администратор: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostStrings.ru.resx new file mode 100644 index 00000000000..5cc592d37e0 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostStrings.ru.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 + + + Невозможно отобразить запрос, так как уже выполняется слишком много вложенных запросов. + + + Не удается обработать цикл ввода. Вызывается ExitCurrentLoop, когда не выполняется ни один цикл ввода. + + + PS> + + + Не удается запустить оболочку. Произошел сбой при инициализации: + + + Не удается запустить оболочку. Вместе с аргументом -ConfigurationFile указан объект InitialSessionState. Обе директивы конфигурации нельзя использовать одновременно. + + + Произошла ошибка, которая не была должным образом обработана. Дополнительная информация приведена ниже. Процесс PowerShell будет завершен. + + + ********************** +Начало расшифровки PowerShell +Время начала: {0:yyyyMMddHHmmss} +Имя пользователя: {1}\{2} +Компьютер: {3} ({4}) +********************** + + + ********************** +Завершение расшифровки PowerShell +Время окончания: {0:yyyyMMddHHmmss} +********************** + + + Не удалось выполнить команду "{0}", так как не загружены некоторые оснастки PowerShell. + + + Команда "{0}" не выполнена, так как сеанс, в котором она должна была выполняться, был закрыт или поврежден + + + Переход в режим отладки. Используйте h или ? для справки. + + + Выполнение {0} + + + {0}:{1,-3} {2} + + + +Текущий сеанс не поддерживает отладку; выполнение будет продолжено. + + + + + Не удается загрузить модуль PSReadLine. Консоль работает без PSReadLine. + + + Указано более одного параметра режима сервера. Параметры режима сервера следует использовать только по одному. + + + Загрузка личных и системных профилей заняла {0} мс. + + + Запустить от имени администратора + + + PushRunspace может отправлять только удаленное пространство выполнения. + + + Параметр "{0}" обязателен и должен быть указан при использовании параметра "{1}". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostUserInterfaceSecurityResources.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostUserInterfaceSecurityResources.ru.resx new file mode 100644 index 00000000000..2fcee197506 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostUserInterfaceSecurityResources.ru.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 + + + Пользователь: + + + Пароль для пользователя {0}: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostUserInterfaceStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostUserInterfaceStrings.ru.resx new file mode 100644 index 00000000000..31e455d8b6c --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ConsoleHostUserInterfaceStrings.ru.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 + + + В коллекции "{0}" должен быть по крайней мере один элемент. + + + Не удается распознать "{1}" как {0} из-за ошибки переполнения. + + + Не удается распознать "{1}" как {0} из-за ошибки формата. + + + "{0}" не распознается как допустимая команда запроса. + + + Справка недоступна для {0}. + + + {0}: + + + Поле "{0}" представляет собой массив нулевого ранга. + + + В {0} должен быть указан по меньшей мере один элемент. + + + Значение "{0}" должно быть допустимым индексом в "{1}" или -1, если вариант по умолчанию не задан. + + + "{0}" должен быть допустимым индексом в "{1}". "{2}" не является допустимым индексом. + + + [?] справка + + + Запрос был отменен. + + + Невозможно обработать горячую клавишу, так как вопросительный знак ("?") нельзя использовать в качестве горячей клавиши. + + + Невозможно отобразить запрос для "{0}", так как не удается загрузить тип "{1}". + + + {0} не может быть пустым или иметь значение NULL. + + + "{0}" не может иметь значения null. + + + (Введите !? для справки.) + + + (по умолчанию — "{0}"): + + + (по умолчанию — "{0}") + + + (значения по умолчанию: {0}) + + + Выбор[{0}]: + + + ОТЛАДКА: {0} + + + ПОДРОБНО: {0} + + + ВНИМАНИЕ! {0} + + + PowerShell находится в режиме NonInteractive. Функции чтения и запросов недоступны. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ManagedEntranceStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ManagedEntranceStrings.ru.resx new file mode 100644 index 00000000000..8384c1418dd --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ManagedEntranceStrings.ru.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} + + + [Ограниченный языковой режим] + + + [Режим АУДИТА с ограничением по языку: без ограничений] + + + [Режим без языка] + + + [Ограниченный языковой режим] + + + {1} Доступна новая предварительная версия PowerShell.: v{0} {2} + {1} Обновите сейчас или ознакомьтесь со страницей релиза по адресу:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Доступна новая стабильная версия PowerShell.: v{0} {2} + {1} Обновите сейчас или ознакомьтесь со страницей релиза по адресу::{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Доступна новая версия PowerShell LTS: v{0} {2} + {1} Обновите сейчас или ознакомьтесь со страницей релиза по адресу:{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 + +Все параметры нечувствительны к регистру. + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ProgressNodeStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ProgressNodeStrings.ru.resx new file mode 100644 index 00000000000..c3eb651aa41 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/ProgressNodeStrings.ru.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}. + + + {0} действие не отображается... + + + Действия не отображаются: {0}... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/ru/TranscriptStrings.ru.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/TranscriptStrings.ru.resx new file mode 100644 index 00000000000..ad1aab120e9 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/ru/TranscriptStrings.ru.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 + + + Расшифровка начата, выходной файл — {0} + + + Расшифровка остановлена, выходной файл — {0} + + + Не удается начать транскрипцию из-за ошибки: {0} + + + Текущий поставщик ({0}) не может открыть файл. + + + Файл {0} доступен только для чтения. Не удается записать в этот файл. "Start-Transcript -Force" очистит атрибут только для чтения. + + + Не удается выполнить операцию, так как путь разрешается в несколько файлов. Эта команда не может работать с несколькими файлами. + + + Файл {0} уже существует, и указан {1}. + + + Произошла ошибка при остановке транскрибирования: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/CommandLineParameterParserStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/CommandLineParameterParserStrings.tr.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/CommandLineParameterParserStrings.tr.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleControlStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleControlStrings.tr.resx new file mode 100644 index 00000000000..148f1d156ab --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleControlStrings.tr.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 + + + Bir kesme işleyicisi eklenirken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Desteği ile iletişime geçin. + + + Bir kesme işleyicisi kaldırılmaya çalışılırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol tanıtıcısı hakkında girdi alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Etkin konsol çıktı arabelleğinin tanıtıcısı alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol modu alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol modu ayarlanırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol girdi arabelleğinden karakterler okunurken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol girdi arabelleğinden girdi kayıtları okunurken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol girdi arabelleğinin içeriği okunurken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol girdi arabelleğindeki olay sayısı alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol girdi arabelleği boşaltılırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol çıktı arabelleği bilgileri alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol çıktı arabelleği boyutu ayarlanırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol çıktı arabelleğine yazılırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol çıktı arabelleği okunurken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Desteği ile iletişime geçin. + + + Konsol çıktı arabelleği karakterlerle doldurulurken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Desteği ile iletişime geçin. + + + Konsol çıktı arabelleği özniteliklerle doldurulurken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol çıktı arabelleği kaydırılırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol pencere bilgileri ayarlanırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Desteği ile iletişime geçin. + + + En büyük konsol pencere boyutu alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol pencere başlığı ayarlanırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Mevcut imleç konumunda konsol çıktı arabelleğine yazılırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol çıktı arabelleği için karakter öznitelikleri ayarlanırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + İmleç bilgileri alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + İmleç bilgileri ayarlanırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Konsol yazı tipi bilgileri alınırken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + + Klavye girdisi gönderilirken Win32 iç hatası "{0}" 0x{1:X} oluştu. Microsoft Müşteri Hizmetleri ile iletişime geçin. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostRawUserInterfaceStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostRawUserInterfaceStrings.tr.resx new file mode 100644 index 00000000000..c860e9c4f48 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostRawUserInterfaceStrings.tr.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 + + + İşlem gerçekleştirilemiyor çünkü sağlanan koordinat geçersiz. Arabelleğin {0} alanı içinde bir koordinat belirtin. + + + Belirtilen boyut çok büyük ya da çok küçük olduğundan arabellek boyutu ayarlanamıyor. + + + Belirtilen değer geçerli olmadığından konsol rengi ayarlanmadı. System.ConsoleColor türü tarafından tanımlanan geçerli bir renk belirtin. + + + Belirtilen imleç boyutu geçerli olmadığından CursorSize işlenemedi. + + + Anahtar seçenekleri okunamıyor. Seçenekleri okumak için aşağıdakilerden birini veya her ikisini ayarlayın: IncludeKeyDown, IncludeKeyUp. + + + {0}, {1} değerinden büyük veya ona eşit olmalıdır. + + + Belirtilen Window X (sütun) konumu kullanılamaz çünkü ekran arabelleğinin genişliğini aşıyor. 0'dan başlayarak, arabelleğin en sol sütunu olacak şekilde başka bir X konumu belirtin. + + + Belirtilen Pencere Y (satır) konumu, ekran arabelleğinin yüksekliğini geçediğinden bu konum kullanılamıyor. Arabelleğin en üst satırı olarak 0 ile başlayarak başka bir Y konumu belirtin. + + + Pencere genişliği 1'den küçük olamaz. + + + Pencere yüksekliği en az 1 olmalıdır. + + + Pencere ekran arabelleğinden daha geniş olamaz. + + + Pencere, ekran arabelleğinden daha uzun olamaz. + + + Pencere {0} değerinden daha geniş olamaz. + + + Pencere {0} değerinden daha uzun olamaz. + + + Pencere boyutu çok dar. + + + Pencere boyutu çok kısa. + + + Pencere başlığı boş olamaz. + + + Pencere başlığı {0} karakterden daha uzun olamaz. + + + Yönetici: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostStrings.tr.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostStrings.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostUserInterfaceSecurityResources.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostUserInterfaceSecurityResources.tr.resx new file mode 100644 index 00000000000..02d8e2d6dc6 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostUserInterfaceSecurityResources.tr.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 + + + Kullanıcı: + + + {0} kullanıcısı için parolayı: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostUserInterfaceStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostUserInterfaceStrings.tr.resx new file mode 100644 index 00000000000..f6c034980cb --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ConsoleHostUserInterfaceStrings.tr.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 + + + “{0}" koleksiyonunda en az bir öğe olmalıdır. + + + “{1}" bir {0} olarak, taşma hatası nedeniyle tanınamıyor. + + + Biçim hatası nedeniyle "{1}" değeri {0} olarak tanınamıyor. + + + “{0}" geçerli bir İstem komutu olarak tanınamıyor. + + + {0} için yardım bulunmuyor. + + + {0}: + + + “{0}" alanı sıfır derecelendirmeli bir dizidir. + + + “{0}" en az bir öğe içermelidir. + + + “{0}”, “{1}” içinde geçerli bir indeks veya varsayılan seçim olmaması için -1 olmalıdır. + + + “{0}" geçerli bir seçim için "{1}" içinde geçerli bir dizin olmalıdır. "{2}" geçerli bir dizin değil. + + + [?] Yardım + + + İstem iptal edildi. + + + Soru işareti ("?") sık erişim tuşu olarak kullanılamadığı için sık erişim tuşu işlenemiyor. + + + “{0}" için istem, "{1}" türü yüklenemediği için görüntülenemiyor. + + + "{0}" değeri null veya boş olamaz. + + + “{0}" null olamaz. + + + (Yardım için !? yazın.) + + + (varsayılan "{0}"dur): + + + (varsayılan "{0}"dur) + + + (varsayılan seçenekler {0}) + + + Seçim[{0}]: + + + HATA AYIKLA: {0} + + + AYRINTILI: {0} + + + UYARI: {0} + + + Windows PowerShell, Etkileşimli Olmayan modda. Okuma ve İstem işlevi kullanılamıyor. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ManagedEntranceStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ManagedEntranceStrings.tr.resx new file mode 100644 index 00000000000..f599e03974c --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ManagedEntranceStrings.tr.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} + + + [Kısıtlı Dil Modu] + + + [Kısıtlı Dil DENETİM Modu: Kısıtlama Yok] + + + [Dil Modu Yok] + + + [Kısıtlı Dil Modu] + + + {1} Yeni bir PowerShell önizleme sürümü kullanıma sunuldu: v{0} {2} + {1} Hemen yükseltin veya şu adresten sürüm sayfasına göz atın:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Yeni bir PowerShell kararlı sürümü kullanıma sunuldu: v{0} {2} + {1} Hemen yükseltin veya şu adresten sürüm sayfasına göz atın:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} Yeni bir PowerShell LTS sürümü kullanıma sunuldu: v{0} {2} + {1} Hemen yükseltin veya şu adresten sürüm sayfasına göz atın:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + Kullanım: 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 Çevrimiçi Yardım https://aka.ms/powershell-docs + +Tüm parametreler büyük/küçük harfe duyarsızdır. + + + + +-File | -f + + File değerinin "-" olması durumunda komut metni standart girişten okunur. + Yönlendirilmiş standart giriş olmadan "pwsh -File -" komutunun çalıştırılması normal bir + oturum başlatır. Bu, File parametresini hiç belirtmemekle aynıdır. + + Hiç parametre yoksa ancak komut satırında değerler varsa bu varsayılan + parametredir. Belirtilen betik yerel kapsamda + ("dot-sourced") çalışır, böylece betiğin oluşturduğu işlevler ve değişkenler + geçerli oturumda kullanılabilir. Betik dosyası yolunu + ve varsa parametreleri girin. File, komuttaki son parametre olmalıdır, çünkü + File parametresi adından sonra yazılan tüm karakterler + betik dosyası yolu ve ardından betik parametreleri olarak yorumlanır. + + Genellikle bir betiğin anahtar parametreleri ya eklenir ya da + atlanır. Örneğin aşağıdaki komut + Get-Script.ps1 betik dosyasının All parametresini kullanır: "-File .\Get-Script.ps1 -All" + + Nadir durumlarda bir anahtar parametresi için bir BOOLEAN değeri sağlamanız + gerekebilir. FILE parametresinin değerinde bir anahtar parametresine BOOLEAN + değeri sağlamak için, parametreyi normal şekilde kullanın; ardından hemen bir iki nokta üst üste + ve boole değeri ekleyin, örneğin: + "-File .\Get-Script.ps1 -All:$False". + + Betiğe geçirilen parametreler geçerli kabuk tarafından yorumlandıktan sonra + değişmez dizeler olarak geçirilir. Örneğin cmd.exe içindeyseniz ve + bir ortam değişkeni değeri geçirmek istiyorsanız cmd.exe + söz dizimini kullanmanız gerekir: "pwsh -File .\test.ps1 -TestParam %windir%" + + Buna karşılık cmd.exe içinde "pwsh -File .\test.ps1 -TestParam $env:windir" komutunu + çalıştırırsanız betik değişmez "$env:windir" dizesini alır. + Çünkü bunun geçerli cmd.exe kabuğunda özel bir anlamı yoktur. + "$env:windir" biçimindeki ortam değişkeni başvurusu bir + Command parametresi içinde kullanılabilir, çünkü orada PowerShell kodu olarak yorumlanır. + + Benzer şekilde aynı komutu bir Batch betiğinden çalıştırmak istiyorsanız + geçerli yürütme dizinini göstermek için ".\" veya "$PSScriptRoot" yerine "%~dp0" kullanmanız gerekir: + "pwsh -File %~dp0test.ps1 -TestParam %windir%". Bunun yerine + ".\test.ps1" kullandıysanız, PowerShell + ".\test.ps1" değişmez yolunu bulamadığından hata verir. + + Çağrılan betik dosyası bir çıkış komutuyla sonlandırıldığında işlem + çıkış kodu, çıkış komutuyla kullanılan sayısal bağımsız değişkene ayarlanır. + Normal sonlandırmada çıkış kodu her zaman 0'dır. + + -Command komutuna benzer şekilde, betik sonlandırma hatası oluştuğunda çıkış kodu + 1 olarak ayarlanır. Bununla birlikte, -Command komutunun aksine + çıkış kodu 0 olduğunda yürütme Ctrl-C ile kesilir. + +-Command | -c + + Belirtilen komutları (ve tüm parametreleri) PowerShell komut istemine + yazılmış gibi yürütür ve ardından NoExit parametresi + belirtilmediyse çıkar. + + Command değeri "-", betik bloğu veya dize olabilir. Command değerinin + "-" olması durumunda komut metni standart girişten okunur. + + Command parametresi yalnızca Command'a geçirilen değeri bir ScriptBlock türü + olarak tanıdığında betik bloğunu yürütme için kabul eder. Bu yalnızca + pwsh başka bir PowerShell ana bilgisayar tarafından çalıştırıldığında mümkündür. ScriptBlock + türü mevcut bir değişkende olabilir, bir ifadeden döndürülebilir + veya PowerShell ana bilgisayarı tarafından + küme ayraçları "{}" içine alınmış sabit bir betik bloğu olarak ayrıştırılarak pwsh'ye geçirilebilir. + + pwsh -Command {Get-WinEvent -LogName security} + + cmd.exe'de, betik bloğu (veya ScriptBlock türü) gibi bir kavram yoktur + bu nedenle Command'a geçirilen değer her zaman bir dize olur. Dize içinde bir + betik bloğu yazabilirsiniz ancak yürütülmek yerine + normal bir PowerShell isteminde yazılmış gibi davranarak + betik bloğunun içeriğini size geri yazdırır. + + Command'a geçirilen bir dize yine de PowerShell betiği olarak yürütülür, bu nedenle + betik bloğu küme ayraçları genellikle cmd.exe'den çalıştırılırken + gerekli değildir. Bir dize içinde tanımlanan satır içi betik bloğunu yürütmek için + "&" çağrı işleci kullanılabilir: + + pwsh -Command "& {Get-WinEvent -LogName security}" + + Command değeri bir dize ise Command, pwsh için son parametre + olmalıdır, çünkü onu takip eden tüm bağımsız değişkenler yürütülecek komutun + parçası olarak yorumlanır. + + Mevcut bir PowerShell oturumu içinden çağrıldığında, sonuçlar + üst kabukta canlı nesneler değil seri durumdan çıkarılmış XML nesneleri olarak döndürülür. + Diğer kabuklar için sonuçlar dize olarak döndürülür. + + Command değerinin "-" olması durumunda komut metni standart girişten + okunur. Command parametresini standart girişle kullanırken standart girişi + yeniden yönlendirmeniz gerekir. Örneğin: + + @' + "in" + + "hi" | + % { "$_ there" } + + "out" + '@ | powershell -NoProfile -Command - + + Bu örnek şu çıkışı oluşturur: + + in + hi there + out + + İşlem çıkış kodu, betik bloğundaki son (yürütülen) güncelleştirmenin + durumuna göre belirlenir. Çıkış kodu, $? $true olduğunda 0 veya + $? $false olduğunda 1 olur. Son komut bir dış program veya + 0 veya 1 dışında bir çıkış kodunu açıkça ayarlayan bir PowerShell betiğiyse + çıkış kodu, işlem çıkış kodu için 1'e dönüştürülür. Belirli çıkış kodunu + korumak için, komut dizenize veya betik bloğunuza exit $LASTEXITCODE ekleyin. + + Benzer şekilde, bir throw veya -ErrorAction Stop gibi + betik sonlandıran (çalışma alanı sonlandıran) bir hata oluşursa + 1 değeri döndürülür. + +-CommandWithArgs | -cwa + + [Deneysel] + Bağımsız değişkenlerle bir PowerShell komutu yürütür. `-Command` komutunun aksine bu + parametre, komut tarafından kullanılabilecek '$args yerleşik değişkenini + doldurur. + + İlk dize komuttur ve boşlukla ayrılmış sonraki dizeler + bağımsız değişkenlerdir. + + Örneğin: + + pwsh -CommandWithArgs '$args | % { "arg: $_" }' arg1 arg2 + + Bu örnek şu çıkışı oluşturur: + + arg: arg1 + arg: arg2 + +-ConfigurationName | -config + + PowerShell'in çalıştırılacağı yapılandırma uç noktasını belirtir. Bu, + varsayılan PowerShell uzak uç noktaları veya belirli kullanıcı rolü özelliklerine sahip + özel bir uç nokta dahil, yerel makinede kayıtlı herhangi bir uç nokta + olabilir. + + Örnek: "pwsh -ConfigurationName AdminRoles" + +-ConfigurationFile + + Bir oturum yapılandırması (.pssc) dosya yolunu belirtir. Yapılandırma + dosyasındaki yapılandırma, PowerShell oturumuna + uygulanır. + + Örnek: "pwsh -ConfigurationFile "C:\ProgramData\PowerShell\MyConfig.pssc" + +-CustomPipeName + + Hata ayıklama ve diğer işlemler arası iletişimler için kullanılan + ek bir IPC sunucusu (adlandırılmış kanal) için kullanılacak adı belirtir. Bu, + diğer PowerShell örneklerine bağlanmak için öngörülebilir bir mekanizma sunar. + Genellikle "Enter-PSHostProcess" üzerinde CustomPipeName parametresiyle kullanılır. + + Bu parametre PowerShell 6.2'de kullanıma sunulmuştur. + + Örneğin: + + # PowerShell örneği 1 + pwsh -CustomPipeName mydebugpipe + # PowerShell örneği 2 + Enter-PSHostProcess -CustomPipeName mydebugpipe + +-EncodedCommand | -e | -ec + + Bir komutun Base64 kodlu dize sürümünü kabul eder. Bu parametreyi + karmaşık, iç içe alıntı gerektiren komutları PowerShell'e göndermek için kullanın. + Base64 gösterimi UTF-16 ile kodlanmış bir dize olmalıdır. + + Örneğin: + + $command = 'dir "c:\program files" ' + $bytes = [System.Text.Encoding]::Unicode.GetBytes($command) + $encodedCommand = [Convert]::ToBase64String($bytes) + pwsh -encodedcommand $encodedCommand + +-ExecutionPolicy | -ex | -ep + + Geçerli oturum için varsayılan yürütme ilkesini ayarlar ve bunu + $env:PSExecutionPolicyPreference ortam değişkenine kaydeder. Bu parametre + kalıcı olarak yapılandırılmış yürütme ilkelerini değiştirmez. + + Bu parametre yalnızca Windows bilgisayarlarda geçerlidir. + $env:PSExecutionPolicyPreference ortam değişkeni, Windows olmayan + platformlarda bulunmaz. + +-InputFormat | -inp | -if + + PowerShell'e gönderilen verilerin biçimini açıklar. Geçerli değerler "Text" + (metin dizeleri) veya "XML" (serileştirilmiş CLIXML biçimi). + +-Interactive | -i + + Kullanıcıya etkileşimli bir istem sunar. NonInteractive parametresinin + tersidir. + +-Login | -l + + Linux ve macOS'ta, PowerShell'i oturum açma kabuğu olarak başlatarak /bin/sh kullanarak + /etc/profile ve ~/.profile gibi oturum açma profillerini yürütür. Windows'da, + bu anahtar hiçbir şey yapmaz. + + [!ÖNEMLİ] PowerShell'i oturum açma kabuğu olarak başlatmak için bu parametrenin önce + geçirilmesi gerekir. Parametre başka bir konumda geçirilirse yoksayılır. + + UNIX benzeri işletim sistemlerinde pwsh'yi oturum açma kabuğu olarak ayarlamak için: + + - Pwsh için tam mutlak yolun /etc/shells altında listelendiğini doğrulayın + + - Bu yol genellikle Linux üzerinde /usr/bin/pwsh veya + macOS üzerinde /usr/local/bin/pwsh gibi görünür + - Bazı yükleme yöntemleriyle, bu giriş + yükleme sırasında otomatik olarak eklenir + - pwsh /etc/shells içinde yoksa bir düzenleyici kullanarak + pwsh yolunu son satıra ekleyin. Bunu düzenlemek için yükseltilmiş ayrıcalıklar + gerekir. + + - Geçerli kullanıcı kabuğunu pwsh olarak ayarlamak için chsh yardımcı programını kullanın: + + chsh -s /usr/bin/pwsh + + [!UYARI] pwsh'yi oturum açma kabuğu olarak ayarlama işlemi şu anda + Linux için Windows Alt Sistemi (WSL) üzerinde desteklenmez ve pwsh'yi burada oturum açma kabuğu olarak + ayarlamayı denemek WSL'nin etkileşimli olarak başlatılamamasına neden olabilir. + +-MTA + + Çok iş parçacıklı bölme kullanarak PowerShell'i başlatın. Bu anahtar yalnızca + Windows'da kullanılabilir. + +-NoExit | -noe + + Başlangıç komutlarını çalıştırdıktan sonra çıkılmaz. + + Örnek: "pwsh -NoExit -Command Get-Date" + +-NoLogo | -nol + + Etkileşimli oturumların başlangıcında başlık metnini gizler. + +-NonInteractive | -noni + + Bu anahtar, kullanıcı girişi gerektirmeyen oturumlar oluşturmak için kullanılır. + Bu, zamanlanmış görevlerde veya CI/CD işlem hatlarında çalışan betikler için yararlıdır. + 'Read-Host' veya onay istemleri gibi etkileşimli özellikleri kullanmaya yönelik herhangi bir girişim + askıda kalmak yerine deyimi sonlandıran hatalara neden olur. + +-NoProfile | -nop + + PowerShell profillerini yüklemez. + +-NoProfileLoadTime + + Yükleme süresi 500 milisaniyeyi aştığında, başlangıçta gösterilen PowerShell profili yükleme süresi + metnini gizler. + +-OutputFormat | -o | -of + + PowerShell'den çıkışın nasıl biçimlendirildiğini belirtir. Geçerli değerler "Text" + (metin dizeleri) veya "XML" (serileştirilmiş CLIXML biçimi). + + Örnek: "pwsh -o XML -c Get-Date" + + Bir PowerShell oturumunda çağrıldığında, seri durumdan çıkarılan nesneleri + düz dizeler yerine çıkış olarak alırsınız. Diğer kabuklardan çağrıldığında çıkış, + CLIXML metni olarak biçimlendirilmiş dize verileri olur. + +-SettingsFile | -settings + + Oturum için sistem genelindeki "powershell.config.json" ayarları dosyasını geçersiz + kılar. Varsayılan olarak, sistem genelindeki ayarlar + "$PSHOME" dizinindeki "powershell.config.json" dosyasından okunur. + + Bu ayarların "-ConfigurationName" bağımsız değişkeniyle belirtilen uç nokta tarafından + kullanılmadığını unutmayın. + + Örnek: "pwsh -SettingsFile c:\myproject\powershell.config.json" + +-SSHServerMode | -sshs + + PowerShell'i bir SSH alt sistemi olarak çalıştırmak için sshd_config içinde kullanılır. Başka + hiçbir kullanım için tasarlanmamıştır veya desteklenmez. + +-STA + + Tek iş parçacıklı bölme kullanarak PowerShell'i başlatın. Bu varsayılandır. + Bu anahtar yalnızca Windows'da kullanılabilir. + +-Version | -v + + PowerShell sürümünü görüntüler. Ek parametreler yok sayılır. + +-WindowStyle | -w + + Oturum için pencere stilini ayarlar. Geçerli değerler Normal, Minimized, + Maximized ve Hidden. + +-WorkingDirectory | -wd + + Başlangıçta yürüterek ilk çalışma dizinini ayarlar. Geçerli herhangi bir + PowerShell dosya yolu desteklenir. + + PowerShell'i giriş dizininizde başlatmak için şu komutu kullanın: pwsh -WorkingDirectory ~ + +-Help, -?, /? + + Pwsh için yardımı görüntüler. PowerShell'de bir pwsh komutu yazıyorsanız + komut parametrelerinin başına eğik çizgi (/) değil kısa çizgi (-) ekleyin. + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ProgressNodeStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ProgressNodeStrings.tr.resx new file mode 100644 index 00000000000..8d58bfca59a --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/ProgressNodeStrings.tr.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} kaldı. + + + {0} etkinlik gösterilmiyor... + + + {0} etkinlik gösterilmiyor... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/tr/TranscriptStrings.tr.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/TranscriptStrings.tr.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/tr/TranscriptStrings.tr.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/CommandLineParameterParserStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/CommandLineParameterParserStrings.zh-Hans.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/CommandLineParameterParserStrings.zh-Hans.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleControlStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleControlStrings.zh-Hans.resx new file mode 100644 index 00000000000..ecaaffc2cf4 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleControlStrings.zh-Hans.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 + + + 添加中断处理程序时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 支持服务部门联系。 + + + 尝试移除中断处理程序时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取有关控制台句柄的输入时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 检索活动控制台输出缓冲区的句柄时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取控制台模式时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 设置控制台模式时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 从控制台输入缓冲区读取字符时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 从控制台输入缓冲区读取输入记录时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 读取控制台输入缓冲区的内容时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取控制台输入缓冲区中的事件数时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 刷新控制台输入缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取控制台输出缓冲区信息时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 设置控制台输出缓冲区大小时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 写入控制台输出缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 读取控制台输出缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 在用字符填充控制台输出缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 在用属性填充控制台输出缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 滚动控制台输出缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 设置控制台窗口信息时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取最大的控制台窗口大小时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 设置控制台窗口标题时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 在当前光标位置写入控制台输出缓冲区时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 设置控制台输出缓冲区的字符属性时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取游标信息时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 设置游标信息时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 获取控制台字体信息时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + + 发送键盘输入时发生 Win32 内部错误 "{0}" 0x{1:X}。请与 Microsoft 客户支持服务部门联系。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostRawUserInterfaceStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostRawUserInterfaceStrings.zh-Hans.resx new file mode 100644 index 00000000000..6979e04986d --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostRawUserInterfaceStrings.zh-Hans.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 + + + 无法处理该操作,因为提供的坐标无效。请指定一个位于 {0} 缓冲区区域内的坐标。 + + + 无法设置缓冲区大小,因为指定的大小过大或过小。 + + + 无法设置控制台颜色,因为指定的值无效。指定 System.ConsoleColor 类型定义的有效颜色。 + + + 无法处理 CursorSize,因为指定的光标大小无效。 + + + 无法读取按键选项。若要读取选项,请设置以下一项或两项: IncludeKeyDown、IncludeKeyUp。 + + + {0} 应该大于或等于 {1}。 + + + 无法使用指定的窗口 X (列)位置,因为它超出了屏幕缓冲区的宽度。请指定另一个 X 位置,缓冲区最左侧的列为 0。 + + + 无法使用指定的窗口 Y (行)位置,因为它超出了屏幕缓冲区的高度。请指定另一个 Y 位置,从缓冲区最顶层的行为 0。 + + + 窗口宽度不能小于 1。 + + + 窗口高度必须至少为 1。 + + + 窗口宽度不能超过屏幕缓冲区。 + + + 窗口高度不能超过屏幕缓冲区。 + + + 窗口宽度不能超过 {0}。 + + + 窗口高度不能超过 {0}。 + + + 窗口大小过窄。 + + + 窗口大小过短。 + + + 窗口标题不能为空。 + + + 窗口标题长度不能超过 {0} 个字符。 + + + 管理员: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostStrings.zh-Hans.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostStrings.zh-Hans.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostUserInterfaceSecurityResources.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostUserInterfaceSecurityResources.zh-Hans.resx new file mode 100644 index 00000000000..7cf6e4b2065 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostUserInterfaceSecurityResources.zh-Hans.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 + + + 用户: + + + 用户 {0} 的密码: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostUserInterfaceStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostUserInterfaceStrings.zh-Hans.resx new file mode 100644 index 00000000000..4523727333a --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ConsoleHostUserInterfaceStrings.zh-Hans.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 + + + “{0}”集合必须包含至少一个元素。 + + + 由于溢出错误,无法将“{1}”识别为 {0}。 + + + 由于格式错误,无法将“{1}”识别为 {0}。 + + + 无法将“{0}”识别为有效的提示命令。 + + + {0} 没有可用的帮助。 + + + {0}: + + + 字段“{0}”是一个零秩数组。 + + + “{0}”应包含至少一个元素。 + + + “{0}”必须是“{1}”的有效索引或 -1(表示没有默认选择)。 + + + “{0}”必须是“{1}”的有效索引。“{2}”不是有效索引。 + + + [?] 帮助 + + + 提示已取消。 + + + 无法处理热键,因为问号("?")不能用作热键。 + + + 无法显示“{0}”的提示,因为无法加载类型“{1}”。 + + + “{0}”不能是 Null 或为空。 + + + “{0}”不得为 null。 + + + (键入 !? 以获取帮助。) + + + (默认值为“{0}”): + + + (默认值为“{0}”) + + + (默认选项为 {0}) + + + Choice[{0}]: + + + 调试: {0} + + + 详细信息: {0} + + + 警告: {0} + + + PowerShell 处于非交互模式。读取和提示功能不可用。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ManagedEntranceStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ManagedEntranceStrings.zh-Hans.resx new file mode 100644 index 00000000000..7f843282c5a --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ManagedEntranceStrings.zh-Hans.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} + + + [受约束的语言模式] + + + [受约束的语言审核模式: 无限制] + + + [无语言模式] + + + [受限语言模式] + + + {1} 有新的 PowerShell 预览版本可用: v{0} {2} + {1} 立即升级,或访问发布页:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} 有新的 PowerShell 稳定版本可用: v{0} {2} + {1} 立即升级,或访问发布页:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} 有新的 PowerShell LTS 版本可用: v{0} {2} + {1} 立即升级,或访问发布页:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + 用法: 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 联机帮助 https://aka.ms/powershell-docs + +所有参数都不区分大小写。 + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ProgressNodeStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ProgressNodeStrings.zh-Hans.resx new file mode 100644 index 00000000000..d3a8bc699a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/ProgressNodeStrings.zh-Hans.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}。 + + + 未显示 {0} 活动... + + + 未显示 {0} 活动... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/TranscriptStrings.zh-Hans.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/TranscriptStrings.zh-Hans.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hans/TranscriptStrings.zh-Hans.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/CommandLineParameterParserStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/CommandLineParameterParserStrings.zh-Hant.resx new file mode 100644 index 00000000000..5bbac3bf85b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/CommandLineParameterParserStrings.zh-Hant.resx @@ -0,0 +1,240 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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. + + + The parameter "-File" is required by policy. + + + The parameter "-NoExit" is disallowed by policy. + + + Server mode is disallowed by policy. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleControlStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleControlStrings.zh-Hant.resx new file mode 100644 index 00000000000..15d52a6c619 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleControlStrings.zh-Hant.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 + + + 新增中斷處理常式時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 支援服務。 + + + 嘗試移除中斷處理常式時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得主控台控制代碼的輸入時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 擷取使用中主控台輸出緩衝區的控制代碼時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得主控台模式時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 設定主控台模式時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 從主控台輸入緩衝區讀取字元時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 從主控台輸入緩衝區讀取輸入記錄時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 讀取主控台輸入緩衝區的內容時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得主控台輸入緩衝區中的事件數目時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 排清主控台輸入緩衝區時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得主控台輸出緩衝區資訊時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 設定主控台輸出緩衝區大小時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 寫入主控台輸出緩衝區時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 讀取主控台輸出緩衝區時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 填入主控台輸出緩衝區字元時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 填入主控台輸出緩衝區屬性時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 捲動主控台輸出緩衝區時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 設定主控台視窗資訊時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得最大主控台視窗大小時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 設定主控台視窗標題時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 在目前游標位置寫入主控台輸出緩衝區時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 設定主控台輸出緩衝區字元屬性時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得游標資訊時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 設定游標資訊時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 取得主控台字型資訊時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + + 傳送鍵盤輸入時發生 Win32 內部錯誤 "{0}" 0x{1:X}。請連絡 Microsoft 客戶支援服務。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostRawUserInterfaceStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostRawUserInterfaceStrings.zh-Hant.resx new file mode 100644 index 00000000000..bec458b8f00 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostRawUserInterfaceStrings.zh-Hant.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 + + + 無法處理作業,因為提供的座標無效。請指定位於 {0} 緩衝區域內的座標。 + + + 無法設定緩衝區大小,因為指定的大小太大或太小。 + + + 無法設定主控台色彩,因為指定的值無效。請指定 System.ConsoleColor 型別定義的有效色彩。 + + + 無法處理 CursorSize,因為指定的游標大小無效。 + + + 無法讀取索引鍵選項。若要讀取選項,請設定下列其中一個或兩個: IncludeKeyDown、IncludeKeyUp。 + + + {0} 應大於或等於 {1}。 + + + 無法使用指定的 Window X (資料行) 位置,因為它超出螢幕緩衝區的寬度。請指定另一個 X 位置,從 0 作為緩衝區最左邊的資料行開始。 + + + 無法使用指定的 Window Y (資料列) 位置,因為它超出螢幕緩衝區的高度。請指定另一個 Y 位置,從 0 作為緩衝區最上方的資料列開始。 + + + 視窗寬度不可小於 1。 + + + 視窗高度必須至少為 1。 + + + 視窗寬度不能超過螢幕緩衝區。 + + + 視窗高度不能超過螢幕緩衝區。 + + + 視窗寬度不能超過 {0}。 + + + 視窗高度不可超過 {0}。 + + + 視窗大小太窄。 + + + 視窗大小太短。 + + + 視窗標題不可為空白。 + + + 視窗標題長度不得超過 {0} 個字元。 + + + 系統管理員: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostStrings.zh-Hant.resx new file mode 100644 index 00000000000..bf7ab57b1a3 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostStrings.zh-Hant.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostUserInterfaceSecurityResources.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostUserInterfaceSecurityResources.zh-Hant.resx new file mode 100644 index 00000000000..fba4efa1319 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostUserInterfaceSecurityResources.zh-Hant.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 + + + 使用者: + + + 使用者 {0} 的密碼: + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostUserInterfaceStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostUserInterfaceStrings.zh-Hant.resx new file mode 100644 index 00000000000..e0881498d1b --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ConsoleHostUserInterfaceStrings.zh-Hant.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 + + + "{0}" 集合必須至少具有一個項目。 + + + 由於溢位錯誤,無法將 "{1}" 辨識為 {0}。 + + + 由於格式錯誤,無法將 "{1}" 辨識為 {0}。 + + + 無法將 "{0}" 辨識為有效的提示命令。 + + + {0} 沒有可用的說明。 + + + {0}: + + + 欄位 "{0}" 是零秩陣列。 + + + "{0}" 應至少有一個元素。 + + + "{0}" 必須是 "{1}" 的有效索引,或使用 -1 表示沒有預設選項。 + + + "{0}" 必須是 "{1}" 的有效索引。"{2}" 不是有效的索引。 + + + [?]說明 + + + 提示已取消。 + + + 無法處理快速鍵,因為問號 ("?") 不能用作快速鍵。 + + + 無法顯示 "{0}" 的提示,因為無法載入類型 "{1}"。 + + + "{0}" 不可以是 Null 或空的。 + + + "{0}" 不得為 Null。 + + + (輸入 !? 以獲取協助。) + + + (預設為 "{0}"): + + + (預設為 "{0}") + + + (預設選項為 {0}) + + + 選擇[{0}]: + + + 偵錯: {0} + + + 詳細資訊: {0} + + + 警告: {0} + + + PowerShell 處於非互動模式。無法使用讀取和提示功能。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ManagedEntranceStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ManagedEntranceStrings.zh-Hant.resx new file mode 100644 index 00000000000..49744d65ee6 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ManagedEntranceStrings.zh-Hant.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} + + + [限制語言模式] + + + [限制語言稽核模式: 無限制] + + + [沒有語言模式] + + + [限制語言模式] + + + {1} 有新的 PowerShell 預覽版本可供使用: 版本 {0} {2} + {1} 立即升級,或於下列發行頁面查看:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} 有新的 PowerShell 穩定版本可供使用: 版本 {0} {2} + {1} 立即升級,或於下列發行頁面查看:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + {1} 有新的 PowerShell LTS 版本可供使用: 版本 {0} {2} + {1} 立即升級,或於下列發行頁面查看:{3}{2} + {1} https://aka.ms/PowerShell-Release?tag=v{0} {4}{2} + + + + 使用方式: 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 線上說明 https://aka.ms/powershell-docs + +所有參數都不區分大小寫。 + + + + +-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 (/). + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ProgressNodeStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ProgressNodeStrings.zh-Hant.resx new file mode 100644 index 00000000000..0ae823aebfa --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/ProgressNodeStrings.zh-Hant.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}。。 + + + 未顯示 {0} 個活動... + + + 未顯示 {0} 個活動... + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/TranscriptStrings.zh-Hant.resx b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/TranscriptStrings.zh-Hant.resx new file mode 100644 index 00000000000..d23d6495940 --- /dev/null +++ b/src/Microsoft.PowerShell.ConsoleHost/resources/zh-Hant/TranscriptStrings.zh-Hant.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} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs deleted file mode 100644 index 1b3f939158f..00000000000 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/EngineInstaller.cs +++ /dev/null @@ -1,78 +0,0 @@ -// 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 monad engine. - /// - /// This class will be built with monad console host dll - /// (System.Management.Automation.dll). - /// - /// 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/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs b/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs deleted file mode 100644 index c532aeb190d..00000000000 --- a/src/Microsoft.PowerShell.ConsoleHost/singleshell/installer/MshHostMshSnapin.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.ComponentModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell -{ - /// - /// PSHostMshSnapin (or PSHostMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad host mshsnapin. - /// - /// This class will be built with monad host engine dll - /// (Microsoft.PowerShell.ConsoleHost.dll). - /// - [RunInstaller(true)] - public sealed class PSHostPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSHostPSSnapIn() - : base() - { - } - - /// - /// Get name of this mshsnapin. - /// - public override string Name - { - get - { - return RegistryStrings.HostMshSnapinName; - } - } - - /// - /// Get the default vendor string for this mshsnapin. - /// - 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 mshsnapin. - /// - 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/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs index d4e566890f0..32ce9993cfb 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProvider.cs @@ -107,7 +107,7 @@ private unsafe void EtwRegister() } // - // implement Dispose Pattern to early deregister from ETW insted of waiting for + // 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 @@ -131,7 +131,10 @@ protected virtual void Dispose(bool disposing) // // check if the object has been already disposed // - if (_disposed == 1) return; + if (_disposed == 1) + { + return; + } if (Interlocked.Exchange(ref _disposed, 1) != 0) { @@ -291,8 +294,7 @@ to fill the passed in ETW data descriptor. { dataDescriptor->Reserved = 0; - string sRet = data as string; - if (sRet != null) + if (data is string sRet) { dataDescriptor->Size = (uint)((sRet.Length + 1) * 2); return sRet; @@ -331,10 +333,10 @@ to fill the passed in ETW data descriptor. *uintptr = (uint)data; dataDescriptor->DataPointer = (ulong)uintptr; } - else if (data is UInt64) + else if (data is ulong) { dataDescriptor->Size = (uint)sizeof(ulong); - UInt64* ulongptr = (ulong*)dataBuffer; + ulong* ulongptr = (ulong*)dataBuffer; *ulongptr = (ulong)data; dataDescriptor->DataPointer = (ulong)ulongptr; } @@ -437,10 +439,7 @@ public bool WriteMessageEvent(string eventMessage, byte eventLevel, long eventKe { int status = 0; - if (eventMessage == null) - { - throw new ArgumentNullException(nameof(eventMessage)); - } + ArgumentNullException.ThrowIfNull(eventMessage); if (IsEnabled(eventLevel, eventKeywords)) { @@ -508,10 +507,7 @@ public bool WriteEvent(in EventDescriptor eventDescriptor, string data) { uint status = 0; - if (data == null) - { - throw new ArgumentNullException("dataString"); - } + ArgumentNullException.ThrowIfNull(data); if (IsEnabled(eventDescriptor.Level, eventDescriptor.Keywords)) { diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs index 7264e485468..1c82891b654 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/EventProviderTraceListener.cs @@ -41,8 +41,7 @@ public string Delimiter [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] set { - if (value == null) - throw new ArgumentNullException("Delimiter"); + ArgumentNullException.ThrowIfNull(value, nameof(Delimiter)); if (value.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); @@ -72,8 +71,7 @@ public EventProviderTraceListener(string providerId, string name) public EventProviderTraceListener(string providerId, string name, string delimiter) : base(name) { - if (delimiter == null) - throw new ArgumentNullException(nameof(delimiter)); + ArgumentNullException.ThrowIfNull(delimiter); if (delimiter.Length == 0) throw new ArgumentException(DotNetEventingStrings.Argument_NeedNonemptyDelimiter); diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs index 007cf74891e..df2b064ebd5 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/Reader/NativeWrapper.cs @@ -307,7 +307,7 @@ public static void EvtClearLog( [System.Security.SecurityCritical] public static EventLogHandle EvtCreateRenderContext( - Int32 valuePathsCount, + int valuePathsCount, string[] valuePaths, UnsafeNativeMethods.EvtRenderContextFlags flags) { @@ -939,7 +939,7 @@ public static void EvtRenderBufferWithContextSystem(EventLogHandle contextHandle break; } - pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); + pointer = new IntPtr(((long)pointer + Marshal.SizeOf(varVal))); } } finally @@ -984,7 +984,7 @@ public static IList EvtRenderBufferWithContextUserOrValues(EventLogHandl { UnsafeNativeMethods.EvtVariant varVal = Marshal.PtrToStructure(pointer); valuesList.Add(ConvertToObject(varVal)); - pointer = new IntPtr(((Int64)pointer + Marshal.SizeOf(varVal))); + pointer = new IntPtr(((long)pointer + Marshal.SizeOf(varVal))); } } @@ -1106,7 +1106,7 @@ public static IEnumerable EvtFormatMessageRenderKeywords(EventLogHandle break; keywordsList.Add(s); // nr of bytes = # chars * 2 + 2 bytes for character '\0'. - pointer = new IntPtr((Int64)pointer + (s.Length * 2) + 2); + pointer = new IntPtr((long)pointer + (s.Length * 2) + 2); } return keywordsList.AsReadOnly(); @@ -1270,23 +1270,23 @@ private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) 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(); - Int16[] arInt16 = new Int16[val.Count]; + 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(); - Int32[] arInt32 = new Int32[val.Count]; + 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(); - Int64[] arInt64 = new Int64[val.Count]; + 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(); - Single[] arSingle = new Single[val.Count]; + 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): @@ -1297,13 +1297,13 @@ private static object ConvertToObject(UnsafeNativeMethods.EvtVariant val) 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(UInt16)); + 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(UInt64)); + 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(UInt32)); + 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): @@ -1375,7 +1375,7 @@ public static Array ConvertToArray(UnsafeNativeMethods.EvtVariant val, int si for (int i = 0; i < val.Count; i++) { array.SetValue(Marshal.PtrToStructure(ptr), i); - ptr = new IntPtr((Int64)ptr + size); + ptr = new IntPtr((long)ptr + size); } return array; @@ -1398,7 +1398,7 @@ public static Array ConvertToBoolArray(UnsafeNativeMethods.EvtVariant val) { bool value = Marshal.ReadInt32(ptr) != 0; array[i] = value; - ptr = new IntPtr((Int64)ptr + 4); + ptr = new IntPtr((long)ptr + 4); } return array; @@ -1419,7 +1419,7 @@ public static Array ConvertToFileTimeArray(UnsafeNativeMethods.EvtVariant val) for (int i = 0; i < val.Count; i++) { array[i] = DateTime.FromFileTime(Marshal.ReadInt64(ptr)); - ptr = new IntPtr((Int64)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes + ptr = new IntPtr((long)ptr + 8 * sizeof(byte)); // FILETIME values are 8 bytes } return array; @@ -1441,7 +1441,7 @@ public static Array ConvertToSysTimeArray(UnsafeNativeMethods.EvtVariant val) { 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((Int64)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes + ptr = new IntPtr((long)ptr + 16 * sizeof(byte)); // SystemTime values are 16 bytes } return array; diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs index 38a3f4a60c7..b7beee133ed 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/DotNetCode/Eventing/UnsafeNativeMethods.cs @@ -268,10 +268,10 @@ internal struct SystemTime internal struct EvtVariant { [FieldOffset(0)] - public UInt32 UInteger; + public uint UInteger; [FieldOffset(0)] - public Int32 Integer; + public int Integer; [FieldOffset(0)] public byte UInt8; @@ -283,7 +283,7 @@ internal struct EvtVariant public ushort UShort; [FieldOffset(0)] - public UInt32 Bool; + public uint Bool; [FieldOffset(0)] public byte ByteVal; @@ -292,13 +292,13 @@ internal struct EvtVariant public byte SByte; [FieldOffset(0)] - public UInt64 ULong; + public ulong ULong; [FieldOffset(0)] - public Int64 Long; + public long Long; [FieldOffset(0)] - public Single Single; + public float Single; [FieldOffset(0)] public double Double; @@ -325,7 +325,7 @@ internal struct EvtVariant public IntPtr GuidReference; [FieldOffset(0)] - public UInt64 FileTime; + public ulong FileTime; [FieldOffset(0)] public IntPtr SystemTime; @@ -334,10 +334,10 @@ internal struct EvtVariant public IntPtr SizeT; [FieldOffset(8)] - public UInt32 Count; // number of elements (not length) in bytes. + public uint Count; // number of elements (not length) in bytes. [FieldOffset(12)] - public UInt32 Type; + public uint Type; } internal enum EvtEventPropertyId @@ -404,15 +404,15 @@ internal enum EvtChannelReferenceFlags internal enum EvtEventMetadataPropertyId { - EventMetadataEventID, // EvtVarTypeUInt32 - EventMetadataEventVersion, // EvtVarTypeUInt32 - EventMetadataEventChannel, // EvtVarTypeUInt32 - EventMetadataEventLevel, // EvtVarTypeUInt32 - EventMetadataEventOpcode, // EvtVarTypeUInt32 - EventMetadataEventTask, // EvtVarTypeUInt32 - EventMetadataEventKeyword, // EvtVarTypeUInt64 - EventMetadataEventMessageID,// EvtVarTypeUInt32 - EventMetadataEventTemplate // EvtVarTypeString + EventMetadataEventID, // EvtVarTypeUInt32 + EventMetadataEventVersion, // EvtVarTypeUInt32 + EventMetadataEventChannel, // EvtVarTypeUInt32 + EventMetadataEventLevel, // EvtVarTypeUInt32 + EventMetadataEventOpcode, // EvtVarTypeUInt32 + EventMetadataEventTask, // EvtVarTypeUInt32 + EventMetadataEventKeyword, // EvtVarTypeUInt64 + EventMetadataEventMessageID, // EvtVarTypeUInt32 + EventMetadataEventTemplate // EvtVarTypeString // EvtEventMetadataPropertyIdEND } @@ -733,7 +733,7 @@ out int publisherIdBufferUsed [SecurityCritical] internal static extern EventLogHandle EvtOpenChannelConfig( EventLogHandle session, - [MarshalAs(UnmanagedType.LPWStr)] String channelPath, + [MarshalAs(UnmanagedType.LPWStr)] string channelPath, int flags ); @@ -823,8 +823,8 @@ int flags [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] [SecurityCritical] internal static extern EventLogHandle EvtCreateRenderContext( - Int32 valuePathsCount, - [MarshalAs(UnmanagedType.LPArray,ArraySubType = UnmanagedType.LPWStr)] + int valuePathsCount, + [MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.LPWStr)] string[] valuePaths, [MarshalAs(UnmanagedType.I4)] EvtRenderContextFlags flags ); @@ -862,10 +862,10 @@ internal struct EvtStringVariant public string StringVal; [FieldOffset(8)] - public UInt32 Count; + public uint Count; [FieldOffset(12)] - public UInt32 Type; + public uint Type; } [DllImport(WEVTAPI, CharSet = CharSet.Unicode, SetLastError = true)] diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj index 81c8fc4e9dd..e3cdb00a3a1 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/Microsoft.PowerShell.CoreCLR.Eventing.csproj @@ -8,7 +8,12 @@ - + + + + $(RootNamespace).resources.%(Filename) + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx index b801e091abd..1cf6b6df5cf 100644 --- a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/DotNetEventingStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/cs/DotNetEventingStrings.cs.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/cs/DotNetEventingStrings.cs.resx new file mode 100644 index 00000000000..a223117eea0 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/cs/DotNetEventingStrings.cs.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 + + + Je vyžadováno nezáporné číslo. + + + Parametr ID musí být v rozsahu {0} až {1}. + + + Celkový počet parametrů nesmí být vyšší než {0}. + + + Počet řetězcových parametrů nesmí být vyšší než {0}. + + + Jako oddělovač nemůže být zadán prázdný řetězec. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/de/DotNetEventingStrings.de.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/de/DotNetEventingStrings.de.resx new file mode 100644 index 00000000000..61175f6d4b9 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/de/DotNetEventingStrings.de.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 + + + Eine nicht negative Zahl ist erforderlich. + + + Der ID-Parameter muss im Bereich {0} bis {1} liegen. + + + Die Gesamtzahl der Parameter darf „{0}“ nicht überschreiten. + + + Die Anzahl von String-Parametern darf „{0}“ nicht überschreiten. + + + Das Trennzeichen darf keine leere Zeichenfolge sein. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/es/DotNetEventingStrings.es.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/es/DotNetEventingStrings.es.resx new file mode 100644 index 00000000000..15295fef6e2 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/es/DotNetEventingStrings.es.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 + + + Se requiere un número no negativo. + + + El parámetro ID debe estar en el intervalo {0} hasta {1}. + + + El número total de parámetros no debe superar {0}. + + + El número de parámetros String no debe superar {0}. + + + El delimitador no puede ser una cadena vacía. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/fr/DotNetEventingStrings.fr.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/fr/DotNetEventingStrings.fr.resx new file mode 100644 index 00000000000..c5d5c3c8526 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/fr/DotNetEventingStrings.fr.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 + + + Un nombre non négatif est nécessaire. + + + Le paramètre ID doit être compris entre {0} et {1}. + + + Le nombre total de paramètres ne doit pas dépasser {0}. + + + Le nombre de paramètres Chaîne ne doit pas dépasser {0}. + + + Le délimiteur ne peut pas être une chaîne vide. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/it/DotNetEventingStrings.it.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/it/DotNetEventingStrings.it.resx new file mode 100644 index 00000000000..4e80ad79c82 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/it/DotNetEventingStrings.it.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 + + + Richiesto numero non negativo. + + + Il parametro ID deve essere compreso tra {0} e {1}. + + + Il numero totale dei parametri non deve superare {0}. + + + Il numero dei parametri di stringa non deve superare {0}. + + + Il delimitatore non può essere una stringa vuota. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ja/DotNetEventingStrings.ja.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ja/DotNetEventingStrings.ja.resx new file mode 100644 index 00000000000..cb4c5b2cae2 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ja/DotNetEventingStrings.ja.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 + + + 正の数値が必要です。 + + + ID パラメーターは {0} から {1} の範囲内である必要があります。 + + + パラメーターの総数は {0} 以下である必要があります。 + + + 文字列パラメーターの数は {0} 以下である必要があります。 + + + 区切り記号を空の文字列にすることはできません。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ko/DotNetEventingStrings.ko.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ko/DotNetEventingStrings.ko.resx new file mode 100644 index 00000000000..ebd801e99a6 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ko/DotNetEventingStrings.ko.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 + + + 음수가 아닌 숫자가 필요합니다. + + + ID 매개 변수는 {0}에서 {1}까지여야 합니다. + + + 전체 매개 변수 수는 {0}을(를) 초과하면 안 됩니다. + + + String 매개 변수의 수는 {0}을(를) 초과할 수 없습니다. + + + 구분 기호는 빈 문자열일 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/pl/DotNetEventingStrings.pl.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/pl/DotNetEventingStrings.pl.resx new file mode 100644 index 00000000000..9949b0bb3df --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/pl/DotNetEventingStrings.pl.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 + + + Wymagana jest liczba nieujemna. + + + Parametr identyfikatora musi znajdować się w zakresie {0} do {1}. + + + Całkowita liczba parametrów nie może przekraczać {0}. + + + Liczba parametrów string nie może przekraczać {0}. + + + Ogranicznik nie może być pustym ciągiem. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/pt-BR/DotNetEventingStrings.pt-BR.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/pt-BR/DotNetEventingStrings.pt-BR.resx new file mode 100644 index 00000000000..c88e249bd31 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/pt-BR/DotNetEventingStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ru/DotNetEventingStrings.ru.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ru/DotNetEventingStrings.ru.resx new file mode 100644 index 00000000000..f8701d3187d --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/ru/DotNetEventingStrings.ru.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 + + + Требуется неотрицательное число. + + + Параметр идентификатора должен быть в диапазоне от {0} до {1}. + + + Общее число параметров не должно превышать {0}. + + + Число параметров String не должно превышать {0}. + + + Разделитель не может быть пустой строкой. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/tr/DotNetEventingStrings.tr.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/tr/DotNetEventingStrings.tr.resx new file mode 100644 index 00000000000..f54223e4207 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/tr/DotNetEventingStrings.tr.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 + + + Negatif olmayan bir sayı gerekiyor. + + + ID parametresi {0} - {1} aralığında olmalıdır. + + + Parametrelerin toplam sayısı en çok {0} olabilir. + + + String parametrelerinin sayısı en fazla {0} olabilir. + + + Sınırlayıcı boş bir dize olamaz. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/zh-Hans/DotNetEventingStrings.zh-Hans.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/zh-Hans/DotNetEventingStrings.zh-Hans.resx new file mode 100644 index 00000000000..02de983ce12 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/zh-Hans/DotNetEventingStrings.zh-Hans.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 + + + 需要非负数。 + + + ID 参数必须处于 {0} 到 {1} 的范围内。 + + + 参数的总数不能超过 {0}。 + + + 字符串参数的数量不能超过 {0}。 + + + 分隔符不能为空字符串。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/zh-Hant/DotNetEventingStrings.zh-Hant.resx b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/zh-Hant/DotNetEventingStrings.zh-Hant.resx new file mode 100644 index 00000000000..1ab6d057c03 --- /dev/null +++ b/src/Microsoft.PowerShell.CoreCLR.Eventing/resources/zh-Hant/DotNetEventingStrings.zh-Hant.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 + + + 需要使用非負數。 + + + ID 參數必須在 {0} 到 {1} 的範圍內。 + + + 參數總數不得超過 {0}。 + + + String 參數的數目不得超過 {0}。 + + + 分隔符號不能為空字串。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs b/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs index 47a66ea8767..356cde68152 100644 --- a/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs +++ b/src/Microsoft.PowerShell.GlobalTool.Shim/GlobalToolShim.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; @@ -10,7 +11,7 @@ namespace Microsoft.PowerShell.GlobalTool.Shim /// /// Shim layer to chose the appropriate runtime for PowerShell DotNet Global tool. /// - public class EntryPoint + public static class EntryPoint { private const string PwshDllName = "pwsh.dll"; @@ -26,13 +27,14 @@ public class EntryPoint public static int Main(string[] args) { var currentPath = new FileInfo(System.Reflection.Assembly.GetEntryAssembly().Location).Directory.FullName; - var isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + var isWindows = OperatingSystem.IsWindows(); string platformFolder = isWindows ? WinFolderName : UnixFolderName; - string argsString = args.Length > 0 ? string.Join(" ", args) : null; + var arguments = new List(args.Length + 1); var pwshPath = Path.Combine(currentPath, platformFolder, PwshDllName); - string processArgs = string.IsNullOrEmpty(argsString) ? $"\"{pwshPath}\"" : $"\"{pwshPath}\" {argsString}"; + arguments.Add(pwshPath); + arguments.AddRange(args); if (File.Exists(pwshPath)) { @@ -41,7 +43,7 @@ public static int Main(string[] args) e.Cancel = true; }; - var process = System.Diagnostics.Process.Start("dotnet", processArgs); + var process = System.Diagnostics.Process.Start("dotnet", arguments); process.WaitForExit(); return process.ExitCode; } diff --git a/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj b/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj index aa845a7817d..d0203344cc2 100644 --- a/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj +++ b/src/Microsoft.PowerShell.GlobalTool.Shim/Microsoft.PowerShell.GlobalTool.Shim.csproj @@ -6,6 +6,7 @@ Microsoft.PowerShell.GlobalTool.Shim EXE Microsoft.PowerShell.GlobalTool.Shim + False diff --git a/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json b/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json index 8ba6dc2eba9..4a5e3e367ec 100644 --- a/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json +++ b/src/Microsoft.PowerShell.GlobalTool.Shim/runtimeconfig.template.json @@ -1,4 +1,4 @@ -// This is required to roll forward to runtime 3.x when 2.x is not installed +// This is required to roll forward to supported minor.patch versions of the runtime. { - "rollForwardOnNoCandidateFx": 2 + "rollForwardOnNoCandidateFx": 1 } diff --git a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs deleted file mode 100644 index 375a8101075..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/AddLocalGroupMemberCommand.cs +++ /dev/null @@ -1,304 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs deleted file mode 100644 index 09e7bdf9452..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/DisableLocalUserCommand.cs +++ /dev/null @@ -1,220 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs deleted file mode 100644 index e321a03e266..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/EnableLocalUserCommand.cs +++ /dev/null @@ -1,220 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs deleted file mode 100644 index 3965c362335..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupCommand.cs +++ /dev/null @@ -1,171 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs deleted file mode 100644 index a10300e9065..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalGroupMemberCommand.cs +++ /dev/null @@ -1,236 +0,0 @@ -// 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((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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs deleted file mode 100644 index e469d043ffa..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/GetLocalUserCommand.cs +++ /dev/null @@ -1,173 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs deleted file mode 100644 index 59e4f4ca13f..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalGroupCommand.cs +++ /dev/null @@ -1,121 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs deleted file mode 100644 index b3916f46071..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/NewLocalUserCommand.cs +++ /dev/null @@ -1,295 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs deleted file mode 100644 index 0c0af710af1..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupCommand.cs +++ /dev/null @@ -1,213 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs deleted file mode 100644 index 7e132405b2a..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalGroupMemberCommand.cs +++ /dev/null @@ -1,302 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs deleted file mode 100644 index 0c61da2e117..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RemoveLocalUserCommand.cs +++ /dev/null @@ -1,214 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs deleted file mode 100644 index f32e3365086..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalGroupCommand.cs +++ /dev/null @@ -1,233 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs deleted file mode 100644 index e6b1297a7d5..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/RenameLocalUserCommand.cs +++ /dev/null @@ -1,233 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs deleted file mode 100644 index b1943971e3d..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalGroupCommand.cs +++ /dev/null @@ -1,180 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs deleted file mode 100644 index 8fafa52c9e4..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Commands/SetLocalUserCommand.cs +++ /dev/null @@ -1,323 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs deleted file mode 100644 index 1c7a7630ea3..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Exceptions.cs +++ /dev/null @@ -1,689 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs deleted file mode 100644 index 007966cb0a8..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Extensions.cs +++ /dev/null @@ -1,206 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs deleted file mode 100644 index b43904fb773..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalGroup.cs +++ /dev/null @@ -1,77 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs deleted file mode 100644 index dcfec24631b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalPrincipal.cs +++ /dev/null @@ -1,100 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs deleted file mode 100644 index 9cad9777cac..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/LocalUser.cs +++ /dev/null @@ -1,142 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs deleted file mode 100644 index c34dbcd64d8..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Native.cs +++ /dev/null @@ -1,424 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs deleted file mode 100644 index 654d221a69b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/NtStatus.cs +++ /dev/null @@ -1,519 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs deleted file mode 100644 index 68a7d31e833..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/PInvokeDllNames.cs +++ /dev/null @@ -1,30 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs deleted file mode 100644 index e87147fd35d..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/Sam.cs +++ /dev/null @@ -1,3276 +0,0 @@ -// 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 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 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) - { - if (version == null) - throw new ArgumentNullException("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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs deleted file mode 100644 index c2d9bc7f95b..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/SamApi.cs +++ /dev/null @@ -1,468 +0,0 @@ -// 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/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs b/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs deleted file mode 100644 index 3534b34cc49..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/LocalAccounts/StringUtil.cs +++ /dev/null @@ -1,70 +0,0 @@ -// 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 precent auto-generation of a default constructor with greater accessability. - /// - 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/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj b/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj deleted file mode 100644 index a85b06d4f90..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/Microsoft.PowerShell.LocalAccounts.csproj +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - PowerShell's Microsoft.PowerShell.LocalAccounts project - Microsoft.PowerShell.LocalAccounts - - - - - - - diff --git a/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx b/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx deleted file mode 100644 index ff1c4a17427..00000000000 --- a/src/Microsoft.PowerShell.LocalAccounts/resources/Microsoft.PowerShell.LocalAccounts.Strings.resx +++ /dev/null @@ -1,234 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj index b6d7fa7f936..f92790f15cc 100644 --- a/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj +++ b/src/Microsoft.PowerShell.SDK/Microsoft.PowerShell.SDK.csproj @@ -15,22 +15,41 @@ + + + - + - - - + + - - - - - - + + + - - + - + + + + + <_RefAssemblyPath Include="%(_ReferencesFromRAR.OriginalItemSpec)%3B" Condition=" '%(_ReferencesFromRAR.NuGetPackageId)' != 'Microsoft.Management.Infrastructure' " /> + + + + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs b/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs deleted file mode 100644 index 3e2e4ff3268..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/AssemblyInfo.cs +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Reflection; -using System.Resources; - -[assembly:AssemblyFileVersionAttribute("3.0.0.0")] -[assembly:AssemblyVersion("3.0.0.0")] - -[assembly:AssemblyCulture("")] -[assembly:NeutralResourcesLanguage("en-US")] diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs deleted file mode 100644 index 4c7dcb146a9..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJob.cs +++ /dev/null @@ -1,1285 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.ComponentModel; -using System.IO; -using System.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Runspaces; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Text; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This is a Job2 derived class that contains a DefinitionJob for - /// running job definition based jobs but can also save and load job - /// results data from file. This class is used to load job result - /// data from previously run jobs so that a user can view results of - /// scheduled job runs. This class also contains the definition of - /// the scheduled job and so can run an instance of the scheduled - /// job and optionally save results to file. - /// - [Serializable] - public sealed class ScheduledJob : Job2, ISerializable - { - #region Private Members - - private ScheduledJobDefinition _jobDefinition; - private Runspace _runspace; - private System.Management.Automation.PowerShell _powerShell; - private Job _job = null; - private bool _asyncJobStop; - private bool _allowSetShouldExit; - private PSHost _host; - - private const string AllowHostSetShouldExit = "AllowSetShouldExitFromRemote"; - - private StatusInfo _statusInfo; - - #endregion - - #region Public Properties - - /// - /// ScheduledJobDefinition. - /// - public ScheduledJobDefinition Definition - { - get { return _jobDefinition; } - - internal set { _jobDefinition = value; } - } - - /// - /// Location of job being run. - /// - public override string Location - { - get - { - return Status.Location; - } - } - - /// - /// Status Message associated with the Job. - /// - public override string StatusMessage - { - get - { - return Status.StatusMessage; - } - } - - /// - /// Indicates whether more data is available from Job. - /// - public override bool HasMoreData - { - get - { - return (_job != null) ? - _job.HasMoreData - : - (Output.Count > 0 || - Error.Count > 0 || - Warning.Count > 0 || - Verbose.Count > 0 || - Progress.Count > 0 || - Debug.Count > 0 || - Information.Count > 0 - ); - } - } - - /// - /// Job command string. - /// - public new string Command - { - get - { - return Status.Command; - } - } - - /// - /// Internal property indicating whether a SetShouldExit is honored - /// while running the scheduled job script. - /// - internal bool AllowSetShouldExit - { - get { return _allowSetShouldExit; } - - set { _allowSetShouldExit = value; } - } - - #endregion - - #region Constructors - - /// - /// Constructor. - /// - /// Job command string for display. - /// Name of job. - /// ScheduledJobDefinition defining job to run. - public ScheduledJob( - string command, - string name, - ScheduledJobDefinition jobDefinition) : - base(command, name) - { - if (command == null) - { - throw new PSArgumentNullException("command"); - } - - if (name == null) - { - throw new PSArgumentNullException("name"); - } - - if (jobDefinition == null) - { - throw new PSArgumentNullException("jobDefinition"); - } - - _jobDefinition = jobDefinition; - - PSJobTypeName = ScheduledJobSourceAdapter.AdapterTypeName; - } - - #endregion - - #region Public Overrides - - /// - /// Starts a job as defined by the contained ScheduledJobDefinition object. - /// - public override void StartJob() - { - lock (SyncRoot) - { - if (_job != null && !IsFinishedState(_job.JobStateInfo.State)) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.JobAlreadyRunning, _jobDefinition.Name); - throw new PSInvalidOperationException(msg); - } - - _statusInfo = null; - _asyncJobStop = false; - PSBeginTime = DateTime.Now; - - if (_powerShell == null) - { - InitialSessionState iss = InitialSessionState.CreateDefault2(); - iss.Commands.Clear(); - iss.Formats.Clear(); - iss.Commands.Add( - new SessionStateCmdletEntry("Start-Job", typeof(Microsoft.PowerShell.Commands.StartJobCommand), null)); - - // Get the default host from the default runspace. - _host = GetDefaultHost(); - _runspace = RunspaceFactory.CreateRunspace(_host, iss); - _runspace.Open(); - _powerShell = System.Management.Automation.PowerShell.Create(); - _powerShell.Runspace = _runspace; - - // Indicate SetShouldExit to host. - AddSetShouldExitToHost(); - } - else - { - _powerShell.Commands.Clear(); - } - - _job = StartJobCommand(_powerShell); - - _job.StateChanged += new EventHandler(HandleJobStateChanged); - SetJobState(_job.JobStateInfo.State); - - // Add all child jobs to this object's list so that - // the user and Receive-Job can retrieve results. - foreach (Job childJob in _job.ChildJobs) - { - this.ChildJobs.Add(childJob); - } - - // Add this job to the local repository. - ScheduledJobSourceAdapter.AddToRepository(this); - } - } - - /// - /// Start job asynchronously. - /// - public override void StartJobAsync() - { - // StartJob(); - throw new PSNotSupportedException(); - } - - /// - /// Stop the job. - /// - public override void StopJob() - { - Job job; - JobState state; - lock (SyncRoot) - { - job = _job; - state = Status.State; - _asyncJobStop = false; - } - - if (IsFinishedState(state)) - { - return; - } - - if (job == null) - { - // Set job state to failed so that it can be removed from the - // cache using Remove-Job. - SetJobState(JobState.Failed); - } - else - { - job.StopJob(); - } - } - - /// - /// Stop the job asynchronously. - /// - public override void StopJobAsync() - { - Job job; - JobState state; - lock (SyncRoot) - { - job = _job; - state = Status.State; - _asyncJobStop = true; - } - - if (IsFinishedState(state)) - { - return; - } - - if (job == null) - { - // Set job state to failed so that it can be removed from the - // cache using Remove-Job. - SetJobState(JobState.Failed); - HandleJobStateChanged(this, - new JobStateEventArgs( - new JobStateInfo(JobState.Failed))); - } - else - { - job.StopJob(); - } - } - - /// - /// SuspendJob. - /// - public override void SuspendJob() - { - throw new PSNotSupportedException(); - } - - /// - /// SuspendJobAsync. - /// - public override void SuspendJobAsync() - { - throw new PSNotSupportedException(); - } - - /// - /// ResumeJob. - /// - public override void ResumeJob() - { - throw new PSNotSupportedException(); - } - - /// - /// ResumeJobAsync. - /// - public override void ResumeJobAsync() - { - throw new PSNotSupportedException(); - } - - /// - /// UnblockJob. - /// - public override void UnblockJob() - { - throw new PSNotSupportedException(); - } - - /// - /// UnblockJobAsync. - /// - public override void UnblockJobAsync() - { - throw new PSNotSupportedException(); - } - - /// - /// StopJob. - /// - /// - /// - public override void StopJob(bool force, string reason) - { - throw new PSNotSupportedException(); - } - - /// - /// StopJobAsync. - /// - /// - /// - public override void StopJobAsync(bool force, string reason) - { - throw new PSNotSupportedException(); - } - /// - /// SuspendJob. - /// - /// - /// - public override void SuspendJob(bool force, string reason) - { - throw new PSNotSupportedException(); - } - - /// - /// SuspendJobAsync. - /// - /// - /// - public override void SuspendJobAsync(bool force, string reason) - { - throw new PSNotSupportedException(); - } - - #endregion - - #region Implementation of ISerializable - - /// - /// Deserialize constructor. - /// - /// SerializationInfo. - /// StreamingContext. - private ScheduledJob( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - DeserializeStatusInfo(info); - DeserializeResultsInfo(info); - PSJobTypeName = ScheduledJobSourceAdapter.AdapterTypeName; - } - - /// - /// Serialize method. - /// - /// SerializationInfo. - /// StreamingContext. - public void GetObjectData( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentException("info"); - } - - SerializeStatusInfo(info); - SerializeResultsInfo(info); - } - - private void SerializeStatusInfo(SerializationInfo info) - { - StatusInfo statusInfo = new StatusInfo( - InstanceId, - Name, - Location, - Command, - StatusMessage, - (_job != null) ? _job.JobStateInfo.State : JobStateInfo.State, - HasMoreData, - PSBeginTime, - PSEndTime, - _jobDefinition); - - info.AddValue("StatusInfo", statusInfo); - } - - private void SerializeResultsInfo(SerializationInfo info) - { - // All other job information is in the child jobs. - Collection output = new Collection(); - Collection error = new Collection(); - Collection warning = new Collection(); - Collection verbose = new Collection(); - Collection progress = new Collection(); - Collection debug = new Collection(); - Collection information = new Collection(); - - if (_job != null) - { - // Collect data from "live" job. - - if (JobStateInfo.Reason != null) - { - error.Add(new ErrorRecord(JobStateInfo.Reason, "ScheduledJobFailedState", ErrorCategory.InvalidResult, null)); - } - - foreach (var item in _job.Error) - { - error.Add(item); - } - - foreach (Job childJob in ChildJobs) - { - if (childJob.JobStateInfo.Reason != null) - { - error.Add(new ErrorRecord(childJob.JobStateInfo.Reason, "ScheduledJobFailedState", ErrorCategory.InvalidResult, null)); - } - - foreach (var item in childJob.Output) - { - output.Add(item); - } - - foreach (var item in childJob.Error) - { - error.Add(item); - } - - foreach (var item in childJob.Warning) - { - warning.Add(item); - } - - foreach (var item in childJob.Verbose) - { - verbose.Add(item); - } - - foreach (var item in childJob.Progress) - { - progress.Add(item); - } - - foreach (var item in childJob.Debug) - { - debug.Add(item); - } - - foreach (var item in childJob.Information) - { - information.Add(item); - } - } - } - else - { - // Collect data from object collections. - - foreach (var item in Output) - { - // Wrap the base object in a new PSObject. This is necessary because the - // source deserialized PSObject doesn't serialize again correctly and breaks - // PS F&O. Not sure if this is a PSObject serialization bug or not. - output.Add(new PSObject(item.BaseObject)); - } - - foreach (var item in Error) - { - error.Add(item); - } - - foreach (var item in Warning) - { - warning.Add(item); - } - - foreach (var item in Verbose) - { - verbose.Add(item); - } - - foreach (var item in Progress) - { - progress.Add(item); - } - - foreach (var item in Debug) - { - debug.Add(item); - } - - foreach (var item in Information) - { - information.Add(item); - } - } - - ResultsInfo resultsInfo = new ResultsInfo( - output, error, warning, verbose, progress, debug, information); - - info.AddValue("ResultsInfo", resultsInfo); - } - - private void DeserializeStatusInfo(SerializationInfo info) - { - StatusInfo statusInfo = (StatusInfo)info.GetValue("StatusInfo", typeof(StatusInfo)); - - Name = statusInfo.Name; - PSBeginTime = statusInfo.StartTime; - PSEndTime = statusInfo.StopTime; - _jobDefinition = statusInfo.Definition; - SetJobState(statusInfo.State, null); - - lock (SyncRoot) - { - _statusInfo = statusInfo; - } - } - - private void DeserializeResultsInfo(SerializationInfo info) - { - ResultsInfo resultsInfo = (ResultsInfo)info.GetValue("ResultsInfo", typeof(ResultsInfo)); - - // Output - CopyOutput(resultsInfo.Output); - - // Error - CopyError(resultsInfo.Error); - - // Warning - CopyWarning(resultsInfo.Warning); - - // Verbose - CopyVerbose(resultsInfo.Verbose); - - // Progress - CopyProgress(resultsInfo.Progress); - - // Debug - CopyDebug(resultsInfo.Debug); - - // Information - CopyInformation(resultsInfo.Information); - } - - #endregion - - #region Internal Methods - - /// - /// Method to update a ScheduledJob based on new state and - /// result data from a provided Job. - /// - /// ScheduledJob to update from. - internal void Update(ScheduledJob fromJob) - { - // We do not update "live" jobs. - if (_job != null || fromJob == null) - { - return; - } - - // - // Update status. - // - PSEndTime = fromJob.PSEndTime; - JobState state = fromJob.JobStateInfo.State; - if (Status.State != state) - { - SetJobState(state, null); - } - - lock (SyncRoot) - { - _statusInfo = new StatusInfo( - fromJob.InstanceId, - fromJob.Name, - fromJob.Location, - fromJob.Command, - fromJob.StatusMessage, - state, - fromJob.HasMoreData, - fromJob.PSBeginTime, - fromJob.PSEndTime, - fromJob._jobDefinition); - } - - // - // Update results. - // - CopyOutput(fromJob.Output); - CopyError(fromJob.Error); - CopyWarning(fromJob.Warning); - CopyVerbose(fromJob.Verbose); - CopyProgress(fromJob.Progress); - CopyDebug(fromJob.Debug); - CopyInformation(fromJob.Information); - } - - #endregion - - #region Private Methods - - private System.Management.Automation.Host.PSHost GetDefaultHost() - { - System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace).AddScript("$host"); - Collection hosts = ps.Invoke(); - if (hosts == null || hosts.Count == 0) - { - System.Diagnostics.Debug.Assert(false, "Current runspace should always return default host."); - return null; - } - - return hosts[0]; - } - - private Job StartJobCommand(System.Management.Automation.PowerShell powerShell) - { - Job job = null; - - // Use PowerShell Start-Job cmdlet to run job. - powerShell.AddCommand("Start-Job"); - - powerShell.AddParameter("Name", _jobDefinition.Name); - - // Add job parameters from the JobInvocationInfo object. - CommandParameterCollection parameters = _jobDefinition.InvocationInfo.Parameters[0]; - foreach (CommandParameter parameter in parameters) - { - switch (parameter.Name) - { - case "ScriptBlock": - powerShell.AddParameter("ScriptBlock", parameter.Value as ScriptBlock); - break; - - case "FilePath": - powerShell.AddParameter("FilePath", parameter.Value as string); - break; - - case "RunAs32": - powerShell.AddParameter("RunAs32", (bool)parameter.Value); - break; - - case "Authentication": - powerShell.AddParameter("Authentication", (AuthenticationMechanism)parameter.Value); - break; - - case "InitializationScript": - powerShell.AddParameter("InitializationScript", parameter.Value as ScriptBlock); - break; - - case "ArgumentList": - powerShell.AddParameter("ArgumentList", parameter.Value as object[]); - break; - } - } - - // Start the job. - Collection rtn = powerShell.Invoke(); - if (rtn != null && rtn.Count == 1) - { - job = rtn[0].BaseObject as Job; - } - - return job; - } - - private void HandleJobStateChanged(object sender, JobStateEventArgs e) - { - SetJobState(e.JobStateInfo.State); - - if (IsFinishedState(e.JobStateInfo.State)) - { - PSEndTime = DateTime.Now; - - // Dispose the PowerShell and Runspace objects. - System.Management.Automation.PowerShell disposePowerShell = null; - Runspace disposeRunspace = null; - lock (SyncRoot) - { - if (_job != null && - IsFinishedState(_job.JobStateInfo.State)) - { - disposePowerShell = _powerShell; - _powerShell = null; - disposeRunspace = _runspace; - _runspace = null; - } - } - - if (disposePowerShell != null) - { - disposePowerShell.Dispose(); - } - - if (disposeRunspace != null) - { - disposeRunspace.Dispose(); - } - - // Raise async job stopped event, if needed. - if (_asyncJobStop) - { - _asyncJobStop = false; - OnStopJobCompleted(new AsyncCompletedEventArgs(null, false, null)); - } - - // Remove AllowSetShouldExit from host. - RemoveSetShouldExitFromHost(); - } - } - - internal bool IsFinishedState(JobState state) - { - return (state == JobState.Completed || state == JobState.Failed || state == JobState.Stopped); - } - - private StatusInfo Status - { - get - { - StatusInfo statusInfo; - lock (SyncRoot) - { - if (_statusInfo != null) - { - // Pass back static status. - statusInfo = _statusInfo; - } - else if (_job != null) - { - // Create current job status. - statusInfo = new StatusInfo( - _job.InstanceId, - _job.Name, - _job.Location, - _job.Command, - _job.StatusMessage, - _job.JobStateInfo.State, - _job.HasMoreData, - PSBeginTime, - PSEndTime, - _jobDefinition); - } - else - { - // Create default static empty status. - _statusInfo = new StatusInfo( - Guid.Empty, - string.Empty, - string.Empty, - string.Empty, - string.Empty, - JobState.NotStarted, - false, - PSBeginTime, - PSEndTime, - _jobDefinition); - - statusInfo = _statusInfo; - } - } - - return statusInfo; - } - } - - private void CopyOutput(ICollection fromOutput) - { - PSDataCollection output = CopyResults(fromOutput); - if (output != null) - { - try - { - Output = output; - } - catch (InvalidJobStateException) { } - } - } - - private void CopyError(ICollection fromError) - { - PSDataCollection error = CopyResults(fromError); - if (error != null) - { - try - { - Error = error; - } - catch (InvalidJobStateException) { } - } - } - - private void CopyWarning(ICollection fromWarning) - { - PSDataCollection warning = CopyResults(fromWarning); - if (warning != null) - { - try - { - Warning = warning; - } - catch (InvalidJobStateException) { } - } - } - - private void CopyVerbose(ICollection fromVerbose) - { - PSDataCollection verbose = CopyResults(fromVerbose); - if (verbose != null) - { - try - { - Verbose = verbose; - } - catch (InvalidJobStateException) { } - } - } - - private void CopyProgress(ICollection fromProgress) - { - PSDataCollection progress = CopyResults(fromProgress); - if (progress != null) - { - try - { - Progress = progress; - } - catch (InvalidJobStateException) { } - } - } - - private void CopyDebug(ICollection fromDebug) - { - PSDataCollection debug = CopyResults(fromDebug); - if (debug != null) - { - try - { - Debug = debug; - } - catch (InvalidJobStateException) { } - } - } - - private void CopyInformation(ICollection fromInformation) - { - PSDataCollection information = CopyResults(fromInformation); - if (information != null) - { - try - { - Information = information; - } - catch (InvalidJobStateException) { } - } - } - - private PSDataCollection CopyResults(ICollection fromResults) - { - if (fromResults != null && fromResults.Count > 0) - { - PSDataCollection returnResults = new PSDataCollection(); - foreach (var item in fromResults) - { - returnResults.Add(item); - } - - return returnResults; - } - - return null; - } - - private void AddSetShouldExitToHost() - { - if (!_allowSetShouldExit || _host == null) { return; } - - PSObject hostPrivateData = _host.PrivateData as PSObject; - if (hostPrivateData != null) - { - // Adds or replaces. - hostPrivateData.Properties.Add(new PSNoteProperty(AllowHostSetShouldExit, true)); - } - } - - private void RemoveSetShouldExitFromHost() - { - if (!_allowSetShouldExit || _host == null) { return; } - - PSObject hostPrivateData = _host.PrivateData as PSObject; - if (hostPrivateData != null) - { - // Removes if exists. - hostPrivateData.Properties.Remove(AllowHostSetShouldExit); - } - } - - #endregion - - #region Private ResultsInfo class - - [Serializable] - private class ResultsInfo : ISerializable - { - // Private Members - private Collection _output; - private Collection _error; - private Collection _warning; - private Collection _verbose; - private Collection _progress; - private Collection _debug; - private Collection _information; - - // Properties - internal Collection Output - { - get { return _output; } - } - - internal Collection Error - { - get { return _error; } - } - - internal Collection Warning - { - get { return _warning; } - } - - internal Collection Verbose - { - get { return _verbose; } - } - - internal Collection Progress - { - get { return _progress; } - } - - internal Collection Debug - { - get { return _debug; } - } - - internal Collection Information - { - get { return _information; } - } - - // Constructors - internal ResultsInfo( - Collection output, - Collection error, - Collection warning, - Collection verbose, - Collection progress, - Collection debug, - Collection information - ) - { - if (output == null) - { - throw new PSArgumentNullException("output"); - } - - if (error == null) - { - throw new PSArgumentNullException("error"); - } - - if (warning == null) - { - throw new PSArgumentNullException("warning"); - } - - if (verbose == null) - { - throw new PSArgumentNullException("verbose"); - } - - if (progress == null) - { - throw new PSArgumentNullException("progress"); - } - - if (debug == null) - { - throw new PSArgumentNullException("debug"); - } - - if (information == null) - { - throw new PSArgumentNullException("information"); - } - - _output = output; - _error = error; - _warning = warning; - _verbose = verbose; - _progress = progress; - _debug = debug; - _information = information; - } - - // ISerializable - private ResultsInfo( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - _output = (Collection)info.GetValue("Results_Output", typeof(Collection)); - _error = (Collection)info.GetValue("Results_Error", typeof(Collection)); - _warning = (Collection)info.GetValue("Results_Warning", typeof(Collection)); - _verbose = (Collection)info.GetValue("Results_Verbose", typeof(Collection)); - _progress = (Collection)info.GetValue("Results_Progress", typeof(Collection)); - _debug = (Collection)info.GetValue("Results_Debug", typeof(Collection)); - - try - { - _information = (Collection)info.GetValue("Results_Information", typeof(Collection)); - } - catch(SerializationException) - { - // The job might not have the info stream. Ignore. - _information = new Collection(); - } - } - - public void GetObjectData( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentException("info"); - } - - info.AddValue("Results_Output", _output); - info.AddValue("Results_Error", _error); - info.AddValue("Results_Warning", _warning); - info.AddValue("Results_Verbose", _verbose); - info.AddValue("Results_Progress", _progress); - info.AddValue("Results_Debug", _debug); - info.AddValue("Results_Information", _information); - } - } - - #endregion - } - - #region Internal StatusInfo Class - - [Serializable] - internal class StatusInfo : ISerializable - { - // Private Members - private Guid _instanceId; - private string _name; - private string _location; - private string _command; - private string _statusMessage; - private JobState _jobState; - private bool _hasMoreData; - private DateTime? _startTime; - private DateTime? _stopTime; - private ScheduledJobDefinition _definition; - - // Properties - internal Guid InstanceId - { - get { return _instanceId; } - } - - internal string Name - { - get { return _name; } - } - - internal string Location - { - get { return _location; } - } - - internal string Command - { - get { return _command; } - } - - internal string StatusMessage - { - get { return _statusMessage; } - } - - internal JobState State - { - get { return _jobState; } - } - - internal bool HasMoreData - { - get { return _hasMoreData; } - } - - internal DateTime? StartTime - { - get { return _startTime; } - } - - internal DateTime? StopTime - { - get { return _stopTime; } - } - - internal ScheduledJobDefinition Definition - { - get { return _definition; } - } - - // Constructors - internal StatusInfo( - Guid instanceId, - string name, - string location, - string command, - string statusMessage, - JobState jobState, - bool hasMoreData, - DateTime? startTime, - DateTime? stopTime, - ScheduledJobDefinition definition) - { - if (definition == null) - { - throw new PSArgumentNullException("definition"); - } - - _instanceId = instanceId; - _name = name; - _location = location; - _command = command; - _statusMessage = statusMessage; - _jobState = jobState; - _hasMoreData = hasMoreData; - _startTime = startTime; - _stopTime = stopTime; - _definition = definition; - } - - // ISerializable - private StatusInfo( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - _instanceId = Guid.Parse(info.GetString("Status_InstanceId")); - _name = info.GetString("Status_Name"); - _location = info.GetString("Status_Location"); - _command = info.GetString("Status_Command"); - _statusMessage = info.GetString("Status_Message"); - _jobState = (JobState)info.GetValue("Status_State", typeof(JobState)); - _hasMoreData = info.GetBoolean("Status_MoreData"); - _definition = (ScheduledJobDefinition)info.GetValue("Status_Definition", typeof(ScheduledJobDefinition)); - - DateTime startTime = info.GetDateTime("Status_StartTime"); - if (startTime != DateTime.MinValue) - { - _startTime = startTime; - } - else - { - _startTime = null; - } - - DateTime stopTime = info.GetDateTime("Status_StopTime"); - if (stopTime != DateTime.MinValue) - { - _stopTime = stopTime; - } - else - { - _stopTime = null; - } - } - - public void GetObjectData( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - info.AddValue("Status_InstanceId", _instanceId); - info.AddValue("Status_Name", _name); - info.AddValue("Status_Location", _location); - info.AddValue("Status_Command", _command); - info.AddValue("Status_Message", _statusMessage); - info.AddValue("Status_State", _jobState); - info.AddValue("Status_MoreData", _hasMoreData); - info.AddValue("Status_Definition", _definition); - - if (_startTime != null) - { - info.AddValue("Status_StartTime", _startTime); - } - else - { - info.AddValue("Status_StartTime", DateTime.MinValue); - } - - if (_stopTime != null) - { - info.AddValue("Status_StopTime", _stopTime); - } - else - { - info.AddValue("Status_StopTime", DateTime.MinValue); - } - } - } - - #endregion -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs deleted file mode 100644 index ecb4fc9caa6..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobDefinition.cs +++ /dev/null @@ -1,2585 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Management.Automation.Tracing; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Text.RegularExpressions; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This class contains all information needed to define a PowerShell job that - /// can be scheduled to run through either stand-alone or through the Windows - /// Task Scheduler. - /// - [Serializable] - public sealed class ScheduledJobDefinition : ISerializable, IDisposable - { - #region Private Members - - private JobInvocationInfo _invocationInfo; - private ScheduledJobOptions _options; - private PSCredential _credential; - private Guid _globalId = Guid.NewGuid(); - private string _name = string.Empty; - private int _id = GetCurrentId(); - private int _executionHistoryLength = DefaultExecutionHistoryLength; - private bool _enabled = true; - private Dictionary _triggers = new Dictionary(); - private Int32 _currentTriggerId; - - private string _definitionFilePath; - private string _definitionOutputPath; - - private bool _isDisposed; - - // Task Action strings. - private const string TaskExecutionPath = @"pwsh.exe"; - private const string TaskArguments = @"-NoLogo -NonInteractive -WindowStyle Hidden -Command ""Import-Module PSScheduledJob; $jobDef = [Microsoft.PowerShell.ScheduledJob.ScheduledJobDefinition]::LoadFromStore('{0}', '{1}'); $jobDef.Run()"""; - private static object LockObject = new object(); - private static int CurrentId = 0; - private static int DefaultExecutionHistoryLength = 32; - - internal static ScheduledJobDefinitionRepository Repository = new ScheduledJobDefinitionRepository(); - - // Task Scheduler COM error codes. - private const int TSErrorDisabledTask = -2147216602; - - #endregion - - #region Public Properties - - /// - /// Contains information needed to run the job such as script parameters, - /// job definition, user credentials, etc. - /// - public JobInvocationInfo InvocationInfo - { - get { return _invocationInfo; } - } - - /// - /// Contains the script commands that define the job. - /// - public JobDefinition Definition - { - get { return _invocationInfo.Definition; } - } - - /// - /// Specifies Task Scheduler options for the scheduled job. - /// - public ScheduledJobOptions Options - { - get { return new ScheduledJobOptions(_options); } - } - - /// - /// Credential. - /// - public PSCredential Credential - { - get { return _credential; } - - internal set { _credential = value; } - } - - /// - /// An array of trigger objects that specify a time/condition - /// for when the job is run. - /// - public List JobTriggers - { - get - { - List notFoundIds; - return GetTriggers(null, out notFoundIds); - } - } - - /// - /// Local instance Id for object instance. - /// - public int Id - { - get { return _id; } - } - - /// - /// Global Id for scheduled job definition. - /// - public Guid GlobalId - { - get { return _globalId; } - } - - /// - /// Name of scheduled job definition. - /// - public string Name - { - get { return _name; } - } - - /// - /// Job command. - /// - public string Command - { - get { return _invocationInfo.Command; } - } - - /// - /// Returns the maximum number of job execution data - /// allowed in the job store. - /// - public int ExecutionHistoryLength - { - get { return _executionHistoryLength; } - } - - /// - /// Determines whether this scheduled job definition is enabled - /// in Task Scheduler. - /// - public bool Enabled - { - get { return _enabled; } - } - - /// - /// Returns the PowerShell command line execution path. - /// - public string PSExecutionPath - { - get { return TaskExecutionPath; } - } - - /// - /// Returns PowerShell command line arguments to run - /// the scheduled job. - /// - public string PSExecutionArgs - { - get - { - // Escape single quotes in name. Double quotes are not allowed - // and are caught during name validation. - string nameEscapeQuotes = _invocationInfo.Name.Replace("'", "''"); - - return string.Format(CultureInfo.InvariantCulture, TaskArguments, nameEscapeQuotes, _definitionFilePath); - } - } - - /// - /// Returns the job run output path for this job definition. - /// - internal string OutputPath - { - get { return _definitionOutputPath; } - } - - #endregion - - #region Constructors - - /// - /// Default constructor is not accessible. - /// - private ScheduledJobDefinition() - { } - - /// - /// Constructor. - /// - /// Information to invoke Job. - /// ScheduledJobTriggers. - /// ScheduledJobOptions. - /// Credential. - public ScheduledJobDefinition( - JobInvocationInfo invocationInfo, - IEnumerable triggers, - ScheduledJobOptions options, - PSCredential credential) - { - if (invocationInfo == null) - { - throw new PSArgumentNullException("invocationInfo"); - } - - _name = invocationInfo.Name; - _invocationInfo = invocationInfo; - - SetTriggers(triggers, false); - _options = (options != null) ? new ScheduledJobOptions(options) : - new ScheduledJobOptions(); - _options.JobDefinition = this; - - _credential = credential; - } - - #endregion - - #region ISerializable Implementation - - /// - /// Serialization constructor. - /// - /// SerializationInfo. - /// StreamingContext. - private ScheduledJobDefinition( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - _options = (ScheduledJobOptions)info.GetValue("Options_Member", typeof(ScheduledJobOptions)); - _globalId = Guid.Parse(info.GetString("GlobalId_Member")); - _name = info.GetString("Name_Member"); - _executionHistoryLength = info.GetInt32("HistoryLength_Member"); - _enabled = info.GetBoolean("Enabled_Member"); - _triggers = (Dictionary)info.GetValue("Triggers_Member", typeof(Dictionary)); - _currentTriggerId = info.GetInt32("CurrentTriggerId_Member"); - _definitionFilePath = info.GetString("FilePath_Member"); - _definitionOutputPath = info.GetString("OutputPath_Member"); - - object invocationObject = info.GetValue("InvocationInfo_Member", typeof(object)); - _invocationInfo = invocationObject as JobInvocationInfo; - - // Set the JobDefinition reference for the ScheduledJobTrigger and - // ScheduledJobOptions objects. - _options.JobDefinition = this; - foreach (ScheduledJobTrigger trigger in _triggers.Values) - { - trigger.JobDefinition = this; - } - - // Instance information. - _isDisposed = false; - } - - /// - /// Serialization constructor. - /// - /// SerializationInfo. - /// StreamingContext. - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - info.AddValue("Options_Member", _options); - info.AddValue("GlobalId_Member", _globalId.ToString()); - info.AddValue("Name_Member", _name); - info.AddValue("HistoryLength_Member", _executionHistoryLength); - info.AddValue("Enabled_Member", _enabled); - info.AddValue("Triggers_Member", _triggers); - info.AddValue("CurrentTriggerId_Member", _currentTriggerId); - info.AddValue("FilePath_Member", _definitionFilePath); - info.AddValue("OutputPath_Member", _definitionOutputPath); - - info.AddValue("InvocationInfo_Member", _invocationInfo); - } - - #endregion - - #region Private Methods - - /// - /// Updates existing information if scheduled job already exists. - /// WTS entry includes command line, options, and trigger conditions. - /// - private void UpdateWTSFromDefinition() - { - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - taskScheduler.UpdateTask(this); - } - } - - /// - /// Compares the current ScheduledJobDefinition task scheduler information - /// with the corresponding information stored in Task Scheduler. If the - /// information is different then the task scheduler information in this - /// object is updated to match what is in Task Scheduler, since that information - /// takes precedence. - /// - /// Task Scheduler information: - /// - Triggers - /// - Options - /// - Enabled state. - /// - /// Boolean if this object data is modified. - private bool UpdateDefinitionFromWTS() - { - bool dataModified = false; - - // Get information from Task Scheduler. - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - bool wtsEnabled = taskScheduler.GetTaskEnabled(_name); - ScheduledJobOptions wtsOptions = taskScheduler.GetJobOptions(_name); - Collection wtsTriggers = taskScheduler.GetJobTriggers(_name); - - // - // Compare with existing object data and modify if necessary. - // - - // Enabled. - if (wtsEnabled != _enabled) - { - _enabled = wtsEnabled; - dataModified = true; - } - - // Options. - if (wtsOptions.DoNotAllowDemandStart != _options.DoNotAllowDemandStart || - wtsOptions.IdleDuration != _options.IdleDuration || - wtsOptions.IdleTimeout != _options.IdleTimeout || - wtsOptions.MultipleInstancePolicy != _options.MultipleInstancePolicy || - wtsOptions.RestartOnIdleResume != _options.RestartOnIdleResume || - wtsOptions.RunElevated != _options.RunElevated || - wtsOptions.RunWithoutNetwork != _options.RunWithoutNetwork || - wtsOptions.ShowInTaskScheduler != _options.ShowInTaskScheduler || - wtsOptions.StartIfNotIdle != _options.StartIfNotIdle || - wtsOptions.StartIfOnBatteries != _options.StartIfOnBatteries || - wtsOptions.StopIfGoingOffIdle != _options.StopIfGoingOffIdle || - wtsOptions.StopIfGoingOnBatteries != _options.StopIfGoingOnBatteries || - wtsOptions.WakeToRun != _options.WakeToRun) - { - // Keep the current scheduled job definition reference. - wtsOptions.JobDefinition = _options.JobDefinition; - _options = wtsOptions; - dataModified = true; - } - - // Triggers. - if (_triggers.Count != wtsTriggers.Count) - { - SetTriggers(wtsTriggers, false); - dataModified = true; - } - else - { - bool foundTriggerDiff = false; - - // Compare each trigger object. - foreach (var wtsTrigger in wtsTriggers) - { - if (_triggers.ContainsKey(wtsTrigger.Id) == false) - { - foundTriggerDiff = true; - break; - } - - ScheduledJobTrigger trigger = _triggers[wtsTrigger.Id]; - if (trigger.DaysOfWeek != wtsTrigger.DaysOfWeek || - trigger.Enabled != wtsTrigger.Enabled || - trigger.Frequency != wtsTrigger.Frequency || - trigger.Interval != wtsTrigger.Interval || - trigger.RandomDelay != wtsTrigger.RandomDelay || - trigger.At != wtsTrigger.At || - trigger.User != wtsTrigger.User) - { - foundTriggerDiff = true; - break; - } - } - - if (foundTriggerDiff) - { - SetTriggers(wtsTriggers, false); - dataModified = true; - } - } - } - - return dataModified; - } - - /// - /// Adds this scheduled job definition to the Task Scheduler. - /// - private void AddToWTS() - { - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - taskScheduler.CreateTask(this); - } - } - - /// - /// Removes this scheduled job definition from the Task Scheduler. - /// This operation will fail if a current instance of this job definition - /// is running. - /// If force == true then all current instances will be stopped. - /// - /// Force removal and stop all running instances. - private void RemoveFromWTS(bool force) - { - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - taskScheduler.RemoveTask(this, force); - } - } - - /// - /// Adds this scheduled job definition to the job definition store. - /// - private void AddToJobStore() - { - FileStream fs = null; - try - { - fs = ScheduledJobStore.CreateFileForJobDefinition(Name); - _definitionFilePath = ScheduledJobStore.GetJobDefinitionLocation(); - _definitionOutputPath = ScheduledJobStore.GetJobRunOutputDirectory(Name); - - XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); - serializer.WriteObject(fs, this); - fs.Flush(); - } - finally - { - if (fs != null) - { - fs.Close(); - } - } - - // If credentials are provided then update permissions. - if (Credential != null) - { - UpdateFilePermissions(Credential.UserName); - } - } - - /// - /// Updates existing file with this definition information. - /// - private void UpdateJobStore() - { - FileStream fs = null; - try - { - // Overwrite the existing file. - fs = GetFileStream( - Name, - _definitionFilePath, - FileMode.Create, - FileAccess.Write, - FileShare.None); - - XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); - serializer.WriteObject(fs, this); - fs.Flush(); - } - finally - { - if (fs != null) - { - fs.Close(); - } - } - - // If credentials are provided then update permissions. - if (Credential != null) - { - UpdateFilePermissions(Credential.UserName); - } - } - - /// - /// Updates definition file permissions for provided user account. - /// - /// Account user name. - private void UpdateFilePermissions(string user) - { - Exception ex = null; - try - { - // Add user for read access to the job definition file. - ScheduledJobStore.SetReadAccessOnDefinitionFile(Name, user); - - // Add user for write access to the job run Output directory. - ScheduledJobStore.SetWriteAccessOnJobRunOutput(Name, user); - } - catch (System.Security.Principal.IdentityNotMappedException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (ArgumentNullException e) - { - ex = e; - } - - if (ex != null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorSettingAccessPermissions, this.Name, Credential.UserName); - throw new ScheduledJobException(msg, ex); - } - } - - /// - /// Removes this scheduled job definition from the job definition store. - /// - private void RemoveFromJobStore() - { - ScheduledJobStore.RemoveJobDefinition(Name); - } - - /// - /// Throws exception if object is disposed. - /// - private void IsDisposed() - { - if (_isDisposed == true) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionObjectDisposed, Name); - throw new RuntimeException(msg); - } - } - - /// - /// If repository is empty try refreshing it from the store. - /// - private void LoadRepository() - { - ScheduledJobDefinition.RefreshRepositoryFromStore(); - } - - /// - /// Validates all triggers in collection. An exception is thrown - /// for invalid triggers. - /// - /// - private void ValidateTriggers(IEnumerable triggers) - { - if (triggers != null) - { - foreach (var trigger in triggers) - { - trigger.Validate(); - } - } - } - - /// - /// Validates the job definition name. Since the job definition - /// name is used in the job store as a directory name, make sure - /// it does not contain any invalid characters. - /// - private static void ValidateName(string name) - { - if (name.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidJobDefName, name); - throw new ScheduledJobException(msg); - } - } - - /// - /// Iterates through all job run files, opens each job - /// run and renames it to the provided new name. - /// - /// New job run name. - private void UpdateJobRunNames( - string newDefName) - { - // Job run results will be under the new scheduled job definition name. - Collection jobRuns = ScheduledJobSourceAdapter.GetJobRuns(newDefName); - if (jobRuns == null) - { - return; - } - - // Load and rename each job. - ScheduledJobDefinition definition = ScheduledJobDefinition.LoadFromStore(newDefName, null); - foreach (DateTime jobRun in jobRuns) - { - ScheduledJob job = null; - try - { - job = ScheduledJobSourceAdapter.LoadJobFromStore(definition.Name, jobRun) as ScheduledJob; - } - catch (ScheduledJobException) - { - continue; - } - catch (DirectoryNotFoundException) - { - continue; - } - catch (FileNotFoundException) - { - continue; - } - catch (UnauthorizedAccessException) - { - continue; - } - catch (IOException) - { - continue; - } - - if (job != null) - { - job.Name = newDefName; - job.Definition = definition; - ScheduledJobSourceAdapter.SaveJobToStore(job); - } - } - } - - /// - /// Handles known Task Scheduler COM error codes. - /// - /// COMException. - /// Error message. - private string ConvertCOMErrorCode(System.Runtime.InteropServices.COMException e) - { - string msg = null; - switch (e.ErrorCode) - { - case TSErrorDisabledTask: - msg = ScheduledJobErrorStrings.ReasonTaskDisabled; - break; - } - - return msg; - } - - #endregion - - #region Internal Methods - - /// - /// Save object to store. - /// - internal void SaveToStore() - { - IsDisposed(); - - UpdateJobStore(); - } - - /// - /// Compares the task scheduler information in this object with - /// what is stored in Task Scheduler. If there is a difference - /// then this object is updated with the information from Task - /// Scheduler and saved to the job store. - /// - internal void SyncWithWTS() - { - Exception notFoundEx = null; - try - { - if (UpdateDefinitionFromWTS()) - { - SaveToStore(); - } - } - catch (DirectoryNotFoundException e) - { - notFoundEx = e; - } - catch (FileNotFoundException e) - { - notFoundEx = e; - } - - if (notFoundEx != null) - { - // There is no corresponding Task Scheduler item for this - // scheduled job definition. Remove this definition from - // the job store for consistency. - Remove(true); - throw notFoundEx; - } - } - - /// - /// Renames scheduled job definition, store directory and task scheduler task. - /// - /// New name of job definition. - internal void RenameAndSave(string newName) - { - if (InvocationInfo.Name.Equals(newName, StringComparison.OrdinalIgnoreCase)) - { - return; - } - - ValidateName(newName); - - // Attempt to rename job store directory. Detect if new name - // is not unique. - string oldName = InvocationInfo.Name; - Exception ex = null; - try - { - ScheduledJobStore.RenameScheduledJobDefDir(oldName, newName); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - - if (ex != null) - { - string msg; - if (!string.IsNullOrEmpty(ex.Message)) - { - msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRenamingScheduledJobWithMessage, oldName, newName, ex.Message); - } - else - { - msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRenamingScheduledJob, oldName, newName); - } - - throw new ScheduledJobException(msg, ex); - } - - try - { - // Remove old named Task Scheduler task. - // This also stops any existing running job. - RemoveFromWTS(true); - - // Update job definition names. - _name = newName; - InvocationInfo.Name = newName; - InvocationInfo.Definition.Name = newName; - _definitionOutputPath = ScheduledJobStore.GetJobRunOutputDirectory(Name); - - // Update job definition in new job store location. - UpdateJobStore(); - - // Add new Task Scheduler task with new name. - // Jobs can start running again. - AddToWTS(); - - // Update any existing job run names. - UpdateJobRunNames(newName); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - finally - { - // Clear job run cache since job runs now appear in new directory location. - ScheduledJobSourceAdapter.ClearRepository(); - } - - // If any part of renaming the various scheduled job components fail, - // aggressively remove scheduled job corrupted state and inform user. - if (ex != null) - { - try - { - Remove(true); - } - catch (ScheduledJobException e) - { - ex.Data.Add("SchedJobRemoveError", e); - } - - string msg; - if (!string.IsNullOrEmpty(ex.Message)) - { - msg = StringUtil.Format(ScheduledJobErrorStrings.BrokenRenamingScheduledJobWithMessage, oldName, newName, ex.Message); - } - else - { - msg = StringUtil.Format(ScheduledJobErrorStrings.BrokenRenamingScheduledJob, oldName, newName); - } - - throw new ScheduledJobException(msg, ex); - } - } - - #endregion - - #region Public Methods - - /// - /// Registers this scheduled job definition object by doing the - /// following: - /// a) Writing this object to the scheduled job object store. - /// b) Registering this job as a Windows Task Scheduler task. - /// c) Adding this object to the local repository. - /// - public void Register() - { - IsDisposed(); - - LoadRepository(); - - ValidateName(Name); - - // First add to the job store. If an exception occurs here - // then this method fails with no clean up. - Exception ex = null; - bool corruptedFile = false; - try - { - AddToJobStore(); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (System.Runtime.Serialization.SerializationException e) - { - corruptedFile = true; - ex = e; - } - catch (System.Runtime.Serialization.InvalidDataContractException e) - { - corruptedFile = true; - ex = e; - } - catch (ScheduledJobException e) - { - // Can be thrown for error setting file access permissions with supplied credentials. - // But file is not considered corrupted if it already exists. - corruptedFile = !(e.FQEID.Equals(ScheduledJobStore.ScheduledJobDefExistsFQEID, StringComparison.OrdinalIgnoreCase)); - ex = e; - } - - if (ex != null) - { - if (corruptedFile) - { - // Remove from store. - try - { - ScheduledJobStore.RemoveJobDefinition(Name); - } - catch (DirectoryNotFoundException) - { } - catch (FileNotFoundException) - { } - catch (UnauthorizedAccessException) - { } - catch (IOException) - { } - } - - if (ex is not ScheduledJobException) - { - // Wrap in ScheduledJobException type. - string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRegisteringDefinitionStore, this.Name); - throw new ScheduledJobException(msg, ex); - } - else - { - // Otherwise just re-throw. - throw ex; - } - } - - // Next register with the Task Scheduler. - ex = null; - try - { - AddToWTS(); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (System.Runtime.InteropServices.COMException e) - { - ex = e; - } - - if (ex != null) - { - // Clean up job store. - RemoveFromJobStore(); - - string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRegisteringDefinitionTask, - this.Name, - (string.IsNullOrEmpty(ex.Message) == false) ? ex.Message : string.Empty); - throw new ScheduledJobException(msg, ex); - } - - // Finally add to the local repository. - Repository.AddOrReplace(this); - } - - /// - /// Saves this scheduled job definition object: - /// a) Rewrites this object to the scheduled job object store. - /// b) Updates the Windows Task Scheduler task. - /// - public void Save() - { - IsDisposed(); - - LoadRepository(); - - ValidateName(Name); - - // First update the Task Scheduler. If an exception occurs here then - // we fail with no clean up. - Exception ex = null; - try - { - UpdateWTSFromDefinition(); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (System.Runtime.InteropServices.COMException e) - { - ex = e; - } - - if (ex != null) - { - // We want this object to remain synchronized with what is in WTS. - SyncWithWTS(); - - string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorUpdatingDefinitionTask, this.Name); - throw new ScheduledJobException(msg, ex); - } - - // Next save to job store. - ex = null; - try - { - UpdateJobStore(); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - - if (ex != null) - { - // Remove this from WTS for consistency. - RemoveFromWTS(true); - - string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorUpdatingDefinitionStore, this.Name); - throw new ScheduledJobException(msg, ex); - } - - // Finally update this object in the local repository. - ScheduledJobDefinition.RefreshRepositoryFromStore(); - Repository.AddOrReplace(this); - } - - /// - /// Removes this definition object: - /// a) Removes from the Task Scheduler - /// or fails if an instance is currently running. - /// or stops any running instances if force is true. - /// b) Removes from the scheduled job definition store. - /// c) Removes from the local repository. - /// d) Disposes this object. - /// - public void Remove(bool force) - { - IsDisposed(); - - // First remove from Task Scheduler. Catch not found - // exceptions and continue. - try - { - RemoveFromWTS(force); - } - catch (System.IO.DirectoryNotFoundException) - { - // Continue with removal. - } - catch (System.IO.FileNotFoundException) - { - // Continue with removal. - } - - // Remove from the Job Store. Catch exceptions and continue - // with removal. - Exception ex = null; - try - { - RemoveFromJobStore(); - } - catch (DirectoryNotFoundException) - { - } - catch (FileNotFoundException) - { - } - catch (ArgumentException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - finally - { - // Remove from the local repository. - Repository.Remove(this); - - // Remove job runs for this definition from local repository. - ScheduledJobSourceAdapter.ClearRepositoryForDefinition(this.Name); - - // Dispose this object. - Dispose(); - } - - if (ex != null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRemovingDefinitionStore, this.Name); - throw new ScheduledJobException(msg, ex); - } - } - - /// - /// Starts the scheduled job immediately. A ScheduledJob object is - /// returned that represents the running command, and this returned - /// job is also added to the local job repository. Job results are - /// not written to the job store. - /// - /// ScheduledJob object for running job. - public ScheduledJob StartJob() - { - IsDisposed(); - - ScheduledJob job = new ScheduledJob(_invocationInfo.Command, _invocationInfo.Name, this); - job.StartJob(); - - return job; - } - - /// - /// Starts registered job definition running from the Task Scheduler. - /// - public void RunAsTask() - { - IsDisposed(); - - Exception ex = null; - string reason = null; - try - { - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - taskScheduler.RunTask(this); - } - } - catch (System.IO.DirectoryNotFoundException e) - { - reason = ScheduledJobErrorStrings.reasonJobNotFound; - ex = e; - } - catch (System.IO.FileNotFoundException e) - { - reason = ScheduledJobErrorStrings.reasonJobNotFound; - ex = e; - } - catch (System.Runtime.InteropServices.COMException e) - { - reason = ConvertCOMErrorCode(e); - ex = e; - } - - if (ex != null) - { - string msg; - if (reason != null) - { - msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRunningAsTaskWithReason, this.Name, reason); - } - else - { - msg = StringUtil.Format(ScheduledJobErrorStrings.ErrorRunningAsTask, this.Name); - } - - throw new ScheduledJobException(msg, ex); - } - } - - #endregion - - #region Public Trigger Methods - - /// - /// Adds new ScheduledJobTriggers. - /// - /// Collection of ScheduledJobTrigger objects. - /// Update Windows Task Scheduler and save to store. - public void AddTriggers( - IEnumerable triggers, - bool save) - { - IsDisposed(); - - if (triggers == null) - { - throw new PSArgumentNullException("triggers"); - } - - // First validate all triggers. - ValidateTriggers(triggers); - - Collection newTriggerIds = new Collection(); - foreach (ScheduledJobTrigger trigger in triggers) - { - ScheduledJobTrigger newTrigger = new ScheduledJobTrigger(trigger); - - newTrigger.Id = ++_currentTriggerId; - newTriggerIds.Add(newTrigger.Id); - newTrigger.JobDefinition = this; - _triggers.Add(newTrigger.Id, newTrigger); - } - - if (save) - { - Save(); - } - } - - /// - /// Removes triggers matching passed in trigger Ids. - /// - /// Trigger Ids to remove. - /// Update Windows Task Scheduler and save to store. - /// Trigger Ids not found. - public List RemoveTriggers( - IEnumerable triggerIds, - bool save) - { - IsDisposed(); - - List idsNotFound = new List(); - bool triggerFound = false; - - // triggerIds is null then remove all triggers. - if (triggerIds == null) - { - _currentTriggerId = 0; - if (_triggers.Count > 0) - { - triggerFound = true; - - foreach (ScheduledJobTrigger trigger in _triggers.Values) - { - trigger.Id = 0; - trigger.JobDefinition = null; - } - - // Create new empty trigger collection. - _triggers = new Dictionary(); - } - } - else - { - foreach (Int32 removeId in triggerIds) - { - if (_triggers.ContainsKey(removeId)) - { - _triggers[removeId].JobDefinition = null; - _triggers[removeId].Id = 0; - _triggers.Remove(removeId); - triggerFound = true; - } - else - { - idsNotFound.Add(removeId); - } - } - } - - if (save && triggerFound) - { - Save(); - } - - return idsNotFound; - } - - /// - /// Updates triggers with provided trigger objects, matching passed in - /// trigger Id with existing trigger Id. - /// - /// Collection of ScheduledJobTrigger objects to update. - /// Update Windows Task Scheduler and save to store. - /// Trigger Ids not found. - public List UpdateTriggers( - IEnumerable triggers, - bool save) - { - IsDisposed(); - - if (triggers == null) - { - throw new PSArgumentNullException("triggers"); - } - - // First validate all triggers. - ValidateTriggers(triggers); - - List idsNotFound = new List(); - bool triggerFound = false; - foreach (ScheduledJobTrigger updateTrigger in triggers) - { - if (_triggers.ContainsKey(updateTrigger.Id)) - { - // Disassociate old trigger from this definition. - _triggers[updateTrigger.Id].JobDefinition = null; - - // Replace older trigger object with new updated one. - ScheduledJobTrigger newTrigger = new ScheduledJobTrigger(updateTrigger); - newTrigger.Id = updateTrigger.Id; - newTrigger.JobDefinition = this; - _triggers[newTrigger.Id] = newTrigger; - triggerFound = true; - } - else - { - idsNotFound.Add(updateTrigger.Id); - } - } - - if (save && triggerFound) - { - Save(); - } - - return idsNotFound; - } - - /// - /// Creates a new set of ScheduledJobTriggers for this object. - /// - /// Array of ScheduledJobTrigger objects to set. - /// Update Windows Task Scheduler and save to store. - public void SetTriggers( - IEnumerable newTriggers, - bool save) - { - IsDisposed(); - - // First validate all triggers. - ValidateTriggers(newTriggers); - - // Disassociate any old trigger objects from this definition. - foreach (ScheduledJobTrigger trigger in _triggers.Values) - { - trigger.JobDefinition = null; - } - - _currentTriggerId = 0; - _triggers = new Dictionary(); - if (newTriggers != null) - { - foreach (ScheduledJobTrigger trigger in newTriggers) - { - ScheduledJobTrigger newTrigger = new ScheduledJobTrigger(trigger); - - newTrigger.Id = ++_currentTriggerId; - newTrigger.JobDefinition = this; - _triggers.Add(newTrigger.Id, newTrigger); - } - } - - if (save) - { - Save(); - } - } - - /// - /// Returns a list of new ScheduledJobTrigger objects corresponding - /// to the passed in trigger Ids. Also returns an array of trigger Ids - /// that were not found in an out parameter. - /// - /// List of trigger Ids. - /// List of not found trigger Ids. - /// List of ScheduledJobTrigger objects. - public List GetTriggers( - IEnumerable triggerIds, - out List notFoundIds) - { - IsDisposed(); - - List newTriggers; - List notFoundList = new List(); - if (triggerIds == null) - { - // Return all triggers. - newTriggers = new List(); - foreach (ScheduledJobTrigger trigger in _triggers.Values) - { - newTriggers.Add(new ScheduledJobTrigger(trigger)); - } - } - else - { - // Filter returned triggers to match requested. - newTriggers = new List(); - foreach (Int32 triggerId in triggerIds) - { - if (_triggers.ContainsKey(triggerId)) - { - newTriggers.Add(new ScheduledJobTrigger(_triggers[triggerId])); - } - else - { - notFoundList.Add(triggerId); - } - } - } - - notFoundIds = notFoundList; - - // Return array of ScheduledJobTrigger objects sorted by Id. - newTriggers.Sort((firstTrigger, secondTrigger) => - { - return ((int)firstTrigger.Id - (int)secondTrigger.Id); - }); - - return newTriggers; - } - - /// - /// Finds and returns a copy of the ScheduledJobTrigger corresponding to - /// the passed in trigger Id. - /// - /// Trigger Id. - /// ScheduledJobTrigger object. - public ScheduledJobTrigger GetTrigger( - Int32 triggerId) - { - IsDisposed(); - - if (_triggers.ContainsKey(triggerId)) - { - return new ScheduledJobTrigger(_triggers[triggerId]); - } - - return null; - } - - #endregion - - #region Public Update Methods - - /// - /// Updates scheduled job options. - /// - /// ScheduledJobOptions or null for default. - /// Update Windows Task Scheduler and save to store. - public void UpdateOptions( - ScheduledJobOptions options, - bool save) - { - IsDisposed(); - - // Disassociate current options object from this definition. - _options.JobDefinition = null; - - // options == null is allowed and signals the use default - // Task Scheduler options. - _options = (options != null) ? new ScheduledJobOptions(options) : - new ScheduledJobOptions(); - _options.JobDefinition = this; - - if (save) - { - Save(); - } - } - - /// - /// Sets the execution history length property. - /// - /// Execution history length. - /// Save to store. - public void SetExecutionHistoryLength( - int executionHistoryLength, - bool save) - { - IsDisposed(); - - _executionHistoryLength = executionHistoryLength; - - if (save) - { - SaveToStore(); - } - } - - /// - /// Clears all execution results in the job store. - /// - public void ClearExecutionHistory() - { - IsDisposed(); - - ScheduledJobStore.RemoveAllJobRuns(Name); - ScheduledJobSourceAdapter.ClearRepositoryForDefinition(Name); - } - - /// - /// Updates the JobInvocationInfo object. - /// - /// JobInvocationInfo. - /// Save to store. - public void UpdateJobInvocationInfo( - JobInvocationInfo jobInvocationInfo, - bool save) - { - IsDisposed(); - - if (jobInvocationInfo == null) - { - throw new PSArgumentNullException("jobInvocationInfo"); - } - - _invocationInfo = jobInvocationInfo; - _name = jobInvocationInfo.Name; - - if (save) - { - SaveToStore(); - } - } - - /// - /// Sets the enabled state of this object. - /// - /// True if enabled. - /// Update Windows Task Scheduler and save to store. - public void SetEnabled( - bool enabled, - bool save) - { - IsDisposed(); - - _enabled = enabled; - - if (save) - { - Save(); - } - } - - /// - /// Sets the name of this scheduled job definition. - /// - /// Name. - /// Update Windows Task Scheduler and save to store. - public void SetName( - string name, - bool save) - { - IsDisposed(); - - _name = (name != null) ? name : string.Empty; - - if (save) - { - Save(); - } - } - - #endregion - - #region IDisposable - - /// - /// Dispose. - /// - public void Dispose() - { - _isDisposed = true; - - GC.SuppressFinalize(this); - } - - #endregion - - #region Static Methods - - /// - /// Synchronizes the local ScheduledJobDefinition repository with the - /// scheduled job definitions in the job store. - /// - /// Callback delegate for each discovered item. - /// Dictionary of errors. - internal static Dictionary RefreshRepositoryFromStore( - Action itemFound = null) - { - Dictionary errors = new Dictionary(); - - // Get current list of job definition files in store, and create hash - // table for quick look up. - IEnumerable jobDefinitionPathNames = ScheduledJobStore.GetJobDefinitions(); - HashSet jobDefinitionNamesHash = new HashSet(); - foreach (string pathName in jobDefinitionPathNames) - { - // Remove path information and use job definition name only. - int indx = pathName.LastIndexOf('\\'); - string jobDefName = (indx != -1) ? pathName.Substring(indx + 1) : pathName; - jobDefinitionNamesHash.Add(jobDefName); - } - - // First remove definition objects not in store. - // Repository.Definitions returns a *copy* of current repository items. - foreach (ScheduledJobDefinition jobDef in Repository.Definitions) - { - if (jobDefinitionNamesHash.Contains(jobDef.Name) == false) - { - Repository.Remove(jobDef); - } - else - { - jobDefinitionNamesHash.Remove(jobDef.Name); - - if (itemFound != null) - { - itemFound(jobDef); - } - } - } - - // Next add definition items not in local repository. - foreach (string jobDefinitionName in jobDefinitionNamesHash) - { - try - { - // Read the job definition object from file and add to local repository. - ScheduledJobDefinition jobDefinition = ScheduledJobDefinition.LoadDefFromStore(jobDefinitionName, null); - Repository.AddOrReplace(jobDefinition); - - if (itemFound != null) - { - itemFound(jobDefinition); - } - } - catch (System.IO.IOException e) - { - errors.Add(jobDefinitionName, e); - } - catch (System.Xml.XmlException e) - { - errors.Add(jobDefinitionName, e); - } - catch (System.TypeInitializationException e) - { - errors.Add(jobDefinitionName, e); - } - catch (System.Runtime.Serialization.SerializationException e) - { - errors.Add(jobDefinitionName, e); - } - catch (System.ArgumentNullException e) - { - errors.Add(jobDefinitionName, e); - } - catch (System.UnauthorizedAccessException e) - { - errors.Add(jobDefinitionName, e); - } - } - - return errors; - } - - /// - /// Reads a ScheduledJobDefinition object from file and - /// returns object. - /// - /// Name of definition to load. - /// Path to definition file. - /// ScheduledJobDefinition object. - internal static ScheduledJobDefinition LoadDefFromStore( - string definitionName, - string definitionPath) - { - ScheduledJobDefinition definition = null; - FileStream fs = null; - try - { - fs = GetFileStream( - definitionName, - definitionPath, - FileMode.Open, - FileAccess.Read, - FileShare.Read); - - XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); - definition = serializer.ReadObject(fs) as ScheduledJobDefinition; - } - finally - { - if (fs != null) - { - fs.Close(); - } - } - - return definition; - } - - /// - /// Creates a new ScheduledJobDefinition object from a file. - /// - /// Name of definition to load. - /// Path to definition file. - /// ScheduledJobDefinition object. - public static ScheduledJobDefinition LoadFromStore( - string definitionName, - string definitionPath) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentNullException("definitionName"); - } - - ScheduledJobDefinition definition = null; - bool corruptedFile = false; - Exception ex = null; - - try - { - definition = LoadDefFromStore(definitionName, definitionPath); - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - corruptedFile = true; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (System.Xml.XmlException e) - { - ex = e; - corruptedFile = true; - } - catch (System.TypeInitializationException e) - { - ex = e; - corruptedFile = true; - } - catch (System.ArgumentNullException e) - { - ex = e; - corruptedFile = true; - } - catch (System.Runtime.Serialization.SerializationException e) - { - ex = e; - corruptedFile = true; - } - - if (ex != null) - { - // - // Remove definition if corrupted. - // But only if the corrupted file is in the default scheduled jobs - // path for the current user. - // - if (corruptedFile && - (definitionPath == null || - ScheduledJobStore.IsDefaultUserPath(definitionPath))) - { - // Remove corrupted scheduled job definition. - RemoveDefinition(definitionName); - - // Throw exception for corrupted/removed job definition. - throw new ScheduledJobException( - StringUtil.Format(ScheduledJobErrorStrings.CantLoadDefinitionFromStore, definitionName), - ex); - } - - // Throw exception for not found job definition. - throw new ScheduledJobException( - StringUtil.Format(ScheduledJobErrorStrings.CannotFindJobDefinition, definitionName), - ex); - } - - // Make sure the deserialized ScheduledJobDefinition object contains the same - // Task Scheduler information that is stored in Task Scheduler. - definition.SyncWithWTS(); - - return definition; - } - - /// - /// Internal helper method to remove a scheduled job definition - /// by name from job store and Task Scheduler. - /// - /// Scheduled job definition name. - internal static void RemoveDefinition( - string definitionName) - { - // Remove from store. - try - { - ScheduledJobStore.RemoveJobDefinition(definitionName); - } - catch (DirectoryNotFoundException) - { } - catch (FileNotFoundException) - { } - catch (UnauthorizedAccessException) - { } - catch (IOException) - { } - - // Check and remove from Task Scheduler. - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - try - { - taskScheduler.RemoveTaskByName(definitionName, true, true); - } - catch (UnauthorizedAccessException) - { } - catch (IOException) - { } - } - } - - private static int GetCurrentId() - { - lock (LockObject) - { - return ++CurrentId; - } - } - - /// - /// Starts a scheduled job based on definition name and returns the - /// running job object. Returned job is also added to the local - /// job repository. Job results are not written to store. - /// - /// ScheduledJobDefinition name. - public static Job2 StartJob( - string DefinitionName) - { - // Load scheduled job definition. - ScheduledJobDefinition jobDefinition = ScheduledJobDefinition.LoadFromStore(DefinitionName, null); - - // Start job. - return jobDefinition.StartJob(); - } - - private static FileStream GetFileStream( - string definitionName, - string definitionPath, - FileMode fileMode, - FileAccess fileAccess, - FileShare fileShare) - { - FileStream fs; - - if (definitionPath == null) - { - // Look for definition in default current user location. - fs = ScheduledJobStore.GetFileForJobDefinition( - definitionName, - fileMode, - fileAccess, - fileShare); - } - else - { - // Look for definition in known path. - fs = ScheduledJobStore.GetFileForJobDefinition( - definitionName, - definitionPath, - fileMode, - fileAccess, - fileShare); - } - - return fs; - } - - #endregion - - #region Running Job - - /// - /// Create a Job2 job, runs it and waits for it to complete. - /// Job status and results are written to the job store. - /// - /// Job2 job object that was run. - public Job2 Run() - { - Job2 job = null; - - using (PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource()) - { - Exception ex = null; - try - { - JobManager jobManager = Runspace.DefaultRunspace.JobManager; - - job = jobManager.NewJob(InvocationInfo); - - // If this is a scheduled job type then include this object so - // so that ScheduledJobSourceAdapter knows where the results are - // to be stored. - ScheduledJob schedJob = job as ScheduledJob; - if (schedJob != null) - { - schedJob.Definition = this; - schedJob.AllowSetShouldExit = true; - } - - // Update job store data when job begins. - job.StateChanged += (object sender, JobStateEventArgs e) => - { - if (e.JobStateInfo.State == JobState.Running) - { - // Write job to store with this running state. - jobManager.PersistJob(job, Definition); - } - }; - - job.StartJob(); - - // Log scheduled job start. - _tracer.WriteScheduledJobStartEvent( - job.Name, - job.PSBeginTime.ToString()); - - // Wait for job to finish. - job.Finished.WaitOne(); - - // Ensure that the job run results are persisted to store. - jobManager.PersistJob(job, Definition); - - // Perform a Receive-Job on the job object. Output data will be dropped - // but we do this to execute any client method calls, in particular we - // want SetShouldExit to set the correct exit code on the process for - // use inside Task Scheduler. - using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) - { - // Run on the default runspace. - ps.AddCommand("Receive-Job").AddParameter("Job", job).AddParameter("Keep", true); - ps.Invoke(); - } - - // Log scheduled job finish. - _tracer.WriteScheduledJobCompleteEvent( - job.Name, - job.PSEndTime.ToString(), - job.JobStateInfo.State.ToString()); - } - catch (RuntimeException e) - { - ex = e; - } - catch (InvalidOperationException e) - { - ex = e; - } - catch (System.Security.SecurityException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (ArgumentException e) - { - ex = e; - } - catch (ScriptCallDepthException e) - { - ex = e; - } - catch (System.Runtime.Serialization.SerializationException e) - { - ex = e; - } - catch (System.Runtime.Serialization.InvalidDataContractException e) - { - ex = e; - } - catch (System.Xml.XmlException e) - { - ex = e; - } - catch (Microsoft.PowerShell.ScheduledJob.ScheduledJobException e) - { - ex = e; - } - - if (ex != null) - { - // Log error. - _tracer.WriteScheduledJobErrorEvent( - this.Name, - ex.Message, - ex.StackTrace.ToString(), - (ex.InnerException != null) ? ex.InnerException.Message : string.Empty); - - throw ex; - } - } - - return job; - } - - #endregion - } - - #region ScheduledJobDefinition Repository - - /// - /// Collection of ScheduledJobDefinition objects. - /// - internal class ScheduledJobDefinitionRepository - { - #region Private Members - - private object _syncObject = new object(); - private Dictionary _definitions = new Dictionary(); - - #endregion - - #region Public Properties - - /// - /// Returns all definition objects in the repository as a List. - /// - public List Definitions - { - get - { - lock (_syncObject) - { - // Sort returned list by Ids. - List rtnList = - new List(_definitions.Values); - - rtnList.Sort((firstJob, secondJob) => - { - if (firstJob.Id > secondJob.Id) - { - return 1; - } - else if (firstJob.Id < secondJob.Id) - { - return -1; - } - else - { - return 0; - } - }); - - return rtnList; - } - } - } - - /// - /// Returns count of object in repository. - /// - public int Count - { - get - { - lock (_syncObject) - { - return _definitions.Count; - } - } - } - - #endregion - - #region Public Methods - - /// - /// Add ScheduledJobDefinition to repository. - /// - /// - public void Add(ScheduledJobDefinition jobDef) - { - if (jobDef == null) - { - throw new PSArgumentNullException("jobDef"); - } - - lock (_syncObject) - { - if (_definitions.ContainsKey(jobDef.Name)) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionAlreadyExistsInLocal, jobDef.Name, jobDef.GlobalId); - throw new ScheduledJobException(msg); - } - - _definitions.Add(jobDef.Name, jobDef); - } - } - - /// - /// Add or replace passed in ScheduledJobDefinition object to repository. - /// - /// - public void AddOrReplace(ScheduledJobDefinition jobDef) - { - if (jobDef == null) - { - throw new PSArgumentNullException("jobDef"); - } - - lock (_syncObject) - { - if (_definitions.ContainsKey(jobDef.Name)) - { - _definitions.Remove(jobDef.Name); - } - - _definitions.Add(jobDef.Name, jobDef); - } - } - - /// - /// Remove ScheduledJobDefinition from repository. - /// - /// - public void Remove(ScheduledJobDefinition jobDef) - { - if (jobDef == null) - { - throw new PSArgumentNullException("jobDef"); - } - - lock (_syncObject) - { - if (_definitions.ContainsKey(jobDef.Name)) - { - _definitions.Remove(jobDef.Name); - } - } - } - - /// - /// Checks to see if a ScheduledJobDefinition object exists with - /// the provided definition name. - /// - /// Definition name. - /// True if definition exists. - public bool Contains(string jobDefName) - { - lock (_syncObject) - { - return _definitions.ContainsKey(jobDefName); - } - } - - /// - /// Clears all ScheduledJobDefinition items from the repository. - /// - public void Clear() - { - lock (_syncObject) - { - _definitions.Clear(); - } - } - - #endregion - } - - #endregion - - #region Exceptions - - /// - /// Exception thrown for errors in Scheduled Jobs. - /// - [Serializable] - public class ScheduledJobException : SystemException - { - /// - /// Creates a new instance of ScheduledJobException class. - /// - public ScheduledJobException() - : base - ( - StringUtil.Format(ScheduledJobErrorStrings.GeneralWTSError) - ) - { - } - - /// - /// Creates a new instance of ScheduledJobException class. - /// - /// - /// The error message that explains the reason for the exception. - /// - public ScheduledJobException(string message) - : base(message) - { - } - - /// - /// Creates a new instance of ScheduledJobException class. - /// - /// - /// The error message that explains the reason for the exception. - /// - /// - /// The exception that is the cause of the current exception. - /// - public ScheduledJobException(string message, Exception innerException) - : base(message, innerException) - { - } - - /// - /// Fully qualified error id for exception. - /// - internal string FQEID - { - get { return _fqeid; } - - set { _fqeid = value ?? string.Empty; } - } - - private string _fqeid = string.Empty; - } - - #endregion - - #region Utilities - - /// - /// Simple string formatting helper. - /// - internal class StringUtil - { - internal static string Format(string formatSpec, object o) - { - return string.Format(System.Threading.Thread.CurrentThread.CurrentCulture, formatSpec, o); - } - - internal static string Format(string formatSpec, params object[] o) - { - return string.Format(System.Threading.Thread.CurrentThread.CurrentCulture, formatSpec, o); - } - } - - #endregion - - #region ScheduledJobInvocationInfo Class - - /// - /// This class defines the JobInvocationInfo class for PowerShell jobs - /// for job scheduling. The following parameters are supported: - /// - /// "ScriptBlock" -> ScriptBlock - /// "FilePath" -> String - /// "InitializationScript" -> ScriptBlock - /// "ArgumentList" -> object[] - /// "RunAs32" -> Boolean - /// "Authentication" -> AuthenticationMechanism. - /// - [Serializable] - public sealed class ScheduledJobInvocationInfo : JobInvocationInfo - { - #region Constructors - - /// - /// Constructor. - /// - /// JobDefinition. - /// Dictionary of parameters. - public ScheduledJobInvocationInfo(JobDefinition definition, Dictionary parameters) - : base(definition, parameters) - { - if (definition == null) - { - throw new PSArgumentNullException("definition"); - } - - Name = definition.Name; - } - - #endregion - - #region Public Strings - - /// - /// ScriptBlock parameter. - /// - public const string ScriptBlockParameter = "ScriptBlock"; - - /// - /// FilePath parameter. - /// - public const string FilePathParameter = "FilePath"; - - /// - /// RunAs32 parameter. - /// - public const string RunAs32Parameter = "RunAs32"; - - /// - /// Authentication parameter. - /// - public const string AuthenticationParameter = "Authentication"; - - /// - /// InitializationScript parameter. - /// - public const string InitializationScriptParameter = "InitializationScript"; - - /// - /// ArgumentList parameter. - /// - public const string ArgumentListParameter = "ArgumentList"; - - #endregion - - #region ISerializable Implementation - - /// - /// Serialization constructor. - /// - /// SerializationInfo. - /// StreamingContext. - internal ScheduledJobInvocationInfo( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - DeserializeInvocationInfo(info); - } - - /// - /// Serialization implementation. - /// - /// SerializationInfo. - /// StreamingContext. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - SerializeInvocationInfo(info); - } - - #endregion - - #region Private Methods - - private void SerializeInvocationInfo(SerializationInfo info) - { - info.AddValue("InvocationInfo_Command", this.Command); - info.AddValue("InvocationInfo_Name", this.Name); - info.AddValue("InvocationInfo_AdapterType", this.Definition.JobSourceAdapterType); - info.AddValue("InvocationInfo_ModuleName", this.Definition.ModuleName); - info.AddValue("InvocationInfo_AdapterTypeName", this.Definition.JobSourceAdapterTypeName); - - // Get the job parameters. - Dictionary parameters = new Dictionary(); - foreach (var commandParam in this.Parameters[0]) - { - if (!parameters.ContainsKey(commandParam.Name)) - { - parameters.Add(commandParam.Name, commandParam.Value); - } - } - - // - // Serialize only parameters that scheduled job knows about. - // - - // ScriptBlock - if (parameters.ContainsKey(ScriptBlockParameter)) - { - ScriptBlock scriptBlock = (ScriptBlock)parameters[ScriptBlockParameter]; - info.AddValue("InvocationParam_ScriptBlock", scriptBlock.ToString()); - } - else - { - info.AddValue("InvocationParam_ScriptBlock", null); - } - - // FilePath - if (parameters.ContainsKey(FilePathParameter)) - { - string filePath = (string)parameters[FilePathParameter]; - info.AddValue("InvocationParam_FilePath", filePath); - } - else - { - info.AddValue("InvocationParam_FilePath", string.Empty); - } - - // InitializationScript - if (parameters.ContainsKey(InitializationScriptParameter)) - { - ScriptBlock scriptBlock = (ScriptBlock)parameters[InitializationScriptParameter]; - info.AddValue("InvocationParam_InitScript", scriptBlock.ToString()); - } - else - { - info.AddValue("InvocationParam_InitScript", string.Empty); - } - - // RunAs32 - if (parameters.ContainsKey(RunAs32Parameter)) - { - bool runAs32 = (bool)parameters[RunAs32Parameter]; - info.AddValue("InvocationParam_RunAs32", runAs32); - } - else - { - info.AddValue("InvocationParam_RunAs32", false); - } - - // Authentication - if (parameters.ContainsKey(AuthenticationParameter)) - { - AuthenticationMechanism authentication = (AuthenticationMechanism)parameters[AuthenticationParameter]; - info.AddValue("InvocationParam_Authentication", authentication); - } - else - { - info.AddValue("InvocationParam_Authentication", AuthenticationMechanism.Default); - } - - // ArgumentList - if (parameters.ContainsKey(ArgumentListParameter)) - { - object[] argList = (object[])parameters[ArgumentListParameter]; - info.AddValue("InvocationParam_ArgList", argList); - } - else - { - info.AddValue("InvocationParam_ArgList", null); - } - } - - private void DeserializeInvocationInfo(SerializationInfo info) - { - string command = info.GetString("InvocationInfo_Command"); - string name = info.GetString("InvocationInfo_Name"); - string moduleName = info.GetString("InvocationInfo_ModuleName"); - string adapterTypeName = info.GetString("InvocationInfo_AdapterTypeName"); - - // - // Parameters - Dictionary parameters = new Dictionary(); - - // ScriptBlock - string script = info.GetString("InvocationParam_ScriptBlock"); - if (script != null) - { - parameters.Add(ScriptBlockParameter, ScriptBlock.Create(script)); - } - - // FilePath - string filePath = info.GetString("InvocationParam_FilePath"); - if (!string.IsNullOrEmpty(filePath)) - { - parameters.Add(FilePathParameter, filePath); - } - - // InitializationScript - script = info.GetString("InvocationParam_InitScript"); - if (!string.IsNullOrEmpty(script)) - { - parameters.Add(InitializationScriptParameter, ScriptBlock.Create(script)); - } - - // RunAs32 - bool runAs32 = info.GetBoolean("InvocationParam_RunAs32"); - parameters.Add(RunAs32Parameter, runAs32); - - // Authentication - AuthenticationMechanism authentication = (AuthenticationMechanism)info.GetValue("InvocationParam_Authentication", - typeof(AuthenticationMechanism)); - parameters.Add(AuthenticationParameter, authentication); - - // ArgumentList - object[] argList = (object[])info.GetValue("InvocationParam_ArgList", typeof(object[])); - if (argList != null) - { - parameters.Add(ArgumentListParameter, argList); - } - - JobDefinition jobDefinition = new JobDefinition(null, command, name); - jobDefinition.ModuleName = moduleName; - jobDefinition.JobSourceAdapterTypeName = adapterTypeName; - - // Convert to JobInvocationParameter collection - CommandParameterCollection paramCollection = new CommandParameterCollection(); - foreach (KeyValuePair param in parameters) - { - CommandParameter paramItem = new CommandParameter(param.Key, param.Value); - paramCollection.Add(paramItem); - } - - this.Definition = jobDefinition; - this.Name = name; - this.Command = command; - this.Parameters.Add(paramCollection); - } - - #endregion - } - - #endregion -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs deleted file mode 100644 index 8f171cd02ba..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobOptions.cs +++ /dev/null @@ -1,405 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Linq; -using System.Management.Automation; -using System.Runtime.Serialization; -using System.Security.Permissions; -using System.Text; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This class contains Windows Task Scheduler options. - /// - [Serializable] - public sealed class ScheduledJobOptions : ISerializable - { - #region Private Members - - // Power settings - private bool _startIfOnBatteries; - private bool _stopIfGoingOnBatteries; - private bool _wakeToRun; - - // Idle settings - private bool _startIfNotIdle; - private bool _stopIfGoingOffIdle; - private bool _restartOnIdleResume; - private TimeSpan _idleDuration; - private TimeSpan _idleTimeout; - - // Security settings - private bool _showInTaskScheduler; - private bool _runElevated; - - // Misc - private bool _runWithoutNetwork; - private bool _donotAllowDemandStart; - private TaskMultipleInstancePolicy _multipleInstancePolicy; - - // ScheduledJobDefinition object associated with this options object. - private ScheduledJobDefinition _jobDefAssociation; - - #endregion - - #region Public Properties - - /// - /// Start task if on batteries. - /// - public bool StartIfOnBatteries - { - get { return _startIfOnBatteries; } - - set { _startIfOnBatteries = value; } - } - - /// - /// Stop task if computer is going on batteries. - /// - public bool StopIfGoingOnBatteries - { - get { return _stopIfGoingOnBatteries; } - - set { _stopIfGoingOnBatteries = value; } - } - - /// - /// Wake computer to run task. - /// - public bool WakeToRun - { - get { return _wakeToRun; } - - set { _wakeToRun = value; } - } - - /// - /// Start task only if computer is not idle. - /// - public bool StartIfNotIdle - { - get { return _startIfNotIdle; } - - set { _startIfNotIdle = value; } - } - - /// - /// Stop task if computer is no longer idle. - /// - public bool StopIfGoingOffIdle - { - get { return _stopIfGoingOffIdle; } - - set { _stopIfGoingOffIdle = value; } - } - /// - /// Restart task on idle resuming. - /// - public bool RestartOnIdleResume - { - get { return _restartOnIdleResume; } - - set { _restartOnIdleResume = value; } - } - - /// - /// How long computer must be idle before task starts. - /// - public TimeSpan IdleDuration - { - get { return _idleDuration; } - - set { _idleDuration = value; } - } - - /// - /// How long task manager will wait for required idle duration. - /// - public TimeSpan IdleTimeout - { - get { return _idleTimeout; } - - set { _idleTimeout = value; } - } - - /// - /// When true task is not shown in Task Scheduler UI. - /// - public bool ShowInTaskScheduler - { - get { return _showInTaskScheduler; } - - set { _showInTaskScheduler = value; } - } - - /// - /// Run task with elevated privileges. - /// - public bool RunElevated - { - get { return _runElevated; } - - set { _runElevated = value; } - } - - /// - /// Run task even if network is not available. - /// - public bool RunWithoutNetwork - { - get { return _runWithoutNetwork; } - - set { _runWithoutNetwork = value; } - } - - /// - /// Do not allow a task to be started on demand. - /// - public bool DoNotAllowDemandStart - { - get { return _donotAllowDemandStart; } - - set { _donotAllowDemandStart = value; } - } - - /// - /// Multiple task instance policy. - /// - public TaskMultipleInstancePolicy MultipleInstancePolicy - { - get { return _multipleInstancePolicy; } - - set { _multipleInstancePolicy = value; } - } - - /// - /// ScheduledJobDefinition object associated with this options object. - /// - public ScheduledJobDefinition JobDefinition - { - get { return _jobDefAssociation; } - - internal set { _jobDefAssociation = value; } - } - - #endregion - - #region Constructors - - /// - /// Default constructor. - /// - public ScheduledJobOptions() - { - _startIfOnBatteries = false; - _stopIfGoingOnBatteries = true; - _wakeToRun = false; - _startIfNotIdle = true; - _stopIfGoingOffIdle = false; - _restartOnIdleResume = false; - _idleDuration = new TimeSpan(0, 10, 0); - _idleTimeout = new TimeSpan(1, 0, 0); - _showInTaskScheduler = true; - _runElevated = false; - _runWithoutNetwork = true; - _donotAllowDemandStart = false; - _multipleInstancePolicy = TaskMultipleInstancePolicy.IgnoreNew; - } - - /// - /// Constructor. - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - /// - internal ScheduledJobOptions( - bool startIfOnBatteries, - bool stopIfGoingOnBatters, - bool wakeToRun, - bool startIfNotIdle, - bool stopIfGoingOffIdle, - bool restartOnIdleResume, - TimeSpan idleDuration, - TimeSpan idleTimeout, - bool showInTaskScheduler, - bool runElevated, - bool runWithoutNetwork, - bool donotAllowDemandStart, - TaskMultipleInstancePolicy multipleInstancePolicy) - { - _startIfOnBatteries = startIfOnBatteries; - _stopIfGoingOnBatteries = stopIfGoingOnBatters; - _wakeToRun = wakeToRun; - _startIfNotIdle = startIfNotIdle; - _stopIfGoingOffIdle = stopIfGoingOffIdle; - _restartOnIdleResume = restartOnIdleResume; - _idleDuration = idleDuration; - _idleTimeout = idleTimeout; - _showInTaskScheduler = showInTaskScheduler; - _runElevated = runElevated; - _runWithoutNetwork = runWithoutNetwork; - _donotAllowDemandStart = donotAllowDemandStart; - _multipleInstancePolicy = multipleInstancePolicy; - } - - /// - /// Copy Constructor. - /// - /// Copy from. - internal ScheduledJobOptions( - ScheduledJobOptions copyOptions) - { - if (copyOptions == null) - { - throw new PSArgumentNullException("copyOptions"); - } - - _startIfOnBatteries = copyOptions.StartIfOnBatteries; - _stopIfGoingOnBatteries = copyOptions.StopIfGoingOnBatteries; - _wakeToRun = copyOptions.WakeToRun; - _startIfNotIdle = copyOptions.StartIfNotIdle; - _stopIfGoingOffIdle = copyOptions.StopIfGoingOffIdle; - _restartOnIdleResume = copyOptions.RestartOnIdleResume; - _idleDuration = copyOptions.IdleDuration; - _idleTimeout = copyOptions.IdleTimeout; - _showInTaskScheduler = copyOptions.ShowInTaskScheduler; - _runElevated = copyOptions.RunElevated; - _runWithoutNetwork = copyOptions.RunWithoutNetwork; - _donotAllowDemandStart = copyOptions.DoNotAllowDemandStart; - _multipleInstancePolicy = copyOptions.MultipleInstancePolicy; - - _jobDefAssociation = copyOptions.JobDefinition; - } - - #endregion - - #region ISerializable Implementation - - /// - /// Serialization constructor. - /// - /// SerializationInfo. - /// StreamingContext. - private ScheduledJobOptions( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - _startIfOnBatteries = info.GetBoolean("StartIfOnBatteries_Value"); - _stopIfGoingOnBatteries = info.GetBoolean("StopIfGoingOnBatteries_Value"); - _wakeToRun = info.GetBoolean("WakeToRun_Value"); - _startIfNotIdle = info.GetBoolean("StartIfNotIdle_Value"); - _stopIfGoingOffIdle = info.GetBoolean("StopIfGoingOffIdle_Value"); - _restartOnIdleResume = info.GetBoolean("RestartOnIdleResume_Value"); - _idleDuration = (TimeSpan)info.GetValue("IdleDuration_Value", typeof(TimeSpan)); - _idleTimeout = (TimeSpan)info.GetValue("IdleTimeout_Value", typeof(TimeSpan)); - _showInTaskScheduler = info.GetBoolean("ShowInTaskScheduler_Value"); - _runElevated = info.GetBoolean("RunElevated_Value"); - _runWithoutNetwork = info.GetBoolean("RunWithoutNetwork_Value"); - _donotAllowDemandStart = info.GetBoolean("DoNotAllowDemandStart_Value"); - _multipleInstancePolicy = (TaskMultipleInstancePolicy)info.GetValue("TaskMultipleInstancePolicy_Value", typeof(TaskMultipleInstancePolicy)); - - // Runtime reference and not saved to store. - _jobDefAssociation = null; - } - - /// - /// GetObjectData for ISerializable implementation. - /// - /// SerializationInfo. - /// StreamingContext. - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - info.AddValue("StartIfOnBatteries_Value", _startIfOnBatteries); - info.AddValue("StopIfGoingOnBatteries_Value", _stopIfGoingOnBatteries); - info.AddValue("WakeToRun_Value", _wakeToRun); - info.AddValue("StartIfNotIdle_Value", _startIfNotIdle); - info.AddValue("StopIfGoingOffIdle_Value", _stopIfGoingOffIdle); - info.AddValue("RestartOnIdleResume_Value", _restartOnIdleResume); - info.AddValue("IdleDuration_Value", _idleDuration); - info.AddValue("IdleTimeout_Value", _idleTimeout); - info.AddValue("ShowInTaskScheduler_Value", _showInTaskScheduler); - info.AddValue("RunElevated_Value", _runElevated); - info.AddValue("RunWithoutNetwork_Value", _runWithoutNetwork); - info.AddValue("DoNotAllowDemandStart_Value", _donotAllowDemandStart); - info.AddValue("TaskMultipleInstancePolicy_Value", _multipleInstancePolicy); - } - - #endregion - - #region Public Methods - - /// - /// Update the associated ScheduledJobDefinition object with the - /// current properties of this object. - /// - public void UpdateJobDefinition() - { - if (_jobDefAssociation == null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAssociatedJobDefinitionForOption); - - throw new RuntimeException(msg); - } - - _jobDefAssociation.UpdateOptions(this, true); - } - - #endregion - } - - #region Public Enums - - /// - /// Enumerates Task Scheduler options for multiple instance polices of - /// scheduled tasks (jobs). - /// - public enum TaskMultipleInstancePolicy - { - /// - /// None. - /// - None = 0, - /// - /// Ignore a new instance of the task (job) - /// - IgnoreNew = 1, - /// - /// Allow parallel running of a task (job) - /// - Parallel = 2, - /// - /// Queue up multiple instances of a task (job) - /// - Queue = 3, - /// - /// Stop currently running task (job) and start a new one. - /// - StopExisting = 4 - } - - #endregion -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs deleted file mode 100644 index 53434c729e7..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobSourceAdapter.cs +++ /dev/null @@ -1,1088 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Management.Automation; -using System.Management.Automation.Runspaces; -using System.Runtime.Serialization; -using System.Text; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This class provides functionality for retrieving scheduled job run results - /// from the scheduled job store. An instance of this object will be registered - /// with the PowerShell JobManager so that GetJobs commands will retrieve schedule - /// job runs from the file based scheduled job store. This allows scheduled job - /// runs to be managed from PowerShell in the same way workflow jobs are managed. - /// - public sealed class ScheduledJobSourceAdapter : JobSourceAdapter - { - #region Private Members - - private static FileSystemWatcher StoreWatcher; - private static object SyncObject = new object(); - private static ScheduledJobRepository JobRepository = new ScheduledJobRepository(); - internal const string AdapterTypeName = "PSScheduledJob"; - - #endregion - - #region Public Strings - - /// - /// BeforeFilter. - /// - public const string BeforeFilter = "Before"; - - /// - /// AfterFilter. - /// - public const string AfterFilter = "After"; - - /// - /// NewestFilter. - /// - public const string NewestFilter = "Newest"; - - #endregion - - #region Constructor - - /// - /// Constructor. - /// - public ScheduledJobSourceAdapter() - { - Name = AdapterTypeName; - } - - #endregion - - #region JobSourceAdapter Implementation - - /// - /// Create a new Job2 results instance. - /// - /// Job specification. - /// Job2. - public override Job2 NewJob(JobInvocationInfo specification) - { - if (specification == null) - { - throw new PSArgumentNullException("specification"); - } - - ScheduledJobDefinition scheduledJobDef = new ScheduledJobDefinition( - specification, null, null, null); - - return new ScheduledJob( - specification.Command, - specification.Name, - scheduledJobDef); - } - - /// - /// Creates a new Job2 object based on a definition name - /// that can be run manually. If the path parameter is - /// null then a default location will be used to find the - /// job definition by name. - /// - /// ScheduledJob definition name. - /// ScheduledJob definition file path. - /// Job2 object. - public override Job2 NewJob(string definitionName, string definitionPath) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - Job2 rtnJob = null; - try - { - ScheduledJobDefinition scheduledJobDef = - ScheduledJobDefinition.LoadFromStore(definitionName, definitionPath); - - rtnJob = new ScheduledJob( - scheduledJobDef.Command, - scheduledJobDef.Name, - scheduledJobDef); - } - catch (FileNotFoundException) - { - // Return null if no job definition exists. - } - - return rtnJob; - } - - /// - /// Get the list of jobs that are currently available in this - /// store. - /// - /// Collection of job objects. - public override IList GetJobs() - { - RefreshRepository(); - - List rtnJobs = new List(); - foreach (var job in JobRepository.Jobs) - { - rtnJobs.Add(job); - } - - return rtnJobs; - } - - /// - /// Get list of jobs that matches the specified names. - /// - /// names to match, can support - /// wildcard if the store supports - /// - /// Collection of jobs that match the specified - /// criteria. - public override IList GetJobsByName(string name, bool recurse) - { - if (string.IsNullOrEmpty(name)) - { - throw new PSArgumentException("name"); - } - - RefreshRepository(); - - WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); - List rtnJobs = new List(); - foreach (var job in JobRepository.Jobs) - { - if (namePattern.IsMatch(job.Name)) - { - rtnJobs.Add(job); - } - } - - return rtnJobs; - } - - /// - /// Get list of jobs that run the specified command. - /// - /// Command to match. - /// - /// Collection of jobs that match the specified - /// criteria. - public override IList GetJobsByCommand(string command, bool recurse) - { - if (string.IsNullOrEmpty(command)) - { - throw new PSArgumentException("command"); - } - - RefreshRepository(); - - WildcardPattern commandPattern = new WildcardPattern(command, WildcardOptions.IgnoreCase); - List rtnJobs = new List(); - foreach (var job in JobRepository.Jobs) - { - if (commandPattern.IsMatch(job.Command)) - { - rtnJobs.Add(job); - } - } - - return rtnJobs; - } - - /// - /// Get job that has the specified id. - /// - /// Guid to match. - /// - /// Job with the specified guid. - public override Job2 GetJobByInstanceId(Guid instanceId, bool recurse) - { - RefreshRepository(); - - foreach (var job in JobRepository.Jobs) - { - if (Guid.Equals(job.InstanceId, instanceId)) - { - return job; - } - } - - return null; - } - - /// - /// Get job that has specific session id. - /// - /// Id to match. - /// - /// Job with the specified id. - public override Job2 GetJobBySessionId(int id, bool recurse) - { - RefreshRepository(); - - foreach (var job in JobRepository.Jobs) - { - if (id == job.Id) - { - return job; - } - } - - return null; - } - - /// - /// Get list of jobs that are in the specified state. - /// - /// State to match. - /// - /// Collection of jobs with the specified - /// state. - public override IList GetJobsByState(JobState state, bool recurse) - { - RefreshRepository(); - - List rtnJobs = new List(); - foreach (var job in JobRepository.Jobs) - { - if (state == job.JobStateInfo.State) - { - rtnJobs.Add(job); - } - } - - return rtnJobs; - } - - /// - /// Get list of jobs based on the adapter specific - /// filter parameters. - /// - /// dictionary containing name value - /// pairs for adapter specific filters - /// - /// Collection of jobs that match the - /// specified criteria. - public override IList GetJobsByFilter(Dictionary filter, bool recurse) - { - if (filter == null) - { - throw new PSArgumentNullException("filter"); - } - - List rtnJobs = new List(); - foreach (var filterItem in filter) - { - switch (filterItem.Key) - { - case BeforeFilter: - GetJobsBefore((DateTime)filterItem.Value, ref rtnJobs); - break; - - case AfterFilter: - GetJobsAfter((DateTime)filterItem.Value, ref rtnJobs); - break; - - case NewestFilter: - GetNewestJobs((int)filterItem.Value, ref rtnJobs); - break; - } - } - - return rtnJobs; - } - - /// - /// Remove a job from the store. - /// - /// Job object to remove. - public override void RemoveJob(Job2 job) - { - if (job == null) - { - throw new PSArgumentNullException("job"); - } - - RefreshRepository(); - - try - { - JobRepository.Remove(job); - ScheduledJobStore.RemoveJobRun( - job.Name, - job.PSBeginTime ?? DateTime.MinValue); - } - catch (DirectoryNotFoundException) - { - } - catch (FileNotFoundException) - { - } - } - - /// - /// Saves job to scheduled job run store. - /// - /// ScheduledJob. - public override void PersistJob(Job2 job) - { - if (job == null) - { - throw new PSArgumentNullException("job"); - } - - SaveJobToStore(job as ScheduledJob); - } - - #endregion - - #region Save Job - - /// - /// Serializes a ScheduledJob and saves it to store. - /// - /// ScheduledJob. - internal static void SaveJobToStore(ScheduledJob job) - { - string outputPath = job.Definition.OutputPath; - if (string.IsNullOrEmpty(outputPath)) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSaveJobNoFilePathSpecified, - job.Name); - throw new ScheduledJobException(msg); - } - - FileStream fsStatus = null; - FileStream fsResults = null; - try - { - // Check the job store results and if maximum number of results exist - // remove the oldest results folder to make room for these new results. - CheckJobStoreResults(outputPath, job.Definition.ExecutionHistoryLength); - - fsStatus = ScheduledJobStore.CreateFileForJobRunItem( - outputPath, - job.PSBeginTime ?? DateTime.MinValue, - ScheduledJobStore.JobRunItem.Status); - - // Save status only in status file stream. - SaveStatusToFile(job, fsStatus); - - fsResults = ScheduledJobStore.CreateFileForJobRunItem( - outputPath, - job.PSBeginTime ?? DateTime.MinValue, - ScheduledJobStore.JobRunItem.Results); - - // Save entire job in results file stream. - SaveResultsToFile(job, fsResults); - } - finally - { - if (fsStatus != null) - { - fsStatus.Close(); - } - - if (fsResults != null) - { - fsResults.Close(); - } - } - } - - /// - /// Writes the job status information to the provided - /// file stream. - /// - /// ScheduledJob job to save. - /// FileStream. - private static void SaveStatusToFile(ScheduledJob job, FileStream fs) - { - StatusInfo statusInfo = new StatusInfo( - job.InstanceId, - job.Name, - job.Location, - job.Command, - job.StatusMessage, - job.JobStateInfo.State, - job.HasMoreData, - job.PSBeginTime, - job.PSEndTime, - job.Definition); - - XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); - serializer.WriteObject(fs, statusInfo); - fs.Flush(); - } - - /// - /// Writes the job (which implements ISerializable) to the provided - /// file stream. - /// - /// ScheduledJob job to save. - /// FileStream. - private static void SaveResultsToFile(ScheduledJob job, FileStream fs) - { - XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); - serializer.WriteObject(fs, job); - fs.Flush(); - } - - /// - /// Check the job store results and if maximum number of results exist - /// remove the oldest results folder to make room for these new results. - /// - /// Output path. - /// Maximum size of stored job results. - private static void CheckJobStoreResults(string outputPath, int executionHistoryLength) - { - // Get current results for this job definition. - Collection jobRuns = ScheduledJobStore.GetJobRunsForDefinitionPath(outputPath); - if (jobRuns.Count <= executionHistoryLength) - { - // There is room for another job run in the store. - return; - } - - // Remove the oldest job run from the store. - DateTime jobRunToRemove = DateTime.MaxValue; - foreach (DateTime jobRun in jobRuns) - { - jobRunToRemove = (jobRun < jobRunToRemove) ? jobRun : jobRunToRemove; - } - - try - { - ScheduledJobStore.RemoveJobRunFromOutputPath(outputPath, jobRunToRemove); - } - catch (UnauthorizedAccessException) - { } - } - - #endregion - - #region Retrieve Job - - /// - /// Finds and load the Job associated with this ScheduledJobDefinition object - /// having the job run date time provided. - /// - /// DateTime of job run to load. - /// ScheduledJobDefinition name. - /// Job2 job loaded from store. - internal static Job2 LoadJobFromStore(string definitionName, DateTime jobRun) - { - FileStream fsResults = null; - Exception ex = null; - bool corruptedFile = false; - Job2 job = null; - - try - { - // Results - fsResults = ScheduledJobStore.GetFileForJobRunItem( - definitionName, - jobRun, - ScheduledJobStore.JobRunItem.Results, - FileMode.Open, - FileAccess.Read, - FileShare.Read); - - job = LoadResultsFromFile(fsResults); - } - catch (ArgumentException e) - { - ex = e; - } - catch (DirectoryNotFoundException e) - { - ex = e; - } - catch (FileNotFoundException e) - { - ex = e; - corruptedFile = true; - } - catch (UnauthorizedAccessException e) - { - ex = e; - } - catch (IOException e) - { - ex = e; - } - catch (System.Runtime.Serialization.SerializationException) - { - corruptedFile = true; - } - catch (System.Runtime.Serialization.InvalidDataContractException) - { - corruptedFile = true; - } - catch (System.Xml.XmlException) - { - corruptedFile = true; - } - catch (System.TypeInitializationException) - { - corruptedFile = true; - } - finally - { - if (fsResults != null) - { - fsResults.Close(); - } - } - - if (corruptedFile) - { - // Remove the corrupted job results file. - ScheduledJobStore.RemoveJobRun(definitionName, jobRun); - } - - if (ex != null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadJobRunFromStore, definitionName, jobRun); - throw new ScheduledJobException(msg, ex); - } - - return job; - } - - /// - /// Loads the Job2 object from provided files stream. - /// - /// FileStream from which to read job object. - /// Created Job2 from file stream. - private static Job2 LoadResultsFromFile(FileStream fs) - { - XmlObjectSerializer serializer = new System.Runtime.Serialization.NetDataContractSerializer(); - return (Job2)serializer.ReadObject(fs); - } - - #endregion - - #region Static Methods - - /// - /// Adds a Job2 object to the repository. - /// - /// Job2. - internal static void AddToRepository(Job2 job) - { - if (job == null) - { - throw new PSArgumentNullException("job"); - } - - JobRepository.AddOrReplace(job); - } - - /// - /// Clears all items in the repository. - /// - internal static void ClearRepository() - { - JobRepository.Clear(); - } - - /// - /// Clears all items for given job definition name in the - /// repository. - /// - /// Scheduled job definition name. - internal static void ClearRepositoryForDefinition(string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - // This returns a new list object of repository jobs. - List jobList = JobRepository.Jobs; - foreach (var job in jobList) - { - if (string.Compare(definitionName, job.Name, - StringComparison.OrdinalIgnoreCase) == 0) - { - JobRepository.Remove(job); - } - } - } - - #endregion - - #region Private Methods - - private void RefreshRepository() - { - ScheduledJobStore.CreateDirectoryIfNotExists(); - CreateFileSystemWatcher(); - - IEnumerable jobDefinitions = ScheduledJobStore.GetJobDefinitions(); - foreach (string definitionName in jobDefinitions) - { - // Create Job2 objects for each job run in store. - Collection jobRuns = GetJobRuns(definitionName); - if (jobRuns == null) - { - continue; - } - - ScheduledJobDefinition definition = null; - foreach (DateTime jobRun in jobRuns) - { - if (jobRun > JobRepository.GetLatestJobRun(definitionName)) - { - Job2 job; - try - { - if (definition == null) - { - definition = ScheduledJobDefinition.LoadFromStore(definitionName, null); - } - - job = LoadJobFromStore(definition.Name, jobRun); - } - catch (ScheduledJobException) - { - continue; - } - catch (DirectoryNotFoundException) - { - continue; - } - catch (FileNotFoundException) - { - continue; - } - catch (UnauthorizedAccessException) - { - continue; - } - catch (IOException) - { - continue; - } - - JobRepository.AddOrReplace(job); - JobRepository.SetLatestJobRun(definitionName, jobRun); - } - } - } - } - - private void CreateFileSystemWatcher() - { - // Lazily create the static file system watcher - // on first use. - if (StoreWatcher == null) - { - lock (SyncObject) - { - if (StoreWatcher == null) - { - StoreWatcher = new FileSystemWatcher(ScheduledJobStore.GetJobDefinitionLocation()); - StoreWatcher.IncludeSubdirectories = true; - StoreWatcher.NotifyFilter = NotifyFilters.LastWrite; - StoreWatcher.Filter = "Results.xml"; - StoreWatcher.EnableRaisingEvents = true; - StoreWatcher.Changed += (object sender, FileSystemEventArgs e) => - { - UpdateRepositoryObjects(e); - }; - } - } - } - } - - private static void UpdateRepositoryObjects(FileSystemEventArgs e) - { - // Extract job run information from change file path. - string updateDefinitionName; - DateTime updateJobRun; - if (!GetJobRunInfo(e.Name, out updateDefinitionName, out updateJobRun)) - { - System.Diagnostics.Debug.Assert(false, "All job run updates should have valid directory names."); - return; - } - - // Find corresponding job in repository. - ScheduledJob updateJob = JobRepository.GetJob(updateDefinitionName, updateJobRun); - if (updateJob == null) - { - return; - } - - // Load updated job information from store. - Job2 job = null; - try - { - job = LoadJobFromStore(updateDefinitionName, updateJobRun); - } - catch (ScheduledJobException) - { } - catch (DirectoryNotFoundException) - { } - catch (FileNotFoundException) - { } - catch (UnauthorizedAccessException) - { } - catch (IOException) - { } - - // Update job in repository based on new job store data. - if (job != null) - { - updateJob.Update(job as ScheduledJob); - } - } - - /// - /// Parses job definition name and job run DateTime from provided path string. - /// Example: - /// path = "ScheduledJob1\\Output\\20111219-200921-369\\Results.xml" - /// 'ScheduledJob1' is the definition name. - /// '20111219-200921-369' is the jobRun DateTime. - /// - /// - /// - /// - /// - private static bool GetJobRunInfo( - string path, - out string definitionName, - out DateTime jobRunReturn) - { - // Parse definition name from path. - string[] pathItems = path.Split(System.IO.Path.DirectorySeparatorChar); - if (pathItems.Length == 4) - { - definitionName = pathItems[0]; - return ScheduledJobStore.ConvertJobRunNameToDateTime(pathItems[2], out jobRunReturn); - } - - definitionName = null; - jobRunReturn = DateTime.MinValue; - return false; - } - - internal static Collection GetJobRuns(string definitionName) - { - Collection jobRuns = null; - try - { - jobRuns = ScheduledJobStore.GetJobRunsForDefinition(definitionName); - } - catch (DirectoryNotFoundException) - { } - catch (FileNotFoundException) - { } - catch (UnauthorizedAccessException) - { } - catch (IOException) - { } - - return jobRuns; - } - - private void GetJobsBefore( - DateTime dateTime, - ref List jobList) - { - foreach (var job in JobRepository.Jobs) - { - if (job.PSEndTime < dateTime && - !jobList.Contains(job)) - { - jobList.Add(job); - } - } - } - - private void GetJobsAfter( - DateTime dateTime, - ref List jobList) - { - foreach (var job in JobRepository.Jobs) - { - if (job.PSEndTime > dateTime && - !jobList.Contains(job)) - { - jobList.Add(job); - } - } - } - - private void GetNewestJobs( - int maxNumber, - ref List jobList) - { - List allJobs = JobRepository.Jobs; - - // Sort descending. - allJobs.Sort((firstJob, secondJob) => - { - if (firstJob.PSEndTime > secondJob.PSEndTime) - { - return -1; - } - else if (firstJob.PSEndTime < secondJob.PSEndTime) - { - return 1; - } - else - { - return 0; - } - }); - - int count = 0; - foreach (var job in allJobs) - { - if (++count > maxNumber) - { - break; - } - - if (!jobList.Contains(job)) - { - jobList.Add(job); - } - } - } - - #endregion - - #region Private Repository Class - - /// - /// Collection of Job2 objects. - /// - internal class ScheduledJobRepository - { - #region Private Members - - private object _syncObject = new object(); - private Dictionary _jobs = new Dictionary(); - private Dictionary _latestJobRuns = new Dictionary(); - - #endregion - - #region Public Properties - - /// - /// Returns all job objects in the repository as a List. - /// - public List Jobs - { - get - { - lock (_syncObject) - { - return new List(_jobs.Values); - } - } - } - - /// - /// Returns count of jobs in repository. - /// - public int Count - { - get - { - lock (_syncObject) - { - return _jobs.Count; - } - } - } - - #endregion - - #region Public Methods - - /// - /// Add Job2 to repository. - /// - /// Job2 to add. - public void Add(Job2 job) - { - if (job == null) - { - throw new PSArgumentNullException("job"); - } - - lock (_syncObject) - { - if (_jobs.ContainsKey(job.InstanceId)) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobAlreadyExistsInLocal, job.Name, job.InstanceId); - throw new ScheduledJobException(msg); - } - - _jobs.Add(job.InstanceId, job); - } - } - - /// - /// Add or replace passed in Job2 object to repository. - /// - /// Job2 to add. - public void AddOrReplace(Job2 job) - { - if (job == null) - { - throw new PSArgumentNullException("job"); - } - - lock (_syncObject) - { - if (_jobs.ContainsKey(job.InstanceId)) - { - _jobs.Remove(job.InstanceId); - } - - _jobs.Add(job.InstanceId, job); - } - } - - /// - /// Remove Job2 from repository. - /// - /// - public void Remove(Job2 job) - { - if (job == null) - { - throw new PSArgumentNullException("job"); - } - - lock (_syncObject) - { - if (_jobs.ContainsKey(job.InstanceId) == false) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.ScheduledJobNotInRepository, job.Name); - throw new ScheduledJobException(msg); - } - - _jobs.Remove(job.InstanceId); - } - } - - /// - /// Clears all Job2 items from the repository. - /// - public void Clear() - { - lock (_syncObject) - { - _jobs.Clear(); - } - } - - /// - /// Gets the latest job run Date/Time for the given definition name. - /// - /// ScheduledJobDefinition name. - /// Job Run DateTime. - public DateTime GetLatestJobRun(string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - lock (_syncObject) - { - if (_latestJobRuns.ContainsKey(definitionName)) - { - return _latestJobRuns[definitionName]; - } - else - { - DateTime startJobRun = DateTime.MinValue; - _latestJobRuns.Add(definitionName, startJobRun); - return startJobRun; - } - } - } - - /// - /// Sets the latest job run Date/Time for the given definition name. - /// - /// - /// - public void SetLatestJobRun(string definitionName, DateTime jobRun) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - lock (_syncObject) - { - if (_latestJobRuns.ContainsKey(definitionName)) - { - _latestJobRuns.Remove(definitionName); - _latestJobRuns.Add(definitionName, jobRun); - } - else - { - _latestJobRuns.Add(definitionName, jobRun); - } - } - } - - /// - /// Search repository for specific job run. - /// - /// Definition name. - /// Job run DateTime. - /// Scheduled job if found. - public ScheduledJob GetJob(string definitionName, DateTime jobRun) - { - lock (_syncObject) - { - foreach (ScheduledJob job in _jobs.Values) - { - if (job.PSBeginTime == null) - { - continue; - } - - DateTime PSBeginTime = job.PSBeginTime ?? DateTime.MinValue; - if (definitionName.Equals(job.Definition.Name, StringComparison.OrdinalIgnoreCase) && - jobRun.Year == PSBeginTime.Year && - jobRun.Month == PSBeginTime.Month && - jobRun.Day == PSBeginTime.Day && - jobRun.Hour == PSBeginTime.Hour && - jobRun.Minute == PSBeginTime.Minute && - jobRun.Second == PSBeginTime.Second && - jobRun.Millisecond == PSBeginTime.Millisecond) - { - return job; - } - } - } - - return null; - } - - #endregion - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs deleted file mode 100644 index bd9d7439696..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobStore.cs +++ /dev/null @@ -1,683 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Globalization; -using System.IO; -using System.Management.Automation; -using System.Security.AccessControl; -using System.Security.Principal; -using System.Text; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This class encapsulates the work of determining the file location where - /// a job definition will be stored and retrieved and where job runs will - /// be stored and retrieved. Scheduled job definitions are stored in a - /// location based on the current user. Job runs are stored in the - /// corresponding scheduled job definition location under an "Output" - /// directory, where each run will have a subdirectory with a name derived - /// from the job run date/time. - /// - /// File Structure for "JobDefinitionFoo": - /// $env:User\AppData\Local\Windows\PowerShell\ScheduledJobs\JobDefinitionFoo\ - /// ScheduledJobDefinition.xml - /// Output\ - /// 110321-130942\ - /// Status.xml - /// Results.xml - /// 110319-173502\ - /// Status.xml - /// Results.xml - /// ... - /// - internal class ScheduledJobStore - { - #region Public Enums - - public enum JobRunItem - { - None = 0, - Status = 1, - Results = 2 - } - - #endregion - - #region Public Strings - - public const string ScheduledJobsPath = @"Microsoft\Windows\PowerShell\ScheduledJobs"; - public const string DefinitionFileName = "ScheduledJobDefinition"; - public const string JobRunOutput = "Output"; - public const string ScheduledJobDefExistsFQEID = "ScheduledJobDefExists"; - - #endregion - - #region Public Methods - - /// - /// Returns FileStream object for existing scheduled job definition. - /// Definition file is looked for in the default user local appdata path. - /// - /// Scheduled job definition name. - /// File mode. - /// File access. - /// File share. - /// FileStream object. - public static FileStream GetFileForJobDefinition( - string definitionName, - FileMode fileMode, - FileAccess fileAccess, - FileShare fileShare) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - string filePathName = GetFilePathName(definitionName, DefinitionFileName); - return File.Open(filePathName, fileMode, fileAccess, fileShare); - } - - /// - /// Returns FileStream object for existing scheduled job definition. - /// Definition file is looked for in the path provided. - /// - /// Scheduled job definition name. - /// Scheduled job definition file path. - /// File mode. - /// File share. - /// File share. - /// - public static FileStream GetFileForJobDefinition( - string definitionName, - string definitionPath, - FileMode fileMode, - FileAccess fileAccess, - FileShare fileShare) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - if (string.IsNullOrEmpty(definitionPath)) - { - throw new PSArgumentException("definitionPath"); - } - - string filePathName = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}\{2}.xml", - definitionPath, definitionName, DefinitionFileName); - return File.Open(filePathName, fileMode, fileAccess, fileShare); - } - - /// - /// Checks the provided path against the the default path of scheduled jobs - /// for the current user. - /// - /// Path for scheduled job definitions. - /// True if paths are equal. - public static bool IsDefaultUserPath(string definitionPath) - { - return definitionPath.Equals(GetJobDefinitionLocation(), StringComparison.OrdinalIgnoreCase); - } - - /// - /// Returns a FileStream object for a new scheduled job definition name. - /// - /// Scheduled job definition name. - /// FileStream object. - public static FileStream CreateFileForJobDefinition( - string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - string filePathName = CreateFilePathName(definitionName, DefinitionFileName); - return File.Create(filePathName); - } - - /// - /// Returns an IEnumerable object of scheduled job definition names in - /// the job store. - /// - /// IEnumerable of job definition names. - public static IEnumerable GetJobDefinitions() - { - // Directory names are identical to the corresponding scheduled job definition names. - string directoryPath = GetDirectoryPath(); - IEnumerable definitions = Directory.EnumerateDirectories(directoryPath); - return (definitions != null) ? definitions : new Collection() as IEnumerable; - } - - /// - /// Returns a FileStream object for an existing scheduled job definition - /// run. - /// - /// Scheduled job definition name. - /// DateTime of job run start time. - /// Job run item. - /// File access. - /// File mode. - /// File share. - /// FileStream object. - public static FileStream GetFileForJobRunItem( - string definitionName, - DateTime runStart, - JobRunItem runItem, - FileMode fileMode, - FileAccess fileAccess, - FileShare fileShare) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - string filePathName = GetRunFilePathName(definitionName, runItem, runStart); - return File.Open(filePathName, fileMode, fileAccess, fileShare); - } - - /// - /// Returns a FileStream object for a new scheduled job definition run. - /// - /// Scheduled job definition path. - /// DateTime of job run start time. - /// Job run item. - /// FileStream object. - public static FileStream CreateFileForJobRunItem( - string definitionOutputPath, - DateTime runStart, - JobRunItem runItem) - { - if (string.IsNullOrEmpty(definitionOutputPath)) - { - throw new PSArgumentException("definitionOutputPath"); - } - - string filePathName = GetRunFilePathNameFromPath(definitionOutputPath, runItem, runStart); - - // If the file already exists, we overwrite it because the job run - // can be updated multiple times while the job is running. - return File.Create(filePathName); - } - - /// - /// Returns a collection of DateTime objects which specify job run directories - /// that are currently in the store. - /// - /// Scheduled job definition name. - /// Collection of DateTime objects. - public static Collection GetJobRunsForDefinition( - string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - string definitionOutputPath = GetJobRunOutputDirectory(definitionName); - - return GetJobRunsForDefinitionPath(definitionOutputPath); - } - - /// - /// Returns a collection of DateTime objects which specify job run directories - /// that are currently in the store. - /// - /// Scheduled job definition job run Output path. - /// Collection of DateTime objects. - public static Collection GetJobRunsForDefinitionPath( - string definitionOutputPath) - { - if (string.IsNullOrEmpty(definitionOutputPath)) - { - throw new PSArgumentException("definitionOutputPath"); - } - - Collection jobRunInfos = new Collection(); - IEnumerable jobRuns = Directory.EnumerateDirectories(definitionOutputPath); - if (jobRuns != null) - { - // Job run directory names are the date/times that the job was started. - foreach (string jobRun in jobRuns) - { - DateTime jobRunDateTime; - int indx = jobRun.LastIndexOf('\\'); - string jobRunName = (indx != -1) ? jobRun.Substring(indx + 1) : jobRun; - if (ConvertJobRunNameToDateTime(jobRunName, out jobRunDateTime)) - { - jobRunInfos.Add(jobRunDateTime); - } - } - } - - return jobRunInfos; - } - - /// - /// Remove the job definition and all job runs from job store. - /// - /// Scheduled Job Definition name. - public static void RemoveJobDefinition( - string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - // Remove job runs, job definition file, and job definition directory. - string jobDefDirectory = GetJobDefinitionPath(definitionName); - Directory.Delete(jobDefDirectory, true); - } - - /// - /// Renames the directory containing the old job definition name - /// to the new name provided. - /// - /// Existing job definition directory. - /// Renamed job definition directory. - public static void RenameScheduledJobDefDir( - string oldDefName, - string newDefName) - { - if (string.IsNullOrEmpty(oldDefName)) - { - throw new PSArgumentException("oldDefName"); - } - - if (string.IsNullOrEmpty(newDefName)) - { - throw new PSArgumentException("newDefName"); - } - - string oldDirPath = GetJobDefinitionPath(oldDefName); - string newDirPath = GetJobDefinitionPath(newDefName); - Directory.Move(oldDirPath, newDirPath); - } - - /// - /// Remove a single job definition job run from the job store. - /// - /// Scheduled Job Definition name. - /// DateTime of job run. - public static void RemoveJobRun( - string definitionName, - DateTime runStart) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - // Remove the job run files and directory. - string runDirectory = GetRunDirectory(definitionName, runStart); - Directory.Delete(runDirectory, true); - } - - /// - /// Remove a single job definition job run from the job store. - /// - /// Scheduled Job Definition Output path. - /// DateTime of job run. - public static void RemoveJobRunFromOutputPath( - string definitionOutputPath, - DateTime runStart) - { - if (string.IsNullOrEmpty(definitionOutputPath)) - { - throw new PSArgumentException("definitionOutputPath"); - } - - // Remove the job run files and directory. - string runDirectory = GetRunDirectoryFromPath(definitionOutputPath, runStart); - Directory.Delete(runDirectory, true); - } - - /// - /// Remove all job runs for this job definition. - /// - /// Scheduled Job Definition name. - public static void RemoveAllJobRuns( - string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - Collection jobRuns = GetJobRunsForDefinition(definitionName); - foreach (DateTime jobRun in jobRuns) - { - string jobRunPath = GetRunDirectory(definitionName, jobRun); - Directory.Delete(jobRunPath, true); - } - } - - /// - /// Set read access on provided definition file for specified user. - /// - /// Definition name. - /// Account user name. - public static void SetReadAccessOnDefinitionFile( - string definitionName, - string user) - { - string filePath = GetFilePathName(definitionName, DefinitionFileName); - - // Get file security for existing file. - FileSecurity fileSecurity = new FileSecurity( - filePath, - AccessControlSections.Access); - - // Create rule. - FileSystemAccessRule fileAccessRule = new FileSystemAccessRule( - user, - FileSystemRights.Read, - AccessControlType.Allow); - fileSecurity.AddAccessRule(fileAccessRule); - - // Apply rule. - File.SetAccessControl(filePath, fileSecurity); - } - - /// - /// Set write access on Output directory for provided definition for - /// specified user. - /// - /// Definition name. - /// Account user name. - public static void SetWriteAccessOnJobRunOutput( - string definitionName, - string user) - { - string outputDirectoryPath = GetJobRunOutputDirectory(definitionName); - AddFullAccessToDirectory(user, outputDirectoryPath); - } - - /// - /// Returns the directory path for job run output for the specified - /// scheduled job definition. - /// - /// Definition name. - /// Directory Path. - public static string GetJobRunOutputDirectory( - string definitionName) - { - if (string.IsNullOrEmpty(definitionName)) - { - throw new PSArgumentException("definitionName"); - } - - return Path.Combine(GetJobDefinitionPath(definitionName), JobRunOutput); - } - - /// - /// Gets the directory path for a Scheduled Job Definition. - /// - /// Directory Path. - public static string GetJobDefinitionLocation() - { -#if UNIX - return Path.Combine(Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE), "ScheduledJobs")); -#else - return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), ScheduledJobsPath); -#endif - } - - public static void CreateDirectoryIfNotExists() - { - GetDirectoryPath(); - } - - #endregion - - #region Private Methods - - /// - /// Gets the directory path for Scheduled Jobs. Will create the directory if - /// it does not exist. - /// - /// Directory Path. - private static string GetDirectoryPath() - { - string pathName; -#if UNIX - pathName = Path.Combine(Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE), "ScheduledJobs")); -#else - pathName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), ScheduledJobsPath); -#endif - if (!Directory.Exists(pathName)) - { - Directory.CreateDirectory(pathName); - } - - return pathName; - } - - /// - /// Creates a ScheduledJob definition directory with provided definition name - /// along with a job run Output directory, and returns a file path/name. - /// ...\ScheduledJobs\definitionName\fileName.xml - /// ...\ScheduledJobs\definitionName\Output\ - /// - /// Definition name. - /// File name. - /// File path/name. - private static string CreateFilePathName(string definitionName, string fileName) - { - string filePath = GetJobDefinitionPath(definitionName); - string outputPath = GetJobRunOutputDirectory(definitionName); - if (Directory.Exists(filePath)) - { - ScheduledJobException ex = new ScheduledJobException(StringUtil.Format(ScheduledJobErrorStrings.JobDefFileAlreadyExists, definitionName)); - ex.FQEID = ScheduledJobDefExistsFQEID; - throw ex; - } - - Directory.CreateDirectory(filePath); - Directory.CreateDirectory(outputPath); - return string.Format(CultureInfo.InstalledUICulture, @"{0}\{1}.xml", filePath, fileName); - } - - /// - /// Returns a file path/name for an existing Scheduled job definition directory. - /// - /// Definition name. - /// File name. - /// File path/name. - private static string GetFilePathName(string definitionName, string fileName) - { - string filePath = GetJobDefinitionPath(definitionName); - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.xml", filePath, fileName); - } - - /// - /// Gets the directory path for a Scheduled Job Definition. - /// - /// Scheduled job definition name. - /// Directory Path. - private static string GetJobDefinitionPath(string definitionName) - { -#if UNIX - return Path.Combine(Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE), "ScheduledJobs", definitionName); -#else - return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), - ScheduledJobsPath, - definitionName); -#endif - } - - /// - /// Returns a directory path for an existing ScheduledJob run result directory. - /// - /// Definition name. - /// File name. - /// Directory Path. - private static string GetRunDirectory( - string definitionName, - DateTime runStart) - { - string directoryPath = GetJobRunOutputDirectory(definitionName); - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", directoryPath, - ConvertDateTimeToJobRunName(runStart)); - } - - /// - /// Returns a directory path for an existing ScheduledJob run based on - /// provided definition Output directory path. - /// - /// Output directory path. - /// File name. - /// Directory Path. - private static string GetRunDirectoryFromPath( - string definitionOutputPath, - DateTime runStart) - { - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", - definitionOutputPath, ConvertDateTimeToJobRunName(runStart)); - } - - /// - /// Returns a file path/name for a run result file. Will create the - /// job run directory if it does not exist. - /// - /// Definition name. - /// Result type. - /// Run date. - /// File path/name. - private static string GetRunFilePathName( - string definitionName, - JobRunItem runItem, - DateTime runStart) - { - string directoryPath = GetJobRunOutputDirectory(definitionName); - string jobRunPath = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", - directoryPath, ConvertDateTimeToJobRunName(runStart)); - - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.xml", jobRunPath, - runItem.ToString()); - } - - /// - /// Returns a file path/name for a job run result, based on the passed in - /// job run output path. Will create the job run directory if it does not - /// exist. - /// - /// Definition job run output path. - /// Result type. - /// Run date. - /// - private static string GetRunFilePathNameFromPath( - string outputPath, - JobRunItem runItem, - DateTime runStart) - { - string jobRunPath = string.Format(CultureInfo.InvariantCulture, @"{0}\{1}", - outputPath, ConvertDateTimeToJobRunName(runStart)); - - if (!Directory.Exists(jobRunPath)) - { - // Create directory for this job run date. - Directory.CreateDirectory(jobRunPath); - } - - return string.Format(CultureInfo.InvariantCulture, @"{0}\{1}.xml", jobRunPath, - runItem.ToString()); - } - - private static void AddFullAccessToDirectory( - string user, - string directoryPath) - { - // Create rule. - DirectoryInfo info = new DirectoryInfo(directoryPath); - DirectorySecurity dSecurity = info.GetAccessControl(); - FileSystemAccessRule fileAccessRule = new FileSystemAccessRule( - user, - FileSystemRights.FullControl, - InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, - PropagationFlags.None, - AccessControlType.Allow); - - // Apply rule. - dSecurity.AddAccessRule(fileAccessRule); - info.SetAccessControl(dSecurity); - } - - // - // String format: 'YYYYMMDD-HHMMSS-SSS' - // ,where SSS is milliseconds. - // - - private static string ConvertDateTimeToJobRunName(DateTime dt) - { - return string.Format(CultureInfo.InvariantCulture, - @"{0:d4}{1:d2}{2:d2}-{3:d2}{4:d2}{5:d2}-{6:d3}", - dt.Year, dt.Month, dt.Day, - dt.Hour, dt.Minute, dt.Second, dt.Millisecond); - } - - /// - /// Converts a jobRun name string to an equivalent DateTime. - /// - /// - /// - /// - internal static bool ConvertJobRunNameToDateTime(string jobRunName, out DateTime jobRun) - { - if (jobRunName == null || jobRunName.Length != 19) - { - jobRun = new DateTime(); - return false; - } - - int year = 0; - int month = 0; - int day = 0; - int hour = 0; - int minute = 0; - int second = 0; - int msecs = 0; - bool success = true; - - try - { - year = Convert.ToInt32(jobRunName.Substring(0, 4)); - month = Convert.ToInt32(jobRunName.Substring(4, 2)); - day = Convert.ToInt32(jobRunName.Substring(6, 2)); - hour = Convert.ToInt32(jobRunName.Substring(9, 2)); - minute = Convert.ToInt32(jobRunName.Substring(11, 2)); - second = Convert.ToInt32(jobRunName.Substring(13, 2)); - msecs = Convert.ToInt32(jobRunName.Substring(16, 3)); - } - catch (FormatException) - { - success = false; - } - catch (OverflowException) - { - success = false; - } - - if (success) - { - jobRun = new DateTime(year, month, day, hour, minute, second, msecs); - } - else - { - jobRun = new DateTime(); - } - - return success; - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs deleted file mode 100644 index f32f33ce008..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobTrigger.cs +++ /dev/null @@ -1,897 +0,0 @@ -// 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.Runtime.Serialization; -using System.Security.Permissions; -using System.Text; -using System.Threading; - -using Microsoft.Management.Infrastructure; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This class contains parameters used to define how/when a PowerShell job is - /// run via the Windows Task Scheduler (WTS). - /// - [Serializable] - public sealed class ScheduledJobTrigger : ISerializable - { - #region Private Members - - private DateTime? _time; - private List _daysOfWeek; - private TimeSpan _randomDelay; - private Int32 _interval = 1; - private string _user; - private TriggerFrequency _frequency = TriggerFrequency.None; - private TimeSpan? _repInterval; - private TimeSpan? _repDuration; - - private Int32 _id; - private bool _enabled = true; - private ScheduledJobDefinition _jobDefAssociation; - - private static string _allUsers = "*"; - - #endregion - - #region Public Properties - - /// - /// Trigger time. - /// - public DateTime? At - { - get { return _time; } - - set { _time = value; } - } - - /// - /// Trigger days of week. - /// - public List DaysOfWeek - { - get { return _daysOfWeek; } - - set { _daysOfWeek = value; } - } - - /// - /// Trigger days or weeks interval. - /// - public Int32 Interval - { - get { return _interval; } - - set { _interval = value; } - } - - /// - /// Trigger frequency. - /// - public TriggerFrequency Frequency - { - get { return _frequency; } - - set { _frequency = value; } - } - - /// - /// Trigger random delay. - /// - public TimeSpan RandomDelay - { - get { return _randomDelay; } - - set { _randomDelay = value; } - } - - /// - /// Trigger Once frequency repetition interval. - /// - public TimeSpan? RepetitionInterval - { - get { return _repInterval; } - - set - { - // A TimeSpan value of zero is equivalent to a null value. - _repInterval = (value != null && value.Value == TimeSpan.Zero) ? - null : value; - } - } - - /// - /// Trigger Once frequency repetition duration. - /// - public TimeSpan? RepetitionDuration - { - get { return _repDuration; } - - set - { - // A TimeSpan value of zero is equivalent to a null value. - _repDuration = (value != null && value.Value == TimeSpan.Zero) ? - null : value; - } - } - - /// - /// Trigger user name. - /// - public string User - { - get { return _user; } - - set { _user = value; } - } - - /// - /// Returns the trigger local Id. - /// - public Int32 Id - { - get { return _id; } - - internal set { _id = value; } - } - - /// - /// Defines enabled state of trigger. - /// - public bool Enabled - { - get { return _enabled; } - - set { _enabled = value; } - } - - /// - /// ScheduledJobDefinition object this trigger is associated with. - /// - public ScheduledJobDefinition JobDefinition - { - get { return _jobDefAssociation; } - - internal set { _jobDefAssociation = value; } - } - - #endregion - - #region Constructors - - /// - /// Default constructor. - /// - public ScheduledJobTrigger() - { } - - /// - /// Constructor. - /// - /// Enabled. - /// Trigger frequency. - /// Trigger time. - /// Weekly days of week. - /// Daily or Weekly interval. - /// Random delay. - /// Repetition interval. - /// Repetition duration. - /// Logon user. - /// Trigger id. - private ScheduledJobTrigger( - bool enabled, - TriggerFrequency frequency, - DateTime? time, - List daysOfWeek, - Int32 interval, - TimeSpan randomDelay, - TimeSpan? repetitionInterval, - TimeSpan? repetitionDuration, - string user, - Int32 id) - { - _enabled = enabled; - _frequency = frequency; - _time = time; - _daysOfWeek = daysOfWeek; - _interval = interval; - _randomDelay = randomDelay; - RepetitionInterval = repetitionInterval; - RepetitionDuration = repetitionDuration; - _user = user; - _id = id; - } - - /// - /// Copy constructor. - /// - /// ScheduledJobTrigger. - internal ScheduledJobTrigger(ScheduledJobTrigger copyTrigger) - { - if (copyTrigger == null) - { - throw new PSArgumentNullException("copyTrigger"); - } - - _enabled = copyTrigger.Enabled; - _frequency = copyTrigger.Frequency; - _id = copyTrigger.Id; - _time = copyTrigger.At; - _daysOfWeek = copyTrigger.DaysOfWeek; - _interval = copyTrigger.Interval; - _randomDelay = copyTrigger.RandomDelay; - _repInterval = copyTrigger.RepetitionInterval; - _repDuration = copyTrigger.RepetitionDuration; - _user = copyTrigger.User; - - _jobDefAssociation = copyTrigger.JobDefinition; - } - - /// - /// Serialization constructor. - /// - /// SerializationInfo. - /// StreamingContext. - private ScheduledJobTrigger( - SerializationInfo info, - StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - DateTime time = info.GetDateTime("Time_Value"); - if (time != DateTime.MinValue) - { - _time = time; - } - else - { - _time = null; - } - - RepetitionInterval = (TimeSpan?)info.GetValue("RepetitionInterval_Value", typeof(TimeSpan)); - RepetitionDuration = (TimeSpan?)info.GetValue("RepetitionDuration_Value", typeof(TimeSpan)); - - _daysOfWeek = (List)info.GetValue("DaysOfWeek_Value", typeof(List)); - _randomDelay = (TimeSpan)info.GetValue("RandomDelay_Value", typeof(TimeSpan)); - _interval = info.GetInt32("Interval_Value"); - _user = info.GetString("User_Value"); - _frequency = (TriggerFrequency)info.GetValue("TriggerFrequency_Value", typeof(TriggerFrequency)); - _id = info.GetInt32("ID_Value"); - _enabled = info.GetBoolean("Enabled_Value"); - - // Runtime reference and not saved to store. - _jobDefAssociation = null; - } - - #endregion - - #region ISerializable Implementation - - /// - /// GetObjectData for ISerializable implementation. - /// - /// - /// - public void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException("info"); - } - - if (_time == null) - { - info.AddValue("Time_Value", DateTime.MinValue); - } - else - { - info.AddValue("Time_Value", _time); - } - - if (_repInterval == null) - { - info.AddValue("RepetitionInterval_Value", TimeSpan.Zero); - } - else - { - info.AddValue("RepetitionInterval_Value", _repInterval); - } - - if (_repDuration == null) - { - info.AddValue("RepetitionDuration_Value", TimeSpan.Zero); - } - else - { - info.AddValue("RepetitionDuration_Value", _repDuration); - } - - info.AddValue("DaysOfWeek_Value", _daysOfWeek); - info.AddValue("RandomDelay_Value", _randomDelay); - info.AddValue("Interval_Value", _interval); - info.AddValue("User_Value", _user); - info.AddValue("TriggerFrequency_Value", _frequency); - info.AddValue("ID_Value", _id); - info.AddValue("Enabled_Value", _enabled); - } - - #endregion - - #region Internal Methods - - internal void ClearProperties() - { - _time = null; - _daysOfWeek = null; - _interval = 1; - _randomDelay = TimeSpan.Zero; - _repInterval = null; - _repDuration = null; - _user = null; - _frequency = TriggerFrequency.None; - _enabled = false; - _id = 0; - } - - internal void Validate() - { - switch (_frequency) - { - case TriggerFrequency.None: - throw new ScheduledJobException(ScheduledJobErrorStrings.MissingJobTriggerType); - - case TriggerFrequency.AtStartup: - // AtStartup has no required parameters. - break; - - case TriggerFrequency.AtLogon: - // AtLogon has no required parameters. - break; - - case TriggerFrequency.Once: - if (_time == null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerTime, ScheduledJobErrorStrings.TriggerOnceType); - throw new ScheduledJobException(msg); - } - - if (_repInterval != null || _repDuration != null) - { - ValidateOnceRepetitionParams(_repInterval, _repDuration); - } - - break; - - case TriggerFrequency.Daily: - if (_time == null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerTime, ScheduledJobErrorStrings.TriggerDailyType); - throw new ScheduledJobException(msg); - } - - if (_interval < 1) - { - throw new ScheduledJobException(ScheduledJobErrorStrings.InvalidDaysIntervalParam); - } - - break; - - case TriggerFrequency.Weekly: - if (_time == null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerTime, ScheduledJobErrorStrings.TriggerWeeklyType); - throw new ScheduledJobException(msg); - } - - if (_interval < 1) - { - throw new ScheduledJobException(ScheduledJobErrorStrings.InvalidWeeksIntervalParam); - } - - if (_daysOfWeek == null || _daysOfWeek.Count == 0) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingJobTriggerDaysOfWeek, ScheduledJobErrorStrings.TriggerWeeklyType); - throw new ScheduledJobException(msg); - } - - break; - } - } - - internal static void ValidateOnceRepetitionParams( - TimeSpan? repInterval, - TimeSpan? repDuration) - { - // Both Interval and Duration parameters must be specified together. - if (repInterval == null || repDuration == null) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParams); - } - - // Interval and Duration parameters must not have negative value. - if (repInterval < TimeSpan.Zero || repDuration < TimeSpan.Zero) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParamValues); - } - - // Zero values are allowed but only if both parameters are set to zero. - // This removes repetition from the Once trigger. - if (repInterval == TimeSpan.Zero && repDuration != TimeSpan.Zero) - { - throw new PSArgumentException(ScheduledJobErrorStrings.MismatchedRepetitionParamValues); - } - - // Parameter values must be GE to one minute unless both are zero to remove repetition. - if (repInterval < TimeSpan.FromMinutes(1) && - !(repInterval == TimeSpan.Zero && repDuration == TimeSpan.Zero)) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionIntervalValue); - } - - // Interval parameter must be LE to Duration parameter. - if (repInterval > repDuration) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionInterval); - } - } - - internal void CopyTo(ScheduledJobTrigger targetTrigger) - { - if (targetTrigger == null) - { - throw new PSArgumentNullException("targetTrigger"); - } - - targetTrigger.Enabled = _enabled; - targetTrigger.Frequency = _frequency; - targetTrigger.Id = _id; - targetTrigger.At = _time; - targetTrigger.DaysOfWeek = _daysOfWeek; - targetTrigger.Interval = _interval; - targetTrigger.RandomDelay = _randomDelay; - targetTrigger.RepetitionInterval = _repInterval; - targetTrigger.RepetitionDuration = _repDuration; - targetTrigger.User = _user; - targetTrigger.JobDefinition = _jobDefAssociation; - } - - #endregion - - #region Static methods - - /// - /// Creates a one time ScheduledJobTrigger object. - /// - /// DateTime when trigger activates. - /// Random delay. - /// Repetition interval. - /// Repetition duration. - /// Trigger Id. - /// Trigger enabled state. - /// ScheduledJobTrigger. - public static ScheduledJobTrigger CreateOnceTrigger( - DateTime time, - TimeSpan delay, - TimeSpan? repetitionInterval, - TimeSpan? repetitionDuration, - Int32 id, - bool enabled) - { - return new ScheduledJobTrigger( - enabled, - TriggerFrequency.Once, - time, - null, - 1, - delay, - repetitionInterval, - repetitionDuration, - null, - id); - } - - /// - /// Creates a daily ScheduledJobTrigger object. - /// - /// Time of day when trigger activates. - /// Days interval for trigger activation. - /// Random delay. - /// Trigger Id. - /// Trigger enabled state. - /// ScheduledJobTrigger. - public static ScheduledJobTrigger CreateDailyTrigger( - DateTime time, - Int32 interval, - TimeSpan delay, - Int32 id, - bool enabled) - { - return new ScheduledJobTrigger( - enabled, - TriggerFrequency.Daily, - time, - null, - interval, - delay, - null, - null, - null, - id); - } - - /// - /// Creates a weekly ScheduledJobTrigger object. - /// - /// Time of day when trigger activates. - /// Weeks interval for trigger activation. - /// Days of the week for trigger activation. - /// Random delay. - /// Trigger Id. - /// Trigger enabled state. - /// ScheduledJobTrigger. - public static ScheduledJobTrigger CreateWeeklyTrigger( - DateTime time, - Int32 interval, - IEnumerable daysOfWeek, - TimeSpan delay, - Int32 id, - bool enabled) - { - List lDaysOfWeek = (daysOfWeek != null) ? new List(daysOfWeek) : null; - - return new ScheduledJobTrigger( - enabled, - TriggerFrequency.Weekly, - time, - lDaysOfWeek, - interval, - delay, - null, - null, - null, - id); - } - - /// - /// Creates a trigger that activates after user log on. - /// - /// Name of user. - /// Random delay. - /// Trigger Id. - /// Trigger enabled state. - /// ScheduledJobTrigger. - public static ScheduledJobTrigger CreateAtLogOnTrigger( - string user, - TimeSpan delay, - Int32 id, - bool enabled) - { - return new ScheduledJobTrigger( - enabled, - TriggerFrequency.AtLogon, - null, - null, - 1, - delay, - null, - null, - string.IsNullOrEmpty(user) ? AllUsers : user, - id); - } - - /// - /// Creates a trigger that activates after OS boot. - /// - /// Random delay. - /// Trigger Id. - /// Trigger enabled state. - /// ScheduledJobTrigger. - public static ScheduledJobTrigger CreateAtStartupTrigger( - TimeSpan delay, - Int32 id, - bool enabled) - { - return new ScheduledJobTrigger( - enabled, - TriggerFrequency.AtStartup, - null, - null, - 1, - delay, - null, - null, - null, - id); - } - - /// - /// Compares provided user name to All Users string ("*"). - /// - /// Logon user name. - /// Boolean, true if All Users. - internal static bool IsAllUsers(string userName) - { - return (string.Compare(userName, ScheduledJobTrigger.AllUsers, - StringComparison.OrdinalIgnoreCase) == 0); - } - - /// - /// Returns the All Users string. - /// - internal static string AllUsers - { - get { return _allUsers; } - } - - #endregion - - #region Public Methods - - /// - /// Update the associated ScheduledJobDefinition object with the - /// current properties of this object. - /// - public void UpdateJobDefinition() - { - if (_jobDefAssociation == null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAssociatedJobDefinitionForTrigger, _id); - throw new RuntimeException(msg); - } - - _jobDefAssociation.UpdateTriggers(new ScheduledJobTrigger[1] { this }, true); - } - - #endregion - } - - #region Public Enums - - /// - /// Specifies trigger types in terms of the frequency that - /// the trigger is activated. - /// - public enum TriggerFrequency - { - /// - /// None. - /// - None = 0, - /// - /// Trigger activates once at a specified time. - /// - Once = 1, - /// - /// Trigger activates daily. - /// - Daily = 2, - /// - /// Trigger activates on a weekly basis and multiple days - /// during the week. - /// - Weekly = 3, - /// - /// Trigger activates at user logon to the operating system. - /// - AtLogon = 4, - /// - /// Trigger activates after machine boot up. - /// - AtStartup = 5 - } - - #endregion - - #region JobTriggerToCimInstanceConverter - /// - /// Class providing implementation of PowerShell conversions for types in Microsoft.Management.Infrastructure namespace. - /// - public sealed class JobTriggerToCimInstanceConverter : PSTypeConverter - { - private static readonly string CIM_TRIGGER_NAMESPACE = @"Root\Microsoft\Windows\TaskScheduler"; - - /// - /// Determines if the converter can convert the parameter to the parameter. - /// - /// The value to convert from. - /// The type to convert to. - /// True if the converter can convert the parameter to the parameter, otherwise false. - public override bool CanConvertFrom(object sourceValue, Type destinationType) - { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } - - return (sourceValue is ScheduledJobTrigger) && (destinationType.Equals(typeof(CimInstance))); - } - - /// - /// Converts the parameter to the parameter using formatProvider and ignoreCase. - /// - /// The value to convert from. - /// The type to convert to. - /// The format provider to use like in IFormattable's ToString. - /// True if case should be ignored. - /// The parameter converted to the parameter using formatProvider and ignoreCase. - /// If no conversion was possible. - public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) - { - if (destinationType == null) - { - throw new ArgumentNullException("destinationType"); - } - - if (sourceValue == null) - { - throw new ArgumentNullException("sourceValue"); - } - - ScheduledJobTrigger originalTrigger = (ScheduledJobTrigger) sourceValue; - using (CimSession cimSession = CimSession.Create(null)) - { - switch (originalTrigger.Frequency) - { - case TriggerFrequency.Weekly: - return ConvertToWeekly(originalTrigger, cimSession); - case TriggerFrequency.Once: - return ConvertToOnce(originalTrigger, cimSession); - case TriggerFrequency.Daily: - return ConvertToDaily(originalTrigger, cimSession); - case TriggerFrequency.AtStartup: - return ConvertToAtStartup(originalTrigger, cimSession); - case TriggerFrequency.AtLogon: - return ConvertToAtLogon(originalTrigger, cimSession); - case TriggerFrequency.None: - return ConvertToDefault(originalTrigger, cimSession); - default: - string errorMsg = StringUtil.Format(ScheduledJobErrorStrings.UnknownTriggerFrequency, - originalTrigger.Frequency.ToString()); - throw new PSInvalidOperationException(errorMsg); - } - } - } - - /// - /// Returns true if the converter can convert the parameter to the parameter. - /// - /// The value to convert from. - /// The type to convert to. - /// True if the converter can convert the parameter to the parameter, otherwise false. - public override bool CanConvertTo(object sourceValue, Type destinationType) - { - return false; - } - - /// - /// Converts the parameter to the parameter using formatProvider and ignoreCase. - /// - /// The value to convert from. - /// The type to convert to. - /// The format provider to use like in IFormattable's ToString. - /// True if case should be ignored. - /// SourceValue converted to the parameter using formatProvider and ignoreCase. - /// If no conversion was possible. - public override object ConvertTo(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) - { - throw new NotImplementedException(); - } - - #region Helper Methods - - private CimInstance ConvertToWeekly(ScheduledJobTrigger trigger, CimSession cimSession) - { - CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskWeeklyTrigger"); - CimInstance cimInstance = new CimInstance(cimClass); - - cimInstance.CimInstanceProperties["DaysOfWeek"].Value = ScheduledJobWTS.ConvertDaysOfWeekToMask(trigger.DaysOfWeek); - cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay); - cimInstance.CimInstanceProperties["WeeksInterval"].Value = trigger.Interval; - - AddCommonProperties(trigger, cimInstance); - return cimInstance; - } - - private CimInstance ConvertToOnce(ScheduledJobTrigger trigger, CimSession cimSession) - { - CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskTimeTrigger"); - CimInstance cimInstance = new CimInstance(cimClass); - - cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay); - - if (trigger.RepetitionInterval != null && trigger.RepetitionDuration != null) - { - CimClass cimRepClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskRepetitionPattern"); - CimInstance cimRepInstance = new CimInstance(cimRepClass); - - cimRepInstance.CimInstanceProperties["Interval"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RepetitionInterval.Value); - - if (trigger.RepetitionDuration == TimeSpan.MaxValue) - { - cimRepInstance.CimInstanceProperties["StopAtDurationEnd"].Value = false; - } - else - { - cimRepInstance.CimInstanceProperties["StopAtDurationEnd"].Value = true; - cimRepInstance.CimInstanceProperties["Duration"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RepetitionDuration.Value); - } - - cimInstance.CimInstanceProperties["Repetition"].Value = cimRepInstance; - } - - AddCommonProperties(trigger, cimInstance); - return cimInstance; - } - - private CimInstance ConvertToDaily(ScheduledJobTrigger trigger, CimSession cimSession) - { - CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskDailyTrigger"); - CimInstance cimInstance = new CimInstance(cimClass); - - cimInstance.CimInstanceProperties["RandomDelay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay); - cimInstance.CimInstanceProperties["DaysInterval"].Value = trigger.Interval; - - AddCommonProperties(trigger, cimInstance); - return cimInstance; - } - - private CimInstance ConvertToAtLogon(ScheduledJobTrigger trigger, CimSession cimSession) - { - CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskLogonTrigger"); - CimInstance cimInstance = new CimInstance(cimClass); - - cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay); - - // Convert the "AllUsers" name ("*" character) to null for Task Scheduler. - string userId = (ScheduledJobTrigger.IsAllUsers(trigger.User)) ? null : trigger.User; - cimInstance.CimInstanceProperties["UserId"].Value = userId; - - AddCommonProperties(trigger, cimInstance); - return cimInstance; - } - - private CimInstance ConvertToAtStartup(ScheduledJobTrigger trigger, CimSession cimSession) - { - CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskBootTrigger"); - CimInstance cimInstance = new CimInstance(cimClass); - - cimInstance.CimInstanceProperties["Delay"].Value = ScheduledJobWTS.ConvertTimeSpanToWTSString(trigger.RandomDelay); - - AddCommonProperties(trigger, cimInstance); - return cimInstance; - } - - private CimInstance ConvertToDefault(ScheduledJobTrigger trigger, CimSession cimSession) - { - CimClass cimClass = cimSession.GetClass(CIM_TRIGGER_NAMESPACE, "MSFT_TaskTrigger"); - CimInstance result = new CimInstance(cimClass); - AddCommonProperties(trigger, result); - return result; - } - - private static void AddCommonProperties(ScheduledJobTrigger trigger, CimInstance cimInstance) - { - cimInstance.CimInstanceProperties["Enabled"].Value = trigger.Enabled; - - if (trigger.At != null) - { - cimInstance.CimInstanceProperties["StartBoundary"].Value = ScheduledJobWTS.ConvertDateTimeToString(trigger.At); - } - } - - #endregion - } - - #endregion -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs b/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs deleted file mode 100644 index a8d76ef7da8..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/ScheduledJobWTS.cs +++ /dev/null @@ -1,961 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Diagnostics; -using System.Globalization; -using System.Management.Automation; -using System.Runtime.InteropServices; -using System.Security.AccessControl; -using System.Text; - -using TaskScheduler; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// Managed code class to provide Windows Task Scheduler functionality for - /// scheduled jobs. - /// - internal sealed class ScheduledJobWTS : IDisposable - { - #region Private Members - - private ITaskService _taskScheduler; - private ITaskFolder _iRootFolder; - - private const short WTSSunday = 0x01; - private const short WTSMonday = 0x02; - private const short WTSTuesday = 0x04; - private const short WTSWednesday = 0x08; - private const short WTSThursday = 0x10; - private const short WTSFriday = 0x20; - private const short WTSSaturday = 0x40; - - // Task Scheduler folders for PowerShell scheduled job tasks. - private const string TaskSchedulerWindowsFolder = @"\Microsoft\Windows"; - private const string ScheduledJobSubFolder = @"PowerShell\ScheduledJobs"; - private const string ScheduledJobTasksRootFolder = @"\Microsoft\Windows\PowerShell\ScheduledJobs"; - - // Define a single Action Id since PowerShell Scheduled Job tasks will have only one action. - private const string ScheduledJobTaskActionId = "StartPowerShellJob"; - - #endregion - - #region Constructors - - public ScheduledJobWTS() - { - // Create the Windows Task Scheduler object. - _taskScheduler = (ITaskService)new TaskScheduler.TaskScheduler(); - - // Connect the task scheduler object to the local machine - // using the current user security token. - _taskScheduler.Connect(null, null, null, null); - - // Get or create the root folder in Task Scheduler for PowerShell scheduled jobs. - _iRootFolder = GetRootFolder(); - } - - #endregion - - #region Public Methods - - /// - /// Retrieves job triggers from WTS with provided task Id. - /// - /// Task Id. - /// Task not found. - /// ScheduledJobTriggers. - public Collection GetJobTriggers( - string taskId) - { - if (string.IsNullOrEmpty(taskId)) - { - throw new PSArgumentException("taskId"); - } - - ITaskDefinition iTaskDefinition = FindTask(taskId); - - Collection jobTriggers = new Collection(); - ITriggerCollection iTriggerCollection = iTaskDefinition.Triggers; - if (iTriggerCollection != null) - { - foreach (ITrigger iTrigger in iTriggerCollection) - { - ScheduledJobTrigger jobTrigger = CreateJobTrigger(iTrigger); - if (jobTrigger == null) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.UnknownTriggerType, taskId, iTrigger.Id); - throw new ScheduledJobException(msg); - } - - jobTriggers.Add(jobTrigger); - } - } - - return jobTriggers; - } - - /// - /// Retrieves options for the provided task Id. - /// - /// Task Id. - /// Task not found. - /// ScheduledJobOptions. - public ScheduledJobOptions GetJobOptions( - string taskId) - { - if (string.IsNullOrEmpty(taskId)) - { - throw new PSArgumentException("taskId"); - } - - ITaskDefinition iTaskDefinition = FindTask(taskId); - - return CreateJobOptions(iTaskDefinition); - } - - /// - /// Returns a boolean indicating whether the job/task is enabled - /// in the Task Scheduler. - /// - /// - /// - public bool GetTaskEnabled( - string taskId) - { - if (string.IsNullOrEmpty(taskId)) - { - throw new PSArgumentException("taskId"); - } - - ITaskDefinition iTaskDefinition = FindTask(taskId); - - return iTaskDefinition.Settings.Enabled; - } - - /// - /// Creates a new task in WTS with information from ScheduledJobDefinition. - /// - /// ScheduledJobDefinition. - public void CreateTask( - ScheduledJobDefinition definition) - { - if (definition == null) - { - throw new PSArgumentNullException("definition"); - } - - // Create task definition - ITaskDefinition iTaskDefinition = _taskScheduler.NewTask(0); - - // Add task options. - AddTaskOptions(iTaskDefinition, definition.Options); - - // Add task triggers. - foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers) - { - AddTaskTrigger(iTaskDefinition, jobTrigger); - } - - // Add task action. - AddTaskAction(iTaskDefinition, definition); - - // Create a security descriptor for the current user so that only the user - // (and Local System account) can see/access the registered task. - string startSddl = "D:P(A;;GA;;;SY)(A;;GA;;;BA)"; // DACL Allow Generic Access to System and BUILTIN\Administrators. - System.Security.Principal.SecurityIdentifier userSid = - System.Security.Principal.WindowsIdentity.GetCurrent().User; - CommonSecurityDescriptor SDesc = new CommonSecurityDescriptor(false, false, startSddl); - SDesc.DiscretionaryAcl.AddAccess(AccessControlType.Allow, userSid, 0x10000000, InheritanceFlags.None, PropagationFlags.None); - string sddl = SDesc.GetSddlForm(AccessControlSections.All); - - // Register this new task with the Task Scheduler. - if (definition.Credential == null) - { - // Register task to run as currently logged on user. - _iRootFolder.RegisterTaskDefinition( - definition.Name, - iTaskDefinition, - (int)_TASK_CREATION.TASK_CREATE, - null, // User name - null, // Password - _TASK_LOGON_TYPE.TASK_LOGON_S4U, - sddl); - } - else - { - // Register task to run under provided user account/credentials. - _iRootFolder.RegisterTaskDefinition( - definition.Name, - iTaskDefinition, - (int)_TASK_CREATION.TASK_CREATE, - definition.Credential.UserName, - GetCredentialPassword(definition.Credential), - _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD, - sddl); - } - } - - /// - /// Removes the WTS task for this ScheduledJobDefinition. - /// Throws error if one or more instances of this task are running. - /// Force parameter will stop all running instances and remove task. - /// - /// ScheduledJobDefinition. - /// Force running instances to stop and remove task. - public void RemoveTask( - ScheduledJobDefinition definition, - bool force = false) - { - if (definition == null) - { - throw new PSArgumentNullException("definition"); - } - - RemoveTaskByName(definition.Name, force, false); - } - - /// - /// Removes a Task Scheduler task from the PowerShell/ScheduledJobs folder - /// based on a task name. - /// - /// Task Scheduler task name. - /// Force running instances to stop and remove task. - /// First check for existence of task. - public void RemoveTaskByName( - string taskName, - bool force, - bool firstCheckForTask) - { - // Get registered task. - IRegisteredTask iRegisteredTask = null; - try - { - iRegisteredTask = _iRootFolder.GetTask(taskName); - } - catch (System.IO.DirectoryNotFoundException) - { - if (!firstCheckForTask) - { - throw; - } - } - catch (System.IO.FileNotFoundException) - { - if (!firstCheckForTask) - { - throw; - } - } - - if (iRegisteredTask == null) - { - return; - } - - // Check to see if any instances of this job/task is running. - IRunningTaskCollection iRunningTasks = iRegisteredTask.GetInstances(0); - if (iRunningTasks.Count > 0) - { - if (!force) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CannotRemoveTaskRunningInstance, taskName); - throw new ScheduledJobException(msg); - } - - // Stop all running tasks. - iRegisteredTask.Stop(0); - } - - // Remove task. - _iRootFolder.DeleteTask(taskName, 0); - } - - /// - /// Starts task running from Task Scheduler. - /// - /// ScheduledJobDefinition. - /// - /// - public void RunTask( - ScheduledJobDefinition definition) - { - // Get registered task. - IRegisteredTask iRegisteredTask = _iRootFolder.GetTask(definition.Name); - - // Run task. - iRegisteredTask.Run(null); - } - - /// - /// Updates an existing task in WTS with information from - /// ScheduledJobDefinition. - /// - /// ScheduledJobDefinition. - public void UpdateTask( - ScheduledJobDefinition definition) - { - if (definition == null) - { - throw new PSArgumentNullException("definition"); - } - - // Get task to update. - ITaskDefinition iTaskDefinition = FindTask(definition.Name); - - // Replace options. - AddTaskOptions(iTaskDefinition, definition.Options); - - // Set enabled state. - iTaskDefinition.Settings.Enabled = definition.Enabled; - - // Replace triggers. - iTaskDefinition.Triggers.Clear(); - foreach (ScheduledJobTrigger jobTrigger in definition.JobTriggers) - { - AddTaskTrigger(iTaskDefinition, jobTrigger); - } - - // Replace action. - iTaskDefinition.Actions.Clear(); - AddTaskAction(iTaskDefinition, definition); - - // Register updated task. - if (definition.Credential == null) - { - // Register task to run as currently logged on user. - _iRootFolder.RegisterTaskDefinition( - definition.Name, - iTaskDefinition, - (int)_TASK_CREATION.TASK_UPDATE, - null, // User name - null, // Password - _TASK_LOGON_TYPE.TASK_LOGON_S4U, - null); - } - else - { - // Register task to run under provided user account/credentials. - _iRootFolder.RegisterTaskDefinition( - definition.Name, - iTaskDefinition, - (int)_TASK_CREATION.TASK_UPDATE, - definition.Credential.UserName, - GetCredentialPassword(definition.Credential), - _TASK_LOGON_TYPE.TASK_LOGON_PASSWORD, - null); - } - } - - #endregion - - #region Private Methods - - /// - /// Creates a new WTS trigger based on the provided ScheduledJobTrigger object - /// and adds it to the provided ITaskDefinition object. - /// - /// ITaskDefinition. - /// ScheduledJobTrigger. - private void AddTaskTrigger( - ITaskDefinition iTaskDefinition, - ScheduledJobTrigger jobTrigger) - { - ITrigger iTrigger = null; - - switch (jobTrigger.Frequency) - { - case TriggerFrequency.AtStartup: - { - iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_BOOT); - IBootTrigger iBootTrigger = iTrigger as IBootTrigger; - Debug.Assert(iBootTrigger != null); - - iBootTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); - - iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); - iTrigger.Enabled = jobTrigger.Enabled; - } - - break; - - case TriggerFrequency.AtLogon: - { - iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_LOGON); - ILogonTrigger iLogonTrigger = iTrigger as ILogonTrigger; - Debug.Assert(iLogonTrigger != null); - - iLogonTrigger.UserId = ScheduledJobTrigger.IsAllUsers(jobTrigger.User) ? null : jobTrigger.User; - iLogonTrigger.Delay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); - - iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); - iTrigger.Enabled = jobTrigger.Enabled; - } - - break; - - case TriggerFrequency.Once: - { - iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_TIME); - ITimeTrigger iTimeTrigger = iTrigger as ITimeTrigger; - Debug.Assert(iTimeTrigger != null); - - iTimeTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); - - // Time trigger repetition. - if (jobTrigger.RepetitionInterval != null && - jobTrigger.RepetitionDuration != null) - { - iTimeTrigger.Repetition.Interval = ConvertTimeSpanToWTSString(jobTrigger.RepetitionInterval.Value); - if (jobTrigger.RepetitionDuration.Value == TimeSpan.MaxValue) - { - iTimeTrigger.Repetition.StopAtDurationEnd = false; - } - else - { - iTimeTrigger.Repetition.StopAtDurationEnd = true; - iTimeTrigger.Repetition.Duration = ConvertTimeSpanToWTSString(jobTrigger.RepetitionDuration.Value); - } - } - - iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At); - iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); - iTrigger.Enabled = jobTrigger.Enabled; - } - - break; - - case TriggerFrequency.Daily: - { - iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_DAILY); - IDailyTrigger iDailyTrigger = iTrigger as IDailyTrigger; - Debug.Assert(iDailyTrigger != null); - - iDailyTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); - iDailyTrigger.DaysInterval = (short)jobTrigger.Interval; - - iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At); - iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); - iTrigger.Enabled = jobTrigger.Enabled; - } - - break; - - case TriggerFrequency.Weekly: - { - iTrigger = iTaskDefinition.Triggers.Create(_TASK_TRIGGER_TYPE2.TASK_TRIGGER_WEEKLY); - IWeeklyTrigger iWeeklyTrigger = iTrigger as IWeeklyTrigger; - Debug.Assert(iWeeklyTrigger != null); - - iWeeklyTrigger.RandomDelay = ConvertTimeSpanToWTSString(jobTrigger.RandomDelay); - iWeeklyTrigger.WeeksInterval = (short)jobTrigger.Interval; - iWeeklyTrigger.DaysOfWeek = ConvertDaysOfWeekToMask(jobTrigger.DaysOfWeek); - - iTrigger.StartBoundary = ConvertDateTimeToString(jobTrigger.At); - iTrigger.Id = jobTrigger.Id.ToString(CultureInfo.InvariantCulture); - iTrigger.Enabled = jobTrigger.Enabled; - } - - break; - } - } - - /// - /// Creates a ScheduledJobTrigger object based on a provided WTS ITrigger. - /// - /// ITrigger. - /// ScheduledJobTrigger. - private ScheduledJobTrigger CreateJobTrigger( - ITrigger iTrigger) - { - ScheduledJobTrigger rtnJobTrigger = null; - - if (iTrigger is IBootTrigger) - { - IBootTrigger iBootTrigger = (IBootTrigger)iTrigger; - rtnJobTrigger = ScheduledJobTrigger.CreateAtStartupTrigger( - ParseWTSTime(iBootTrigger.Delay), - ConvertStringId(iBootTrigger.Id), - iBootTrigger.Enabled); - } - else if (iTrigger is ILogonTrigger) - { - ILogonTrigger iLogonTrigger = (ILogonTrigger)iTrigger; - rtnJobTrigger = ScheduledJobTrigger.CreateAtLogOnTrigger( - iLogonTrigger.UserId, - ParseWTSTime(iLogonTrigger.Delay), - ConvertStringId(iLogonTrigger.Id), - iLogonTrigger.Enabled); - } - else if (iTrigger is ITimeTrigger) - { - ITimeTrigger iTimeTrigger = (ITimeTrigger)iTrigger; - TimeSpan repInterval = ParseWTSTime(iTimeTrigger.Repetition.Interval); - TimeSpan repDuration = (repInterval != TimeSpan.Zero && iTimeTrigger.Repetition.StopAtDurationEnd == false) ? - TimeSpan.MaxValue : ParseWTSTime(iTimeTrigger.Repetition.Duration); - rtnJobTrigger = ScheduledJobTrigger.CreateOnceTrigger( - DateTime.Parse(iTimeTrigger.StartBoundary, CultureInfo.InvariantCulture), - ParseWTSTime(iTimeTrigger.RandomDelay), - repInterval, - repDuration, - ConvertStringId(iTimeTrigger.Id), - iTimeTrigger.Enabled); - } - else if (iTrigger is IDailyTrigger) - { - IDailyTrigger iDailyTrigger = (IDailyTrigger)iTrigger; - rtnJobTrigger = ScheduledJobTrigger.CreateDailyTrigger( - DateTime.Parse(iDailyTrigger.StartBoundary, CultureInfo.InvariantCulture), - (Int32)iDailyTrigger.DaysInterval, - ParseWTSTime(iDailyTrigger.RandomDelay), - ConvertStringId(iDailyTrigger.Id), - iDailyTrigger.Enabled); - } - else if (iTrigger is IWeeklyTrigger) - { - IWeeklyTrigger iWeeklyTrigger = (IWeeklyTrigger)iTrigger; - rtnJobTrigger = ScheduledJobTrigger.CreateWeeklyTrigger( - DateTime.Parse(iWeeklyTrigger.StartBoundary, CultureInfo.InvariantCulture), - (Int32)iWeeklyTrigger.WeeksInterval, - ConvertMaskToDaysOfWeekArray(iWeeklyTrigger.DaysOfWeek), - ParseWTSTime(iWeeklyTrigger.RandomDelay), - ConvertStringId(iWeeklyTrigger.Id), - iWeeklyTrigger.Enabled); - } - - return rtnJobTrigger; - } - - private void AddTaskOptions( - ITaskDefinition iTaskDefinition, - ScheduledJobOptions jobOptions) - { - iTaskDefinition.Settings.DisallowStartIfOnBatteries = !jobOptions.StartIfOnBatteries; - iTaskDefinition.Settings.StopIfGoingOnBatteries = jobOptions.StopIfGoingOnBatteries; - iTaskDefinition.Settings.WakeToRun = jobOptions.WakeToRun; - iTaskDefinition.Settings.RunOnlyIfIdle = !jobOptions.StartIfNotIdle; - iTaskDefinition.Settings.IdleSettings.StopOnIdleEnd = jobOptions.StopIfGoingOffIdle; - iTaskDefinition.Settings.IdleSettings.RestartOnIdle = jobOptions.RestartOnIdleResume; - iTaskDefinition.Settings.IdleSettings.IdleDuration = ConvertTimeSpanToWTSString(jobOptions.IdleDuration); - iTaskDefinition.Settings.IdleSettings.WaitTimeout = ConvertTimeSpanToWTSString(jobOptions.IdleTimeout); - iTaskDefinition.Settings.Hidden = !jobOptions.ShowInTaskScheduler; - iTaskDefinition.Settings.RunOnlyIfNetworkAvailable = !jobOptions.RunWithoutNetwork; - iTaskDefinition.Settings.AllowDemandStart = !jobOptions.DoNotAllowDemandStart; - iTaskDefinition.Settings.MultipleInstances = ConvertFromMultiInstances(jobOptions.MultipleInstancePolicy); - iTaskDefinition.Principal.RunLevel = (jobOptions.RunElevated) ? - _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST : _TASK_RUNLEVEL.TASK_RUNLEVEL_LUA; - } - - private ScheduledJobOptions CreateJobOptions( - ITaskDefinition iTaskDefinition) - { - ITaskSettings iTaskSettings = iTaskDefinition.Settings; - IPrincipal iPrincipal = iTaskDefinition.Principal; - - return new ScheduledJobOptions( - !iTaskSettings.DisallowStartIfOnBatteries, - iTaskSettings.StopIfGoingOnBatteries, - iTaskSettings.WakeToRun, - !iTaskSettings.RunOnlyIfIdle, - iTaskSettings.IdleSettings.StopOnIdleEnd, - iTaskSettings.IdleSettings.RestartOnIdle, - ParseWTSTime(iTaskSettings.IdleSettings.IdleDuration), - ParseWTSTime(iTaskSettings.IdleSettings.WaitTimeout), - !iTaskSettings.Hidden, - iPrincipal.RunLevel == _TASK_RUNLEVEL.TASK_RUNLEVEL_HIGHEST, - !iTaskSettings.RunOnlyIfNetworkAvailable, - !iTaskSettings.AllowDemandStart, - ConvertToMultiInstances(iTaskSettings)); - } - - private void AddTaskAction( - ITaskDefinition iTaskDefinition, - ScheduledJobDefinition definition) - { - IExecAction iExecAction = iTaskDefinition.Actions.Create(_TASK_ACTION_TYPE.TASK_ACTION_EXEC) as IExecAction; - Debug.Assert(iExecAction != null); - - iExecAction.Id = ScheduledJobTaskActionId; - iExecAction.Path = definition.PSExecutionPath; - iExecAction.Arguments = definition.PSExecutionArgs; - } - - /// - /// Gets and returns the unsecured password for the provided - /// PSCredential object. - /// - /// PSCredential. - /// Unsecured password string. - private string GetCredentialPassword(PSCredential credential) - { - if (credential == null) - { - return null; - } - - IntPtr unmanagedString = IntPtr.Zero; - try - { - unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(credential.Password); - return Marshal.PtrToStringUni(unmanagedString); - } - finally - { - Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString); - } - } - - #endregion - - #region Private Utility Methods - - /// - /// Gets the Task Scheduler root folder for Scheduled Jobs or - /// creates it if it does not exist. - /// - /// Scheduled Jobs root folder. - private ITaskFolder GetRootFolder() - { - ITaskFolder iTaskRootFolder = null; - - try - { - iTaskRootFolder = _taskScheduler.GetFolder(ScheduledJobTasksRootFolder); - } - catch (System.IO.DirectoryNotFoundException) - { - } - catch (System.IO.FileNotFoundException) - { - // This can be thrown if COM interop tries to load the Microsoft.PowerShell.ScheduledJob - // assembly again. - } - - if (iTaskRootFolder == null) - { - // Create the PowerShell Scheduled Job root folder. - ITaskFolder iTSWindowsFolder = _taskScheduler.GetFolder(TaskSchedulerWindowsFolder); - iTaskRootFolder = iTSWindowsFolder.CreateFolder(ScheduledJobSubFolder); - } - - return iTaskRootFolder; - } - - /// - /// Finds a task with the provided Task Id and returns it as - /// a ITaskDefinition object. - /// - /// Task Id. - /// ITaskDefinition. - private ITaskDefinition FindTask(string taskId) - { - try - { - ITaskFolder iTaskFolder = _taskScheduler.GetFolder(ScheduledJobTasksRootFolder); - IRegisteredTask iRegisteredTask = iTaskFolder.GetTask(taskId); - return iRegisteredTask.Definition; - } - catch (System.IO.DirectoryNotFoundException e) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CannotFindTaskId, taskId); - throw new ScheduledJobException(msg, e); - } - } - - private Int32 ConvertStringId(string triggerId) - { - Int32 triggerIdVal = 0; - - try - { - triggerIdVal = Convert.ToInt32(triggerId); - } - catch (FormatException) - { } - catch (OverflowException) - { } - - return triggerIdVal; - } - - /// - /// Helper method to parse a WTS time string and return - /// a corresponding TimeSpan object. Note that the - /// year and month values are ignored. - /// Format: - /// "PnYnMnDTnHnMnS" - /// "P" - Date separator - /// "nY" - year value. - /// "nM" - month value. - /// "nD" - day value. - /// "T" - Time separator - /// "nH" - hour value. - /// "nM" - minute value. - /// "nS" - second value. - /// - /// Formatted time string. - /// TimeSpan. - private TimeSpan ParseWTSTime(string wtsTime) - { - if (string.IsNullOrEmpty(wtsTime)) - { - return new TimeSpan(0); - } - - int days = 0; - int hours = 0; - int minutes = 0; - int seconds = 0; - int indx = 0; - int length = wtsTime.Length; - StringBuilder str = new StringBuilder(); - - try - { - while (indx != length) - { - char c = wtsTime[indx++]; - - switch (c) - { - case 'P': - str.Clear(); - while (indx != length && - wtsTime[indx] != 'T') - { - char c2 = wtsTime[indx++]; - if (c2 == 'Y') - { - // Ignore year value. - str.Clear(); - } - else if (c2 == 'M') - { - // Ignore month value. - str.Clear(); - } - else if (c2 == 'D') - { - days = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); - str.Clear(); - } - else if (c2 >= '0' && c2 <= '9') - { - str.Append(c2); - } - } - - break; - - case 'T': - str.Clear(); - while (indx != length && - wtsTime[indx] != 'P') - { - char c2 = wtsTime[indx++]; - if (c2 == 'H') - { - hours = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); - str.Clear(); - } - else if (c2 == 'M') - { - minutes = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); - str.Clear(); - } - else if (c2 == 'S') - { - seconds = Convert.ToInt32(str.ToString(), CultureInfo.InvariantCulture); - str.Clear(); - } - else if (c2 >= '0' && c2 <= '9') - { - str.Append(c2); - } - } - - break; - } - } - } - catch (FormatException) - { } - catch (OverflowException) - { } - - return new TimeSpan(days, hours, minutes, seconds); - } - - /// - /// Creates WTS formatted time string based on TimeSpan parameter. - /// - /// TimeSpan. - /// WTS time string. - internal static string ConvertTimeSpanToWTSString(TimeSpan time) - { - return string.Format( - CultureInfo.InvariantCulture, - "P{0}DT{1}H{2}M{3}S", - time.Days, - time.Hours, - time.Minutes, - time.Seconds); - } - - /// - /// Converts DateTime to string for WTS. - /// - /// DateTime. - /// DateTime string. - internal static string ConvertDateTimeToString(DateTime? dt) - { - if (dt == null) - { - return string.Empty; - } - else - { - return dt.Value.ToString("s", CultureInfo.InvariantCulture); - } - } - - /// - /// Returns a bitmask representing days of week as - /// required by Windows Task Scheduler API. - /// - /// Array of DayOfWeek. - /// WTS days of week mask. - internal static short ConvertDaysOfWeekToMask(IEnumerable daysOfWeek) - { - short rtnValue = 0; - foreach (DayOfWeek day in daysOfWeek) - { - switch (day) - { - case DayOfWeek.Sunday: - rtnValue |= WTSSunday; - break; - - case DayOfWeek.Monday: - rtnValue |= WTSMonday; - break; - - case DayOfWeek.Tuesday: - rtnValue |= WTSTuesday; - break; - - case DayOfWeek.Wednesday: - rtnValue |= WTSWednesday; - break; - - case DayOfWeek.Thursday: - rtnValue |= WTSThursday; - break; - - case DayOfWeek.Friday: - rtnValue |= WTSFriday; - break; - - case DayOfWeek.Saturday: - rtnValue |= WTSSaturday; - break; - } - } - - return rtnValue; - } - - /// - /// Converts WTS days of week mask to an array of DayOfWeek type. - /// - /// WTS days of week mask. - /// Days of week as List. - private List ConvertMaskToDaysOfWeekArray(short mask) - { - List daysOfWeek = new List(); - - if ((mask & WTSSunday) != 0) { daysOfWeek.Add(DayOfWeek.Sunday); } - - if ((mask & WTSMonday) != 0) { daysOfWeek.Add(DayOfWeek.Monday); } - - if ((mask & WTSTuesday) != 0) { daysOfWeek.Add(DayOfWeek.Tuesday); } - - if ((mask & WTSWednesday) != 0) { daysOfWeek.Add(DayOfWeek.Wednesday); } - - if ((mask & WTSThursday) != 0) { daysOfWeek.Add(DayOfWeek.Thursday); } - - if ((mask & WTSFriday) != 0) { daysOfWeek.Add(DayOfWeek.Friday); } - - if ((mask & WTSSaturday) != 0) { daysOfWeek.Add(DayOfWeek.Saturday); } - - return daysOfWeek; - } - - private TaskMultipleInstancePolicy ConvertToMultiInstances( - ITaskSettings iTaskSettings) - { - switch (iTaskSettings.MultipleInstances) - { - case _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW: - return TaskMultipleInstancePolicy.IgnoreNew; - - case _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL: - return TaskMultipleInstancePolicy.Parallel; - - case _TASK_INSTANCES_POLICY.TASK_INSTANCES_QUEUE: - return TaskMultipleInstancePolicy.Queue; - - case _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING: - return TaskMultipleInstancePolicy.StopExisting; - } - - Debug.Assert(false); - return TaskMultipleInstancePolicy.None; - } - - private _TASK_INSTANCES_POLICY ConvertFromMultiInstances( - TaskMultipleInstancePolicy jobPolicies) - { - switch (jobPolicies) - { - case TaskMultipleInstancePolicy.IgnoreNew: - return _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; - - case TaskMultipleInstancePolicy.Parallel: - return _TASK_INSTANCES_POLICY.TASK_INSTANCES_PARALLEL; - - case TaskMultipleInstancePolicy.Queue: - return _TASK_INSTANCES_POLICY.TASK_INSTANCES_QUEUE; - - case TaskMultipleInstancePolicy.StopExisting: - return _TASK_INSTANCES_POLICY.TASK_INSTANCES_STOP_EXISTING; - - default: - return _TASK_INSTANCES_POLICY.TASK_INSTANCES_IGNORE_NEW; - } - } - - #endregion - - #region IDisposable - - /// - /// Dispose. - /// - public void Dispose() - { - // Release reference to Task Scheduler object so that the COM - // object can be released. - _iRootFolder = null; - _taskScheduler = null; - - GC.SuppressFinalize(this); - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs deleted file mode 100644 index 2936fcf78c6..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/AddJobTrigger.cs +++ /dev/null @@ -1,146 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet adds ScheduledJobTriggers to ScheduledJobDefinition objects. - /// - [Cmdlet(VerbsCommon.Add, "JobTrigger", DefaultParameterSetName = AddJobTriggerCommand.JobDefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223913")] - public sealed class AddJobTriggerCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string JobDefinitionParameterSet = "JobDefinition"; - private const string JobDefinitionIdParameterSet = "JobDefinitionId"; - private const string JobDefinitionNameParameterSet = "JobDefinitionName"; - - /// - /// ScheduledJobTrigger. - /// - [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = AddJobTriggerCommand.JobDefinitionParameterSet)] - [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = AddJobTriggerCommand.JobDefinitionIdParameterSet)] - [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = AddJobTriggerCommand.JobDefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobTrigger[] Trigger - { - get { return _triggers; } - - set { _triggers = value; } - } - - private ScheduledJobTrigger[] _triggers; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = AddJobTriggerCommand.JobDefinitionIdParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Int32[] Id - { - get { return _ids; } - - set { _ids = value; } - } - - private Int32[] _ids; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = AddJobTriggerCommand.JobDefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return _names; } - - set { _names = value; } - } - - private string[] _names; - - /// - /// ScheduledJobDefinition. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = AddJobTriggerCommand.JobDefinitionParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobDefinition[] InputObject - { - get { return _definitions; } - - set { _definitions = value; } - } - - private ScheduledJobDefinition[] _definitions; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case JobDefinitionParameterSet: - AddToJobDefinition(_definitions); - break; - - case JobDefinitionIdParameterSet: - AddToJobDefinition(GetJobDefinitionsById(_ids)); - break; - - case JobDefinitionNameParameterSet: - AddToJobDefinition(GetJobDefinitionsByName(_names)); - break; - } - } - - #endregion - - #region Private Methods - - private void AddToJobDefinition(IEnumerable jobDefinitions) - { - foreach (ScheduledJobDefinition definition in jobDefinitions) - { - try - { - definition.AddTriggers(_triggers, true); - } - catch (ScheduledJobException e) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantAddJobTriggersToDefinition, definition.Name); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "CantAddJobTriggersToScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); - WriteError(errorRecord); - } - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs deleted file mode 100644 index d76b1829d42..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinition.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet disables the specified ScheduledJobDefinition. - /// - [Cmdlet(VerbsLifecycle.Disable, "ScheduledJob", SupportsShouldProcess = true, DefaultParameterSetName = DisableScheduledJobDefinitionBase.DefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223927")] - [OutputType(typeof(ScheduledJobDefinition))] - public sealed class DisableScheduledJobCommand : DisableScheduledJobDefinitionBase - { - #region Properties - - /// - /// Returns true if scheduled job definition should be enabled, - /// false otherwise. - /// - protected override bool Enabled - { - get { return false; } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs deleted file mode 100644 index d06020ed3d6..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobDefinitionBase.cs +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// Base class for the DisableScheduledJobCommand, EnableScheduledJobCommand cmdlets. - /// - public abstract class DisableScheduledJobDefinitionBase : ScheduleJobCmdletBase - { - #region Parameters - - /// - /// DefinitionIdParameterSet. - /// - protected const string DefinitionIdParameterSet = "DefinitionId"; - - /// - /// DefinitionNameParameterSet. - /// - protected const string DefinitionNameParameterSet = "DefinitionName"; - - /// - /// DefinitionParameterSet. - /// - protected const string DefinitionParameterSet = "Definition"; - - /// - /// ScheduledJobDefinition. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = DisableScheduledJobDefinitionBase.DefinitionParameterSet)] - [ValidateNotNull] - public ScheduledJobDefinition InputObject - { - get { return _definition; } - - set { _definition = value; } - } - - private ScheduledJobDefinition _definition; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = DisableScheduledJobDefinitionBase.DefinitionIdParameterSet)] - public Int32 Id - { - get { return _definitionId; } - - set { _definitionId = value; } - } - - private Int32 _definitionId; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = DisableScheduledJobDefinitionBase.DefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - public string Name - { - get { return _definitionName; } - - set { _definitionName = value; } - } - - private string _definitionName; - - /// - /// Pass through ScheduledJobDefinition object. - /// - [Parameter(ParameterSetName = DisableScheduledJobDefinitionBase.DefinitionParameterSet)] - [Parameter(ParameterSetName = DisableScheduledJobDefinitionBase.DefinitionIdParameterSet)] - [Parameter(ParameterSetName = DisableScheduledJobDefinitionBase.DefinitionNameParameterSet)] - public SwitchParameter PassThru - { - get { return _passThru; } - - set { _passThru = value; } - } - - private SwitchParameter _passThru; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - ScheduledJobDefinition definition = null; - - switch (ParameterSetName) - { - case DefinitionParameterSet: - definition = _definition; - break; - - case DefinitionIdParameterSet: - definition = GetJobDefinitionById(_definitionId); - break; - - case DefinitionNameParameterSet: - definition = GetJobDefinitionByName(_definitionName); - break; - } - - string verbName = Enabled ? VerbsLifecycle.Enable : VerbsLifecycle.Disable; - - if (definition != null && - ShouldProcess(definition.Name, verbName)) - { - try - { - definition.SetEnabled(Enabled, true); - } - catch (ScheduledJobException e) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSetEnableOnJobDefinition, definition.Name); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "CantSetEnableOnScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); - WriteError(errorRecord); - } - - if (_passThru) - { - WriteObject(definition); - } - } - } - - #endregion - - #region Properties - - /// - /// Returns true if scheduled job definition should be enabled, - /// false otherwise. - /// - protected abstract bool Enabled - { - get; - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs deleted file mode 100644 index 02e37c0acfb..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/DisableJobTrigger.cs +++ /dev/null @@ -1,35 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet enables triggers on a ScheduledJobDefinition object. - /// - [Cmdlet(VerbsLifecycle.Disable, "JobTrigger", SupportsShouldProcess = true, DefaultParameterSetName = DisableJobTriggerCommand.EnabledParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223918")] - public sealed class DisableJobTriggerCommand : EnableDisableScheduledJobCmdletBase - { - #region Enabled Implementation - - /// - /// Property to determine if trigger should be enabled or disabled. - /// - internal override bool Enabled - { - get { return false; } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs deleted file mode 100644 index c00626e6d64..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableDisableCmdletBase.cs +++ /dev/null @@ -1,96 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// Base class for DisableJobTrigger, EnableJobTrigger cmdlets. - /// - public abstract class EnableDisableScheduledJobCmdletBase : ScheduleJobCmdletBase - { - #region Parameters - - /// - /// JobDefinition parameter set. - /// - protected const string EnabledParameterSet = "JobEnabled"; - - /// - /// ScheduledJobTrigger objects to set properties on. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = EnableDisableScheduledJobCmdletBase.EnabledParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobTrigger[] InputObject - { - get { return _triggers; } - - set { _triggers = value; } - } - - /// - /// Pass through for scheduledjobtrigger object. - /// - [Parameter(ParameterSetName = EnableDisableScheduledJobCmdletBase.EnabledParameterSet)] - public SwitchParameter PassThru - { - get { return _passThru; } - - set { _passThru = value; } - } - - private SwitchParameter _passThru; - - private ScheduledJobTrigger[] _triggers; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - // Update each trigger with the current enabled state. - foreach (ScheduledJobTrigger trigger in _triggers) - { - trigger.Enabled = Enabled; - if (trigger.JobDefinition != null) - { - trigger.UpdateJobDefinition(); - } - - if (_passThru) - { - WriteObject(trigger); - } - } - } - - #endregion - - #region Internal Properties - - /// - /// Property to determine if trigger should be enabled or disabled. - /// - internal abstract bool Enabled - { - get; - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs deleted file mode 100644 index 6f236ea57af..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobDefinition.cs +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet enables the specified ScheduledJobDefinition. - /// - [Cmdlet(VerbsLifecycle.Enable, "ScheduledJob", SupportsShouldProcess = true, DefaultParameterSetName = DisableScheduledJobDefinitionBase.DefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223926")] - [OutputType(typeof(ScheduledJobDefinition))] - public sealed class EnableScheduledJobCommand : DisableScheduledJobDefinitionBase - { - #region Properties - - /// - /// Returns true if scheduled job definition should be enabled, - /// false otherwise. - /// - protected override bool Enabled - { - get { return true; } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs deleted file mode 100644 index 955dde31dfe..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs +++ /dev/null @@ -1,35 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet disables triggers on a ScheduledJobDefinition object. - /// - [Cmdlet(VerbsLifecycle.Enable, "JobTrigger", SupportsShouldProcess = true, DefaultParameterSetName = EnableJobTriggerCommand.EnabledParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223917")] - public sealed class EnableJobTriggerCommand : EnableDisableScheduledJobCmdletBase - { - #region Enabled Implementation - - /// - /// Property to determine if trigger should be enabled or disabled. - /// - internal override bool Enabled - { - get { return true; } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs deleted file mode 100644 index 772027f4fa5..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobDefinition.cs +++ /dev/null @@ -1,100 +0,0 @@ -// 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.ScheduledJob -{ - /// - /// This cmdlet gets scheduled job definition objects from the local repository. - /// - [Cmdlet(VerbsCommon.Get, "ScheduledJob", DefaultParameterSetName = GetScheduledJobCommand.DefinitionIdParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223923")] - [OutputType(typeof(ScheduledJobDefinition))] - public sealed class GetScheduledJobCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string DefinitionIdParameterSet = "DefinitionId"; - private const string DefinitionNameParameterSet = "DefinitionName"; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, - ParameterSetName = GetScheduledJobCommand.DefinitionIdParameterSet)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Int32[] Id - { - get { return _definitionIds; } - - set { _definitionIds = value; } - } - - private Int32[] _definitionIds; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = GetScheduledJobCommand.DefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return _definitionNames; } - - set { _definitionNames = value; } - } - - private string[] _definitionNames; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case DefinitionIdParameterSet: - if (_definitionIds == null) - { - FindAllJobDefinitions( - (definition) => - { - WriteObject(definition); - }); - } - else - { - FindJobDefinitionsById( - _definitionIds, - (definition) => - { - WriteObject(definition); - }); - } - - break; - - case DefinitionNameParameterSet: - FindJobDefinitionsByName( - _definitionNames, - (definition) => - { - WriteObject(definition); - }); - break; - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs deleted file mode 100644 index 0218395f3a1..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetJobTrigger.cs +++ /dev/null @@ -1,147 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet gets ScheduledJobTriggers for the specified ScheduledJobDefinition object. - /// - [Cmdlet(VerbsCommon.Get, "JobTrigger", DefaultParameterSetName = GetJobTriggerCommand.JobDefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223915")] - [OutputType(typeof(ScheduledJobTrigger))] - public sealed class GetJobTriggerCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string JobDefinitionParameterSet = "JobDefinition"; - private const string JobDefinitionIdParameterSet = "JobDefinitionId"; - private const string JobDefinitionNameParameterSet = "JobDefinitionName"; - - /// - /// Trigger number to get. - /// - [Parameter(Position = 1, - ParameterSetName = GetJobTriggerCommand.JobDefinitionParameterSet)] - [Parameter(Position = 1, - ParameterSetName = GetJobTriggerCommand.JobDefinitionIdParameterSet)] - [Parameter(Position = 1, - ParameterSetName = GetJobTriggerCommand.JobDefinitionNameParameterSet)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Int32[] TriggerId - { - get { return _triggerIds; } - - set { _triggerIds = value; } - } - - private Int32[] _triggerIds; - - /// - /// ScheduledJobDefinition. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = GetJobTriggerCommand.JobDefinitionParameterSet)] - [ValidateNotNull] - public ScheduledJobDefinition InputObject - { - get { return _definition; } - - set { _definition = value; } - } - - private ScheduledJobDefinition _definition; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = GetJobTriggerCommand.JobDefinitionIdParameterSet)] - public Int32 Id - { - get { return _definitionId; } - - set { _definitionId = value; } - } - - private Int32 _definitionId; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = GetJobTriggerCommand.JobDefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - public string Name - { - get { return _name; } - - set { _name = value; } - } - - private string _name; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case JobDefinitionParameterSet: - WriteTriggers(_definition); - break; - - case JobDefinitionIdParameterSet: - WriteTriggers(GetJobDefinitionById(_definitionId)); - break; - - case JobDefinitionNameParameterSet: - WriteTriggers(GetJobDefinitionByName(_name)); - break; - } - } - - #endregion - - #region Private Methods - - private void WriteTriggers(ScheduledJobDefinition definition) - { - if (definition == null) - { - return; - } - - List notFoundIds; - List triggers = definition.GetTriggers(_triggerIds, out notFoundIds); - - // Write found trigger objects. - foreach (ScheduledJobTrigger trigger in triggers) - { - WriteObject(trigger); - } - - // Report any triggers that were not found. - foreach (Int32 notFoundId in notFoundIds) - { - WriteTriggerNotFoundError(notFoundId, definition.Name, definition); - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs deleted file mode 100644 index 4de3131b223..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/GetScheduledJobOption.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet gets scheduled job option object from a provided ScheduledJobDefinition object. - /// - [Cmdlet(VerbsCommon.Get, "ScheduledJobOption", DefaultParameterSetName = GetScheduledJobOptionCommand.JobDefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223920")] - [OutputType(typeof(ScheduledJobOptions))] - public sealed class GetScheduledJobOptionCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string JobDefinitionParameterSet = "JobDefinition"; - private const string JobDefinitionIdParameterSet = "JobDefinitionId"; - private const string JobDefinitionNameParameterSet = "JobDefinitionName"; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = GetScheduledJobOptionCommand.JobDefinitionIdParameterSet)] - public Int32 Id - { - get { return _id; } - - set { _id = value; } - } - - private Int32 _id; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = true, - ParameterSetName = GetScheduledJobOptionCommand.JobDefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - public string Name - { - get { return _name; } - - set { _name = value; } - } - - private string _name; - - /// - /// ScheduledJobDefinition. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = GetScheduledJobOptionCommand.JobDefinitionParameterSet)] - [ValidateNotNull] - public ScheduledJobDefinition InputObject - { - get { return _definition; } - - set { _definition = value; } - } - - private ScheduledJobDefinition _definition; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - // Get ScheduledJobDefinition object. - ScheduledJobDefinition definition = null; - switch (ParameterSetName) - { - case JobDefinitionParameterSet: - definition = _definition; - break; - - case JobDefinitionIdParameterSet: - definition = GetJobDefinitionById(_id); - break; - - case JobDefinitionNameParameterSet: - definition = GetJobDefinitionByName(_name); - break; - } - - // Return options from the definition object. - if (definition != null) - { - WriteObject(definition.Options); - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs deleted file mode 100644 index 99ce575bec3..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/NewJobTrigger.cs +++ /dev/null @@ -1,360 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet creates a new scheduled job trigger based on the provided - /// parameter values. - /// - [Cmdlet(VerbsCommon.New, "JobTrigger", DefaultParameterSetName = NewJobTriggerCommand.OnceParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223912")] - [OutputType(typeof(ScheduledJobTrigger))] - public sealed class NewJobTriggerCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string AtLogonParameterSet = "AtLogon"; - private const string AtStartupParameterSet = "AtStartup"; - private const string OnceParameterSet = "Once"; - private const string DailyParameterSet = "Daily"; - private const string WeeklyParameterSet = "Weekly"; - - /// - /// Daily interval for trigger. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.DailyParameterSet)] - public Int32 DaysInterval - { - get { return _daysInterval; } - - set { _daysInterval = value; } - } - - private Int32 _daysInterval = 1; - - /// - /// Weekly interval for trigger. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.WeeklyParameterSet)] - public Int32 WeeksInterval - { - get { return _weeksInterval; } - - set { _weeksInterval = value; } - } - - private Int32 _weeksInterval = 1; - - /// - /// Random delay for trigger. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.AtLogonParameterSet)] - [Parameter(ParameterSetName = NewJobTriggerCommand.AtStartupParameterSet)] - [Parameter(ParameterSetName = NewJobTriggerCommand.OnceParameterSet)] - [Parameter(ParameterSetName = NewJobTriggerCommand.DailyParameterSet)] - [Parameter(ParameterSetName = NewJobTriggerCommand.WeeklyParameterSet)] - public TimeSpan RandomDelay - { - get { return _randomDelay; } - - set { _randomDelay = value; } - } - - private TimeSpan _randomDelay; - - /// - /// Job start date/time for trigger. - /// - [Parameter(Mandatory = true, - ParameterSetName = NewJobTriggerCommand.OnceParameterSet)] - [Parameter(Mandatory = true, - ParameterSetName = NewJobTriggerCommand.DailyParameterSet)] - [Parameter(Mandatory = true, - ParameterSetName = NewJobTriggerCommand.WeeklyParameterSet)] - public DateTime At - { - get { return _atTime; } - - set { _atTime = value; } - } - - private DateTime _atTime; - - /// - /// User name for AtLogon trigger. User name is used to determine which user - /// log on causes the trigger to activate. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.AtLogonParameterSet)] - [ValidateNotNullOrEmpty] - public string User - { - get { return _user; } - - set { _user = value; } - } - - private string _user; - - /// - /// Days of week for trigger applies only to the Weekly parameter set. - /// Specifies which day(s) of the week the weekly trigger is activated. - /// - [Parameter(Mandatory = true, ParameterSetName = NewJobTriggerCommand.WeeklyParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public DayOfWeek[] DaysOfWeek - { - get { return _daysOfWeek; } - - set { _daysOfWeek = value; } - } - - private DayOfWeek[] _daysOfWeek; - - /// - /// Switch to specify an AtStartup trigger. - /// - [Parameter(Mandatory = true, Position = 0, - ParameterSetName = NewJobTriggerCommand.AtStartupParameterSet)] - public SwitchParameter AtStartup - { - get { return _atStartup; } - - set { _atStartup = value; } - } - - private SwitchParameter _atStartup; - - /// - /// Switch to specify an AtLogon trigger. - /// - [Parameter(Mandatory = true, Position = 0, - ParameterSetName = NewJobTriggerCommand.AtLogonParameterSet)] - public SwitchParameter AtLogOn - { - get { return _atLogon; } - - set { _atLogon = value; } - } - - private SwitchParameter _atLogon; - - /// - /// Switch to specify a Once (one time) trigger. - /// - [Parameter(Mandatory = true, Position = 0, - ParameterSetName = NewJobTriggerCommand.OnceParameterSet)] - public SwitchParameter Once - { - get { return _once; } - - set { _once = value; } - } - - private SwitchParameter _once; - - /// - /// Repetition interval of a one time trigger. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.OnceParameterSet)] - public TimeSpan RepetitionInterval - { - get { return _repInterval; } - - set { _repInterval = value; } - } - - private TimeSpan _repInterval; - - /// - /// Repetition duration of a one time trigger. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.OnceParameterSet)] - public TimeSpan RepetitionDuration - { - get { return _repDuration; } - - set { _repDuration = value; } - } - - private TimeSpan _repDuration; - - /// - /// Repetition interval repeats indefinitely. - /// - [Parameter(ParameterSetName = NewJobTriggerCommand.OnceParameterSet)] - public SwitchParameter RepeatIndefinitely - { - get { return _repRepeatIndefinitely; } - - set { _repRepeatIndefinitely = value; } - } - - private SwitchParameter _repRepeatIndefinitely; - - /// - /// Switch to specify a Daily trigger. - /// - [Parameter(Mandatory = true, Position = 0, - ParameterSetName = NewJobTriggerCommand.DailyParameterSet)] - public SwitchParameter Daily - { - get { return _daily; } - - set { _daily = value; } - } - - private SwitchParameter _daily; - - /// - /// Switch to specify a Weekly trigger. - /// - [Parameter(Mandatory = true, Position = 0, - ParameterSetName = NewJobTriggerCommand.WeeklyParameterSet)] - public SwitchParameter Weekly - { - get { return _weekly; } - - set { _weekly = value; } - } - - private SwitchParameter _weekly; - - #endregion - - #region Cmdlet Overrides - - /// - /// Do begin processing. - /// - protected override void BeginProcessing() - { - base.BeginProcessing(); - - // Validate parameters. - if (_daysInterval < 1) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidDaysIntervalParam); - } - - if (_weeksInterval < 1) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidWeeksIntervalParam); - } - } - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case AtLogonParameterSet: - CreateAtLogonTrigger(); - break; - - case AtStartupParameterSet: - CreateAtStartupTrigger(); - break; - - case OnceParameterSet: - CreateOnceTrigger(); - break; - - case DailyParameterSet: - CreateDailyTrigger(); - break; - - case WeeklyParameterSet: - CreateWeeklyTrigger(); - break; - } - } - - #endregion - - #region Private Methods - - private void CreateAtLogonTrigger() - { - WriteObject(ScheduledJobTrigger.CreateAtLogOnTrigger(_user, _randomDelay, 0, true)); - } - - private void CreateAtStartupTrigger() - { - WriteObject(ScheduledJobTrigger.CreateAtStartupTrigger(_randomDelay, 0, true)); - } - - private void CreateOnceTrigger() - { - TimeSpan? repInterval = null; - TimeSpan? repDuration = null; - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || - MyInvocation.BoundParameters.ContainsKey(nameof(RepeatIndefinitely))) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepeatIndefinitely))) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration))) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepeatIndefinitelyParams); - } - - if (!MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval))) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionRepeatParams); - } - - _repDuration = TimeSpan.MaxValue; - } - else if (!MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || !MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration))) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParams); - } - - if (_repInterval < TimeSpan.Zero || _repDuration < TimeSpan.Zero) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParamValues); - } - - if (_repInterval < TimeSpan.FromMinutes(1)) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionIntervalValue); - } - - if (_repInterval > _repDuration) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionInterval); - } - - repInterval = _repInterval; - repDuration = _repDuration; - } - - WriteObject(ScheduledJobTrigger.CreateOnceTrigger(_atTime, _randomDelay, repInterval, repDuration, 0, true)); - } - - private void CreateDailyTrigger() - { - WriteObject(ScheduledJobTrigger.CreateDailyTrigger(_atTime, _daysInterval, _randomDelay, 0, true)); - } - - private void CreateWeeklyTrigger() - { - WriteObject(ScheduledJobTrigger.CreateWeeklyTrigger(_atTime, _weeksInterval, _daysOfWeek, _randomDelay, 0, true)); - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs deleted file mode 100644 index 09eab549426..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/NewScheduledJobOption.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet creates a new scheduled job option object based on the provided - /// parameter values. - /// - [Cmdlet(VerbsCommon.New, "ScheduledJobOption", DefaultParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223919")] - [OutputType(typeof(ScheduledJobOptions))] - public sealed class NewScheduledJobOptionCommand : ScheduledJobOptionCmdletBase - { - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - WriteObject(new ScheduledJobOptions( - StartIfOnBattery, - !ContinueIfGoingOnBattery, - WakeToRun, - !StartIfIdle, - StopIfGoingOffIdle, - RestartOnIdleResume, - IdleDuration, - IdleTimeout, - !HideInTaskScheduler, - RunElevated, - !RequireNetwork, - DoNotAllowDemandStart, - MultipleInstancePolicy)); - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs deleted file mode 100644 index e473f91dfd4..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RegisterJobDefinition.cs +++ /dev/null @@ -1,408 +0,0 @@ -// 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.Runspaces; - -using Microsoft.PowerShell.Commands; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet creates a new scheduled job definition object based on the provided - /// parameter values and registers it with the Task Scheduler. - /// - [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] - [Cmdlet(VerbsLifecycle.Register, "ScheduledJob", SupportsShouldProcess = true, DefaultParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223922")] - [OutputType(typeof(ScheduledJobDefinition))] - public sealed class RegisterScheduledJobCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string FilePathParameterSet = "FilePath"; - private const string ScriptBlockParameterSet = "ScriptBlock"; - - /// - /// File path for script to be run in job. - /// - [Parameter(Position = 1, Mandatory = true, - ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Alias("Path")] - [ValidateNotNullOrEmpty] - public string FilePath - { - get { return _filePath; } - - set { _filePath = value; } - } - - private string _filePath; - - /// - /// ScriptBlock containing script to run in job. - /// - [Parameter(Position = 1, Mandatory = true, - ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNull] - public ScriptBlock ScriptBlock - { - get { return _scriptBlock; } - - set { _scriptBlock = value; } - } - - private ScriptBlock _scriptBlock; - - /// - /// Name of scheduled job definition. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNullOrEmpty] - public string Name - { - get { return _name; } - - set { _name = value; } - } - - private string _name; - - /// - /// Triggers to define when job will run. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobTrigger[] Trigger - { - get { return _triggers; } - - set { _triggers = value; } - } - - private ScheduledJobTrigger[] _triggers; - - /// - /// Initialization script to run before the job starts. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNull] - public ScriptBlock InitializationScript - { - get { return _initializationScript; } - - set { _initializationScript = value; } - } - - private ScriptBlock _initializationScript; - - /// - /// Runs the job in a 32-bit PowerShell process. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - public SwitchParameter RunAs32 - { - get { return _runAs32; } - - set { _runAs32 = value; } - } - - private SwitchParameter _runAs32; - - /// - /// Credentials for job. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [Credential()] - public PSCredential Credential - { - get { return _credential; } - - set { _credential = value; } - } - - private PSCredential _credential; - - /// - /// Authentication mechanism to use for job. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - public AuthenticationMechanism Authentication - { - get { return _authenticationMechanism; } - - set { _authenticationMechanism = value; } - } - - private AuthenticationMechanism _authenticationMechanism; - - /// - /// Scheduling options for job. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNull] - public ScheduledJobOptions ScheduledJobOption - { - get { return _options; } - - set { _options = value; } - } - - private ScheduledJobOptions _options; - - /// - /// Argument list for FilePath parameter. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public object[] ArgumentList - { - get { return _arguments; } - - set { _arguments = value; } - } - - private object[] _arguments; - - /// - /// Maximum number of job results allowed in job store. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - public int MaxResultCount - { - get { return _executionHistoryLength; } - - set { _executionHistoryLength = value; } - } - - private int _executionHistoryLength; - - /// - /// Runs scheduled job immediately after successful registration. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - public SwitchParameter RunNow - { - get { return _runNow; } - - set { _runNow = value; } - } - - private SwitchParameter _runNow; - - /// - /// Runs scheduled job at the repetition interval indicated by the - /// TimeSpan value for an unending duration. - /// - [Parameter(ParameterSetName = RegisterScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = RegisterScheduledJobCommand.ScriptBlockParameterSet)] - public TimeSpan RunEvery - { - get { return _runEvery; } - - set { _runEvery = value; } - } - - private TimeSpan _runEvery; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - string targetString = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, Name); - if (!ShouldProcess(targetString, VerbsLifecycle.Register)) - { - return; - } - - ScheduledJobDefinition definition = null; - - switch (ParameterSetName) - { - case ScriptBlockParameterSet: - definition = CreateScriptBlockDefinition(); - break; - - case FilePathParameterSet: - definition = CreateFilePathDefinition(); - break; - } - - if (definition != null) - { - // Set the MaxCount value if available. - if (MyInvocation.BoundParameters.ContainsKey(nameof(MaxResultCount))) - { - if (MaxResultCount < 1) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidMaxResultCount); - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "InvalidMaxResultCountParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, null); - WriteError(errorRecord); - - return; - } - - definition.SetExecutionHistoryLength(MaxResultCount, false); - } - - try - { - // If RunEvery parameter is specified then create a job trigger for the definition that - // runs the job at the requested interval. - if (MyInvocation.BoundParameters.ContainsKey(nameof(RunEvery))) - { - AddRepetitionJobTriggerToDefinition( - definition, - RunEvery, - false); - } - - definition.Register(); - WriteObject(definition); - - if (_runNow) - { - definition.RunAsTask(); - } - } - catch (ScheduledJobException e) - { - // Check for access denied error. - if (e.InnerException != null && e.InnerException is System.UnauthorizedAccessException) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.UnauthorizedAccessError, definition.Name); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "UnauthorizedAccessToRegisterScheduledJobDefinition", ErrorCategory.PermissionDenied, definition); - WriteError(errorRecord); - } - else if (e.InnerException != null && e.InnerException is System.IO.DirectoryNotFoundException) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.DirectoryNotFoundError, definition.Name); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "DirectoryNotFoundWhenRegisteringScheduledJobDefinition", ErrorCategory.ObjectNotFound, definition); - WriteError(errorRecord); - } - else if (e.InnerException != null && e.InnerException is System.Runtime.Serialization.InvalidDataContractException) - { - string innerMsg = (!string.IsNullOrEmpty(e.InnerException.Message)) ? e.InnerException.Message : string.Empty; - string msg = StringUtil.Format(ScheduledJobErrorStrings.CannotSerializeData, definition.Name, innerMsg); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "CannotSerializeDataWhenRegisteringScheduledJobDefinition", ErrorCategory.InvalidData, definition); - WriteError(errorRecord); - } - else - { - // Create record around known exception type. - ErrorRecord errorRecord = new ErrorRecord(e, "CantRegisterScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); - WriteError(errorRecord); - } - } - } - } - - #endregion - - #region Private Methods - - private ScheduledJobDefinition CreateScriptBlockDefinition() - { - JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), ScriptBlock.ToString(), _name); - jobDefinition.ModuleName = ModuleName; - Dictionary parameterCollection = CreateCommonParameters(); - - // ScriptBlock, mandatory - parameterCollection.Add(ScheduledJobInvocationInfo.ScriptBlockParameter, ScriptBlock); - - JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameterCollection); - - ScheduledJobDefinition definition = new ScheduledJobDefinition(jobInvocationInfo, Trigger, - ScheduledJobOption, _credential); - - return definition; - } - - private ScheduledJobDefinition CreateFilePathDefinition() - { - JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), FilePath, _name); - jobDefinition.ModuleName = ModuleName; - Dictionary parameterCollection = CreateCommonParameters(); - - // FilePath, mandatory - if (!FilePath.EndsWith(".ps1", StringComparison.OrdinalIgnoreCase)) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePathFile); - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this); - WriteError(errorRecord); - - return null; - } - - Collection pathInfos = SessionState.Path.GetResolvedPSPathFromPSPath(FilePath); - if (pathInfos.Count != 1) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidFilePath); - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "InvalidFilePathParameterForRegisterScheduledJobDefinition", ErrorCategory.InvalidArgument, this); - WriteError(errorRecord); - - return null; - } - - parameterCollection.Add(ScheduledJobInvocationInfo.FilePathParameter, pathInfos[0].Path); - - JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameterCollection); - - ScheduledJobDefinition definition = new ScheduledJobDefinition(jobInvocationInfo, Trigger, - ScheduledJobOption, _credential); - - return definition; - } - - private Dictionary CreateCommonParameters() - { - Dictionary parameterCollection = new Dictionary(); - - parameterCollection.Add(ScheduledJobInvocationInfo.RunAs32Parameter, RunAs32.ToBool()); - parameterCollection.Add(ScheduledJobInvocationInfo.AuthenticationParameter, Authentication); - - if (InitializationScript != null) - { - parameterCollection.Add(ScheduledJobInvocationInfo.InitializationScriptParameter, InitializationScript); - } - - if (ArgumentList != null) - { - parameterCollection.Add(ScheduledJobInvocationInfo.ArgumentListParameter, ArgumentList); - } - - return parameterCollection; - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs deleted file mode 100644 index 81cdb8ecc35..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/RemoveJobTrigger.cs +++ /dev/null @@ -1,150 +0,0 @@ -// 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.Management.Automation; -using System.Management.Automation.Host; -using System.Management.Automation.Internal; -using System.Threading; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet removes ScheduledJobTriggers from ScheduledJobDefinition objects. - /// - [Cmdlet(VerbsCommon.Remove, "JobTrigger", DefaultParameterSetName = RemoveJobTriggerCommand.JobDefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223914")] - public sealed class RemoveJobTriggerCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string JobDefinitionParameterSet = "JobDefinition"; - private const string JobDefinitionIdParameterSet = "JobDefinitionId"; - private const string JobDefinitionNameParameterSet = "JobDefinitionName"; - - /// - /// Trigger number to remove. - /// - [Parameter(ParameterSetName = RemoveJobTriggerCommand.JobDefinitionParameterSet)] - [Parameter(ParameterSetName = RemoveJobTriggerCommand.JobDefinitionIdParameterSet)] - [Parameter(ParameterSetName = RemoveJobTriggerCommand.JobDefinitionNameParameterSet)] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Int32[] TriggerId - { - get { return _triggerIds; } - - set { _triggerIds = value; } - } - - private Int32[] _triggerIds; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = RemoveJobTriggerCommand.JobDefinitionIdParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Int32[] Id - { - get { return _definitionIds; } - - set { _definitionIds = value; } - } - - private Int32[] _definitionIds; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = RemoveJobTriggerCommand.JobDefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return _names; } - - set { _names = value; } - } - - private string[] _names; - - /// - /// ScheduledJobDefinition. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = RemoveJobTriggerCommand.JobDefinitionParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobDefinition[] InputObject - { - get { return _definitions; } - - set { _definitions = value; } - } - - private ScheduledJobDefinition[] _definitions; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case JobDefinitionParameterSet: - RemoveFromJobDefinition(_definitions); - break; - - case JobDefinitionIdParameterSet: - RemoveFromJobDefinition(GetJobDefinitionsById(_definitionIds)); - break; - - case JobDefinitionNameParameterSet: - RemoveFromJobDefinition(GetJobDefinitionsByName(_names)); - break; - } - } - - #endregion - - #region Private Methods - - private void RemoveFromJobDefinition(IEnumerable definitions) - { - foreach (ScheduledJobDefinition definition in definitions) - { - List notFoundIds = new List(); - try - { - notFoundIds = definition.RemoveTriggers(_triggerIds, true); - } - catch (ScheduledJobException e) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantRemoveTriggersFromDefinition, definition.Name); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "CantRemoveTriggersFromScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); - WriteError(errorRecord); - } - - // Report not found errors. - foreach (Int32 idNotFound in notFoundIds) - { - WriteTriggerNotFoundError(idNotFound, definition.Name, definition); - } - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs deleted file mode 100644 index e8112877019..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SchedJobCmdletBase.cs +++ /dev/null @@ -1,468 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// Base class for ScheduledJob cmdlets. - /// - public abstract class ScheduleJobCmdletBase : PSCmdlet - { - #region Cmdlet Strings - - /// - /// Scheduled job module name. - /// - protected const string ModuleName = "PSScheduledJob"; - - #endregion - - #region Utility Methods - - /// - /// Makes delegate callback call for each scheduledjob definition object found. - /// - /// Callback delegate for each discovered item. - internal void FindAllJobDefinitions( - Action itemFound) - { - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore((definition) => - { - if (ValidateJobDefinition(definition)) - { - itemFound(definition); - } - }); - HandleAllLoadErrors(errors); - } - - /// - /// Returns a single ScheduledJobDefinition object from the local - /// scheduled job definition repository corresponding to the provided id. - /// - /// Local repository scheduled job definition id. - /// Errors/warnings are written to host. - /// ScheduledJobDefinition object. - internal ScheduledJobDefinition GetJobDefinitionById( - Int32 id, - bool writeErrorsAndWarnings = true) - { - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore(null); - HandleAllLoadErrors(errors); - - foreach (var definition in ScheduledJobDefinition.Repository.Definitions) - { - if (definition.Id == id && - ValidateJobDefinition(definition)) - { - return definition; - } - } - - if (writeErrorsAndWarnings) - { - WriteDefinitionNotFoundByIdError(id); - } - - return null; - } - - /// - /// Returns an array of ScheduledJobDefinition objects from the local - /// scheduled job definition repository corresponding to the provided Ids. - /// - /// Local repository scheduled job definition ids. - /// Errors/warnings are written to host. - /// List of ScheduledJobDefinition objects. - internal List GetJobDefinitionsById( - Int32[] ids, - bool writeErrorsAndWarnings = true) - { - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore(null); - HandleAllLoadErrors(errors); - - List definitions = new List(); - HashSet findIds = new HashSet(ids); - foreach (var definition in ScheduledJobDefinition.Repository.Definitions) - { - if (findIds.Contains(definition.Id) && - ValidateJobDefinition(definition)) - { - definitions.Add(definition); - findIds.Remove(definition.Id); - } - } - - if (writeErrorsAndWarnings) - { - foreach (int id in findIds) - { - WriteDefinitionNotFoundByIdError(id); - } - } - - return definitions; - } - - /// - /// Makes delegate callback call for each scheduledjob definition object found. - /// - /// Local repository scheduled job definition ids. - /// Callback delegate for each discovered item. - /// Errors/warnings are written to host. - internal void FindJobDefinitionsById( - Int32[] ids, - Action itemFound, - bool writeErrorsAndWarnings = true) - { - HashSet findIds = new HashSet(ids); - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore((definition) => - { - if (findIds.Contains(definition.Id) && - ValidateJobDefinition(definition)) - { - itemFound(definition); - findIds.Remove(definition.Id); - } - }); - - HandleAllLoadErrors(errors); - - if (writeErrorsAndWarnings) - { - foreach (Int32 id in findIds) - { - WriteDefinitionNotFoundByIdError(id); - } - } - } - - /// - /// Returns an array of ScheduledJobDefinition objects from the local - /// scheduled job definition repository corresponding to the given name. - /// - /// Scheduled job definition name. - /// Errors/warnings are written to host. - /// ScheduledJobDefinition object. - internal ScheduledJobDefinition GetJobDefinitionByName( - string name, - bool writeErrorsAndWarnings = true) - { - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore(null); - - // Look for match. - WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); - foreach (var definition in ScheduledJobDefinition.Repository.Definitions) - { - if (namePattern.IsMatch(definition.Name) && - ValidateJobDefinition(definition)) - { - return definition; - } - } - - // Look for load error. - foreach (var error in errors) - { - if (namePattern.IsMatch(error.Key)) - { - HandleLoadError(error.Key, error.Value); - } - } - - if (writeErrorsAndWarnings) - { - WriteDefinitionNotFoundByNameError(name); - } - - return null; - } - - /// - /// Returns an array of ScheduledJobDefinition objects from the local - /// scheduled job definition repository corresponding to the given names. - /// - /// Scheduled job definition names. - /// Errors/warnings are written to host. - /// List of ScheduledJobDefinition objects. - internal List GetJobDefinitionsByName( - string[] names, - bool writeErrorsAndWarnings = true) - { - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore(null); - - List definitions = new List(); - foreach (string name in names) - { - WildcardPattern namePattern = new WildcardPattern(name, WildcardOptions.IgnoreCase); - - // Look for match. - bool nameFound = false; - foreach (var definition in ScheduledJobDefinition.Repository.Definitions) - { - if (namePattern.IsMatch(definition.Name) && - ValidateJobDefinition(definition)) - { - nameFound = true; - definitions.Add(definition); - } - } - - // Look for load error. - foreach (var error in errors) - { - if (namePattern.IsMatch(error.Key)) - { - HandleLoadError(error.Key, error.Value); - } - } - - if (!nameFound && writeErrorsAndWarnings) - { - WriteDefinitionNotFoundByNameError(name); - } - } - - return definitions; - } - - /// - /// Makes delegate callback call for each scheduledjob definition object found. - /// - /// Scheduled job definition names. - /// Callback delegate for each discovered item. - /// Errors/warnings are written to host. - internal void FindJobDefinitionsByName( - string[] names, - Action itemFound, - bool writeErrorsAndWarnings = true) - { - HashSet notFoundNames = new HashSet(names); - Dictionary patterns = new Dictionary(); - foreach (string name in names) - { - if (!patterns.ContainsKey(name)) - { - patterns.Add(name, new WildcardPattern(name, WildcardOptions.IgnoreCase)); - } - } - - Dictionary errors = ScheduledJobDefinition.RefreshRepositoryFromStore((definition) => - { - foreach (var item in patterns) - { - if (item.Value.IsMatch(definition.Name) && - ValidateJobDefinition(definition)) - { - itemFound(definition); - if (notFoundNames.Contains(item.Key)) - { - notFoundNames.Remove(item.Key); - } - } - } - }); - - // Look for load error. - foreach (var error in errors) - { - foreach (var item in patterns) - { - if (item.Value.IsMatch(error.Key)) - { - HandleLoadError(error.Key, error.Value); - } - } - } - - if (writeErrorsAndWarnings) - { - foreach (var name in notFoundNames) - { - WriteDefinitionNotFoundByNameError(name); - } - } - } - - /// - /// Writes a "Trigger not found" error to host. - /// - /// Trigger Id not found. - /// ScheduledJobDefinition name. - /// Error object. - internal void WriteTriggerNotFoundError( - Int32 notFoundId, - string definitionName, - object errorObject) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.TriggerNotFound, notFoundId, definitionName); - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "ScheduledJobTriggerNotFound", ErrorCategory.ObjectNotFound, errorObject); - WriteError(errorRecord); - } - - /// - /// Writes a "Definition not found for Id" error to host. - /// - /// Definition Id. - internal void WriteDefinitionNotFoundByIdError( - Int32 defId) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionNotFoundById, defId); - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "ScheduledJobDefinitionNotFoundById", ErrorCategory.ObjectNotFound, null); - WriteError(errorRecord); - } - - /// - /// Writes a "Definition not found for Name" error to host. - /// - /// Definition Name. - internal void WriteDefinitionNotFoundByNameError( - string name) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.DefinitionNotFoundByName, name); - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "ScheduledJobDefinitionNotFoundByName", ErrorCategory.ObjectNotFound, null); - WriteError(errorRecord); - } - - /// - /// Writes a "Load from job store" error to host. - /// - /// Scheduled job definition name. - /// Exception thrown during loading. - internal void WriteErrorLoadingDefinition(string name, Exception error) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantLoadDefinitionFromStore, name); - Exception reason = new RuntimeException(msg, error); - ErrorRecord errorRecord = new ErrorRecord(reason, "CantLoadScheduledJobDefinitionFromStore", ErrorCategory.InvalidOperation, null); - WriteError(errorRecord); - } - - /// - /// Creates a Once job trigger with provided repetition interval and an - /// infinite duration, and adds the trigger to the provided scheduled job - /// definition object. - /// - /// ScheduledJobDefinition. - /// Rep interval. - /// Save definition change. - internal static void AddRepetitionJobTriggerToDefinition( - ScheduledJobDefinition definition, - TimeSpan repInterval, - bool save) - { - if (definition == null) - { - throw new PSArgumentNullException("definition"); - } - - TimeSpan repDuration = TimeSpan.MaxValue; - - // Validate every interval value. - if (repInterval < TimeSpan.Zero || repDuration < TimeSpan.Zero) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionParamValues); - } - - if (repInterval < TimeSpan.FromMinutes(1)) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionIntervalValue); - } - - if (repInterval > repDuration) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidRepetitionInterval); - } - - // Create job trigger. - var trigger = ScheduledJobTrigger.CreateOnceTrigger( - DateTime.Now, - TimeSpan.Zero, - repInterval, - repDuration, - 0, - true); - - definition.AddTriggers(new ScheduledJobTrigger[] { trigger }, save); - } - - #endregion - - #region Private Methods - - private void HandleAllLoadErrors(Dictionary errors) - { - foreach (var error in errors) - { - HandleLoadError(error.Key, error.Value); - } - } - - private void HandleLoadError(string name, Exception e) - { - if (e is System.IO.IOException || - e is System.Xml.XmlException || - e is System.TypeInitializationException || - e is System.Runtime.Serialization.SerializationException || - e is System.ArgumentNullException) - { - // Remove the corrupted scheduled job definition and - // notify user with error message. - ScheduledJobDefinition.RemoveDefinition(name); - WriteErrorLoadingDefinition(name, e); - } - } - - private void ValidateJobDefinitions() - { - foreach (var definition in ScheduledJobDefinition.Repository.Definitions) - { - ValidateJobDefinition(definition); - } - } - - /// - /// Validates the job definition object retrieved from store by syncing - /// its data with the corresponding Task Scheduler task. If no task - /// is found then validation fails. - /// - /// - /// - private bool ValidateJobDefinition(ScheduledJobDefinition definition) - { - Exception ex = null; - try - { - definition.SyncWithWTS(); - } - catch (System.IO.DirectoryNotFoundException e) - { - ex = e; - } - catch (System.IO.FileNotFoundException e) - { - ex = e; - } - catch (System.ArgumentNullException e) - { - ex = e; - } - - if (ex != null) - { - WriteErrorLoadingDefinition(definition.Name, ex); - } - - return (ex == null); - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs deleted file mode 100644 index cd70dc0a8f1..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/ScheduledJobOptionCmdletBase.cs +++ /dev/null @@ -1,219 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// Base class for NewScheduledJobOption, SetScheduledJobOption cmdlets. - /// - public abstract class ScheduledJobOptionCmdletBase : ScheduleJobCmdletBase - { - #region Parameters - - /// - /// Options parameter set name. - /// - protected const string OptionsParameterSet = "Options"; - - /// - /// Scheduled job task is run with elevated privileges when this switch is selected. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter RunElevated - { - get { return _runElevated; } - - set { _runElevated = value; } - } - - private SwitchParameter _runElevated = false; - - /// - /// Scheduled job task is hidden in Windows Task Scheduler when true. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter HideInTaskScheduler - { - get { return _hideInTaskScheduler; } - - set { _hideInTaskScheduler = value; } - } - - private SwitchParameter _hideInTaskScheduler = false; - - /// - /// Scheduled job task will be restarted when machine becomes idle. This is applicable - /// only if the job was configured to stop when no longer idle. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter RestartOnIdleResume - { - get { return _restartOnIdleResume; } - - set { _restartOnIdleResume = value; } - } - - private SwitchParameter _restartOnIdleResume = false; - - /// - /// Provides task scheduler options for multiple running instances of the job. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public TaskMultipleInstancePolicy MultipleInstancePolicy - { - get { return _multipleInstancePolicy; } - - set { _multipleInstancePolicy = value; } - } - - private TaskMultipleInstancePolicy _multipleInstancePolicy = TaskMultipleInstancePolicy.IgnoreNew; - - /// - /// Prevents the job task from being started manually via Task Scheduler UI. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter DoNotAllowDemandStart - { - get { return _doNotAllowDemandStart; } - - set { _doNotAllowDemandStart = value; } - } - - private SwitchParameter _doNotAllowDemandStart = false; - - /// - /// Allows the job task to be run only when network connection available. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter RequireNetwork - { - get { return _requireNetwork; } - - set { _requireNetwork = value; } - } - - private SwitchParameter _requireNetwork = false; - - /// - /// Stops running job started by Task Scheduler if computer is no longer idle. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter StopIfGoingOffIdle - { - get { return _stopIfGoingOffIdle; } - - set { _stopIfGoingOffIdle = value; } - } - - private SwitchParameter _stopIfGoingOffIdle = false; - - /// - /// Will wake the computer to run the job if computer is in sleep mode when - /// trigger activates. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter WakeToRun - { - get { return _wakeToRun; } - - set { _wakeToRun = value; } - } - - private SwitchParameter _wakeToRun = false; - - /// - /// Continue running task job if computer going on battery. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter ContinueIfGoingOnBattery - { - get { return _continueIfGoingOnBattery; } - - set { _continueIfGoingOnBattery = value; } - } - - private SwitchParameter _continueIfGoingOnBattery = false; - - /// - /// Will start job task even if computer is running on battery power. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter StartIfOnBattery - { - get { return _startIfOnBattery; } - - set { _startIfOnBattery = value; } - } - - private SwitchParameter _startIfOnBattery = false; - - /// - /// Specifies how long Task Scheduler will wait for idle time after a trigger has - /// activated before giving up trying to run job during computer idle. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public TimeSpan IdleTimeout - { - get { return _idleTimeout; } - - set { _idleTimeout = value; } - } - - private TimeSpan _idleTimeout = new TimeSpan(1, 0, 0); - - /// - /// How long the computer needs to be idle before a triggered job task is started. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public TimeSpan IdleDuration - { - get { return _idleDuration; } - - set { _idleDuration = value; } - } - - private TimeSpan _idleDuration = new TimeSpan(0, 10, 0); - - /// - /// Will start job task if machine is idle. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter StartIfIdle - { - get { return _startIfIdle; } - - set { _startIfIdle = value; } - } - - private SwitchParameter _startIfIdle = false; - - #endregion - - #region Cmdlet Overrides - - /// - /// Begin processing. - /// - protected override void BeginProcessing() - { - // Validate parameters. - if (MyInvocation.BoundParameters.ContainsKey(nameof(IdleTimeout)) && - _idleTimeout < TimeSpan.Zero) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidIdleTimeout); - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(IdleDuration)) && - _idleDuration < TimeSpan.Zero) - { - throw new PSArgumentException(ScheduledJobErrorStrings.InvalidIdleDuration); - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs deleted file mode 100644 index 0d56f5640e4..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobDefinition.cs +++ /dev/null @@ -1,552 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Diagnostics.CodeAnalysis; -using System.Management.Automation; -using System.Management.Automation.Runspaces; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet updates a scheduled job definition object based on the provided - /// parameter values and saves changes to job store and Task Scheduler. - /// - [Cmdlet(VerbsCommon.Set, "ScheduledJob", DefaultParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223924")] - [OutputType(typeof(ScheduledJobDefinition))] - public sealed class SetScheduledJobCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string ExecutionParameterSet = "Execution"; - private const string ScriptBlockParameterSet = "ScriptBlock"; - private const string FilePathParameterSet = "FilePath"; - - /// - /// Name of scheduled job definition. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNullOrEmpty] - public string Name - { - get { return _name; } - - set { _name = value; } - } - - private string _name; - - /// - /// File path for script to be run in job. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [Alias("Path")] - [ValidateNotNullOrEmpty] - public string FilePath - { - get { return _filePath; } - - set { _filePath = value; } - } - - private string _filePath; - - /// - /// ScriptBlock containing script to run in job. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [ValidateNotNull] - public ScriptBlock ScriptBlock - { - get { return _scriptBlock; } - - set { _scriptBlock = value; } - } - - private ScriptBlock _scriptBlock; - - /// - /// Triggers to define when job will run. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobTrigger[] Trigger - { - get { return _triggers; } - - set { _triggers = value; } - } - - private ScheduledJobTrigger[] _triggers; - - /// - /// Initialization script to run before the job starts. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [ValidateNotNull] - public ScriptBlock InitializationScript - { - get { return _initializationScript; } - - set { _initializationScript = value; } - } - - private ScriptBlock _initializationScript; - - /// - /// Runs the job in a 32-bit PowerShell process. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - public SwitchParameter RunAs32 - { - get { return _runAs32; } - - set { _runAs32 = value; } - } - - private SwitchParameter _runAs32; - - /// - /// Credentials for job. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [Credential()] - public PSCredential Credential - { - get { return _credential; } - - set { _credential = value; } - } - - private PSCredential _credential; - - /// - /// Authentication mechanism to use for job. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - public AuthenticationMechanism Authentication - { - get { return _authenticationMechanism; } - - set { _authenticationMechanism = value; } - } - - private AuthenticationMechanism _authenticationMechanism; - - /// - /// Scheduling options for job. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [ValidateNotNull] - public ScheduledJobOptions ScheduledJobOption - { - get { return _options; } - - set { _options = value; } - } - - private ScheduledJobOptions _options; - - /// - /// Input for the job. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)] - [ValidateNotNull] - public ScheduledJobDefinition InputObject - { - get { return _definition; } - - set { _definition = value; } - } - - private ScheduledJobDefinition _definition; - - /// - /// ClearExecutionHistory. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)] - public SwitchParameter ClearExecutionHistory - { - get { return _clearExecutionHistory; } - - set { _clearExecutionHistory = value; } - } - - private SwitchParameter _clearExecutionHistory; - - /// - /// Maximum number of job results allowed in job store. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - public int MaxResultCount - { - get { return _executionHistoryLength; } - - set { _executionHistoryLength = value; } - } - - private int _executionHistoryLength; - - /// - /// Pass the ScheduledJobDefinition object through to output. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.ExecutionParameterSet)] - public SwitchParameter PassThru - { - get { return _passThru; } - - set { _passThru = value; } - } - - private SwitchParameter _passThru; - - /// - /// Argument list. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public object[] ArgumentList - { - get { return _arguments; } - - set { _arguments = value; } - } - - private object[] _arguments; - - /// - /// Runs scheduled job immediately after successfully setting job definition. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - public SwitchParameter RunNow - { - get { return _runNow; } - - set { _runNow = value; } - } - - private SwitchParameter _runNow; - - /// - /// Runs scheduled job at the repetition interval indicated by the - /// TimeSpan value for an unending duration. - /// - [Parameter(ParameterSetName = SetScheduledJobCommand.ScriptBlockParameterSet)] - [Parameter(ParameterSetName = SetScheduledJobCommand.FilePathParameterSet)] - public TimeSpan RunEvery - { - get { return _runEvery; } - - set { _runEvery = value; } - } - - private TimeSpan _runEvery; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - switch (ParameterSetName) - { - case ExecutionParameterSet: - UpdateExecutionDefinition(); - break; - - case ScriptBlockParameterSet: - case FilePathParameterSet: - UpdateDefinition(); - break; - } - - try - { - // If RunEvery parameter is specified then create a job trigger for the definition that - // runs the job at the requested interval. - bool addedTrigger = false; - if (MyInvocation.BoundParameters.ContainsKey(nameof(RunEvery))) - { - AddRepetitionJobTriggerToDefinition( - _definition, - RunEvery, - false); - - addedTrigger = true; - } - - if (Trigger != null || ScheduledJobOption != null || Credential != null || addedTrigger) - { - // Save definition to file and update WTS. - _definition.Save(); - } - else - { - // No WTS changes. Save definition to store only. - _definition.SaveToStore(); - } - - if (_runNow) - { - _definition.RunAsTask(); - } - } - catch (ScheduledJobException e) - { - ErrorRecord errorRecord; - - if (e.InnerException != null && - e.InnerException is System.UnauthorizedAccessException) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.NoAccessOnSetJobDefinition, _definition.Name); - errorRecord = new ErrorRecord(new RuntimeException(msg, e), - "NoAccessFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition); - } - else if (e.InnerException != null && - e.InnerException is System.IO.IOException) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.IOFailureOnSetJobDefinition, _definition.Name); - errorRecord = new ErrorRecord(new RuntimeException(msg, e), - "IOFailureOnSetJobDefinition", ErrorCategory.InvalidOperation, _definition); - } - else - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantSetJobDefinition, _definition.Name); - errorRecord = new ErrorRecord(new RuntimeException(msg, e), - "CantSetPropertiesToScheduledJobDefinition", ErrorCategory.InvalidOperation, _definition); - } - - WriteError(errorRecord); - } - - if (_passThru) - { - WriteObject(_definition); - } - } - - #endregion - - #region Private Methods - - private void UpdateExecutionDefinition() - { - if (_clearExecutionHistory) - { - _definition.ClearExecutionHistory(); - } - } - - private void UpdateDefinition() - { - if (_name != null && - string.Compare(_name, _definition.Name, StringComparison.OrdinalIgnoreCase) != 0) - { - _definition.RenameAndSave(_name); - } - - UpdateJobInvocationInfo(); - - if (MyInvocation.BoundParameters.ContainsKey(nameof(MaxResultCount))) - { - _definition.SetExecutionHistoryLength(MaxResultCount, false); - } - - if (Credential != null) - { - _definition.Credential = Credential; - } - - if (Trigger != null) - { - _definition.SetTriggers(Trigger, false); - } - - if (ScheduledJobOption != null) - { - _definition.UpdateOptions(ScheduledJobOption, false); - } - } - - /// - /// Create new ScheduledJobInvocationInfo object with update information and - /// update the job definition object. - /// - private void UpdateJobInvocationInfo() - { - Dictionary parameters = UpdateParameters(); - string name = _definition.Name; - string command; - - if (ScriptBlock != null) - { - command = ScriptBlock.ToString(); - } - else if (FilePath != null) - { - command = FilePath; - } - else - { - command = _definition.InvocationInfo.Command; - } - - JobDefinition jobDefinition = new JobDefinition(typeof(ScheduledJobSourceAdapter), command, name); - jobDefinition.ModuleName = ModuleName; - JobInvocationInfo jobInvocationInfo = new ScheduledJobInvocationInfo(jobDefinition, parameters); - - _definition.UpdateJobInvocationInfo(jobInvocationInfo, false); - } - - /// - /// Creates a new parameter dictionary with update parameters. - /// - /// Updated parameters. - private Dictionary UpdateParameters() - { - Debug.Assert(_definition.InvocationInfo.Parameters.Count != 0, - "ScheduledJobDefinition must always have some job invocation parameters"); - Dictionary newParameters = new Dictionary(); - foreach (CommandParameter parameter in _definition.InvocationInfo.Parameters[0]) - { - newParameters.Add(parameter.Name, parameter.Value); - } - - // RunAs32 - if (MyInvocation.BoundParameters.ContainsKey(nameof(RunAs32))) - { - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.RunAs32Parameter)) - { - newParameters[ScheduledJobInvocationInfo.RunAs32Parameter] = RunAs32.ToBool(); - } - else - { - newParameters.Add(ScheduledJobInvocationInfo.RunAs32Parameter, RunAs32.ToBool()); - } - } - - // Authentication - if (MyInvocation.BoundParameters.ContainsKey(nameof(Authentication))) - { - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.AuthenticationParameter)) - { - newParameters[ScheduledJobInvocationInfo.AuthenticationParameter] = Authentication; - } - else - { - newParameters.Add(ScheduledJobInvocationInfo.AuthenticationParameter, Authentication); - } - } - - // InitializationScript - if (InitializationScript == null) - { - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.InitializationScriptParameter)) - { - newParameters.Remove(ScheduledJobInvocationInfo.InitializationScriptParameter); - } - } - else - { - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.InitializationScriptParameter)) - { - newParameters[ScheduledJobInvocationInfo.InitializationScriptParameter] = InitializationScript; - } - else - { - newParameters.Add(ScheduledJobInvocationInfo.InitializationScriptParameter, InitializationScript); - } - } - - // ScriptBlock - if (ScriptBlock != null) - { - // FilePath cannot also be specified. - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter)) - { - newParameters.Remove(ScheduledJobInvocationInfo.FilePathParameter); - } - - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter)) - { - newParameters[ScheduledJobInvocationInfo.ScriptBlockParameter] = ScriptBlock; - } - else - { - newParameters.Add(ScheduledJobInvocationInfo.ScriptBlockParameter, ScriptBlock); - } - } - - // FilePath - if (FilePath != null) - { - // ScriptBlock cannot also be specified. - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ScriptBlockParameter)) - { - newParameters.Remove(ScheduledJobInvocationInfo.ScriptBlockParameter); - } - - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.FilePathParameter)) - { - newParameters[ScheduledJobInvocationInfo.FilePathParameter] = FilePath; - } - else - { - newParameters.Add(ScheduledJobInvocationInfo.FilePathParameter, FilePath); - } - } - - // ArgumentList - if (ArgumentList == null) - { - // Clear existing argument list only if new scriptblock or script file path was specified - // (in this case old argument list is invalid). - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter) && - (ScriptBlock != null || FilePath != null)) - { - newParameters.Remove(ScheduledJobInvocationInfo.ArgumentListParameter); - } - } - else - { - if (newParameters.ContainsKey(ScheduledJobInvocationInfo.ArgumentListParameter)) - { - newParameters[ScheduledJobInvocationInfo.ArgumentListParameter] = ArgumentList; - } - else - { - newParameters.Add(ScheduledJobInvocationInfo.ArgumentListParameter, ArgumentList); - } - } - - return newParameters; - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs deleted file mode 100644 index 4eeab7fcc72..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetJobTrigger.cs +++ /dev/null @@ -1,945 +0,0 @@ -// 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.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet sets properties on a trigger for a ScheduledJobDefinition. - /// - [Cmdlet(VerbsCommon.Set, "JobTrigger", DefaultParameterSetName = SetJobTriggerCommand.DefaultParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223916")] - [OutputType(typeof(ScheduledJobTrigger))] - public sealed class SetJobTriggerCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string DefaultParameterSet = "DefaultParams"; - - /// - /// ScheduledJobTrigger objects to set properties on. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobTrigger[] InputObject - { - get { return _triggers; } - - set { _triggers = value; } - } - - private ScheduledJobTrigger[] _triggers; - - /// - /// Daily interval for trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public Int32 DaysInterval - { - get { return _daysInterval; } - - set { _daysInterval = value; } - } - - private Int32 _daysInterval = 1; - - /// - /// Weekly interval for trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public Int32 WeeksInterval - { - get { return _weeksInterval; } - - set { _weeksInterval = value; } - } - - private Int32 _weeksInterval = 1; - - /// - /// Random delay for trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public TimeSpan RandomDelay - { - get { return _randomDelay; } - - set { _randomDelay = value; } - } - - private TimeSpan _randomDelay; - - /// - /// Job start date/time for trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public DateTime At - { - get { return _atTime; } - - set { _atTime = value; } - } - - private DateTime _atTime; - - /// - /// User name for AtLogon trigger. The AtLogon parameter set will create a trigger - /// that activates after log on for the provided user name. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - [ValidateNotNullOrEmpty] - public string User - { - get { return _user; } - - set { _user = value; } - } - - private string _user; - - /// - /// Days of week for trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public DayOfWeek[] DaysOfWeek - { - get { return _daysOfWeek; } - - set { _daysOfWeek = value; } - } - - private DayOfWeek[] _daysOfWeek; - - /// - /// Switch to specify an AtStartup trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter AtStartup - { - get { return _atStartup; } - - set { _atStartup = value; } - } - - private SwitchParameter _atStartup; - - /// - /// Switch to specify an AtLogon trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter AtLogOn - { - get { return _atLogon; } - - set { _atLogon = value; } - } - - private SwitchParameter _atLogon; - - /// - /// Switch to specify an Once trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter Once - { - get { return _once; } - - set { _once = value; } - } - - private SwitchParameter _once; - - /// - /// Repetition interval of a one time trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public TimeSpan RepetitionInterval - { - get { return _repInterval; } - - set { _repInterval = value; } - } - - private TimeSpan _repInterval; - - /// - /// Repetition duration of a one time trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public TimeSpan RepetitionDuration - { - get { return _repDuration; } - - set { _repDuration = value; } - } - - private TimeSpan _repDuration; - - /// - /// Repetition interval repeats indefinitely. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter RepeatIndefinitely - { - get { return _repRepeatIndefinitely; } - - set { _repRepeatIndefinitely = value; } - } - - private SwitchParameter _repRepeatIndefinitely; - - /// - /// Switch to specify an Daily trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter Daily - { - get { return _daily; } - - set { _daily = value; } - } - - private SwitchParameter _daily; - - /// - /// Switch to specify an Weekly trigger. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter Weekly - { - get { return _weekly; } - - set { _weekly = value; } - } - - private SwitchParameter _weekly; - - /// - /// Pass through job trigger object. - /// - [Parameter(ParameterSetName = SetJobTriggerCommand.DefaultParameterSet)] - public SwitchParameter PassThru - { - get { return _passThru; } - - set { _passThru = value; } - } - - private SwitchParameter _passThru; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - // Validate the parameter set and write any errors. - TriggerFrequency newTriggerFrequency = TriggerFrequency.None; - if (!ValidateParameterSet(ref newTriggerFrequency)) - { - return; - } - - // Update each trigger object with the current parameter set. - // The associated scheduled job definition will also be updated. - foreach (ScheduledJobTrigger trigger in _triggers) - { - ScheduledJobTrigger originalTrigger = new ScheduledJobTrigger(trigger); - if (!UpdateTrigger(trigger, newTriggerFrequency)) - { - continue; - } - - ScheduledJobDefinition definition = trigger.JobDefinition; - if (definition != null) - { - bool jobUpdateFailed = false; - - try - { - trigger.UpdateJobDefinition(); - } - catch (ScheduledJobException e) - { - jobUpdateFailed = true; - - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantUpdateTriggerOnJobDef, definition.Name, trigger.Id); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "CantSetPropertiesOnJobTrigger", ErrorCategory.InvalidOperation, trigger); - WriteError(errorRecord); - } - - if (jobUpdateFailed) - { - // Restore trigger to original configuration. - originalTrigger.CopyTo(trigger); - } - } - - if (_passThru) - { - WriteObject(trigger); - } - } - } - - #endregion - - #region Private Methods - - private bool ValidateParameterSet(ref TriggerFrequency newTriggerFrequency) - { - // First see if a switch parameter was set. - List switchParamList = new List(); - if (MyInvocation.BoundParameters.ContainsKey(nameof(AtStartup))) - { - switchParamList.Add(TriggerFrequency.AtStartup); - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(AtLogon))) - { - switchParamList.Add(TriggerFrequency.AtLogon); - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(Once))) - { - switchParamList.Add(TriggerFrequency.Once); - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(Daily))) - { - switchParamList.Add(TriggerFrequency.Daily); - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(Weekly))) - { - switchParamList.Add(TriggerFrequency.Weekly); - } - - if (switchParamList.Count > 1) - { - WriteValidationError(ScheduledJobErrorStrings.ConflictingTypeParams); - return false; - } - - newTriggerFrequency = (switchParamList.Count == 1) ? switchParamList[0] : TriggerFrequency.None; - - // Validate parameters against the new trigger frequency value. - bool rtnValue = false; - switch (newTriggerFrequency) - { - case TriggerFrequency.None: - rtnValue = true; - break; - - case TriggerFrequency.AtStartup: - rtnValue = ValidateStartupParams(); - break; - - case TriggerFrequency.AtLogon: - rtnValue = ValidateLogonParams(); - break; - - case TriggerFrequency.Once: - rtnValue = ValidateOnceParams(); - break; - - case TriggerFrequency.Daily: - rtnValue = ValidateDailyParams(); - break; - - case TriggerFrequency.Weekly: - rtnValue = ValidateWeeklyParams(); - break; - - default: - Debug.Assert(false, "Invalid trigger frequency value."); - rtnValue = false; - break; - } - - return rtnValue; - } - - private bool ValidateStartupParams() - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerStartUpType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerStartUpType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidAtTime, ScheduledJobErrorStrings.TriggerStartUpType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerStartUpType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerStartUpType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || - MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerStartUpType); - WriteValidationError(msg); - return false; - } - - return true; - } - - private bool ValidateLogonParams() - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerLogonType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerLogonType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidAtTime, ScheduledJobErrorStrings.TriggerLogonType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerLogonType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || - MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerLogonType); - WriteValidationError(msg); - return false; - } - - return true; - } - - private bool ValidateOnceParams(ScheduledJobTrigger trigger = null) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerOnceType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerOnceType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerOnceType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerOnceType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) - { - _repDuration = TimeSpan.MaxValue; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || - MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) - { - // Validate Once trigger repetition parameters. - try - { - ScheduledJobTrigger.ValidateOnceRepetitionParams(_repInterval, _repDuration); - } - catch (PSArgumentException e) - { - WriteValidationError(e.Message); - return false; - } - } - - if (trigger != null) - { - if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingAtTime, ScheduledJobErrorStrings.TriggerOnceType); - WriteValidationError(msg); - return false; - } - } - - return true; - } - - private bool ValidateDailyParams(ScheduledJobTrigger trigger = null) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)) && - _daysInterval < 1) - { - WriteValidationError(ScheduledJobErrorStrings.InvalidDaysIntervalParam); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidWeeksInterval, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysOfWeek, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || - MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - - if (trigger != null) - { - if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingAtTime, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - } - - return true; - } - - private bool ValidateWeeklyParams(ScheduledJobTrigger trigger = null) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidDaysInterval, ScheduledJobErrorStrings.TriggerWeeklyType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)) && - _weeksInterval < 1) - { - WriteValidationError(ScheduledJobErrorStrings.InvalidWeeksIntervalParam); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidUser, ScheduledJobErrorStrings.TriggerWeeklyType); - WriteValidationError(msg); - return false; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) || MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) || - MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInfiniteDuration))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.InvalidSetTriggerRepetition, ScheduledJobErrorStrings.TriggerWeeklyType); - WriteValidationError(msg); - return false; - } - - if (trigger != null) - { - if (trigger.At == null && !MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingAtTime, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - - if ((trigger.DaysOfWeek == null || trigger.DaysOfWeek.Count == 0) && - !MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.MissingDaysOfWeek, ScheduledJobErrorStrings.TriggerDailyType); - WriteValidationError(msg); - return false; - } - } - - return true; - } - - private bool UpdateTrigger(ScheduledJobTrigger trigger, TriggerFrequency triggerFrequency) - { - if (triggerFrequency != TriggerFrequency.None) - { - // - // User has specified a specific trigger type. - // Parameters have been validated for this trigger type. - // - if (triggerFrequency != trigger.Frequency) - { - // Changing to a new trigger type. - return CreateTrigger(trigger, triggerFrequency); - } - else - { - // Modifying existing trigger type. - return ModifyTrigger(trigger, triggerFrequency); - } - } - else - { - // We are updating an existing trigger. Need to validate params - // against each trigger type we are updating. - return ModifyTrigger(trigger, trigger.Frequency, true); - } - } - - private bool CreateTrigger(ScheduledJobTrigger trigger, TriggerFrequency triggerFrequency) - { - switch (triggerFrequency) - { - case TriggerFrequency.AtStartup: - CreateAtStartupTrigger(trigger); - break; - - case TriggerFrequency.AtLogon: - CreateAtLogonTrigger(trigger); - break; - - case TriggerFrequency.Once: - if (trigger.Frequency != triggerFrequency && - !ValidateOnceParams(trigger)) - { - return false; - } - - CreateOnceTrigger(trigger); - break; - - case TriggerFrequency.Daily: - if (trigger.Frequency != triggerFrequency && - !ValidateDailyParams(trigger)) - { - return false; - } - - CreateDailyTrigger(trigger); - break; - - case TriggerFrequency.Weekly: - if (trigger.Frequency != triggerFrequency && - !ValidateWeeklyParams(trigger)) - { - return false; - } - - CreateWeeklyTrigger(trigger); - break; - } - - return true; - } - - private bool ModifyTrigger(ScheduledJobTrigger trigger, TriggerFrequency triggerFrequency, bool validate = false) - { - switch (triggerFrequency) - { - case TriggerFrequency.AtStartup: - if (validate && - !ValidateStartupParams()) - { - return false; - } - - ModifyStartupTrigger(trigger); - break; - - case TriggerFrequency.AtLogon: - if (validate && - !ValidateLogonParams()) - { - return false; - } - - ModifyLogonTrigger(trigger); - break; - - case TriggerFrequency.Once: - if (validate && - !ValidateOnceParams()) - { - return false; - } - - ModifyOnceTrigger(trigger); - break; - - case TriggerFrequency.Daily: - if (validate && - !ValidateDailyParams()) - { - return false; - } - - ModifyDailyTrigger(trigger); - break; - - case TriggerFrequency.Weekly: - if (validate && - !ValidateWeeklyParams()) - { - return false; - } - - ModifyWeeklyTrigger(trigger); - break; - } - - return true; - } - - private void ModifyStartupTrigger(ScheduledJobTrigger trigger) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay))) - { - trigger.RandomDelay = _randomDelay; - } - } - - private void ModifyLogonTrigger(ScheduledJobTrigger trigger) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay))) - { - trigger.RandomDelay = _randomDelay; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(User))) - { - trigger.User = string.IsNullOrEmpty(_user) ? ScheduledJobTrigger.AllUsers : _user; - } - } - - private void ModifyOnceTrigger(ScheduledJobTrigger trigger) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay))) - { - trigger.RandomDelay = _randomDelay; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval))) - { - trigger.RepetitionInterval = _repInterval; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration))) - { - trigger.RepetitionDuration = _repDuration; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - trigger.At = _atTime; - } - } - - private void ModifyDailyTrigger(ScheduledJobTrigger trigger) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay))) - { - trigger.RandomDelay = _randomDelay; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - trigger.At = _atTime; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval))) - { - trigger.Interval = _daysInterval; - } - } - - private void ModifyWeeklyTrigger(ScheduledJobTrigger trigger) - { - if (MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay))) - { - trigger.RandomDelay = _randomDelay; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(At))) - { - trigger.At = _atTime; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval))) - { - trigger.Interval = _weeksInterval; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek))) - { - trigger.DaysOfWeek = new List(_daysOfWeek); - } - } - - private void CreateAtLogonTrigger(ScheduledJobTrigger trigger) - { - bool enabled = trigger.Enabled; - int id = trigger.Id; - TimeSpan randomDelay = trigger.RandomDelay; - string user = string.IsNullOrEmpty(trigger.User) ? ScheduledJobTrigger.AllUsers : trigger.User; - - trigger.ClearProperties(); - trigger.Frequency = TriggerFrequency.AtLogon; - trigger.Enabled = enabled; - trigger.Id = id; - - trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay; - trigger.User = MyInvocation.BoundParameters.ContainsKey(nameof(User)) ? _user : user; - } - - private void CreateAtStartupTrigger(ScheduledJobTrigger trigger) - { - bool enabled = trigger.Enabled; - int id = trigger.Id; - TimeSpan randomDelay = trigger.RandomDelay; - - trigger.ClearProperties(); - trigger.Frequency = TriggerFrequency.AtStartup; - trigger.Enabled = enabled; - trigger.Id = id; - - trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay; - } - - private void CreateOnceTrigger(ScheduledJobTrigger trigger) - { - bool enabled = trigger.Enabled; - int id = trigger.Id; - TimeSpan randomDelay = trigger.RandomDelay; - DateTime? atTime = trigger.At; - TimeSpan? repInterval = trigger.RepetitionInterval; - TimeSpan? repDuration = trigger.RepetitionDuration; - - trigger.ClearProperties(); - trigger.Frequency = TriggerFrequency.Once; - trigger.Enabled = enabled; - trigger.Id = id; - - trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay; - trigger.At = MyInvocation.BoundParameters.ContainsKey(nameof(At)) ? _atTime : atTime; - trigger.RepetitionInterval = MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionInterval)) ? _repInterval : repInterval; - trigger.RepetitionDuration = MyInvocation.BoundParameters.ContainsKey(nameof(RepetitionDuration)) ? _repDuration : repDuration; - } - - private void CreateDailyTrigger(ScheduledJobTrigger trigger) - { - bool enabled = trigger.Enabled; - int id = trigger.Id; - TimeSpan randomDelay = trigger.RandomDelay; - DateTime? atTime = trigger.At; - int interval = trigger.Interval; - - trigger.ClearProperties(); - trigger.Frequency = TriggerFrequency.Daily; - trigger.Enabled = enabled; - trigger.Id = id; - - trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay; - trigger.At = MyInvocation.BoundParameters.ContainsKey(nameof(At)) ? _atTime : atTime; - trigger.Interval = MyInvocation.BoundParameters.ContainsKey(nameof(DaysInterval)) ? _daysInterval : interval; - } - - private void CreateWeeklyTrigger(ScheduledJobTrigger trigger) - { - bool enabled = trigger.Enabled; - int id = trigger.Id; - TimeSpan randomDelay = trigger.RandomDelay; - DateTime? atTime = trigger.At; - int interval = trigger.Interval; - List daysOfWeek = trigger.DaysOfWeek; - - trigger.ClearProperties(); - trigger.Frequency = TriggerFrequency.Weekly; - trigger.Enabled = enabled; - trigger.Id = id; - - trigger.RandomDelay = MyInvocation.BoundParameters.ContainsKey(nameof(RandomDelay)) ? _randomDelay : randomDelay; - trigger.At = MyInvocation.BoundParameters.ContainsKey(nameof(At)) ? _atTime : atTime; - trigger.Interval = MyInvocation.BoundParameters.ContainsKey(nameof(WeeksInterval)) ? _weeksInterval : interval; - trigger.DaysOfWeek = MyInvocation.BoundParameters.ContainsKey(nameof(DaysOfWeek)) ? new List(_daysOfWeek) : daysOfWeek; - } - - private void WriteValidationError(string msg) - { - Exception reason = new RuntimeException(msg); - ErrorRecord errorRecord = new ErrorRecord(reason, "SetJobTriggerParameterValidationError", ErrorCategory.InvalidArgument, null); - WriteError(errorRecord); - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs deleted file mode 100644 index bc1e07b1473..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/SetScheduledJobOption.cs +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.Management.Automation; - -namespace Microsoft.PowerShell.ScheduledJob -{ - /// - /// This cmdlet sets the provided scheduled job options to the provided ScheduledJobOptions objects. - /// - [Cmdlet(VerbsCommon.Set, "ScheduledJobOption", DefaultParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223921")] - [OutputType(typeof(ScheduledJobOptions))] - public class SetScheduledJobOptionCommand : ScheduledJobOptionCmdletBase - { - #region Parameters - - /// - /// ScheduledJobOptions object. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - [ValidateNotNull] - public ScheduledJobOptions InputObject - { - get { return _jobOptions; } - - set { _jobOptions = value; } - } - - private ScheduledJobOptions _jobOptions; - - /// - /// Pas the ScheduledJobOptions object through to output. - /// - [Parameter(ParameterSetName = ScheduledJobOptionCmdletBase.OptionsParameterSet)] - public SwitchParameter PassThru - { - get { return _passThru; } - - set { _passThru = value; } - } - - private SwitchParameter _passThru; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - // Update ScheduledJobOptions object with current parameters. - // Update switch parameters only if they were selected. - // Also update the ScheduledJobDefinition object associated with this options object. - if (MyInvocation.BoundParameters.ContainsKey(nameof(StartIfOnBattery))) - { - _jobOptions.StartIfOnBatteries = StartIfOnBattery; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(ContinueIfGoingOnBattery))) - { - _jobOptions.StopIfGoingOnBatteries = !ContinueIfGoingOnBattery; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(WakeToRun))) - { - _jobOptions.WakeToRun = WakeToRun; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(StartIfIdle))) - { - _jobOptions.StartIfNotIdle = !StartIfIdle; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(StopIfGoingOffIdle))) - { - _jobOptions.StopIfGoingOffIdle = StopIfGoingOffIdle; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RestartOnIdleResume))) - { - _jobOptions.RestartOnIdleResume = RestartOnIdleResume; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(HideInTaskScheduler))) - { - _jobOptions.ShowInTaskScheduler = !HideInTaskScheduler; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RunElevated))) - { - _jobOptions.RunElevated = RunElevated; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(RequireNetwork))) - { - _jobOptions.RunWithoutNetwork = !RequireNetwork; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(DoNotAllowDemandStart))) - { - _jobOptions.DoNotAllowDemandStart = DoNotAllowDemandStart; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(IdleDuration))) - { - _jobOptions.IdleDuration = IdleDuration; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(IdleTimeout))) - { - _jobOptions.IdleTimeout = IdleTimeout; - } - - if (MyInvocation.BoundParameters.ContainsKey(nameof(MultipleInstancePolicy))) - { - _jobOptions.MultipleInstancePolicy = MultipleInstancePolicy; - } - - // Update ScheduledJobDefinition with changes. - if (_jobOptions.JobDefinition != null) - { - _jobOptions.UpdateJobDefinition(); - } - - if (_passThru) - { - WriteObject(_jobOptions); - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs b/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs deleted file mode 100644 index c6c3885fb90..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/commands/UnregisterJobDefinition.cs +++ /dev/null @@ -1,157 +0,0 @@ -// 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.ScheduledJob -{ - /// - /// This cmdlet removes the specified ScheduledJobDefinition objects from the - /// Task Scheduler, job store, and local repository. - /// - [Cmdlet(VerbsLifecycle.Unregister, "ScheduledJob", SupportsShouldProcess = true, DefaultParameterSetName = UnregisterScheduledJobCommand.DefinitionParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223925")] - public sealed class UnregisterScheduledJobCommand : ScheduleJobCmdletBase - { - #region Parameters - - private const string DefinitionIdParameterSet = "DefinitionId"; - private const string DefinitionNameParameterSet = "DefinitionName"; - private const string DefinitionParameterSet = "Definition"; - - /// - /// ScheduledJobDefinition Id. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = UnregisterScheduledJobCommand.DefinitionIdParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Int32[] Id - { - get { return _definitionIds; } - - set { _definitionIds = value; } - } - - private Int32[] _definitionIds; - - /// - /// ScheduledJobDefinition Name. - /// - [Parameter(Position = 0, Mandatory = true, - ParameterSetName = UnregisterScheduledJobCommand.DefinitionNameParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public string[] Name - { - get { return _names; } - - set { _names = value; } - } - - private string[] _names; - - /// - /// ScheduledJobDefinition. - /// - [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, - ParameterSetName = UnregisterScheduledJobCommand.DefinitionParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public ScheduledJobDefinition[] InputObject - { - get { return _definitions; } - - set { _definitions = value; } - } - - private ScheduledJobDefinition[] _definitions; - - /// - /// When true this will stop any running instances of this job definition before - /// removing the definition. - /// - [Parameter(ParameterSetName = UnregisterScheduledJobCommand.DefinitionIdParameterSet)] - [Parameter(ParameterSetName = UnregisterScheduledJobCommand.DefinitionNameParameterSet)] - [Parameter(ParameterSetName = UnregisterScheduledJobCommand.DefinitionParameterSet)] - public SwitchParameter Force - { - get { return _force; } - - set { _force = value; } - } - - private SwitchParameter _force; - - #endregion - - #region Cmdlet Overrides - - /// - /// Process input. - /// - protected override void ProcessRecord() - { - List definitions = null; - switch (ParameterSetName) - { - case DefinitionParameterSet: - definitions = new List(_definitions); - break; - - case DefinitionNameParameterSet: - definitions = GetJobDefinitionsByName(_names); - break; - - case DefinitionIdParameterSet: - definitions = GetJobDefinitionsById(_definitionIds); - break; - } - - if (definitions != null) - { - foreach (ScheduledJobDefinition definition in definitions) - { - string targetString = StringUtil.Format(ScheduledJobErrorStrings.DefinitionWhatIf, definition.Name); - if (ShouldProcess(targetString, VerbsLifecycle.Unregister)) - { - // Removes the ScheduledJobDefinition from the job store, - // Task Scheduler, and disposes the object. - try - { - definition.Remove(_force); - } - catch (ScheduledJobException e) - { - string msg = StringUtil.Format(ScheduledJobErrorStrings.CantUnregisterDefinition, definition.Name); - Exception reason = new RuntimeException(msg, e); - ErrorRecord errorRecord = new ErrorRecord(reason, "CantUnregisterScheduledJobDefinition", ErrorCategory.InvalidOperation, definition); - WriteError(errorRecord); - } - } - } - } - - // Check for unknown definition names. - if ((_names != null && _names.Length > 0) && - (_definitions == null || _definitions.Length < _names.Length)) - { - // Make sure there is no PowerShell task in Task Scheduler with removed names. - // This covers the case where the scheduled job definition was manually removed from - // the job store but remains as a PowerShell task in Task Scheduler. - using (ScheduledJobWTS taskScheduler = new ScheduledJobWTS()) - { - foreach (string name in _names) - { - taskScheduler.RemoveTaskByName(name, true, true); - } - } - } - } - - #endregion - } -} diff --git a/src/Microsoft.PowerShell.ScheduledJob/resources/ScheduledJobErrorStrings.resx b/src/Microsoft.PowerShell.ScheduledJob/resources/ScheduledJobErrorStrings.resx deleted file mode 100644 index 047abfee829..00000000000 --- a/src/Microsoft.PowerShell.ScheduledJob/resources/ScheduledJobErrorStrings.resx +++ /dev/null @@ -1,387 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 scheduled job {0}. - {0} is the scheduled job definition name that cannot be found. - - - Cannot find scheduled job definition {0} in the Task Scheduler. - - - The scheduled job definition {0} cannot be removed because one or more instances are currently running. You can remove and stop all running instances by using the Force parameter. - - - An error occurred while adding triggers to the scheduled job {0}. - - - There is no entry in Task Scheduler for scheduled job definition {0}. A new Task Scheduler entry has been created for this scheduled job definition. - - - Cannot get the {0} scheduled job because it is corrupted or in an irresolvable state. Because it cannot run, PowerShell has deleted {0} and its results from the computer. To recreate the scheduled job, use the Register-ScheduledJob cmdlet. For more information about corrupted scheduled jobs, see about_Scheduled_Jobs_Troubleshooting. - {0} is the name of the scheduled job definition. - - - An error occurred while loading job run results for scheduled job {0} with job run date {1}. - - - An error occurred while registering the scheduled job {0}. - - - An error occurred while removing job triggers from scheduled job {0}. - - - One or more scheduled job runs could not be retrieved {0}. - - - Job {0} cannot be saved because no file path was specified. - - - Job {0} has not been run and cannot be saved. Run the job first, and then save results. - - - An error occurred while enabling or disabling the scheduled job {0}. - - - An error occurred while setting properties on the scheduled job {0}. - - - Cannot start a job from the {0} scheduled job definition. - - - An error occurred while unregistering the scheduled job {0}. - - - An error occurred while updating the scheduled job definition {0} with this trigger {1}. See exception details for more information. - - - Only one JobTrigger type can be specified: AtStartup, AtLogon, Once, Daily, or Weekly. - - - A scheduled job definition object {0} already exists in the local scheduled job repository having this Global ID {1}. - - - A scheduled job definition object with Global ID {0} could not be found. - - - A scheduled job definition with ID {0} could not be found. - - - A scheduled job definition with Name {0} could not be found. - - - This scheduled job definition object {0} has been disposed. - - - Scheduled job definition {0}. - - - A directory not found error occurred while registering scheduled job definition {0}. Make sure you are running PowerShell with elevated privileges. - - - An error occurred while registering scheduled job definition {0}. Cannot add this definition object to the job store. - - - An error occurred while registering scheduled job definition {0} to the Windows Task Scheduler. The Task Scheduler error is: {1}. - - - An error occurred while unregistering scheduled job definition {0}. - - - An error occurred while setting file access permissions for job definition {0} and user {1}. - - - An error occurred while updating scheduled job definition {0}. Cannot update this definition in the job store. - - - An error occurred while updating scheduled job definition {0}. Cannot update this definition with the Windows Task Scheduler. - - - An error has occurred within the Task Scheduler. - - - The At parameter is not valid for the {0} job trigger type. - - - The DaysInterval parameter is not valid for the {0} job trigger type. - - - The DaysInterval parameter value must be greater than zero. - - - The DaysOfWeek parameter is not valid for the {0} job trigger type. - - - The FilePath parameter is not valid. - - - Only PowerShell script files are allowed for FilePath parameter. Specify a file with .ps1 extension. - - - The IdleDuration parameter cannot have a negative value. - - - The IdleTimeout parameter cannot have a negative value. - - - The scheduled job definition name {0} contains characters that are not valid. - - - The MaxResultCount parameter cannot have a negative or zero value. - - - The User parameter is not valid for the {0} job trigger type. - - - The WeeksInterval parameter is not valid for the {0} job trigger type. - - - The WeeksInterval parameter value must be greater than zero. - - - An I/O failure occurred while updating the scheduled job definition {0}. This could mean a file is missing or corrupted, either in Task Scheduler or in the PowerShell scheduled job store. You might need to create the scheduled job definition again. - {0} is the scheduled job definition name - - - Job {0} is currently running. - - - The scheduled job definition {0} already exists in the job definition store. - - - The scheduled job results {0} already exist in the job results store. - - - The At parameter is required for the {0} job trigger type. - - - The DaysOfWeek parameter is required for the {0} job trigger type. - - - The job trigger {0} requires the DaysOfWeek parameter to be defined. - - - The Job trigger {0} requires the At parameter to be defined. - - - No Frequency type has been specified for this job trigger. One of the following job trigger frequencies must be specified: AtStartup, AtLogon, Once, Daily, Weekly. - - - An access denied error occurred while updating the scheduled job definition {0}. Try running PowerShell with elevated user rights; that is, Run as Administrator. - {0} is the scheduled job definition name - - - There is no scheduled job definition object associated with this options object. - - - There is no scheduled job definition object associated with this trigger {0}. - - - The scheduled job {0} already exists in the local repository. - - - The scheduled job {0} is not in the local job repository. - - - The scheduled job definition {0} already exists in Task Scheduler. - - - Daily - - - AtLogon - - - A scheduled job trigger with ID {0} was not found for the scheduled job definition {1}. - - - Once - - - AtStartup - - - Weekly - - - An access denied error occurred when registering scheduled job definition {0}. Try running PowerShell with elevated user rights; that is, Run As Administrator. - - - Cannot convert a ScheduledJobTrigger object with TriggerFrequency value of {0}. - - - An unknown trigger type was returned from Task Scheduler for scheduled job definition {0} with trigger ID {1}. - - - The scheduled job definition {0} could not be saved because one of the values in the ArgumentList parameter cannot be converted to XML. If possible, change the ArgumentList values to types that are easily converted to XML, such as strings, integers, and hash tables. {1} - {0} is the name of the scheduled job definition that cannot be registered -{1} is the inner exception message from .Net serialization, or empty if no exception message. - - - Commands that interact with the host program, such as Write-Host, cannot be included in PowerShell scheduled jobs because scheduled jobs do not interact with the host program. Use an alternate command that does not interact with the host program, such as Write-Output or Out-File. - - - The RepetitionInterval parameter value must be less than or equal to the RepetitionDuration parameter value. - - - The RepetitionInterval parameter value must be greater than 1 minute. - - - The RepetitionInterval and RepetitionDuration Job trigger parameters must be specified together. - - - The Repetition parameters cannot have negative values. - - - The Repetition parameters are not valid for the {0} job trigger type. - - - The RepetitionInterval parameter cannot have a value of zero unless the RepetitionDuration parameter also has a zero value. A zero value removes repetition behavior from the Job trigger. - - - An error occurred while attempting to rename scheduled job from {0} to {1}. - - - An error occurred while attempting to rename scheduled job from {0} to {1} with error message: {2}. - - - An unrecoverable error occurred while renaming the scheduled job from {0} to {1}. The scheduled job will be removed. - - - An unrecoverable error occurred while renaming the scheduled job from {0} to {1} with message {2}. The scheduled job will be removed. - - - An error occurred while running scheduled job definition {0} from the Task Scheduler. - - - An error occurred while running scheduled job definition {0} from the Task Scheduler because {1}. - - - You cannot specify the RepetitionDuration and RepeatIndefinitely parameters in the same command. - - - When you use the RepeatIndefinitely parameter, the RepetitionInterval parameter is required. - - - the scheduled job definition could not be found - - - the scheduled job definition is disabled - - diff --git a/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj b/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj index a6dadabfed2..8e991d177b4 100644 --- a/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj +++ b/src/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.csproj @@ -11,10 +11,8 @@ - - - - + + $(RootNamespace).resources.%(Filename) + - diff --git a/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx b/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx index d4c08f78bab..833793ecf25 100644 --- a/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx +++ b/src/Microsoft.PowerShell.Security/resources/CertificateCommands.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx b/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx index ded11aab0a2..11e70869c16 100644 --- a/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx +++ b/src/Microsoft.PowerShell.Security/resources/CertificateProviderStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -144,9 +144,6 @@ Invoke Certificate Manager - - {0} is not supported in the current operating system. - Item: {0} Destination: {1} diff --git a/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx b/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx index 9f47134f147..6d646ddee45 100644 --- a/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx +++ b/src/Microsoft.PowerShell.Security/resources/CmsCommands.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx b/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx index d1bb4f0b23c..f2a48e21ed2 100644 --- a/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx +++ b/src/Microsoft.PowerShell.Security/resources/ExecutionPolicyCommands.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx b/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx index af2242e5828..a418bb03920 100644 --- a/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx +++ b/src/Microsoft.PowerShell.Security/resources/SecureStringCommands.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx b/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx deleted file mode 100644 index e86df194720..00000000000 --- a/src/Microsoft.PowerShell.Security/resources/SecurityMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx b/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx index 53f5371fc4c..dcbbc53bd51 100644 --- a/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx +++ b/src/Microsoft.PowerShell.Security/resources/SignatureCommands.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -121,7 +121,7 @@ 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> + 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. diff --git a/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx b/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx index b067e9dc988..2a0404efe7f 100644 --- a/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx +++ b/src/Microsoft.PowerShell.Security/resources/UtilsStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/Microsoft.PowerShell.Security/resources/cs/CertificateCommands.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/CertificateCommands.cs.resx new file mode 100644 index 00000000000..5650a043915 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/CertificateCommands.cs.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 + + + Zadejte heslo: + + + Příkaz nemůže najít žádný ze zadaných souborů. + + + Následující soubor nebyl nalezen: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/cs/CertificateProviderStrings.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/CertificateProviderStrings.cs.resx new file mode 100644 index 00000000000..c05c2ffc1b8 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/CertificateProviderStrings.cs.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 + + + Zprostředkovatel certifikátu X509 + + + Certifikát X509 nelze najít v cestě {0}. + + + V cestě {0} nelze najít úložiště certifikátů X509. + + + Úložiště certifikátů nelze najít, protože zadané umístění úložiště X509 {0} není platné. + + + Cestu nelze zpracovat, protože cesta {0} není platná cesta zprostředkovatele certifikátu. + + + Přesunout certifikát + + + Odebrat certifikát + + + Odeberte certifikát a jeho privátní klíč. + + + Vyvolat Správce certifikátů + + + Položka: {0} Cíl: {1} + + + Kontejner certifikátů nelze přesunout. + + + Certifikát nelze přesunout z úložiště uživatelů do počítače nebo z počítače. + + + Certifikát nelze přesunout do stejného úložiště. + + + Nelze vytvořit jinou položku než úložiště certifikátů. + + + Vytváření úložišť certifikátů v části CurrentUser není podporováno. + + + Odstraňování úložišť certifikátů v části CurrentUser není podporováno. + + + Cíl není platné úložiště. + + + Položka: {0} + + + Úložiště {0} je integrované systémové úložiště a nelze ho odstranit. + + + Kontejner certifikátů nelze odebrat. + + + Privátní klíč byl přeskočen. Certifikát nemá přidružení privátního klíče. + + + Operace je v kořenovém úložišti uživatele a uživatelské rozhraní není povoleno. + + + . Následující chyba může být výsledkem přihlašovacích údajů uživatele vyžadovaných ve vzdáleném počítači. Informace o tom, jak povolit a používat CredSSP pro delegování pomocí vzdálené komunikace PowerShellu, najdete v nápovědě k rutině Enable-WSManCredSSP. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/cs/CmsCommands.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/CmsCommands.cs.resx new file mode 100644 index 00000000000..213cc64a867 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/CmsCommands.cs.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 + + + Cesta {0} musí odkazovat na jedinou cestu systému souborů. + + + Ochranu zprávy nejde zrušit. Vstup neobsahoval žádný šifrovaný obsah. + + + Ochranu zprávy nejde zrušit. Vstup neobsahoval žádný šifrovaný obsah. Pokud chcete v případě, že se nezjistí žádný šifrovaný obsah, vypsat původní obsah, zadejte parametr {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/cs/ExecutionPolicyCommands.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/ExecutionPolicyCommands.cs.resx new file mode 100644 index 00000000000..ed01a40e566 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/ExecutionPolicyCommands.cs.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 úspěšně aktualizoval zásady spouštění, ale toto nastavení přepisují zásady definované v konkrétnějším oboru. Kvůli tomuto přepsání zůstanou v prostředí platné aktuální efektivní zásady spouštění {0}. Nastavení zásad spouštění zobrazíte zadáním příkazu Get-ExecutionPolicy -List. Další informace najdete zadáním příkazu Get-Help Set-ExecutionPolicy. + + + Kontaktujte správce systému. + + + Zásady spouštění nejde získat. Zadejte pouze parametr List nebo Scope. + + + Zásady spouštění nejde nastavit. Zásady spouštění v oborech MachinePolicy nebo UserPolicy je nutné nastavit prostřednictvím Zásad skupiny. + + + Změna zásad spouštění + + + Zásady spouštění vás chrání před skripty, kterým nedůvěřujete. Změnou zásad spouštění se můžete vystavit bezpečnostním rizikům popsaným v tématu nápovědy about_Execution_Policies na adrese https://go.microsoft.com/fwlink/?LinkID=135170. Chcete zásady spouštění změnit? + + + {0} +Pokud chcete změnit zásady spouštění pro výchozí obor (LocalMachine), spusťte PowerShell pomocí možnosti Spustit jako správce. Pokud chcete změnit zásady spouštění pro aktuálního uživatele, spusťte příkaz Set-ExecutionPolicy -Scope CurrentUser. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/cs/SecureStringCommands.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/SecureStringCommands.cs.resx new file mode 100644 index 00000000000..99bd02f9cb2 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/SecureStringCommands.cs.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 + + + Zadejte tajný kód: + + + Systém nemůže zabezpečit vstup ve formátu prostého textu. Pokud chcete toto upozornění potlačit a převést prostý text na SecureString, spusťte příkaz znovu s parametrem Force. Další informace získáte zadáním příkazu get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/cs/SignatureCommands.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/SignatureCommands.cs.resx new file mode 100644 index 00000000000..53953301899 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/SignatureCommands.cs.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 + + + Kód nejde podepsat. Zadaný certifikát není vhodný k podepisování kódu. + + + Kód nejde podepsat. Adresa URL serveru časového razítka musí být plně kvalifikovaná ve formátu http://<server url> nebo https://<server url>. + + + Rutina Get-AuthenticodeSignature nepodporuje adresáře. Zadejte cestu k souboru a zkuste to znovu. + + + Soubor {0} nebyl nalezen. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/cs/UtilsStrings.cs.resx b/src/Microsoft.PowerShell.Security/resources/cs/UtilsStrings.cs.resx new file mode 100644 index 00000000000..f7b84f81ffa --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/cs/UtilsStrings.cs.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 + + + Soubor {0} nelze digitálně podepsat, protože je menší než 4 bajty. Aby bylo možné soubory digitálně podepsat, musí mít velikost alespoň 4 bajty. + + + Operaci nelze provést, protože není podporována pro objekt nalezený v cestě {0}. + + + Nelze získat seznam ACL, protože neexistuje požadovaná metoda GetSecurityDescriptor. + + + Nelze nastavit seznam ACL, protože neexistuje metoda SetSecurityDescriptor, kterou je potřeba vyvolat. + + + Operaci se nepodařilo provést, protože při vyvolání metody došlo k výjimce. + + + Nepodařilo se vytvořit seznam SACL se zadanou zásadou centrálního přístupu. + + + Prázdný seznam SACL nelze vytvořit. + + + Nepovedlo se povolit SeSecurityPrivilege. + + + Nepovedlo se nastavit zásady centrálního přístupu. + + + Parametry ClearCentralAccessPolicy a CentralAccessPolicy nelze použít současně. + + + Identifikátor nebo název zásad centrálního přístupu nejsou platné. Pokud zadáváte identifikátor, musí začínat řetězcem S-1-17. Pokud zadáváte název, musí být zásada použita na cílovém počítači. + + + Žádost o přihlašovací údaje k PowerShellu + + + Zadejte vaše přihlašovací údaje. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/CertificateCommands.de.resx b/src/Microsoft.PowerShell.Security/resources/de/CertificateCommands.de.resx new file mode 100644 index 00000000000..e3c19261c8c --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/CertificateCommands.de.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 + + + Kennwort eingeben: + + + Der Befehl kann keine der angegebenen Dateien finden. + + + Die folgende Datei konnte nicht gefunden werden: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/CertificateProviderStrings.de.resx b/src/Microsoft.PowerShell.Security/resources/de/CertificateProviderStrings.de.resx new file mode 100644 index 00000000000..ebf4214fb95 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/CertificateProviderStrings.de.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 Zertifikatanbieter + + + Das X509-Zertifikat wurde unter dem Pfad {0} nicht gefunden. + + + Der X509-Zertifikatspeicher wurde im Pfad {0} nicht gefunden. + + + Der Zertifikatspeicher wurde nicht gefunden, da der angegebene X509-Speicherort {0} ungültig ist. + + + Der Pfad kann nicht verarbeitet werden, da der Pfad {0} kein gültiger Zertifikatanbieterpfad ist. + + + Zertifikat verschieben + + + Zertifikat entfernen + + + Entfernen Sie das Zertifikat und den zugehörigen privaten Schlüssel. + + + Zertifikat-Manager aufrufen + + + Element: {0} Ziel: {1} + + + Sie können keinen Zertifikatcontainer verschieben. + + + Sie können ein Zertifikat nicht aus dem Benutzerspeicher auf den Computer oder vom Computer verschieben. + + + Sie können ein Zertifikat nicht in denselben Speicher verschieben. + + + Sie können kein anderes Element als den Zertifikatspeicher erstellen. + + + Das Erstellen von Zertifikatspeichern unter CurrentUser wird nicht unterstützt. + + + Das Löschen von Zertifikatspeichern unter CurrentUser wird nicht unterstützt. + + + Das Ziel ist kein gültiger Speicher. + + + Element: {0} + + + Der Speicher {0} ist ein integrierter Systemspeicher und kann nicht gelöscht werden. + + + Ein Zertifikatcontainer kann nicht entfernt werden. + + + Privater Schlüssel übersprungen. Das Zertifikat weist keine Zuordnung mit einem privaten Schlüssel auf. + + + Der Vorgang befindet sich im Benutzerstammspeicher und die Benutzeroberfläche ist nicht zulässig. + + + . Der folgende Fehler kann auf Benutzeranmeldeinformationen zurückzuführen sein, die auf dem Remotecomputer erforderlich sind. Informationen zum Aktivieren und Verwenden von CredSSP für die Delegierung mit PowerShell-Remoting finden Sie in der Hilfe zum Enable-WSManCredSSP-Cmdlet. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/CmsCommands.de.resx b/src/Microsoft.PowerShell.Security/resources/de/CmsCommands.de.resx new file mode 100644 index 00000000000..1553d13cf75 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/CmsCommands.de.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 + + + Der Pfad „{0}“ muss auf einen einzelnen Dateisystempfad verweisen. + + + Der Schutz der Nachricht kann nicht aufgehoben werden. Die Eingabe enthielt keinen verschlüsselten Inhalt. + + + Der Schutz der Nachricht kann nicht aufgehoben werden. Die Eingabe enthielt keinen verschlüsselten Inhalt. Geben Sie den Parameter „{0}“ an, wenn Sie den ursprünglichen Inhalt ausgeben möchten, wenn kein verschlüsselter Inhalt erkannt wird. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/ExecutionPolicyCommands.de.resx b/src/Microsoft.PowerShell.Security/resources/de/ExecutionPolicyCommands.de.resx new file mode 100644 index 00000000000..0ab8b00242e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/ExecutionPolicyCommands.de.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 hat Ihre Ausführungsrichtlinie erfolgreich aktualisiert, aber die Einstellung wird durch eine Richtlinie überschrieben, die in einem spezifischeren Bereich definiert ist. Aufgrund der Außerkraftsetzung behält Ihre Shell die aktuelle effektive Ausführungsrichtlinie von {0} bei. Geben Sie „Get-ExecutionPolicy -List“ ein, um ihre Ausführungsrichtlinieneinstellungen anzuzeigen. Weitere Informationen finden Sie unter „Get-Help Set-ExecutionPolicy“. + + + Wenden Sie sich an Ihren Systemadministrator. + + + Ausführungsrichtlinie kann nicht abrufen werden. Geben Sie nur die Listen- oder Bereichsparameter an. + + + Die Ausführungsrichtlinie kann nicht festgelegt werden. Ausführungsrichtlinien in den Bereichen „MachinePolicy“ oder „UserPolicy“ müssen über die Gruppenrichtlinie festgelegt werden. + + + Änderung der Ausführungsrichtlinie + + + Die Ausführungsrichtlinie schützt Sie vor Skripten, denen Sie nicht vertrauen. Wenn Sie die Ausführungsrichtlinie ändern, sind Sie möglicherweise den Sicherheitsrisiken ausgesetzt, die im about_Execution_Policies Hilfethema unter https://go.microsoft.com/fwlink/?LinkID=135170 beschrieben werden. Möchten Sie die Ausführungsrichtlinie ändern? + + + {0} +Um die Ausführungsrichtlinie für den Standardbereich (LocalMachine) zu ändern, öffnen Sie PowerShell mit der Option „Als Administrator ausführen“. Führen Sie „Set-ExecutionPolicy -Scope CurrentUser“ aus, um die Ausführungsrichtlinie für den aktuellen Benutzer zu ändern. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/SecureStringCommands.de.resx b/src/Microsoft.PowerShell.Security/resources/de/SecureStringCommands.de.resx new file mode 100644 index 00000000000..9ec0fe6b89c --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/SecureStringCommands.de.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 + + + Geheimnis eingeben: + + + Das System kann Nur-Text-Eingaben nicht schützen. Um diese Warnung zu unterdrücken und den Nur-Text in eine SecureString zu konvertieren, führen Sie den Befehl erneut mit dem Parameter Force aus. Weitere Informationen erhalten Sie mit: get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/SignatureCommands.de.resx b/src/Microsoft.PowerShell.Security/resources/de/SignatureCommands.de.resx new file mode 100644 index 00000000000..2554443ab4d --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/SignatureCommands.de.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 + + + Code kann nicht signiert werden. Das angegebene Zertifikat ist nicht zum Codesignieren geeignet. + + + Code kann nicht signiert werden. Die TimeStamp-Server-URL muss in der Form http://<server url> oder https://<server url> vollqualifiziert sein. + + + Das Get-AuthenticodeSignature „cmdlet“ unterstützt keine Verzeichnisse. Geben Sie einen Pfad zu einer Datei an, und wiederholen Sie den Vorgang. + + + Die Datei „{0}“ wurde nicht gefunden. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/de/UtilsStrings.de.resx b/src/Microsoft.PowerShell.Security/resources/de/UtilsStrings.de.resx new file mode 100644 index 00000000000..bd0a9c5fb84 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/de/UtilsStrings.de.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/CertificateCommands.es.resx b/src/Microsoft.PowerShell.Security/resources/es/CertificateCommands.es.resx new file mode 100644 index 00000000000..232fc929067 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/CertificateCommands.es.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 + + + Escribir contraseña: + + + El comando no encuentra ninguno de los archivos especificados. + + + No se encontró el siguiente archivo: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/CertificateProviderStrings.es.resx b/src/Microsoft.PowerShell.Security/resources/es/CertificateProviderStrings.es.resx new file mode 100644 index 00000000000..0e17657beaa --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/CertificateProviderStrings.es.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 + + + Proveedor de certificados X509 + + + No se encuentra el certificado X509 en la ruta de acceso {0}. + + + No se encuentra el almacén de certificados X509 en la ruta de acceso {0}. + + + No se encuentra el almacén de certificados porque la ubicación {0} del almacén X509 especificada no es válida. + + + No se puede procesar la ruta de acceso porque la ruta de acceso {0} no es una ruta de acceso de proveedor de certificados válida. + + + Mover certificado + + + Quitar certificado + + + Quite el certificado y su clave privada. + + + Invocar administrador de certificados + + + Elemento: {0} Destino: {1} + + + No se puede mover un contenedor de certificados. + + + No se puede mover un certificado del almacén de usuarios al equipo o desde este. + + + No se puede mover un certificado al mismo almacén. + + + No se puede crear un elemento que no sea el almacén de certificados. + + + No se admite la creación de almacenes de certificados en CurrentUser. + + + No se admite la eliminación de almacenes de certificados en CurrentUser. + + + El destino no es un almacén válido. + + + Elemento: {0} + + + El almacén {0} es un almacén del sistema integrado y no se puede eliminar. + + + No se puede quitar un contenedor de certificados. + + + Clave privada omitida. El certificado no tiene ninguna asociación de clave privada. + + + La operación está en el almacén raíz del usuario y no se permite la interfaz de usuario. + + + . El siguiente error puede deberse a las credenciales de usuario necesarias en el equipo remoto. Consulte la ayuda del cmdlet Enable-WSManCredSSP sobre cómo habilitar y usar CredSSP para la delegación con la comunicación remota de PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/CmsCommands.es.resx b/src/Microsoft.PowerShell.Security/resources/es/CmsCommands.es.resx new file mode 100644 index 00000000000..23154f6a150 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/CmsCommands.es.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 + + + La ruta "{0}" debe hacer referencia a una única ruta del sistema de archivos. + + + No se puede desproteger el mensaje. La entrada no contenía contenido cifrado. + + + No se puede desproteger el mensaje. La entrada no contenía contenido cifrado. Especifique el parámetro "{0}" si desea mostrar el contenido original cuando no se detecte contenido cifrado. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/ExecutionPolicyCommands.es.resx b/src/Microsoft.PowerShell.Security/resources/es/ExecutionPolicyCommands.es.resx new file mode 100644 index 00000000000..05fdb1e6f0e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/ExecutionPolicyCommands.es.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 actualizó correctamente la directiva de ejecución, pero la configuración se invalida mediante una directiva definida en un ámbito más específico. Debido a la invalidación, el shell conservará su directiva de ejecución vigente actual de {0}. Escriba "Get-ExecutionPolicy -List" para ver la configuración de la directiva de ejecución. Para obtener más información, consulte "Get-Help Set-ExecutionPolicy". + + + Póngase en contacto con el administrador del sistema. + + + No se puede obtener la directiva de ejecución. Especifique solo los parámetros List o Scope. + + + No se puede establecer la directiva de ejecución. Las directivas de ejecución en los ámbitos MachinePolicy o UserPolicy deben establecerse a través de directiva de grupo. + + + Cambio de directiva de ejecución + + + La directiva de ejecución le ayuda a protegerse de scripts en los que no confía. Si cambia la directiva de ejecución, podría exponerse a los riesgos de seguridad descritos en el tema de ayuda about_Execution_Policies en https://go.microsoft.com/fwlink/?LinkID=135170. ¿Desea cambiar la directiva de ejecución? + + + {0} +Para cambiar la directiva de ejecución para el ámbito predeterminado (LocalMachine), inicie PowerShell con la opción "Ejecutar como administrador". Para cambiar la directiva de ejecución del usuario actual, ejecute "Set-ExecutionPolicy -Scope CurrentUser". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/SecureStringCommands.es.resx b/src/Microsoft.PowerShell.Security/resources/es/SecureStringCommands.es.resx new file mode 100644 index 00000000000..506aa860951 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/SecureStringCommands.es.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 + + + Escribir secreto: + + + El sistema no puede proteger la entrada de texto sin formato. Para quitar esta advertencia y convertir el texto sin formato en un SecureString, vuelva a ejecutar el comando especificando el parámetro Force. Para obtener más información, escriba: get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/SignatureCommands.es.resx b/src/Microsoft.PowerShell.Security/resources/es/SignatureCommands.es.resx new file mode 100644 index 00000000000..0d61c48b43f --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/SignatureCommands.es.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 + + + No se puede firmar el código. El certificado especificado no es adecuado para la firma de código. + + + No se puede firmar el código. La URL del servidor de marca de tiempo debe estar completa, en la forma http://<server url> o https://<server url>. + + + El cmdlet Get-AuthenticodeSignature no admite directorios. Proporcione una ruta de acceso a un archivo y vuelva a intentarlo. + + + No se ha encontrado el archivo {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/es/UtilsStrings.es.resx b/src/Microsoft.PowerShell.Security/resources/es/UtilsStrings.es.resx new file mode 100644 index 00000000000..bd0a9c5fb84 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/es/UtilsStrings.es.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/CertificateCommands.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/CertificateCommands.fr.resx new file mode 100644 index 00000000000..de7120b7397 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/CertificateCommands.fr.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 + + + Entrez le mot de passe : + + + La commande ne peut trouver aucun des fichiers spécifiés. + + + Le fichier suivant est introuvable : {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/CertificateProviderStrings.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/CertificateProviderStrings.fr.resx new file mode 100644 index 00000000000..ef078539b16 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/CertificateProviderStrings.fr.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 + + + Fournisseur de certificat X509 + + + Nous ne pouvons pas trouver le certificat X509 au chemin d’accès {0}. + + + Nous ne pouvons pas trouver le magasin de certificats X509 au chemin d’accès {0}. + + + Nous ne pouvons pas trouver le magasin de certificats, car l’emplacement du magasin X509 spécifié {0} n’est pas valide. + + + Vous ne pouvez pas traiter le chemin d’accès, car le chemin {0} n’est pas un chemin de fournisseur de certificats valide. + + + Déplacer un certificat + + + Supprimer le certificat + + + Supprimez le certificat et sa clé privée. + + + Appeler le gestionnaire de certificats + + + Élément : {0} Destination : {1} + + + Vous ne pouvez pas déplacer un conteneur de certificats. + + + Vous ne pouvez pas déplacer un certificat d’un magasin utilisateur vers ou à partir d’un ordinateur. + + + Vous ne pouvez pas déplacer un certificat vers le même magasin. + + + Vous ne pouvez pas créer un élément autre qu’un magasin de certificats. + + + La création de magasins de certificats sous CurrentUser n’est pas prise en charge. + + + La suppression de magasins de certificats sous CurrentUser n’est pas prise en charge. + + + La destination n’est pas un magasin valide. + + + Élément : {0} + + + Le magasin {0} est un magasin système intégré et vous ne pouvez pas le supprimer. + + + Vous ne pouvez pas supprimer un conteneur de certificats. + + + Clé privée ignorée. Le certificat n’a aucune association de clé privée. + + + L’opération concerne le magasin racine de l’utilisateur et l’interface utilisateur n’est pas autorisée. + + + . L’erreur suivante peut être due à des informations d’identification de l’utilisateur requises sur l’ordinateur distant. Consultez l’aide de la cmdlet Enable-WSManCredSSP pour savoir comment activer et utiliser CredSSP pour la délégation avec la communication à distance de PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/CmsCommands.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/CmsCommands.fr.resx new file mode 100644 index 00000000000..89dfad5bada --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/CmsCommands.fr.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 + + + Le chemin « {0} » doit faire référence à un seul chemin du système de fichiers. + + + Nous ne pouvons pas lever la protection du message. L’entrée ne contenait aucun contenu chiffré. + + + Nous ne pouvons pas lever la protection du message. L’entrée ne contenait aucun contenu chiffré. Spécifiez le paramètre « {0} » si vous souhaitez afficher le contenu d’origine lorsqu’aucun contenu chiffré n’est détecté. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/ExecutionPolicyCommands.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/ExecutionPolicyCommands.fr.resx new file mode 100644 index 00000000000..1debeaf2f37 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/ExecutionPolicyCommands.fr.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 a correctement mis à jour votre stratégie d’exécution, mais le paramètre est remplacé par une stratégie définie dans une étendue plus spécifique. En raison de ce remplacement, votre interpréteur de commandes conservera sa stratégie d’exécution effective actuelle de {0}. Tapez « Get-ExecutionPolicy -List » pour afficher vos paramètres de stratégie d’exécution. Pour découvrir plus d’informations, veuillez consultez « Get-Help Set-ExecutionPolicy ». + + + Contactez l’administrateur système. + + + Nous ne pouvons pas obtenir une stratégie d’exécution. Spécifiez uniquement les paramètres List ou Scope. + + + Nous ne pouvons pas définir de stratégie d’exécution. Vous devez définir les stratégies d’exécution aux étendues MachinePolicy ou UserPolicy via la stratégie de groupe. + + + Stratégie d’exécution à utiliser + + + La stratégie d’exécution vous permet de vous protéger contre les scripts auxquels vous ne faites pas confiance. Il est possible que la modification de la stratégie d’exécution vous expose aux risques de sécurité décrits dans la rubrique d’Aide about_Execution_Policies à l’adresse https://go.microsoft.com/fwlink/?LinkID=135170. Voulez-vous modifier la stratégie d’exécution ? + + + {0} +Si vous souhaitez modifier la stratégie d’exécution associée à l’étendue par défaut (LocalMachine), lancez PowerShell avec l’option « Exécuter en tant qu’administrateur ». Pour modifier la stratégie d’exécution de l’utilisateur actuel, exécutez « Set-ExecutionPolicy -Scope CurrentUser ». + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/SecureStringCommands.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/SecureStringCommands.fr.resx new file mode 100644 index 00000000000..654f9ae268c --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/SecureStringCommands.fr.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 + + + Entrer le secret : + + + Le système ne peut pas protéger l’entrée en texte brut. Pour supprimer cet avertissement et convertir le texte brut en SecureString, réexécutez la commande spécifiant le paramètre Force. Pour plus d’informations, tapez : get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/SignatureCommands.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/SignatureCommands.fr.resx new file mode 100644 index 00000000000..1229fd6a972 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/SignatureCommands.fr.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 + + + Impossible de signer le code. Le certificat spécifié ne convient pas pour la signature de code. + + + Impossible de signer le code. L’URL du serveur TimeStamp doit être entièrement qualifiée et prendre la forme http://<server url> ou https://<server url>. + + + L’applet de commande Get-AuthenticodeSignature ne prend pas en charge les dossiers. Indiquez un chemin d’accès à un fichier, puis réessayez. + + + Le fichier « {0} » est introuvable + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/fr/UtilsStrings.fr.resx b/src/Microsoft.PowerShell.Security/resources/fr/UtilsStrings.fr.resx new file mode 100644 index 00000000000..bd0a9c5fb84 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/fr/UtilsStrings.fr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/CertificateCommands.it.resx b/src/Microsoft.PowerShell.Security/resources/it/CertificateCommands.it.resx new file mode 100644 index 00000000000..e3e140c5e1e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/CertificateCommands.it.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 + + + Immettere la password: + + + Non è possibile trovare i file specificati. + + + Non è stato possibile trovare il seguente file: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/CertificateProviderStrings.it.resx b/src/Microsoft.PowerShell.Security/resources/it/CertificateProviderStrings.it.resx new file mode 100644 index 00000000000..d992872743e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/CertificateProviderStrings.it.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 + + + Provider di certificati X509 + + + Non è possibile trovare il certificato X509 nel percorso {0}. + + + Non è possibile trovare l'archivio certificati X509 nel percorso {0}. + + + Non è possibile trovare l'archivio certificati perché il percorso dell'archivio X509 specificato {0} non è valido. + + + Non è possibile elaborare il percorso perché il percorso {0} non è un percorso del provider di certificati valido. + + + Sposta certificato + + + Rimuovi certificato + + + Rimuovere il certificato e la relativa chiave privata. + + + Richiamare Gestione certificati + + + Elemento: {0} Destinazione: {1} + + + Non è possibile spostare un contenitore di certificati. + + + Non è possibile spostare un certificato dall'archivio utenti a o dal computer. + + + Non è possibile spostare un certificato nello stesso archivio. + + + Non è possibile creare un elemento diverso dall'archivio certificati. + + + La creazione di archivi certificati in CurrentUser non è supportata. + + + L'eliminazione di archivi certificati in CurrentUser non è supportata. + + + La destinazione non è un archivio valido. + + + Elemento: {0} + + + L'archivio {0} è un archivio di sistema predefinito e non può essere eliminato. + + + Non è possibile rimuovere un contenitore di certificati. + + + Chiave privata ignorata. Il certificato non è associato ad alcuna chiave privata. + + + L'operazione si trova nell'archivio radice dell'utente e l'interfaccia utente non è consentita. + + + . L'errore seguente può essere dovuto alle credenziali utente necessarie nel computer remoto. Vedere la Guida del cmdlet Enable-WSManCredSSP su come abilitare e usare CredSSP per la delega con la comunicazione remota di PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/CmsCommands.it.resx b/src/Microsoft.PowerShell.Security/resources/it/CmsCommands.it.resx new file mode 100644 index 00000000000..6906cec081d --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/CmsCommands.it.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 + + + Il percorso "{0}" deve fare riferimento a un singolo percorso del file system. + + + Non è possibile rimuovere la protezione del messaggio. L'input non conteneva alcun contenuto crittografato. + + + Non è possibile rimuovere la protezione del messaggio. L'input non conteneva alcun contenuto crittografato. Specificare il parametro "{0}" se si desidera restituire il contenuto originale quando non viene rilevato alcun contenuto crittografato. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/ExecutionPolicyCommands.it.resx b/src/Microsoft.PowerShell.Security/resources/it/ExecutionPolicyCommands.it.resx new file mode 100644 index 00000000000..000cf2999ce --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/ExecutionPolicyCommands.it.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 ha aggiornato il criterio di esecuzione, ma l'impostazione viene sostituita da un criterio definito in un ambito più specifico. A causa dell'override, la shell manterrà effettivo il criterio di esecuzione di {0} corrente. Digitare "Get-ExecutionPolicy -List" per visualizzare le impostazioni del criterio di esecuzione. Per altre informazioni, vedere "Get-Help Set-ExecutionPolicy". + + + Contattare l'amministratore di sistema. + + + Non è possibile recuperare il criterio di esecuzione. Specificare solo i parametri List o Scope. + + + Non è possibile impostare il criterio di esecuzione. I criteri di esecuzione negli ambiti MachinePolicy o UserPolicy devono essere impostati tramite Criteri di gruppo. + + + Modifica del criterio di esecuzione + + + Il criterio di esecuzione consente di proteggersi da script non attendibili. La modifica del criterio di esecuzione potrebbe esporre l'utente ai rischi per la sicurezza descritti nell'argomento della Guida about_Execution_Policies help topic at https://go.microsoft.com/fwlink/?LinkID=135170. Modificare il criterio di esecuzione? + + + {0} +Per modificare il criterio di esecuzione per l'ambito predefinito (LocalMachine), aprire PowerShell con l'opzione "Esegui come amministratore". Per modificare il criterio di esecuzione per l'utente corrente, eseguire "Set-ExecutionPolicy -Scope CurrentUser". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/SecureStringCommands.it.resx b/src/Microsoft.PowerShell.Security/resources/it/SecureStringCommands.it.resx new file mode 100644 index 00000000000..8cbdacd90ca --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/SecureStringCommands.it.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 + + + Immettere il segreto: + + + Il sistema non può proteggere l'input di testo normale. Per non visualizzare più questo avviso e convertire il testo normale in una SecureString, eseguire nuovamente il comando specificando il parametro Force. Per altre informazioni, digitare: get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/SignatureCommands.it.resx b/src/Microsoft.PowerShell.Security/resources/it/SignatureCommands.it.resx new file mode 100644 index 00000000000..ca5a33371dc --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/SignatureCommands.it.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 + + + Non è possibile firmare il codice. Il certificato specificato non è adatto per la firma del codice. + + + Non è possibile firmare il codice. L'URL del server TimeStamp deve essere completo nel formato http://<url server> o https://<url server>. + + + Il cmdlet Get-AuthenticodeSignature non supporta le directory. Specificare un percorso di un file e riprovare. + + + Non è possibile trovare il file {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/it/UtilsStrings.it.resx b/src/Microsoft.PowerShell.Security/resources/it/UtilsStrings.it.resx new file mode 100644 index 00000000000..5029a251038 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/it/UtilsStrings.it.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 + + + Non è possibile firmare digitalmente il file perché il file {0} è più piccolo di 4 byte. I file devono avere almeno 4 byte per poter essere firmati digitalmente. + + + Non è possibile eseguire l'operazione perché non è supportata nell'oggetto trovato nel percorso {0}. + + + Non è possibile ottenere l'ACL perché il metodo necessario, GetSecurityDescriptor, non esiste. + + + Non è possibile impostare l'ACL perché il metodo necessario da invocare, SetSecurityDescriptor, non esiste. + + + Non è stato possibile eseguire l'operazione perché è stata generata un'eccezione durante l'invocazione del metodo. + + + Non è possibile creare un SACL con il criterio di accesso centrale specificato. + + + Non è possibile creare una SACL vuota. + + + Non è possibile abilitare SeSecurityPrivilege. + + + Non è possibile impostare il criterio di accesso centrale. + + + I parametri ClearCentralAccessPolicy e CentralAccessPolicy non possono essere usati contemporaneamente. + + + Identificatore o nome del criterio di accesso centrale non valido. Se si specifica un identificatore, deve iniziare con S-1-17. Se si specifica un nome, il criterio deve essere applicato al computer di destinazione. + + + Richiesta di credenziali di PowerShell + + + Immettere le credenziali. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/CertificateCommands.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/CertificateCommands.ja.resx new file mode 100644 index 00000000000..0b79de4a1ff --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/CertificateCommands.ja.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 + + + パスワードの入力: + + + コマンドは、指定されたファイルを見つけることができません。 + + + 次のファイルが見つかりませんでした: {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/CertificateProviderStrings.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/CertificateProviderStrings.ja.resx new file mode 100644 index 00000000000..040eb62c5e7 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/CertificateProviderStrings.ja.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 証明書プロバイダー + + + パス {0} に X509 証明書が見つかりません。 + + + パス {0} に X509 証明書ストアが見つかりません。 + + + 指定された X509 ストアの場所 {0} が無効なため、証明書ストアを見つけられません。 + + + パス {0} が有効な証明書プロバイダー パスではないため、パスを処理できません。 + + + 証明書を移動 + + + 証明書の削除 + + + 証明書とその秘密キーを削除します。 + + + 証明書マネージャーを呼び出す + + + 項目: {0} 宛先: {1} + + + 証明書コンテナーは移動できません。 + + + 証明書をユーザー ストアからコンピューター ストアへ、またはその逆に移動することはできません。 + + + 証明書を同じストアに移動することはできません。 + + + 証明書ストア以外の項目は作成できません。 + + + CurrentUser 配下の証明書ストアの作成はサポートされていません。 + + + CurrentUser 配下の証明書ストアの削除はサポートされていません。 + + + 移動先が有効なストアではありません。 + + + 項目: {0} + + + ストア {0} は組み込みのシステム ストアであるため、削除できません。 + + + 証明書コンテナーは削除できません。 + + + 秘密キーはスキップされました。証明書に秘密キーの関連付けがありません。 + + + 操作はユーザー ルート ストアに対して行われ、UI は許可されていません。 + + + 。次のエラーは、リモート コンピューターでユーザー資格情報が必要なために発生した可能性があります。PowerShell リモート処理での委任に CredSSP を有効にして使用する方法については、Enable-WSManCredSSP コマンドレットのヘルプを参照してください。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/CmsCommands.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/CmsCommands.ja.resx new file mode 100644 index 00000000000..f941c3b1d8d --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/CmsCommands.ja.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 + + + パス '{0}' は、1 つのファイル システム パスを参照する必要があります。 + + + メッセージの保護を解除できません。入力には暗号化されたコンテンツが含まれていませんでした。 + + + メッセージの保護を解除できません。入力には暗号化されたコンテンツが含まれていませんでした。暗号化されたコンテンツが検出されない場合に元のコンテンツを出力する場合は、'{0}' パラメーターを指定します。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/ExecutionPolicyCommands.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/ExecutionPolicyCommands.ja.resx new file mode 100644 index 00000000000..4a13be22c15 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/ExecutionPolicyCommands.ja.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 によって実行ポリシーが正常に更新されましたが、より具体的なスコープで定義されたポリシーによって設定がオーバーライドされます。 オーバーライドにより、シェルは {0} の現在の有効な実行ポリシーを保持します。実行ポリシー設定を表示するには、「Get-ExecutionPolicy -List」と入力します。詳細については、「Get-Help Set-ExecutionPolicy」を参照してください。 + + + システム管理者に連絡してください。 + + + 実行ポリシーを取得できません。List パラメーターまたは Scope パラメーターのみを指定します。 + + + 実行ポリシーを設定できません。MachinePolicy スコープまたは UserPolicy スコープでの実行ポリシーは、グループ ポリシーを使用して設定する必要があります。 + + + 実行ポリシーの変更 + + + 実行ポリシーは、信頼できないスクリプトから保護するのに役立ちます。実行ポリシーを変更すると、https://go.microsoft.com/fwlink/?LinkID=135170 の about_Execution_Policies ヘルプ トピックで説明されているセキュリティ リスクが発生する可能性があります。実行ポリシーを変更しますか? + + + {0} +"管理者として実行" オプションを使用して PowerShell を開き、既定 (LocalMachine) のスコープの実行ポリシーを変更します。現在のユーザーの実行ポリシーを変更するには、"Set-ExecutionPolicy -Scope CurrentUser" を実行します。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/SecureStringCommands.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/SecureStringCommands.ja.resx new file mode 100644 index 00000000000..545d07108fa --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/SecureStringCommands.ja.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 + + + シークレットを入力してください: + + + システムはプレーン テキスト入力を保護できません。この警告を表示せずにプレーン テキストを SecureString に変換するには、Force パラメーターを指定してコマンドを再実行してください。詳細については、次を入力してください: get-help ConvertTo-SecureString。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/SignatureCommands.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/SignatureCommands.ja.resx new file mode 100644 index 00000000000..dbfe3cd4ac6 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/SignatureCommands.ja.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 + + + コードに署名できません。指定された証明書はコード署名に適していません。 + + + コードに署名できません。 TimeStamp サーバー URL は、http://<server url> または https://<server url> の形式で完全修飾されている必要があります。 + + + Get-AuthenticodeSignature コマンドレットではディレクトリはサポートされていません。ファイルへのパスを指定して再試行してください。 + + + ファイル {0} が見つかりませんでした。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ja/UtilsStrings.ja.resx b/src/Microsoft.PowerShell.Security/resources/ja/UtilsStrings.ja.resx new file mode 100644 index 00000000000..a23e432de0a --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ja/UtilsStrings.ja.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 + + + ファイル {0} のサイズが 4 バイト未満であるため、ファイルにデジタル署名できません。デジタル署名するには、ファイルは 4 バイト以上である必要があります。 + + + この操作は、パス {0} で見つかったオブジェクトではサポートされていないため、実行できません。 + + + 必要なメソッド GetSecurityDescriptor が存在しないため、ACL を取得できません。 + + + 呼び出す必要があるメソッド SetSecurityDescriptor が存在しないため、ACL を設定できません。 + + + メソッドの呼び出し中に例外がスローされたため、操作を実行できませんでした。 + + + 指定された集約型アクセス ポリシーで SACL を作成できませんでした。 + + + 空の SACL を作成できませんでした。 + + + SeSecurityPrivilege を有効にできませんでした。 + + + 集約型アクセス ポリシーを設定できませんでした。 + + + ClearCentralAccessPolicy と CentralAccessPolicy パラメーターを同時に使用することはできません。 + + + 集約型アクセス ポリシーの識別子または名前が無効です。識別子を指定する場合は、S-1-17 で始まる必要があります。名前を指定する場合は、ターゲット マシンにポリシーを適用する必要があります。 + + + PowerShell 資格情報の要求 + + + 資格情報を入力してください。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/CertificateCommands.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/CertificateCommands.ko.resx new file mode 100644 index 00000000000..1a3ae2c18e5 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/CertificateCommands.ko.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 + + + 암호 입력: + + + 명령이 지정한 파일을 하나도 찾을 수 없습니다. + + + 다음 파일을 찾을 수 없습니다: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/CertificateProviderStrings.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/CertificateProviderStrings.ko.resx new file mode 100644 index 00000000000..3c3674698de --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/CertificateProviderStrings.ko.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 인증서 공급자 + + + {0} 경로에서 X509 인증서를 찾을 수 없습니다. + + + {0} 경로에서 X509 인증서 저장소를 찾을 수 없습니다. + + + 지정한 X509 저장소 위치 {0}이(가) 올바르지 않아 인증서 저장소를 찾을 수 없습니다. + + + 경로 {0}이(가) 올바른 인증서 공급자 경로가 아니므로 경로를 처리할 수 없습니다. + + + 인증서 이동 + + + 인증서 제거 + + + 인증서와 프라이빗 키를 제거합니다. + + + 인증서 관리자 호출 + + + 항목: {0} 대상: {1} + + + 인증서 컨테이너를 이동할 수 없습니다. + + + 사용자 저장소와 컴퓨터 저장소 간에는 인증서를 이동할 수 없습니다. + + + 인증서를 동일한 저장소로 이동할 수 없습니다. + + + 인증서 저장소 외의 항목은 만들 수 없습니다. + + + CurrentUser 아래에 인증서 저장소를 만들 수 없습니다. + + + CurrentUser 아래의 인증서 저장소는 삭제할 수 없습니다. + + + 대상이 올바른 저장소가 아닙니다. + + + 항목: {0} + + + 저장소 {0}은(는) 기본 제공 시스템 저장소이므로 삭제할 수 없습니다. + + + 인증서 컨테이너를 제거할 수 없습니다. + + + 개인 키를 건너뜁니다. 이 인증서에는 개인 키 연결이 없습니다. + + + 작업이 사용자 루트 저장소에서 수행 중이므로 UI를 사용할 수 없습니다. + + + . 다음 오류는 원격 컴퓨터에 사용자 자격 증명이 필요해서 발생할 수 있습니다. PowerShell 원격에서 위임에 CredSSP를 사용하도록 설정하고 사용하는 방법은 Enable-WSManCredSSP Cmdlet 도움말을 참조하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/CmsCommands.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/CmsCommands.ko.resx new file mode 100644 index 00000000000..844e9baf534 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/CmsCommands.ko.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 + + + 경로 '{0}'은(는) 단일 파일 시스템 경로를 참조해야 합니다. + + + 메시지의 보호를 해제할 수 없습니다. 입력에 암호화된 콘텐츠가 없습니다. + + + 메시지의 보호를 해제할 수 없습니다. 입력에 암호화된 콘텐츠가 없습니다. 암호화된 콘텐츠가 검색되지 않을 때 원래 콘텐츠를 출력하려면 '{0}' 매개 변수를 지정하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/ExecutionPolicyCommands.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/ExecutionPolicyCommands.ko.resx new file mode 100644 index 00000000000..30df8252d91 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/ExecutionPolicyCommands.ko.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에서 실행 정책을 업데이트했지만, 더 구체적인 범위에 정의된 정책이 이 설정을 재정의합니다. 재정의로 인해 셸은 현재 유효한 실행 정책 {0}을(를) 유지합니다. 실행 정책 설정을 보려면 "Get-ExecutionPolicy -List"를 입력하세요. 자세한 내용은 "Get-Help Set-ExecutionPolicy"를 참조하세요. + + + 시스템 관리자에게 문의하세요. + + + 실행 정책을 가져올 수 없습니다. List 또는 Scope 매개 변수만 지정하세요. + + + 실행 정책을 설정할 수 없습니다. MachinePolicy 또는 UserPolicy 범위의 실행 정책은 그룹 정책을 통해 설정해야 합니다. + + + 실행 정책 변경 + + + 실행 정책은 신뢰하지 않는 스크립트로부터 보호하는 데 도움이 됩니다. 실행 정책을 변경하면 https://go.microsoft.com/fwlink/?LinkID=135170의 about_Execution_Policies 도움말 항목에 설명된 보안 위험에 노출될 수 있습니다. 실행 정책을 변경하시겠습니까? + + + {0} +기본(LocalMachine) 범위에 대한 실행 정책을 변경하려면 "관리자 권한으로 실행" 옵션으로 PowerShell을 시작합니다. 현재 사용자의 실행 정책을 변경하려면 "Set-ExecutionPolicy -Scope CurrentUser"를 실행하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/SecureStringCommands.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/SecureStringCommands.ko.resx new file mode 100644 index 00000000000..2dcb54bc4ff --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/SecureStringCommands.ko.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 + + + 비밀 입력: + + + 시스템은 일반 텍스트 입력을 보호할 수 없습니다. 이 경고를 표시하지 않고 일반 텍스트를 SecureString으로 변환하려면 Force 매개 변수를 지정해 명령을 다시 실행하세요. 자세한 내용은 get-help ConvertTo-SecureString을 입력하세요. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/SignatureCommands.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/SignatureCommands.ko.resx new file mode 100644 index 00000000000..cad136557e5 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/SignatureCommands.ko.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 + + + 코드에 서명할 수 없습니다. 지정한 인증서는 코드 서명에 적합하지 않습니다. + + + 코드에 서명할 수 없습니다. TimeStamp 서버 URL은 http://<server url> 또는 https://<server url> 형식의 완전한 정규화된 경로여야 합니다. + + + Get-AuthenticodeSignature cmdlet은 디렉터리를 지원하지 않습니다. 파일 경로를 지정하고 다시 시도하세요. + + + 파일 {0}을(를) 찾을 수 없습니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ko/UtilsStrings.ko.resx b/src/Microsoft.PowerShell.Security/resources/ko/UtilsStrings.ko.resx new file mode 100644 index 00000000000..5023a06ea8e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ko/UtilsStrings.ko.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 + + + 파일 {0}의 크기가 4바이트보다 작아 파일에 디지털 서명을 할 수 없습니다. 디지털 서명을 하려면 Files가 최소 4바이트여야 합니다. + + + 경로 {0}에서 찾은 개체는 지원되지 않으므로 작업을 수행할 수 없습니다. + + + 필요한 메서드인 GetSecurityDescriptor가 없으므로 ACL을 가져올 수 없습니다. + + + 호출해야 하는 메서드인 SetSecurityDescriptor가 없으므로 ACL을 설정할 수 없습니다. + + + 메서드를 호출하는 동안 예외가 발생하여 작업을 수행할 수 없습니다. + + + 지정된 중앙 액세스 정책으로 SACL을 만들 수 없습니다. + + + 빈 SACL을 만들 수 없습니다. + + + SeSecurityPrivilege를 사용하도록 설정할 수 없습니다. + + + 중앙 액세스 정책을 설정할 수 없습니다. + + + ClearCentralAccessPolicy와 CentralAccessPolicy 매개 변수는 동시에 사용할 수 없습니다. + + + 중앙 액세스 정책 식별자 또는 이름이 올바르지 않습니다. 식별자를 지정하는 경우 S-1-17로 시작해야 합니다. 이름을 지정하는 경우 대상 컴퓨터에 정책이 적용되어 있어야 합니다. + + + PowerShell 자격 증명 요청 + + + 자격 증명을 입력합니다. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/CertificateCommands.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/CertificateCommands.pl.resx new file mode 100644 index 00000000000..29857400635 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/CertificateCommands.pl.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 + + + Wprowadź hasło: + + + Polecenie nie może odnaleźć żadnego z określonych plików. + + + Nie można odnaleźć następującego pliku: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/CertificateProviderStrings.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/CertificateProviderStrings.pl.resx new file mode 100644 index 00000000000..686ee70d2bd --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/CertificateProviderStrings.pl.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 + + + Dostawca certyfikatów X509 + + + Nie można odnaleźć certyfikatu X509 w ścieżce {0}. + + + Nie można odnaleźć magazynu certyfikatów X509 w ścieżce {0}. + + + Nie można odnaleźć magazynu certyfikatów, ponieważ określona lokalizacja magazynu X509 {0} jest nieprawidłowa. + + + Nie można przetworzyć ścieżki, ponieważ ścieżka {0} nie jest prawidłową ścieżką dostawcy certyfikatów. + + + Przenieś certyfikat + + + Usuń certyfikat + + + Usuń certyfikat i jego klucz prywatny. + + + Wywoływanie Menedżera certyfikatów + + + Element: {0} Miejsce docelowe: {1} + + + Nie można przenieść kontenera certyfikatów. + + + Nie można przenieść certyfikatu z magazynu użytkownika na komputer ani z komputera do magazynu użytkownika. + + + Nie można przenieść certyfikatu do tego samego magazynu. + + + Nie można utworzyć elementu innego niż magazyn certyfikatów. + + + Tworzenie magazynów certyfikatów w obszarze CurrentUser nie jest obsługiwane. + + + Usuwanie magazynów certyfikatów w obszarze CurrentUser nie jest obsługiwane. + + + Miejsce docelowe nie jest prawidłowym magazynem. + + + Element: {0} + + + Magazyn {0} jest wbudowanym magazynem systemowym i nie można go usunąć. + + + Nie można usunąć kontenera certyfikatów. + + + Pominięto klucz prywatny. Certyfikat nie ma skojarzonego klucza prywatnego. + + + Operacja dotyczy głównego magazynu użytkownika i nie można użyć interfejsu użytkownika. + + + . Następujący błąd może wynikać z poświadczeń użytkownika wymaganych na komputerze zdalnym. Zobacz pomoc polecenia cmdlet Enable-WSManCredSSP, aby dowiedzieć się, jak włączyć i używać CredSSP do delegowania w zdalnym programie PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/CmsCommands.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/CmsCommands.pl.resx new file mode 100644 index 00000000000..b8baba584c6 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/CmsCommands.pl.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 + + + Ścieżka „{0}” musi odwoływać się do pojedynczej ścieżki systemu plików. + + + Nie można wyłączyć ochrony wiadomości. Dane wejściowe nie zawierały zaszyfrowanej zawartości. + + + Nie można wyłączyć ochrony wiadomości. Dane wejściowe nie zawierały zaszyfrowanej zawartości. Określ parametr „{0}”, jeśli chcesz wygenerować oryginalną zawartość, gdy nie zostanie wykryta żadna zaszyfrowana zawartość. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/ExecutionPolicyCommands.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/ExecutionPolicyCommands.pl.resx new file mode 100644 index 00000000000..0b44d11e651 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/ExecutionPolicyCommands.pl.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 + + + Program PowerShell pomyślnie zaktualizował zasady wykonywania, ale ustawienie to zostało zastąpione przez zasady zdefiniowane w bardziej szczegółowym zakresie. Ze względu na to zastąpienie Twoja powłoka zachowa bieżącą efektywną zasadę wykonywania {0}. Wpisz „Get-ExecutionPolicy -List”, aby wyświetlić ustawienia zasad wykonywania. Aby uzyskać więcej informacji, zobacz „Get-Help Set-ExecutionPolicy”. + + + Skontaktuj się z administratorem systemu. + + + Nie można pobrać zasad wykonywania. Określ tylko parametry List lub Scope. + + + Nie można ustawić zasad wykonywania. Zasady wykonywania w zakresach MachinePolicy lub UserPolicy trzeba ustawić za pomocą Zasad grupy. + + + Zmiana zasad wykonywania + + + Zasady wykonywania pomagają chronić Cię przed skryptami, którym nie ufasz. Zmiana zasad wykonywania może narazić Cię na zagrożenia bezpieczeństwa opisane w temacie pomocy about_Execution_Policies pod adresem https://go.microsoft.com/fwlink/?LinkID=135170. Czy chcesz zmienić zasady wykonywania? + + + {0} +Aby zmienić zasady wykonywania dla domyślnego zakresu (LocalMachine), uruchom program PowerShell, wybierając opcję „Uruchom jako administrator”. Aby zmienić zasady wykonywania dla bieżącego użytkownika, uruchom polecenie „Set-ExecutionPolicy -Scope CurrentUser”. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/SecureStringCommands.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/SecureStringCommands.pl.resx new file mode 100644 index 00000000000..f4c8ff73b89 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/SecureStringCommands.pl.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 + + + Wprowadź wpis tajny: + + + System nie może chronić danych wejściowych w postaci zwykłego tekstu. Aby wyłączyć to ostrzeżenie i przekonwertować zwykły tekst na obiekt SecureString, ponownie wydaj polecenie, określając parametr Force. Aby uzyskać więcej informacji, wpisz: get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/SignatureCommands.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/SignatureCommands.pl.resx new file mode 100644 index 00000000000..9523eb1271c --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/SignatureCommands.pl.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 + + + Nie można podpisać kodu. Określony certyfikat nie jest odpowiedni do podpisywania kodu. + + + Nie można podpisać kodu. Adres URL serwera TimeStamp musi być w pełni kwalifikowany w postaci adresu http://<server url> lub https:///<server url>. + + + Polecenie cmdlet Get-AuthenticodeSignature nie obsługuje katalogów. Podaj ścieżkę do pliku i spróbuj ponownie. + + + Nie znaleziono pliku „{0}”. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pl/UtilsStrings.pl.resx b/src/Microsoft.PowerShell.Security/resources/pl/UtilsStrings.pl.resx new file mode 100644 index 00000000000..bd0a9c5fb84 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pl/UtilsStrings.pl.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/CertificateCommands.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/CertificateCommands.pt-BR.resx new file mode 100644 index 00000000000..e89d119031b --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/CertificateCommands.pt-BR.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}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/CertificateProviderStrings.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/CertificateProviderStrings.pt-BR.resx new file mode 100644 index 00000000000..f3b08732974 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/CertificateProviderStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/CmsCommands.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/CmsCommands.pt-BR.resx new file mode 100644 index 00000000000..d46d177cd7b --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/CmsCommands.pt-BR.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 + + + O caminho '{0}' deve se referir a um único caminho do sistema de arquivos. + + + Não é possível cancelar a proteção da mensagem. A entrada não continha conteúdo criptografado. + + + Não é possível cancelar a proteção da mensagem. A entrada não continha conteúdo criptografado. Especifique o parâmetro '{0}' se quiser gerar o conteúdo original quando nenhum conteúdo criptografado for detectado. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/ExecutionPolicyCommands.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/ExecutionPolicyCommands.pt-BR.resx new file mode 100644 index 00000000000..f9560e251fb --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/ExecutionPolicyCommands.pt-BR.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 + + + O PowerShell atualizou com sucesso sua política de execução, mas a configuração foi substituída por uma política definida em um escopo mais específico. Devido à substituição, seu shell manterá a política de execução efetiva atual de {0}. Digite "Get-ExecutionPolicy -List" para ver as configurações da sua política de execução. Para obter mais informações, consulte "Get-Help Set-ExecutionPolicy". + + + Contate o administrador de sistema. + + + Não é possível obter a política de execução. Especifique somente os parâmetros Lista ou Escopo. + + + Não é possível definir a política de execução. As políticas de execução nos escopos MachinePolicy ou UserPolicy devem ser definidas por meio da Política de Grupo. + + + Alteração de Política de Execução + + + A política de execução ajuda a proteger você contra scripts nos quais você não confia. Alterar a política de execução pode expor você aos riscos de segurança descritos no tópico about_Execution_Policies ajuda em https://go.microsoft.com/fwlink/?LinkID=135170. Deseja alterar a política de execução? + + + {0} +Para alterar a política de execução para o escopo padrão (LocalMachine), inicie o PowerShell com a opção "Executar como administrador". Para alterar a política de execução do usuário atual, execute "Set-ExecutionPolicy -Scope CurrentUser". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/SecureStringCommands.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/SecureStringCommands.pt-BR.resx new file mode 100644 index 00000000000..c49866d98da --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/SecureStringCommands.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/SignatureCommands.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/SignatureCommands.pt-BR.resx new file mode 100644 index 00000000000..230012b3337 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/SignatureCommands.pt-BR.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 + + + Não é possível assinar o código. O certificado especificado não é adequado para assinatura de código. + + + Não é possível assinar o código. A URL do servidor TimeStamp deve ser totalmente qualificada no formato http://<server url> ou https://<server url>. + + + O cmdlet Get-AuthenticodeSignature não dá suporte a diretórios. Forneça um caminho para um arquivo e tente novamente. + + + O arquivo {0} não foi encontrado. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/pt-BR/UtilsStrings.pt-BR.resx b/src/Microsoft.PowerShell.Security/resources/pt-BR/UtilsStrings.pt-BR.resx new file mode 100644 index 00000000000..bd0a9c5fb84 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/pt-BR/UtilsStrings.pt-BR.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/CertificateCommands.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/CertificateCommands.ru.resx new file mode 100644 index 00000000000..89416199683 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/CertificateCommands.ru.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 + + + Введите пароль: + + + Не удается найти ни один из указанных файлов. + + + Не удалось найти следующий файл: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/CertificateProviderStrings.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/CertificateProviderStrings.ru.resx new file mode 100644 index 00000000000..45b9f2708d6 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/CertificateProviderStrings.ru.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 + + + Не удается найти сертификат X509 на пути {0}. + + + Не удается найти хранилище сертификатов X509 на пути {0}. + + + Невозможно найти хранилище сертификатов, так как указанное расположение хранилища X509 {0} недопустимо. + + + Невозможно обработать путь, так как путь {0} не является допустимым путем поставщика сертификатов. + + + Переместить сертификат + + + Удалить сертификат + + + Удалить сертификат и его закрытый ключ. + + + Вызвать диспетчер сертификатов + + + Элемент: {0} Назначение: {1} + + + Невозможно переместить контейнер сертификата. + + + Нельзя переместить сертификат из хранилища пользователя на компьютер или обратно. + + + Невозможно переместить сертификат в то же хранилище. + + + Невозможно создать элемент, отличный от хранилища сертификатов. + + + Создание хранилищ сертификатов в CurrentUser не поддерживается. + + + Удаление хранилищ сертификатов в CurrentUser не поддерживается. + + + Место назначения не является допустимым хранилищем. + + + Элемент: {0} + + + Хранилище {0} является встроенным системным хранилищем и не может быть удалено. + + + Невозможно удалить контейнер сертификата. + + + Закрытый ключ пропущен. У сертификата нет связей закрытого ключа. + + + Операция выполняется в корневом хранилище пользователя, и использование пользовательского интерфейса не допускается. + + + . Следующая ошибка может быть вызвана тем, что учетные данные пользователя необходимы на удаленном компьютере. См. "Справка по командлету Enable-WSManCredSSP", чтобы узнать, как включить и использовать CredSSP для делегирования при удаленном взаимодействии PowerShell. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/CmsCommands.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/CmsCommands.ru.resx new file mode 100644 index 00000000000..e210477d708 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/CmsCommands.ru.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 + + + Путь {0} должен указывать только на один путь файловой системы. + + + Не удается снять защиту с сообщения. Входные данные не содержали зашифрованного содержимого. + + + Не удается снять защиту с сообщения. Входные данные не содержали зашифрованного содержимого. Укажите параметр {0}, если требуется вывести исходное содержимое в случае, когда зашифрованное содержимое не обнаружено. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/ExecutionPolicyCommands.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/ExecutionPolicyCommands.ru.resx new file mode 100644 index 00000000000..95b38ef7064 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/ExecutionPolicyCommands.ru.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 обновил политику выполнения, но этот параметр переопределяется политикой, заданной в более конкретной области. Из-за этого переопределения оболочка сохранит текущую действующую политику выполнения {0}. Введите "Get-ExecutionPolicy -List", чтобы просмотреть параметры политики выполнения. Подробнее см. в разделе "Get-Help Set-ExecutionPolicy". + + + Обратитесь к администратору. + + + Невозможно получить политику выполнения. Укажите только параметры List или Scope. + + + Невозможно настроить политику выполнения. Политики выполнения в областях MachinePolicy или UserPolicy нужно настраивать с помощью групповой политики. + + + Изменение политики выполнения + + + Политика выполнения помогает защитить вас от сценариев, которым вы не доверяете. Изменение политики выполнения может подвергнуть вас рискам безопасности, описанным в разделе справки о политиках выполнения по адресу https://go.microsoft.com/fwlink/?LinkID=135170. Изменить политику выполнения? + + + {0} +Чтобы изменить политику выполнения для области по умолчанию (LocalMachine), запустите PowerShell с помощью параметра "Запуск от имени администратора". Чтобы изменить политику выполнения для текущего пользователя, выполните команду "Set-ExecutionPolicy -Scope CurrentUser". + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/SecureStringCommands.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/SecureStringCommands.ru.resx new file mode 100644 index 00000000000..ef7a9f5d933 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/SecureStringCommands.ru.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 + + + Введите секрет: + + + Система не может защитить ввод в виде обычного текста. Чтобы подавить это предупреждение и преобразовать обычный текст в SecureString, повторите команду, указав параметр Force. Для получения дополнительных сведений введите: get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/SignatureCommands.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/SignatureCommands.ru.resx new file mode 100644 index 00000000000..967b9e702f1 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/SignatureCommands.ru.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 + + + Не удается подписать код. Указанный сертификат не подходит для подписания кода. + + + Не удается подписать код. URL-адрес сервера TimeStamp должен быть указан полностью в формате http://<server url> или https://<server url>. + + + Командлет Get-AuthenticodeSignature не поддерживает каталоги. Укажите путь к файлу и повторите попытку. + + + Файл {0} не найден. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/ru/UtilsStrings.ru.resx b/src/Microsoft.PowerShell.Security/resources/ru/UtilsStrings.ru.resx new file mode 100644 index 00000000000..e397c2f6884 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/ru/UtilsStrings.ru.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 + + + Невозможно поставить цифровую подпись на файл {0}, так как его размер составляет менее 4 байт. Для цифровой подписи файлы должны иметь размер не менее 4 байт. + + + Не удается выполнить операцию, так как она не поддерживается для объекта, найденного в пути {0}. + + + Не удается получить ACL, так как необходимый метод GetSecurityDescriptor не существует. + + + Не удается задать ACL, так как метод, который нужно вызвать, SetSecurityDescriptor, не существует. + + + Не удалось выполнить операцию, так как во время вызова метода возникло исключение. + + + Не удалось создать SACL с указанной централизованной политикой доступа. + + + Не удалось создать пустой системный список управления доступом. + + + Не удалось включить SeSecurityPrivilege. + + + Не удалось задать центральную политику доступа. + + + Параметры ClearCentralAccessPolicy и CentralAccessPolicy нельзя использовать одновременно. + + + Недопустим идентификатор или имя централизованной политики доступа. Если указан идентификатор, он должен начинаться с S-1-17. Если указано имя, политика должна быть применена на целевом компьютере. + + + Запрос учетных данных PowerShell + + + Введите свои учетные данные. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/CertificateCommands.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/CertificateCommands.tr.resx new file mode 100644 index 00000000000..eb176111b43 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/CertificateCommands.tr.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 + + + Parola girin: + + + Komut belirtilen dosyaların hiçbirini bulamıyor. + + + Şu dosya bulunamadı: {0}. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/CertificateProviderStrings.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/CertificateProviderStrings.tr.resx new file mode 100644 index 00000000000..f5dfed979fc --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/CertificateProviderStrings.tr.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 Sertifika Sağlayıcısı + + + X509 sertifikası {0} yolunda bulunamıyor. + + + X509 sertifika depolama alanı {0} yolunda bulunamıyor. + + + Belirtilen {0} X509 depolama alanı konumu geçerli olmadığından sertifika depolama alanı bulunamıyor. + + + {0} yolu geçerli bir sertifika sağlayıcısı yolu olmadığından yol işlenemiyor. + + + Sertifikayı taşı + + + Sertifikayı kaldır + + + Sertifikayı ve özel anahtarını kaldırın. + + + Sertifika Yöneticisini Çağır + + + Öğe: {0} Hedef: {1} + + + Sertifika kapsayıcısını taşıyamazsınız. + + + Bir sertifikayı kullanıcı deposundan makineye ya da makineden kullanıcı deposuna taşıyamazsınız. + + + Sertifikayı aynı depolama alanına taşıyamazsınız. + + + Sertifika depolama alanı dışında bir öğe oluşturamazsınız. + + + CurrentUser altındaki sertifika depolama alanlarının oluşturulması desteklenmiyor. + + + CurrentUser altındaki sertifika depolama alanlarının silinmesi desteklenmiyor. + + + Hedef geçerli bir depolama alanı değil. + + + Öğe: {0} + + + {0} depolama alanı yerleşik bir sistem deposudur ve silinemez. + + + Sertifika kapsayıcısını kaldıramazsınız. + + + Özel anahtar atlandı. Sertifikanın özel anahtar ilişkisi yok. + + + İşlem kullanıcı kök deposunda ve kullanıcı arabirimine izin verilmiyor. + + + . Aşağıdaki hata, uzak makinede gerekli olan kullanıcı kimlik bilgilerinden kaynaklanıyor olabilir. PowerShell uzaktan iletişimiyle temsilci seçimi için CredSSP'yi etkinleştirme ve kullanma hakkında Enable-WSManCredSSP Cmdlet'i yardımına bakın. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/CmsCommands.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/CmsCommands.tr.resx new file mode 100644 index 00000000000..7af4e1ca60f --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/CmsCommands.tr.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 + + + ‘{0}' yolu tek bir dosya sistemi yolunu göstermelidir. + + + İleti korunamıyor. Girişte şifrelenmiş içerik yoktu. + + + İleti korunamıyor. Girişte şifrelenmiş içerik yoktu. Şifrelenmiş içerik algılanmadığında özgün içeriği çıktı olarak vermek istiyorsanız '{0}' parametresini belirtin. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/ExecutionPolicyCommands.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/ExecutionPolicyCommands.tr.resx new file mode 100644 index 00000000000..f6afd048a4b --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/ExecutionPolicyCommands.tr.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 + + + Windows PowerShell yürütme ilkenizi başarıyla güncelleştirdi, ancak ayar daha belirli bir kapsamda tanımlanan bir ilke tarafından geçersiz kılınıyor. Geçersiz kılma nedeniyle, kabuğunuz geçerli etkili yürütme ilkesi olarak {0} değerini koruyacak. Yürütme ilkenizi görüntülemek için "Get-ExecutionPolicy -List" yazın. Daha fazla bilgi için lütfen "Get-Help Set-ExecutionPolicy" bölümüne bakın. + + + Sistem yöneticinize başvurun. + + + Yürütme ilkesi alınamıyor. Yalnızca List veya Scope parametrelerini belirtin. + + + Yürütme ilkesi ayarlanamıyor. MachinePolicy veya UserPolicy kapsamlarındaki yürütme ilkeleri Grup İlkesi aracılığıyla ayarlanmalıdır. + + + Yürütme İlkesi Değişikliği + + + Yürütme ilkesi, güvenmediğiniz betiklerden sizi korumaya yardımcı olur. Yürütme ilkesini değiştirmek, https://go.microsoft.com/fwlink/?LinkID=135170 adresindeki about_Execution_Policies yardım konusunda açıklanan güvenlik risklerine sizi kullanıma sunabilir. Yürütme ilkesini değiştirmek istiyor musunuz? + + + {0} +Varsayılan (LocalMachine) kapsamı için yürütme ilkesini değiştirmek üzere, PowerShell'i "Yönetici olarak çalıştır" seçeneğiyle başlatın. Geçerli kullanıcı için yürütme ilkesini değiştirmek üzere, "Set-ExecutionPolicy -Scope CurrentUser" komutunu çalıştırın. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/SecureStringCommands.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/SecureStringCommands.tr.resx new file mode 100644 index 00000000000..131fc06f1b4 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/SecureStringCommands.tr.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 + + + Gizli diziyi girin: + + + Sistem düz metin girişini koruyamaz. Bu uyarıyı bastırmak ve düz metni SecureString'e dönüştürmek için, Force parametresini belirterek komutu yeniden çalıştırın. Daha fazla bilgi için şunu yazın: get-help ConvertTo-SecureString. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/SignatureCommands.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/SignatureCommands.tr.resx new file mode 100644 index 00000000000..b2ee520becb --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/SignatureCommands.tr.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 + + + Kod imzalanamıyor. Belirtilen sertifika kod imzalama için uygun değil. + + + Kod imzalanamıyor. Zaman damgası sunucusu URL'si, http://<server url> veya https://<server url> biçiminde tam olarak belirtilmelidir. + + + Get-AuthenticodeSignature cmdlet'i dizinleri desteklemez. Bir dosya yolu sağlayıp yeniden deneyin. + + + {0} dosyası bulunamadı. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/tr/UtilsStrings.tr.resx b/src/Microsoft.PowerShell.Security/resources/tr/UtilsStrings.tr.resx new file mode 100644 index 00000000000..bd0a9c5fb84 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/tr/UtilsStrings.tr.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. + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/CertificateCommands.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/CertificateCommands.zh-Hans.resx new file mode 100644 index 00000000000..f6f3806358e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/CertificateCommands.zh-Hans.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 + + + 输入密码: + + + 命令找不到任何指定的文件。 + + + 找不到以下文件: {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/CertificateProviderStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/CertificateProviderStrings.zh-Hans.resx new file mode 100644 index 00000000000..924150c4a5f --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/CertificateProviderStrings.zh-Hans.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 证书提供程序 + + + 在路径 {0} 处找不到 X509 证书。 + + + 在路径 {0} 处找不到 X509 证书。 + + + 找不到证书存储,因为指定的 X509 存储位置 {0} 无效。 + + + 无法处理路径,因为路径 {0} 不是有效的证书提供程序路径。 + + + 移动证书 + + + 删除证书 + + + 删除证书及其私钥。 + + + 调用证书管理器 + + + 项: {0} 目标: {1} + + + 无法移动证书容器。 + + + 不能将证书从用户存储移动到计算机存储,或从计算机存储移动到用户存储。 + + + 不能将证书移动到同一存储区。 + + + 除了证书存储之外,无法创建其他项。 + + + 不支持在 CurrentUser 下创建证书存储。 + + + 不支持删除 CurrentUser 下的证书存储。 + + + 该目标不是有效的存储。 + + + 项: {0} + + + 存储 {0} 是内置系统存储,无法删除。 + + + 无法删除证书容器。 + + + 已跳过私钥。该证书没有关联的私钥。 + + + 此操作针对用户根存储,不允许使用 UI。 + + + 。以下错误可能是远程计算机上需要用户凭据所致。请参阅 Enable-WSManCredSSP Cmdlet 帮助,了解如何启用 CredSSP,并在 PowerShell 远程处理中将其用于委派操作。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/CmsCommands.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/CmsCommands.zh-Hans.resx new file mode 100644 index 00000000000..cb88f0a137e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/CmsCommands.zh-Hans.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 + + + 路径“{0}”必须引用单个文件系统路径。 + + + 无法取消保护消息。输入不包含任何加密内容。 + + + 无法取消保护消息。输入不包含任何加密内容。如果希望在未检测到加密内容时输出原始内容,请指定“{0}”参数。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/ExecutionPolicyCommands.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/ExecutionPolicyCommands.zh-Hans.resx new file mode 100644 index 00000000000..dc2b00874a8 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/ExecutionPolicyCommands.zh-Hans.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 已成功更新你的执行策略,但该设置被在更具体作用域中定义的策略覆盖。 由于该覆盖,你的 shell 将保留当前生效的执行策略 {0}。键入“Get-ExecutionPolicy -List”以查看你的执行策略设置。有关详细信息,请参阅“Get-Help Set-ExecutionPolicy”。 + + + 请与你的系统管理员联系。 + + + 无法获取执行策略。请仅指定 List 或 Scope 参数。 + + + 无法设置执行策略。必须通过组策略设置 MachinePolicy 或 UserPolicy 范围的执行策略。 + + + 执行策略更改 + + + 执行策略可帮助你防范不受信任的脚本。更改执行策略可能会使你面临 https://go.microsoft.com/fwlink/?LinkID=135170 中 about_Execution_Policies 帮助主题所述的安全风险。是否要更改执行策略? + + + {0} +若要更改默认 (LocalMachine) 范围的执行策略,请使用“以管理员身份运行”选项启动 PowerShell。若要更改当前用户的执行策略,请运行“Set-ExecutionPolicy -Scope CurrentUser”。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/SecureStringCommands.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/SecureStringCommands.zh-Hans.resx new file mode 100644 index 00000000000..c4124ad4916 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/SecureStringCommands.zh-Hans.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 + + + 输入密钥: + + + 系统无法保护纯文本输入。若要取消显示此警告并将纯文本转换为 SecureString,请重新运行命令,并指定 Force 参数。有关详细信息,请输入 get-help ConvertTo-SecureString。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/SignatureCommands.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/SignatureCommands.zh-Hans.resx new file mode 100644 index 00000000000..63e8b5ea500 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/SignatureCommands.zh-Hans.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 + + + 无法对代码进行签名。指定的证书不适用于代码签名。 + + + 无法对代码进行签名。 时间戳服务器 URL 必须以 http://<server url> or https://<server url> 的形式完全限定。 + + + Get-AuthenticodeSignature cmdlet 不支持目录。提供文件的路径,然后重试。 + + + 找不到文件 {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hans/UtilsStrings.zh-Hans.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hans/UtilsStrings.zh-Hans.resx new file mode 100644 index 00000000000..15782d8e9f5 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hans/UtilsStrings.zh-Hans.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 + + + 无法对文件进行数字签名,因为文件 {0} 大小小于 4 个字节。文件必须至少为 4 个字节才能进行数字签名。 + + + 无法执行该操作,因为在路径 {0} 中找到的对象不支持它。 + + + 无法获取 ACL,因为所需方法 GetSecurityDescriptor 不存在。 + + + 无法设置 ACL,因为它需要调用的方法 SetSecurityDescriptor 不存在。 + + + 无法执行操作,因为在方法调用期间引发了异常。 + + + 无法使用指定的中心访问策略创建 SACL。 + + + 无法创建空 SACL。 + + + 无法启用 SeSecurityPrivilege。 + + + 无法设置中心访问策略。 + + + 无法同时使用 ClearCentralAccessPolicy 和 CentralAccessPolicy 参数。 + + + 中心访问策略标识符或名称无效。如果指定标识符,则它必须以 S-1-17 开头。如果指定名称,则必须在目标计算机上应用策略。 + + + PowerShell 凭据请求 + + + 输入凭据。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/CertificateCommands.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/CertificateCommands.zh-Hant.resx new file mode 100644 index 00000000000..245b7fc45ac --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/CertificateCommands.zh-Hant.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 + + + 輸入密碼: + + + 命令找不到任何指定的檔案。 + + + 找不到下列檔案: {0} + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/CertificateProviderStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/CertificateProviderStrings.zh-Hant.resx new file mode 100644 index 00000000000..5a857d6f203 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/CertificateProviderStrings.zh-Hant.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 憑證提供者 + + + 在路徑 {0} 找不到 X509 憑證。 + + + 在路徑 {0} 找不到 X509 憑證存放區。 + + + 找不到憑證存放區,因為指定的 X509 存放區位置 {0} 無效。 + + + 無法處理路徑,因為路徑 {0} 不是有效的憑證提供者路徑。 + + + 移動憑證 + + + 移除憑證 + + + 移除憑證及其私密金鑰。 + + + 叫用 [憑證管理員] + + + 項目: {0} 目的地: {1} + + + 您無法移動憑證容器。 + + + 您無法將憑證從使用者存放區移至或移出電腦。 + + + 您無法將憑證移至相同的存放區。 + + + 您無法建立憑證存放區以外的項目。 + + + 不支援在 CurrentUser 下建立憑證存放區。 + + + 不支援在 CurrentUser 下刪除憑證存放區。 + + + 目的地不是有效的存放區。 + + + 項目: {0} + + + 存放區 {0} 是內建的系統存放區,因此無法刪除。 + + + 您無法移除憑證容器。 + + + 已跳過私密金鑰。此憑證沒有私密金鑰關聯。 + + + 此作業在使用者根存放區上進行,因此不允許 UI。 + + + 。下列錯誤可能是遠端電腦需要使用者認證所導致。請參閱 Enable-WSManCredSSP Cmdlet 說明,了解如何透過 PowerShell 遠端功能啟用及使用 CredSSP 進行委派。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/CmsCommands.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/CmsCommands.zh-Hant.resx new file mode 100644 index 00000000000..5e5ca7dd828 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/CmsCommands.zh-Hant.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 + + + 路徑 '{0}' 必須指向單一檔案系統路徑。 + + + 無法解除保護訊息。輸入包含未加密內容。 + + + 無法解除保護訊息。輸入包含未加密內容。如果您希望在未偵測到加密內容時輸出原始內容,請指定 '{0}' 參數。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/ExecutionPolicyCommands.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/ExecutionPolicyCommands.zh-Hant.resx new file mode 100644 index 00000000000..5ebae4b8b32 --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/ExecutionPolicyCommands.zh-Hant.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 已成功更新您的執行原則,但這項設定已由定義在更具體範圍內的原則覆寫。 由於這項覆寫,您的 shell 將保留目前生效的執行原則為 {0}。輸入 "Get-ExecutionPolicy -List" 以檢視您的執行原則設定。如需詳細資訊,請參閱 "Get-Help Set-ExecutionPolicy"。 + + + 請連絡系統管理員。 + + + 無法取得執行原則。請只指定 List 或 Scope 參數。 + + + 無法設定執行原則。必須透過群組原則設定 MachinePolicy 或 UserPolicy 範圍的執行原則。 + + + 執行原則變更 + + + 執行原則可協助保護您免於不信任的指令碼。變更執行原則可能會讓您暴露於 https://go.microsoft.com/fwlink/?LinkID=135170 中 about_Execution_Policies 說明主題所描述的安全性風險。您要變更執行原則嗎? + + + {0} +若要變更預設 (LocalMachine) 範圍的執行原則,請使用 [以系統管理員身分執行] 選項啟動 PowerShell。若要變更目前使用者的執行原則,請執行「Set-ExecutionPolicy -Scope CurrentUser」。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/SecureStringCommands.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/SecureStringCommands.zh-Hant.resx new file mode 100644 index 00000000000..a33129981dd --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/SecureStringCommands.zh-Hant.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 + + + 輸入祕密: + + + 系統無法保護純文字輸入。若要抑制此警告並將純文字轉換為 SecureString,請重新執行命令並指定 Force 參數。如需詳細資訊,請輸入: get-help ConvertTo-SecureString。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/SignatureCommands.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/SignatureCommands.zh-Hant.resx new file mode 100644 index 00000000000..8c55bd7081e --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/SignatureCommands.zh-Hant.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 + + + 無法簽署程式碼。指定的憑證不適合程式碼簽署。 + + + 無法簽署程式碼。 TimeStamp 伺服器 URL 必須使用完整格式,例如 http://<server url> 或 https://<server url>。 + + + Get-AuthenticodeSignature Cmdlet 不支援目錄。請提供檔案的路徑,然後再試一次。 + + + 找不到檔案 {0}。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/resources/zh-Hant/UtilsStrings.zh-Hant.resx b/src/Microsoft.PowerShell.Security/resources/zh-Hant/UtilsStrings.zh-Hant.resx new file mode 100644 index 00000000000..876e050975f --- /dev/null +++ b/src/Microsoft.PowerShell.Security/resources/zh-Hant/UtilsStrings.zh-Hant.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 + + + 無法數位簽署檔案,因為檔案 {0} 的大小小於 4 個位元組。Files 必須至少有 4 個位元組才能進行數位簽署。 + + + 無法執行作業,因為路徑 {0} 中找到的物件不支援此作業。 + + + 無法取得 ACL,因為必要的方法 GetSecurityDescriptor 不存在。 + + + 無法設定 ACL,因為需要呼叫的方法 SetSecurityDescriptor 不存在。 + + + 無法執行作業,因為在方法呼叫期間擲回了例外狀況。 + + + 無法使用指定的集中存取原則建立 SACL。 + + + 無法建立空白的 SACL。 + + + 無法啟用 SeSecurityPrivilege。 + + + 無法設定中央存取原則。 + + + 無法同時使用 ClearCentralAccessPolicy 和 CentralAccessPolicy 參數。 + + + 集中存取原則識別碼或名稱無效。如果指定識別碼,則必須以 S-1-17 開頭。如果指定名稱,則必須先將原則套用到目標電腦。 + + + PowerShell 認證要求 + + + 輸入認證。 + + \ No newline at end of file diff --git a/src/Microsoft.PowerShell.Security/security/AclCommands.cs b/src/Microsoft.PowerShell.Security/security/AclCommands.cs index c0994a57a53..e39b296d154 100644 --- a/src/Microsoft.PowerShell.Security/security/AclCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/AclCommands.cs @@ -207,7 +207,7 @@ public static string GetOwner(PSObject instance) throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (!(instance.BaseObject is ObjectSecurity sd)) + if (instance.BaseObject is not ObjectSecurity sd) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -246,7 +246,7 @@ public static string GetGroup(PSObject instance) throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (!(instance.BaseObject is ObjectSecurity sd)) + if (instance.BaseObject is not ObjectSecurity sd) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -291,8 +291,7 @@ public static AuthorizationRuleCollection GetAccess(PSObject instance) } // Get DACL - CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (sd is CommonObjectSecurity cos) { return cos.GetAccessRules(true, true, typeof(NTAccount)); } @@ -326,8 +325,7 @@ public static AuthorizationRuleCollection GetAudit(PSObject instance) PSTraceSource.NewArgumentException(nameof(instance)); } - CommonObjectSecurity cos = sd as CommonObjectSecurity; - if (cos != null) + if (sd is CommonObjectSecurity cos) { return cos.GetAuditRules(true, true, typeof(NTAccount)); } @@ -572,7 +570,7 @@ public static string GetSddl(PSObject instance) throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (!(instance.BaseObject is ObjectSecurity sd)) + if (instance.BaseObject is not ObjectSecurity sd) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -625,7 +623,7 @@ public GetAclCommand() /// security descriptor. Default is the current location. /// [Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByPath")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string[] Path { get @@ -664,8 +662,8 @@ public PSObject InputObject /// security descriptor. Default is the current location. /// [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] - [Alias("PSPath")] - [ValidateNotNullOrEmpty()] + [Alias("PSPath", "LP")] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { @@ -687,7 +685,7 @@ public string[] LiteralPath /// Gets or sets the audit flag of the command. This flag /// determines if audit rules should also be retrieved. /// - [Parameter()] + [Parameter] public SwitchParameter Audit { get @@ -718,7 +716,7 @@ private SwitchParameter AllCentralAccessPolicies /// determines whether the information about all central access policies /// available on the machine should be displayed. /// - [Parameter()] + [Parameter] public SwitchParameter AllCentralAccessPolicies { get @@ -931,7 +929,7 @@ public PSObject InputObject /// security descriptor. /// [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] - [Alias("PSPath")] + [Alias("PSPath", "LP")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { @@ -1027,7 +1025,7 @@ public SwitchParameter ClearCentralAccessPolicy /// If true, the security descriptor is also passed /// down the output pipeline. /// - [Parameter()] + [Parameter] public SwitchParameter Passthru { get diff --git a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs index a86bf657853..4d0cad2d3e9 100644 --- a/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CatalogCommands.cs @@ -145,7 +145,7 @@ public NewFileCatalogCommand() : base("New-FileCatalog") { } /// /// Catalog version. /// - [Parameter()] + [Parameter] public int CatalogVersion { get @@ -160,7 +160,7 @@ public int CatalogVersion } // Based on the Catalog version we will decide which hashing Algorithm to use - private int catalogVersion = 1; + private int catalogVersion = 2; /// /// Generate the Catalog for the Path. @@ -223,7 +223,7 @@ public TestFileCatalogCommand() : base("Test-FileCatalog") { } /// /// - [Parameter()] + [Parameter] public SwitchParameter Detailed { get { return detailed; } @@ -236,7 +236,7 @@ public SwitchParameter Detailed /// /// Patterns used to exclude files from DiskPaths and Catalog. /// - [Parameter()] + [Parameter] public string[] FilesToSkip { get diff --git a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs index 4723aa7fbf0..e3a386ee507 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateCommands.cs @@ -44,7 +44,7 @@ public string[] FilePath /// certificate. /// [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = "ByLiteralPath")] - [Alias("PSPath")] + [Alias("PSPath", "LP")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { @@ -208,8 +208,11 @@ protected override void ProcessRecord() 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/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs index d0c71e82260..37c687a7770 100644 --- a/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs +++ b/src/Microsoft.PowerShell.Security/security/CertificateProvider.cs @@ -26,7 +26,7 @@ using Dbg = System.Management.Automation; using DWORD = System.UInt32; using Runspaces = System.Management.Automation.Runspaces; -using Security = System.Management.Automation.Security; +using SMASecurity = System.Management.Automation.Security; namespace Microsoft.PowerShell.Commands { @@ -214,9 +214,9 @@ public override string ToString() // 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) ? - _punycodeName : - _unicodeName + " (" + _punycodeName + ")"; + return string.Equals(_punycodeName, _unicodeName, StringComparison.Ordinal) + ? _punycodeName + : _unicodeName + " (" + _punycodeName + ")"; } } @@ -275,7 +275,7 @@ protected override bool ReleaseHandle() if (handle != IntPtr.Zero) { - fResult = Security.NativeMethods.CertCloseStore(handle, 0); + fResult = SMASecurity.NativeMethods.CertCloseStore(handle, 0); handle = IntPtr.Zero; } @@ -318,25 +318,25 @@ public void Open(bool includeArchivedCerts) _valid = false; _open = false; - Security.NativeMethods.CertOpenStoreFlags StoreFlags = - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_STORE_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_SHARE_CONTEXT_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG; + 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 |= Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG; + StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_STORE_ENUM_ARCHIVED_FLAG; } switch (_storeLocation.Location) { case StoreLocation.LocalMachine: - StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; break; case StoreLocation.CurrentUser: - StoreFlags |= Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + StoreFlags |= SMASecurity.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; break; default: @@ -344,9 +344,9 @@ public void Open(bool includeArchivedCerts) break; } - IntPtr hCertStore = Security.NativeMethods.CertOpenStore( - Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, - Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore( + SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, IntPtr.Zero, // hCryptProv StoreFlags, _storeName); @@ -364,10 +364,10 @@ public void Open(bool includeArchivedCerts) "UserDS", StringComparison.OrdinalIgnoreCase)) { - if (!Security.NativeMethods.CertControlStore( + if (!SMASecurity.NativeMethods.CertControlStore( _storeHandle.Handle, 0, - Security.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC, + SMASecurity.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_AUTO_RESYNC, IntPtr.Zero)) { _storeHandle = null; @@ -391,12 +391,12 @@ public IntPtr GetNextCert(IntPtr certContext) if (!_open) { throw Marshal.GetExceptionForHR( - Security.NativeMethods.CRYPT_E_NOT_FOUND); + SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND); } if (Valid) { - certContext = Security.NativeMethods.CertEnumCertificatesInStore( + certContext = SMASecurity.NativeMethods.CertEnumCertificatesInStore( _storeHandle.Handle, certContext); } @@ -415,18 +415,18 @@ public IntPtr GetCertByName(string Name) if (!_open) { throw Marshal.GetExceptionForHR( - Security.NativeMethods.CRYPT_E_NOT_FOUND); + SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND); } if (Valid) { if (DownLevelHelper.HashLookupSupported()) { - certContext = Security.NativeMethods.CertFindCertificateInStore( + certContext = SMASecurity.NativeMethods.CertFindCertificateInStore( _storeHandle.Handle, - Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, 0, // dwFindFlags - Security.NativeMethods.CertFindType.CERT_FIND_HASH_STR, + SMASecurity.NativeMethods.CertFindType.CERT_FIND_HASH_STR, Name, IntPtr.Zero); // pPrevCertContext } @@ -464,7 +464,7 @@ public IntPtr GetCertByName(string Name) public void FreeCert(IntPtr certContext) { - Security.NativeMethods.CertFreeCertificateContext(certContext); + SMASecurity.NativeMethods.CertFreeCertificateContext(certContext); } /// @@ -556,6 +556,7 @@ internal enum CertificateProviderItem [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 @@ -723,16 +724,11 @@ protected override void RemoveItem( ThrowInvalidOperation(errorId, message); } - if (DynamicParameters != null) + if (DynamicParameters != null && DynamicParameters is ProviderRemoveItemDynamicParameters dp) { - ProviderRemoveItemDynamicParameters dp = - DynamicParameters as ProviderRemoveItemDynamicParameters; - if (dp != null) + if (dp.DeleteKey) { - if (dp.DeleteKey) - { - fDeleteKey = true; - } + fDeleteKey = true; } } @@ -887,9 +883,8 @@ protected override void MoveItem( object store = GetItemAtPath(destination, false, out isDestContainer); X509Certificate2 certificate = cert as X509Certificate2; - X509NativeStore certstore = store as X509NativeStore; - if (certstore != null) + if (store is X509NativeStore certstore) { certstore.Open(true); @@ -925,7 +920,7 @@ protected override void MoveItem( /// /// The path of the certificate store to create. /// - /// + /// /// Ignored. /// Only support store. /// @@ -973,15 +968,15 @@ protected override void NewItem( ThrowInvalidOperation(errorId, message); } - const Security.NativeMethods.CertOpenStoreFlags StoreFlags = - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_CREATE_NEW_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_MAXIMUM_ALLOWED_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + 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 = Security.NativeMethods.CertOpenStore( - Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, - Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore( + SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, IntPtr.Zero, // hCryptProv StoreFlags, pathElements[1]); @@ -992,7 +987,7 @@ protected override void NewItem( else // free native store handle { bool fResult = false; - fResult = Security.NativeMethods.CertCloseStore(hCertStore, 0); + fResult = SMASecurity.NativeMethods.CertCloseStore(hCertStore, 0); } X509Store outStore = new(pathElements[1], StoreLocation.LocalMachine); @@ -1067,23 +1062,18 @@ protected override bool HasChildItems(string path) if ((item != null) && isContainer) { - X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) + if (item is X509StoreLocation storeLocation) { result = storeLocation.StoreNames.Count > 0; } - else + else if (item is X509NativeStore store) { - X509NativeStore store = item as X509NativeStore; - if (store != null) + store.Open(IncludeArchivedCerts()); + IntPtr certContext = store.GetFirstCert(); + if (certContext != IntPtr.Zero) { - store.Open(IncludeArchivedCerts()); - IntPtr certContext = store.GetFirstCert(); - if (certContext != IntPtr.Zero) - { - store.FreeCert(certContext); - result = true; - } + store.FreeCert(certContext); + result = true; } } } @@ -1258,20 +1248,15 @@ protected override void GetItem(string path) return; } - X509StoreLocation storeLocation = item as X509StoreLocation; - if (storeLocation != null) // store location + if (item is X509StoreLocation storeLocation) // store location { WriteItemObject(item, path, isContainer); } - else // store + else if (item is X509NativeStore store) // store { - X509NativeStore store = item as X509NativeStore; - if (store != null) - { - // create X509Store - X509Store outStore = new(store.StoreName, store.Location.Location); - WriteItemObject(outStore, path, isContainer); - } + // create X509Store + X509Store outStore = new(store.StoreName, store.Location.Location); + WriteItemObject(outStore, path, isContainer); } } } @@ -1567,7 +1552,7 @@ private static string NormalizePath(string path) string[] elts = GetPathElements(path); - path = string.Join("\\", elts); + path = string.Join('\\', elts); } return path; @@ -1615,8 +1600,8 @@ private static string[] GetPathElements(string path) private void DoDeleteKey(IntPtr pProvInfo) { IntPtr hProv = IntPtr.Zero; - Security.NativeMethods.CRYPT_KEY_PROV_INFO keyProvInfo = - Marshal.PtrToStructure(pProvInfo); + SMASecurity.NativeMethods.CRYPT_KEY_PROV_INFO keyProvInfo = + Marshal.PtrToStructure(pProvInfo); IntPtr hWnd = DetectUIHelper.GetOwnerWindow(Host); @@ -1624,33 +1609,33 @@ private void DoDeleteKey(IntPtr pProvInfo) { if (hWnd != IntPtr.Zero) { - if (Security.NativeMethods.CryptAcquireContext( + if (SMASecurity.NativeMethods.CryptAcquireContext( ref hProv, keyProvInfo.pwszContainerName, keyProvInfo.pwszProvName, (int)keyProvInfo.dwProvType, - (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_VERIFYCONTEXT)) + (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_VERIFYCONTEXT)) { unsafe { void* pWnd = hWnd.ToPointer(); - Security.NativeMethods.CryptSetProvParam( + SMASecurity.NativeMethods.CryptSetProvParam( hProv, - Security.NativeMethods.ProviderParam.PP_CLIENT_HWND, + SMASecurity.NativeMethods.ProviderParam.PP_CLIENT_HWND, &pWnd, 0); - Security.NativeMethods.CryptReleaseContext(hProv, 0); + SMASecurity.NativeMethods.CryptReleaseContext(hProv, 0); } } } - if (!Security.NativeMethods.CryptAcquireContext( + if (!SMASecurity.NativeMethods.CryptAcquireContext( ref hProv, keyProvInfo.pwszContainerName, keyProvInfo.pwszProvName, (int)keyProvInfo.dwProvType, - keyProvInfo.dwFlags | (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_DELETEKEYSET | - (hWnd == IntPtr.Zero ? (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT : 0))) + keyProvInfo.dwFlags | (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_DELETEKEYSET | + (hWnd == IntPtr.Zero ? (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT : 0))) { ThrowErrorRemoting(Marshal.GetLastWin32Error()); } @@ -1663,21 +1648,21 @@ private void DoDeleteKey(IntPtr pProvInfo) IntPtr hCNGProv = IntPtr.Zero; IntPtr hCNGKey = IntPtr.Zero; - if ((keyProvInfo.dwFlags & (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_MACHINE_KEYSET) != 0) + if ((keyProvInfo.dwFlags & (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_MACHINE_KEYSET) != 0) { - cngKeyFlag = (uint)Security.NativeMethods.NCryptDeletKeyFlag.NCRYPT_MACHINE_KEY_FLAG; + cngKeyFlag = (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_MACHINE_KEY_FLAG; } if (hWnd == IntPtr.Zero || - (keyProvInfo.dwFlags & (uint)Security.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT) != 0) + (keyProvInfo.dwFlags & (uint)SMASecurity.NativeMethods.ProviderFlagsEnum.CRYPT_SILENT) != 0) { - cngKeyFlag |= (uint)Security.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG; + cngKeyFlag |= (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG; } int stat = 0; try { - stat = Security.NativeMethods.NCryptOpenStorageProvider( + stat = SMASecurity.NativeMethods.NCryptOpenStorageProvider( ref hCNGProv, keyProvInfo.pwszProvName, 0); @@ -1686,7 +1671,7 @@ private void DoDeleteKey(IntPtr pProvInfo) ThrowErrorRemoting(stat); } - stat = Security.NativeMethods.NCryptOpenKey( + stat = SMASecurity.NativeMethods.NCryptOpenKey( hCNGProv, ref hCNGKey, keyProvInfo.pwszContainerName, @@ -1697,21 +1682,21 @@ private void DoDeleteKey(IntPtr pProvInfo) ThrowErrorRemoting(stat); } - if ((cngKeyFlag & (uint)Security.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG) != 0) + if ((cngKeyFlag & (uint)SMASecurity.NativeMethods.NCryptDeletKeyFlag.NCRYPT_SILENT_FLAG) != 0) { unsafe { void* pWnd = hWnd.ToPointer(); - Security.NativeMethods.NCryptSetProperty( + SMASecurity.NativeMethods.NCryptSetProperty( hCNGProv, - Security.NativeMethods.NCRYPT_WINDOW_HANDLE_PROPERTY, + SMASecurity.NativeMethods.NCRYPT_WINDOW_HANDLE_PROPERTY, &pWnd, sizeof(void*), 0); // dwFlags } } - stat = Security.NativeMethods.NCryptDeleteKey(hCNGKey, 0); + stat = SMASecurity.NativeMethods.NCryptDeleteKey(hCNGKey, 0); if (stat != 0) { ThrowErrorRemoting(stat); @@ -1722,10 +1707,10 @@ private void DoDeleteKey(IntPtr pProvInfo) finally { if (hCNGProv != IntPtr.Zero) - result = Security.NativeMethods.NCryptFreeObject(hCNGProv); + result = SMASecurity.NativeMethods.NCryptFreeObject(hCNGProv); if (hCNGKey != IntPtr.Zero) - result = Security.NativeMethods.NCryptFreeObject(hCNGKey); + result = SMASecurity.NativeMethods.NCryptFreeObject(hCNGKey); } } } @@ -1741,7 +1726,7 @@ private void DoDeleteKey(IntPtr pProvInfo) private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePath) { // if recurse is true, remove every cert in the store - IntPtr localName = Security.NativeMethods.CryptFindLocalizedName(storeName); + IntPtr localName = SMASecurity.NativeMethods.CryptFindLocalizedName(storeName); string[] pathElements = GetPathElements(sourcePath); if (localName == IntPtr.Zero)//not find, we can remove { @@ -1766,17 +1751,17 @@ private void RemoveCertStore(string storeName, bool fDeleteKey, string sourcePat certContext = store.GetNextCert(certContext); } // remove the cert store - const Security.NativeMethods.CertOpenStoreFlags StoreFlags = - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_READONLY_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_OPEN_EXISTING_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_STORE_DELETE_FLAG | - Security.NativeMethods.CertOpenStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + 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 = Security.NativeMethods.CertOpenStore( - Security.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, - Security.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, + IntPtr hCertStore = SMASecurity.NativeMethods.CertOpenStore( + SMASecurity.NativeMethods.CertOpenStoreProvider.CERT_STORE_PROV_SYSTEM, + SMASecurity.NativeMethods.CertOpenStoreEncodingType.X509_ASN_ENCODING, IntPtr.Zero, // hCryptProv StoreFlags, storeName); @@ -1848,17 +1833,17 @@ private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, str if (fDeleteKey) { // it is fine if below call fails - if (Security.NativeMethods.CertGetCertificateContextProperty( + if (SMASecurity.NativeMethods.CertGetCertificateContextProperty( cert.Handle, - Security.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, + SMASecurity.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, IntPtr.Zero, ref provSize)) { pProvInfo = Marshal.AllocHGlobal((int)provSize); - if (Security.NativeMethods.CertGetCertificateContextProperty( + if (SMASecurity.NativeMethods.CertGetCertificateContextProperty( cert.Handle, - Security.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, + SMASecurity.NativeMethods.CertPropertyId.CERT_KEY_PROV_INFO_PROP_ID, pProvInfo, ref provSize)) { @@ -1878,8 +1863,8 @@ private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, str // do remove certificate // should not use the original handle - if (!Security.NativeMethods.CertDeleteCertificateFromStore( - Security.NativeMethods.CertDuplicateCertificateContext(cert.Handle))) + if (!SMASecurity.NativeMethods.CertDeleteCertificateFromStore( + SMASecurity.NativeMethods.CertDuplicateCertificateContext(cert.Handle))) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } @@ -1887,8 +1872,8 @@ private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, str // commit the change to physical store if (sourcePath.Contains("UserDS")) { - Security.NativeMethods.CERT_CONTEXT context = - Marshal.PtrToStructure(cert.Handle); + SMASecurity.NativeMethods.CERT_CONTEXT context = + Marshal.PtrToStructure(cert.Handle); CommitUserDS(context.hCertStore); } @@ -1915,10 +1900,10 @@ private void DoRemove(X509Certificate2 cert, bool fDeleteKey, bool fMachine, str /// No return. private static void CommitUserDS(IntPtr storeHandle) { - if (!Security.NativeMethods.CertControlStore( + if (!SMASecurity.NativeMethods.CertControlStore( storeHandle, 0, - Security.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_COMMIT, + SMASecurity.NativeMethods.CertControlStoreType.CERT_STORE_CTRL_COMMIT, IntPtr.Zero)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); @@ -1940,7 +1925,7 @@ private void DoMove(string destination, X509Certificate2 cert, X509NativeStore s IntPtr outCert = IntPtr.Zero; // duplicate cert first - dupCert = Security.NativeMethods.CertDuplicateCertificateContext(cert.Handle); + dupCert = SMASecurity.NativeMethods.CertDuplicateCertificateContext(cert.Handle); if (dupCert == IntPtr.Zero) { @@ -1948,16 +1933,16 @@ private void DoMove(string destination, X509Certificate2 cert, X509NativeStore s } else { - if (!Security.NativeMethods.CertAddCertificateContextToStore( + if (!SMASecurity.NativeMethods.CertAddCertificateContextToStore( store.StoreHandle, cert.Handle, - (uint)Security.NativeMethods.AddCertificateContext.CERT_STORE_ADD_ALWAYS, + (uint)SMASecurity.NativeMethods.AddCertificateContext.CERT_STORE_ADD_ALWAYS, ref outCert)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } - if (!Security.NativeMethods.CertDeleteCertificateFromStore(dupCert)) + if (!SMASecurity.NativeMethods.CertDeleteCertificateFromStore(dupCert)) { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } @@ -1973,7 +1958,7 @@ private void DoMove(string destination, X509Certificate2 cert, X509NativeStore s if (sourcePath.Contains("UserDS")) { - Security.NativeMethods.CERT_CONTEXT context = Marshal.PtrToStructure(cert.Handle); + SMASecurity.NativeMethods.CERT_CONTEXT context = Marshal.PtrToStructure(cert.Handle); CommitUserDS(context.hCertStore); } @@ -2545,10 +2530,7 @@ private X509NativeStore GetStore(string storePath, } } - if (s_storeCache == null) - { - s_storeCache = new X509NativeStore(storeLocation, storeName); - } + s_storeCache ??= new X509NativeStore(storeLocation, storeName); return s_storeCache; } @@ -2646,51 +2628,46 @@ private CertificateFilterInfo GetFilter() { CertificateFilterInfo filter = null; - if (DynamicParameters != null) + if (DynamicParameters != null && DynamicParameters is CertificateProviderDynamicParameters dp) { - CertificateProviderDynamicParameters dp = - DynamicParameters as CertificateProviderDynamicParameters; - if (dp != null) + if (dp.CodeSigningCert) { - if (dp.CodeSigningCert) - { - filter = new CertificateFilterInfo(); - filter.Purpose = CertificatePurpose.CodeSigning; - } + filter = new CertificateFilterInfo(); + filter.Purpose = CertificatePurpose.CodeSigning; + } - if (dp.DocumentEncryptionCert) - { - filter ??= new CertificateFilterInfo(); - filter.Purpose = CertificatePurpose.DocumentEncryption; - } + 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.DnsName != null) + { + filter ??= new CertificateFilterInfo(); + filter.DnsName = new WildcardPattern(dp.DnsName, WildcardOptions.IgnoreCase); + } - if (dp.Eku != null) + if (dp.Eku != null) + { + filter ??= new CertificateFilterInfo(); + filter.Eku = new List(); + foreach (var pattern in dp.Eku) { - filter ??= new CertificateFilterInfo(); - filter.Eku = new List(); - foreach (var pattern in dp.Eku) - { - filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase)); - } + filter.Eku.Add(new WildcardPattern(pattern, WildcardOptions.IgnoreCase)); } + } - if (dp.ExpiringInDays >= 0) - { - filter ??= new CertificateFilterInfo(); - filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays); - } + if (dp.ExpiringInDays >= 0) + { + filter ??= new CertificateFilterInfo(); + filter.Expiring = DateTime.Now.AddDays(dp.ExpiringInDays); + } - if (dp.SSLServerAuthentication) - { - filter ??= new CertificateFilterInfo(); - filter.SSLServerAuthentication = true; - } + if (dp.SSLServerAuthentication) + { + filter ??= new CertificateFilterInfo(); + filter.SSLServerAuthentication = true; } } @@ -3151,9 +3128,9 @@ public static bool ReadSendAsTrustedIssuerProperty(X509Certificate2 cert) int propSize = 0; // try to get the property // it is fine if fail for not there - if (Security.NativeMethods.CertGetCertificateContextProperty( + if (SMASecurity.NativeMethods.CertGetCertificateContextProperty( cert.Handle, - Security.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, + SMASecurity.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, IntPtr.Zero, ref propSize)) { @@ -3164,7 +3141,7 @@ public static bool ReadSendAsTrustedIssuerProperty(X509Certificate2 cert) { // if fail int error = Marshal.GetLastWin32Error(); - if (error != Security.NativeMethods.CRYPT_E_NOT_FOUND) + if (error != SMASecurity.NativeMethods.CRYPT_E_NOT_FOUND) { throw new System.ComponentModel.Win32Exception(error); } @@ -3183,7 +3160,7 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin if (DownLevelHelper.TrustedIssuerSupported()) { IntPtr propertyPtr = IntPtr.Zero; - Security.NativeMethods.CRYPT_DATA_BLOB dataBlob = new(); + SMASecurity.NativeMethods.CRYPT_DATA_BLOB dataBlob = new(); dataBlob.cbData = 0; dataBlob.pbData = IntPtr.Zero; X509Certificate certFromStore = null; @@ -3230,9 +3207,9 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin } // set property - if (!Security.NativeMethods.CertSetCertificateContextProperty( + if (!SMASecurity.NativeMethods.CertSetCertificateContextProperty( certFromStore != null ? certFromStore.Handle : cert.Handle, - Security.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, + SMASecurity.NativeMethods.CertPropertyId.CERT_SEND_AS_TRUSTED_ISSUER_PROP_ID, 0, propertyPtr)) { @@ -3249,7 +3226,7 @@ public static void WriteSendAsTrustedIssuerProperty(X509Certificate2 cert, strin } else { - Marshal.ThrowExceptionForHR(Security.NativeMethods.NTE_NOT_SUPPORTED); + Marshal.ThrowExceptionForHR(SMASecurity.NativeMethods.NTE_NOT_SUPPORTED); } } @@ -3313,17 +3290,13 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) foreach (X509Extension extension in cert.Extensions) { // Filter to the OID for EKU - if (extension.Oid.Value == "2.5.29.37") + if (extension.Oid.Value == "2.5.29.37" && extension is X509EnhancedKeyUsageExtension ext) { - X509EnhancedKeyUsageExtension ext = extension as X509EnhancedKeyUsageExtension; - if (ext != null) + OidCollection oids = ext.EnhancedKeyUsages; + foreach (Oid oid in oids) { - OidCollection oids = ext.EnhancedKeyUsages; - foreach (Oid oid in oids) - { - EnhancedKeyUsageRepresentation ekuString = new(oid.FriendlyName, oid.Value); - _ekuList.Add(ekuString); - } + EnhancedKeyUsageRepresentation ekuString = new(oid.FriendlyName, oid.Value); + _ekuList.Add(ekuString); } } } @@ -3336,20 +3309,30 @@ public EnhancedKeyUsageProperty(X509Certificate2 cert) public sealed class DnsNameProperty { private readonly List _dnsList = new(); - private readonly System.Globalization.IdnMapping idnMapping = new(); + private readonly IdnMapping idnMapping = new(); - private const string dnsNamePrefix = "DNS Name="; private const string distinguishedNamePrefix = "CN="; /// /// Get property of DnsNameList. /// - public List DnsNameList + public List DnsNameList => _dnsList; + + private DnsNameRepresentation GetDnsNameRepresentation(string dnsName) { - get + string unicodeName; + + try { - return _dnsList; + unicodeName = idnMapping.GetUnicode(dnsName); } + catch (ArgumentException) + { + // The name is not valid Punycode, assume it's valid ASCII. + unicodeName = dnsName; + } + + return new DnsNameRepresentation(dnsName, unicodeName); } /// @@ -3357,61 +3340,32 @@ public List DnsNameList /// public DnsNameProperty(X509Certificate2 cert) { - string name; - string unicodeName; - DnsNameRepresentation dnsName; _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, System.StringComparison.OrdinalIgnoreCase) && + if (cert.Subject.StartsWith(distinguishedNamePrefix, StringComparison.OrdinalIgnoreCase) && !cert.Subject.Contains(',')) { - name = cert.Subject.Substring(distinguishedNamePrefix.Length); - try - { - unicodeName = idnMapping.GetUnicode(name); - } - catch (System.ArgumentException) - { - // The name is not valid punyCode, assume it's valid ascii. - unicodeName = name; - } - - dnsName = new DnsNameRepresentation(name, unicodeName); + 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) { - // Filter to the OID for Subject Alternative Name - if (extension.Oid.Value == "2.5.29.17") + if (extension is X509SubjectAlternativeNameExtension sanExtension) { - string[] names = extension.Format(true).Split(Environment.NewLine); - foreach (string nameLine in names) + foreach (string dnsNameEntry in sanExtension.EnumerateDnsNames()) { - // Get the part after 'DNS Name=' - if (nameLine.StartsWith(dnsNamePrefix, System.StringComparison.InvariantCultureIgnoreCase)) - { - name = nameLine.Substring(dnsNamePrefix.Length); - try - { - unicodeName = idnMapping.GetUnicode(name); - } - catch (System.ArgumentException) - { - // The name is not valid punyCode, assume it's valid ascii. - unicodeName = name; - } - - dnsName = new DnsNameRepresentation(name, unicodeName); + 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); - } + // Only add the name if it is not the same as an existing name. + if (!_dnsList.Contains(dnsName)) + { + _dnsList.Add(dnsName); } } } @@ -3470,7 +3424,6 @@ internal static IntPtr GetOwnerWindow(PSHost host) return IntPtr.Zero; } #else - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr hWnd = IntPtr.Zero; private static bool firstRun = true; @@ -3486,12 +3439,12 @@ internal static IntPtr GetOwnerWindow(PSHost host) if (hWnd == IntPtr.Zero) { - hWnd = Security.NativeMethods.GetConsoleWindow(); + hWnd = SMASecurity.NativeMethods.GetConsoleWindow(); } if (hWnd == IntPtr.Zero) { - hWnd = Security.NativeMethods.GetDesktopWindow(); + hWnd = SMASecurity.NativeMethods.GetDesktopWindow(); } } } @@ -3505,8 +3458,7 @@ private static bool IsUIAllowed(PSHost host) return false; uint SessionId; - uint ProcessId = (uint)System.Diagnostics.Process.GetCurrentProcess().Id; - if (!Security.NativeMethods.ProcessIdToSessionId(ProcessId, out SessionId)) + if (!SMASecurity.NativeMethods.ProcessIdToSessionId((uint)Environment.ProcessId, out SessionId)) return false; if (SessionId == 0) @@ -3549,20 +3501,19 @@ internal static class Crypt32Helpers /// /// Get a list of store names at the specified location. /// - [ArchitectureSensitive] internal static List GetStoreNamesAtLocation(StoreLocation location) { - Security.NativeMethods.CertStoreFlags locationFlag = - Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + SMASecurity.NativeMethods.CertStoreFlags locationFlag = + SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; switch (location) { case StoreLocation.CurrentUser: - locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; + locationFlag = SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_CURRENT_USER; break; case StoreLocation.LocalMachine: - locationFlag = Security.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; + locationFlag = SMASecurity.NativeMethods.CertStoreFlags.CERT_SYSTEM_STORE_LOCAL_MACHINE; break; default: @@ -3570,7 +3521,7 @@ internal static List GetStoreNamesAtLocation(StoreLocation location) break; } - Security.NativeMethods.CertEnumSystemStoreCallBackProto callBack = new(CertEnumSystemStoreCallBack); + SMASecurity.NativeMethods.CertEnumSystemStoreCallBackProto callBack = new(CertEnumSystemStoreCallBack); // Return a new list to avoid synchronization issues. @@ -3579,7 +3530,7 @@ internal static List GetStoreNamesAtLocation(StoreLocation location) { storeNames.Clear(); - Security.NativeMethods.CertEnumSystemStore(locationFlag, IntPtr.Zero, + SMASecurity.NativeMethods.CertEnumSystemStore(locationFlag, IntPtr.Zero, IntPtr.Zero, callBack); foreach (string name in storeNames) { diff --git a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs index 9fde804d220..5e8e6d19b46 100644 --- a/src/Microsoft.PowerShell.Security/security/CmsCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CmsCommands.cs @@ -35,8 +35,8 @@ public CmsMessageRecipient[] To /// Gets or sets the content of the CMS Message. /// [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ParameterSetName = "ByContent")] - [AllowNull()] - [AllowEmptyString()] + [AllowNull] + [AllowEmptyString] public PSObject Content { get; @@ -202,8 +202,8 @@ 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()] + [AllowNull] + [AllowEmptyString] public string Content { get; @@ -308,8 +308,7 @@ protected override void EndProcessing() } // Extract out the bytes and Base64 decode them - int startIndex, endIndex; - byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out startIndex, out endIndex); + byte[] contentBytes = CmsUtils.RemoveAsciiArmor(actualContent, CmsUtils.BEGIN_CMS_SIGIL, CmsUtils.END_CMS_SIGIL, out int _, out int _); if (contentBytes == null) { ErrorRecord error = new( @@ -351,8 +350,8 @@ 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()] + [AllowNull] + [AllowEmptyString] public string Content { get; @@ -398,7 +397,7 @@ public string LiteralPath /// Determines whether to include the decrypted content in its original context, /// rather than just output the decrypted content itself. /// - [Parameter()] + [Parameter] public SwitchParameter IncludeContext { get; diff --git a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs index 33238c0ca6c..cc354ee1531 100644 --- a/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/CredentialCommands.cs @@ -9,7 +9,7 @@ namespace Microsoft.PowerShell.Commands /// /// Defines the implementation of the 'get-credential' cmdlet. /// The get-credential Cmdlet establishes a credential object called a - /// Msh credential, by pairing a given username with + /// PSCredential, by pairing a given username with /// a prompted password. That credential object can then be used for other /// operations involving security. /// @@ -33,7 +33,7 @@ public sealed class GetCredentialCommand : PSCmdlet /// [Parameter(Position = 0, ParameterSetName = credentialSet)] [ValidateNotNull] - [Credential()] + [Credential] public PSCredential Credential { get; set; } /// @@ -55,7 +55,7 @@ public string Message /// Gets and sets the user supplied username to be used while creating the PSCredential. /// [Parameter(Position = 0, Mandatory = false, ParameterSetName = messageSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string UserName { get { return _userName; } diff --git a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs index 6333541e242..29179a7046d 100644 --- a/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SecureStringCommands.cs @@ -239,7 +239,7 @@ public ConvertToSecureStringCommand() : base("ConvertTo-SecureString") { } /// Gets or sets the unsecured string to be imported. /// [Parameter(Position = 0, ValueFromPipeline = true, Mandatory = true)] - public String String + public string String { get { @@ -311,8 +311,7 @@ protected override void ProcessRecord() byte[] iv = null; // If this is a V2 package - if (String.IndexOf(SecureStringHelper.SecureStringExportHeader, - StringComparison.OrdinalIgnoreCase) == 0) + if (String.StartsWith(SecureStringHelper.SecureStringExportHeader, StringComparison.OrdinalIgnoreCase)) { try { @@ -326,7 +325,7 @@ protected override void ProcessRecord() // representation, then parse it into its components. byte[] inputBytes = Convert.FromBase64String(remainingData); string dataPackage = System.Text.Encoding.Unicode.GetString(inputBytes); - string[] dataElements = dataPackage.Split(Utils.Separators.Pipe); + string[] dataElements = dataPackage.Split('|'); if (dataElements.Length == 3) { @@ -359,8 +358,7 @@ protected override void ProcessRecord() } else { - importedString = new SecureString(); - foreach (char currentChar in String) { importedString.AppendChar(currentChar); } + importedString = SecureStringHelper.FromPlainTextString(String); } } catch (ArgumentException e) diff --git a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs index 5d5bb06b667..53a662ca4f9 100644 --- a/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs +++ b/src/Microsoft.PowerShell.Security/security/SignatureCommands.cs @@ -44,7 +44,7 @@ public string[] FilePath /// digital signature. /// [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = "ByLiteralPath")] - [Alias("PSPath")] + [Alias("PSPath", "LP")] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] LiteralPath { @@ -294,7 +294,7 @@ protected override Signature PerformAction(string filePath) /// protected override Signature PerformAction(string sourcePathOrExtension, byte[] content) { - return SignatureHelper.GetSignature(sourcePathOrExtension, System.Text.Encoding.Unicode.GetString(content)); + return SignatureHelper.GetSignature(sourcePathOrExtension, content); } } @@ -374,10 +374,7 @@ public string TimestampServer set { - if (value == null) - { - value = string.Empty; - } + value ??= string.Empty; _timestampServer = value; } @@ -404,12 +401,12 @@ public string HashAlgorithm } } - private string _hashAlgorithm = null; + private string _hashAlgorithm = "SHA256"; /// /// Property that sets force parameter. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get diff --git a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs index efd205e5769..6d602d2d99f 100644 --- a/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs +++ b/src/Microsoft.PowerShell.Security/security/certificateproviderexceptions.cs @@ -12,7 +12,6 @@ namespace Microsoft.PowerShell.Commands /// Defines the base class for exceptions thrown by the /// certificate provider when the specified item cannot be located. /// - [Serializable] public class CertificateProviderItemNotFoundException : SystemException { /// @@ -60,10 +59,11 @@ public CertificateProviderItemNotFoundException(string message, /// /// The streaming context. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CertificateProviderItemNotFoundException(SerializationInfo info, - StreamingContext context) - : base(info, context) + StreamingContext context) { + throw new NotSupportedException(); } /// @@ -83,7 +83,6 @@ internal CertificateProviderItemNotFoundException(Exception innerException) /// Defines the exception thrown by the certificate provider /// when the specified X509 certificate cannot be located. /// - [Serializable] public class CertificateNotFoundException : CertificateProviderItemNotFoundException { @@ -134,10 +133,11 @@ public CertificateNotFoundException(string message, /// /// The streaming context. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CertificateNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } /// @@ -157,7 +157,6 @@ internal CertificateNotFoundException(Exception innerException) /// Defines the exception thrown by the certificate provider /// when the specified X509 store cannot be located. /// - [Serializable] public class CertificateStoreNotFoundException : CertificateProviderItemNotFoundException { @@ -170,6 +169,23 @@ public CertificateStoreNotFoundException() { } + /// + /// 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. @@ -198,22 +214,6 @@ public CertificateStoreNotFoundException(string message, { } - /// - /// Initializes a new instance of the CertificateStoreNotFoundException - /// class with the specified serialization information, and context. - /// - /// - /// The serialization information. - /// - /// - /// The streaming context. - /// - protected CertificateStoreNotFoundException(SerializationInfo info, - StreamingContext context) - : base(info, context) - { - } - /// /// Initializes a new instance of the CertificateStoreNotFoundException /// class with the specified inner exception. @@ -231,7 +231,6 @@ internal CertificateStoreNotFoundException(Exception innerException) /// Defines the exception thrown by the certificate provider /// when the specified X509 store location cannot be located. /// - [Serializable] public class CertificateStoreLocationNotFoundException : CertificateProviderItemNotFoundException { @@ -244,6 +243,23 @@ public CertificateStoreLocationNotFoundException() { } + /// + /// 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. @@ -272,22 +288,6 @@ public CertificateStoreLocationNotFoundException(string message, { } - /// - /// Initializes a new instance of the CertificateStoreLocationNotFoundException - /// class with the specified serialization information, and context. - /// - /// - /// The serialization information. - /// - /// - /// The streaming context. - /// - protected CertificateStoreLocationNotFoundException(SerializationInfo info, - StreamingContext context) - : base(info, context) - { - } - /// /// Initializes a new instance of the CertificateStoreLocationNotFoundException /// class with the specified inner exception. diff --git a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs b/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs deleted file mode 100644 index efc4ec63daa..00000000000 --- a/src/Microsoft.PowerShell.Security/singleshell/installer/MshSecurityMshSnapin.cs +++ /dev/null @@ -1,90 +0,0 @@ -// 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 -{ - /// - /// MshSecurityMshSnapin (or MshSecurityMshSnapinInstaller) is a class for facilitating registry - /// of necessary information for monad security mshsnapin. - /// - /// This class will be built with monad security dll. - /// - [RunInstaller(true)] - public sealed class PSSecurityPSSnapIn : PSSnapIn - { - /// - /// Create an instance of this class. - /// - public PSSecurityPSSnapIn() - : base() - { - } - - /// - /// Get name of this mshsnapin. - /// - public override string Name - { - get - { - return RegistryStrings.SecurityMshSnapinName; - } - } - - /// - /// Get the default vendor string for this mshsnapin. - /// - 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 mshsnapin. - /// - 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/src/Microsoft.WSMan.Management/ConfigProvider.cs b/src/Microsoft.WSMan.Management/ConfigProvider.cs index 9e3d9bd05b1..55141379faa 100644 --- a/src/Microsoft.WSMan.Management/ConfigProvider.cs +++ b/src/Microsoft.WSMan.Management/ConfigProvider.cs @@ -62,7 +62,7 @@ public sealed class WSManConfigProvider : NavigationCmdletProvider, ICmdletProvi string ICmdletProviderSupportsHelp.GetHelpMaml(string helpItemName, string path) { // Get the leaf node from the path for which help is requested. - int ChildIndex = path.LastIndexOf("\\", StringComparison.OrdinalIgnoreCase); + int ChildIndex = path.LastIndexOf('\\'); if (ChildIndex == -1) { // Means we are at host level, where no new-item is supported. Return empty string. @@ -617,7 +617,10 @@ protected override void GetItem(string path) SessionObjCache.TryGetValue(host, out sessionobj); XmlDocument xmlResource = FindResourceValue(sessionobj, uri, null); - if (xmlResource == null) { return; } + if (xmlResource == null) + { + return; + } // if endswith '\', removes it. if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) @@ -1021,20 +1024,15 @@ protected override void SetItem(string path, object value) strPathChk = strPathChk + WSManStringLiterals.containerPlugin + WSManStringLiterals.DefaultPathSeparator; if (path.EndsWith(strPathChk + currentpluginname, StringComparison.OrdinalIgnoreCase)) { - if (WSManStringLiterals.ConfigRunAsUserName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) + if (WSManStringLiterals.ConfigRunAsUserName.Equals(ChildName, StringComparison.OrdinalIgnoreCase) && value is PSCredential runAsCredentials) { - PSCredential runAsCredentials = value as PSCredential; - - if (runAsCredentials != null) - { - // UserName - value = runAsCredentials.UserName; + // UserName + value = runAsCredentials.UserName; - pluginConfiguration.UpdateOneConfiguration( - ".", - WSManStringLiterals.ConfigRunAsPasswordName, - GetStringFromSecureString(runAsCredentials.Password)); - } + pluginConfiguration.UpdateOneConfiguration( + ".", + WSManStringLiterals.ConfigRunAsPasswordName, + GetStringFromSecureString(runAsCredentials.Password)); } if (WSManStringLiterals.ConfigRunAsPasswordName.Equals(ChildName, StringComparison.OrdinalIgnoreCase)) @@ -1301,8 +1299,7 @@ protected override void SetItem(string path, object value) } } - WSManProviderSetItemDynamicParameters dynParams = DynamicParameters as WSManProviderSetItemDynamicParameters; - if (dynParams != null) + if (DynamicParameters is WSManProviderSetItemDynamicParameters dynParams) { if (dynParams.Concatenate) { @@ -1965,9 +1962,8 @@ protected override object NewItemDynamicParameters(string path, string itemTypeN private void NewItemCreateComputerConnection(string Name) { helper = new WSManHelper(this); - WSManProviderNewItemComputerParameters dynParams = DynamicParameters as WSManProviderNewItemComputerParameters; string parametersetName = "ComputerName"; - if (dynParams != null) + if (DynamicParameters is WSManProviderNewItemComputerParameters dynParams) { if (dynParams.ConnectionURI != null) { @@ -2064,8 +2060,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h // to create a new plugin if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { - WSManProviderNewItemPluginParameters niParams = DynamicParameters as WSManProviderNewItemPluginParameters; - if (niParams != null) + if (DynamicParameters is WSManProviderNewItemPluginParameters niParams) { if (string.IsNullOrEmpty(niParams.File)) { @@ -2155,8 +2150,7 @@ private void NewItemPluginOrPluginChild(object sessionobj, string path, string h strPathChk += WSManStringLiterals.containerResources; if (path.EndsWith(strPathChk, StringComparison.OrdinalIgnoreCase)) { - WSManProviderNewItemResourceParameters niParams = DynamicParameters as WSManProviderNewItemResourceParameters; - if (niParams != null) + if (DynamicParameters is WSManProviderNewItemResourceParameters niParams) { mshObj.Properties.Add(new PSNoteProperty("Resource", niParams.ResourceUri)); mshObj.Properties.Add(new PSNoteProperty("Capability", niParams.Capability)); @@ -3413,10 +3407,7 @@ private static string NormalizePath(string path, string host) /// private PSObject GetItemValue(string path) { - if (string.IsNullOrEmpty(path) || (path.Length == 0)) - { - throw new ArgumentNullException(path); - } + ArgumentException.ThrowIfNullOrEmpty(path); // if endswith '\', removes it. if (path.EndsWith(WSManStringLiterals.DefaultPathSeparator.ToString(), StringComparison.OrdinalIgnoreCase)) @@ -5059,9 +5050,9 @@ private static ArrayList ProcessPluginSecurityLevel(ArrayList arrSecurity, XmlDo /// Resource URI for the XML. /// Name of the Host. /// Type of Operation. - ///List of Resources. - ///List of Securities - ///List of initialization parameters. + /// 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) { @@ -5193,10 +5184,9 @@ private object ValidateAndGetUserObject(string configurationName, object value) /// Value to append. private static string GetStringFromSecureString(object propertyValue) { - SecureString value = propertyValue as SecureString; string passwordValueToAdd = string.Empty; - if (value != null) + if (propertyValue is SecureString value) { IntPtr ptr = Marshal.SecureStringToBSTR(value); passwordValueToAdd = Marshal.PtrToStringAuto(ptr); @@ -5607,15 +5597,15 @@ public string ApplicationName [Parameter] [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = "nameSet")] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "UseSSL". @@ -5766,7 +5756,7 @@ public string File /// Parameter for RunAs credentials for a Plugin. /// [ValidateNotNull] - [Parameter()] + [Parameter] public PSCredential RunAsCredential { get { return this.runAsCredentials; } @@ -5779,7 +5769,7 @@ public PSCredential RunAsCredential /// /// Parameter for Plugin Host Process configuration (Shared or Separate). /// - [Parameter()] + [Parameter] public SwitchParameter UseSharedProcess { get { return this.sharedHost; } @@ -5792,7 +5782,7 @@ public SwitchParameter UseSharedProcess /// /// Parameter for Auto Restart configuration for Plugin. /// - [Parameter()] + [Parameter] public SwitchParameter AutoRestart { get { return this.autoRestart; } @@ -5805,7 +5795,7 @@ public SwitchParameter AutoRestart /// /// Parameter for Idle timeout for HostProcess. /// - [Parameter()] + [Parameter] public uint? ProcessIdleTimeoutSec { get @@ -5946,7 +5936,7 @@ public string Issuer /// /// Parameter Subject. /// - [Parameter()] + [Parameter] [ValidateNotNullOrEmpty] public string Subject { @@ -6191,7 +6181,7 @@ public class WSManProviderSetItemDynamicParameters /// /// Parameter Concatenate. /// - [Parameter()] + [Parameter] public SwitchParameter Concatenate { get { return _concatenate; } diff --git a/src/Microsoft.WSMan.Management/CredSSP.cs b/src/Microsoft.WSMan.Management/CredSSP.cs index cd5e6d3fc4d..a8457ab5bc2 100644 --- a/src/Microsoft.WSMan.Management/CredSSP.cs +++ b/src/Microsoft.WSMan.Management/CredSSP.cs @@ -200,7 +200,8 @@ private void DisableServerSideSettings() return; } - string inputXml = string.Format(CultureInfo.InvariantCulture, + string inputXml = string.Format( + CultureInfo.InvariantCulture, @"false", helper.Service_CredSSP_XMLNmsp); @@ -389,6 +390,7 @@ protected override void BeginProcessing() /// 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*/ @@ -411,7 +413,7 @@ public string[] DelegateComputer /// /// Property that sets force parameter. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get { return force; } @@ -512,6 +514,7 @@ private void EnableClientSideSettings() try { XmlDocument xmldoc = new XmlDocument(); + // push the xml string with credssp enabled xmldoc.LoadXml(m_SessionObj.Put(helper.CredSSP_RUri, newxmlcontent, 0)); @@ -591,9 +594,11 @@ private void EnableServerSideSettings() try { XmlDocument xmldoc = new XmlDocument(); - string newxmlcontent = string.Format(CultureInfo.InvariantCulture, + 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); @@ -736,6 +741,7 @@ private void UpdateGPORegistrySettings(string applicationname, string[] delegate [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 diff --git a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs index 0129554c30b..3182c04c535 100644 --- a/src/Microsoft.WSMan.Management/CurrentConfigurations.cs +++ b/src/Microsoft.WSMan.Management/CurrentConfigurations.cs @@ -11,7 +11,7 @@ namespace Microsoft.WSMan.Management /// Class that queries the server and gets current configurations. /// Also provides a generic way to update the configurations. /// - internal class CurrentConfigurations + internal sealed class CurrentConfigurations { /// /// Prefix used to add NameSpace of root element to namespace manager. @@ -61,10 +61,7 @@ public XmlDocument RootDocument /// Current server session. public CurrentConfigurations(IWSManSession serverSession) { - if (serverSession == null) - { - throw new ArgumentNullException(nameof(serverSession)); - } + ArgumentNullException.ThrowIfNull(serverSession); this.rootDocument = new XmlDocument(); this.serverSession = serverSession; @@ -79,10 +76,7 @@ public CurrentConfigurations(IWSManSession serverSession) /// False, if operation failed. public bool RefreshCurrentConfiguration(string responseOfGet) { - if (string.IsNullOrEmpty(responseOfGet)) - { - throw new ArgumentNullException(nameof(responseOfGet)); - } + ArgumentException.ThrowIfNullOrEmpty(responseOfGet); this.rootDocument.LoadXml(responseOfGet); this.documentElement = this.rootDocument.DocumentElement; @@ -98,13 +92,10 @@ public bool RefreshCurrentConfiguration(string responseOfGet) /// Issues a PUT request with the ResourceUri provided. /// /// Resource URI to use. - /// False, if operation is not succesful. + /// False, if operation is not successful. public void PutConfigurationOnServer(string resourceUri) { - if (string.IsNullOrEmpty(resourceUri)) - { - throw new ArgumentNullException(nameof(resourceUri)); - } + ArgumentException.ThrowIfNullOrEmpty(resourceUri); this.serverSession.Put(resourceUri, this.rootDocument.InnerXml, 0); } @@ -117,10 +108,7 @@ public void PutConfigurationOnServer(string resourceUri) /// Path with namespace to the node from Root element. Must not end with '/'. public void RemoveOneConfiguration(string pathToNodeFromRoot) { - if (pathToNodeFromRoot == null) - { - throw new ArgumentNullException(nameof(pathToNodeFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); XmlNode nodeToRemove = this.documentElement.SelectSingleNode( @@ -150,20 +138,9 @@ public void RemoveOneConfiguration(string pathToNodeFromRoot) /// Value of the configurations. public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurationName, string configurationValue) { - if (pathToNodeFromRoot == null) - { - throw new ArgumentNullException(nameof(pathToNodeFromRoot)); - } - - if (string.IsNullOrEmpty(configurationName)) - { - throw new ArgumentNullException(nameof(configurationName)); - } - - if (configurationValue == null) - { - throw new ArgumentNullException(nameof(configurationValue)); - } + ArgumentNullException.ThrowIfNull(pathToNodeFromRoot); + ArgumentException.ThrowIfNullOrEmpty(configurationName); + ArgumentNullException.ThrowIfNull(configurationValue); XmlNode nodeToUpdate = this.documentElement.SelectSingleNode( @@ -195,10 +172,7 @@ public void UpdateOneConfiguration(string pathToNodeFromRoot, string configurati /// Value of the Node, or Null if no node present. public string GetOneConfiguration(string pathFromRoot) { - if (pathFromRoot == null) - { - throw new ArgumentNullException(nameof(pathFromRoot)); - } + ArgumentNullException.ThrowIfNull(pathFromRoot); XmlNode requiredNode = this.documentElement.SelectSingleNode( diff --git a/src/Microsoft.WSMan.Management/Interop.cs b/src/Microsoft.WSMan.Management/Interop.cs index 6685770b0ef..3abb938a572 100644 --- a/src/Microsoft.WSMan.Management/Interop.cs +++ b/src/Microsoft.WSMan.Management/Interop.cs @@ -173,7 +173,7 @@ public enum AuthenticationMechanism [ComImport] [TypeLibType((short)4304)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -255,7 +255,7 @@ string Error [ComImport] [TypeLibType((short)4288)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -312,7 +312,7 @@ string Password [ComImport] [TypeLibType((short)4288)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -336,7 +336,7 @@ string CertificateThumbprint [ComImport] [TypeLibType((short)4288)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -386,7 +386,7 @@ void SetProxy(int accessType, [ComImport] [TypeLibType((short)4288)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -450,7 +450,7 @@ string Error [TypeLibType((short)4304)] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix")] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -706,7 +706,7 @@ string Error [ComImport] [TypeLibType((short)4288)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -734,18 +734,19 @@ public interface IWSManResourceLocator [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] string ResourceUri { - // IDL: HRESULT resourceUri ([out, retval] BSTR* ReturnValue); + // 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)] - [return: MarshalAs(UnmanagedType.BStr)] - get; + set; - // IDL: HRESULT resourceUri (BSTR value); + // IDL: HRESULT resourceUri ([out, retval] BSTR* ReturnValue); [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "resource")] [SuppressMessage("Microsoft.Design", "CA1056:UriPropertiesShouldNotBeStrings")] [DispId(1)] - set; + [return: MarshalAs(UnmanagedType.BStr)] + get; } /// AddSelector method of IWSManResourceLocator interface. Add selector to resource locator @@ -818,14 +819,16 @@ string FragmentDialect int MustUnderstandOptions { - // IDL: HRESULT MustUnderstandOptions ([out, retval] long* ReturnValue); - - [DispId(7)] - get; // 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 @@ -860,7 +863,7 @@ string Error [ComImport] [TypeLibType((short)4288)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif @@ -1005,7 +1008,7 @@ int Timeout [ComImport] [TypeLibType((short)400)] #if CORECLR - [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] + [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] #else [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIDispatch)] #endif diff --git a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs index 36f65e52705..da92a680ab3 100644 --- a/src/Microsoft.WSMan.Management/InvokeWSManAction.cs +++ b/src/Microsoft.WSMan.Management/InvokeWSManAction.cs @@ -24,6 +24,7 @@ namespace Microsoft.WSMan.Management /// -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 { /// @@ -146,15 +147,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "SelectorSet". diff --git a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj index 84fc158cc0f..5dc59c5ecef 100644 --- a/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj +++ b/src/Microsoft.WSMan.Management/Microsoft.WSMan.Management.csproj @@ -10,15 +10,13 @@ - + - - $(DefineConstants);CORECLR - - - + + $(RootNamespace).resources.%(Filename) + diff --git a/src/Microsoft.WSMan.Management/NewWSManSession.cs b/src/Microsoft.WSMan.Management/NewWSManSession.cs index 30959f3ced5..09b22af9924 100644 --- a/src/Microsoft.WSMan.Management/NewWSManSession.cs +++ b/src/Microsoft.WSMan.Management/NewWSManSession.cs @@ -26,6 +26,7 @@ namespace Microsoft.WSMan.Management /// Connect-WSMan. /// [Cmdlet(VerbsCommon.New, "WSManSessionOption", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2096845")] + [OutputType(typeof(SessionOption))] public class NewWSManSessionOptionCommand : PSCmdlet { /// @@ -170,8 +171,8 @@ public SwitchParameter SkipRevocationCheck /// [Parameter] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SPN")] - [ValidateRange(0, Int32.MaxValue)] - public Int32 SPNPort + [ValidateRange(0, int.MaxValue)] + public int SPNPort { get { @@ -184,7 +185,7 @@ public Int32 SPNPort } } - private Int32 spnport; + private int spnport; /// /// The following is the definition of the input parameter "Timeout". @@ -192,8 +193,8 @@ public Int32 SPNPort /// [Parameter] [Alias("OperationTimeoutMSec")] - [ValidateRange(0, Int32.MaxValue)] - public Int32 OperationTimeout + [ValidateRange(0, int.MaxValue)] + public int OperationTimeout { get { @@ -206,7 +207,7 @@ public Int32 OperationTimeout } } - private Int32 operationtimeout; + private int operationtimeout; /// /// The following is the definition of the input parameter "UnEncrypted". diff --git a/src/Microsoft.WSMan.Management/PingWSMan.cs b/src/Microsoft.WSMan.Management/PingWSMan.cs index a04167a0f1b..88b443a6ef0 100644 --- a/src/Microsoft.WSMan.Management/PingWSMan.cs +++ b/src/Microsoft.WSMan.Management/PingWSMan.cs @@ -23,6 +23,7 @@ namespace Microsoft.WSMan.Management /// service is running. /// [Cmdlet(VerbsDiagnostic.Test, "WSMan", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=2097114")] + [OutputType(typeof(XmlElement))] public class TestWSManCommand : AuthenticatingWSManCommand, IDisposable { /// @@ -95,15 +96,15 @@ public override AuthenticationMechanism Authentication /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "UseSSL". diff --git a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs index c318ea76477..9ad9e39c332 100644 --- a/src/Microsoft.WSMan.Management/Set-QuickConfig.cs +++ b/src/Microsoft.WSMan.Management/Set-QuickConfig.cs @@ -30,6 +30,7 @@ namespace Microsoft.WSMan.Management /// 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 { /// @@ -55,7 +56,7 @@ public SwitchParameter UseSSL /// Property that sets force parameter. This will allow /// configuring WinRM without prompting the user. /// - [Parameter()] + [Parameter] public SwitchParameter Force { get { return force; } @@ -68,7 +69,7 @@ public SwitchParameter Force /// /// Property that will allow configuring WinRM with Public profile exception enabled. /// - [Parameter()] + [Parameter] public SwitchParameter SkipNetworkProfileCheck { get { return skipNetworkProfileCheck; } diff --git a/src/Microsoft.WSMan.Management/WSManConnections.cs b/src/Microsoft.WSMan.Management/WSManConnections.cs index 85c5d1ba0ae..cac5196740f 100644 --- a/src/Microsoft.WSMan.Management/WSManConnections.cs +++ b/src/Microsoft.WSMan.Management/WSManConnections.cs @@ -213,15 +213,15 @@ public Hashtable OptionSet [Parameter] [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = "ComputerName")] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "SessionOption". @@ -360,10 +360,7 @@ public string ComputerName protected override void BeginProcessing() { WSManHelper helper = new WSManHelper(this); - if (computername == null) - { - computername = "localhost"; - } + computername ??= "localhost"; if (this.SessionState.Path.CurrentProviderLocation(WSManStringLiterals.rootpath).Path.StartsWith(WSManStringLiterals.rootpath + ":" + WSManStringLiterals.DefaultPathSeparator + computername, StringComparison.OrdinalIgnoreCase)) { diff --git a/src/Microsoft.WSMan.Management/WSManInstance.cs b/src/Microsoft.WSMan.Management/WSManInstance.cs index 733316c785f..c96b002123d 100644 --- a/src/Microsoft.WSMan.Management/WSManInstance.cs +++ b/src/Microsoft.WSMan.Management/WSManInstance.cs @@ -29,6 +29,7 @@ namespace Microsoft.WSMan.Management /// -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 @@ -247,7 +248,7 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "Enumerate")] [Parameter(ParameterSetName = "GetInstance")] - public Int32 Port + public int Port { get { @@ -260,7 +261,7 @@ public Int32 Port } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "Associations". @@ -325,7 +326,7 @@ public Uri ResourceURI [Parameter(ParameterSetName = "Enumerate")] [ValidateNotNullOrEmpty] - [ValidateSetAttribute(new string[] { "object", "epr", "objectandepr" })] + [ValidateSet(new string[] { "object", "epr", "objectandepr" })] [Alias("RT")] public string ReturnType { @@ -685,6 +686,7 @@ protected override void EndProcessing() /// -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 @@ -822,15 +824,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "ResourceURI". @@ -1146,15 +1148,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "ResourceURI". @@ -1324,6 +1326,7 @@ protected override void ProcessRecord() /// 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 { /// @@ -1428,15 +1431,15 @@ public Hashtable OptionSet /// [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] - [ValidateRange(1, Int32.MaxValue)] - public Int32 Port + [ValidateRange(1, int.MaxValue)] + public int Port { get { return port; } set { port = value; } } - private Int32 port = 0; + private int port = 0; /// /// The following is the definition of the input parameter "ResourceURI". diff --git a/src/Microsoft.WSMan.Management/WsManHelper.cs b/src/Microsoft.WSMan.Management/WsManHelper.cs index 000cb871abb..9249c7f4b88 100644 --- a/src/Microsoft.WSMan.Management/WsManHelper.cs +++ b/src/Microsoft.WSMan.Management/WsManHelper.cs @@ -22,7 +22,7 @@ namespace Microsoft.WSMan.Management { [SuppressMessage("Microsoft.Design", "CA1054:UriParametersShouldNotBeStrings", MessageId = "0#")] - internal class WSManHelper + internal sealed class WSManHelper { // regular expressions private const string PTRN_URI_LAST = @"([a-z_][-a-z0-9._]*)$"; @@ -89,7 +89,7 @@ internal class WSManHelper // // // Below class is just a static container which would release sessions in case this DLL is unloaded. - internal class Sessions + internal sealed class Sessions { /// /// Dictionary object to store the connection. @@ -178,15 +178,8 @@ private static string FormatResourceMsgFromResourcetextS( string resourceName, object[] args) { - if (resourceManager == null) - { - throw new ArgumentNullException(nameof(resourceManager)); - } - - if (string.IsNullOrEmpty(resourceName)) - { - throw new ArgumentNullException(nameof(resourceName)); - } + ArgumentNullException.ThrowIfNull(resourceManager); + ArgumentException.ThrowIfNullOrEmpty(resourceName); string template = resourceManager.GetString(resourceName); @@ -370,17 +363,8 @@ internal string ReadFile(string path) } finally { - if (_sr != null) - { - // _sr.Close(); - _sr.Dispose(); - } - - if (_fs != null) - { - // _fs.Close(); - _fs.Dispose(); - } + _sr?.Dispose(); + _fs?.Dispose(); } return strOut; @@ -627,7 +611,7 @@ internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism aut if ((credential != null) && (certificateThumbprint != null)) { string message = FormatResourceMsgFromResourcetextS( - "AmbiguosAuthentication", + "AmbiguousAuthentication", "CertificateThumbPrint", "credential"); throw new InvalidOperationException(message); @@ -638,7 +622,7 @@ internal static void ValidateSpecifiedAuthentication(AuthenticationMechanism aut (certificateThumbprint != null)) { string message = FormatResourceMsgFromResourcetextS( - "AmbiguosAuthentication", + "AmbiguousAuthentication", "CertificateThumbPrint", authentication.ToString()); throw new InvalidOperationException(message); @@ -1078,13 +1062,10 @@ internal static void LoadResourceData() { try { - string filepath = System.Environment.ExpandEnvironmentVariables("%Windir%") + "\\System32\\Winrm\\" + -#if CORECLR - "0409" /* TODO: don't assume it is always English on CSS? */ -#else - string.Concat("0", string.Format(CultureInfo.CurrentCulture, "{0:x2}", checked((uint)CultureInfo.CurrentUICulture.LCID))) -#endif - + "\\" + "winrm.ini"; + 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); diff --git a/src/Microsoft.WSMan.Management/WsManSnapin.cs b/src/Microsoft.WSMan.Management/WsManSnapin.cs deleted file mode 100644 index 4093caf12db..00000000000 --- a/src/Microsoft.WSMan.Management/WsManSnapin.cs +++ /dev/null @@ -1,92 +0,0 @@ -// 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/src/Microsoft.WSMan.Management/resources/WsManResources.resx b/src/Microsoft.WSMan.Management/resources/WsManResources.resx index c55aab1132f..0c33749488b 100644 --- a/src/Microsoft.WSMan.Management/resources/WsManResources.resx +++ b/src/Microsoft.WSMan.Management/resources/WsManResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -191,7 +191,7 @@ Do you want to enable CredSSP authentication? 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. diff --git a/src/Microsoft.WSMan.Management/resources/WsManResources.txt b/src/Microsoft.WSMan.Management/resources/WsManResources.txt index 50cf1bf1fe5..10702e5ccea 100644 --- a/src/Microsoft.WSMan.Management/resources/WsManResources.txt +++ b/src/Microsoft.WSMan.Management/resources/WsManResources.txt @@ -56,7 +56,7 @@ CredSSPServiceConfigured=This computer is configured to receive credentials from 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? -AmbiguosAuthentication=A {0} cannot be specified when {1} is specified. +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. diff --git a/src/Microsoft.WSMan.Management/resources/cs/WsManResources.cs.resx b/src/Microsoft.WSMan.Management/resources/cs/WsManResources.cs.resx new file mode 100644 index 00000000000..dc579cf1106 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/cs/WsManResources.cs.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Tento příkaz nelze použít, protože soubor neexistuje. Zkontrolujte, zda soubor existuje, a spusťte příkaz znovu. + + + Vytvoří novou položku ClientCertificate. + + + Tento příkaz nelze spustit, protože identifikátor URI připojení nemá správný formát. Zkontrolujte prosím identifikátor URI připojení a spusťte příkaz znovu. + + + Ověřování CredSSP umožňuje odeslat přihlašovací údaje uživatele z tohoto počítače do vzdáleného počítače. Pokud použijete ověřování CredSSP pro připojení ke škodlivému nebo napadenému počítači, bude mít tento počítač přístup k vašemu uživatelskému jménu a heslu. Další informace najdete v tématu nápovědy Enable-WSManCredSSP. +Chcete povolit ověřování CredSSP? + + + Vytvoří novou položku naslouchacího procesu. + + + Tento příkaz upraví nastavení zabezpečení prostředku v následujícím modulu plug-in služby WinRM: {0}. +Chcete pokračovat? + + + Spuštěním rutiny Set-Item s nastavením konfigurace WinRM {0} aktualizujte hodnotu na {1}. + + + Tento příkaz nelze spustit, protože toto nastavení nelze povolit. + + + Tento příkaz vytvoří novou položku naslouchacího procesu. + +Chcete pokračovat? + + + Přístup je odepřený. Tuto rutinu musíte spustit z procesu se zvýšenými oprávněními. + + + Tento příkaz nelze použít, protože kořen jednotky WsMan není v této verzi systému Windows podporován. + + + Spustit službu WinRM + + + Ověřování CredSSP umožňuje serveru přijímat přihlašovací údaje uživatele ze vzdáleného počítače. Pokud na serveru povolíte ověřování CredSSP, bude mít server přístup k uživatelskému jménu a heslu klientského počítače, pokud je klientský počítač odešle. Další informace najdete v tématu nápovědy Enable-WSManCredSSP. +Chcete povolit ověřování CredSSP? + + + Rychlá konfigurace WinRM + + + Microsoft + + + Tento příkaz nemůže nastavit vstupní hodnotu, protože tyto hodnoty představují primární klíče nebo položky kontejneru objektu prostředku. Změňte vstupní hodnotu a spusťte příkaz znovu. + + + Konfigurace ověřování CredSSP pro službu WS-Management + + + Nastavit hodnotu položky + + + Typ System.Object[] nelze převést na typ System.String vyžadovaný parametrem. Zadaná metoda není podporována. + + + Tento počítač není nakonfigurován pro příjem přihlašovacích údajů ze vzdáleného klientského počítače. + + + Tento příkaz nelze použít z aktuální cesty. Přejděte do kořenové cesty zprostředkovatele pomocí cd\ a spusťte příkaz znovu. + + + Tato rutina PowerShellu není k dispozici pro systémy Windows XP a Windows Server 2003. + + + Tento příkaz nelze použít, protože parametr odpovídá netextové vlastnosti v ResourceURI. Zkontrolujte vstupní parametry a spusťte příkaz znovu. + + + Parametr {0} nelze zadat, pokud je zadán parametr {1}. + + + Klient WinRM nemůže dokončit operaci. Zkontrolujte, zda je název počítače platný. + + + Parametr {0} je povinný, pokud je hodnota parametru {1} rovna {2}. + + + Tento příkaz nelze použít, protože není zadána hodnota parametru. Zkontrolujte hodnotu a spusťte příkaz znovu. + + + Tento příkaz nelze použít, protože cesta neexistuje. Zkontrolujte, zda cesta existuje, a spusťte příkaz znovu. + + + Konfigurace zabezpečení modulu plug-in WinRM. + + + Tento příkaz nelze použít v aktuální cestě, protože tato rutina není na této úrovni cesty zprostředkovatele podporována. + + + Tento počítač není nakonfigurován tak, aby umožňoval delegování nových přihlašovacích údajů. + + + Provedené změny konfigurace se projeví až po restartování služby WinRM. Chcete-li restartovat službu WinRM, spusťte následující příkaz: Restart-Service winrm. + + + Spuštění příkazu Set-WSManQuickConfig má významné důsledky pro zabezpečení, protože na tomto počítači povoluje vzdálenou správu prostřednictvím služby WinRM. +Tento příkaz: + 1. Zkontroluje, jestli je služba WinRM spuštěná. Pokud služba WinRM není spuštěná, spustí se. + 2. Nastaví typ spouštění služby WinRM na Automaticky. + 3. Vytvoří naslouchací proces pro příjem požadavků na libovolné IP adrese. Ve výchozím nastavení se používá přenos HTTP. + 4. Povolí výjimku brány firewall pro provoz služby WS-Management. + 5. Povolí ověřování služby Kerberos a Negotiate. +Chcete na tomto počítači povolit vzdálenou správu prostřednictvím služby WinRM? + + + Hodnotu RunAsPassword nelze nastavit, pokud není nastavena hodnota RunAsUser. Nastavte hodnoty RunAsUser a RunAsPassword v PowerShellu voláním rutiny Set-Item s hodnotou atributu -Path nastavenou na hodnotu RunAsUser. + + + Aktualizovaná konfigurace může ovlivnit fungování modulů plug-in, jejichž hodnota kvóty pro jednotlivé moduly plug-in je větší než {0}. Ověřte konfiguraci všech zaregistrovaných modulů plug-in a změňte hodnoty kvót pro jednotlivé moduly plug-in u dotčených modulů plug-in. + + + Tento příkaz nastaví hodnotu položky. + +Chcete pokračovat? + + + Tento počítač je nakonfigurován tak, aby umožňoval delegování nových přihlašovacích údajů na následující cíle: + + + Kořen úložiště konfigurace WsMan + + + Tento příkaz nelze spustit, protože služba WinRM není spuštěná. + + + Tento příkaz nelze použít, protože kořenová cesta neexistuje. Zkontrolujte kořenovou cestu a spusťte příkaz znovu. + + + Tento příkaz nelze použít v aktuální cestě, protože rutina Remove-Item není na této úrovni cesty zprostředkovatele podporována. + + + Tento příkaz upraví seznam TrustedHosts klienta WinRM. Počítače v seznamu TrustedHosts nemusí být ověřeny. Klient může do těchto počítačů odesílat přihlašovací údaje. Opravdu chcete tento seznam změnit? + + + Tento příkaz upraví nastavení RootSDDL služby WinRM. RootSDDL ukládá výchozí nastavení zabezpečení pro všechny prostředky zabezpečitelné pomocí služby WinRM, které neurčují vlastní deskriptor SDDL. Změna SDDL může ovlivnit zabezpečení mnoha prostředků služby WinRM. Opravdu chcete změnit tato výchozí nastavení? + + + Tento příkaz nelze použít bez přihlašovacích údajů, protože se používá základní ověřování nebo ověřování hodnotou hash. Pomocí parametru Credentials zadejte hodnotu a spusťte příkaz. + + + Aktualizovaná konfigurace se projeví pouze v případě, že je menší než nebo rovna hodnotě globální kvóty {0}. Ověřte hodnotu globální kvóty pomocí rutiny PowerShellu Get-Item {0}. + + + Tento příkaz nelze spustit, protože toto nastavení nelze zakázat. + + + Hodnotu prvku {0} v cestě {1} se nepodařilo najít. + + + Tento příkaz nelze použít bez základního ověřování nebo ověřování hodnotou hash, protože jsou zadány přihlašovací údaje. Použijte základní ověřování nebo ověřování hodnotou hash a spusťte příkaz. + + + Konfigurace zabezpečení WinRM + + + Tento příkaz nelze použít v aktuální cestě, protože rutina New-Item není na této úrovni cesty zprostředkovatele podporována. + + + Tento příkaz nelze použít, protože konfigurace je poškozená. Chcete-li obnovit výchozí konfiguraci, spusťte příkaz WinRM invoke Restore WinRM/config. + + + Tento příkaz nelze použít, protože typ hodnoty parametru je neplatný. Konfigurace {0} očekává hodnotu typu {1}. Ověřte správnost hodnoty a zkuste to znovu. + + + Služba WinRM momentálně není spuštěná. Spuštěním tohoto příkazu se spustí služba WinRM. + +Chcete pokračovat? + + + Tento příkaz nelze použít, protože parametr neodpovídá žádné vlastnosti v ResourceURI. Zkontrolujte vstupní parametry a spusťte příkaz znovu. + + + Tento počítač je nakonfigurován pro příjem přihlašovacích údajů ze vzdáleného klientského počítače. + + + Parametr {0} nelze použít, pokud je hodnota parametru {1} rovna {2}. Parametr {0} lze použít pouze v případě, že hodnota parametru {1} je {3}. + + + Provedené změny konfigurace se projeví až po restartování služby WinRM na počítači {0}. + + + Tento příkaz nelze použít z aktuální cesty. Přejděte do kořenové cesty zprostředkovatele pomocí cd\ a spusťte příkaz znovu. + + + Tento modul snap-in PowerShellu obsahuje rutiny (například Get-WSManInstance a Set-WSManInstance), které hostitel PowerShellu používá ke správě operací WSMan. + + + Tento příkaz nelze použít k odebrání počítače localhost, protože bude vždy připojený. Zadejte jiný připojený počítač a spusťte příkaz znovu. + + + Tento příkaz vytvoří novou položku ClientCertificate. + +Chcete pokračovat? + + + Hodnotu RunAsPassword nelze odebrat. Odeberte hodnoty RunAsUser a RunAsPassword v PowerShellu voláním rutiny Clear-Item s hodnotou atributu -Path nastavenou na hodnotu RunAsUser. + + + Jednotku se zadaným kořenovým adresářem nejde vytvořit. Kořenová cesta neexistuje. + + + Tento příkaz nelze použít, protože parametr odpovídá více vlastnostem v ResourceURI. Zkontrolujte vstupní parametry a spusťte příkaz znovu. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/de/WsManResources.de.resx b/src/Microsoft.WSMan.Management/resources/de/WsManResources.de.resx new file mode 100644 index 00000000000..e6f696931af --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/de/WsManResources.de.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Dieser Befehl kann nicht verwendet werden, da die Datei nicht vorhanden ist. Überprüfen Sie das Vorhandensein der Datei, und führen Sie den Befehl aus. + + + Erstellen eines neuen ClientCertificate-Elements. + + + Dieser Befehl kann nicht ausgeführt werden, da der Verbindungs-URI nicht das richtige Format aufweist. Überprüfen Sie den Verbindungs-URI, und führen Sie den Befehl erneut aus. + + + Die CredSSP-Authentifizierung ermöglicht es, die Benutzeranmeldeinformationen auf diesem Computer an einen Remotecomputer zu senden. Wenn Sie die CredSSP-Authentifizierung für eine Verbindung mit einem schädlichen oder kompromittierten Computer verwenden, hat dieser Computer Zugriff auf Ihren Benutzernamen und Ihr Kennwort. Weitere Informationen finden Sie im Hilfethema „Enable-WSManCredSSP“. +Möchten Sie die CredSSP-Authentifizierung aktivieren? + + + Erstellt ein neues Listener-Element. + + + Mit diesem Befehl werden die Sicherheitseinstellungen für eine Ressource im folgenden WinRM-Plug-In geändert: {0}. +Möchten Sie fortfahren? + + + „Set-Item“ für die WinRM-Konfigurationseinstellung „{0}“, um den Wert auf „{1}“ zu aktualisieren + + + Dieser Befehl kann nicht ausgeführt werden, da die Einstellung nicht aktiviert werden kann. + + + Mit diesem Befehl wird ein neues Listenerelement erstellt. + +Möchten Sie fortfahren? + + + Der Zugriff wird verweigert. Sie müssen dieses Cmdlet aus einem Prozess mit erhöhten Rechten ausführen. + + + Dieser Befehl kann nicht verwendet werden, da der WsMan-Laufwerkstamm unter dieser Version von Windows nicht unterstützt wird. + + + WinRM-Dienst starten + + + Die CredSSP-Authentifizierung ermöglicht es dem Server, Benutzeranmeldeinformationen von einem Remotecomputer zu akzeptieren. Wenn Sie die CredSSP-Authentifizierung auf dem Server aktivieren, hat der Server Zugriff auf den Benutzernamen und das Kennwort des Clientcomputers, wenn dieser sie sendet. Weitere Informationen finden Sie im Hilfethema „Enable-WSManCredSSP“. +Möchten Sie die CredSSP-Authentifizierung aktivieren? + + + WinRM-Schnellkonfiguration + + + Microsoft + + + Dieser Befehl kann den Eingabewert nicht festlegen, da diese Werte Primärschlüssel oder Containerelemente des Ressourcenobjekts sind. Ändern Sie den Eingabewert, und führen Sie den Befehl aus. + + + CredSSP-Authentifizierungskonfiguration für WS-Management + + + Wert des Elements festlegen + + + „System.Object[]“ kann nicht in den für den Parameter erforderlichen Typ „System.String“ konvertiert werden. Die angegebene Methode wird nicht unterstützt. + + + Dieser Computer ist nicht für den Empfang von Anmeldeinformationen von einem Remoteclientcomputer konfiguriert. + + + Dieser Befehl kann vom aktuellen Pfad aus nicht verwendet werden. Wechseln Sie mit „cd\“ zum Stammpfad des Anbieters, und führen Sie den Befehl erneut aus. + + + Dieses PowerShell-Cmdlet ist für Windows XP und Windows Server 2003 nicht verfügbar. + + + Dieser Befehl kann nicht verwendet werden, da der Parameter mit einer Nichttexteigenschaft des Ressourcen-URI übereinstimmt. Überprüfen Sie die Eingabeparameter, und führen Sie den Befehl aus. + + + Eine „{0}“ kann nicht angegeben werden, wenn „{1}“ angegeben ist. + + + Der WinRM-Client kann den Vorgang nicht abschließen. Überprüfen Sie, ob der Computername gültig ist. + + + Der {0}-Parameter ist erforderlich, wenn der Wert des {1}-Parameters „{2}“ ist. + + + Dieser Befehl kann nicht verwendet werden, da kein Parameterwert angegeben wurde. Überprüfen Sie den Wert erneut, und führen Sie den Befehl aus. + + + Dieser Befehl kann nicht verwendet werden, da der Pfad nicht vorhanden ist. Überprüfen Sie das Vorhandensein des Pfads, und führen Sie den Befehl aus. + + + Sicherheitskonfiguration für das WinRM-Plug-In. + + + Dieser Befehl kann im aktuellen Pfad nicht verwendet werden, da dieses Cmdlet auf dieser Ebene des Anbieterpfads nicht unterstützt wird. + + + Der Computer ist nicht zum Zulassen der Delegierung von aktuellen Anmeldeinformationen konfiguriert. + + + Die von Ihnen vorgenommenen Konfigurationsänderungen werden erst wirksam, nachdem der WinRM-Dienst neu gestartet wurde. Führen Sie den folgenden Befehl aus, um den WinRM-Dienst neu zu starten: „Restart-Service winrm“ + + + Das Ausführen des Befehls Set-WSManQuickConfig hat erhebliche Auswirkungen auf die Sicherheit, da damit die Remoteverwaltung über den WinRM-Dienst auf diesem Computer aktiviert wird. +Dieser Befehl: + 1. Überprüft, ob der WinRM-Dienst ausgeführt wird. Wenn der WinRM-Dienst nicht ausgeführt wird, wird er gestartet. + 2. Legt den Starttyp des WinRM-Diensts auf „Automatisch“ fest. + 3. Erstellen eines Listeners zum Annehmen von Anforderungen an jeder IP-Adresse Der Transport erfolgt standardmäßig über HTTP. + 4. Aktivieren einer Firewallausnahme für den WS-Management-Datenverkehr. + 5. Aktivieren der Kerberos- und Negotiate-Dienstauthentifizierung. +Möchten Sie die Remoteverwaltung über den WinRM-Dienst auf diesem Computer aktivieren? + + + Der Wert für RunAsPassword kann nicht ohne einen festgelegten Wert für RunAsUser festgelegt werden. Legen Sie den Wert sowohl für „RunAsUser“ als auch für „RunAsPassword“ in PowerShell fest, indem Sie das Cmdlet „Set-Item“ mit dem -Path-Attribut aufrufen, dessen Wert dem Wert von RunAsUser entspricht. + + + Die aktualisierte Konfiguration kann sich auf den Betrieb der Plug-Ins auswirken, deren Kontingentwert pro Plug-In größer als {0} ist. Überprüfen Sie die Konfiguration aller registrierten Plug-Ins, und ändern Sie die Kontingentwerte pro Plug-In für die betroffenen Plug-Ins. + + + Mit diesem Befehl wird der Wert des Elements festgelegt. + +Möchten Sie fortfahren? + + + Der Computer ist so konfiguriert, dass das Delegieren neuer Anmeldeinformationen an die folgenden Ziele zulässig ist: + + + Stamm des WsMan-Konfigurationsspeichers. + + + Dieser Befehl kann nicht ausgeführt werden, da der WinRM-Dienst nicht gestartet ist. + + + Dieser Befehl kann nicht verwendet werden, da der Stammpfad nicht vorhanden ist. Überprüfen Sie den Stammpfad, und führen Sie den Befehl aus. + + + Dieser Befehl kann im aktuellen Pfad nicht verwendet werden, da „Remove-Item“ auf dieser Ebene des Anbieterpfads nicht unterstützt wird. + + + Mit diesem Befehl wird die TrustedHosts-Liste für den WinRM-Client geändert. Die Computer in der TrustedHosts-Liste sind möglicherweise nicht authentifiziert. Der Client sendet möglicherweise Anmeldeinformationen an diese Computer. Möchten Sie diese Liste wirklich ändern? + + + Mit diesem Befehl wird die RootSDDL-Einstellung für den WinRM-Dienst geändert. Die RootSDDL speichert die standardmäßigen Sicherheitseinstellungen für alle sicherungsfähigen WinRM-Ressourcen, die keine eigene SDDL angeben. Das Ändern der SDDL kann die Sicherheit vieler WinRM-Ressourcen beeinflussen. Möchten Sie diese Standardeinstellungen wirklich ändern? + + + Dieser Befehl kann nicht ohne Anmeldeinformationen verwendet werden, da der Standard- oder Digest-Authentifizierungsalgorithmus verwendet wird. Verwenden Sie den Parameter Anmeldeinformationen, um einen Wert anzugeben, und führen Sie den Befehl aus. + + + Die aktualisierte Konfiguration ist nur wirksam, wenn sie kleiner oder gleich dem Wert des globalen Kontingents „{0}“ ist. Überprüfen Sie den Wert des globalen Kontingents mithilfe des PowerShell-Cmdlets „Get-Item {0}“. + + + Dieser Befehl kann nicht ausgeführt werden, da die Einstellung nicht deaktiviert werden kann. + + + Der Wert für das Element „{0}“ wurde im Pfad {1} nicht gefunden. + + + Dieser Befehl kann nicht ohne den Standard- oder Digest-Authentifizierungsalgorithmus verwendet werden, da Anmeldeinformationen angegeben wurden. Verwenden Sie den Standard- oder Digest-Authentifizierungsalgorithmus, und führen Sie den Befehl aus. + + + WinRM-Sicherheitskonfiguration + + + Dieser Befehl kann im aktuellen Pfad nicht verwendet werden, da „New-Item“ auf dieser Ebene des Anbieterpfads nicht unterstützt wird. + + + Dieser Befehl kann nicht verwendet werden, da die Konfiguration beschädigt ist. Führen Sie „WinRM invoke Restore WinRM/config“ aus, um die Standardkonfiguration wiederherzustellen. + + + Dieser Befehl kann nicht verwendet werden, da der Parameterwerttyp ungültig ist. {0}-Konfiguration erwartet einen Wert vom Typ „{1}“. Stellen Sie sicher, dass der Wert korrekt ist, und versuchen Sie es erneut. + + + Der WinRM-Dienst ist derzeit nicht gestartet. Wenn dieser Befehl ausgeführt wird, wird der WinRM-Dienst gestartet. + +Möchten Sie fortfahren? + + + Dieser Befehl kann nicht verwendet werden, da der Parameter mit keiner Eigenschaft des Ressourcen-URI übereinstimmt. Überprüfen Sie die Eingabeparameter, und führen Sie den Befehl aus. + + + Dieser Computer ist für den Empfang von Anmeldeinformationen von einem Remoteclientcomputer konfiguriert. + + + Der {0}-Parameter kann nicht verwendet werden, wenn der Wert des {1}-Parameters „{2}“ ist. Der {0}-Parameter kann nur verwendet werden, wenn der Wert des {1}-Parameters „{3}“ ist. + + + Die von Ihnen vorgenommenen Konfigurationsänderungen werden erst wirksam, nachdem der WinRM-Dienst auf „{0}“ neu gestartet wurde. + + + Dieser Befehl kann vom aktuellen Pfad aus nicht verwendet werden. Wechseln Sie mit „cd\“ zum Stammpfad des Anbieters, und führen Sie den Befehl erneut aus. + + + Dieses PowerShell-Snap-In enthält Cmdlets, z. B. Get-WSManInstance und Set-WSManInstance, die vom PowerShell-Host zum Verwalten von WSMan-Vorgängen verwendet werden. + + + Dieser Befehl kann nicht zum Entfernen des Computers „localhost“ verwendet werden, da er immer verbunden ist. Geben Sie einen anderen verbundenen Computer an, und führen Sie den Befehl aus. + + + Mit diesem Befehl wird ein neues ClientCertificate-Element erstellt. + +Möchten Sie fortfahren? + + + Der Wert RunAsPassword kann nicht entfernt werden. Entfernen Sie die Werte für RunAsUser und RunAsPassword in PowerShell, indem Sie das Cmdlet Clear-Item mit dem -Path-Attribut aufrufen, dessen Wert dem Wert von RunAsUser entspricht. + + + Es kann kein Laufwerk mit dem angegebenen Stamm erstellt werden. Der Stammpfad ist nicht vorhanden. + + + Dieser Befehl kann nicht verwendet werden, da der Parameter mit mehreren Eigenschaften des Ressourcen-URI übereinstimmt. Überprüfen Sie die Eingabeparameter, und führen Sie den Befehl aus. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/es/WsManResources.es.resx b/src/Microsoft.WSMan.Management/resources/es/WsManResources.es.resx new file mode 100644 index 00000000000..36351a880a8 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/es/WsManResources.es.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede usar este comando porque el archivo no existe. Compruebe la existencia del archivo y ejecute el comando. + + + Crea un nuevo elemento ClientCertificate. + + + No se puede ejecutar este comando porque el formato del URI de conexión no es correcto. Compruebe el URI de conexión y vuelva a ejecutar el comando. + + + La autenticación CredSSP permite que las credenciales de usuario de este equipo se envíen a un equipo remoto. Si usa la autenticación CredSSP para una conexión a un equipo malintencionado o comprometido, ese equipo tendrá acceso a su nombre de usuario y contraseña. Para obtener más información, vea el tema de Ayuda Enable-WSManCredSSP. +¿Desea habilitar la autenticación CredSSP? + + + Crea un nuevo elemento de Escucha. + + + Este comando modifica la configuración de seguridad de un recurso en el siguiente complemento de WinRM: {0}. +¿Desea continuar? + + + "Set-Item" en el valor de configuración de WinRM "{0}" para actualizar el valor a "{1}" + + + No se puede ejecutar este comando porque no se puede habilitar la configuración. + + + Este comando crea un nuevo elemento de Escucha. + +¿Desea continuar? + + + Acceso denegado. Debe ejecutar este cmdlet desde un proceso con privilegios elevados. + + + No se puede usar este comando porque la raíz de la unidad WsMan no se admite en esta versión del sistema operativo Windows. + + + Iniciar servicio WinRM + + + La autenticación CredSSP permite que el servidor acepte credenciales de usuario de un equipo remoto. Si habilita la autenticación CredSSP en el servidor, este tendrá acceso al nombre de usuario y la contraseña del equipo cliente si este los envía. Para obtener más información, vea el tema de Ayuda Enable-WSManCredSSP. +¿Desea habilitar la autenticación CredSSP? + + + Configuración rápida de WinRM + + + Microsoft + + + Este comando no puede establecer el valor de entrada porque estos valores son claves primarias o elementos de contenedor del objeto de recurso. Cambie el valor de entrada y ejecute el comando. + + + Configuración de autenticación CredSSP para WS-Management + + + Establecer el valor del elemento + + + No se puede convertir "System.Object[]" al tipo "System.String" requerido por el parámetro. No se admite el método especificado. + + + Este equipo no está configurado para recibir credenciales de un equipo cliente remoto. + + + No se puede usar este comando desde la ruta de acceso actual. Vaya a la ruta de acceso raíz del proveedor mediante cd\ y vuelva a ejecutar el comando. + + + Este cmdlet de PowerShell no está disponible para Windows XP y Windows Server 2003. + + + No se puede usar este comando porque el parámetro coincide con una propiedad que no es de texto en ResourceURI. Compruebe los parámetros de entrada y ejecute el comando. + + + Un {0} no se puede especificar cuando se especifica {1}. + + + El cliente WinRM no puede completar la operación. Compruebe si el nombre del equipo es válido. + + + El parámetro {0} es obligatorio cuando el valor del parámetro {1} es {2}. + + + No se puede usar este comando porque no se proporcionó el valor del parámetro. Vuelva a comprobar el valor y ejecute el comando. + + + No se puede usar este comando porque la ruta de acceso no existe. Compruebe la existencia de la ruta de acceso y ejecute el comando. + + + Configuración de seguridad para el complemento de WinRM. + + + Este comando no se puede usar en la ruta de acceso actual porque este cmdlet no se admite en este nivel de la ruta de acceso del proveedor. + + + El equipo no está configurado para permitir la delegación de credenciales nuevas. + + + Los cambios de configuración realizados solo serán efectivos después de reiniciar el servicio WinRM. Para reiniciar el servicio WinRM, ejecute el siguiente comando: "Restart-Service winrm" + + + Ejecutar el comando Set-WSManQuickConfig tiene importantes implicaciones de seguridad, ya que habilita la administración remota a través del servicio WinRM en este equipo. +Este comando: + 1. Comprueba si el servicio WinRM está en ejecución. Si no se está ejecutando el servicio WinRM, se inicia. + 2. Establece en automático el tipo de inicio del servicio WinRM. + 3. Crea un agente de escucha para aceptar solicitudes en cualquier dirección IP. De manera predeterminada, el transporte es HTTP. + 4. Habilita una excepción de firewall para tráfico de WS-Management. + 5. Habilita la autenticación de servicio Kerberos y Negotiate. +¿Desea habilitar la administración remota a través del servicio WinRM en este equipo? + + + El valor de RunAsPassword no se puede establecer sin un valor establecido para RunAsUser. Establezca los valores de RunAsUser y RunAsPassword en Powershell llamando al cmdlet Set-Item con el valor del atributo -Path igual al valor de RunAsUser. + + + La configuración actualizada puede afectar al funcionamiento de los complementos con un valor de cuota por complemento superior a {0}. Compruebe la configuración de todos los complementos registrados y cambie los valores de cuota por complemento de los complementos afectados. + + + Este comando establece el valor del elemento. + +¿Desea continuar? + + + La máquina está configurada para permitir la delegación de credenciales nuevas a los siguientes destinos: + + + Raíz del almacenamiento de configuración de WsMan. + + + No se puede ejecutar este comando porque el servicio WinRM no está iniciado. + + + No se puede usar este comando porque la ruta de acceso raíz no existe. Compruebe la ruta de acceso raíz y ejecute el comando. + + + Este comando no se puede usar en la ruta de acceso actual porque Remove-Item no se admite en este nivel de la ruta de acceso del proveedor. + + + Este comando modifica la lista TrustedHosts para el cliente WinRM. Es posible que los equipos de la lista TrustedHosts no estén autenticados. Es posible que el cliente envíe información de credenciales a estos equipos. ¿Está seguro de que desea modificar esta lista? + + + Este comando modifica la configuración de RootSDDL para el servicio WinRM. RootSDDL almacena la configuración de seguridad predeterminada para cualquier recurso de WinRM protegible que no especifique su propio SDDL. Cambiar el SDDL puede afectar a la seguridad de muchos recursos de WinRM. ¿Está seguro de que desea modificar esta configuración predeterminada? + + + Este comando no se puede usar sin credenciales porque el algoritmo de autenticación es Básico o Implícito. Use el parámetro Credenciales para especificar un valor y ejecute el comando. + + + La configuración actualizada solo es efectiva si es menor o igual que el valor de la cuota global {0}. Compruebe el valor de la cuota global mediante el cmdlet de PowerShell "Get-Item {0}". + + + No se puede ejecutar este comando porque no se puede deshabilitar la configuración. + + + No se encuentra el valor del elemento "{0}" en la ruta de acceso {1}. + + + Este comando no se puede usar sin el algoritmo de autenticación Básico o Implícito porque se especificaron credenciales. Use el algoritmo de autenticación Básico o Implícito y ejecute el comando. + + + Configuración de seguridad de WinRM. + + + Este comando no se puede usar en la ruta de acceso actual porque New-Item no se admite en este nivel de la ruta de acceso del proveedor. + + + No se puede usar este comando porque la configuración está dañada. Ejecute WinRM invoke Restore WinRM/config para restaurar la configuración predeterminada + + + No se puede usar este comando porque el tipo de valor del parámetro no es válido. La configuración {0} espera un valor de Tipo {1}. Compruebe que el valor es correcto e inténtelo de nuevo. + + + El servicio WinRM no está iniciado actualmente. Al ejecutar este comando, se iniciará el servicio WinRM. + +¿Desea continuar? + + + No se puede usar este comando porque el parámetro no coincide con ninguna propiedad del ResourceURI. Compruebe los parámetros de entrada y ejecute el comando. + + + Este equipo está configurado para recibir credenciales de un equipo cliente remoto. + + + El parámetro {0} no se puede usar cuando el valor del parámetro {1} es {2}. El parámetro {0} solo se puede usar cuando el valor del parámetro {1} es {3}. + + + Los cambios de configuración realizados solo serán efectivos después de reiniciar el servicio WinRM en {0}. + + + No se puede usar este comando desde la ruta de acceso actual. Vaya a la ruta de acceso raíz del proveedor mediante cd\ y vuelva a ejecutar el comando. + + + Este complemento de PowerShell contiene cmdlets (como Get-WSManInstance y Set-WSManInstance) que el host de PowerShell usa para administrar las operaciones de WSMan. + + + Este comando no se puede usar para quitar el equipo "localhost" porque siempre estará conectado. Proporcione otro equipo conectado y ejecute el comando. + + + Este comando crea un nuevo elemento ClientCertificate. + +¿Desea continuar? + + + No se puede quitar el valor RunAsPassword. Quite los valores de RunAsUser y RunAsPassword en PowerShell llamando al cmdlet Clear-Item con el valor del atributo -Path igual al valor de RunAsUser. + + + No se puede crear una unidad con la raíz especificada. La ruta de acceso raíz no existe. + + + No se puede usar este comando porque el parámetro coincide con varias propiedades de ResourceURI. Compruebe los parámetros de entrada y ejecute el comando. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/fr/WsManResources.fr.resx b/src/Microsoft.WSMan.Management/resources/fr/WsManResources.fr.resx new file mode 100644 index 00000000000..1b084108421 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/fr/WsManResources.fr.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impossible d’utiliser cette commande, car le fichier n’existe pas. Vérifiez l’existence du fichier et exécutez votre commande. + + + Crée un élément ClientCertificate. + + + Cette commande ne peut pas être exécutée car l'URI de connexion n'est pas au format correct. Veuillez vérifier l'URI de connexion et exécuter à nouveau votre commande. + + + L’authentification CredSSP permet d’envoyer les informations d’identification de l’utilisateur sur cet ordinateur à un ordinateur distant. Si vous utilisez l’authentification CredSSP pour une connexion à un ordinateur malveillant ou compromis, cet ordinateur aura accès à votre nom d’utilisateur et à votre mot de passe. Pour plus d’informations, consultez la rubrique d’aide Enable-WSManCredSSP. +Voulez-vous activer l’authentification CredSSP ? + + + Crée un élément Écouteur. + + + Cette commande modifie les paramètres de sécurité sur une ressource dans le plug-in WinRM suivant : {0}. +Voulez-vous continuer ? + + + « Set-Item » sur le paramètre de configuration WinRM «{0}» pour mettre à jour la valeur sur «{1}» + + + Impossible d’exécuter cette commande, car le paramètre ne peut pas être activé. + + + Cette commande crée un élément Écouteur. + +Voulez-vous continuer ? + + + L'accès est refusé. Vous devez exécuter cette applet de commande à partir d’un processus avec élévation de privilèges. + + + Cette commande ne peut pas être utilisée, car la racine du lecteur WsMan n’est pas prise en charge sur cette version du système d’exploitation Windows. + + + Démarrer le service WinRM + + + L’authentification CredSSP permet au serveur d’accepter les informations d’identification de l’utilisateur à partir d’un ordinateur distant. Si vous activez l’authentification CredSSP sur le serveur, le serveur aura accès au nom d’utilisateur et au mot de passe de l’ordinateur client si l’ordinateur client les envoie. Pour plus d’informations, consultez la rubrique d’aide Enable-WSManCredSSP. +Souhaitez-vous activer l'authentification CredSSP ? + + + Configuration rapide WinRM + + + Microsoft + + + Cette commande ne peut pas définir la valeur d'entrée car ces valeurs sont des clés primaires ou des éléments conteneurs de l'objet ressource. Modifiez la valeur d’entrée et exécutez votre commande. + + + Configuration de l’authentification CredSSP pour WS-Management + + + Définir la valeur de l’élément + + + Impossible de convertir 'System.Object[]' en type 'System.String' requis par le paramètre. La méthode spécifiée n’est pas prise en charge. + + + Cet ordinateur n’est pas configuré pour recevoir les informations d’identification d’un ordinateur client distant. + + + Cette commande ne peut pas être utilisée à partir du chemin d’accès actuel. Accédez au répertoire racine du fournisseur à l'aide de la commande cd\ et exécutez à nouveau votre commande. + + + Cette applet de commande PowerShell n’est pas disponible sur Windows XP et Windows Server 2003. + + + Cette commande ne peut pas être utilisée car le paramètre correspond à une propriété non textuelle de ResourceURI. Vérifiez les paramètres d'entrée et exécutez votre commande. + + + Un {0} ne peut pas être spécifié lorsque {1} est spécifié. + + + Le client WinRM ne peut pas terminer l’opération. Vérifiez si le nom de l’ordinateur est valide. + + + Le paramètre {0} est obligatoire lorsque la valeur du paramètre {1} est {2}. + + + Impossible d’utiliser cette commande, car la valeur de paramètre n’est pas fournie. Vérifiez à nouveau la valeur et exécutez votre commande. + + + Impossible d’utiliser cette commande, car le chemin d’accès n’existe pas. Vérifiez l’existence du chemin d’accès et exécutez votre commande. + + + Configuration de la sécurité pour le plug-in WinRM. + + + Cette commande ne peut pas être utilisée dans le chemin d’accès actuel, car cette applet de commande n’est pas prise en charge à ce niveau du chemin du fournisseur. + + + L’ordinateur n’est pas configuré pour autoriser la délégation de nouvelles informations d’identification. + + + Les modifications de configuration que vous avez apportées ne seront effectives qu’après le redémarrage du service WinRM. Pour redémarrer le service WinRM, exécutez la commande suivante : « Restart-Service winrm » + + + L’exécution de la commande Set-WSManQuickConfig a des implications importantes en matière de sécurité, car elle permet la gestion à distance via le service WinRM sur cet ordinateur. +Cette commande : + 1. Vérifie si le service WinRM est en cours d’exécution. Si le service WinRM n’est pas en cours d’exécution, le service est démarré. + 2. Définit le type de démarrage du service WinRM sur automatique. + 3. Crée un écouteur pour accepter les requêtes sur n'importe quelle adresse IP. Par défaut, le transport est HTTP. + 4. Active une exception de pare-feu pour le trafic WS-Management. + 5. Active l’authentification du service Kerberos et Negotiate. +Voulez-vous activer la gestion à distance via le service WinRM sur cet ordinateur ? + + + La valeur de RunAsPassword ne peut pas être définie sans une valeur définie pour RunAsUser. Définissez la valeur pour RunAsUser et RunAsPassword dans PowerShell en appelant l’applet de commande Set-Item avec la valeur de l’attribut -Path égale à la valeur de RunAsUser. + + + La configuration mise à jour peut affecter le fonctionnement des plug-ins dont la valeur de quota par plug-in est supérieure à {0}. Vérifiez la configuration de tous les plug-ins inscrits et modifiez les valeurs de quota par plug-in pour les plug-ins concernés. + + + Cette commande définit la valeur de l’élément. + +Voulez-vous continuer ? + + + L’ordinateur est configuré pour permettre la délégation de nouvelles informations d’identification aux cibles suivantes : + + + Racine du stockage de configuration WsMan. + + + Impossible d’exécuter cette commande, car le service WinRM n’est pas démarré. + + + Impossible d’utiliser cette commande, car le chemin d’accès racine n’existe pas. Vérifiez le chemin racine et exécutez votre commande. + + + Cette commande ne peut pas être utilisée dans le chemin d’accès actuel, car Remove-Item n’est pas pris en charge à ce niveau du chemin du fournisseur. + + + Cette commande modifie la liste TrustedHosts pour le client WinRM. Les ordinateurs de la liste TrustedHosts peuvent ne pas être authentifiés. Le client peut envoyer des informations d’identification à ces ordinateurs. Voulez-vous vraiment modifier cette liste ? + + + Cette commande modifie le paramètre RootSDDL pour le service WinRM. RootSDDL stocke les paramètres de sécurité par défaut pour toute ressource sécurisable WinRM qui ne spécifie pas son propre SDDL. La modification du SDDL peut affecter la sécurité de nombreuses ressources WinRM. Voulez-vous vraiment modifier ces paramètres par défaut ? + + + Cette commande ne peut être utilisée sans authentification car l'algorithme d'authentification est de type Basic ou Digest. Utilisez le paramètre Credentials pour spécifier la valeur et exécuter votre commande. + + + La configuration mise à jour n’est effective que si elle est inférieure ou égale à la valeur du quota global {0}. Vérifiez la valeur du quota global à l’aide de l’applet de commande PowerShell « Get-Item {0}». + + + Impossible d’exécuter cette commande, car le paramètre ne peut pas être désactivé. + + + Impossible de trouver la valeur de l’élément «{0}» dans le chemin d’accès {1}. + + + Cette commande ne peut être utilisée sans l'algorithme d'authentification Basic ou Digest car des informations d'identification sont spécifiées. Utilisez l'algorithme d'authentification Basic ou Digest et exécutez votre commande. + + + Configuration de la sécurité WinRM. + + + Cette commande ne peut pas être utilisée dans le chemin d’accès actuel, car New-Item n’est pas pris en charge à ce niveau du chemin du fournisseur. + + + Impossible d’utiliser cette commande, car la configuration est endommagée. Exécutez WinRM et saisissez « Restaurer WinRM/config » pour rétablir la configuration par défaut + + + Impossible d’utiliser cette commande, car le type de valeur du paramètre n’est pas valide. {0} configuration attend une valeur de type {1}. Vérifiez que la valeur est correcte et réessayez. + + + Le service WinRM n’est pas démarré actuellement. L’exécution de cette commande démarre le service WinRM. + +Voulez-vous continuer ? + + + Cette commande ne peut pas être utilisée car le paramètre ne correspond à aucune propriété de ResourceURI. Vérifiez les paramètres d'entrée et exécutez votre commande. + + + Cet ordinateur est configuré pour recevoir les informations d’identification d’un ordinateur client distant. + + + Impossible d’utiliser le paramètre {0} lorsque la valeur du paramètre {1} est {2}. Le paramètre {0} ne peut être utilisé que lorsque la valeur du paramètre {1} est {3}. + + + Les modifications de configuration que vous avez apportées ne seront effectives qu’après le redémarrage du service WinRM le {0}. + + + Cette commande ne peut pas être utilisée à partir du chemin d’accès actuel. Accédez au répertoire racine du fournisseur à l'aide de la commande cd\ et exécutez à nouveau votre commande. + + + Ce composant logiciel enfichable PowerShell contient des applets de commande (telles que Get-WSManInstance et Set-WSManInstance) utilisées par l’hôte PowerShell pour gérer les opérations WSMan. + + + Cette commande ne peut pas être utilisée pour supprimer l’ordinateur « localhost », car il sera toujours connecté. Donnez un autre ordinateur connecté et exécutez votre commande. + + + Cette commande crée un élément ClientCertificate. + +Voulez-vous continuer ? + + + Impossible de supprimer la valeur RunAsPassword. Supprimez les valeurs pour RunAsUser et RunAsPassword dans PowerShell en appelant l’applet de commande Clear-Item avec la valeur de l’attribut -Path égale à la valeur de RunAsUser. + + + Nous ne pouvons pas créer un lecteur avec la racine spécifiée. Le chemin racine n’existe pas. + + + Cette commande ne peut pas être utilisée car le paramètre correspond à plusieurs propriétés de ResourceURI. Vérifiez les paramètres d'entrée et exécutez votre commande. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/it/WsManResources.it.resx b/src/Microsoft.WSMan.Management/resources/it/WsManResources.it.resx new file mode 100644 index 00000000000..4b2e314219d --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/it/WsManResources.it.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Questo comando non può essere usato perché il file non esiste. Verificare che il file esista ed eseguire il comando. + + + Crea un nuovo elemento ClientCertificate. + + + Questo comando non può essere eseguito perché l'URI di connessione non è nel formato corretto. Controllare l'URI di connessione ed eseguire di nuovo il comando. + + + L'autenticazione CredSSP consente l'invio delle credenziali utente di questo computer a un computer remoto. Se si usa l'autenticazione CredSSP per una connessione a un computer dannoso o compromesso, tale computer avrà accesso al nome utente e alla password. Per altre informazioni, vedere l'argomento della Guida Enable-WSManCredSSP. +Abilitare l'autenticazione CredSSP? + + + Crea un nuovo elemento listener. + + + Questo comando consente di modificare le impostazioni di sicurezza di una risorsa nel seguente plug-in Gestione remota Windows: {0}. +Continuare? + + + "Set-Item" nell'impostazione di configurazione di Gestione remota Windows "{0}" per aggiornare il valore in "{1}" + + + Non è possibile eseguire il comando perché non è possibile abilitare l'impostazione. + + + Questo comando crea un nuovo elemento Listener. + +Continuare? + + + Accesso negato. È necessario eseguire questo cmdlet da un processo con privilegi elevati. + + + Non è possibile usare questo comando perché la radice dell'unità WsMan non è supportata in questa versione del sistema operativo Windows. + + + Avvia il servizio Gestione remota Windows + + + L'autenticazione CredSSP consente al server di accettare le credenziali utente da un computer remoto. Se abiliti l'autenticazione CredSSP nel server, il server avrà accesso al nome utente e alla password del computer client, se inviati dal computer client. Per altre informazioni, vedere l'argomento della Guida Enable-WSManCredSSP. +Abilitare l'autenticazione CredSSP? + + + Configurazione rapida di Gestione remota Windows + + + Microsoft + + + Questo comando non può impostare il valore di input perché tali valori sono chiavi primarie o elementi Contenitore dell'oggetto risorsa. Modificare il valore di input ed eseguire il comando. + + + Configurazione dell'autenticazione CredSSP per WS-Management + + + Imposta il valore dell'elemento + + + Non è possibile convertire 'System.Object[]' nel tipo 'System.String' richiesto dal parametro. Il metodo specificato non è supportato. + + + Il computer non è configurato per ricevere credenziali da un computer client remoto. + + + Non è possibile utilizzare questo comando dal percorso corrente. Passare al percorso radice del provider usando cd\ ed eseguire di nuovo il comando. + + + Questo cmdlet di PowerShell non è disponibile per Windows XP e Windows Server 2003. + + + Questo comando non può essere usato perché il parametro corrisponde a una proprietà non testuale in ResourceURI. Controllare i parametri di input ed eseguire il comando. + + + Un {0} non può essere specificato quando {1} è specificato. + + + Il client Gestione remota Windows non può completare l'operazione. Verificare che il nome del computer sia valido. + + + Il parametro {0} è obbligatorio quando il valore del parametro {1} è {2}. + + + Questo comando non può essere usato perché il valore del parametro non è specificato. Controllare di nuovo il valore ed eseguire il comando. + + + Questo comando non può essere usato perché il percorso non esiste. Verificare che il percorso esista ed eseguire il comando. + + + Configurazione di sicurezza per il plug-in Gestione remota Windows. + + + Non è possibile usare questo comando nel percorso corrente perché questo cmdlet non è supportato a questo livello del percorso del provider. + + + Il computer non è configurato per consentire la delega di nuove credenziali. + + + Le modifiche apportate alla configurazione saranno effettive solo dopo il riavvio del servizio Gestione remota Windows. Per riavviare il servizio Gestione remota Windows, eseguire il comando seguente: 'Restart-Service winrm' + + + L'esecuzione del comando Set-WSManQuickConfig ha implicazioni significative per la sicurezza, in quanto abilita la gestione remota tramite il servizio Gestione remota Windows in questo computer. +Questo comando: + 1. Verifica se il servizio Gestione remota Windows è in esecuzione. Se non è in esecuzione, il servizio Gestione remota Windows viene avviato. + 2. Imposta il tipo di avvio del servizio Gestione remota Windows su Automatico. + 3. Crea un listener per accettare le richieste in qualsiasi indirizzo IP. Per impostazione predefinita, il trasporto è HTTP. + 4. Abilita un'eccezione del firewall per il traffico WS-Management. + 5. Abilita l'autenticazione del servizio Kerberos e Negotiate. +Abilitare la gestione remota tramite il servizio Gestione remota Windows in questo computer? + + + Non è possibile impostare il valore di RunAsPassword senza un valore impostato per RunAsUser. Impostare entrambi i valori, RunAsUser e RunAsPassword, in PowerShell chiamando il cmdlet Set-Item con il valore dell'attributo -Path uguale al valore di RunAsUser. + + + La configurazione aggiornata potrebbe influire sul funzionamento dei plug-in con un valore di quota per plug-in maggiore di {0}. Verificare la configurazione di tutti i plug-in registrati e modificare i valori di quota per plug-in per i plug-in interessati. + + + Questo comando imposta il valore dell'elemento. + +Continuare? + + + Il computer è configurato per consentire la delega di credenziali nuove alle destinazioni seguenti: + + + Radice dell'archiviazione della configurazione WsMan. + + + Non è possibile eseguire questo comando perché il servizio Gestione remota Windows non è avviato. + + + Questo comando non può essere usato perché il percorso radice non esiste. Controllare il percorso radice ed eseguire il comando. + + + Non è possibile usare questo comando nel percorso corrente perché Remove-Item non è supportato a questo livello del percorso del provider. + + + Questo comando modifica l'elenco TrustedHosts per il client Gestione remota Windows. I computer nell'elenco di TrustedHosts potrebbero non essere autenticati. Il client potrebbe inviare informazioni sulle credenziali a questi computer. Modificare questo elenco? + + + Questo comando modifica l'impostazione RootSDDL per il servizio Gestione remota Windows. RootSDDL archivia le impostazioni di sicurezza predefinite per qualsiasi risorsa a protezione diretta Gestione remota Windows che non specifica il proprio SDDL. La modifica dell'SDDL potrebbe influire sulla sicurezza di molte risorse Gestione remota Windows. Modificare queste impostazioni predefinite? + + + Questo comando non può essere usato senza credenziali perché l'algoritmo di autenticazione è Basic o Digest. Usare il parametro Credentials per specificare il valore ed eseguire il comando. + + + La configurazione aggiornata è effettiva solo se è minore o uguale al valore della quota globale {0}. Verificare il valore della quota globale usando il cmdlet di PowerShell "Get-Item {0}". + + + Non è possibile eseguire il comando perché l'impostazione non può essere disabilitata. + + + Non è possibile trovare il valore dell'elemento "{0}" nel percorso {1}. + + + Questo comando non può essere usato senza l'algoritmo di autenticazione Basic o Digest perché sono specificate credenziali. Usare l'algoritmo di autenticazione Basic o Digest ed eseguire il comando. + + + Configurazione di sicurezza Gestione remota Windows. + + + Non è possibile usare questo comando nel percorso corrente perché New-Item non è supportato a questo livello del percorso del provider. + + + Questo comando non può essere usato perché la configurazione è danneggiata. Eseguire WinRM invoke Restore WinRM/config per ripristinare la configurazione predefinita + + + Non è possibile utilizzare questo comando perché il tipo di valore del parametro non è valido. La configurazione di {0} prevede un valore di tipo {1}. Verificare che il valore sia corretto e riprovare. + + + Il servizio Gestione remota Windows non è attualmente avviato. L'esecuzione di questo comando avvierà il servizio Gestione remota Windows. + +Continuare? + + + Questo comando non può essere usato perché il parametro non corrisponde ad alcuna proprietà in ResourceURI. Controllare i parametri di input ed eseguire il comando. + + + Il computer è configurato per ricevere credenziali da un computer client remoto. + + + Il parametro {0} non può essere usato quando il valore del parametro {1} è {2}. Il parametro {0} può essere usato solo quando il valore del parametro {1} è {3}. + + + Le modifiche apportate alla configurazione saranno effettive solo dopo il riavvio del servizio Gestione remota Windows in {0}. + + + Non è possibile utilizzare questo comando dal percorso corrente. Passare al percorso radice del provider usando cd\ ed eseguire di nuovo il comando. + + + Questo snap-in di PowerShell contiene cmdlet, ad esempio Get-WSManInstance e Set-WSManInstance, usati dall'host di PowerShell per gestire le operazioni WSMan. + + + Questo comando non può essere usato per rimuovere il computer 'localhost' perché sarà sempre connesso. Specificare un altro computer connesso ed eseguire il comando. + + + Questo comando crea un nuovo elemento ClientCertificate. + +Continuare? + + + Non è possibile rimuovere il valore RunAsPassword. Rimuovere i valori RunAsUser e RunAsPassword in PowerShell chiamando il cmdlet Clear-Item con il valore dell'attributo -Path uguale al valore di RunAsUser. + + + Non è possibile creare un'unità con la radice specificata. Il percorso radice non esiste. + + + Questo comando non può essere usato perché il parametro corrisponde a più proprietà in ResourceURI. Controllare i parametri di input ed eseguire il comando. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/ja/WsManResources.ja.resx b/src/Microsoft.WSMan.Management/resources/ja/WsManResources.ja.resx new file mode 100644 index 00000000000..a6f593f296d --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/ja/WsManResources.ja.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ファイルが存在しないため、このコマンドは使用できません。ファイルの存在を確認し、コマンドを実行してください。 + + + 新しい ClientCertificate 項目を作成します。 + + + 接続 URI の形式が正しくないため、このコマンドを実行できません。接続 URI を確認し、コマンドをもう一度実行してください。 + + + CredSSP 認証を使用すると、このコンピューターのユーザー資格情報をリモート コンピューターに送信できます。悪意のあるコンピューターまたは侵害されたコンピューターへの接続に CredSSP 認証を使用する場合、そのコンピューターはユーザー名とパスワードにアクセスできます。詳細については、Enable-WSManCredSSP のヘルプ トピックを参照してください。 +CredSSP 認証を有効にしますか? + + + 新しいリスナー項目を作成します。 + + + このコマンドは、次の WinRM プラグインのリソースのセキュリティ設定を変更します: {0}。 +続行しますか? + + + 値を "{1}" に更新するための WinRM 構成設定 "{0}" の "Set-Item" + + + 設定を有効にできないため、このコマンドを実行できません。 + + + このコマンドは、新しいリスナー項目を作成します。 + +続行しますか? + + + アクセスは拒否されました。昇格されたプロセスからこのコマンドレットを実行する必要があります。 + + + このバージョンの Windows OS では WsMan ドライブ ルートがサポートされていないため、このコマンドは使用できません。 + + + WinRM サービスの開始 + + + CredSSP 認証を使用すると、サーバーはリモート コンピューターからユーザー資格情報を受け入れます。サーバーで CredSSP 認証を有効にした場合、クライアント コンピューターから送信された場合、サーバーはクライアント コンピューターのユーザー名とパスワードにアクセスできます。詳細については、Enable-WSManCredSSP のヘルプ トピックを参照してください。 +CredSSP 認証を有効にしますか? + + + WinRM クイック構成 + + + Microsoft + + + これらの値はリソース オブジェクトの主キーまたはコンテナー項目であるため、このコマンドは入力値を設定できません。入力値を変更し、コマンドを実行します。 + + + WS-Management の CredSSP 認証構成 + + + 項目の値を設定する + + + 'System.Object[]' をパラメーターに必要な型 'System.String' に変換できません。指定されたメソッドはサポートされていません。 + + + このコンピューターは、リモート クライアント コンピューターから資格情報を受信するように構成されていません。 + + + このコマンドは、現在のパスからは使用できません。cd\ を使用してプロバイダーのルート パスに移動し、コマンドをもう一度実行してください。 + + + この PowerShell コマンドレットは、Windows XP および Windows Server 2003 では使用できません。 + + + パラメーターが ResourceURI のテキスト以外のプロパティと一致するため、このコマンドを使用できません。入力パラメーターを確認し、コマンドを実行してください。 + + + {1} が指定されている場合、{0} は指定できません。 + + + WinRM クライアントは操作を完了できません。コンピューター名が有効かどうかを確認してください。 + + + {1} パラメーター値が {2} の場合、{0} パラメーターは必須です。 + + + パラメーター値が指定されていないため、このコマンドは使用できません。値をもう一度確認し、コマンドを実行します。 + + + パスが存在しないため、このコマンドは使用できません。パスの存在を確認し、コマンドを実行します。 + + + WinRM プラグインのセキュリティ構成。 + + + このコマンドレットはこのレベルのプロバイダー パスではサポートされていないため、現在のパスではこのコマンドを使用できません。 + + + このマシンは、新しい資格情報の委任を許可するようには構成されていません。 + + + 行った構成の変更は、WinRM サービスが再起動された後にのみ有効になります。 WinRM サービスを再起動するには、次のコマンドを実行します: 'Restart-Service winrm' + + + Set-WSManQuickConfig コマンドを実行すると、このコンピューターの WinRM サービスを介したリモート管理が可能になり、セキュリティに大きな影響があります。 +このコマンドは次のとおりです: + 1. WinRM サービスが実行されているかどうかを確認します。WinRM サービスが実行されていない場合は、サービスを開始します。 + 2. WinRM サービスのスタートアップの種類を自動に設定されます。 + 3. 任意の IP アドレスで要求を受け入れるリスナーが作成されます。既定では、トランスポートは HTTP です。 + 4. WS-Management トラフィックのファイアウォール例外が有効になります。 + 5. Kerberos および Negotiate サービス認証が有効になります。 +このコンピューターの WinRM サービスを使用してリモート管理を有効にしますか? + + + RunAsPassword の値は、RunAsUser に値を設定しないと設定できません。-Path 属性の値が RunAsUser の値と等しい Set-Item コマンドレットを呼び出して、PowerShell で RunAsUser と RunAsPassword の両方の値を設定してください。 + + + 更新された構成は、プラグインごとのクォータ値が {0} より大きいプラグインの操作に影響する可能性があります。登録されているすべてのプラグインの構成を確認し、影響を受けるプラグインの、プラグインごとのクォータ値を変更します。 + + + このコマンドは、Item の値を設定します。 + +続行しますか? + + + このマシンは、次のターゲットへの新しい資格情報の委任を許可するように構成されています: + + + WsMan Config Storage のルート。 + + + WinRM サービスが開始されていないため、このコマンドを実行できません。 + + + ルート パスが存在しないため、このコマンドは使用できません。ルート パスを確認し、コマンドを実行してください。 + + + Remove-Item はこのレベルのプロバイダー パスではサポートされていないため、現在のパスではこのコマンドを使用できません。 + + + このコマンドは、WinRM クライアントの TrustedHosts リストを変更します。TrustedHosts リスト内のコンピューターが認証されていない可能性があります。クライアントは、これらのコンピューターに資格情報を送信する場合があります。このリストを変更しますか? + + + このコマンドにより WinRM サービスの RootSDDL 設定が変更されます。 RootSDDL には、独自の SDDL を指定しない WinRM セキュリティ保護可能なリソースの既定のセキュリティ設定が格納されます。SDDL を変更すると、多くの WinRM リソースのセキュリティに影響する可能性があります。これらの既定の設定を変更しますか? + + + 認証アルゴリズムが Basic または Digest であるため、このコマンドは資格情報なしでは使用できません。Credentials パラメーターを使用して値を指定し、コマンドを実行してください。 + + + 更新された構成は、グローバル クォータ {0} の値以下の場合にのみ有効です。PowerShell コマンドレット "Get-Item {0}" を使用して、グローバル クォータの値を確認します。 + + + 設定を無効にできないため、このコマンドを実行できません。 + + + パス {1} に "{0}" 要素の値が見つかりません。 + + + 資格情報が指定されているため、基本認証アルゴリズムまたはダイジェスト認証アルゴリズムがないと、このコマンドを使用できません。基本認証アルゴリズムまたはダイジェスト認証アルゴリズムを使用して、コマンドを実行してください。 + + + WinRM セキュリティの構成を同期します。 + + + New-Item はこのレベルのプロバイダー パスでサポートされていないため、現在のパスではこのコマンドを使用できません。 + + + 構成が壊れているため、このコマンドは使用できません。WinRM を実行して Restore WinRM/config を呼び出し、既定の構成を復元します + + + パラメーター値の型が無効なため、このコマンドは使用できません。{0} 構成では、型 {1} の値が必要です。値が正しいことを確認してから、もう一度やり直してください。 + + + WinRM サービスは現在開始されていません。このコマンドを実行すると、WinRM サービスが開始されます。 + +続行しますか? + + + パラメーターが ResourceURI のどのプロパティとも一致しないため、このコマンドを使用できません。入力パラメーターを確認して、コマンドを実行してください。 + + + このコンピューターは、リモート クライアント コンピューターから資格情報を受信するように構成されています。 + + + {1} パラメーター値が {2} の場合、{0} パラメーターは使用できません。{0} パラメーターは、{1} パラメーター値が {3} の場合にのみ使用できます。 + + + 行った構成の変更は、WinRM サービスが {0} に再起動された後にのみ有効になります。 + + + このコマンドは、現在のパスからは使用できません。cd\ を使用してプロバイダーのルート パスに移動し、コマンドをもう一度実行してください。 + + + この PowerShell スナップインには、PowerShell ホストが WSMan 操作を管理するために使用するコマンドレット (Get-WSManInstance や Set-WSManInstance など) が含まれています。 + + + このコマンドは、常に接続されるため、コンピューター 'localhost' を削除するために使用できません。他の接続されたコンピューターを指定して、コマンドを実行します。 + + + このコマンドは、新しい ClientCertificate 項目を作成します。 + +続行しますか? + + + RunAsPassword 値を削除できません。PowerShell で -Path 属性の値が RunAsUser の値と等しい Clear-Item コマンドレットを呼び出して、RunAsUser と RunAsPassword の値を削除してください。 + + + 指定されたルートを持つドライブを作成できません。ルート パスが存在しません。 + + + パラメーターが ResourceURI の複数のプロパティと一致するため、このコマンドを使用できません。入力パラメーターを確認して、コマンドを実行してください。 + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/ko/WsManResources.ko.resx b/src/Microsoft.WSMan.Management/resources/ko/WsManResources.ko.resx new file mode 100644 index 00000000000..a9f1bcd4008 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/ko/WsManResources.ko.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 파일이 없으므로 이 명령을 사용할 수 없습니다. 파일이 있는지 확인하고 명령을 실행하세요. + + + 새 ClientCertificate 항목을 만듭니다. + + + 연결 URI가 올바른 형식이 아니므로 이 명령을 실행할 수 없습니다. 연결 URI를 확인하고 명령을 다시 실행하세요. + + + CredSSP 인증을 사용하면 이 컴퓨터의 사용자 자격 증명을 원격 컴퓨터로 보낼 수 있습니다. 악의적이거나 손상된 컴퓨터에 연결하기 위해 CredSSP 인증을 사용하는 경우 해당 컴퓨터는 사용자 이름 및 암호에 액세스할 수 있습니다. 자세한 내용은 Enable-WSManCredSSP 도움말 항목을 참조하세요. +CredSSP 인증을 사용하도록 설정하시겠습니까? + + + 새 수신기 항목을 만듭니다. + + + 이 명령은 다음 WinRM 플러그 인의 리소스에 대한 보안 설정을 수정합니다. {0}. +계속하시겠습니까? + + + WinRM 구성 설정 "{0}"의 값을 "{1}"로 업데이트하려면 "Set-Item"을 사용하세요. + + + 설정을 사용하도록 설정할 수 없으므로 이 명령을 실행할 수 없습니다. + + + 이 명령은 새 수신기 항목을 만듭니다. + +계속하시겠습니까? + + + 액세스가 거부되었습니다. 관리자 권한이 있는 프로세스에서 이 cmdlet을 실행해야 합니다. + + + 이 버전의 Windows OS에서는 WsMan 드라이브 루트가 지원되지 않으므로 이 명령을 사용할 수 없습니다. + + + WinRM 서비스 시작 + + + CredSSP 인증을 사용하면 서버가 원격 컴퓨터의 사용자 자격 증명을 수락할 수 있습니다. 서버에서 CredSSP 인증을 사용하도록 설정하면 클라이언트 컴퓨터가 자격 증명을 보낼 때 서버에서 해당 사용자 이름과 암호에 액세스할 수 있습니다. 자세한 내용은 Enable-WSManCredSSP 도움말 항목을 참조하세요. +CredSSP 인증을 사용하도록 설정하시겠습니까? + + + WinRM 빠른 구성 + + + Microsoft + + + 이러한 값은 리소스 개체의 기본 키 또는 컨테이너 항목이므로 이 명령은 입력 값을 설정할 수 없습니다. 입력 값을 변경하고 명령을 실행합니다. + + + WS-Management에 대한 CredSSP 인증 구성 + + + 항목의 값 설정 + + + 'System.Object[]'를 매개 변수에 필요한 'System.String' 형식으로 변환할 수 없습니다. 지정한 메서드는 지원되지 않습니다. + + + 이 컴퓨터는 원격 클라이언트 컴퓨터에서 자격 증명을 받도록 구성되지 않았습니다. + + + 이 명령은 현재 경로에서 사용할 수 없습니다. cd\를 사용하여 공급자의 루트 경로로 이동하고 명령을 다시 실행합니다. + + + 이 PowerShell cmdlet은 Windows XP 및 Windows Server 2003에서 사용할 수 없습니다. + + + 매개 변수가 ResourceURI의 텍스트가 아닌 속성과 일치하므로 이 명령을 사용할 수 없습니다. 입력 매개 변수를 확인하고 명령을 실행하세요. + + + {1}이(가) 지정된 경우 {0}을(를) 지정할 수 없습니다. + + + WinRM 클라이언트가 작업을 완료할 수 없습니다. 컴퓨터 이름이 유효한지 확인합니다. + + + {1} 매개 변수 값이 {2}인 경우 {0} 매개 변수는 필수입니다. + + + 매개 변수 값이 제공되지 않았으므로 이 명령을 사용할 수 없습니다. 값을 다시 확인하고 명령을 실행하세요. + + + 경로가 없으므로 이 명령을 사용할 수 없습니다. 경로가 있는지 확인하고 명령을 실행하세요. + + + WinRM 플러그 인에 대한 보안 구성입니다. + + + 이 cmdlet은 이 공급자 경로 수준에서 지원되지 않으므로 현재 경로에서 이 명령을 사용할 수 없습니다. + + + 컴퓨터가 새 자격 증명 위임을 허용하도록 구성되어 있지 않습니다. + + + 수행한 구성 변경 내용은 WinRM 서비스를 다시 시작한 후에만 적용됩니다. WinRM 서비스를 다시 시작하려면 'Restart-Service winrm' 명령을 실행하세요. + + + Set-WSManQuickConfig 명령을 실행하면 이 컴퓨터의 WinRM 서비스를 통해 원격 관리를 사용할 수 있으므로 보안에 상당한 영향을 미칩니다. +이 명령: + 1. WinRM 서비스가 실행 중인지 확인합니다. WinRM 서비스가 실행되고 있지 않으면 서비스가 시작됩니다. + 2. WinRM 서비스 시작 유형을 자동으로 설정합니다. + 3. 모든 IP 주소에 대한 요청을 수락하는 수신기를 만듭니다. 기본적으로 전송은 HTTP입니다. + 4. WS-Management 트래픽에 대해 방화벽 예외를 사용하도록 설정합니다. + 5. Kerberos 및 협상 서비스 인증을 사용하도록 설정합니다. +이 컴퓨터에서 WinRM 서비스를 통해 원격 관리를 사용하도록 설정하시겠습니까? + + + RunAsUser에 대한 값을 설정하지 않으면 RunAsPassword 값을 설정할 수 없습니다. -Path 특성 값이 RunAsUser 값과 같은 Set-Item cmdlet을 호출하여 Powershell에서 RunAsUser 및 RunAsPassword의 값을 설정합니다. + + + 업데이트된 구성은 플러그 인당 할당량 값이 {0}보다 큰 플러그 인의 작업에 영향을 줄 수 있습니다. 등록된 모든 플러그 인의 구성을 확인하고 영향을 받는 플러그 인의 플러그 인당 할당량 값을 변경하세요. + + + 이 명령은 항목의 값을 설정합니다. + +계속하시겠습니까? + + + 컴퓨터가 다음 대상에 대한 새 자격 증명 위임을 허용하도록 구성되었습니다. + + + WsMan 구성 저장소의 루트입니다. + + + WinRM 서비스가 시작되지 않았기 때문에 이 명령을 실행할 수 없습니다. + + + 루트 경로가 없으므로 이 명령을 사용할 수 없습니다. 루트 경로를 확인하고 명령을 실행하세요. + + + Remove-Item은 이 공급자 경로 수준에서 지원되지 않으므로 현재 경로에서 이 명령을 사용할 수 없습니다. + + + 이 명령은 WinRM 클라이언트의 TrustedHosts 목록을 수정합니다. TrustedHosts 목록의 컴퓨터는 인증되지 않았을 수 있습니다. 클라이언트가 이러한 컴퓨터로 자격 증명 정보를 보낼 수도 있습니다. 이 목록을 수정하시겠습니까? + + + 이 명령은 WinRM 서비스의 RootSDDL 설정을 수정합니다. RootSDDL은 자체 SDDL을 지정하지 않은 WinRM 보안 개체 리소스의 기본 보안 설정을 저장합니다. SDDL을 변경하면 여러 WinRM 리소스의 보안에 영향을 줄 수 있습니다. 이러한 기본 설정을 수정하시겠습니까? + + + 인증 알고리즘이 Basic 또는 Digest이므로 자격 증명 없이 이 명령을 사용할 수 없습니다. Credentials 매개 변수를 사용하여 값을 지정하고 명령을 실행합니다. + + + 업데이트된 구성은 전역 할당량 값 {0}보다 작거나 같은 경우에만 적용됩니다. PowerShell cmdlet "Get-Item {0}"을(를) 사용하여 전역 할당량 값을 확인합니다. + + + 설정을 사용하지 않도록 설정할 수 없으므로 이 명령을 실행할 수 없습니다. + + + 경로{1}에서 "{0}" 요소의 값을 찾을 수 없습니다. + + + 자격 증명이 지정되어 있으므로 Basic 또는 Digest 인증 알고리즘 없이 이 명령을 사용할 수 없습니다. Basic 또는 Digest 인증 알고리즘을 사용하여 명령을 실행하세요. + + + WinRM 보안 구성입니다. + + + New-Item은 이 공급자 경로 수준에서 지원되지 않으므로 현재 경로에서 이 명령을 사용할 수 없습니다. + + + 구성이 손상되었으므로 이 명령을 사용할 수 없습니다. WinRM 호출 실행 기본 구성을 복원하려면 WinRM/config를 복원하세요. + + + 매개 변수 값 형식이 잘못되었으므로 이 명령을 사용할 수 없습니다. {0} 구성에는 Type {1} 값이 필요합니다. 값이 올바른지 확인하고 다시 시도하세요. + + + WinRM 서비스가 현재 시작되지 않았습니다. 이 명령을 실행하면 WinRM 서비스가 시작됩니다. + +계속하시겠습니까? + + + 매개 변수가 ResourceURI의 속성과 일치하지 않으므로 이 명령을 사용할 수 없습니다. 입력 매개 변수를 확인하고 명령을 실행하세요. + + + 이 컴퓨터는 원격 클라이언트 컴퓨터에서 자격 증명을 받도록 구성되어 있습니다. + + + {1} 매개 변수 값이 {2}인 경우 {0} 매개 변수를 사용할 수 없습니다. {0} 매개 변수는 {1} 매개 변수 값이 {3}인 경우에만 사용할 수 있습니다. + + + 수행한 구성 변경 내용은 {0}에서 WinRM 서비스를 다시 시작한 후에만 적용됩니다. + + + 이 명령은 현재 경로에서 사용할 수 없습니다. cd\를 사용하여 공급자의 루트 경로로 이동하고 명령을 다시 실행합니다. + + + 이 PowerShell 스냅인에는 PowerShell 호스트에서 WSMan 작업을 관리하는 데 사용하는 cmdlet(예: Get-WSManInstance 및 Set-WSManInstance 등)이 포함되어 있습니다. + + + 이 명령은 항상 연결되므로 'localhost' 컴퓨터를 제거하는 데 사용할 수 없습니다. 다른 연결된 컴퓨터를 제공하고 명령을 실행합니다. + + + 이 명령은 새 ClientCertificate 항목을 만듭니다. + +계속하시겠습니까? + + + RunAsPassword 값을 제거할 수 없습니다. -Path 특성 값이 RunAsUser 값과 같은 Clear-Item cmdlet을 호출하여 PowerShell에서 RunAsUser 및 RunAsPassword 값을 제거합니다. + + + 지정한 루트로 드라이브를 만들 수 없습니다. 루트 경로가 없습니다. + + + 매개 변수가 ResourceURI의 여러 속성과 일치하므로 이 명령을 사용할 수 없습니다. 입력 매개 변수를 확인하고 명령을 실행하세요. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/pl/WsManResources.pl.resx b/src/Microsoft.WSMan.Management/resources/pl/WsManResources.pl.resx new file mode 100644 index 00000000000..825f677f4f6 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/pl/WsManResources.pl.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można użyć tego polecenia, ponieważ plik nie istnieje. Sprawdź, czy plik istnieje i uruchom swoje polecenie. + + + Tworzy nowy element ClientCertificate. + + + Nie można wykonać tego polecenia, ponieważ identyfikator URI połączenia ma nieprawidłowy format. Sprawdź identyfikator URI połączenia i uruchom polecenie ponownie. + + + Uwierzytelnianie CredSSP umożliwia wysłanie poświadczeń użytkownika na tym komputerze do komputera zdalnego. Jeśli użyjesz uwierzytelniania CredSSP podczas łączenia się ze złośliwym komputerem lub który ma naruszone zabezpieczenia, komputer ten uzyska dostęp do Twojej nazwy użytkownika i hasła. Więcej informacji można znaleźć w temacie pomocy Enable-WSManCredSSP. +Czy chcesz włączyć uwierzytelnianie CredSSP? + + + Tworzy nowy element nasłuchujący. + + + To polecenie modyfikuje ustawienia zabezpieczeń zasobu w następującym dodatku usługi WinRM: {0}. +Czy na pewno chcesz kontynuować? + + + Element „Set-Item” w ustawieniu konfiguracji usługi WinRM „{0}”, aby zaktualizować wartość na „{1}” + + + Nie można wykonać tego polecenia, ponieważ nie można włączyć ustawienia. + + + To polecenie tworzy nowy element nasłuchujący. + +Czy na pewno chcesz kontynuować? + + + Odmowa dostępu. To polecenie cmdlet trzeba uruchomić z procesu z podwyższonymi uprawnieniami. + + + Tego polecenia nie można użyć, ponieważ katalog główny dysku WsMan nie jest obsługiwany w tej wersji systemu operacyjnego Windows. + + + Uruchom usługę WinRM + + + Uwierzytelnianie CredSSP umożliwia serwerowi akceptowanie poświadczeń użytkownika z komputera zdalnego. Jeśli włączysz uwierzytelnianie CredSSP na serwerze, serwer uzyska dostęp do nazwy użytkownika i hasła komputera klienckiego, jeśli ten je prześle. Więcej informacji można znaleźć w temacie pomocy Enable-WSManCredSSP. +Czy chcesz włączyć uwierzytelnianie CredSSP? + + + Szybka konfiguracja usługi WinRM + + + Microsoft + + + Tego polecenia nie można użyć do ustawienia wartości wejściowej, ponieważ są to klucze podstawowe lub elementy kontenera obiektu zasobu. Zmień wartość wejściową i uruchom swoje polecenie. + + + Konfiguracja uwierzytelniania CredSSP dla protokołu WS-Management + + + Ustaw wartość elementu + + + Nie można przekonwertować elementu „System.Object[]” na typ „System.String” wymagany przez parametr. Podana metoda nie jest obsługiwana. + + + Ten komputer nie jest skonfigurowany do odbierania poświadczeń ze zdalnego komputera klienckiego. + + + Tego polecenia nie można użyć z bieżącej ścieżki. Przejdź do ścieżki katalogu głównego dostawcy za pomocą polecenia cd\ i ponownie uruchom swoje polecenie. + + + To polecenie cmdlet programu PowerShell nie jest dostępne w systemach Windows XP i Windows Server 2003. + + + Tego polecenia nie można użyć, ponieważ parametr jest zgodny z właściwością inną niż tekstowa w identyfikatorze URI zasobu. Sprawdź parametry wejściowe i uruchom swoje polecenie. + + + Nie można określić elementu {0}, gdy określono element{1}. + + + Klient usługi WinRM nie może ukończyć operacji. Sprawdź, czy nazwa komputera jest prawidłowa. + + + Parametr {0} jest wymagany, gdy wartość parametru {1} to {2}. + + + Tego polecenia nie można użyć, ponieważ nie podano wartości parametru. Sprawdź ponownie wartość i uruchom swoje polecenie. + + + Nie można użyć tego polecenia, ponieważ ścieżka nie istnieje. Sprawdź, czy ścieżka istnieje i uruchom swoje polecenie. + + + Konfiguracja zabezpieczeń wtyczki usługi WinRM. + + + Tego polecenia nie można użyć w bieżącej ścieżce, ponieważ to polecenie cmdlet nie jest obsługiwane na tym poziomie ścieżki dostawcy. + + + Maszyna nie jest skonfigurowana w sposób umożliwiający delegowanie nowych poświadczeń. + + + Wprowadzone zmiany konfiguracji zaczną obowiązywać dopiero po ponownym uruchomieniu usługi WinRM. Aby ponownie uruchomić usługę WinRM, uruchom następujące polecenie: „Restart-Service winrm” + + + Uruchomienie polecenia Set-WSManQuickConfig ma istotny wpływ na zabezpieczenia, ponieważ włącza zdalne zarządzanie na tym komputerze za pośrednictwem usługi WinRM. +To polecenie: + 1. Sprawdza, czy usługa WinRM jest uruchomiona. Jeżeli usługa WinRM nie jest uruchomiona, zostanie ona uruchomiona. + 2. Ustawia typ uruchamiania usługi WinRM na automatyczny. + 3. Tworzy obiekt nasłuchujący, który będzie akceptował żądania z dowolnego adresu IP. Domyślnie transportem jest protokół HTTP. + 4. Włącza wyjątek zapory dla ruchu WS-Management. + 5. Włącza uwierzytelnianie usługi Kerberos i Negotiate. +Czy chcesz włączyć zdalne zarządzanie za pośrednictwem usługi WinRM na tym komputerze? + + + Nie można ustawić wartości RunAsPassword bez ustawienia wartości RunAsUser. Ustaw wartości dla elementów RunAsUser i RunAsPassword w programie PowerShell, wywołując polecenie cmdlet „Set-Item” z wartością atrybutu ścieżki równą wartości RunAsUser. + + + Zaktualizowana konfiguracja może wpłynąć na działanie wtyczek, których wartość limitu na wtyczkę jest większa niż {0}. Sprawdź konfigurację wszystkich zarejestrowanych wtyczek i zmień wartości limitu dla wtyczek, których to dotyczy. + + + To polecenie ustawia wartość elementu. + +Czy na pewno chcesz kontynuować? + + + Maszyna jest skonfigurowana tak, aby zezwalać na delegowanie świeżych poświadczeń do następujących elementów docelowych: + + + Katalog główny magazynu konfiguracji WsMan. + + + Nie można wykonać tego polecenia, ponieważ usługa WinRM nie jest uruchomiona. + + + Tego polecenia nie można użyć, ponieważ ścieżka katalogu głównego nie istnieje. Sprawdź ścieżkę katalogu głównego i uruchom swoje polecenie. + + + Tego polecenia nie można użyć w bieżącej ścieżce, ponieważ element Remove-Item nie jest obsługiwane na tym poziomie ścieżki dostawcy. + + + To polecenie modyfikuje listę TrustedHosts dla klienta usługi WinRM. Komputery znajdujące się na liście TrustedHosts mogą nie być uwierzytelnione. Klient może wysłać informacje o poświadczeniach do tych komputerów. Czy na pewno chcesz zmodyfikować tę listę? + + + To polecenie modyfikuje ustawienie RootSDDL dla usługi WinRM. Parametr RootSDDL przechowuje domyślne ustawienia zabezpieczeń dla każdego zabezpieczanego zasobu usługi WinRM, który nie określa własnego parametru SDDL. Zmiana parametru SDDL może mieć wpływ na zabezpieczenia wielu zasobów usługi WinRM. Czy na pewno chcesz zmodyfikować te ustawienia domyślne? + + + Tego polecenia nie można użyć bez poświadczeń, ponieważ algorytm uwierzytelniania jest podstawowy lub szyfrowany. Użyj parametru poświadczeń, aby określić wartość i uruchomić polecenie. + + + Zaktualizowana konfiguracja jest skuteczna tylko wtedy, gdy jest mniejsza lub równa wartości globalnego limitu przydziału {0}. Sprawdź wartość globalnego limitu przydziału przy użyciu polecenia cmdlet programu PowerShell „Get-Item {0}”. + + + Nie można wykonać tego polecenia, ponieważ nie można wyłączyć ustawienia. + + + Nie można odnaleźć wartości dla elementu „{0}” w ścieżce {1}. + + + Tego polecenia nie można użyć bez algorytmu uwierzytelniania podstawowego lub szyfrowanego, ponieważ określono poświadczenia. Użyj algorytmu uwierzytelniania podstawowego lub szyfrowanego i uruchom swoje polecenie. + + + Konfiguracja zabezpieczeń usługi WinRM. + + + Tego polecenia nie można użyć w bieżącej ścieżce, ponieważ element New-Item nie jest obsługiwane na tym poziomie ścieżki dostawcy. + + + Tego polecenia nie można użyć, ponieważ konfiguracja jest uszkodzona. Uruchom usługę WinRM wywołaj polecenie „Restore WinRM/config”, aby przywrócić konfigurację domyślną + + + Nie można użyć tego polecenia, ponieważ typ wartości parametru jest nieprawidłowy. Konfiguracja {0} oczekuje wartości typu {1}. Sprawdź, czy wartość jest poprawna, i spróbuj ponownie. + + + Usługa WinRM nie jest obecnie uruchomiona. Uruchomienie tego polecenia spowoduje uruchomienie usługi WinRM. + +Czy na pewno chcesz kontynuować? + + + Nie można użyć tego polecenia, ponieważ parametr nie pasuje do żadnej właściwości w identyfikatorze ResourceURI. Sprawdź parametry wejściowe i uruchom swoje polecenie. + + + Ten komputer jest skonfigurowany do odbierania poświadczeń ze zdalnego komputera klienckiego. + + + Nie można użyć parametru {0}, gdy wartość parametru {1} to {2}. Parametr {0} można stosować tylko wtedy, gdy wartością parametru {1} jest {3}. + + + Wprowadzone zmiany konfiguracji zaczną obowiązywać dopiero po ponownym uruchomieniu usługi WinRM na {0}. + + + Tego polecenia nie można użyć z bieżącej ścieżki. Przejdź do ścieżki katalogu głównego dostawcy za pomocą polecenia cd\ i ponownie uruchom swoje polecenie. + + + Ta przystawka programu PowerShell zawiera polecenia cmdlet (takie jak Get-WSManInstance i Set-WSManInstance), które są używane przez hosta programu PowerShell do zarządzania operacjami WSMan. + + + Tego polecenia nie można użyć do usunięcia komputera „localhost”, ponieważ będzie on zawsze połączony. Podaj inny połączony komputer i uruchom swoje polecenie. + + + To polecenie tworzy nowy element ClientCertificate. + +Czy na pewno chcesz kontynuować? + + + Nie można usunąć wartości RunAsPassword. Usuń wartości RunAsUser i RunAsPassword w programie PowerShell, wywołując polecenie cmdlet „Clear-Item” z wartością atrybutu ścieżki równą wartości RunAsUser. + + + Nie można utworzyć dysku z określonym katalogiem głównym. Ścieżka główna nie istnieje. + + + Nie można użyć tego polecenia, ponieważ parametr pasuje do wielu właściwości w identyfikatorze ResourceURI. Sprawdź parametry wejściowe i uruchom swoje polecenie. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/pt-BR/WsManResources.pt-BR.resx b/src/Microsoft.WSMan.Management/resources/pt-BR/WsManResources.pt-BR.resx new file mode 100644 index 00000000000..ffc030df191 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/pt-BR/WsManResources.pt-BR.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Este comando não pode ser usado porque o arquivo não existe. Verifique a existência do arquivo e faça a execução do seu comando. + + + Crie um item ClientCertificate. + + + Este comando não pode ser executado porque o URI de Conexão não está no formato correto. Verifique o URI de conexão e faça a execução do seu comando novamente. + + + A autenticação CredSSP permite que as credenciais do usuário neste computador sejam enviadas a um computador remoto. Se você usar a autenticação CredSSP para uma conexão com um computador mal-intencionado ou comprometido, esse computador terá acesso ao seu nome de usuário e à sua senha. Para obter mais informações, confira o tópico da Ajuda Enable-WSManCredSSP. +Deseja habilitar a autenticação CredSSP? + + + Cria um item Ouvinte. + + + Este comando modifica as configurações de segurança de um recurso no seguinte plug-in do WinRM: {0}. +Deseja continuar? + + + "Set-Item" na configuração "{0}" do WinRM para atualizar o valor para "{1}" + + + Este comando não pode ser executado porque a configuração não pode ser habilitada. + + + Este comando cria um item Ouvinte. + +Deseja continuar? + + + Acesso negado. Você precisa executar este cmdlet em um processo elevado. + + + Este comando não pode ser usado porque a raiz da unidade WsMan não tem suporte nesta versão do Sistema Operacional Windows. + + + Iniciar Serviço WinRM + + + A autenticação CredSSP permite que o servidor aceite credenciais do usuário de um computador de repositório remoto. Se você habilitar a autenticação CredSSP no servidor, o servidor terá acesso ao nome de usuário e à senha do computador cliente se o computador cliente os enviar. Para obter mais informações, confira o tópico da Ajuda Enable-WSManCredSSP. +Deseja habilitar a autenticação CredSSP? + + + Configuração Rápida do WinRM + + + Microsoft + + + Este comando não pode definir o valor de entrada porque esses valores são chaves primárias ou itens de Contêiner do objeto de recurso. Altere o valor de entrada e execute seu comando. + + + Configuração de Autenticação do CredSSP para WS-Management + + + Defina o valor do item + + + Não é possível converter 'System.Object[]' no tipo 'System.String' exigido pelo parâmetro. O método especificado não tem suporte. + + + Este computador não está configurado para receber credenciais de um computador cliente remoto. + + + Este comando não pode ser usado a partir do caminho atual. Mova para o caminho raiz do provedor usando cd\ e execute seu comando novamente. + + + Este cmdlet do PowerShell não está disponível para Windows XP e Windows Server 2003. + + + Este comando não pode ser usado porque o parâmetro corresponde a uma propriedade que não é de texto no ResourceURI. Verifique os parâmetros de entrada e execute seu comando. + + + Não é possível especificar {0} quando {1} está especificado. + + + O cliente WinRM não pode concluir a operação. Verifique se o nome do computador é válido. + + + O parâmetro {0} é obrigatório quando o valor do parâmetro {1} é {2}. + + + Este comando não pode ser usado porque o Valor do Parâmetro não foi fornecido. Verifique o valor novamente e execute seu comando. + + + Este comando não pode ser usado porque o caminho não existe. Verifique a existência do caminho e execute seu comando. + + + Configuração de Segurança para o Plug-in do WinRM. + + + Este comando não pode ser usado no caminho atual porque esse cmdlet não tem suporte neste nível do caminho do Provedor. + + + O computador não está configurado para permitir a delegação de novas credenciais. + + + As alterações de configuração feitas só serão efetivas depois que o serviço WinRM for reiniciado. Para reiniciar o serviço WinRM, faça a execução do seguinte comando: 'Restart-Serviço winrm' + + + A execução do comando Set-WSManQuickConfig tem implicações significativas de segurança, pois habilita o gerenciamento remoto por meio do serviço WinRM neste computador. +Este comando: + 1. Verifica se o serviço WinRM está em execução. Se o serviço WinRM não estiver em execução, o serviço será iniciado. + 2. Define o tipo de inicialização do serviço WinRM como automático. + 3. Cria um ouvinte para aceitar solicitações em qualquer endereço IP. Por padrão, o transporte é HTTP. + 4. Habilita uma exceção de firewall para o tráfego do WS-Management. + 5. Habilita a autenticação de serviço por Kerberos e Negotiate. +Deseja habilitar o gerenciamento remoto por meio do serviço WinRM neste computador? + + + O valor de RunAsPassword não pode ser definido sem um conjunto de valores para RunAsUser. Defina o valor de RunAsUser e RunAsPassword no Powershell por meio da chamada do cmdlet Set-Item com o valor do atributo -Path igual ao valor de RunAsUser. + + + A configuração atualizada pode afetar a operação dos plugins que têm um valor de cota por plugin superior a {0}. Verifique a configuração de todos os plugins registrados e altere os valores de cota por plugin dos plugins afetados. + + + Este comando define o valor do Item. + +Deseja continuar? + + + O computador está configurado para permitir a delegação de credenciais novas aos seguintes destinos: + + + Raiz do Armazenamento de Configuração do WsMan. + + + Este comando não pode ser executado porque o Serviço WinRM não foi iniciado. + + + Este comando não pode ser usado porque o caminho raiz não existe. Verifique o caminho raiz e execute seu comando. + + + Este comando não pode ser usado no caminho atual porque Remove-Item não tem suporte neste nível do caminho do Provedor. + + + Este comando modifica a lista TrustedHosts do cliente WinRM. Os computadores na lista TrustedHosts podem não estar autenticados. O cliente pode enviar informações de credencial a esses computadores. Tem certeza de que deseja modificar esta lista? + + + Este comando modifica a configuração RootSDDL do serviço WinRM. RootSDDL armazena as configurações de segurança padrão de qualquer recurso protegível do WinRM que não especifique seu próprio SDDL. A alteração da SDDL pode afetar a segurança de muitos recursos do WinRM. Tem certeza de que deseja modificar essas configurações padrão? + + + Este comando não pode ser usado sem uma credencial porque o algoritmo de autenticação é Basic ou Digest. Use o parâmetro Credentials para especificar o valor e executar seu comando. + + + A configuração atualizada só será efetiva se for menor ou igual ao valor da cota global {0}. Verifique o valor da cota global usando o cmdlet do PowerShell "Get-Item {0}". + + + Este comando não pode ser executado porque a configuração não pode ser desabilitada. + + + Não é possível localizar o valor do elemento "{0}" no caminho {1}. + + + Este comando não pode ser usado sem o algoritmo de autenticação Basic ou Digest porque há credenciais especificadas. Use o algoritmo de autenticação Basic ou Digest e faça a execução do seu comando. + + + Configuração de Segurança do WinRM. + + + Este comando não pode ser usado no caminho atual porque New-Item não tem suporte neste nível do caminho do Provedor. + + + Este comando não pode ser usado porque a configuração está corrompida. Execute WinRM invoke Restore WinRM/config para restaurar a configuração padrão + + + Este comando não pode ser usado porque o tipo de valor do parâmetro é inválido. A configuração {0} espera um valor do Tipo {1}. Verifique se o valor está correto e tente novamente. + + + O serviço WinRM não está em execução no momento. A execução deste comando iniciará o serviço WinRM. + +Deseja continuar? + + + Este comando não pode ser usado porque o parâmetro não corresponde a nenhuma propriedade em ResourceURI. Verifique os parâmetros de entrada e execute o comando. + + + Este computador está configurado para receber credenciais de um computador cliente remoto. + + + O parâmetro {0} não pode ser usado quando o valor do parâmetro {1} é {2}. O parâmetro {0} só pode ser usado quando o valor do parâmetro {1} é {3}. + + + As alterações de configuração feitas só serão efetivas depois que o serviço WinRM for reiniciado em {0}. + + + Este comando não pode ser usado a partir do caminho atual. Mova para o caminho raiz do provedor usando cd\ e execute seu comando novamente. + + + Este snap-in do PowerShell contém cmdlets (como Get-WSManInstance e Set-WSManInstance) que são usados pelo host do PowerShell para gerenciar operações do WSMan. + + + Este comando não pode ser usado para remover o computador 'localhost' porque ele permanecerá sempre conectado. Forneça outro computador conectado e execute seu comando. + + + Este comando cria um item ClientCertificate. + +Deseja continuar? + + + O valor RunAsPassword não pode ser removido. Remover os valores de RunAsUser e RunAsPassword no PowerShell por meio da chamada Clear-Item do cmdlet com o valor do atributo -Path igual ao valor de RunAsUser. + + + Não é possível criar uma unidade com a raiz especificada. O caminho raiz não existe. + + + Este comando não pode ser usado porque o parâmetro corresponde a várias propriedades no ResourceURI. Verifique os parâmetros de entrada e execute o comando novamente. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/ru/WsManResources.ru.resx b/src/Microsoft.WSMan.Management/resources/ru/WsManResources.ru.resx new file mode 100644 index 00000000000..81c0e215ed5 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/ru/WsManResources.ru.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Эту команду нельзя использовать, так как файл не существует. Проверьте существование файла и выполните команду. + + + Создает новый элемент ClientCertificate. + + + Эту команду нельзя выполнить, так как URI подключения имеет неверный формат. Проверьте URI подключения и выполните команду еще раз. + + + Проверка подлинности CredSSP позволяет передавать учетные данные пользователя с этого компьютера на удаленный компьютер. Если для подключения к вредоносному или взломанному компьютеру используется проверка подлинности CredSSP, этот компьютер получит доступ к имени пользователя и паролю. Подробнее см. в разделе «Справка по Enable-WSManCredSSP». +Вы хотите включить проверку подлинности CredSSP? + + + Создает новый элемент Listener. + + + Эта команда изменяет параметры безопасности ресурса в следующем подключаемом модуле WinRM: {0}. +Продолжить? + + + "Set-Item" для параметра конфигурации WinRM {0} для обновления значения до {1} + + + Эту команду нельзя выполнить, так как параметр нельзя включить. + + + Эта команда создает новый элемент Listener. + +Продолжить? + + + В доступе отказано. Необходимо запустить этот командлет из процесса с повышенными правами. + + + Эту команду нельзя использовать, так как корень диска WsMan не поддерживается в этой версии Windows. + + + Запустить службу WinRM + + + Проверка подлинности CredSSP позволяет серверу принимать учетные данные пользователя с удаленного компьютера. Если на сервере включена проверка подлинности CredSSP, сервер получит доступ к имени пользователя и паролю клиентского компьютера, если клиентский компьютер их отправит. Подробнее см. в разделе «Справка по Enable-WSManCredSSP». +Вы хотите включить проверку подлинности CredSSP? + + + Быстрая настройка WinRM + + + Корпорация Майкрософт + + + Этой команде не удается задать входное значение, так как эти значения являются первичными ключами или элементами контейнера объекта ресурса. Измените входное значение и выполните команду. + + + Конфигурация проверки подлинности CredSSP для WS-Management + + + Задать значение элемента + + + Не удается преобразовать System.Object[] в тип System.String, требуемый параметром. Указанный метод не поддерживается. + + + Этот компьютер не настроен на получение учетных данных от удаленного клиентского компьютера. + + + Эту команду нельзя использовать из текущего пути. Перейдите в корневой путь поставщика с помощью cd\ и выполните команду еще раз. + + + Этот командлет PowerShell недоступен в Windows XP и Windows Server 2003. + + + Эту команду нельзя использовать, так как параметр соответствует нетекстовому свойству ResourceURI. Проверьте входные параметры и выполните команду. + + + {0} нельзя указывать, если указан {1}. + + + Клиенту WinRM не удается завершить операцию. Проверьте, что имя компьютера указано правильно. + + + Параметр {0} обязателен, если параметр {1} имеет значение {2}. + + + Эту команду нельзя использовать, так как не указано значение параметра. Проверьте значение еще раз и выполните команду. + + + Эту команду нельзя использовать, так как путь не существует. Проверьте существование пути и выполните команду. + + + Конфигурация безопасности для подключаемого модуля WinRM. + + + Эту команду нельзя использовать в текущем пути, так как этот командлет не поддерживается на этом уровне пути поставщика. + + + Параметры компьютера не позволяют делегировать новые учетные данные. + + + Внесенные изменения конфигурации вступят в силу только после перезапуска службы WinRM. Чтобы перезапустить службу WinRM, выполните следующую команду: Restart-Service winrm + + + Выполнение команды Set-WSManQuickConfig имеет серьезные последствия для безопасности, так как она включает удаленное управление через службу WinRM на этом компьютере. +Эта команда: + 1. Проверяет, запущена ли служба WinRM. Если служба WinRM не запущена, она запускается. + 2. Устанавливает автоматический тип запуска службы WinRM. + 3. Создает прослушиватель для принятия запросов по любому IP-адресу. По умолчанию транспортом является HTTP. + 4. Включает исключение брандмауэра для трафика WS-Management. + 5. Включает проверку подлинности службы Kerberos и Negotiate. +Вы хотите включить удаленное управление через службу WinRM на этом компьютере? + + + Значение RunAsPassword нельзя задать, пока не задано значение RunAsUser. Задайте значения для RunAsUser и RunAsPassword в PowerShell, вызвав командлет Set-Item со значением атрибута -Path, равным значению RunAsUser. + + + Обновленная конфигурация может повлиять на работу подключаемых модулей, у которых значение квоты на один модуль больше {0}. Проверьте конфигурацию всех зарегистрированных подключаемых модулей и измените значения квоты для затронутых модулей. + + + Эта команда устанавливает значение элемента. + +Продолжить? + + + Компьютер настроен на разрешение делегирования новых учетных данных следующим целевым объектам: + + + Корень хранилища конфигурации WsMan. + + + Эту команду нельзя выполнить, так как служба WinRM не запущена. + + + Эту команду нельзя использовать, так как корневой путь не существует. Проверьте корневой путь и выполните команду. + + + Эту команду нельзя использовать в текущем пути, так как Remove-Item не поддерживается на этом уровне пути поставщика. + + + Эта команда изменяет список TrustedHosts для клиента WinRM. Компьютеры в списке TrustedHosts могут не проходить проверку подлинности. Клиент может отправить этим компьютерам сведения об учетных данных. Вы действительно хотите изменить этот список? + + + Эта команда изменяет параметр RootSDDL для службы WinRM. RootSDDL хранит параметры безопасности по умолчанию для любого защищаемого ресурса WinRM, который не задает собственный SDDL. Изменение SDDL может повлиять на безопасность многих ресурсов WinRM. Вы уверены, что хотите изменить эти параметры по умолчанию? + + + Эту команду нельзя использовать без учетных данных, так как алгоритм проверки подлинности — Basic или Digest. Укажите значение с помощью параметра Credentials и выполните команду. + + + Обновленная конфигурация вступает в силу, только если ее значение меньше или равно значению глобальной квоты {0}. Проверьте значение глобальной квоты с помощью командлета PowerShell "Get-Item {0}". + + + Эту команду нельзя выполнить, так как параметр нельзя отключить. + + + Не удалось найти значение элемента {0} в пути {1}. + + + Эту команду нельзя использовать без алгоритма проверки подлинности Basic или Digest, так как указаны учетные данные. Используйте алгоритм проверки подлинности Basic или Digest и выполните команду. + + + Конфигурация безопасности WinRM. + + + Эту команду нельзя использовать в текущем пути, так как New-Item не поддерживается на этом уровне пути поставщика. + + + Эту команду нельзя использовать, так как конфигурация повреждена. Запустите WinRM invoke Restore WinRM/config, чтобы восстановить конфигурацию по умолчанию + + + Невозможно использовать эту команду, так как тип значения параметра недопустим. Конфигурация {0} ожидает значение типа {1}. Проверьте правильность значения и повторите попытку. + + + Служба WinRM сейчас не запущена. При выполнении этой команды служба WinRM будет запущена. + +Продолжить? + + + Эту команду нельзя использовать, так как параметр не соответствует ни одному свойству в ResourceURI. Проверьте входные параметры и выполните команду. + + + Этот компьютер настроен на получение учетных данных от удаленного клиентского компьютера. + + + Параметр {0} нельзя использовать, если параметр {1} имеет значение {2}. Параметр {0} можно использовать, только если параметр {1} имеет значение {3}. + + + Внесенные изменения конфигурации вступят в силу только после перезапуска службы WinRM на {0}. + + + Эту команду нельзя использовать из текущего пути. Перейдите в корневой путь поставщика с помощью cd\ и выполните команду еще раз. + + + Эта оснастка PowerShell содержит такие командлеты как Get-WSManInstance и Set-WSManInstance, которые узел PowerShell использует для управления операциями WSMan. + + + Эту команду нельзя использовать для удаления localhost компьютера, так как он всегда будет подключен. Укажите другой подключенный компьютер и выполните команду. + + + Эта команда создает новый элемент ClientCertificate. + +Продолжить? + + + Значение RunAsPassword нельзя удалить. Удалите значения RunAsUser и RunAsPassword в PowerShell, вызвав командлет Clear-Item со значением атрибута -Path, равным значению RunAsUser. + + + Не удалось создать диск с указанным корнем. Корневой путь не существует. + + + Эту команду нельзя использовать, так как параметр соответствует нескольким свойствам в ResourceURI. Проверьте входные параметры и выполните команду. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/tr/WsManResources.tr.resx b/src/Microsoft.WSMan.Management/resources/tr/WsManResources.tr.resx new file mode 100644 index 00000000000..eaf77ad05f4 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/tr/WsManResources.tr.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Dosya mevcut olmadığından bu komut kullanılamıyor. Dosyanın mevcut olduğunu denetleyin ve komutunuzu çalıştırın. + + + Yeni bir ClientCertificate öğesi oluşturur. + + + Bağlantı URI'si doğru biçimde olmadığından bu komut yürütülemiyor. Lütfen bağlantı URI'sini denetleyin ve komutunuzu yeniden çalıştırın. + + + CredSSP kimlik doğrulaması, bu bilgisayardaki kullanıcı kimlik bilgilerinin uzak bir bilgisayara gönderilmesine izin verir. Kötü amaçlı veya güvenliği ihlal edilmiş bir bilgisayara bağlanmak için CredSSP kimlik doğrulamasını kullanırsanız, o bilgisayar kullanıcı adınıza ve parolanıza erişebilir. Daha fazla bilgi için Enable-WSManCredSSP Yardım konusuna bakın. +CredSSP kimlik doğrulamasını etkinleştirmek istiyor musunuz? + + + Yeni bir Dinleyici öğesi oluşturur. + + + Bu komut, şu WinRM eklentisindeki bir kaynağın güvenlik ayarlarını değiştirir: {0}. +Devam etmek istiyor musunuz? + + + Değeri "{1}" olarak güncelleştirmek için WinRM yapılandırma ayarı "{0}" üzerindeki "Set-Item" + + + Ayar etkinleştirilemediği için bu komut yürütülemiyor. + + + Bu komut yeni bir Dinleyici öğesi oluşturur. + +Devam etmek istiyor musunuz? + + + Erişim reddedildi. Bu cmdlet'i yükseltilmiş bir işlemden çalıştırmanız gerekir. + + + WsMan sürücü kökü Windows işletim sisteminin bu sürümünde desteklenmediğinden bu komut kullanılamıyor. + + + WinRM Hizmetini Başlat + + + CredSSP kimlik doğrulaması, sunucunun uzak bir bilgisayardan kullanıcı kimlik bilgilerini kabul etmesine izin verir. Sunucuda CredSSP kimlik doğrulamasını etkinleştirirseniz, istemci bilgisayar bunları gönderirse sunucu istemci bilgisayarın kullanıcı adı ve parolasına erişebilir. Daha fazla bilgi için Enable-WSManCredSSP Yardım konusuna bakın. +CredSSP kimlik doğrulamasını etkinleştirmek istiyor musunuz? + + + WinRM Hızlı Yapılandırma + + + Microsoft + + + Bu komut, bu değerler kaynak nesnesinin Birincil anahtarları veya Kapsayıcı öğeleri olduğu için giriş değerini ayarlayamaz. Giriş değerini değiştirin ve komutunuzu çalıştırın. + + + WS-Management için CredSSP Kimlik Doğrulama Yapılandırması + + + Öğenin değerini ayarlayın + + + 'System.Object[]', parametrenin gerektirdiği 'System.String' türüne dönüştürülemiyor. Belirtilen yöntem desteklenmiyor. + + + Bu bilgisayar, kimlik bilgilerini uzak bir istemci bilgisayardan alacak şekilde yapılandırıldı. + + + Bu komut geçerli yoldan kullanılamaz. cd\ kullanarak sağlayıcının kök yoluna gidin ve komutunuzu yeniden çalıştırın. + + + Bu PowerShell cmdlet'i Windows XP ve Windows Server 2003'te kullanılamaz. + + + Parametre, ResourceURI üzerindeki metin olmayan bir özellikle eşleştiğinden bu komut kullanılamıyor. Giriş parametrelerini denetleyin ve komutunuzu çalıştırın. + + + {1} belirtildiğinde bir {0} belirtilemez. + + + WinRM istemcisi işlemi tamamlayamıyor. Bilgisayar adının geçerli olup olmadığını denetleyin. + + + {0} parametresi, {1} parametresinin değeri {2}olduğunda zorunludur. + + + Parametre Değeri sağlanmadığından bu komut kullanılamıyor. Değeri yeniden denetleyin ve komutunuzu çalıştırın. + + + Yol mevcut olmadığından bu komut kullanılamıyor. Yolun mevcut olduğunu denetleyin ve komutunuzu çalıştırın. + + + WinRM Eklentisi için Güvenlik Yapılandırması. + + + Bu Sağlayıcı yolunun bu düzeyinde bu cmdlet desteklenmediğinden bu komut geçerli yolda kullanılamaz. + + + Makine, yeni kimlik bilgilerinin temsilci olarak atanmasına izin verecek şekilde yapılandırılmamış. + + + Yaptığınız yapılandırma değişiklikleri yalnızca WinRM hizmeti yeniden başlatıldıktan sonra etkili olur. WinRM hizmetini yeniden başlatmak için şu komutu çalıştırın: 'Restart-Service winrm' + + + Set-WSManQuickConfig komutunu çalıştırmak, bu bilgisayarda WinRM hizmeti aracılığıyla uzaktan yönetimi etkinleştirdiği için önemli güvenlik etkileri oluşturur. +Bu komut: + 1. WinRM hizmetinin çalışıp çalışmadığını denetler. WinRM hizmeti çalışmıyorsa, hizmet başlatılır. + 2. WinRM hizmetinin başlangıç türünü otomatik olarak ayarlar. + Herhangi bir IP adresinde isteği kabul etmek için dinleyici oluşturur. Varsayılan olarak aktarım HTTP'dir. + 4. WS-Management trafiği için bir güvenlik duvarı özel durumunu etkinleştirir. + 5. Kerberos ve Negotiate hizmet kimlik doğrulamasını etkinleştirir. +Bu bilgisayarda WinRM hizmeti aracılığıyla uzaktan yönetimi etkinleştirmek istiyor musunuz? + + + RunAsUser için bir değer ayarlanmadan RunAsPassword değeri ayarlanamaz. -Path özniteliğinin değeri RunAsUser değerine eşit olacak şekilde Set-Item cmdlet'ini çağırarak PowerShell'de hem RunAsUser hem de RunAsPassword değerlerini ayarlayın. + + + Güncelleştirilmiş yapılandırma, eklenti başına kota değeri {0} değerinden büyük olan eklentilerin çalışmasını etkileyebilir. Tüm kayıtlı eklentilerin yapılandırmasını doğrulayın ve etkilenen eklentiler için eklenti başına kota değerlerini değiştirin. + + + Bu komut Item öğesinin değerini ayarlar. + +Devam etmek istiyor musunuz? + + + Makine, yeni kimlik bilgilerinin aşağıdaki hedeflere temsilci olarak atanmasına izin verecek şekilde yapılandırıldı: + + + WsMan Yapılandırma Depolamasının kökü. + + + WinRM Hizmeti başlatılmadığından bu komut yürütülemiyor. + + + Kök yolu mevcut olmadığından bu komut kullanılamıyor. Kök yolunu denetleyin ve komutunuzu çalıştırın. + + + Bu Sağlayıcı yolunun bu düzeyinde Remove-Item desteklenmediğinden bu komut geçerli yolda kullanılamaz. + + + Bu komut, WinRM istemcisinin TrustedHosts listesini değiştirir. TrustedHosts listesindeki bilgisayarların kimliği doğrulanmamış olabilir. İstemci, kimlik bilgilerini bu bilgisayarlara gönderebilir. Bu listeyi değiştirmek istediğinizden emin misiniz? + + + Bu komut, WinRM hizmeti için RootSDDL ayarını değiştirir. RootSDDL, kendi SDDL'sini belirtmeyen tüm WinRM güvenlikli kaynakları için varsayılan güvenlik ayarlarını depolar. SDDL'nin değiştirilmesi, birçok WinRM kaynağının güvenliğini etkileyebilir. Bu varsayılan ayarları değiştirmek istediğinizden emin misiniz? + + + Kimlik doğrulama algoritması Temel veya Özet olduğu için bu komut kimlik bilgileri olmadan kullanılamaz. Değer belirtmek için Credentials parametresini kullanın ve komutunuzu çalıştırın. + + + Güncelleştirilmiş yapılandırma yalnızca genel kota {0} değerinden küçük veya buna eşitse geçerlidir. Genel kota değerini PowerShell cmdlet'i "Get-Item {0}" ile doğrulayın. + + + Ayar devre dışı bırakılamadığı için bu komut yürütülemiyor. + + + {1} yolunda "{0}" öğesi için değer bulunamıyor. + + + Kimlik bilgileri belirtildiği için bu komut Temel veya Özet kimlik doğrulama algoritması olmadan kullanılamaz. Temel veya Özet kimlik doğrulama algoritmasını kullanın ve komutunuzu çalıştırın. + + + WinRM Güvenlik Yapılandırması. + + + Bu Sağlayıcı yolunun bu düzeyinde New-Item desteklenmediğinden bu komut geçerli yolda kullanılamaz. + + + Yapılandırma bozuk olduğundan bu komut kullanılamıyor. Varsayılan yapılandırmayı geri yüklemek için WinRM invoke Restore WinRM/config komutunu çalıştırın + + + Parametre değeri türü geçersiz olduğundan bu komut kullanılamaz. {0} yapılandırması, {1} Türünde bir değer bekliyor. Değerin doğru olduğundan emin olun ve yeniden deneyin. + + + WinRM hizmeti şu anda başlatılmadı. Bu komutu çalıştırmak WinRM hizmetini başlatır. + +Devam etmek istiyor musunuz? + + + Parametre, ResourceURI üzerindeki hiçbir özellikle eşleşmediğinden bu komut kullanılamıyor. Giriş parametrelerini denetleyin ve komutunuzu çalıştırın. + + + Bu bilgisayar, kimlik bilgilerini uzak bir istemci bilgisayardan alacak şekilde yapılandırıldı. + + + {0} parametresi, {1} parametresinin değeri {2}olduğunda kullanılamaz. {0} parametresi yalnızca {1} parametresinin değeri {3} olduğunda kullanılabilir. + + + Yaptığınız yapılandırma değişiklikleri yalnızca WinRM hizmeti {0} üzerinde yeniden başlatıldıktan sonra etkili olur. + + + Bu komut geçerli yoldan kullanılamaz. cd\ kullanarak sağlayıcının kök yoluna gidin ve komutunuzu yeniden çalıştırın. + + + Bu PowerShell ek bileşeni, PowerShell ana bilgisayarı tarafından WSMan işlemlerini yönetmek için kullanılan cmdlet'leri (örneğin Get-WSManInstance ve Set-WSManInstance) içerir. + + + Bu bilgisayar her zaman bağlı olduğundan, bu komut, 'localhost' bilgisayarını kaldırmak için kullanılamaz. Başka bir bağlı bilgisayar belirtin ve komutunuzu çalıştırın. + + + Bu komut yeni bir ClientCertificate öğesi oluşturur. + +Devam etmek istiyor musunuz? + + + RunAsPassword değeri kaldırılamaz. -Path özniteliğinin değeri RunAsUser değerine eşit olacak şekilde Clear-Item cmdlet'ini çağırarak PowerShell'de RunAsUser ve RunAsPassword değerlerini kaldırın. + + + Belirtilen köke sahip bir sürücü oluşturulamıyor. Kök yol yok. + + + Parametre, ResourceURI üzerindeki birden fazla özellikle eşleştiğinden bu komut kullanılamıyor. Giriş parametrelerini denetleyin ve komutunuzu çalıştırın. + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/zh-Hans/WsManResources.zh-Hans.resx b/src/Microsoft.WSMan.Management/resources/zh-Hans/WsManResources.zh-Hans.resx new file mode 100644 index 00000000000..f234a0ecad5 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/zh-Hans/WsManResources.zh-Hans.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法使用此命令,因为文件不存在。检查文件是否存在并运行命令。 + + + 创建新的 ClientCertificate 项。 + + + 无法执行此命令,因为连接 URI 的格式不正确。请检查连接 URI,然后再次运行命令。 + + + CredSSP 身份验证允许将此计算机上的用户凭据发送到远程计算机。如果你使用 CredSSP 身份验证连接到恶意计算机或已遭入侵的计算机,该计算机将可以访问你的用户名和密码。有关详细信息,请参阅 Enable-WSManCredSSP 帮助主题。 +是否要启用 CredSSP 身份验证? + + + 创建新的侦听器项。 + + + 此命令将修改以下 WinRM 插件中资源的安全设置: {0}。 +是否要继续? + + + WinRM 配置设置“{0}”上的 "Set-Item" 将值更新为“{1}” + + + 无法执行此命令,因为无法启用该设置。 + + + 此命令将创建一个新的侦听器项。 + +是否要继续? + + + 拒绝访问。需要从提升的进程运行此 cmdlet。 + + + 无法使用此命令,因为此版本的 Windows 操作系统不支持 WsMan 驱动器根目录。 + + + 启动 WinRM 服务 + + + CredSSP 身份验证允许服务器接受来自远程计算机的用户凭据。如果在服务器上启用 CredSSP 身份验证,并且客户端计算机发送了这些凭据,则服务器将可以访问客户端计算机的用户名和密码。有关详细信息,请参阅 Enable-WSManCredSSP 帮助主题。 +是否要启用 CredSSP 身份验证? + + + WinRM 快速配置 + + + Microsoft + + + 此命令无法设置输入值,因为这些值是资源对象的主键或容器项。请更改输入值并运行命令。 + + + WS-Management 的 CredSSP 身份验证配置 + + + 设置项的值 + + + 无法将 "System.Object[]" 转换为参数所需的类型 "System.String"。不支持指定的方法。 + + + 此计算机未配置为接收来自远程客户端计算机的凭据。 + + + 无法从当前路径使用此命令。请使用 cd\ 转到提供程序的根路径,然后再次运行命令。 + + + 此 PowerShell cmdlet 在 Windows XP 和 Windows Server 2003 上不可用。 + + + 无法使用此命令,因为参数与 ResourceURI 上的非文本属性匹配。请检查输入参数并运行命令。 + + + 指定 {1} 时,无法指定 {0}。 + + + WinRM 客户端无法完成该操作。请检查计算机名是否有效。 + + + 当 {1} 参数值为 {2} 时,{0} 参数是必需的。 + + + 无法使用此命令,因为未提供参数值。请再次检查值并运行命令。 + + + 无法使用此命令,因为路径不存在。检查路径是否存在并运行命令。 + + + WinRM 插件的安全配置。 + + + 无法在当前路径中使用此命令,因为此级别的提供程序路径不支持此 cmdlet。 + + + 未将此计算机配置为允许委派新凭据。 + + + 所做的配置更改仅在 WinRM 服务重新启动后才有效。 要重新启动 WinRM 服务,请运行以下命令: "Restart-Service winrm" + + + 运行 Set-WSManQuickConfig 命令具有重大的安全隐患,因为它可通过此计算机上的 WinRM 服务进行远程管理。 +此命令: + 1. 检查 WinRM 服务是否正在运行。如果 WinRM 服务未运行,则启动该服务。 + 2. 将 WinRM 服务启动类型设置为自动。 + 3. 创建一个可接受任何 IP 地址上的请求的侦听器。默认情况下,传输为 HTTP。 + 4. 为 WS-Management 流量启用防火墙例外。 + 5. 启用 Kerberos 和 Negotiate 服务身份验证。 +是否要在此计算机上通过 WinRM 服务启用远程管理? + + + 如果未为 RunAsUser 设置值,则无法设置 RunAsPassword 的值。调用 Set-Item cmdlet,并将 -Path 属性的值设为 RunAsUser 的值,以在 Powershell 中设置 RunAsUser 和 RunAsPassword 的值。 + + + 更新的配置可能会影响每个插件配额值大于 {0} 的插件的操作。验证所有已注册插件的配置,并更改受影响插件的每个插件配额值。 + + + 此命令设置该项的值。 + +是否要继续? + + + 计算机配置为允许将新凭据委派给以下目标: + + + WsMan 配置存储的根目录。 + + + 无法执行此命令,因为 WinRM 服务未启动。 + + + 根路径不存在,无法使用此命令。请检查根路径并运行命令。 + + + 无法在当前路径中使用此命令,因为此级别的提供程序路径不支持 Remove-Item。 + + + 此命令将修改 WinRM 客户端的 TrustedHosts 列表。TrustedHosts 列表中的计算机可能未通过身份验证。客户端可能会向这些计算机发送凭据信息。是否确定要修改此列表? + + + 此命令会修改 WinRM 服务的 RootSDDL 设置。 RootSDDL 存储任何未指定自身 SDDL 的 WinRM 安全资源的默认安全设置。更改 SDDL 可能会影响许多 WinRM 资源的安全性。是否确定要修改这些默认设置? + + + 由于身份验证算法为 Basic 或 Digest,因此无法在没有凭据的情况下使用此命令。使用 Credentials 参数指定值并运行命令。 + + + 更新后的配置仅在其小于或等于全局配额 {0} 的值时才生效。请使用 PowerShell cmdlet“Get-Item {0}”验证全局配额的值。 + + + 无法执行此命令,因为无法禁用该设置。 + + + 在路径 {1} 中找不到“{0}”元素的值。 + + + 由于已指定凭据,因此不能在没有 Basic 或 Digest 身份验证算法的情况下使用此命令。请使用 Basic 或 Digest 身份验证算法并运行命令。 + + + WinRM 安全配置。 + + + 无法在当前路径中使用此命令,因为此级别的提供程序路径不支持 New-Item。 + + + 无法使用此命令,因为配置已损坏。请运行 WinRM invoke Restore WinRM/config 以还原默认配置 + + + 无法使用此命令,因为参数值类型无效。{0} 配置需要类型为 {1} 的值。请验证值是否正确,然后重试。 + + + 当前未启动 WinRM 服务。运行此命令将启动 WinRM 服务。 + +是否要继续? + + + 无法使用此命令,因为该参数与 ResourceURI 上的任何属性都不匹配。请检查输入参数并运行命令。 + + + 此计算机配置为接收来自远程客户端计算机的凭据。 + + + 当 {1} 参数值为 {2} 时,无法使用 {0} 参数。仅当 {1} 参数值为 {3} 时,才能使用 {0} 参数。 + + + 只有在 {0} 上重新启动 WinRM 服务后,所做的配置更改才会生效。 + + + 无法从当前路径使用此命令。请使用 cd\ 转到提供程序的根路径,然后再次运行命令。 + + + 此 PowerShell 管理单元包含由 PowerShell 主机用来管理 WSMan 操作的 cmdlet (例如 Get-WSManInstance 和 Set-WSManInstance)。 + + + 此命令不能用于删除计算机 "localhost",因为它将始终处于连接状态。请提供其他已连接的计算机并运行命令。 + + + 此命令创建新的 ClientCertificate 项。 + +是否要继续? + + + 无法删除 RunAsPassword 值。通过调用 Clear-Item cmdlet (其中 -Path 属性的值等于 RunAsUser 的值)来删除 PowerShell 中 RunAsUser 和 RunAsPassword 的值。 + + + 无法使用指定的根创建驱动器。根路径不存在。 + + + 无法使用此命令,因为该参数与 ResourceURI 上的多个属性匹配。请检查输入参数并运行命令。 + + \ No newline at end of file diff --git a/src/Microsoft.WSMan.Management/resources/zh-Hant/WsManResources.zh-Hant.resx b/src/Microsoft.WSMan.Management/resources/zh-Hant/WsManResources.zh-Hant.resx new file mode 100644 index 00000000000..63e1da5a520 --- /dev/null +++ b/src/Microsoft.WSMan.Management/resources/zh-Hant/WsManResources.zh-Hant.resx @@ -0,0 +1,330 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 因為檔案不存在,所以無法使用此命令。請檔案存在,然後執行您的命令。 + + + 建立新的 ClientCertificate 項目。 + + + 因為連線 URI 的格式不正確,所以無法執行此命令。請檢查連線 URI,然後再次執行您的命令。 + + + CredSSP 驗證可讓此電腦上的使用者認證傳送到遠端電腦。如果您使用 CredSSP 驗證連線到惡意或已遭入侵的電腦,該電腦就能存取您的使用者名稱和密碼。如需詳細資訊,請參閱 Enable-WSManCredSSP 說明主題。 +您要啟用 CredSSP 驗證嗎? + + + 建立新接聽程式項目。 + + + 此命令會修改下列 WinRM 外掛程式中資源的安全性設定: {0}。 +要繼續嗎? + + + 在 WinRM 組態設定 "{0}" 上使用 "Set-Item",將值更新為 "{1}" + + + 因為無法啟用設定,所以無法執行此命令。 + + + 此命令會建立新的接聽程式項目。 + +要繼續嗎? + + + 存取遭到拒絕。您必須從已提升權限的程序執行此 Cmdlet。 + + + 因為此 Windows 作業系統版本不支援 WsMan 磁碟機根目錄,所以無法使用此命令。 + + + 啟動 WinRM 服務 + + + CredSSP 驗證可讓伺服器接受來自遠端電腦的使用者認證。如果您在伺服器上啟用 CredSSP 驗證,當用戶端電腦傳送這些認證時,伺服器就能存取用戶端電腦的使用者名稱和密碼。如需詳細資訊,請參閱 Enable-WSManCredSSP 說明主題。 +您要啟用 CredSSP 驗證嗎? + + + WinRM 快速設定 + + + Microsoft + + + 此命令無法設定輸入值,因為這些值是資源物件的主索引鍵或容器項目。請變更輸入值,然後執行您的命令。 + + + WS-Management 的 CredSSP 驗證設定 + + + 設定項目的值 + + + 無法將 'System.Object[]' 轉換為參數所需的 'System.String' 類型。不支援指定的方法。 + + + 此電腦未設定為接收來自遠端用戶端電腦的認證。 + + + 無法從目前的路徑使用此命令。請使用 cd\ 移至提供者的根路徑,然後再次執行您的命令。 + + + 此 PowerShell Cmdlet 無法在 Windows XP 和 Windows Server 2003 上使用。 + + + 因為參數符合 ResourceURI 上的非文字屬性,所以無法使用此命令。請檢查輸入參數,然後執行您的命令。 + + + 當指定 {1} 時,無法指定 {0}。 + + + WinRM 用戶端無法完成作業。請檢查電腦名稱是否有效。 + + + 當 {1} 參數的值為 {2} 時,{0} 參數為必要參數。 + + + 因為未提供參數值,所以無法使用此命令。請再次檢查值,然後執行您的命令。 + + + 因為路徑不存在,所以無法使用此命令。請路徑存在,然後執行您的命令。 + + + WinRM 外掛程式的安全性設定。 + + + 因為此層級的提供者路徑不支援此 Cmdlet,所以無法在目前的路徑中使用此命令。 + + + 尚未設定電腦以允許委派新認證。 + + + 您所做的設定變更,只有在 WinRM 服務重新啟動 WinRM 服務後才會生效。 若要重新啟動 WinRM 服務,請執行下列命令: 'Restart-Service winrm' + + + 執行 Set-WSManQuickConfig 命令會對安全性造成重大影響,因為它會透過此電腦上的 WinRM 服務啟用遠端管理。 +此命令: + 1. 檢查 WinRM 服務是否正在執行。若 WinRM 服務未執行,會啟動該服務。 + 2. 將 WinRM 服務的啟動類型設定為自動。 + 3. 建立接聽程式,以接受任何 IP 位址的要求。根據預設,傳輸通訊協定是 HTTP。 + 4. 針對 WS-Management 流量啟用防火牆例外狀況。 + 5. 啟用 Kerberos 和 Negotiate 服務驗證。 +您要透過此電腦上的 WinRM 服務啟用遠端管理嗎? + + + 若未設定 RunAsUser 的值,就無法設定 RunAsPassword 的值。請在 PowerShell 中呼叫 Set-Item Cmdlet,並將 -Path 屬性的值設為 RunAsUser 的值,以設定 RunAsUser 和 RunAsPassword 的值。 + + + 更新的設定可能會影響每個外掛程式配額值大於 {0} 的外掛程式作業。請確認所有已註冊外掛程式的設定,並變更受影響外掛程式的每個外掛程式配額值。 + + + 此命令會設定項目的值。 + +要繼續嗎? + + + 電腦已設定為允許將新的認證委派給下列目標: + + + WsMan 設定儲存區的根目錄。 + + + 因為 WinRM 服務未啟動,所以無法執行此命令。 + + + 因為根路徑不存在,所以無法使用此命令。請檢查根路徑,然後執行您的命令。 + + + 因為此層級的提供者路徑不支援 Remove-Item,所以無法在目前的路徑中使用此命令。 + + + 此命令會修改 WinRM 用戶端的 TrustedHosts 清單。TrustedHosts 清單中的電腦可能未經驗證。用戶端可能會將認證資訊傳送給這些電腦。確定要修改此清單嗎? + + + 此命令會修改 WinRM 服務的 RootSDDL 設定。 RootSDDL 會儲存任何未指定其本身 SDDL 之 WinRM 安全資源的預設安全性設定。變更 SDDL 可能會影響許多 WinRM 資源的安全性。確定要修改這些預設設定嗎? + + + 因為驗證演算法為 Basic 或 Digest,所以沒有認證無法使用此命令。請使用 Credentials 參數指定值,然後執行您的命令。 + + + 更新的設定只有在小於或等於全域配額 {0} 的值時才會生效。請使用 PowerShell Cmdlet "Get-Item {0}" 驗證全域配額的值。 + + + 因為無法停用設定,所以無法執行此命令。 + + + 在路徑 {1} 中找不到 "{0}" 元素的值。 + + + 因為已指定認證,所以無法在沒有 Basic 或 Digest 驗證演算法的情況下使用此命令。請使用 Basic 或 Digest 驗證演算法,然後執行您的命令。 + + + WinRM 安全性設定。 + + + 因為此層級的提供者路徑不支援 New-Item,所以無法在目前的路徑中使用此命令。 + + + 因為設定已損毀,所以無法使用此命令。請執行 WinRM invoke Restore WinRM/config 以還原預設設定 + + + 因為參數值類型無效,所以無法使用此命令。{0} 設定必須為類型值 {1}。請確認值正確,然後再試一次。 + + + WinRM 服務目前未啟動。執行此命令會啟動 WinRM 服務。 + +要繼續嗎? + + + 因為參數不符合 ResourceURI 上的任何屬性,所以無法使用此命令。請檢查輸入參數,然後執行您的命令。 + + + 此電腦已設定為接收來自遠端用戶端電腦的認證。 + + + 當 {1} 參數的值為 {2} 時,無法使用 {0} 參數。只有當 {1} 參數的值為 {3} 時,才能使用 {0} 參數。 + + + 您所做的設定變更,只有在 {0} 重新啟動 WinRM 服務後才會生效。 + + + 無法從目前的路徑使用此命令。請使用 cd\ 移至提供者的根路徑,然後再次執行您的命令。 + + + 此 PowerShell 嵌入式管理單元包含 Cmdlet (例如 Get-WSManInstance 和 Set-WSManInstance),供 PowerShell 主機用來管理 WSMan 作業。 + + + 此命令無法用來移除電腦 'localhost',因為它會一直保持連線。請提供其他已連線的電腦,然後執行您的命令。 + + + 此命令會建立新的 ClientCertificate 項目。 + +要繼續嗎? + + + 無法移除 RunAsPassword 值。請在 PowerShell 中呼叫 Clear-Item Cmdlet,並將 -Path 屬性的值設為 RunAsUser 的值,以移除 RunAsUser 和 RunAsPassword 的值。 + + + 無法使用指定的根目錄建立磁碟機。根路徑不存在。 + + + 因為參數符合 ResourceURI 上多個屬性,所以無法使用此命令。請檢查輸入參數,然後執行您的命令。 + + \ No newline at end of file diff --git a/src/Modules/PSGalleryModules.csproj b/src/Modules/PSGalleryModules.csproj index ae838f27601..ad19ae75b1a 100644 --- a/src/Modules/PSGalleryModules.csproj +++ b/src/Modules/PSGalleryModules.csproj @@ -5,18 +5,18 @@ Microsoft Corporation (c) Microsoft Corporation. - net6.0 + net11.0 true - - - - - + + + + + diff --git a/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 b/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 index 0270ceffca0..3c2581795f7 100644 --- a/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 +++ b/src/Modules/Shared/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.psd1 @@ -10,5 +10,5 @@ FunctionsToExport = @() CmdletsToExport="Start-Transcript", "Stop-Transcript" AliasesToExport = @() NestedModules="Microsoft.PowerShell.ConsoleHost.dll" -HelpInfoURI = 'https://aka.ms/powershell71-help' +HelpInfoURI = 'https://aka.ms/powershell75-help' } diff --git a/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 index da8f8707945..21563c1da7c 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -7,7 +7,7 @@ ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" NestedModules="Microsoft.PowerShell.Commands.Management.dll" -HelpInfoURI = 'https://aka.ms/powershell71-help' +HelpInfoURI = 'https://aka.ms/powershell75-help' FunctionsToExport = @() AliasesToExport = @("gcb", "gtz", "scb") CmdletsToExport=@("Add-Content", diff --git a/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 index 1f4cc15e118..adab0df2849 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 @@ -1,14 +1,14 @@ @{ -GUID="A94C8C7E-9810-47C0-B8AF-65089C13A35A" -Author="PowerShell" -CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation." -ModuleVersion="7.0.0.0" +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" +PowerShellVersion = "3.0" FunctionsToExport = @() -CmdletsToExport="Get-Credential", "Get-ExecutionPolicy", "Set-ExecutionPolicy", "ConvertFrom-SecureString", "ConvertTo-SecureString", "Get-PfxCertificate" , "Protect-CmsMessage", "Unprotect-CmsMessage", "Get-CmsMessage" +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/powershell71-help' +NestedModules = "Microsoft.PowerShell.Security.dll" +HelpInfoURI = 'https://aka.ms/powershell75-help' } diff --git a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index b883acdd0d6..df841837696 100644 --- a/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Unix/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -19,30 +19,17 @@ CmdletsToExport = @( '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', 'Invoke-RestMethod', 'Debug-Runspace', 'Get-Runspace', + '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' + '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/powershell71-help' -PrivateData = @{ - PSData = @{ - ExperimentalFeatures = @( - @{ - Name = 'Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace' - Description = 'Enables -BreakAll parameter on Debug-Runspace and Debug-Job cmdlets to allow users to decide if they want PowerShell to break immediately in the current location when they attach a debugger. Enables -Runspace parameter on *-PSBreakpoint cmdlets to support management of breakpoints in another runspace.' - } - @{ - Name = 'Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck' - Description = 'Enable -SkipLimitCheck switch for Import-PowerShellDataFile to not enforce built-in hashtable limits' - } - ) - } -} +HelpInfoURI = 'https://aka.ms/powershell75-help' } diff --git a/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 b/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 index 4b38d4abc9e..734fe45016d 100644 --- a/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 +++ b/src/Modules/Windows/CimCmdlets/CimCmdlets.psd1 @@ -14,5 +14,5 @@ CmdletsToExport= "Get-CimAssociatedInstance", "Get-CimClass", "Get-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/powershell71-help" +HelpInfoUri="https://aka.ms/powershell75-help" } diff --git a/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 index ed2344b51b2..7f77777b137 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.psd1 @@ -12,5 +12,5 @@ AliasesToExport = @() NestedModules="Microsoft.PowerShell.Commands.Diagnostics.dll" TypesToProcess="GetEvent.types.ps1xml" FormatsToProcess="Event.format.ps1xml", "Diagnostics.format.ps1xml" -HelpInfoURI = 'https://aka.ms/powershell71-help' +HelpInfoURI = 'https://aka.ms/powershell75-help' } diff --git a/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 index f7cd1dc6ace..f7582920935 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.psd1 @@ -7,7 +7,7 @@ ModuleVersion="7.0.0.0" CompatiblePSEditions = @("Core") PowerShellVersion="3.0" NestedModules="Microsoft.PowerShell.Commands.Management.dll" -HelpInfoURI = 'https://aka.ms/powershell71-help' +HelpInfoURI = 'https://aka.ms/powershell75-help' FunctionsToExport = @() AliasesToExport = @("gcb", "gin", "gtz", "scb", "stz") CmdletsToExport=@("Add-Content", diff --git a/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 index cbc5b2dc78e..0953b2d1cca 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1 @@ -1,14 +1,18 @@ @{ -GUID="A94C8C7E-9810-47C0-B8AF-65089C13A35A" -Author="PowerShell" -CompanyName="Microsoft Corporation" -Copyright="Copyright (c) Microsoft Corporation." -ModuleVersion="7.0.0.0" +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" +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" +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" -HelpInfoURI = 'https://aka.ms/powershell71-help' +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/src/Modules/Windows/Microsoft.PowerShell.Security/Security.types.ps1xml b/src/Modules/Windows/Microsoft.PowerShell.Security/Security.types.ps1xml new file mode 100644 index 00000000000..b1171c98e6a --- /dev/null +++ b/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/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 index 5ea504197fa..2043543a8a5 100644 --- a/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 +++ b/src/Modules/Windows/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.psd1 @@ -17,31 +17,17 @@ CmdletsToExport = @( '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', + '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' + 'Out-GridView', 'Show-Command', 'Out-Printer', 'ConvertTo-CliXml', 'ConvertFrom-CliXml' ) FunctionsToExport = @() AliasesToExport = @('fhx') NestedModules = @("Microsoft.PowerShell.Commands.Utility.dll") -HelpInfoURI = 'https://aka.ms/powershell71-help' -PrivateData = @{ - PSData = @{ - ExperimentalFeatures = @( - @{ - Name = 'Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace' - Description = 'Enables -BreakAll parameter on Debug-Runspace and Debug-Job cmdlets to allow users to decide if they want PowerShell to break immediately in the current location when they attach a debugger. Enables -Runspace parameter on *-PSBreakpoint cmdlets to support management of breakpoints in another runspace.' - } - @{ - Name = 'Microsoft.PowerShell.Utility.PSImportPSDataFileSkipLimitCheck' - Description = 'Enable -NoLimit switch for Import-PowerShellDataFile to not enforce built-in hashtable limits' - } - ) - } -} +HelpInfoURI = 'https://aka.ms/powershell75-help' } diff --git a/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 b/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 index d2bb2398541..ced706c9fde 100644 --- a/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 +++ b/src/Modules/Windows/Microsoft.WSMan.Management/Microsoft.WSMan.Management.psd1 @@ -11,5 +11,5 @@ CmdletsToExport="Disable-WSManCredSSP", "Enable-WSManCredSSP", "Get-WSManCredSSP AliasesToExport = @() NestedModules="Microsoft.WSMan.Management.dll" FormatsToProcess="WSMan.format.ps1xml" -HelpInfoURI = 'https://aka.ms/powershell71-help' +HelpInfoURI = 'https://aka.ms/powershell75-help' } diff --git a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 index dded04d4920..3b53d6740e5 100644 --- a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 +++ b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psd1 @@ -10,5 +10,5 @@ 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/powershell71-help" + HelpInfoUri="https://aka.ms/powershell75-help" } diff --git a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 index ce0739eb622..c31e9f25963 100644 --- a/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 +++ b/src/Modules/Windows/PSDiagnostics/PSDiagnostics.psm1 @@ -4,21 +4,22 @@ <# PowerShell Diagnostics Module This module contains a set of wrapper scripts that - enable a user to use ETW tracing in Windows - PowerShell. + enable a user to use ETW tracing in PowerShell 7. #> -$script:Logman="$env:windir\system32\logman.exe" -$script:wsmanlogfile = "$env:windir\system32\wsmtraces.log" -$script:wsmprovfile = "$env:windir\system32\wsmtraceproviders.txt" +$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="Microsoft-Windows-PowerShell" +$script:psprovidername = "PowerShellCore" $script:wsmprovidername = "Microsoft-Windows-WinRM" $script:oplog = "/Operational" -$script:analyticlog="/Analytic" -$script:debuglog="/Debug" -$script:wevtutil="$env:windir\system32\wevtutil.exe" +$script:analyticlog = "/Analytic" +$script:debuglog = "/Debug" +$script:wevtutil = "${script:windir}\system32\wevtutil.exe" $script:slparam = "sl" $script:glparam = "gl" @@ -169,7 +170,6 @@ function Enable-PSWSManCombinedTrace $provfile = [io.path]::GetTempFilename() - $traceFileName = [string][Guid]::NewGuid() if ($DoNotOverwriteExistingTrace) { $fileName = [string][guid]::newguid() $logfile = $PSHOME + "\\Traces\\PSTrace_$fileName.etl" @@ -177,8 +177,8 @@ function Enable-PSWSManCombinedTrace $logfile = $PSHOME + "\\Traces\\PSTrace.etl" } - "Microsoft-Windows-PowerShell 0 5" | Out-File $provfile -Encoding ascii - "Microsoft-Windows-WinRM 0 5" | Out-File $provfile -Encoding ascii -Append + "$script:psprovidername 0 5" | Out-File $provfile -Encoding ascii + "$script:wsmprovidername 0 5" | Out-File $provfile -Encoding ascii -Append if (!(Test-Path $PSHOME\Traces)) { @@ -192,7 +192,7 @@ function Enable-PSWSManCombinedTrace Start-Trace -SessionName $script:pssession -OutputFilePath $logfile -ProviderFilePath $provfile -ETS - Remove-Item $provfile -Force -ea 0 + Remove-Item $provfile -Force -ErrorAction SilentlyContinue } function Disable-PSWSManCombinedTrace diff --git a/src/Modules/nuget.config b/src/Modules/nuget.config index f5a7f806a36..388a65572dd 100644 --- a/src/Modules/nuget.config +++ b/src/Modules/nuget.config @@ -2,8 +2,7 @@ - - + diff --git a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man index 5d4dd473f4b..bb4e15351e5 100644 --- a/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man +++ b/src/PowerShell.Core.Instrumentation/PowerShell.Core.Instrumentation.man @@ -121,6 +121,18 @@ value="0x3002" version="1" /> + + + + + + this cell is the table header, footer or body --> bottom @@ -381,4 +381,4 @@ - \ No newline at end of file + diff --git a/src/System.Management.Automation/AssemblyInfo.cs b/src/System.Management.Automation/AssemblyInfo.cs index 1963b331ef1..e265bb453c8 100644 --- a/src/System.Management.Automation/AssemblyInfo.cs +++ b/src/System.Management.Automation/AssemblyInfo.cs @@ -6,33 +6,12 @@ using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("powershell-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("powershell-perf,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] +[assembly: InternalsVisibleTo("powershell-fuzz-tests,PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -[assembly: InternalsVisibleTo("Microsoft.Test.Management.Automation.GPowershell.Analyzers,PublicKey=00240000048000009400000006020000002400005253413100040000010001003f8c902c8fe7ac83af7401b14c1bd103973b26dfafb2b77eda478a2539b979b56ce47f36336741b4ec52bbc51fecd51ba23810cec47070f3e29a2261a2d1d08e4b2b4b457beaa91460055f78cc89f21cd028377af0cc5e6c04699b6856a1e49d5fad3ef16d3c3d6010f40df0a7d6cc2ee11744b5cfb42e0f19a52b8a29dc31b0")] - -#if NOT_SIGNED -// These attributes aren't every used, it's just a hack to get VS to not complain -// about access when editing using the project files that don't actually build. -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Utility")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Management")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Security")] -[assembly: InternalsVisibleTo(@"System.Management.Automation.Remoting")] -[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ConsoleHost")] -#else [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Utility" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Commands.Management" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.Security" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo(@"System.Management.Automation.Remoting" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] [assembly: InternalsVisibleTo(@"Microsoft.PowerShell.ConsoleHost" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] -#endif - -namespace System.Management.Automation -{ - internal static class NTVerpVars - { - internal const int PRODUCTMAJORVERSION = 10; - internal const int PRODUCTMINORVERSION = 0; - internal const int PRODUCTBUILD = 10032; - internal const int PRODUCTBUILD_QFE = 0; - internal const int PACKAGEBUILD_QFE = 814; - } -} +[assembly: InternalsVisibleTo(@"Microsoft.PowerShell.DscSubsystem" + @",PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] diff --git a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs index 5bd9be5c62b..5a15df53ca8 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsAssemblyLoadContext.cs @@ -9,13 +9,14 @@ using System.Runtime.InteropServices; using System.Reflection; using System.Runtime.Loader; +using Microsoft.PowerShell.Telemetry; namespace System.Management.Automation { /// /// The powershell custom AssemblyLoadContext implementation. /// - internal partial class PowerShellAssemblyLoadContext + internal sealed partial class PowerShellAssemblyLoadContext { #region Resource_Strings @@ -36,16 +37,19 @@ internal partial class PowerShellAssemblyLoadContext /// /// Initialize a singleton of PowerShellAssemblyLoadContext. /// - internal static PowerShellAssemblyLoadContext InitializeSingleton(string basePaths) + internal static PowerShellAssemblyLoadContext InitializeSingleton(string basePaths, bool throwOnReentry) { lock (s_syncObj) { - if (Instance != null) + if (Instance is null) + { + Instance = new PowerShellAssemblyLoadContext(basePaths); + } + else if (throwOnReentry) { throw new InvalidOperationException(SingletonAlreadyInitialized); } - Instance = new PowerShellAssemblyLoadContext(basePaths); return Instance; } } @@ -232,6 +236,9 @@ internal IEnumerable GetAssembly(string namespaceQualifiedTypeName) /// | /// |--- 'osx-x64' subfolder /// | |--- native.dylib + /// | + /// |--- 'osx-arm64' subfolder + /// | |--- native.dylib /// internal static IntPtr NativeDllHandler(Assembly assembly, string libraryName) { @@ -343,9 +350,6 @@ private bool TryFindInGAC(AssemblyName assemblyName, out string assemblyFilePath return false; } - bool assemblyFound = false; - char dirSeparator = IO.Path.DirectorySeparatorChar; - if (string.IsNullOrEmpty(_winDir)) { // cache value of '_winDir' folder in member variable. @@ -355,21 +359,21 @@ private bool TryFindInGAC(AssemblyName assemblyName, out string assemblyFilePath if (string.IsNullOrEmpty(_gacPathMSIL)) { // cache value of '_gacPathMSIL' folder in member variable. - _gacPathMSIL = $"{_winDir}{dirSeparator}Microsoft.NET{dirSeparator}assembly{dirSeparator}GAC_MSIL"; + _gacPathMSIL = Path.Join(_winDir, "Microsoft.NET", "assembly", "GAC_MSIL"); } - assemblyFound = FindInGac(_gacPathMSIL, assemblyName, out assemblyFilePath); + bool assemblyFound = FindInGac(_gacPathMSIL, assemblyName, out assemblyFilePath); if (!assemblyFound) { - string gacBitnessAwarePath = null; + string gacBitnessAwarePath; if (Environment.Is64BitProcess) { if (string.IsNullOrEmpty(_gacPath64)) { - // cache value of '_gacPath64' folder in member variable. - _gacPath64 = $"{_winDir}{dirSeparator}Microsoft.NET{dirSeparator}assembly{dirSeparator}GAC_64"; + var gacName = RuntimeInformation.ProcessArchitecture == Architecture.Arm64 ? "GAC_Arm64" : "GAC_64"; + _gacPath64 = Path.Join(_winDir, "Microsoft.NET", "assembly", gacName); } gacBitnessAwarePath = _gacPath64; @@ -378,8 +382,7 @@ private bool TryFindInGAC(AssemblyName assemblyName, out string assemblyFilePath { if (string.IsNullOrEmpty(_gacPath32)) { - // cache value of '_gacPath32' folder in member variable. - _gacPath32 = $"{_winDir}{dirSeparator}Microsoft.NET{dirSeparator}assembly{dirSeparator}GAC_32"; + _gacPath32 = Path.Join(_winDir, "Microsoft.NET", "assembly", "GAC_32"); } gacBitnessAwarePath = _gacPath32; @@ -397,13 +400,12 @@ private static bool FindInGac(string gacRoot, AssemblyName assemblyName, out str bool assemblyFound = false; assemblyPath = null; - char dirSeparator = IO.Path.DirectorySeparatorChar; - string tempAssemblyDirPath = $"{gacRoot}{dirSeparator}{assemblyName.Name}"; + string tempAssemblyDirPath = Path.Join(gacRoot, assemblyName.Name); if (Directory.Exists(tempAssemblyDirPath)) { // Enumerate all directories, sort by name and select the last. This selects the latest version. - var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).OrderBy(d => d).LastOrDefault(); + var chosenVersionDirectory = Directory.EnumerateDirectories(tempAssemblyDirPath).Order().LastOrDefault(); if (!string.IsNullOrEmpty(chosenVersionDirectory)) { @@ -540,19 +542,19 @@ private static string GetNativeDllSubFolderName(out string ext) ext = string.Empty; var processArch = RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(); - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (Platform.IsWindows) { folderName = "win-" + processArch; ext = ".dll"; } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + else if (Platform.IsLinux) { folderName = "linux-" + processArch; ext = ".so"; } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) + else if (Platform.IsMacOS) { - folderName = "osx-x64"; + folderName = "osx-" + processArch; ext = ".dylib"; } @@ -581,10 +583,44 @@ public static class PowerShellAssemblyLoadContextInitializer /// public static void SetPowerShellAssemblyLoadContext([MarshalAs(UnmanagedType.LPWStr)] string basePaths) { - if (string.IsNullOrEmpty(basePaths)) - throw new ArgumentNullException(nameof(basePaths)); + ArgumentException.ThrowIfNullOrEmpty(basePaths); + + // Disallow calling this method from native code for more than once. + PowerShellAssemblyLoadContext.InitializeSingleton(basePaths, throwOnReentry: true); + } + } + + /// + /// Provides helper functions to facilitate calling managed code from a native PowerShell host. + /// + public static unsafe class PowerShellUnsafeAssemblyLoad + { + /// + /// Load an assembly in memory from unmanaged code. + /// + /// + /// This API is covered by the experimental feature 'PSLoadAssemblyFromNativeCode', + /// and it may be deprecated and removed in future. + /// + /// Unmanaged pointer to assembly data buffer. + /// Size in bytes of the assembly data buffer. + /// Returns zero on success and non-zero on failure. + [UnmanagedCallersOnly] + public static int LoadAssemblyFromNativeMemory(IntPtr data, int size) + { + int result = 0; + try + { + using var stream = new UnmanagedMemoryStream((byte*)data, size); + AssemblyLoadContext.Default.LoadFromStream(stream); + } + catch + { + result = -1; + } - PowerShellAssemblyLoadContext.InitializeSingleton(basePaths); + ApplicationInsightsTelemetry.SendUseTelemetry("PowerShellUnsafeAssemblyLoad", result == 0 ? "1" : "0"); + return result; } } } diff --git a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs index b5e657d497f..4cbb346fb14 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsPlatform.cs @@ -5,19 +5,16 @@ using System.ComponentModel; using System.IO; using System.Runtime.InteropServices; - +using System.Management.Automation.Internal; using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; namespace System.Management.Automation { /// /// These are platform abstractions and platform specific implementations. /// - public static class Platform + public static partial class Platform { - private static string _tempDirectory = null; - /// /// True if the current platform is Linux. /// @@ -25,7 +22,7 @@ public static bool IsLinux { get { - return RuntimeInformation.IsOSPlatform(OSPlatform.Linux); + return OperatingSystem.IsLinux(); } } @@ -36,7 +33,7 @@ public static bool IsMacOS { get { - return RuntimeInformation.IsOSPlatform(OSPlatform.OSX); + return OperatingSystem.IsMacOS(); } } @@ -47,7 +44,7 @@ public static bool IsWindows { get { - return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + return OperatingSystem.IsWindows(); } } @@ -72,7 +69,10 @@ public static bool IsNanoServer #if UNIX return false; #else - if (_isNanoServer.HasValue) { return _isNanoServer.Value; } + if (_isNanoServer.HasValue) + { + return _isNanoServer.Value; + } _isNanoServer = false; using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels")) @@ -102,7 +102,10 @@ public static bool IsIoT #if UNIX return false; #else - if (_isIoT.HasValue) { return _isIoT.Value; } + if (_isIoT.HasValue) + { + return _isIoT.Value; + } _isIoT = false; using (RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion")) @@ -132,7 +135,10 @@ public static bool IsWindowsDesktop #if UNIX return false; #else - if (_isWindowsDesktop.HasValue) { return _isWindowsDesktop.Value; } + if (_isWindowsDesktop.HasValue) + { + return _isWindowsDesktop.Value; + } _isWindowsDesktop = !IsNanoServer && !IsIoT; return _isWindowsDesktop.Value; @@ -140,22 +146,83 @@ public static bool IsWindowsDesktop } } + /// + /// Gets a value indicating whether the underlying system supports single-threaded apartment. + /// + public static bool IsStaSupported + { + get + { +#if UNIX + return false; +#else + return _isStaSupported.Value; +#endif + } + } + #if UNIX // Gets the location for cache and config folders. internal static readonly string CacheDirectory = Platform.SelectProductNameForDirectory(Platform.XDG_Type.CACHE); internal static readonly string ConfigDirectory = Platform.SelectProductNameForDirectory(Platform.XDG_Type.CONFIG); #else // Gets the location for cache and config folders. - internal static readonly string CacheDirectory = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Microsoft\PowerShell"; - internal static readonly string ConfigDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + @"\PowerShell"; + internal static readonly string CacheDirectory = SafeDeriveFromSpecialFolder( + Environment.SpecialFolder.LocalApplicationData, + @"Microsoft\PowerShell"); + + internal static readonly string ConfigDirectory = SafeDeriveFromSpecialFolder( + Environment.SpecialFolder.Personal, + @"PowerShell"); + + private static readonly Lazy _isStaSupported = new Lazy(() => + { + int result = Interop.Windows.CoInitializeEx(IntPtr.Zero, Interop.Windows.COINIT_APARTMENTTHREADED); + + // Per COM documentation: Each successful call to CoInitializeEx (including S_FALSE) + // must be balanced by a corresponding call to CoUninitialize. + // - S_OK (0) means we initialized for the first time. + // - S_FALSE (1) means already initialized, but still increments the reference count. + // Both require CoUninitialize to decrement the reference count. + if (result >= 0) + { + Interop.Windows.CoUninitialize(); + } + + return result != Interop.Windows.E_NOTIMPL; + }); private static bool? _isNanoServer = null; private static bool? _isIoT = null; private static bool? _isWindowsDesktop = null; #endif + internal static bool TryDeriveFromCache(string path1, out string result) + { + if (CacheDirectory is null or []) + { + result = null; + return false; + } + + result = Path.Combine(CacheDirectory, path1); + return true; + } + + internal static bool TryDeriveFromCache(string path1, string path2, out string result) + { + if (CacheDirectory is null or []) + { + result = null; + return false; + } + + result = Path.Combine(CacheDirectory, path1, path2); + return true; + } + // format files - internal static readonly List FormatFileNames = new() + internal static readonly string[] FormatFileNames = new string[] { "Certificate.format.ps1xml", "Diagnostics.format.ps1xml", @@ -183,43 +250,48 @@ internal static class CommonEnvVariableNames #endif } - /// - /// Remove the temporary directory created for the current process. - /// - internal static void RemoveTemporaryDirectory() + private static string SafeDeriveFromSpecialFolder(Environment.SpecialFolder specialFolder, string subPath) { - if (_tempDirectory == null) + string basePath = Environment.GetFolderPath(specialFolder, Environment.SpecialFolderOption.DoNotVerify); + if (string.IsNullOrWhiteSpace(basePath)) { - return; + return string.Empty; } - try - { - Directory.Delete(_tempDirectory, true); - } - catch - { - // ignore if there is a failure - } - - _tempDirectory = null; + return Path.Join(basePath, subPath); } +#if UNIX + private static string s_tempHome = null; + /// - /// Get a temporary directory to use for the current process. + /// Get the 'HOME' environment variable or create a temporary home directory if the environment variable is not set. /// - internal static string GetTemporaryDirectory() + private static string GetHomeOrCreateTempHome() { - if (_tempDirectory != null) + const string tempHomeFolderName = "pwsh-{0}-98288ff9-5712-4a14-9a11-23693b9cd91a"; + + string envHome = Environment.GetEnvironmentVariable("HOME") ?? s_tempHome; + if (envHome is not null) { - return _tempDirectory; + return envHome; } - _tempDirectory = PsUtils.GetTemporaryDirectory(); - return _tempDirectory; + try + { + s_tempHome = Path.Combine(Path.GetTempPath(), StringUtil.Format(tempHomeFolderName, Environment.UserName)); + Directory.CreateDirectory(s_tempHome); + } + catch (UnauthorizedAccessException) + { + // Directory creation may fail if the account doesn't have filesystem permission such as some service accounts. + // Return an empty string in this case so the process working directory will be used. + s_tempHome = string.Empty; + } + + return s_tempHome; } -#if UNIX /// /// X Desktop Group configuration type enum. /// @@ -239,230 +311,100 @@ public enum XDG_Type DEFAULT } - private static string s_tempHomeDir = null; - /// /// Function for choosing directory location of PowerShell for profile loading. /// - public static string SelectProductNameForDirectory(Platform.XDG_Type dirpath) + public static string SelectProductNameForDirectory(XDG_Type dirpath) { // TODO: XDG_DATA_DIRS implementation as per GitHub issue #1060 - string xdgconfighome = System.Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); - string xdgdatahome = System.Environment.GetEnvironmentVariable("XDG_DATA_HOME"); - string xdgcachehome = System.Environment.GetEnvironmentVariable("XDG_CACHE_HOME"); - string envHome = System.Environment.GetEnvironmentVariable(CommonEnvVariableNames.Home); - if (envHome == null) - { - s_tempHomeDir ??= GetTemporaryDirectory(); - envHome = s_tempHomeDir; - } + string xdgconfighome = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); + string xdgdatahome = Environment.GetEnvironmentVariable("XDG_DATA_HOME"); + string xdgcachehome = Environment.GetEnvironmentVariable("XDG_CACHE_HOME"); + string envHome = GetHomeOrCreateTempHome(); string xdgConfigHomeDefault = Path.Combine(envHome, ".config", "powershell"); string xdgDataHomeDefault = Path.Combine(envHome, ".local", "share", "powershell"); string xdgModuleDefault = Path.Combine(xdgDataHomeDefault, "Modules"); string xdgCacheDefault = Path.Combine(envHome, ".cache", "powershell"); - switch (dirpath) + try { - case Platform.XDG_Type.CONFIG: - // the user has set XDG_CONFIG_HOME corresponding to profile path - if (string.IsNullOrEmpty(xdgconfighome)) - { - // xdg values have not been set - return xdgConfigHomeDefault; - } - - else - { - return Path.Combine(xdgconfighome, "powershell"); - } - - case Platform.XDG_Type.DATA: - // the user has set XDG_DATA_HOME corresponding to module path - if (string.IsNullOrEmpty(xdgdatahome)) - { - // create the xdg folder if needed - if (!Directory.Exists(xdgDataHomeDefault)) + switch (dirpath) + { + case XDG_Type.CONFIG: + // Use 'XDG_CONFIG_HOME' if it's set, otherwise use the default path. + return string.IsNullOrEmpty(xdgconfighome) + ? xdgConfigHomeDefault + : Path.Combine(xdgconfighome, "powershell"); + + case XDG_Type.DATA: + // Use 'XDG_DATA_HOME' if it's set, otherwise use the default path. + if (string.IsNullOrEmpty(xdgdatahome)) { - try - { - Directory.CreateDirectory(xdgDataHomeDefault); - } - catch (UnauthorizedAccessException) - { - // service accounts won't have permission to create user folder - return GetTemporaryDirectory(); - } + // Create the default data directory if it doesn't exist. + Directory.CreateDirectory(xdgDataHomeDefault); + return xdgDataHomeDefault; } - - return xdgDataHomeDefault; - } - else - { return Path.Combine(xdgdatahome, "powershell"); - } - case Platform.XDG_Type.USER_MODULES: - // the user has set XDG_DATA_HOME corresponding to module path - if (string.IsNullOrEmpty(xdgdatahome)) - { - // xdg values have not been set - if (!Directory.Exists(xdgModuleDefault)) // module folder not always guaranteed to exist + case XDG_Type.USER_MODULES: + // Use 'XDG_DATA_HOME' if it's set, otherwise use the default path. + if (string.IsNullOrEmpty(xdgdatahome)) { - try - { - Directory.CreateDirectory(xdgModuleDefault); - } - catch (UnauthorizedAccessException) - { - // service accounts won't have permission to create user folder - return GetTemporaryDirectory(); - } + Directory.CreateDirectory(xdgModuleDefault); + return xdgModuleDefault; } - - return xdgModuleDefault; - } - else - { return Path.Combine(xdgdatahome, "powershell", "Modules"); - } - case Platform.XDG_Type.SHARED_MODULES: - return "/usr/local/share/powershell/Modules"; + case XDG_Type.SHARED_MODULES: + return "/usr/local/share/powershell/Modules"; - case Platform.XDG_Type.CACHE: - // the user has set XDG_CACHE_HOME - if (string.IsNullOrEmpty(xdgcachehome)) - { - // xdg values have not been set - if (!Directory.Exists(xdgCacheDefault)) // module folder not always guaranteed to exist + case XDG_Type.CACHE: + // Use 'XDG_CACHE_HOME' if it's set, otherwise use the default path. + if (string.IsNullOrEmpty(xdgcachehome)) { - try - { - Directory.CreateDirectory(xdgCacheDefault); - } - catch (UnauthorizedAccessException) - { - // service accounts won't have permission to create user folder - return GetTemporaryDirectory(); - } + Directory.CreateDirectory(xdgCacheDefault); + return xdgCacheDefault; } - return xdgCacheDefault; - } - else - { - if (!Directory.Exists(Path.Combine(xdgcachehome, "powershell"))) - { - try - { - Directory.CreateDirectory(Path.Combine(xdgcachehome, "powershell")); - } - catch (UnauthorizedAccessException) - { - // service accounts won't have permission to create user folder - return GetTemporaryDirectory(); - } - } - - return Path.Combine(xdgcachehome, "powershell"); - } - - case Platform.XDG_Type.DEFAULT: - // default for profile location - return xdgConfigHomeDefault; + string cachePath = Path.Combine(xdgcachehome, "powershell"); + Directory.CreateDirectory(cachePath); + return cachePath; - default: - // xdgConfigHomeDefault needs to be created in the edge case that we do not have the folder or it was deleted - // This folder is the default in the event of all other failures for data storage - if (!Directory.Exists(xdgConfigHomeDefault)) - { - try - { - Directory.CreateDirectory(xdgConfigHomeDefault); - } - catch - { - Console.Error.WriteLine("Failed to create default data directory: " + xdgConfigHomeDefault); - } - } + case XDG_Type.DEFAULT: + // Use 'xdgConfigHomeDefault' for 'XDG_Type.DEFAULT' and create the directory if it doesn't exist. + Directory.CreateDirectory(xdgConfigHomeDefault); + return xdgConfigHomeDefault; - return xdgConfigHomeDefault; + default: + throw new InvalidOperationException("Unreachable code."); + } + } + catch (UnauthorizedAccessException) + { + // Directory creation may fail if the account doesn't have filesystem permission such as some service accounts. + // Return an empty string in this case so the process working directory will be used. + return string.Empty; } } #endif /// - /// The code is copied from the .NET implementation. - /// - internal static string GetFolderPath(System.Environment.SpecialFolder folder) - { - return InternalGetFolderPath(folder); - } - - /// - /// The API set 'api-ms-win-shell-shellfolders-l1-1-0.dll' was removed from NanoServer, so we cannot depend on 'SHGetFolderPathW' - /// to get the special folder paths. Instead, we need to rely on the basic environment variables to get the special folder paths. + /// Mimic 'Environment.GetFolderPath(folder)' on Unix. /// - /// - /// The path to the specified system special folder, if that folder physically exists on your computer. - /// Otherwise, an empty string (string.Empty). - /// - private static string InternalGetFolderPath(System.Environment.SpecialFolder folder) + internal static string GetFolderPath(Environment.SpecialFolder folder) { - string folderPath = null; #if UNIX - string envHome = System.Environment.GetEnvironmentVariable(Platform.CommonEnvVariableNames.Home); - if (envHome == null) + return folder switch { - envHome = Platform.GetTemporaryDirectory(); - } - - switch (folder) - { - case System.Environment.SpecialFolder.ProgramFiles: - folderPath = "/bin"; - if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; } - - break; - case System.Environment.SpecialFolder.ProgramFilesX86: - folderPath = "/usr/bin"; - if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; } - - break; - case System.Environment.SpecialFolder.System: - case System.Environment.SpecialFolder.SystemX86: - folderPath = "/sbin"; - if (!System.IO.Directory.Exists(folderPath)) { folderPath = null; } - - break; - case System.Environment.SpecialFolder.Personal: - folderPath = envHome; - break; - case System.Environment.SpecialFolder.LocalApplicationData: - folderPath = System.IO.Path.Combine(envHome, ".config"); - if (!System.IO.Directory.Exists(folderPath)) - { - try - { - System.IO.Directory.CreateDirectory(folderPath); - } - catch (UnauthorizedAccessException) - { - // directory creation may fail if the account doesn't have filesystem permission such as some service accounts - folderPath = string.Empty; - } - } - - break; - default: - throw new NotSupportedException(); - } + Environment.SpecialFolder.ProgramFiles => Directory.Exists("/bin") ? "/bin" : string.Empty, + Environment.SpecialFolder.MyDocuments => GetHomeOrCreateTempHome(), + _ => throw new NotSupportedException() + }; #else - folderPath = System.Environment.GetFolderPath(folder); + return Environment.GetFolderPath(folder, Environment.SpecialFolderOption.DoNotVerify); #endif - return folderPath ?? string.Empty; } // Platform methods prefixed NonWindows are: @@ -475,21 +417,11 @@ private static string InternalGetFolderPath(System.Environment.SpecialFolder fol // - only to be used with the IsWindows feature query, and only if // no other more specific feature query makes sense - internal static bool NonWindowsIsHardLink(ref IntPtr handle) - { - return Unix.IsHardLink(ref handle); - } - internal static bool NonWindowsIsHardLink(FileSystemInfo fileInfo) { return Unix.IsHardLink(fileInfo); } - internal static string NonWindowsInternalGetTarget(string path) - { - return Unix.NativeMethods.FollowSymLink(path); - } - internal static string NonWindowsGetUserFromPid(int path) { return Unix.NativeMethods.GetUserFromPid(path); @@ -532,11 +464,9 @@ internal static bool NonWindowsIsSameFileSystemItem(string pathOne, string pathT return Unix.NativeMethods.IsSameFileSystemItem(pathOne, pathTwo); } - internal static bool NonWindowsGetInodeData(string path, out System.ValueTuple inodeData) + internal static bool NonWindowsGetInodeData(string path, out ValueTuple inodeData) { - UInt64 device = 0UL; - UInt64 inode = 0UL; - var result = Unix.NativeMethods.GetInodeData(path, out device, out inode); + var result = Unix.NativeMethods.GetInodeData(path, out ulong device, out ulong inode); inodeData = (device, inode); return result == 0; @@ -557,6 +487,16 @@ internal static int NonWindowsGetProcessParentPid(int pid) return IsMacOS ? Unix.NativeMethods.GetPPid(pid) : Unix.GetProcFSParentPid(pid); } + internal static bool NonWindowsKillProcess(int pid) + { + return Unix.NativeMethods.KillProcess(pid); + } + + internal static int NonWindowsWaitPid(int pid, bool nohang) + { + return Unix.NativeMethods.WaitPid(pid, nohang); + } + // Please note that `Win32Exception(Marshal.GetLastWin32Error())` // works *correctly* on Linux in that it creates an exception with // the string perror would give you for the last set value of errno. @@ -564,10 +504,10 @@ internal static int NonWindowsGetProcessParentPid(int pid) // to a PAL value and calls strerror_r underneath to generate the message. /// Unix specific implementations of required functionality. - internal static class Unix + internal static partial class Unix { - private static Dictionary usernameCache = new(); - private static Dictionary groupnameCache = new(); + private static readonly Dictionary usernameCache = new(); + private static readonly Dictionary groupnameCache = new(); /// The type of a Unix file system item. public enum ItemType @@ -697,82 +637,73 @@ public class CommonStat private const char CanRead = 'r'; private const char CanWrite = 'w'; private const char CanExecute = 'x'; - - // helper for getting unix mode - private Dictionary modeMap = new() - { - { StatMask.OwnerRead, CanRead }, - { StatMask.OwnerWrite, CanWrite }, - { StatMask.OwnerExecute, CanExecute }, - { StatMask.GroupRead, CanRead }, - { StatMask.GroupWrite, CanWrite }, - { StatMask.GroupExecute, CanExecute }, - { StatMask.OtherRead, CanRead }, - { StatMask.OtherWrite, CanWrite }, - { StatMask.OtherExecute, CanExecute }, - }; - - private StatMask[] permissions = new StatMask[] - { - StatMask.OwnerRead, - StatMask.OwnerWrite, - StatMask.OwnerExecute, - StatMask.GroupRead, - StatMask.GroupWrite, - StatMask.GroupExecute, - StatMask.OtherRead, - StatMask.OtherWrite, - StatMask.OtherExecute - }; + private const char NoPerm = '-'; + private const char SetAndExec = 's'; + private const char SetAndNotExec = 'S'; + private const char StickyAndExec = 't'; + private const char StickyAndNotExec = 'T'; // The item type and the character representation for the first element in the stat string - private Dictionary itemTypeTable = new() + private static readonly Dictionary itemTypeTable = new() { - { ItemType.BlockDevice, 'b' }, + { ItemType.BlockDevice, 'b' }, { ItemType.CharacterDevice, 'c' }, - { ItemType.Directory, 'd' }, - { ItemType.File, '-' }, - { ItemType.NamedPipe, 'p' }, - { ItemType.Socket, 's' }, - { ItemType.SymbolicLink, 'l' }, + { ItemType.Directory, 'd' }, + { ItemType.File, '-' }, + { ItemType.NamedPipe, 'p' }, + { ItemType.Socket, 's' }, + { ItemType.SymbolicLink, 'l' }, }; + // We'll create a few common mode strings here to reduce allocations and improve performance a bit. + private const string OwnerReadGroupReadOtherRead = "-r--r--r--"; + private const string OwnerReadWriteGroupReadOtherRead = "-rw-r--r--"; + private const string DirectoryOwnerFullGroupReadExecOtherReadExec = "drwxr-xr-x"; + /// Convert the mode to a string which is usable in our formatting. /// The mode converted into a Unix style string similar to the output of ls. public string GetModeString() { - int offset = 0; - char[] modeCharacters = new char[10]; - modeCharacters[offset++] = itemTypeTable[ItemType]; + // On an Ubuntu system (docker), these 3 are roughly 70% of all the permissions + if ((Mode & 0xFFF) == 292) + { + return OwnerReadGroupReadOtherRead; + } - foreach (StatMask permission in permissions) + if ((Mode & 0xFFF) == 420) { - // determine whether we are setuid, sticky, or the usual rwx. - if ((Mode & (int)permission) == (int)permission) - { - if ((permission == StatMask.OwnerExecute && IsSetUid) || (permission == StatMask.GroupExecute && IsSetGid)) - { - // Check for setuid and add 's' - modeCharacters[offset] = 's'; - } - else if (permission == StatMask.OtherExecute && IsSticky && (ItemType == ItemType.Directory)) - { - // Directories are sticky, rather than setuid - modeCharacters[offset] = 't'; - } - else - { - modeCharacters[offset] = modeMap[permission]; - } - } - else - { - modeCharacters[offset] = '-'; - } + return OwnerReadWriteGroupReadOtherRead; + } - offset++; + if (ItemType == ItemType.Directory & (Mode & 0xFFF) == 493) + { + return DirectoryOwnerFullGroupReadExecOtherReadExec; } + UnixFileMode modeInfo = (UnixFileMode)Mode; + + Span modeCharacters = [ + itemTypeTable[ItemType], + + modeInfo.HasFlag(UnixFileMode.UserRead) ? CanRead : NoPerm, + modeInfo.HasFlag(UnixFileMode.UserWrite) ? CanWrite : NoPerm, + modeInfo.HasFlag(UnixFileMode.SetUser) ? + (modeInfo.HasFlag(UnixFileMode.UserExecute) ? SetAndExec : SetAndNotExec) : + (modeInfo.HasFlag(UnixFileMode.UserExecute) ? CanExecute : NoPerm), + + modeInfo.HasFlag(UnixFileMode.GroupRead) ? CanRead : NoPerm, + modeInfo.HasFlag(UnixFileMode.GroupWrite) ? CanWrite : NoPerm, + modeInfo.HasFlag(UnixFileMode.SetGroup) ? + (modeInfo.HasFlag(UnixFileMode.GroupExecute) ? SetAndExec : SetAndNotExec) : + (modeInfo.HasFlag(UnixFileMode.GroupExecute) ? CanExecute : NoPerm), + + modeInfo.HasFlag(UnixFileMode.OtherRead) ? CanRead : NoPerm, + modeInfo.HasFlag(UnixFileMode.OtherWrite) ? CanWrite : NoPerm, + modeInfo.HasFlag(UnixFileMode.StickyBit) ? + (modeInfo.HasFlag(UnixFileMode.OtherExecute) ? StickyAndExec : StickyAndNotExec) : + (modeInfo.HasFlag(UnixFileMode.OtherExecute) ? CanExecute : NoPerm), + ]; + return new string(modeCharacters); } @@ -823,15 +754,6 @@ internal static ErrorCategory GetErrorCategory(int errno) return (ErrorCategory)Unix.NativeMethods.GetErrorCategory(errno); } - /// Is this a hardlink. - /// The handle to a file. - /// A boolean that represents whether the item is a hardlink. - public static bool IsHardLink(ref IntPtr handle) - { - // TODO:PSL implement using fstat to query inode refcount to see if it is a hard link - return false; - } - /// Determine if the item is a hardlink. /// A FileSystemInfo to check to determine if it is a hardlink. /// A boolean that represents whether the item is a hardlink. @@ -972,20 +894,40 @@ public static int GetProcFSParentPid(int pid) { const int invalidPid = -1; - // read /proc//stat - // 4th column will contain the ppid, 92 in the example below - // ex: 93 (bash) S 92 93 2 4294967295 ... - var path = $"/proc/{pid}/stat"; + // read /proc//status + // Row beginning with PPid: \d is the parent process id. + // This used to check /proc//stat but that file was meant + // to be a space delimited line but it contains a value which + // could contain spaces itself. Using the status file is a lot + // simpler because each line contains a record with a simple + // label. + // https://github.com/PowerShell/PowerShell/issues/17541#issuecomment-1159911577 + var path = $"/proc/{pid}/status"; try { - var stat = System.IO.File.ReadAllText(path); - var parts = stat.Split(' ', 5); - if (parts.Length < 5) + using FileStream fs = File.OpenRead(path); + using StreamReader sr = new(fs); + string line; + while ((line = sr.ReadLine()) != null) { - return invalidPid; + if (!line.StartsWith("PPid:\t", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + string[] lineSplit = line.Split('\t', 2, StringSplitOptions.RemoveEmptyEntries); + if (lineSplit.Length != 2) + { + continue; + } + + if (int.TryParse(lineSplit[1].Trim(), out var ppid)) + { + return ppid; + } } - return Int32.Parse(parts[3]); + return invalidPid; } catch (Exception) { @@ -994,31 +936,40 @@ public static int GetProcFSParentPid(int pid) } /// The native methods class. - internal static class NativeMethods + internal static partial class NativeMethods { private const string psLib = "libpsl-native"; // Ansi is a misnomer, it is hardcoded to UTF-8 on Linux and macOS - // C bools are 1 byte and so must be marshaled as I1 + // C bools are 1 byte and so must be marshalled as I1 - [DllImport(psLib, CharSet = CharSet.Ansi)] - internal static extern int GetErrorCategory(int errno); + [LibraryImport(psLib)] + internal static partial int GetErrorCategory(int errno); - [DllImport(psLib)] - internal static extern int GetPPid(int pid); + [LibraryImport(psLib)] + internal static partial int GetPPid(int pid); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int GetLinkCount([MarshalAs(UnmanagedType.LPStr)] string filePath, out int linkCount); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static partial int GetLinkCount(string filePath, out int linkCount); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool IsExecutable([MarshalAs(UnmanagedType.LPStr)] string filePath); + internal static partial bool IsExecutable(string filePath); - [DllImport(psLib, CharSet = CharSet.Ansi)] - internal static extern uint GetCurrentThreadId(); + [LibraryImport(psLib)] + internal static partial uint GetCurrentThreadId(); - // This is a struct tm from . - [StructLayout(LayoutKind.Sequential)] + [LibraryImport(psLib)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool KillProcess(int pid); + + [LibraryImport(psLib)] + internal static partial int WaitPid(int pid, [MarshalAs(UnmanagedType.Bool)] bool nohang); + + // This is the struct `private_tm` from setdate.h in libpsl-native. + // Packing is set to 4 to match the unmanaged declaration. + // https://github.com/PowerShell/PowerShell-Native/blob/c5575ceb064e60355b9fee33eabae6c6d2708d14/src/libpsl-native/src/setdate.h#L23 + [StructLayout(LayoutKind.Sequential, Pack = 4)] internal unsafe struct UnixTm { /// Seconds (0-60). @@ -1065,33 +1016,25 @@ internal static UnixTm DateTimeToUnixTm(DateTime date) return tm; } - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern unsafe int SetDate(UnixTm* tm); + [LibraryImport(psLib, SetLastError = true)] + internal static unsafe partial int SetDate(UnixTm* tm); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int CreateSymLink([MarshalAs(UnmanagedType.LPStr)] string filePath, - [MarshalAs(UnmanagedType.LPStr)] string target); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial int CreateSymLink(string filePath, string target); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int CreateHardLink([MarshalAs(UnmanagedType.LPStr)] string filePath, - [MarshalAs(UnmanagedType.LPStr)] string target); - - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - [return: MarshalAs(UnmanagedType.LPStr)] - internal static extern string FollowSymLink([MarshalAs(UnmanagedType.LPStr)] string filePath); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial int CreateHardLink(string filePath, string target); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [LibraryImport(psLib)] [return: MarshalAs(UnmanagedType.LPStr)] - internal static extern string GetUserFromPid(int pid); + internal static partial string GetUserFromPid(int pid); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool IsSameFileSystemItem([MarshalAs(UnmanagedType.LPStr)] string filePathOne, - [MarshalAs(UnmanagedType.LPStr)] string filePathTwo); + internal static partial bool IsSameFileSystemItem(string filePathOne, string filePathTwo); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern int GetInodeData([MarshalAs(UnmanagedType.LPStr)] string path, - out UInt64 device, out UInt64 inode); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial int GetInodeData(string path, out ulong device, out ulong inode); /// /// This is a struct from getcommonstat.h in the native library. @@ -1169,17 +1112,17 @@ internal struct CommonStatStruct internal int IsSticky; } - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern unsafe int GetCommonLStat(string filePath, [Out] out CommonStatStruct cs); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static unsafe partial int GetCommonLStat(string filePath, out CommonStatStruct cs); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern unsafe int GetCommonStat(string filePath, [Out] out CommonStatStruct cs); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8, SetLastError = true)] + internal static unsafe partial int GetCommonStat(string filePath, out CommonStatStruct cs); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern string GetPwUid(int id); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial string GetPwUid(int id); - [DllImport(psLib, CharSet = CharSet.Ansi, SetLastError = true)] - internal static extern string GetGrGid(int id); + [LibraryImport(psLib, StringMarshalling = StringMarshalling.Utf8)] + internal static partial string GetGrGid(int id); } } } diff --git a/src/System.Management.Automation/CoreCLR/CorePsStub.cs b/src/System.Management.Automation/CoreCLR/CorePsStub.cs index d99bcbb398b..e439cc30ff2 100644 --- a/src/System.Management.Automation/CoreCLR/CorePsStub.cs +++ b/src/System.Management.Automation/CoreCLR/CorePsStub.cs @@ -431,14 +431,31 @@ namespace System.Management.Automation.Security /// /// Application white listing security policies only affect Windows OSs. /// - internal sealed class SystemPolicy + public sealed class SystemPolicy { private SystemPolicy() { } + /// + /// Writes to PowerShell WDAC Audit mode ETW log. + /// + /// Current execution context. + /// Audit message title. + /// Audit message message. + /// Fully Qualified ID. + /// Stops code execution and goes into debugger mode. + internal static void LogWDACAuditMessage( + ExecutionContext context, + string title, + string message, + string fqid, + bool dropIntoDebugger = false) + { + } + /// /// Gets the system lockdown policy. /// - /// Always return SystemEnforcementMode.None in CSS (trusted) + /// Always return SystemEnforcementMode.None on non-Windows platforms. public static SystemEnforcementMode GetSystemLockdownPolicy() { return SystemEnforcementMode.None; @@ -447,7 +464,7 @@ public static SystemEnforcementMode GetSystemLockdownPolicy() /// /// Gets lockdown policy as applied to a file. /// - /// Always return SystemEnforcementMode.None in CSS (trusted) + /// Always return SystemEnforcementMode.None on non-Windows platforms. public static SystemEnforcementMode GetLockdownPolicy(string path, System.Runtime.InteropServices.SafeHandle handle) { return SystemEnforcementMode.None; @@ -457,12 +474,26 @@ internal static bool IsClassInApprovedList(Guid clsid) { throw new NotImplementedException("SystemPolicy.IsClassInApprovedList not implemented"); } + + /// + /// Gets the system wide script file policy enforcement for an open file. + /// Based on system WDAC (Windows Defender Application Control) or AppLocker policies. + /// + /// Script file path for policy check. + /// FileStream object to script file path. + /// Policy check result for script file. + public static SystemScriptFileEnforcement GetFilePolicyEnforcement( + string filePath, + System.IO.FileStream fileStream) + { + return SystemScriptFileEnforcement.None; + } } /// /// How the policy is being enforced. /// - internal enum SystemEnforcementMode + public enum SystemEnforcementMode { /// Not enforced at all None = 0, @@ -473,6 +504,37 @@ internal enum SystemEnforcementMode /// Enabled, enforce restrictions Enforce = 2 } + + /// + /// System wide policy enforcement for a specific script file. + /// + public enum SystemScriptFileEnforcement + { + /// + /// No policy enforcement. + /// + None = 0, + + /// + /// Script file is blocked from running. + /// + Block = 1, + + /// + /// Script file is allowed to run without restrictions (FullLanguage mode). + /// + Allow = 2, + + /// + /// Script file is allowed to run in ConstrainedLanguage mode only. + /// + AllowConstrained = 3, + + /// + /// Script file is allowed to run in FullLanguage mode but will emit ConstrainedLanguage restriction audit logs. + /// + AllowConstrainedAudit = 4 + } } // Porting note: Tracing is absolutely not available on Linux diff --git a/src/System.Management.Automation/DscSupport/CimDSCParser.cs b/src/System.Management.Automation/DscSupport/CimDSCParser.cs index 2901148813b..283ec1bcad8 100644 --- a/src/System.Management.Automation/DscSupport/CimDSCParser.cs +++ b/src/System.Management.Automation/DscSupport/CimDSCParser.cs @@ -22,6 +22,8 @@ using Microsoft.Management.Infrastructure.Serialization; using Microsoft.PowerShell.Commands; +using static Microsoft.PowerShell.SecureStringHelper; + namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal { /// @@ -259,12 +261,7 @@ private static object ConvertCimInstancePsCredential(string providerName, CimIns throw invalidOperationException; } - // Extract the password into a SecureString. - var password = new SecureString(); - foreach (char t in plainPassWord) - { - password.AppendChar(t); - } + SecureString password = SecureStringHelper.FromPlainTextString(plainPassWord); password.MakeReadOnly(); return new PSCredential(userName, password); @@ -320,8 +317,8 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input /// internal class CimDSCParser { - private CimMofDeserializer _deserializer; - private CimMofDeserializer.OnClassNeeded _onClassNeeded; + private readonly CimMofDeserializer _deserializer; + private readonly CimMofDeserializer.OnClassNeeded _onClassNeeded; /// /// @@ -528,11 +525,8 @@ public DscClassCacheEntry(DSCResourceRunAsCredential aDSCResourceRunAsCredential public static class DscClassCache { private const string InboxDscResourceModulePath = "WindowsPowershell\\v1.0\\Modules\\PsDesiredStateConfiguration"; - private const string reservedDynamicKeywords = "^(Synchronization|Certificate|IIS|SQL)$"; - - private const string reservedProperties = "^(Require|Trigger|Notify|Before|After|Subscribe)$"; - private static PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); // Constants for items in the module qualified name (Module\Version\ClassName) private const int IndexModuleName = 0; @@ -564,10 +558,7 @@ private static Dictionary ClassCache { get { - if (t_classCache == null) - { - t_classCache = new Dictionary(StringComparer.OrdinalIgnoreCase); - } + t_classCache ??= new Dictionary(StringComparer.OrdinalIgnoreCase); return t_classCache; } @@ -583,10 +574,7 @@ private static Dictionary> ByClassModuleCache { get { - if (t_byClassModuleCache == null) - { - t_byClassModuleCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); - } + t_byClassModuleCache ??= new Dictionary>(StringComparer.OrdinalIgnoreCase); return t_byClassModuleCache; } @@ -602,10 +590,7 @@ private static Dictionary> ByClassModuleCache { get { - if (t_byFileClassCache == null) - { - t_byFileClassCache = new Dictionary>(StringComparer.OrdinalIgnoreCase); - } + t_byFileClassCache ??= new Dictionary>(StringComparer.OrdinalIgnoreCase); return t_byFileClassCache; } @@ -621,10 +606,7 @@ private static HashSet ScriptKeywordFileCache { get { - if (t_scriptKeywordFileCache == null) - { - t_scriptKeywordFileCache = new HashSet(StringComparer.OrdinalIgnoreCase); - } + t_scriptKeywordFileCache ??= new HashSet(StringComparer.OrdinalIgnoreCase); return t_scriptKeywordFileCache; } @@ -724,7 +706,7 @@ public static void Initialize(Collection errors, List moduleP continue; } - foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(d => Directory.EnumerateFiles(d, "*.schema.mof"))) + foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof"))) { ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors); } @@ -741,12 +723,12 @@ public static void Initialize(Collection errors, List moduleP if (!Directory.Exists(systemResourceRoot)) { - configSystemPath = Platform.GetFolderPath(Environment.SpecialFolder.System); + configSystemPath = Environment.GetFolderPath(Environment.SpecialFolder.System); systemResourceRoot = Path.Combine(configSystemPath, "Configuration"); inboxModulePath = InboxDscResourceModulePath; } - var programFilesDirectory = Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles); + var programFilesDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); Debug.Assert(programFilesDirectory != null, "Program Files environment variable does not exist!"); var customResourceRoot = Path.Combine(programFilesDirectory, "WindowsPowerShell\\Configuration"); Debug.Assert(Directory.Exists(customResourceRoot), "%ProgramFiles%\\WindowsPowerShell\\Configuration Directory does not exist"); @@ -776,7 +758,7 @@ public static void Initialize(Collection errors, List moduleP continue; } - foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(d => Directory.EnumerateFiles(d, "*.schema.mof"))) + foreach (var schemaFile in Directory.EnumerateDirectories(resources).SelectMany(static d => Directory.EnumerateFiles(d, "*.schema.mof"))) { ImportClasses(schemaFile, s_defaultModuleInfoForResource, errors); } @@ -822,7 +804,10 @@ private static void LoadDSCResourceIntoCache(Collection errors, List< { foreach (string moduleDir in modulePathList) { - if (!Directory.Exists(moduleDir)) continue; + if (!Directory.Exists(moduleDir)) + { + continue; + } var dscResourcesPath = Path.Combine(moduleDir, "DscResources"); if (Directory.Exists(dscResourcesPath)) @@ -933,7 +918,7 @@ private static CimClass MyClassCallback(string serverName, string namespaceName, { foreach (KeyValuePair cimClass in ClassCache) { - string cachedClassName = cimClass.Key.Split(Utils.Separators.Backslash)[IndexClassName]; + string cachedClassName = cimClass.Key.Split('\\')[IndexClassName]; if (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase)) { return cimClass.Value.CimClassInstance; @@ -985,10 +970,7 @@ public static List ImportClasses(string path, Tuple m { // Ignore modules with invalid schemas. s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e); - if (errors != null) - { - errors.Add(e); - } + errors?.Add(e); } if (classes != null) @@ -1010,15 +992,12 @@ public static List ImportClasses(string path, Tuple m // allow sharing of nested objects. if (!IsSameNestedObject(cimClass, c)) { - var files = string.Join(",", GetFileDefiningClass(className)); + var files = string.Join(',', GetFileDefiningClass(className)); PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( ParserStrings.DuplicateCimClassDefinition, className, path, files); e.SetErrorId("DuplicateCimClassDefinition"); - if (errors != null) - { - errors.Add(e); - } + errors?.Add(e); } } @@ -1107,7 +1086,7 @@ public static void ClearCache() /// private static string GetModuleQualifiedResourceName(string moduleName, string moduleVersion, string className, string resourceName) { - return string.Format(CultureInfo.InvariantCulture, "{0}\\{1}\\{2}\\{3}", moduleName, moduleVersion, className, resourceName); + return string.Create(CultureInfo.InvariantCulture, $"{moduleName}\\{moduleVersion}\\{className}\\{resourceName}"); } /// @@ -1120,7 +1099,7 @@ private static string GetModuleQualifiedResourceName(string moduleName, string m private static List> FindResourceInCache(string moduleName, string className, string resourceName) { return (from cacheEntry in ClassCache - let splittedName = cacheEntry.Key.Split(Utils.Separators.Backslash) + let splittedName = cacheEntry.Key.Split('\\') let cachedClassName = splittedName[IndexClassName] let cachedModuleName = splittedName[IndexModuleName] let cachedResourceName = splittedName[IndexFriendlyName] @@ -1146,7 +1125,7 @@ private static List GetCachedClasses() public static List GetCachedClassesForModule(PSModuleInfo module) { List cachedClasses = new(); - var moduleQualifiedName = string.Format(CultureInfo.InvariantCulture, "{0}\\{1}", module.Name, module.Version.ToString()); + var moduleQualifiedName = string.Create(CultureInfo.InvariantCulture, $"{module.Name}\\{module.Version}"); foreach (var dscClassCacheEntry in ClassCache) { if (dscClassCacheEntry.Key.StartsWith(moduleQualifiedName, StringComparison.OrdinalIgnoreCase)) @@ -1282,13 +1261,6 @@ public static void ValidateInstanceText(string instanceText) parser.ValidateInstanceText(instanceText); } - private static bool IsMagicProperty(string propertyName) - { - return System.Text.RegularExpressions.Regex.Match(propertyName, - "^(ResourceId|SourceInfo|ModuleName|ModuleVersion|ConfigurationName)$", - System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success; - } - private static string GetFriendlyName(CimClass cimClass) { try @@ -1316,7 +1288,7 @@ public static Collection GetCachedKeywords() foreach (KeyValuePair cachedClass in ClassCache) { - string[] splittedName = cachedClass.Key.Split(Utils.Separators.Backslash); + string[] splittedName = cachedClass.Key.Split('\\'); string moduleName = splittedName[IndexModuleName]; string moduleVersion = splittedName[IndexModuleVersion]; @@ -1385,7 +1357,8 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi // // Skip all of the base, meta, registration and other classes that are not intended to be used directly by a script author // - if (System.Text.RegularExpressions.Regex.Match(keywordString, "^OMI_Base|^OMI_.*Registration", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success) + if (keywordString.StartsWith("OMI_Base", StringComparison.OrdinalIgnoreCase) || + (keywordString.StartsWith("OMI_", StringComparison.OrdinalIgnoreCase) && keywordString.IndexOf("Registration", 4, StringComparison.OrdinalIgnoreCase) >= 0)) { return null; } @@ -1401,7 +1374,7 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi }; // If it's one of reserved dynamic keyword, mark it - if (System.Text.RegularExpressions.Regex.Match(keywordString, reservedDynamicKeywords, System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success) + if (IsReservedDynamicKeyword(keywordString)) { keyword.IsReservedKeyword = true; } @@ -1459,7 +1432,7 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi } } // If it's one of our reserved properties, save it for error reporting - if (System.Text.RegularExpressions.Regex.Match(prop.Name, reservedProperties, System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success) + if (IsReservedProperty(prop.Name)) { keyword.HasReservedProperties = true; continue; @@ -1558,6 +1531,27 @@ private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Versi UpdateKnownRestriction(keyword); return keyword; + + static bool IsMagicProperty(string propertyName) => + string.Equals(propertyName, "ResourceId", StringComparison.OrdinalIgnoreCase) || + string.Equals(propertyName, "SourceInfo", StringComparison.OrdinalIgnoreCase) || + string.Equals(propertyName, "ModuleName", StringComparison.OrdinalIgnoreCase) || + string.Equals(propertyName, "ModuleVersion", StringComparison.OrdinalIgnoreCase) || + string.Equals(propertyName, "ConfigurationName", StringComparison.OrdinalIgnoreCase); + + static bool IsReservedDynamicKeyword(string keyword) => + string.Equals(keyword, "Synchronization", StringComparison.OrdinalIgnoreCase) || + string.Equals(keyword, "Certificate", StringComparison.OrdinalIgnoreCase) || + string.Equals(keyword, "IIS", StringComparison.OrdinalIgnoreCase) || + string.Equals(keyword, "SQL", StringComparison.OrdinalIgnoreCase); + + static bool IsReservedProperty(string name) => + string.Equals(name, "Require", StringComparison.OrdinalIgnoreCase) || + string.Equals(name, "Trigger", StringComparison.OrdinalIgnoreCase) || + string.Equals(name, "Notify", StringComparison.OrdinalIgnoreCase) || + string.Equals(name, "Before", StringComparison.OrdinalIgnoreCase) || + string.Equals(name, "After", StringComparison.OrdinalIgnoreCase) || + string.Equals(name, "Subscribe", StringComparison.OrdinalIgnoreCase); } /// @@ -1622,8 +1616,8 @@ public static void LoadDefaultCimKeywords(Collection errors) /// /// Load the default system CIM classes and create the corresponding keywords. - /// A dictionary to add the defined functions to, may be null. /// + /// A dictionary to add the defined functions to, may be null. public static void LoadDefaultCimKeywords(Dictionary functionsToDefine) { LoadDefaultCimKeywords(functionsToDefine, null, null, false); @@ -1896,10 +1890,7 @@ private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatement { if (keywordAst.Keyword.Keyword.Equals("Node")) { - if (errorList == null) - { - errorList = new List(); - } + errorList ??= new List(); errorList.Add(new ParseError(kwAst.Extent, "ImportDscResourceInsideNode", @@ -1956,8 +1947,7 @@ private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatem object evalResultObject; if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false)) { - var presentName = evalResultObject as string; - if (presentName != null) + if (evalResultObject is string presentName) { if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0) { @@ -2043,7 +2033,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, { string moduleString = moduleToImport.Version == null ? moduleToImport.Name - : string.Format(CultureInfo.CurrentCulture, "<{0}, {1}>", moduleToImport.Name, moduleToImport.Version); + : string.Create(CultureInfo.CurrentCulture, $"<{moduleToImport.Name}, {moduleToImport.Version}>"); errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse", string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString))); @@ -2151,8 +2141,7 @@ public static void LoadResourcesFromModule(IScriptExtent scriptExtent, { try { - string unused; - foundResources = ImportCimKeywordsFromModule(moduleInfo, resourceToImport, out unused); + foundResources = ImportCimKeywordsFromModule(moduleInfo, resourceToImport, out _); } catch (Exception) { @@ -2320,8 +2309,7 @@ internal static string GenerateMofForAst(TypeDefinitionAst typeAst) internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List embeddedInstanceTypes, ref string[] enumNames) { TypeName propTypeName; - var arrayTypeName = typeName as ArrayTypeName; - if (arrayTypeName != null) + if (typeName is ArrayTypeName arrayTypeName) { isArrayType = true; propTypeName = arrayTypeName.ElementType as TypeName; @@ -2344,7 +2332,7 @@ internal static string MapTypeNameToMofType(ITypeName typeName, string memberNam if (propTypeName._typeDefinitionAst.IsEnum) { - enumNames = propTypeName._typeDefinitionAst.Members.Select(m => m.Name).ToArray(); + enumNames = propTypeName._typeDefinitionAst.Members.Select(static m => m.Name).ToArray(); isArrayType = false; embeddedInstanceType = null; return "string"; @@ -2364,9 +2352,9 @@ internal static string MapTypeNameToMofType(ITypeName typeName, string memberNam private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder sb, List embeddedInstanceTypes) { var className = typeAst.Name; - sb.AppendFormat(CultureInfo.InvariantCulture, "[ClassVersion(\"1.0.0\"), FriendlyName(\"{0}\")]\nclass {0}", className); + sb.Append(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); - if (typeAst.Attributes.Any(a => a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))) + if (typeAst.Attributes.Any(static a => a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))) { sb.Append(" : OMI_BaseResource"); } @@ -2384,15 +2372,13 @@ private static void GenerateMofForAst(TypeDefinitionAst typeAst, StringBuilder s while (bases.Count > 0) { var b = bases.Dequeue(); - var tc = b as TypeConstraintAst; - if (tc != null) + if (b is TypeConstraintAst tc) { b = tc.TypeName.GetReflectionType(); if (b == null) { - var td = tc.TypeName as TypeName; - if (td != null && td._typeDefinitionAst != null) + if (tc.TypeName is TypeName td && td._typeDefinitionAst != null) { ProcessMembers(sb, embeddedInstanceTypes, td._typeDefinitionAst, className); foreach (var b1 in td._typeDefinitionAst.BaseTypes) @@ -2434,8 +2420,7 @@ private static bool GetResourceMethodsLineNumber(TypeDefinitionAst typeDefinitio methodsLinePosition = new Dictionary(); foreach (var member in typeDefinitionAst.Members) { - var functionMemberAst = member as FunctionMemberAst; - if (functionMemberAst != null) + if (member is FunctionMemberAst functionMemberAst) { if (functionMemberAst.Name.Equals(getMethodName, StringComparison.OrdinalIgnoreCase)) { @@ -2481,7 +2466,7 @@ public static bool GetResourceMethodsLinePosition(PSModuleInfo moduleInfo, strin if (moduleInfo.NestedModules != null) { - foreach (var nestedModule in moduleInfo.NestedModules.Where(m => !string.IsNullOrEmpty(m.Path))) + foreach (var nestedModule in moduleInfo.NestedModules.Where(static m => !string.IsNullOrEmpty(m.Path))) { moduleFiles.Add(nestedModule.Path); } @@ -2515,9 +2500,7 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan { foreach (var member in typeDefinitionAst.Members) { - var property = member as PropertyMemberAst; - - if (property == null || property.IsStatic || + if (member is not PropertyMemberAst property || property.IsStatic || property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute))) { continue; @@ -2557,14 +2540,12 @@ private static void ProcessMembers(StringBuilder sb, List embeddedInstan out embeddedInstanceType, embeddedInstanceTypes, ref enumNames); } + string mofAttr = MapAttributesToMof(enumNames, attributes, embeddedInstanceType); string arrayAffix = isArrayType ? "[]" : string.Empty; - sb.AppendFormat(CultureInfo.InvariantCulture, - " {0}{1} {2}{3};\n", - MapAttributesToMof(enumNames, attributes, embeddedInstanceType), - mofType, - member.Name, - arrayAffix); + sb.Append( + CultureInfo.InvariantCulture, + $" {mofAttr}{mofType} {member.Name}{arrayAffix};\n"); } } @@ -2622,13 +2603,15 @@ private static bool GetResourceDefinitionsFromModule(string fileName, out IEnume resourceDefinitions = ast.FindAll(n => { - var typeAst = n as TypeDefinitionAst; - if (typeAst != null) + if (n is TypeDefinitionAst typeAst) { for (int i = 0; i < typeAst.Attributes.Count; i++) { var a = typeAst.Attributes[i]; - if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) return true; + if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) + { + return true; + } } } @@ -2682,7 +2665,10 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m } } - if (skip) continue; + if (skip) + { + continue; + } // Parse the Resource Attribute to see if RunAs behavior is specified for the resource. DSCResourceRunAsCredential runAsBehavior = DSCResourceRunAsCredential.Default; @@ -2692,13 +2678,9 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m { foreach (var na in attr.NamedArguments) { - if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase)) + if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase) && attr.GetAttribute() is DscResourceAttribute dscResourceAttribute) { - var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; - if (dscResourceAttribute != null) - { - runAsBehavior = dscResourceAttribute.RunAsCredential; - } + runAsBehavior = dscResourceAttribute.RunAsCredential; } } } @@ -2715,16 +2697,16 @@ private static bool ImportKeywordsFromScriptFile(string fileName, PSModuleInfo m private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new() { { typeof(sbyte), "sint8" }, - { typeof(byte) , "uint8"}, - { typeof(short) , "sint16"}, - { typeof(ushort) , "uint16"}, - { typeof(int) , "sint32"}, - { typeof(uint) , "uint32"}, - { typeof(long) , "sint64"}, + { typeof(byte), "uint8"}, + { typeof(short), "sint16"}, + { typeof(ushort), "uint16"}, + { typeof(int), "sint32"}, + { typeof(uint), "uint32"}, + { typeof(long), "sint64"}, { typeof(ulong), "uint64" }, - { typeof(float) , "real32"}, - { typeof(double) , "real64"}, - { typeof(bool) , "boolean"}, + { typeof(float), "real32"}, + { typeof(double), "real64"}, + { typeof(bool), "boolean"}, { typeof(string), "string" }, { typeof(DateTime), "datetime" }, { typeof(PSCredential), "string" }, @@ -2932,8 +2914,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable bool needComma = false; foreach (var attr in customAttributes) { - var dscProperty = attr as DscPropertyAttribute; - if (dscProperty != null) + if (attr is DscPropertyAttribute dscProperty) { if (dscProperty.Key) { @@ -2956,8 +2937,7 @@ private static string MapAttributesToMof(string[] enumNames, IEnumerable continue; } - var validateSet = attr as ValidateSetAttribute; - if (validateSet != null) + if (attr is ValidateSetAttribute validateSet) { bool valueMapComma = false; StringBuilder sbValues = new(", Values{"); @@ -3072,7 +3052,7 @@ private static void GenerateMofForType(Type type, StringBuilder sb, List { var className = type.Name; // Friendly name is required by module validator to verify resource instance against the exclusive resource name list. - sb.AppendFormat(CultureInfo.InvariantCulture, "[ClassVersion(\"1.0.0\"), FriendlyName(\"{0}\")]\nclass {0}", className); + sb.Append(CultureInfo.InvariantCulture, $"[ClassVersion(\"1.0.0\"), FriendlyName(\"{className}\")]\nclass {className}"); if (type.GetCustomAttributes().Any()) { @@ -3087,9 +3067,9 @@ private static void GenerateMofForType(Type type, StringBuilder sb, List private static void ProcessMembers(Type type, StringBuilder sb, List embeddedInstanceTypes, string className) { - foreach (var member in type.GetMembers(BindingFlags.Instance | BindingFlags.Public).Where(m => m is PropertyInfo || m is FieldInfo)) + foreach (var member in type.GetMembers(BindingFlags.Instance | BindingFlags.Public).Where(static m => m is PropertyInfo || m is FieldInfo)) { - if (member.CustomAttributes.All(cad => cad.AttributeType != typeof(DscPropertyAttribute))) + if (member.CustomAttributes.All(static cad => cad.AttributeType != typeof(DscPropertyAttribute))) { continue; } @@ -3112,21 +3092,21 @@ private static void ProcessMembers(Type type, StringBuilder sb, List emb } // TODO - validate type and name - bool isArrayType; - string embeddedInstanceType; - string mofType = MapTypeToMofType(memberType, member.Name, className, out isArrayType, out embeddedInstanceType, + string mofType = MapTypeToMofType( + memberType, + member.Name, + className, + out bool isArrayType, + out string embeddedInstanceType, embeddedInstanceTypes); + + var enumNames = memberType.IsEnum ? Enum.GetNames(memberType) : null; + string mofAttr = MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType); string arrayAffix = isArrayType ? "[]" : string.Empty; - var enumNames = memberType.IsEnum - ? Enum.GetNames(memberType) - : null; - sb.AppendFormat(CultureInfo.InvariantCulture, - " {0}{1} {2}{3};\n", - MapAttributesToMof(enumNames, member.GetCustomAttributes(true), embeddedInstanceType), - mofType, - member.Name, - arrayAffix); + sb.Append( + CultureInfo.InvariantCulture, + $" {mofAttr}{mofType} {member.Name}{arrayAffix};\n"); } } @@ -3141,7 +3121,7 @@ private static bool ImportKeywordsFromAssembly(PSModuleInfo module, var parser = new Microsoft.PowerShell.DesiredStateConfiguration.CimDSCParser(MyClassCallback); IEnumerable resourceDefinitions = - assembly.GetTypes().Where(t => t.GetCustomAttributes().Any()); + assembly.GetTypes().Where(static t => t.GetCustomAttributes().Any()); foreach (var r in resourceDefinitions) { @@ -3157,7 +3137,10 @@ private static bool ImportKeywordsFromAssembly(PSModuleInfo module, } } - if (skip) continue; + if (skip) + { + continue; + } var mof = GenerateMofForType(r); @@ -3275,14 +3258,15 @@ public static bool ImportCimKeywordsFromModule(PSModuleInfo module, string resou // try { - var dscResourceDirectories = Directory.GetDirectories(dscResourcesPath); - foreach (var directory in dscResourceDirectories) + foreach (var directory in Directory.EnumerateDirectories(dscResourcesPath)) { - var schemaFiles = Directory.GetFiles(directory, "*.schema.mof", SearchOption.TopDirectoryOnly); - if (schemaFiles.Length > 0) + IEnumerable schemaFiles = Directory.EnumerateFiles(directory, "*.schema.mof", SearchOption.TopDirectoryOnly); + string tempSchemaFilepath = schemaFiles.FirstOrDefault(); + + Debug.Assert(schemaFiles.Count() == 1, "A valid DSCResource module can have only one schema mof file"); + + if (tempSchemaFilepath is not null) { - Debug.Assert(schemaFiles.Length == 1, "A valid DSCResource module can have only one schema mof file"); - var tempSchemaFilepath = schemaFiles[0]; var classes = GetCachedClassByFileName(tempSchemaFilepath) ?? ImportClasses(tempSchemaFilepath, new Tuple(module.Name, module.Version), errors); if (classes != null) { @@ -3635,7 +3619,7 @@ public static string GetDSCResourceUsageString(DynamicKeyword keyword) bool listKeyProperties = true; while (true) { - foreach (var prop in keyword.Properties.OrderBy(ob => ob.Key)) + foreach (var prop in keyword.Properties.OrderBy(static ob => ob.Key)) { if (string.Equals(prop.Key, "ResourceId", StringComparison.OrdinalIgnoreCase)) { @@ -3702,7 +3686,7 @@ private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, // Do the property values map if (prop.ValueMap != null && prop.ValueMap.Count > 0) { - formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.OrderBy(x => x)) + " }"); + formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.Order()) + " }"); } // We prepend optional property with "[" so close out it here. This way it is shown with [ ] to indication optional diff --git a/src/System.Management.Automation/DscSupport/JsonCimDSCParser.cs b/src/System.Management.Automation/DscSupport/JsonCimDSCParser.cs deleted file mode 100755 index c2221cb3f33..00000000000 --- a/src/System.Management.Automation/DscSupport/JsonCimDSCParser.cs +++ /dev/null @@ -1,68 +0,0 @@ -// 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.Security; - -namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform -{ - /// - /// Class that does high level Cim schema parsing. - /// - internal class CimDSCParser - { - private readonly JsonDeserializer _jsonDeserializer; - - internal CimDSCParser() - { - _jsonDeserializer = JsonDeserializer.Create(); - } - - internal IEnumerable ParseSchemaJson(string filePath, bool useNewRunspace = false) - { - try - { - string json = File.ReadAllText(filePath); - string fileNameDefiningClass = Path.GetFileNameWithoutExtension(filePath); - int dotIndex = fileNameDefiningClass.IndexOf(".schema", StringComparison.InvariantCultureIgnoreCase); - if (dotIndex != -1) - { - fileNameDefiningClass = fileNameDefiningClass.Substring(0, dotIndex); - } - - IEnumerable result = _jsonDeserializer.DeserializeClasses(json, useNewRunspace); - foreach (dynamic classObject in result) - { - string superClassName = classObject.SuperClassName; - string className = classObject.ClassName; - if (string.Equals(superClassName, "OMI_BaseResource", StringComparison.OrdinalIgnoreCase)) - { - // Get the name of the file without schema.mof/json extension - if (!className.Equals(fileNameDefiningClass, StringComparison.OrdinalIgnoreCase)) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( - ParserStrings.ClassNameNotSameAsDefiningFile, className, fileNameDefiningClass); - throw e; - } - } - } - - return result; - } - catch (Exception exception) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( - exception, ParserStrings.CimDeserializationError, filePath); - - e.SetErrorId("CimDeserializationError"); - throw e; - } - } - } -} diff --git a/src/System.Management.Automation/DscSupport/JsonDeserializer.cs b/src/System.Management.Automation/DscSupport/JsonDeserializer.cs deleted file mode 100755 index 319560f0a09..00000000000 --- a/src/System.Management.Automation/DscSupport/JsonDeserializer.cs +++ /dev/null @@ -1,72 +0,0 @@ -// 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.Runspaces; - -namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform -{ - internal class JsonDeserializer - { - #region Constructors - - /// - /// Instantiates a default deserializer. - /// - /// Default deserializer. - public static JsonDeserializer Create() - { - return new JsonDeserializer(); - } - - #endregion Constructors - - #region Methods - - /// - /// Returns schema of Cim classes from specified json file. - /// - /// Json text to deserialize. - /// If a new runspace should be used. - /// Deserialized PSObjects. - public IEnumerable DeserializeClasses(string json, bool useNewRunspace = false) - { - if (string.IsNullOrEmpty(json)) - { - throw new ArgumentNullException(nameof(json)); - } - - System.Management.Automation.PowerShell powerShell = null; - - if (useNewRunspace) - { - // currently using RunspaceMode.NewRunspace will reset PSModulePath env var for the entire process - // this is something we want to avoid in DSC GuestConfigAgent scenario, so we use following workaround - var s_iss = InitialSessionState.CreateDefault(); - s_iss.EnvironmentVariables.Add( - new SessionStateVariableEntry( - "PSModulePath", - Environment.GetEnvironmentVariable("PSModulePath"), - description: null)); - powerShell = System.Management.Automation.PowerShell.Create(s_iss); - } - else - { - powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); - } - - using (powerShell) - { - return powerShell.AddCommand("Microsoft.PowerShell.Utility\\ConvertFrom-Json") - .AddParameter("InputObject", json) - .AddParameter("Depth", 100) // maximum supported by cmdlet - .Invoke(); - } - } - - #endregion Methods - } -} diff --git a/src/System.Management.Automation/DscSupport/JsonDscClassCache.cs b/src/System.Management.Automation/DscSupport/JsonDscClassCache.cs deleted file mode 100755 index 2fe4f7c2606..00000000000 --- a/src/System.Management.Automation/DscSupport/JsonDscClassCache.cs +++ /dev/null @@ -1,2498 +0,0 @@ -// 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.IO; -using System.Linq; -using System.Management.Automation; -using System.Management.Automation.Language; -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security; -using System.Text; -using System.Text.RegularExpressions; - -using Microsoft.PowerShell.Commands; - -namespace Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform -{ - /// - /// Class that defines Dsc cache entries. - /// - internal class DscClassCacheEntry - { - /// - /// Initializes a new instance of the class. - /// - public DscClassCacheEntry() - : this(DSCResourceRunAsCredential.Default, isImportedImplicitly: false, cimClassInstance: null, modulePath: string.Empty) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// Run as credential value. - /// Resource is imported implicitly. - /// Class definition. - /// Path of module defining the class. - public DscClassCacheEntry(DSCResourceRunAsCredential dscResourceRunAsCredential, bool isImportedImplicitly, PSObject cimClassInstance, string modulePath) - { - DscResRunAsCred = dscResourceRunAsCredential; - IsImportedImplicitly = isImportedImplicitly; - CimClassInstance = cimClassInstance; - ModulePath = modulePath; - } - - /// - /// Gets or sets the RunAs Credentials that this DSC resource will use. - /// - public DSCResourceRunAsCredential DscResRunAsCred { get; set; } - - /// - /// Gets or sets a value indicating if we have implicitly imported this resource. - /// - public bool IsImportedImplicitly { get; set; } - - /// - /// Gets or sets CimClass instance for this resource. - /// - public PSObject CimClassInstance { get; set; } - - /// - /// Gets or sets path of the implementing module for this resource. - /// - public string ModulePath { get; set; } - } - - /// - /// DSC class cache for this runspace. - /// - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", - Justification = "Needed Internal use only")] - public static class DscClassCache - { - private static readonly HashSet s_reservedDynamicKeywords = new HashSet(new[] { "Synchronization", "Certificate", "IIS", "SQL" }, StringComparer.OrdinalIgnoreCase); - - private static readonly HashSet s_reservedProperties = new HashSet(new[] { "Require", "Trigger", "Notify", "Before", "After", "Subscribe" }, StringComparer.OrdinalIgnoreCase); - - /// - /// Experimental feature name for DSC v3. - /// - public const string DscExperimentalFeatureName = "PS7DscSupport"; - - private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("DSC", "DSC Class Cache"); - - // Constants for items in the module qualified name (Module\Version\ClassName) - private const int ModuleNameIndex = 0; - private const int ModuleVersionIndex = 1; - private const int ClassNameIndex = 2; - private const int FriendlyNameIndex = 3; - - // Create a HashSet for fast lookup. According to MSDN, the time complexity of search for an element in a HashSet is O(1) - private static readonly HashSet s_hiddenResourceCache = - new HashSet(StringComparer.OrdinalIgnoreCase) { "MSFT_BaseConfigurationProviderRegistration", "MSFT_CimConfigurationProviderRegistration", "MSFT_PSConfigurationProviderRegistration" }; - - // A collection to prevent circular importing case when Import-DscResource does not have a module specified - [ThreadStatic] - private static readonly HashSet t_currentImportDscResourceInvocations = new(StringComparer.OrdinalIgnoreCase); - - /// - /// Gets DSC class cache for this runspace. - /// Cache stores the DSCRunAsBehavior, cim class and boolean to indicate if an Inbox resource has been implicitly imported. - /// - private static Dictionary ClassCache - { - get => t_classCache ??= new Dictionary(StringComparer.OrdinalIgnoreCase); - } - - [ThreadStatic] - private static Dictionary t_classCache; - - /// - /// Gets DSC class cache for GuestConfig; it is similar to ClassCache, but maintains values between operations. - /// - private static Dictionary GuestConfigClassCache - { - get => t_guestConfigClassCache ??= new Dictionary(StringComparer.OrdinalIgnoreCase); - } - - [ThreadStatic] - private static Dictionary t_guestConfigClassCache; - - /// - /// DSC classname to source module mapper. - /// - private static Dictionary> ByClassModuleCache - => t_byClassModuleCache ??= new Dictionary>(StringComparer.OrdinalIgnoreCase); - - [ThreadStatic] - private static Dictionary> t_byClassModuleCache; - - /// - /// Default ModuleName and ModuleVersion to use. - /// - private static readonly Tuple s_defaultModuleInfoForResource = new Tuple("PSDesiredStateConfiguration", new Version(3, 0)); - - /// - /// When this property is set to true, DSC Cache will cache multiple versions of a resource. - /// That means it will cache duplicate resource classes (class names for a resource in two different module versions are same). - /// NOTE: This property should be set to false for DSC compiler related methods/functionality, such as Import-DscResource, - /// because the Mof serializer does not support deserialization of classes with different versions. - /// - [ThreadStatic] - private static bool t_cacheResourcesFromMultipleModuleVersions; - - private static bool CacheResourcesFromMultipleModuleVersions - { - get - { - return t_cacheResourcesFromMultipleModuleVersions; - } - - set - { - t_cacheResourcesFromMultipleModuleVersions = value; - } - } - - [ThreadStatic] - private static bool t_newApiIsUsed = false; - - /// - /// Flag shows if PS7 DSC APIs were used. - /// - public static bool NewApiIsUsed - { - get - { - return t_newApiIsUsed; - } - - set - { - t_newApiIsUsed = value; - } - } - - /// - /// Initialize the class cache with the default classes in $ENV:SystemDirectory\Configuration. - /// - public static void Initialize() - { - Initialize(errors: null, modulePathList: null); - } - - /// - /// Initialize the class cache with default classes that come with PSDesiredStateConfiguration module. - /// - /// Collection of any errors encountered during initialization. - /// List of module path from where DSC PS modules will be loaded. - public static void Initialize(Collection errors, List modulePathList) - { - s_tracer.WriteLine("Initializing DSC class cache"); - - // Load the base schema files. - ClearCache(); - var dscConfigurationDirectory = Environment.GetEnvironmentVariable("DSC_HOME"); - if (string.IsNullOrEmpty(dscConfigurationDirectory)) - { - var moduleInfos = ModuleCmdletBase.GetModuleIfAvailable(new Microsoft.PowerShell.Commands.ModuleSpecification() - { - Name = "PSDesiredStateConfiguration", - - // Version in the next line is actually MinimumVersion - Version = new Version(3, 0, 0) - }); - - if (moduleInfos.Count > 0) - { - // to be consistent with Import-Module behavior, we use the first occurrence that we find in PSModulePath - var moduleDirectory = Path.GetDirectoryName(moduleInfos[0].Path); - dscConfigurationDirectory = Path.Join(moduleDirectory, "Configuration"); - } - else - { - // when all else has failed use location of system-wide PS module directory (i.e. /usr/local/share/powershell/Modules) as backup - dscConfigurationDirectory = Path.Join(ModuleIntrinsics.GetSharedModulePath(), "PSDesiredStateConfiguration", "Configuration"); - } - } - - if (!Directory.Exists(dscConfigurationDirectory)) - { - throw new DirectoryNotFoundException(string.Format(ParserStrings.PsDscMissingSchemaStore, dscConfigurationDirectory)); - } - - var resourceBaseFile = Path.Join(dscConfigurationDirectory, "BaseRegistration", "BaseResource.schema.json"); - ImportBaseClasses(resourceBaseFile, s_defaultModuleInfoForResource, errors, false); - var metaConfigFile = Path.Join(dscConfigurationDirectory, "BaseRegistration", "MSFT_DSCMetaConfiguration.json"); - ImportBaseClasses(metaConfigFile, s_defaultModuleInfoForResource, errors, false); - } - - /// - /// Import base classes from the given file. - /// - /// Path to schema file. - /// Module information. - /// Error collection that will be shown to the user. - /// Flag for implicitly imported resource. - /// Class objects from schema file. - public static IEnumerable ImportBaseClasses(string path, Tuple moduleInfo, Collection errors, bool importInBoxResourcesImplicitly) - { - if (string.IsNullOrEmpty(path)) - { - throw PSTraceSource.NewArgumentNullException(nameof(path)); - } - - s_tracer.WriteLine("DSC ClassCache: importing file: {0}", path); - - var parser = new CimDSCParser(); - - IEnumerable classes = null; - try - { - classes = parser.ParseSchemaJson(path); - } - catch (PSInvalidOperationException e) - { - // Ignore modules with invalid schemas. - s_tracer.WriteLine("DSC ClassCache: Error importing file '{0}', with error '{1}'. Skipping file.", path, e); - if (errors != null) - { - errors.Add(e); - } - } - - if (classes != null) - { - foreach (dynamic c in classes) - { - var className = c.ClassName; - - if (string.IsNullOrEmpty(className)) - { - // ClassName is empty - skipping class import - continue; - } - - string alias = GetFriendlyName(c); - var friendlyName = string.IsNullOrEmpty(alias) ? className : alias; - string moduleQualifiedResourceName = GetModuleQualifiedResourceName(moduleInfo.Item1, moduleInfo.Item2.ToString(), className, friendlyName); - DscClassCacheEntry cimClassInfo; - - if (ClassCache.TryGetValue(moduleQualifiedResourceName, out cimClassInfo)) - { - if (errors != null) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException( - ParserStrings.DuplicateCimClassDefinition, className, path, cimClassInfo.ModulePath); - - e.SetErrorId("DuplicateCimClassDefinition"); - errors.Add(e); - } - - continue; - } - - if (s_hiddenResourceCache.Contains(className)) - { - continue; - } - - var classCacheEntry = new DscClassCacheEntry(DSCResourceRunAsCredential.NotSupported, importInBoxResourcesImplicitly, c, path); - ClassCache[moduleQualifiedResourceName] = classCacheEntry; - GuestConfigClassCache[moduleQualifiedResourceName] = classCacheEntry; - ByClassModuleCache[className] = moduleInfo; - } - - var sb = new System.Text.StringBuilder(); - foreach (dynamic c in classes) - { - sb.Append(c.ClassName); - sb.Append(','); - } - - s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added the following classes to the cache: {1}", path, sb.ToString()); - } - else - { - s_tracer.WriteLine("DSC ClassCache: loading file '{0}' added no classes to the cache."); - } - - return classes; - } - - /// - /// Get text from SecureString. - /// - /// Value of SecureString. - /// Decoded string. - public static string GetStringFromSecureString(SecureString value) - { - string passwordValueToAdd = string.Empty; - - if (value != null) - { - IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(value); - passwordValueToAdd = Marshal.PtrToStringUni(ptr); - Marshal.ZeroFreeCoTaskMemUnicode(ptr); - } - - return passwordValueToAdd; - } - - /// - /// Clear out the existing collection of CIM classes and associated keywords. - /// - public static void ClearCache() - { - if (!ExperimentalFeature.IsEnabled(DscExperimentalFeatureName)) - { - throw new InvalidOperationException(ParserStrings.PS7DscSupportDisabled); - } - - s_tracer.WriteLine("DSC class: clearing the cache and associated keywords."); - ClassCache.Clear(); - ByClassModuleCache.Clear(); - CacheResourcesFromMultipleModuleVersions = false; - t_currentImportDscResourceInvocations.Clear(); - } - - private static string GetModuleQualifiedResourceName(string moduleName, string moduleVersion, string className, string resourceName) - { - return string.Format(CultureInfo.InvariantCulture, "{0}\\{1}\\{2}\\{3}", moduleName, moduleVersion, className, resourceName); - } - - private static List> FindResourceInCache(string moduleName, string className, string resourceName) - { - return (from cacheEntry in ClassCache - let splittedName = cacheEntry.Key.Split(Utils.Separators.Backslash) - let cachedClassName = splittedName[ClassNameIndex] - let cachedModuleName = splittedName[ModuleNameIndex] - let cachedResourceName = splittedName[FriendlyNameIndex] - where (string.Equals(cachedResourceName, resourceName, StringComparison.OrdinalIgnoreCase) - || (string.Equals(cachedClassName, className, StringComparison.OrdinalIgnoreCase) - && string.Equals(cachedModuleName, moduleName, StringComparison.OrdinalIgnoreCase))) - select cacheEntry).ToList(); - } - - /// - /// Returns class declaration from GuestConfigClassCache. - /// - /// Module name. - /// Module version. - /// Name of the class. - /// Friendly name of the resource. - /// Class declaration from cache. - public static PSObject GetGuestConfigCachedClass(string moduleName, string moduleVersion, string className, string resourceName) - { - if (!ExperimentalFeature.IsEnabled(DscExperimentalFeatureName)) - { - throw new InvalidOperationException(ParserStrings.PS7DscSupportDisabled); - } - - var moduleQualifiedResourceName = GetModuleQualifiedResourceName(moduleName, moduleVersion, className, string.IsNullOrEmpty(resourceName) ? className : resourceName); - DscClassCacheEntry classCacheEntry = null; - if (GuestConfigClassCache.TryGetValue(moduleQualifiedResourceName, out classCacheEntry)) - { - return classCacheEntry.CimClassInstance; - } - else - { - // if class was not found with current ResourceName then it may be a class with non-empty FriendlyName that caller does not know, so perform a broad search - string partialClassPath = string.Join('\\', moduleName, moduleVersion, className, string.Empty); - foreach (string key in GuestConfigClassCache.Keys) - { - if (key.StartsWith(partialClassPath)) - { - return GuestConfigClassCache[key].CimClassInstance; - } - } - - return null; - } - } - - /// - /// Clears GuestConfigClassCache. - /// - public static void ClearGuestConfigClassCache() - { - GuestConfigClassCache.Clear(); - } - - private static bool IsMagicProperty(string propertyName) - { - return System.Text.RegularExpressions.Regex.Match(propertyName, "^(ResourceId|SourceInfo|ModuleName|ModuleVersion|ConfigurationName)$", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success; - } - - private static string GetFriendlyName(dynamic cimClass) - { - return cimClass.FriendlyName; - } - - /// - /// Method to get the cached classes in the form of DynamicKeyword. - /// - /// Dynamic keyword collection. - public static Collection GetKeywordsFromCachedClasses() - { - if (!ExperimentalFeature.IsEnabled(DscExperimentalFeatureName)) - { - throw new InvalidOperationException(ParserStrings.PS7DscSupportDisabled); - } - - Collection keywords = new Collection(); - - foreach (KeyValuePair cachedClass in ClassCache) - { - string[] splittedName = cachedClass.Key.Split(Utils.Separators.Backslash); - string moduleName = splittedName[ModuleNameIndex]; - string moduleVersion = splittedName[ModuleVersionIndex]; - - var keyword = CreateKeywordFromCimClass(moduleName, Version.Parse(moduleVersion), cachedClass.Value.CimClassInstance, cachedClass.Value.DscResRunAsCred); - if (keyword is not null) - { - keywords.Add(keyword); - } - } - - return keywords; - } - - private static void CreateAndRegisterKeywordFromCimClass(string moduleName, Version moduleVersion, PSObject cimClass, Dictionary functionsToDefine, DSCResourceRunAsCredential runAsBehavior) - { - var keyword = CreateKeywordFromCimClass(moduleName, moduleVersion, cimClass, runAsBehavior); - if (keyword is null) - { - return; - } - - // keyword is already defined and we don't allow redefine it - if (!CacheResourcesFromMultipleModuleVersions && DynamicKeyword.ContainsKeyword(keyword.Keyword)) - { - var oldKeyword = DynamicKeyword.GetKeyword(keyword.Keyword); - if (oldKeyword.ImplementingModule is null || - !oldKeyword.ImplementingModule.Equals(moduleName, StringComparison.OrdinalIgnoreCase) || oldKeyword.ImplementingModuleVersion != moduleVersion) - { - var e = PSTraceSource.NewInvalidOperationException(ParserStrings.DuplicateKeywordDefinition, keyword.Keyword); - e.SetErrorId("DuplicateKeywordDefinition"); - throw e; - } - } - - // Add the dynamic keyword to the table - DynamicKeyword.AddKeyword(keyword); - - // And now define the driver functions in the current scope... - if (functionsToDefine != null) - { - functionsToDefine[moduleName + "\\" + keyword.Keyword] = CimKeywordImplementationFunction; - } - } - - private static DynamicKeyword CreateKeywordFromCimClass(string moduleName, Version moduleVersion, dynamic cimClass, DSCResourceRunAsCredential runAsBehavior) - { - var resourceName = cimClass.ClassName; - string alias = GetFriendlyName(cimClass); - var keywordString = string.IsNullOrEmpty(alias) ? resourceName : alias; - - // Skip all of the base, meta, registration and other classes that are not intended to be used directly by a script author - if (System.Text.RegularExpressions.Regex.Match(keywordString, "^OMI_Base|^OMI_.*Registration", System.Text.RegularExpressions.RegexOptions.IgnoreCase).Success) - { - return null; - } - - var keyword = new DynamicKeyword() - { - BodyMode = DynamicKeywordBodyMode.Hashtable, - Keyword = keywordString, - ResourceName = resourceName, - ImplementingModule = moduleName, - ImplementingModuleVersion = moduleVersion, - SemanticCheck = CheckMandatoryPropertiesPresent - }; - - // If it's one of reserved dynamic keyword, mark it - if (s_reservedDynamicKeywords.Contains(keywordString)) - { - keyword.IsReservedKeyword = true; - } - - // see if it's a resource type i.e. it inherits from OMI_BaseResource - bool isResourceType = false; - - // previous version of this code was the only place that referenced CimSuperClass - // so to simplify things we just check superclass to be OMI_BaseResource - // with assumption that current code will not work for multi-level class inheritance (which is never used in practice according to DSC team) - // this simplification allows us to avoid linking objects together using CimSuperClass field during deserialization - if ((!string.IsNullOrEmpty(cimClass.SuperClassName)) && string.Equals("OMI_BaseResource", cimClass.SuperClassName, StringComparison.OrdinalIgnoreCase)) - { - isResourceType = true; - } - - // If it's a resource type, then a resource name is required. - keyword.NameMode = isResourceType ? DynamicKeywordNameMode.NameRequired : DynamicKeywordNameMode.NoName; - - // Add the settable properties to the keyword object - if (cimClass.ClassProperties != null) - { - foreach (var prop in cimClass.ClassProperties) - { - // If the property has the Read qualifier, skip it. - if (string.Equals(prop.Qualifiers?.Read?.ToString(), "True", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - // If it's one of our magic properties, skip it - if (IsMagicProperty(prop.Name)) - { - continue; - } - - if (runAsBehavior == DSCResourceRunAsCredential.NotSupported) - { - if (string.Equals(prop.Name, "PsDscRunAsCredential", StringComparison.OrdinalIgnoreCase)) - { - // skip adding PsDscRunAsCredential to the dynamic word for the dsc resource. - continue; - } - } - - // If it's one of our reserved properties, save it for error reporting - if (s_reservedProperties.Contains(prop.Name)) - { - keyword.HasReservedProperties = true; - continue; - } - - // Otherwise, add it to the Keyword List. - var keyProp = new System.Management.Automation.Language.DynamicKeywordProperty(); - keyProp.Name = prop.Name; - - // Copy the type name string. If it's an embedded instance, need to grab it from the ReferenceClassName - bool referenceClassNameIsNullOrEmpty = string.IsNullOrEmpty(prop.ReferenceClassName); - if (prop.CimType == "Instance" && !referenceClassNameIsNullOrEmpty) - { - keyProp.TypeConstraint = prop.ReferenceClassName; - } - else if (prop.CimType == "InstanceArray" && !referenceClassNameIsNullOrEmpty) - { - keyProp.TypeConstraint = prop.ReferenceClassName + "[]"; - } - else - { - keyProp.TypeConstraint = prop.CimType.ToString(); - } - - // Check to see if there is a Values attribute and save the list of allowed values if so. - var values = prop.Qualifiers?.Values; - if (values is not null) - { - foreach (var val in values) - { - keyProp.Values.Add(val.ToString()); - } - } - - // Check to see if there is a ValueMap attribute and save the list of allowed values if so. - var nativeValueMap = prop.Qualifiers?.ValueMap; - List valueMap = null; - if (nativeValueMap is not null) - { - valueMap = new List(); - foreach (var val in nativeValueMap) - { - valueMap.Add(val.ToString()); - } - } - - // Check to see if this property has the Required qualifier associated with it. - if (string.Equals(prop.Qualifiers?.Required?.ToString(), "True", StringComparison.OrdinalIgnoreCase)) - { - keyProp.Mandatory = true; - } - - // Check to see if this property has the Key qualifier associated with it. - if (string.Equals(prop.Qualifiers?.Key?.ToString(), "True", StringComparison.OrdinalIgnoreCase)) - { - keyProp.Mandatory = true; - keyProp.IsKey = true; - } - - // set the property to mandatory is specified for the resource. - if (runAsBehavior == DSCResourceRunAsCredential.Mandatory) - { - if (string.Equals(prop.Name, "PsDscRunAsCredential", StringComparison.OrdinalIgnoreCase)) - { - keyProp.Mandatory = true; - } - } - - if (valueMap is not null && keyProp.Values.Count > 0) - { - if (valueMap.Count != keyProp.Values.Count) - { - s_tracer.WriteLine( - "DSC CreateDynamicKeywordFromClass: the count of values for qualifier 'Values' and 'ValueMap' doesn't match. count of 'Values': {0}, count of 'ValueMap': {1}. Skip the keyword '{2}'.", - keyProp.Values.Count, - valueMap.Count, - keyword.Keyword); - return null; - } - - for (int index = 0; index < valueMap.Count; index++) - { - string key = keyProp.Values[index]; - string value = valueMap[index]; - - if (keyProp.ValueMap.ContainsKey(key)) - { - s_tracer.WriteLine( - "DSC CreateDynamicKeywordFromClass: same string value '{0}' appears more than once in qualifier 'Values'. Skip the keyword '{1}'.", - key, - keyword.Keyword); - return null; - } - - keyProp.ValueMap.Add(key, value); - } - } - - keyword.Properties.Add(prop.Name, keyProp); - } - } - - // update specific keyword with range constraints - UpdateKnownRestriction(keyword); - - return keyword; - } - - private static void UpdateKnownRestriction(DynamicKeyword keyword) - { - const int RefreshFrequencyMin = 30; - const int RefreshFrequencyMax = 44640; - - const int ConfigurationModeFrequencyMin = 15; - const int ConfigurationModeFrequencyMax = 44640; - - if ( - string.Equals( - keyword.ResourceName, - "MSFT_DSCMetaConfigurationV2", - StringComparison.OrdinalIgnoreCase) - || - string.Equals( - keyword.ResourceName, - "MSFT_DSCMetaConfiguration", - StringComparison.OrdinalIgnoreCase)) - { - if (keyword.Properties["RefreshFrequencyMins"] is not null) - { - keyword.Properties["RefreshFrequencyMins"].Range = new Tuple(RefreshFrequencyMin, RefreshFrequencyMax); - } - - if (keyword.Properties["ConfigurationModeFrequencyMins"] != null) - { - keyword.Properties["ConfigurationModeFrequencyMins"].Range = new Tuple(ConfigurationModeFrequencyMin, ConfigurationModeFrequencyMax); - } - - if (keyword.Properties["DebugMode"] is not null) - { - keyword.Properties["DebugMode"].Values.Remove("ResourceScriptBreakAll"); - keyword.Properties["DebugMode"].ValueMap.Remove("ResourceScriptBreakAll"); - } - } - } - - /// - /// Load the default system CIM classes and create the corresponding keywords. - /// - /// Collection of any errors encountered while loading keywords. - public static void LoadDefaultCimKeywords(Collection errors) - { - LoadDefaultCimKeywords(functionsToDefine: null, errors, modulePathList: null, cacheResourcesFromMultipleModuleVersions: false); - } - - /// - /// Load the default system CIM classes and create the corresponding keywords. - /// - /// A dictionary to add the defined functions to, may be null. - public static void LoadDefaultCimKeywords(Dictionary functionsToDefine) - { - LoadDefaultCimKeywords(functionsToDefine, errors: null, modulePathList: null, cacheResourcesFromMultipleModuleVersions: false); - } - - /// - /// Load the default system CIM classes and create the corresponding keywords. - /// - /// Collection of any errors encountered while loading keywords. - /// Allow caching the resources from multiple versions of modules. - public static void LoadDefaultCimKeywords(Collection errors, bool cacheResourcesFromMultipleModuleVersions) - { - LoadDefaultCimKeywords(functionsToDefine: null, errors, modulePathList: null, cacheResourcesFromMultipleModuleVersions); - } - - /// - /// Load the default system CIM classes and create the corresponding keywords. - /// - /// A dictionary to add the defined functions to, may be null. - /// Collection of any errors encountered while loading keywords. - /// List of module path from where DSC PS modules will be loaded. - /// Allow caching the resources from multiple versions of modules. - private static void LoadDefaultCimKeywords( - Dictionary functionsToDefine, - Collection errors, - List modulePathList, - bool cacheResourcesFromMultipleModuleVersions) - { - if (!ExperimentalFeature.IsEnabled(DscExperimentalFeatureName)) - { - Exception exception = new InvalidOperationException(ParserStrings.PS7DscSupportDisabled); - errors.Add(exception); - return; - } - - NewApiIsUsed = true; - DynamicKeyword.Reset(); - Initialize(errors, modulePathList); - - // Initialize->ClearCache resets CacheResourcesFromMultipleModuleVersions to false, - // workaround is to set it after Initialize method call. - // Initialize method imports all the Inbox resources and internal classes which belongs to only one version - // of the module, so it is ok if this property is not set during cache initialization. - CacheResourcesFromMultipleModuleVersions = cacheResourcesFromMultipleModuleVersions; - - foreach (dynamic cimClass in ClassCache.Values) - { - var className = cimClass.CimClassInstance.ClassName; - var moduleInfo = ByClassModuleCache[className]; - CreateAndRegisterKeywordFromCimClass(moduleInfo.Item1, moduleInfo.Item2, cimClass.CimClassInstance, functionsToDefine, cimClass.DscResRunAsCred); - } - - // And add the Node keyword definitions - if (!DynamicKeyword.ContainsKeyword("Node")) - { - // Implement dispatch to the Node keyword. - var nodeKeyword = new DynamicKeyword() - { - BodyMode = DynamicKeywordBodyMode.ScriptBlock, - ImplementingModule = s_defaultModuleInfoForResource.Item1, - ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2, - NameMode = DynamicKeywordNameMode.NameRequired, - Keyword = "Node", - }; - DynamicKeyword.AddKeyword(nodeKeyword); - } - - // And add the Import-DscResource keyword definitions - if (!DynamicKeyword.ContainsKeyword("Import-DscResource")) - { - // Implement dispatch to the Node keyword. - var nodeKeyword = new DynamicKeyword() - { - BodyMode = DynamicKeywordBodyMode.Command, - ImplementingModule = s_defaultModuleInfoForResource.Item1, - ImplementingModuleVersion = s_defaultModuleInfoForResource.Item2, - NameMode = DynamicKeywordNameMode.NoName, - Keyword = "Import-DscResource", - MetaStatement = true, - PostParse = ImportResourcePostParse, - SemanticCheck = ImportResourceCheckSemantics - }; - DynamicKeyword.AddKeyword(nodeKeyword); - } - } - - // This function is called after parsing the Import-DscResource keyword and it's arguments, but before parsing anything else. - private static ParseError[] ImportResourcePostParse(DynamicKeywordStatementAst ast) - { - var elements = Ast.CopyElements(ast.CommandElements); - var commandAst = new CommandAst(ast.Extent, elements, TokenKind.Unknown, null); - - const string NameParam = "Name"; - const string ModuleNameParam = "ModuleName"; - const string ModuleVersionParam = "ModuleVersion"; - - StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false); - - var errorList = new List(); - foreach (var bindingException in bindingResult.BindingExceptions.Values) - { - errorList.Add(new ParseError(bindingException.CommandElement.Extent, "ParameterBindingException", bindingException.BindingException.Message)); - } - - ParameterBindingResult moduleNameBindingResult = null; - ParameterBindingResult resourceNameBindingResult = null; - ParameterBindingResult moduleVersionBindingResult = null; - - foreach (var binding in bindingResult.BoundParameters) - { - // Error case when positional parameter values are specified - var boundParameterName = binding.Key; - var parameterBindingResult = binding.Value; - if (boundParameterName.All(char.IsDigit)) - { - errorList.Add(new ParseError(parameterBindingResult.Value.Extent, "ImportDscResourcePositionalParamsNotSupported", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourcePositionalParamsNotSupported))); - continue; - } - - if (NameParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase)) - { - resourceNameBindingResult = parameterBindingResult; - } - else if (ModuleNameParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase)) - { - moduleNameBindingResult = parameterBindingResult; - } - else if (ModuleVersionParam.StartsWith(boundParameterName, StringComparison.OrdinalIgnoreCase)) - { - moduleVersionBindingResult = parameterBindingResult; - } - else - { - errorList.Add(new ParseError(parameterBindingResult.Value.Extent, "ImportDscResourceNeedParams", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams))); - } - } - - if (errorList.Count == 0 && moduleNameBindingResult == null && resourceNameBindingResult == null) - { - errorList.Add(new ParseError(ast.Extent, "ImportDscResourceNeedParams", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams))); - } - - // Check here if Version is specified but modulename is not specified - if (moduleVersionBindingResult != null && moduleNameBindingResult == null) - { - // only add this error again to the error list if resources is not null - // if resources and modules are both null we have already added this error in collection - // we do not want to do this twice. since we are giving same error ImportDscResourceNeedParams in both cases - // once we have different error messages for 2 scenarios we can remove this check - if (resourceNameBindingResult is not null) - { - errorList.Add(new ParseError(ast.Extent, "ImportDscResourceNeedModuleNameWithModuleVersion", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams))); - } - } - - string[] resourceNames = null; - if (resourceNameBindingResult is not null) - { - object resourceName = null; - if (!IsConstantValueVisitor.IsConstant(resourceNameBindingResult.Value, out resourceName, true, true) || - !LanguagePrimitives.TryConvertTo(resourceName, out resourceNames)) - { - errorList.Add(new ParseError(resourceNameBindingResult.Value.Extent, "RequiresInvalidStringArgument", string.Format(CultureInfo.CurrentCulture, ParserStrings.RequiresInvalidStringArgument, NameParam))); - } - } - - System.Version moduleVersion = null; - if (moduleVersionBindingResult is not null) - { - object moduleVer = null; - if (!IsConstantValueVisitor.IsConstant(moduleVersionBindingResult.Value, out moduleVer, true, true)) - { - errorList.Add(new ParseError(moduleVersionBindingResult.Value.Extent, "RequiresArgumentMustBeConstant", ParserStrings.RequiresArgumentMustBeConstant)); - } - - if (moduleVer is double) - { - // this happens in case -ModuleVersion 1.0, then use extent text for that. - // The better way to do it would be define static binding API against CommandInfo, that holds information about parameter types. - // This way, we can avoid this ugly special-casing and say that -ModuleVersion has type [System.Version]. - moduleVer = moduleVersionBindingResult.Value.Extent.Text; - } - - if (!LanguagePrimitives.TryConvertTo(moduleVer, out moduleVersion)) - { - errorList.Add(new ParseError(moduleVersionBindingResult.Value.Extent, "RequiresVersionInvalid", ParserStrings.RequiresVersionInvalid)); - } - } - - ModuleSpecification[] moduleSpecifications = null; - if (moduleNameBindingResult is not null) - { - object moduleName = null; - if (!IsConstantValueVisitor.IsConstant(moduleNameBindingResult.Value, out moduleName, true, true)) - { - errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "RequiresArgumentMustBeConstant", ParserStrings.RequiresArgumentMustBeConstant)); - } - - if (LanguagePrimitives.TryConvertTo(moduleName, out moduleSpecifications)) - { - // if resourceNames are specified then we can not specify multiple modules name - if (moduleSpecifications is not null && moduleSpecifications.Length > 1 && resourceNames is not null) - { - errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "ImportDscResourceMultipleModulesNotSupportedWithName", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceMultipleModulesNotSupportedWithName))); - } - - // if moduleversion is specified then we can not specify multiple modules name - if (moduleSpecifications is not null && moduleSpecifications.Length > 1 && moduleVersion is not null) - { - errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "ImportDscResourceMultipleModulesNotSupportedWithVersion", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams))); - } - - // if moduleversion is specified then we can not specify another version in modulespecification object of ModuleName - if (moduleSpecifications is not null && (moduleSpecifications[0].Version is not null || moduleSpecifications[0].MaximumVersion is not null) && moduleVersion is not null) - { - errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "ImportDscResourceMultipleModuleVersionsNotSupported", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceNeedParams))); - } - - // If moduleVersion is specified we have only one module Name in valid scenario - // So update it's version property in module specification object that will be used to load modules - if (moduleSpecifications is not null && moduleSpecifications[0].Version is null && moduleSpecifications[0].MaximumVersion is null && moduleVersion is not null) - { - moduleSpecifications[0].Version = moduleVersion; - } - } - else - { - errorList.Add(new ParseError(moduleNameBindingResult.Value.Extent, "RequiresInvalidStringArgument", string.Format(CultureInfo.CurrentCulture, ParserStrings.RequiresInvalidStringArgument, ModuleNameParam))); - } - } - - if (errorList.Count == 0) - { - // No errors, try to load the resources - LoadResourcesFromModuleInImportResourcePostParse(ast.Extent, moduleSpecifications, resourceNames, errorList); - } - - return errorList.ToArray(); - } - - // This function performs semantic checks for Import-DscResource - private static ParseError[] ImportResourceCheckSemantics(DynamicKeywordStatementAst ast) - { - List errorList = null; - - var keywordAst = Ast.GetAncestorAst(ast.Parent); - while (keywordAst is not null) - { - if (keywordAst.Keyword.Keyword.Equals("Node")) - { - if (errorList is null) - { - errorList = new List(); - } - - errorList.Add(new ParseError(ast.Extent, "ImportDscResourceInsideNode", string.Format(CultureInfo.CurrentCulture, ParserStrings.ImportDscResourceInsideNode))); - break; - } - - keywordAst = Ast.GetAncestorAst(keywordAst.Parent); - } - - if (errorList is not null) - { - return errorList.ToArray(); - } - else - { - return null; - } - } - - // This function performs semantic checks for all DSC Resources keywords. - private static ParseError[] CheckMandatoryPropertiesPresent(DynamicKeywordStatementAst ast) - { - HashSet mandatoryPropertiesNames = new HashSet(StringComparer.OrdinalIgnoreCase); - foreach (var pair in ast.Keyword.Properties) - { - if (pair.Value.Mandatory) - { - mandatoryPropertiesNames.Add(pair.Key); - } - } - - // by design mandatoryPropertiesNames are not empty at this point: - // every resource must have at least one Key property. - HashtableAst hashtableAst = null; - foreach (var commandElementsAst in ast.CommandElements) - { - hashtableAst = commandElementsAst as HashtableAst; - if (hashtableAst != null) - { - break; - } - } - - if (hashtableAst is null) - { - // nothing to validate - return null; - } - - foreach (var pair in hashtableAst.KeyValuePairs) - { - object evalResultObject; - if (IsConstantValueVisitor.IsConstant(pair.Item1, out evalResultObject, forAttribute: false, forRequires: false)) - { - var presentName = evalResultObject as string; - if (presentName is not null) - { - if (mandatoryPropertiesNames.Remove(presentName) && mandatoryPropertiesNames.Count == 0) - { - // optimization, once all mandatory properties are specified, we can safely exit. - return null; - } - } - } - } - - if (mandatoryPropertiesNames.Count > 0) - { - ParseError[] errors = new ParseError[mandatoryPropertiesNames.Count]; - var extent = ast.CommandElements[0].Extent; - int i = 0; - foreach (string name in mandatoryPropertiesNames) - { - errors[i] = new ParseError( - extent, - "MissingValueForMandatoryProperty", - string.Format( - CultureInfo.CurrentCulture, - ParserStrings.MissingValueForMandatoryProperty, - ast.Keyword.Keyword, - ast.Keyword.Properties.First(p => StringComparer.OrdinalIgnoreCase.Equals(p.Value.Name, name)).Value.TypeConstraint, - name)); - i++; - } - - return errors; - } - - return null; - } - - /// - /// Load DSC resources from specified module. - /// - /// Script statement loading the module, can be null. - /// Module information, can be null. - /// Name of the resource to be loaded from module. - /// List of errors reported by the method. - internal static void LoadResourcesFromModuleInImportResourcePostParse( - IScriptExtent scriptExtent, - ModuleSpecification[] moduleSpecifications, - string[] resourceNames, - List errorList) - { - // get all required modules - var modules = new Collection(); - if (moduleSpecifications is not null) - { - foreach (var moduleToImport in moduleSpecifications) - { - bool foundModule = false; - var moduleInfos = ModuleCmdletBase.GetModuleIfAvailable(moduleToImport); - - if (moduleInfos.Count >= 1 && (moduleToImport.Version is not null || moduleToImport.Guid is not null)) - { - foreach (var psModuleInfo in moduleInfos) - { - if ((moduleToImport.Guid.HasValue && moduleToImport.Guid.Equals(psModuleInfo.Guid)) || - (moduleToImport.Version is not null && - moduleToImport.Version.Equals(psModuleInfo.Version))) - { - modules.Add(psModuleInfo); - foundModule = true; - break; - } - } - } - else if (moduleInfos.Count == 1) - { - modules.Add(moduleInfos[0]); - foundModule = true; - } - - if (!foundModule) - { - if (moduleInfos.Count > 1) - { - errorList.Add( - new ParseError( - scriptExtent, - "MultipleModuleEntriesFoundDuringParse", - string.Format(CultureInfo.CurrentCulture, ParserStrings.MultipleModuleEntriesFoundDuringParse, moduleToImport.Name))); - } - else - { - string moduleString = moduleToImport.Version == null - ? moduleToImport.Name - : string.Format(CultureInfo.CurrentCulture, "<{0}, {1}>", moduleToImport.Name, moduleToImport.Version); - - errorList.Add(new ParseError(scriptExtent, "ModuleNotFoundDuringParse", string.Format(CultureInfo.CurrentCulture, ParserStrings.ModuleNotFoundDuringParse, moduleString))); - } - - return; - } - } - } - else if (resourceNames is not null) - { - // Lookup the required resources under available PowerShell modules when modulename is not specified - // Make sure that this is not a circular import/parsing - var callLocation = string.Join(':', scriptExtent.File, scriptExtent.StartLineNumber, scriptExtent.StartColumnNumber, scriptExtent.Text); - if (!t_currentImportDscResourceInvocations.Contains(callLocation)) - { - t_currentImportDscResourceInvocations.Add(callLocation); - using (var powerShell = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace)) - { - powerShell.AddCommand("Get-Module"); - powerShell.AddParameter("ListAvailable"); - modules = powerShell.Invoke(); - } - } - } - - // When ModuleName only specified, we need to import all resources from that module - var resourcesToImport = new List(); - if (resourceNames is null || resourceNames.Length == 0) - { - resourcesToImport.Add("*"); - } - else - { - resourcesToImport.AddRange(resourceNames); - } - - foreach (var moduleInfo in modules) - { - var resourcesFound = new List(); - var exceptionList = new System.Collections.ObjectModel.Collection(); - LoadPowerShellClassResourcesFromModule(primaryModuleInfo: moduleInfo, moduleInfo: moduleInfo, resourcesToImport: resourcesToImport, resourcesFound: resourcesFound, errorList: exceptionList, functionsToDefine: null, recurse: true, extent: scriptExtent); - foreach (Exception ex in exceptionList) - { - errorList.Add(new ParseError(scriptExtent, "ClassResourcesLoadingFailed", ex.Message)); - } - - foreach (var resource in resourcesFound) - { - resourcesToImport.Remove(resource); - } - - if (resourcesToImport.Count == 0) - { - break; - } - } - - if (resourcesToImport.Count > 0) - { - foreach (var resourceNameToImport in resourcesToImport) - { - if (!resourceNameToImport.Contains('*')) - { - errorList.Add(new ParseError(scriptExtent, "DscResourcesNotFoundDuringParsing", string.Format(CultureInfo.CurrentCulture, ParserStrings.DscResourcesNotFoundDuringParsing, resourceNameToImport))); - } - } - } - } - - private static void LoadPowerShellClassResourcesFromModule( - PSModuleInfo primaryModuleInfo, - PSModuleInfo moduleInfo, - ICollection resourcesToImport, - ICollection resourcesFound, - Collection errorList, - Dictionary functionsToDefine = null, - bool recurse = true, - IScriptExtent extent = null) - { - if (primaryModuleInfo._declaredDscResourceExports is null || primaryModuleInfo._declaredDscResourceExports.Count == 0) - { - return; - } - - if (moduleInfo.ModuleType == ModuleType.Binary) - { - throw PSTraceSource.NewArgumentException("isConfiguration", ParserStrings.ConfigurationNotSupportedInPowerShellCore); - } - else - { - string scriptPath = null; - if (moduleInfo.RootModule is not null) - { - scriptPath = Path.Join(moduleInfo.ModuleBase, moduleInfo.RootModule); - } - else if (moduleInfo.Path is not null) - { - scriptPath = moduleInfo.Path; - } - - LoadPowerShellClassResourcesFromModule(scriptPath, primaryModuleInfo, resourcesToImport, resourcesFound, functionsToDefine, errorList, extent); - } - - if (moduleInfo.NestedModules is not null && recurse) - { - foreach (var nestedModule in moduleInfo.NestedModules) - { - LoadPowerShellClassResourcesFromModule(primaryModuleInfo, nestedModule, resourcesToImport, resourcesFound, errorList, functionsToDefine, recurse: false, extent: extent); - } - } - } - - /// - /// Import class resources from module. - /// - /// Module information. - /// Collection of resources to import. - /// Functions to define. - /// List of errors to return. - /// The list of resources imported from this module. - public static List ImportClassResourcesFromModule(PSModuleInfo moduleInfo, ICollection resourcesToImport, Dictionary functionsToDefine, Collection errors) - { - if (!ExperimentalFeature.IsEnabled(DscExperimentalFeatureName)) - { - throw new InvalidOperationException(ParserStrings.PS7DscSupportDisabled); - } - - var resourcesImported = new List(); - LoadPowerShellClassResourcesFromModule(moduleInfo, moduleInfo, resourcesToImport, resourcesImported, errors, functionsToDefine); - return resourcesImported; - } - - internal static PSObject[] GenerateJsonClassesForAst(TypeDefinitionAst typeAst, PSModuleInfo module, DSCResourceRunAsCredential runAsBehavior) - { - var embeddedInstanceTypes = new List(); - - var result = GenerateJsonClassesForAst(typeAst, embeddedInstanceTypes); - var visitedInstances = new List(); - visitedInstances.Add(typeAst); - var classes = ProcessEmbeddedInstanceTypes(embeddedInstanceTypes, visitedInstances); - AddEmbeddedInstanceTypesToCaches(classes, module, runAsBehavior); - - return result; - } - - private static List ProcessEmbeddedInstanceTypes(List embeddedInstanceTypes, List visitedInstances) - { - var result = new List(); - while (embeddedInstanceTypes.Count > 0) - { - var batchedTypes = embeddedInstanceTypes.Where(x => !visitedInstances.Contains(x)).ToArray(); - embeddedInstanceTypes.Clear(); - - for (int i = batchedTypes.Length - 1; i >= 0; i--) - { - visitedInstances.Add(batchedTypes[i]); - var typeAst = batchedTypes[i] as TypeDefinitionAst; - if (typeAst is not null) - { - var classes = GenerateJsonClassesForAst(typeAst, embeddedInstanceTypes); - result.AddRange(classes); - } - } - } - - return result; - } - - private static void AddEmbeddedInstanceTypesToCaches(IEnumerable classes, PSModuleInfo module, DSCResourceRunAsCredential runAsBehavior) - { - foreach (dynamic c in classes) - { - var className = c.ClassName; - string alias = GetFriendlyName(c); - var friendlyName = string.IsNullOrEmpty(alias) ? className : alias; - var moduleQualifiedResourceName = GetModuleQualifiedResourceName(module.Name, module.Version.ToString(), className, friendlyName); - var classCacheEntry = new DscClassCacheEntry(runAsBehavior, false, c, module.Path); - ClassCache[moduleQualifiedResourceName] = classCacheEntry; - GuestConfigClassCache[moduleQualifiedResourceName] = classCacheEntry; - ByClassModuleCache[className] = new Tuple(module.Name, module.Version); - } - } - - internal static string MapTypeNameToMofType(ITypeName typeName, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List embeddedInstanceTypes, ref string[] enumNames) - { - TypeName propTypeName; - var arrayTypeName = typeName as ArrayTypeName; - if (arrayTypeName is not null) - { - isArrayType = true; - propTypeName = arrayTypeName.ElementType as TypeName; - } - else - { - isArrayType = false; - propTypeName = typeName as TypeName; - } - - if (propTypeName is null || propTypeName._typeDefinitionAst is null) - { - throw new NotSupportedException(string.Format( - CultureInfo.InvariantCulture, - ParserStrings.UnsupportedPropertyTypeOfDSCResourceClass, - memberName, - typeName.FullName, - typeName)); - } - - if (propTypeName._typeDefinitionAst.IsEnum) - { - enumNames = propTypeName._typeDefinitionAst.Members.Select(m => m.Name).ToArray(); - isArrayType = false; - embeddedInstanceType = null; - return "string"; - } - - if (!embeddedInstanceTypes.Contains(propTypeName._typeDefinitionAst)) - { - embeddedInstanceTypes.Add(propTypeName._typeDefinitionAst); - } - - embeddedInstanceType = propTypeName.Name.Replace('.', '_'); - return "Instance"; - } - - private static PSObject[] GenerateJsonClassesForAst(TypeDefinitionAst typeAst, List embeddedInstanceTypes) - { - // MOF-based implementation of this used to generate MOF string representing classes/typeAst and pass it to MMI/MOF deserializer to get CimClass array - // Here we are avoiding that roundtrip by constructing the resulting PSObjects directly - var className = typeAst.Name; - - string cimSuperClassName = null; - if (typeAst.Attributes.Any(a => a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute))) - { - cimSuperClassName = "OMI_BaseResource"; - } - - var cimClassProperties = ProcessMembers(embeddedInstanceTypes, typeAst, className).ToArray(); - - Queue bases = new Queue(); - foreach (var b in typeAst.BaseTypes) - { - bases.Enqueue(b); - } - - while (bases.Count > 0) - { - var b = bases.Dequeue(); - var tc = b as TypeConstraintAst; - - if (tc is not null) - { - b = tc.TypeName.GetReflectionType(); - if (b is null) - { - var td = tc.TypeName as TypeName; - if (td is not null && td._typeDefinitionAst is not null) - { - ProcessMembers(embeddedInstanceTypes, td._typeDefinitionAst, className); - foreach (var b1 in td._typeDefinitionAst.BaseTypes) - { - bases.Enqueue(b1); - } - } - - continue; - } - } - } - - var result = new PSObject(); - result.Properties.Add(new PSNoteProperty("ClassName", className)); - result.Properties.Add(new PSNoteProperty("FriendlyName", className)); - result.Properties.Add(new PSNoteProperty("SuperClassName", cimSuperClassName)); - result.Properties.Add(new PSNoteProperty("ClassProperties", cimClassProperties)); - - return new[] { result }; - } - - private static List ProcessMembers(List embeddedInstanceTypes, TypeDefinitionAst typeDefinitionAst, string className) - { - List result = new List(); - - foreach (var member in typeDefinitionAst.Members) - { - var property = member as PropertyMemberAst; - - if (property == null || property.IsStatic || - property.Attributes.All(a => a.TypeName.GetReflectionAttributeType() != typeof(DscPropertyAttribute))) - { - continue; - } - - var memberType = property.PropertyType is null - ? typeof(object) - : property.PropertyType.TypeName.GetReflectionType(); - - var attributes = new List(); - for (int i = 0; i < property.Attributes.Count; i++) - { - attributes.Add(property.Attributes[i].GetAttribute()); - } - - string mofType; - bool isArrayType; - string embeddedInstanceType; - string[] enumNames = null; - - if (memberType != null) - { - mofType = MapTypeToMofType(memberType, member.Name, className, out isArrayType, out embeddedInstanceType, embeddedInstanceTypes); - if (memberType.IsEnum) - { - enumNames = Enum.GetNames(memberType); - } - } - else - { - // PropertyType can't be null, we used typeof(object) above in that case so we don't get here. - mofType = MapTypeNameToMofType(property.PropertyType.TypeName, member.Name, className, out isArrayType, out embeddedInstanceType, embeddedInstanceTypes, ref enumNames); - } - - var propertyObject = new PSObject(); - propertyObject.Properties.Add(new PSNoteProperty(@"Name", member.Name)); - propertyObject.Properties.Add(new PSNoteProperty(@"CimType", mofType + (isArrayType ? "Array" : string.Empty))); - if (!string.IsNullOrEmpty(embeddedInstanceType)) - { - propertyObject.Properties.Add(new PSNoteProperty(@"ReferenceClassName", embeddedInstanceType)); - } - - PSObject attributesPSObject = null; - foreach (var attr in attributes) - { - var dscProperty = attr as DscPropertyAttribute; - if (dscProperty is not null) - { - if (attributesPSObject is null) - { - attributesPSObject = new PSObject(); - } - - if (dscProperty.Key) - { - attributesPSObject.Properties.Add(new PSNoteProperty("Key", true)); - } - - if (dscProperty.Mandatory) - { - attributesPSObject.Properties.Add(new PSNoteProperty("Required", true)); - } - - if (dscProperty.NotConfigurable) - { - attributesPSObject.Properties.Add(new PSNoteProperty("Read", true)); - } - - continue; - } - - var validateSet = attr as ValidateSetAttribute; - if (validateSet is not null) - { - if (attributesPSObject is null) - { - attributesPSObject = new PSObject(); - } - - List valueMap = new List(validateSet.ValidValues); - List values = new List(validateSet.ValidValues); - attributesPSObject.Properties.Add(new PSNoteProperty("ValueMap", valueMap)); - attributesPSObject.Properties.Add(new PSNoteProperty("Values", values)); - } - } - - if (attributesPSObject is not null) - { - propertyObject.Properties.Add(new PSNoteProperty(@"Qualifiers", attributesPSObject)); - } - - result.Add(propertyObject); - } - - return result; - } - - private static bool GetResourceDefinitionsFromModule(string fileName, out IEnumerable resourceDefinitions, Collection errorList, IScriptExtent extent) - { - resourceDefinitions = null; - - if (string.IsNullOrEmpty(fileName)) - { - return false; - } - - if (!".psm1".Equals(Path.GetExtension(fileName), StringComparison.OrdinalIgnoreCase) && - !".ps1".Equals(Path.GetExtension(fileName), StringComparison.OrdinalIgnoreCase)) - { - return false; - } - - Token[] tokens; - ParseError[] errors; - var ast = Parser.ParseFile(fileName, out tokens, out errors); - - if (errors is not null && errors.Length > 0) - { - if (errorList is not null && extent is not null) - { - List errorMessages = new List(); - foreach (var error in errors) - { - errorMessages.Add(error.ToString()); - } - - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.FailToParseModuleScriptFile, fileName, string.Join(Environment.NewLine, errorMessages)); - e.SetErrorId("FailToParseModuleScriptFile"); - errorList.Add(e); - } - - return false; - } - - resourceDefinitions = ast.FindAll( - n => - { - var typeAst = n as TypeDefinitionAst; - if (typeAst is not null) - { - for (int i = 0; i < typeAst.Attributes.Count; i++) - { - var a = typeAst.Attributes[i]; - if (a.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) - { - return true; - } - } - } - - return false; - }, - false); - - return true; - } - - private static bool LoadPowerShellClassResourcesFromModule(string fileName, PSModuleInfo module, ICollection resourcesToImport, ICollection resourcesFound, Dictionary functionsToDefine, Collection errorList, IScriptExtent extent) - { - IEnumerable resourceDefinitions; - if (!GetResourceDefinitionsFromModule(fileName, out resourceDefinitions, errorList, extent)) - { - return false; - } - - var result = false; - - const WildcardOptions options = WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant; - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings(module._declaredDscResourceExports, options); - - foreach (var r in resourceDefinitions) - { - result = true; - var resourceDefnAst = (TypeDefinitionAst)r; - - if (!SessionStateUtilities.MatchesAnyWildcardPattern(resourceDefnAst.Name, patternList, true)) - { - continue; - } - - bool skip = true; - foreach (var toImport in resourcesToImport) - { - if (WildcardPattern.Get(toImport, WildcardOptions.IgnoreCase).IsMatch(resourceDefnAst.Name)) - { - skip = false; - break; - } - } - - if (skip) - { - continue; - } - - // Parse the Resource Attribute to see if RunAs behavior is specified for the resource. - DSCResourceRunAsCredential runAsBehavior = DSCResourceRunAsCredential.Default; - foreach (var attr in resourceDefnAst.Attributes) - { - if (attr.TypeName.GetReflectionAttributeType() == typeof(DscResourceAttribute)) - { - foreach (var na in attr.NamedArguments) - { - if (na.ArgumentName.Equals("RunAsCredential", StringComparison.OrdinalIgnoreCase)) - { - var dscResourceAttribute = attr.GetAttribute() as DscResourceAttribute; - if (dscResourceAttribute != null) - { - runAsBehavior = dscResourceAttribute.RunAsCredential; - } - } - } - } - } - - var classes = GenerateJsonClassesForAst(resourceDefnAst, module, runAsBehavior); - - ProcessJsonForDynamicKeywords(module, resourcesFound, functionsToDefine, classes, runAsBehavior, errorList); - } - - return result; - } - - private static readonly Dictionary s_mapPrimitiveDotNetTypeToMof = new Dictionary() - { - { typeof(sbyte), "sint8" }, - { typeof(byte), "uint8" }, - { typeof(short), "sint16" }, - { typeof(ushort), "uint16" }, - { typeof(int), "sint32" }, - { typeof(uint), "uint32" }, - { typeof(long), "sint64" }, - { typeof(ulong), "uint64" }, - { typeof(float), "real32" }, - { typeof(double), "real64" }, - { typeof(bool), "boolean" }, - { typeof(string), "string" }, - { typeof(DateTime), "datetime" }, - { typeof(PSCredential), "string" }, - { typeof(char), "char16" }, - }; - - internal static string MapTypeToMofType(Type type, string memberName, string className, out bool isArrayType, out string embeddedInstanceType, List embeddedInstanceTypes) - { - isArrayType = false; - if (type.IsValueType) - { - type = Nullable.GetUnderlyingType(type) ?? type; - } - - if (type.IsEnum) - { - embeddedInstanceType = null; - return "string"; - } - - if (type == typeof(Hashtable)) - { - // Hashtable is obviously not an array, but in the mof, we represent - // it as string[] (really, embeddedinstance of MSFT_KeyValuePair), but - // we need an array to hold each entry in the hashtable. - isArrayType = true; - embeddedInstanceType = "MSFT_KeyValuePair"; - return "string"; - } - - if (type == typeof(PSCredential)) - { - embeddedInstanceType = "MSFT_Credential"; - return "string"; - } - - if (type.IsArray) - { - isArrayType = true; - bool temp; - var elementType = type.GetElementType(); - if (!elementType.IsArray) - { - return MapTypeToMofType(type.GetElementType(), memberName, className, out temp, out embeddedInstanceType, embeddedInstanceTypes); - } - } - else - { - string cimType; - if (s_mapPrimitiveDotNetTypeToMof.TryGetValue(type, out cimType)) - { - embeddedInstanceType = null; - return cimType; - } - } - - bool supported = false; - bool missingDefaultConstructor = false; - if (type.IsValueType) - { - if (s_mapPrimitiveDotNetTypeToMof.ContainsKey(type)) - { - supported = true; - } - } - else if (!type.IsAbstract) - { - // Must have default constructor, at least 1 public property/field, and no base classes - if (type.GetConstructor(Type.EmptyTypes) is null) - { - missingDefaultConstructor = true; - } - else if (type.BaseType == typeof(object) && - (type.GetProperties(BindingFlags.Instance | BindingFlags.Public).Length > 0 || - type.GetFields(BindingFlags.Instance | BindingFlags.Public).Length > 0)) - { - supported = true; - } - } - - if (supported) - { - if (!embeddedInstanceTypes.Contains(type)) - { - embeddedInstanceTypes.Add(type); - } - - // The type is obviously not a string, but in the mof, we represent - // it as string (really, embeddedinstance of the class type) - embeddedInstanceType = type.FullName.Replace('.', '_'); - return "string"; - } - - if (missingDefaultConstructor) - { - throw new NotSupportedException(string.Format( - CultureInfo.InvariantCulture, - ParserStrings.DscResourceMissingDefaultConstructor, - type.Name)); - } - else - { - throw new NotSupportedException(string.Format( - CultureInfo.InvariantCulture, - ParserStrings.UnsupportedPropertyTypeOfDSCResourceClass, - memberName, - type.Name, - className)); - } - } - - private static void ProcessJsonForDynamicKeywords( - PSModuleInfo module, - ICollection resourcesFound, - Dictionary functionsToDefine, - PSObject[] classes, - DSCResourceRunAsCredential runAsBehavior, - Collection errors) - { - foreach (dynamic c in classes) - { - var className = c.ClassName; - string alias = GetFriendlyName(c); - var friendlyName = string.IsNullOrEmpty(alias) ? className : alias; - if (!CacheResourcesFromMultipleModuleVersions) - { - // Find & remove the previous version of the resource. - List> resourceList = FindResourceInCache(module.Name, className, friendlyName); - - if (resourceList.Count > 0 && !string.IsNullOrEmpty(resourceList[0].Key)) - { - ClassCache.Remove(resourceList[0].Key); - - // keyword is already defined and it is a Inbox resource, remove it - if (DynamicKeyword.ContainsKeyword(friendlyName) && resourceList[0].Value.IsImportedImplicitly) - { - DynamicKeyword.RemoveKeyword(friendlyName); - } - } - } - - var moduleQualifiedResourceName = GetModuleQualifiedResourceName(module.Name, module.Version.ToString(), className, friendlyName); - DscClassCacheEntry existingCacheEntry = null; - if (ClassCache.TryGetValue(moduleQualifiedResourceName, out existingCacheEntry)) - { - if (errors is not null) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.DuplicateCimClassDefinition, className, module.Path, existingCacheEntry.ModulePath); - e.SetErrorId("DuplicateCimClassDefinition"); - errors.Add(e); - } - } - else - { - var classCacheEntry = new DscClassCacheEntry(runAsBehavior, false, c, module.Path); - ClassCache[moduleQualifiedResourceName] = classCacheEntry; - GuestConfigClassCache[moduleQualifiedResourceName] = classCacheEntry; - ByClassModuleCache[className] = new Tuple(module.Name, module.Version); - resourcesFound.Add(className); - CreateAndRegisterKeywordFromCimClass(module.Name, module.Version, c, functionsToDefine, runAsBehavior); - } - } - } - - /// - /// Returns an error record to use in the case of a malformed resource reference in the DependsOn list. - /// - /// The malformed resource. - /// The referencing resource instance. - /// Generated error record. - public static ErrorRecord GetBadlyFormedRequiredResourceIdErrorRecord(string badDependsOnReference, string definingResource) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.GetBadlyFormedRequiredResourceId, badDependsOnReference, definingResource); - e.SetErrorId("GetBadlyFormedRequiredResourceId"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of a malformed resource reference in the exclusive resources list. - /// - /// The malformed resource. - /// The referencing resource instance. - /// Generated error record. - public static ErrorRecord GetBadlyFormedExclusiveResourceIdErrorRecord(string badExclusiveResourcereference, string definingResource) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.GetBadlyFormedExclusiveResourceId, badExclusiveResourcereference, definingResource); - e.SetErrorId("GetBadlyFormedExclusiveResourceId"); - return e.ErrorRecord; - } - - /// - /// If a partial configuration is in 'Pull' Mode, it needs a configuration source. - /// - /// Resource id. - /// Generated error record. - public static ErrorRecord GetPullModeNeedConfigurationSource(string resourceId) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.GetPullModeNeedConfigurationSource, resourceId); - e.SetErrorId("GetPullModeNeedConfigurationSource"); - return e.ErrorRecord; - } - - /// - /// Refresh Mode can not be Disabled for the Partial Configurations. - /// - /// Resource id. - /// Generated error record. - public static ErrorRecord DisabledRefreshModeNotValidForPartialConfig(string resourceId) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.DisabledRefreshModeNotValidForPartialConfig, resourceId); - e.SetErrorId("DisabledRefreshModeNotValidForPartialConfig"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of a malformed resource reference in the DependsOn list. - /// - /// The duplicate resource identifier. - /// The node being defined. - /// The error record to use. - public static ErrorRecord DuplicateResourceIdInNodeStatementErrorRecord(string duplicateResourceId, string nodeName) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.DuplicateResourceIdInNodeStatement, duplicateResourceId, nodeName); - e.SetErrorId("DuplicateResourceIdInNodeStatement"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of a configuration name is invalid. - /// - /// Configuration name. - /// Generated error record. - public static ErrorRecord InvalidConfigurationNameErrorRecord(string configurationName) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.InvalidConfigurationName, configurationName); - e.SetErrorId("InvalidConfigurationName"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of the given value for a property is invalid. - /// - /// Property name. - /// Property value. - /// Keyword name. - /// Valid property values. - /// Generated error record. - public static ErrorRecord InvalidValueForPropertyErrorRecord(string propertyName, string value, string keywordName, string validValues) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.InvalidValueForProperty, value, propertyName, keywordName, validValues); - e.SetErrorId("InvalidValueForProperty"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in case the given property is not valid LocalConfigurationManager property. - /// - /// Property name. - /// Valid properties. - /// Generated error record. - public static ErrorRecord InvalidLocalConfigurationManagerPropertyErrorRecord(string propertyName, string validProperties) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.InvalidLocalConfigurationManagerProperty, propertyName, validProperties); - e.SetErrorId("InvalidLocalConfigurationManagerProperty"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of the given value for a property is not supported. - /// - /// Property name. - /// Property value. - /// Keyword name. - /// Valid property values. - /// Generated error record. - public static ErrorRecord UnsupportedValueForPropertyErrorRecord(string propertyName, string value, string keywordName, string validValues) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.UnsupportedValueForProperty, value, propertyName, keywordName, validValues); - e.SetErrorId("UnsupportedValueForProperty"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of no value is provided for a mandatory property. - /// - /// Keyword name. - /// Type name. - /// Property name. - /// Generated error record. - public static ErrorRecord MissingValueForMandatoryPropertyErrorRecord(string keywordName, string typeName, string propertyName) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.MissingValueForMandatoryProperty, keywordName, typeName, propertyName); - e.SetErrorId("MissingValueForMandatoryProperty"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use in the case of more than one values are provided for DebugMode property. - /// - /// Generated error record. - public static ErrorRecord DebugModeShouldHaveOneValue() - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.DebugModeShouldHaveOneValue); - e.SetErrorId("DebugModeShouldHaveOneValue"); - return e.ErrorRecord; - } - - /// - /// Return an error to indicate a value is out of range for a dynamic keyword property. - /// - /// Rroperty name. - /// Resource name. - /// Provided value. - /// Valid range lower bound. - /// Valid range upper bound. - /// Generated error record. - public static ErrorRecord ValueNotInRangeErrorRecord(string property, string name, int providedValue, int lower, int upper) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.ValueNotInRange, property, name, providedValue, lower, upper); - e.SetErrorId("ValueNotInRange"); - return e.ErrorRecord; - } - - /// - /// Returns an error record to use when composite resource and its resource instances both has PsDscRunAsCredentials value. - /// - /// ResourceId of resource. - /// Generated error record. - public static ErrorRecord PsDscRunAsCredentialMergeErrorForCompositeResources(string resourceId) - { - PSInvalidOperationException e = PSTraceSource.NewInvalidOperationException(ParserStrings.PsDscRunAsCredentialMergeErrorForCompositeResources, resourceId); - e.SetErrorId("PsDscRunAsCredentialMergeErrorForCompositeResources"); - return e.ErrorRecord; - } - - /// - /// Routine to format a usage string from keyword. The resulting string should look like: - /// User [string] #ResourceName - /// { - /// UserName = [string] - /// [ Description = [string] ] - /// [ Disabled = [bool] ] - /// [ Ensure = [string] { Absent | Present } ] - /// [ Force = [bool] ] - /// [ FullName = [string] ] - /// [ Password = [PSCredential] ] - /// [ PasswordChangeNotAllowed = [bool] ] - /// [ PasswordChangeRequired = [bool] ] - /// [ PasswordNeverExpires = [bool] ] - /// [ DependsOn = [string[]] ] - /// } - /// - /// Dynamic keyword. - /// Usage string. - public static string GetDSCResourceUsageString(DynamicKeyword keyword) - { - StringBuilder usageString; - switch (keyword.NameMode) - { - // Name must be present and simple non-empty bare word - case DynamicKeywordNameMode.SimpleNameRequired: - usageString = new StringBuilder(keyword.Keyword + " [string] # Resource Name"); - break; - - // Name must be present but can also be an expression - case DynamicKeywordNameMode.NameRequired: - usageString = new StringBuilder(keyword.Keyword + " [string[]] # Name List"); - break; - - // Name may be optionally present, but if it is present, it must be a non-empty bare word. - case DynamicKeywordNameMode.SimpleOptionalName: - usageString = new StringBuilder(keyword.Keyword + " [ [string] ] # Optional Name"); - break; - - // Name may be optionally present, expression or bare word - case DynamicKeywordNameMode.OptionalName: - usageString = new StringBuilder(keyword.Keyword + " [ [string[]] ] # Optional NameList"); - break; - - // Does not take a name - default: - usageString = new StringBuilder(keyword.Keyword); - break; - } - - usageString.Append("\n{\n"); - - bool listKeyProperties = true; - while (true) - { - foreach (var prop in keyword.Properties.OrderBy(ob => ob.Key)) - { - if (string.Equals(prop.Key, "ResourceId", StringComparison.OrdinalIgnoreCase)) - { - continue; - } - - var propVal = prop.Value; - if ((listKeyProperties && propVal.IsKey) || (!listKeyProperties && !propVal.IsKey)) - { - usageString.Append(propVal.Mandatory ? " " : " [ "); - usageString.Append(prop.Key); - usageString.Append(" = "); - usageString.Append(FormatCimPropertyType(propVal, !propVal.Mandatory)); - } - } - - if (listKeyProperties) - { - listKeyProperties = false; - } - else - { - break; - } - } - - usageString.Append('}'); - - return usageString.ToString(); - } - - /// - /// Format the type name of a CIM property in a presentable way. - /// - /// Dynamic keyword property. - /// If this is optional property or not. - /// CIM property type string. - private static StringBuilder FormatCimPropertyType(DynamicKeywordProperty prop, bool isOptionalProperty) - { - string cimTypeName = prop.TypeConstraint; - StringBuilder formattedTypeString = new StringBuilder(); - - if (string.Equals(cimTypeName, "MSFT_Credential", StringComparison.OrdinalIgnoreCase)) - { - formattedTypeString.Append("[PSCredential]"); - } - else if (string.Equals(cimTypeName, "MSFT_KeyValuePair", StringComparison.OrdinalIgnoreCase) || string.Equals(cimTypeName, "MSFT_KeyValuePair[]", StringComparison.OrdinalIgnoreCase)) - { - formattedTypeString.Append("[Hashtable]"); - } - else - { - string convertedTypeString = System.Management.Automation.LanguagePrimitives.ConvertTypeNameToPSTypeName(cimTypeName); - if (!string.IsNullOrEmpty(convertedTypeString) && !string.Equals(convertedTypeString, "[]", StringComparison.OrdinalIgnoreCase)) - { - formattedTypeString.Append(convertedTypeString); - } - else - { - formattedTypeString.Append("[" + cimTypeName + "]"); - } - } - - // Do the property values map - if (prop.ValueMap is not null && prop.ValueMap.Count > 0) - { - formattedTypeString.Append(" { " + string.Join(" | ", prop.ValueMap.Keys.OrderBy(x => x)) + " }"); - } - - // We prepend optional property with "[" so close out it here. This way it is shown with [ ] to indication optional - if (isOptionalProperty) - { - formattedTypeString.Append(']'); - } - - formattedTypeString.Append('\n'); - - return formattedTypeString; - } - - /// - /// Gets the scriptblock that implements the CIM keyword functionality. - /// - private static ScriptBlock CimKeywordImplementationFunction - { - get - { - // The scriptblock cache will handle mutual exclusion - return s_cimKeywordImplementationFunction ??= ScriptBlock.Create(CimKeywordImplementationFunctionText); - } - } - - private static ScriptBlock s_cimKeywordImplementationFunction; - - private const string CimKeywordImplementationFunctionText = @" - param ( - [Parameter(Mandatory)] - $KeywordData, - [Parameter(Mandatory)] - $Name, - [Parameter(Mandatory)] - [Hashtable] - $Value, - [Parameter(Mandatory)] - $SourceMetadata - ) - -# walk the call stack to get at all of the enclosing configuration resource IDs - $stackedConfigs = @(Get-PSCallStack | - where { ($null -ne $_.InvocationInfo.MyCommand) -and ($_.InvocationInfo.MyCommand.CommandType -eq 'Configuration') }) -# keep all but the top-most - $stackedConfigs = $stackedConfigs[0..(@($stackedConfigs).Length - 2)] -# and build the complex resource ID suffix. - $complexResourceQualifier = ( $stackedConfigs | ForEach-Object { '[' + $_.Command + ']' + $_.InvocationInfo.BoundParameters['InstanceName'] } ) -join '::' - -# -# Utility function used to validate that the DependsOn arguments are well-formed. -# The function also adds them to the define nodes resource collection. -# in the case of resources generated inside a script resource, this routine -# will also fix up the DependsOn references to '[Type]Instance::[OuterType]::OuterInstance -# - function Test-DependsOn - { - -# make sure the references are well-formed - $updatedDependsOn = foreach ($DependsOnVar in $value['DependsOn']) { -# match [ResourceType]ResourceName. ResourceName should starts with [a-z_0-9] followed by [a-z_0-9\p{Zs}\.\\-]* - if ($DependsOnVar -notmatch '^\[[a-z]\w*\][a-z_0-9][a-z_0-9\p{Zs}\.\\-]*$') - { - Update-ConfigurationErrorCount - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::GetBadlyFormedRequiredResourceIdErrorRecord($DependsOnVar, $resourceId)) - } - -# Fix up DependsOn for nested names - if ($MyTypeName -and $typeName -ne $MyTypeName -and $InstanceName) - { - ""$DependsOnVar::$complexResourceQualifier"" - } - else - { - $DependsOnVar - } - } - - $value['DependsOn']= $updatedDependsOn - - if($null -ne $DependsOn) - { -# -# Combine DependsOn with dependson from outer composite resource -# which is set as local variable $DependsOn at the composite resource context -# - $value['DependsOn']= @($value['DependsOn']) + $DependsOn - } - -# Save the resource id in a per-node dictionary to do cross validation at the end - Set-NodeResources $resourceId @( $value['DependsOn']) - -# Remove depends on because it need to be fixed up for composite resources -# We do it in ValidateNodeResource and Update-Depends on in configuration/Node function - $value.Remove('DependsOn') - } - -# A copy of the value object with correctly-cased property names - $canonicalizedValue = @{} - - $typeName = $keywordData.ResourceName # CIM type - $keywordName = $keywordData.Keyword # user-friendly alias that is used in scripts - $keyValues = '' - $debugPrefix = "" ${TypeName}:"" # set up a debug prefix string that makes it easier to track what's happening. - - Write-Debug ""${debugPrefix} RESOURCE PROCESSING STARTED [KeywordName='$keywordName'] Function='$($myinvocation.Invocationname)']"" - -# Check whether it's an old style metaconfig - $OldMetaConfig = $false - if ((-not $IsMetaConfig) -and ($keywordName -ieq 'LocalConfigurationManager')) { - $OldMetaConfig = $true - } - -# Check to see if it's a resource keyword. If so add the meta-properties to the canonical property collection. - $resourceId = $null -# todo: need to include configuration managers and partial configuration - if (($keywordData.Properties.Keys -contains 'DependsOn') -or (($KeywordData.ImplementingModule -ieq 'PSDesiredStateConfigurationEngine') -and ($KeywordData.NameMode -eq [System.Management.Automation.Language.DynamicKeywordNameMode]::NameRequired))) - { - - $resourceId = ""[$keywordName]$name"" - if ($MyTypeName -and $keywordName -ne $MyTypeName -and $InstanceName) - { - $resourceId += ""::$complexResourceQualifier"" - } - - Write-Debug ""${debugPrefix} ResourceID = $resourceId"" - -# copy the meta-properties - $canonicalizedValue['ResourceID'] = $resourceId - $canonicalizedValue['SourceInfo'] = $SourceMetadata - if(-not $IsMetaConfig) - { - $canonicalizedValue['ModuleName'] = $keywordData.ImplementingModule - $canonicalizedValue['ModuleVersion'] = $keywordData.ImplementingModuleVersion -as [string] - } - -# see if there is already a resource with this ID. - if (Test-NodeResources $resourceId) - { - Update-ConfigurationErrorCount - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::DuplicateResourceIdInNodeStatementErrorRecord($resourceId, (Get-PSCurrentConfigurationNode))) - } - else - { -# If there are prerequisite resources, validate that the references are well-formed strings -# This routine also adds the resource to the global node resources table. - Test-DependsOn - -# Check if PsDscRunCredential is being specified as Arguments to Configuration - if($null -ne $PsDscRunAsCredential) - { -# Check if resource is also trying to set the value for RunAsCred -# In that case we will generate error during compilation, this is merge error - if($null -ne $value['PsDscRunAsCredential']) - { - Update-ConfigurationErrorCount - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::PsDscRunAsCredentialMergeErrorForCompositeResources($resourceId)) - } -# Set the Value of RunAsCred to that of outer configuration - else - { - $value['PsDscRunAsCredential'] = $PsDscRunAsCredential - } - } - -# Save the resource id in a per-node dictionary to do cross validation at the end - if($keywordData.ImplementingModule -ieq ""PSDesiredStateConfigurationEngine"") - { -#$keywordName is PartialConfiguration - if($keywordName -eq 'PartialConfiguration') - { -# RefreshMode is 'Pull' and .ConfigurationSource is empty - if($value['RefreshMode'] -eq 'Pull' -and -not $value['ConfigurationSource']) - { - Update-ConfigurationErrorCount - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::GetPullModeNeedConfigurationSource($resourceId)) - } - -# Verify that RefreshMode is not Disabled for Partial configuration - if($value['RefreshMode'] -eq 'Disabled') - { - Update-ConfigurationErrorCount - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::DisabledRefreshModeNotValidForPartialConfig($resourceId)) - } - - if($null -ne $value['ConfigurationSource']) - { - Set-NodeManager $resourceId $value['ConfigurationSource'] - } - - if($null -ne $value['ResourceModuleSource']) - { - Set-NodeResourceSource $resourceId $value['ResourceModuleSource'] - } - } - - if($null -ne $value['ExclusiveResources']) - { -# make sure the references are well-formed - foreach ($ExclusiveResource in $value['ExclusiveResources']) { - if (($ExclusiveResource -notmatch '^[a-z][a-z_0-9]*\\[a-z][a-z_0-9]*$') -and ($ExclusiveResource -notmatch '^[a-z][a-z_0-9]*$') -and ($ExclusiveResource -notmatch '^[a-z][a-z_0-9]*\\\*$')) - { - Update-ConfigurationErrorCount - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::GetBadlyFormedExclusiveResourceIdErrorRecord($ExclusiveResource, $resourceId)) - } - } - -# Save the resource id in a per-node dictionary to do cross validation at the end -# Validate resource exist -# Also update the resource reference from module\friendlyname to module\name - $value['ExclusiveResources'] = @(Set-NodeExclusiveResources $resourceId @( $value['ExclusiveResources'] )) - } - } - } - } - else - { - Write-Debug ""${debugPrefix} TYPE IS NOT AS DSC RESOURCE"" - } - -# -# Copy the user-supplied values into a new collection with canonicalized property names -# - foreach ($key in $keywordData.Properties.Keys) - { - Write-Debug ""${debugPrefix} Processing property '$key' ["" - - if ($value.Contains($key)) - { - if ($OldMetaConfig -and (-not ($V1MetaConfigPropertyList -contains $key))) - { - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::InvalidLocalConfigurationManagerPropertyErrorRecord($key, ($V1MetaConfigPropertyList -join ', '))) - Update-ConfigurationErrorCount - } -# see if there is a list of allowed values for this property (similar to an enum) - $allowedValues = $keywordData.Properties[$key].Values -# If there is and user-provided value is not in that list, write an error. - if ($allowedValues) - { - if(($null -eq $value[$key]) -and ($allowedValues -notcontains $value[$key])) - { - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::InvalidValueForPropertyErrorRecord($key, ""$($value[$key])"", $keywordData.Keyword, ($allowedValues -join ', '))) - Update-ConfigurationErrorCount - } - else - { - $notAllowedValue=$null - foreach($v in $value[$key]) - { - if($allowedValues -notcontains $v) - { - $notAllowedValue +=$v.ToString() + ', ' - } - } - - if($notAllowedValue) - { - $notAllowedValue = $notAllowedValue.Substring(0, $notAllowedValue.Length -2) - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::UnsupportedValueForPropertyErrorRecord($key, $notAllowedValue, $keywordData.Keyword, ($allowedValues -join ', '))) - Update-ConfigurationErrorCount - } - } - } - -# see if a value range is defined for this property - $allowedRange = $keywordData.Properties[$key].Range - if($allowedRange) - { - $castedValue = $value[$key] -as [int] - if((($castedValue -is [int]) -and (($castedValue -lt $keywordData.Properties[$key].Range.Item1) -or ($castedValue -gt $keywordData.Properties[$key].Range.Item2))) -or ($null -eq $castedValue)) - { - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::ValueNotInRangeErrorRecord($key, $keywordName, $value[$key], $keywordData.Properties[$key].Range.Item1, $keywordData.Properties[$key].Range.Item2)) - Update-ConfigurationErrorCount - } - } - - Write-Debug ""${debugPrefix} Canonicalized property '$key' = '$($value[$key])'"" - - if ($keywordData.Properties[$key].IsKey) - { - if($null -eq $value[$key]) - { - $keyValues += ""::__NULL__"" - } - else - { - $keyValues += ""::"" + $value[$key] - } - } - -# see if ValueMap is also defined for this property (actual values) - $allowedValueMap = $keywordData.Properties[$key].ValueMap -#if it is and the ValueMap contains the user-provided value as a key, use the actual value - if ($allowedValueMap -and $allowedValueMap.ContainsKey($value[$key])) - { - $canonicalizedValue[$key] = $allowedValueMap[$value[$key]] - } - else - { - $canonicalizedValue[$key] = $value[$key] - } - } - elseif ($keywordData.Properties[$key].Mandatory) - { -# If the property was mandatory but the user didn't provide a value, write and error. - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::MissingValueForMandatoryPropertyErrorRecord($keywordData.Keyword, $keywordData.Properties[$key].TypeConstraint, $Key)) - Update-ConfigurationErrorCount - } - - Write-Debug ""${debugPrefix} Processing completed '$key' ]"" - } - - if($keyValues) - { - $keyValues = $keyValues.Substring(2) # Remove the leading '::' - Add-NodeKeys $keyValues $keywordName - Test-ConflictingResources $keywordName $canonicalizedValue $keywordData - } - -# update OMI_ConfigurationDocument - if($IsMetaConfig) - { - if($keywordData.ResourceName -eq 'OMI_ConfigurationDocument') - { - if($(Get-PSMetaConfigurationProcessed)) - { - $PSMetaConfigDocumentInstVersionInfo = Get-PSMetaConfigDocumentInstVersionInfo - $canonicalizedValue['MinimumCompatibleVersion']=$PSMetaConfigDocumentInstVersionInfo['MinimumCompatibleVersion'] - } - else - { - Set-PSMetaConfigDocInsProcessedBeforeMeta - $canonicalizedValue['MinimumCompatibleVersion']='1.0.0' - } - } - - if(($keywordData.ResourceName -eq 'MSFT_WebDownloadManager') ` - -or ($keywordData.ResourceName -eq 'MSFT_FileDownloadManager') ` - -or ($keywordData.ResourceName -eq 'MSFT_WebResourceManager') ` - -or ($keywordData.ResourceName -eq 'MSFT_FileResourceManager') ` - -or ($keywordData.ResourceName -eq 'MSFT_WebReportManager') ` - -or ($keywordData.ResourceName -eq 'MSFT_SignatureValidation') ` - -or ($keywordData.ResourceName -eq 'MSFT_PartialConfiguration')) - { - Set-PSMetaConfigVersionInfoV2 - } - } - elseif($keywordData.ResourceName -eq 'OMI_ConfigurationDocument') - { - $canonicalizedValue['MinimumCompatibleVersion']='1.0.0' - $canonicalizedValue['CompatibleVersionAdditionalProperties']=@('Omi_BaseResource:ConfigurationName') - } - - if(($keywordData.ResourceName -eq 'MSFT_DSCMetaConfiguration') -or ($keywordData.ResourceName -eq 'MSFT_DSCMetaConfigurationV2')) - { - if($canonicalizedValue['DebugMode'] -and @($canonicalizedValue['DebugMode']).Length -gt 1) - { -# we only allow one value for debug mode now. - Write-Error -ErrorRecord ([Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache]::DebugModeShouldHaveOneValue()) - Update-ConfigurationErrorCount - } - } - -# Generate the MOF text for this resource instance. -# when generate mof text for OMI_ConfigurationDocument we handle below two cases: -# 1. we will add versioning related property based on meta configuration instance already process -# 2. we update the existing OMI_ConfigurationDocument instance if it already exists when process meta configuration instance - $aliasId = ConvertTo-MOFInstance $keywordName $canonicalizedValue - -# If a OMI_ConfigurationDocument is executed outside of a node statement, it becomes the default -# for all nodes that don't have an explicit OMI_ConfigurationDocument declaration - if ($keywordData.ResourceName -eq 'OMI_ConfigurationDocument' -and -not (Get-PSCurrentConfigurationNode)) - { - $data = Get-MoFInstanceText $aliasId - Write-Debug ""${debugPrefix} DEFINING DEFAULT CONFIGURATION DOCUMENT: $data"" - Set-PSDefaultConfigurationDocument $data - } - - Write-Debug ""${debugPrefix} MOF alias for this resource is '$aliasId'"" - -# always return the aliasId so the generated file will be well-formed if not valid - $aliasId - - Write-Debug ""${debugPrefix} RESOURCE PROCESSING COMPLETED. TOTAL ERROR COUNT: $(Get-ConfigurationErrorCount)"" - - "; - } -} diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs index 374cadf31d8..4c8d23971af 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/FileSystem_format_ps1xml.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections.Generic; +using System.Globalization; namespace System.Management.Automation.Runspaces { @@ -42,27 +43,27 @@ internal static IEnumerable GetFormatData() private static IEnumerable ViewsOf_FileSystemTypes(CustomControl[] sharedControls) { #if UNIX - if (ExperimentalFeature.IsEnabled("PSUnixFileStat")) - { - yield return new FormatViewDefinition("childrenWithUnixStat", - TableControl.Create() - .GroupByProperty("PSParentPath", customControl: sharedControls[0]) - .AddHeader(Alignment.Left, label: "UnixMode", width: 10) - .AddHeader(Alignment.Left, label: "User", width: 16) - .AddHeader(Alignment.Left, label: "Group", width: 16) - .AddHeader(Alignment.Right, label: "LastWriteTime", width: 18) - .AddHeader(Alignment.Right, label: "Size", width: 14) - .AddHeader(Alignment.Left, label: "Name") - .StartRowDefinition(wrap: true) - .AddPropertyColumn("UnixMode") - .AddPropertyColumn("User") - .AddPropertyColumn("Group") - .AddScriptBlockColumn(scriptBlock: @"'{0:d} {0:HH}:{0:mm}' -f $_.LastWriteTime") - .AddPropertyColumn("Size") - .AddPropertyColumn("NameString") - .EndRowDefinition() - .EndTable()); - } + yield return new FormatViewDefinition("childrenWithUnixStat", + TableControl.Create() + .GroupByProperty("PSParentPath", customControl: sharedControls[0]) + .AddHeader(Alignment.Left, label: "UnixMode", width: 10) + .AddHeader(Alignment.Right, label: "User", width: 10) + .AddHeader(Alignment.Left, label: "Group", width: 10) + .AddHeader( + Alignment.Right, + label: "LastWriteTime", + width: String.Format(CultureInfo.CurrentCulture, "{0:d} {0:HH}:{0:mm}", CultureInfo.CurrentCulture.Calendar.MaxSupportedDateTime).Length) + .AddHeader(Alignment.Right, label: "Size", width: 12) + .AddHeader(Alignment.Left, label: "Name") + .StartRowDefinition(wrap: true) + .AddPropertyColumn("UnixMode") + .AddPropertyColumn("User") + .AddPropertyColumn("Group") + .AddScriptBlockColumn(scriptBlock: @"'{0:d} {0:HH}:{0:mm}' -f $_.LastWriteTime") + .AddPropertyColumn("Size") + .AddPropertyColumn("NameString") + .EndRowDefinition() + .EndTable()); #endif yield return new FormatViewDefinition("children", diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs index d04ea1bdedf..fc5ddc5ab9a 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/HelpV3_format_ps1xml.cs @@ -175,7 +175,7 @@ internal static IEnumerable GetFormatData() .EndControl(); var sharedControls = new CustomControl[] { - null,//MamlParameterValueGroupControl, + null, //MamlParameterValueGroupControl, MamlParameterControl, MamlTypeControl, MamlParameterValueControl, diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs index d18de013397..6825ec14e6c 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/Help_format_ps1xml.cs @@ -350,7 +350,7 @@ internal static IEnumerable GetFormatData() .AddNewline() .AddText(HelpDisplayStrings.ParameterPosition) .AddScriptBlockExpressionBinding(@" ", selectedByScript: @"($_.position -eq $()) -or ($_.position -eq '')", customControl: control7) - .AddScriptBlockExpressionBinding(@"$_.position", selectedByScript: "$_.position -ne $()") + .AddScriptBlockExpressionBinding(@"$_.position", selectedByScript: "$_.position -ne $()") .AddNewline() .AddText(HelpDisplayStrings.ParameterDefaultValue) .AddPropertyExpressionBinding(@"defaultValue") @@ -358,6 +358,9 @@ internal static IEnumerable GetFormatData() .AddText(HelpDisplayStrings.AcceptsPipelineInput) .AddPropertyExpressionBinding(@"pipelineInput") .AddNewline() + .AddText(HelpDisplayStrings.ParameterAliases) + .AddPropertyExpressionBinding(@"aliases") + .AddNewline() .AddText(HelpDisplayStrings.AcceptsWildCardCharacters) .AddPropertyExpressionBinding(@"globbing", customControl: MamlTrueFalseShortControl) .AddNewline() @@ -677,10 +680,7 @@ private static IEnumerable ViewsOf_MamlCommandHelpInfo_Ful .StartFrame(leftIndent: 4) .AddPropertyExpressionBinding(@"title") .AddNewline() - .AddNewline() - .StartFrame(leftIndent: 4) - .AddPropertyExpressionBinding(@"alert", enumerateCollection: true, customControl: sharedControls[11]) - .EndFrame() + .AddPropertyExpressionBinding(@"alert", enumerateCollection: true, customControl: sharedControls[11]) .AddNewline() .EndFrame() .EndEntry() diff --git a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs index b29fe0bb5de..24d99d4dd4b 100644 --- a/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs +++ b/src/System.Management.Automation/FormatAndOutput/DefaultFormatters/PowerShellCore_format_ps1xml.cs @@ -137,6 +137,10 @@ internal static IEnumerable GetFormatData() "System.Management.Automation.Subsystem.SubsystemInfo", ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo()); + yield return new ExtendedTypeDefinition( + "System.Management.Automation.Subsystem.SubsystemInfo+ImplementationInfo", + ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo_ImplementationInfo()); + yield return new ExtendedTypeDefinition( "System.Management.Automation.ShellVariable", ViewsOf_System_Management_Automation_ShellVariable()); @@ -248,6 +252,10 @@ internal static IEnumerable GetFormatData() "Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo", ViewsOf_Microsoft_PowerShell_MarkdownRender_MarkdownOptionInfo()); + yield return new ExtendedTypeDefinition( + "Microsoft.PowerShell.Commands.TestConnectionCommand+TcpPortStatus", + ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_TcpPortStatus()); + yield return new ExtendedTypeDefinition( "Microsoft.PowerShell.Commands.TestConnectionCommand+PingStatus", ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_PingStatus()); @@ -276,6 +284,10 @@ internal static IEnumerable GetFormatData() "System.Management.Automation.PSStyle+ProgressConfiguration", ViewsOf_System_Management_Automation_PSStyleProgressConfiguration()); + yield return new ExtendedTypeDefinition( + "System.Management.Automation.PSStyle+FileInfoFormatting", + ViewsOf_System_Management_Automation_PSStyleFileInfoFormat()); + yield return new ExtendedTypeDefinition( "System.Management.Automation.PSStyle+ForegroundColor", ViewsOf_System_Management_Automation_PSStyleForegroundColor()); @@ -770,6 +782,21 @@ private static IEnumerable ViewsOf_System_Management_Autom .EndTable()); } + private static IEnumerable ViewsOf_System_Management_Automation_Subsystem_SubsystemInfo_ImplementationInfo() + { + yield return new FormatViewDefinition( + "System.Management.Automation.Subsystem.SubsystemInfo+ImplementationInfo", + ListControl.Create() + .StartEntry() + .AddItemProperty(@"Id") + .AddItemProperty(@"Kind") + .AddItemProperty(@"Name") + .AddItemProperty(@"Description") + .AddItemProperty(@"ImplementationType") + .EndEntry() + .EndList()); + } + private static IEnumerable ViewsOf_System_Management_Automation_ShellVariable() { yield return new FormatViewDefinition("ShellVariable", @@ -806,29 +833,19 @@ private static IEnumerable ViewsOf_System_Management_Autom $maxDepth = 10 $ellipsis = ""`u{2026}"" $resetColor = '' - if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - $resetColor = [System.Management.Automation.VTUtility]::GetEscapeSequence( - [System.Management.Automation.VTUtility+VT]::Reset - ) - } - - function Get-VT100Color([ConsoleColor] $color) { - if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - return '' - } + $errorColor = '' + $accentColor = '' - return [System.Management.Automation.VTUtility]::GetEscapeSequence($color) + if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { + $resetColor = $PSStyle.Reset + $errorColor = $psstyle.Formatting.Error + $accentColor = $PSStyle.Formatting.FormatAccent } function Show-ErrorRecord($obj, [int]$indent = 0, [int]$depth = 1) { $newline = [Environment]::Newline $output = [System.Text.StringBuilder]::new() $prefix = ' ' * $indent - $accentColor = '' - - if ($null -ne $Host.PrivateData) { - $accentColor = Get-VT100Color ($Host.PrivateData.FormatAccentColor ?? $Host.PrivateData.ErrorForegroundColor) - } $expandTypes = @( 'Microsoft.Rest.HttpRequestMessageWrapper' @@ -901,9 +918,9 @@ private static IEnumerable ViewsOf_System_Management_Autom $null = $output.Append($prop.Value) } # Dictionary and Hashtable we want to show as Key/Value pairs, we don't do the extra whitespace alignment here - elseif ($prop.Value.GetType().Name.StartsWith('Dictionary') -or $prop.Value.GetType().Name -eq 'Hashtable') { + elseif ($prop.Value -is [System.Collections.IDictionary]) { $isFirstElement = $true - foreach ($key in $prop.Value.Keys) { + foreach ($key in ($prop.Value.Keys | Sort-Object)) { if ($isFirstElement) { $null = $output.Append($newline) } @@ -929,20 +946,42 @@ private static IEnumerable ViewsOf_System_Management_Autom $isFirstElement = $true foreach ($value in $prop.Value) { $null = $output.Append($newline) - if (!$isFirstElement) { - $null = $output.Append($newline) + $valueIndent = ' ' * ($newIndent + 2) + + if ($value -is [Type]) { + # Just show the typename instead of it as an object + $null = $output.Append(""${prefix}${valueIndent}[$($value.ToString())]"") + } + elseif ($value -is [string] -or $value.GetType().IsPrimitive) { + $null = $output.Append(""${prefix}${valueIndent}${value}"") + } + else { + if (!$isFirstElement) { + $null = $output.Append($newline) + } + $null = $output.Append((Show-ErrorRecord $value $newIndent ($depth + 1))) } - $null = $output.Append((Show-ErrorRecord $value $newIndent ($depth + 1))) $isFirstElement = $false } } } + elseif ($prop.Value -is [Type]) { + # Just show the typename instead of it as an object + $null = $output.Append(""[$($prop.Value.ToString())]"") + } # Anything else, we convert to string. # ToString() can throw so we use LanguagePrimitives.TryConvertTo() to hide a convert error else { $value = $null if ([System.Management.Automation.LanguagePrimitives]::TryConvertTo($prop.Value, [string], [ref]$value) -and $value -ne $null) { + if ($prop.Name -eq 'PositionMessage') { + $value = $value.Insert($value.IndexOf('~'), $errorColor) + } + elseif ($prop.Name -eq 'Message') { + $value = $errorColor + $value + } + $isFirstLine = $true if ($value.Contains($newline)) { # the 3 is to account for ' : ' @@ -995,12 +1034,18 @@ private static IEnumerable ViewsOf_System_Management_Autom yield return new FormatViewDefinition("ErrorInstance", CustomControl.Create(outOfBand: true) .StartEntry() - .AddScriptBlockExpressionBinding(@" - if (@('NativeCommandErrorMessage','NativeCommandError') -notcontains $_.FullyQualifiedErrorId -and @('CategoryView','ConciseView') -notcontains $ErrorView) + .AddScriptBlockExpressionBinding( + """ + $errorColor = '' + $commandPrefix = '' + if (@('NativeCommandErrorMessage','NativeCommandError') -notcontains $_.FullyQualifiedErrorId -and @('CategoryView','ConciseView','DetailedView') -notcontains $ErrorView) { $myinv = $_.InvocationInfo - if ($myinv -and $myinv.MyCommand) - { + if ($Host.UI.SupportsVirtualTerminal) { + $errorColor = $PSStyle.Formatting.Error + } + + $commandPrefix = if ($myinv -and $myinv.MyCommand) { switch -regex ( $myinv.MyCommand.CommandType ) { ([System.Management.Automation.CommandTypes]::ExternalScript) @@ -1045,41 +1090,27 @@ private static IEnumerable ViewsOf_System_Management_Autom $myinv.InvocationName + ' : ' } } - ") - .AddScriptBlockExpressionBinding(@" + + $errorColor + $commandPrefix + """) + .AddScriptBlockExpressionBinding( + """ Set-StrictMode -Off + $ErrorActionPreference = 'Stop' + trap { 'Error found in error view definition: ' + $_.Exception.Message } $newline = [Environment]::Newline - function Get-ConciseViewPositionMessage { - - $resetColor = '' - if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - $resetColor = [System.Management.Automation.VTUtility]::GetEscapeSequence( - [System.Management.Automation.VTUtility+VT]::Reset - ) - } - - function Get-VT100Color([ConsoleColor] $color) { - if (!$Host.UI.SupportsVirtualTerminal -or !([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { - return '' - } - - return [System.Management.Automation.VTUtility]::GetEscapeSequence($color) - } - - # return length of string sans VT100 codes - function Get-RawStringLength($string) { - $vtCodes = ""`e[0m"", ""`e[2;30m"", ""`e[2;31m"", ""`e[2;32m"", ""`e[2;33m"", ""`e[2;34m"", - ""`e[2;35m"", ""`e[2;36m"", ""`e[2;37m"", ""`e[1;30m"", ""`e[1;31m"", ""`e[1;32m"", - ""`e[1;33m"", ""`e[1;34m"", ""`e[1;35m"", ""`e[1;36m"", ""`e[1;37m"" + $resetColor = '' + $errorColor = '' + $accentColor = '' - $newString = $string - foreach ($vtCode in $vtCodes) { - $newString = $newString.Replace($vtCode, '') - } + if ($Host.UI.SupportsVirtualTerminal -and ([string]::IsNullOrEmpty($env:__SuppressAnsiEscapeSequences))) { + $resetColor = $PSStyle.Reset + $errorColor = $PSStyle.Formatting.Error + $accentColor = $PSStyle.Formatting.ErrorAccent + } - return $newString.Length - } + function Get-ConciseViewPositionMessage { # returns a string cut to last whitespace function Get-TruncatedString($string, [int]$length) { @@ -1091,45 +1122,53 @@ function Get-ConciseViewPositionMessage { return ($string.Substring(0,$length) -split '\s',-2)[0] } - $errorColor = '' - $accentColor = '' - - if ($null -ne $Host.PrivateData) { - $errorColor = Get-VT100Color $Host.PrivateData.ErrorForegroundColor - $accentColor = Get-VT100Color ($Host.PrivateData.ErrorAccentColor ?? $errorColor) - } - $posmsg = '' $headerWhitespace = '' $offsetWhitespace = '' $message = '' $prefix = '' - # Don't show line information if script module - if (($myinv -and $myinv.ScriptName -or $myinv.ScriptLineNumber -gt 1 -or $err.CategoryInfo.Category -eq 'ParserError') -and !($myinv.ScriptName.EndsWith('.psm1', [System.StringComparison]::OrdinalIgnoreCase))) { - $useTargetObject = $false + # Handle case where there is a TargetObject from a Pester `Should` assertion failure and we can show the error at the target rather than the script source + # Note that in some versions, this is a Dictionary<,> and in others it's a hashtable. So we explicitly cast to a shared interface in the method invocation + # to force using `IDictionary.Contains`. Hashtable does have it's own `ContainKeys` as well, but if they ever opt to use a custom `IDictionary`, that may not. + $useTargetObject = $null -ne $err.TargetObject -and + $err.TargetObject -is [System.Collections.IDictionary] -and + ([System.Collections.IDictionary]$err.TargetObject).Contains('Line') -and + ([System.Collections.IDictionary]$err.TargetObject).Contains('LineText') + + # The checks here determine if we show line detailed error information: + # - check if `ParserError` and comes from PowerShell which eventually results in a ParseException, but during this execution it's an ErrorRecord + $isParseError = $err.CategoryInfo.Category -eq 'ParserError' -and + $err.Exception -is [System.Management.Automation.ParentContainsErrorRecordException] + + # - check if invocation is a script or multiple lines in the console + $isMultiLineOrExternal = $myinv.ScriptName -or $myinv.ScriptLineNumber -gt 1 + + # - check that it's not a script module as expectation is that users don't want to see the line of error within a module + $shouldShowLineDetail = ($isParseError -or $isMultiLineOrExternal) -and + $myinv.ScriptName -notmatch '\.psm1$' + + if ($useTargetObject -or $shouldShowLineDetail) { - # Handle case where there is a TargetObject and we can show the error at the target rather than the script source - if ($_.TargetObject.Line -and $_.TargetObject.LineText) { - $posmsg = ""${resetcolor}$($_.TargetObject.File)${newline}"" - $useTargetObject = $true + if ($useTargetObject) { + $posmsg = "${resetcolor}$($err.TargetObject.File)${newline}" } elseif ($myinv.ScriptName) { if ($env:TERM_PROGRAM -eq 'vscode') { # If we are running in vscode, we know the file:line:col links are clickable so we use this format - $posmsg = ""${resetcolor}$($myinv.ScriptName):$($myinv.ScriptLineNumber):$($myinv.OffsetInLine)${newline}"" + $posmsg = "${resetcolor}$($myinv.ScriptName):$($myinv.ScriptLineNumber):$($myinv.OffsetInLine)${newline}" } else { - $posmsg = ""${resetcolor}$($myinv.ScriptName):$($myinv.ScriptLineNumber)${newline}"" + $posmsg = "${resetcolor}$($myinv.ScriptName):$($myinv.ScriptLineNumber)${newline}" } } else { - $posmsg = ""${newline}"" + $posmsg = "${newline}" } if ($useTargetObject) { - $scriptLineNumber = $_.TargetObject.Line - $scriptLineNumberLength = $_.TargetObject.Line.ToString().Length + $scriptLineNumber = $err.TargetObject.Line + $scriptLineNumberLength = $err.TargetObject.Line.ToString().Length } else { $scriptLineNumber = $myinv.ScriptLineNumber @@ -1146,13 +1185,42 @@ function Get-ConciseViewPositionMessage { } $verticalBar = '|' - $posmsg += ""${accentColor}${headerWhitespace}Line ${verticalBar}${newline}"" + $posmsg += "${accentColor}${headerWhitespace}Line ${verticalBar}${newline}" $highlightLine = '' if ($useTargetObject) { $line = $_.TargetObject.LineText.Trim() + $offsetLength = 0 $offsetInLine = 0 + $startColumn = 0 + if ( + ([System.Collections.IDictionary]$_.TargetObject).Contains('StartColumn') -and + [System.Management.Automation.LanguagePrimitives]::TryConvertTo[int]($_.TargetObject.StartColumn, [ref]$startColumn) -and + $null -ne $startColumn -and + $startColumn -gt 0 -and + $startColumn -le $line.Length + ) { + $endColumn = 0 + if (-not ( + ([System.Collections.IDictionary]$_.TargetObject).Contains('EndColumn') -and + [System.Management.Automation.LanguagePrimitives]::TryConvertTo[int]($_.TargetObject.EndColumn, [ref]$endColumn) -and + $null -ne $endColumn -and + $endColumn -gt $startColumn -and + $endColumn -le ($line.Length + 1) + )) { + $endColumn = $line.Length + 1 + } + + # Input is expected to be 1-based index to match the extent positioning + # but we use 0-based indexing below. + $startColumn -= 1 + $endColumn -= 1 + + $highlightLine = "$(" " * $startColumn)$("~" * ($endColumn - $startColumn))" + $offsetLength = $endColumn - $startColumn + $offsetInLine = $startColumn + } } else { $positionMessage = $myinv.PositionMessage.Split($newline) @@ -1171,19 +1239,19 @@ function Get-ConciseViewPositionMessage { $line = $line.Insert($offsetInLine + $offsetLength, $resetColor).Insert($offsetInLine, $accentColor) } - $posmsg += ""${accentColor}${lineWhitespace}${ScriptLineNumber} ${verticalBar} ${resetcolor}${line}"" + $posmsg += "${accentColor}${lineWhitespace}${ScriptLineNumber} ${verticalBar} ${resetcolor}${line}" $offsetWhitespace = ' ' * $offsetInLine - $prefix = ""${accentColor}${headerWhitespace} ${verticalBar} ${errorColor}"" + $prefix = "${accentColor}${headerWhitespace} ${verticalBar} ${errorColor}" if ($highlightLine -ne '') { - $posMsg += ""${prefix}${highlightLine}${newline}"" + $posMsg += "${prefix}${highlightLine}${newline}" } - $message = ""${prefix}"" + $message = "${prefix}" } if (! $err.ErrorDetails -or ! $err.ErrorDetails.Message) { - if ($err.CategoryInfo.Category -eq 'ParserError' -and $err.Exception.Message.Contains(""~$newline"")) { + if ($err.CategoryInfo.Category -eq 'ParserError' -and $err.Exception.Message.Contains("~$newline")) { # need to parse out the relevant part of the pre-rendered positionmessage - $message += $err.Exception.Message.split(""~$newline"")[1].split(""${newline}${newline}"")[0] + $message += $err.Exception.Message.split("~$newline")[1].split("${newline}${newline}")[0] } elseif ($err.Exception) { $message += $err.Exception.Message @@ -1201,11 +1269,11 @@ function Get-ConciseViewPositionMessage { # if rendering line information, break up the message if it's wider than the console if ($myinv -and $myinv.ScriptName -or $err.CategoryInfo.Category -eq 'ParserError') { - $prefixLength = Get-RawStringLength -string $prefix + $prefixLength = [System.Management.Automation.Internal.StringDecorated]::new($prefix).ContentLength $prefixVtLength = $prefix.Length - $prefixLength # replace newlines in message so it lines up correct - $message = $message.Replace($newline, ' ').Replace(""`n"", ' ').Replace(""`t"", ' ') + $message = $message.Replace($newline, ' ').Replace("`n", ' ').Replace("`t", ' ') $windowWidth = 120 if ($Host.UI.RawUI -ne $null) { @@ -1240,7 +1308,7 @@ function Get-ConciseViewPositionMessage { $message += $newline } - $posmsg += ""${errorColor}"" + $message + $posmsg += "${errorColor}" + $message $reason = 'Error' if ($err.Exception -and $err.Exception.WasThrownFromThrowStatement) { @@ -1252,8 +1320,8 @@ function Get-ConciseViewPositionMessage { $reason = $myinv.MyCommand } # If it's a scriptblock, better to show the command in the scriptblock that had the error - elseif ($_.CategoryInfo.Activity) { - $reason = $_.CategoryInfo.Activity + elseif ($err.CategoryInfo.Activity) { + $reason = $err.CategoryInfo.Activity } elseif ($myinv.MyCommand) { $reason = $myinv.MyCommand @@ -1270,7 +1338,7 @@ function Get-ConciseViewPositionMessage { $errorMsg = 'Error' - ""${errorColor}${reason}: ${posmsg}${resetcolor}"" + "${errorColor}${reason}: ${posmsg}${resetcolor}" } $myinv = $_.InvocationInfo @@ -1281,69 +1349,84 @@ function Get-ConciseViewPositionMessage { } if ($err.FullyQualifiedErrorId -eq 'NativeCommandErrorMessage' -or $err.FullyQualifiedErrorId -eq 'NativeCommandError') { - $err.Exception.Message + return "${errorColor}$($err.Exception.Message)${resetcolor}" } - else - { - $myinv = $err.InvocationInfo - if ($ErrorView -eq 'ConciseView') { - $posmsg = Get-ConciseViewPositionMessage - } - elseif ($myinv -and ($myinv.MyCommand -or ($err.CategoryInfo.Category -ne 'ParserError'))) { - $posmsg = $myinv.PositionMessage - } else { - $posmsg = '' - } - if ($posmsg -ne '') - { + if ($ErrorView -eq 'DetailedView') { + $message = Get-Error | Out-String + return "${errorColor}${message}${resetcolor}" + } + + if ($ErrorView -eq 'CategoryView') { + $message = $err.CategoryInfo.GetMessage() + return "${errorColor}${message}${resetcolor}" + } + + $posmsg = '' + if ($ErrorView -eq 'ConciseView') { + $posmsg = Get-ConciseViewPositionMessage + } + elseif ($myinv -and ($myinv.MyCommand -or ($err.CategoryInfo.Category -ne 'ParserError'))) { + $posmsg = $myinv.PositionMessage + if ($posmsg -ne '') { $posmsg = $newline + $posmsg } + } - if ($err.PSMessageDetails) { - $posmsg = ' : ' + $err.PSMessageDetails + $posmsg + if ($err.PSMessageDetails) { + $posmsg = ' : ' + $err.PSMessageDetails + $posmsg + } + + if ($ErrorView -eq 'ConciseView') { + $recommendedAction = $_.ErrorDetails.RecommendedAction + if (-not [String]::IsNullOrWhiteSpace($recommendedAction)) { + $recommendedAction = $newline + + ${errorColor} + + ' Recommendation: ' + + $recommendedAction + + ${resetcolor} } - if ($ErrorView -eq 'ConciseView') { - return $posmsg + if ($err.PSMessageDetails) { + $posmsg = "${errorColor}${posmsg}" } + return $posmsg + $recommendedAction + } - $indent = 4 + $indent = 4 - $errorCategoryMsg = $err.ErrorCategory_Message + $errorCategoryMsg = $err.ErrorCategory_Message - if ($null -ne $errorCategoryMsg) - { - $indentString = '+ CategoryInfo : ' + $err.ErrorCategory_Message - } - else - { - $indentString = '+ CategoryInfo : ' + $err.CategoryInfo - } + if ($null -ne $errorCategoryMsg) + { + $indentString = '+ CategoryInfo : ' + $err.ErrorCategory_Message + } + else + { + $indentString = '+ CategoryInfo : ' + $err.CategoryInfo + } - $posmsg += $newline + $indentString + $posmsg += $newline + $indentString - $indentString = ""+ FullyQualifiedErrorId : "" + $err.FullyQualifiedErrorId - $posmsg += $newline + $indentString + $indentString = "+ FullyQualifiedErrorId : " + $err.FullyQualifiedErrorId + $posmsg += $newline + $indentString - $originInfo = $err.OriginInfo + $originInfo = $err.OriginInfo - if (($null -ne $originInfo) -and ($null -ne $originInfo.PSComputerName)) - { - $indentString = ""+ PSComputerName : "" + $originInfo.PSComputerName - $posmsg += $newline + $indentString - } + if (($null -ne $originInfo) -and ($null -ne $originInfo.PSComputerName)) + { + $indentString = "+ PSComputerName : " + $originInfo.PSComputerName + $posmsg += $newline + $indentString + } - if ($ErrorView -eq 'CategoryView') { - $err.CategoryInfo.GetMessage() - } - elseif (! $err.ErrorDetails -or ! $err.ErrorDetails.Message) { - $err.Exception.Message + $posmsg - } else { - $err.ErrorDetails.Message + $posmsg - } + $finalMsg = if ($err.ErrorDetails.Message) { + $err.ErrorDetails.Message + $posmsg + } else { + $err.Exception.Message + $posmsg } - ") + + "${errorColor}${finalMsg}${resetcolor}" + """) .EndEntry() .EndControl()); } @@ -1905,6 +1988,31 @@ private static IEnumerable ViewsOf_Microsoft_PowerShell_Ma .EndList()); } + private static IEnumerable ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_TcpPortStatus() + { + yield return new FormatViewDefinition( + "Microsoft.PowerShell.Commands.TestConnectionCommand+TcpPortStatus", + TableControl.Create() + .AddHeader(Alignment.Right, label: "Id", width: 4) + .AddHeader(Alignment.Left, label: "Source", width: 16) + .AddHeader(Alignment.Left, label: "Address", width: 25) + .AddHeader(Alignment.Right, label: "Port", width: 7) + .AddHeader(Alignment.Right, label: "Latency(ms)", width: 7) + .AddHeader(Alignment.Left, label: "Connected", width: 10) + .AddHeader(Alignment.Left, label: "Status", width: 24) + .StartRowDefinition() + .AddPropertyColumn("Id") + .AddPropertyColumn("Source") + .AddPropertyColumn("TargetAddress") + .AddPropertyColumn("Port") + .AddPropertyColumn("Latency") + .AddPropertyColumn("Connected") + .AddPropertyColumn("Status") + .EndRowDefinition() + .GroupByProperty("Target") + .EndTable()); + } + private static IEnumerable ViewsOf_Microsoft_PowerShell_Commands_TestConnectionCommand_PingStatus() { yield return new FormatViewDefinition( @@ -2036,6 +2144,8 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Blink)$($_.Blink.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Blink") .AddItemScriptBlock(@"""$($_.BoldOff)$($_.BoldOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "BoldOff") .AddItemScriptBlock(@"""$($_.Bold)$($_.Bold.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Bold") + .AddItemScriptBlock(@"""$($_.DimOff)$($_.DimOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "DimOff") + .AddItemScriptBlock(@"""$($_.Dim)$($_.Dim.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Dim") .AddItemScriptBlock(@"""$($_.Hidden)$($_.Hidden.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Hidden") .AddItemScriptBlock(@"""$($_.HiddenOff)$($_.HiddenOff.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "HiddenOff") .AddItemScriptBlock(@"""$($_.Reverse)$($_.Reverse.Replace(""""`e"""",'`e'))$($_.Reset)""", label: "Reverse") @@ -2053,42 +2163,51 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.Formatting.Warning)$($_.Formatting.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Warning") .AddItemScriptBlock(@"""$($_.Formatting.Verbose)$($_.Formatting.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") .AddItemScriptBlock(@"""$($_.Formatting.Debug)$($_.Formatting.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Debug") + .AddItemScriptBlock(@"""$($_.Formatting.TableHeader)$($_.Formatting.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.TableHeader") + .AddItemScriptBlock(@"""$($_.Formatting.CustomTableHeaderLabel)$($_.Formatting.CustomTableHeaderLabel.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.CustomTableHeaderLabel") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackName)$($_.Formatting.FeedbackName.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackName") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackText)$($_.Formatting.FeedbackText.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackText") + .AddItemScriptBlock(@"""$($_.Formatting.FeedbackAction)$($_.Formatting.FeedbackAction.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.FeedbackAction") .AddItemScriptBlock(@"""$($_.Progress.Style)$($_.Progress.Style.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Progress.Style") .AddItemScriptBlock(@"""$($_.Progress.MaxWidth)""", label: "Progress.MaxWidth") .AddItemScriptBlock(@"""$($_.Progress.View)""", label: "Progress.View") .AddItemScriptBlock(@"""$($_.Progress.UseOSCIndicator)""", label: "Progress.UseOSCIndicator") + .AddItemScriptBlock(@"""$($_.FileInfo.Directory)$($_.FileInfo.Directory.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FileInfo.Directory") + .AddItemScriptBlock(@"""$($_.FileInfo.SymbolicLink)$($_.FileInfo.SymbolicLink.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FileInfo.SymbolicLink") + .AddItemScriptBlock(@"""$($_.FileInfo.Executable)$($_.FileInfo.Executable.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FileInfo.Executable") + .AddItemScriptBlock(@"""$([string]::Join(',',$_.FileInfo.Extension.Keys))""", label: "FileInfo.Extension") .AddItemScriptBlock(@"""$($_.Foreground.Black)$($_.Foreground.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Black") + .AddItemScriptBlock(@"""$($_.Foreground.BrightBlack)$($_.Foreground.BrightBlack.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightBlack") .AddItemScriptBlock(@"""$($_.Foreground.White)$($_.Foreground.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.White") - .AddItemScriptBlock(@"""$($_.Foreground.DarkGray)$($_.Foreground.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.DarkGray") - .AddItemScriptBlock(@"""$($_.Foreground.LightGray)$($_.Foreground.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightGray") + .AddItemScriptBlock(@"""$($_.Foreground.BrightWhite)$($_.Foreground.BrightWhite.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightWhite") .AddItemScriptBlock(@"""$($_.Foreground.Red)$($_.Foreground.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Red") - .AddItemScriptBlock(@"""$($_.Foreground.LightRed)$($_.Foreground.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightRed") + .AddItemScriptBlock(@"""$($_.Foreground.BrightRed)$($_.Foreground.BrightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightRed") .AddItemScriptBlock(@"""$($_.Foreground.Magenta)$($_.Foreground.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Magenta") - .AddItemScriptBlock(@"""$($_.Foreground.LightMagenta)$($_.Foreground.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightMagenta") + .AddItemScriptBlock(@"""$($_.Foreground.BrightMagenta)$($_.Foreground.BrightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightMagenta") .AddItemScriptBlock(@"""$($_.Foreground.Blue)$($_.Foreground.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Blue") - .AddItemScriptBlock(@"""$($_.Foreground.LightBlue)$($_.Foreground.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightBlue") + .AddItemScriptBlock(@"""$($_.Foreground.BrightBlue)$($_.Foreground.BrightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightBlue") .AddItemScriptBlock(@"""$($_.Foreground.Cyan)$($_.Foreground.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Cyan") - .AddItemScriptBlock(@"""$($_.Foreground.LightCyan)$($_.Foreground.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightCyan") + .AddItemScriptBlock(@"""$($_.Foreground.BrightCyan)$($_.Foreground.BrightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightCyan") .AddItemScriptBlock(@"""$($_.Foreground.Green)$($_.Foreground.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Green") - .AddItemScriptBlock(@"""$($_.Foreground.LightGreen)$($_.Foreground.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightGreen") + .AddItemScriptBlock(@"""$($_.Foreground.BrightGreen)$($_.Foreground.BrightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightGreen") .AddItemScriptBlock(@"""$($_.Foreground.Yellow)$($_.Foreground.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.Yellow") - .AddItemScriptBlock(@"""$($_.Foreground.LightYellow)$($_.Foreground.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.LightYellow") + .AddItemScriptBlock(@"""$($_.Foreground.BrightYellow)$($_.Foreground.BrightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Foreground.BrightYellow") .AddItemScriptBlock(@"""$($_.Background.Black)$($_.Background.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Black") + .AddItemScriptBlock(@"""$($_.Background.BrightBlack)$($_.Background.BrightBlack.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightBlack") .AddItemScriptBlock(@"""$($_.Background.White)$($_.Background.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.White") - .AddItemScriptBlock(@"""$($_.Background.DarkGray)$($_.Background.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.DarkGray") - .AddItemScriptBlock(@"""$($_.Background.LightGray)$($_.Background.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightGray") + .AddItemScriptBlock(@"""$($_.Background.BrightWhite)$($_.Background.BrightWhite.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightWhite") .AddItemScriptBlock(@"""$($_.Background.Red)$($_.Background.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Red") - .AddItemScriptBlock(@"""$($_.Background.LightRed)$($_.Background.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightRed") + .AddItemScriptBlock(@"""$($_.Background.BrightRed)$($_.Background.BrightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightRed") .AddItemScriptBlock(@"""$($_.Background.Magenta)$($_.Background.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Magenta") - .AddItemScriptBlock(@"""$($_.Background.LightMagenta)$($_.Background.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightMagenta") + .AddItemScriptBlock(@"""$($_.Background.BrightMagenta)$($_.Background.BrightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightMagenta") .AddItemScriptBlock(@"""$($_.Background.Blue)$($_.Background.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Blue") - .AddItemScriptBlock(@"""$($_.Background.LightBlue)$($_.Background.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightBlue") + .AddItemScriptBlock(@"""$($_.Background.BrightBlue)$($_.Background.BrightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightBlue") .AddItemScriptBlock(@"""$($_.Background.Cyan)$($_.Background.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Cyan") - .AddItemScriptBlock(@"""$($_.Background.LightCyan)$($_.Background.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightCyan") + .AddItemScriptBlock(@"""$($_.Background.BrightCyan)$($_.Background.BrightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightCyan") .AddItemScriptBlock(@"""$($_.Background.Green)$($_.Background.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Green") - .AddItemScriptBlock(@"""$($_.Background.LightGreen)$($_.Background.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightGreen") + .AddItemScriptBlock(@"""$($_.Background.BrightGreen)$($_.Background.BrightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightGreen") .AddItemScriptBlock(@"""$($_.Background.Yellow)$($_.Background.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.Yellow") - .AddItemScriptBlock(@"""$($_.Background.LightYellow)$($_.Background.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.LightYellow") + .AddItemScriptBlock(@"""$($_.Background.BrightYellow)$($_.Background.BrightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Background.BrightYellow") .EndEntry() .EndList()); } @@ -2102,8 +2221,13 @@ private static IEnumerable ViewsOf_System_Management_Autom .AddItemScriptBlock(@"""$($_.ErrorAccent)$($_.ErrorAccent.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "ErrorAccent") .AddItemScriptBlock(@"""$($_.Error)$($_.Error.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Error") .AddItemScriptBlock(@"""$($_.Warning)$($_.Warning.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Warning") - .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Formatting.Verbose") + .AddItemScriptBlock(@"""$($_.Verbose)$($_.Verbose.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Verbose") .AddItemScriptBlock(@"""$($_.Debug)$($_.Debug.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Debug") + .AddItemScriptBlock(@"""$($_.TableHeader)$($_.TableHeader.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "TableHeader") + .AddItemScriptBlock(@"""$($_.CustomTableHeaderLabel)$($_.CustomTableHeaderLabel.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "CustomTableHeaderLabel") + .AddItemScriptBlock(@"""$($_.FeedbackName)$($_.FeedbackName.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackName") + .AddItemScriptBlock(@"""$($_.FeedbackText)$($_.FeedbackText.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackText") + .AddItemScriptBlock(@"""$($_.FeedbackAction)$($_.FeedbackAction.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "FeedbackAction") .EndEntry() .EndList()); } @@ -2121,52 +2245,85 @@ private static IEnumerable ViewsOf_System_Management_Autom .EndList()); } + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleFileInfoFormat() + { + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+FileInfoFormatting", + ListControl.Create() + .StartEntry() + .AddItemScriptBlock(@"""$($_.Directory)$($_.Directory.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Directory") + .AddItemScriptBlock(@"""$($_.SymbolicLink)$($_.SymbolicLink.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "SymbolicLink") + .AddItemScriptBlock(@"""$($_.Executable)$($_.Executable.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Executable") + .AddItemScriptBlock(@" + $sb = [System.Text.StringBuilder]::new() + $maxKeyLength = 0 + foreach ($key in $_.Extension.Keys) { + if ($key.Length -gt $maxKeyLength) { + $maxKeyLength = $key.Length + } + } + + foreach ($key in $_.Extension.Keys) { + $null = $sb.Append($key.PadRight($maxKeyLength)) + $null = $sb.Append(' = ""') + $null = $sb.Append($_.Extension[$key]) + $null = $sb.Append($_.Extension[$key].Replace(""`e"",'`e')) + $null = $sb.Append($PSStyle.Reset) + $null = $sb.Append('""') + $null = $sb.Append([Environment]::NewLine) + } + + $sb.ToString()", + label: "Extension") + .EndEntry() + .EndList()); + } + private static IEnumerable ViewsOf_System_Management_Automation_PSStyleForegroundColor() { yield return new FormatViewDefinition("System.Management.Automation.PSStyle+ForegroundColor", ListControl.Create() .StartEntry() .AddItemScriptBlock(@"""$($_.Black)$($_.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Black") + .AddItemScriptBlock(@"""$($_.BrightBlack)$($_.BrightBlack.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightBlack") .AddItemScriptBlock(@"""$($_.White)$($_.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "White") - .AddItemScriptBlock(@"""$($_.DarkGray)$($_.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "DarkGray") - .AddItemScriptBlock(@"""$($_.LightGray)$($_.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGray") + .AddItemScriptBlock(@"""$($_.BrightWhite)$($_.BrightWhite.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightWhite") .AddItemScriptBlock(@"""$($_.Red)$($_.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Red") - .AddItemScriptBlock(@"""$($_.LightRed)$($_.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightRed") + .AddItemScriptBlock(@"""$($_.BrightRed)$($_.BrightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightRed") .AddItemScriptBlock(@"""$($_.Magenta)$($_.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Magenta") - .AddItemScriptBlock(@"""$($_.LightMagenta)$($_.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightMagenta") + .AddItemScriptBlock(@"""$($_.BrightMagenta)$($_.BrightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightMagenta") .AddItemScriptBlock(@"""$($_.Blue)$($_.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Blue") - .AddItemScriptBlock(@"""$($_.LightBlue)$($_.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightBlue") + .AddItemScriptBlock(@"""$($_.BrightBlue)$($_.BrightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightBlue") .AddItemScriptBlock(@"""$($_.Cyan)$($_.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Cyan") - .AddItemScriptBlock(@"""$($_.LightCyan)$($_.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightCyan") + .AddItemScriptBlock(@"""$($_.BrightCyan)$($_.BrightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightCyan") .AddItemScriptBlock(@"""$($_.Green)$($_.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Green") - .AddItemScriptBlock(@"""$($_.LightGreen)$($_.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGreen") + .AddItemScriptBlock(@"""$($_.BrightGreen)$($_.BrightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightGreen") .AddItemScriptBlock(@"""$($_.Yellow)$($_.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Yellow") - .AddItemScriptBlock(@"""$($_.LightYellow)$($_.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightYellow") + .AddItemScriptBlock(@"""$($_.BrightYellow)$($_.BrightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightYellow") .EndEntry() .EndList()); } private static IEnumerable ViewsOf_System_Management_Automation_PSStyleBackgroundColor() { - yield return new FormatViewDefinition("System.Management.Automation.PSStyle+ForegroundColor", + yield return new FormatViewDefinition("System.Management.Automation.PSStyle+BackgroundColor", ListControl.Create() .StartEntry() .AddItemScriptBlock(@"""$($_.Black)$($_.Black.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Black") + .AddItemScriptBlock(@"""$($_.BrightBlack)$($_.BrightBlack.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightBlack") .AddItemScriptBlock(@"""$($_.White)$($_.White.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "White") - .AddItemScriptBlock(@"""$($_.DarkGray)$($_.DarkGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "DarkGray") - .AddItemScriptBlock(@"""$($_.LightGray)$($_.LightGray.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGray") + .AddItemScriptBlock(@"""$($_.BrightWhite)$($_.BrightWhite.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightWhite") .AddItemScriptBlock(@"""$($_.Red)$($_.Red.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Red") - .AddItemScriptBlock(@"""$($_.LightRed)$($_.LightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightRed") + .AddItemScriptBlock(@"""$($_.BrightRed)$($_.BrightRed.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightRed") .AddItemScriptBlock(@"""$($_.Magenta)$($_.Magenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Magenta") - .AddItemScriptBlock(@"""$($_.LightMagenta)$($_.LightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightMagenta") + .AddItemScriptBlock(@"""$($_.BrightMagenta)$($_.BrightMagenta.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightMagenta") .AddItemScriptBlock(@"""$($_.Blue)$($_.Blue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Blue") - .AddItemScriptBlock(@"""$($_.LightBlue)$($_.LightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightBlue") + .AddItemScriptBlock(@"""$($_.BrightBlue)$($_.BrightBlue.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightBlue") .AddItemScriptBlock(@"""$($_.Cyan)$($_.Cyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Cyan") - .AddItemScriptBlock(@"""$($_.LightCyan)$($_.LightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightCyan") + .AddItemScriptBlock(@"""$($_.BrightCyan)$($_.BrightCyan.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightCyan") .AddItemScriptBlock(@"""$($_.Green)$($_.Green.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Green") - .AddItemScriptBlock(@"""$($_.LightGreen)$($_.LightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightGreen") + .AddItemScriptBlock(@"""$($_.BrightGreen)$($_.BrightGreen.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightGreen") .AddItemScriptBlock(@"""$($_.Yellow)$($_.Yellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "Yellow") - .AddItemScriptBlock(@"""$($_.LightYellow)$($_.LightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "LightYellow") + .AddItemScriptBlock(@"""$($_.BrightYellow)$($_.BrightYellow.Replace(""""`e"""",'`e'))$($PSStyle.Reset)""", label: "BrightYellow") .EndEntry() .EndList()); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs index dcfb79d4aed..e59cae40146 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseCommand.cs @@ -22,6 +22,7 @@ internal TerminatingErrorContext(PSCmdlet command) _command = command; } + [System.Diagnostics.CodeAnalysis.DoesNotReturn] internal void ThrowTerminatingError(ErrorRecord errorRecord) { _command.ThrowTerminatingError(errorRecord); diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs index 18b74cbcfe1..be31a1db9a8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommand.cs @@ -9,6 +9,7 @@ using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; +using Microsoft.PowerShell.Commands; namespace Microsoft.PowerShell.Commands.Internal.Format { @@ -727,8 +728,15 @@ public class OuterFormatTableAndListBase : OuterFormatShapeCommandBase /// will be determined using property sets, etc. /// [Parameter(Position = 0)] + [ValidateNotNullOrEmpty] public object[] Property { get; set; } + /// + /// Optional parameter for excluding properties from formatting. + /// + [Parameter] + public string[] ExcludeProperty { get; set; } + #endregion internal override FormattingCommandLineParameters GetCommandLineParameters() @@ -751,6 +759,18 @@ internal override FormattingCommandLineParameters GetCommandLineParameters() internal void GetCommandLineProperties(FormattingCommandLineParameters parameters, bool isTable) { + // Check View conflicts first (before any auto-expansion) + if (!string.IsNullOrEmpty(this.View)) + { + // View cannot be used with Property or ExcludeProperty + if ((Property is not null && Property.Length != 0) || (ExcludeProperty is not null && ExcludeProperty.Length != 0)) + { + ReportCannotSpecifyViewAndProperty(); + } + + parameters.viewName = this.View; + } + if (Property != null) { CommandParameterDefinition def; @@ -765,15 +785,21 @@ internal void GetCommandLineProperties(FormattingCommandLineParameters parameter parameters.mshParameterList = processor.ProcessParameters(Property, invocationContext); } - if (!string.IsNullOrEmpty(this.View)) + if (ExcludeProperty is not null) { - // we have a view command line switch - if (parameters.mshParameterList.Count != 0) + parameters.excludePropertyFilter = new PSPropertyExpressionFilter(ExcludeProperty); + + // ExcludeProperty implies -Property * for better UX + if (Property is null || Property.Length == 0) { - ReportCannotSpecifyViewAndProperty(); - } + CommandParameterDefinition def = isTable + ? new FormatTableParameterDefinition() + : new FormatListParameterDefinition(); + ParameterProcessor processor = new ParameterProcessor(def); + TerminatingErrorContext invocationContext = new TerminatingErrorContext(this); - parameters.viewName = this.View; + parameters.mshParameterList = processor.ProcessParameters(new object[] { "*" }, invocationContext); + } } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs index 95c58353457..498f6098a24 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseFormattingCommandParameters.cs @@ -70,6 +70,11 @@ internal sealed class FormattingCommandLineParameters /// Extension mechanism for shape specific parameters. /// internal ShapeSpecificParameters shapeParameters = null; + + /// + /// Filter for excluding properties from formatting. + /// + internal PSPropertyExpressionFilter excludePropertyFilter = null; } /// @@ -176,15 +181,13 @@ internal override object Verify(object val, // need to check the type: // it can be a string or a script block - ScriptBlock sb = val as ScriptBlock; - if (sb != null) + if (val is ScriptBlock sb) { PSPropertyExpression ex = new PSPropertyExpression(sb); return ex; } - string s = val as string; - if (s != null) + if (val is string s) { if (string.IsNullOrEmpty(s)) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs index 48ab1307681..113acf3fa6a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/BaseOutputtingCommand.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; @@ -129,15 +128,10 @@ private bool ProcessObject(PSObject so) } // instantiate the cache if not done yet - if (_cache == null) - { - _cache = new FormattedObjectsCache(this.LineOutput.RequiresBuffering); - } + _cache ??= new FormattedObjectsCache(this.LineOutput.RequiresBuffering); // no need for formatting, just process the object - FormatStartData formatStart = o as FormatStartData; - - if (formatStart != null) + if (o is FormatStartData formatStart) { // get autosize flag from object // turn on group caching @@ -149,8 +143,7 @@ private bool ProcessObject(PSObject so) else { // If the format info doesn't define column widths, then auto-size based on the first ten elements - TableHeaderInfo headerInfo = formatStart.shapeInfo as TableHeaderInfo; - if ((headerInfo != null) && + if ((formatStart.shapeInfo is TableHeaderInfo headerInfo) && (headerInfo.tableColumnInfoList.Count > 0) && (headerInfo.tableColumnInfoList[0].width == 0)) { @@ -262,8 +255,7 @@ private enum PreprocessingState { raw, processed, error } /// Whether the object needs to be shunted to preprocessing. private bool NeedsPreprocessing(object o) { - FormatEntryData fed = o as FormatEntryData; - if (fed != null) + if (o is FormatEntryData fed) { // we got an already pre-processed object if (!fed.outOfBand) @@ -326,8 +318,7 @@ private void ValidateCurrentFormattingState(FormattingState expectedFormattingSt // need to abort the command string violatingCommand = "format-*"; - StartData sdObj = obj as StartData; - if (sdObj != null) + if (obj is StartData sdObj) { if (sdObj.shapeInfo is WideViewHeaderInfo) { @@ -387,18 +378,16 @@ private FormatMessagesContextManager.OutputContext CreateOutputContext( FormatMessagesContextManager.OutputContext parentContext, FormatInfoData formatInfoData) { - FormatStartData formatStartData = formatInfoData as FormatStartData; // initialize the format context - if (formatStartData != null) + if (formatInfoData is FormatStartData formatStartData) { FormatOutputContext foc = new FormatOutputContext(parentContext, formatStartData); return foc; } - GroupStartData gsd = formatInfoData as GroupStartData; // we are starting a group, initialize the group context - if (gsd != null) + if (formatInfoData is GroupStartData gsd) { GroupOutputContext goc = null; @@ -460,9 +449,16 @@ private void ProcessFormatStart(FormatMessagesContextManager.OutputContext c) /// Current context, with Fs in it. private void ProcessFormatEnd(FormatEndData fe, FormatMessagesContextManager.OutputContext c) { - // Console.WriteLine("ProcessFormatEnd"); - // we just add an empty line to the display - this.LineOutput.WriteLine(string.Empty); + if (c is FormatOutputContext foContext + && foContext.Data.shapeInfo is ListViewHeaderInfo) + { + // Skip writing out a new line for List view, because we already wrote out + // an extra new line after displaying the last list entry. + return; + } + + // We just add an empty line to the display. + LineOutput.WriteLine(string.Empty); } /// @@ -541,8 +537,7 @@ private void ProcessPayload(FormatEntryData fed, FormatMessagesContextManager.Ou private void ProcessOutOfBandPayload(FormatEntryData fed) { // try if it is raw text - RawTextFormatEntry rte = fed.formatEntryInfo as RawTextFormatEntry; - if (rte != null) + if (fed.formatEntryInfo is RawTextFormatEntry rte) { if (fed.isHelpObject) { @@ -553,15 +548,15 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) } else { - _lo.WriteLine(rte.text); + // Write out raw text without any changes to it. + _lo.WriteRawText(rte.text); } return; } // try if it is a complex entry - ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve != null && cve.formatValueList != null) + if (fed.formatEntryInfo is ComplexViewEntry cve && cve.formatValueList != null) { ComplexWriter complexWriter = new ComplexWriter(); @@ -571,8 +566,7 @@ private void ProcessOutOfBandPayload(FormatEntryData fed) return; } // try if it is a list view - ListViewEntry lve = fed.formatEntryInfo as ListViewEntry; - if (lve != null && lve.listViewFieldList != null) + if (fed.formatEntryInfo is ListViewEntry lve && lve.listViewFieldList != null) { ListWriter listWriter = new ListWriter(); @@ -624,9 +618,7 @@ private FormatOutputContext FormatContext { for (FormatMessagesContextManager.OutputContext oc = _ctxManager.ActiveOutputContext; oc != null; oc = oc.ParentContext) { - FormatOutputContext foc = oc as FormatOutputContext; - - if (foc != null) + if (oc is FormatOutputContext foc) return foc; } @@ -651,17 +643,13 @@ private void ProcessCachedGroup(FormatStartData formatStartData, List /// Context for the outer scope of the format sequence. /// - private class FormatOutputContext : FormatMessagesContextManager.OutputContext + private sealed class FormatOutputContext : FormatMessagesContextManager.OutputContext { /// /// Construct a context to push on the stack. @@ -978,11 +966,10 @@ internal TableOutputContext(OutCommandInner cmd, /// internal override void Initialize() { - TableFormattingHint tableHint = this.InnerCommand.RetrieveFormattingHint() as TableFormattingHint; int[] columnWidthsHint = null; - // We expect that console width is less then 120. + // We expect that console width is less than 120. - if (tableHint != null) + if (this.InnerCommand.RetrieveFormattingHint() is TableFormattingHint tableHint) { columnWidthsHint = tableHint.columnWidths; } @@ -999,16 +986,18 @@ internal override void Initialize() // create arrays for widths and alignment Span columnWidths = columns <= StackAllocThreshold ? stackalloc int[columns] : new int[columns]; Span alignment = columns <= StackAllocThreshold ? stackalloc int[columns] : new int[columns]; + Span headerMatchesProperty = columns <= StackAllocThreshold ? stackalloc bool[columns] : new bool[columns]; int k = 0; foreach (TableColumnInfo tci in this.CurrentTableHeaderInfo.tableColumnInfoList) { columnWidths[k] = (columnWidthsHint != null) ? columnWidthsHint[k] : tci.width; alignment[k] = tci.alignment; + headerMatchesProperty[k] = tci.HeaderMatchesProperty; k++; } - this.Writer.Initialize(0, _consoleWidth, columnWidths, alignment, this.CurrentTableHeaderInfo.hideHeader); + this.Writer.Initialize(0, _consoleWidth, columnWidths, alignment, headerMatchesProperty, this.CurrentTableHeaderInfo.hideHeader); } /// @@ -1117,33 +1106,40 @@ private void InternalInitialize(ListViewEntry lve) internal static string[] GetProperties(ListViewEntry lve) { - StringCollection props = new StringCollection(); - foreach (ListViewField lvf in lve.listViewFieldList) + int count = lve.listViewFieldList.Count; + + if (count == 0) { - props.Add(lvf.label ?? lvf.propertyName); + return null; } - if (props.Count == 0) - return null; - string[] retVal = new string[props.Count]; - props.CopyTo(retVal, 0); - return retVal; + string[] result = new string[count]; + for (int index = 0; index < result.Length; ++index) + { + ListViewField lvf = lve.listViewFieldList[index]; + result[index] = lvf.label ?? lvf.propertyName; + } + + return result; } internal static string[] GetValues(ListViewEntry lve) { - StringCollection vals = new StringCollection(); + int count = lve.listViewFieldList.Count; - foreach (ListViewField lvf in lve.listViewFieldList) + if (count == 0) { - vals.Add(lvf.formatPropertyField.propertyValue); + return null; } - if (vals.Count == 0) - return null; - string[] retVal = new string[vals.Count]; - vals.CopyTo(retVal, 0); - return retVal; + string[] result = new string[count]; + for (int index = 0; index < result.Length; ++index) + { + ListViewField lvf = lve.listViewFieldList[index]; + result[index] = lvf.formatPropertyField.propertyValue; + } + + return result; } /// @@ -1202,13 +1198,11 @@ internal override void Initialize() // set the hard wider default, to be used if no other info is available int itemsPerRow = 2; - // get the header info and the view hint - WideFormattingHint hint = this.InnerCommand.RetrieveFormattingHint() as WideFormattingHint; - + // get the header info int columnsOnTheScreen = GetConsoleWindowWidth(this.InnerCommand._lo.ColumnNumber); // give a preference to the hint, if there - if (hint != null && hint.maxWidth > 0) + if (this.InnerCommand.RetrieveFormattingHint() is WideFormattingHint hint && hint.maxWidth > 0) { itemsPerRow = TableWriter.ComputeWideViewBestItemsPerRowFit(hint.maxWidth, columnsOnTheScreen); } @@ -1230,7 +1224,7 @@ internal override void Initialize() alignment[k] = TextAlignment.Left; } - this.Writer.Initialize(0, columnsOnTheScreen, columnWidths, alignment, false, GetConsoleWindowHeight(this.InnerCommand._lo.RowNumber)); + this.Writer.Initialize(leftMarginIndent: 0, columnsOnTheScreen, columnWidths, alignment, headerMatchesProperty: null, suppressHeader: false, screenRows: GetConsoleWindowHeight(this.InnerCommand._lo.RowNumber)); } /// @@ -1296,7 +1290,7 @@ private void WriteStringBuffer() /// Helper class to accumulate the display values so that when the end /// of a line is reached, a full line can be composed. /// - private class StringValuesBuffer + private sealed class StringValuesBuffer { /// /// Construct the buffer. @@ -1389,10 +1383,10 @@ internal override void Initialize() /// FormatEntryData to process. internal override void ProcessPayload(FormatEntryData fed) { - ComplexViewEntry cve = fed.formatEntryInfo as ComplexViewEntry; - if (cve == null || cve.formatValueList == null) - return; - _writer.WriteObject(cve.formatValueList); + if (fed.formatEntryInfo is ComplexViewEntry cve && cve.formatValueList is not null) + { + _writer.WriteObject(cve.formatValueList); + } } private readonly ComplexWriter _writer = new ComplexWriter(); diff --git a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs index e96115b78da..a69ad41c965 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ComplexWriter.cs @@ -6,6 +6,7 @@ using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Globalization; +using System.Management.Automation; using System.Management.Automation.Internal; using System.Text; @@ -68,8 +69,7 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) { foreach (object obj in fe.formatValueList) { - FormatEntry feChild = obj as FormatEntry; - if (feChild != null) + if (obj is FormatEntry feChild) { if (currentDepth < maxRecursionDepth) { @@ -98,15 +98,13 @@ private void GenerateFormatEntryDisplay(FormatEntry fe, int currentDepth) continue; } - FormatTextField ftf = obj as FormatTextField; - if (ftf != null) + if (obj is FormatTextField ftf) { this.AddToBuffer(ftf.text); continue; } - FormatPropertyField fpf = obj as FormatPropertyField; - if (fpf != null) + if (obj is FormatPropertyField fpf) { this.AddToBuffer(fpf.propertyValue); } @@ -146,7 +144,7 @@ private void WriteToScreen() int indentationAbsoluteValue = (firstLineIndentation > 0) ? firstLineIndentation : -firstLineIndentation; if (indentationAbsoluteValue >= usefulWidth) { - // valu too big, we reset it to zero + // value too big, we reset it to zero firstLineIndentation = 0; } @@ -237,10 +235,7 @@ internal IndentationStackFrame(IndentationManager mgr) public void Dispose() { - if (_mgr != null) - { - _mgr.RemoveStackFrame(); - } + _mgr?.RemoveStackFrame(); } private readonly IndentationManager _mgr; @@ -321,6 +316,7 @@ internal struct GetWordsResult { internal string Word; internal string Delim; + internal bool VtResetAdded; } /// @@ -328,9 +324,10 @@ internal struct GetWordsResult /// internal sealed class StringManipulationHelper { - private static readonly char s_softHyphen = '\u00AD'; - private static readonly char s_hardHyphen = '\u2011'; - private static readonly char s_nonBreakingSpace = '\u00A0'; + private const char SoftHyphen = '\u00AD'; + private const char HardHyphen = '\u2011'; + private const char NonBreakingSpace = '\u00A0'; + private static readonly Collection s_cultureCollection = new Collection(); static StringManipulationHelper() @@ -353,27 +350,71 @@ static StringManipulationHelper() private static IEnumerable GetWords(string s) { StringBuilder sb = new StringBuilder(); - GetWordsResult result = new GetWordsResult(); + StringBuilder vtSeqs = null; + Dictionary vtRanges = null; + + var valueStrDec = new ValueStringDecorated(s); + if (valueStrDec.IsDecorated) + { + vtSeqs = new StringBuilder(); + vtRanges = valueStrDec.EscapeSequenceRanges; + } + bool wordHasVtSeqs = false; for (int i = 0; i < s.Length; i++) { - // Soft hyphen = \u00AD - Should break, and add a hyphen if needed. If not needed for a break, hyphen should be absent - if (s[i] == ' ' || s[i] == '\t' || s[i] == s_softHyphen) + if (vtRanges?.TryGetValue(i, out int len) == true) { - result.Word = sb.ToString(); - sb.Clear(); - result.Delim = new string(s[i], 1); + var vtSpan = s.AsSpan(i, len); + sb.Append(vtSpan); - yield return result; + if (vtSpan.SequenceEqual(PSStyle.Instance.Reset)) + { + // The Reset sequence will void all previous VT sequences. + vtSeqs.Clear(); + wordHasVtSeqs = false; + } + else + { + vtSeqs.Append(vtSpan); + wordHasVtSeqs = true; + } + + i += len - 1; + continue; } - // Non-breaking space = \u00A0 - ideally shouldn't wrap - // Hard hyphen = \u2011 - Should not break - else if (s[i] == s_hardHyphen || s[i] == s_nonBreakingSpace) + + string delimiter = null; + if (s[i] is ' ' or '\t' or SoftHyphen) { - result.Word = sb.ToString(); - sb.Clear(); - result.Delim = string.Empty; + // Soft hyphen = \u00AD - Should break, and add a hyphen if needed. + // If not needed for a break, hyphen should be absent. + delimiter = new string(s[i], 1); + } + else if (s[i] is HardHyphen or NonBreakingSpace) + { + // Non-breaking space = \u00A0 - ideally shouldn't wrap. + // Hard hyphen = \u2011 - Should not break. + delimiter = string.Empty; + } + + if (delimiter is not null) + { + bool vtResetAdded = false; + if (wordHasVtSeqs && !sb.EndsWith(PSStyle.Instance.Reset)) + { + vtResetAdded = true; + sb.Append(PSStyle.Instance.Reset); + } + var result = new GetWordsResult() + { + Word = sb.ToString(), + Delim = delimiter, + VtResetAdded = vtResetAdded + }; + + sb.Clear().Append(vtSeqs); yield return result; } else @@ -382,10 +423,23 @@ private static IEnumerable GetWords(string s) } } - result.Word = sb.ToString(); - result.Delim = string.Empty; + if (wordHasVtSeqs) + { + if (sb.Length == vtSeqs.Length) + { + // This indicates 'sb' only contains all VT sequences, which may happen when the string ends with a word delimiter. + // For a word that contains VT sequence only, it's the same as an empty string to the formatting system, + // because nothing will actually be rendered. + // So, we use an empty string in this case to avoid unneeded string allocations. + sb.Clear(); + } + else if (!sb.EndsWith(PSStyle.Instance.Reset)) + { + sb.Append(PSStyle.Instance.Reset); + } + } - yield return result; + yield return new GetWordsResult() { Word = sb.ToString(), Delim = string.Empty }; } internal static StringCollection GenerateLines(DisplayCells displayCells, string val, int firstLineLen, int followingLinesLen) @@ -412,14 +466,16 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa } // break string on newlines and process each line separately - string[] lines = SplitLines(val); + List lines = SplitLines(val); - for (int k = 0; k < lines.Length; k++) + for (int k = 0; k < lines.Count; k++) { - if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen) + string currentLine = lines[k]; + + if (currentLine == null || displayCells.Length(currentLine) <= firstLineLen) { // we do not need to split further, just add - retVal.Add(lines[k]); + retVal.Add(currentLine); continue; } @@ -432,7 +488,7 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa int offset = 0; // offset into the line we are splitting - while (true) + while (offset < currentLine.Length) { // acquire the current active display line length (it can very from call to call) int currentDisplayLen = accumulator.ActiveLen; @@ -440,7 +496,7 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa // determine if the current tail would fit or not // for the remaining part of the string, determine its display cell count - int currentCellsToFit = displayCells.Length(lines[k], offset); + int currentCellsToFit = displayCells.Length(currentLine, offset); // determine if we fit into the line int excessCells = currentCellsToFit - currentDisplayLen; @@ -449,7 +505,7 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa { // we are not at the end of the string, select a sub string // that would fit in the remaining display length - int charactersToAdd = displayCells.GetHeadSplitLength(lines[k], offset, currentDisplayLen); + int charactersToAdd = displayCells.TruncateTail(currentLine, offset, currentDisplayLen); if (charactersToAdd <= 0) { @@ -463,7 +519,7 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa else { // of the given length, add it to the accumulator - accumulator.AddLine(lines[k].Substring(offset, charactersToAdd)); + accumulator.AddLine(currentLine.VtSubstring(offset, charactersToAdd)); } // increase the offset by the # of characters added @@ -472,7 +528,7 @@ private static StringCollection GenerateLinesWithoutWordWrap(DisplayCells displa else { // we reached the last (partial) line, we add it all - accumulator.AddLine(lines[k].Substring(offset)); + accumulator.AddLine(currentLine.VtSubstring(offset)); break; } } @@ -528,9 +584,9 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe } // break string on newlines and process each line separately - string[] lines = SplitLines(val); + List lines = SplitLines(val); - for (int k = 0; k < lines.Length; k++) + for (int k = 0; k < lines.Count; k++) { if (lines[k] == null || displayCells.Length(lines[k]) <= firstLineLen) { @@ -543,28 +599,34 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe int lineWidth = firstLineLen; bool firstLine = true; StringBuilder singleLine = new StringBuilder(); + string resetStr = PSStyle.Instance.Reset; foreach (GetWordsResult word in GetWords(lines[k])) { string wordToAdd = word.Word; + string suffix = null; // Handle soft hyphen - if (word.Delim == s_softHyphen.ToString()) + if (word.Delim.Length == 1 && word.Delim[0] is SoftHyphen) { - int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(s_softHyphen.ToString()); + int wordWidthWithHyphen = displayCells.Length(wordToAdd) + displayCells.Length(SoftHyphen); // Add hyphen only if necessary if (wordWidthWithHyphen == spacesLeft) { - wordToAdd += "-"; + suffix = "-"; } } - else + else if (!string.IsNullOrEmpty(word.Delim)) { - if (!string.IsNullOrEmpty(word.Delim)) - { - wordToAdd += word.Delim; - } + suffix = word.Delim; + } + + if (suffix is not null) + { + wordToAdd = word.VtResetAdded + ? wordToAdd.Insert(wordToAdd.Length - resetStr.Length, suffix) + : wordToAdd + suffix; } int wordWidth = displayCells.Length(wordToAdd); @@ -589,15 +651,35 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe // Word is wider than a single line if (wordWidth > lineWidth) { - foreach (char c in wordToAdd) + Dictionary vtRanges = null; + StringBuilder vtSeqs = null; + + var valueStrDec = new ValueStringDecorated(wordToAdd); + if (valueStrDec.IsDecorated) { - char charToAdd = c; - int charWidth = displayCells.Length(c); + vtSeqs = new StringBuilder(); + vtRanges = valueStrDec.EscapeSequenceRanges; + } - // corner case: we have a two cell character and the current - // display length is one. - // add a single cell arbitrary character instead of the original - // one and keep going + bool hasEscSeqs = false; + for (int i = 0; i < wordToAdd.Length; i++) + { + if (vtRanges?.TryGetValue(i, out int len) == true) + { + var vtSpan = wordToAdd.AsSpan(i, len); + singleLine.Append(vtSpan); + vtSeqs.Append(vtSpan); + + hasEscSeqs = true; + i += len - 1; + continue; + } + + char charToAdd = wordToAdd[i]; + int charWidth = displayCells.Length(charToAdd); + + // Corner case: we have a two cell character and the current display length is one. + // Add a single cell arbitrary character instead of the original one and keep going. if (charWidth > lineWidth) { charToAdd = '?'; @@ -606,9 +688,13 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe if (charWidth > spacesLeft) { + if (hasEscSeqs && !singleLine.EndsWith(resetStr)) + { + singleLine.Append(resetStr); + } + retVal.Add(singleLine.ToString()); - singleLine.Clear(); - singleLine.Append(charToAdd); + singleLine.Clear().Append(vtSeqs).Append(charToAdd); if (firstLine) { @@ -630,8 +716,7 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe if (wordWidth > spacesLeft) { retVal.Add(singleLine.ToString()); - singleLine.Clear(); - singleLine.Append(wordToAdd); + singleLine.Clear().Append(wordToAdd); if (firstLine) { @@ -661,49 +746,87 @@ private static StringCollection GenerateLinesWithWordWrap(DisplayCells displayCe /// /// String to split. /// String array with the values. - internal static string[] SplitLines(string s) + internal static List SplitLines(string s) { - if (string.IsNullOrEmpty(s)) - return new string[1] { s }; + if (string.IsNullOrEmpty(s) || !s.Contains('\n')) + { + return new List(capacity: 1) { s?.Replace("\r", string.Empty) }; + } StringBuilder sb = new StringBuilder(); + List list = new List(); - foreach (char c in s) + StringBuilder vtSeqs = null; + Dictionary vtRanges = null; + + var valueStrDec = new ValueStringDecorated(s); + if (valueStrDec.IsDecorated) { - if (c != '\r') - sb.Append(c); + vtSeqs = new StringBuilder(); + vtRanges = valueStrDec.EscapeSequenceRanges; } - return sb.ToString().Split(s_newLineChar); - } - -#if false - internal static string StripNewLines (string s) - { - if (string.IsNullOrEmpty (s)) - return s; + bool hasVtSeqs = false; + for (int i = 0; i < s.Length; i++) + { + if (vtRanges?.TryGetValue(i, out int len) == true) + { + var vtSpan = s.AsSpan(i, len); + sb.Append(vtSpan); - string[] lines = SplitLines (s); + if (vtSpan.SequenceEqual(PSStyle.Instance.Reset)) + { + // The Reset sequence will void all previous VT sequences. + vtSeqs.Clear(); + hasVtSeqs = false; + } + else + { + vtSeqs.Append(vtSpan); + hasVtSeqs = true; + } - if (lines.Length == 0) - return null; + i += len - 1; + continue; + } - if (lines.Length == 1) - return lines[0]; + char c = s[i]; + if (c == '\n') + { + if (hasVtSeqs && !sb.EndsWith(PSStyle.Instance.Reset)) + { + sb.Append(PSStyle.Instance.Reset); + } - StringBuilder sb = new StringBuilder (); + list.Add(sb.ToString()); + sb.Clear().Append(vtSeqs); + } + else if (c != '\r') + { + sb.Append(c); + } + } - for (int k = 0; k < lines.Length; k++) + if (hasVtSeqs) { - if (k == 0) - sb.Append (lines[k]); - else - sb.Append (" " + lines[k]); + if (sb.Length == vtSeqs.Length) + { + // This indicates 'sb' only contains all VT sequences, which may happen when the string ends with '\n'. + // For a sub-string that contains VT sequence only, it's the same as an empty string to the formatting + // system, because nothing will actually be rendered. + // So, we use an empty string in this case to avoid unneeded string allocations. + sb.Clear(); + } + else if (!sb.EndsWith(PSStyle.Instance.Reset)) + { + sb.Append(PSStyle.Instance.Reset); + } } - return sb.ToString (); + list.Add(sb.ToString()); + return list; } -#endif + internal static string TruncateAtNewLine(string s) { if (string.IsNullOrEmpty(s)) @@ -711,7 +834,7 @@ internal static string TruncateAtNewLine(string s) return string.Empty; } - int lineBreak = s.IndexOfAny(s_lineBreakChars); + int lineBreak = s.AsSpan().IndexOfAny('\n', '\r'); if (lineBreak < 0) { @@ -725,8 +848,5 @@ internal static string PadLeft(string val, int count) { return StringUtil.Padding(count) + val; } - - private static readonly char[] s_newLineChar = new char[] { '\n' }; - private static readonly char[] s_lineBreakChars = new char[] { '\n', '\r' }; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs index 43cab48d003..2ae4ac2626e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/FormatTable.cs @@ -19,9 +19,8 @@ namespace System.Management.Automation.Runspaces { /// /// This exception is used by Formattable constructor to indicate errors - /// occured during construction time. + /// occurred during construction time. /// - [Serializable] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "FormatTable")] public class FormatTableLoadException : RuntimeException { @@ -70,7 +69,7 @@ public FormatTableLoadException(string message, Exception innerException) /// time. /// /// - /// The errors that occured + /// The errors that occurred. /// internal FormatTableLoadException(ConcurrentBag loadErrors) : base(StringUtil.Format(FormatAndOutXmlLoadingStrings.FormatTableLoadErrors)) @@ -84,55 +83,14 @@ internal FormatTableLoadException(ConcurrentBag loadErrors) /// /// /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected FormatTableLoadException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - int errorCount = info.GetInt32("ErrorCount"); - if (errorCount > 0) - { - _errors = new Collection(); - for (int index = 0; index < errorCount; index++) - { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - _errors.Add(info.GetString(key)); - } - } + throw new NotSupportedException(); } #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - if (_errors != null) - { - int errorCount = _errors.Count; - info.AddValue("ErrorCount", errorCount); - - for (int index = 0; index < errorCount; index++) - { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - info.AddValue(key, _errors[index]); - } - } - } - /// /// Set the default ErrorRecord. /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs index a7e7df0a5d7..9ebc79a762a 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/XmlLoaderBase.cs @@ -384,14 +384,10 @@ private bool MatchNodeNameHelper(XmlNode n, string s, bool allowAttributes) match = true; } - if (match && !allowAttributes) + if (match && !allowAttributes && n is XmlElement e && e.Attributes.Count > 0) { - XmlElement e = n as XmlElement; - if (e != null && e.Attributes.Count > 0) - { - // Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. - ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); - } + // Error at XPath {0} in file {1}: The XML Element {2} does not allow attributes. + ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.AttributesNotAllowed, ComputeCurrentXPath(), FilePath, n.Name)); } return match; @@ -600,8 +596,7 @@ protected string ComputeCurrentXPath() path.Insert(0, "/"); if (sf.index != -1) { - path.Insert(1, string.Format(CultureInfo.InvariantCulture, - "{0}[{1}]", sf.node.Name, sf.index + 1)); + path.Insert(1, string.Create(CultureInfo.InvariantCulture, $"{sf.node.Name}[{sf.index + 1}]")); } else { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs index f126dddcadc..0190a31ddc9 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData.cs @@ -361,6 +361,7 @@ internal sealed class FieldPropertyToken : PropertyTokenBase internal sealed class FieldFormattingDirective { internal string formatString = null; // optional + internal bool isTable = false; } #endregion Elementary Tokens @@ -886,7 +887,7 @@ internal static EntrySelectedBy Get(List references) { if (tr.conditionToken != null) { - if (result.SelectionCondition == null) result.SelectionCondition = new List(); + result.SelectionCondition ??= new List(); result.SelectionCondition.Add(new DisplayEntry(tr.conditionToken)); continue; @@ -895,7 +896,7 @@ internal static EntrySelectedBy Get(List references) if (tr is TypeGroupReference) continue; - if (result.TypeNames == null) result.TypeNames = new List(); + result.TypeNames ??= new List(); result.TypeNames.Add(tr.name); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs index d3290c18752..822703fde21 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Complex.cs @@ -179,14 +179,12 @@ internal static CustomItemBase Create(FormatToken token) return new CustomItemNewline(); } - var textToken = token as TextToken; - if (textToken != null) + if (token is TextToken textToken) { return new CustomItemText { Text = textToken.text }; } - var frameToken = token as FrameToken; - if (frameToken != null) + if (token is FrameToken frameToken) { var frame = new CustomItemFrame { @@ -211,8 +209,7 @@ internal static CustomItemBase Create(FormatToken token) return frame; } - var cpt = token as CompoundPropertyToken; - if (cpt != null) + if (token is CompoundPropertyToken cpt) { var cie = new CustomItemExpression { EnumerateCollection = cpt.enumerateCollection }; @@ -226,19 +223,14 @@ internal static CustomItemBase Create(FormatToken token) cie.Expression = new DisplayEntry(cpt.expression); } - if (cpt.control != null) + if (cpt.control is ComplexControlBody complexControlBody) { - cie.CustomControl = new CustomControl((ComplexControlBody)cpt.control, null); + cie.CustomControl = new CustomControl(complexControlBody, null); } return cie; } - var fpt = token as FieldPropertyToken; - if (fpt != null) - { - } - Diagnostics.Assert(false, "Unexpected formatting token kind"); return null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs index 6025acfff44..293b4c5b82e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_List.cs @@ -208,8 +208,7 @@ public List SelectedBy { get { - if (EntrySelectedBy == null) - EntrySelectedBy = new EntrySelectedBy { TypeNames = new List() }; + EntrySelectedBy ??= new EntrySelectedBy { TypeNames = new List() }; return EntrySelectedBy.TypeNames; } } @@ -319,8 +318,7 @@ internal ListControlEntryItem(ListControlItemDefinition definition) Label = definition.label.text; } - FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (definition.formatTokenList[0] is FieldPropertyToken fpt) { if (fpt.fieldFormattingDirective.formatString != null) { diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs index e509530538d..026b9b82f73 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Table.cs @@ -446,10 +446,9 @@ internal TableControlRow(TableRowDefinition rowdefinition) : this() foreach (TableRowItemDefinition itemdef in rowdefinition.rowItemDefinitionList) { - FieldPropertyToken fpt = itemdef.formatTokenList[0] as FieldPropertyToken; TableControlColumn column; - if (fpt != null) + if (itemdef.formatTokenList[0] is FieldPropertyToken fpt) { column = new TableControlColumn(fpt.expression.expressionValue, itemdef.alignment, fpt.expression.isScriptBlock, fpt.fieldFormattingDirective.formatString); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs index 4f87998fd1e..1f5b42fd262 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayDescriptionData_Wide.cs @@ -187,8 +187,7 @@ public List SelectedBy { get { - if (EntrySelectedBy == null) - EntrySelectedBy = new EntrySelectedBy { TypeNames = new List() }; + EntrySelectedBy ??= new EntrySelectedBy { TypeNames = new List() }; return EntrySelectedBy.TypeNames; } } @@ -205,8 +204,7 @@ internal WideControlEntryItem() internal WideControlEntryItem(WideControlEntryDefinition definition) : this() { - FieldPropertyToken fpt = definition.formatTokenList[0] as FieldPropertyToken; - if (fpt != null) + if (definition.formatTokenList[0] is FieldPropertyToken fpt) { DisplayEntry = new DisplayEntry(fpt.expression); FormatString = fpt.fieldFormattingDirective.formatString; diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs index fbdd1287a02..b5eb4d456e8 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/displayResourceManagerCache.cs @@ -142,7 +142,7 @@ private sealed class AssemblyLoadResult /// Helper class to resolve an assembly name to an assembly reference /// The class caches previous results for faster lookup. /// - private class AssemblyNameResolver + private sealed class AssemblyNameResolver { /// /// Resolve the assembly name against the set of loaded assemblies. diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs index c42bd21adc7..629e419d5a2 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataManager.cs @@ -409,7 +409,10 @@ private static TypeInfoDataBase LoadFromFileHelper( continue; } - if (etwEnabled) RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath); + if (etwEnabled) + { + RunspaceEventSource.Log.ProcessFormatFileStart(file.FullPath); + } if (!ProcessBuiltin(file, db, expressionFactory, logEntries, ref success)) { @@ -428,7 +431,10 @@ private static TypeInfoDataBase LoadFromFileHelper( { string mshsnapinMessage = StringUtil.Format(FormatAndOutXmlLoadingStrings.MshSnapinQualifiedError, info.psSnapinName, entry.message); info.errors.Add(mshsnapinMessage); - if (entry.failToLoadFile) { file.FailToLoadFile = true; } + if (entry.failToLoadFile) + { + file.FailToLoadFile = true; + } } } // now aggregate the entries... @@ -436,7 +442,10 @@ private static TypeInfoDataBase LoadFromFileHelper( } } - if (etwEnabled) RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath); + if (etwEnabled) + { + RunspaceEventSource.Log.ProcessFormatFileStop(file.FullPath); + } } // add any sensible defaults to the database diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs index 60953d22c26..de6df333951 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataQuery.cs @@ -143,9 +143,8 @@ private int ComputeBestMatch(AppliesTo appliesTo, PSObject currentObject) } int currentMatch = BestMatchIndexUndefined; - TypeReference tr = r as TypeReference; - if (tr != null) + if (r is TypeReference tr) { // we have a type currentMatch = MatchTypeIndex(tr.name, currentObject, ex); @@ -486,18 +485,25 @@ private static void TraceHelper(ViewDefinition vd, bool isMatched) foreach (TypeOrGroupReference togr in vd.appliesTo.referenceList) { StringBuilder sb = new StringBuilder(); - TypeReference tr = togr as TypeReference; sb.Append(isMatched ? "MATCH FOUND" : "NOT MATCH"); - if (tr != null) + if (togr is TypeReference tr) { - sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} TYPE: {2}", - ControlBase.GetControlShapeName(vd.mainControl), vd.name, tr.name); + sb.AppendFormat( + CultureInfo.InvariantCulture, + " {0} NAME: {1} TYPE: {2}", + ControlBase.GetControlShapeName(vd.mainControl), + vd.name, + tr.name); } else { TypeGroupReference tgr = togr as TypeGroupReference; - sb.AppendFormat(CultureInfo.InvariantCulture, " {0} NAME: {1} GROUP: {2}", - ControlBase.GetControlShapeName(vd.mainControl), vd.name, tgr.name); + sb.AppendFormat( + CultureInfo.InvariantCulture, + " {0} NAME: {1} GROUP: {2}", + ControlBase.GetControlShapeName(vd.mainControl), + vd.name, + tgr.name); } ActiveTracer.WriteLine(sb.ToString()); @@ -593,16 +599,14 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a foreach (TypeOrGroupReference r in appliesTo.referenceList) { // if it is a type reference, just add the type name - TypeReference tr = r as TypeReference; - if (tr != null) + if (r is TypeReference tr) { - if (!allTypes.Contains(tr.name)) - allTypes.Add(tr.name); + allTypes.Add(tr.name); } else { // check if we have a type group reference - if (!(r is TypeGroupReference tgr)) + if (r is not TypeGroupReference tgr) continue; // find the type group definition the reference points to @@ -614,8 +618,7 @@ internal static AppliesTo GetAllApplicableTypes(TypeInfoDataBase db, AppliesTo a // we found the group, go over it foreach (TypeReference x in tgd.typeReferenceList) { - if (!allTypes.Contains(x.name)) - allTypes.Add(x.name); + allTypes.Add(x.name); } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs index 8c1c251f149..b8a25e5e207 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader.cs @@ -277,7 +277,7 @@ internal bool LoadXmlFile( /// The ExtendedTypeDefinition instance to load formatting data from. /// Database instance to load the formatting data into. /// Expression factory to validate the script block. - /// Do we implicitly trust the script blocks (so they should run in full langauge mode)? + /// Do we implicitly trust the script blocks (so they should run in full language mode)? /// True when the view is for help output. /// internal bool LoadFormattingData( @@ -436,10 +436,13 @@ private void LoadData(ExtendedTypeDefinition typeDefinition, TypeInfoDataBase db ViewDefinition view = LoadViewFromObjectModel(typeDefinition.TypeNames, formatView, viewIndex++); if (view != null) { - ReportTrace(string.Format(CultureInfo.InvariantCulture, + ReportTrace(string.Format( + CultureInfo.InvariantCulture, "{0} view {1} is loaded from the 'FormatViewDefinition' at index {2} in 'ExtendedTypeDefinition' with type name {3}", ControlBase.GetControlShapeName(view.mainControl), - view.name, viewIndex - 1, typeDefinition.TypeName)); + view.name, + viewIndex - 1, + typeDefinition.TypeName)); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); @@ -1082,20 +1085,17 @@ private ComplexControlEntryDefinition LoadComplexControlEntryDefinitionFromObjec private FormatToken LoadFormatTokenFromObjectModel(CustomItemBase item, int viewIndex, string typeName) { - var newline = item as CustomItemNewline; - if (newline != null) + if (item is CustomItemNewline newline) { return new NewLineToken { count = newline.Count }; } - var text = item as CustomItemText; - if (text != null) + if (item is CustomItemText text) { return new TextToken { text = text.Text }; } - var expr = item as CustomItemExpression; - if (expr != null) + if (item is CustomItemExpression expr) { var cpt = new CompoundPropertyToken { enumerateCollection = expr.EnumerateCollection }; @@ -1763,9 +1763,8 @@ private TextToken LoadTextToken(XmlNode n) private bool LoadStringResourceReference(XmlNode n, out StringResourceReference resource) { resource = null; - XmlElement e = n as XmlElement; - if (e == null) + if (n is not XmlElement e) { // Error at XPath {0} in file {1}: Node should be an XmlElement. this.ReportError(StringUtil.Format(FormatAndOutXmlLoadingStrings.NonXmlElementNode, ComputeCurrentXPath(), FilePath)); diff --git a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs index 505c766b9d1..c6d191284e6 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/DisplayDatabase/typeDataXmlLoader_Views.cs @@ -27,10 +27,12 @@ private void LoadViewDefinitions(TypeInfoDataBase db, XmlNode viewDefinitionsNod ViewDefinition view = LoadView(n, index++); if (view != null) { - ReportTrace(string.Format(CultureInfo.InvariantCulture, + ReportTrace(string.Format( + CultureInfo.InvariantCulture, "{0} view {1} is loaded from file {2}", ControlBase.GetControlShapeName(view.mainControl), - view.name, view.loadingInfo.filePath)); + view.name, + view.loadingInfo.filePath)); // we are fine, add the view to the list db.viewDefinitionsSection.viewDefinitionList.Add(view); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs index 3eabcc975a0..1018936d2c1 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatMsgCtxManager.cs @@ -68,8 +68,7 @@ internal OutputContext(OutputContext parentContextInStack) internal void Process(object o) { PacketInfoData formatData = o as PacketInfoData; - FormatEntryData fed = formatData as FormatEntryData; - if (fed != null) + if (formatData is FormatEntryData fed) { OutputContext ctx = null; diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs index f29033e3c8d..963b5a0f88b 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections.Generic; +using System.Linq; using System.Collections.ObjectModel; using System.Management.Automation; using System.Management.Automation.Internal; @@ -141,13 +142,10 @@ private void InitializeAutoSize() return; } // check if we have a view with autosize checked - if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null) + if (this.dataBaseInfo.view != null && this.dataBaseInfo.view.mainControl != null + && this.dataBaseInfo.view.mainControl is ControlBody controlBody && controlBody.autosize.HasValue) { - ControlBody controlBody = this.dataBaseInfo.view.mainControl as ControlBody; - if (controlBody != null && controlBody.autosize.HasValue) - { - _autosize = controlBody.autosize.Value; - } + _autosize = controlBody.autosize.Value; } } @@ -219,7 +217,7 @@ internal GroupStartData GenerateGroupStartData(PSObject firstObjectInGroup, int if (formatErrorObject != null && formatErrorObject.exception != null) { - // if we did no thave any errors in the expression evaluation + // if we did not have any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayFormatErrorString) @@ -350,8 +348,50 @@ protected class DataBaseInfo protected DataBaseInfo dataBaseInfo = new DataBaseInfo(); - protected List activeAssociationList = null; - protected FormattingCommandLineParameters inputParameters = null; + /// + /// Builds the raw association list for the given object. + /// Subclasses override this to provide cmdlet-specific property expansion logic. + /// + /// The object to build the association list for. + /// The list of properties specified by the user, or null if not specified. + /// The raw association list, or null if not applicable. + protected virtual List BuildRawAssociationList(PSObject so, List propertyList) + { + return null; + } + + /// + /// Builds the active association list for the given object, with ExcludeProperty filter applied. + /// + /// The object to build the association list for. + /// The filtered association list. + protected List BuildActiveAssociationList(PSObject so) + { + var propertyList = parameters?.mshParameterList; + var excludeFilter = parameters?.excludePropertyFilter; + var rawList = BuildRawAssociationList(so, propertyList); + return ApplyExcludeFilter(rawList, excludeFilter); + } + + /// + /// Applies the ExcludeProperty filter to the given association list. + /// + /// The list to filter. + /// The exclude filter to apply. + /// The filtered list, or the original list if no filter is specified. + internal static List ApplyExcludeFilter( + List associationList, + PSPropertyExpressionFilter excludeFilter) + { + if (associationList is null || excludeFilter is null) + { + return associationList; + } + + return associationList + .Where(item => !excludeFilter.IsMatch(item.ResolvedExpression)) + .ToList(); + } protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PSPropertyExpression ex, FieldFormattingDirective directive) @@ -387,7 +427,7 @@ protected string GetExpressionDisplayValue(PSObject so, int enumerationLimit, PS } else if (formatErrorObject != null && formatErrorObject.exception != null) { - // if we did no thave any errors in the expression evaluation + // if we did not have any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayErrorStrings) @@ -439,17 +479,14 @@ protected FormatPropertyField GenerateFormatPropertyField(List form if (formatTokenList.Count != 0) { FormatToken token = formatTokenList[0]; - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, ex, fpt.fieldFormattingDirective, out result); } - else + else if (token is TextToken tt) { - TextToken tt = token as TextToken; - if (tt != null) - fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); + fpf.propertyValue = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } else diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs index c1645b09ad5..b81c0c0f860 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Complex.cs @@ -16,7 +16,6 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); - this.inputParameters = parameters; } internal override FormatStartData GenerateStartData(PSObject so) @@ -40,7 +39,7 @@ internal override FormatEntryData GeneratePayload(PSObject so, int enumerationLi private ComplexViewEntry GenerateComplexViewEntryFromProperties(PSObject so, int enumerationLimit) { ComplexViewObjectBrowser browser = new ComplexViewObjectBrowser(this.ErrorManager, this.expressionFactory, enumerationLimit); - return browser.GenerateView(so, this.inputParameters); + return browser.GenerateView(so, this.parameters); } private ComplexViewEntry GenerateComplexViewEntryFromDataBaseInfo(PSObject so, int enumerationLimit) @@ -107,8 +106,7 @@ private bool ExecuteFormatControl(TraversalInfo level, ControlBase control, ComplexControlBody complexBody = null; // we might have a reference - ControlReference controlReference = control as ControlReference; - if (controlReference != null && controlReference.controlType == typeof(ComplexControlBody)) + if (control is ControlReference controlReference && controlReference.controlType == typeof(ComplexControlBody)) { // retrieve the reference complexBody = DisplayDataQuery.ResolveControlReference( @@ -205,8 +203,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, #region foreach loop foreach (FormatToken t in formatTokenList) { - TextToken tt = t as TextToken; - if (tt != null) + if (t is TextToken tt) { FormatTextField ftf = new FormatTextField(); ftf.text = _db.displayResourceManagerCache.GetTextTokenString(tt); @@ -214,8 +211,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } - var newline = t as NewLineToken; - if (newline != null) + if (t is NewLineToken newline) { for (int i = 0; i < newline.count; i++) { @@ -225,8 +221,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } - FrameToken ft = t as FrameToken; - if (ft != null) + if (t is FrameToken ft) { // instantiate a new entry and attach a frame info object FormatEntry feFrame = new FormatEntry(); @@ -245,8 +240,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, continue; } #region CompoundPropertyToken - CompoundPropertyToken cpt = t as CompoundPropertyToken; - if (cpt != null) + if (t is CompoundPropertyToken cpt) { if (!EvaluateDisplayCondition(so, cpt.conditionToken)) { @@ -283,10 +277,7 @@ private void ExecuteFormatTokenList(TraversalInfo level, { // Since it is a leaf node we just consider it an empty string and go // on with formatting - if (val == null) - { - val = string.Empty; - } + val ??= string.Empty; FieldFormattingDirective fieldFormattingDirective = null; StringFormatError formatErrorObject = null; @@ -433,17 +424,18 @@ internal ComplexViewObjectBrowser(FormatErrorManager resultErrorManager, PSPrope /// of the object. /// /// Object to process. - /// Parameters from the command line. + /// Parameters from the command line. /// Complex view entry to send to the output command. - internal ComplexViewEntry GenerateView(PSObject so, FormattingCommandLineParameters inputParameters) + internal ComplexViewEntry GenerateView(PSObject so, FormattingCommandLineParameters parameters) { - _complexSpecificParameters = (ComplexSpecificParameters)inputParameters.shapeParameters; + _parameters = parameters; + _complexSpecificParameters = (ComplexSpecificParameters)parameters.shapeParameters; int maxDepth = _complexSpecificParameters.maxDepth; TraversalInfo level = new TraversalInfo(0, maxDepth); List mshParameterList = null; - mshParameterList = inputParameters.mshParameterList; + mshParameterList = parameters.mshParameterList; // create a top level entry as root of the tree ComplexViewEntry cve = new ComplexViewEntry(); @@ -494,7 +486,7 @@ private void DisplayRawObject(PSObject so, List formatValueList) if (formatErrorObject != null && formatErrorObject.exception != null) { - // if we did no thave any errors in the expression evaluation + // if we did not have any errors in the expression evaluation // we might have errors in the formatting, if present _errorManager.LogStringFormatError(formatErrorObject); if (_errorManager.DisplayFormatErrorString) @@ -521,6 +513,9 @@ private void DisplayObject(PSObject so, TraversalInfo currentLevel, List activeAssociationList = AssociationManager.SetupActiveProperties(parameterList, so, _expressionFactory); + // Apply ExcludeProperty filter using the centralized method + activeAssociationList = ViewGenerator.ApplyExcludeFilter(activeAssociationList, _parameters?.excludePropertyFilter); + // create a format entry FormatEntry fe = new FormatEntry(); formatValueList.Add(fe); @@ -717,7 +712,7 @@ private string GetObjectDisplayName(PSObject so) if (_complexSpecificParameters.classDisplay == ComplexSpecificParameters.ClassInfoDisplay.shortName) { // get the last token in the full name - string[] arr = typeNames[0].Split(Utils.Separators.Dot); + string[] arr = typeNames[0].Split('.'); if (arr.Length > 0) return arr[arr.Length - 1]; } @@ -766,6 +761,7 @@ private List AddIndentationLevel(List formatValueList) return feFrame.formatValueList; } + private FormattingCommandLineParameters _parameters; private ComplexSpecificParameters _complexSpecificParameters; /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs index 1cee3067011..35287d7c2e4 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_List.cs @@ -30,9 +30,14 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper { _listBody = (ListControlBody)this.dataBaseInfo.view.mainControl; } + } - this.inputParameters = parameters; - SetUpActiveProperties(so); + /// + /// Builds the raw association list for list formatting. + /// + protected override List BuildRawAssociationList(PSObject so, List propertyList) + { + return AssociationManager.SetupActiveProperties(propertyList, so, this.expressionFactory); } /// @@ -114,20 +119,17 @@ private ListViewEntry GenerateListViewEntryFromDataBaseInfo(PSObject so, int enu // we try to fall back and see if we have an un-resolved PSPropertyExpression FormatToken token = listItem.formatTokenList[0]; - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { PSPropertyExpression ex = this.expressionFactory.CreateFromExpressionToken(fpt.expression, this.dataBaseInfo.view.loadingInfo); // use the un-resolved PSPropertyExpression string as a label lvf.label = ex.ToString(); } - else + else if (token is TextToken tt) { - TextToken tt = token as TextToken; - if (tt != null) - // we had a text token, use it as a label (last resort...) - lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); + // we had a text token, use it as a label (last resort...) + lvf.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } @@ -181,17 +183,14 @@ private ListControlEntryDefinition GetActiveListControlEntryDefinition(ListContr private ListViewEntry GenerateListViewEntryFromProperties(PSObject so, int enumerationLimit) { - // compute active properties every time - if (this.activeAssociationList == null) - { - SetUpActiveProperties(so); - } + // Build active association list (with ExcludeProperty filter applied) + var associationList = BuildActiveAssociationList(so); ListViewEntry lve = new ListViewEntry(); - for (int k = 0; k < this.activeAssociationList.Count; k++) + for (int k = 0; k < associationList.Count; k++) { - MshResolvedExpressionParameterAssociation a = this.activeAssociationList[k]; + MshResolvedExpressionParameterAssociation a = associationList[k]; ListViewField lvf = new ListViewField(); if (a.OriginatingParameter != null) @@ -221,19 +220,7 @@ private ListViewEntry GenerateListViewEntryFromProperties(PSObject so, int enume lvf.formatPropertyField.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, a.ResolvedExpression, directive); lve.listViewFieldList.Add(lvf); } - - this.activeAssociationList = null; return lve; } - - private void SetUpActiveProperties(PSObject so) - { - List mshParameterList = null; - - if (this.inputParameters != null) - mshParameterList = this.inputParameters.mshParameterList; - - this.activeAssociationList = AssociationManager.SetupActiveProperties(mshParameterList, so, this.expressionFactory); - } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs index bfd3291dd46..3b14c0754ba 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Table.cs @@ -14,6 +14,8 @@ internal sealed class TableViewGenerator : ViewGenerator // tableBody to use for this instance of the ViewGenerator; private TableControlBody _tableBody; + private List _activeAssociationList; + internal override void Initialize(TerminatingErrorContext terminatingErrorContext, PSPropertyExpressionFactory mshExpressionFactory, TypeInfoDataBase db, ViewDefinition view, FormattingCommandLineParameters formatParameters) { base.Initialize(terminatingErrorContext, mshExpressionFactory, db, view, formatParameters); @@ -34,46 +36,48 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper _tableBody = (TableControlBody)this.dataBaseInfo.view.mainControl; } - List rawMshParameterList = null; - - if (parameters != null) - rawMshParameterList = parameters.mshParameterList; + // Build the active association list (with ExcludeProperty filter applied) + _activeAssociationList = BuildActiveAssociationList(so); + } + /// + /// Builds the raw association list for table formatting. + /// + protected override List BuildRawAssociationList(PSObject so, List propertyList) + { // check if we received properties from the command line - if (rawMshParameterList != null && rawMshParameterList.Count > 0) + if (propertyList is not null && propertyList.Count > 0) { - this.activeAssociationList = AssociationManager.ExpandTableParameters(rawMshParameterList, so); - return; + return AssociationManager.ExpandTableParameters(propertyList, so); } // we did not get any properties: // try to get properties from the default property set of the object - this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory); - if (this.activeAssociationList.Count > 0) + var list = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory); + if (list.Count > 0) { // we got a valid set of properties from the default property set..add computername for // remoteobjects (if available) if (PSObjectHelper.ShouldShowComputerNameProperty(so)) { - activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, + list.Add(new MshResolvedExpressionParameterAssociation(null, new PSPropertyExpression(RemotingConstants.ComputerNameNoteProperty))); } - return; + return list; } // we failed to get anything from the default property set - this.activeAssociationList = AssociationManager.ExpandAll(so); - if (this.activeAssociationList.Count > 0) + list = AssociationManager.ExpandAll(so); + if (list.Count > 0) { // Remove PSComputerName and PSShowComputerName from the display as needed. - AssociationManager.HandleComputerNameProperties(so, activeAssociationList); - FilterActiveAssociationList(); - return; + AssociationManager.HandleComputerNameProperties(so, list); + return LimitAssociationListSize(list); } // we were unable to retrieve any properties, so we leave an empty list - this.activeAssociationList = new List(); + return new List(); } /// @@ -124,30 +128,29 @@ internal override FormatStartData GenerateStartData(PSObject so) } /// - /// Method to filter resolved expressions as per table view needs. + /// Limits the association list size for table view. /// 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 void FilterActiveAssociationList() + /// The list to limit. + /// The limited list. + private static List LimitAssociationListSize( + List list) { - // 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 = 10; + const int maxCount = 10; - if (activeAssociationList.Count > nMax) + if (list.Count <= maxCount) { - List tmp = this.activeAssociationList; - this.activeAssociationList = new List(); - for (int k = 0; k < nMax; k++) - this.activeAssociationList.Add(tmp[k]); + return list; } - return; + var result = new List(maxCount); + for (int k = 0; k < maxCount; k++) + { + result.Add(list[k]); + } + + return result; } private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) @@ -172,7 +175,14 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) ci.width = colHeader.width; ci.alignment = colHeader.alignment; if (colHeader.label != null) + { + if (colHeader.label.text != string.Empty) + { + ci.HeaderMatchesProperty = so.Properties[colHeader.label.text] is not null; + } + ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(colHeader.label); + } } if (ci.alignment == TextAlignment.Undefined) @@ -187,18 +197,13 @@ private TableHeaderInfo GenerateTableHeaderInfoFromDataBaseInfo(PSObject so) token = rowItem.formatTokenList[0]; if (token != null) { - FieldPropertyToken fpt = token as FieldPropertyToken; - if (fpt != null) + if (token is FieldPropertyToken fpt) { ci.label = fpt.expression.expressionValue; } - else + else if (token is TextToken tt) { - TextToken tt = token as TextToken; - if (tt != null) - { - ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); - } + ci.label = this.dataBaseInfo.db.displayResourceManagerCache.GetTextTokenString(tt); } } else @@ -219,10 +224,11 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) TableHeaderInfo thi = new TableHeaderInfo(); thi.hideHeader = this.HideHeaders; + thi.repeatHeader = this.RepeatHeader; - for (int k = 0; k < this.activeAssociationList.Count; k++) + for (int k = 0; k < _activeAssociationList.Count; k++) { - MshResolvedExpressionParameterAssociation a = this.activeAssociationList[k]; + MshResolvedExpressionParameterAssociation a = _activeAssociationList[k]; TableColumnInfo ci = new TableColumnInfo(); // set the label of the column @@ -233,10 +239,7 @@ private TableHeaderInfo GenerateTableHeaderInfoFromProperties(PSObject so) ci.propertyName = (string)key; } - if (ci.propertyName == null) - { - ci.propertyName = this.activeAssociationList[k].ResolvedExpression.ToString(); - } + ci.propertyName ??= _activeAssociationList[k].ResolvedExpression.ToString(); // set the width of the table if (a.OriginatingParameter != null) @@ -391,10 +394,7 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition == null) - { - matchingRowDefinition = match.BestMatch as TableRowDefinition; - } + matchingRowDefinition ??= match.BestMatch as TableRowDefinition; if (matchingRowDefinition == null) { @@ -412,10 +412,7 @@ private List GetActiveTableRowDefinition(TableControlBod } } - if (matchingRowDefinition == null) - { - matchingRowDefinition = match.BestMatch as TableRowDefinition; - } + matchingRowDefinition ??= match.BestMatch as TableRowDefinition; } } @@ -474,16 +471,22 @@ private TableRowEntry GenerateTableRowEntryFromDataBaseInfo(PSObject so, int enu private TableRowEntry GenerateTableRowEntryFromFromProperties(PSObject so, int enumerationLimit) { TableRowEntry tre = new TableRowEntry(); - for (int k = 0; k < this.activeAssociationList.Count; k++) + for (int k = 0; k < _activeAssociationList.Count; k++) { FormatPropertyField fpf = new FormatPropertyField(); FieldFormattingDirective directive = null; - if (activeAssociationList[k].OriginatingParameter != null) + if (_activeAssociationList[k].OriginatingParameter != null) + { + directive = _activeAssociationList[k].OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; + } + + if (directive is null) { - directive = activeAssociationList[k].OriginatingParameter.GetEntry(FormatParameterDefinitionKeys.FormatStringEntryKey) as FieldFormattingDirective; + directive = new FieldFormattingDirective(); + directive.isTable = true; } - fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, this.activeAssociationList[k].ResolvedExpression, directive); + fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, _activeAssociationList[k].ResolvedExpression, directive); tre.formatPropertyFieldList.Add(fpf); } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs index 26c0af670c7..bfa364cc450 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewGenerator_Wide.cs @@ -13,7 +13,40 @@ internal override void Initialize(TerminatingErrorContext errorContext, PSProper PSObject so, TypeInfoDataBase db, FormattingCommandLineParameters parameters) { base.Initialize(errorContext, expressionFactory, so, db, parameters); - this.inputParameters = parameters; + } + + /// + /// Builds the raw association list for wide formatting. + /// + protected override List BuildRawAssociationList(PSObject so, List propertyList) + { + // check if we received properties from the command line + if (propertyList is not null && propertyList.Count > 0) + { + return AssociationManager.ExpandParameters(propertyList, so); + } + + // we did not get any properties: + // try to get the display property of the object + PSPropertyExpression displayNameExpression = PSObjectHelper.GetDisplayNameExpression(so, this.expressionFactory); + if (displayNameExpression is not null) + { + return new List + { + new MshResolvedExpressionParameterAssociation(null, displayNameExpression) + }; + } + + // try to get the default property set (we will use the first property) + var list = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory); + if (list.Count == 0) + { + // we failed to get anything from the default property set + // just get all the properties + list = AssociationManager.ExpandAll(so); + } + + return list; } internal override FormatStartData GenerateStartData(PSObject so) @@ -130,20 +163,17 @@ private WideControlEntryDefinition GetActiveWideControlEntryDefinition(WideContr private WideViewEntry GenerateWideViewEntryFromProperties(PSObject so, int enumerationLimit) { - // compute active properties every time - if (this.activeAssociationList == null) - { - SetUpActiveProperty(so); - } + // Build active association list (with ExcludeProperty filter applied) + var associationList = BuildActiveAssociationList(so); WideViewEntry wve = new WideViewEntry(); FormatPropertyField fpf = new FormatPropertyField(); wve.formatPropertyField = fpf; - if (this.activeAssociationList.Count > 0) + if (associationList.Count > 0) { // get the first one - MshResolvedExpressionParameterAssociation a = this.activeAssociationList[0]; + MshResolvedExpressionParameterAssociation a = associationList[0]; FieldFormattingDirective directive = null; if (a.OriginatingParameter != null) { @@ -152,46 +182,7 @@ private WideViewEntry GenerateWideViewEntryFromProperties(PSObject so, int enume fpf.propertyValue = this.GetExpressionDisplayValue(so, enumerationLimit, a.ResolvedExpression, directive); } - - this.activeAssociationList = null; return wve; } - - private void SetUpActiveProperty(PSObject so) - { - List rawMshParameterList = null; - - if (this.inputParameters != null) - rawMshParameterList = this.inputParameters.mshParameterList; - - // check if we received properties from the command line - if (rawMshParameterList != null && rawMshParameterList.Count > 0) - { - this.activeAssociationList = AssociationManager.ExpandParameters(rawMshParameterList, so); - return; - } - - // we did not get any properties: - // try to get the display property of the object - PSPropertyExpression displayNameExpression = PSObjectHelper.GetDisplayNameExpression(so, this.expressionFactory); - if (displayNameExpression != null) - { - this.activeAssociationList = new List(); - this.activeAssociationList.Add(new MshResolvedExpressionParameterAssociation(null, displayNameExpression)); - return; - } - - // try to get the default property set (we will use the first property) - this.activeAssociationList = AssociationManager.ExpandDefaultPropertySet(so, this.expressionFactory); - if (this.activeAssociationList.Count > 0) - { - // we got a valid set of properties from the default property set - return; - } - - // we failed to get anything from the default property set - // just get all the properties - this.activeAssociationList = AssociationManager.ExpandAll(so); - } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs index 0737e43476e..891dfce6829 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatViewManager.cs @@ -646,8 +646,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) { ErrorRecord errorRecord = null; string msg = null; - PSPropertyExpressionError psPropertyExpressionError = error as PSPropertyExpressionError; - if (psPropertyExpressionError != null) + if (error is PSPropertyExpressionError psPropertyExpressionError) { errorRecord = new ErrorRecord( psPropertyExpressionError.result.Exception, @@ -660,8 +659,7 @@ private static ErrorRecord GenerateErrorRecord(FormattingError error) errorRecord.ErrorDetails = new ErrorDetails(msg); } - StringFormatError formattingError = error as StringFormatError; - if (formattingError != null) + if (error is StringFormatError formattingError) { errorRecord = new ErrorRecord( formattingError.exception, diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs index bb2c8ff93e7..c8b077918fe 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormatXMLWriter.cs @@ -13,7 +13,7 @@ namespace Microsoft.PowerShell.Commands /// /// Helper class for writing formatting directives to XML. /// - internal class FormatXmlWriter + internal sealed class FormatXmlWriter { private XmlWriter _writer; private bool _exportScriptBlock; @@ -385,8 +385,7 @@ internal void WriteCustomControl(CustomControl customControl) internal void WriteCustomItem(CustomItemBase item) { - var newline = item as CustomItemNewline; - if (newline != null) + if (item is CustomItemNewline newline) { for (int i = 0; i < newline.Count; i++) { @@ -396,15 +395,13 @@ internal void WriteCustomItem(CustomItemBase item) return; } - var text = item as CustomItemText; - if (text != null) + if (item is CustomItemText text) { _writer.WriteElementString("Text", text.Text); return; } - var expr = item as CustomItemExpression; - if (expr != null) + if (item is CustomItemExpression expr) { _writer.WriteStartElement("ExpressionBinding"); if (expr.EnumerateCollection) diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs index f4ac55d1feb..4af1ee54d81 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjects.cs @@ -18,7 +18,7 @@ // representation that mig have been introduced by serialization. // // There is also the need to preserve type information across serialization -// boundaries, therefore the objects provide a GUID based machanism to +// boundaries, therefore the objects provide a GUID based mechanism to // preserve the information. // @@ -207,6 +207,7 @@ internal sealed partial class TableColumnInfo : FormatInfoData public int alignment = TextAlignment.Left; public string label = null; public string propertyName = null; + public bool HeaderMatchesProperty = true; } internal sealed class ListViewHeaderInfo : ShapeInfo diff --git a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs index 285e4d4c02b..7ae144702ba 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/FormattingObjectsDeserializer.cs @@ -30,8 +30,7 @@ internal FormatObjectDeserializer(TerminatingErrorContext errorContext) internal bool IsFormatInfoData(PSObject so) { - var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (PSObject.Base(so) is FormatInfoData fid) { if (fid is FormatStartData || fid is FormatEndData || @@ -55,7 +54,7 @@ fid is GroupEndData || return false; } - if (!(GetProperty(so, FormatInfoData.classidProperty) is string classId)) + if (GetProperty(so, FormatInfoData.classidProperty) is not string classId) { // it's not one of the objects derived from FormatInfoData return false; @@ -86,8 +85,7 @@ fid is GroupEndData || /// Deserialized object or null. internal object Deserialize(PSObject so) { - var fid = PSObject.Base(so) as FormatInfoData; - if (fid != null) + if (PSObject.Base(so) is FormatInfoData fid) { if (fid is FormatStartData || fid is FormatEndData || @@ -111,7 +109,7 @@ fid is GroupEndData || return so; } - if (!(GetProperty(so, FormatInfoData.classidProperty) is string classId)) + if (GetProperty(so, FormatInfoData.classidProperty) is not string classId) { // it's not one of the objects derived from FormatInfoData, // just return it as is @@ -325,9 +323,7 @@ internal WriteStreamType DeserializeWriteStreamTypeMemberVariable(PSObject so) internal FormatInfoData DeserializeObject(PSObject so) { FormatInfoData fid = FormatInfoDataClassFactory.CreateInstance(so, this); - - if (fid != null) - fid.Deserialize(so, this); + fid?.Deserialize(so, this); return fid; } @@ -355,31 +351,31 @@ static FormatInfoDataClassFactory() { s_constructors = new Dictionary> { - {FormatStartData.CLSID, () => new FormatStartData()}, - {FormatEndData.CLSID, () => new FormatEndData()}, - {GroupStartData.CLSID, () => new GroupStartData()}, - {GroupEndData.CLSID, () => new GroupEndData()}, - {FormatEntryData.CLSID, () => new FormatEntryData()}, - {WideViewHeaderInfo.CLSID, () => new WideViewHeaderInfo()}, - {TableHeaderInfo.CLSID, () => new TableHeaderInfo()}, - {TableColumnInfo.CLSID, () => new TableColumnInfo()}, - {ListViewHeaderInfo.CLSID, () => new ListViewHeaderInfo()}, - {ListViewEntry.CLSID, () => new ListViewEntry()}, - {ListViewField.CLSID, () => new ListViewField()}, - {TableRowEntry.CLSID, () => new TableRowEntry()}, - {WideViewEntry.CLSID, () => new WideViewEntry()}, - {ComplexViewHeaderInfo.CLSID, () => new ComplexViewHeaderInfo()}, - {ComplexViewEntry.CLSID, () => new ComplexViewEntry()}, - {GroupingEntry.CLSID, () => new GroupingEntry()}, - {PageHeaderEntry.CLSID, () => new PageHeaderEntry()}, - {PageFooterEntry.CLSID, () => new PageFooterEntry()}, - {AutosizeInfo.CLSID, () => new AutosizeInfo()}, - {FormatNewLine.CLSID, () => new FormatNewLine()}, - {FrameInfo.CLSID, () => new FrameInfo()}, - {FormatTextField.CLSID, () => new FormatTextField()}, - {FormatPropertyField.CLSID, () => new FormatPropertyField()}, - {FormatEntry.CLSID, () => new FormatEntry()}, - {RawTextFormatEntry.CLSID, () => new RawTextFormatEntry()} + {FormatStartData.CLSID, static () => new FormatStartData()}, + {FormatEndData.CLSID, static () => new FormatEndData()}, + {GroupStartData.CLSID, static () => new GroupStartData()}, + {GroupEndData.CLSID, static () => new GroupEndData()}, + {FormatEntryData.CLSID, static () => new FormatEntryData()}, + {WideViewHeaderInfo.CLSID, static () => new WideViewHeaderInfo()}, + {TableHeaderInfo.CLSID, static () => new TableHeaderInfo()}, + {TableColumnInfo.CLSID, static () => new TableColumnInfo()}, + {ListViewHeaderInfo.CLSID, static () => new ListViewHeaderInfo()}, + {ListViewEntry.CLSID, static () => new ListViewEntry()}, + {ListViewField.CLSID, static () => new ListViewField()}, + {TableRowEntry.CLSID, static () => new TableRowEntry()}, + {WideViewEntry.CLSID, static () => new WideViewEntry()}, + {ComplexViewHeaderInfo.CLSID, static () => new ComplexViewHeaderInfo()}, + {ComplexViewEntry.CLSID, static () => new ComplexViewEntry()}, + {GroupingEntry.CLSID, static () => new GroupingEntry()}, + {PageHeaderEntry.CLSID, static () => new PageHeaderEntry()}, + {PageFooterEntry.CLSID, static () => new PageFooterEntry()}, + {AutosizeInfo.CLSID, static () => new AutosizeInfo()}, + {FormatNewLine.CLSID, static () => new FormatNewLine()}, + {FrameInfo.CLSID, static () => new FrameInfo()}, + {FormatTextField.CLSID, static () => new FormatTextField()}, + {FormatPropertyField.CLSID, static () => new FormatPropertyField()}, + {FormatEntry.CLSID, static () => new FormatEntry()}, + {RawTextFormatEntry.CLSID, static () => new RawTextFormatEntry()} }; } diff --git a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs index 32d4565da5d..7bca25ea828 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ILineOutput.cs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections.Generic; using System.Globalization; using System.IO; using System.Management.Automation; +using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Text; @@ -13,60 +15,112 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { /// /// Base class providing support for string manipulation. - /// This class is a tear off class provided by the LineOutput class - /// - /// Assumptions (in addition to the assumptions made for LineOutput): - /// - characters map to one or more character cells - /// - /// NOTE: we provide a base class that is valid for devices that have a - /// 1:1 mapping between a UNICODE character and a display cell. + /// This class is a tear off class provided by the LineOutput class. /// internal class DisplayCells { - internal virtual int Length(string str) + /// + /// Calculate the buffer cell length of the given string. + /// + /// String that may contain VT escape sequences. + /// Number of buffer cells the string needs to take. + internal int Length(string str) { return Length(str, 0); } + /// + /// Calculate the buffer cell length of the given string. + /// + /// String that may contain VT escape sequences. + /// + /// When the string doesn't contain VT sequences, it's the starting index. + /// When the string contains VT sequences, it means starting from the 'n-th' char that doesn't belong to a escape sequence. + /// Number of buffer cells the string needs to take. internal virtual int Length(string str, int offset) { - int length = 0; + if (string.IsNullOrEmpty(str)) + { + return 0; + } - foreach (char c in str) + var valueStrDec = new ValueStringDecorated(str); + if (valueStrDec.IsDecorated) { - length += LengthInBufferCells(c); + str = valueStrDec.ToString(OutputRendering.PlainText); } - return length - offset; - } + int length = 0; + for (; offset < str.Length; offset++) + { + length += CharLengthInBufferCells(str[offset]); + } - internal virtual int Length(char character) { return 1; } + return length; + } - internal virtual int GetHeadSplitLength(string str, int displayCells) + /// + /// Calculate the buffer cell length of the given character. + /// + /// + /// Number of buffer cells the character needs to take. + internal virtual int Length(char character) { - return GetHeadSplitLength(str, 0, displayCells); + return CharLengthInBufferCells(character); } - internal virtual int GetHeadSplitLength(string str, int offset, int displayCells) + /// + /// Truncate from the tail of the string. + /// + /// String that may contain VT escape sequences. + /// Number of buffer cells to fit in. + /// Number of non-escape-sequence characters from head of the string that can fit in the space. + internal int TruncateTail(string str, int displayCells) { - int len = str.Length - offset; - return (len < displayCells) ? len : displayCells; + return TruncateTail(str, offset: 0, displayCells); } - internal virtual int GetTailSplitLength(string str, int displayCells) + /// + /// Truncate from the tail of the string. + /// + /// String that may contain VT escape sequences. + /// + /// When the string doesn't contain VT sequences, it's the starting index. + /// When the string contains VT sequences, it means starting from the 'n-th' char that doesn't belong to a escape sequence. + /// Number of buffer cells to fit in. + /// Number of non-escape-sequence characters from head of the string that can fit in the space. + internal int TruncateTail(string str, int offset, int displayCells) { - return GetTailSplitLength(str, 0, displayCells); + var valueStrDec = new ValueStringDecorated(str); + if (valueStrDec.IsDecorated) + { + str = valueStrDec.ToString(OutputRendering.PlainText); + } + + return GetFitLength(str, offset, displayCells, startFromHead: true); } - internal virtual int GetTailSplitLength(string str, int offset, int displayCells) + /// + /// Truncate from the head of the string. + /// + /// String that may contain VT escape sequences. + /// Number of buffer cells to fit in. + /// Number of non-escape-sequence characters from head of the string that should be skipped. + internal int TruncateHead(string str, int displayCells) { - int len = str.Length - offset; - return (len < displayCells) ? len : displayCells; + var valueStrDec = new ValueStringDecorated(str); + if (valueStrDec.IsDecorated) + { + str = valueStrDec.ToString(OutputRendering.PlainText); + } + + int tailCount = GetFitLength(str, offset: 0, displayCells, startFromHead: false); + return str.Length - tailCount; } #region Helpers - protected static int LengthInBufferCells(char c) + protected static int CharLengthInBufferCells(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 @@ -83,7 +137,7 @@ protected static int LengthInBufferCells(char c) ((uint)(c - 0xffe0) <= (0xffe6 - 0xffe0))); // We can ignore these ranges because .Net strings use surrogate pairs - // for this range and we do not handle surrogage pairs. + // for this range and we do not handle surrogate pairs. // (c >= 0x20000 && c <= 0x2fffd) || // (c >= 0x30000 && c <= 0x3fffd) return 1 + (isWide ? 1 : 0); @@ -93,25 +147,26 @@ protected static int LengthInBufferCells(char c) /// Given a string and a number of display cells, it computes how many /// characters would fit starting from the beginning or end of the string. /// - /// String to be displayed. + /// String to be displayed, which doesn't contain any VT sequences. /// Offset inside the string. /// Number of display cells. - /// If true compute from the head (i.e. k++) else from the tail (i.e. k--). + /// If true compute from the head (i.e. k++) else from the tail (i.e. k--). /// Number of characters that would fit. - protected int GetSplitLengthInternalHelper(string str, int offset, int displayCells, bool head) + protected int GetFitLength(string str, int offset, int displayCells, bool startFromHead) { int filledDisplayCellsCount = 0; // number of cells that are filled in int charactersAdded = 0; // number of characters that fit int currCharDisplayLen; // scratch variable - int k = (head) ? offset : str.Length - 1; - int kFinal = (head) ? str.Length - 1 : offset; + int k = startFromHead ? offset : str.Length - 1; + int kFinal = startFromHead ? str.Length - 1 : offset; while (true) { - if ((head && (k > kFinal)) || ((!head) && (k < kFinal))) + if ((startFromHead && k > kFinal) || (!startFromHead && k < kFinal)) { break; } + // compute the cell number for the current character currCharDisplayLen = this.Length(str[k]); @@ -120,6 +175,7 @@ protected int GetSplitLengthInternalHelper(string str, int offset, int displayCe // if we added this character it would not fit, we cannot continue break; } + // keep adding, we fit filledDisplayCellsCount += currCharDisplayLen; charactersAdded++; @@ -131,13 +187,13 @@ protected int GetSplitLengthInternalHelper(string str, int offset, int displayCe break; } - k = (head) ? (k + 1) : (k - 1); + k = startFromHead ? (k + 1) : (k - 1); } return charactersAdded; } - #endregion + #endregion } /// @@ -194,6 +250,13 @@ internal virtual void ExecuteBufferPlayBack(DoPlayBackCall playback) { } /// internal abstract void WriteLine(string s); + /// + /// Write a line of string as raw text to the output device, with no change to the string. + /// For example, keeping VT escape sequences intact in it. + /// + /// The raw text to be written to the device. + internal virtual void WriteRawText(string s) => WriteLine(s); + internal WriteStreamType WriteStream { get; @@ -324,10 +387,10 @@ private void WriteLineInternal(string val, int cols) } // check for line breaks - string[] lines = StringManipulationHelper.SplitLines(val); + List lines = StringManipulationHelper.SplitLines(val); // process the substrings as separate lines - for (int k = 0; k < lines.Length; k++) + for (int k = 0; k < lines.Count; k++) { // compute the display length of the string int displayLength = _displayCells.Length(lines[k]); @@ -353,11 +416,11 @@ private void WriteLineInternal(string val, int cols) { // the string is still too long to fit, write the first cols characters // and go back for more wraparound - int splitLen = _displayCells.GetHeadSplitLength(s, cols); - WriteLineInternal(s.Substring(0, splitLen), cols); + int headCount = _displayCells.TruncateTail(s, cols); + WriteLineInternal(s.VtSubstring(0, headCount), cols); // chop off the first fieldWidth characters, already printed - s = s.Substring(splitLen); + s = s.VtSubstring(headCount); if (_displayCells.Length(s) <= cols) { // if we fit, print the tail of the string and we are done @@ -375,7 +438,7 @@ private void WriteLineInternal(string val, int cols) /// Implementation of the ILineOutput interface accepting an instance of a /// TextWriter abstract class. /// - internal class TextWriterLineOutput : LineOutput + internal sealed class TextWriterLineOutput : LineOutput { #region ILineOutput methods @@ -411,9 +474,17 @@ internal override int RowNumber /// internal override void WriteLine(string s) { - CheckStopProcessing(); + WriteRawText(PSHostUserInterface.GetOutputString(s, isHost: false)); + } - s = Utils.GetOutputString(s, isHost: false); + /// + /// 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(); if (_suppressNewline) { @@ -424,6 +495,7 @@ internal override void WriteLine(string s) _writer.WriteLine(s); } } + #endregion /// diff --git a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs index 91a7b8698a6..988b1133748 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/ListWriter.cs @@ -2,9 +2,12 @@ // Licensed under the MIT License. using System; +using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; +using System.Management.Automation; using System.Management.Automation.Internal; +using System.Text; namespace Microsoft.PowerShell.Commands.Internal.Format { @@ -29,6 +32,11 @@ internal class ListWriter /// private int _columnWidth = 0; + /// + /// A cached string builder used within this type to reduce creation of temporary strings. + /// + private readonly StringBuilder _cachedBuilder = new(); + /// /// /// Names of the properties to display. @@ -59,6 +67,10 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC // check if we have to truncate the labels int maxAllowableLabelLength = screenColumnWidth - Separator.Length - MinFieldWidth; + if (InternalTestHooks.ForceFormatListFixedLabelWidth) + { + maxAllowableLabelLength = 10; + } // find out the max display length (cell count) of the property names _propertyLabelsDisplayLength = 0; // reset max @@ -83,19 +95,20 @@ internal void Initialize(string[] propertyNames, int screenColumnWidth, DisplayC for (int k = 0; k < propertyNames.Length; k++) { + string propertyName = propertyNames[k]; if (propertyNameCellCounts[k] < _propertyLabelsDisplayLength) { // shorter than the max, add padding - _propertyLabels[k] = propertyNames[k] + StringUtil.Padding(_propertyLabelsDisplayLength - propertyNameCellCounts[k]); + _propertyLabels[k] = propertyName + StringUtil.Padding(_propertyLabelsDisplayLength - propertyNameCellCounts[k]); } else if (propertyNameCellCounts[k] > _propertyLabelsDisplayLength) { // longer than the max, clip - _propertyLabels[k] = propertyNames[k].Substring(0, dc.GetHeadSplitLength(propertyNames[k], _propertyLabelsDisplayLength)); + _propertyLabels[k] = propertyName.VtSubstring(0, dc.TruncateTail(propertyName, _propertyLabelsDisplayLength)); } else { - _propertyLabels[k] = propertyNames[k]; + _propertyLabels[k] = propertyName; } _propertyLabels[k] += Separator; @@ -164,16 +177,15 @@ internal void WriteProperties(string[] values, LineOutput lo) /// LineOutput interface to write to. private void WriteProperty(int k, string propertyValue, LineOutput lo) { - if (propertyValue == null) - propertyValue = string.Empty; + propertyValue ??= string.Empty; // make sure we honor embedded newlines - string[] lines = StringManipulationHelper.SplitLines(propertyValue); + List lines = StringManipulationHelper.SplitLines(propertyValue); // padding to use in the lines after the first string padding = null; - for (int i = 0; i < lines.Length; i++) + for (int i = 0; i < lines.Count; i++) { string prependString = null; @@ -181,8 +193,7 @@ private void WriteProperty(int k, string propertyValue, LineOutput lo) prependString = _propertyLabels[k]; else { - if (padding == null) - padding = StringUtil.Padding(_propertyLabelsDisplayLength); + padding ??= StringUtil.Padding(_propertyLabelsDisplayLength); prependString = padding; } @@ -197,11 +208,10 @@ private void WriteProperty(int k, string propertyValue, LineOutput lo) /// /// String to add to the left. /// Line to print. - /// LineOuput to write to. + /// LineOutput to write to. private void WriteSingleLineHelper(string prependString, string line, LineOutput lo) { - if (line == null) - line = string.Empty; + line ??= string.Empty; // compute the width of the field for the value string (in screen cells) int fieldCellCount = _columnWidth - _propertyLabelsDisplayLength; @@ -209,20 +219,52 @@ private void WriteSingleLineHelper(string prependString, string line, LineOutput // split the lines StringCollection sc = StringManipulationHelper.GenerateLines(lo.DisplayCells, line, fieldCellCount, fieldCellCount); - // padding to use in the lines after the first - string padding = StringUtil.Padding(_propertyLabelsDisplayLength); + // The padding to use in the lines after the first. + string headPadding = null; + + // The VT style used for the list label. + string style = PSStyle.Instance.Formatting.FormatAccent; + string reset = PSStyle.Instance.Reset; // display the string collection for (int k = 0; k < sc.Count; k++) { + string str = sc[k]; + _cachedBuilder.Clear(); + if (k == 0) { - lo.WriteLine(prependString + sc[k]); + if (string.IsNullOrWhiteSpace(prependString) || style == string.Empty) + { + // - Sometimes 'prependString' is just padding white spaces, and we don't + // need to add formatting escape sequences in such a case. + // - Otherwise, if the style is an empty string, then the user has chosen + // to not apply a style to the list label. + _cachedBuilder.Append(prependString).Append(str); + } + else + { + // Apply the style to the list label. + _cachedBuilder + .Append(style) + .Append(prependString) + .Append(reset) + .Append(str); + } } else { - lo.WriteLine(padding + sc[k]); + // Lazily calculate the padding to use for the subsequent lines as it's quite often that only the first line exists. + headPadding ??= StringUtil.Padding(_propertyLabelsDisplayLength); + _cachedBuilder.Append(headPadding).Append(str); + } + + if (str.Contains(ValueStringDecorated.ESC) && !str.AsSpan().TrimEnd().EndsWith(reset, StringComparison.Ordinal)) + { + _cachedBuilder.Append(reset); } + + lo.WriteLine(_cachedBuilder.ToString()); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs index 41ea611f198..a551ef89bed 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputManager.cs @@ -92,19 +92,14 @@ internal override void ProcessRecord() internal override void EndProcessing() { // shut down only if we ever processed a pipeline object - if (_mgr != null) - _mgr.ShutDown(); + _mgr?.ShutDown(); } internal override void StopProcessing() { lock (_syncRoot) { - if (_lo != null) - { - _lo.StopProcessing(); - } - + _lo?.StopProcessing(); _isStopped = true; } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs index 1909b03939c..333b0b42689 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/OutputQueue.cs @@ -43,8 +43,7 @@ internal OutputGroupQueue(FormattedObjectsCache.ProcessCachedGroupNotification c /// Objects the cache needs to return. It can be null. internal List Add(PacketInfoData o) { - FormatStartData fsd = o as FormatStartData; - if (fsd != null) + if (o is FormatStartData fsd) { // just cache the reference (used during the notification call) _formatStartData = fsd; @@ -120,12 +119,10 @@ private void UpdateObjectCount(PacketInfoData o) { // add only of it's not a control message // and it's not out of band - FormatEntryData fed = o as FormatEntryData; - - if (fed == null || fed.outOfBand) - return; - - _currentObjectCount++; + if (o is FormatEntryData fed && !fed.outOfBand) + { + _currentObjectCount++; + } } private void Notify() @@ -139,8 +136,7 @@ private void Notify() foreach (PacketInfoData x in _queue) { - FormatEntryData fed = x as FormatEntryData; - if (fed != null && fed.outOfBand) + if (x is FormatEntryData fed && fed.outOfBand) continue; validObjects.Add(x); diff --git a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs index b8e1890b37f..534f9541195 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/PSStyle.cs @@ -1,6 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation.Internal; + namespace System.Management.Automation { #region OutputRendering @@ -9,17 +13,14 @@ namespace System.Management.Automation /// public enum OutputRendering { - /// Automatic by PowerShell. - Automatic = 0, + /// Render ANSI only to host. + Host = 0, /// Render as plaintext. PlainText = 1, /// Render as ANSI. Ansi = 2, - - /// Render ANSI only to host. - Host = 3, } #endregion OutputRendering @@ -52,79 +53,79 @@ public sealed class ForegroundColor public string Black { get; } = "\x1b[30m"; /// - /// Gets the color blue. + /// Gets the color red. /// - public string Blue { get; } = "\x1b[34m"; + public string Red { get; } = "\x1b[31m"; /// - /// Gets the color cyan. + /// Gets the color green. /// - public string Cyan { get; } = "\x1b[36m"; + public string Green { get; } = "\x1b[32m"; /// - /// Gets the color dark gray. + /// Gets the color yellow. /// - public string DarkGray { get; } = "\x1b[90m"; + public string Yellow { get; } = "\x1b[33m"; /// - /// Gets the color green. + /// Gets the color blue. /// - public string Green { get; } = "\x1b[32m"; + public string Blue { get; } = "\x1b[34m"; /// - /// Gets the color light blue. + /// Gets the color magenta. /// - public string LightBlue { get; } = "\x1b[94m"; + public string Magenta { get; } = "\x1b[35m"; /// - /// Gets the color light cyan. + /// Gets the color cyan. /// - public string LightCyan { get; } = "\x1b[96m"; + public string Cyan { get; } = "\x1b[36m"; /// - /// Gets the color light gray. + /// Gets the color white. /// - public string LightGray { get; } = "\x1b[97m"; + public string White { get; } = "\x1b[37m"; /// - /// Gets the color light green. + /// Gets the color bright black. /// - public string LightGreen { get; } = "\x1b[92m"; + public string BrightBlack { get; } = "\x1b[90m"; /// - /// Gets the color light magenta. + /// Gets the color bright red. /// - public string LightMagenta { get; } = "\x1b[95m"; + public string BrightRed { get; } = "\x1b[91m"; /// - /// Gets the color light red. + /// Gets the color bright green. /// - public string LightRed { get; } = "\x1b[91m"; + public string BrightGreen { get; } = "\x1b[92m"; /// - /// Gets the color light yellow. + /// Gets the color bright yellow. /// - public string LightYellow { get; } = "\x1b[93m"; + public string BrightYellow { get; } = "\x1b[93m"; /// - /// Gets the color magenta. + /// Gets the color bright blue. /// - public string Magenta { get; } = "\x1b[35m"; + public string BrightBlue { get; } = "\x1b[94m"; /// - /// Gets the color read. + /// Gets the color bright magenta. /// - public string Red { get; } = "\x1b[31m"; + public string BrightMagenta { get; } = "\x1b[95m"; /// - /// Gets the color white. + /// Gets the color bright cyan. /// - public string White { get; } = "\x1b[37m"; + public string BrightCyan { get; } = "\x1b[96m"; /// - /// Gets the color yellow. + /// Gets the color bright white. /// - public string Yellow { get; } = "\x1b[33m"; + public string BrightWhite { get; } = "\x1b[97m"; /// /// Set as RGB (Red, Green, Blue). @@ -154,6 +155,16 @@ public string FromRgb(int rgb) return FromRgb(red, green, blue); } + + /// + /// Return the VT escape sequence for a foreground color. + /// + /// The foreground color to be mapped from. + /// The VT escape sequence representing the foreground color. + public string FromConsoleColor(ConsoleColor color) + { + return MapForegroundColorToEscapeSequence(color); + } } /// @@ -167,79 +178,79 @@ public sealed class BackgroundColor public string Black { get; } = "\x1b[40m"; /// - /// Gets the color blue. + /// Gets the color red. /// - public string Blue { get; } = "\x1b[44m"; + public string Red { get; } = "\x1b[41m"; /// - /// Gets the color cyan. + /// Gets the color green. /// - public string Cyan { get; } = "\x1b[46m"; + public string Green { get; } = "\x1b[42m"; /// - /// Gets the color dark gray. + /// Gets the color yellow. /// - public string DarkGray { get; } = "\x1b[100m"; + public string Yellow { get; } = "\x1b[43m"; /// - /// Gets the color green. + /// Gets the color blue. /// - public string Green { get; } = "\x1b[42m"; + public string Blue { get; } = "\x1b[44m"; /// - /// Gets the color light blue. + /// Gets the color magenta. /// - public string LightBlue { get; } = "\x1b[104m"; + public string Magenta { get; } = "\x1b[45m"; /// - /// Gets the color light cyan. + /// Gets the color cyan. /// - public string LightCyan { get; } = "\x1b[106m"; + public string Cyan { get; } = "\x1b[46m"; /// - /// Gets the color light gray. + /// Gets the color white. /// - public string LightGray { get; } = "\x1b[107m"; + public string White { get; } = "\x1b[47m"; /// - /// Gets the color light green. + /// Gets the color bright black. /// - public string LightGreen { get; } = "\x1b[102m"; + public string BrightBlack { get; } = "\x1b[100m"; /// - /// Gets the color light magenta. + /// Gets the color bright red. /// - public string LightMagenta { get; } = "\x1b[105m"; + public string BrightRed { get; } = "\x1b[101m"; /// - /// Gets the color light red. + /// Gets the color bright green. /// - public string LightRed { get; } = "\x1b[101m"; + public string BrightGreen { get; } = "\x1b[102m"; /// - /// Gets the color light yellow. + /// Gets the color bright yellow. /// - public string LightYellow { get; } = "\x1b[103m"; + public string BrightYellow { get; } = "\x1b[103m"; /// - /// Gets the color magenta. + /// Gets the color bright blue. /// - public string Magenta { get; } = "\x1b[45m"; + public string BrightBlue { get; } = "\x1b[104m"; /// - /// Gets the color read. + /// Gets the color bright magenta. /// - public string Red { get; } = "\x1b[41m"; + public string BrightMagenta { get; } = "\x1b[105m"; /// - /// Gets the color white. + /// Gets the color bright cyan. /// - public string White { get; } = "\x1b[47m"; + public string BrightCyan { get; } = "\x1b[106m"; /// - /// Gets the color yellow. + /// Gets the color bright white. /// - public string Yellow { get; } = "\x1b[43m"; + public string BrightWhite { get; } = "\x1b[107m"; /// /// The color set as RGB (Red, Green, Blue). @@ -269,6 +280,16 @@ public string FromRgb(int rgb) return FromRgb(red, green, blue); } + + /// + /// Return the VT escape sequence for a background color. + /// + /// The background color to be mapped from. + /// The VT escape sequence representing the background color. + public string FromConsoleColor(ConsoleColor color) + { + return MapBackgroundColorToEscapeSequence(color); + } } /// @@ -279,12 +300,33 @@ public sealed class ProgressConfiguration /// /// Gets or sets the style for progress bar. /// - public string Style { get; set; } = "\x1b[33;1m"; + public string Style + { + get => _style; + set => _style = ValidateNoContent(value); + } + + private string _style = "\x1b[33;1m"; /// /// Gets or sets the max width of the progress bar. /// - public int MaxWidth { get; set; } = 120; + public int MaxWidth + { + get => _maxWidth; + set + { + // Width less than 18 does not render correctly due to the different parts of the progress bar. + if (value < 18) + { + throw new ArgumentOutOfRangeException(nameof(MaxWidth), PSStyleStrings.ProgressWidthTooSmall); + } + + _maxWidth = value; + } + } + + private int _maxWidth = 120; /// /// Gets or sets the view for progress bar. @@ -305,38 +347,299 @@ public sealed class FormattingData /// /// Gets or sets the accent style for formatting. /// - public string FormatAccent { get; set; } = "\x1b[32;1m"; + public string FormatAccent + { + get => _formatAccent; + set => _formatAccent = ValidateNoContent(value); + } + + private string _formatAccent = "\x1b[32;1m"; + + /// + /// Gets or sets the style for table headers. + /// + public string TableHeader + { + get => _tableHeader; + set => _tableHeader = ValidateNoContent(value); + } + + private string _tableHeader = "\x1b[32;1m"; + + /// + /// Gets or sets the style for custom table headers. + /// + public string CustomTableHeaderLabel + { + get => _customTableHeaderLabel; + set => _customTableHeaderLabel = ValidateNoContent(value); + } + + private string _customTableHeaderLabel = "\x1b[32;1;3m"; /// /// Gets or sets the accent style for errors. /// - public string ErrorAccent { get; set; } = "\x1b[36;1m"; + public string ErrorAccent + { + get => _errorAccent; + set => _errorAccent = ValidateNoContent(value); + } + + private string _errorAccent = "\x1b[36;1m"; /// /// Gets or sets the style for error messages. /// - public string Error { get; set; } = "\x1b[31;1m"; + public string Error + { + get => _error; + set => _error = ValidateNoContent(value); + } + + private string _error = "\x1b[31;1m"; /// /// Gets or sets the style for warning messages. /// - public string Warning { get; set; } = "\x1b[33;1m"; + public string Warning + { + get => _warning; + set => _warning = ValidateNoContent(value); + } + + private string _warning = "\x1b[33;1m"; /// /// Gets or sets the style for verbose messages. /// - public string Verbose { get; set; } = "\x1b[33;1m"; + public string Verbose + { + get => _verbose; + set => _verbose = ValidateNoContent(value); + } + + private string _verbose = "\x1b[33;1m"; /// /// Gets or sets the style for debug messages. /// - public string Debug { get; set; } = "\x1b[33;1m"; + public string Debug + { + get => _debug; + set => _debug = ValidateNoContent(value); + } + + private string _debug = "\x1b[33;1m"; + + /// + /// Gets or sets the style for rendering feedback provider names. + /// + public string FeedbackName + { + get => _feedbackName; + set => _feedbackName = ValidateNoContent(value); + } + + // Yellow by default. + private string _feedbackName = "\x1b[33m"; + + /// + /// Gets or sets the style for rendering feedback message. + /// + public string FeedbackText + { + get => _feedbackText; + set => _feedbackText = ValidateNoContent(value); + } + + // BrightCyan by default. + private string _feedbackText = "\x1b[96m"; + + /// + /// Gets or sets the style for rendering feedback actions. + /// + public string FeedbackAction + { + get => _feedbackAction; + set => _feedbackAction = ValidateNoContent(value); + } + + // BrightWhite by default. + private string _feedbackAction = "\x1b[97m"; + } + + /// + /// Contains formatting styles for FileInfo objects. + /// + public sealed class FileInfoFormatting + { + /// + /// Gets or sets the style for directories. + /// + public string Directory + { + get => _directory; + set => _directory = ValidateNoContent(value); + } + + private string _directory = "\x1b[44;1m"; + + /// + /// Gets or sets the style for symbolic links. + /// + public string SymbolicLink + { + get => _symbolicLink; + set => _symbolicLink = ValidateNoContent(value); + } + + private string _symbolicLink = "\x1b[36;1m"; + + /// + /// Gets or sets the style for executables. + /// + public string Executable + { + get => _executable; + set => _executable = ValidateNoContent(value); + } + + private string _executable = "\x1b[32;1m"; + + /// + /// Custom dictionary handling validation of extension and content. + /// + public sealed class FileExtensionDictionary + { + private static string ValidateExtension(string extension) + { + if (!extension.StartsWith('.')) + { + throw new ArgumentException(PSStyleStrings.ExtensionNotStartingWithPeriod); + } + + return extension; + } + + private readonly Dictionary _extensionDictionary = new(StringComparer.OrdinalIgnoreCase); + + /// + /// Add new extension and decoration to dictionary. + /// + /// Extension to add. + /// ANSI string value to add. + public void Add(string extension, string decoration) + { + _extensionDictionary.Add(ValidateExtension(extension), ValidateNoContent(decoration)); + } + + /// + /// Add new extension and decoration to dictionary without validation. + /// + /// Extension to add. + /// ANSI string value to add. + internal void AddWithoutValidation(string extension, string decoration) + { + _extensionDictionary.Add(extension, decoration); + } + + /// + /// Remove an extension from dictionary. + /// + /// Extension to remove. + public void Remove(string extension) + { + _extensionDictionary.Remove(ValidateExtension(extension)); + } + + /// + /// Clear the dictionary. + /// + public void Clear() + { + _extensionDictionary.Clear(); + } + + /// + /// Gets or sets the decoration by specified extension. + /// + /// Extension to get decoration for. + /// The decoration for specified extension. + public string this[string extension] + { + get + { + return _extensionDictionary[ValidateExtension(extension)]; + } + + set + { + _extensionDictionary[ValidateExtension(extension)] = ValidateNoContent(value); + } + } + + /// + /// Gets whether the dictionary contains the specified extension. + /// + /// Extension to check for. + /// True if the dictionary contains the specified extension, otherwise false. + public bool ContainsKey(string extension) + { + if (string.IsNullOrEmpty(extension)) + { + return false; + } + + return _extensionDictionary.ContainsKey(ValidateExtension(extension)); + } + + /// + /// Gets the extensions for the dictionary. + /// + /// The extensions for the dictionary. + public IEnumerable Keys + { + get + { + return _extensionDictionary.Keys; + } + } + } + + /// + /// Gets the style for archive. + /// + public FileExtensionDictionary Extension { get; } + + /// + /// Initializes a new instance of the class. + /// + public FileInfoFormatting() + { + Extension = new FileExtensionDictionary(); + + // archives + Extension.AddWithoutValidation(".zip", "\x1b[31;1m"); + Extension.AddWithoutValidation(".tgz", "\x1b[31;1m"); + Extension.AddWithoutValidation(".gz", "\x1b[31;1m"); + Extension.AddWithoutValidation(".tar", "\x1b[31;1m"); + Extension.AddWithoutValidation(".nupkg", "\x1b[31;1m"); + Extension.AddWithoutValidation(".cab", "\x1b[31;1m"); + Extension.AddWithoutValidation(".7z", "\x1b[31;1m"); + + // powershell + Extension.AddWithoutValidation(".ps1", "\x1b[33;1m"); + Extension.AddWithoutValidation(".psd1", "\x1b[33;1m"); + Extension.AddWithoutValidation(".psm1", "\x1b[33;1m"); + Extension.AddWithoutValidation(".ps1xml", "\x1b[33;1m"); + } } /// /// Gets or sets the rendering mode for output. /// - public OutputRendering OutputRendering { get; set; } = OutputRendering.Automatic; + public OutputRendering OutputRendering { get; set; } = OutputRendering.Host; /// /// Gets value to turn off all attributes. @@ -363,6 +666,16 @@ public sealed class FormattingData /// public string Bold { get; } = "\x1b[1m"; + /// + /// Gets value to turn off dim. + /// + public string DimOff { get; } = "\x1b[22m"; + + /// + /// Gets value to turn on dim. + /// + public string Dim { get; } = "\x1b[2m"; + /// /// Gets value to turn on hidden. /// @@ -444,6 +757,11 @@ public string FormatHyperlink(string text, Uri link) /// public BackgroundColor Background { get; } + /// + /// Gets FileInfo colors. + /// + public FileInfoFormatting FileInfo { get; } + private static readonly PSStyle s_psstyle = new PSStyle(); private PSStyle() @@ -452,6 +770,20 @@ private PSStyle() Progress = new ProgressConfiguration(); Foreground = new ForegroundColor(); Background = new BackgroundColor(); + FileInfo = new FileInfoFormatting(); + } + + private static string ValidateNoContent(string text) + { + ArgumentNullException.ThrowIfNull(text); + + var decorartedString = new ValueStringDecorated(text); + if (decorartedString.ContentLength > 0) + { + throw new ArgumentException(string.Format(PSStyleStrings.TextContainsContent, decorartedString.ToString(OutputRendering.PlainText))); + } + + return text; } /// @@ -464,6 +796,116 @@ public static PSStyle Instance return s_psstyle; } } + + /// + /// The map of background console colors to escape sequences. + /// + private static readonly string[] BackgroundColorMap = + { + "\x1b[40m", // Black + "\x1b[44m", // DarkBlue + "\x1b[42m", // DarkGreen + "\x1b[46m", // DarkCyan + "\x1b[41m", // DarkRed + "\x1b[45m", // DarkMagenta + "\x1b[43m", // DarkYellow + "\x1b[47m", // Gray + "\x1b[100m", // DarkGray + "\x1b[104m", // Blue + "\x1b[102m", // Green + "\x1b[106m", // Cyan + "\x1b[101m", // Red + "\x1b[105m", // Magenta + "\x1b[103m", // Yellow + "\x1b[107m", // White + }; + + /// + /// The map of foreground console colors to escape sequences. + /// + private static readonly string[] ForegroundColorMap = + { + "\x1b[30m", // Black + "\x1b[34m", // DarkBlue + "\x1b[32m", // DarkGreen + "\x1b[36m", // DarkCyan + "\x1b[31m", // DarkRed + "\x1b[35m", // DarkMagenta + "\x1b[33m", // DarkYellow + "\x1b[37m", // Gray + "\x1b[90m", // DarkGray + "\x1b[94m", // Blue + "\x1b[92m", // Green + "\x1b[96m", // Cyan + "\x1b[91m", // Red + "\x1b[95m", // Magenta + "\x1b[93m", // Yellow + "\x1b[97m", // White + }; + + /// + /// Return the VT escape sequence for a ConsoleColor. + /// + /// The to be mapped from. + /// Whether or not it's a background color. + /// The VT escape sequence representing the color. + internal static string MapColorToEscapeSequence(ConsoleColor color, bool isBackground) + { + int index = (int)color; + if (index < 0 || index >= ForegroundColorMap.Length) + { + throw new ArgumentOutOfRangeException(paramName: nameof(color)); + } + + return (isBackground ? BackgroundColorMap : ForegroundColorMap)[index]; + } + + /// + /// Return the VT escape sequence for a foreground color. + /// + /// The foreground color to be mapped from. + /// The VT escape sequence representing the foreground color. + public static string MapForegroundColorToEscapeSequence(ConsoleColor foregroundColor) + => MapColorToEscapeSequence(foregroundColor, isBackground: false); + + /// + /// Return the VT escape sequence for a background color. + /// + /// The background color to be mapped from. + /// The VT escape sequence representing the background color. + public static string MapBackgroundColorToEscapeSequence(ConsoleColor backgroundColor) + => MapColorToEscapeSequence(backgroundColor, isBackground: true); + + /// + /// Return the VT escape sequence for a pair of foreground and background colors. + /// + /// The foreground color of the color pair. + /// The background color of the color pair. + /// The VT escape sequence representing the foreground and background color pair. + public static string MapColorPairToEscapeSequence(ConsoleColor foregroundColor, ConsoleColor backgroundColor) + { + int foreIndex = (int)foregroundColor; + int backIndex = (int)backgroundColor; + + if (foreIndex < 0 || foreIndex >= ForegroundColorMap.Length) + { + throw new ArgumentOutOfRangeException(paramName: nameof(foregroundColor)); + } + + if (backIndex < 0 || backIndex >= BackgroundColorMap.Length) + { + throw new ArgumentOutOfRangeException(paramName: nameof(backgroundColor)); + } + + string foreground = ForegroundColorMap[foreIndex]; + string background = BackgroundColorMap[backIndex]; + + return string.Concat( + foreground.AsSpan(start: 0, length: foreground.Length - 1), + ";".AsSpan(), + background.AsSpan(start: 2)); + } } + #endregion PSStyle } diff --git a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs index 3c1041f9c47..c76d5ebc50e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/StringDecorated.cs @@ -3,6 +3,7 @@ #nullable enable +using System.Collections.Generic; using System.Text.RegularExpressions; namespace System.Management.Automation.Internal @@ -20,10 +21,7 @@ private string PlainText { get { - if (_plaintextcontent == null) - { - _plaintextcontent = ValueStringDecorated.AnsiRegex.Replace(_text, string.Empty); - } + _plaintextcontent ??= ValueStringDecorated.AnsiRegex.Replace(_text, string.Empty); return _plaintextcontent; } @@ -55,7 +53,10 @@ public StringDecorated(string text) /// Render the decorarted string using automatic output rendering. /// /// Rendered string based on automatic output rendering. - public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + public override string ToString() => ToString( + PSStyle.Instance.OutputRendering == OutputRendering.PlainText + ? OutputRendering.PlainText + : OutputRendering.Ansi); /// /// Return string representation of content depending on output rendering mode. @@ -64,28 +65,17 @@ public StringDecorated(string text) /// Rendered string based on outputRendering. public string ToString(OutputRendering outputRendering) { - if (!_isDecorated) - { - return _text; - } - - if (outputRendering == OutputRendering.Automatic) + if (outputRendering == OutputRendering.Host) { - outputRendering = OutputRendering.Ansi; - if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) - { - outputRendering = OutputRendering.PlainText; - } + throw new ArgumentException(StringDecoratedStrings.RequireExplicitRendering); } - if (outputRendering == OutputRendering.PlainText) - { - return PlainText; - } - else + if (!_isDecorated) { return _text; } + + return outputRendering == OutputRendering.PlainText ? PlainText : _text; } } @@ -95,22 +85,53 @@ internal struct ValueStringDecorated private readonly bool _isDecorated; private readonly string _text; private string? _plaintextcontent; + private Dictionary? _vtRanges; private string PlainText { get { - if (_plaintextcontent == null) - { - _plaintextcontent = AnsiRegex.Replace(_text, string.Empty); - } + _plaintextcontent ??= AnsiRegex.Replace(_text, string.Empty); return _plaintextcontent; } } + // graphics/color mode ESC[1;2;...m + private const string GraphicsRegex = @"(\x1b\[\d*(;\d+)*m)"; + + // CSI escape sequences + private const string CsiRegex = @"(\x1b\[\?\d+[hl])"; + + // Hyperlink escape sequences. Note: '.*?' makes '.*' do non-greedy match. + private const string HyperlinkRegex = @"(\x1b\]8;;.*?\x1b\\)"; + // replace regex with .NET 6 API once available - internal static readonly Regex AnsiRegex = new Regex(@"\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])", RegexOptions.Compiled); + internal static readonly Regex AnsiRegex = new Regex($"{GraphicsRegex}|{CsiRegex}|{HyperlinkRegex}", RegexOptions.Compiled); + + /// + /// Get the ranges of all escape sequences in the text. + /// + /// + /// A dictionary with the key being the starting index of an escape sequence, + /// and the value being the length of the escape sequence. + /// + internal Dictionary? EscapeSequenceRanges + { + get + { + if (_isDecorated && _vtRanges is null) + { + _vtRanges = new Dictionary(); + foreach (Match match in AnsiRegex.Matches(_text)) + { + _vtRanges.Add(match.Index, match.Length); + } + } + + return _vtRanges; + } + } /// /// Initializes a new instance of the struct. @@ -120,7 +141,8 @@ public ValueStringDecorated(string text) { _text = text; _isDecorated = text.Contains(ESC); - _plaintextcontent = null; + _plaintextcontent = _isDecorated ? null : text; + _vtRanges = null; } /// @@ -139,7 +161,10 @@ public ValueStringDecorated(string text) /// Render the decorarted string using automatic output rendering. /// /// Rendered string based on automatic output rendering. - public override string ToString() => _isDecorated ? ToString(OutputRendering.Automatic) : _text; + public override string ToString() => ToString( + PSStyle.Instance.OutputRendering == OutputRendering.PlainText + ? OutputRendering.PlainText + : OutputRendering.Ansi); /// /// Return string representation of content depending on output rendering mode. @@ -148,28 +173,17 @@ public ValueStringDecorated(string text) /// Rendered string based on outputRendering. public string ToString(OutputRendering outputRendering) { - if (!_isDecorated) + if (outputRendering == OutputRendering.Host) { - return _text; - } - - if (outputRendering == OutputRendering.Automatic) - { - outputRendering = OutputRendering.Ansi; - if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) - { - outputRendering = OutputRendering.PlainText; - } + throw new ArgumentException(StringDecoratedStrings.RequireExplicitRendering); } - if (outputRendering == OutputRendering.PlainText) - { - return PlainText; - } - else + if (!_isDecorated) { return _text; } + + return outputRendering == OutputRendering.PlainText ? PlainText : _text; } } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs index 54aaa9438c5..49b9005a88e 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/TableWriter.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.Specialized; +using System.Management.Automation; using System.Management.Automation.Internal; using System.Text; @@ -16,16 +17,17 @@ internal class TableWriter /// /// Information about each column boundaries. /// - private class ColumnInfo + private sealed class ColumnInfo { internal int startCol = 0; internal int width = 0; internal int alignment = TextAlignment.Left; + internal bool HeaderMatchesProperty = true; } /// /// Class containing information about the tabular layout. /// - private class ScreenInfo + private sealed class ScreenInfo { internal int screenColumns = 0; internal int screenRows = 0; @@ -41,9 +43,6 @@ private class ScreenInfo private ScreenInfo _si; - private const char ESC = '\u001b'; - private const string ResetConsoleVt100Code = "\u001b[m"; - private List _header; internal static int ComputeWideViewBestItemsPerRowFit(int stringLen, int screenColumns) @@ -84,9 +83,10 @@ internal static int ComputeWideViewBestItemsPerRowFit(int stringLen, int screenC /// Number of character columns on the screen. /// Array of specified column widths. /// Array of alignment flags. + /// Array of flags where the header label matches a property name. /// If true, suppress header printing. /// Number of rows on the screen. - internal void Initialize(int leftMarginIndent, int screenColumns, Span columnWidths, ReadOnlySpan alignment, bool suppressHeader, int screenRows = int.MaxValue) + internal void Initialize(int leftMarginIndent, int screenColumns, Span columnWidths, ReadOnlySpan alignment, ReadOnlySpan headerMatchesProperty, bool suppressHeader, int screenRows = int.MaxValue) { if (leftMarginIndent < 0) { @@ -141,6 +141,11 @@ internal void Initialize(int leftMarginIndent, int screenColumns, Span colu _si.columnInfo[k].startCol = startCol; _si.columnInfo[k].width = columnWidths[k]; _si.columnInfo[k].alignment = alignment[k]; + if (!headerMatchesProperty.IsEmpty) + { + _si.columnInfo[k].HeaderMatchesProperty = headerMatchesProperty[k]; + } + startCol += columnWidths[k] + ScreenInfo.separatorCharacterCount; } } @@ -153,6 +158,9 @@ internal int GenerateHeader(string[] values, LineOutput lo) } else if (_header != null) { + string style = PSStyle.Instance.Formatting.TableHeader; + string reset = PSStyle.Instance.Reset; + foreach (string line in _header) { lo.WriteLine(line); @@ -164,7 +172,7 @@ internal int GenerateHeader(string[] values, LineOutput lo) _header = new List(); // generate the row with the header labels - GenerateRow(values, lo, true, null, lo.DisplayCells, _header); + GenerateRow(values, lo, true, null, lo.DisplayCells, _header, isHeader: true); // generate an array of "--" as header markers below // the column header labels @@ -191,14 +199,16 @@ internal int GenerateHeader(string[] values, LineOutput lo) breakLine[k] = StringUtil.DashPadding(count); } - GenerateRow(breakLine, lo, false, null, lo.DisplayCells, _header); + GenerateRow(breakLine, lo, false, null, lo.DisplayCells, _header, isHeader: true); return _header.Count; } - internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOnlySpan alignment, DisplayCells dc, List generatedRows) + internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOnlySpan alignment, DisplayCells dc, List generatedRows, bool isHeader = false) { if (_disabled) + { return; + } // build the current row alignment settings int cols = _si.columnInfo.Length; @@ -216,15 +226,22 @@ internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOn for (int i = 0; i < currentAlignment.Length; i++) { if (alignment[i] == TextAlignment.Undefined) + { currentAlignment[i] = _si.columnInfo[i].alignment; + } else + { currentAlignment[i] = alignment[i]; + } } } + string style = PSStyle.Instance.Formatting.TableHeader; + string reset = PSStyle.Instance.Reset; + if (multiLine) { - foreach (string line in GenerateTableRow(values, currentAlignment, lo.DisplayCells)) + foreach (string line in GenerateTableRow(values, currentAlignment, lo.DisplayCells, isHeader)) { generatedRows?.Add(line); lo.WriteLine(line); @@ -232,13 +249,13 @@ internal void GenerateRow(string[] values, LineOutput lo, bool multiLine, ReadOn } else { - string line = GenerateRow(values, currentAlignment, dc); + string line = GenerateRow(values, currentAlignment, dc, isHeader); generatedRows?.Add(line); lo.WriteLine(line); } } - private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, DisplayCells ds) + private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, DisplayCells ds, bool isHeader) { // select the active columns (skip hidden ones) Span validColumnArray = _si.columnInfo.Length <= OutCommandInner.StackAllocThreshold ? stackalloc int[_si.columnInfo.Length] : new int[_si.columnInfo.Length]; @@ -267,8 +284,7 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, } // obtain a set of tokens for each field - scArray[k] = GenerateMultiLineRowField(values[validColumnArray[k]], validColumnArray[k], - alignment[validColumnArray[k]], ds, addPadding); + scArray[k] = GenerateMultiLineRowField(values[validColumnArray[k]], validColumnArray[k], alignment[validColumnArray[k]], ds, addPadding); // NOTE: the following padding operations assume that we // pad with a blank (or any character that ALWAYS maps to a single screen cell @@ -299,7 +315,9 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, for (int k = 0; k < scArray.Length; k++) { if (scArray[k].Count > screenRows) + { screenRows = scArray[k].Count; + } } // column headers can span multiple rows if the width of the column is shorter than the header text like: @@ -311,7 +329,6 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, // 1 2 3 // // To ensure we don't add whitespace to the end, we need to determine the last column in each row with content - System.Span lastColWithContent = screenRows <= OutCommandInner.StackAllocThreshold ? stackalloc int[screenRows] : new int[screenRows]; for (int row = 0; row < screenRows; row++) { @@ -366,17 +383,36 @@ private string[] GenerateTableRow(string[] values, ReadOnlySpan alignment, for (int row = 0; row < screenRows; row++) { StringBuilder sb = new StringBuilder(); + // for a given row, walk the columns for (int col = 0; col < scArray.Length; col++) { + string value = scArray[col][row]; + // if the column is the last column with content, we need to trim trailing whitespace, unless there is only one row if (col == lastColWithContent[row] && screenRows > 1) { - sb.Append(scArray[col][row].TrimEnd()); + value = value.TrimEnd(); } - else + + if (isHeader) { - sb.Append(scArray[col][row]); + if (_si.columnInfo[col].HeaderMatchesProperty) + { + sb.Append(PSStyle.Instance.Formatting.TableHeader); + } + else if (value.Length > 0) + { + // after the first column, each additional column starts with a whitespace for separation + value = value.Insert(col == 0 ? 0 : 1, PSStyle.Instance.Formatting.CustomTableHeaderLabel); + } + } + + sb.Append(value); + + if (isHeader) + { + sb.Append(PSStyle.Instance.Reset); } } @@ -403,7 +439,7 @@ private StringCollection GenerateMultiLineRowField(string val, int k, int alignm return sc; } - private string GenerateRow(string[] values, ReadOnlySpan alignment, DisplayCells dc) + private string GenerateRow(string[] values, ReadOnlySpan alignment, DisplayCells dc, bool isHeader) { StringBuilder sb = new StringBuilder(); @@ -437,11 +473,18 @@ private string GenerateRow(string[] values, ReadOnlySpan alignment, Display } } - sb.Append(GenerateRowField(values[k], _si.columnInfo[k].width, alignment[k], dc, addPadding)); - if (values[k].Contains(ESC)) + string rowField = GenerateRowField(values[k], _si.columnInfo[k].width, alignment[k], dc, addPadding); + if (isHeader) + { + sb.Append(PSStyle.Instance.Formatting.TableHeader); + } + + sb.Append(rowField); + + if (isHeader || (rowField is not null && rowField.Contains(ValueStringDecorated.ESC) && !rowField.AsSpan().TrimEnd().EndsWith(PSStyle.Instance.Reset))) { // Reset the console output if the content of this column contains ESC - sb.Append(ResetConsoleVt100Code); + sb.Append(PSStyle.Instance.Reset); } } @@ -452,14 +495,12 @@ private static string GenerateRowField(string val, int width, int alignment, Dis { // make sure the string does not have any embedded in it string s = StringManipulationHelper.TruncateAtNewLine(val); - - string currentValue = s; - int currentValueDisplayLength = dc.Length(currentValue); + int currentValueDisplayLength = dc.Length(s); if (currentValueDisplayLength < width) { // the string is shorter than the width of the column - // need to pad with with blanks to reach the desired width + // need to pad with blanks to reach the desired width int padCount = width - currentValueDisplayLength; switch (alignment) { @@ -511,18 +552,10 @@ private static string GenerateRowField(string val, int width, int alignment, Dis case TextAlignment.Right: { // get from "abcdef" to "...f" - int tailCount = dc.GetTailSplitLength(s, truncationDisplayLength); - s = s.Substring(s.Length - tailCount); - s = PSObjectHelper.Ellipsis + s; - } - - break; - - case TextAlignment.Center: - { - // get from "abcdef" to "a..." - s = s.Substring(0, dc.GetHeadSplitLength(s, truncationDisplayLength)); - s += PSObjectHelper.Ellipsis; + s = s.VtSubstring( + startOffset: dc.TruncateHead(s, truncationDisplayLength), + prependStr: PSObjectHelper.EllipsisStr, + appendStr: null); } break; @@ -531,8 +564,11 @@ private static string GenerateRowField(string val, int width, int alignment, Dis { // left align is the default // get from "abcdef" to "a..." - s = s.Substring(0, dc.GetHeadSplitLength(s, truncationDisplayLength)); - s += PSObjectHelper.Ellipsis; + s = s.VtSubstring( + startOffset: 0, + length: dc.TruncateTail(s, truncationDisplayLength), + prependStr: null, + appendStr: PSObjectHelper.EllipsisStr); } break; @@ -541,23 +577,12 @@ private static string GenerateRowField(string val, int width, int alignment, Dis else { // not enough space for the ellipsis, just truncate at the width - int len = width; - switch (alignment) { case TextAlignment.Right: { // get from "abcdef" to "f" - int tailCount = dc.GetTailSplitLength(s, len); - s = s.Substring(s.Length - tailCount, tailCount); - } - - break; - - case TextAlignment.Center: - { - // get from "abcdef" to "a" - s = s.Substring(0, dc.GetHeadSplitLength(s, len)); + s = s.VtSubstring(startOffset: dc.TruncateHead(s, width)); } break; @@ -566,7 +591,7 @@ private static string GenerateRowField(string val, int width, int alignment, Dis { // left align is the default // get from "abcdef" to "a" - s = s.Substring(0, dc.GetHeadSplitLength(s, len)); + s = s.VtSubstring(startOffset: 0, length: dc.TruncateTail(s, width)); } break; diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs index 7760e86b13d..ea200bcb5f5 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/MshObjectUtil.cs @@ -26,6 +26,7 @@ internal static class PSObjectHelper #endregion tracer internal const char Ellipsis = '\u2026'; + internal const string EllipsisStr = "\u2026"; internal static string PSObjectIsOfExactType(Collection typeNames) { @@ -120,8 +121,7 @@ internal static PSPropertyExpressionResult GetDisplayName(PSObject target, PSPro /// Object to extract the IEnumerable from. internal static IEnumerable GetEnumerable(object obj) { - PSObject mshObj = obj as PSObject; - if (mshObj != null) + if (obj is PSObject mshObj) { obj = mshObj.BaseObject; } @@ -207,8 +207,9 @@ private static string GetObjectName(object x, PSPropertyExpressionFactory expres /// Expression factory to create PSPropertyExpression. /// Limit on IEnumerable enumeration. /// Stores errors during string conversion. + /// Determine if to format floating point numbers using current culture. /// String representation. - internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject) + internal static string SmartToString(PSObject so, PSPropertyExpressionFactory expressionFactory, int enumerationLimit, StringFormatError formatErrorObject, bool formatFloat = false) { if (so == null) return string.Empty; @@ -226,8 +227,7 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex IEnumerator enumerator = e.GetEnumerator(); if (enumerator != null) { - IBlockingEnumerator be = enumerator as IBlockingEnumerator; - if (be != null) + if (enumerator is IBlockingEnumerator be) { while (be.MoveNext(false)) { @@ -293,7 +293,23 @@ internal static string SmartToString(PSObject so, PSPropertyExpressionFactory ex return sb.ToString(); } - // take care of the case there is no base object + if (formatFloat && so.BaseObject is not null) + { + // format numbers using the current culture + if (so.BaseObject is double dbl) + { + return dbl.ToString("F"); + } + else if (so.BaseObject is float f) + { + return f.ToString("F"); + } + else if (so.BaseObject is decimal d) + { + return d.ToString("F"); + } + } + return so.ToString(); } catch (Exception e) when (e is ExtendedTypeSystemException || e is InvalidOperationException) @@ -332,43 +348,49 @@ internal static string FormatField(FieldFormattingDirective directive, object va StringFormatError formatErrorObject, PSPropertyExpressionFactory expressionFactory) { PSObject so = PSObjectHelper.AsPSObject(val); - if (directive != null && !string.IsNullOrEmpty(directive.formatString)) + bool isTable = false; + if (directive is not null) { - // we have a formatting directive, apply it - // NOTE: with a format directive, we do not make any attempt - // to deal with IEnumerable - try + isTable = directive.isTable; + if (!string.IsNullOrEmpty(directive.formatString)) { - // use some heuristics to determine if we have "composite formatting" - // 2004/11/16-JonN This is heuristic but should be safe enough - if (directive.formatString.Contains("{0") || directive.formatString.Contains('}')) + // we have a formatting directive, apply it + // NOTE: with a format directive, we do not make any attempt + // to deal with IEnumerable + try { - // we do have it, just use it - return string.Format(CultureInfo.CurrentCulture, directive.formatString, so); + // use some heuristics to determine if we have "composite formatting" + // 2004/11/16-JonN This is heuristic but should be safe enough + if (directive.formatString.Contains("{0") || directive.formatString.Contains('}')) + { + // we do have it, just use it + return string.Format(CultureInfo.CurrentCulture, directive.formatString, so); + } + // we fall back to the PSObject's IFormattable.ToString() + // pass a null IFormatProvider + return so.ToString(directive.formatString, formatProvider: null); } - // we fall back to the PSObject's IFormattable.ToString() - // pass a null IFormatProvider - return so.ToString(directive.formatString, null); - } - catch (Exception e) // 2004/11/17-JonN This covers exceptions thrown in - // string.Format and PSObject.ToString(). - // I think we can swallow these. - { - // NOTE: we catch all the exceptions, since we do not know - // what the underlying object access would throw - if (formatErrorObject != null) + catch (Exception e) // 2004/11/17-JonN This covers exceptions thrown in + // string.Format and PSObject.ToString(). + // I think we can swallow these. { - formatErrorObject.sourceObject = so; - formatErrorObject.exception = e; - formatErrorObject.formatString = directive.formatString; - return string.Empty; + // NOTE: we catch all the exceptions, since we do not know + // what the underlying object access would throw + if (formatErrorObject is not null) + { + formatErrorObject.sourceObject = so; + formatErrorObject.exception = e; + formatErrorObject.formatString = directive.formatString; + return string.Empty; + } } } } + // we do not have a formatting directive or we failed the formatting (fallback) // but we did not report as an error; // this call would deal with IEnumerable if the object implements it - return PSObjectHelper.SmartToString(so, expressionFactory, enumerationLimit, formatErrorObject); + return PSObjectHelper.SmartToString(so, expressionFactory, enumerationLimit, formatErrorObject, isTable); } private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) @@ -394,22 +416,18 @@ private static PSMemberSet MaskDeserializedAndGetStandardMembers(PSObject so) private static List GetDefaultPropertySet(PSMemberSet standardMembersSet) { - if (standardMembersSet != null) + if (standardMembersSet != null && standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] is PSPropertySet defaultDisplayPropertySet) { - PSPropertySet defaultDisplayPropertySet = standardMembersSet.Members[TypeTable.DefaultDisplayPropertySet] as PSPropertySet; - if (defaultDisplayPropertySet != null) + List retVal = new List(); + foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) { - List retVal = new List(); - foreach (string prop in defaultDisplayPropertySet.ReferencedPropertyNames) + if (!string.IsNullOrEmpty(prop)) { - if (!string.IsNullOrEmpty(prop)) - { - retVal.Add(new PSPropertyExpression(prop)); - } + retVal.Add(new PSPropertyExpression(prop)); } - - return retVal; } + + return retVal; } return new List(); @@ -433,21 +451,17 @@ internal static List GetDefaultPropertySet(PSObject so) private static PSPropertyExpression GetDefaultNameExpression(PSMemberSet standardMembersSet) { - if (standardMembersSet != null) + if (standardMembersSet != null && standardMembersSet.Members[TypeTable.DefaultDisplayProperty] is PSNoteProperty defaultDisplayProperty) { - PSNoteProperty defaultDisplayProperty = standardMembersSet.Members[TypeTable.DefaultDisplayProperty] as PSNoteProperty; - if (defaultDisplayProperty != null) + string expressionString = defaultDisplayProperty.Value.ToString(); + if (string.IsNullOrEmpty(expressionString)) { - string expressionString = defaultDisplayProperty.Value.ToString(); - if (string.IsNullOrEmpty(expressionString)) - { - // invalid data, the PSObject is empty - return null; - } - else - { - return new PSPropertyExpression(expressionString); - } + // invalid data, the PSObject is empty + return null; + } + else + { + return new PSPropertyExpression(expressionString); } } diff --git a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs index 68921ddb0e8..55ee3c30ddb 100644 --- a/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs +++ b/src/System.Management.Automation/FormatAndOutput/common/Utilities/Mshexpression.cs @@ -215,8 +215,7 @@ public List ResolveNames(PSObject target, bool expand) foreach (PSMemberInfo member in members) { // it can be a property set - PSPropertySet propertySet = member as PSPropertySet; - if (propertySet != null) + if (member is PSPropertySet propertySet) { if (expand) { @@ -326,15 +325,12 @@ private PSPropertyExpressionResult GetValue(PSObject target, bool eatExceptions) } else { - if (_getValueDynamicSite == null) - { - _getValueDynamicSite = - CallSite>.Create( - PSGetMemberBinder.Get( - _stringValue, - classScope: (Type)null, - @static: false)); - } + _getValueDynamicSite ??= + CallSite>.Create( + PSGetMemberBinder.Get( + _stringValue, + classScope: (Type)null, + @static: false)); result = _getValueDynamicSite.Target.Invoke(_getValueDynamicSite, target); } @@ -379,5 +375,42 @@ private static PSObject IfHashtableWrapAsPSCustomObject(PSObject target, out boo private bool _isResolved = false; #endregion Private Members + + } + + /// + /// Helper class to do wildcard matching on PSPropertyExpressions. + /// + internal sealed class PSPropertyExpressionFilter + { + /// + /// Initializes a new instance of the class + /// with the specified array of patterns. + /// + /// Array of pattern strings to use. + internal PSPropertyExpressionFilter(string[] wildcardPatternsStrings) + { + ArgumentNullException.ThrowIfNull(wildcardPatternsStrings); + + _wildcardPatterns = new WildcardPattern[wildcardPatternsStrings.Length]; + for (int k = 0; k < wildcardPatternsStrings.Length; k++) + { + _wildcardPatterns[k] = WildcardPattern.Get(wildcardPatternsStrings[k], WildcardOptions.IgnoreCase); + } + } + + /// + /// Try to match the expression against the array of wildcard patterns. + /// The first match short-circuits the search. + /// + /// PSPropertyExpression to test against. + /// True if there is a match, else false. + internal bool IsMatch(PSPropertyExpression expression) + { + string expressionString = expression.ToString(); + return _wildcardPatterns.Any(pattern => pattern.IsMatch(expressionString)); + } + + private readonly WildcardPattern[] _wildcardPatterns; } } diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs index 4750b099b01..f828b673de0 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/ConsoleLineOutput.cs @@ -1,11 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -// NOTE: define this if you want to test the output on US machine and ASCII -// characters -//#define TEST_MULTICELL_ON_SINGLE_CELL_LOCALE - using System; +using System.Collections.Generic; using System.Collections.Specialized; using System.Management.Automation; using System.Management.Automation.Internal; @@ -17,105 +14,50 @@ namespace Microsoft.PowerShell.Commands.Internal.Format { -#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE - - /// - /// Test class to provide easily overridable behavior for testing on US machines - /// using US data. - /// NOTE: the class just forces any uppercase letter [A-Z] to be prepended - /// with an underscore (e.g. "A" becomes "_A", but "a" stays the same) - /// - internal class DisplayCellsTest : DisplayCells - { - internal override int Length(string str, int offset) - { - int len = 0; - for (int k = offset; k < str.Length; k++) - { - len += this.Length(str[k]); - } - - return len; - } - - internal override int Length(char character) - { - if (character >= 'A' && character <= 'Z') - return 2; - return 1; - } - - internal override int GetHeadSplitLength(string str, int offset, int displayCells) - { - return GetSplitLengthInternalHelper(str, offset, displayCells, true); - } - - internal override int GetTailSplitLength(string str, int offset, int displayCells) - { - return GetSplitLengthInternalHelper(str, offset, displayCells, false); - } - - internal string GenerateTestString(string str) - { - StringBuilder sb = new StringBuilder(); - for (int k = 0; k < str.Length; k++) - { - char ch = str[k]; - if (this.Length(ch) == 2) - { - sb.Append('_'); - } - - sb.Append(ch); - } - - return sb.ToString(); - } - - } -#endif - /// /// Tear off class. /// - internal class DisplayCellsPSHost : DisplayCells + internal class DisplayCellsHost : DisplayCells { - internal DisplayCellsPSHost(PSHostRawUserInterface rawUserInterface) + internal DisplayCellsHost(PSHostRawUserInterface rawUserInterface) { _rawUserInterface = rawUserInterface; } internal override int Length(string str, int offset) { - Dbg.Assert(offset >= 0, "offset >= 0"); - Dbg.Assert(string.IsNullOrEmpty(str) || (offset < str.Length), "offset < str.Length"); - - try + if (string.IsNullOrEmpty(str)) { - return _rawUserInterface.LengthInBufferCells(str, offset); + return 0; } - catch + + if (offset < 0 || offset >= str.Length) { - // thrown when external host rawui is not implemented, in which case - // we will fallback to the default value. + throw PSTraceSource.NewArgumentException(nameof(offset)); } - return string.IsNullOrEmpty(str) ? 0 : str.Length - offset; - } - - internal override int Length(string str) - { try { - return _rawUserInterface.LengthInBufferCells(str); + var valueStrDec = new ValueStringDecorated(str); + if (valueStrDec.IsDecorated) + { + str = valueStrDec.ToString(OutputRendering.PlainText); + } + + int length = 0; + for (; offset < str.Length; offset++) + { + length += _rawUserInterface.LengthInBufferCells(str[offset]); + } + + return length; } catch { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. + return base.Length(str, offset); } - - return string.IsNullOrEmpty(str) ? 0 : str.Length; } internal override int Length(char character) @@ -128,19 +70,8 @@ internal override int Length(char character) { // thrown when external host rawui is not implemented, in which case // we will fallback to the default value. + return base.Length(character); } - - return 1; - } - - internal override int GetHeadSplitLength(string str, int offset, int displayCells) - { - return GetSplitLengthInternalHelper(str, offset, displayCells, true); - } - - internal override int GetTailSplitLength(string str, int offset, int displayCells) - { - return GetSplitLengthInternalHelper(str, offset, displayCells, false); } private readonly PSHostRawUserInterface _rawUserInterface; @@ -156,6 +87,11 @@ internal sealed class ConsoleLineOutput : LineOutput internal static readonly PSTraceSource tracer = PSTraceSource.GetTracer("ConsoleLineOutput", "ConsoleLineOutput"); #endregion tracer + /// + /// The default buffer cell calculation already works for the PowerShell console host and Visual studio code host. + /// + private static readonly HashSet s_psHost = new(StringComparer.Ordinal) { "ConsoleHost", "Visual Studio Code Host" }; + #region LineOutput implementation /// /// The # of columns is just the width of the screen buffer (not the @@ -234,12 +170,13 @@ internal override DisplayCells DisplayCells get { CheckStopProcessing(); - if (_displayCellsPSHost != null) + if (_displayCellsHost != null) { - return _displayCellsPSHost; + return _displayCellsHost; } + // fall back if we do not have a Msh host specific instance - return _displayCellsPSHost; + return _displayCellsDefault; } } #endregion @@ -247,39 +184,38 @@ internal override DisplayCells DisplayCells /// /// Constructor for the ConsoleLineOutput. /// - /// PSHostUserInterface to wrap. + /// PSHostUserInterface to wrap. /// True if we require prompting for page breaks. /// Error context to throw exceptions. - internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, TerminatingErrorContext errorContext) + internal ConsoleLineOutput(PSHost host, bool paging, TerminatingErrorContext errorContext) { - if (hostConsole == null) - throw PSTraceSource.NewArgumentNullException(nameof(hostConsole)); + if (host == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(host)); + } + if (errorContext == null) + { throw PSTraceSource.NewArgumentNullException(nameof(errorContext)); + } - _console = hostConsole; + _console = host.UI; _errorContext = errorContext; if (paging) { tracer.WriteLine("paging is needed"); - // if we need to do paging, instantiate a prompt handler - // that will take care of the screen interaction + + // If we need to do paging, instantiate a prompt handler that will take care of the screen interaction string promptString = StringUtil.Format(FormatAndOut_out_xxx.ConsoleLineOutput_PagingPrompt); _prompt = new PromptHandler(promptString, this); } - PSHostRawUserInterface raw = _console.RawUI; - if (raw != null) + if (!s_psHost.Contains(host.Name) && _console.RawUI is not null) { - tracer.WriteLine("there is a valid raw interface"); -#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE - // create a test instance with fake behavior - this._displayCellsPSHost = new DisplayCellsTest(); -#else // set only if we have a valid raw interface - _displayCellsPSHost = new DisplayCellsPSHost(raw); -#endif + tracer.WriteLine("there is a valid raw interface"); + _displayCellsHost = new DisplayCellsHost(_console.RawUI); } // instantiate the helper to do the line processing when ILineOutput.WriteXXX() is called @@ -302,9 +238,6 @@ internal ConsoleLineOutput(PSHostUserInterface hostConsole, bool paging, Termina /// String to write. private void OnWriteLine(string s) { -#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE - s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); -#endif // Do any default transcription. _console.TranscribeResult(s); @@ -349,10 +282,6 @@ private void OnWriteLine(string s) /// String to write. private void OnWrite(string s) { -#if TEST_MULTICELL_ON_SINGLE_CELL_LOCALE - s = ((DisplayCellsTest)this._displayCellsPSHost).GenerateTestString(s); -#endif - switch (this.WriteStream) { case WriteStreamType.Error: @@ -466,7 +395,7 @@ private bool NeedToPrompt /// /// Object to manage prompting. /// - private class PromptHandler + private sealed class PromptHandler { /// /// Prompt handler with the given prompt. @@ -591,7 +520,7 @@ internal PromptResponse PromptUser(PSHostUserInterface console) private readonly PromptHandler _prompt = null; /// - /// Conter for the # of lines written when prompting is on. + /// Counter for the # of lines written when prompting is on. /// private long _linesWritten = 0; @@ -601,14 +530,14 @@ internal PromptResponse PromptUser(PSHostUserInterface console) private bool _disableLineWrittenEvent = false; /// - /// Refecence to the PSHostUserInterface interface we use. + /// Reference to the PSHostUserInterface interface we use. /// private readonly PSHostUserInterface _console = null; /// /// Msh host specific string manipulation helper. /// - private readonly DisplayCells _displayCellsPSHost; + private readonly DisplayCells _displayCellsHost; /// /// Reference to error context to throw Msh exceptions. diff --git a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs index 2582a1e68db..20fcf54e593 100644 --- a/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs +++ b/src/System.Management.Automation/FormatAndOutput/out-console/OutConsole.cs @@ -14,7 +14,7 @@ namespace Microsoft.PowerShell.Commands /// /// Null sink to absorb pipeline output. /// - [CmdletAttribute("Out", "Null", SupportsShouldProcess = false, + [Cmdlet("Out", "Null", SupportsShouldProcess = false, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096792", RemotingCapability = RemotingCapability.None)] public class OutNullCommand : PSCmdlet { @@ -49,7 +49,7 @@ public class OutDefaultCommand : FrontEndCommandBase /// invoked via API. This ensures that the objects pass through the formatting and output /// system, but can still make it to the API consumer. /// - [Parameter()] + [Parameter] public SwitchParameter Transcript { get; set; } /// @@ -65,14 +65,11 @@ public OutDefaultCommand() /// protected override void BeginProcessing() { - PSHostUserInterface console = this.Host.UI; - ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, false, new TerminatingErrorContext(this)); + var lineOutput = new ConsoleLineOutput(Host, false, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; - MshCommandRuntime mrt = this.CommandRuntime as MshCommandRuntime; - - if (mrt != null) + if (this.CommandRuntime is MshCommandRuntime mrt) { mrt.MergeUnclaimedPreviousErrorResults = true; } @@ -206,8 +203,7 @@ public SwitchParameter Paging /// protected override void BeginProcessing() { - PSHostUserInterface console = this.Host.UI; - ConsoleLineOutput lineOutput = new ConsoleLineOutput(console, _paging, new TerminatingErrorContext(this)); + var lineOutput = new ConsoleLineOutput(Host, _paging, new TerminatingErrorContext(this)); ((OutputManagerInner)this.implementation).LineOutput = lineOutput; base.BeginProcessing(); diff --git a/src/System.Management.Automation/GlobalSuppressions.cs b/src/System.Management.Automation/GlobalSuppressions.cs new file mode 100644 index 00000000000..99e9a7c98ac --- /dev/null +++ b/src/System.Management.Automation/GlobalSuppressions.cs @@ -0,0 +1,8 @@ +using System.Diagnostics.CodeAnalysis; + +[assembly: SuppressMessage( + "Style", + "IDE0044:Add readonly modifier", + Justification = "see src/System.Management.Automation/engine/ComInterop/README.md", + Scope = "NamespaceAndDescendants", + Target = "~N:System.Management.Automation.ComInterop")] diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.cs b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.cs new file mode 100644 index 00000000000..29325d27899 --- /dev/null +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.cs @@ -0,0 +1,136 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Globalization; +using Microsoft.CodeAnalysis; + +namespace SMA +{ + /// + /// Source Code Generator to create partial PSVersionInfo class. + /// + [Generator] + public class PSVersionInfoGenerator : IIncrementalGenerator + { + /// + /// Not used. + /// + /// Generator initialization context. + public void Initialize(IncrementalGeneratorInitializationContext context) + { + IncrementalValueProvider buildOptionsProvider = context.AnalyzerConfigOptionsProvider + .Select(static (provider, _) => + { + provider.GlobalOptions.TryGetValue("build_property.ProductVersion", out var productVersion); + provider.GlobalOptions.TryGetValue("build_property.PSCoreBuildVersion", out var mainVersion); + provider.GlobalOptions.TryGetValue("build_property.PowerShellVersion", out var gitDescribe); + provider.GlobalOptions.TryGetValue("build_property.ReleaseTag", out var releaseTag); + + BuildOptions options = new() + { + ProductVersion = productVersion ?? string.Empty, + MainVersion = mainVersion ?? string.Empty, + GitDescribe = gitDescribe ?? string.Empty, + ReleaseTag = releaseTag ?? string.Empty + }; + + return options; + }); + + context.RegisterSourceOutput( + buildOptionsProvider, + static (context, buildOptions) => + { + string gitCommitId = string.IsNullOrEmpty(buildOptions.ReleaseTag) ? buildOptions.GitDescribe : buildOptions.ReleaseTag; + if (gitCommitId.StartsWith("v")) + { + gitCommitId = gitCommitId.Substring(1); + } + + var versions = ParsePSVersion(buildOptions.MainVersion); + string result = string.Format( + CultureInfo.InvariantCulture, + SourceTemplate, + buildOptions.ProductVersion, + gitCommitId, + versions.major, + versions.minor, + versions.patch, + versions.preReleaseLabel); + + // We must use specific file name suffix (*.g.cs,*.g, *.i.cs, *.generated.cs, *.designer.cs) + // so that Roslyn analyzers skip the file. + context.AddSource("PSVersionInfo.g.cs", result); + }); + } + + private struct BuildOptions + { + public string ProductVersion; + public string MainVersion; + public string GitDescribe; + public string ReleaseTag; + } + + // We must put " +// This file is auto-generated by PSVersionInfoGenerator. +// + +namespace System.Management.Automation +{{ + public static partial class PSVersionInfo + {{ + // Defined in 'PowerShell.Common.props' as 'ProductVersion' + // Example: + // - when built from a commit: ProductVersion = '7.3.0-preview.8 Commits: 29 SHA: 52c6b...' + // - when built from a preview release tag: ProductVersion = '7.3.0-preview.8 SHA: f1ec9...' + // - when built from a stable release tag: ProductVersion = '7.3.0 SHA: f1ec9...' + internal const string ProductVersion = ""{0}""; + + // The git commit id that the build is based off. + // Defined in 'PowerShell.Common.props' as 'PowerShellVersion' or 'ReleaseTag', + // depending on whether the '-ReleaseTag' is specified when building. + // Example: + // - when built from a commit: GitCommitId = '7.3.0-preview.8-29-g52c6b...' + // - when built from a preview release tag: GitCommitId = '7.3.0-preview.8' + // - when built from a stable release tag: GitCommitId = '7.3.0' + internal const string GitCommitId = ""{1}""; + + // The PowerShell version components. + // The version string is defined in 'PowerShell.Common.props' as 'PSCoreBuildVersion', + // but we break it into components to save the overhead of parsing at runtime. + // Example: + // - '7.3.0-preview.8' for preview release or private build + // - '7.3.0' for stable release + private const int Version_Major = {2}; + private const int Version_Minor = {3}; + private const int Version_Patch = {4}; + private const string Version_Label = ""{5}""; + }} +}}"; + + private static (int major, int minor, int patch, string preReleaseLabel) ParsePSVersion(string mainVersion) + { + // We only handle the pre-defined PSVersion format here, e.g. 7.x.x or 7.x.x-preview.x + int dashIndex = mainVersion.IndexOf('-'); + bool hasLabel = dashIndex != -1; + string preReleaseLabel = hasLabel ? mainVersion.Substring(dashIndex + 1) : string.Empty; + + if (hasLabel) + { + mainVersion = mainVersion.Substring(0, dashIndex); + } + + int majorEnd = mainVersion.IndexOf('.'); + int minorEnd = mainVersion.LastIndexOf('.'); + + int major = int.Parse(mainVersion.Substring(0, majorEnd), NumberStyles.Integer, CultureInfo.InvariantCulture); + int minor = int.Parse(mainVersion.Substring(majorEnd + 1, minorEnd - majorEnd - 1), NumberStyles.Integer, CultureInfo.InvariantCulture); + int patch = int.Parse(mainVersion.Substring(minorEnd + 1), NumberStyles.Integer, CultureInfo.InvariantCulture); + + return (major, minor, patch, preReleaseLabel); + } + } +} diff --git a/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj new file mode 100644 index 00000000000..86dd852a8d8 --- /dev/null +++ b/src/System.Management.Automation/SourceGenerators/PSVersionInfoGenerator/PSVersionInfoGenerator.csproj @@ -0,0 +1,20 @@ + + + Generate code for SMA using source generator + SMA.Generator + + + + + netstandard2.0 + preview + true + true + enable + + + + + + + diff --git a/src/System.Management.Automation/System.Management.Automation.csproj b/src/System.Management.Automation/System.Management.Automation.csproj index 98231ee66bc..852b66e0efd 100644 --- a/src/System.Management.Automation/System.Management.Automation.csproj +++ b/src/System.Management.Automation/System.Management.Automation.csproj @@ -2,70 +2,62 @@ PowerShell's System.Management.Automation project - $(NoWarn);CS1570;CS1734;CA1416 + $(NoWarn);CS1570;CS1734;CA1416;CA2022 System.Management.Automation + + + true + gen\SourceGenerated + + + + + + + + + + + + - + - + - - - - - - - - - - + + + + + + - - + + + + - - $(DefineConstants);CORECLR - - - - - - - - - - - - - - - - - - - - - - + + + - - - + + + - @@ -73,4 +65,13 @@ + + + + + + + $(RootNamespace).resources.%(Filename) + + diff --git a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs index 66649420101..77328bf0257 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/EnumWriter.cs @@ -23,8 +23,8 @@ private static ModuleBuilder CreateModuleBuilder() return mb; } - private static Lazy s_moduleBuilder = new(CreateModuleBuilder, isThreadSafe: true); - private static object s_moduleBuilderUsageLock = new(); + private static readonly Lazy s_moduleBuilder = new(CreateModuleBuilder, isThreadSafe: true); + private static readonly object s_moduleBuilderUsageLock = new(); internal static string GetEnumFullName(EnumMetadataEnum enumMetadata) { diff --git a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs index 1640dec33b9..c2d30f6610e 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/MethodInvocationInfo.cs @@ -21,8 +21,8 @@ public sealed class MethodInvocationInfo /// Return value of the method (ok to pass if the method doesn't return anything). public MethodInvocationInfo(string name, IEnumerable parameters, MethodParameter returnValue) { - if (name == null) throw new ArgumentNullException(nameof(name)); - if (parameters == null) throw new ArgumentNullException(nameof(parameters)); + ArgumentNullException.ThrowIfNull(name); + ArgumentNullException.ThrowIfNull(parameters); // returnValue can be null MethodName = name; @@ -62,20 +62,17 @@ internal IEnumerable GetArgumentsOfType() where T : class continue; } - var objectInstance = methodParameter.Value as T; - if (objectInstance != null) + if (methodParameter.Value is T objectInstance) { result.Add(objectInstance); continue; } - var objectInstanceArray = methodParameter.Value as IEnumerable; - if (objectInstanceArray != null) + if (methodParameter.Value is IEnumerable objectInstanceArray) { foreach (object element in objectInstanceArray) { - var objectInstance2 = element as T; - if (objectInstance2 != null) + if (element is T objectInstance2) { result.Add(objectInstance2); } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs index a840ca527fd..082d7218023 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ObjectModelWrapper.cs @@ -17,43 +17,26 @@ public abstract class CmdletAdapter { internal void Initialize(PSCmdlet cmdlet, string className, string classVersion, IDictionary privateData) { - if (cmdlet == null) - { - throw new ArgumentNullException(nameof(cmdlet)); - } - - if (string.IsNullOrEmpty(className)) - { - throw new ArgumentNullException(nameof(className)); - } + ArgumentNullException.ThrowIfNull(cmdlet); + ArgumentException.ThrowIfNullOrEmpty(className); - if (classVersion == null) // possible and ok to have classVersion==string.Empty - { - throw new ArgumentNullException(nameof(classVersion)); - } - - if (privateData == null) - { - throw new ArgumentNullException(nameof(privateData)); - } + // possible and ok to have classVersion==string.Empty + ArgumentNullException.ThrowIfNull(classVersion); + ArgumentNullException.ThrowIfNull(privateData); _cmdlet = cmdlet; _className = className; _classVersion = classVersion; _privateData = privateData; - var compiledScript = this.Cmdlet as PSScriptCmdlet; - if (compiledScript != null) + if (this.Cmdlet is PSScriptCmdlet compiledScript) { compiledScript.StoppingEvent += delegate { this.StopProcessing(); }; compiledScript.DisposingEvent += delegate { var disposable = this as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } + disposable?.Dispose(); }; } } diff --git a/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs b/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs index 36f781d98a0..e71e4c7c04f 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/QueryBuilder.cs @@ -52,7 +52,7 @@ public abstract class QueryBuilder /// Property name to query on. /// Property values to accept in the query. /// - /// if should be treated as a containing a wildcard pattern; + /// if should be treated as a containing a wildcard pattern; /// otherwise. /// /// @@ -69,7 +69,7 @@ public virtual void FilterByProperty(string propertyName, IEnumerable allowedPro /// Property name to query on. /// Property values to reject in the query. /// - /// if should be treated as a containing a wildcard pattern; + /// if should be treated as a containing a wildcard pattern; /// otherwise. /// /// diff --git a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs index a663160645c..e0bbcaa3969 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/ScriptWriter.cs @@ -100,14 +100,12 @@ internal ScriptWriter( } catch (InvalidOperationException e) { - XmlSchemaException schemaException = e.InnerException as XmlSchemaException; - if (schemaException != null) + if (e.InnerException is XmlSchemaException schemaException) { throw new XmlException(schemaException.Message, schemaException, schemaException.LineNumber, schemaException.LinePosition); } - XmlException xmlException = e.InnerException as XmlException; - if (xmlException != null) + if (e.InnerException is XmlException xmlException) { throw xmlException; } @@ -240,7 +238,7 @@ private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) StringBuilder attributes = new(150); if (cmdletMetadata.Aliases != null) { - attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); + attributes.Append("[Alias('" + string.Join("','", cmdletMetadata.Aliases.Select(static alias => CodeGeneration.EscapeSingleQuotedStringContent(alias))) + "')]"); } if (cmdletMetadata.Obsolete != null) @@ -249,7 +247,7 @@ private static string GetCmdletAttributes(CommonCmdletMetadata cmdletMetadata) ? ("'" + CodeGeneration.EscapeSingleQuotedStringContent(cmdletMetadata.Obsolete.Message) + "'") : string.Empty; string newline = (attributes.Length > 0) ? Environment.NewLine : string.Empty; - attributes.AppendFormat(CultureInfo.InvariantCulture, "{0}[Obsolete({1})]", newline, obsoleteMsg); + attributes.Append(CultureInfo.InvariantCulture, $"{newline}[Obsolete({obsoleteMsg})]"); } return attributes.ToString(); @@ -386,7 +384,7 @@ private List GetMethodParameterSets(StaticCmdletMetadata staticCmdlet) return new List(parameterSetNames.Keys); } - private Dictionary _staticMethodMetadataToUniqueId = new(); + private readonly Dictionary _staticMethodMetadataToUniqueId = new(); private string GetMethodParameterSet(CommonMethodMetadata methodMetadata) { @@ -517,13 +515,53 @@ private Type GetDotNetType(TypeMetadata typeMetadata) Dbg.Assert(typeMetadata != null, "Caller should verify typeMetadata != null"); string psTypeText; - List matchingEnums = (_cmdletizationMetadata.Enums ?? Enumerable.Empty()) - .Where(e => Regex.IsMatch( - typeMetadata.PSType, - string.Format(CultureInfo.InvariantCulture, @"\b{0}\b", Regex.Escape(e.EnumName)), - RegexOptions.CultureInvariant)) - .ToList(); - EnumMetadataEnum matchingEnum = matchingEnums.Count == 1 ? matchingEnums[0] : null; + EnumMetadataEnum matchingEnum = null; + + if (_cmdletizationMetadata.Enums is not null) + { + string psType = typeMetadata.PSType; + foreach (EnumMetadataEnum e in _cmdletizationMetadata.Enums) + { + int index = psType.IndexOf(e.EnumName, StringComparison.Ordinal); + if (index == -1) + { + // Fast return if 'PSType' doesn't contain the enum name at all. + continue; + } + + bool matchFound = false; + if (index == 0) + { + // Handle 2 common cases here (cover over 99% of how enum name is used in 'PSType'): + // - 'PSType' is exactly the enum name. + // - 'PSType' is the array format of the enum. + ReadOnlySpan remains = psType.AsSpan(e.EnumName.Length); + matchFound = remains.Length is 0 || remains.Equals("[]", StringComparison.Ordinal); + } + + if (!matchFound) + { + // Now we have to fall back to the expensive regular expression matching, because 'PSType' + // could be a composite type like 'Nullable' or 'Dictionary', + // but we don't want the case where the enum name is part of another type's name. + matchFound = Regex.IsMatch(psType, $@"\b{Regex.Escape(e.EnumName)}\b"); + } + + if (matchFound) + { + if (matchingEnum is null) + { + matchingEnum = e; + continue; + } + + // If more than one matching enum names were found, we treat it as no match found. + matchingEnum = null; + break; + } + } + } + if (matchingEnum != null) { psTypeText = typeMetadata.PSType.Replace(matchingEnum.EnumName, EnumWriter.GetEnumFullName(matchingEnum)); @@ -788,8 +826,7 @@ private void SetParameters(CommandMetadata commandMetadata, params Dictionary p.Items != null)) + foreach (PropertyMetadata property in getCmdletParameters.QueryableProperties.Where(static p => p.Items != null)) { for (int i = 0; i < property.Items.Length; i++) { @@ -1681,7 +1730,7 @@ private void GenerateQueryParametersProcessing( if (getCmdletParameters.QueryableAssociations != null) { - foreach (Association association in getCmdletParameters.QueryableAssociations.Where(a => a.AssociatedInstance != null)) + foreach (Association association in getCmdletParameters.QueryableAssociations.Where(static a => a.AssociatedInstance != null)) { ParameterMetadata parameterMetadata = GenerateAssociationClause( commonParameterSets, queryParameterSets, methodParameterSets, association, association.AssociatedInstance, output); @@ -1983,7 +2032,7 @@ private void WriteCmdlet(TextWriter output, InstanceCmdletMetadata instanceCmdle } else if (queryParameterSets.Count == 1) { - commandMetadata.DefaultParameterSetName = queryParameterSets.Single(); + commandMetadata.DefaultParameterSetName = queryParameterSets[0]; } AddPassThruParameter(commonParameters, instanceCmdlet); @@ -2100,7 +2149,7 @@ private void WriteGetCmdlet(TextWriter output) /* 1 */ CodeGeneration.EscapeSingleQuotedStringContent(commandMetadata.Name)); } - private static object s_enumCompilationLock = new(); + private static readonly object s_enumCompilationLock = new(); private static void CompileEnum(EnumMetadataEnum enumMetadata) { @@ -2203,7 +2252,7 @@ internal void ReportExportedCommands(PSModuleInfo moduleInfo, string prefix) { cmdletMetadatas = cmdletMetadatas.Concat( - _cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet.Select(c => c.CmdletMetadata)); + _cmdletizationMetadata.Class.InstanceCmdlets.Cmdlet.Select(static c => c.CmdletMetadata)); } } @@ -2211,7 +2260,7 @@ internal void ReportExportedCommands(PSModuleInfo moduleInfo, string prefix) { cmdletMetadatas = cmdletMetadatas.Concat( - _cmdletizationMetadata.Class.StaticCmdlets.Select(c => c.CmdletMetadata)); + _cmdletizationMetadata.Class.StaticCmdlets.Select(static c => c.CmdletMetadata)); } foreach (CommonCmdletMetadata cmdletMetadata in cmdletMetadatas) diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs index 8614c6a3994..76b7a3c2c52 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.objectModel.autogen.cs @@ -23,8 +23,8 @@ namespace Microsoft.PowerShell.Cmdletization.Xml /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlRoot(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)] internal partial class PowerShellMetadata { private ClassMetadata _classField; @@ -46,7 +46,7 @@ public ClassMetadata Class } /// - [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Enum", IsNullable = false)] public EnumMetadataEnum[] Enums { get @@ -64,7 +64,7 @@ public EnumMetadataEnum[] Enums /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadata { private string _versionField; @@ -126,7 +126,7 @@ public ClassMetadataInstanceCmdlets InstanceCmdlets } /// - [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Cmdlet", IsNullable = false)] public StaticCmdletMetadata[] StaticCmdlets { get @@ -141,7 +141,7 @@ public StaticCmdletMetadata[] StaticCmdlets } /// - [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Data", IsNullable = false)] public ClassMetadataData[] CmdletAdapterPrivateData { get @@ -156,7 +156,7 @@ public ClassMetadataData[] CmdletAdapterPrivateData } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string CmdletAdapter { get @@ -171,7 +171,7 @@ public string CmdletAdapter } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string ClassName { get @@ -186,7 +186,7 @@ public string ClassName } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string ClassVersion { get @@ -204,7 +204,7 @@ public string ClassVersion /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadataInstanceCmdlets { private GetCmdletParameters _getCmdletParametersField; @@ -242,7 +242,7 @@ public GetCmdletMetadata GetCmdlet } /// - [System.Xml.Serialization.XmlElementAttribute("Cmdlet")] + [System.Xml.Serialization.XmlElement("Cmdlet")] public InstanceCmdletMetadata[] Cmdlet { get @@ -260,7 +260,7 @@ public InstanceCmdletMetadata[] Cmdlet /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class GetCmdletParameters { private PropertyMetadata[] _queryablePropertiesField; @@ -272,7 +272,7 @@ internal partial class GetCmdletParameters private string _defaultCmdletParameterSetField; /// - [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Property", IsNullable = false)] public PropertyMetadata[] QueryableProperties { get @@ -287,7 +287,7 @@ public PropertyMetadata[] QueryableProperties } /// - [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem(IsNullable = false)] public Association[] QueryableAssociations { get @@ -302,7 +302,7 @@ public Association[] QueryableAssociations } /// - [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Option", IsNullable = false)] public QueryOption[] QueryOptions { get @@ -317,7 +317,7 @@ public QueryOption[] QueryOptions } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string DefaultCmdletParameterSet { get @@ -335,7 +335,7 @@ public string DefaultCmdletParameterSet /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class PropertyMetadata { private TypeMetadata _typeField; @@ -361,11 +361,11 @@ public TypeMetadata Type } /// - [System.Xml.Serialization.XmlElementAttribute("ExcludeQuery", typeof(WildcardablePropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("MaxValueQuery", typeof(PropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("MinValueQuery", typeof(PropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("RegularQuery", typeof(WildcardablePropertyQuery))] - [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")] + [System.Xml.Serialization.XmlElement("ExcludeQuery", typeof(WildcardablePropertyQuery))] + [System.Xml.Serialization.XmlElement("MaxValueQuery", typeof(PropertyQuery))] + [System.Xml.Serialization.XmlElement("MinValueQuery", typeof(PropertyQuery))] + [System.Xml.Serialization.XmlElement("RegularQuery", typeof(WildcardablePropertyQuery))] + [System.Xml.Serialization.XmlChoiceIdentifier("ItemsElementName")] public PropertyQuery[] Items { get @@ -380,8 +380,8 @@ public PropertyQuery[] Items } /// - [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlElement("ItemsElementName")] + [System.Xml.Serialization.XmlIgnore()] public ItemsChoiceType[] ItemsElementName { get @@ -396,7 +396,7 @@ public ItemsChoiceType[] ItemsElementName } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string PropertyName { get @@ -414,7 +414,7 @@ public string PropertyName /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class TypeMetadata { private string _pSTypeField; @@ -422,7 +422,7 @@ internal partial class TypeMetadata private string _eTSTypeField; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string PSType { get @@ -437,7 +437,7 @@ public string PSType } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string ETSType { get @@ -455,7 +455,7 @@ public string ETSType /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class Association { private AssociationAssociatedInstance _associatedInstanceField; @@ -481,7 +481,7 @@ public AssociationAssociatedInstance AssociatedInstance } /// - [System.Xml.Serialization.XmlAttributeAttribute("Association")] + [System.Xml.Serialization.XmlAttribute("Association")] public string Association1 { get @@ -496,7 +496,7 @@ public string Association1 } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string SourceRole { get @@ -511,7 +511,7 @@ public string SourceRole } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string ResultRole { get @@ -529,7 +529,7 @@ public string ResultRole /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class AssociationAssociatedInstance { private TypeMetadata _typeField; @@ -568,7 +568,7 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter { private bool _errorOnNoMatchField; @@ -576,7 +576,7 @@ internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : C private bool _errorOnNoMatchFieldSpecified; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool ErrorOnNoMatch { get @@ -591,7 +591,7 @@ public bool ErrorOnNoMatch } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ErrorOnNoMatchSpecified { get @@ -607,10 +607,10 @@ public bool ErrorOnNoMatchSpecified } /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] + [System.Xml.Serialization.XmlInclude(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata { private bool _valueFromPipelineField; @@ -624,7 +624,7 @@ internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletPara private string[] _cmdletParameterSetsField; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool ValueFromPipeline { get @@ -639,7 +639,7 @@ public bool ValueFromPipeline } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ValueFromPipelineSpecified { get @@ -654,7 +654,7 @@ public bool ValueFromPipelineSpecified } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool ValueFromPipelineByPropertyName { get @@ -669,7 +669,7 @@ public bool ValueFromPipelineByPropertyName } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ValueFromPipelineByPropertyNameSpecified { get @@ -684,7 +684,7 @@ public bool ValueFromPipelineByPropertyNameSpecified } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string[] CmdletParameterSets { get @@ -700,13 +700,13 @@ public string[] CmdletParameterSets } /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForInstanceMethodParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForStaticMethodParameter))] + [System.Xml.Serialization.XmlInclude(typeof(CmdletParameterMetadataForGetCmdletParameter))] + [System.Xml.Serialization.XmlInclude(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] + [System.Xml.Serialization.XmlInclude(typeof(CmdletParameterMetadataForInstanceMethodParameter))] + [System.Xml.Serialization.XmlInclude(typeof(CmdletParameterMetadataForStaticMethodParameter))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadata { private object _allowEmptyCollectionField; @@ -852,7 +852,7 @@ public CmdletParameterMetadataValidateRange ValidateRange } /// - [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("AllowedValue", IsNullable = false)] public string[] ValidateSet { get @@ -881,7 +881,7 @@ public ObsoleteAttributeMetadata Obsolete } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool IsMandatory { get @@ -896,7 +896,7 @@ public bool IsMandatory } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool IsMandatorySpecified { get @@ -911,7 +911,7 @@ public bool IsMandatorySpecified } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string[] Aliases { get @@ -926,7 +926,7 @@ public string[] Aliases } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string PSName { get @@ -941,7 +941,7 @@ public string PSName } /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + [System.Xml.Serialization.XmlAttribute(DataType = "nonNegativeInteger")] public string Position { get @@ -959,7 +959,7 @@ public string Position /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateCount { private string _minField; @@ -967,7 +967,7 @@ internal partial class CmdletParameterMetadataValidateCount private string _maxField; /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + [System.Xml.Serialization.XmlAttribute(DataType = "nonNegativeInteger")] public string Min { get @@ -982,7 +982,7 @@ public string Min } /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + [System.Xml.Serialization.XmlAttribute(DataType = "nonNegativeInteger")] public string Max { get @@ -1000,7 +1000,7 @@ public string Max /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateLength { private string _minField; @@ -1008,7 +1008,7 @@ internal partial class CmdletParameterMetadataValidateLength private string _maxField; /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + [System.Xml.Serialization.XmlAttribute(DataType = "nonNegativeInteger")] public string Min { get @@ -1023,7 +1023,7 @@ public string Min } /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] + [System.Xml.Serialization.XmlAttribute(DataType = "nonNegativeInteger")] public string Max { get @@ -1041,7 +1041,7 @@ public string Max /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataValidateRange { private string _minField; @@ -1049,7 +1049,7 @@ internal partial class CmdletParameterMetadataValidateRange private string _maxField; /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + [System.Xml.Serialization.XmlAttribute(DataType = "integer")] public string Min { get @@ -1064,7 +1064,7 @@ public string Min } /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + [System.Xml.Serialization.XmlAttribute(DataType = "integer")] public string Max { get @@ -1082,13 +1082,13 @@ public string Max /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ObsoleteAttributeMetadata { private string _messageField; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string Message { get @@ -1106,7 +1106,7 @@ public string Message /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata { private bool _valueFromPipelineByPropertyNameField; @@ -1114,7 +1114,7 @@ internal partial class CmdletParameterMetadataForInstanceMethodParameter : Cmdle private bool _valueFromPipelineByPropertyNameFieldSpecified; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool ValueFromPipelineByPropertyName { get @@ -1129,7 +1129,7 @@ public bool ValueFromPipelineByPropertyName } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ValueFromPipelineByPropertyNameSpecified { get @@ -1147,7 +1147,7 @@ public bool ValueFromPipelineByPropertyNameSpecified /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata { private bool _valueFromPipelineField; @@ -1159,7 +1159,7 @@ internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletP private bool _valueFromPipelineByPropertyNameFieldSpecified; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool ValueFromPipeline { get @@ -1174,7 +1174,7 @@ public bool ValueFromPipeline } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ValueFromPipelineSpecified { get @@ -1189,7 +1189,7 @@ public bool ValueFromPipelineSpecified } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool ValueFromPipelineByPropertyName { get @@ -1204,7 +1204,7 @@ public bool ValueFromPipelineByPropertyName } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ValueFromPipelineByPropertyNameSpecified { get @@ -1222,7 +1222,7 @@ public bool ValueFromPipelineByPropertyNameSpecified /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class QueryOption { private TypeMetadata _typeField; @@ -1260,7 +1260,7 @@ public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string OptionName { get @@ -1278,7 +1278,7 @@ public string OptionName /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class GetCmdletMetadata { private CommonCmdletMetadata _cmdletMetadataField; @@ -1317,7 +1317,7 @@ public GetCmdletParameters GetCmdletParameters /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonCmdletMetadata { private ObsoleteAttributeMetadata _obsoleteField; @@ -1349,7 +1349,7 @@ public ObsoleteAttributeMetadata Obsolete } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string Verb { get @@ -1364,7 +1364,7 @@ public string Verb } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string Noun { get @@ -1379,7 +1379,7 @@ public string Noun } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string[] Aliases { get @@ -1394,7 +1394,7 @@ public string[] Aliases } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public ConfirmImpact ConfirmImpact { get @@ -1409,7 +1409,7 @@ public ConfirmImpact ConfirmImpact } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool ConfirmImpactSpecified { get @@ -1424,7 +1424,7 @@ public bool ConfirmImpactSpecified } /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")] + [System.Xml.Serialization.XmlAttribute(DataType = "anyURI")] public string HelpUri { get @@ -1441,7 +1441,7 @@ public string HelpUri /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] public enum ConfirmImpact { /// @@ -1460,7 +1460,7 @@ public enum ConfirmImpact /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticCmdletMetadata { private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField; @@ -1482,7 +1482,7 @@ public StaticCmdletMetadataCmdletMetadata CmdletMetadata } /// - [System.Xml.Serialization.XmlElementAttribute("Method")] + [System.Xml.Serialization.XmlElement("Method")] public StaticMethodMetadata[] Method { get @@ -1500,13 +1500,13 @@ public StaticMethodMetadata[] Method /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata { private string _defaultCmdletParameterSetField; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string DefaultCmdletParameterSet { get @@ -1524,7 +1524,7 @@ public string DefaultCmdletParameterSet /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticMethodMetadata : CommonMethodMetadata { private StaticMethodParameterMetadata[] _parametersField; @@ -1532,7 +1532,7 @@ internal partial class StaticMethodMetadata : CommonMethodMetadata private string _cmdletParameterSetField; /// - [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Parameter", IsNullable = false)] public StaticMethodParameterMetadata[] Parameters { get @@ -1547,7 +1547,7 @@ public StaticMethodParameterMetadata[] Parameters } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string CmdletParameterSet { get @@ -1565,7 +1565,7 @@ public string CmdletParameterSet /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata { private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField; @@ -1604,7 +1604,7 @@ public CmdletOutputMetadata CmdletOutputMetadata /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CmdletOutputMetadata { private object _errorCodeField; @@ -1626,7 +1626,7 @@ public object ErrorCode } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string PSName { get @@ -1642,11 +1642,11 @@ public string PSName } /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodParameterMetadata))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodParameterMetadata))] + [System.Xml.Serialization.XmlInclude(typeof(InstanceMethodParameterMetadata))] + [System.Xml.Serialization.XmlInclude(typeof(StaticMethodParameterMetadata))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodParameterMetadata { private TypeMetadata _typeField; @@ -1670,7 +1670,7 @@ public TypeMetadata Type } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string ParameterName { get @@ -1685,7 +1685,7 @@ public string ParameterName } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string DefaultValue { get @@ -1703,7 +1703,7 @@ public string DefaultValue /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata { private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField; @@ -1740,11 +1740,11 @@ public CmdletOutputMetadata CmdletOutputMetadata } /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodMetadata))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodMetadata))] + [System.Xml.Serialization.XmlInclude(typeof(InstanceMethodMetadata))] + [System.Xml.Serialization.XmlInclude(typeof(StaticMethodMetadata))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodMetadata { private CommonMethodMetadataReturnValue _returnValueField; @@ -1766,7 +1766,7 @@ public CommonMethodMetadataReturnValue ReturnValue } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string MethodName { get @@ -1784,7 +1784,7 @@ public string MethodName /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class CommonMethodMetadataReturnValue { private TypeMetadata _typeField; @@ -1823,13 +1823,13 @@ public CmdletOutputMetadata CmdletOutputMetadata /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceMethodMetadata : CommonMethodMetadata { private InstanceMethodParameterMetadata[] _parametersField; /// - [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] + [System.Xml.Serialization.XmlArrayItem("Parameter", IsNullable = false)] public InstanceMethodParameterMetadata[] Parameters { get @@ -1847,7 +1847,7 @@ public InstanceMethodParameterMetadata[] Parameters /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class InstanceCmdletMetadata { private CommonCmdletMetadata _cmdletMetadataField; @@ -1900,10 +1900,10 @@ public GetCmdletParameters GetCmdletParameters } /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(WildcardablePropertyQuery))] + [System.Xml.Serialization.XmlInclude(typeof(WildcardablePropertyQuery))] [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class PropertyQuery { private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; @@ -1926,7 +1926,7 @@ public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMeta /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class WildcardablePropertyQuery : PropertyQuery { private bool _allowGlobbingField; @@ -1934,7 +1934,7 @@ internal partial class WildcardablePropertyQuery : PropertyQuery private bool _allowGlobbingFieldSpecified; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool AllowGlobbing { get @@ -1949,7 +1949,7 @@ public bool AllowGlobbing } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool AllowGlobbingSpecified { get @@ -1966,7 +1966,7 @@ public bool AllowGlobbingSpecified /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)] + [System.Xml.Serialization.XmlType(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)] public enum ItemsChoiceType { /// @@ -1985,7 +1985,7 @@ public enum ItemsChoiceType /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class ClassMetadataData { private string _nameField; @@ -1993,7 +1993,7 @@ internal partial class ClassMetadataData private string _valueField; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string Name { get @@ -2008,7 +2008,7 @@ public string Name } /// - [System.Xml.Serialization.XmlTextAttribute()] + [System.Xml.Serialization.XmlText()] public string Value { get @@ -2026,7 +2026,7 @@ public string Value /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class EnumMetadataEnum { private EnumMetadataEnumValue[] _valueField; @@ -2040,7 +2040,7 @@ internal partial class EnumMetadataEnum private bool _bitwiseFlagsFieldSpecified; /// - [System.Xml.Serialization.XmlElementAttribute("Value")] + [System.Xml.Serialization.XmlElement("Value")] public EnumMetadataEnumValue[] Value { get @@ -2055,7 +2055,7 @@ public EnumMetadataEnumValue[] Value } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string EnumName { get @@ -2070,7 +2070,7 @@ public string EnumName } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string UnderlyingType { get @@ -2085,7 +2085,7 @@ public string UnderlyingType } /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public bool BitwiseFlags { get @@ -2100,7 +2100,7 @@ public bool BitwiseFlags } /// - [System.Xml.Serialization.XmlIgnoreAttribute()] + [System.Xml.Serialization.XmlIgnore()] public bool BitwiseFlagsSpecified { get @@ -2118,7 +2118,7 @@ public bool BitwiseFlagsSpecified /// [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] + [System.Xml.Serialization.XmlType(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] internal partial class EnumMetadataEnumValue { private string _nameField; @@ -2126,7 +2126,7 @@ internal partial class EnumMetadataEnumValue private string _valueField; /// - [System.Xml.Serialization.XmlAttributeAttribute()] + [System.Xml.Serialization.XmlAttribute()] public string Name { get @@ -2141,7 +2141,7 @@ public string Name } /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] + [System.Xml.Serialization.XmlAttribute(DataType = "integer")] public string Value { get diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs index 9c53032284e..6cfed8ebe2d 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/CoreCLR/cmdlets-over-objects.xmlSerializer.autogen.cs @@ -289,12 +289,12 @@ protected Exception CreateUnknownNodeException() protected Exception CreateUnknownTypeException(XmlQualifiedName type) { - return new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUnknownType. Name: {0}, Namespace {1}, CurrentTag: {2}", type.Name, type.Namespace, CurrentTag())); + return new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUnknownType. Name: {type.Name}, Namespace: {type.Namespace}, CurrentTag: {CurrentTag()}")); } protected Exception CreateUnknownConstantException(string value, Type enumType) { - return new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUnknownConstant. Value: {0}, EnumType: {1}", value, enumType.Name)); + return new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUnknownConstant. Value: {value}, EnumType: {enumType.Name}")); } protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable) @@ -426,7 +426,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) if (ns == null) { // Namespace prefix '{0}' is not defined. - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, "XmlUndefinedAlias. Prefix: {0}", prefix)); + throw new InvalidOperationException(string.Create(CultureInfo.CurrentCulture, $"XmlUndefinedAlias. Prefix: {prefix}")); } return new XmlQualifiedName(_r.NameTable.Add(localName), ns); @@ -6678,10 +6678,7 @@ internal sealed class PowerShellMetadataSerializer { internal object Deserialize(XmlReader reader) { - if (reader == null) - { - throw new ArgumentNullException("reader"); - } + ArgumentNullException.ThrowIfNull(reader); XmlSerializationReader1 cdxmlSerializationReader = new XmlSerializationReader1(reader); return cdxmlSerializationReader.Read50_PowerShellMetadata(); diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs deleted file mode 100644 index e2b87d4adf9..00000000000 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.objectModel.autogen.cs +++ /dev/null @@ -1,2240 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// PLEASE DO NOT EDIT THIS FILE BY HAND!!! -// -// This file has been generated -// by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// -// Generation timestamp: 10/21/2013 18:29:23 - -#pragma warning disable -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.17929 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -// -// This source code was auto-generated by xsd, Version=4.0.30319.17929. -// - -namespace Microsoft.PowerShell.Cmdletization.Xml -{ - using System.Xml.Serialization; - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - [System.Xml.Serialization.XmlRootAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IsNullable = false)] - internal partial class PowerShellMetadata - { - private ClassMetadata _classField; - - private EnumMetadataEnum[] _enumsField; - - /// - public ClassMetadata Class - { - get - { - return this._classField; - } - - set - { - this._classField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Enum", IsNullable = false)] - public EnumMetadataEnum[] Enums - { - get - { - return this._enumsField; - } - - set - { - this._enumsField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ClassMetadata - { - private string _versionField; - - private string _defaultNounField; - - private ClassMetadataInstanceCmdlets _instanceCmdletsField; - - private StaticCmdletMetadata[] _staticCmdletsField; - - private ClassMetadataData[] _cmdletAdapterPrivateDataField; - - private string _cmdletAdapterField; - - private string _classNameField; - - private string _classVersionField; - - /// - public string Version - { - get - { - return this._versionField; - } - - set - { - this._versionField = value; - } - } - - /// - public string DefaultNoun - { - get - { - return this._defaultNounField; - } - - set - { - this._defaultNounField = value; - } - } - - /// - public ClassMetadataInstanceCmdlets InstanceCmdlets - { - get - { - return this._instanceCmdletsField; - } - - set - { - this._instanceCmdletsField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Cmdlet", IsNullable = false)] - public StaticCmdletMetadata[] StaticCmdlets - { - get - { - return this._staticCmdletsField; - } - - set - { - this._staticCmdletsField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Data", IsNullable = false)] - public ClassMetadataData[] CmdletAdapterPrivateData - { - get - { - return this._cmdletAdapterPrivateDataField; - } - - set - { - this._cmdletAdapterPrivateDataField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletAdapter - { - get - { - return this._cmdletAdapterField; - } - - set - { - this._cmdletAdapterField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassName - { - get - { - return this._classNameField; - } - - set - { - this._classNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ClassVersion - { - get - { - return this._classVersionField; - } - - set - { - this._classVersionField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ClassMetadataInstanceCmdlets - { - private GetCmdletParameters _getCmdletParametersField; - - private GetCmdletMetadata _getCmdletField; - - private InstanceCmdletMetadata[] _cmdletField; - - /// - public GetCmdletParameters GetCmdletParameters - { - get - { - return this._getCmdletParametersField; - } - - set - { - this._getCmdletParametersField = value; - } - } - - /// - public GetCmdletMetadata GetCmdlet - { - get - { - return this._getCmdletField; - } - - set - { - this._getCmdletField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("Cmdlet")] - public InstanceCmdletMetadata[] Cmdlet - { - get - { - return this._cmdletField; - } - - set - { - this._cmdletField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class GetCmdletParameters - { - private PropertyMetadata[] _queryablePropertiesField; - - private Association[] _queryableAssociationsField; - - private QueryOption[] _queryOptionsField; - - private string _defaultCmdletParameterSetField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Property", IsNullable = false)] - public PropertyMetadata[] QueryableProperties - { - get - { - return this._queryablePropertiesField; - } - - set - { - this._queryablePropertiesField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute(IsNullable = false)] - public Association[] QueryableAssociations - { - get - { - return this._queryableAssociationsField; - } - - set - { - this._queryableAssociationsField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Option", IsNullable = false)] - public QueryOption[] QueryOptions - { - get - { - return this._queryOptionsField; - } - - set - { - this._queryOptionsField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultCmdletParameterSet - { - get - { - return this._defaultCmdletParameterSetField; - } - - set - { - this._defaultCmdletParameterSetField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class PropertyMetadata - { - private TypeMetadata _typeField; - - private PropertyQuery[] _itemsField; - - private ItemsChoiceType[] _itemsElementNameField; - - private string _propertyNameField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("ExcludeQuery", typeof(WildcardablePropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("MaxValueQuery", typeof(PropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("MinValueQuery", typeof(PropertyQuery))] - [System.Xml.Serialization.XmlElementAttribute("RegularQuery", typeof(WildcardablePropertyQuery))] - [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemsElementName")] - public PropertyQuery[] Items - { - get - { - return this._itemsField; - } - - set - { - this._itemsField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("ItemsElementName")] - [System.Xml.Serialization.XmlIgnoreAttribute()] - public ItemsChoiceType[] ItemsElementName - { - get - { - return this._itemsElementNameField; - } - - set - { - this._itemsElementNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PropertyName - { - get - { - return this._propertyNameField; - } - - set - { - this._propertyNameField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class TypeMetadata - { - private string _pSTypeField; - - private string _eTSTypeField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSType - { - get - { - return this._pSTypeField; - } - - set - { - this._pSTypeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ETSType - { - get - { - return this._eTSTypeField; - } - - set - { - this._eTSTypeField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class Association - { - private AssociationAssociatedInstance _associatedInstanceField; - - private string _association1Field; - - private string _sourceRoleField; - - private string _resultRoleField; - - /// - public AssociationAssociatedInstance AssociatedInstance - { - get - { - return this._associatedInstanceField; - } - - set - { - this._associatedInstanceField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute("Association")] - public string Association1 - { - get - { - return this._association1Field; - } - - set - { - this._association1Field = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string SourceRole - { - get - { - return this._sourceRoleField; - } - - set - { - this._sourceRoleField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ResultRole - { - get - { - return this._resultRoleField; - } - - set - { - this._resultRoleField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class AssociationAssociatedInstance - { - private TypeMetadata _typeField; - - private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForGetCmdletFilteringParameter : CmdletParameterMetadataForGetCmdletParameter - { - private bool _errorOnNoMatchField; - - private bool _errorOnNoMatchFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ErrorOnNoMatch - { - get - { - return this._errorOnNoMatchField; - } - - set - { - this._errorOnNoMatchField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ErrorOnNoMatchSpecified - { - get - { - return this._errorOnNoMatchFieldSpecified; - } - - set - { - this._errorOnNoMatchFieldSpecified = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForGetCmdletParameter : CmdletParameterMetadata - { - private bool _valueFromPipelineField; - - private bool _valueFromPipelineFieldSpecified; - - private bool _valueFromPipelineByPropertyNameField; - - private bool _valueFromPipelineByPropertyNameFieldSpecified; - - private string[] _cmdletParameterSetsField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipeline - { - get - { - return this._valueFromPipelineField; - } - - set - { - this._valueFromPipelineField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified - { - get - { - return this._valueFromPipelineFieldSpecified; - } - - set - { - this._valueFromPipelineFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName - { - get - { - return this._valueFromPipelineByPropertyNameField; - } - - set - { - this._valueFromPipelineByPropertyNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified - { - get - { - return this._valueFromPipelineByPropertyNameFieldSpecified; - } - - set - { - this._valueFromPipelineByPropertyNameFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] CmdletParameterSets - { - get - { - return this._cmdletParameterSetsField; - } - - set - { - this._cmdletParameterSetsField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForGetCmdletFilteringParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForInstanceMethodParameter))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(CmdletParameterMetadataForStaticMethodParameter))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadata - { - private object _allowEmptyCollectionField; - - private object _allowEmptyStringField; - - private object _allowNullField; - - private object _validateNotNullField; - - private object _validateNotNullOrEmptyField; - - private CmdletParameterMetadataValidateCount _validateCountField; - - private CmdletParameterMetadataValidateLength _validateLengthField; - - private CmdletParameterMetadataValidateRange _validateRangeField; - - private string[] _validateSetField; - - private ObsoleteAttributeMetadata _obsoleteField; - - private bool _isMandatoryField; - - private bool _isMandatoryFieldSpecified; - - private string[] _aliasesField; - - private string _pSNameField; - - private string _positionField; - - /// - public object AllowEmptyCollection - { - get - { - return this._allowEmptyCollectionField; - } - - set - { - this._allowEmptyCollectionField = value; - } - } - - /// - public object AllowEmptyString - { - get - { - return this._allowEmptyStringField; - } - - set - { - this._allowEmptyStringField = value; - } - } - - /// - public object AllowNull - { - get - { - return this._allowNullField; - } - - set - { - this._allowNullField = value; - } - } - - /// - public object ValidateNotNull - { - get - { - return this._validateNotNullField; - } - - set - { - this._validateNotNullField = value; - } - } - - /// - public object ValidateNotNullOrEmpty - { - get - { - return this._validateNotNullOrEmptyField; - } - - set - { - this._validateNotNullOrEmptyField = value; - } - } - - /// - public CmdletParameterMetadataValidateCount ValidateCount - { - get - { - return this._validateCountField; - } - - set - { - this._validateCountField = value; - } - } - - /// - public CmdletParameterMetadataValidateLength ValidateLength - { - get - { - return this._validateLengthField; - } - - set - { - this._validateLengthField = value; - } - } - - /// - public CmdletParameterMetadataValidateRange ValidateRange - { - get - { - return this._validateRangeField; - } - - set - { - this._validateRangeField = value; - } - } - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("AllowedValue", IsNullable = false)] - public string[] ValidateSet - { - get - { - return this._validateSetField; - } - - set - { - this._validateSetField = value; - } - } - - /// - public ObsoleteAttributeMetadata Obsolete - { - get - { - return this._obsoleteField; - } - - set - { - this._obsoleteField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool IsMandatory - { - get - { - return this._isMandatoryField; - } - - set - { - this._isMandatoryField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool IsMandatorySpecified - { - get - { - return this._isMandatoryFieldSpecified; - } - - set - { - this._isMandatoryFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases - { - get - { - return this._aliasesField; - } - - set - { - this._aliasesField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName - { - get - { - return this._pSNameField; - } - - set - { - this._pSNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Position - { - get - { - return this._positionField; - } - - set - { - this._positionField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataValidateCount - { - private string _minField; - - private string _maxField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Min - { - get - { - return this._minField; - } - - set - { - this._minField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Max - { - get - { - return this._maxField; - } - - set - { - this._maxField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataValidateLength - { - private string _minField; - - private string _maxField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Min - { - get - { - return this._minField; - } - - set - { - this._minField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "nonNegativeInteger")] - public string Max - { - get - { - return this._maxField; - } - - set - { - this._maxField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataValidateRange - { - private string _minField; - - private string _maxField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] - public string Min - { - get - { - return this._minField; - } - - set - { - this._minField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] - public string Max - { - get - { - return this._maxField; - } - - set - { - this._maxField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ObsoleteAttributeMetadata - { - private string _messageField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Message - { - get - { - return this._messageField; - } - - set - { - this._messageField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForInstanceMethodParameter : CmdletParameterMetadata - { - private bool _valueFromPipelineByPropertyNameField; - - private bool _valueFromPipelineByPropertyNameFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName - { - get - { - return this._valueFromPipelineByPropertyNameField; - } - - set - { - this._valueFromPipelineByPropertyNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified - { - get - { - return this._valueFromPipelineByPropertyNameFieldSpecified; - } - - set - { - this._valueFromPipelineByPropertyNameFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletParameterMetadataForStaticMethodParameter : CmdletParameterMetadata - { - private bool _valueFromPipelineField; - - private bool _valueFromPipelineFieldSpecified; - - private bool _valueFromPipelineByPropertyNameField; - - private bool _valueFromPipelineByPropertyNameFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipeline - { - get - { - return this._valueFromPipelineField; - } - - set - { - this._valueFromPipelineField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineSpecified - { - get - { - return this._valueFromPipelineFieldSpecified; - } - - set - { - this._valueFromPipelineFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool ValueFromPipelineByPropertyName - { - get - { - return this._valueFromPipelineByPropertyNameField; - } - - set - { - this._valueFromPipelineByPropertyNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ValueFromPipelineByPropertyNameSpecified - { - get - { - return this._valueFromPipelineByPropertyNameFieldSpecified; - } - - set - { - this._valueFromPipelineByPropertyNameFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class QueryOption - { - private TypeMetadata _typeField; - - private CmdletParameterMetadataForGetCmdletParameter _cmdletParameterMetadataField; - - private string _optionNameField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - public CmdletParameterMetadataForGetCmdletParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string OptionName - { - get - { - return this._optionNameField; - } - - set - { - this._optionNameField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class GetCmdletMetadata - { - private CommonCmdletMetadata _cmdletMetadataField; - - private GetCmdletParameters _getCmdletParametersField; - - /// - public CommonCmdletMetadata CmdletMetadata - { - get - { - return this._cmdletMetadataField; - } - - set - { - this._cmdletMetadataField = value; - } - } - - /// - public GetCmdletParameters GetCmdletParameters - { - get - { - return this._getCmdletParametersField; - } - - set - { - this._getCmdletParametersField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonCmdletMetadata - { - private ObsoleteAttributeMetadata _obsoleteField; - - private string _verbField; - - private string _nounField; - - private string[] _aliasesField; - - private ConfirmImpact _confirmImpactField; - - private bool _confirmImpactFieldSpecified; - - private string _helpUriField; - - /// - public ObsoleteAttributeMetadata Obsolete - { - get - { - return this._obsoleteField; - } - - set - { - this._obsoleteField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Verb - { - get - { - return this._verbField; - } - - set - { - this._verbField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Noun - { - get - { - return this._nounField; - } - - set - { - this._nounField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string[] Aliases - { - get - { - return this._aliasesField; - } - - set - { - this._aliasesField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public ConfirmImpact ConfirmImpact - { - get - { - return this._confirmImpactField; - } - - set - { - this._confirmImpactField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool ConfirmImpactSpecified - { - get - { - return this._confirmImpactFieldSpecified; - } - - set - { - this._confirmImpactFieldSpecified = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "anyURI")] - public string HelpUri - { - get - { - return this._helpUriField; - } - - set - { - this._helpUriField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - public enum ConfirmImpact - { - /// - None, - - /// - Low, - - /// - Medium, - - /// - High, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticCmdletMetadata - { - private StaticCmdletMetadataCmdletMetadata _cmdletMetadataField; - - private StaticMethodMetadata[] _methodField; - - /// - public StaticCmdletMetadataCmdletMetadata CmdletMetadata - { - get - { - return this._cmdletMetadataField; - } - - set - { - this._cmdletMetadataField = value; - } - } - - /// - [System.Xml.Serialization.XmlElementAttribute("Method")] - public StaticMethodMetadata[] Method - { - get - { - return this._methodField; - } - - set - { - this._methodField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticCmdletMetadataCmdletMetadata : CommonCmdletMetadata - { - private string _defaultCmdletParameterSetField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultCmdletParameterSet - { - get - { - return this._defaultCmdletParameterSetField; - } - - set - { - this._defaultCmdletParameterSetField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticMethodMetadata : CommonMethodMetadata - { - private StaticMethodParameterMetadata[] _parametersField; - - private string _cmdletParameterSetField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] - public StaticMethodParameterMetadata[] Parameters - { - get - { - return this._parametersField; - } - - set - { - this._parametersField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string CmdletParameterSet - { - get - { - return this._cmdletParameterSetField; - } - - set - { - this._cmdletParameterSetField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class StaticMethodParameterMetadata : CommonMethodParameterMetadata - { - private CmdletParameterMetadataForStaticMethodParameter _cmdletParameterMetadataField; - - private CmdletOutputMetadata _cmdletOutputMetadataField; - - /// - public CmdletParameterMetadataForStaticMethodParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - - /// - public CmdletOutputMetadata CmdletOutputMetadata - { - get - { - return this._cmdletOutputMetadataField; - } - - set - { - this._cmdletOutputMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CmdletOutputMetadata - { - private object _errorCodeField; - - private string _pSNameField; - - /// - public object ErrorCode - { - get - { - return this._errorCodeField; - } - - set - { - this._errorCodeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string PSName - { - get - { - return this._pSNameField; - } - - set - { - this._pSNameField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodParameterMetadata))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodParameterMetadata))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodParameterMetadata - { - private TypeMetadata _typeField; - - private string _parameterNameField; - - private string _defaultValueField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string ParameterName - { - get - { - return this._parameterNameField; - } - - set - { - this._parameterNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string DefaultValue - { - get - { - return this._defaultValueField; - } - - set - { - this._defaultValueField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class InstanceMethodParameterMetadata : CommonMethodParameterMetadata - { - private CmdletParameterMetadataForInstanceMethodParameter _cmdletParameterMetadataField; - - private CmdletOutputMetadata _cmdletOutputMetadataField; - - /// - public CmdletParameterMetadataForInstanceMethodParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - - /// - public CmdletOutputMetadata CmdletOutputMetadata - { - get - { - return this._cmdletOutputMetadataField; - } - - set - { - this._cmdletOutputMetadataField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(InstanceMethodMetadata))] - [System.Xml.Serialization.XmlIncludeAttribute(typeof(StaticMethodMetadata))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodMetadata - { - private CommonMethodMetadataReturnValue _returnValueField; - - private string _methodNameField; - - /// - public CommonMethodMetadataReturnValue ReturnValue - { - get - { - return this._returnValueField; - } - - set - { - this._returnValueField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string MethodName - { - get - { - return this._methodNameField; - } - - set - { - this._methodNameField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class CommonMethodMetadataReturnValue - { - private TypeMetadata _typeField; - - private CmdletOutputMetadata _cmdletOutputMetadataField; - - /// - public TypeMetadata Type - { - get - { - return this._typeField; - } - - set - { - this._typeField = value; - } - } - - /// - public CmdletOutputMetadata CmdletOutputMetadata - { - get - { - return this._cmdletOutputMetadataField; - } - - set - { - this._cmdletOutputMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class InstanceMethodMetadata : CommonMethodMetadata - { - private InstanceMethodParameterMetadata[] _parametersField; - - /// - [System.Xml.Serialization.XmlArrayItemAttribute("Parameter", IsNullable = false)] - public InstanceMethodParameterMetadata[] Parameters - { - get - { - return this._parametersField; - } - - set - { - this._parametersField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class InstanceCmdletMetadata - { - private CommonCmdletMetadata _cmdletMetadataField; - - private InstanceMethodMetadata _methodField; - - private GetCmdletParameters _getCmdletParametersField; - - /// - public CommonCmdletMetadata CmdletMetadata - { - get - { - return this._cmdletMetadataField; - } - - set - { - this._cmdletMetadataField = value; - } - } - - /// - public InstanceMethodMetadata Method - { - get - { - return this._methodField; - } - - set - { - this._methodField = value; - } - } - - /// - public GetCmdletParameters GetCmdletParameters - { - get - { - return this._getCmdletParametersField; - } - - set - { - this._getCmdletParametersField = value; - } - } - } - - /// - [System.Xml.Serialization.XmlIncludeAttribute(typeof(WildcardablePropertyQuery))] - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class PropertyQuery - { - private CmdletParameterMetadataForGetCmdletFilteringParameter _cmdletParameterMetadataField; - - /// - public CmdletParameterMetadataForGetCmdletFilteringParameter CmdletParameterMetadata - { - get - { - return this._cmdletParameterMetadataField; - } - - set - { - this._cmdletParameterMetadataField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class WildcardablePropertyQuery : PropertyQuery - { - private bool _allowGlobbingField; - - private bool _allowGlobbingFieldSpecified; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool AllowGlobbing - { - get - { - return this._allowGlobbingField; - } - - set - { - this._allowGlobbingField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool AllowGlobbingSpecified - { - get - { - return this._allowGlobbingFieldSpecified; - } - - set - { - this._allowGlobbingFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Xml.Serialization.XmlTypeAttribute(Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11", IncludeInSchema = false)] - public enum ItemsChoiceType - { - /// - ExcludeQuery, - - /// - MaxValueQuery, - - /// - MinValueQuery, - - /// - RegularQuery, - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class ClassMetadataData - { - private string _nameField; - - private string _valueField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Name - { - get - { - return this._nameField; - } - - set - { - this._nameField = value; - } - } - - /// - [System.Xml.Serialization.XmlTextAttribute()] - public string Value - { - get - { - return this._valueField; - } - - set - { - this._valueField = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class EnumMetadataEnum - { - private EnumMetadataEnumValue[] _valueField; - - private string _enumNameField; - - private string _underlyingTypeField; - - private bool _bitwiseFlagsField; - - private bool _bitwiseFlagsFieldSpecified; - - /// - [System.Xml.Serialization.XmlElementAttribute("Value")] - public EnumMetadataEnumValue[] Value - { - get - { - return this._valueField; - } - - set - { - this._valueField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string EnumName - { - get - { - return this._enumNameField; - } - - set - { - this._enumNameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string UnderlyingType - { - get - { - return this._underlyingTypeField; - } - - set - { - this._underlyingTypeField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public bool BitwiseFlags - { - get - { - return this._bitwiseFlagsField; - } - - set - { - this._bitwiseFlagsField = value; - } - } - - /// - [System.Xml.Serialization.XmlIgnoreAttribute()] - public bool BitwiseFlagsSpecified - { - get - { - return this._bitwiseFlagsFieldSpecified; - } - - set - { - this._bitwiseFlagsFieldSpecified = value; - } - } - } - - /// - [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.17929")] - [System.SerializableAttribute()] - [System.Diagnostics.DebuggerStepThroughAttribute()] - [System.ComponentModel.DesignerCategoryAttribute("code")] - [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true, Namespace = "http://schemas.microsoft.com/cmdlets-over-objects/2009/11")] - internal partial class EnumMetadataEnumValue - { - private string _nameField; - - private string _valueField; - - /// - [System.Xml.Serialization.XmlAttributeAttribute()] - public string Name - { - get - { - return this._nameField; - } - - set - { - this._nameField = value; - } - } - - /// - [System.Xml.Serialization.XmlAttributeAttribute(DataType = "integer")] - public string Value - { - get - { - return this._valueField; - } - - set - { - this._valueField = value; - } - } - } -} - diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs deleted file mode 100644 index a05d597999a..00000000000 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xmlSerializer.autogen.cs +++ /dev/null @@ -1,10023 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// PLEASE DO NOT EDIT THIS FILE BY HAND!!! -// -// This file has been generated -// by D:\bluedev\admin\monad\src\cimSupport\cmdletization\xml\generate.ps1 -// -// Generation timestamp: 10/21/2013 18:29:23 - -#pragma warning disable -#if _DYNAMIC_XMLSERIALIZER_COMPILATION - -#endif - -namespace Microsoft.PowerShell.Cmdletization.Xml -{ - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializationWriter1 : System.Xml.Serialization.XmlSerializationWriter - { - public void Write50_PowerShellMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteEmptyTag(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - return; - } - - TopLevelElement(); - Write39_PowerShellMetadata(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)o), false, false); - } - - public void Write51_ClassMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ClassMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write36_ClassMetadata(@"ClassMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o), true, false); - } - - public void Write52_ClassMetadataInstanceCmdlets(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ClassMetadataInstanceCmdlets", string.Empty); - return; - } - - TopLevelElement(); - Write40_ClassMetadataInstanceCmdlets(@"ClassMetadataInstanceCmdlets", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o), true, false); - } - - public void Write53_GetCmdletParameters(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"GetCmdletParameters", string.Empty); - return; - } - - TopLevelElement(); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o), true, false); - } - - public void Write54_PropertyMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"PropertyMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write15_PropertyMetadata(@"PropertyMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)o), true, false); - } - - public void Write55_TypeMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"TypeMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write2_TypeMetadata(@"TypeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o), true, false); - } - - public void Write56_Association(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"Association", string.Empty); - return; - } - - TopLevelElement(); - Write17_Association(@"Association", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)o), true, false); - } - - public void Write57_AssociationAssociatedInstance(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"AssociationAssociatedInstance", string.Empty); - return; - } - - TopLevelElement(); - Write41_AssociationAssociatedInstance(@"AssociationAssociatedInstance", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o), true, false); - } - - public void Write58_CmdletParameterMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write10_CmdletParameterMetadata(@"CmdletParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)o), true, false); - } - - public void Write59_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletParameter", string.Empty); - return; - } - - TopLevelElement(); - Write11_Item(@"CmdletParameterMetadataForGetCmdletParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o), true, false); - } - - public void Write60_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForGetCmdletFilteringParameter", string.Empty); - return; - } - - TopLevelElement(); - Write12_Item(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o), true, false); - } - - public void Write61_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataValidateCount", string.Empty); - return; - } - - TopLevelElement(); - Write42_Item(@"CmdletParameterMetadataValidateCount", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o), true, false); - } - - public void Write62_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataValidateLength", string.Empty); - return; - } - - TopLevelElement(); - Write43_Item(@"CmdletParameterMetadataValidateLength", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o), true, false); - } - - public void Write63_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataValidateRange", string.Empty); - return; - } - - TopLevelElement(); - Write44_Item(@"CmdletParameterMetadataValidateRange", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o), true, false); - } - - public void Write64_ObsoleteAttributeMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ObsoleteAttributeMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write7_ObsoleteAttributeMetadata(@"ObsoleteAttributeMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o), true, false); - } - - public void Write65_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForInstanceMethodParameter", string.Empty); - return; - } - - TopLevelElement(); - Write9_Item(@"CmdletParameterMetadataForInstanceMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o), true, false); - } - - public void Write66_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletParameterMetadataForStaticMethodParameter", string.Empty); - return; - } - - TopLevelElement(); - Write8_Item(@"CmdletParameterMetadataForStaticMethodParameter", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o), true, false); - } - - public void Write67_QueryOption(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"QueryOption", string.Empty); - return; - } - - TopLevelElement(); - Write18_QueryOption(@"QueryOption", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)o), true, false); - } - - public void Write68_GetCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"GetCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write22_GetCmdletMetadata(@"GetCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o), true, false); - } - - public void Write69_CommonCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write21_CommonCmdletMetadata(@"CommonCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o), true, false); - } - - public void Write70_ConfirmImpact(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteEmptyTag(@"ConfirmImpact", string.Empty); - return; - } - - WriteElementString(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o))); - } - - public void Write71_StaticCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write34_StaticCmdletMetadata(@"StaticCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)o), true, false); - } - - public void Write72_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticCmdletMetadataCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write45_Item(@"StaticCmdletMetadataCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o), true, false); - } - - public void Write73_CommonMethodMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonMethodMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write29_CommonMethodMetadata(@"CommonMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)o), true, false); - } - - public void Write74_StaticMethodMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticMethodMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write28_StaticMethodMetadata(@"StaticMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o), true, false); - } - - public void Write75_CommonMethodParameterMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonMethodParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write26_CommonMethodParameterMetadata(@"CommonMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)o), true, false); - } - - public void Write76_StaticMethodParameterMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"StaticMethodParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write27_StaticMethodParameterMetadata(@"StaticMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o), true, false); - } - - public void Write77_CmdletOutputMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CmdletOutputMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o), true, false); - } - - public void Write78_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"InstanceMethodParameterMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write25_Item(@"InstanceMethodParameterMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o), true, false); - } - - public void Write79_Item(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"CommonMethodMetadataReturnValue", string.Empty); - return; - } - - TopLevelElement(); - Write46_Item(@"CommonMethodMetadataReturnValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o), true, false); - } - - public void Write80_InstanceMethodMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"InstanceMethodMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write30_InstanceMethodMetadata(@"InstanceMethodMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o), true, false); - } - - public void Write81_InstanceCmdletMetadata(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"InstanceCmdletMetadata", string.Empty); - return; - } - - TopLevelElement(); - Write31_InstanceCmdletMetadata(@"InstanceCmdletMetadata", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)o), true, false); - } - - public void Write82_PropertyQuery(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"PropertyQuery", string.Empty); - return; - } - - TopLevelElement(); - Write14_PropertyQuery(@"PropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)o), true, false); - } - - public void Write83_WildcardablePropertyQuery(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"WildcardablePropertyQuery", string.Empty); - return; - } - - TopLevelElement(); - Write13_WildcardablePropertyQuery(@"WildcardablePropertyQuery", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o), true, false); - } - - public void Write84_ItemsChoiceType(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteEmptyTag(@"ItemsChoiceType", string.Empty); - return; - } - - WriteElementString(@"ItemsChoiceType", @"", Write3_ItemsChoiceType(((global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)o))); - } - - public void Write85_ClassMetadataData(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"ClassMetadataData", string.Empty); - return; - } - - TopLevelElement(); - Write47_ClassMetadataData(@"ClassMetadataData", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)o), true, false); - } - - public void Write86_EnumMetadataEnum(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"EnumMetadataEnum", string.Empty); - return; - } - - TopLevelElement(); - Write48_EnumMetadataEnum(@"EnumMetadataEnum", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)o), true, false); - } - - public void Write87_EnumMetadataEnumValue(object o) - { - WriteStartDocument(); - if (o == null) - { - WriteNullTagLiteral(@"EnumMetadataEnumValue", string.Empty); - return; - } - - TopLevelElement(); - Write49_EnumMetadataEnumValue(@"EnumMetadataEnumValue", @"", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)o), true, false); - } - - private void Write49_EnumMetadataEnumValue(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"EnumMetadataEnumValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - WriteAttribute(@"Value", @"", ((global::System.String)o.@Value)); - WriteEndElement(o); - } - - private void Write48_EnumMetadataEnum(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"EnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); - WriteAttribute(@"UnderlyingType", @"", ((global::System.String)o.@UnderlyingType)); - if (o.@BitwiseFlagsSpecified) - { - WriteAttribute(@"BitwiseFlags", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@BitwiseFlags))); - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])o.@Value; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write37_EnumMetadataEnumValue(@"Value", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)a[ia]), false, false); - } - } - } - - if (o.@BitwiseFlagsSpecified) - { - } - - WriteEndElement(o); - } - - private void Write37_EnumMetadataEnumValue(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - WriteAttribute(@"Value", @"", ((global::System.String)o.@Value)); - WriteEndElement(o); - } - - private void Write47_ClassMetadataData(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - if ((object)(o.@Value) != null) - { - WriteValue(((global::System.String)o.@Value)); - } - - WriteEndElement(o); - } - - private string Write3_ItemsChoiceType(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType v) - { - string s = null; - switch (v) - { - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery: s = @"ExcludeQuery"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery: s = @"MaxValueQuery"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery: s = @"MinValueQuery"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery: s = @"RegularQuery"; break; - default: throw CreateInvalidEnumValueException(((System.Int64)v).ToString(System.Globalization.CultureInfo.InvariantCulture), @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType"); - } - - return s; - } - - private void Write13_WildcardablePropertyQuery(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"WildcardablePropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@AllowGlobbingSpecified) - { - WriteAttribute(@"AllowGlobbing", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@AllowGlobbing))); - } - - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - if (o.@AllowGlobbingSpecified) - { - } - - WriteEndElement(o); - } - - private void Write12_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForGetCmdletFilteringParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) - { - WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - { - global::System.String[] a = (global::System.String[])o.@CmdletParameterSets; - if (a != null) - { - Writer.WriteStartAttribute(null, @"CmdletParameterSets", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ErrorOnNoMatchSpecified) - { - WriteAttribute(@"ErrorOnNoMatch", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ErrorOnNoMatch))); - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineSpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - if (o.@ErrorOnNoMatchSpecified) - { - } - - WriteEndElement(o); - } - - private void Write7_ObsoleteAttributeMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ObsoleteAttributeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Message", @"", ((global::System.String)o.@Message)); - WriteEndElement(o); - } - - private void Write6_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write5_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write4_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write1_Object(string n, string ns, global::System.Object o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::System.Object)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) - { - Write49_EnumMetadataEnumValue(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) - { - Write48_EnumMetadataEnum(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) - { - Write47_ClassMetadataData(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) - { - Write46_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) - { - Write44_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) - { - Write43_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) - { - Write42_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) - { - Write41_AssociationAssociatedInstance(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) - { - Write40_ClassMetadataInstanceCmdlets(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) - { - Write36_ClassMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) - { - Write34_StaticCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) - { - Write31_InstanceCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) - { - Write26_CommonMethodParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) - { - Write27_StaticMethodParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) - { - Write25_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) - { - Write29_CommonMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) - { - Write30_InstanceMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) - { - Write28_StaticMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) - { - Write23_CmdletOutputMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) - { - Write22_GetCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) - { - Write21_CommonCmdletMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - Write45_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) - { - Write19_GetCmdletParameters(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) - { - Write18_QueryOption(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) - { - Write17_Association(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.Association)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) - { - Write15_PropertyMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) - { - Write14_PropertyQuery(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) - { - Write13_WildcardablePropertyQuery(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) - { - Write10_CmdletParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) - { - Write11_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - Write12_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) - { - Write9_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) - { - Write8_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) - { - Write7_ObsoleteAttributeMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) - { - Write2_TypeMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ItemsChoiceType", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Writer.WriteString(Write3_ItemsChoiceType((global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)o)); - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::System.String[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::System.String[] a = (global::System.String[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfPropertyMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write15_PropertyMetadata(@"Property", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfAssociation", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write17_Association(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfQueryOption", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write18_QueryOption(@"Option", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ConfirmImpact", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Writer.WriteString(Write20_ConfirmImpact((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o)); - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfStaticMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write27_StaticMethodParameterMetadata(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfInstanceMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write25_Item(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfStaticCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write34_StaticCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfClassMetadataData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write35_ClassMetadataData(@"Data", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])) - { - Writer.WriteStartElement(n, ns); - WriteXsiType(@"ArrayOfEnumMetadataEnum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])o; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write38_EnumMetadataEnum(@"Enum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)a[ia]), false, false); - } - } - } - - Writer.WriteEndElement(); - return; - } - else - { - WriteTypedPrimitive(n, ns, o, true); - return; - } - } - - WriteStartElement(n, ns, o, false, null); - WriteEndElement(o); - } - - private void Write38_EnumMetadataEnum(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"EnumName", @"", ((global::System.String)o.@EnumName)); - WriteAttribute(@"UnderlyingType", @"", ((global::System.String)o.@UnderlyingType)); - if (o.@BitwiseFlagsSpecified) - { - WriteAttribute(@"BitwiseFlags", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@BitwiseFlags))); - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])o.@Value; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write37_EnumMetadataEnumValue(@"Value", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)a[ia]), false, false); - } - } - } - - if (o.@BitwiseFlagsSpecified) - { - } - - WriteEndElement(o); - } - - private void Write35_ClassMetadataData(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Name", @"", ((global::System.String)o.@Name)); - if ((object)(o.@Value) != null) - { - WriteValue(((global::System.String)o.@Value)); - } - - WriteEndElement(o); - } - - private void Write34_StaticCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write33_Item(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o.@CmdletMetadata), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])o.@Method; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write28_StaticMethodMetadata(@"Method", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)a[ia]), false, false); - } - } - } - - WriteEndElement(o); - } - - private void Write28_StaticMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); - WriteAttribute(@"CmdletParameterSet", @"", ((global::System.String)o.@CmdletParameterSet)); - Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])o.@Parameters); - if (a != null) - { - WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write27_StaticMethodParameterMetadata(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write27_StaticMethodParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); - WriteAttribute(@"DefaultValue", @"", ((global::System.String)o.@DefaultValue)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write8_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o.@CmdletParameterMetadata), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write23_CmdletOutputMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - Write1_Object(@"ErrorCode", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ErrorCode), false, false); - WriteEndElement(o); - } - - private void Write8_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForStaticMethodParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) - { - WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineSpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - WriteEndElement(o); - } - - private void Write2_TypeMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"TypeMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"PSType", @"", ((global::System.String)o.@PSType)); - WriteAttribute(@"ETSType", @"", ((global::System.String)o.@ETSType)); - WriteEndElement(o); - } - - private void Write24_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write33_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); - WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ConfirmImpactSpecified) - { - WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); - } - - WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); - WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@ConfirmImpactSpecified) - { - } - - WriteEndElement(o); - } - - private string Write20_ConfirmImpact(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact v) - { - string s = null; - switch (v) - { - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@None: s = @"None"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Low: s = @"Low"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Medium: s = @"Medium"; break; - case global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@High: s = @"High"; break; - default: throw CreateInvalidEnumValueException(((System.Int64)v).ToString(System.Globalization.CultureInfo.InvariantCulture), @"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact"); - } - - return s; - } - - private void Write25_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"InstanceMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); - WriteAttribute(@"DefaultValue", @"", ((global::System.String)o.@DefaultValue)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write9_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o.@CmdletParameterMetadata), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write9_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForInstanceMethodParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - WriteEndElement(o); - } - - private void Write18_QueryOption(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"QueryOption", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"OptionName", @"", ((global::System.String)o.@OptionName)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write11_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write11_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - Write12_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataForGetCmdletParameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - if (o.@ValueFromPipelineSpecified) - { - WriteAttribute(@"ValueFromPipeline", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipeline))); - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - WriteAttribute(@"ValueFromPipelineByPropertyName", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@ValueFromPipelineByPropertyName))); - } - { - global::System.String[] a = (global::System.String[])o.@CmdletParameterSets; - if (a != null) - { - Writer.WriteStartAttribute(null, @"CmdletParameterSets", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - if (o.@ValueFromPipelineSpecified) - { - } - - if (o.@ValueFromPipelineByPropertyNameSpecified) - { - } - - WriteEndElement(o); - } - - private void Write17_Association(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.Association o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Association", @"", ((global::System.String)o.@Association1)); - WriteAttribute(@"SourceRole", @"", ((global::System.String)o.@SourceRole)); - WriteAttribute(@"ResultRole", @"", ((global::System.String)o.@ResultRole)); - Write16_AssociationAssociatedInstance(@"AssociatedInstance", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)o.@AssociatedInstance), false, false); - WriteEndElement(o); - } - - private void Write16_AssociationAssociatedInstance(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write15_PropertyMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"PropertyMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"PropertyName", @"", ((global::System.String)o.@PropertyName)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])o.@Items; - if (a != null) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[] c = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])o.@ItemsElementName; - if (c == null || c.Length < a.Length) - { - throw CreateInvalidChoiceIdentifierValueException(@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType", @"ItemsElementName"); - } - - for (int ia = 0; ia < a.Length; ia++) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery ai = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)a[ia]; - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType ci = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)c[ia]; - { - if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery"); - Write13_WildcardablePropertyQuery(@"RegularQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)ai), false, false); - } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery"); - Write13_WildcardablePropertyQuery(@"ExcludeQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)ai), false, false); - } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery"); - Write14_PropertyQuery(@"MaxValueQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)ai), false, false); - } - else if (ci == Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery && ((object)(ai) != null)) - { - if (((object)ai) != null && ai is not global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery) throw CreateMismatchChoiceException(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery", @"ItemsElementName", @"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery"); - Write14_PropertyQuery(@"MinValueQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)ai), false, false); - } - else if ((object)(ai) != null) - { - throw CreateUnknownTypeException(ai); - } - } - } - } - } - - WriteEndElement(o); - } - - private void Write14_PropertyQuery(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) - { - Write13_WildcardablePropertyQuery(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"PropertyQuery", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write10_CmdletParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) - { - Write11_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) - { - Write12_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) - { - Write9_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) - { - Write8_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - if (o.@IsMandatorySpecified) - { - WriteAttribute(@"IsMandatory", @"", System.Xml.XmlConvert.ToString((global::System.Boolean)((global::System.Boolean)o.@IsMandatory))); - } - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - WriteAttribute(@"PSName", @"", ((global::System.String)o.@PSName)); - WriteAttribute(@"Position", @"", ((global::System.String)o.@Position)); - Write1_Object(@"AllowEmptyCollection", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyCollection), false, false); - Write1_Object(@"AllowEmptyString", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowEmptyString), false, false); - Write1_Object(@"AllowNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@AllowNull), false, false); - Write1_Object(@"ValidateNotNull", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNull), false, false); - Write1_Object(@"ValidateNotNullOrEmpty", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.Object)o.@ValidateNotNullOrEmpty), false, false); - Write4_Item(@"ValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)o.@ValidateCount), false, false); - Write5_Item(@"ValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)o.@ValidateLength), false, false); - Write6_Item(@"ValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)o.@ValidateRange), false, false); - { - global::System.String[] a = (global::System.String[])((global::System.String[])o.@ValidateSet); - if (a != null) - { - WriteStartElement(@"ValidateSet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - WriteElementString(@"AllowedValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)a[ia])); - } - - WriteEndElement(); - } - } - - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@IsMandatorySpecified) - { - } - - WriteEndElement(o); - } - - private void Write19_GetCmdletParameters(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])o.@QueryableProperties); - if (a != null) - { - WriteStartElement(@"QueryableProperties", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write15_PropertyMetadata(@"Property", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])((global::Microsoft.PowerShell.Cmdletization.Xml.Association[])o.@QueryableAssociations); - if (a != null) - { - WriteStartElement(@"QueryableAssociations", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write17_Association(@"Association", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.Association)a[ia]), false, false); - } - - WriteEndElement(); - } - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])o.@QueryOptions); - if (a != null) - { - WriteStartElement(@"QueryOptions", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write18_QueryOption(@"Option", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write45_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"StaticCmdletMetadataCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); - WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ConfirmImpactSpecified) - { - WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); - } - - WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); - WriteAttribute(@"DefaultCmdletParameterSet", @"", ((global::System.String)o.@DefaultCmdletParameterSet)); - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@ConfirmImpactSpecified) - { - } - - WriteEndElement(o); - } - - private void Write21_CommonCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) - { - Write45_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Verb", @"", ((global::System.String)o.@Verb)); - WriteAttribute(@"Noun", @"", ((global::System.String)o.@Noun)); - { - global::System.String[] a = (global::System.String[])o.@Aliases; - if (a != null) - { - Writer.WriteStartAttribute(null, @"Aliases", string.Empty); - for (int i = 0; i < a.Length; i++) - { - global::System.String ai = (global::System.String)a[i]; - if (i != 0) Writer.WriteString(" "); - WriteValue(ai); - } - - Writer.WriteEndAttribute(); - } - } - - if (o.@ConfirmImpactSpecified) - { - WriteAttribute(@"ConfirmImpact", @"", Write20_ConfirmImpact(((global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)o.@ConfirmImpact))); - } - - WriteAttribute(@"HelpUri", @"", ((global::System.String)o.@HelpUri)); - Write7_ObsoleteAttributeMetadata(@"Obsolete", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)o.@Obsolete), false, false); - if (o.@ConfirmImpactSpecified) - { - } - - WriteEndElement(o); - } - - private void Write22_GetCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"GetCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write21_CommonCmdletMetadata(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o.@CmdletMetadata), false, false); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - WriteEndElement(o); - } - - private void Write30_InstanceMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"InstanceMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); - Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])o.@Parameters); - if (a != null) - { - WriteStartElement(@"Parameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write25_Item(@"Parameter", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write29_CommonMethodMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) - { - Write30_InstanceMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) - { - Write28_StaticMethodMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonMethodMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"MethodName", @"", ((global::System.String)o.@MethodName)); - Write24_Item(@"ReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)o.@ReturnValue), false, false); - WriteEndElement(o); - } - - private void Write26_CommonMethodParameterMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) - { - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) - { - Write27_StaticMethodParameterMetadata(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)o, isNullable, true); - return; - } - else if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) - { - Write25_Item(n, ns, (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)o, isNullable, true); - return; - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonMethodParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"ParameterName", @"", ((global::System.String)o.@ParameterName)); - WriteAttribute(@"DefaultValue", @"", ((global::System.String)o.@DefaultValue)); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - WriteEndElement(o); - } - - private void Write31_InstanceCmdletMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"InstanceCmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write21_CommonCmdletMetadata(@"CmdletMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)o.@CmdletMetadata), false, false); - Write30_InstanceMethodMetadata(@"Method", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)o.@Method), false, false); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - WriteEndElement(o); - } - - private void Write36_ClassMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ClassMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"CmdletAdapter", @"", ((global::System.String)o.@CmdletAdapter)); - WriteAttribute(@"ClassName", @"", ((global::System.String)o.@ClassName)); - WriteAttribute(@"ClassVersion", @"", ((global::System.String)o.@ClassVersion)); - WriteElementString(@"Version", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)o.@Version)); - WriteElementString(@"DefaultNoun", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::System.String)o.@DefaultNoun)); - Write32_ClassMetadataInstanceCmdlets(@"InstanceCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)o.@InstanceCmdlets), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])o.@StaticCmdlets); - if (a != null) - { - WriteStartElement(@"StaticCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write34_StaticCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)a[ia]), false, false); - } - - WriteEndElement(); - } - } - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])o.@CmdletAdapterPrivateData); - if (a != null) - { - WriteStartElement(@"CmdletAdapterPrivateData", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write35_ClassMetadataData(@"Data", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - private void Write32_ClassMetadataInstanceCmdlets(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - Write22_GetCmdletMetadata(@"GetCmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o.@GetCmdlet), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])o.@Cmdlet; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write31_InstanceCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)a[ia]), false, false); - } - } - } - - WriteEndElement(o); - } - - private void Write40_ClassMetadataInstanceCmdlets(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"ClassMetadataInstanceCmdlets", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write19_GetCmdletParameters(@"GetCmdletParameters", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)o.@GetCmdletParameters), false, false); - Write22_GetCmdletMetadata(@"GetCmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)o.@GetCmdlet), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])o.@Cmdlet; - if (a != null) - { - for (int ia = 0; ia < a.Length; ia++) - { - Write31_InstanceCmdletMetadata(@"Cmdlet", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)a[ia]), false, false); - } - } - } - - WriteEndElement(o); - } - - private void Write41_AssociationAssociatedInstance(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"AssociationAssociatedInstance", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write12_Item(@"CmdletParameterMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)o.@CmdletParameterMetadata), false, false); - WriteEndElement(o); - } - - private void Write42_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataValidateCount", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write43_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataValidateLength", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write44_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CmdletParameterMetadataValidateRange", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - WriteAttribute(@"Min", @"", ((global::System.String)o.@Min)); - WriteAttribute(@"Max", @"", ((global::System.String)o.@Max)); - WriteEndElement(o); - } - - private void Write46_Item(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(@"CommonMethodMetadataReturnValue", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write2_TypeMetadata(@"Type", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)o.@Type), false, false); - Write23_CmdletOutputMetadata(@"CmdletOutputMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)o.@CmdletOutputMetadata), false, false); - WriteEndElement(o); - } - - private void Write39_PowerShellMetadata(string n, string ns, global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o, bool isNullable, bool needType) - { - if ((object)o == null) - { - if (isNullable) WriteNullTagLiteral(n, ns); - return; - } - - if (!needType) - { - System.Type t = o.GetType(); - if (t == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) - { - } - else - { - throw CreateUnknownTypeException(o); - } - } - - WriteStartElement(n, ns, o, false, null); - if (needType) WriteXsiType(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - Write36_ClassMetadata(@"Class", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)o.@Class), false, false); - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])o.@Enums); - if (a != null) - { - WriteStartElement(@"Enums", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", null, false); - for (int ia = 0; ia < a.Length; ia++) - { - Write38_EnumMetadataEnum(@"Enum", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11", ((global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)a[ia]), false, false); - } - - WriteEndElement(); - } - } - - WriteEndElement(o); - } - - protected override void InitCallbacks() - { - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializationReader1 : System.Xml.Serialization.XmlSerializationReader - { - public object Read50_PowerShellMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id1_PowerShellMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o = Read39_PowerShellMetadata(false, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:PowerShellMetadata"); - } - - return (object)o; - } - - public object Read51_ClassMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id3_ClassMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read36_ClassMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ClassMetadata"); - } - - return (object)o; - } - - public object Read52_ClassMetadataInstanceCmdlets() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id5_ClassMetadataInstanceCmdlets && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read40_ClassMetadataInstanceCmdlets(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ClassMetadataInstanceCmdlets"); - } - - return (object)o; - } - - public object Read53_GetCmdletParameters() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read19_GetCmdletParameters(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":GetCmdletParameters"); - } - - return (object)o; - } - - public object Read54_PropertyMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id7_PropertyMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read15_PropertyMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":PropertyMetadata"); - } - - return (object)o; - } - - public object Read55_TypeMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id8_TypeMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read2_TypeMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":TypeMetadata"); - } - - return (object)o; - } - - public object Read56_Association() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read17_Association(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":Association"); - } - - return (object)o; - } - - public object Read57_AssociationAssociatedInstance() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id10_AssociationAssociatedInstance && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read41_AssociationAssociatedInstance(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":AssociationAssociatedInstance"); - } - - return (object)o; - } - - public object Read58_CmdletParameterMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read10_CmdletParameterMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadata"); - } - - return (object)o; - } - - public object Read59_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id12_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read11_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForGetCmdletParameter"); - } - - return (object)o; - } - - public object Read60_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id13_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read12_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForGetCmdletFilteringParameter"); - } - - return (object)o; - } - - public object Read61_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id14_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read42_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataValidateCount"); - } - - return (object)o; - } - - public object Read62_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id15_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read43_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataValidateLength"); - } - - return (object)o; - } - - public object Read63_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id16_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read44_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataValidateRange"); - } - - return (object)o; - } - - public object Read64_ObsoleteAttributeMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id17_ObsoleteAttributeMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read7_ObsoleteAttributeMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ObsoleteAttributeMetadata"); - } - - return (object)o; - } - - public object Read65_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id18_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read9_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForInstanceMethodParameter"); - } - - return (object)o; - } - - public object Read66_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id19_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read8_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletParameterMetadataForStaticMethodParameter"); - } - - return (object)o; - } - - public object Read67_QueryOption() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id20_QueryOption && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read18_QueryOption(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":QueryOption"); - } - - return (object)o; - } - - public object Read68_GetCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id21_GetCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read22_GetCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":GetCmdletMetadata"); - } - - return (object)o; - } - - public object Read69_CommonCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id22_CommonCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read21_CommonCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonCmdletMetadata"); - } - - return (object)o; - } - - public object Read70_ConfirmImpact() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - { - o = Read20_ConfirmImpact(Reader.ReadElementString()); - } - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ConfirmImpact"); - } - - return (object)o; - } - - public object Read71_StaticCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id24_StaticCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read34_StaticCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticCmdletMetadata"); - } - - return (object)o; - } - - public object Read72_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id25_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read45_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticCmdletMetadataCmdletMetadata"); - } - - return (object)o; - } - - public object Read73_CommonMethodMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id26_CommonMethodMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read29_CommonMethodMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonMethodMetadata"); - } - - return (object)o; - } - - public object Read74_StaticMethodMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id27_StaticMethodMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read28_StaticMethodMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticMethodMetadata"); - } - - return (object)o; - } - - public object Read75_CommonMethodParameterMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id28_CommonMethodParameterMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read26_CommonMethodParameterMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonMethodParameterMetadata"); - } - - return (object)o; - } - - public object Read76_StaticMethodParameterMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id29_StaticMethodParameterMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read27_StaticMethodParameterMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":StaticMethodParameterMetadata"); - } - - return (object)o; - } - - public object Read77_CmdletOutputMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read23_CmdletOutputMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CmdletOutputMetadata"); - } - - return (object)o; - } - - public object Read78_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id31_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read25_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":InstanceMethodParameterMetadata"); - } - - return (object)o; - } - - public object Read79_Item() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id32_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read46_Item(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":CommonMethodMetadataReturnValue"); - } - - return (object)o; - } - - public object Read80_InstanceMethodMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id33_InstanceMethodMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read30_InstanceMethodMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":InstanceMethodMetadata"); - } - - return (object)o; - } - - public object Read81_InstanceCmdletMetadata() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id34_InstanceCmdletMetadata && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read31_InstanceCmdletMetadata(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":InstanceCmdletMetadata"); - } - - return (object)o; - } - - public object Read82_PropertyQuery() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id35_PropertyQuery && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read14_PropertyQuery(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":PropertyQuery"); - } - - return (object)o; - } - - public object Read83_WildcardablePropertyQuery() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id36_WildcardablePropertyQuery && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read13_WildcardablePropertyQuery(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":WildcardablePropertyQuery"); - } - - return (object)o; - } - - public object Read84_ItemsChoiceType() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id37_ItemsChoiceType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - { - o = Read3_ItemsChoiceType(Reader.ReadElementString()); - } - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ItemsChoiceType"); - } - - return (object)o; - } - - public object Read85_ClassMetadataData() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id38_ClassMetadataData && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read47_ClassMetadataData(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":ClassMetadataData"); - } - - return (object)o; - } - - public object Read86_EnumMetadataEnum() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id39_EnumMetadataEnum && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read48_EnumMetadataEnum(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":EnumMetadataEnum"); - } - - return (object)o; - } - - public object Read87_EnumMetadataEnumValue() - { - object o = null; - Reader.MoveToContent(); - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id40_EnumMetadataEnumValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o = Read49_EnumMetadataEnumValue(true, true); - } - else - { - throw CreateUnknownNodeException(); - } - } - else - { - UnknownNode(null, @":EnumMetadataEnumValue"); - } - - return (object)o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read49_EnumMetadataEnumValue(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id40_EnumMetadataEnumValue && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Value = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name, :Value"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations0 = 0; - int readerCount0 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations0, ref readerCount0); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum Read48_EnumMetadataEnum(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id39_EnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a_0 = null; - int ca_0 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id43_EnumName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@EnumName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id44_UnderlyingType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@UnderlyingType = Reader.Value; - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id45_BitwiseFlags && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@BitwiseFlags = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@BitwiseFlagsSpecified = true; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations1 = 0; - int readerCount1 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])EnsureArrayIndex(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)); a_0[ca_0++] = Read37_EnumMetadataEnumValue(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations1, ref readerCount1); - } - - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue Read37_EnumMetadataEnumValue(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Value = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name, :Value"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations2 = 0; - int readerCount2 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations2, ref readerCount2); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData Read47_ClassMetadataData(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id38_ClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations3 = 0; - int readerCount3 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - string tmp = null; - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else if (Reader.NodeType == System.Xml.XmlNodeType.Text || - Reader.NodeType == System.Xml.XmlNodeType.CDATA || - Reader.NodeType == System.Xml.XmlNodeType.Whitespace || - Reader.NodeType == System.Xml.XmlNodeType.SignificantWhitespace) - { - tmp = ReadString(tmp, false); - o.@Value = tmp; - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations3, ref readerCount3); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType Read3_ItemsChoiceType(string s) - { - switch (s) - { - case @"ExcludeQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery; - case @"MaxValueQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery; - case @"MinValueQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery; - case @"RegularQuery": return global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery; - default: throw CreateUnknownConstantException(s, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); - } - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery Read13_WildcardablePropertyQuery(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id46_AllowGlobbing && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@AllowGlobbing = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@AllowGlobbingSpecified = true; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":AllowGlobbing"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations4 = 0; - int readerCount4 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations4, ref readerCount4); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter Read12_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - global::System.String[] a_16 = null; - int ca_16 = 0; - bool[] paramsRead = new bool[18]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id51_ValueFromPipeline && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipeline = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineSpecified = true; - paramsRead[14] = true; - } - else if (!paramsRead[15] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[15] = true; - } - else if (((object)Reader.LocalName == (object)_id53_CmdletParameterSets && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_16 = (global::System.String[])EnsureArrayIndex(a_16, ca_16, typeof(global::System.String)); a_16[ca_16++] = vals[i]; - } - } - else if (!paramsRead[17] && ((object)Reader.LocalName == (object)_id54_ErrorOnNoMatch && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ErrorOnNoMatch = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ErrorOnNoMatchSpecified = true; - paramsRead[17] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets, :ErrorOnNoMatch"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations5 = 0; - int readerCount5 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations6 = 0; - int readerCount6 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations6, ref readerCount6); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations5, ref readerCount5); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata Read7_ObsoleteAttributeMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id17_ObsoleteAttributeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata(); - bool[] paramsRead = new bool[1]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id66_Message && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Message = Reader.Value; - paramsRead[0] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Message"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations7 = 0; - int readerCount7 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations7, ref readerCount7); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange Read6_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations8 = 0; - int readerCount8 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations8, ref readerCount8); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength Read5_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations9 = 0; - int readerCount9 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations9, ref readerCount9); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount Read4_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations10 = 0; - int readerCount10 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations10, ref readerCount10); - } - - ReadEndElement(); - return o; - } - - private global::System.Object Read1_Object(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (isNull) - { - if (xsiType != null) return (global::System.Object)ReadTypedNull(xsiType); - else return null; - } - - if (xsiType == null) - { - return ReadTypedPrimitive(new System.Xml.XmlQualifiedName("anyType", "http://www.w3.org/2001/XMLSchema")); - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id40_EnumMetadataEnumValue && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read49_EnumMetadataEnumValue(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id39_EnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read48_EnumMetadataEnum(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id38_ClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read47_ClassMetadataData(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id32_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read46_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id16_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read44_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id15_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read43_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id14_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read42_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id10_AssociationAssociatedInstance && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read41_AssociationAssociatedInstance(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id5_ClassMetadataInstanceCmdlets && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read40_ClassMetadataInstanceCmdlets(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id3_ClassMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read36_ClassMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id24_StaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read34_StaticCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id34_InstanceCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read31_InstanceCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id28_CommonMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read26_CommonMethodParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read27_StaticMethodParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read25_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id26_CommonMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read29_CommonMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read30_InstanceMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read28_StaticMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id30_CmdletOutputMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read23_CmdletOutputMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id21_GetCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read22_GetCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id22_CommonCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read21_CommonCmdletMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read45_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id6_GetCmdletParameters && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read19_GetCmdletParameters(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id20_QueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read18_QueryOption(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id9_Association && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read17_Association(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id7_PropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read15_PropertyMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id35_PropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read14_PropertyQuery(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read13_WildcardablePropertyQuery(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id11_CmdletParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read10_CmdletParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read11_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read12_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read9_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read8_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id17_ObsoleteAttributeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read7_ObsoleteAttributeMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id8_TypeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read2_TypeMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id37_ItemsChoiceType && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - Reader.ReadStartElement(); - object e = Read3_ItemsChoiceType(CollapseWhitespace(Reader.ReadString())); - ReadEndElement(); - return e; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id69_ArrayOfString && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::System.String[] a = null; - if (!ReadNull()) - { - global::System.String[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations11 = 0; - int readerCount11 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - z_0_0 = (global::System.String[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::System.String)); z_0_0[cz_0_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations11, ref readerCount11); - } - - ReadEndElement(); - } - - a = (global::System.String[])ShrinkArray(z_0_0, cz_0_0, typeof(global::System.String), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id70_ArrayOfPropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations12 = 0; - int readerCount12 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id71_Property && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)); z_0_0[cz_0_0++] = Read15_PropertyMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations12, ref readerCount12); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id72_ArrayOfAssociation && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations13 = 0; - int readerCount13 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)); z_0_0[cz_0_0++] = Read17_Association(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations13, ref readerCount13); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id73_ArrayOfQueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations14 = 0; - int readerCount14 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id74_Option && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)); z_0_0[cz_0_0++] = Read18_QueryOption(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations14, ref readerCount14); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id23_ConfirmImpact && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - Reader.ReadStartElement(); - object e = Read20_ConfirmImpact(CollapseWhitespace(Reader.ReadString())); - ReadEndElement(); - return e; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id75_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations15 = 0; - int readerCount15 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)); z_0_0[cz_0_0++] = Read27_StaticMethodParameterMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations15, ref readerCount15); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id77_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations16 = 0; - int readerCount16 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)); z_0_0[cz_0_0++] = Read25_Item(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations16, ref readerCount16); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id78_ArrayOfStaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations17 = 0; - int readerCount17 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)); z_0_0[cz_0_0++] = Read34_StaticCmdletMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations17, ref readerCount17); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id80_ArrayOfClassMetadataData && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations18 = 0; - int readerCount18 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id81_Data && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)); z_0_0[cz_0_0++] = Read35_ClassMetadataData(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations18, ref readerCount18); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); - } - - return a; - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id82_ArrayOfEnumMetadataEnum && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a = null; - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] z_0_0 = null; - int cz_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations19 = 0; - int readerCount19 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id83_Enum && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - z_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])EnsureArrayIndex(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)); z_0_0[cz_0_0++] = Read38_EnumMetadataEnum(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations19, ref readerCount19); - } - - ReadEndElement(); - } - - a = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(z_0_0, cz_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); - } - - return a; - } - else - return ReadTypedPrimitive((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::System.Object o; - o = new global::System.Object(); - bool[] paramsRead = Array.Empty(); - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations20 = 0; - int readerCount20 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations20, ref readerCount20); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum Read38_EnumMetadataEnum(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum(); - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[] a_0 = null; - int ca_0 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id43_EnumName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@EnumName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id44_UnderlyingType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@UnderlyingType = Reader.Value; - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id45_BitwiseFlags && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@BitwiseFlags = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@BitwiseFlagsSpecified = true; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":EnumName, :UnderlyingType, :BitwiseFlags"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations21 = 0; - int readerCount21 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id42_Value && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])EnsureArrayIndex(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)); a_0[ca_0++] = Read37_EnumMetadataEnumValue(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Value"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations21, ref readerCount21); - } - - o.@Value = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue[])ShrinkArray(a_0, ca_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData Read35_ClassMetadataData(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id41_Name && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Name = Reader.Value; - paramsRead[0] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Name"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations22 = 0; - int readerCount22 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - string tmp = null; - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else if (Reader.NodeType == System.Xml.XmlNodeType.Text || - Reader.NodeType == System.Xml.XmlNodeType.CDATA || - Reader.NodeType == System.Xml.XmlNodeType.Whitespace || - Reader.NodeType == System.Xml.XmlNodeType.SignificantWhitespace) - { - tmp = ReadString(tmp, false); - o.@Value = tmp; - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations22, ref readerCount22); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata Read34_StaticCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id24_StaticCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[] a_1 = null; - int ca_1 = 0; - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations23 = 0; - int readerCount23 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id84_CmdletMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletMetadata = Read33_Item(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id85_Method && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)); a_1[ca_1++] = Read28_StaticMethodMetadata(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations23, ref readerCount23); - } - - o.@Method = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata Read28_StaticMethodMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id86_MethodName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@MethodName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id87_CmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@CmdletParameterSet = Reader.Value; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":MethodName, :CmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations24 = 0; - int readerCount24 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id88_ReturnValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ReturnValue = Read24_Item(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id89_Parameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[] a_2_0 = null; - int ca_2_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations25 = 0; - int readerCount25 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)); a_2_0[ca_2_0++] = Read27_StaticMethodParameterMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations25, ref readerCount25); - } - - ReadEndElement(); - } - - o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations24, ref readerCount24); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata Read27_StaticMethodParameterMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata(); - bool[] paramsRead = new bool[5]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id90_ParameterName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ParameterName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultValue = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":ParameterName, :DefaultValue"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations26 = 0; - int readerCount26 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read8_Item(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[4] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations26, ref readerCount26); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata Read23_CmdletOutputMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id30_CmdletOutputMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":PSName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations27 = 0; - int readerCount27 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id93_ErrorCode && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ErrorCode = Read1_Object(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ErrorCode"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations27, ref readerCount27); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter Read8_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - bool[] paramsRead = new bool[16]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id51_ValueFromPipeline && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipeline = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineSpecified = true; - paramsRead[14] = true; - } - else if (!paramsRead[15] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[15] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations28 = 0; - int readerCount28 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations29 = 0; - int readerCount29 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations29, ref readerCount29); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations28, ref readerCount28); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata Read2_TypeMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id8_TypeMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id94_PSType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSType = Reader.Value; - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id95_ETSType && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ETSType = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":PSType, :ETSType"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations30 = 0; - int readerCount30 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations30, ref readerCount30); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue Read24_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations31 = 0; - int readerCount31 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations31, ref readerCount31); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata Read33_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); - global::System.String[] a_3 = null; - int ca_3 = 0; - bool[] paramsRead = new bool[7]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id96_Verb && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Verb = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id97_Noun && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Noun = Reader.Value; - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_3 = (global::System.String[])EnsureArrayIndex(a_3, ca_3, typeof(global::System.String)); a_3[ca_3++] = vals[i]; - } - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = true; - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@HelpUri = CollapseWhitespace(Reader.Value); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id99_DefaultCmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultCmdletParameterSet = Reader.Value; - paramsRead[6] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations32 = 0; - int readerCount32 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations32, ref readerCount32); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact Read20_ConfirmImpact(string s) - { - switch (s) - { - case @"None": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@None; - case @"Low": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Low; - case @"Medium": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@Medium; - case @"High": return global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact.@High; - default: throw CreateUnknownConstantException(s, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)); - } - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata Read25_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata(); - bool[] paramsRead = new bool[5]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id90_ParameterName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ParameterName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultValue = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":ParameterName, :DefaultValue"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations33 = 0; - int readerCount33 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read9_Item(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[4] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations33, ref readerCount33); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter Read9_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - bool[] paramsRead = new bool[15]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[14] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipelineByPropertyName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations34 = 0; - int readerCount34 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations35 = 0; - int readerCount35 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations35, ref readerCount35); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations34, ref readerCount34); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption Read18_QueryOption(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id20_QueryOption && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption(); - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id100_OptionName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@OptionName = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":OptionName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations36 = 0; - int readerCount36 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read11_Item(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations36, ref readerCount36); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter Read11_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read12_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - global::System.String[] a_16 = null; - int ca_16 = 0; - bool[] paramsRead = new bool[17]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!paramsRead[14] && ((object)Reader.LocalName == (object)_id51_ValueFromPipeline && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipeline = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineSpecified = true; - paramsRead[14] = true; - } - else if (!paramsRead[15] && ((object)Reader.LocalName == (object)_id52_Item && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ValueFromPipelineByPropertyName = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@ValueFromPipelineByPropertyNameSpecified = true; - paramsRead[15] = true; - } - else if (((object)Reader.LocalName == (object)_id53_CmdletParameterSets && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_16 = (global::System.String[])EnsureArrayIndex(a_16, ca_16, typeof(global::System.String)); a_16[ca_16++] = vals[i]; - } - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position, :ValueFromPipeline, :ValueFromPipelineByPropertyName, :CmdletParameterSets"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations37 = 0; - int readerCount37 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations38 = 0; - int readerCount38 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations38, ref readerCount38); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations37, ref readerCount37); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - o.@CmdletParameterSets = (global::System.String[])ShrinkArray(a_16, ca_16, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.Association Read17_Association(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id9_Association && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.Association o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.Association(); - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Association1 = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id101_SourceRole && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@SourceRole = Reader.Value; - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id102_ResultRole && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ResultRole = Reader.Value; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Association, :SourceRole, :ResultRole"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations39 = 0; - int readerCount39 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id103_AssociatedInstance && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AssociatedInstance = Read16_AssociationAssociatedInstance(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AssociatedInstance"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations39, ref readerCount39); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance Read16_AssociationAssociatedInstance(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations40 = 0; - int readerCount40 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations40, ref readerCount40); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata Read15_PropertyMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id7_PropertyMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[] a_1 = null; - int ca_1 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[] choice_a_1 = null; - int cchoice_a_1 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id104_PropertyName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PropertyName = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":PropertyName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Items = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery), true); - o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations41 = 0; - int readerCount41 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id105_MaxValueQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read14_PropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MaxValueQuery; - } - else if (((object)Reader.LocalName == (object)_id106_RegularQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read13_WildcardablePropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@RegularQuery; - } - else if (((object)Reader.LocalName == (object)_id107_ExcludeQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read13_WildcardablePropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@ExcludeQuery; - } - else if (((object)Reader.LocalName == (object)_id108_MinValueQuery && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])EnsureArrayIndex(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)); a_1[ca_1++] = Read14_PropertyQuery(false, true); - choice_a_1 = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])EnsureArrayIndex(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)); choice_a_1[cchoice_a_1++] = global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType.@MinValueQuery; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MaxValueQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:RegularQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ExcludeQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MinValueQuery"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MaxValueQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:RegularQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ExcludeQuery, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:MinValueQuery"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations41, ref readerCount41); - } - - o.@Items = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery[])ShrinkArray(a_1, ca_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery), true); - o.@ItemsElementName = (global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType[])ShrinkArray(choice_a_1, cchoice_a_1, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery Read14_PropertyQuery(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id35_PropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id36_WildcardablePropertyQuery && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read13_WildcardablePropertyQuery(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery(); - bool[] paramsRead = new bool[1]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations42 = 0; - int readerCount42 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations42, ref readerCount42); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata Read10_CmdletParameterMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id11_CmdletParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id12_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read11_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id13_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read12_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id18_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read9_Item(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id19_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read8_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata(); - global::System.String[] a_8 = null; - int ca_8 = 0; - global::System.String[] a_11 = null; - int ca_11 = 0; - bool[] paramsRead = new bool[14]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[10] && ((object)Reader.LocalName == (object)_id47_IsMandatory && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@IsMandatory = System.Xml.XmlConvert.ToBoolean(Reader.Value); - o.@IsMandatorySpecified = true; - paramsRead[10] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_11 = (global::System.String[])EnsureArrayIndex(a_11, ca_11, typeof(global::System.String)); a_11[ca_11++] = vals[i]; - } - } - else if (!paramsRead[12] && ((object)Reader.LocalName == (object)_id49_PSName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@PSName = Reader.Value; - paramsRead[12] = true; - } - else if (!paramsRead[13] && ((object)Reader.LocalName == (object)_id50_Position && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Position = CollapseWhitespace(Reader.Value); - paramsRead[13] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":IsMandatory, :Aliases, :PSName, :Position"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations43 = 0; - int readerCount43 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id55_AllowEmptyCollection && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyCollection = Read1_Object(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id56_AllowEmptyString && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowEmptyString = Read1_Object(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id57_AllowNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@AllowNull = Read1_Object(false, true); - paramsRead[2] = true; - } - else if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id58_ValidateNotNull && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNull = Read1_Object(false, true); - paramsRead[3] = true; - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id59_ValidateNotNullOrEmpty && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateNotNullOrEmpty = Read1_Object(false, true); - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id60_ValidateCount && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateCount = Read4_Item(false, true); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id61_ValidateLength && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateLength = Read5_Item(false, true); - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id62_ValidateRange && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ValidateRange = Read6_Item(false, true); - paramsRead[7] = true; - } - else if (((object)Reader.LocalName == (object)_id63_ValidateSet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::System.String[] a_8_0 = null; - int ca_8_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations44 = 0; - int readerCount44 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id64_AllowedValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - a_8_0 = (global::System.String[])EnsureArrayIndex(a_8_0, ca_8_0, typeof(global::System.String)); a_8_0[ca_8_0++] = Reader.ReadElementString(); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowedValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations44, ref readerCount44); - } - - ReadEndElement(); - } - - o.@ValidateSet = (global::System.String[])ShrinkArray(a_8_0, ca_8_0, typeof(global::System.String), false); - } - } - else if (!paramsRead[9] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[9] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyCollection, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowEmptyString, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:AllowNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNull, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateNotNullOrEmpty, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateCount, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateLength, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateRange, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ValidateSet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations43, ref readerCount43); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_11, ca_11, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters Read19_GetCmdletParameters(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id6_GetCmdletParameters && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters(); - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a_0 = null; - int ca_0 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a_1 = null; - int ca_1 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[4]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[3] && ((object)Reader.LocalName == (object)_id99_DefaultCmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultCmdletParameterSet = Reader.Value; - paramsRead[3] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":DefaultCmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations45 = 0; - int readerCount45 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id109_QueryableProperties && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[] a_0_0 = null; - int ca_0_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations46 = 0; - int readerCount46 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id71_Property && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_0_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])EnsureArrayIndex(a_0_0, ca_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)); a_0_0[ca_0_0++] = Read15_PropertyMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Property"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations46, ref readerCount46); - } - - ReadEndElement(); - } - - o.@QueryableProperties = (global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata[])ShrinkArray(a_0_0, ca_0_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata), false); - } - } - else if (((object)Reader.LocalName == (object)_id110_QueryableAssociations && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.Association[] a_1_0 = null; - int ca_1_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations47 = 0; - int readerCount47 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id9_Association && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])EnsureArrayIndex(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)); a_1_0[ca_1_0++] = Read17_Association(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Association"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations47, ref readerCount47); - } - - ReadEndElement(); - } - - o.@QueryableAssociations = (global::Microsoft.PowerShell.Cmdletization.Xml.Association[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association), false); - } - } - else if (((object)Reader.LocalName == (object)_id111_QueryOptions && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[] a_2_0 = null; - int ca_2_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations48 = 0; - int readerCount48 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id74_Option && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)); a_2_0[ca_2_0++] = Read18_QueryOption(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Option"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations48, ref readerCount48); - } - - ReadEndElement(); - } - - o.@QueryOptions = (global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableProperties, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableAssociations, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryOptions"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableProperties, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryableAssociations, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:QueryOptions"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations45, ref readerCount45); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata Read45_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata(); - global::System.String[] a_3 = null; - int ca_3 = 0; - bool[] paramsRead = new bool[7]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id96_Verb && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Verb = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id97_Noun && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Noun = Reader.Value; - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_3 = (global::System.String[])EnsureArrayIndex(a_3, ca_3, typeof(global::System.String)); a_3[ca_3++] = vals[i]; - } - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = true; - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@HelpUri = CollapseWhitespace(Reader.Value); - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id99_DefaultCmdletParameterSet && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultCmdletParameterSet = Reader.Value; - paramsRead[6] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri, :DefaultCmdletParameterSet"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations49 = 0; - int readerCount49 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations49, ref readerCount49); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata Read21_CommonCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id22_CommonCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id25_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read45_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata(); - global::System.String[] a_3 = null; - int ca_3 = 0; - bool[] paramsRead = new bool[6]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id96_Verb && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Verb = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id97_Noun && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Noun = Reader.Value; - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id48_Aliases && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - string listValues = Reader.Value; - string[] vals = listValues.Split(null); - for (int i = 0; i < vals.Length; i++) - { - a_3 = (global::System.String[])EnsureArrayIndex(a_3, ca_3, typeof(global::System.String)); a_3[ca_3++] = vals[i]; - } - } - else if (!paramsRead[4] && ((object)Reader.LocalName == (object)_id23_ConfirmImpact && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ConfirmImpact = Read20_ConfirmImpact(Reader.Value); - o.@ConfirmImpactSpecified = true; - paramsRead[4] = true; - } - else if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id98_HelpUri && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@HelpUri = CollapseWhitespace(Reader.Value); - paramsRead[5] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Verb, :Noun, :Aliases, :ConfirmImpact, :HelpUri"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations50 = 0; - int readerCount50 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id65_Obsolete && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Obsolete = Read7_ObsoleteAttributeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Obsolete"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations50, ref readerCount50); - } - - o.@Aliases = (global::System.String[])ShrinkArray(a_3, ca_3, typeof(global::System.String), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata Read22_GetCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id21_GetCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations51 = 0; - int readerCount51 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id84_CmdletMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletMetadata = Read21_CommonCmdletMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations51, ref readerCount51); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata Read30_InstanceMethodMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id86_MethodName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@MethodName = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":MethodName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations52 = 0; - int readerCount52 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id88_ReturnValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ReturnValue = Read24_Item(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id89_Parameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[] a_2_0 = null; - int ca_2_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations53 = 0; - int readerCount53 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id76_Parameter && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])EnsureArrayIndex(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)); a_2_0[ca_2_0++] = Read25_Item(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameter"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations53, ref readerCount53); - } - - ReadEndElement(); - } - - o.@Parameters = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata[])ShrinkArray(a_2_0, ca_2_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Parameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations52, ref readerCount52); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata Read29_CommonMethodMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id26_CommonMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id33_InstanceMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read30_InstanceMethodMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id27_StaticMethodMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read28_StaticMethodMetadata(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id86_MethodName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@MethodName = Reader.Value; - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":MethodName"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations54 = 0; - int readerCount54 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id88_ReturnValue && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@ReturnValue = Read24_Item(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:ReturnValue"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations54, ref readerCount54); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata Read26_CommonMethodParameterMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id28_CommonMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id29_StaticMethodParameterMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read27_StaticMethodParameterMetadata(isNullable, false); - else if (((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id31_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - return Read25_Item(isNullable, false); - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata(); - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id90_ParameterName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ParameterName = Reader.Value; - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id91_DefaultValue && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@DefaultValue = Reader.Value; - paramsRead[2] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":ParameterName, :DefaultValue"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations55 = 0; - int readerCount55 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations55, ref readerCount55); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata Read31_InstanceCmdletMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id34_InstanceCmdletMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata(); - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations56 = 0; - int readerCount56 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id84_CmdletMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletMetadata = Read21_CommonCmdletMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id85_Method && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Method = Read30_InstanceMethodMetadata(false, true); - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[2] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletMetadata, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Method, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations56, ref readerCount56); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata Read36_ClassMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id3_ClassMetadata && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a_3 = null; - int ca_3 = 0; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a_4 = null; - int ca_4 = 0; - bool[] paramsRead = new bool[8]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[5] && ((object)Reader.LocalName == (object)_id112_CmdletAdapter && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@CmdletAdapter = Reader.Value; - paramsRead[5] = true; - } - else if (!paramsRead[6] && ((object)Reader.LocalName == (object)_id113_ClassName && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ClassName = Reader.Value; - paramsRead[6] = true; - } - else if (!paramsRead[7] && ((object)Reader.LocalName == (object)_id114_ClassVersion && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@ClassVersion = Reader.Value; - paramsRead[7] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":CmdletAdapter, :ClassName, :ClassVersion"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations57 = 0; - int readerCount57 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id115_Version && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - o.@Version = Reader.ReadElementString(); - } - - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id116_DefaultNoun && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - { - o.@DefaultNoun = Reader.ReadElementString(); - } - - paramsRead[1] = true; - } - else if (!paramsRead[2] && ((object)Reader.LocalName == (object)_id117_InstanceCmdlets && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@InstanceCmdlets = Read32_ClassMetadataInstanceCmdlets(false, true); - paramsRead[2] = true; - } - else if (((object)Reader.LocalName == (object)_id118_StaticCmdlets && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[] a_3_0 = null; - int ca_3_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations58 = 0; - int readerCount58 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_3_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])EnsureArrayIndex(a_3_0, ca_3_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)); a_3_0[ca_3_0++] = Read34_StaticCmdletMetadata(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations58, ref readerCount58); - } - - ReadEndElement(); - } - - o.@StaticCmdlets = (global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata[])ShrinkArray(a_3_0, ca_3_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata), false); - } - } - else if (((object)Reader.LocalName == (object)_id119_CmdletAdapterPrivateData && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[] a_4_0 = null; - int ca_4_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations59 = 0; - int readerCount59 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id81_Data && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_4_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])EnsureArrayIndex(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)); a_4_0[ca_4_0++] = Read35_ClassMetadataData(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Data"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations59, ref readerCount59); - } - - ReadEndElement(); - } - - o.@CmdletAdapterPrivateData = (global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData[])ShrinkArray(a_4_0, ca_4_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Version, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:DefaultNoun, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:InstanceCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:StaticCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletAdapterPrivateData"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Version, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:DefaultNoun, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:InstanceCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:StaticCmdlets, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletAdapterPrivateData"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations57, ref readerCount57); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets Read32_ClassMetadataInstanceCmdlets(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations60 = 0; - int readerCount60 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id120_GetCmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdlet = Read22_GetCmdletMetadata(false, true); - paramsRead[1] = true; - } - else if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])EnsureArrayIndex(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)); a_2[ca_2++] = Read31_InstanceCmdletMetadata(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations60, ref readerCount60); - } - - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets Read40_ClassMetadataInstanceCmdlets(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id5_ClassMetadataInstanceCmdlets && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets(); - global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[] a_2 = null; - int ca_2 = 0; - bool[] paramsRead = new bool[3]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations61 = 0; - int readerCount61 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id6_GetCmdletParameters && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdletParameters = Read19_GetCmdletParameters(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id120_GetCmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@GetCmdlet = Read22_GetCmdletMetadata(false, true); - paramsRead[1] = true; - } - else if (((object)Reader.LocalName == (object)_id79_Cmdlet && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_2 = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])EnsureArrayIndex(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)); a_2[ca_2++] = Read31_InstanceCmdletMetadata(false, true); - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdletParameters, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:GetCmdlet, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Cmdlet"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations61, ref readerCount61); - } - - o.@Cmdlet = (global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata[])ShrinkArray(a_2, ca_2, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata), true); - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance Read41_AssociationAssociatedInstance(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id10_AssociationAssociatedInstance && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations62 = 0; - int readerCount62 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id11_CmdletParameterMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletParameterMetadata = Read12_Item(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletParameterMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations62, ref readerCount62); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount Read42_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id14_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations63 = 0; - int readerCount63 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations63, ref readerCount63); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength Read43_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id15_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations64 = 0; - int readerCount64 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations64, ref readerCount64); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange Read44_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id16_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id67_Min && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Min = CollapseWhitespace(Reader.Value); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id68_Max && (object)Reader.NamespaceURI == (object)_id4_Item)) - { - o.@Max = CollapseWhitespace(Reader.Value); - paramsRead[1] = true; - } - else if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o, @":Min, :Max"); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations65 = 0; - int readerCount65 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - UnknownNode((object)o, string.Empty); - } - else - { - UnknownNode((object)o, string.Empty); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations65, ref readerCount65); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue Read46_Item(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id32_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue(); - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations66 = 0; - int readerCount66 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id92_Type && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Type = Read2_TypeMetadata(false, true); - paramsRead[0] = true; - } - else if (!paramsRead[1] && ((object)Reader.LocalName == (object)_id30_CmdletOutputMetadata && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@CmdletOutputMetadata = Read23_CmdletOutputMetadata(false, true); - paramsRead[1] = true; - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Type, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:CmdletOutputMetadata"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations66, ref readerCount66); - } - - ReadEndElement(); - return o; - } - - private global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata Read39_PowerShellMetadata(bool isNullable, bool checkType) - { - System.Xml.XmlQualifiedName xsiType = checkType ? GetXsiType() : null; - bool isNull = false; - if (isNullable) isNull = ReadNull(); - if (checkType) - { - if (xsiType == null || ((object)((System.Xml.XmlQualifiedName)xsiType).Name == (object)_id4_Item && (object)((System.Xml.XmlQualifiedName)xsiType).Namespace == (object)_id2_Item)) - { - } - else - throw CreateUnknownTypeException((System.Xml.XmlQualifiedName)xsiType); - } - - if (isNull) return null; - global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata o; - o = new global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata(); - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a_1 = null; - int ca_1 = 0; - bool[] paramsRead = new bool[2]; - while (Reader.MoveToNextAttribute()) - { - if (!IsXmlnsAttribute(Reader.Name)) - { - UnknownNode((object)o); - } - } - - Reader.MoveToElement(); - if (Reader.IsEmptyElement) - { - Reader.Skip(); - return o; - } - - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations67 = 0; - int readerCount67 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (!paramsRead[0] && ((object)Reader.LocalName == (object)_id121_Class && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - o.@Class = Read36_ClassMetadata(false, true); - paramsRead[0] = true; - } - else if (((object)Reader.LocalName == (object)_id122_Enums && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - if (!ReadNull()) - { - global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[] a_1_0 = null; - int ca_1_0 = 0; - if ((Reader.IsEmptyElement)) - { - Reader.Skip(); - } - else - { - Reader.ReadStartElement(); - Reader.MoveToContent(); - int whileIterations68 = 0; - int readerCount68 = ReaderCount; - while (Reader.NodeType != System.Xml.XmlNodeType.EndElement && Reader.NodeType != System.Xml.XmlNodeType.None) - { - if (Reader.NodeType == System.Xml.XmlNodeType.Element) - { - if (((object)Reader.LocalName == (object)_id83_Enum && (object)Reader.NamespaceURI == (object)_id2_Item)) - { - a_1_0 = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])EnsureArrayIndex(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)); a_1_0[ca_1_0++] = Read38_EnumMetadataEnum(false, true); - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - } - else - { - UnknownNode(null, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enum"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations68, ref readerCount68); - } - - ReadEndElement(); - } - - o.@Enums = (global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum[])ShrinkArray(a_1_0, ca_1_0, typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum), false); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); - } - } - else - { - UnknownNode((object)o, @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Class, http://schemas.microsoft.com/cmdlets-over-objects/2009/11:Enums"); - } - - Reader.MoveToContent(); - CheckReaderCount(ref whileIterations67, ref readerCount67); - } - - ReadEndElement(); - return o; - } - - protected override void InitCallbacks() - { - } - - private string _id72_ArrayOfAssociation; - private string _id46_AllowGlobbing; - private string _id6_GetCmdletParameters; - private string _id25_Item; - private string _id62_ValidateRange; - private string _id118_StaticCmdlets; - private string _id58_ValidateNotNull; - private string _id17_ObsoleteAttributeMetadata; - private string _id49_PSName; - private string _id116_DefaultNoun; - private string _id38_ClassMetadataData; - private string _id114_ClassVersion; - private string _id66_Message; - private string _id65_Obsolete; - private string _id51_ValueFromPipeline; - private string _id108_MinValueQuery; - private string _id119_CmdletAdapterPrivateData; - private string _id21_GetCmdletMetadata; - private string _id120_GetCmdlet; - private string _id67_Min; - private string _id56_AllowEmptyString; - private string _id30_CmdletOutputMetadata; - private string _id106_RegularQuery; - private string _id74_Option; - private string _id75_Item; - private string _id23_ConfirmImpact; - private string _id117_InstanceCmdlets; - private string _id83_Enum; - private string _id40_EnumMetadataEnumValue; - private string _id111_QueryOptions; - private string _id34_InstanceCmdletMetadata; - private string _id60_ValidateCount; - private string _id45_BitwiseFlags; - private string _id81_Data; - private string _id31_Item; - private string _id1_PowerShellMetadata; - private string _id98_HelpUri; - private string _id91_DefaultValue; - private string _id4_Item; - private string _id32_Item; - private string _id43_EnumName; - private string _id122_Enums; - private string _id82_ArrayOfEnumMetadataEnum; - private string _id14_Item; - private string _id48_Aliases; - private string _id115_Version; - private string _id11_CmdletParameterMetadata; - private string _id70_ArrayOfPropertyMetadata; - private string _id9_Association; - private string _id102_ResultRole; - private string _id29_StaticMethodParameterMetadata; - private string _id97_Noun; - private string _id47_IsMandatory; - private string _id35_PropertyQuery; - private string _id54_ErrorOnNoMatch; - private string _id3_ClassMetadata; - private string _id77_Item; - private string _id2_Item; - private string _id22_CommonCmdletMetadata; - private string _id37_ItemsChoiceType; - private string _id36_WildcardablePropertyQuery; - private string _id113_ClassName; - private string _id64_AllowedValue; - private string _id52_Item; - private string _id55_AllowEmptyCollection; - private string _id13_Item; - private string _id76_Parameter; - private string _id19_Item; - private string _id105_MaxValueQuery; - private string _id101_SourceRole; - private string _id5_ClassMetadataInstanceCmdlets; - private string _id112_CmdletAdapter; - private string _id10_AssociationAssociatedInstance; - private string _id93_ErrorCode; - private string _id41_Name; - private string _id68_Max; - private string _id50_Position; - private string _id100_OptionName; - private string _id84_CmdletMetadata; - private string _id87_CmdletParameterSet; - private string _id104_PropertyName; - private string _id28_CommonMethodParameterMetadata; - private string _id107_ExcludeQuery; - private string _id92_Type; - private string _id33_InstanceMethodMetadata; - private string _id63_ValidateSet; - private string _id53_CmdletParameterSets; - private string _id15_Item; - private string _id109_QueryableProperties; - private string _id57_AllowNull; - private string _id80_ArrayOfClassMetadataData; - private string _id99_DefaultCmdletParameterSet; - private string _id20_QueryOption; - private string _id89_Parameters; - private string _id90_ParameterName; - private string _id61_ValidateLength; - private string _id78_ArrayOfStaticCmdletMetadata; - private string _id16_Item; - private string _id39_EnumMetadataEnum; - private string _id7_PropertyMetadata; - private string _id110_QueryableAssociations; - private string _id86_MethodName; - private string _id8_TypeMetadata; - private string _id71_Property; - private string _id27_StaticMethodMetadata; - private string _id94_PSType; - private string _id44_UnderlyingType; - private string _id103_AssociatedInstance; - private string _id79_Cmdlet; - private string _id18_Item; - private string _id85_Method; - private string _id95_ETSType; - private string _id26_CommonMethodMetadata; - private string _id88_ReturnValue; - private string _id69_ArrayOfString; - private string _id24_StaticCmdletMetadata; - private string _id59_ValidateNotNullOrEmpty; - private string _id96_Verb; - private string _id121_Class; - private string _id73_ArrayOfQueryOption; - private string _id12_Item; - private string _id42_Value; - - protected override void InitIDs() - { - _id72_ArrayOfAssociation = Reader.NameTable.Add(@"ArrayOfAssociation"); - _id46_AllowGlobbing = Reader.NameTable.Add(@"AllowGlobbing"); - _id6_GetCmdletParameters = Reader.NameTable.Add(@"GetCmdletParameters"); - _id25_Item = Reader.NameTable.Add(@"StaticCmdletMetadataCmdletMetadata"); - _id62_ValidateRange = Reader.NameTable.Add(@"ValidateRange"); - _id118_StaticCmdlets = Reader.NameTable.Add(@"StaticCmdlets"); - _id58_ValidateNotNull = Reader.NameTable.Add(@"ValidateNotNull"); - _id17_ObsoleteAttributeMetadata = Reader.NameTable.Add(@"ObsoleteAttributeMetadata"); - _id49_PSName = Reader.NameTable.Add(@"PSName"); - _id116_DefaultNoun = Reader.NameTable.Add(@"DefaultNoun"); - _id38_ClassMetadataData = Reader.NameTable.Add(@"ClassMetadataData"); - _id114_ClassVersion = Reader.NameTable.Add(@"ClassVersion"); - _id66_Message = Reader.NameTable.Add(@"Message"); - _id65_Obsolete = Reader.NameTable.Add(@"Obsolete"); - _id51_ValueFromPipeline = Reader.NameTable.Add(@"ValueFromPipeline"); - _id108_MinValueQuery = Reader.NameTable.Add(@"MinValueQuery"); - _id119_CmdletAdapterPrivateData = Reader.NameTable.Add(@"CmdletAdapterPrivateData"); - _id21_GetCmdletMetadata = Reader.NameTable.Add(@"GetCmdletMetadata"); - _id120_GetCmdlet = Reader.NameTable.Add(@"GetCmdlet"); - _id67_Min = Reader.NameTable.Add(@"Min"); - _id56_AllowEmptyString = Reader.NameTable.Add(@"AllowEmptyString"); - _id30_CmdletOutputMetadata = Reader.NameTable.Add(@"CmdletOutputMetadata"); - _id106_RegularQuery = Reader.NameTable.Add(@"RegularQuery"); - _id74_Option = Reader.NameTable.Add(@"Option"); - _id75_Item = Reader.NameTable.Add(@"ArrayOfStaticMethodParameterMetadata"); - _id23_ConfirmImpact = Reader.NameTable.Add(@"ConfirmImpact"); - _id117_InstanceCmdlets = Reader.NameTable.Add(@"InstanceCmdlets"); - _id83_Enum = Reader.NameTable.Add(@"Enum"); - _id40_EnumMetadataEnumValue = Reader.NameTable.Add(@"EnumMetadataEnumValue"); - _id111_QueryOptions = Reader.NameTable.Add(@"QueryOptions"); - _id34_InstanceCmdletMetadata = Reader.NameTable.Add(@"InstanceCmdletMetadata"); - _id60_ValidateCount = Reader.NameTable.Add(@"ValidateCount"); - _id45_BitwiseFlags = Reader.NameTable.Add(@"BitwiseFlags"); - _id81_Data = Reader.NameTable.Add(@"Data"); - _id31_Item = Reader.NameTable.Add(@"InstanceMethodParameterMetadata"); - _id1_PowerShellMetadata = Reader.NameTable.Add(@"PowerShellMetadata"); - _id98_HelpUri = Reader.NameTable.Add(@"HelpUri"); - _id91_DefaultValue = Reader.NameTable.Add(@"DefaultValue"); - _id4_Item = Reader.NameTable.Add(string.Empty); - _id32_Item = Reader.NameTable.Add(@"CommonMethodMetadataReturnValue"); - _id43_EnumName = Reader.NameTable.Add(@"EnumName"); - _id122_Enums = Reader.NameTable.Add(@"Enums"); - _id82_ArrayOfEnumMetadataEnum = Reader.NameTable.Add(@"ArrayOfEnumMetadataEnum"); - _id14_Item = Reader.NameTable.Add(@"CmdletParameterMetadataValidateCount"); - _id48_Aliases = Reader.NameTable.Add(@"Aliases"); - _id115_Version = Reader.NameTable.Add(@"Version"); - _id11_CmdletParameterMetadata = Reader.NameTable.Add(@"CmdletParameterMetadata"); - _id70_ArrayOfPropertyMetadata = Reader.NameTable.Add(@"ArrayOfPropertyMetadata"); - _id9_Association = Reader.NameTable.Add(@"Association"); - _id102_ResultRole = Reader.NameTable.Add(@"ResultRole"); - _id29_StaticMethodParameterMetadata = Reader.NameTable.Add(@"StaticMethodParameterMetadata"); - _id97_Noun = Reader.NameTable.Add(@"Noun"); - _id47_IsMandatory = Reader.NameTable.Add(@"IsMandatory"); - _id35_PropertyQuery = Reader.NameTable.Add(@"PropertyQuery"); - _id54_ErrorOnNoMatch = Reader.NameTable.Add(@"ErrorOnNoMatch"); - _id3_ClassMetadata = Reader.NameTable.Add(@"ClassMetadata"); - _id77_Item = Reader.NameTable.Add(@"ArrayOfInstanceMethodParameterMetadata"); - _id2_Item = Reader.NameTable.Add(@"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - _id22_CommonCmdletMetadata = Reader.NameTable.Add(@"CommonCmdletMetadata"); - _id37_ItemsChoiceType = Reader.NameTable.Add(@"ItemsChoiceType"); - _id36_WildcardablePropertyQuery = Reader.NameTable.Add(@"WildcardablePropertyQuery"); - _id113_ClassName = Reader.NameTable.Add(@"ClassName"); - _id64_AllowedValue = Reader.NameTable.Add(@"AllowedValue"); - _id52_Item = Reader.NameTable.Add(@"ValueFromPipelineByPropertyName"); - _id55_AllowEmptyCollection = Reader.NameTable.Add(@"AllowEmptyCollection"); - _id13_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForGetCmdletFilteringParameter"); - _id76_Parameter = Reader.NameTable.Add(@"Parameter"); - _id19_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForStaticMethodParameter"); - _id105_MaxValueQuery = Reader.NameTable.Add(@"MaxValueQuery"); - _id101_SourceRole = Reader.NameTable.Add(@"SourceRole"); - _id5_ClassMetadataInstanceCmdlets = Reader.NameTable.Add(@"ClassMetadataInstanceCmdlets"); - _id112_CmdletAdapter = Reader.NameTable.Add(@"CmdletAdapter"); - _id10_AssociationAssociatedInstance = Reader.NameTable.Add(@"AssociationAssociatedInstance"); - _id93_ErrorCode = Reader.NameTable.Add(@"ErrorCode"); - _id41_Name = Reader.NameTable.Add(@"Name"); - _id68_Max = Reader.NameTable.Add(@"Max"); - _id50_Position = Reader.NameTable.Add(@"Position"); - _id100_OptionName = Reader.NameTable.Add(@"OptionName"); - _id84_CmdletMetadata = Reader.NameTable.Add(@"CmdletMetadata"); - _id87_CmdletParameterSet = Reader.NameTable.Add(@"CmdletParameterSet"); - _id104_PropertyName = Reader.NameTable.Add(@"PropertyName"); - _id28_CommonMethodParameterMetadata = Reader.NameTable.Add(@"CommonMethodParameterMetadata"); - _id107_ExcludeQuery = Reader.NameTable.Add(@"ExcludeQuery"); - _id92_Type = Reader.NameTable.Add(@"Type"); - _id33_InstanceMethodMetadata = Reader.NameTable.Add(@"InstanceMethodMetadata"); - _id63_ValidateSet = Reader.NameTable.Add(@"ValidateSet"); - _id53_CmdletParameterSets = Reader.NameTable.Add(@"CmdletParameterSets"); - _id15_Item = Reader.NameTable.Add(@"CmdletParameterMetadataValidateLength"); - _id109_QueryableProperties = Reader.NameTable.Add(@"QueryableProperties"); - _id57_AllowNull = Reader.NameTable.Add(@"AllowNull"); - _id80_ArrayOfClassMetadataData = Reader.NameTable.Add(@"ArrayOfClassMetadataData"); - _id99_DefaultCmdletParameterSet = Reader.NameTable.Add(@"DefaultCmdletParameterSet"); - _id20_QueryOption = Reader.NameTable.Add(@"QueryOption"); - _id89_Parameters = Reader.NameTable.Add(@"Parameters"); - _id90_ParameterName = Reader.NameTable.Add(@"ParameterName"); - _id61_ValidateLength = Reader.NameTable.Add(@"ValidateLength"); - _id78_ArrayOfStaticCmdletMetadata = Reader.NameTable.Add(@"ArrayOfStaticCmdletMetadata"); - _id16_Item = Reader.NameTable.Add(@"CmdletParameterMetadataValidateRange"); - _id39_EnumMetadataEnum = Reader.NameTable.Add(@"EnumMetadataEnum"); - _id7_PropertyMetadata = Reader.NameTable.Add(@"PropertyMetadata"); - _id110_QueryableAssociations = Reader.NameTable.Add(@"QueryableAssociations"); - _id86_MethodName = Reader.NameTable.Add(@"MethodName"); - _id8_TypeMetadata = Reader.NameTable.Add(@"TypeMetadata"); - _id71_Property = Reader.NameTable.Add(@"Property"); - _id27_StaticMethodMetadata = Reader.NameTable.Add(@"StaticMethodMetadata"); - _id94_PSType = Reader.NameTable.Add(@"PSType"); - _id44_UnderlyingType = Reader.NameTable.Add(@"UnderlyingType"); - _id103_AssociatedInstance = Reader.NameTable.Add(@"AssociatedInstance"); - _id79_Cmdlet = Reader.NameTable.Add(@"Cmdlet"); - _id18_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForInstanceMethodParameter"); - _id85_Method = Reader.NameTable.Add(@"Method"); - _id95_ETSType = Reader.NameTable.Add(@"ETSType"); - _id26_CommonMethodMetadata = Reader.NameTable.Add(@"CommonMethodMetadata"); - _id88_ReturnValue = Reader.NameTable.Add(@"ReturnValue"); - _id69_ArrayOfString = Reader.NameTable.Add(@"ArrayOfString"); - _id24_StaticCmdletMetadata = Reader.NameTable.Add(@"StaticCmdletMetadata"); - _id59_ValidateNotNullOrEmpty = Reader.NameTable.Add(@"ValidateNotNullOrEmpty"); - _id96_Verb = Reader.NameTable.Add(@"Verb"); - _id121_Class = Reader.NameTable.Add(@"Class"); - _id73_ArrayOfQueryOption = Reader.NameTable.Add(@"ArrayOfQueryOption"); - _id12_Item = Reader.NameTable.Add(@"CmdletParameterMetadataForGetCmdletParameter"); - _id42_Value = Reader.NameTable.Add(@"Value"); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal abstract class XmlSerializer1 : System.Xml.Serialization.XmlSerializer - { - protected override System.Xml.Serialization.XmlSerializationReader CreateReader() - { - return new XmlSerializationReader1(); - } - - protected override System.Xml.Serialization.XmlSerializationWriter CreateWriter() - { - return new XmlSerializationWriter1(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class PowerShellMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"PowerShellMetadata", @"http://schemas.microsoft.com/cmdlets-over-objects/2009/11"); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write50_PowerShellMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read50_PowerShellMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ClassMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ClassMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write51_ClassMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read51_ClassMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ClassMetadataInstanceCmdletsSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ClassMetadataInstanceCmdlets", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write52_ClassMetadataInstanceCmdlets(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read52_ClassMetadataInstanceCmdlets(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class GetCmdletParametersSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"GetCmdletParameters", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write53_GetCmdletParameters(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read53_GetCmdletParameters(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class PropertyMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"PropertyMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write54_PropertyMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read54_PropertyMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class TypeMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"TypeMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write55_TypeMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read55_TypeMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class AssociationSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"Association", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write56_Association(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read56_Association(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class AssociationAssociatedInstanceSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"AssociationAssociatedInstance", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write57_AssociationAssociatedInstance(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read57_AssociationAssociatedInstance(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write58_CmdletParameterMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read58_CmdletParameterMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForGetCmdletParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write59_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read59_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForGetCmdletFilteringParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForGetCmdletFilteringParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write60_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read60_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataValidateCountSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateCount", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write61_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read61_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataValidateLengthSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateLength", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write62_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read62_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataValidateRangeSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataValidateRange", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write63_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read63_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ObsoleteAttributeMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ObsoleteAttributeMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write64_ObsoleteAttributeMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read64_ObsoleteAttributeMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForInstanceMethodParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForInstanceMethodParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write65_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read65_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletParameterMetadataForStaticMethodParameterSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletParameterMetadataForStaticMethodParameter", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write66_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read66_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class QueryOptionSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"QueryOption", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write67_QueryOption(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read67_QueryOption(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class GetCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"GetCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write68_GetCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read68_GetCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write69_CommonCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read69_CommonCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ConfirmImpactSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ConfirmImpact", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write70_ConfirmImpact(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read70_ConfirmImpact(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write71_StaticCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read71_StaticCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticCmdletMetadataCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticCmdletMetadataCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write72_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read72_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonMethodMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonMethodMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write73_CommonMethodMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read73_CommonMethodMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticMethodMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticMethodMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write74_StaticMethodMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read74_StaticMethodMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonMethodParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonMethodParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write75_CommonMethodParameterMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read75_CommonMethodParameterMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class StaticMethodParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"StaticMethodParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write76_StaticMethodParameterMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read76_StaticMethodParameterMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CmdletOutputMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CmdletOutputMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write77_CmdletOutputMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read77_CmdletOutputMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class InstanceMethodParameterMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"InstanceMethodParameterMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write78_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read78_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class CommonMethodMetadataReturnValueSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"CommonMethodMetadataReturnValue", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write79_Item(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read79_Item(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class InstanceMethodMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"InstanceMethodMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write80_InstanceMethodMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read80_InstanceMethodMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class InstanceCmdletMetadataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"InstanceCmdletMetadata", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write81_InstanceCmdletMetadata(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read81_InstanceCmdletMetadata(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class PropertyQuerySerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"PropertyQuery", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write82_PropertyQuery(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read82_PropertyQuery(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class WildcardablePropertyQuerySerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"WildcardablePropertyQuery", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write83_WildcardablePropertyQuery(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read83_WildcardablePropertyQuery(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ItemsChoiceTypeSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ItemsChoiceType", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write84_ItemsChoiceType(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read84_ItemsChoiceType(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class ClassMetadataDataSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"ClassMetadataData", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write85_ClassMetadataData(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read85_ClassMetadataData(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class EnumMetadataEnumSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"EnumMetadataEnum", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write86_EnumMetadataEnum(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read86_EnumMetadataEnum(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal sealed class EnumMetadataEnumValueSerializer : XmlSerializer1 - { - public override bool CanDeserialize(System.Xml.XmlReader xmlReader) - { - return xmlReader.IsStartElement(@"EnumMetadataEnumValue", string.Empty); - } - - protected override void Serialize(object objectToSerialize, System.Xml.Serialization.XmlSerializationWriter writer) - { - ((XmlSerializationWriter1)writer).Write87_EnumMetadataEnumValue(objectToSerialize); - } - - protected override object Deserialize(System.Xml.Serialization.XmlSerializationReader reader) - { - return ((XmlSerializationReader1)reader).Read87_EnumMetadataEnumValue(); - } - } - - [System.CodeDom.Compiler.GeneratedCodeAttribute("sgen", "4.0")] - internal class XmlSerializerContract : global::System.Xml.Serialization.XmlSerializerImplementation - { - public override global::System.Xml.Serialization.XmlSerializationReader Reader { get { return new XmlSerializationReader1(); } } - - public override global::System.Xml.Serialization.XmlSerializationWriter Writer { get { return new XmlSerializationWriter1(); } } - - private System.Collections.Hashtable _readMethods = null; - public override System.Collections.Hashtable ReadMethods - { - get - { - if (_readMethods == null) - { - System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata:http://schemas.microsoft.com/cmdlets-over-objects/2009/11::False:"] = @"Read50_PowerShellMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata::"] = @"Read51_ClassMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets::"] = @"Read52_ClassMetadataInstanceCmdlets"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters::"] = @"Read53_GetCmdletParameters"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata::"] = @"Read54_PropertyMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata::"] = @"Read55_TypeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.Association::"] = @"Read56_Association"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance::"] = @"Read57_AssociationAssociatedInstance"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata::"] = @"Read58_CmdletParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter::"] = @"Read59_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter::"] = @"Read60_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount::"] = @"Read61_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength::"] = @"Read62_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange::"] = @"Read63_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata::"] = @"Read64_ObsoleteAttributeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter::"] = @"Read65_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter::"] = @"Read66_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.QueryOption::"] = @"Read67_QueryOption"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata::"] = @"Read68_GetCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata::"] = @"Read69_CommonCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact::"] = @"Read70_ConfirmImpact"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata::"] = @"Read71_StaticCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata::"] = @"Read72_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata::"] = @"Read73_CommonMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata::"] = @"Read74_StaticMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata::"] = @"Read75_CommonMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata::"] = @"Read76_StaticMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata::"] = @"Read77_CmdletOutputMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata::"] = @"Read78_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue::"] = @"Read79_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata::"] = @"Read80_InstanceMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata::"] = @"Read81_InstanceCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery::"] = @"Read82_PropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::"] = @"Read83_WildcardablePropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType::"] = @"Read84_ItemsChoiceType"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData::"] = @"Read85_ClassMetadataData"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum::"] = @"Read86_EnumMetadataEnum"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::"] = @"Read87_EnumMetadataEnumValue"; - if (_readMethods == null) _readMethods = _tmp; - } - - return _readMethods; - } - } - - private System.Collections.Hashtable _writeMethods = null; - public override System.Collections.Hashtable WriteMethods - { - get - { - if (_writeMethods == null) - { - System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata:http://schemas.microsoft.com/cmdlets-over-objects/2009/11::False:"] = @"Write50_PowerShellMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata::"] = @"Write51_ClassMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets::"] = @"Write52_ClassMetadataInstanceCmdlets"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters::"] = @"Write53_GetCmdletParameters"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata::"] = @"Write54_PropertyMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata::"] = @"Write55_TypeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.Association::"] = @"Write56_Association"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance::"] = @"Write57_AssociationAssociatedInstance"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata::"] = @"Write58_CmdletParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter::"] = @"Write59_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter::"] = @"Write60_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount::"] = @"Write61_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength::"] = @"Write62_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange::"] = @"Write63_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata::"] = @"Write64_ObsoleteAttributeMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter::"] = @"Write65_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter::"] = @"Write66_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.QueryOption::"] = @"Write67_QueryOption"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata::"] = @"Write68_GetCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata::"] = @"Write69_CommonCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact::"] = @"Write70_ConfirmImpact"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata::"] = @"Write71_StaticCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata::"] = @"Write72_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata::"] = @"Write73_CommonMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata::"] = @"Write74_StaticMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata::"] = @"Write75_CommonMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata::"] = @"Write76_StaticMethodParameterMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata::"] = @"Write77_CmdletOutputMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata::"] = @"Write78_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue::"] = @"Write79_Item"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata::"] = @"Write80_InstanceMethodMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata::"] = @"Write81_InstanceCmdletMetadata"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery::"] = @"Write82_PropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::"] = @"Write83_WildcardablePropertyQuery"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType::"] = @"Write84_ItemsChoiceType"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData::"] = @"Write85_ClassMetadataData"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum::"] = @"Write86_EnumMetadataEnum"; - _tmp[@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::"] = @"Write87_EnumMetadataEnumValue"; - if (_writeMethods == null) _writeMethods = _tmp; - } - - return _writeMethods; - } - } - - private System.Collections.Hashtable _typedSerializers = null; - public override System.Collections.Hashtable TypedSerializers - { - get - { - if (_typedSerializers == null) - { - System.Collections.Hashtable _tmp = new System.Collections.Hashtable(); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance::", new AssociationAssociatedInstanceSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.Association::", new AssociationSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets::", new ClassMetadataInstanceCmdletsSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata:http://schemas.microsoft.com/cmdlets-over-objects/2009/11::False:", new PowerShellMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue::", new EnumMetadataEnumValueSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata::", new StaticCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType::", new ItemsChoiceTypeSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery::", new PropertyQuerySerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata::", new CmdletParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata::", new CommonMethodParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata::", new StaticMethodMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata::", new ObsoleteAttributeMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata::", new InstanceCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue::", new CommonMethodMetadataReturnValueSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata::", new PropertyMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter::", new CmdletParameterMetadataForGetCmdletParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata::", new CmdletOutputMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum::", new EnumMetadataEnumSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.QueryOption::", new QueryOptionSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata::", new InstanceMethodParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange::", new CmdletParameterMetadataValidateRangeSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData::", new ClassMetadataDataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact::", new ConfirmImpactSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata::", new StaticCmdletMetadataCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata::", new GetCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength::", new CmdletParameterMetadataValidateLengthSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata::", new InstanceMethodMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata::", new CommonMethodMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount::", new CmdletParameterMetadataValidateCountSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters::", new GetCmdletParametersSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter::", new CmdletParameterMetadataForInstanceMethodParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata::", new CommonCmdletMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata::", new TypeMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter::", new CmdletParameterMetadataForGetCmdletFilteringParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata::", new StaticMethodParameterMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter::", new CmdletParameterMetadataForStaticMethodParameterSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata::", new ClassMetadataSerializer()); - _tmp.Add(@"Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery::", new WildcardablePropertyQuerySerializer()); - if (_typedSerializers == null) _typedSerializers = _tmp; - } - - return _typedSerializers; - } - } - - public override bool CanSerialize(System.Type type) - { - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) return true; - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) return true; - return false; - } - - public override System.Xml.Serialization.XmlSerializer GetSerializer(System.Type type) - { - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PowerShellMetadata)) return new PowerShellMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadata)) return new ClassMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataInstanceCmdlets)) return new ClassMetadataInstanceCmdletsSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletParameters)) return new GetCmdletParametersSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyMetadata)) return new PropertyMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.TypeMetadata)) return new TypeMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.Association)) return new AssociationSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.AssociationAssociatedInstance)) return new AssociationAssociatedInstanceSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadata)) return new CmdletParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletParameter)) return new CmdletParameterMetadataForGetCmdletParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForGetCmdletFilteringParameter)) return new CmdletParameterMetadataForGetCmdletFilteringParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateCount)) return new CmdletParameterMetadataValidateCountSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateLength)) return new CmdletParameterMetadataValidateLengthSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataValidateRange)) return new CmdletParameterMetadataValidateRangeSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ObsoleteAttributeMetadata)) return new ObsoleteAttributeMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForInstanceMethodParameter)) return new CmdletParameterMetadataForInstanceMethodParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletParameterMetadataForStaticMethodParameter)) return new CmdletParameterMetadataForStaticMethodParameterSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.QueryOption)) return new QueryOptionSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.GetCmdletMetadata)) return new GetCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonCmdletMetadata)) return new CommonCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ConfirmImpact)) return new ConfirmImpactSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadata)) return new StaticCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticCmdletMetadataCmdletMetadata)) return new StaticCmdletMetadataCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadata)) return new CommonMethodMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodMetadata)) return new StaticMethodMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodParameterMetadata)) return new CommonMethodParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.StaticMethodParameterMetadata)) return new StaticMethodParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CmdletOutputMetadata)) return new CmdletOutputMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodParameterMetadata)) return new InstanceMethodParameterMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.CommonMethodMetadataReturnValue)) return new CommonMethodMetadataReturnValueSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceMethodMetadata)) return new InstanceMethodMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.InstanceCmdletMetadata)) return new InstanceCmdletMetadataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.PropertyQuery)) return new PropertyQuerySerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.WildcardablePropertyQuery)) return new WildcardablePropertyQuerySerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ItemsChoiceType)) return new ItemsChoiceTypeSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.ClassMetadataData)) return new ClassMetadataDataSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnum)) return new EnumMetadataEnumSerializer(); - if (type == typeof(global::Microsoft.PowerShell.Cmdletization.Xml.EnumMetadataEnumValue)) return new EnumMetadataEnumValueSerializer(); - return null; - } - } -} - diff --git a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd index 0766b785451..67ee8b0b0dc 100644 --- a/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd +++ b/src/System.Management.Automation/cimSupport/cmdletization/xml/cmdlets-over-objects.xsd @@ -9,10 +9,10 @@ Licensed under the MIT License. - + - + @@ -25,16 +25,16 @@ Licensed under the MIT License. ]> - This schema defines the format of PowerShell CIM Modules. - A PowerShell CIM Module defines a set of cmdlets that interact with a CIM class. - + A PowerShell CIM Module defines a set of cmdlets that interact with a CIM class. + A PowerShell CIM Module needs to be saved in a file with ".cdxml" extension. A ".cdxml" file can be imported into a PowerShell session directly by Import-Module cmdlet, or by referring to the ".cdxml" file from NestedModules or RootModule entry of @@ -87,7 +87,7 @@ Licensed under the MIT License. - + @@ -103,36 +103,36 @@ Licensed under the MIT License. - + EnumName attribute specifies the name of a .NET enum. This is the name to use in a PSType attribute. - - The name should include a namespace to avoid naming conflicts + + The name should include a namespace to avoid naming conflicts (i.e. the name should be "Networking.MyEnum" rather than "MyEnum"). - + The system will prefix the name of the enum with the following namespace: "Microsoft.PowerShell.Cmdletization.GeneratedTypes" (i.e. "Networking.MyEnum" will become "Microsoft.PowerShell.Cmdletization.GeneratedTypes.Networking.MyEnum"). When referring to the enum in types.ps1xml and format.ps1xml files, one has to use the full, prefixed name of the enum. - + Underlying type of the enum. - + C# Language Specification allows (in section 4.1.9 "Enumeration types") only the following - underlying types: - byte (System.Byte), - sbyte (System.SByte), - short (System.Int16), - ushort (System.UInt16), - int (System.Int32), - uint (System.UInt32), + underlying types: + byte (System.Byte), + sbyte (System.SByte), + short (System.Int16), + ushort (System.UInt16), + int (System.Int32), + uint (System.UInt32), long (System.Int64), ulong (System.UInt64). @@ -142,7 +142,7 @@ Licensed under the MIT License. - BitwiseFlags attribute specifies if the .NET enum will be decorated with a System.FlagsAttribute. + BitwiseFlags attribute specifies if the .NET enum will be decorated with a System.FlagsAttribute. @@ -196,7 +196,7 @@ Licensed under the MIT License. - + @@ -240,10 +240,10 @@ Licensed under the MIT License. CmdletAdapter attribute specifies which .NET class is responsible for translating - cmdlet invocations into queries and method invocations. - - If this attribute is ommited, then by default the cmdlets are translated into WMI queries and method invocations. - + cmdlet invocations into queries and method invocations. + + If this attribute is ommited, then by default the cmdlets are translated into WMI queries and method invocations. + The class specified here has to be derived from Microsoft.PowerShell.Cmdletization.CmdletAdapter class. @@ -253,7 +253,7 @@ Licensed under the MIT License. ClassName attribute specified the class that the cmdlets work against. - + Example: "root/cimv2/Win32_Process" @@ -282,8 +282,8 @@ Licensed under the MIT License. Cmdlet element under InstanceCmdlets element defines a cmdlet that wraps an instance method. - - Cmdlet parameters of a cmdlet defined this way are a sum of + + Cmdlet parameters of a cmdlet defined this way are a sum of 1) cmdlet parameters defined through GetCmdletParameters elements 2) cmdlet parameters mapped to input parameters of the method defined by Method element @@ -313,7 +313,7 @@ Licensed under the MIT License. Cmdlet element under StaticCmdlets element defines a cmdlet that wraps one or more static methods. - + Cmdlet parameters of a cmdlet defined this way are mapped to input parameters of methods defined by Method element Each wrapped method corresponds to a parameter set of the cmdlet. @@ -341,9 +341,9 @@ Licensed under the MIT License. GetCmdlet element defines cmdlet metadata for the cmdlet that queries for object instances. - + If GetCmdlet element is ommited, then the default verb ("Get") and noun (based on <DefaultNoun> element) are going to be used. - + GetCmdlet element is typically used for one of the following items: - To allow the Get cmdlet to have different GetCmdletParameters than other cmdlets (for example to make all parameters optional for Get cmdlet, but make some parameters mandatory for other cmdlets) - To change the verb of the cmdlet (for example to use "Find" where appropriate) @@ -365,19 +365,19 @@ Licensed under the MIT License. - + - + Verb attribute specifies the verb of the cmdlet. - + Please refer to Cmdlet Design Guidelines for a list of approved verbs. - + Verb attribute is equivalent to the verbName parameter of System.Management.Automation.CmdletAttribute constructor. @@ -387,9 +387,9 @@ Licensed under the MIT License. Noun attribute specifies the noun of the cmdlet. - + If the Noun attribute is ommited, then contents of the DefaultNoun element are used. - + Noun attribute is equivalent to the nounName parameter of System.Management.Automation.CmdletAttribute constructor. @@ -407,9 +407,9 @@ Licensed under the MIT License. ConfirmImpact attribute specifies the impact of the cmdlet. - + ConfirmImpact attribute determines the default -Confirm and -WhatIf behavior. - + ConfirmImpact attribute is equivalent to the ConfirmImpact property of System.Management.Automation.CmdletAttribute. Presence of the ConfirmImpact attribute is equivalent to setting to true the SupportsShouldProcess property of System.Management.Automation.CmdletAttribute. @@ -420,11 +420,11 @@ Licensed under the MIT License. HelpUri attribute specifies the URI with the help content. - + HelpUri attribute is used for the following help experience: Get-Help -Online <cmdlet name> - + HelpUri attribute is equivalent to the HelpUri property of System.Management.Automation.CmdletAttribute - + Example: "http://go.microsoft.com/fwlink/?LinkID=113309" @@ -454,12 +454,12 @@ Licensed under the MIT License. - + CmdletParameterSet attribute specifies the name of a cmdlet parameter set associated with the static method. - + If CmdletParameterSet is ommited, then the name of the cmdlet parameter set is auto-generated based on the name of the method. @@ -467,7 +467,7 @@ Licensed under the MIT License. - + @@ -508,8 +508,8 @@ Licensed under the MIT License. MethodName attribute specified the name of the method that the cmdlet invocations are mapped to. - - Some method names are recognized and handled in a special way. + + Some method names are recognized and handled in a special way. "cim:CreateInstance" is mapped to the WMI's static, intrinsic CreateInstance method. Names of method parameters have to map to names of properties. "cim:ModifyInstance" is mapped to the WMI's instance, intrinsic ModifyInstance method. Names of method parameters have to map to names of properties. "cim:DeleteInstance" is mapped to the WMI's instance, intrinsic DeleteInstance method. All method parameters are ignored. @@ -547,7 +547,7 @@ Licensed under the MIT License. - + @@ -594,7 +594,7 @@ Licensed under the MIT License. - + @@ -606,12 +606,12 @@ Licensed under the MIT License. - + Association attribute specifies the name of the association between the cmdlet argument and the instances the cmdlet acts against. - + Association attribute is equivalent to the associationClassName parameter of EnumerateAssociatedInstances method of Microsoft.Management.Infrastructure.CimSession class. @@ -627,7 +627,7 @@ Licensed under the MIT License. - + @@ -638,7 +638,7 @@ Licensed under the MIT License. - + @@ -651,43 +651,43 @@ Licensed under the MIT License. RegularQuery element defines a cmdlet parameter that limits which objects will be processed by the cmdlet - only objects with a property value equal to the cmdlet parameter argument will be processed. - + Comparison of strings and characters is always case-insensitive. - + Example for <RegularQuery> element that is applied to an ObjectId property: The following cmdlet invocation: Get-MyObject -ObjectId 123,456 will be translated into the following WQL query: - SELECT * FROM MyObject WHERE ((ObjectId = 123) OR (ObjectId = 456)) - + SELECT * FROM MyObject WHERE ((ObjectId = 123) OR (ObjectId = 456)) + Example for <RegularQuery AllowGlobbing="false" > element that is applied to a Name property: The following cmdlet invocation: - Get-MyObject -LiteralName p*,q* + Get-MyObject -LiteralName p*,q* will be translated into the following WQL query: - SELECT * FROM MyObject WHERE ((Name = "p*") OR (Name = "q*")) - + SELECT * FROM MyObject WHERE ((Name = "p*") OR (Name = "q*")) + Example for <RegularQuery AllowGlobbing="true" > element that is applied to a Name property: The following cmdlet invocation: - Get-MyObject -Name p*,q* + Get-MyObject -Name p*,q* will be translated into the following WQL query: - SELECT * FROM MyObject WHERE ((Name like "p%") OR (Name like "q%")) + SELECT * FROM MyObject WHERE ((Name like "p%") OR (Name like "q%")) - + ExcludeQuery element defines a cmdlet parameter that limits which objects will be processed by the cmdlet - only objects with a property value *not* equal to the cmdlet parameter argument will be processed. - + Comparison of strings and characters is always case-insensitive. - + Example for <ExcludeQuery> element that is applied to an ObjectId property: The following cmdlet invocation: Get-MyObject -ExcludeObjectId 123,456 will be translated into the following WQL query: - SELECT * FROM MyObject WHERE ((NOT Name = 123) AND (NOT Name = 456)) + SELECT * FROM MyObject WHERE ((NOT Name = 123) AND (NOT Name = 456)) @@ -697,7 +697,7 @@ Licensed under the MIT License. MinValueQuery element defines a cmdlet parameter that limits which objects will be processed by the cmdlet - only objects with a property value greater than or equal to the cmdlet parameter argument will be processed. - + Example for <MinValueQuery> element that is applied to an WorkingSet property: The following cmdlet invocation: Get-MyObject -MinWorkingSet 123 @@ -725,17 +725,17 @@ Licensed under the MIT License. - + - AllowGlobbing attribute specifies if strings with globbing characters (wildcards) are supported. - + AllowGlobbing attribute specifies if strings with globbing characters (wildcards) are supported. + Example of a wildcard: "foo*" (matches all strings beginning with "foo") - + If AllowGlobbing attribute is ommited then its value is based on the type of the filtered property. @@ -777,19 +777,19 @@ Licensed under the MIT License. - + - + CmdletParameterSets attribute is a whitespace-separated list of names of parameter sets, that the cmdlet parameter should belong to. - + If this parameter is ommited, then the cmdlet parameter belongs to all parameter sets. @@ -797,7 +797,7 @@ Licensed under the MIT License. - + @@ -817,14 +817,14 @@ Licensed under the MIT License. - + - + @@ -844,14 +844,14 @@ Licensed under the MIT License. - + PSName attribute specifies the name of a cmdlet parameter. - + If PSName attribute is ommited then it is based on the contents of PropertyName or ParameterName or OptionName attribute (whichever one is applicable). - + Example: <Property PropertyName="Name"> ... @@ -870,11 +870,11 @@ Licensed under the MIT License. Position attribute specifies position of the cmdlet parameter. - + If Position attribute is ommited, then the cmdlet parameter cannot be used positionally - the user always has to explicitly specify the name of the parameter. - + System may change relative parameter positions to guarantee that cmdlet parameters defined by GetCmdletParameters element are always - before cmdlet parameters defined under Method element. + before cmdlet parameters defined under Method element. @@ -885,7 +885,7 @@ Licensed under the MIT License. - + @@ -898,19 +898,19 @@ Licensed under the MIT License. PSType attribute specifies the name of the .NET type of the cmdlet parameter. - + Example: "System.String" - + ETSType attribute specifies the PowerShell type name of the type of the cmdlet parameter. - + ETSType attribute is equivalent to System.Management.Automation.PSTypeNameAttribute. - + Example: "Microsoft.Management.Infrastructure.CimInstance#Win32_Process" @@ -1011,7 +1011,7 @@ Licensed under the MIT License. - + @@ -1026,7 +1026,7 @@ Licensed under the MIT License. - + @@ -1034,7 +1034,7 @@ Licensed under the MIT License. - + diff --git a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs index f9aa9f9b73c..202c3e98e48 100644 --- a/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs +++ b/src/System.Management.Automation/cimSupport/other/ciminstancetypeadapter.cs @@ -21,8 +21,6 @@ namespace Microsoft.PowerShell.Cim /// Implementing the PropertyOnlyAdapter for the time being as CimInstanceTypeAdapter currently /// supports only properties. If method support is needed in future, this should derive from /// Adapter class. - /// - /// The Adapter registration is done in monad\src\singleshell\installer\MshManagementMshSnapin.cs /// public sealed class CimInstanceAdapter : PSPropertyAdapter { @@ -63,8 +61,7 @@ private static PSAdaptedProperty GetPSComputerNameAdapter(CimInstance cimInstanc public override System.Collections.ObjectModel.Collection GetProperties(object baseObject) { // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -109,8 +106,7 @@ public override PSAdaptedProperty GetProperty(object baseObject, string property } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format(CultureInfo.InvariantCulture, CimInstanceTypeAdapterResources.BaseObjectNotCimInstance, @@ -144,8 +140,7 @@ public override PSAdaptedProperty GetFirstPropertyOrDefault(object baseObject, M } // baseObject should never be null - CimInstance cimInstance = baseObject as CimInstance; - if (cimInstance == null) + if (baseObject is not CimInstance cimInstance) { string msg = string.Format( CultureInfo.InvariantCulture, @@ -197,13 +192,9 @@ internal static string CimTypeToTypeNameDisplayString(CimType cimType) /// public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); - CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (adaptedProperty.Tag is CimProperty cimProperty) { return CimTypeToTypeNameDisplayString(cimProperty.CimType); } @@ -222,13 +213,9 @@ public override string GetPropertyTypeName(PSAdaptedProperty adaptedProperty) /// public override object GetPropertyValue(PSAdaptedProperty adaptedProperty) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); - CimProperty cimProperty = adaptedProperty.Tag as CimProperty; - if (cimProperty != null) + if (adaptedProperty.Tag is CimProperty cimProperty) { return cimProperty.Value; } @@ -246,16 +233,11 @@ private static void AddTypeNameHierarchy(IList typeNamesWithNamespace, I { if (!string.IsNullOrEmpty(namespaceName)) { - string fullTypeName = string.Format(CultureInfo.InvariantCulture, - "Microsoft.Management.Infrastructure.CimInstance#{0}/{1}", - namespaceName, - className); + string fullTypeName = string.Create(CultureInfo.InvariantCulture, $"Microsoft.Management.Infrastructure.CimInstance#{namespaceName}/{className}"); typeNamesWithNamespace.Add(fullTypeName); } - typeNamesWithoutNamespace.Add(string.Format(CultureInfo.InvariantCulture, - "Microsoft.Management.Infrastructure.CimInstance#{0}", - className)); + typeNamesWithoutNamespace.Add(string.Create(CultureInfo.InvariantCulture, $"Microsoft.Management.Infrastructure.CimInstance#{className}")); } private static List GetInheritanceChain(CimInstance cimInstance) @@ -285,7 +267,7 @@ private static List GetInheritanceChain(CimInstance cimInstance) /// public override Collection GetTypeNameHierarchy(object baseObject) { - if (!(baseObject is CimInstance cimInstance)) + if (baseObject is not CimInstance cimInstance) { throw new ArgumentNullException(nameof(baseObject)); } @@ -361,7 +343,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) return false; } - if (!(adaptedProperty.Tag is CimProperty cimProperty)) + if (adaptedProperty.Tag is not CimProperty cimProperty) { return false; } @@ -377,10 +359,7 @@ public override bool IsSettable(PSAdaptedProperty adaptedProperty) /// public override void SetPropertyValue(PSAdaptedProperty adaptedProperty, object value) { - if (adaptedProperty == null) - { - throw new ArgumentNullException(nameof(adaptedProperty)); - } + ArgumentNullException.ThrowIfNull(adaptedProperty); if (!IsSettable(adaptedProperty)) { diff --git a/src/System.Management.Automation/engine/ApplicationInfo.cs b/src/System.Management.Automation/engine/ApplicationInfo.cs index 5fe76424f5a..ca46023b66b 100644 --- a/src/System.Management.Automation/engine/ApplicationInfo.cs +++ b/src/System.Management.Automation/engine/ApplicationInfo.cs @@ -8,7 +8,7 @@ namespace System.Management.Automation { /// - /// Provides information for applications that are not directly executable by Monad. + /// Provides information for applications that are not directly executable by PowerShell. /// /// /// An application is any file that is executable by Windows either directly or through diff --git a/src/System.Management.Automation/engine/ArgumentToVersionTransformationAttribute.cs b/src/System.Management.Automation/engine/ArgumentToVersionTransformationAttribute.cs new file mode 100644 index 00000000000..facaa9e3e1a --- /dev/null +++ b/src/System.Management.Automation/engine/ArgumentToVersionTransformationAttribute.cs @@ -0,0 +1,58 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; + +namespace System.Management.Automation +{ + /// + /// To make it easier to specify a version, we add some conversions that wouldn't happen otherwise: + /// * A simple integer, i.e. 2; + /// * A string without a dot, i.e. "2". + /// + internal class ArgumentToVersionTransformationAttribute : ArgumentTransformationAttribute + { + /// + public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) + { + object version = PSObject.Base(inputData); + + if (version is string versionStr) + { + if (TryConvertFromString(versionStr, out var convertedVersion)) + { + return convertedVersion; + } + + if (versionStr.Contains('.')) + { + // If the string contains a '.', let the Version constructor handle the conversion. + return inputData; + } + } + + if (version is double) + { + // The conversion to int below is wrong, but the usual conversions will turn + // the double into a string, so just return the original object. + return inputData; + } + + if (LanguagePrimitives.TryConvertTo(version, out var majorVersion)) + { + return new Version(majorVersion, 0); + } + + return inputData; + } + + protected virtual bool TryConvertFromString(string versionString, [NotNullWhen(true)] out Version? version) + { + version = null; + return false; + } + } +} diff --git a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs index a2c2cd8321e..596a4142e93 100644 --- a/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs +++ b/src/System.Management.Automation/engine/ArgumentTypeConverterAttribute.cs @@ -65,7 +65,7 @@ internal object Transform(EngineIntrinsics engineIntrinsics, object inputData, b else temp = result; - if (!(temp is PSReference reference)) + if (temp is not PSReference reference) { throw new PSInvalidCastException("InvalidCastExceptionReferenceTypeExpected", null, ExtendedTypeSystem.ReferenceTypeExpected); diff --git a/src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs b/src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs new file mode 100644 index 00000000000..f1391924d6b --- /dev/null +++ b/src/System.Management.Automation/engine/AsyncByteStreamTransfer.cs @@ -0,0 +1,83 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Buffers; +using System.IO; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Management.Automation; + +/// +/// Represents the transfer of bytes from one to another +/// asynchronously. +/// +internal sealed class AsyncByteStreamTransfer : IDisposable +{ + private const int DefaultBufferSize = 1024; + + private readonly BytePipe _bytePipe; + + private readonly BytePipe _destinationPipe; + + private readonly Memory _buffer; + + private readonly CancellationTokenSource _cts = new(); + + private Task? _readToBufferTask; + + public AsyncByteStreamTransfer( + BytePipe bytePipe, + BytePipe destinationPipe) + { + _bytePipe = bytePipe; + _destinationPipe = destinationPipe; + _buffer = new byte[DefaultBufferSize]; + } + + public Task EOF => _readToBufferTask ?? Task.CompletedTask; + + public void BeginReadChunks() + { + _readToBufferTask = Task.Run(ReadBufferAsync); + } + + public void Dispose() => _cts.Cancel(); + + private async Task ReadBufferAsync() + { + Stream stream; + Stream? destinationStream = null; + try + { + stream = await _bytePipe.GetStream(_cts.Token); + destinationStream = await _destinationPipe.GetStream(_cts.Token); + + while (true) + { + int bytesRead; + bytesRead = await stream.ReadAsync(_buffer, _cts.Token); + if (bytesRead is 0) + { + break; + } + + destinationStream.Write(_buffer.Span.Slice(0, bytesRead)); + } + } + catch (IOException) + { + return; + } + catch (OperationCanceledException) + { + return; + } + finally + { + destinationStream?.Close(); + } + } +} diff --git a/src/System.Management.Automation/engine/Attributes.cs b/src/System.Management.Automation/engine/Attributes.cs index 8ab2530b030..dac3a2ac377 100644 --- a/src/System.Management.Automation/engine/Attributes.cs +++ b/src/System.Management.Automation/engine/Attributes.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using System.Management.Automation.Security; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -86,7 +87,7 @@ namespace System.Management.Automation /// validates the argument as a whole. If the argument value may /// be an enumerable, you can derive from /// which will take care of unrolling the enumerable and validate each element individually. - /// It is also recommended to override to return a readable string + /// It is also recommended to override to return a readable string /// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]". /// If this attribute is applied to a string parameter, the string command argument will be validated. /// If this attribute is applied to a string[] parameter, the string[] command argument will be validated. @@ -153,7 +154,7 @@ protected ValidateArgumentsAttribute() /// and override the /// /// abstract method, after which they can apply the attribute to their parameters. - /// It is also recommended to override to return a readable string + /// It is also recommended to override to return a readable string /// similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]". /// If this attribute is applied to a string parameter, the string command argument will be validated. /// If this attribute is applied to a string[] parameter, each string command argument will be validated. @@ -843,7 +844,7 @@ public sealed class ValidateLengthAttribute : ValidateEnumeratedArgumentsAttribu /// For invalid arguments. protected override void ValidateElement(object element) { - if (!(element is string objectString)) + if (element is not string objectString) { throw new ValidationMetadataException( "ValidateLengthNotString", @@ -1088,6 +1089,12 @@ public ValidateRangeAttribute(ValidateRangeKind kind) : base() private static void ValidateRange(object element, ValidateRangeKind rangeKind) { + if (element is TimeSpan ts) + { + ValidateTimeSpanRange(ts, rangeKind); + return; + } + Type commonType = GetCommonType(typeof(int), element.GetType()); if (commonType == null) { @@ -1212,6 +1219,59 @@ private void ValidateRange(object element) } } + private static void ValidateTimeSpanRange(TimeSpan element, ValidateRangeKind rangeKind) + { + TimeSpan zero = TimeSpan.Zero; + + switch (rangeKind) + { + case ValidateRangeKind.Positive: + if (zero.CompareTo(element) >= 0) + { + throw new ValidationMetadataException( + "ValidateRangePositiveFailure", + null, + Metadata.ValidateRangePositiveFailure, + element.ToString()); + } + + break; + case ValidateRangeKind.NonNegative: + if (zero.CompareTo(element) > 0) + { + throw new ValidationMetadataException( + "ValidateRangeNonNegativeFailure", + null, + Metadata.ValidateRangeNonNegativeFailure, + element.ToString()); + } + + break; + case ValidateRangeKind.Negative: + if (zero.CompareTo(element) <= 0) + { + throw new ValidationMetadataException( + "ValidateRangeNegativeFailure", + null, + Metadata.ValidateRangeNegativeFailure, + element.ToString()); + } + + break; + case ValidateRangeKind.NonPositive: + if (zero.CompareTo(element) < 0) + { + throw new ValidationMetadataException( + "ValidateRangeNonPositiveFailure", + null, + Metadata.ValidateRangeNonPositiveFailure, + element.ToString()); + } + + break; + } + } + private static Type GetCommonType(Type minType, Type maxType) { Type resultType = null; @@ -1252,6 +1312,28 @@ private static Type GetCommonType(Type minType, Type maxType) return resultType; } + + /// + /// Returns only the elements that passed the attribute's validation. + /// + /// The objects to validate. + internal IEnumerable GetValidatedElements(IEnumerable elementsToValidate) + { + foreach (var el in elementsToValidate) + { + try + { + ValidateElement(el); + } + catch (ValidationMetadataException) + { + // Element was not in range - drop + continue; + } + + yield return el; + } + } } /// @@ -1274,11 +1356,11 @@ public sealed class ValidatePatternAttribute : ValidateEnumeratedArgumentsAttrib /// Gets or sets the custom error message pattern that is displayed to the user. /// The text representation of the object being validated and the validating regex is passed as /// the first and second formatting parameters to the ErrorMessage formatting pattern. - /// + /// /// /// [ValidatePattern("\s+", ErrorMessage="The text '{0}' did not pass validation of regex '{1}'")] /// - /// + /// /// public string ErrorMessage { get; set; } @@ -1340,11 +1422,11 @@ public sealed class ValidateScriptAttribute : ValidateEnumeratedArgumentsAttribu /// Gets or sets the custom error message that is displayed to the user. /// The item being validated and the validating scriptblock is passed as the first and second /// formatting argument. - /// + /// /// /// [ValidateScript("$_ % 2", ErrorMessage = "The item '{0}' did not pass validation of script '{1}'")] /// - /// + /// /// public string ErrorMessage { get; set; } @@ -1605,11 +1687,11 @@ public sealed class ValidateSetAttribute : ValidateEnumeratedArgumentsAttribute /// Gets or sets the custom error message that is displayed to the user. /// The item being validated and a text representation of the validation set is passed as the /// first and second formatting argument to the formatting pattern. - /// + /// /// /// [ValidateSet("A","B","C", ErrorMessage="The item '{0}' is not part of the set '{1}'.") /// - /// + /// /// public string ErrorMessage { get; set; } @@ -1729,7 +1811,7 @@ public ValidateSetAttribute(Type valuesGeneratorType) // Add a valid values generator to the cache. // We don't cache valid values; we expect that valid values will be cached in the generator. validValuesGenerator = s_ValidValuesGeneratorCache.GetOrAdd( - valuesGeneratorType, (key) => (IValidateSetValuesGenerator)Activator.CreateInstance(key)); + valuesGeneratorType, static (key) => (IValidateSetValuesGenerator)Activator.CreateInstance(key)); } } @@ -1770,11 +1852,21 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { if (ExecutionContext.IsMarkedAsUntrusted(arguments)) { - throw new ValidationMetadataException( - "ValidateTrustedDataFailure", - null, - Metadata.ValidateTrustedDataFailure, - arguments); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + throw new ValidationMetadataException( + "ValidateTrustedDataFailure", + null, + Metadata.ValidateTrustedDataFailure, + arguments); + } + + SystemPolicy.LogWDACAuditMessage( + context: null, + title: Metadata.WDACParameterArgNotTrustedLogTitle, + message: StringUtil.Format(Metadata.WDACParameterArgNotTrustedMessage, arguments), + fqid: "ParameterArgumentNotTrusted", + dropIntoDebugger: true); } } } @@ -1785,7 +1877,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin /// /// Allows a NULL as the argument to a mandatory parameter. /// - [AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AllowNullAttribute : CmdletMetadataAttribute { /// @@ -1797,7 +1889,7 @@ public AllowNullAttribute() { } /// /// Allows an empty string as the argument to a mandatory string parameter. /// - [AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AllowEmptyStringAttribute : CmdletMetadataAttribute { /// @@ -1809,7 +1901,7 @@ public AllowEmptyStringAttribute() { } /// /// Allows an empty collection as the argument to a mandatory collection parameter. /// - [AttributeUsageAttribute(AttributeTargets.Field | AttributeTargets.Property)] + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public sealed class AllowEmptyCollectionAttribute : CmdletMetadataAttribute { /// @@ -1864,7 +1956,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin Metadata.ValidateNotNullFailure); } - if (!(arguments is string path)) + if (arguments is not string path) { throw new ValidationMetadataException( "PathArgumentIsNotValid", @@ -1994,7 +2086,10 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. - if (isElementValueType) { return; } + if (isElementValueType) + { + return; + } IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments); while (enumerator.MoveNext()) @@ -2013,15 +2108,30 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } /// - /// Validates that the parameters's argument is not null, is not an empty string, and is not - /// an empty collection. + /// Validates that the parameters's argument is not null, is not an empty string or a + /// string with white-space characters only, and is not an empty collection. /// - [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] - public sealed class ValidateNotNullOrEmptyAttribute : NullValidationAttributeBase + public abstract class ValidateNotNullOrAttributeBase : NullValidationAttributeBase { + /// + /// Used to check the type of string validation to perform. + /// + protected readonly bool _checkWhiteSpace; + + /// + /// Validates that the parameters's argument is not null, is not an empty string or a + /// string with white-space characters only, and is not an empty collection. + /// + protected ValidateNotNullOrAttributeBase(bool checkWhiteSpace) + { + _checkWhiteSpace = checkWhiteSpace; + } + /// /// Validates that the parameters's argument is not null, is not an empty string, and is /// not an empty collection. If argument is a collection, each argument is verified. + /// It can also validate that the parameters's argument is not a string that consists + /// only of white-space characters. /// /// The arguments to verify. /// @@ -2041,7 +2151,17 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } else if (arguments is string str) { - if (string.IsNullOrEmpty(str)) + if (_checkWhiteSpace) + { + if (string.IsNullOrWhiteSpace(str)) + { + throw new ValidationMetadataException( + "ArgumentIsEmptyOrWhiteSpace", + null, + Metadata.ValidateNotNullOrWhiteSpaceFailure); + } + } + else if (string.IsNullOrEmpty(str)) { throw new ValidationMetadataException( "ArgumentIsEmpty", @@ -2053,7 +2173,10 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin { bool isEmpty = true; IEnumerator enumerator = LanguagePrimitives.GetEnumerator(arguments); - if (enumerator.MoveNext()) { isEmpty = false; } + if (enumerator.MoveNext()) + { + isEmpty = false; + } // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. @@ -2072,7 +2195,17 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin if (element is string elementAsString) { - if (string.IsNullOrEmpty(elementAsString)) + if (_checkWhiteSpace) + { + if (string.IsNullOrWhiteSpace(elementAsString)) + { + throw new ValidationMetadataException( + "ArgumentCollectionContainsEmptyOrWhiteSpace", + null, + Metadata.ValidateNotNullOrWhiteSpaceCollectionFailure); + } + } + else if (string.IsNullOrEmpty(elementAsString)) { throw new ValidationMetadataException( "ArgumentCollectionContainsEmpty", @@ -2104,6 +2237,42 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin } } + /// + /// Validates that the parameters's argument is not null, is not an empty string, and is + /// not an empty collection. If argument is a collection, each argument is verified. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public sealed class ValidateNotNullOrEmptyAttribute : ValidateNotNullOrAttributeBase + { + /// + /// Validates that the parameters's argument is not null, is not an empty string, and is + /// not an empty collection. If argument is a collection, each argument is verified. + /// + public ValidateNotNullOrEmptyAttribute() + : base(checkWhiteSpace: false) + { + } + } + + /// + /// Validates that the parameters's argument is not null, is not an empty string, is not a string that + /// consists only of white-space characters, and is not an empty collection. If argument is a collection, + /// each argument is verified. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public sealed class ValidateNotNullOrWhiteSpaceAttribute : ValidateNotNullOrAttributeBase + { + /// + /// Validates that the parameters's argument is not null, is not an empty string, is not a string that + /// consists only of white-space characters, and is not an empty collection. If argument is a collection, + /// each argument is verified. + /// + public ValidateNotNullOrWhiteSpaceAttribute() + : base(checkWhiteSpace: true) + { + } + } + #endregion NULL validation attributes #endregion Data validate Attributes @@ -2123,7 +2292,7 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin /// and override the /// abstract method, after which they /// can apply the attribute to their parameters. - /// It is also recommended to override to return a readable + /// It is also recommended to override to return a readable /// string similar to the attribute declaration, for example "[ValidateRangeAttribute(5,10)]". /// If multiple transformations are defined on a parameter, they will be invoked in series, /// each getting the output of the previous transformation. diff --git a/src/System.Management.Automation/engine/AutomationEngine.cs b/src/System.Management.Automation/engine/AutomationEngine.cs index 7da8f4200e5..592796d5bb0 100644 --- a/src/System.Management.Automation/engine/AutomationEngine.cs +++ b/src/System.Management.Automation/engine/AutomationEngine.cs @@ -1,10 +1,10 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Linq; using System.Management.Automation.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Text; namespace System.Management.Automation { @@ -14,8 +14,15 @@ namespace System.Management.Automation /// internal class AutomationEngine { + static AutomationEngine() + { + // Register the encoding provider to load encodings that are not supported by default, + // so as to allow them to be used in user's script/code. + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); + } + // Holds the parser to use for this instance of the engine... - internal Language.Parser EngineParser; + internal Parser EngineParser; /// /// Returns the handle to the execution context @@ -79,7 +86,7 @@ internal string Expand(string s) /// Compile a piece of text into a parse tree for later execution. /// /// The text to parse. - /// True iff the scriptblock will be added to history. + /// True if-and-only-if the scriptblock will be added to history. /// The parse text as a parsetree node. internal ScriptBlock ParseScriptBlock(string script, bool addToHistory) { @@ -98,12 +105,22 @@ internal ScriptBlock ParseScriptBlock(string script, string fileName, bool addTo if (errors.Length > 0) { - if (errors[0].IncompleteInput) + ParseException ex = errors[0].IncompleteInput + ? new IncompleteParseException(errors[0].Message, errors[0].ErrorId) + : new ParseException(errors); + + if (addToHistory) { - throw new IncompleteParseException(errors[0].Message, errors[0].ErrorId); + // Try associating the parsing error with the history item if we can. + InvocationInfo invInfo = ex.ErrorRecord.InvocationInfo; + LocalRunspace localRunspace = Context.CurrentRunspace as LocalRunspace; + if (invInfo is not null && localRunspace?.History is not null) + { + invInfo.HistoryId = localRunspace.History.GetNextHistoryId(); + } } - throw new ParseException(errors); + throw ex; } return new ScriptBlock(ast, isFilter: false); diff --git a/src/System.Management.Automation/engine/AutomationNull.cs b/src/System.Management.Automation/engine/AutomationNull.cs index 38016c3c513..7cf4742b7b4 100644 --- a/src/System.Management.Automation/engine/AutomationNull.cs +++ b/src/System.Management.Automation/engine/AutomationNull.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation.Internal /// /// It's a singleton class. Sealed to prevent subclassing. Any operation that /// returns no actual value should return this object AutomationNull.Value. - /// Anything that evaluates an MSH expression should be prepared to deal + /// Anything that evaluates a PowerShell expression should be prepared to deal /// with receiving this result and discarding it. When received in an /// evaluation where a value is required, it should be replaced with null. /// diff --git a/src/System.Management.Automation/engine/BytePipe.cs b/src/System.Management.Automation/engine/BytePipe.cs new file mode 100644 index 00000000000..03eb827df98 --- /dev/null +++ b/src/System.Management.Automation/engine/BytePipe.cs @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Diagnostics; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.PowerShell.Telemetry; + +namespace System.Management.Automation; + +/// +/// Represents a lazily retrieved for transfering bytes +/// to or from. +/// +internal abstract class BytePipe +{ + public abstract Task GetStream(CancellationToken cancellationToken); + + internal AsyncByteStreamTransfer Bind(BytePipe bytePipe) + { + Debug.Assert(bytePipe is not null); + return new AsyncByteStreamTransfer(bytePipe, destinationPipe: this); + } +} + +/// +/// Represents a lazily retrieved from the underlying +/// . +/// +internal sealed class NativeCommandProcessorBytePipe : BytePipe +{ + private readonly NativeCommandProcessor _nativeCommand; + + private readonly bool _stdout; + + internal NativeCommandProcessorBytePipe( + NativeCommandProcessor nativeCommand, + bool stdout) + { + Debug.Assert(nativeCommand is not null); + _nativeCommand = nativeCommand; + _stdout = stdout; + } + + public override async Task GetStream(CancellationToken cancellationToken) + { + // If the native command we're wrapping is the upstream command then + // NativeCommandProcessor.Prepare will have already been called before + // the creation of this BytePipe. + if (_stdout) + { + return _nativeCommand.GetStream(stdout: true); + } + + await _nativeCommand.WaitForProcessInitializationAsync(cancellationToken); + return _nativeCommand.GetStream(stdout: false); + } +} + +/// +/// Provides an byte pipe implementation representing a . +/// +internal sealed class FileBytePipe : BytePipe +{ + private readonly Stream _stream; + + private FileBytePipe(Stream stream) + { + Debug.Assert(stream is not null); + _stream = stream; + } + + internal static FileBytePipe Create(string fileName, bool append) + { + FileStream fileStream; + try + { + PathUtils.MasterStreamOpen( + fileName, + resolvedEncoding: null, + defaultEncoding: false, + append, + Force: true, + NoClobber: false, + out fileStream, + streamWriter: out _, + readOnlyFileInfo: out _, + isLiteralPath: true); + } + catch (Exception e) when (e.Data.Contains(typeof(ErrorRecord))) + { + // The error record is attached to the exception when thrown to preserve + // the call stack. + ErrorRecord? errorRecord = e.Data[typeof(ErrorRecord)] as ErrorRecord; + if (errorRecord is null) + { + throw; + } + + e.Data.Remove(typeof(ErrorRecord)); + throw new RuntimeException(null, e, errorRecord); + } + + ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandPreserveBytePipe", "f"); + + return new FileBytePipe(fileStream); + } + + public override Task GetStream(CancellationToken cancellationToken) => Task.FromResult(_stream); +} diff --git a/src/System.Management.Automation/engine/COM/ComDispatch.cs b/src/System.Management.Automation/engine/COM/ComDispatch.cs index 3f6afa6440e..8e0417e17cc 100644 --- a/src/System.Management.Automation/engine/COM/ComDispatch.cs +++ b/src/System.Management.Automation/engine/COM/ComDispatch.cs @@ -5,6 +5,7 @@ using COM = System.Runtime.InteropServices.ComTypes; +#nullable enable namespace System.Management.Automation { /// @@ -19,7 +20,7 @@ internal interface IDispatch int GetTypeInfoCount(out int info); [PreserveSig] - int GetTypeInfo(int iTInfo, int lcid, out COM.ITypeInfo ppTInfo); + int GetTypeInfo(int iTInfo, int lcid, out COM.ITypeInfo? ppTInfo); void GetIDsOfNames( [MarshalAs(UnmanagedType.LPStruct)] Guid iid, @@ -34,7 +35,7 @@ void Invoke( int lcid, COM.INVOKEKIND wFlags, [In, Out][MarshalAs(UnmanagedType.LPArray)] COM.DISPPARAMS[] paramArray, - out object pVarResult, + out object? pVarResult, out ComInvoker.EXCEPINFO pExcepInfo, out uint puArgErr); } diff --git a/src/System.Management.Automation/engine/COM/ComInvoker.cs b/src/System.Management.Automation/engine/COM/ComInvoker.cs index 3834be3de8e..ea8b8b96d79 100644 --- a/src/System.Management.Automation/engine/COM/ComInvoker.cs +++ b/src/System.Management.Automation/engine/COM/ComInvoker.cs @@ -7,9 +7,6 @@ using COM = System.Runtime.InteropServices.ComTypes; -// Disable obsolete warnings about VarEnum and COM-marshaling APIs in CoreCLR -#pragma warning disable 618 - namespace System.Management.Automation { internal static class ComInvoker @@ -280,7 +277,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ { for (int i = 0; i < argCount; i++) { - VariantClear(variantArgArray + s_variantSize * i); + Interop.Windows.VariantClear(variantArgArray + s_variantSize * i); } Marshal.FreeCoTaskMem(variantArgArray); @@ -297,7 +294,7 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ { for (int i = 0; i < refCount; i++) { - VariantClear(tmpVariants + s_variantSize * i); + Interop.Windows.VariantClear(tmpVariants + s_variantSize * i); } Marshal.FreeCoTaskMem(tmpVariants); @@ -305,13 +302,6 @@ internal static object Invoke(IDispatch target, int dispId, object[] args, bool[ } } - /// - /// Clear variables of type VARIANTARG (or VARIANT) before the memory containing the VARIANTARG is freed. - /// - /// - [DllImport("oleaut32.dll")] - internal static extern void VariantClear(IntPtr pVariant); - /// /// We have to declare 'bstrSource', 'bstrDescription' and 'bstrHelpFile' as pointers because /// CLR marshalling layer would try to free those BSTRs by default and that is not correct. diff --git a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs index 851325e82ec..eab6122a002 100644 --- a/src/System.Management.Automation/engine/COM/ComTypeInfo.cs +++ b/src/System.Management.Automation/engine/COM/ComTypeInfo.cs @@ -105,7 +105,10 @@ private void Initialize() for (int i = 0; i < typeattr.cFuncs; i++) { COM.FUNCDESC funcdesc = GetFuncDesc(_typeinfo, i); - if (funcdesc.memid == DISPID_NEWENUM) { NewEnumInvokeKind = funcdesc.invkind; } + if (funcdesc.memid == DISPID_NEWENUM) + { + NewEnumInvokeKind = funcdesc.invkind; + } if ((funcdesc.wFuncFlags & 0x1) == 0x1) { @@ -183,10 +186,7 @@ private void AddProperty(string strName, COM.FUNCDESC funcdesc, int index) _properties[strName] = prop; } - if (prop != null) - { - prop.UpdateFuncDesc(funcdesc, index); - } + prop?.UpdateFuncDesc(funcdesc, index); } private void AddMethod(string strName, int index) @@ -198,10 +198,7 @@ private void AddMethod(string strName, int index) _methods[strName] = method; } - if (method != null) - { - method.AddFuncDesc(index); - } + method?.AddFuncDesc(index); } /// @@ -209,7 +206,6 @@ private void AddMethod(string strName, int index) /// /// Reference to ITypeInfo from which to get TypeAttr. /// - [ArchitectureSensitive] internal static COM.TYPEATTR GetTypeAttr(COM.ITypeInfo typeinfo) { IntPtr pTypeAttr; @@ -224,7 +220,6 @@ internal static COM.TYPEATTR GetTypeAttr(COM.ITypeInfo typeinfo) /// /// /// - [ArchitectureSensitive] internal static COM.FUNCDESC GetFuncDesc(COM.ITypeInfo typeinfo, int index) { IntPtr pFuncDesc; diff --git a/src/System.Management.Automation/engine/COM/ComUtil.cs b/src/System.Management.Automation/engine/COM/ComUtil.cs index e244e4cdf3f..8cd5e73b835 100644 --- a/src/System.Management.Automation/engine/COM/ComUtil.cs +++ b/src/System.Management.Automation/engine/COM/ComUtil.cs @@ -141,9 +141,6 @@ private static string GetStringFromCustomType(COM.ITypeInfo typeinfo, IntPtr ref return "UnknownCustomtype"; } - // Disable obsolete warning about VarEnum in CoreCLR -#pragma warning disable 618 - /// /// This function gets a string representation of the Type Descriptor /// This is used in generating signature for Properties and Methods. @@ -259,8 +256,6 @@ internal static Type GetTypeFromTypeDesc(COM.TYPEDESC typedesc) return VarEnumSelector.GetTypeForVarEnum(vt); } -#pragma warning restore 618 - /// /// Converts a FuncDesc out of GetFuncDesc into a MethodInformation. /// diff --git a/src/System.Management.Automation/engine/CmdletInfo.cs b/src/System.Management.Automation/engine/CmdletInfo.cs index 05b7548f9fc..cf3ba1cab13 100644 --- a/src/System.Management.Automation/engine/CmdletInfo.cs +++ b/src/System.Management.Automation/engine/CmdletInfo.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation { /// - /// The command information for MSH cmdlets that are directly executable by MSH. + /// The command information for cmdlets that are directly executable by PowerShell. /// public class CmdletInfo : CommandInfo { @@ -380,11 +380,8 @@ public override ReadOnlyCollection OutputType } } - if (provider == null) - { - // No path argument, so just use the current path to choose the provider. - provider = Context.SessionState.Path.CurrentLocation.Provider; - } + // If no path argument, just use the current path to choose the provider. + provider ??= Context.SessionState.Path.CurrentLocation.Provider; provider.GetOutputTypes(Name, providerTypes); if (providerTypes.Count > 0) diff --git a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs index 440b9ead537..b9cf67b29e6 100644 --- a/src/System.Management.Automation/engine/CmdletParameterBinderController.cs +++ b/src/System.Management.Automation/engine/CmdletParameterBinderController.cs @@ -202,10 +202,7 @@ internal void BindCommandLineParameters(Collection arg internal void BindCommandLineParametersNoValidation(Collection arguments) { var psCompiledScriptCmdlet = this.Command as PSScriptCmdlet; - if (psCompiledScriptCmdlet != null) - { - psCompiledScriptCmdlet.PrepareForBinding(this.CommandLineParameters); - } + psCompiledScriptCmdlet?.PrepareForBinding(this.CommandLineParameters); InitUnboundArguments(arguments); CommandMetadata cmdletMetadata = _commandMetadata; @@ -270,8 +267,7 @@ internal void BindCommandLineParametersNoValidation(Collection GetDefaultParameterVa foreach (DictionaryEntry entry in DefaultParameterValues) { - if (!(entry.Key is string key)) + if (entry.Key is not string key) { continue; } @@ -1045,10 +1041,7 @@ private bool RestoreParameter(CommandParameterInternal argumentToBind, MergedCom _commandMetadata.ImplementsDynamicParameters, "The metadata for the dynamic parameters should only be available if the command supports IDynamicParameters"); - if (_dynamicParameterBinder != null) - { - _dynamicParameterBinder.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); - } + _dynamicParameterBinder?.BindParameter(argumentToBind.ParameterName, argumentToBind.ArgumentValue, parameter.Parameter); break; } @@ -1452,8 +1445,7 @@ private bool BindParameter( BoundObsoleteParameterNames.Add(parameter.Parameter.Name); - if (ObsoleteParameterWarningList == null) - ObsoleteParameterWarningList = new List(); + ObsoleteParameterWarningList ??= new List(); ObsoleteParameterWarningList.Add(warningRecord); } @@ -1628,7 +1620,10 @@ private void HandleCommandLineDynamicParameters(out ParameterBindingException ou } catch (Exception e) // Catch-all OK, this is a third-party callout { - if (e is ProviderInvocationException) { throw; } + if (e is ProviderInvocationException) + { + throw; + } ParameterBindingException bindingException = new ParameterBindingException( @@ -2661,7 +2656,7 @@ Cmdlet command IEnumerable allParameterSetMetadatas = boundParameters.Values .Concat(unboundParameters) - .SelectMany(p => p.Parameter.ParameterSetData.Values); + .SelectMany(static p => p.Parameter.ParameterSetData.Values); uint allParameterSetFlags = 0; foreach (ParameterSetSpecificMetadata parameterSetMetadata in allParameterSetMetadatas) { @@ -2675,8 +2670,8 @@ Cmdlet command "This method should only be called when there is an ambiguity wrt parameter sets"); IEnumerable parameterSetMetadatasForUnboundMandatoryParameters = unboundParameters - .SelectMany(p => p.Parameter.ParameterSetData.Values) - .Where(p => p.IsMandatory); + .SelectMany(static p => p.Parameter.ParameterSetData.Values) + .Where(static p => p.IsMandatory); foreach (ParameterSetSpecificMetadata parameterSetMetadata in parameterSetMetadatasForUnboundMandatoryParameters) { remainingParameterSetsWithNoMandatoryUnboundParameters &= (~parameterSetMetadata.ParameterSetFlag); @@ -2991,7 +2986,7 @@ internal static string BuildMissingParamsString(CollectionThe original event with handler added. private object InPlaceAdd(object handler) { - Requires.NotNull(handler, nameof(handler)); + Requires.NotNull(handler); VerifyHandler(handler); ComEventsSink comEventSink = ComEventsSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, true); @@ -88,7 +88,7 @@ private object InPlaceAdd(object handler) /// The original event with handler removed. private object InPlaceSubtract(object handler) { - Requires.NotNull(handler, nameof(handler)); + Requires.NotNull(handler); VerifyHandler(handler); ComEventsSink comEventSink = ComEventsSink.FromRuntimeCallableWrapper(_rcw, _sourceIid, false); diff --git a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs index 726f336ec71..a88abc09f1e 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComBinder.cs @@ -35,8 +35,8 @@ public static bool IsComObject(object value) /// True if operation was bound successfully; otherwise, false. public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject instance, out DynamicMetaObject result, bool delayInvocation) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); + Requires.NotNull(binder); + Requires.NotNull(instance); if (TryGetMetaObject(ref instance)) { @@ -66,9 +66,9 @@ public static bool TryBindGetMember(GetMemberBinder binder, DynamicMetaObject in /// True if operation was bound successfully; otherwise, false. public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject instance, DynamicMetaObject value, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(value); if (TryGetMetaObject(ref instance)) { @@ -91,9 +91,9 @@ public static bool TryBindSetMember(SetMemberBinder binder, DynamicMetaObject in /// True if operation was bound successfully; otherwise, false. public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObjectInvoke(ref instance)) { @@ -116,9 +116,9 @@ public static bool TryBindInvoke(InvokeBinder binder, DynamicMetaObject instance /// True if operation was bound successfully; otherwise, false. public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProperty, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObject(ref instance)) { @@ -158,9 +158,9 @@ public static bool TryBindInvokeMember(InvokeMemberBinder binder, bool isSetProp /// True if operation was bound successfully; otherwise, false. public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); if (TryGetMetaObjectInvoke(ref instance)) { @@ -183,10 +183,10 @@ public static bool TryBindGetIndex(GetIndexBinder binder, DynamicMetaObject inst /// True if operation was bound successfully; otherwise, false. public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject instance, DynamicMetaObject[] args, DynamicMetaObject value, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); - Requires.NotNull(args, nameof(args)); - Requires.NotNull(value, nameof(value)); + Requires.NotNull(binder); + Requires.NotNull(instance); + Requires.NotNull(args); + Requires.NotNull(value); if (TryGetMetaObjectInvoke(ref instance)) { @@ -208,8 +208,8 @@ public static bool TryBindSetIndex(SetIndexBinder binder, DynamicMetaObject inst /// True if operation was bound successfully; otherwise, false. public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, out DynamicMetaObject result) { - Requires.NotNull(binder, nameof(binder)); - Requires.NotNull(instance, nameof(instance)); + Requires.NotNull(binder); + Requires.NotNull(instance); if (IsComObject(instance.Value)) { @@ -245,7 +245,7 @@ public static bool TryConvert(ConvertBinder binder, DynamicMetaObject instance, /// The collection of member names. internal static IList GetDynamicDataMemberNames(object value) { - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value); Requires.Condition(IsComObject(value), nameof(value)); return ComObject.ObjectToComObject(value).GetMemberNames(true); @@ -260,7 +260,7 @@ internal static IList GetDynamicDataMemberNames(object value) /// The collection of pairs that represent data member's names and their data. internal static IList> GetDynamicDataMembers(object value, IEnumerable names) { - Requires.NotNull(value, nameof(value)); + Requires.NotNull(value); Requires.Condition(IsComObject(value), nameof(value)); return ComObject.ObjectToComObject(value).GetMembers(names); @@ -310,8 +310,8 @@ internal class ComGetMemberBinder : GetMemberBinder private readonly GetMemberBinder _originalBinder; internal bool _canReturnCallables; - internal ComGetMemberBinder(GetMemberBinder originalBinder, bool canReturnCallables) : - base(originalBinder.Name, originalBinder.IgnoreCase) + internal ComGetMemberBinder(GetMemberBinder originalBinder, bool canReturnCallables) + : base(originalBinder.Name, originalBinder.IgnoreCase) { _originalBinder = originalBinder; _canReturnCallables = canReturnCallables; @@ -343,8 +343,8 @@ internal class ComInvokeMemberBinder : InvokeMemberBinder private readonly InvokeMemberBinder _originalBinder; internal bool IsPropertySet; - internal ComInvokeMemberBinder(InvokeMemberBinder originalBinder, bool isPropertySet) : - base(originalBinder.Name, originalBinder.IgnoreCase, originalBinder.CallInfo) + internal ComInvokeMemberBinder(InvokeMemberBinder originalBinder, bool isPropertySet) + : base(originalBinder.Name, originalBinder.IgnoreCase, originalBinder.CallInfo) { _originalBinder = originalBinder; this.IsPropertySet = isPropertySet; diff --git a/src/System.Management.Automation/engine/ComInterop/ComEventsSink.Extended.cs b/src/System.Management.Automation/engine/ComInterop/ComEventsSink.Extended.cs index f52ded959c2..0d63276a3ea 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComEventsSink.Extended.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComEventsSink.Extended.cs @@ -18,10 +18,7 @@ private void Initialize(object rcw, Guid iid) public void AddHandler(int dispid, object func) { ComEventsMethod method = FindMethod(dispid); - if (method == null) - { - method = AddMethod(dispid); - } + method ??= AddMethod(dispid); if (func is Delegate d) { diff --git a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs index 758281c7ac4..8a6e81f0800 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComFallbackMetaObject.cs @@ -23,31 +23,31 @@ internal ComFallbackMetaObject(Expression expression, BindingRestrictions restri public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackGetIndex(UnwrapSelf(), indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackSetIndex(UnwrapSelf(), indexes, value); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackGetMember(UnwrapSelf()); } public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackInvokeMember(UnwrapSelf(), args); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.FallbackSetMember(UnwrapSelf(), value); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs index 6876425acf7..3765f5ba68b 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComInvokeBinder.cs @@ -114,10 +114,7 @@ private ParameterExpression ParamVariantsVariable { get { - if (_paramVariants == null) - { - _paramVariants = Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"); - } + _paramVariants ??= Expression.Variable(VariantArray.GetStructType(_args.Length), "paramVariants"); return _paramVariants; } } @@ -140,10 +137,7 @@ private static Type MarshalType(DynamicMetaObject mo, bool isByRef) if (isByRef) { // Null just means that null was supplied. - if (marshalType == null) - { - marshalType = mo.Expression.Type; - } + marshalType ??= mo.Expression.Type; marshalType = marshalType.MakeByRefType(); } return marshalType; @@ -173,7 +167,10 @@ internal DynamicMetaObject Invoke() private static void AddNotNull(List list, ParameterExpression var) { - if (var != null) list.Add(var); + if (var != null) + { + list.Add(var); + } } private Expression CreateScope(Expression expression) @@ -398,7 +395,7 @@ private Expression GenerateFinallyBlock() } /// - /// Create a stub for the target of the optimized lopop. + /// Create a stub for the target of the optimized loop. /// /// private Expression MakeIDispatchInvokeTarget() diff --git a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs index bc75f83ba0a..39c9d1dbe05 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMetaObject.cs @@ -16,37 +16,37 @@ internal ComMetaObject(Expression expression, BindingRestrictions restrictions, public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(args.AddFirst(WrapSelf())); } public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(args.AddFirst(WrapSelf())); } public override DynamicMetaObject BindGetMember(GetMemberBinder binder) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf()); } public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), value); } public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), indexes); } public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return binder.Defer(WrapSelf(), indexes.AddLast(value)); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs index 35b4c9fa25d..45932e1598a 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComMethodDesc.cs @@ -95,7 +95,9 @@ public bool IsPropertyPutRef } internal int ParamCount { get; } + public Type ReturnType { get; set; } + public Type InputType { get; set; } public ParameterInformation[] ParameterInformation diff --git a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs index c10f1424cf5..5bd086874a6 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComRuntimeHelpers.cs @@ -296,8 +296,15 @@ internal static class UnsafeMethods { #region public members - public static unsafe IntPtr ConvertInt32ByrefToPtr(ref int value) { return (IntPtr)System.Runtime.CompilerServices.Unsafe.AsPointer(ref value); } - public static unsafe IntPtr ConvertVariantByrefToPtr(ref Variant value) { return (IntPtr)System.Runtime.CompilerServices.Unsafe.AsPointer(ref value); } + public static unsafe IntPtr ConvertInt32ByrefToPtr(ref int value) + { + return (IntPtr)System.Runtime.CompilerServices.Unsafe.AsPointer(ref value); + } + + public static unsafe IntPtr ConvertVariantByrefToPtr(ref Variant value) + { + return (IntPtr)System.Runtime.CompilerServices.Unsafe.AsPointer(ref value); + } internal static Variant GetVariantForObject(object obj) { @@ -315,7 +322,7 @@ internal static void InitVariantForObject(object obj, ref Variant variant) Debug.Assert(obj != null); // GetNativeVariantForObject is very expensive for values that marshal as VT_DISPATCH - // also is is extremely common scenario when object at hand is an RCW. + // also is extremely common scenario when object at hand is an RCW. // Therefore we are going to test for IDispatch before defaulting to GetNativeVariantForObject. if (obj is IDispatch) { @@ -365,8 +372,7 @@ public static unsafe int IDispatchInvoke( fixed (ExcepInfo* pExcepInfo = &excepInfo) fixed (uint* pArgErr = &argErr) { - var pfnIDispatchInvoke = (delegate* unmanaged) - (*(*(void***)dispatchPointer + 6 /* IDispatch.Invoke slot */)); + var pfnIDispatchInvoke = (delegate* unmanaged)(*(*(void***)dispatchPointer + 6 /* IDispatch.Invoke slot */)); int hresult = pfnIDispatchInvoke(dispatchPointer, memberDispId, &IID_NULL, 0, (ushort)flags, pDispParams, pResult, pExcepInfo, pArgErr); @@ -375,7 +381,7 @@ public static unsafe int IDispatchInvoke( && (flags & ComTypes.INVOKEKIND.INVOKE_FUNC) != 0 && (flags & (ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT | ComTypes.INVOKEKIND.INVOKE_PROPERTYPUTREF)) == 0) { - // Re-invoke with no result argument to accomodate Word + // Re-invoke with no result argument to accommodate Word hresult = pfnIDispatchInvoke(dispatchPointer, memberDispId, &IID_NULL, 0, (ushort)ComTypes.INVOKEKIND.INVOKE_FUNC, pDispParams, null, pExcepInfo, pArgErr); } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs index 1ff4fac18cf..2f2886d6555 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeClassDesc.cs @@ -17,15 +17,11 @@ internal class ComTypeClassDesc : ComTypeDesc, IDynamicMetaObjectProvider public object CreateInstance() { - if (_typeObj == null) - { - _typeObj = Type.GetTypeFromCLSID(Guid); - } + _typeObj ??= Type.GetTypeFromCLSID(Guid); return Activator.CreateInstance(Type.GetTypeFromCLSID(Guid)); } - internal ComTypeClassDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : - base(typeInfo, typeLibDesc) + internal ComTypeClassDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : base(typeInfo, typeLibDesc) { ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); Guid = typeAttr.guid; @@ -47,19 +43,12 @@ private void AddInterface(ComTypes.ITypeInfo itfTypeInfo, bool isSourceItf) if (isSourceItf) { - if (_sourceItfs == null) - { - _sourceItfs = new LinkedList(); - } + _sourceItfs ??= new LinkedList(); _sourceItfs.AddLast(itfName); } else { - if (_itfs == null) - { - _itfs = new LinkedList(); - } - + _itfs ??= new LinkedList(); _itfs.AddLast(itfName); } } diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs index 92e9ea8ed6f..a4b90913e9b 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeDesc.cs @@ -118,6 +118,7 @@ internal bool TryGetPutRef(string name, out ComMethodDesc method) method = null; return false; } + internal void AddPutRef(string name, ComMethodDesc method) { name = name.ToUpper(System.Globalization.CultureInfo.InvariantCulture); diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs index 5752fac1e5f..00fe57c2b44 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeEnumDesc.cs @@ -15,13 +15,9 @@ internal sealed class ComTypeEnumDesc : ComTypeDesc, IDynamicMetaObjectProvider private readonly string[] _memberNames; private readonly object[] _memberValues; - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "", TypeName); - } + public override string ToString() => $""; - internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : - base(typeInfo, typeLibDesc) + internal ComTypeEnumDesc(ComTypes.ITypeInfo typeInfo, ComTypeLibDesc typeLibDesc) : base(typeInfo, typeLibDesc) { ComTypes.TYPEATTR typeAttr = ComRuntimeHelpers.GetTypeAttrForTypeInfo(typeInfo); string[] memberNames = new string[typeAttr.cVars]; diff --git a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs index 2b81c76b6eb..8f373e52a72 100644 --- a/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs +++ b/src/System.Management.Automation/engine/ComInterop/ComTypeLibDesc.cs @@ -32,10 +32,7 @@ private ComTypeLibDesc() _classes = new LinkedList(); } - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "", Name); - } + public override string ToString() => $""; public string Documentation { diff --git a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs index df0f54009ac..e99bdd3741f 100644 --- a/src/System.Management.Automation/engine/ComInterop/DispCallable.cs +++ b/src/System.Management.Automation/engine/ComInterop/DispCallable.cs @@ -19,10 +19,7 @@ internal DispCallable(IDispatchComObject dispatch, string memberName, int dispId DispId = dispId; } - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "", MemberName); - } + public override string ToString() => $""; public IDispatchComObject DispatchComObject { get; } diff --git a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs index 4f829b6241d..74314850a59 100644 --- a/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs +++ b/src/System.Management.Automation/engine/ComInterop/ExcepInfo.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation.ComInterop { /// - /// This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshaling. + /// This is similar to ComTypes.EXCEPINFO, but lets us do our own custom marshalling. /// [StructLayout(LayoutKind.Sequential)] internal struct ExcepInfo diff --git a/src/System.Management.Automation/engine/ComInterop/Helpers.cs b/src/System.Management.Automation/engine/ComInterop/Helpers.cs index 513c3126476..a780e095e20 100644 --- a/src/System.Management.Automation/engine/ComInterop/Helpers.cs +++ b/src/System.Management.Automation/engine/ComInterop/Helpers.cs @@ -1,8 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable + using System; using System.Linq.Expressions; +using System.Runtime.CompilerServices; namespace System.Management.Automation.ComInterop { @@ -33,12 +36,9 @@ internal static Expression Convert(Expression expression, Type type) internal static class Requires { [System.Diagnostics.Conditional("DEBUG")] - internal static void NotNull(object value, string paramName) + internal static void NotNull(object value, [CallerArgumentExpression("value")] string? paramName = null) { - if (value == null) - { - throw new ArgumentNullException(paramName); - } + ArgumentNullException.ThrowIfNull(value, paramName); } [System.Diagnostics.Conditional("DEBUG")] diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs index c3a16639b62..7c2a3c106a7 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchComObject.cs @@ -22,7 +22,7 @@ namespace System.Management.Automation.ComInterop /// default arguments?). So obj.foo() is ambiguous as it could mean invoking method foo, /// or it could mean invoking the function pointer returned by property foo. /// We are attempting to find whether we need to call a method or a property by examining - /// the ITypeInfo associated with the IDispatch. ITypeInfo tell's use what parameters the method + /// the ITypeInfo associated with the IDispatch. ITypeInfo tells us what parameters the method /// expects, is it a method or a property, what is the default property of the object, how to /// create an enumerator for collections etc. /// @@ -99,7 +99,7 @@ public override string ToString() typeName = "IDispatch"; } - return string.Format(CultureInfo.CurrentCulture, "{0} ({1})", RuntimeCallableWrapper.ToString(), typeName); + return $"{RuntimeCallableWrapper} ({typeName})"; } public ComTypeDesc ComTypeDesc @@ -222,7 +222,7 @@ internal bool TryGetMemberMethodExplicit(string name, out ComMethodDesc method) return false; } - throw Error.CouldNotGetDispId(name, string.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); + throw Error.CouldNotGetDispId(name, string.Create(CultureInfo.InvariantCulture, $"0x{hresult:X})")); } internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method, Type limitType, bool holdsNull) @@ -258,7 +258,7 @@ internal bool TryGetPropertySetterExplicit(string name, out ComMethodDesc method return false; } - throw Error.CouldNotGetDispId(name, string.Format(CultureInfo.InvariantCulture, "0x{0:X})", hresult)); + throw Error.CouldNotGetDispId(name, string.Create(CultureInfo.InvariantCulture, $"0x{hresult:X})")); } internal override IList GetMemberNames(bool dataOnly) @@ -271,10 +271,7 @@ internal override IList GetMemberNames(bool dataOnly) internal override IList> GetMembers(IEnumerable names) { - if (names == null) - { - names = GetMemberNames(true); - } + names ??= GetMemberNames(true); Type comType = RuntimeCallableWrapper.GetType(); diff --git a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs index b340cf54967..9826ac9d467 100644 --- a/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs +++ b/src/System.Management.Automation/engine/ComInterop/IDispatchMetaObject.cs @@ -23,7 +23,7 @@ internal IDispatchMetaObject(Expression expression, IDispatchComObject self) public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); ComMethodDesc method = null; @@ -63,7 +63,7 @@ public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, Dy public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetGetItem(out ComMethodDesc method)) { @@ -108,7 +108,7 @@ public override DynamicMetaObject BindGetMember(GetMemberBinder binder) ComBinder.ComGetMemberBinder comBinder = binder as ComBinder.ComGetMemberBinder; bool canReturnCallables = comBinder?._canReturnCallables ?? false; - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); // 1. Try methods if (_self.TryGetMemberMethod(binder.Name, out ComMethodDesc method)) @@ -187,7 +187,7 @@ private DynamicMetaObject BindEvent(ComEventDesc eventDesc) public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetGetItem(out ComMethodDesc getItem)) { @@ -203,7 +203,7 @@ public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMet public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); if (_self.TryGetSetItem(out ComMethodDesc setItem)) { @@ -238,7 +238,7 @@ public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMet public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value) { - Requires.NotNull(binder, nameof(binder)); + Requires.NotNull(binder); return // 1. Check for simple property put diff --git a/src/System.Management.Automation/engine/ComInterop/InteropServices/ComEventsMethod.cs b/src/System.Management.Automation/engine/ComInterop/InteropServices/ComEventsMethod.cs index d31ca0299c9..f8ff1e09855 100644 --- a/src/System.Management.Automation/engine/ComInterop/InteropServices/ComEventsMethod.cs +++ b/src/System.Management.Automation/engine/ComInterop/InteropServices/ComEventsMethod.cs @@ -83,10 +83,7 @@ private void PreProcessSignature() && pi.ParameterType.HasElementType && pi.ParameterType.GetElementType()!.IsEnum) { - if (targetTypes == null) - { - targetTypes = new Type?[_expectedParamsCount]; - } + targetTypes ??= new Type?[_expectedParamsCount]; targetTypes[i] = pi.ParameterType.GetElementType(); } diff --git a/src/System.Management.Automation/engine/ComInterop/InteropServices/Variant.cs b/src/System.Management.Automation/engine/ComInterop/InteropServices/Variant.cs index 24405957f72..941f471b666 100644 --- a/src/System.Management.Automation/engine/ComInterop/InteropServices/Variant.cs +++ b/src/System.Management.Automation/engine/ComInterop/InteropServices/Variant.cs @@ -276,9 +276,6 @@ public unsafe void CopyFromIndirect(object value) } } - [DllImport("oleaut32.dll")] - internal static extern void VariantClear(IntPtr variant); - /// /// Release any unmanaged memory associated with the Variant /// @@ -306,7 +303,7 @@ public void Clear() { fixed (void* pThis = &this) { - VariantClear((IntPtr)pThis); + Interop.Windows.VariantClear((nint)pThis); } } @@ -343,6 +340,7 @@ public sbyte AsI1 Debug.Assert(VariantType == VarEnum.VT_I1); return _typeUnion._unionTypes._i1; } + set { Debug.Assert(IsEmpty); @@ -360,6 +358,7 @@ public short AsI2 Debug.Assert(VariantType == VarEnum.VT_I2); return _typeUnion._unionTypes._i2; } + set { Debug.Assert(IsEmpty); @@ -377,6 +376,7 @@ public int AsI4 Debug.Assert(VariantType == VarEnum.VT_I4); return _typeUnion._unionTypes._i4; } + set { Debug.Assert(IsEmpty); @@ -394,6 +394,7 @@ public long AsI8 Debug.Assert(VariantType == VarEnum.VT_I8); return _typeUnion._unionTypes._i8; } + set { Debug.Assert(IsEmpty); @@ -411,6 +412,7 @@ public byte AsUi1 Debug.Assert(VariantType == VarEnum.VT_UI1); return _typeUnion._unionTypes._ui1; } + set { Debug.Assert(IsEmpty); @@ -428,6 +430,7 @@ public ushort AsUi2 Debug.Assert(VariantType == VarEnum.VT_UI2); return _typeUnion._unionTypes._ui2; } + set { Debug.Assert(IsEmpty); @@ -445,6 +448,7 @@ public uint AsUi4 Debug.Assert(VariantType == VarEnum.VT_UI4); return _typeUnion._unionTypes._ui4; } + set { Debug.Assert(IsEmpty); @@ -462,6 +466,7 @@ public ulong AsUi8 Debug.Assert(VariantType == VarEnum.VT_UI8); return _typeUnion._unionTypes._ui8; } + set { Debug.Assert(IsEmpty); @@ -479,6 +484,7 @@ public int AsInt Debug.Assert(VariantType == VarEnum.VT_INT); return _typeUnion._unionTypes._int; } + set { Debug.Assert(IsEmpty); @@ -496,6 +502,7 @@ public uint AsUint Debug.Assert(VariantType == VarEnum.VT_UINT); return _typeUnion._unionTypes._uint; } + set { Debug.Assert(IsEmpty); @@ -513,6 +520,7 @@ public bool AsBool Debug.Assert(VariantType == VarEnum.VT_BOOL); return _typeUnion._unionTypes._bool != 0; } + set { Debug.Assert(IsEmpty); @@ -532,6 +540,7 @@ public int AsError Debug.Assert(VariantType == VarEnum.VT_ERROR); return _typeUnion._unionTypes._error; } + set { Debug.Assert(IsEmpty); @@ -549,6 +558,7 @@ public float AsR4 Debug.Assert(VariantType == VarEnum.VT_R4); return _typeUnion._unionTypes._r4; } + set { Debug.Assert(IsEmpty); @@ -566,6 +576,7 @@ public double AsR8 Debug.Assert(VariantType == VarEnum.VT_R8); return _typeUnion._unionTypes._r8; } + set { Debug.Assert(IsEmpty); @@ -586,6 +597,7 @@ public decimal AsDecimal v._typeUnion._vt = 0; return v._decimal; } + set { Debug.Assert(IsEmpty); @@ -605,6 +617,7 @@ public decimal AsCy Debug.Assert(VariantType == VarEnum.VT_CY); return decimal.FromOACurrency(_typeUnion._unionTypes._cy); } + set { Debug.Assert(IsEmpty); @@ -622,6 +635,7 @@ public DateTime AsDate Debug.Assert(VariantType == VarEnum.VT_DATE); return DateTime.FromOADate(_typeUnion._unionTypes._date); } + set { Debug.Assert(IsEmpty); @@ -639,6 +653,7 @@ public string AsBstr Debug.Assert(VariantType == VarEnum.VT_BSTR); return (string)Marshal.PtrToStringBSTR(this._typeUnion._unionTypes._bstr); } + set { Debug.Assert(IsEmpty); @@ -660,6 +675,7 @@ public object? AsUnknown } return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._unknown); } + set { Debug.Assert(IsEmpty); @@ -688,6 +704,7 @@ public object? AsDispatch } return Marshal.GetObjectForIUnknown(_typeUnion._unionTypes._dispatch); } + set { Debug.Assert(IsEmpty); diff --git a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs index 68c394033fc..926bb460a09 100644 --- a/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs +++ b/src/System.Management.Automation/engine/ComInterop/SplatCallSite.cs @@ -24,15 +24,13 @@ internal SplatCallSite(object callable) } public delegate object InvokeDelegate(object[] args); + internal object Invoke(object[] args) { Debug.Assert(args != null); // Create a CallSite and invoke it. - if (_site == null) - { - _site = CallSite>.Create(SplatInvokeBinder.Instance); - } + _site ??= CallSite>.Create(SplatInvokeBinder.Instance); return _site.Target(_site, _callable, args); } diff --git a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs index 0d4ee61dcf7..04217bd0bb6 100644 --- a/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs +++ b/src/System.Management.Automation/engine/ComInterop/TypeUtils.cs @@ -38,6 +38,7 @@ internal static bool AreReferenceAssignable(Type dest, Type src) } return false; } + //CONFORMING internal static bool AreAssignable(Type dest, Type src) { @@ -101,11 +102,9 @@ internal static MethodInfo GetUserDefinedCoercionMethod(Type convertFrom, Type c // try lifted conversion if (nnExprType != convertFrom || nnConvType != convertToType) { - method = FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly); - if (method == null) - { - method = FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); - } + method = + FindConversionOperator(eMethods, nnExprType, nnConvType, implicitOnly) ?? + FindConversionOperator(cMethods, nnExprType, nnConvType, implicitOnly); if (method != null) { return method; diff --git a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs index c7f6b120919..a9e1594ae1c 100644 --- a/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs +++ b/src/System.Management.Automation/engine/ComInterop/VarEnumSelector.cs @@ -98,7 +98,7 @@ internal static Type GetTypeForVarEnum(VarEnum vt) } /// - /// Gets the managed type that an object needs to be coverted to in order for it to be able + /// Gets the managed type that an object needs to be converted to in order for it to be able /// to be represented as a Variant. /// /// In general, there is a many-to-many mapping between Type and VarEnum. However, this method @@ -211,7 +211,7 @@ private static List GetConversionsToComPrimitiveTypeFamilies(Type argum if (TypeUtils.IsImplicitlyConvertible(argumentType, candidateManagedType, true)) { compatibleComTypes.Add(candidateType); - // Move on to the next type family. We need atmost one type from each family + // Move on to the next type family. We need at most one type from each family break; } } @@ -352,7 +352,7 @@ private static bool TryGetPrimitiveComTypeViaConversion(Type argumentType, out V // We will try VT_DISPATCH and then call GetNativeVariantForObject. private const VarEnum VT_DEFAULT = VarEnum.VT_RECORD; - private VarEnum GetComType(ref Type argumentType) + private static VarEnum GetComType(ref Type argumentType) { if (argumentType == typeof(Missing)) { @@ -429,9 +429,9 @@ private VarEnum GetComType(ref Type argumentType) } /// - /// Get the COM Variant type that argument should be marshaled as for a call to COM. + /// Get the COM Variant type that argument should be marshalled as for a call to COM. /// - private VariantBuilder GetVariantBuilder(Type argumentType) + private static VariantBuilder GetVariantBuilder(Type argumentType) { //argumentType is coming from MarshalType, null means the dynamic object holds //a null value and not byref @@ -455,7 +455,7 @@ private VariantBuilder GetVariantBuilder(Type argumentType) if (elementType == typeof(object) || elementType == typeof(DBNull)) { //no meaningful value to pass ByRef. - //perhaps the calee will replace it with something. + //perhaps the callee will replace it with something. //need to pass as a variant reference elementVarEnum = VarEnum.VT_VARIANT; } diff --git a/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs b/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs index 3a47dbd2ba4..9cab38d0773 100644 --- a/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs +++ b/src/System.Management.Automation/engine/ComInterop/Variant.Extended.cs @@ -282,10 +282,7 @@ internal static System.Reflection.MethodInfo GetByrefSetter(VarEnum varType) } } - public override string ToString() - { - return string.Format(CultureInfo.CurrentCulture, "Variant ({0})", VariantType); - } + public override string ToString() => $"Variant ({VariantType})"; public void SetAsIConvertible(IConvertible value) { diff --git a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs index a196eb96079..d4f8af57b74 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantArray.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantArray.cs @@ -58,10 +58,25 @@ internal static MemberExpression GetStructField(ParameterExpression variantArray internal static Type GetStructType(int args) { Debug.Assert(args >= 0); - if (args <= 1) return typeof(VariantArray1); - if (args <= 2) return typeof(VariantArray2); - if (args <= 4) return typeof(VariantArray4); - if (args <= 8) return typeof(VariantArray8); + if (args <= 1) + { + return typeof(VariantArray1); + } + + if (args <= 2) + { + return typeof(VariantArray2); + } + + if (args <= 4) + { + return typeof(VariantArray4); + } + + if (args <= 8) + { + return typeof(VariantArray8); + } int size = 1; while (args > size) diff --git a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs index edcb0eb0f10..baabb25cd75 100644 --- a/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs +++ b/src/System.Management.Automation/engine/ComInterop/VariantBuilder.cs @@ -16,6 +16,7 @@ internal class VariantBuilder private MemberExpression _variant; private readonly ArgBuilder _argBuilder; private readonly VarEnum _targetComType; + internal ParameterExpression TempVariable { get; private set; } internal VariantBuilder(VarEnum targetComType, ArgBuilder builder) diff --git a/src/System.Management.Automation/engine/CommandBase.cs b/src/System.Management.Automation/engine/CommandBase.cs index da2e97e516b..3708611df07 100644 --- a/src/System.Management.Automation/engine/CommandBase.cs +++ b/src/System.Management.Automation/engine/CommandBase.cs @@ -8,8 +8,7 @@ using System.Management.Automation.Internal.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; - -using Dbg = System.Management.Automation.Diagnostics; +using System.Threading; namespace System.Management.Automation.Internal { @@ -132,6 +131,13 @@ internal bool IsStopping } } + /// + /// Gets the CancellationToken that is signaled when the pipeline is stopping. + /// + internal CancellationToken StopToken => commandRuntime is MshCommandRuntime mcr + ? mcr.PipelineProcessor.PipelineStopToken + : default; + /// /// The information about the command. /// @@ -233,6 +239,13 @@ internal virtual void DoStopProcessing() { } + /// + /// When overridden in the derived class, performs clean-up after the command execution. + /// + internal virtual void DoCleanResource() + { + } + #endregion Override /// @@ -272,6 +285,26 @@ internal void InternalDispose(bool isDisposing) namespace System.Management.Automation { + #region NativeArgumentPassingStyle + /// + /// Defines the different native command argument parsing options. + /// + public enum NativeArgumentPassingStyle + { + /// Use legacy argument parsing via ProcessStartInfo.Arguments. + Legacy = 0, + + /// Use new style argument passing via ProcessStartInfo.ArgumentList. + Standard = 1, + + /// + /// Use specific to Windows passing style which is Legacy for selected files on Windows, but + /// Standard for everything else. This is the default behavior for Windows. + /// + Windows = 2 + } + #endregion NativeArgumentPassingStyle + #region ErrorView /// /// Defines the potential ErrorView options. @@ -286,6 +319,9 @@ public enum ErrorView /// Concise shows more information on the context of the error or just the message if not a script or parser error. ConciseView = 2, + + /// Detailed will leverage Get-Error to get much more detailed information for the error. + DetailedView = 3, } #endregion ErrorView @@ -367,11 +403,11 @@ public enum ConfirmImpact /// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by /// which users create their own Cmdlets. Extending this class provides support for the most /// common functionality, including object output and record processing. - /// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, + /// If your Cmdlet requires access to the PowerShell Runtime (for example, variables in the session state, /// access to the host, or information about the current Cmdlet Providers,) then you should instead /// derive from the PSCmdlet base class. /// The public members defined by the PSCmdlet class are not designed to be overridden; instead, they - /// provided access to different aspects of the MSH runtime. + /// provided access to different aspects of the PowerShell runtime. /// In both cases, users should first develop and implement an object model to accomplish their /// task, extending the Cmdlet or PSCmdlet classes only as a thin management layer. /// diff --git a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs index f31065080c6..9956cf9fa92 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CommandCompletion.cs @@ -4,13 +4,11 @@ using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; -using System.Text.RegularExpressions; #if LEGACYTELEMETRY +using System.Diagnostics; using Microsoft.PowerShell.Telemetry.Internal; #endif @@ -93,7 +91,7 @@ public static Tuple MapStringInputToParsedInput(s /// public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options) { - if (input == null) + if (input == null || input.Length == 0) { return s_emptyCommandCompletion; } @@ -126,12 +124,16 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo throw PSTraceSource.NewArgumentNullException(nameof(positionOfCursor)); } + if (ast.Extent.Text.Length == 0) + { + return s_emptyCommandCompletion; + } + return CompleteInputImpl(ast, tokens, positionOfCursor, options); } /// /// Invokes the script function TabExpansion2. - /// For legacy support, TabExpansion2 will indirectly call TabExpansion if it exists. /// /// The input script to complete. /// The offset in where completion is requested. @@ -141,7 +143,7 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "powershell")] public static CommandCompletion CompleteInput(string input, int cursorIndex, Hashtable options, PowerShell powershell) { - if (input == null) + if (input == null || input.Length == 0) { return s_emptyCommandCompletion; } @@ -180,21 +182,11 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has if (!powershell.IsChild) { CheckScriptCallOnRemoteRunspace(remoteRunspace); + + // TabExpansion2 script is not available prior to PSv3. if (remoteRunspace.GetCapabilities().Equals(Runspaces.RunspaceCapability.Default)) { - // Capability: - // NamedPipeTransport (0x2) -> If remoteMachine is Threshold or later - // SupportsDisconnect (0x1) -> If remoteMachine is Win8 or later - // Default (0x0) -> If remoteMachine is Win7 - // Remoting to a Win7 machine. Use the legacy tab completion function from V1/V2 - int replacementIndex; - int replacementLength; - - powershell.Commands.Clear(); - var results = InvokeLegacyTabExpansion(powershell, input, cursorIndex, true, out replacementIndex, out replacementLength); - return new CommandCompletion( - new Collection(results ?? EmptyCompletionResult), - -1, replacementIndex, replacementLength); + return s_emptyCommandCompletion; } } } @@ -204,7 +196,6 @@ public static CommandCompletion CompleteInput(string input, int cursorIndex, Has /// /// Invokes the script function TabExpansion2. - /// For legacy support, TabExpansion2 will indirectly call TabExpansion if it exists. /// /// The ast for pre-parsed input. /// @@ -235,6 +226,11 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo throw PSTraceSource.NewArgumentNullException(nameof(powershell)); } + if (ast.Extent.Text.Length == 0) + { + return s_emptyCommandCompletion; + } + // If we are in a debugger stop, let the debugger do the command completion. var debugger = powershell.Runspace?.Debugger; if ((debugger != null) && debugger.InBreakpoint) @@ -255,31 +251,17 @@ public static CommandCompletion CompleteInput(Ast ast, Token[] tokens, IScriptPo if (!powershell.IsChild) { CheckScriptCallOnRemoteRunspace(remoteRunspace); + + // TabExpansion2 script is not available prior to PSv3. if (remoteRunspace.GetCapabilities().Equals(Runspaces.RunspaceCapability.Default)) { - // Capability: - // SupportsDisconnect (0x1) -> If remoteMachine is Win8 or later - // Default (0x0) -> If remoteMachine is Win7 - // Remoting to a Win7 machine. Use the legacy tab completion function from V1/V2 - int replacementIndex; - int replacementLength; - - // When call the win7 TabExpansion script, the input should be the single current line - powershell.Commands.Clear(); - var inputAndCursor = GetInputAndCursorFromAst(cursorPosition); - var results = InvokeLegacyTabExpansion(powershell, inputAndCursor.Item1, inputAndCursor.Item2, true, out replacementIndex, out replacementLength); - return new CommandCompletion( - new Collection(results ?? EmptyCompletionResult), - -1, replacementIndex + inputAndCursor.Item3, replacementLength); - } - else - { - // Call script on a remote win8 machine - // when call the win8 TabExpansion2 script, the input should be the whole script text - string input = ast.Extent.Text; - int cursorIndex = ((InternalScriptPosition)cursorPosition).Offset; - return CallScriptWithStringParameterSet(input, cursorIndex, options, powershell); + return s_emptyCommandCompletion; } + + // When calling the TabExpansion2 script, the input should be the whole script text + string input = ast.Extent.Text; + int cursorIndex = ((InternalScriptPosition)cursorPosition).Offset; + return CallScriptWithStringParameterSet(input, cursorIndex, options, powershell); } } @@ -526,810 +508,55 @@ private static CommandCompletion CompleteInputImpl(Ast ast, Token[] tokens, IScr { var context = LocalPipeline.GetExecutionContextFromTLS(); - bool cleanupModuleAnalysisAppDomain = context.TakeResponsibilityForModuleAnalysisAppDomain(); - - try - { - // First, check if a V1/V2 implementation of TabExpansion exists. If so, the user had overridden - // the built-in version, so we should continue to use theirs. - int replacementIndex = -1; - int replacementLength = -1; - List results = null; - - if (NeedToInvokeLegacyTabExpansion(powershell)) - { - var inputAndCursor = GetInputAndCursorFromAst(positionOfCursor); - results = InvokeLegacyTabExpansion(powershell, inputAndCursor.Item1, inputAndCursor.Item2, false, out replacementIndex, out replacementLength); - replacementIndex += inputAndCursor.Item3; - } - - if (results == null || results.Count == 0) - { - /* BROKEN code commented out, fix sometime - // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls - // from our results. We do this by faking out the session so that TabExpansion2 isn't anywhere to be found. - MutableTuple tupleForFrameToSkipPast = null; - foreach (var stackEntry in context.Debugger.GetCallStack()) - { - dynamic stackEntryAsPSObj = PSObject.AsPSObject(stackEntry); - if (stackEntryAsPSObj.Command.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) - { - tupleForFrameToSkipPast = stackEntry.FunctionContext._localsTuple; - break; - } - } + int replacementIndex = -1; + int replacementLength = -1; + List results = null; - SessionStateScope scopeToRestore = null; - if (tupleForFrameToSkipPast != null) - { - // Find this tuple in the scope stack. - scopeToRestore = context.EngineSessionState.CurrentScope; - var scope = context.EngineSessionState.CurrentScope; - while (scope != null && scope.LocalsTuple != tupleForFrameToSkipPast) - { - scope = scope.Parent; - } - - if (scope != null) - { - context.EngineSessionState.CurrentScope = scope.Parent; - } - } - - try - { - */ - var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); - results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); - /* - } - finally - { - if (scopeToRestore != null) - { - context.EngineSessionState.CurrentScope = scopeToRestore; - } - } - */ - } - - var completionResults = results ?? EmptyCompletionResult; - -#if LEGACYTELEMETRY - // no telemetry here. We don't capture tab completion performance. - sw.Stop(); - TelemetryAPI.ReportTabCompletionTelemetry(sw.ElapsedMilliseconds, completionResults.Count, - completionResults.Count > 0 ? completionResults[0].ResultType : CompletionResultType.Text); -#endif - return new CommandCompletion( - new Collection(completionResults), - -1, - replacementIndex, - replacementLength); - } - finally { - if (cleanupModuleAnalysisAppDomain) + // If we were invoked from TabExpansion2, we want to "remove" TabExpansion2 and anything it calls + // from our results. We do this by faking out the session so that TabExpansion2 isn't anywhere to be found. + SessionStateScope scopeToRestore; + if (context.CurrentCommandProcessor is not null + && context.CurrentCommandProcessor.Command.CommandInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase) + && context.CurrentCommandProcessor.UseLocalScope + && context.EngineSessionState.CurrentScope.Parent is not null) { - context.ReleaseResponsibilityForModuleAnalysisAppDomain(); - } - } - } - } - - private static Tuple GetInputAndCursorFromAst(IScriptPosition cursorPosition) - { - var line = cursorPosition.Line; - var cursor = cursorPosition.ColumnNumber - 1; - var adjustment = cursorPosition.Offset - cursor; - return Tuple.Create(line.Substring(0, cursor), cursor, adjustment); - } - - private static bool NeedToInvokeLegacyTabExpansion(PowerShell powershell) - { - var executionContext = powershell.GetContextFromTLS(); - - // We don't want command discovery to search unloaded modules for TabExpansion. - var functionInfo = executionContext.EngineSessionState.GetFunction("TabExpansion"); - if (functionInfo != null) - return true; - - var aliasInfo = executionContext.EngineSessionState.GetAlias("TabExpansion"); - if (aliasInfo != null) - return true; - - return false; - } - - private static List InvokeLegacyTabExpansion(PowerShell powershell, string input, int cursorIndex, bool remoteToWin7, out int replacementIndex, out int replacementLength) - { - List results = null; - - var legacyInput = (cursorIndex != input.Length) ? input.Substring(0, cursorIndex) : input; - char quote; - var lastword = LastWordFinder.FindLastWord(legacyInput, out replacementIndex, out quote); - replacementLength = legacyInput.Length - replacementIndex; - var helper = new PowerShellExecutionHelper(powershell); - - powershell.AddCommand("TabExpansion").AddArgument(legacyInput).AddArgument(lastword); - - Exception exceptionThrown; - var oldResults = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (oldResults != null) - { - results = new List(); - foreach (var oldResult in oldResults) - { - var completionResult = PSObject.Base(oldResult) as CompletionResult; - if (completionResult == null) - { - var oldResultStr = oldResult.ToString(); - - // Add back the quotes we removed if the result isn't quoted - if (quote != '\0') - { - if (oldResultStr.Length > 2 && oldResultStr[0] != quote) - { - oldResultStr = quote + oldResultStr + quote; - } - } - - completionResult = new CompletionResult(oldResultStr); - } - - results.Add(completionResult); - } - } - - if (remoteToWin7 && (results == null || results.Count == 0)) - { - string quoteStr = quote == '\0' ? string.Empty : quote.ToString(); - results = PSv2CompletionCompleter.PSv2GenerateMatchSetOfFiles(helper, lastword, replacementIndex == 0, quoteStr); - var cmdletResults = PSv2CompletionCompleter.PSv2GenerateMatchSetOfCmdlets(helper, lastword, quoteStr, replacementIndex == 0); - - if (cmdletResults != null && cmdletResults.Count > 0) - { - results.AddRange(cmdletResults); - } - } - - return results; - } - - /// - /// PSv2CompletionCompleter implements the algorithm we use to complete cmdlet/file names in PowerShell v2. This class - /// exists for legacy purpose only. It is used only in a remote interactive session from Win8 to Win7. V3 and forward - /// uses completely different completers. - /// - /// - /// The implementation of file name completion is completely different on V2 and V3 for remote scenarios. On PSv3, the - /// CompletionResults are generated always on the target machine, and - /// - private static class PSv2CompletionCompleter - { - private static readonly Regex s_cmdletTabRegex = new Regex(@"^[\w\*\?]+-[\w\*\?]*"); - private static readonly char[] s_charsRequiringQuotedString = "`&@'#{}()$,;|<> \t".ToCharArray(); - - #region "Handle Command" - - /// - /// Used when remoting from a win8 machine to a win7 machine. - /// - /// - /// - /// - private static bool PSv2IsCommandLikeCmdlet(string lastWord, out bool isSnapinSpecified) - { - isSnapinSpecified = false; - - string[] cmdletParts = lastWord.Split(Utils.Separators.Backslash); - if (cmdletParts.Length == 1) - { - return s_cmdletTabRegex.IsMatch(lastWord); - } - - if (cmdletParts.Length == 2) - { - isSnapinSpecified = PSSnapInInfo.IsPSSnapinIdValid(cmdletParts[0]); - if (isSnapinSpecified) - { - return s_cmdletTabRegex.IsMatch(cmdletParts[1]); - } - } - - return false; - } - - private readonly struct CommandAndName - { - internal readonly PSObject Command; - internal readonly PSSnapinQualifiedName CommandName; - - internal CommandAndName(PSObject command, PSSnapinQualifiedName commandName) - { - this.Command = command; - this.CommandName = commandName; - } - } - - /// - /// Used when remoting from a win8 machine to a win7 machine. Complete command names. - /// - /// - /// - /// - /// - /// - internal static List PSv2GenerateMatchSetOfCmdlets(PowerShellExecutionHelper helper, string lastWord, string quote, bool completingAtStartOfLine) - { - var results = new List(); - bool isSnapinSpecified; - - if (!PSv2IsCommandLikeCmdlet(lastWord, out isSnapinSpecified)) - return results; - - helper.CurrentPowerShell - .AddCommand("Get-Command") - .AddParameter("Name", lastWord + "*") - .AddCommand("Sort-Object") - .AddParameter("Property", "Name"); - - Exception exceptionThrown; - Collection commands = helper.ExecuteCurrentPowerShell(out exceptionThrown); - - if (commands != null && commands.Count > 0) - { - // convert the PSObjects into strings - CommandAndName[] cmdlets = new CommandAndName[commands.Count]; - // if the command causes cmdlets from multiple mshsnapin is returned, - // append the mshsnapin name to disambiguate the cmdlets. - for (int i = 0; i < commands.Count; ++i) - { - PSObject command = commands[i]; - string cmdletFullName = CmdletInfo.GetFullName(command); - cmdlets[i] = new CommandAndName(command, PSSnapinQualifiedName.GetInstance(cmdletFullName)); - } - - if (isSnapinSpecified) - { - foreach (CommandAndName cmdlet in cmdlets) - { - AddCommandResult(cmdlet, true, completingAtStartOfLine, quote, results); - } + scopeToRestore = context.EngineSessionState.CurrentScope; + context.EngineSessionState.CurrentScope = scopeToRestore.Parent; } else { - PrependSnapInNameForSameCmdletNames(cmdlets, completingAtStartOfLine, quote, results); - } - } - - return results; - } - - private static void AddCommandResult(CommandAndName commandAndName, bool useFullName, bool completingAtStartOfLine, string quote, List results) - { - Diagnostics.Assert(results != null, "Caller needs to make sure the result list is not null"); - - string name = useFullName ? commandAndName.CommandName.FullName : commandAndName.CommandName.ShortName; - string quotedFileName = AddQuoteIfNecessary(name, quote, completingAtStartOfLine); - - var commandType = SafeGetProperty(commandAndName.Command, "CommandType"); - if (commandType == null) - { - return; - } - - string toolTip; - string displayName = SafeGetProperty(commandAndName.Command, "Name"); - - if (commandType.Value == CommandTypes.Cmdlet || commandType.Value == CommandTypes.Application) - { - toolTip = SafeGetProperty(commandAndName.Command, "Definition"); - } - else - { - toolTip = displayName; - } - - results.Add(new CompletionResult(quotedFileName, displayName, CompletionResultType.Command, toolTip)); - } - - private static void PrependSnapInNameForSameCmdletNames(CommandAndName[] cmdlets, bool completingAtStartOfLine, string quote, List results) - { - Diagnostics.Assert(cmdlets != null && cmdlets.Length > 0, - "HasMultiplePSSnapIns must be called with a non-empty collection of PSObject"); - - int i = 0; - bool previousMatched = false; - while (true) - { - CommandAndName commandAndName = cmdlets[i]; - - int lookAhead = i + 1; - if (lookAhead >= cmdlets.Length) - { - AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); - break; + scopeToRestore = null; } - CommandAndName nextCommandAndName = cmdlets[lookAhead]; - - if (string.Equals( - commandAndName.CommandName.ShortName, - nextCommandAndName.CommandName.ShortName, - StringComparison.OrdinalIgnoreCase)) - { - AddCommandResult(commandAndName, true, completingAtStartOfLine, quote, results); - previousMatched = true; - } - else + try { - AddCommandResult(commandAndName, previousMatched, completingAtStartOfLine, quote, results); - previousMatched = false; + var completionAnalysis = new CompletionAnalysis(ast, tokens, positionOfCursor, options); + results = completionAnalysis.GetResults(powershell, out replacementIndex, out replacementLength); } - - i++; - } - } - - #endregion "Handle Command" - - #region "Handle File Names" - - internal static List PSv2GenerateMatchSetOfFiles(PowerShellExecutionHelper helper, string lastWord, bool completingAtStartOfLine, string quote) - { - var results = new List(); - - // lastWord is treated as an PSPath. The match set includes those items that match that - // path, namely, the union of: - // (S1) the sorted set of items matching the last word - // (S2) the sorted set of items matching the last word + * - // If the last word contains no wildcard characters, then S1 is the empty set. S1 is always - // a subset of S2, but we want to present S1 first, then (S2 - S1) next. The idea is that - // if the user typed some wildcard characters, they'd prefer to see those matches before - // all of the rest. - - // Determine if we need to quote the paths we parse - - lastWord ??= string.Empty; - bool isLastWordEmpty = string.IsNullOrEmpty(lastWord); - bool lastCharIsStar = !isLastWordEmpty && lastWord.EndsWith('*'); - bool containsGlobChars = WildcardPattern.ContainsWildcardCharacters(lastWord); - - string wildWord = lastWord + "*"; - bool shouldFullyQualifyPaths = PSv2ShouldFullyQualifyPathsPath(helper, lastWord); - - // NTRAID#Windows Out Of Band Releases-927933-2006/03/13-JeffJon - // Need to detect when the path is a provider-direct path and make sure - // to remove the provider-qualifier when the resolved path is returned. - bool isProviderDirectPath = lastWord.StartsWith(@"\\", StringComparison.Ordinal) || - lastWord.StartsWith("//", StringComparison.Ordinal); - - List s1 = null; - List s2 = null; - - if (containsGlobChars && !isLastWordEmpty) - { - s1 = PSv2FindMatches( - helper, - lastWord, - shouldFullyQualifyPaths); - } - - if (!lastCharIsStar) - { - s2 = PSv2FindMatches( - helper, - wildWord, - shouldFullyQualifyPaths); - } - - IEnumerable combinedMatches = CombineMatchSets(s1, s2); - - if (combinedMatches != null) - { - foreach (var combinedMatch in combinedMatches) + finally { - string combinedMatchPath = WildcardPattern.Escape(combinedMatch.Path); - string combinedMatchConvertedPath = WildcardPattern.Escape(combinedMatch.ConvertedPath); - string completionText = isProviderDirectPath ? combinedMatchConvertedPath : combinedMatchPath; - - completionText = AddQuoteIfNecessary(completionText, quote, completingAtStartOfLine); - - bool? isContainer = SafeGetProperty(combinedMatch.Item, "PSIsContainer"); - string childName = SafeGetProperty(combinedMatch.Item, "PSChildName"); - string toolTip = PowerShellExecutionHelper.SafeToString(combinedMatch.ConvertedPath); - - if (isContainer != null && childName != null && toolTip != null) + if (scopeToRestore != null) { - CompletionResultType resultType = isContainer.Value - ? CompletionResultType.ProviderContainer - : CompletionResultType.ProviderItem; - results.Add(new CompletionResult(completionText, childName, resultType, toolTip)); + context.EngineSessionState.CurrentScope = scopeToRestore; } } } - return results; - } - - private static string AddQuoteIfNecessary(string completionText, string quote, bool completingAtStartOfLine) - { - if (completionText.IndexOfAny(s_charsRequiringQuotedString) != -1) - { - bool needAmpersand = quote.Length == 0 && completingAtStartOfLine; - string quoteInUse = quote.Length == 0 ? "'" : quote; - completionText = quoteInUse == "'" ? completionText.Replace("'", "''") : completionText; - completionText = quoteInUse + completionText + quoteInUse; - completionText = needAmpersand ? "& " + completionText : completionText; - } - else - { - completionText = quote + completionText + quote; - } - - return completionText; - } - - private static IEnumerable CombineMatchSets(List s1, List s2) - { - if (s1 == null || s1.Count < 1) - { - // only s2 contains results; which may be null or empty - return s2; - } - - if (s2 == null || s2.Count < 1) - { - // only s1 contains results - return s1; - } - - // s1 and s2 contain results - Diagnostics.Assert(s1 != null && s1.Count > 0, "s1 should have results"); - Diagnostics.Assert(s2 != null && s2.Count > 0, "if s1 has results, s2 must also"); - Diagnostics.Assert(s1.Count <= s2.Count, "s2 should always be larger than s1"); - - var result = new List(); + var completionResults = results ?? EmptyCompletionResult; - // we need to remove from s2 those items in s1. Since the results from FindMatches will be sorted, - // just copy out the unique elements from s2 and s1. We know that every element of S1 will be in S2, - // so the result set will be S1 + (S2 - S1), which is the same size as S2. - result.AddRange(s1); - for (int i = 0, j = 0; i < s2.Count; ++i) - { - if (j < s1.Count && string.Equals(s2[i].Path, s1[j].Path, StringComparison.CurrentCultureIgnoreCase)) - { - ++j; - continue; - } - - result.Add(s2[i]); - } - -#if DEBUG - Diagnostics.Assert(result.Count == s2.Count, "result should be the same size as s2, see the size comment above"); - for (int i = 0; i < s1.Count; ++i) - { - string path = result[i].Path; - int j = result.FindLastIndex(item => item.Path == path); - Diagnostics.Assert(j == i, "elements of s1 should only come at the start of the results"); - } +#if LEGACYTELEMETRY + // no telemetry here. We don't capture tab completion performance. + sw.Stop(); + TelemetryAPI.ReportTabCompletionTelemetry(sw.ElapsedMilliseconds, completionResults.Count, + completionResults.Count > 0 ? completionResults[0].ResultType : CompletionResultType.Text); #endif - return result; - } - - private static T SafeGetProperty(PSObject psObject, string propertyName) - { - if (psObject == null) - { - return default(T); - } - - PSPropertyInfo property = psObject.Properties[propertyName]; - if (property == null) - { - return default(T); - } - - object propertyValue = property.Value; - if (propertyValue == null) - { - return default(T); - } - - T returnValue; - if (LanguagePrimitives.TryConvertTo(propertyValue, out returnValue)) - { - return returnValue; - } - - return default(T); - } - - private static bool PSv2ShouldFullyQualifyPathsPath(PowerShellExecutionHelper helper, string lastWord) - { - // These are special cases, as they represent cases where the user expects to - // see the full path. - if (lastWord.StartsWith('~') || - lastWord.StartsWith('\\') || - lastWord.StartsWith('/')) - { - return true; - } - - helper.CurrentPowerShell - .AddCommand("Split-Path") - .AddParameter("Path", lastWord) - .AddParameter("IsAbsolute", true); - - bool isAbsolute = helper.ExecuteCommandAndGetResultAsBool(); - return isAbsolute; - } - - private readonly struct PathItemAndConvertedPath - { - internal readonly string Path; - internal readonly PSObject Item; - internal readonly string ConvertedPath; - - internal PathItemAndConvertedPath(string path, PSObject item, string convertedPath) - { - this.Path = path; - this.Item = item; - this.ConvertedPath = convertedPath; - } - } - - private static List PSv2FindMatches(PowerShellExecutionHelper helper, string path, bool shouldFullyQualifyPaths) - { - Diagnostics.Assert(!string.IsNullOrEmpty(path), "path should have a value"); - var result = new List(); - - Exception exceptionThrown; - PowerShell powershell = helper.CurrentPowerShell; - - // It's OK to use script, since tab completion is useless when the remote Win7 machine is in nolanguage mode - if (!shouldFullyQualifyPaths) - { - powershell.AddScript(string.Format( - CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -Relative -WarningAction SilentlyContinue | ForEach-Object {{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", - path)); - } - else - { - powershell.AddScript(string.Format( - CultureInfo.InvariantCulture, - "& {{ trap {{ continue }} ; resolve-path {0} -WarningAction SilentlyContinue | ForEach-Object {{,($_,(get-item $_ -WarningAction SilentlyContinue),(convert-path $_ -WarningAction SilentlyContinue))}} }}", - path)); - } - - Collection paths = helper.ExecuteCurrentPowerShell(out exceptionThrown); - if (paths == null || paths.Count == 0) - { - return null; - } - - foreach (PSObject t in paths) - { - var pathsArray = t.BaseObject as IList; - if (pathsArray != null && pathsArray.Count == 3) - { - object objectPath = pathsArray[0]; - PSObject item = pathsArray[1] as PSObject; - object convertedPath = pathsArray[1]; - - if (objectPath == null || item == null || convertedPath == null) - { - continue; - } - - result.Add(new PathItemAndConvertedPath( - PowerShellExecutionHelper.SafeToString(objectPath), - item, - PowerShellExecutionHelper.SafeToString(convertedPath))); - } - } - - if (result.Count == 0) - { - return null; - } - - result.Sort((PathItemAndConvertedPath x, PathItemAndConvertedPath y) => - { - Diagnostics.Assert(x.Path != null && y.Path != null, "SafeToString always returns a non-null string"); - return string.Compare(x.Path, y.Path, StringComparison.CurrentCultureIgnoreCase); - }); - - return result; - } - - #endregion "Handle File Names" - } - - /// - /// LastWordFinder implements the algorithm we use to search for the last word in a line of input taken from the console. - /// This class exists for legacy purposes only - V3 and forward uses a slightly different interface. - /// - private class LastWordFinder - { - internal static string FindLastWord(string sentence, out int replacementIndexOut, out char closingQuote) - { - return (new LastWordFinder(sentence)).FindLastWord(out replacementIndexOut, out closingQuote); - } - - private LastWordFinder(string sentence) - { - _replacementIndex = 0; - Diagnostics.Assert(sentence != null, "need to provide an instance"); - _sentence = sentence; - } - - /// - /// Locates the last "word" in a string of text. A word is a conguous sequence of characters that are not - /// whitespace, or a contiguous set grouped by single or double quotes. Can be called by at most 1 thread at a time - /// per LastWordFinder instance. - /// - /// - /// Receives the character index (from the front of the string) of the starting point of the located word, or 0 if - /// the word starts at the beginning of the sentence. - /// - /// - /// Receives the quote character that would be needed to end the sentence with a balanced pair of quotes. For - /// instance, if sentence is "foo then " is returned, if sentence if "foo" then nothing is returned, if sentence is - /// 'foo then ' is returned, if sentence is 'foo' then nothing is returned. - /// - /// The last word located, or the empty string if no word could be found. - private string FindLastWord(out int replacementIndexOut, out char closingQuote) - { - bool inSingleQuote = false; - bool inDoubleQuote = false; - - ReplacementIndex = 0; - - for (_sentenceIndex = 0; _sentenceIndex < _sentence.Length; ++_sentenceIndex) - { - Diagnostics.Assert(!(inSingleQuote && inDoubleQuote), - "Can't be in both single and double quotes"); - - char c = _sentence[_sentenceIndex]; - - // there are 3 possibilities: - // 1) a new sequence is starting, - // 2) a sequence is ending, or - // 3) a sequence is due to end on the next matching quote, end-of-sentence, or whitespace - - if (c == '\'') - { - HandleQuote(ref inSingleQuote, ref inDoubleQuote, c); - } - else if (c == '"') - { - HandleQuote(ref inDoubleQuote, ref inSingleQuote, c); - } - else if (c == '`') - { - Consume(c); - if (++_sentenceIndex < _sentence.Length) - { - Consume(_sentence[_sentenceIndex]); - } - } - else if (IsWhitespace(c)) - { - if (_sequenceDueToEnd) - { - // we skipped a quote earlier, now end that sequence - - _sequenceDueToEnd = false; - if (inSingleQuote) - { - inSingleQuote = false; - } - - if (inDoubleQuote) - { - inDoubleQuote = false; - } - - ReplacementIndex = _sentenceIndex + 1; - } - else if (inSingleQuote || inDoubleQuote) - { - // a sequence is started and we're in quotes - - Consume(c); - } - else - { - // no sequence is started, so ignore c - - ReplacementIndex = _sentenceIndex + 1; - } - } - else - { - // a sequence is started and we're in it - - Consume(c); - } - } - - string result = new string(_wordBuffer, 0, _wordBufferIndex); - - closingQuote = inSingleQuote ? '\'' : inDoubleQuote ? '"' : '\0'; - replacementIndexOut = ReplacementIndex; - return result; + return new CommandCompletion( + new Collection(completionResults), + -1, + replacementIndex, + replacementLength); } - - private void HandleQuote(ref bool inQuote, ref bool inOppositeQuote, char c) - { - if (inOppositeQuote) - { - // a sequence is started, and we're in it. - Consume(c); - return; - } - - if (inQuote) - { - if (_sequenceDueToEnd) - { - // I've ended a sequence and am starting another; don't consume c, update replacementIndex - ReplacementIndex = _sentenceIndex + 1; - } - - _sequenceDueToEnd = !_sequenceDueToEnd; - } - else - { - // I'm starting a sequence; don't consume c, update replacementIndex - inQuote = true; - ReplacementIndex = _sentenceIndex; - } - } - - private void Consume(char c) - { - Diagnostics.Assert(_wordBuffer != null, "wordBuffer is not initialized"); - Diagnostics.Assert(_wordBufferIndex < _wordBuffer.Length, "wordBufferIndex is out of range"); - - _wordBuffer[_wordBufferIndex++] = c; - } - - private int ReplacementIndex - { - get - { - return _replacementIndex; - } - - set - { - Diagnostics.Assert(value >= 0 && value < _sentence.Length + 1, "value out of range"); - - // when we set the replacement index, that means we're also resetting our word buffer. we know wordBuffer - // will never be longer than sentence. - - _wordBuffer = new char[_sentence.Length]; - _wordBufferIndex = 0; - _replacementIndex = value; - } - } - - private static bool IsWhitespace(char c) - { - return (c == ' ') || (c == '\x0009'); - } - - private readonly string _sentence; - private char[] _wordBuffer; - private int _wordBufferIndex; - private int _replacementIndex; - private int _sentenceIndex; - private bool _sequenceDueToEnd; } #endregion private methods diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs index f8961956a31..9c4a61a6833 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionAnalysis.cs @@ -9,6 +9,8 @@ using System.Reflection; using System.Text; using System.Text.RegularExpressions; +using System.Management.Automation.Subsystem; +using System.Management.Automation.Subsystem.DSC; namespace System.Management.Automation { @@ -153,6 +155,19 @@ internal static AstAnalysisContext ExtractAstContext(Ast inputAst, Token[] input ast => IsCursorWithinOrJustAfterExtent(positionForAstSearch, ast.Extent), searchNestedScriptBlocks: true).ToList(); + if (relatedAsts.Count == 0) + { + relatedAsts.Add(inputAst); + } + + // If the last ast is an unnamed block that starts with "param" the cursor is inside a param block. + // To avoid adding special handling to all the completers that look at the last ast, we remove it here because it's not useful for completion. + if (relatedAsts[^1].Extent.Text.StartsWith("param", StringComparison.OrdinalIgnoreCase) + && relatedAsts[^1] is NamedBlockAst namedBlock && namedBlock.Unnamed) + { + relatedAsts.RemoveAt(relatedAsts.Count - 1); + } + Diagnostics.Assert(tokenAtCursor == null || tokenBeforeCursor == null, "Only one of these tokens can be non-null"); return new AstAnalysisContext(tokenAtCursor, tokenBeforeCursor, relatedAsts, replacementIndex); @@ -173,10 +188,7 @@ private CompletionContext InitializeCompletionContext(TypeInferenceContext typeI { var astContext = ExtractAstContext(_ast, _tokens, _cursorPosition); - if (typeInferenceContext.CurrentTypeDefinitionAst == null) - { - typeInferenceContext.CurrentTypeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(astContext.RelatedAsts.Last()); - } + typeInferenceContext.CurrentTypeDefinitionAst ??= Ast.GetAncestorTypeDefinitionAst(astContext.RelatedAsts.Last()); ExecutionContext executionContext = typeInferenceContext.ExecutionContext; @@ -239,8 +251,7 @@ private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCurs { Tuple fileConditionTuple; - var errorStatement = lastAst as ErrorStatementAst; - if (errorStatement != null && errorStatement.Flags != null && errorStatement.Kind != null && tokenBeforeCursor != null && + if (lastAst is ErrorStatementAst errorStatement && errorStatement.Flags is not null && errorStatement.Kind is not null && tokenBeforeCursor is not null && errorStatement.Kind.Kind.Equals(TokenKind.Switch) && errorStatement.Flags.TryGetValue("file", out fileConditionTuple)) { // Handle "switch -file " @@ -250,24 +261,239 @@ private static bool CompleteAgainstSwitchFile(Ast lastAst, Token tokenBeforeCurs if (lastAst.Parent is CommandExpressionAst) { // Handle "switch -file m" or "switch -file *.ps1" - if (!(lastAst.Parent.Parent is PipelineAst pipeline)) + if (lastAst.Parent.Parent is not PipelineAst pipeline) { return false; } - errorStatement = pipeline.Parent as ErrorStatementAst; - if (errorStatement == null || errorStatement.Kind == null || errorStatement.Flags == null) + if (pipeline.Parent is not ErrorStatementAst parentErrorStatement || parentErrorStatement.Kind is null || parentErrorStatement.Flags is null) { return false; } - return (errorStatement.Kind.Kind.Equals(TokenKind.Switch) && - errorStatement.Flags.TryGetValue("file", out fileConditionTuple) && fileConditionTuple.Item2 == pipeline); + return (parentErrorStatement.Kind.Kind.Equals(TokenKind.Switch) && + parentErrorStatement.Flags.TryGetValue("file", out fileConditionTuple) && fileConditionTuple.Item2 == pipeline); } return false; } + /// + /// Check if we should complete parameter names for switch cases on $PSBoundParameters.Keys + /// + private static List CompleteAgainstSwitchCaseCondition(CompletionContext completionContext) + { + var lastAst = completionContext.RelatedAsts.Last(); + + PipelineAst conditionPipeline = null; + Ast switchAst = null; + + // Check if we're in a switch statement (complete) or error statement (incomplete switch) + if (lastAst.Parent is SwitchStatementAst switchStatementAst) + { + // Verify that the lastAst is one of the clause conditions (not in the body) + bool isClauseCondition = switchStatementAst.Clauses.Any(clause => clause.Item1 == lastAst); + + if (!isClauseCondition) + { + return null; + } + + conditionPipeline = switchStatementAst.Condition as PipelineAst; + switchAst = switchStatementAst; + } + else + { + // Check for incomplete switch parsed as ErrorStatementAst + if (lastAst.Parent is not ErrorStatementAst errorStatementAst || errorStatementAst.Kind is null || + errorStatementAst.Kind.Kind != TokenKind.Switch) + { + return null; + } + + // For ErrorStatementAst, the case value is in Bodies, condition is in Conditions + bool isInBodies = errorStatementAst.Bodies != null && errorStatementAst.Bodies.Any(body => body == lastAst); + + if (!isInBodies) + { + return null; + } + + // Get the condition from ErrorStatementAst.Conditions + if (errorStatementAst.Conditions != null && errorStatementAst.Conditions.Count > 0) + { + conditionPipeline = errorStatementAst.Conditions[0] as PipelineAst; + } + switchAst = errorStatementAst; + } + + if (conditionPipeline == null || conditionPipeline.PipelineElements.Count != 1) + { + return null; + } + + if (conditionPipeline.PipelineElements[0] is not CommandExpressionAst commandExpressionAst) + { + return null; + } + + // Check if the expression is a member access on $PSBoundParameters.Keys + if (commandExpressionAst.Expression is not MemberExpressionAst memberExpressionAst) + { + return null; + } + + // Check if the target is $PSBoundParameters + if (memberExpressionAst.Expression is not VariableExpressionAst variableExpressionAst || + !variableExpressionAst.VariablePath.UserPath.Equals("PSBoundParameters", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + // Check if the member is "Keys" + if (memberExpressionAst.Member is not StringConstantExpressionAst memberNameAst || + !memberNameAst.Value.Equals("Keys", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + // Find the nearest param block by traversing up the AST + var paramBlockAst = FindNearestParamBlock(switchAst.Parent); + + if (paramBlockAst == null || paramBlockAst.Parameters.Count == 0) + { + return null; + } + + // Generate completion results from parameter names + var wordToComplete = completionContext.WordToComplete ?? string.Empty; + return CreateParameterCompletionResults(paramBlockAst, wordToComplete); + } + + /// + /// Check if we should complete parameter names for $PSBoundParameters access patterns + /// Supports: $PSBoundParameters.ContainsKey('...'), $PSBoundParameters['...'], $PSBoundParameters.Remove('...') + /// + private static List CompleteAgainstPSBoundParametersAccess(CompletionContext completionContext) + { + var lastAst = completionContext.RelatedAsts.Last(); + + // Must be a string constant + if (lastAst is not StringConstantExpressionAst stringAst) + { + return null; + } + + ExpressionAst targetAst = null; + + // Check for method invocation: $PSBoundParameters.ContainsKey('...') or $PSBoundParameters.Remove('...') + if (lastAst.Parent is InvokeMemberExpressionAst invokeMemberAst) + { + if (invokeMemberAst.Member is StringConstantExpressionAst memberName && + (memberName.Value.Equals("ContainsKey", StringComparison.OrdinalIgnoreCase) || + memberName.Value.Equals("Remove", StringComparison.OrdinalIgnoreCase))) + { + targetAst = invokeMemberAst.Expression; + } + } + // Check for indexer: $PSBoundParameters['...'] + else if (lastAst.Parent is IndexExpressionAst indexAst) + { + targetAst = indexAst.Target; + } + + if (targetAst is null) + { + return null; + } + + // Check if target is $PSBoundParameters + if (targetAst is not VariableExpressionAst variableAst || + !variableAst.VariablePath.UserPath.Equals("PSBoundParameters", StringComparison.OrdinalIgnoreCase)) + { + return null; + } + + // Find the nearest param block + var paramBlockAst = FindNearestParamBlock(lastAst.Parent); + + if (paramBlockAst == null || paramBlockAst.Parameters.Count == 0) + { + return null; + } + + // Generate completion results from parameter names + var wordToComplete = completionContext.WordToComplete ?? string.Empty; + + // Determine quote style based on the string constant type + string quoteChar = string.Empty; + if (stringAst.StringConstantType == StringConstantType.SingleQuoted) + { + quoteChar = "'"; + } + else if (stringAst.StringConstantType == StringConstantType.DoubleQuoted) + { + quoteChar = "\""; + } + + return CreateParameterCompletionResults(paramBlockAst, wordToComplete, quoteChar); + } + + /// + /// Finds the nearest ParamBlockAst by traversing up the AST hierarchy. + /// + /// The AST node to start searching from. + /// The nearest ParamBlockAst if found; otherwise, null. + private static ParamBlockAst FindNearestParamBlock(Ast startAst) + { + Ast current = startAst; + while (current != null) + { + if (current is FunctionDefinitionAst functionDefinitionAst) + { + return functionDefinitionAst.Body?.ParamBlock; + } + else if (current is ScriptBlockAst scriptBlockAst) + { + var paramBlock = scriptBlockAst.ParamBlock; + if (paramBlock != null) + { + return paramBlock; + } + } + + current = current.Parent; + } + + return null; + } + + /// + /// Creates completion results from parameter names with optional quote wrapping. + /// + /// The parameter block containing parameters to complete. + /// The partial word to match against parameter names. + /// Optional quote character to wrap completion text (empty string for no quotes). + /// A list of completion results, or null if no matches found. + private static List CreateParameterCompletionResults( + ParamBlockAst paramBlockAst, + string wordToComplete, + string quoteChar = "") + { + var result = paramBlockAst.Parameters + .Select(parameter => parameter.Name.VariablePath.UserPath) + .Where(parameterName => parameterName.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + .Select(parameterName => + new CompletionResult( + quoteChar + parameterName + quoteChar, + parameterName, + CompletionResultType.ParameterValue, + parameterName)) + .ToList(); + + return result.Count > 0 ? result : null; + } + private static bool CompleteOperator(Token tokenAtCursor, Ast lastAst) { if (tokenAtCursor.Kind == TokenKind.Minus) @@ -375,7 +601,10 @@ internal List GetResults(PowerShell powerShell, out int replac completionContext.ExecutionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } - return GetResultHelper(completionContext, out replacementIndex, out replacementLength, false); + List results = GetResultHelper(completionContext, out replacementIndex, out replacementLength); + CompletionCompleters.RemoveLastNullCompletionResult(results); + + return results; } finally { @@ -386,7 +615,7 @@ internal List GetResults(PowerShell powerShell, out int replac } } - internal List GetResultHelper(CompletionContext completionContext, out int replacementIndex, out int replacementLength, bool isQuotedString) + internal List GetResultHelper(CompletionContext completionContext, out int replacementIndex, out int replacementLength) { replacementIndex = -1; replacementLength = -1; @@ -414,14 +643,20 @@ internal List GetResultHelper(CompletionContext completionCont case TokenKind.Generic: case TokenKind.MinusMinus: // for native commands '--' case TokenKind.Identifier: - result = GetResultForIdentifier(completionContext, ref replacementIndex, ref replacementLength, isQuotedString); + if (!tokenAtCursor.TokenFlags.HasFlag(TokenFlags.TypeName)) + { + result = CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength); + if (result is not null) + { + return result; + } + + result = GetResultForIdentifier(completionContext, ref replacementIndex, ref replacementLength); + } + break; case TokenKind.Parameter: - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) - break; - completionContext.WordToComplete = tokenAtCursor.Text; var cmdAst = lastAst.Parent as CommandAst; if (lastAst is StringConstantExpressionAst && cmdAst != null && cmdAst.CommandElements.Count == 1) @@ -464,16 +699,13 @@ internal List GetResultHelper(CompletionContext completionCont case TokenKind.QuestionDot: replacementIndex += tokenAtCursor.Text.Length; replacementLength = 0; - result = CompletionCompleters.CompleteMember(completionContext, @static: tokenAtCursor.Kind == TokenKind.ColonColon); + result = CompletionCompleters.CompleteMember(completionContext, @static: tokenAtCursor.Kind == TokenKind.ColonColon, ref replacementLength); + break; case TokenKind.Comment: - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) - break; - completionContext.WordToComplete = tokenAtCursor.Text; - result = CompletionCompleters.CompleteComment(completionContext); + result = CompletionCompleters.CompleteComment(completionContext, ref replacementIndex, ref replacementLength); break; case TokenKind.StringExpandable: @@ -488,8 +720,30 @@ internal List GetResultHelper(CompletionContext completionCont return completions; } } + else if (lastAst.Parent is BinaryExpressionAst binaryExpression) + { + completionContext.WordToComplete = (tokenAtCursor as StringToken).Value; + result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); + if (result.Count > 0) + { + return result; + } + } + else if (lastAst.Parent is IndexExpressionAst indexExpressionAst) + { + // Handles quoted string inside index expression like: $PSVersionTable[""] + completionContext.WordToComplete = (tokenAtCursor as StringToken).Value; + // Check for $PSBoundParameters indexer first + var psBoundResult = CompleteAgainstPSBoundParametersAccess(completionContext); + if (psBoundResult != null && psBoundResult.Count > 0) + { + return psBoundResult; + } + + return CompletionCompleters.CompleteIndexExpression(completionContext, indexExpressionAst.Target); + } - result = GetResultForString(completionContext, ref replacementIndex, ref replacementLength, isQuotedString); + result = GetResultForString(completionContext, ref replacementIndex, ref replacementLength); break; case TokenKind.RBracket: @@ -517,9 +771,14 @@ internal List GetResultHelper(CompletionContext completionCont break; case TokenKind.Comma: - // Handle array elements such as dir .\cd, || dir -Path: .\cd, - if (lastAst is ErrorExpressionAst && - (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst)) + // Handle array elements such as the followings: + // - `dir .\cd,` + // - `dir -Path: .\cd,` + // - `dir .\abc.txt, -File` + // - `dir -Path .\abc.txt, -File` + // - `dir -Path: .\abc.txt, -File` + if (lastAst is ErrorExpressionAst or ArrayLiteralAst && + lastAst.Parent is CommandAst or CommandParameterAst) { replacementIndex += replacementLength; replacementLength = 0; @@ -544,8 +803,7 @@ internal List GetResultHelper(CompletionContext completionCont // { // DependsOn=@('[user]x',|) // - bool unused; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); + result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _); } break; @@ -659,6 +917,19 @@ internal List GetResultHelper(CompletionContext completionCont return completions; } } + else if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0) + { + foreach (AttributeBaseAst attribute in paramAst.Attributes) + { + if (IsCursorWithinOrJustAfterExtent(_cursorPosition, attribute.Extent)) + { + completionContext.ReplacementIndex = replacementIndex += tokenAtCursor.Text.Length; + completionContext.ReplacementLength = replacementLength = 0; + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + break; + } + } + } else { // Handle scenarios such as 'configuration foo { File ab { Attributes =' @@ -673,13 +944,82 @@ internal List GetResultHelper(CompletionContext completionCont // DependsOn=@(|) // DependsOn=(| // - bool unused; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); + result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _); } break; } + + case TokenKind.Format: + case TokenKind.Not: + case TokenKind.Bnot: + case TokenKind.And: + case TokenKind.Or: + case TokenKind.Xor: + case TokenKind.Band: + case TokenKind.Bor: + case TokenKind.Bxor: + case TokenKind.Join: + case TokenKind.Ieq: + case TokenKind.Ine: + case TokenKind.Ige: + case TokenKind.Igt: + case TokenKind.Ilt: + case TokenKind.Ile: + case TokenKind.Ilike: + case TokenKind.Inotlike: + case TokenKind.Imatch: + case TokenKind.Inotmatch: + case TokenKind.Ireplace: + case TokenKind.Icontains: + case TokenKind.Inotcontains: + case TokenKind.Iin: + case TokenKind.Inotin: + case TokenKind.Isplit: + case TokenKind.Ceq: + case TokenKind.Cne: + case TokenKind.Cge: + case TokenKind.Cgt: + case TokenKind.Clt: + case TokenKind.Cle: + case TokenKind.Clike: + case TokenKind.Cnotlike: + case TokenKind.Cmatch: + case TokenKind.Cnotmatch: + case TokenKind.Creplace: + case TokenKind.Ccontains: + case TokenKind.Cnotcontains: + case TokenKind.Cin: + case TokenKind.Cnotin: + case TokenKind.Csplit: + case TokenKind.Is: + case TokenKind.IsNot: + case TokenKind.As: + case TokenKind.Shl: + case TokenKind.Shr: + result = CompletionCompleters.CompleteOperator(tokenAtCursor.Text); + break; + + case TokenKind.LBracket: + if (lastAst.Parent is IndexExpressionAst indexExpression) + { + // Handles index expression with cursor right after lbracket like: $PSVersionTable[] + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); + if (result.Count > 0) + { + replacementIndex++; + replacementLength--; + } + } + break; default: + result = CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength); + if (result is not null) + { + return result; + } + if ((tokenAtCursor.TokenFlags & TokenFlags.Keyword) != 0) { completionContext.WordToComplete = tokenAtCursor.Text; @@ -728,8 +1068,7 @@ internal List GetResultHelper(CompletionContext completionCont bool skipAutoCompleteForCommandCall = isCursorLineEmpty && !isLineContinuationBeforeCursor; bool lastAstIsExpressionAst = lastAst is ExpressionAst; - if (!isQuotedString && - !skipAutoCompleteForCommandCall && + if (!skipAutoCompleteForCommandCall && (lastAst is CommandParameterAst || lastAst is CommandAst || (lastAstIsExpressionAst && lastAst.Parent is CommandAst) || (lastAstIsExpressionAst && lastAst.Parent is CommandParameterAst) || @@ -768,7 +1107,7 @@ internal List GetResultHelper(CompletionContext completionCont replacementLength = completionContext.ReplacementLength; } } - else if (!isQuotedString) + else { // // Handle completion of empty line within configuration statement @@ -803,6 +1142,75 @@ internal List GetResultHelper(CompletionContext completionCont result = GetResultForIdentifierInConfiguration(completionContext, configAst, keywordAst, out matched); } } + + // Handles following scenario where user is tab completing a member on an empty line: + // "Hello". + // + if ((result is null || result.Count == 0) && tokenBeforeCursor is not null) + { + switch (completionContext.TokenBeforeCursor.Kind) + { + + case TokenKind.Dot: + case TokenKind.ColonColon: + case TokenKind.QuestionDot: + replacementIndex = cursor.Offset; + replacementLength = 0; + result = CompletionCompleters.CompleteMember(completionContext, @static: completionContext.TokenBeforeCursor.Kind == TokenKind.ColonColon, ref replacementLength); + break; + + case TokenKind.LParen: + case TokenKind.Comma: + if (lastAst is AttributeAst) + { + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + } + + if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0) + { + foreach (AttributeBaseAst attribute in paramAst.Attributes) + { + if (IsCursorWithinOrJustAfterExtent(_cursorPosition, attribute.Extent)) + { + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + break; + } + } + } + break; + + case TokenKind.Ieq: + case TokenKind.Ceq: + case TokenKind.Ine: + case TokenKind.Cne: + case TokenKind.Ilike: + case TokenKind.Clike: + case TokenKind.Inotlike: + case TokenKind.Cnotlike: + case TokenKind.Imatch: + case TokenKind.Cmatch: + case TokenKind.Inotmatch: + case TokenKind.Cnotmatch: + if (lastAst is BinaryExpressionAst binaryExpression) + { + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); + } + break; + + case TokenKind.LBracket: + if (lastAst.Parent is IndexExpressionAst indexExpression) + { + // Handles index expression where cursor is on a new line after the lbracket like: $PSVersionTable[\n] + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); + } + break; + + default: + break; + } + } } else if (completionContext.TokenAtCursor == null) { @@ -836,7 +1244,7 @@ internal List GetResultHelper(CompletionContext completionCont break; } } - + if (lastAst is AttributeAst) { completionContext.ReplacementLength = replacementLength = 0; @@ -844,10 +1252,80 @@ internal List GetResultHelper(CompletionContext completionCont break; } - bool unused; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out unused); + if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0) + { + foreach (AttributeBaseAst attribute in paramAst.Attributes) + { + if (IsCursorWithinOrJustAfterExtent(_cursorPosition, attribute.Extent)) + { + completionContext.ReplacementLength = replacementLength = 0; + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + break; + } + } + + break; + } + + result = GetResultForEnumPropertyValueOfDSCResource(completionContext, string.Empty, ref replacementIndex, ref replacementLength, out _); + break; + } + + case TokenKind.Break: + case TokenKind.Continue: + { + if ((lastAst is BreakStatementAst breakStatement && breakStatement.Label is null) + || (lastAst is ContinueStatementAst continueStatement && continueStatement.Label is null)) + { + result = CompleteLoopLabel(completionContext); + } break; } + + case TokenKind.Using: + return CompleteUsingKeywords(completionContext.CursorPosition.Offset, _tokens, ref replacementIndex, ref replacementLength); + + case TokenKind.Dot: + case TokenKind.ColonColon: + case TokenKind.QuestionDot: + // Handles following scenario with whitespace after member access token: "Hello". + replacementIndex = cursor.Offset; + replacementLength = 0; + result = CompletionCompleters.CompleteMember(completionContext, @static: tokenBeforeCursor.Kind == TokenKind.ColonColon, ref replacementLength); + if (result is not null && result.Count > 0) + { + return result; + } + break; + + case TokenKind.Ieq: + case TokenKind.Ceq: + case TokenKind.Ine: + case TokenKind.Cne: + case TokenKind.Ilike: + case TokenKind.Clike: + case TokenKind.Inotlike: + case TokenKind.Cnotlike: + case TokenKind.Imatch: + case TokenKind.Cmatch: + case TokenKind.Inotmatch: + case TokenKind.Cnotmatch: + if (lastAst is BinaryExpressionAst binaryExpression) + { + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteComparisonOperatorValues(completionContext, binaryExpression.Left); + } + break; + + case TokenKind.LBracket: + if (lastAst.Parent is IndexExpressionAst indexExpression) + { + // Handles index expression with whitespace between lbracket and cursor like: $PSVersionTable[ ] + completionContext.WordToComplete = string.Empty; + result = CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); + } + break; + default: break; } @@ -902,6 +1380,11 @@ internal List GetResultHelper(CompletionContext completionCont } } + if (typeNameToComplete is null && tokenAtCursor?.TokenFlags.HasFlag(TokenFlags.TypeName) == true) + { + typeNameToComplete = new TypeName(tokenAtCursor.Extent, tokenAtCursor.Text); + } + if (typeNameToComplete != null) { // See if the typename to complete really is within the typename, and if so, which one, in the case of generics. @@ -909,13 +1392,19 @@ internal List GetResultHelper(CompletionContext completionCont replacementIndex = typeNameToComplete.Extent.StartOffset; replacementLength = typeNameToComplete.Extent.EndOffset - replacementIndex; completionContext.WordToComplete = typeNameToComplete.FullName; - result = CompletionCompleters.CompleteType(completionContext); + return CompletionCompleters.CompleteType(completionContext); } } if (result == null || result.Count == 0) { result = GetResultForHashtable(completionContext); + // Handles the following scenario: [ipaddress]@{Address=""; } + if (result?.Count > 0) + { + replacementIndex = completionContext.CursorPosition.Offset; + replacementLength = 0; + } } if (result == null || result.Count == 0) @@ -938,59 +1427,56 @@ internal List GetResultHelper(CompletionContext completionCont // Helper method to auto complete hashtable key private static List GetResultForHashtable(CompletionContext completionContext) { - var lastAst = completionContext.RelatedAsts.Last(); - HashtableAst tempHashtableAst = null; - IScriptPosition cursor = completionContext.CursorPosition; - var hashTableAst = lastAst as HashtableAst; - if (hashTableAst != null) + Ast lastRelatedAst = null; + var cursorPosition = completionContext.CursorPosition; + + // Enumeration is used over the LastAst pattern because empty lines following a key-value pair will set LastAst to the value. + // Example: + // @{ + // Key1="Value1" + // + // } + // In this case the last 3 Asts will be StringConstantExpression, CommandExpression, and Pipeline instead of the expected Hashtable + for (int i = completionContext.RelatedAsts.Count - 1; i >= 0; i--) + { + Ast ast = completionContext.RelatedAsts[i]; + if (cursorPosition.Offset >= ast.Extent.StartOffset && cursorPosition.Offset <= ast.Extent.EndOffset) + { + lastRelatedAst = ast; + break; + } + } + + if (lastRelatedAst is HashtableAst hashtableAst) { - // Check if the cursor within the hashtable - if (cursor.Offset < hashTableAst.Extent.EndOffset) + // Cursor is just after the hashtable: @{} + if (completionContext.TokenAtCursor is not null && completionContext.TokenAtCursor.Kind == TokenKind.RCurly) { - tempHashtableAst = hashTableAst; + return null; } - else if (cursor.Offset == hashTableAst.Extent.EndOffset) + + bool cursorIsWithinOrOnSameLineAsKeypair = false; + foreach (var pair in hashtableAst.KeyValuePairs) { - // Exclude the scenario that cursor at the end of hashtable, i.e. after '}' - if (completionContext.TokenAtCursor == null || - completionContext.TokenAtCursor.Kind != TokenKind.RCurly) + if (cursorPosition.Offset >= pair.Item1.Extent.StartOffset + && (cursorPosition.Offset <= pair.Item2.Extent.EndOffset || cursorPosition.LineNumber == pair.Item2.Extent.EndLineNumber)) { - tempHashtableAst = hashTableAst; + cursorIsWithinOrOnSameLineAsKeypair = true; + break; } } - } - else - { - // Handle property completion on a blank line for DynamicKeyword statement - Ast lastChildofHashtableAst; - hashTableAst = Ast.GetAncestorHashtableAst(lastAst, out lastChildofHashtableAst); - // Check if the hashtable within a DynamicKeyword statement - if (hashTableAst != null) + if (cursorIsWithinOrOnSameLineAsKeypair) { - var keywordAst = Ast.GetAncestorAst(hashTableAst); - if (keywordAst != null) + var tokenBeforeOrAtCursor = completionContext.TokenBeforeCursor ?? completionContext.TokenAtCursor; + if (tokenBeforeOrAtCursor.Kind != TokenKind.Semi) { - // Handle only empty line - if (string.IsNullOrWhiteSpace(cursor.Line)) - { - // Check if the cursor outside of last child of hashtable and within the hashtable - if (cursor.Offset > lastChildofHashtableAst.Extent.EndOffset && - cursor.Offset <= hashTableAst.Extent.EndOffset) - { - tempHashtableAst = hashTableAst; - } - } + return null; } } - } - - hashTableAst = tempHashtableAst; - if (hashTableAst != null) - { completionContext.ReplacementIndex = completionContext.CursorPosition.Offset; completionContext.ReplacementLength = 0; - return CompletionCompleters.CompleteHashtableKey(completionContext, hashTableAst); + return CompletionCompleters.CompleteHashtableKey(completionContext, hashtableAst); } return null; @@ -1054,7 +1540,7 @@ private static string GetFirstLineSubString(string stringToComplete, out bool ha hasNewLine = false; if (!string.IsNullOrEmpty(stringToComplete)) { - var index = stringToComplete.IndexOfAny(Utils.Separators.CrLf); + var index = stringToComplete.AsSpan().IndexOfAny('\r', '\n'); if (index >= 0) { stringToComplete = stringToComplete.Substring(0, index); @@ -1195,6 +1681,121 @@ private static bool TryGetTypeConstraintOnVariable( return typeConstraint != null || setConstraint != null; } + private static List CompletePropertyAssignment(MemberExpressionAst memberExpression, CompletionContext context) + { + if (SafeExprEvaluator.TrySafeEval(memberExpression, context.ExecutionContext, out var evalValue)) + { + if (evalValue is not null) + { + Type type = evalValue.GetType(); + if (type.IsEnum) + { + return GetResultForEnum(type, context); + } + + return null; + } + } + + _ = TryGetInferredCompletionsForAssignment(memberExpression, context, out List result); + return result; + } + + private static bool TryGetInferredCompletionsForAssignment(Ast expression, CompletionContext context, out List result) + { + result = null; + IList inferredTypes; + if (expression.Parent is ConvertExpressionAst convertExpression) + { + inferredTypes = new PSTypeName[] { new(convertExpression.Type.TypeName) }; + } + else if (expression is MemberExpressionAst) + { + inferredTypes = AstTypeInference.InferTypeOf(expression); + } + else if (expression is VariableExpressionAst varExpression) + { + PSTypeName typeConstraint = CompletionCompleters.GetLastDeclaredTypeConstraint(varExpression, context.TypeInferenceContext); + if (typeConstraint is null) + { + return false; + } + + inferredTypes = new PSTypeName[] { typeConstraint }; + } + else + { + return false; + } + + if (inferredTypes.Count == 0) + { + return false; + } + + var values = new SortedSet(); + foreach (PSTypeName type in inferredTypes) + { + Type loadedType = type.Type; + if (loadedType is not null) + { + if (loadedType.IsEnum) + { + foreach (string value in Enum.GetNames(loadedType)) + { + _ = values.Add(value); + } + } + } + else if (type is not null && type.TypeDefinitionAst.IsEnum) + { + foreach (MemberAst member in type.TypeDefinitionAst.Members) + { + if (member is PropertyMemberAst property) + { + _ = values.Add(property.Name); + } + } + } + } + + string wordToComplete; + if (string.IsNullOrEmpty(context.WordToComplete)) + { + if (context.TokenAtCursor is not null && context.TokenAtCursor.Kind != TokenKind.Equals) + { + wordToComplete = context.TokenAtCursor.Text + "*"; + } + else + { + wordToComplete = "*"; + } + } + else + { + wordToComplete = context.WordToComplete + "*"; + } + + result = new List(); + var pattern = new WildcardPattern(wordToComplete, WildcardOptions.IgnoreCase); + foreach (string name in values) + { + string quotedName = GetQuotedString(name, context); + if (pattern.IsMatch(quotedName)) + { + result.Add(new CompletionResult(quotedName, name, CompletionResultType.Property, name)); + } + } + + if (result.Count == 0) + { + result = null; + return false; + } + + return true; + } + private static bool TryGetCompletionsForVariableAssignment( CompletionContext completionContext, AssignmentStatementAst assignmentAst, @@ -1226,6 +1827,12 @@ bool TryGetResultForSet(Type typeConstraint, ValidateSetAttribute setConstraint, return false; } + if (assignmentAst.Left is MemberExpressionAst member) + { + completions = CompletePropertyAssignment(member, completionContext); + return completions is not null; + } + completions = null; // Try to get the variable from the assignment, plus any type constraint on it @@ -1255,7 +1862,7 @@ bool TryGetResultForSet(Type typeConstraint, ValidateSetAttribute setConstraint, // If the assignment itself was unconstrained, the variable still might be if (!TryGetTypeConstraintOnVariable(completionContext, variableAst.VariablePath.UserPath, out typeConstraint, out setConstraint)) { - return false; + return TryGetInferredCompletionsForAssignment(variableAst, completionContext, out completions); } // Again try the [ValidateSet()] constraint first @@ -1441,7 +2048,7 @@ private static List GetResultForEnumPropertyValueOfDSCResource Diagnostics.Assert(isCursorInString || (!hasNewLine), "hasNoQuote and hasNewLine cannot be true at the same time"); if (property.ValueMap != null && property.ValueMap.Count > 0) { - IEnumerable orderedValues = property.ValueMap.Keys.OrderBy(x => x).Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); + IEnumerable orderedValues = property.ValueMap.Keys.Order().Where(v => !existingValues.Contains(v, StringComparer.OrdinalIgnoreCase)); var matchedResults = orderedValues.Where(v => wildcardPattern.IsMatch(v)); if (matchedResults == null || !matchedResults.Any()) { @@ -1523,111 +2130,65 @@ private static List GetResultForEnumPropertyValueOfDSCResource return result; } - private List GetResultForString(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength, bool isQuotedString) + private static List GetResultForString(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) { - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) { return null; } - - var tokenAtCursor = completionContext.TokenAtCursor; var lastAst = completionContext.RelatedAsts.Last(); - - List result = null; var expandableString = lastAst as ExpandableStringExpressionAst; var constantString = lastAst as StringConstantExpressionAst; if (constantString == null && expandableString == null) { return null; } string strValue = constantString != null ? constantString.Value : expandableString.Value; - StringConstantType strType = constantString != null ? constantString.StringConstantType : expandableString.StringConstantType; - string subInput = null; - bool shouldContinue; - result = GetResultForEnumPropertyValueOfDSCResource(completionContext, strValue, ref replacementIndex, ref replacementLength, out shouldContinue); - if (!shouldContinue || (result != null && result.Count > 0)) + // Check for switch case completion on $PSBoundParameters.Keys + completionContext.WordToComplete = strValue; + var switchCaseResult = CompleteAgainstSwitchCaseCondition(completionContext); + if (switchCaseResult != null && switchCaseResult.Count > 0) { - return result; + return switchCaseResult; } - if (strType == StringConstantType.DoubleQuoted) + // Check for $PSBoundParameters access patterns (ContainsKey, indexer, Remove) + var psBoundResult = CompleteAgainstPSBoundParametersAccess(completionContext); + if (psBoundResult != null && psBoundResult.Count > 0) { - var match = Regex.Match(strValue, @"(\$[\w\d]+\.[\w\d\*]*)$"); - if (match.Success) - { - subInput = match.Groups[1].Value; - } - else if ((match = Regex.Match(strValue, @"(\[[\w\d\.]+\]::[\w\d\*]*)$")).Success) - { - subInput = match.Groups[1].Value; - } + return psBoundResult; } - // Handle variable/member completion - if (subInput != null) + bool shouldContinue; + List result = GetResultForEnumPropertyValueOfDSCResource(completionContext, strValue, ref replacementIndex, ref replacementLength, out shouldContinue); + if (!shouldContinue || (result != null && result.Count > 0)) { - int stringStartIndex = tokenAtCursor.Extent.StartScriptPosition.Offset; - int cursorIndexInString = _cursorPosition.Offset - stringStartIndex - 1; - if (cursorIndexInString >= strValue.Length) - cursorIndexInString = strValue.Length; + return result; + } - var analysis = new CompletionAnalysis(_ast, _tokens, _cursorPosition, _options); - var subContext = analysis.CreateCompletionContext(completionContext.TypeInferenceContext); + var commandElementAst = lastAst as CommandElementAst; + string wordToComplete = + CompletionCompleters.ConcatenateStringPathArguments(commandElementAst, string.Empty, completionContext); - var subResult = analysis.GetResultHelper(subContext, out int subReplaceIndex, out _, true); + if (wordToComplete != null) + { + completionContext.WordToComplete = wordToComplete; - if (subResult != null && subResult.Count > 0) + // Handle scenarios like this: cd 'c:\windows\win' + if (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst) { - result = new List(); - replacementIndex = stringStartIndex + 1 + (cursorIndexInString - subInput.Length); - replacementLength = subInput.Length; - ReadOnlySpan prefix = subInput.AsSpan(0, subReplaceIndex); - - foreach (CompletionResult entry in subResult) - { - string completionText = string.Concat(prefix, entry.CompletionText.AsSpan()); - if (entry.ResultType == CompletionResultType.Property) - { - completionText = TokenKind.DollarParen.Text() + completionText + TokenKind.RParen.Text(); - } - else if (entry.ResultType == CompletionResultType.Method) - { - completionText = TokenKind.DollarParen.Text() + completionText; - } - - completionText += "\""; - result.Add(new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip)); - } + result = CompletionCompleters.CompleteCommandArgument(completionContext); + replacementIndex = completionContext.ReplacementIndex; + replacementLength = completionContext.ReplacementLength; } - } - else - { - var commandElementAst = lastAst as CommandElementAst; - string wordToComplete = - CompletionCompleters.ConcatenateStringPathArguments(commandElementAst, string.Empty, completionContext); - - if (wordToComplete != null) + // Handle scenarios like this: "c:\wind". Treat the StringLiteral/StringExpandable as path/command + else { - completionContext.WordToComplete = wordToComplete; + // Handle path/commandname completion for quoted string + result = new List(CompletionCompleters.CompleteFilename(completionContext)); - // Handle scenarios like this: cd 'c:\windows\win' - if (lastAst.Parent is CommandAst || lastAst.Parent is CommandParameterAst) + // Try command name completion only if the text contains '-' + if (wordToComplete.Contains('-')) { - result = CompletionCompleters.CompleteCommandArgument(completionContext); - replacementIndex = completionContext.ReplacementIndex; - replacementLength = completionContext.ReplacementLength; - } - // Handle scenarios like this: "c:\wind". Treat the StringLiteral/StringExpandable as path/command - else - { - // Handle path/commandname completion for quoted string - result = new List(CompletionCompleters.CompleteFilename(completionContext)); - - // Try command name completion only if the text contains '-' - if (wordToComplete.Contains('-')) + var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); + if (commandNameResult != null && commandNameResult.Count > 0) { - var commandNameResult = CompletionCompleters.CompleteCommand(completionContext); - if (commandNameResult != null && commandNameResult.Count > 0) - { - result.AddRange(commandNameResult); - } + result.AddRange(commandNameResult); } } } @@ -1721,15 +2282,19 @@ private static List GetResultForIdentifierInConfiguration( foreach (var keyword in matchedResults) { - string usageString = Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache.NewApiIsUsed - ? Microsoft.PowerShell.DesiredStateConfiguration.Internal.CrossPlatform.DscClassCache.GetDSCResourceUsageString(keyword) - : Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.GetDSCResourceUsageString(keyword); - - if (results == null) + string usageString = string.Empty; + ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem(); + if (dscSubsystem != null) + { + usageString = dscSubsystem.GetDSCResourceUsageString(keyword); + } + else { - results = new List(); + usageString = Microsoft.PowerShell.DesiredStateConfiguration.Internal.DscClassCache.GetDSCResourceUsageString(keyword); } + results ??= new List(); + results.Add(new CompletionResult( keyword.Keyword, keyword.Keyword, @@ -1741,15 +2306,34 @@ private static List GetResultForIdentifierInConfiguration( return results; } - private List GetResultForIdentifier(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength, bool isQuotedString) + private static List GetResultForIdentifier(CompletionContext completionContext, ref int replacementIndex, ref int replacementLength) { + List result = null; var tokenAtCursor = completionContext.TokenAtCursor; var lastAst = completionContext.RelatedAsts.Last(); - List result = null; var tokenAtCursorText = tokenAtCursor.Text; completionContext.WordToComplete = tokenAtCursorText; + // Check for switch case completion on $PSBoundParameters.Keys + var switchCaseResult = CompleteAgainstSwitchCaseCondition(completionContext); + if (switchCaseResult != null && switchCaseResult.Count > 0) + { + return switchCaseResult; + } + + // Check for $PSBoundParameters access patterns (ContainsKey, indexer, Remove) + var psBoundResult = CompleteAgainstPSBoundParametersAccess(completionContext); + if (psBoundResult != null && psBoundResult.Count > 0) + { + return psBoundResult; + } + + if (lastAst.Parent is BreakStatementAst || lastAst.Parent is ContinueStatementAst) + { + return CompleteLoopLabel(completionContext); + } + var strConst = lastAst as StringConstantExpressionAst; if (strConst != null) { @@ -1769,7 +2353,12 @@ private List GetResultForIdentifier(CompletionContext completi switch (usingState.UsingStatementKind) { case UsingStatementKind.Assembly: - break; + HashSet assemblyExtensions = new(StringComparer.OrdinalIgnoreCase) + { + StringLiterals.PowerShellILAssemblyExtension + }; + return CompletionCompleters.CompleteFilename(completionContext, containerOnly: false, assemblyExtensions).ToList(); + case UsingStatementKind.Command: break; case UsingStatementKind.Module: @@ -1805,76 +2394,101 @@ private List GetResultForIdentifier(CompletionContext completi } } - result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); - if (result != null) return result; + if (completionContext.TokenAtCursor.TokenFlags == TokenFlags.MemberName) + { + if (lastAst is NamedAttributeArgumentAst || lastAst.Parent is NamedAttributeArgumentAst) + { + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + } + else if (lastAst is VariableExpressionAst && lastAst.Parent is ParameterAst paramAst && paramAst.Attributes.Count > 0) + { + foreach (AttributeBaseAst attribute in paramAst.Attributes) + { + if (IsCursorWithinOrJustAfterExtent(completionContext.CursorPosition, attribute.Extent)) + { + result = GetResultForAttributeArgument(completionContext, ref replacementIndex, ref replacementLength); + break; + } + } + } + + if (result is not null) + { + return result; + } + } if ((tokenAtCursor.TokenFlags & TokenFlags.CommandName) != 0) { // Handle completion for a path with variable, such as: $PSHOME\ty if (completionContext.RelatedAsts.Count > 0 && completionContext.RelatedAsts[0] is ScriptBlockAst) { - Ast cursorAst = null; - var cursorPosition = (InternalScriptPosition)_cursorPosition; - int offsetBeforeCmdName = cursorPosition.Offset - tokenAtCursorText.Length; - if (offsetBeforeCmdName >= 0) - { - var cursorBeforeCmdName = cursorPosition.CloneWithNewOffset(offsetBeforeCmdName); - var scriptBlockAst = (ScriptBlockAst)completionContext.RelatedAsts[0]; - cursorAst = GetLastAstAtCursor(scriptBlockAst, cursorBeforeCmdName); - } + Ast cursorAst = completionContext.RelatedAsts[0].FindAll( + ast => ast.Extent.EndOffset <= tokenAtCursor.Extent.StartOffset + && ast.Extent is not EmptyScriptExtent, + searchNestedScriptBlocks: true).LastOrDefault(); - if (cursorAst != null && - cursorAst.Extent.EndLineNumber == tokenAtCursor.Extent.StartLineNumber && - cursorAst.Extent.EndColumnNumber == tokenAtCursor.Extent.StartColumnNumber) + if (cursorAst is not null) { - if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) + if (cursorAst.Extent.EndOffset == tokenAtCursor.Extent.StartOffset) { - string wordToComplete = - CompletionCompleters.ConcatenateStringPathArguments(cursorAst as CommandElementAst, tokenAtCursorText, completionContext); - if (wordToComplete != null) + if (tokenAtCursorText.AsSpan().IndexOfAny('\\', '/') == 0) { - completionContext.WordToComplete = wordToComplete; - result = new List(CompletionCompleters.CompleteFilename(completionContext)); - if (result.Count > 0) + string wordToComplete = + CompletionCompleters.ConcatenateStringPathArguments(cursorAst as CommandElementAst, tokenAtCursorText, completionContext); + if (wordToComplete != null) + { + completionContext.WordToComplete = wordToComplete; + result = new List(CompletionCompleters.CompleteFilename(completionContext)); + if (result.Count > 0) + { + replacementIndex = cursorAst.Extent.StartScriptPosition.Offset; + replacementLength += cursorAst.Extent.Text.Length; + } + + return result; + } + else { + var variableAst = cursorAst as VariableExpressionAst; + string fullPath = variableAst != null + ? CompletionCompleters.CombineVariableWithPartialPath( + variableAst: variableAst, + extraText: tokenAtCursorText, + executionContext: completionContext.ExecutionContext) + : null; + + if (fullPath == null) { return result; } + + // Continue trying the filename/commandname completion for scenarios like this: $aa\d + completionContext.WordToComplete = fullPath; replacementIndex = cursorAst.Extent.StartScriptPosition.Offset; replacementLength += cursorAst.Extent.Text.Length; - } - return result; + completionContext.ReplacementIndex = replacementIndex; + completionContext.ReplacementLength = replacementLength; + } } - else + // Continue trying the filename/commandname completion for scenarios like this: $aa[get- + else if (cursorAst is not ErrorExpressionAst || cursorAst.Parent is not IndexExpressionAst) { - var variableAst = cursorAst as VariableExpressionAst; - string fullPath = variableAst != null - ? CompletionCompleters.CombineVariableWithPartialPath( - variableAst: variableAst, - extraText: tokenAtCursorText, - executionContext: completionContext.ExecutionContext) - : null; - - if (fullPath == null) { return result; } - - // Continue trying the filename/commandname completion for scenarios like this: $aa\d - completionContext.WordToComplete = fullPath; - replacementIndex = cursorAst.Extent.StartScriptPosition.Offset; - replacementLength += cursorAst.Extent.Text.Length; - - completionContext.ReplacementIndex = replacementIndex; - completionContext.ReplacementLength = replacementLength; + return result; } } - // Continue trying the filename/commandname completion for scenarios like this: $aa[get- - else if (cursorAst is not ErrorExpressionAst || cursorAst.Parent is not IndexExpressionAst) + + if (cursorAst.Parent is IndexExpressionAst indexExpression && indexExpression.Index is ErrorExpressionAst) { - return result; + if (completionContext.WordToComplete.EndsWith(']')) + { + completionContext.WordToComplete = completionContext.WordToComplete.Remove(completionContext.WordToComplete.Length - 1); + } + + // Handles index expression with unquoted word like: $PSVersionTable[psver] + return CompletionCompleters.CompleteIndexExpression(completionContext, indexExpression.Target); } } } - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) { return result; } - // Handle the StringExpandableToken; var strToken = tokenAtCursor as StringExpandableToken; if (strToken != null && strToken.NestedTokens != null && strConst != null) @@ -1944,8 +2558,6 @@ private List GetResultForIdentifier(CompletionContext completi // When it's the content of a quoted string, we only handle variable/member completion if (isSingleDash) { - if (isQuotedString) { return result; } - var res = CompletionCompleters.CompleteCommandParameter(completionContext); if (res.Count != 0) { @@ -1957,8 +2569,24 @@ private List GetResultForIdentifier(CompletionContext completi } TokenKind memberOperator = TokenKind.Unknown; - bool isMemberCompletion = (lastAst.Parent is MemberExpressionAst); - bool isStatic = isMemberCompletion && ((MemberExpressionAst)lastAst.Parent).Static; + bool isMemberCompletion = lastAst.Parent is MemberExpressionAst; + bool isStatic = false; + if (isMemberCompletion) + { + var currentExpression = (MemberExpressionAst)lastAst.Parent; + // Handles following scenario with an incomplete member access token at the end of the statement: + // [System.IO.FileInfo]::new().Directory.BaseName.Length. + // Traverses up the expressions until it finds one under at the cursor + while (currentExpression.Extent.EndOffset >= completionContext.CursorPosition.Offset + && currentExpression.Expression is MemberExpressionAst memberExpression + && memberExpression.Member.Extent.EndOffset >= completionContext.CursorPosition.Offset) + { + currentExpression = memberExpression; + } + + isStatic = currentExpression.Static; + } + bool isWildcard = false; if (!isMemberCompletion) @@ -2009,7 +2637,7 @@ private List GetResultForIdentifier(CompletionContext completi if (isMemberCompletion) { - result = CompletionCompleters.CompleteMember(completionContext, @static: (isStatic || memberOperator == TokenKind.ColonColon)); + result = CompletionCompleters.CompleteMember(completionContext, @static: (isStatic || memberOperator == TokenKind.ColonColon), ref replacementLength); // If the last token was just a '.', we tried to complete members. That may // have failed because it wasn't really an attempt to complete a member, in @@ -2035,9 +2663,6 @@ private List GetResultForIdentifier(CompletionContext completi } } - // When it's the content of a quoted string, we only handle variable/member completion - if (isQuotedString) { return result; } - bool needFileCompletion = false; if (lastAst.Parent is FileRedirectionAst || CompleteAgainstSwitchFile(lastAst, completionContext.TokenBeforeCursor)) { @@ -2049,7 +2674,7 @@ private List GetResultForIdentifier(CompletionContext completi completionContext.WordToComplete = wordToComplete; } } - else if (tokenAtCursorText.IndexOfAny(Utils.Separators.Directory) == 0) + else if (tokenAtCursorText.AsSpan().IndexOfAny('\\', '/') == 0) { var command = lastAst.Parent as CommandBaseAst; if (command != null && command.Redirections.Count > 0) @@ -2093,6 +2718,7 @@ private List GetResultForIdentifier(CompletionContext completi result = CompletionCompleters.CompleteCommandArgument(completionContext); replacementIndex = completionContext.ReplacementIndex; replacementLength = completionContext.ReplacementLength; + return result; } @@ -2101,33 +2727,47 @@ private static List GetResultForAttributeArgument(CompletionCo // Attribute member arguments Type attributeType = null; string argName = string.Empty; - Ast argAst = completionContext.RelatedAsts.Find(ast => ast is NamedAttributeArgumentAst); - NamedAttributeArgumentAst namedArgAst = argAst as NamedAttributeArgumentAst; - if (argAst != null && namedArgAst != null) + Ast argAst = completionContext.RelatedAsts.Find(static ast => ast is NamedAttributeArgumentAst); + AttributeAst attAst; + if (argAst is NamedAttributeArgumentAst namedArgAst) { - attributeType = ((AttributeAst)namedArgAst.Parent).TypeName.GetReflectionAttributeType(); + attAst = (AttributeAst)namedArgAst.Parent; + attributeType = attAst.TypeName.GetReflectionAttributeType(); argName = namedArgAst.ArgumentName; replacementIndex = namedArgAst.Extent.StartOffset; replacementLength = argName.Length; } else { - Ast astAtt = completionContext.RelatedAsts.Find(ast => ast is AttributeAst); - AttributeAst attAst = astAtt as AttributeAst; - if (astAtt != null && attAst != null) + Ast astAtt = completionContext.RelatedAsts.Find(static ast => ast is AttributeAst); + attAst = astAtt as AttributeAst; + if (attAst is not null) { attributeType = attAst.TypeName.GetReflectionAttributeType(); } } - if (attributeType != null) + if (attributeType is not null) { + int cursorPosition = completionContext.CursorPosition.Offset; + var existingArguments = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var namedArgument in attAst.NamedArguments) + { + if (cursorPosition < namedArgument.Extent.StartOffset || cursorPosition > namedArgument.Extent.EndOffset) + { + existingArguments.Add(namedArgument.ArgumentName); + } + } + PropertyInfo[] propertyInfos = attributeType.GetProperties(BindingFlags.Public | BindingFlags.Instance); List result = new List(); foreach (PropertyInfo property in propertyInfos) { - // Ignore getter-only properties, including 'TypeId' (all attributes inherit it). - if (!property.CanWrite) { continue; } + // Ignore getter-only properties and properties that have already been set. + if (!property.CanWrite || existingArguments.Contains(property.Name)) + { + continue; + } if (property.Name.StartsWith(argName, StringComparison.OrdinalIgnoreCase)) { @@ -2191,5 +2831,116 @@ private static List CompleteFileNameAsCommand(CompletionContex return result; } + + /// + /// Complete loop labels after labeled control flow statements such as Break and Continue. + /// + private static List CompleteLoopLabel(CompletionContext completionContext) + { + var result = new List(); + foreach (Ast ast in completionContext.RelatedAsts) + { + if (ast is LabeledStatementAst labeledStatement + && labeledStatement.Label is not null + && (completionContext.WordToComplete is null || labeledStatement.Label.StartsWith(completionContext.WordToComplete, StringComparison.OrdinalIgnoreCase))) + { + result.Add(new CompletionResult(labeledStatement.Label, labeledStatement.Label, CompletionResultType.Text, labeledStatement.Extent.Text)); + } + else if (ast is ErrorStatementAst errorStatement) + { + // Handles incomplete do/switch loops (other labeled statements do not need this special treatment) + // The regex looks for the loopLabel of errorstatements that look like do/switch loops + // For example in ":Label do " it will find "Label". + var labelMatch = Regex.Match(errorStatement.Extent.Text, @"(?<=^:)\w+(?=\s+(do|switch)\b(?!-))", RegexOptions.IgnoreCase); + if (labelMatch.Success) + { + result.Add(new CompletionResult(labelMatch.Value, labelMatch.Value, CompletionResultType.Text, errorStatement.Extent.Text)); + } + } + } + + if (result.Count == 0) + { + return null; + } + + return result; + } + + private static List CompleteUsingKeywords(int cursorOffset, Token[] tokens, ref int replacementIndex, ref int replacementLength) + { + var result = new List(); + Token tokenBeforeCursor = null; + Token tokenAtCursor = null; + + for (int i = tokens.Length - 1; i >= 0; i--) + { + if (tokens[i].Extent.EndOffset < cursorOffset && tokens[i].Kind != TokenKind.LineContinuation) + { + tokenBeforeCursor = tokens[i]; + break; + } + else if (tokens[i].Extent.StartOffset <= cursorOffset && tokens[i].Extent.EndOffset >= cursorOffset && tokens[i].Kind != TokenKind.LineContinuation) + { + tokenAtCursor = tokens[i]; + } + } + + if (tokenBeforeCursor is not null && tokenBeforeCursor.Kind == TokenKind.Using) + { + string wordToComplete = null; + if (tokenAtCursor is not null) + { + replacementIndex = tokenAtCursor.Extent.StartOffset; + replacementLength = tokenAtCursor.Extent.Text.Length; + wordToComplete = tokenAtCursor.Text; + } + else + { + replacementIndex = cursorOffset; + replacementLength = 0; + } + + foreach (var keyword in s_usingKeywords) + { + if (string.IsNullOrEmpty(wordToComplete) || keyword.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult(keyword, keyword, CompletionResultType.Keyword, GetUsingKeywordToolTip(keyword))); + } + } + } + + if (result.Count > 0) + { + return result; + } + + return null; + } + + private static string GetUsingKeywordToolTip(string keyword) + { + switch (keyword) + { + case "assembly": + return TabCompletionStrings.AssemblyKeywordDescription; + case "module": + return TabCompletionStrings.ModuleKeywordDescription; + case "namespace": + return TabCompletionStrings.NamespaceKeywordDescription; + case "type": + return TabCompletionStrings.TypeKeywordDescription; + default: + return null; + } + } + + private static readonly string[] s_usingKeywords = new string[] + { + "assembly", + "module", + "namespace", + "type" + }; } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs index 853b79e7843..80cead788d3 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -12,6 +13,7 @@ using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using System.Management.Automation.Provider; using System.Management.Automation.Runspaces; using System.Reflection; using System.Runtime.InteropServices; @@ -24,6 +26,7 @@ using Microsoft.PowerShell; using Microsoft.PowerShell.Cim; using Microsoft.PowerShell.Commands; +using Microsoft.PowerShell.Commands.Internal.Format; namespace System.Management.Automation { @@ -61,7 +64,6 @@ public static IEnumerable CompleteCommand(string commandName) /// /// /// - [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public static IEnumerable CompleteCommand(string commandName, string moduleName, CommandTypes commandTypes = CommandTypes.All) { var runspace = Runspace.DefaultRunspace; @@ -86,7 +88,7 @@ private static List CompleteCommand(CompletionContext context, var addAmpersandIfNecessary = IsAmpersandNeeded(context, false); string commandName = context.WordToComplete; - string quote = HandleDoubleAndSingleQuote(ref commandName); + string quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref commandName); List commandResults = null; @@ -194,7 +196,7 @@ List ExecuteGetCommandCommand(bool useModulePrefix) if (commandInfos != null && commandInfos.Count > 1) { // OrderBy is using stable sorting - var sortedCommandInfos = commandInfos.OrderBy(a => a, new CommandNameComparer()); + var sortedCommandInfos = commandInfos.Order(new CommandNameComparer()); completionResults = MakeCommandsUnique(sortedCommandInfos, useModulePrefix, addAmpersandIfNecessary, quote); } else @@ -231,7 +233,7 @@ internal static CompletionResult GetCommandNameCompletionResult(string name, obj syntax = string.IsNullOrEmpty(syntax) ? name : syntax; bool needAmpersand; - if (CompletionRequiresQuotes(name, false)) + if (CompletionHelpers.CompletionRequiresQuotes(name)) { needAmpersand = quote == string.Empty && addAmpersandIfNecessary; string quoteInUse = quote == string.Empty ? "'" : quote; @@ -326,53 +328,72 @@ internal static List MakeCommandsUnique(IEnumerable } } - List endResults = null; foreach (var keyValuePair in commandTable) { - var commandList = keyValuePair.Value as List; - if (commandList != null) + if (keyValuePair.Value is List commandList) { - if (endResults == null) + var modulesWithCommand = new HashSet(StringComparer.OrdinalIgnoreCase); + var importedModules = new HashSet(StringComparer.OrdinalIgnoreCase); + var commandInfoList = new List(commandList.Count); + for (int i = 0; i < commandList.Count; i++) { - endResults = new List(); - } + if (commandList[i] is not CommandInfo commandInfo) + { + continue; + } - // The first command might be an un-prefixed commandInfo that we get by importing a module with the -Prefix parameter, - // in that case, we should add the module name qualification because if the module is not in the module path, calling - // 'Get-Foo' directly doesn't work - string completionName = keyValuePair.Key; - if (!includeModulePrefix) - { - var commandInfo = commandList[0] as CommandInfo; - if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) + commandInfoList.Add(commandInfo); + if (commandInfo.CommandType == CommandTypes.Application) { - Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); - if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) - { - completionName = commandInfo.ModuleName + "\\" + completionName; - } + continue; + } + + modulesWithCommand.Add(commandInfo.ModuleName); + if ((commandInfo.CommandType == CommandTypes.Cmdlet && commandInfo.CommandMetadata.CommandType is not null) + || (commandInfo.CommandType is CommandTypes.Function or CommandTypes.Filter && commandInfo.Definition != string.Empty) + || (commandInfo.CommandType == CommandTypes.Alias && commandInfo.Definition is not null)) + { + // Checks if the command or source module has been imported. + _ = importedModules.Add(commandInfo.ModuleName); } } - results.Add(GetCommandNameCompletionResult(completionName, commandList[0], addAmpersandIfNecessary, quote)); + if (commandInfoList.Count == 0) + { + continue; + } - // For the other commands that are hidden, we need to disambiguate, - // but put these at the end as it's less likely any of the hidden - // commands are desired. If we can't add anything to disambiguate, - // then we'll skip adding a completion result. - for (int index = 1; index < commandList.Count; index++) + int moduleCount = modulesWithCommand.Count; + modulesWithCommand.Clear(); + int index; + if (commandInfoList[0].CommandType == CommandTypes.Application + || importedModules.Count == 1 + || moduleCount < 2) { - var commandInfo = commandList[index] as CommandInfo; - Diagnostics.Assert(commandInfo != null, "Elements should always be CommandInfo"); + // We can use the short name for this command because there's no ambiguity about which command it resolves to. + // If the first element is an application then we know there's no conflicting commands/aliases (because of the command precedence). + // If there's just 1 module imported then the short name refers to that module (and it will be the first element in the list) + // If there's less than 2 unique modules exporting that command then we can use the short name because it can only refer to that module. + index = 1; + results.Add(GetCommandNameCompletionResult(keyValuePair.Key, commandInfoList[0], addAmpersandIfNecessary, quote)); + modulesWithCommand.Add(commandInfoList[0].ModuleName); + } + else + { + index = 0; + } + for (; index < commandInfoList.Count; index++) + { + CommandInfo commandInfo = commandInfoList[index]; if (commandInfo.CommandType == CommandTypes.Application) { - endResults.Add(GetCommandNameCompletionResult(commandInfo.Definition, commandInfo, addAmpersandIfNecessary, quote)); + results.Add(GetCommandNameCompletionResult(commandInfo.Definition, commandInfo, addAmpersandIfNecessary, quote)); } - else if (!string.IsNullOrEmpty(commandInfo.ModuleName)) + else if (!string.IsNullOrEmpty(commandInfo.ModuleName) && modulesWithCommand.Add(commandInfo.ModuleName)) { var name = commandInfo.ModuleName + "\\" + commandInfo.Name; - endResults.Add(GetCommandNameCompletionResult(name, commandInfo, addAmpersandIfNecessary, quote)); + results.Add(GetCommandNameCompletionResult(name, commandInfo, addAmpersandIfNecessary, quote)); } } } @@ -399,15 +420,10 @@ internal static List MakeCommandsUnique(IEnumerable } } - if (endResults != null && endResults.Count > 0) - { - results.AddRange(endResults); - } - return results; } - private class FindFunctionsVisitor : AstVisitor + private sealed class FindFunctionsVisitor : AstVisitor { internal readonly List FunctionDefinitions = new List(); @@ -424,16 +440,34 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst fun internal static List CompleteModuleName(CompletionContext context, bool loadedModulesOnly, bool skipEditionCheck = false) { - var moduleName = context.WordToComplete ?? string.Empty; + var wordToComplete = context.WordToComplete ?? string.Empty; var result = new List(); - var quote = HandleDoubleAndSingleQuote(ref moduleName); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); + + // Indicates if we should search for modules where the last part of the name matches the input text + // eg: Host finds Microsoft.PowerShell.Host + // If the user has entered a manual wildcard, or a module name that contains a "." we assume they only want results that matches the input exactly. + bool shortNameSearch = wordToComplete.Length > 0 && !WildcardPattern.ContainsWildcardCharacters(wordToComplete) && !wordToComplete.Contains('.'); + + if (!wordToComplete.EndsWith('*')) + { + wordToComplete += "*"; + } - if (!moduleName.EndsWith('*')) + string[] moduleNames; + WildcardPattern shortNamePattern; + if (shortNameSearch) + { + moduleNames = new string[] { wordToComplete, "*." + wordToComplete }; + shortNamePattern = new WildcardPattern(wordToComplete, WildcardOptions.IgnoreCase); + } + else { - moduleName += "*"; + moduleNames = new string[] { wordToComplete }; + shortNamePattern = null; } - var powershell = context.Helper.AddCommandWithPreferenceSetting("Get-Module", typeof(GetModuleCommand)).AddParameter("Name", moduleName); + var powershell = context.Helper.AddCommandWithPreferenceSetting("Get-Module", typeof(GetModuleCommand)).AddParameter("Name", moduleNames); if (!loadedModulesOnly) { powershell.AddParameter("ListAvailable", true); @@ -445,32 +479,58 @@ internal static List CompleteModuleName(CompletionContext cont } } - Exception exceptionThrown; - var psObjects = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); + Collection psObjects = context.Helper.ExecuteCurrentPowerShell(out _); if (psObjects != null) { - foreach (dynamic moduleInfo in psObjects) + // When PowerShell is used interactively, completion is usually triggered by PSReadLine, with PSReadLine's SessionState + // as the engine session state. In that case, results from the module search may contain a nested module of PSReadLine, + // which should be filtered out below. + // When the completion is triggered from global session state, such as when running 'TabExpansion2' from command line, + // the module associated with engine session state will be null. + // + // Note that, it's intentional to not hard code the name 'PSReadLine' in the change, so that in case the tab completion + // is triggered from within a different module, its nested modules can also be filtered out. + HashSet nestedModulesToFilterOut = null; + PSModuleInfo currentModule = context.ExecutionContext.EngineSessionState.Module; + if (loadedModulesOnly && currentModule?.NestedModules.Count > 0) { - var completionText = moduleInfo.Name.ToString(); - var listItemText = completionText; - var toolTip = "Description: " + moduleInfo.Description.ToString() + "\r\nModuleType: " - + moduleInfo.ModuleType.ToString() + "\r\nPath: " - + moduleInfo.Path.ToString(); + nestedModulesToFilterOut = new(currentModule.NestedModules); + } + + var completedModules = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (PSObject item in psObjects) + { + var moduleInfo = (PSModuleInfo)item.BaseObject; + var completionText = moduleInfo.Name; + if (!completedModules.Add(completionText)) + { + continue; + } - if (CompletionRequiresQuotes(completionText, false)) + if (shortNameSearch + && completionText.Contains('.') + && !shortNamePattern.IsMatch(completionText.Substring(completionText.LastIndexOf('.') + 1)) + && !shortNamePattern.IsMatch(completionText)) { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; + // This check is to make sure we don't return a module whose name only matches the user specified word in the middle. + // For example, when user completes with 'gmo power', we should not return 'Microsoft.PowerShell.Utility'. + continue; } - else + + if (nestedModulesToFilterOut is not null + && nestedModulesToFilterOut.Contains(moduleInfo)) { - completionText = quote + completionText + quote; + continue; } - result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, toolTip)); + var toolTip = "Description: " + moduleInfo.Description + "\r\nModuleType: " + + moduleInfo.ModuleType.ToString() + "\r\nPath: " + + moduleInfo.Path; + + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); + + result.Add(new CompletionResult(completionText, listItemText: moduleInfo.Name, CompletionResultType.ParameterValue, toolTip)); } } @@ -494,8 +554,7 @@ internal static List CompleteCommandParameter(CompletionContex DynamicKeywordStatementAst keywordAst = null; for (int i = context.RelatedAsts.Count - 1; i >= 0; i--) { - if (keywordAst == null) - keywordAst = context.RelatedAsts[i] as DynamicKeywordStatementAst; + keywordAst ??= context.RelatedAsts[i] as DynamicKeywordStatementAst; parameterAst = (context.RelatedAsts[i] as CommandParameterAst); if (parameterAst != null) break; } @@ -513,7 +572,7 @@ internal static List CompleteCommandParameter(CompletionContex var lastAst = context.RelatedAsts.Last(); var wordToMatch = string.Concat(context.WordToComplete.AsSpan(1), "*"); var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase); - var parameterNames = keywordAst.CommandElements.Where(ast => ast is CommandParameterAst).Select(ast => (ast as CommandParameterAst).ParameterName); + var parameterNames = keywordAst.CommandElements.Where(static ast => ast is CommandParameterAst).Select(static ast => (ast as CommandParameterAst).ParameterName); foreach (var parameterName in s_parameterNamesOfImportDSCResource) { if (pattern.IsMatch(parameterName) && !parameterNames.Contains(parameterName, StringComparer.OrdinalIgnoreCase)) @@ -532,6 +591,7 @@ internal static List CompleteCommandParameter(CompletionContex return result; } + bool bindPositionalParameters = true; if (parameterAst != null) { // Parent must be a command @@ -542,7 +602,7 @@ internal static List CompleteCommandParameter(CompletionContex else { // No CommandParameterAst is found. It could be a StringConstantExpressionAst "-" - if (!(context.RelatedAsts[context.RelatedAsts.Count - 1] is StringConstantExpressionAst dashAst)) + if (context.RelatedAsts[context.RelatedAsts.Count - 1] is not StringConstantExpressionAst dashAst) return result; if (!dashAst.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) return result; @@ -550,10 +610,24 @@ internal static List CompleteCommandParameter(CompletionContex // Parent must be a command commandAst = (CommandAst)dashAst.Parent; partialName = string.Empty; + + // If the user tries to tab complete a new parameter in front of a positional argument like: dir - C:\ + // the user may want to add the parameter name so we don't want to bind positional arguments + if (commandAst is not null) + { + foreach (var element in commandAst.CommandElements) + { + if (element.Extent.StartOffset > context.TokenAtCursor.Extent.StartOffset) + { + bindPositionalParameters = element is CommandParameterAst; + break; + } + } + } } PseudoBindingInfo pseudoBinding = new PseudoParameterBinder() - .DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion); + .DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion, bindPositionalParameters); // The command cannot be found or it's not a cmdlet, not a script cmdlet, not a function. // Try completing as if it the parameter is a command argument for native command completion. if (pseudoBinding == null) @@ -595,6 +669,11 @@ private static List GetParameterCompletionResults(string param { Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "The pseudo binding should succeed"); List result = new List(); + Assembly commandAssembly = null; + if (bindingInfo.CommandInfo is CmdletInfo cmdletInfo) + { + commandAssembly = cmdletInfo.CommandMetadata.CommandType.Assembly; + } if (parameterName == string.Empty) { @@ -602,7 +681,8 @@ private static List GetParameterCompletionResults(string param parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.UnboundParameters, - withColon); + withColon, + commandAssembly); return result; } @@ -624,7 +704,8 @@ private static List GetParameterCompletionResults(string param parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.UnboundParameters, - withColon); + withColon, + commandAssembly); } return result; @@ -639,7 +720,8 @@ private static List GetParameterCompletionResults(string param parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.BoundParameters.Values, - withColon); + withColon, + commandAssembly); } return result; @@ -695,29 +777,101 @@ private static List GetParameterCompletionResults(string param break; } - Diagnostics.Assert(matchedParameterName != null, "we should find matchedParameterName from the BoundArguments"); + if (matchedParameterName is null) + { + // The pseudo binder has skipped a parameter + // This will happen when completing parameters for commands with dynamic parameters. + result = GetParameterCompletionResults( + parameterName, + bindingInfo.ValidParameterSetsFlags, + bindingInfo.UnboundParameters, + withColon, + commandAssembly); + return result; + } + MergedCompiledCommandParameter param = bindingInfo.BoundParameters[matchedParameterName]; WildcardPattern pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase); string parameterType = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] "; + + string helpMessage = string.Empty; + if (param.Parameter.CompiledAttributes is not null) + { + foreach (Attribute attr in param.Parameter.CompiledAttributes) + { + if (attr is ParameterAttribute pattr && TryGetParameterHelpMessage(pattr, commandAssembly, out string attrHelpMessage)) + { + helpMessage = $" - {attrHelpMessage}"; + break; + } + } + } + string colonSuffix = withColon ? ":" : string.Empty; if (pattern.IsMatch(matchedParameterName)) { - string completionText = "-" + matchedParameterName + colonSuffix; - string tooltip = parameterType + matchedParameterName; + string completionText = $"-{matchedParameterName}{colonSuffix}"; + string tooltip = $"{parameterType}{matchedParameterName}{helpMessage}"; result.Add(new CompletionResult(completionText, matchedParameterName, CompletionResultType.ParameterName, tooltip)); } - - // Process alias when there is partial input - result.AddRange(from alias in param.Parameter.Aliases - where pattern.IsMatch(alias) - select - new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName, - parameterType + alias)); + else + { + // Process alias when there is partial input + foreach (var alias in param.Parameter.Aliases) + { + if (pattern.IsMatch(alias)) + { + result.Add(new CompletionResult( + $"-{alias}{colonSuffix}", + alias, + CompletionResultType.ParameterName, + $"{parameterType}{alias}{helpMessage}")); + } + } + } return result; } +#nullable enable + /// + /// Try and get the help message text for the parameter attribute. + /// + /// The attribute to check for the help message. + /// The assembly to lookup resources messages, this should be the assembly the cmdlet is defined in. + /// The help message if it was found otherwise null. + /// True if the help message was set or false if not.> + private static bool TryGetParameterHelpMessage( + ParameterAttribute attr, + Assembly? assembly, + [NotNullWhen(true)] out string? message) + { + message = null; + + if (attr.HelpMessage is not null) + { + message = attr.HelpMessage; + return true; + } + + if (assembly is null || attr.HelpMessageBaseName is null || attr.HelpMessageResourceId is null) + { + return false; + } + + try + { + message = ResourceManagerCache.GetResourceString(assembly, attr.HelpMessageBaseName, attr.HelpMessageResourceId); + return message is not null; + } + catch (Exception) + { + return false; + } + } +#nullable disable + /// /// Get the parameter completion results by using the given valid parameter sets and available parameters. /// @@ -725,12 +879,14 @@ where pattern.IsMatch(alias) /// /// /// + /// Optional assembly used to lookup parameter help messages. /// private static List GetParameterCompletionResults( string parameterName, uint validParameterSetFlags, IEnumerable parameters, - bool withColon) + bool withColon, + Assembly commandAssembly = null) { var result = new List(); var commonParamResult = new List(); @@ -746,6 +902,7 @@ private static List GetParameterCompletionResults( string name = param.Parameter.Name; string type = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] "; + string helpMessage = null; bool isCommonParameter = Cmdlet.CommonParameters.Contains(name, StringComparer.OrdinalIgnoreCase); List listInUse = isCommonParameter ? commonParamResult : result; @@ -761,33 +918,45 @@ private static List GetParameterCompletionResults( { foreach (var attr in compiledAttributes) { - var pattr = attr as ParameterAttribute; - if (pattr != null && pattr.DontShow) + if (attr is ParameterAttribute pattr) { - showToUser = false; - addCommonParameters = false; - break; + if (pattr.DontShow) + { + showToUser = false; + addCommonParameters = false; + break; + } + + if (helpMessage is null && TryGetParameterHelpMessage(pattr, commandAssembly, out string attrHelpMessage)) + { + helpMessage = $" - {attrHelpMessage}"; + } } } } if (showToUser) { - string completionText = "-" + name + colonSuffix; - string tooltip = type + name; + string completionText = $"-{name}{colonSuffix}"; + string tooltip = $"{type}{name}{helpMessage}"; listInUse.Add(new CompletionResult(completionText, name, CompletionResultType.ParameterName, tooltip)); } } - - if (parameterName != string.Empty) + else if (parameterName != string.Empty) { // Process alias when there is partial input - listInUse.AddRange(from alias in param.Parameter.Aliases - where pattern.IsMatch(alias) - select - new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName, - type + alias)); + foreach (var alias in param.Parameter.Aliases) + { + if (pattern.IsMatch(alias)) + { + listInUse.Add(new CompletionResult( + $"-{alias}{colonSuffix}", + alias, + CompletionResultType.ParameterName, + type + alias)); + } + } } } @@ -878,7 +1047,7 @@ internal static List CompleteCommandArgument(CompletionContext partialPathAst.StringConstantType == StringConstantType.BareWord && secondToLastAst.Extent.EndLineNumber == partialPathAst.Extent.StartLineNumber && secondToLastAst.Extent.EndColumnNumber == partialPathAst.Extent.StartColumnNumber && - partialPathAst.Value.IndexOfAny(Utils.Separators.Directory) == 0) + partialPathAst.Value.AsSpan().IndexOfAny('\\', '/') == 0) { var secondToLastStringConstantAst = secondToLastAst as StringConstantExpressionAst; var secondToLastExpandableStringAst = secondToLastAst as ExpandableStringExpressionAst; @@ -1209,7 +1378,7 @@ internal static List CompleteCommandArgument(CompletionContext if (ret != null && ret.Count > 0) { - var prefix = TokenKind.LParen.Text() + input.Substring(0, fakeReplacementIndex); + string prefix = string.Concat(TokenKind.LParen.Text(), input.AsSpan(0, fakeReplacementIndex)); foreach (CompletionResult entry in ret) { string completionText = prefix + entry.CompletionText; @@ -1258,7 +1427,7 @@ internal static List CompleteCommandArgument(CompletionContext // Treat it as the file name completion // Handle this scenario: & 'c:\a b'\ string fileName = pathAst.Value; - if (commandAst.InvocationOperator != TokenKind.Unknown && fileName.IndexOfAny(Utils.Separators.Directory) == 0 && + if (commandAst.InvocationOperator != TokenKind.Unknown && fileName.AsSpan().IndexOfAny('\\', '/') == 0 && commandAst.CommandElements.Count == 2 && commandAst.CommandElements[0] is StringConstantExpressionAst && commandAst.CommandElements[0].Extent.EndLineNumber == expressionAst.Extent.StartLineNumber && commandAst.CommandElements[0].Extent.EndColumnNumber == expressionAst.Extent.StartColumnNumber) @@ -1328,7 +1497,8 @@ internal static List CompleteCommandArgument(CompletionContext context.Options.Remove("LiteralPaths"); } - if (context.WordToComplete != string.Empty && context.WordToComplete.Contains('-')) + // The word to complete contains a dash and it's not the first character. We try command names in this case. + if (context.WordToComplete.IndexOf('-') > 0) { var commandResults = CompleteCommand(context); if (commandResults != null) @@ -1573,13 +1743,20 @@ private static void CompletePositionalArgument( (defaultParameterSetFlag & validParameterSetFlags) != 0; MergedCompiledCommandParameter positionalParam = null; + MergedCompiledCommandParameter bestMatchParam = null; + ParameterSetSpecificMetadata bestMatchSet = null; + + // Finds the parameter with the position closest to the specified position foreach (MergedCompiledCommandParameter param in parameters) { bool isInParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets; if (!isInParameterSet) + { continue; + } var parameterSetDataCollection = param.Parameter.GetMatchingParameterSetData(validParameterSetFlags); + foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection) { // in the first pass, we skip the remaining argument ones @@ -1591,36 +1768,45 @@ private static void CompletePositionalArgument( // Check the position int positionInParameterSet = parameterSetData.Position; - if (positionInParameterSet == int.MinValue || positionInParameterSet != position) + if (positionInParameterSet < position) { - // The parameter is not positional, or its position is not what we want + // The parameter is not positional (position == int.MinValue), or its position is lower than what we want. continue; } - if (isDefaultParameterSetValid) + if (bestMatchSet is null + || bestMatchSet.Position > positionInParameterSet + || (isDefaultParameterSetValid && positionInParameterSet == bestMatchSet.Position && defaultParameterSetFlag == parameterSetData.ParameterSetFlag)) { - if (parameterSetData.ParameterSetFlag == defaultParameterSetFlag) + bestMatchParam = param; + bestMatchSet = parameterSetData; + if (positionInParameterSet == position) { - ProcessParameter(commandName, commandAst, context, result, param, boundArguments); - isProcessedAsPositional = result.Count > 0; break; } - else - { - if (positionalParam == null) - positionalParam = param; - } + } + } + } + + if (bestMatchParam is not null) + { + if (isDefaultParameterSetValid) + { + if (bestMatchSet.ParameterSetFlag == defaultParameterSetFlag) + { + ProcessParameter(commandName, commandAst, context, result, bestMatchParam, boundArguments); + isProcessedAsPositional = result.Count > 0; } else { - isProcessedAsPositional = true; - ProcessParameter(commandName, commandAst, context, result, param, boundArguments); - break; + positionalParam ??= bestMatchParam; } } - - if (isProcessedAsPositional) - break; + else + { + isProcessedAsPositional = true; + ProcessParameter(commandName, commandAst, context, result, bestMatchParam, boundArguments); + } } if (!isProcessedAsPositional && positionalParam != null) @@ -1656,9 +1842,9 @@ private static void CompletePositionalArgument( /// /// /// If the argument completion falls into these pre-defined cases: - /// 1. The matching parameter is of type Enum - /// 2. The matching parameter is of type SwitchParameter - /// 3. The matching parameter is declared with ValidateSetAttribute + /// 1. The matching parameter is declared with ValidateSetAttribute + /// 2. The matching parameter is of type Enum + /// 3. The matching parameter is of type SwitchParameter /// 4. Falls into the native command argument completion /// a null instance of CompletionResult is added to the end of the /// "result" list, to indicate that this particular argument completion @@ -1681,78 +1867,24 @@ private static void ProcessParameter( parameterType = parameterType.GetElementType(); } - if (parameterType.IsEnum) - { - RemoveLastNullCompletionResult(result); - - string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(parameterType); - string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); - - string wordToComplete = context.WordToComplete; - string quote = HandleDoubleAndSingleQuote(ref wordToComplete); - - var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); - var enumList = new List(); - - foreach (string value in enumArray) - { - if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase)) - { - string completionText = quote == string.Empty ? value : quote + value + quote; - fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterValue, value); - continue; - } - - if (pattern.IsMatch(value)) - { - enumList.Add(value); - } - } - - if (fullMatch != null) - { - result.Add(fullMatch); - } - - enumList.Sort(); - result.AddRange(from entry in enumList - let completionText = quote == string.Empty ? entry : quote + entry + quote - select new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); - - result.Add(CompletionResult.Null); - return; - } - - if (parameterType.Equals(typeof(SwitchParameter))) - { - RemoveLastNullCompletionResult(result); - - if (context.WordToComplete == string.Empty || context.WordToComplete.Equals("$", StringComparison.Ordinal)) - { - result.Add(new CompletionResult("$true", "$true", CompletionResultType.ParameterValue, "$true")); - result.Add(new CompletionResult("$false", "$false", CompletionResultType.ParameterValue, "$false")); - } - - result.Add(CompletionResult.Null); - return; - } - foreach (ValidateArgumentsAttribute att in parameter.Parameter.ValidationAttributes) { if (att is ValidateSetAttribute setAtt) { RemoveLastNullCompletionResult(result); - string wordToComplete = context.WordToComplete; - string quote = HandleDoubleAndSingleQuote(ref wordToComplete); + string wordToComplete = context.WordToComplete ?? string.Empty; + string quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var setList = new List(); foreach (string value in setAtt.ValidValues) { - if (value == string.Empty) { continue; } + if (value == string.Empty) + { + continue; + } if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase)) { @@ -1777,23 +1909,8 @@ private static void ProcessParameter( { string realEntry = entry; string completionText = entry; - if (quote == string.Empty) - { - if (CompletionRequiresQuotes(entry, false)) - { - realEntry = CodeGeneration.EscapeSingleQuotedStringContent(entry); - completionText = "'" + realEntry + "'"; - } - } - else - { - if (quote.Equals("'", StringComparison.OrdinalIgnoreCase)) - { - realEntry = CodeGeneration.EscapeSingleQuotedStringContent(entry); - } - completionText = quote + realEntry + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); } @@ -1803,52 +1920,117 @@ private static void ProcessParameter( } } - NativeCommandArgumentCompletion(commandName, parameter.Parameter, result, commandAst, context, boundArguments); - } - - private static IEnumerable NativeCommandArgumentCompletion_InferTypesOfArgument( - Dictionary boundArguments, - CommandAst commandAst, - CompletionContext context, - string parameterName) - { - if (boundArguments == null) + if (parameterType.IsEnum) { - yield break; - } + RemoveLastNullCompletionResult(result); - AstParameterArgumentPair astParameterArgumentPair; - if (!boundArguments.TryGetValue(parameterName, out astParameterArgumentPair)) - { - yield break; - } + IEnumerable enumValues = LanguagePrimitives.EnumSingleTypeConverter.GetEnumValues(parameterType); - Ast argumentAst = null; - switch (astParameterArgumentPair.ParameterArgumentType) - { - case AstParameterArgumentType.AstPair: + // Exclude values not accepted by ValidateRange-attributes + foreach (ValidateArgumentsAttribute att in parameter.Parameter.ValidationAttributes) + { + if (att is ValidateRangeAttribute rangeAtt) { - AstPair astPair = (AstPair)astParameterArgumentPair; - argumentAst = astPair.Argument; + enumValues = rangeAtt.GetValidatedElements(enumValues); } + } - break; + string wordToComplete = context.WordToComplete ?? string.Empty; + string quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); - case AstParameterArgumentType.PipeObject: + var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); + var enumList = new List(); + + foreach (Enum value in enumValues) + { + string name = value.ToString(); + if (wordToComplete.Equals(name, StringComparison.OrdinalIgnoreCase)) { - var pipelineAst = commandAst.Parent as PipelineAst; - if (pipelineAst != null) - { - int i; - for (i = 0; i < pipelineAst.PipelineElements.Count; i++) - { - if (pipelineAst.PipelineElements[i] == commandAst) - break; - } + string completionText = quote == string.Empty ? name : quote + name + quote; + fullMatch = new CompletionResult(completionText, name, CompletionResultType.ParameterValue, name); + continue; + } - if (i != 0) - { - argumentAst = pipelineAst.PipelineElements[i - 1]; + if (pattern.IsMatch(name)) + { + enumList.Add(name); + } + } + + if (fullMatch != null) + { + result.Add(fullMatch); + } + + enumList.Sort(); + result.AddRange(from entry in enumList + let completionText = quote == string.Empty ? entry : quote + entry + quote + select new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); + + result.Add(CompletionResult.Null); + return; + } + + if (parameterType.Equals(typeof(SwitchParameter))) + { + RemoveLastNullCompletionResult(result); + + if (context.WordToComplete == string.Empty || context.WordToComplete.Equals("$", StringComparison.Ordinal)) + { + result.Add(new CompletionResult("$true", "$true", CompletionResultType.ParameterValue, "$true")); + result.Add(new CompletionResult("$false", "$false", CompletionResultType.ParameterValue, "$false")); + } + + result.Add(CompletionResult.Null); + return; + } + + NativeCommandArgumentCompletion(commandName, parameter.Parameter, result, commandAst, context, boundArguments); + } + + private static IEnumerable NativeCommandArgumentCompletion_InferTypesOfArgument( + Dictionary boundArguments, + CommandAst commandAst, + CompletionContext context, + string parameterName) + { + if (boundArguments == null) + { + yield break; + } + + AstParameterArgumentPair astParameterArgumentPair; + if (!boundArguments.TryGetValue(parameterName, out astParameterArgumentPair)) + { + yield break; + } + + Ast argumentAst = null; + switch (astParameterArgumentPair.ParameterArgumentType) + { + case AstParameterArgumentType.AstPair: + { + AstPair astPair = (AstPair)astParameterArgumentPair; + argumentAst = astPair.Argument; + } + + break; + + case AstParameterArgumentType.PipeObject: + { + var pipelineAst = commandAst.Parent as PipelineAst; + if (pipelineAst != null) + { + int i; + for (i = 0; i < pipelineAst.PipelineElements.Count; i++) + { + if (pipelineAst.PipelineElements[i] == commandAst) + break; + } + + if (i != 0) + { + argumentAst = pipelineAst.PipelineElements[i - 1]; } } } @@ -1996,7 +2178,7 @@ private static void NativeCommandArgumentCompletion( string parameterName = parameter.Name; // Fall back to the commandAst command name if a command name is not found. This can be caused by a script block or AST with the matching function definition being passed to CompleteInput - // This allows for editors and other tools using CompleteInput with Script/AST definations to get values from RegisteredArgumentCompleters to better match the console experience. + // This allows for editors and other tools using CompleteInput with Script/AST definitions to get values from RegisteredArgumentCompleters to better match the console experience. // See issue https://github.com/PowerShell/PowerShell/issues/10567 string actualCommandName = string.IsNullOrEmpty(commandName) ? commandAst.GetCommandName() @@ -2030,19 +2212,17 @@ private static void NativeCommandArgumentCompletion( { try { - if (argumentCompleterAttribute.Type != null) + var completer = argumentCompleterAttribute.CreateArgumentCompleter(); + + if (completer != null) { - var completer = Activator.CreateInstance(argumentCompleterAttribute.Type) as IArgumentCompleter; - if (completer != null) + var customResults = completer.CompleteArgument(commandName, parameterName, + context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); + if (customResults != null) { - var customResults = completer.CompleteArgument(commandName, parameterName, - context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); - if (customResults != null) - { - result.AddRange(customResults); - result.Add(CompletionResult.Null); - return; - } + result.AddRange(customResults); + result.Add(CompletionResult.Null); + return; } } else @@ -2084,6 +2264,12 @@ private static void NativeCommandArgumentCompletion( break; } + if (parameterName.Equals("ExcludeModule", StringComparison.OrdinalIgnoreCase)) + { + NativeCompletionGetCommand(context, moduleName: null, parameterName, result); + break; + } + if (parameterName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { var moduleNames = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "Module"); @@ -2122,6 +2308,22 @@ private static void NativeCommandArgumentCompletion( NativeCompletionGetHelpCommand(context, parameterName, /* isHelpRelated: */ true, result); break; } + case "Save-Help": + { + if (parameterName.Equals("Module", StringComparison.OrdinalIgnoreCase)) + { + CompleteModule(context, result); + } + break; + } + case "Update-Help": + { + if (parameterName.Equals("Module", StringComparison.OrdinalIgnoreCase)) + { + CompleteModule(context, result); + } + break; + } case "Invoke-Expression": { if (parameterName.Equals("Command", StringComparison.OrdinalIgnoreCase)) @@ -2275,7 +2477,7 @@ private static void NativeCommandArgumentCompletion( { if (parameterName.Equals("MemberName", StringComparison.OrdinalIgnoreCase)) { - NativeCompletionMemberName(context, result, commandAst); + NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName], propertiesOnly: false); } break; @@ -2284,14 +2486,32 @@ private static void NativeCommandArgumentCompletion( case "Measure-Object": case "Sort-Object": case "Where-Object": + { + if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) + { + NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); + } + else if (parameterName.Equals("Value", StringComparison.OrdinalIgnoreCase) + && boundArguments?["Property"] is AstPair pair && pair.Argument is StringConstantExpressionAst stringAst) + { + NativeCompletionMemberValue(context, result, commandAst, stringAst.Value); + } + + break; + } case "Format-Custom": case "Format-List": case "Format-Table": case "Format-Wide": { - if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) + if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) + || parameterName.Equals("ExcludeProperty", StringComparison.OrdinalIgnoreCase)) + { + NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); + } + else if (parameterName.Equals("View", StringComparison.OrdinalIgnoreCase)) { - NativeCompletionMemberName(context, result, commandAst); + NativeCompletionFormatViewName(context, boundArguments, result, commandAst, commandName); } break; @@ -2302,7 +2522,7 @@ private static void NativeCommandArgumentCompletion( || parameterName.Equals("ExcludeProperty", StringComparison.OrdinalIgnoreCase) || parameterName.Equals("ExpandProperty", StringComparison.OrdinalIgnoreCase)) { - NativeCompletionMemberName(context, result, commandAst); + NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); } break; @@ -2324,8 +2544,22 @@ private static void NativeCommandArgumentCompletion( case "Invoke-CimMethod": case "New-CimInstance": case "Register-CimIndicationEvent": + case "Set-CimInstance": { - NativeCompletionCimCommands(parameterName, boundArguments, result, commandAst, context); + // Avoids completion for parameters that expect a hashtable. + if (parameterName.Equals("Arguments", StringComparison.OrdinalIgnoreCase) + || (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) && !commandName.Equals("Get-CimInstance"))) + { + break; + } + + HashSet excludedValues = null; + if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) && boundArguments["Property"] is AstPair pair) + { + excludedValues = GetParameterValues(pair, context.CursorPosition.Offset); + } + + NativeCompletionCimCommands(parameterName, boundArguments, result, commandAst, context, excludedValues, commandName); break; } @@ -2404,9 +2638,8 @@ private static ScriptBlock GetCustomArgumentCompleter( } } - var registeredCompleters = optionKey.Equals("NativeArgumentCompleters", StringComparison.OrdinalIgnoreCase) - ? context.NativeArgumentCompleters - : context.CustomArgumentCompleters; + bool isNative = optionKey.Equals("NativeArgumentCompleters", StringComparison.OrdinalIgnoreCase); + var registeredCompleters = isNative ? context.NativeArgumentCompleters : context.CustomArgumentCompleters; if (registeredCompleters != null) { @@ -2417,6 +2650,13 @@ private static ScriptBlock GetCustomArgumentCompleter( return scriptBlock; } } + + // For a native command, if a fallback completer is registered, then return it. + // For example, the 'Microsoft.PowerShell.UnixTabCompletion' module. + if (isNative && registeredCompleters.TryGetValue(RegisterArgumentCompleterCommand.FallbackCompleterKey, out scriptBlock)) + { + return scriptBlock; + } } return null; @@ -2435,14 +2675,17 @@ private static bool InvokeScriptArgumentCompleter( scriptBlock, new object[] { commandName, parameterName, wordToComplete, commandAst, GetBoundArgumentsAsHashtable(context) }, resultList); - if (result) - { - resultList.Add(CompletionResult.Null); - } return result; } + /// + /// Invoke the custom argument completer and process its return values. + /// If we consider the completion successful, we add a null instance of the type 'CompletionResult' + /// to the end of the 'result' list to indicate that the argument completion has been processed, so we + /// will not go through the default argument completion even if the 'result' list is still empty. + /// + /// 'true' if the argument completion was successful. 'false' otherwise. private static bool InvokeScriptArgumentCompleter( ScriptBlock scriptBlock, object[] argumentsToCompleter, @@ -2462,20 +2705,44 @@ private static bool InvokeScriptArgumentCompleter( return false; } + if (customResults.Count is 1 && customResults[0] is { BaseObject: "" } or null) + { + // If the script block returns a single empty string or a null value, we will treat it as if it has + // completed successfully but has no results to return. + // This allows a custom completer to suppress the default completions that we may fall back otherwise. + result.Add(CompletionResult.Null); + return true; + } + + int initialCount = result.Count; + foreach (var customResult in customResults) { - var resultAsCompletion = customResult.BaseObject as CompletionResult; - if (resultAsCompletion != null) + if (customResult is null) + { + continue; + } + + if (customResult.BaseObject is CompletionResult resultAsCompletion) { result.Add(resultAsCompletion); continue; } var resultAsString = customResult.ToString(); - result.Add(new CompletionResult(resultAsString)); + if (!string.IsNullOrEmpty(resultAsString)) + { + result.Add(new CompletionResult(resultAsString)); + } } - return true; + bool success = result.Count > initialCount; + if (success) + { + result.Add(CompletionResult.Null); + } + + return success; } // All the methods for native command argument completion will add a null instance of the type CompletionResult to the end of the @@ -2483,9 +2750,9 @@ private static bool InvokeScriptArgumentCompleter( // and has been processed already. So if the "result" list is still empty afterward, we will not go through the default argument completion anymore. #region Native Command Argument Completion - private static void RemoveLastNullCompletionResult(List result) + internal static void RemoveLastNullCompletionResult(List result) { - if (result.Count > 0 && result[result.Count - 1].Equals(CompletionResult.Null)) + if (result?.Count > 0 && result[^1].Equals(CompletionResult.Null)) { result.RemoveAt(result.Count - 1); } @@ -2496,7 +2763,9 @@ private static void NativeCompletionCimCommands( Dictionary boundArguments, List result, CommandAst commandAst, - CompletionContext context) + CompletionContext context, + HashSet excludedValues, + string commandName) { if (boundArguments != null) { @@ -2517,6 +2786,7 @@ private static void NativeCompletionCimCommands( } } + RemoveLastNullCompletionResult(result); if (parameter.Equals("Namespace", StringComparison.OrdinalIgnoreCase)) { NativeCompletionCimNamespace(result, context); @@ -2562,6 +2832,16 @@ private static void NativeCompletionCimCommands( { NativeCompletionCimMethodName(pseudoboundCimNamespace, pseudoboundClassName, !gotInstance, result, context); } + else if (parameter.Equals("Arguments", StringComparison.OrdinalIgnoreCase)) + { + string pseudoboundMethodName = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "MethodName").FirstOrDefault(); + NativeCompletionCimMethodArgumentName(pseudoboundCimNamespace, pseudoboundClassName, pseudoboundMethodName, excludedValues, result, context); + } + else if (parameter.Equals("Property", StringComparison.OrdinalIgnoreCase)) + { + bool includeReadOnly = !commandName.Equals("Set-CimInstance", StringComparison.OrdinalIgnoreCase); + NativeCompletionCimPropertyName(pseudoboundCimNamespace, pseudoboundClassName, includeReadOnly, excludedValues, result, context); + } } } @@ -2598,7 +2878,7 @@ private static IEnumerable NativeCompletionCimAssociationResultClassName resultClassNames.AddRange( cimSession.QueryInstances(cimNamespaceOfSource ?? "root/cimv2", "WQL", query) - .Select(associationInstance => associationInstance.CimSystemProperties.ClassName)); + .Select(static associationInstance => associationInstance.CimSystemProperties.ClassName)); cimClass = cimClass.CimSuperClass; } @@ -2627,7 +2907,7 @@ private static void NativeCompletionCimAssociationResultClassName( WildcardPattern resultClassNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); result.AddRange(resultClassNames .Where(resultClassNamePattern.IsMatch) - .Select(x => new CompletionResult(x, x, CompletionResultType.Type, string.Format(CultureInfo.InvariantCulture, "{0} -> {1}", pseudoboundClassName, x)))); + .Select(x => new CompletionResult(x, x, CompletionResultType.Type, string.Create(CultureInfo.InvariantCulture, $"{pseudoboundClassName} -> {x}")))); } private static void NativeCompletionCimMethodName( @@ -2658,7 +2938,7 @@ private static void NativeCompletionCimMethodName( continue; } - bool currentMethodIsStatic = methodDeclaration.Qualifiers.Any(q => q.Name.Equals("Static", StringComparison.OrdinalIgnoreCase)); + bool currentMethodIsStatic = methodDeclaration.Qualifiers.Any(static q => q.Name.Equals("Static", StringComparison.OrdinalIgnoreCase)); if ((currentMethodIsStatic && !staticMethod) || (!currentMethodIsStatic && staticMethod)) { continue; @@ -2670,7 +2950,7 @@ private static void NativeCompletionCimMethodName( bool gotFirstParameter = false; foreach (var methodParameter in methodDeclaration.Parameters) { - bool outParameter = methodParameter.Qualifiers.Any(q => q.Name.Equals("Out", StringComparison.OrdinalIgnoreCase)); + bool outParameter = methodParameter.Qualifiers.Any(static q => q.Name.Equals("Out", StringComparison.OrdinalIgnoreCase)); if (!gotFirstParameter) { @@ -2701,7 +2981,83 @@ private static void NativeCompletionCimMethodName( localResults.Add(new CompletionResult(methodName, methodName, CompletionResultType.Method, tooltipText.ToString())); } - result.AddRange(localResults.OrderBy(x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); + result.AddRange(localResults.OrderBy(static x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); + } + + private static void NativeCompletionCimMethodArgumentName( + string pseudoboundNamespace, + string pseudoboundClassName, + string pseudoboundMethodName, + HashSet excludedParameters, + List result, + CompletionContext context) + { + if (string.IsNullOrWhiteSpace(pseudoboundClassName) || string.IsNullOrWhiteSpace(pseudoboundMethodName)) + { + return; + } + + CimClass cimClass; + using (var cimSession = CimSession.Create(null)) + { + using var options = new CimOperationOptions(); + options.Flags |= CimOperationFlags.LocalizedQualifiers; + cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName, options); + } + + var methodParameters = cimClass.CimClassMethods[pseudoboundMethodName]?.Parameters; + if (methodParameters is null) + { + return; + } + + foreach (var parameter in methodParameters) + { + if ((string.IsNullOrEmpty(context.WordToComplete) || parameter.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) + && (excludedParameters is null || !excludedParameters.Contains(parameter.Name)) + && parameter.Qualifiers["In"]?.Value is true) + { + string parameterDescription = parameter.Qualifiers["Description"]?.Value as string ?? string.Empty; + string toolTip = $"[{CimInstanceAdapter.CimTypeToTypeNameDisplayString(parameter.CimType)}] {parameterDescription}"; + result.Add(new CompletionResult(parameter.Name, parameter.Name, CompletionResultType.Property, toolTip)); + } + } + } + + private static void NativeCompletionCimPropertyName( + string pseudoboundNamespace, + string pseudoboundClassName, + bool includeReadOnly, + HashSet excludedProperties, + List result, + CompletionContext context) + { + if (string.IsNullOrWhiteSpace(pseudoboundClassName)) + { + return; + } + + CimClass cimClass; + using (var cimSession = CimSession.Create(null)) + { + using var options = new CimOperationOptions(); + options.Flags |= CimOperationFlags.LocalizedQualifiers; + cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName, options); + } + + foreach (var property in cimClass.CimClassProperties) + { + bool isReadOnly = (property.Flags & CimFlags.ReadOnly) != 0; + if ((!isReadOnly || (isReadOnly && includeReadOnly)) + && (string.IsNullOrEmpty(context.WordToComplete) || property.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) + && (excludedProperties is null || !excludedProperties.Contains(property.Name))) + { + string propertyDescription = property.Qualifiers["Description"]?.Value as string ?? string.Empty; + string accessString = isReadOnly ? "{ get; }" : "{ get; set; }"; + string toolTip = $"[{CimInstanceAdapter.CimTypeToTypeNameDisplayString(property.CimType)}] {accessString} {propertyDescription}"; + result.Add(new CompletionResult(property.Name, property.Name, CompletionResultType.Property, toolTip)); + } + } } private static readonly ConcurrentDictionary> s_cimNamespaceToClassNames = @@ -2776,7 +3132,7 @@ private static void NativeCompletionCimNamespace( string prefixOfChildNamespace = string.Empty; if (!string.IsNullOrEmpty(context.WordToComplete)) { - int lastSlashOrBackslash = context.WordToComplete.LastIndexOfAny(Utils.Separators.Directory); + int lastSlashOrBackslash = context.WordToComplete.AsSpan().LastIndexOfAny('\\', '/'); if (lastSlashOrBackslash != (-1)) { containerNamespace = context.WordToComplete.Substring(0, lastSlashOrBackslash); @@ -2802,7 +3158,7 @@ private static void NativeCompletionCimNamespace( continue; } - if (!(namespaceNameProperty.Value is string childNamespace)) + if (namespaceNameProperty.Value is not string childNamespace) { continue; } @@ -2820,7 +3176,7 @@ private static void NativeCompletionCimNamespace( } } - result.AddRange(namespaceResults.OrderBy(x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); + result.AddRange(namespaceResults.OrderBy(static x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); } private static void NativeCompletionGetCommand(CompletionContext context, string moduleName, string paramName, List result) @@ -2847,39 +3203,46 @@ private static void NativeCompletionGetCommand(CompletionContext context, string result.Add(CompletionResult.Null); } - else if (!string.IsNullOrEmpty(paramName) && paramName.Equals("Module", StringComparison.OrdinalIgnoreCase)) + else if (!string.IsNullOrEmpty(paramName) + && (paramName.Equals("Module", StringComparison.OrdinalIgnoreCase) + || paramName.Equals("ExcludeModule", StringComparison.OrdinalIgnoreCase))) { - RemoveLastNullCompletionResult(result); + CompleteModule(context, result); + } + } + + private static void CompleteModule(CompletionContext context, List result) + { + RemoveLastNullCompletionResult(result); - var modules = new HashSet(StringComparer.OrdinalIgnoreCase); - var moduleResults = CompleteModuleName(context, loadedModulesOnly: true); - if (moduleResults != null) + var modules = new HashSet(StringComparer.OrdinalIgnoreCase); + var moduleResults = CompleteModuleName(context, loadedModulesOnly: true); + if (moduleResults != null) + { + foreach (CompletionResult moduleResult in moduleResults) { - foreach (CompletionResult moduleResult in moduleResults) + if (!modules.Contains(moduleResult.ToolTip)) { - if (!modules.Contains(moduleResult.ToolTip)) - { - modules.Add(moduleResult.ToolTip); - result.Add(moduleResult); - } + modules.Add(moduleResult.ToolTip); + result.Add(moduleResult); } } + } - moduleResults = CompleteModuleName(context, loadedModulesOnly: false); - if (moduleResults != null) + moduleResults = CompleteModuleName(context, loadedModulesOnly: false); + if (moduleResults != null) + { + foreach (CompletionResult moduleResult in moduleResults) { - foreach (CompletionResult moduleResult in moduleResults) + if (!modules.Contains(moduleResult.ToolTip)) { - if (!modules.Contains(moduleResult.ToolTip)) - { - modules.Add(moduleResult.ToolTip); - result.Add(moduleResult); - } + modules.Add(moduleResult.ToolTip); + result.Add(moduleResult); } } - - result.Add(CompletionResult.Null); } + + result.Add(CompletionResult.Null); } private static void NativeCompletionGetHelpCommand(CompletionContext context, string paramName, bool isHelpRelated, List result) @@ -2919,7 +3282,7 @@ private static void NativeCompletionEventLogCommands(CompletionContext context, RemoveLastNullCompletionResult(result); var logName = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref logName); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref logName); if (!logName.EndsWith('*')) { @@ -2941,17 +3304,7 @@ private static void NativeCompletionEventLogCommands(CompletionContext context, var completionText = eventLog.Log.ToString(); var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); if (pattern.IsMatch(listItemText)) { @@ -2970,7 +3323,7 @@ private static void NativeCompletionJobCommands(CompletionContext context, strin return; var wordToComplete = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref wordToComplete); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { @@ -3032,17 +3385,7 @@ private static void NativeCompletionJobCommands(CompletionContext context, strin var completionText = psJob.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3057,7 +3400,7 @@ private static void NativeCompletionScheduledJobCommands(CompletionContext conte return; var wordToComplete = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref wordToComplete); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { @@ -3107,17 +3450,7 @@ private static void NativeCompletionScheduledJobCommands(CompletionContext conte var completionText = psJob.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3191,7 +3524,7 @@ private static void NativeCompletionProcessCommands(CompletionContext context, s return; var wordToComplete = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref wordToComplete); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { @@ -3247,17 +3580,7 @@ private static void NativeCompletionProcessCommands(CompletionContext context, s continue; uniqueSet.Add(completionText); - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); // on macOS, system processes names will be empty if PowerShell isn't run as `sudo` if (string.IsNullOrEmpty(listItemText)) @@ -3282,7 +3605,7 @@ private static void NativeCompletionProviderCommands(CompletionContext context, RemoveLastNullCompletionResult(result); var providerName = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref providerName); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref providerName); if (!providerName.EndsWith('*')) { @@ -3300,17 +3623,7 @@ private static void NativeCompletionProviderCommands(CompletionContext context, var completionText = providerInfo.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3326,7 +3639,7 @@ private static void NativeCompletionDriveCommands(CompletionContext context, str RemoveLastNullCompletionResult(result); var wordToComplete = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref wordToComplete); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { @@ -3348,17 +3661,7 @@ private static void NativeCompletionDriveCommands(CompletionContext context, str var completionText = driveInfo.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3373,7 +3676,7 @@ private static void NativeCompletionServiceCommands(CompletionContext context, s return; var wordToComplete = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref wordToComplete); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { @@ -3399,17 +3702,7 @@ private static void NativeCompletionServiceCommands(CompletionContext context, s var completionText = serviceInfo.DisplayName; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3430,17 +3723,7 @@ private static void NativeCompletionServiceCommands(CompletionContext context, s var completionText = serviceInfo.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3460,7 +3743,7 @@ private static void NativeCompletionVariableCommands(CompletionContext context, RemoveLastNullCompletionResult(result); var variableName = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref variableName); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref variableName); if (!variableName.EndsWith('*')) { variableName += "*"; @@ -3486,7 +3769,7 @@ private static void NativeCompletionVariableCommands(CompletionContext context, completionText = completionText.Replace("*", "`*"); } - if (!completionText.Equals("$", StringComparison.Ordinal) && CompletionRequiresQuotes(completionText, false)) + if (!completionText.Equals("$", StringComparison.Ordinal) && CompletionHelpers.CompletionRequiresQuotes(completionText)) { var quoteInUse = effectiveQuote == string.Empty ? "'" : effectiveQuote; if (quoteInUse == "'") @@ -3519,7 +3802,7 @@ private static void NativeCompletionAliasCommands(CompletionContext context, str if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { var commandName = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref commandName); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref commandName); if (!commandName.EndsWith('*')) { @@ -3536,17 +3819,7 @@ private static void NativeCompletionAliasCommands(CompletionContext context, str var completionText = aliasInfo.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3580,7 +3853,7 @@ private static void NativeCompletionTraceSourceCommands(CompletionContext contex RemoveLastNullCompletionResult(result); var traceSourceName = context.WordToComplete ?? string.Empty; - var quote = HandleDoubleAndSingleQuote(ref traceSourceName); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref traceSourceName); if (!traceSourceName.EndsWith('*')) { @@ -3599,17 +3872,7 @@ private static void NativeCompletionTraceSourceCommands(CompletionContext contex var completionText = trace.Name; var listItemText = completionText; - if (CompletionRequiresQuotes(completionText, false)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - completionText = completionText.Replace("'", "''"); - completionText = quoteInUse + completionText + quoteInUse; - } - else - { - completionText = quote + completionText + quote; - } + completionText = CompletionHelpers.QuoteCompletionText(completionText, quote); result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } @@ -3787,44 +4050,132 @@ private static void NativeCompletionPathArgument(CompletionContext context, stri result.Add(CompletionResult.Null); } - private static void NativeCompletionMemberName(CompletionContext context, List result, CommandAst commandAst) + private static IEnumerable GetInferenceTypes(CompletionContext context, CommandAst commandAst) { // Command is something like where-object/foreach-object/format-list/etc. where there is a parameter that is a property name // and we want member names based on the input object, which is either the parameter InputObject, or comes from the pipeline. - if (!(commandAst.Parent is PipelineAst pipelineAst)) - return; + if (commandAst.Parent is not PipelineAst pipelineAst) + { + return null; + } int i; for (i = 0; i < pipelineAst.PipelineElements.Count; i++) { if (pipelineAst.PipelineElements[i] == commandAst) + { break; + } } IEnumerable prevType = null; if (i == 0) { + // based on a type of the argument which is binded to 'InputObject' parameter. AstParameterArgumentPair pair; if (!context.PseudoBindingInfo.BoundArguments.TryGetValue("InputObject", out pair) || !pair.ArgumentSpecified) { - return; + return null; } var astPair = pair as AstPair; if (astPair == null || astPair.Argument == null) { - return; + return null; } prevType = AstTypeInference.InferTypeOf(astPair.Argument, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } else { + // based on OutputTypeAttribute() of the first cmdlet in pipeline. prevType = AstTypeInference.InferTypeOf(pipelineAst.PipelineElements[i - 1], context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } - CompleteMemberByInferredType(context.TypeInferenceContext, prevType, result, context.WordToComplete + "*", filter: IsPropertyMember, isStatic: false); + return prevType; + } + + private static void NativeCompletionMemberName(CompletionContext context, List result, CommandAst commandAst, AstParameterArgumentPair parameterInfo, bool propertiesOnly = true) + { + IEnumerable prevType = TypeInferenceVisitor.GetInferredEnumeratedTypes(GetInferenceTypes(context, commandAst)); + if (prevType is not null) + { + HashSet excludedMembers = null; + if (parameterInfo is AstPair pair) + { + excludedMembers = GetParameterValues(pair, context.CursorPosition.Offset); + } + + Func filter = propertiesOnly ? IsPropertyMember : null; + CompleteMemberByInferredType(context.TypeInferenceContext, prevType, result, context.WordToComplete + "*", filter, isStatic: false, excludedMembers, addMethodParenthesis: false); + } + + result.Add(CompletionResult.Null); + } + + private static void NativeCompletionMemberValue(CompletionContext context, List result, CommandAst commandAst, string propertyName) + { + string wordToComplete = context.WordToComplete.Trim('"', '\''); + IEnumerable prevTypes = GetInferenceTypes(context, commandAst); + if (prevTypes is not null) + { + foreach (var type in prevTypes) + { + if (type.Type is null) + { + continue; + } + + PropertyInfo property = type.Type.GetProperty(propertyName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); + if (property is not null && property.PropertyType.IsEnum) + { + foreach (var value in property.PropertyType.GetEnumNames()) + { + if (value.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult(value, value, CompletionResultType.ParameterValue, value)); + } + } + + break; + } + } + } + + result.Add(CompletionResult.Null); + } + + /// + /// Returns all string values bound to a parameter except the one the cursor is currently at. + /// + private static HashSetGetParameterValues(AstPair parameter, int cursorOffset) + { + var result = new HashSet(StringComparer.OrdinalIgnoreCase); + var parameterValues = parameter.Argument.FindAll(ast => !(cursorOffset >= ast.Extent.StartOffset && cursorOffset <= ast.Extent.EndOffset) && ast is StringConstantExpressionAst, searchNestedScriptBlocks: false); + foreach (Ast ast in parameterValues) + { + result.Add(ast.Extent.Text); + } + + return result; + } + + private static void NativeCompletionFormatViewName( + CompletionContext context, + Dictionary boundArguments, + List result, + CommandAst commandAst, + string commandName) + { + IEnumerable prevType = NativeCommandArgumentCompletion_InferTypesOfArgument(boundArguments, commandAst, context, "InputObject"); + + if (prevType is not null) + { + string[] inferTypeNames = prevType.Select(t => t.Name).ToArray(); + CompleteFormatViewByInferredType(context, inferTypeNames, result, commandName); + } + result.Add(CompletionResult.Null); } @@ -3952,9 +4303,11 @@ private static ArgumentLocation FindTargetArgumentLocation(Collection token.Extent.StartOffset) + if ((token.Kind == TokenKind.Parameter && token.Extent.StartOffset == arg.Parameter.Extent.StartOffset) + || (token.Extent.StartOffset > arg.Argument.Extent.StartOffset && token.Extent.EndOffset < arg.Argument.Extent.EndOffset)) { - // case: Get-Cmdlet -Param abc + // case 1: Get-Cmdlet -Param abc + // case 2: dir -Path .\abc.txt, -File return new ArgumentLocation() { Argument = arg, IsPositional = false, Position = -1 }; } } @@ -4124,374 +4477,738 @@ internal static IEnumerable CompleteFilename(CompletionContext internal static IEnumerable CompleteFilename(CompletionContext context, bool containerOnly, HashSet extension) { var wordToComplete = context.WordToComplete; - var quote = HandleDoubleAndSingleQuote(ref wordToComplete); - var results = new List(); + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); - // First, try to match \\server\share - var shareMatch = Regex.Match(wordToComplete, "^\\\\\\\\([^\\\\]+)\\\\([^\\\\]*)$"); + // Matches file shares with and without the provider name and with either slash direction. + // Avoids matching Windows device paths like \\.\CDROM0 and \\?\Volume{b8f3fc1c-5cd6-4553-91e2-d6814c4cd375}\ + var shareMatch = s_shareMatch.Match(wordToComplete); if (shareMatch.Success) { // Only match share names, no filenames. - var server = shareMatch.Groups[1].Value; - var sharePattern = WildcardPattern.Get(shareMatch.Groups[2].Value + "*", WildcardOptions.IgnoreCase); + var provider = shareMatch.Groups[1].Value; + var server = shareMatch.Groups[2].Value; + var sharePattern = WildcardPattern.Get(shareMatch.Groups[3].Value + "*", WildcardOptions.IgnoreCase); var ignoreHidden = context.GetOption("IgnoreHiddenShares", @default: false); var shares = GetFileShares(server, ignoreHidden); + if (shares.Count == 0) + { + return CommandCompletion.EmptyCompletionResult; + } + + var shareResults = new List(shares.Count); foreach (var share in shares) { if (sharePattern.IsMatch(share)) { - string shareFullPath = "\\\\" + server + "\\" + share; - if (quote != string.Empty) + string sharePath = $"\\\\{server}\\{share}"; + string completionText; + if (quote == string.Empty) { - shareFullPath = quote + shareFullPath + quote; + completionText = share.Contains(' ') + ? $"'{provider}{sharePath}'" + : $"{provider}{sharePath}"; + } + else + { + completionText = $"{quote}{provider}{sharePath}{quote}"; } - results.Add(new CompletionResult(shareFullPath, shareFullPath, CompletionResultType.ProviderContainer, shareFullPath)); + shareResults.Add(new CompletionResult(completionText, share, CompletionResultType.ProviderContainer, sharePath)); } } + + return shareResults; + } + + string filter; + string basePath; + int providerSeparatorIndex = -1; + bool defaultRelativePath = false; + bool inputUsedHomeChar = false; + + if (string.IsNullOrEmpty(wordToComplete)) + { + filter = "*"; + basePath = "."; + defaultRelativePath = true; } else { - // We want to prefer relative paths in a completion result unless the user has already - // specified a drive or portion of the path. - var executionContext = context.ExecutionContext; - var defaultRelative = string.IsNullOrWhiteSpace(wordToComplete) - || (wordToComplete.IndexOfAny(Utils.Separators.Directory) != 0 && - !Regex.Match(wordToComplete, @"^~[\\/]+.*").Success && - !executionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _)); - var relativePaths = context.GetOption("RelativePaths", @default: defaultRelative); - var useLiteralPath = context.GetOption("LiteralPaths", @default: false); + providerSeparatorIndex = wordToComplete.IndexOf("::", StringComparison.Ordinal); + int pathStartOffset = providerSeparatorIndex == -1 ? 0 : providerSeparatorIndex + 2; + inputUsedHomeChar = pathStartOffset + 2 <= wordToComplete.Length + && wordToComplete[pathStartOffset] is '~' + && wordToComplete[pathStartOffset + 1] is '/' or '\\'; - if (useLiteralPath && LocationGlobber.StringContainsGlobCharacters(wordToComplete)) + // This simple analysis is quick but doesn't handle scenarios where a separator character is not actually a separator + // For example "\" or ":" in *nix filenames. This is only a problem if it appears to be the last separator though. + int lastSeparatorIndex = wordToComplete.LastIndexOfAny(Utils.Separators.DirectoryOrDrive); + if (lastSeparatorIndex == -1) { - wordToComplete = WildcardPattern.Escape(wordToComplete, Utils.Separators.StarOrQuestion); + // Input is a simple word with no path separators like: "Program Files" + filter = $"{wordToComplete}*"; + basePath = "."; + defaultRelativePath = true; } - - if (!defaultRelative && wordToComplete.Length >= 2 && wordToComplete[1] == ':' && char.IsLetter(wordToComplete[0]) && executionContext != null) - { - // We don't actually need the drive, but the drive must be "mounted" in PowerShell before completion - // can succeed. This call will mount the drive if it wasn't already. - executionContext.SessionState.Drive.GetAtScope(wordToComplete.Substring(0, 1), "global"); - } - - var powerShellExecutionHelper = context.Helper; - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Resolve-Path") - .AddParameter("Path", wordToComplete + "*"); - - Exception exceptionThrown; - var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - - if (psobjs != null) + else { - var isFileSystem = false; - var wordContainsProviderId = ProviderSpecified(wordToComplete); - - if (psobjs.Count > 0) + if (lastSeparatorIndex + 1 == wordToComplete.Length) { - dynamic firstObj = psobjs[0]; - var provider = firstObj.Provider as ProviderInfo; - isFileSystem = provider != null && - provider.Name.Equals(FileSystemProvider.ProviderName, - StringComparison.OrdinalIgnoreCase); + // Input ends with a separator like: "./", "filesystem::" or "C:" + filter = "*"; + basePath = wordToComplete; } else { - try - { - ProviderInfo provider; - if (defaultRelative) - { - provider = executionContext.EngineSessionState.CurrentDrive.Provider; - } - else - { - executionContext.LocationGlobber.GetProviderPath(wordToComplete, out provider); - } - - isFileSystem = provider != null && - provider.Name.Equals(FileSystemProvider.ProviderName, - StringComparison.OrdinalIgnoreCase); - } - catch (Exception) - { - } + // Input contains a separator, but doesn't end with one like: "C:\Program Fil" or "Registry::HKEY_LOC" + filter = $"{wordToComplete.Substring(lastSeparatorIndex + 1)}*"; + basePath = wordToComplete.Substring(0, lastSeparatorIndex + 1); } - if (isFileSystem) + if (!inputUsedHomeChar && basePath[0] is not '/' and not '\\') { - bool hiddenFilesAreHandled = false; + defaultRelativePath = !context.ExecutionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _); + } + } + } - if (psobjs.Count > 0 && !LocationGlobber.StringContainsGlobCharacters(wordToComplete)) - { - string leaf = null; - string pathWithoutProvider = wordContainsProviderId - ? wordToComplete.Substring(wordToComplete.IndexOf(':') + 2) - : wordToComplete; + StringConstantType stringType; + switch (quote) + { + case "": + stringType = StringConstantType.BareWord; + break; - try - { - leaf = Path.GetFileName(pathWithoutProvider); - } - catch (Exception) - { - } + case "\"": + stringType = StringConstantType.DoubleQuoted; + break; + + default: + stringType = StringConstantType.SingleQuoted; + break; + } - var notHiddenEntries = new HashSet(StringComparer.OrdinalIgnoreCase); - string providerPath = null; + var useLiteralPath = context.GetOption("LiteralPaths", @default: false); + if (useLiteralPath) + { + basePath = EscapePath(basePath, stringType, useLiteralPath, out _); + } - foreach (dynamic entry in psobjs) - { - providerPath = entry.ProviderPath; - if (string.IsNullOrEmpty(providerPath)) - { - // This is unexpected. ProviderPath should never be null or an empty string - leaf = null; - break; - } + PowerShell currentPS = context.Helper + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Resolve-Path") + .AddParameter("Path", basePath); - if (!notHiddenEntries.Contains(providerPath)) - { - notHiddenEntries.Add(providerPath); - } - } + string relativeBasePath; + var useRelativePath = context.GetOption("RelativePaths", @default: defaultRelativePath); + if (useRelativePath) + { + if (providerSeparatorIndex != -1) + { + // User must have requested relative paths but that's not valid with provider paths. + return CommandCompletion.EmptyCompletionResult; + } - if (leaf != null) - { - leaf += "*"; - var parentPath = Path.GetDirectoryName(providerPath); + var lastAst = context.RelatedAsts?[^1]; + if (lastAst?.Parent is UsingStatementAst usingStatement + && usingStatement.UsingStatementKind is UsingStatementKind.Module or UsingStatementKind.Assembly + && lastAst.Extent.File is not null) + { + relativeBasePath = Directory.GetParent(lastAst.Extent.File).FullName; + _ = currentPS.AddParameter("RelativeBasePath", relativeBasePath); + } + else + { + relativeBasePath = context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath; + } + } + else + { + relativeBasePath = string.Empty; + } - // ProviderPath should be absolute path for FileSystem entries - if (!string.IsNullOrEmpty(parentPath)) - { - string[] entries = null; - try - { - entries = Directory.GetFileSystemEntries(parentPath, leaf, _enumerationOptions); - } - catch (Exception) - { - } + var resolvedPaths = context.Helper.ExecuteCurrentPowerShell(out _); + if (resolvedPaths is null || resolvedPaths.Count == 0) + { + return CommandCompletion.EmptyCompletionResult; + } - if (entries != null) - { - hiddenFilesAreHandled = true; + var resolvedProvider = ((PathInfo)resolvedPaths[0].BaseObject).Provider; + string providerPrefix; + if (providerSeparatorIndex == -1) + { + providerPrefix = string.Empty; + } + else if (providerSeparatorIndex == resolvedProvider.Name.Length) + { + providerPrefix = $"{resolvedProvider.Name}::"; + } + else + { + providerPrefix = $"{resolvedProvider.ModuleName}\\{resolvedProvider.Name}::"; + } - if (entries.Length > notHiddenEntries.Count) - { - // Do the iteration only if there are hidden files - foreach (var entry in entries) - { - if (notHiddenEntries.Contains(entry)) - continue; - - var fileInfo = new FileInfo(entry); - try - { - if ((fileInfo.Attributes & FileAttributes.Hidden) != 0) - { - PSObject wrapper = PSObject.AsPSObject(entry); - psobjs.Add(wrapper); - } - } - catch - { - // do nothing if can't get file attributes - } - } - } - } - } - } - } + List results; + switch (resolvedProvider.Name) + { + case FileSystemProvider.ProviderName: + results = GetFileSystemProviderResults( + context, + resolvedProvider, + resolvedPaths, + filter, + extension, + containerOnly, + useRelativePath, + useLiteralPath, + inputUsedHomeChar, + providerPrefix, + stringType, + relativeBasePath); + break; - if (!hiddenFilesAreHandled) - { - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") - .AddParameter("Path", wordToComplete + "*") - .AddParameter("Hidden", true); + default: + results = GetDefaultProviderResults( + context, + resolvedProvider, + resolvedPaths, + filter, + containerOnly, + useRelativePath, + useLiteralPath, + inputUsedHomeChar, + providerPrefix, + stringType); + break; + } - var hiddenItems = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (hiddenItems != null && hiddenItems.Count > 0) - { - foreach (var hiddenItem in hiddenItems) - { - psobjs.Add(hiddenItem); - } - } - } - } + return results.OrderBy(x => x.ToolTip); + } - // Sorting the results by the path - var sortedPsobjs = psobjs.OrderBy(a => a, new ItemPathComparer()); + /// + /// Helper method for generating path completion results for the file system provider. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static List GetFileSystemProviderResults( + CompletionContext context, + ProviderInfo provider, + Collection resolvedPaths, + string filterText, + HashSet includedExtensions, + bool containersOnly, + bool relativePaths, + bool literalPaths, + bool inputUsedHome, + string providerPrefix, + StringConstantType stringType, + string relativeBasePath) + { +#if DEBUG + Diagnostics.Assert(provider.Name.Equals(FileSystemProvider.ProviderName), "Provider should be filesystem provider."); +#endif + var enumerationOptions = _enumerationOptions; + var results = new List(); + string homePath = inputUsedHome && !string.IsNullOrEmpty(provider.Home) ? provider.Home : null; - foreach (PSObject psobj in sortedPsobjs) - { - object baseObj = PSObject.Base(psobj); - string path = null, providerPath = null; + WildcardPattern wildcardFilter; + if (WildcardPattern.ContainsRangeWildcard(filterText)) + { + wildcardFilter = WildcardPattern.Get(filterText, WildcardOptions.IgnoreCase); + filterText = "*"; + } + else + { + wildcardFilter = null; + } - // Get the path, the PSObject could be: - // 1. a PathInfo object -- results of Resolve-Path - // 2. a FileSystemInfo Object -- results of Get-ChildItem - // 3. a string -- the path results return by the direct .NET API invocation - var baseObjAsPathInfo = baseObj as PathInfo; - if (baseObjAsPathInfo != null) - { - path = baseObjAsPathInfo.Path; - providerPath = baseObjAsPathInfo.ProviderPath; - } - else if (baseObj is FileSystemInfo) - { - // The target provider is the FileSystem - dynamic dirResult = psobj; - providerPath = dirResult.FullName; - path = wordContainsProviderId ? dirResult.PSPath : providerPath; - } - else - { - var baseObjAsString = baseObj as string; - if (baseObjAsString != null) - { - // The target provider is the FileSystem - providerPath = baseObjAsString; - path = wordContainsProviderId - ? FileSystemProvider.ProviderName + "::" + baseObjAsString - : providerPath; - } - } + foreach (var item in resolvedPaths) + { + var pathInfo = (PathInfo)item.BaseObject; + var dirInfo = new DirectoryInfo(pathInfo.ProviderPath); - if (path == null) continue; - if (isFileSystem && providerPath == null) continue; + bool baseQuotesNeeded = false; + string basePath; + if (!relativePaths) + { + if (pathInfo.Drive is null) + { + basePath = dirInfo.FullName; + } + else + { + int stringStartIndex = pathInfo.Drive.Root.EndsWith(provider.ItemSeparator) && pathInfo.Drive.Root.Length > 1 + ? pathInfo.Drive.Root.Length - 1 + : pathInfo.Drive.Root.Length; - string completionText; - if (relativePaths) - { - try - { - var sessionStateInternal = executionContext.EngineSessionState; - completionText = sessionStateInternal.NormalizeRelativePath(path, sessionStateInternal.CurrentLocation.ProviderPath); - string parentDirectory = ".." + StringLiterals.DefaultPathSeparator; - if (!completionText.StartsWith(parentDirectory, StringComparison.Ordinal)) - completionText = Path.Combine(".", completionText); - } - catch (Exception) - { - // The object at the specified path is not accessable, such as c:\hiberfil.sys (for hibernation) or c:\pagefile.sys (for paging) - // We ignore those files - continue; - } - } - else - { - completionText = path; - } + basePath = pathInfo.Drive.VolumeSeparatedByColon + ? string.Concat(pathInfo.Drive.Name, ":", dirInfo.FullName.AsSpan(stringStartIndex)) + : string.Concat(pathInfo.Drive.Name, dirInfo.FullName.AsSpan(stringStartIndex)); + } - if (ProviderSpecified(completionText) && !wordContainsProviderId) - { - // Remove the provider id from the path: cd \\scratch2\scratch\dongbw - var index = completionText.IndexOf(':'); - completionText = completionText.Substring(index + 2); - } + basePath = basePath.EndsWith(provider.ItemSeparator) + ? providerPrefix + basePath + : providerPrefix + basePath + provider.ItemSeparator; + basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); + } + else + { + basePath = null; + } + IEnumerable fileSystemObjects = containersOnly + ? dirInfo.EnumerateDirectories(filterText, enumerationOptions) + : dirInfo.EnumerateFileSystemInfos(filterText, enumerationOptions); - if (CompletionRequiresQuotes(completionText, !useLiteralPath)) - { - var quoteInUse = quote == string.Empty ? "'" : quote; - if (quoteInUse == "'") - { - completionText = completionText.Replace("'", "''"); - } - else - { - // When double quote is in use, we have to escape the backtip and '$' even when using literal path - // Get-Content -LiteralPath ".\a``g.txt" - completionText = completionText.Replace("`", "``"); - completionText = completionText.Replace("$", "`$"); - } + foreach (var entry in fileSystemObjects) + { + bool isContainer = entry.Attributes.HasFlag(FileAttributes.Directory); + if (!isContainer && includedExtensions is not null && !includedExtensions.Contains(entry.Extension)) + { + continue; + } - if (!useLiteralPath) - { - if (quoteInUse == "'") - { - completionText = completionText.Replace("[", "`["); - completionText = completionText.Replace("]", "`]"); - } - else - { - completionText = completionText.Replace("[", "``["); - completionText = completionText.Replace("]", "``]"); - } - } + var entryName = entry.Name; + if (wildcardFilter is not null && !wildcardFilter.IsMatch(entryName)) + { + continue; + } - completionText = quoteInUse + completionText + quoteInUse; - } - else if (quote != string.Empty) + if (basePath is null) + { + basePath = context.ExecutionContext.EngineSessionState.NormalizeRelativePath( + entry.FullName, + relativeBasePath); + if (!basePath.StartsWith($"..{provider.ItemSeparator}", StringComparison.Ordinal)) { - completionText = quote + completionText + quote; + basePath = $".{provider.ItemSeparator}{basePath}"; } - if (isFileSystem) + basePath = basePath.Remove(basePath.Length - entry.Name.Length); + basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); + } + + var resultType = isContainer + ? CompletionResultType.ProviderContainer + : CompletionResultType.ProviderItem; + + bool leafQuotesNeeded; + var completionText = NewPathCompletionText( + basePath, + EscapePath(entryName, stringType, literalPaths, out leafQuotesNeeded), + stringType, + containsNestedExpressions: false, + forceQuotes: baseQuotesNeeded || leafQuotesNeeded, + addAmpersand: false); + results.Add(new CompletionResult(completionText, entryName, resultType, entry.FullName)); + } + } + + return results; + } + + /// + /// Helper method for generating path completion results standard providers that don't need any special treatment. + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + /// + private static List GetDefaultProviderResults( + CompletionContext context, + ProviderInfo provider, + Collection resolvedPaths, + string filterText, + bool containersOnly, + bool relativePaths, + bool literalPaths, + bool inputUsedHome, + string providerPrefix, + StringConstantType stringType) + { + string homePath = inputUsedHome && !string.IsNullOrEmpty(provider.Home) + ? provider.Home + : null; + + var pattern = WildcardPattern.Get(filterText, WildcardOptions.IgnoreCase); + var results = new List(); + + foreach (var item in resolvedPaths) + { + var pathInfo = (PathInfo)item.BaseObject; + string baseTooltip = pathInfo.ProviderPath.Equals(string.Empty, StringComparison.Ordinal) + ? pathInfo.Path + : pathInfo.ProviderPath; + if (baseTooltip[^1] is not '\\' and not '/' and not ':') + { + baseTooltip += provider.ItemSeparator; + } + + _ = context.Helper.CurrentPowerShell + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") + .AddParameter("LiteralPath", pathInfo.Path); + + bool hadErrors; + var childItemOutput = context.Helper.ExecuteCurrentPowerShell(out _, out hadErrors); + + if (childItemOutput.Count == 1 && + (pathInfo.Provider.FullName + "::" + pathInfo.ProviderPath).EqualsOrdinalIgnoreCase(childItemOutput[0].Properties["PSPath"].Value as string)) + { + // Get-ChildItem returned the item itself instead of the children so there must be no child items to complete. + continue; + } + + var childrenInfoTable = new Dictionary(childItemOutput.Count); + var childNameList = new List(childItemOutput.Count); + + if (hadErrors) + { + // Get-ChildItem failed to get some items (Access denied or something) + // Save relevant info and try again to get just the names. + foreach (dynamic child in childItemOutput) + { + childrenInfoTable.Add(GetChildNameFromPsObject(child, provider.ItemSeparator), child.PSIsContainer); + } + + _ = context.Helper.CurrentPowerShell + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") + .AddParameter("LiteralPath", pathInfo.Path) + .AddParameter("Name"); + childItemOutput = context.Helper.ExecuteCurrentPowerShell(out _); + foreach (var child in childItemOutput) + { + var childName = (string)child.BaseObject; + childNameList.Add(childName); + } + } + else + { + foreach (dynamic child in childItemOutput) + { + var childName = GetChildNameFromPsObject(child, provider.ItemSeparator); + childrenInfoTable.Add(childName, child.PSIsContainer); + childNameList.Add(childName); + } + } + + if (childNameList.Count == 0) + { + continue; + } + + string basePath = providerPrefix.Length > 0 + ? string.Concat(providerPrefix, pathInfo.Path.AsSpan(providerPrefix.Length)) + : pathInfo.Path; + if (basePath[^1] is not '\\' and not '/' and not ':') + { + basePath += provider.ItemSeparator; + } + + if (relativePaths) + { + basePath = context.ExecutionContext.EngineSessionState.NormalizeRelativePath( + basePath + childNameList[0], context.ExecutionContext.SessionState.Internal.CurrentLocation.ProviderPath); + if (!basePath.StartsWith($"..{provider.ItemSeparator}", StringComparison.Ordinal)) + { + basePath = $".{provider.ItemSeparator}{basePath}"; + } + + basePath = basePath.Remove(basePath.Length - childNameList[0].Length); + } + + bool baseQuotesNeeded; + basePath = RebuildPathWithVars(basePath, homePath, stringType, literalPaths, out baseQuotesNeeded); + + foreach (var childName in childNameList) + { + if (!pattern.IsMatch(childName)) + { + continue; + } + + CompletionResultType resultType; + if (childrenInfoTable.TryGetValue(childName, out bool isContainer)) + { + if (containersOnly && !isContainer) { - // Use .NET APIs directly to reduce the time overhead - var isContainer = Directory.Exists(providerPath); - if (containerOnly && !isContainer) - continue; + continue; + } - if (!containerOnly && !isContainer && !CheckFileExtension(providerPath, extension)) - continue; + resultType = isContainer + ? CompletionResultType.ProviderContainer + : CompletionResultType.ProviderItem; + } + else + { + resultType = CompletionResultType.Text; + } + + bool leafQuotesNeeded; + var completionText = NewPathCompletionText( + basePath, + EscapePath(childName, stringType, literalPaths, out leafQuotesNeeded), + stringType, + containsNestedExpressions: false, + forceQuotes: baseQuotesNeeded || leafQuotesNeeded, + addAmpersand: false); + results.Add(new CompletionResult(completionText, childName, resultType, baseTooltip + childName)); + } + } + + return results; + } + + private static string GetChildNameFromPsObject(dynamic psObject, char separator) + { + if (((PSObject)psObject).BaseObject is string result) + { + // The "Get-ChildItem" call for this provider returned a string that we assume is the child name. + // This is what the SCCM provider returns. + return result; + } + + string childName = psObject.PSChildName; + if (childName is not null) + { + return childName; + } + + // Some providers (Like the variable provider) don't include a PSChildName property + // so we get the child name from the path instead. + childName = psObject.PSPath ?? string.Empty; + int ProviderSeparatorIndex = childName.IndexOf("::", StringComparison.Ordinal); + childName = childName.Substring(ProviderSeparatorIndex + 2); + int indexOfName = childName.LastIndexOf(separator); + if (indexOfName == -1 || indexOfName + 1 == childName.Length) + { + return childName; + } + + return childName.Substring(indexOfName + 1); + } + + /// + /// Takes a path and rebuilds it with the specified variable replacements. + /// Also escapes special characters as needed. + /// + private static string RebuildPathWithVars( + string path, + string homePath, + StringConstantType stringType, + bool literalPath, + out bool quotesAreNeeded) + { + var sb = new StringBuilder(path.Length); + int homeIndex = string.IsNullOrEmpty(homePath) + ? -1 + : path.IndexOf(homePath, StringComparison.OrdinalIgnoreCase); + quotesAreNeeded = false; + bool useSingleQuoteEscapeRules = stringType is StringConstantType.SingleQuoted or StringConstantType.BareWord; + + for (int i = 0; i < path.Length; i++) + { + // on Windows, we need to preserve the expanded home path as native commands don't understand it +#if UNIX + if (i == homeIndex) + { + _ = sb.Append('~'); + i += homePath.Length - 1; + continue; + } +#endif + + EscapeCharIfNeeded(sb, path, i, stringType, literalPath, useSingleQuoteEscapeRules, ref quotesAreNeeded); + _ = sb.Append(path[i]); + } + + return sb.ToString(); + } + + private static string EscapePath(string path, StringConstantType stringType, bool literalPath, out bool quotesAreNeeded) + { + var sb = new StringBuilder(path.Length); + bool useSingleQuoteEscapeRules = stringType is StringConstantType.SingleQuoted or StringConstantType.BareWord; + quotesAreNeeded = false; + + for (int i = 0; i < path.Length; i++) + { + EscapeCharIfNeeded(sb, path, i, stringType, literalPath, useSingleQuoteEscapeRules, ref quotesAreNeeded); + _ = sb.Append(path[i]); + } + + return sb.ToString(); + } + + private static void EscapeCharIfNeeded( + StringBuilder sb, + string path, + int index, + StringConstantType stringType, + bool literalPath, + bool useSingleQuoteEscapeRules, + ref bool quotesAreNeeded) + { + switch (path[index]) + { + case '#': + case '-': + case '@': + if (index == 0 && stringType == StringConstantType.BareWord) + { + // Chars that would start a new token when used as the first char in a bareword argument. + quotesAreNeeded = true; + } + break; - string tooltip = providerPath, listItemText = Path.GetFileName(providerPath); - results.Add(new CompletionResult(completionText, listItemText, - isContainer ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem, - tooltip)); + case ' ': + case ',': + case ';': + case '(': + case ')': + case '{': + case '}': + case '|': + case '&': + if (stringType == StringConstantType.BareWord) + { + // Chars that would start a new token when used anywhere in a bareword argument. + quotesAreNeeded = true; + } + break; + + case '[': + case ']': + if (!literalPath) + { + // Wildcard characters that need to be escaped. + int backtickCount; + if (useSingleQuoteEscapeRules) + { + backtickCount = 1; } else { - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item") - .AddParameter("LiteralPath", path); - var items = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (items != null && items.Count == 1) - { - dynamic item = items[0]; - var isContainer = LanguagePrimitives.ConvertTo(item.PSIsContainer); - - if (containerOnly && !isContainer) - continue; - - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Convert-Path") - .AddParameter("LiteralPath", item.PSPath); - var tooltips = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - string tooltip = null, listItemText = item.PSChildName; - if (tooltips != null && tooltips.Count == 1) - { - tooltip = PSObject.Base(tooltips[0]) as string; - } + backtickCount = sb[^1] == '`' ? 4 : 2; + } - if (string.IsNullOrEmpty(listItemText)) - { - // For provider items that don't have PSChildName values, such as variable::error - listItemText = item.Name; - } + _ = sb.Append('`', backtickCount); + quotesAreNeeded = true; + } + break; - results.Add(new CompletionResult(completionText, listItemText, - isContainer ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem, - tooltip ?? path)); - } - else - { - // We can get here when get-item fails, perhaps due an acl or whatever. - results.Add(new CompletionResult(completionText)); - } + case '`': + // Literal backtick needs to be escaped to not be treated as an escape character + if (useSingleQuoteEscapeRules) + { + if (!literalPath) + { + _ = sb.Append('`'); + } + } + else + { + int backtickCount = !literalPath && sb[^1] == '`' ? 3 : 1; + _ = sb.Append('`', backtickCount); + } + + if (stringType is StringConstantType.BareWord or StringConstantType.DoubleQuoted) + { + quotesAreNeeded = true; + } + break; + + case '$': + // $ needs to be escaped so following chars are not parsed as a variable/subexpression + if (!useSingleQuoteEscapeRules) + { + _ = sb.Append('`'); + } + + if (stringType is StringConstantType.BareWord or StringConstantType.DoubleQuoted) + { + quotesAreNeeded = true; + } + break; + + default: + if (useSingleQuoteEscapeRules) + { + // Bareword or singlequoted input string. + if (path[index].IsSingleQuote()) + { + // SingleQuotes are escaped with more single quotes. quotesAreNeeded is set so bareword strings can quoted. + _ = sb.Append('\''); + quotesAreNeeded = true; } + else if (!quotesAreNeeded && stringType == StringConstantType.BareWord && path[index].IsDoubleQuote()) + { + // Bareword string with double quote inside. Make sure to quote it so we don't need to escape it. + quotesAreNeeded = true; + } + } + else if (path[index].IsDoubleQuote()) + { + // Double quoted or bareword with variables input string. Need to escape double quotes. + _ = sb.Append('`'); + quotesAreNeeded = true; + } + break; + } + } + + private static string NewPathCompletionText(string parent, string leaf, StringConstantType stringType, bool containsNestedExpressions, bool forceQuotes, bool addAmpersand) + { + string result; + if (stringType == StringConstantType.SingleQuoted) + { + result = addAmpersand ? $"& '{parent}{leaf}'" : $"'{parent}{leaf}'"; + } + else if (stringType == StringConstantType.DoubleQuoted) + { + result = addAmpersand ? $"& \"{parent}{leaf}\"" : $"\"{parent}{leaf}\""; + } + else + { + if (forceQuotes) + { + if (containsNestedExpressions) + { + result = addAmpersand ? $"& \"{parent}{leaf}\"" : $"\"{parent}{leaf}\""; + } + else + { + result = addAmpersand ? $"& '{parent}{leaf}'" : $"'{parent}{leaf}'"; } } + else + { + result = string.Concat(parent, leaf); + } } - return results; + return result; } + private static readonly Regex s_shareMatch = new( + @"(^Microsoft\.PowerShell\.Core\\FileSystem::|^FileSystem::|^)(?:\\\\|//)(?![.|?])([^\\/]+)(?:\\|/)([^\\/]*)$", + RegexOptions.IgnoreCase | RegexOptions.Compiled); + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct SHARE_INFO_1 { @@ -4500,52 +5217,63 @@ private struct SHARE_INFO_1 public string remark; } - private const int MAX_PREFERRED_LENGTH = -1; - private const int NERR_Success = 0; - private const int ERROR_MORE_DATA = 234; - private const int STYPE_DISKTREE = 0; - private const int STYPE_MASK = 0x000000FF; - private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior }; - [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] - private static extern int NetShareEnum(string serverName, int level, out IntPtr bufptr, int prefMaxLen, - out uint entriesRead, out uint totalEntries, ref uint resumeHandle); - internal static List GetFileShares(string machine, bool ignoreHidden) { #if UNIX return new List(); #else - IntPtr shBuf; - uint numEntries; + nint shBuf = nint.Zero; + uint numEntries = 0; uint totalEntries; uint resumeHandle = 0; - int result = NetShareEnum(machine, 1, out shBuf, - MAX_PREFERRED_LENGTH, out numEntries, out totalEntries, - ref resumeHandle); - - var shares = new List(); - if (result == NERR_Success || result == ERROR_MORE_DATA) + try { - for (int i = 0; i < numEntries; ++i) + int result = Interop.Windows.NetShareEnum( + machine, + level: 1, + out shBuf, + Interop.Windows.MAX_PREFERRED_LENGTH, + out numEntries, + out totalEntries, + ref resumeHandle); + + var shares = new List(); + if (result == Interop.Windows.ERROR_SUCCESS || result == Interop.Windows.ERROR_MORE_DATA) { - IntPtr curInfoPtr = (IntPtr)((long)shBuf + (Marshal.SizeOf() * i)); - SHARE_INFO_1 shareInfo = Marshal.PtrToStructure(curInfoPtr); + for (int i = 0; i < numEntries; ++i) + { + nint curInfoPtr = shBuf + (Marshal.SizeOf() * i); + SHARE_INFO_1 shareInfo = Marshal.PtrToStructure(curInfoPtr); - if ((shareInfo.type & STYPE_MASK) != STYPE_DISKTREE) - continue; - if (ignoreHidden && shareInfo.netname.EndsWith('$')) - continue; - shares.Add(shareInfo.netname); + if ((shareInfo.type & Interop.Windows.STYPE_MASK) != Interop.Windows.STYPE_DISKTREE) + { + continue; + } + + if (ignoreHidden && shareInfo.netname.EndsWith('$')) + { + continue; + } + + shares.Add(shareInfo.netname); + } } - } - return shares; + return shares; + } + finally + { + if (shBuf != nint.Zero) + { + Interop.Windows.NetApiBufferFree(shBuf); + } + } #endif } @@ -4580,31 +5308,51 @@ public static IEnumerable CompleteVariable(string variableName return CompleteVariable(new CompletionContext { WordToComplete = variableName, Helper = helper, ExecutionContext = executionContext }); } - private static readonly string[] s_variableScopes = new string[] { "Global:", "Local:", "Script:", "Private:" }; + private static readonly string[] s_variableScopes = new string[] { "Global:", "Local:", "Script:", "Private:", "Using:" }; - private static readonly char[] s_charactersRequiringQuotes = new char[] { - '-', '`', '&', '@', '\'', '"', '#', '{', '}', '(', ')', '$', ',', ';', '|', '<', '>', ' ', '.', '\\', '/', '\t', '^', - }; + private static readonly SearchValues s_charactersRequiringQuotes = SearchValues.Create("-`&@'\"#{}()$,;|<> .\\/ \t^"); + + private static bool ContainsCharactersRequiringQuotes(ReadOnlySpan text) + => text.ContainsAny(s_charactersRequiringQuotes); internal static List CompleteVariable(CompletionContext context) { - HashSet hashedResults = new HashSet(StringComparer.OrdinalIgnoreCase); - List results = new List(); + HashSet hashedResults = new(StringComparer.OrdinalIgnoreCase); + List results = new(); + List tempResults = new(); var wordToComplete = context.WordToComplete; + string scopePrefix = string.Empty; var colon = wordToComplete.IndexOf(':'); + if (colon >= 0) + { + scopePrefix = wordToComplete.Remove(colon + 1); + wordToComplete = wordToComplete.Substring(colon + 1); + } - var lastAst = context.RelatedAsts?.Last(); + var lastAst = context.RelatedAsts?[^1]; var variableAst = lastAst as VariableExpressionAst; + if (lastAst is PropertyMemberAst || + (lastAst is not null && lastAst.Parent is ParameterAst parameter && parameter.DefaultValue != lastAst)) + { + // User is adding a new parameter or a class member, variable tab completion is not useful. + return results; + } var prefix = variableAst != null && variableAst.Splatted ? "@" : "$"; + bool tokenAtCursorUsedBraces = context.TokenAtCursor is not null && context.TokenAtCursor.Text.StartsWith("${"); // Look for variables in the input (e.g. parameters, etc.) before checking session state - these // variables might not exist in session state yet. var wildcardPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); - if (lastAst != null) + if (lastAst is not null) { Ast parent = lastAst.Parent; - var findVariablesVisitor = new FindVariablesVisitor { CompletionVariableAst = lastAst }; + var findVariablesVisitor = new FindVariablesVisitor + { + CompletionVariableAst = lastAst, + StopSearchOffset = lastAst.Extent.StartOffset, + Context = context.TypeInferenceContext + }; while (parent != null) { if (parent is IParameterMetadataProvider) @@ -4616,216 +5364,740 @@ internal static List CompleteVariable(CompletionContext contex parent = parent.Parent; } - foreach (Tuple varAst in findVariablesVisitor.VariableSources) + foreach (string varName in findVariablesVisitor.FoundVariables) { - Ast astTarget = null; - string userPath = null; + if (!wildcardPattern.IsMatch(varName)) + { + continue; + } - VariableExpressionAst variableDefinitionAst = varAst.Item2 as VariableExpressionAst; - if (variableDefinitionAst != null) + VariableInfo varInfo = findVariablesVisitor.VariableInfoTable[varName]; + PSTypeName varType = varInfo.LastDeclaredConstraint ?? varInfo.LastAssignedType; + string toolTip; + if (varType is null) { - userPath = varAst.Item1; - astTarget = varAst.Item2.Parent; + toolTip = varName; } else { - CommandAst commandParameterAst = varAst.Item2 as CommandAst; - if (commandParameterAst != null) - { - userPath = varAst.Item1; - astTarget = varAst.Item2; - } + toolTip = varType.Type is not null + ? StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(varType.Type, dropNamespaces: true), varName) + : varType.Name; } - if (string.IsNullOrEmpty(userPath)) - { - Diagnostics.Assert(false, "Found a variable source but it was an unknown AST type."); - } + var completionText = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(varName) + ? prefix + scopePrefix + varName + : prefix + "{" + scopePrefix + varName + "}"; + AddUniqueVariable(hashedResults, results, completionText, varName, toolTip); + } + } - if (wildcardPattern.IsMatch(userPath)) + if (colon == -1) + { + var allVariables = context.ExecutionContext.SessionState.Internal.GetVariableTable(); + foreach (var key in allVariables.Keys) + { + if (wildcardPattern.IsMatch(key)) { - var completedName = (userPath.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + userPath - : prefix + "{" + userPath + "}"; - var tooltip = userPath; - var ast = astTarget; - - while (ast != null) + var variable = allVariables[key]; + var name = variable.Name; + var value = variable.Value; + var toolTip = value is null + ? key + : StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(value.GetType(), dropNamespaces: true), key); + if (!string.IsNullOrEmpty(variable.Description)) { - var parameterAst = ast as ParameterAst; - if (parameterAst != null) - { - var typeConstraint = parameterAst.Attributes.OfType().FirstOrDefault(); - if (typeConstraint != null) - { - tooltip = StringUtil.Format("{0}${1}", typeConstraint.Extent.Text, userPath); - } - - break; - } - - var assignmentAst = ast.Parent as AssignmentStatementAst; - if (assignmentAst != null) - { - if (assignmentAst.Left == ast) - { - tooltip = ast.Extent.Text; - } - - break; - } - - var commandAst = ast as CommandAst; - if (commandAst != null) - { - PSTypeName discoveredType = AstTypeInference.InferTypeOf(ast, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).FirstOrDefault(); - if (discoveredType != null) - { - tooltip = StringUtil.Format("[{0}]${1}", discoveredType.Name, userPath); - } - - break; - } - - ast = ast.Parent; + toolTip += $" - {variable.Description}"; } - AddUniqueVariable(hashedResults, results, completedName, userPath, tooltip); + var completionText = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(name) + ? prefix + name + : prefix + "{" + name + "}"; + AddUniqueVariable(hashedResults, tempResults, completionText, key, toolTip); } } - } - string pattern; - string provider; - if (colon == -1) - { - pattern = "variable:" + wordToComplete + "*"; - provider = string.Empty; + if (tempResults.Count > 0) + { + results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase)); + tempResults.Clear(); + } } else { - provider = wordToComplete.Substring(0, colon + 1); - if (s_variableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) + string pattern; + if (s_variableScopes.Contains(scopePrefix, StringComparer.OrdinalIgnoreCase)) { - pattern = string.Concat("variable:", wordToComplete.AsSpan(colon + 1), "*"); + pattern = string.Concat("variable:", wordToComplete, "*"); } else { - pattern = wordToComplete + "*"; + pattern = scopePrefix + wordToComplete + "*"; } - } - - var powerShellExecutionHelper = context.Helper; - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", pattern) - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); - Exception exceptionThrown; - var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) - { - foreach (dynamic psobj in psobjs) + var powerShellExecutionHelper = context.Helper; + powerShellExecutionHelper + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", pattern) + .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); + + var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); + + if (psobjs is not null) { - var name = psobj.Name as string; - if (!string.IsNullOrEmpty(name)) + foreach (dynamic psobj in psobjs) { - var tooltip = name; - var variable = PSObject.Base(psobj) as PSVariable; - if (variable != null) + var name = psobj.Name as string; + if (!string.IsNullOrEmpty(name)) { - var value = variable.Value; - if (value != null) + var tooltip = name; + var variable = PSObject.Base(psobj) as PSVariable; + if (variable != null) { - tooltip = StringUtil.Format("[{0}]${1}", - ToStringCodeMethods.Type(value.GetType(), - dropNamespaces: true), name); + var value = variable.Value; + if (value != null) + { + tooltip = StringUtil.Format("[{0}]${1}", + ToStringCodeMethods.Type(value.GetType(), + dropNamespaces: true), name); + } + + if (!string.IsNullOrEmpty(variable.Description)) + { + tooltip += $" - {variable.Description}"; + } } - } - var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + provider + name - : prefix + "{" + provider + name + "}"; - AddUniqueVariable(hashedResults, results, completedName, name, tooltip); + var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(name) + ? prefix + scopePrefix + name + : prefix + "{" + scopePrefix + name + "}"; + AddUniqueVariable(hashedResults, results, completedName, name, tooltip); + } } } } if (colon == -1 && "env".StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) { - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", "env:*") - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Key"); + var envVars = Environment.GetEnvironmentVariables(); + foreach (var key in envVars.Keys) + { + var name = "env:" + key; + var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(name) + ? prefix + name + : prefix + "{" + name + "}"; + AddUniqueVariable(hashedResults, tempResults, completedName, name, "[string]" + name); + } + + results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase)); + tempResults.Clear(); + } - psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + if (colon == -1) + { + // Return variables already in session state first, because we can sometimes give better information, + // like the variables type. + foreach (var specialVariable in s_specialVariablesCache.Value) { - foreach (dynamic psobj in psobjs) + if (wildcardPattern.IsMatch(specialVariable)) { - var name = psobj.Name as string; - if (!string.IsNullOrEmpty(name)) - { - name = "env:" + name; - var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + name - : prefix + "{" + name + "}"; - AddUniqueVariable(hashedResults, results, completedName, name, "[string]" + name); - } + var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(specialVariable) + ? prefix + specialVariable + : prefix + "{" + specialVariable + "}"; + + AddUniqueVariable(hashedResults, results, completedName, specialVariable, specialVariable); + } + } + + var allDrives = context.ExecutionContext.SessionState.Drive.GetAll(); + foreach (var drive in allDrives) + { + if (drive.Name.Length < 2 + || !wildcardPattern.IsMatch(drive.Name) + || !drive.Provider.ImplementingType.IsAssignableTo(typeof(IContentCmdletProvider))) + { + continue; } + + var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(drive.Name) + ? prefix + drive.Name + ":" + : prefix + "{" + drive.Name + ":}"; + var tooltip = string.IsNullOrEmpty(drive.Description) + ? drive.Name + : drive.Description; + AddUniqueVariable(hashedResults, tempResults, completedName, drive.Name, tooltip); + } + + if (tempResults.Count > 0) + { + results.AddRange(tempResults.OrderBy(item => item.ListItemText, StringComparer.OrdinalIgnoreCase)); + } + + foreach (var scope in s_variableScopes) + { + if (wildcardPattern.IsMatch(scope)) + { + var completedName = !tokenAtCursorUsedBraces && !ContainsCharactersRequiringQuotes(scope) + ? prefix + scope + : prefix + "{" + scope + "}"; + AddUniqueVariable(hashedResults, results, completedName, scope, scope); + } + } + } + + return results; + } + + private static void AddUniqueVariable(HashSet hashedResults, List results, string completionText, string listItemText, string tooltip) + { + if (hashedResults.Add(completionText)) + { + results.Add(new CompletionResult(completionText, listItemText, CompletionResultType.Variable, tooltip)); + } + } + + internal static readonly HashSet s_varModificationCommands = new(StringComparer.OrdinalIgnoreCase) + { + "New-Variable", + "nv", + "Set-Variable", + "set", + "sv" + }; + + internal static readonly string[] s_varModificationParameters = new string[] + { + "Name", + "Value" + }; + + internal static readonly string[] s_outVarParameters = new string[] + { + "ErrorVariable", + "ev", + "WarningVariable", + "wv", + "InformationVariable", + "iv", + "OutVariable", + "ov", + + }; + + internal static readonly string[] s_pipelineVariableParameters = new string[] + { + "PipelineVariable", + "pv" + }; + + internal static readonly HashSet s_localScopeCommandNames = new(StringComparer.OrdinalIgnoreCase) + { + "Microsoft.PowerShell.Core\\ForEach-Object", + "ForEach-Object", + "foreach", + "%", + "Microsoft.PowerShell.Core\\Where-Object", + "Where-Object", + "where", + "?", + "BeforeAll", + "BeforeEach" + }; + + private sealed class VariableInfo + { + internal PSTypeName LastDeclaredConstraint; + internal PSTypeName LastAssignedType; + } + + private sealed class FindVariablesVisitor : AstVisitor2 + { + internal Ast Top; + internal Ast CompletionVariableAst; + internal readonly List FoundVariables = new(); + internal readonly Dictionary VariableInfoTable = new(StringComparer.OrdinalIgnoreCase); + internal int StopSearchOffset; + internal TypeInferenceContext Context; + + private static PSTypeName GetInferredVarTypeFromAst(Ast ast) + { + PSTypeName type; + switch (ast) + { + case ConstantExpressionAst constant: + type = new PSTypeName(constant.StaticType); + break; + + case ExpandableStringExpressionAst: + type = new PSTypeName(typeof(string)); + break; + + case ConvertExpressionAst convertExpression: + type = new PSTypeName(convertExpression.Type.TypeName); + break; + + case HashtableAst: + type = new PSTypeName(typeof(Hashtable)); + break; + + case ArrayExpressionAst: + case ArrayLiteralAst: + type = new PSTypeName(typeof(object[])); + break; + + case ScriptBlockExpressionAst: + type = new PSTypeName(typeof(ScriptBlock)); + break; + + default: + type = null; + break; } + + return type; } - // Return variables already in session state first, because we can sometimes give better information, - // like the variables type. - foreach (var specialVariable in s_specialVariablesCache.Value) + private void SaveVariableInfo(string variableName, PSTypeName variableType, bool isConstraint) { - if (wildcardPattern.IsMatch(specialVariable)) + if (VariableInfoTable.TryGetValue(variableName, out VariableInfo varInfo)) { - var completedName = (specialVariable.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + specialVariable - : prefix + "{" + specialVariable + "}"; + if (isConstraint) + { + varInfo.LastDeclaredConstraint = variableType; + } + else + { + varInfo.LastAssignedType = variableType; + } + } + else + { + varInfo = isConstraint + ? new VariableInfo() { LastDeclaredConstraint = variableType } + : new VariableInfo() { LastAssignedType = variableType }; + VariableInfoTable.Add(variableName, varInfo); + FoundVariables.Add(variableName); + } + } - AddUniqueVariable(hashedResults, results, completedName, specialVariable, specialVariable); + public override AstVisitAction DefaultVisit(Ast ast) + { + if (ast.Extent.StartOffset > StopSearchOffset) + { + // When visiting do while/until statements, the condition will be visited before the statement block. + // The condition itself may not be interesting if it's after the cursor, but the statement block could be. + return ast is PipelineBaseAst && ast.Parent is DoUntilStatementAst or DoWhileStatementAst + ? AstVisitAction.SkipChildren + : AstVisitAction.StopVisit; } + + return AstVisitAction.Continue; } - if (colon == -1) + public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { - // If no drive was specified, then look for matching drives/scopes - pattern = wordToComplete + "*"; - powerShellExecutionHelper - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive").AddParameter("Name", pattern) - .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); - psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); - if (psobjs != null) + if (assignmentStatementAst.Extent.StartOffset > StopSearchOffset) { - foreach (var psobj in psobjs) + return assignmentStatementAst.Parent is DoUntilStatementAst or DoWhileStatementAst ? + AstVisitAction.SkipChildren + : AstVisitAction.StopVisit; + } + + ProcessAssignmentLeftSide(assignmentStatementAst.Left, assignmentStatementAst.Right); + return AstVisitAction.Continue; + } + + private void ProcessAssignmentLeftSide(ExpressionAst left, StatementAst right) + { + if (left is AttributedExpressionAst attributedExpression) + { + var firstConvertExpression = attributedExpression as ConvertExpressionAst; + ExpressionAst child = attributedExpression.Child; + while (child is AttributedExpressionAst attributeChild) + { + if (firstConvertExpression is null && attributeChild is ConvertExpressionAst convertExpression) + { + // Multiple type constraint can be set on a variable like this: [int] [string] $Var1 = 1 + // But it's the left most type constraint that determines the final type. + firstConvertExpression = convertExpression; + } + + child = attributeChild.Child; + } + + if (child is VariableExpressionAst variableExpression) + { + if (variableExpression == CompletionVariableAst || s_specialVariablesCache.Value.Contains(variableExpression.VariablePath.UserPath)) + { + return; + } + + if (firstConvertExpression is not null) + { + SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, new PSTypeName(firstConvertExpression.Type.TypeName), isConstraint: true); + } + else + { + PSTypeName lastAssignedType = right is CommandExpressionAst commandExpression + ? GetInferredVarTypeFromAst(commandExpression.Expression) + : null; + SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, lastAssignedType, isConstraint: false); + } + } + } + else if (left is VariableExpressionAst variableExpression) + { + if (variableExpression == CompletionVariableAst || s_specialVariablesCache.Value.Contains(variableExpression.VariablePath.UserPath)) + { + return; + } + + PSTypeName lastAssignedType; + if (right is CommandExpressionAst commandExpression) + { + lastAssignedType = GetInferredVarTypeFromAst(commandExpression.Expression); + } + else + { + lastAssignedType = null; + } + + SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, lastAssignedType, isConstraint: false); + } + else if (left is ArrayLiteralAst array) + { + foreach (ExpressionAst expression in array.Elements) + { + ProcessAssignmentLeftSide(expression, right); + } + } + else if (left is ParenExpressionAst parenExpression) + { + ExpressionAst pureExpression = parenExpression.Pipeline.GetPureExpression(); + if (pureExpression is not null) + { + ProcessAssignmentLeftSide(pureExpression, right); + } + } + } + + public override AstVisitAction VisitCommand(CommandAst commandAst) + { + if (commandAst.Extent.StartOffset > StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + var commandName = commandAst.GetCommandName(); + if (commandName is not null && s_varModificationCommands.Contains(commandName)) + { + StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, resolve: false, s_varModificationParameters); + if (bindingResult is not null + && bindingResult.BoundParameters.TryGetValue("Name", out ParameterBindingResult variableName)) + { + var nameValue = variableName.ConstantValue as string; + if (nameValue is not null) + { + PSTypeName variableType; + if (bindingResult.BoundParameters.TryGetValue("Value", out ParameterBindingResult variableValue)) + { + variableType = GetInferredVarTypeFromAst(variableValue.Value); + } + else + { + variableType = null; + } + + SaveVariableInfo(nameValue, variableType, isConstraint: false); + } + } + } + + var bindResult = StaticParameterBinder.BindCommand(commandAst, resolve: false); + if (bindResult is not null) + { + foreach (var parameterName in s_outVarParameters) { - var driveInfo = PSObject.Base(psobj) as PSDriveInfo; - if (driveInfo != null) + if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult outVarBind)) { - var name = driveInfo.Name; - if (name != null && !string.IsNullOrWhiteSpace(name) && name.Length > 1) + var varName = outVarBind.ConstantValue as string; + if (varName is not null) { - var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + name + ":" - : prefix + "{" + name + ":}"; + SaveVariableInfo(varName, new PSTypeName(typeof(ArrayList)), isConstraint: false); + } + } + } - var tooltip = string.IsNullOrEmpty(driveInfo.Description) ? name : driveInfo.Description; - AddUniqueVariable(hashedResults, results, completedName, name, tooltip); + if (commandAst.Parent is PipelineAst pipeline && pipeline.Extent.EndOffset > CompletionVariableAst.Extent.StartOffset) + { + foreach (var parameterName in s_pipelineVariableParameters) + { + if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult pipeVarBind)) + { + var varName = pipeVarBind.ConstantValue as string; + if (varName is not null) + { + var inferredTypes = AstTypeInference.InferTypeOf(commandAst, Context, TypeInferenceRuntimePermissions.AllowSafeEval); + PSTypeName varType = inferredTypes.Count == 0 + ? null + : inferredTypes[0]; + SaveVariableInfo(varName, varType, isConstraint: false); + } } } } } - var scopePattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); - foreach (var scope in s_variableScopes) + foreach (RedirectionAst redirection in commandAst.Redirections) { - if (scopePattern.IsMatch(scope)) + if (redirection is FileRedirectionAst fileRedirection + && fileRedirection.Location is StringConstantExpressionAst redirectTarget + && redirectTarget.Value.StartsWith("variable:", StringComparison.OrdinalIgnoreCase) + && redirectTarget.Value.Length > "variable:".Length) { - var completedName = (scope.IndexOfAny(s_charactersRequiringQuotes) == -1) - ? prefix + scope - : prefix + "{" + scope + "}"; - AddUniqueVariable(hashedResults, results, completedName, scope, scope); + string varName = redirectTarget.Value.Substring("variable:".Length); + PSTypeName varType; + switch (fileRedirection.FromStream) + { + case RedirectionStream.Error: + varType = new PSTypeName(typeof(ErrorRecord)); + break; + + case RedirectionStream.Warning: + varType = new PSTypeName(typeof(WarningRecord)); + break; + + case RedirectionStream.Verbose: + varType = new PSTypeName(typeof(VerboseRecord)); + break; + + case RedirectionStream.Debug: + varType = new PSTypeName(typeof(DebugRecord)); + break; + + case RedirectionStream.Information: + varType = new PSTypeName(typeof(InformationRecord)); + break; + + default: + varType = null; + break; + } + + SaveVariableInfo(varName, varType, isConstraint: false); + } + } + + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitParameter(ParameterAst parameterAst) + { + if (parameterAst.Extent.StartOffset > StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + VariableExpressionAst variableExpression = parameterAst.Name; + if (variableExpression == CompletionVariableAst) + { + return AstVisitAction.Continue; + } + + SaveVariableInfo(variableExpression.VariablePath.UnqualifiedPath, new PSTypeName(parameterAst.StaticType), isConstraint: true); + + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) + { + if (forEachStatementAst.Extent.StartOffset > StopSearchOffset || forEachStatementAst.Variable == CompletionVariableAst) + { + return AstVisitAction.StopVisit; + } + + SaveVariableInfo(forEachStatementAst.Variable.VariablePath.UnqualifiedPath, variableType: null, isConstraint: false); + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitAttribute(AttributeAst attributeAst) + { + // Attributes can't assign values to variables so they aren't interesting. + return AstVisitAction.SkipChildren; + } + + public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) + { + return functionDefinitionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; + } + + public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) + { + if (scriptBlockExpressionAst == Top) + { + return AstVisitAction.Continue; + } + + Ast parent = scriptBlockExpressionAst.Parent; + // This loop checks if the scriptblock is used as a command, or an argument for a command, eg: ForEach-Object -Process {$Var1 = "Hello"}, {Var2 = $true} + while (true) + { + if (parent is CommandAst cmdAst) + { + string cmdName = cmdAst.GetCommandName(); + return s_localScopeCommandNames.Contains(cmdName) + || (cmdAst.CommandElements[0] is ScriptBlockExpressionAst && cmdAst.InvocationOperator == TokenKind.Dot) + ? AstVisitAction.Continue + : AstVisitAction.SkipChildren; + } + + if (parent is not CommandExpressionAst and not PipelineAst and not StatementBlockAst and not ArrayExpressionAst and not ArrayLiteralAst) + { + return AstVisitAction.SkipChildren; + } + + parent = parent.Parent; + } + } + + public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) + { + if (dataStatementAst.Extent.StartOffset >= StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + if (dataStatementAst.Variable is not null) + { + SaveVariableInfo(dataStatementAst.Variable, variableType: null, isConstraint: false); + } + + return AstVisitAction.SkipChildren; + } + } + + private static readonly Lazy> s_specialVariablesCache = new(BuildSpecialVariablesCache); + + private static SortedSet BuildSpecialVariablesCache() + { + var result = new SortedSet(StringComparer.OrdinalIgnoreCase); + foreach (var member in typeof(SpecialVariables).GetFields(BindingFlags.NonPublic | BindingFlags.Static)) + { + if (member.FieldType.Equals(typeof(string))) + { + result.Add((string)member.GetValue(null)); + } + } + + return result; + } + + internal static PSTypeName GetLastDeclaredTypeConstraint(VariableExpressionAst variableAst, TypeInferenceContext typeInferenceContext) + { + Ast parent = variableAst.Parent; + var findVariablesVisitor = new FindVariablesVisitor() + { + CompletionVariableAst = variableAst, + StopSearchOffset = variableAst.Extent.StartOffset, + Context = typeInferenceContext + }; + while (parent != null) + { + if (parent is IParameterMetadataProvider) + { + findVariablesVisitor.Top = parent; + parent.Visit(findVariablesVisitor); + } + + if (findVariablesVisitor.VariableInfoTable.TryGetValue(variableAst.VariablePath.UserPath, out VariableInfo varInfo) + && varInfo.LastDeclaredConstraint is not null) + { + return varInfo.LastDeclaredConstraint; + } + + parent = parent.Parent; + } + + return null; + } + + #endregion Variables + + #region Comments + + internal static List CompleteComment(CompletionContext context, ref int replacementIndex, ref int replacementLength) + { + if (context.WordToComplete.StartsWith("<#", StringComparison.Ordinal)) + { + return CompleteCommentHelp(context, ref replacementIndex, ref replacementLength); + } + + // Complete #requires statements + if (context.WordToComplete.StartsWith("#requires ", StringComparison.OrdinalIgnoreCase)) + { + return CompleteRequires(context, ref replacementIndex, ref replacementLength); + } + + var results = new List(); + + // Complete the history entries + Match matchResult = Regex.Match(context.WordToComplete, @"^#([\w\-]*)$"); + if (!matchResult.Success) + { + return results; + } + + string wordToComplete = matchResult.Groups[1].Value; + Collection psobjs; + + int entryId; + if (Regex.IsMatch(wordToComplete, @"^[0-9]+$") && LanguagePrimitives.TryConvertTo(wordToComplete, out entryId)) + { + context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)).AddParameter("Id", entryId); + psobjs = context.Helper.ExecuteCurrentPowerShell(out _); + + if (psobjs != null && psobjs.Count == 1) + { + var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo; + if (historyInfo != null) + { + var commandLine = historyInfo.CommandLine; + if (!string.IsNullOrEmpty(commandLine)) + { + // var tooltip = "Id: " + historyInfo.Id + "\n" + + // "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" + + // "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" + + // "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n"; + // Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts + results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine)); + } + } + } + + return results; + } + + wordToComplete = "*" + wordToComplete + "*"; + context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)); + + psobjs = context.Helper.ExecuteCurrentPowerShell(out _); + var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); + + if (psobjs != null) + { + for (int index = psobjs.Count - 1; index >= 0; index--) + { + var psobj = psobjs[index]; + if (PSObject.Base(psobj) is not HistoryInfo historyInfo) continue; + + var commandLine = historyInfo.CommandLine; + if (!string.IsNullOrEmpty(commandLine) && pattern.IsMatch(commandLine)) + { + // var tooltip = "Id: " + historyInfo.Id + "\n" + + // "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" + + // "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" + + // "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n"; + // Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts + results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine)); } } } @@ -4833,161 +6105,493 @@ internal static List CompleteVariable(CompletionContext contex return results; } - private static void AddUniqueVariable(HashSet hashedResults, List results, string completionText, string listItemText, string tooltip) + private static List CompleteRequires(CompletionContext context, ref int replacementIndex, ref int replacementLength) { - if (!hashedResults.Contains(completionText)) + var results = new List(); + + int cursorIndex = context.CursorPosition.ColumnNumber - 1; + string lineToCursor = context.CursorPosition.Line.Substring(0, cursorIndex); + + // RunAsAdministrator must be the last parameter in a Requires statement so no completion if the cursor is after the parameter. + if (lineToCursor.Contains(" -RunAsAdministrator", StringComparison.OrdinalIgnoreCase)) { - hashedResults.Add(completionText); - results.Add(new CompletionResult(completionText, listItemText, CompletionResultType.Variable, tooltip)); + return results; + } + + // Regex to find parameter like " -Parameter1" or " -" + MatchCollection hashtableKeyMatches = Regex.Matches(lineToCursor, @"\s+-([A-Za-z]+|$)"); + if (hashtableKeyMatches.Count == 0) + { + return results; + } + + Group currentParameterMatch = hashtableKeyMatches[^1].Groups[1]; + + // Complete the parameter if the cursor is at a parameter + if (currentParameterMatch.Index + currentParameterMatch.Length == cursorIndex) + { + string currentParameterPrefix = currentParameterMatch.Value; + + replacementIndex = context.CursorPosition.Offset - currentParameterPrefix.Length; + replacementLength = currentParameterPrefix.Length; + + // Produce completions for all parameters that begin with the prefix we've found, + // but which haven't already been specified in the line we need to complete + foreach (string parameter in s_requiresParameters) + { + if (parameter.StartsWith(currentParameterPrefix, StringComparison.OrdinalIgnoreCase) + && !context.CursorPosition.Line.Contains($" -{parameter}", StringComparison.OrdinalIgnoreCase)) + { + string toolTip = GetRequiresParametersToolTip(parameter); + results.Add(new CompletionResult(parameter, parameter, CompletionResultType.ParameterName, toolTip)); + } + } + + return results; + } + + // Regex to find parameter values (any text that appears after various delimiters) + hashtableKeyMatches = Regex.Matches(lineToCursor, @"(\s+|,|;|{|\""|'|=)(\w+|$)"); + string currentValue; + if (hashtableKeyMatches.Count == 0) + { + currentValue = string.Empty; + } + else + { + currentValue = hashtableKeyMatches[^1].Groups[2].Value; + } + + replacementIndex = context.CursorPosition.Offset - currentValue.Length; + replacementLength = currentValue.Length; + + // Complete PSEdition parameter values + if (currentParameterMatch.Value.Equals("PSEdition", StringComparison.OrdinalIgnoreCase)) + { + foreach (string psEditionEntry in s_requiresPSEditions) + { + if (psEditionEntry.StartsWith(currentValue, StringComparison.OrdinalIgnoreCase)) + { + string toolTip = GetRequiresPsEditionsToolTip(psEditionEntry); + results.Add(new CompletionResult(psEditionEntry, psEditionEntry, CompletionResultType.ParameterValue, toolTip)); + } + } + + return results; + } + + // Complete Modules module specification values + if (currentParameterMatch.Value.Equals("Modules", StringComparison.OrdinalIgnoreCase)) + { + int hashtableStart = lineToCursor.LastIndexOf("@{"); + int hashtableEnd = lineToCursor.LastIndexOf('}'); + + bool insideHashtable = hashtableStart != -1 && (hashtableEnd == -1 || hashtableEnd < hashtableStart); + + // If not inside a hashtable, try to complete a module simple name + if (!insideHashtable) + { + context.WordToComplete = currentValue; + return CompleteModuleName(context, true); + } + + string hashtableString = lineToCursor.Substring(hashtableStart); + + // Regex to find hashtable keys with or without quotes + hashtableKeyMatches = Regex.Matches(hashtableString, @"(@{|;)\s*(?:'|\""|\w*)\w*"); + + // Build the list of keys we might want to complete, based on what's already been provided + var moduleSpecKeysToComplete = new HashSet(s_requiresModuleSpecKeys); + bool sawModuleNameLast = false; + foreach (Match existingHashtableKeyMatch in hashtableKeyMatches) + { + string existingHashtableKey = existingHashtableKeyMatch.Value.TrimStart(s_hashtableKeyPrefixes); + + if (string.IsNullOrEmpty(existingHashtableKey)) + { + continue; + } + + // Remove the existing key we just saw + moduleSpecKeysToComplete.Remove(existingHashtableKey); + + // We need to remember later if we saw "ModuleName" as the last hashtable key, for completions + if (sawModuleNameLast = existingHashtableKey.Equals("ModuleName", StringComparison.OrdinalIgnoreCase)) + { + continue; + } + + // "RequiredVersion" is mutually exclusive with "ModuleVersion" and "MaximumVersion" + if (existingHashtableKey.Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase) + || existingHashtableKey.Equals("MaximumVersion", StringComparison.OrdinalIgnoreCase)) + { + moduleSpecKeysToComplete.Remove("RequiredVersion"); + continue; + } + + if (existingHashtableKey.Equals("RequiredVersion", StringComparison.OrdinalIgnoreCase)) + { + moduleSpecKeysToComplete.Remove("ModuleVersion"); + moduleSpecKeysToComplete.Remove("MaximumVersion"); + continue; + } + } + + Group lastHashtableKeyPrefixGroup = hashtableKeyMatches[^1].Groups[0]; + + // If we're not completing a key for the hashtable, try to complete module names, but nothing else + bool completingHashtableKey = lastHashtableKeyPrefixGroup.Index + lastHashtableKeyPrefixGroup.Length == hashtableString.Length; + if (!completingHashtableKey) + { + if (sawModuleNameLast) + { + context.WordToComplete = currentValue; + return CompleteModuleName(context, true); + } + + return results; + } + + // Now try to complete hashtable keys + foreach (string moduleSpecKey in moduleSpecKeysToComplete) + { + if (moduleSpecKey.StartsWith(currentValue, StringComparison.OrdinalIgnoreCase)) + { + string toolTip = GetRequiresModuleSpecKeysToolTip(moduleSpecKey); + results.Add(new CompletionResult(moduleSpecKey, moduleSpecKey, CompletionResultType.ParameterValue, toolTip)); + } + } } + + return results; } - private class FindVariablesVisitor : AstVisitor + private static readonly string[] s_requiresParameters = new string[] + { + "Modules", + "PSEdition", + "RunAsAdministrator", + "Version" + }; + + private static string GetRequiresParametersToolTip(string name) => name switch + { + "Modules" => TabCompletionStrings.RequiresModulesParameterDescription, + "PSEdition" => TabCompletionStrings.RequiresPSEditionParameterDescription, + "RunAsAdministrator" => TabCompletionStrings.RequiresRunAsAdministratorParameterDescription, + "Version" => TabCompletionStrings.RequiresVersionParameterDescription, + _ => string.Empty + }; + + private static readonly string[] s_requiresPSEditions = new string[] + { + "Core", + "Desktop" + }; + + private static string GetRequiresPsEditionsToolTip(string name) => name switch + { + "Core" => TabCompletionStrings.RequiresPsEditionCoreDescription, + "Desktop" => TabCompletionStrings.RequiresPsEditionDesktopDescription, + _ => string.Empty + }; + + private static readonly string[] s_requiresModuleSpecKeys = new string[] + { + "GUID", + "MaximumVersion", + "ModuleName", + "ModuleVersion", + "RequiredVersion" + }; + + private static string GetRequiresModuleSpecKeysToolTip(string name) => name switch + { + "GUID" => TabCompletionStrings.RequiresModuleSpecGUIDDescription, + "MaximumVersion" => TabCompletionStrings.RequiresModuleSpecMaximumVersionDescription, + "ModuleName" => TabCompletionStrings.RequiresModuleSpecModuleNameDescription, + "ModuleVersion" => TabCompletionStrings.RequiresModuleSpecModuleVersionDescription, + "RequiredVersion" => TabCompletionStrings.RequiresModuleSpecRequiredVersionDescription, + _ => string.Empty + }; + + private static readonly char[] s_hashtableKeyPrefixes = new[] + { + '@', + '{', + ';', + '"', + '\'', + ' ', + }; + + private static List CompleteCommentHelp(CompletionContext context, ref int replacementIndex, ref int replacementLength) { - internal Ast Top; - internal Ast CompletionVariableAst; - internal readonly List> VariableSources = new List>(); + // Finds comment keywords like ".DESCRIPTION" + MatchCollection usedKeywords = Regex.Matches(context.TokenAtCursor.Text, @"(?<=^\s*\.)\w*", RegexOptions.Multiline); + if (usedKeywords.Count == 0) + { + return null; + } - public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) + // Last keyword at or before the cursor + Match lineKeyword = null; + for (int i = usedKeywords.Count - 1; i >= 0; i--) { - if (variableExpressionAst != CompletionVariableAst) + Match keyword = usedKeywords[i]; + if (context.CursorPosition.Offset >= keyword.Index + context.TokenAtCursor.Extent.StartOffset) { - VariableSources.Add(new Tuple(variableExpressionAst.VariablePath.UserPath, variableExpressionAst)); + lineKeyword = keyword; + break; } + } - return AstVisitAction.Continue; + if (lineKeyword is null) + { + return null; } - public override AstVisitAction VisitCommand(CommandAst commandAst) + // Cursor is within or at the start/end of the keyword + if (context.CursorPosition.Offset <= lineKeyword.Index + lineKeyword.Length + context.TokenAtCursor.Extent.StartOffset) { - // MSFT: 784739 Stack overflow during tab completion of pipeline variable - // $null | % -pv p { $p -> In this case $p is pipelinevariable - // and is used in the same command. PipelineVariables are not available - // in the command they are assigned in. Hence the following code ignores - // if the variable being completed is in the command extent. - if ((commandAst != CompletionVariableAst) && (!CompletionVariableAst.Extent.IsWithin(commandAst.Extent))) - { - string[] desiredParameters = new string[] { "PV", "PipelineVariable", "OV", "OutVariable" }; + replacementIndex = context.TokenAtCursor.Extent.StartOffset + lineKeyword.Index; + replacementLength = lineKeyword.Value.Length; - StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, desiredParameters); - if (bindingResult != null) + var validKeywords = new HashSet(s_commentHelpKeywords, StringComparer.OrdinalIgnoreCase); + foreach (Match keyword in usedKeywords) + { + if (keyword == lineKeyword || s_commentHelpAllowedDuplicateKeywords.Contains(keyword.Value)) { - ParameterBindingResult parameterBindingResult; + continue; + } - foreach (string commandVariableParameter in desiredParameters) - { - if (bindingResult.BoundParameters.TryGetValue(commandVariableParameter, out parameterBindingResult)) - { - VariableSources.Add(new Tuple((string)parameterBindingResult.ConstantValue, commandAst)); - } - } + validKeywords.Remove(keyword.Value); + } + + var result = new List(); + foreach (string keyword in validKeywords) + { + if (keyword.StartsWith(lineKeyword.Value, StringComparison.OrdinalIgnoreCase)) + { + string toolTip = GetCommentHelpKeywordsToolTip(keyword); + result.Add(new CompletionResult(keyword, keyword, CompletionResultType.Keyword, toolTip)); } } - return AstVisitAction.Continue; + return result.Count > 0 ? result : null; } - public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) + // Finds the argument for the keyword (any characters following the keyword, ignoring leading/trailing whitespace). For example "C:\New folder" + Match keywordArgument = Regex.Match(context.CursorPosition.Line, @"(?<=^\s*\.\w+\s+)\S.*(?<=\S)"); + int lineStartIndex = lineKeyword.Index - context.CursorPosition.Line.IndexOf(lineKeyword.Value) + context.TokenAtCursor.Extent.StartOffset; + int argumentIndex = keywordArgument.Success ? keywordArgument.Index : context.CursorPosition.ColumnNumber - 1; + + replacementIndex = lineStartIndex + argumentIndex; + replacementLength = keywordArgument.Value.Length; + + if (lineKeyword.Value.Equals("PARAMETER", StringComparison.OrdinalIgnoreCase)) { - return functionDefinitionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; + return CompleteCommentParameterValue(context, keywordArgument.Value); } - public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) + if (lineKeyword.Value.Equals("FORWARDHELPTARGETNAME", StringComparison.OrdinalIgnoreCase)) { - return scriptBlockExpressionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; + var result = new List(CompleteCommand(keywordArgument.Value, "*", CommandTypes.All)); + return result.Count > 0 ? result : null; } - public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) + if (lineKeyword.Value.Equals("FORWARDHELPCATEGORY", StringComparison.OrdinalIgnoreCase)) { - return scriptBlockAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; + var result = new List(); + foreach (string category in s_commentHelpForwardCategories) + { + if (category.StartsWith(keywordArgument.Value, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult(category)); + } + } + return result.Count > 0 ? result : null; } - } - private static readonly Lazy> s_specialVariablesCache = new Lazy>(BuildSpecialVariablesCache); - - private static SortedSet BuildSpecialVariablesCache() - { - var result = new SortedSet(); - foreach (var member in typeof(SpecialVariables).GetFields(BindingFlags.NonPublic | BindingFlags.Static)) + if (lineKeyword.Value.Equals("REMOTEHELPRUNSPACE", StringComparison.OrdinalIgnoreCase)) { - if (member.FieldType.Equals(typeof(string))) + var result = new List(); + foreach (CompletionResult variable in CompleteVariable(keywordArgument.Value)) { - result.Add((string)member.GetValue(null)); + // ListItemText is used because it excludes the "$" as expected by REMOTEHELPRUNSPACE. + result.Add(new CompletionResult(variable.ListItemText, variable.ListItemText, variable.ResultType, variable.ToolTip)); } + return result.Count > 0 ? result : null; } - return result; + if (lineKeyword.Value.Equals("EXTERNALHELP", StringComparison.OrdinalIgnoreCase)) + { + context.WordToComplete = keywordArgument.Value; + var result = new List(CompleteFilename(context, containerOnly: false, (new HashSet() { ".xml" }))); + return result.Count > 0 ? result : null; + } + + return null; } - #endregion Variables + private static readonly string[] s_commentHelpKeywords = new string[] + { + "COMPONENT", + "DESCRIPTION", + "EXAMPLE", + "EXTERNALHELP", + "FORWARDHELPCATEGORY", + "FORWARDHELPTARGETNAME", + "FUNCTIONALITY", + "INPUTS", + "LINK", + "NOTES", + "OUTPUTS", + "PARAMETER", + "REMOTEHELPRUNSPACE", + "ROLE", + "SYNOPSIS" + }; - #region Comments + private static string GetCommentHelpKeywordsToolTip(string name) => name switch + { + "COMPONENT" => TabCompletionStrings.CommentHelpCOMPONENTKeywordDescription, + "DESCRIPTION" => TabCompletionStrings.CommentHelpDESCRIPTIONKeywordDescription, + "EXAMPLE" => TabCompletionStrings.CommentHelpEXAMPLEKeywordDescription, + "EXTERNALHELP" => TabCompletionStrings.CommentHelpEXTERNALHELPKeywordDescription, + "FORWARDHELPCATEGORY" => TabCompletionStrings.CommentHelpFORWARDHELPCATEGORYKeywordDescription, + "FORWARDHELPTARGETNAME" => TabCompletionStrings.CommentHelpFORWARDHELPTARGETNAMEKeywordDescription, + "FUNCTIONALITY" => TabCompletionStrings.CommentHelpFUNCTIONALITYKeywordDescription, + "INPUTS" => TabCompletionStrings.CommentHelpINPUTSKeywordDescription, + "LINK" => TabCompletionStrings.CommentHelpLINKKeywordDescription, + "NOTES" => TabCompletionStrings.CommentHelpNOTESKeywordDescription, + "OUTPUTS" => TabCompletionStrings.CommentHelpOUTPUTSKeywordDescription, + "PARAMETER" => TabCompletionStrings.CommentHelpPARAMETERKeywordDescription, + "REMOTEHELPRUNSPACE" => TabCompletionStrings.CommentHelpREMOTEHELPRUNSPACEKeywordDescription, + "ROLE" => TabCompletionStrings.CommentHelpROLEKeywordDescription, + "SYNOPSIS" => TabCompletionStrings.CommentHelpSYNOPSISKeywordDescription, + _ => string.Empty + }; - // Complete the history entries - internal static List CompleteComment(CompletionContext context) + private static readonly HashSet s_commentHelpAllowedDuplicateKeywords = new(StringComparer.OrdinalIgnoreCase) { - List results = new List(); + "EXAMPLE", + "LINK", + "PARAMETER" + }; - Match matchResult = Regex.Match(context.WordToComplete, @"^#([\w\-]*)$"); - if (!matchResult.Success) { return results; } + private static readonly string[] s_commentHelpForwardCategories = new string[] + { + "Alias", + "All", + "Cmdlet", + "ExternalScript", + "FAQ", + "Filter", + "Function", + "General", + "Glossary", + "HelpFile", + "Provider", + "ScriptCommand" + }; - string wordToComplete = matchResult.Groups[1].Value; - Collection psobjs; + private static FunctionDefinitionAst GetCommentHelpFunctionTarget(CompletionContext context) + { + if (context.TokenAtCursor.Kind != TokenKind.Comment) + { + return null; + } - int entryId; - if (Regex.IsMatch(wordToComplete, @"^[0-9]+$") && LanguagePrimitives.TryConvertTo(wordToComplete, out entryId)) + Ast lastAst = context.RelatedAsts[^1]; + Ast firstAstAfterComment = lastAst.Find(ast => ast.Extent.StartOffset >= context.TokenAtCursor.Extent.EndOffset && ast is not NamedBlockAst, searchNestedScriptBlocks: false); + + // Comment-based help can apply to a following function definition if it starts within 2 lines + int commentEndLine = context.TokenAtCursor.Extent.EndLineNumber + 2; + + if (lastAst is NamedBlockAst) { - context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)).AddParameter("Id", entryId); - psobjs = context.Helper.ExecuteCurrentPowerShell(out _); + // Helpblock before function inside advanced function + if (firstAstAfterComment is not null + && firstAstAfterComment.Extent.StartLineNumber <= commentEndLine + && firstAstAfterComment is FunctionDefinitionAst outerHelpFunctionDefAst) + { + return outerHelpFunctionDefAst; + } - if (psobjs != null && psobjs.Count == 1) + // Helpblock inside function + if (lastAst.Parent.Parent is FunctionDefinitionAst innerHelpFunctionDefAst) { - var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo; - if (historyInfo != null) - { - var commandLine = historyInfo.CommandLine; - if (!string.IsNullOrEmpty(commandLine)) - { - // var tooltip = "Id: " + historyInfo.Id + "\n" + - // "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" + - // "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" + - // "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n"; - // Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts - results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine)); - } - } + return innerHelpFunctionDefAst; } + } - return results; + if (lastAst is ScriptBlockAst) + { + // Helpblock before function + if (firstAstAfterComment is not null + && firstAstAfterComment.Extent.StartLineNumber <= commentEndLine + && firstAstAfterComment is FunctionDefinitionAst statement) + { + return statement; + } + + // Advanced function with help inside + if (lastAst.Parent is FunctionDefinitionAst advFuncDefAst) + { + return advFuncDefAst; + } } - wordToComplete = "*" + wordToComplete + "*"; - context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)); + return null; + } - psobjs = context.Helper.ExecuteCurrentPowerShell(out _); - var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); + private static List CompleteCommentParameterValue(CompletionContext context, string wordToComplete) + { + FunctionDefinitionAst foundFunction = GetCommentHelpFunctionTarget(context); - if (psobjs != null) + ReadOnlyCollection foundParameters = null; + if (foundFunction is not null) { - for (int index = psobjs.Count - 1; index >= 0; index--) + foundParameters = foundFunction.Parameters ?? foundFunction.Body.ParamBlock?.Parameters; + } + else if (context.RelatedAsts[^1] is ScriptBlockAst scriptAst) + { + // The helpblock is for a script file + foundParameters = scriptAst.ParamBlock?.Parameters; + } + + if (foundParameters is null || foundParameters.Count == 0) + { + return null; + } + + var parametersToShow = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (ParameterAst parameter in foundParameters) + { + if (parameter.Name.VariablePath.UserPath.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) { - var psobj = psobjs[index]; - if (!(PSObject.Base(psobj) is HistoryInfo historyInfo)) continue; + parametersToShow.Add(parameter.Name.VariablePath.UserPath); + } + } - var commandLine = historyInfo.CommandLine; - if (!string.IsNullOrEmpty(commandLine) && pattern.IsMatch(commandLine)) - { - // var tooltip = "Id: " + historyInfo.Id + "\n" + - // "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" + - // "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" + - // "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n"; - // Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts - results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine)); - } + MatchCollection usedParameters = Regex.Matches(context.TokenAtCursor.Text, @"(?<=^\s*\.parameter\s+)\w.*(?<=\S)", RegexOptions.Multiline | RegexOptions.IgnoreCase); + foreach (Match parameter in usedParameters) + { + if (wordToComplete.Equals(parameter.Value, StringComparison.OrdinalIgnoreCase)) + { + continue; } + parametersToShow.Remove(parameter.Value); } - return results; + var result = new List(); + foreach (string parameter in parametersToShow) + { + result.Add(new CompletionResult(parameter)); + } + + return result.Count > 0 ? result : null; } #endregion Comments @@ -4999,17 +6603,19 @@ internal static List CompleteComment(CompletionContext context new List> { new Tuple("Where", "Where({ expression } [, mode [, numberToReturn]])"), - new Tuple("ForEach", "ForEach(expression [, arguments...])") + new Tuple("ForEach", "ForEach(expression [, arguments...])"), + new Tuple("PSWhere", "PSWhere({ expression } [, mode [, numberToReturn]])"), + new Tuple("PSForEach", "PSForEach(expression [, arguments...])"), }; // List of DSC collection-value variables private static readonly HashSet s_dscCollectionVariables = new HashSet(StringComparer.OrdinalIgnoreCase) { "SelectedNodes", "AllNodes" }; - internal static List CompleteMember(CompletionContext context, bool @static) + internal static List CompleteMember(CompletionContext context, bool @static, ref int replacementLength) { // If we get here, we know that either: - // * the cursor appeared immediately after a member access token ('.' or '::'). + // * the cursor appeared after a member access token ('.' or '::'). // * the parent of the ast on the cursor was a member expression. // // In the first case, we have 2 possibilities: @@ -5017,31 +6623,35 @@ internal static List CompleteMember(CompletionContext context, // * the last ast is a string constant, with something like: echo $foo. var results = new List(); - var lastAst = context.RelatedAsts.Last(); - var lastAstAsMemberExpr = lastAst as MemberExpressionAst; + var memberName = "*"; Ast memberNameCandidateAst = null; ExpressionAst targetExpr = null; - if (lastAstAsMemberExpr != null) + + if (lastAst is MemberExpressionAst LastAstAsMemberExpression) { // If the cursor is not inside the member name in the member expression, assume // that the user had incomplete input, but the parser got lucky and succeeded parsing anyway. - if (context.TokenAtCursor.Extent.StartOffset >= lastAstAsMemberExpr.Member.Extent.StartOffset) + if (context.TokenAtCursor is not null && context.TokenAtCursor.Extent.StartOffset >= LastAstAsMemberExpression.Member.Extent.StartOffset) { - memberNameCandidateAst = lastAstAsMemberExpr.Member; + memberNameCandidateAst = LastAstAsMemberExpression.Member; } - targetExpr = lastAstAsMemberExpr.Expression; + targetExpr = LastAstAsMemberExpression.Expression; + // Handles scenario where the cursor is after the member access token but before the text + // like: "".Le + // which completes the member using the partial text after the cursor. + if (LastAstAsMemberExpression.Member is StringConstantExpressionAst stringExpression && stringExpression.Extent.StartOffset <= context.CursorPosition.Offset) + { + memberName = $"{stringExpression.Value}*"; + } } else { memberNameCandidateAst = lastAst; } - var memberNameAst = memberNameCandidateAst as StringConstantExpressionAst; - - var memberName = "*"; - if (memberNameAst != null) + if (memberNameCandidateAst is StringConstantExpressionAst memberNameAst) { // Make sure to correctly handle: echo $foo. if (!memberNameAst.Value.Equals(".", StringComparison.OrdinalIgnoreCase) && !memberNameAst.Value.Equals("::", StringComparison.OrdinalIgnoreCase)) @@ -5055,8 +6665,7 @@ internal static List CompleteMember(CompletionContext context, return results; } - var commandAst = lastAst.Parent as CommandAst; - if (commandAst != null) + if (lastAst.Parent is CommandAst commandAst) { int i; for (i = commandAst.CommandElements.Count - 1; i >= 0; --i) @@ -5076,10 +6685,36 @@ internal static List CompleteMember(CompletionContext context, targetExpr = nextToLastAst as ExpressionAst; } } - else if (lastAst.Parent is MemberExpressionAst) + else if (lastAst.Parent is MemberExpressionAst parentAsMemberExpression) { + if (lastAst is ErrorExpressionAst) + { + // Handles scenarios like $PSVersionTable.PSVersi.Major. + // where the cursor is moved back to a previous member expression while + // there's an incomplete member expression at the end + targetExpr = parentAsMemberExpression; + do + { + if (targetExpr is MemberExpressionAst memberExpression) + { + targetExpr = memberExpression.Expression; + } + else + { + break; + } + } while (targetExpr.Extent.EndOffset >= context.CursorPosition.Offset); + + if (targetExpr.Parent != parentAsMemberExpression + && targetExpr.Parent is MemberExpressionAst memberAst + && memberAst.Member is StringConstantExpressionAst stringExpression + && stringExpression.Extent.StartOffset <= context.CursorPosition.Offset) + { + memberName = $"{stringExpression.Value}*"; + } + } // If 'targetExpr' has already been set, we should skip this step. This is for some member completion - // cases in ISE. In ISE, we may add a new statement in the middle of existing statements as follows: + // cases in VSCode, where we may add a new statement in the middle of existing statements as follows: // $xml = New-Object Xml // $xml. // $xml.Save("C:\data.xml") @@ -5087,24 +6722,45 @@ internal static List CompleteMember(CompletionContext context, // a MemberExpressionAst '$xml.$xml', whose parent is still a MemberExpressionAst '$xml.$xml.Save'. // But here we DO NOT want to re-assign 'targetExpr' to be '$xml.$xml'. 'targetExpr' in this case // should be '$xml'. - if (targetExpr == null) + else { - var memberExprAst = (MemberExpressionAst)lastAst.Parent; - targetExpr = memberExprAst.Expression; + targetExpr ??= parentAsMemberExpression.Expression; } } - else if (lastAst.Parent is BinaryExpressionAst && context.TokenAtCursor.Kind.Equals(TokenKind.Multiply)) + else if (lastAst.Parent is BinaryExpressionAst binaryExpression && context.TokenAtCursor.Kind.Equals(TokenKind.Multiply)) { - var memberExprAst = ((BinaryExpressionAst)lastAst.Parent).Left as MemberExpressionAst; - if (memberExprAst != null) + if (binaryExpression.Left is MemberExpressionAst memberExpression) { - targetExpr = memberExprAst.Expression; - if (memberExprAst.Member is StringConstantExpressionAst) + targetExpr = memberExpression.Expression; + if (memberExpression.Member is StringConstantExpressionAst stringExpression) { - memberName = ((StringConstantExpressionAst)memberExprAst.Member).Value + "*"; + memberName = $"{stringExpression.Value}*"; } } } + else if (lastAst.Parent is ErrorStatementAst errorStatement) + { + // Handles switches like: + // switch ($x) + // { + // 'RandomString'. + // { } + // } + Ast astBeforeMemberAccessToken = null; + for (int i = errorStatement.Bodies.Count - 1; i >= 0; i--) + { + astBeforeMemberAccessToken = errorStatement.Bodies[i]; + if (astBeforeMemberAccessToken.Extent.EndOffset < lastAst.Extent.EndOffset) + { + break; + } + } + + if (astBeforeMemberAccessToken is ExpressionAst expression) + { + targetExpr = expression; + } + } if (targetExpr == null) { @@ -5137,6 +6793,11 @@ internal static List CompleteMember(CompletionContext context, inferredTypes = AstTypeInference.InferTypeOf(targetExpr, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).ToArray(); } + if (!@static && inferredTypes.Length == 1 && inferredTypes[0].Name.Equals("System.Void", StringComparison.OrdinalIgnoreCase)) + { + return results; + } + if (inferredTypes != null && inferredTypes.Length > 0) { // Use inferred types if we have any @@ -5193,28 +6854,77 @@ internal static List CompleteMember(CompletionContext context, } } + if (memberName != "*" && results.Count > 0) + { + // -1 because membername always has a trailing wildcard * + replacementLength = memberName.Length - 1; + } + return results; } + internal static List CompleteComparisonOperatorValues(CompletionContext context, ExpressionAst operatorLeftValue) + { + var result = new List(); + var resolvedTypes = new List(); + + if (SafeExprEvaluator.TrySafeEval(operatorLeftValue, context.ExecutionContext, out object value) && value is not null) + { + resolvedTypes.Add(value.GetType()); + } + else + { + var inferredTypes = AstTypeInference.InferTypeOf(operatorLeftValue, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); + foreach (var type in inferredTypes) + { + if (type.Type is not null) + { + resolvedTypes.Add(type.Type); + } + } + } + + foreach (var type in resolvedTypes) + { + if (type.IsEnum) + { + foreach (var name in type.GetEnumNames()) + { + if (name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult($"'{name}'", name, CompletionResultType.ParameterValue, name)); + } + } + + break; + } + } + + return result; + } + /// /// Complete members against extension methods 'Where' and 'ForEach' /// - private static void CompleteExtensionMethods(string memberName, List results) + private static void CompleteExtensionMethods(string memberName, List results, bool addMethodParenthesis = true) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); - CompleteExtensionMethods(pattern, results); + CompleteExtensionMethods(pattern, results, addMethodParenthesis); } /// /// Complete members against extension methods 'Where' and 'ForEach' based on the given pattern. /// - private static void CompleteExtensionMethods(WildcardPattern pattern, List results) + private static void CompleteExtensionMethods(WildcardPattern pattern, List results, bool addMethodParenthesis) { - results.AddRange(from member in s_extensionMethods - where pattern.IsMatch(member.Item1) - select - new CompletionResult(member.Item1 + "(", member.Item1, - CompletionResultType.Method, member.Item2)); + foreach (var member in s_extensionMethods) + { + if (pattern.IsMatch(member.Item1)) + { + string completionText = addMethodParenthesis ? $"{member.Item1}(" : member.Item1; + results.Add(new CompletionResult(completionText, member.Item1, CompletionResultType.Method, member.Item2)); + } + } } /// @@ -5244,23 +6954,143 @@ private static bool IsInDscContext(ExpressionAst expression) return Ast.GetAncestorAst(expression) != null; } - internal static void CompleteMemberByInferredType(TypeInferenceContext context, IEnumerable inferredTypes, List results, string memberName, Func filter, bool isStatic) + internal static List CompleteIndexExpression(CompletionContext context, ExpressionAst indexTarget) + { + var result = new List(); + object value; + if (SafeExprEvaluator.TrySafeEval(indexTarget, context.ExecutionContext, out value) + && value is not null + && PSObject.Base(value) is IDictionary dictionary) + { + foreach (var key in dictionary.Keys) + { + if (key is string keyAsString && keyAsString.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult($"'{keyAsString}'", keyAsString, CompletionResultType.Property, keyAsString)); + } + } + } + else + { + var inferredTypes = AstTypeInference.InferTypeOf(indexTarget, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); + foreach (var type in inferredTypes) + { + if (type is PSSyntheticTypeName synthetic) + { + foreach (var member in synthetic.Members) + { + if (member.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) + { + result.Add(new CompletionResult($"'{member.Name}'", member.Name, CompletionResultType.Property, member.Name)); + } + } + } + } + } + return result; + } + + private static void CompleteFormatViewByInferredType(CompletionContext context, string[] inferredTypeNames, List results, string commandName) + { + var typeInfoDB = context.TypeInferenceContext.ExecutionContext.FormatDBManager.GetTypeInfoDataBase(); + + if (typeInfoDB is null) + { + return; + } + + Type controlBodyType = commandName switch + { + "Format-Table" => typeof(TableControlBody), + "Format-List" => typeof(ListControlBody), + "Format-Wide" => typeof(WideControlBody), + "Format-Custom" => typeof(ComplexControlBody), + _ => null + }; + + Diagnostics.Assert(controlBodyType is not null, "This should never happen unless a new Format-* cmdlet is added"); + + var wordToComplete = context.WordToComplete; + var quote = CompletionHelpers.HandleDoubleAndSingleQuote(ref wordToComplete); + WildcardPattern viewPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); + + var uniqueNames = new HashSet(); + foreach (ViewDefinition viewDefinition in typeInfoDB.viewDefinitionsSection.viewDefinitionList) + { + if (viewDefinition?.appliesTo is not null && controlBodyType == viewDefinition.mainControl.GetType()) + { + foreach (TypeOrGroupReference applyTo in viewDefinition.appliesTo.referenceList) + { + foreach (string inferredTypeName in inferredTypeNames) + { + // We use 'StartsWith()' because 'applyTo.Name' can look like "System.Diagnostics.Process#IncludeUserName". + if (applyTo.name.StartsWith(inferredTypeName, StringComparison.OrdinalIgnoreCase) + && uniqueNames.Add(viewDefinition.name) + && viewPattern.IsMatch(viewDefinition.name)) + { + string completionText = viewDefinition.name; + // If the string is quoted or if it contains characters that need quoting, quote it in single quotes + if (quote != string.Empty || ContainsCharactersRequiringQuotes(viewDefinition.name)) + { + completionText = "'" + completionText.Replace("'", "''") + "'"; + } + + results.Add(new CompletionResult(completionText, viewDefinition.name, CompletionResultType.Text, viewDefinition.name)); + } + } + } + } + } + } + + internal static void CompleteMemberByInferredType( + TypeInferenceContext context, + IEnumerable inferredTypes, + List results, + string memberName, + Func filter, + bool isStatic, + HashSet excludedMembers = null, + bool addMethodParenthesis = true, + bool ignoreTypesWithoutDefaultConstructor = false) { bool extensionMethodsAdded = false; HashSet typeNameUsed = new HashSet(StringComparer.OrdinalIgnoreCase); WildcardPattern memberNamePattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (var psTypeName in inferredTypes) { - if (typeNameUsed.Contains(psTypeName.Name)) + if (!typeNameUsed.Add(psTypeName.Name) + || (ignoreTypesWithoutDefaultConstructor && psTypeName.Type is not null && psTypeName.Type.GetConstructor(Type.EmptyTypes) is null && !psTypeName.Type.IsInterface)) { continue; } - typeNameUsed.Add(psTypeName.Name); + if (ignoreTypesWithoutDefaultConstructor && psTypeName.TypeDefinitionAst is not null) + { + bool foundConstructor = false; + bool foundDefaultConstructor = false; + foreach (var member in psTypeName.TypeDefinitionAst.Members) + { + if (member is FunctionMemberAst methodDefinition && methodDefinition.IsConstructor) + { + foundConstructor = true; + if (methodDefinition.Parameters.Count == 0) + { + foundDefaultConstructor = true; + break; + } + } + } + if (foundConstructor && !foundDefaultConstructor) + { + continue; + } + } + var members = context.GetMembersByInferredType(psTypeName, isStatic, filter); foreach (var member in members) { - AddInferredMember(member, memberNamePattern, results); + AddInferredMember(member, memberNamePattern, results, excludedMembers, addMethodParenthesis); } // Check if we need to complete against the extension methods 'Where' and 'ForEach' @@ -5268,7 +7098,7 @@ internal static void CompleteMemberByInferredType(TypeInferenceContext context, { // Complete extension methods 'Where' and 'ForEach' for Enumerable types extensionMethodsAdded = true; - CompleteExtensionMethods(memberNamePattern, results); + CompleteExtensionMethods(memberNamePattern, results, addMethodParenthesis); } } @@ -5280,14 +7110,13 @@ internal static void CompleteMemberByInferredType(TypeInferenceContext context, .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object") .AddParameter("Property", new[] { "ResultType", "ListItemText" }) .AddParameter("Unique"); - Exception unused; - var sortedResults = powerShellExecutionHelper.ExecuteCurrentPowerShell(out unused, results); + var sortedResults = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _, results); results.Clear(); - results.AddRange(sortedResults.Select(psobj => PSObject.Base(psobj) as CompletionResult)); + results.AddRange(sortedResults.Select(static psobj => PSObject.Base(psobj) as CompletionResult)); } } - private static void AddInferredMember(object member, WildcardPattern memberNamePattern, List results) + private static void AddInferredMember(object member, WildcardPattern memberNamePattern, List results, HashSet excludedMembers, bool addMethodParenthesis) { string memberName = null; bool isMethod = false; @@ -5313,7 +7142,7 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP { memberName = methodCacheEntry[0].method.Name; isMethod = true; - getToolTip = () => string.Join("\n", methodCacheEntry.methodInformationStructures.Select(m => m.methodDefinition)); + getToolTip = () => string.Join('\n', methodCacheEntry.methodInformationStructures.Select(static m => m.methodDefinition)); } var psMemberInfo = member as PSMemberInfo; @@ -5332,21 +7161,45 @@ private static void AddInferredMember(object member, WildcardPattern memberNameP getToolTip = () => GetCimPropertyToString(cimProperty); } - var memberAst = member as MemberAst; - if (memberAst != null) + if (member is MemberAst memberAst) { - memberName = memberAst is CompilerGeneratedMemberFunctionAst ? "new" : memberAst.Name; - isMethod = memberAst is FunctionMemberAst || memberAst is CompilerGeneratedMemberFunctionAst; + if (memberAst is CompilerGeneratedMemberFunctionAst) + { + memberName = "new"; + isMethod = true; + } + else if (memberAst is FunctionMemberAst functionMember) + { + memberName = functionMember.IsConstructor ? "new" : functionMember.Name; + isMethod = true; + } + else + { + memberName = memberAst.Name; + isMethod = false; + } getToolTip = memberAst.GetTooltip; } - if (memberName == null || !memberNamePattern.IsMatch(memberName)) + if (memberName == null || !memberNamePattern.IsMatch(memberName) || (excludedMembers is not null && excludedMembers.Contains(memberName))) { return; } var completionResultType = isMethod ? CompletionResultType.Method : CompletionResultType.Property; - var completionText = isMethod ? memberName + "(" : memberName; + string completionText; + if (isMethod && addMethodParenthesis) + { + completionText = $"{memberName}("; + } + else if (ContainsCharactersRequiringQuotes(memberName)) + { + completionText = $"'{memberName}'"; + } + else + { + completionText = memberName; + } results.Add(new CompletionResult(completionText, memberName, completionResultType, getToolTip())); } @@ -5388,6 +7241,12 @@ private static bool IsWriteablePropertyMember(object member) return psPropertyInfo.IsSettable; } + if (member is PropertyMemberAst) + { + // Properties in PowerShell classes are always writeable + return true; + } + return false; } @@ -5539,7 +7398,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string /// This type represents a generic type for type name completion. It only contains information that can be /// inferred from the full type name. /// - private class GenericTypeCompletionInStringFormat : TypeCompletionInStringFormat + private sealed class GenericTypeCompletionInStringFormat : TypeCompletionInStringFormat { /// /// Get the number of generic type arguments required by the type represented by this instance. @@ -5591,7 +7450,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string if (i != 0) tooltip.Append(", "); tooltip.Append(GenericArgumentCount == 1 ? "T" - : string.Format(CultureInfo.InvariantCulture, "T{0}", i + 1)); + : string.Create(CultureInfo.InvariantCulture, $"T{i + 1}")); } tooltip.Append(']'); @@ -5656,7 +7515,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string /// /// This type represents a generic type for type name completion. It contains the actual type instance. /// - private class GenericTypeCompletion : TypeCompletion + private sealed class GenericTypeCompletion : TypeCompletion { internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { @@ -5693,7 +7552,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string /// /// This type represents a namespace for namespace completion. /// - private class NamespaceCompletion : TypeCompletionBase + private sealed class NamespaceCompletion : TypeCompletionBase { internal string Namespace; @@ -5715,7 +7574,7 @@ internal override CompletionResult GetCompletionResult(string keyMatched, string } } - private class TypeCompletionMapping + private sealed class TypeCompletionMapping { // The Key is the string we'll be searching on. It could complete to various things. internal string Key; @@ -5824,7 +7683,7 @@ private static TypeCompletionMapping[][] InitializeTypeCache() #endregion Process_LoadedAssemblies - var grouping = entries.Values.GroupBy(t => t.Key.Count(c => c == '.')).OrderBy(g => g.Key).ToArray(); + var grouping = entries.Values.GroupBy(static t => t.Key.Count(c => c == '.')).OrderBy(static g => g.Key).ToArray(); var localTypeCache = new TypeCompletionMapping[grouping.Last().Key + 1][]; foreach (var group in grouping) { @@ -5941,7 +7800,7 @@ internal static List CompleteNamespace(CompletionContext conte var localTypeCache = s_typeCache ?? InitializeTypeCache(); var results = new List(); var wordToComplete = context.WordToComplete; - var dots = wordToComplete.Count(c => c == '.'); + var dots = wordToComplete.Count(static c => c == '.'); if (dots >= localTypeCache.Length || localTypeCache[dots] == null) { return results; @@ -5957,7 +7816,7 @@ internal static List CompleteNamespace(CompletionContext conte } } - results.Sort((c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); + results.Sort(static (c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); return results; } @@ -5985,7 +7844,7 @@ internal static List CompleteType(CompletionContext context, s var results = new List(); var completionTextSet = new HashSet(StringComparer.OrdinalIgnoreCase); var wordToComplete = context.WordToComplete; - var dots = wordToComplete.Count(c => c == '.'); + var dots = wordToComplete.Count(static c => c == '.'); if (dots >= localTypeCache.Length || localTypeCache[dots] == null) { return results; @@ -6016,7 +7875,7 @@ internal static List CompleteType(CompletionContext context, s if (context.RelatedAsts != null && context.RelatedAsts.Count > 0) { var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; - var typeAsts = scriptBlockAst.FindAll(ast => ast is TypeDefinitionAst, false).Cast(); + var typeAsts = scriptBlockAst.FindAll(static ast => ast is TypeDefinitionAst, false).Cast(); foreach (var typeAst in typeAsts.Where(ast => pattern.IsMatch(ast.Name))) { string toolTipPrefix = string.Empty; @@ -6031,7 +7890,7 @@ internal static List CompleteType(CompletionContext context, s } } - results.Sort((c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); + results.Sort(static (c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); return results; } @@ -6071,67 +7930,31 @@ private static string GetNamespaceToRemove(CompletionContext context, TypeComple internal static List CompleteHelpTopics(CompletionContext context) { - var results = new List(); - var searchPaths = new List(); - var currentCulture = CultureInfo.CurrentCulture.Name; - - // Add the user scope path first, since it is searched in order. - var userHelpRoot = Path.Combine(HelpUtils.GetUserHomeHelpSearchPath(), currentCulture); - - if (Directory.Exists(userHelpRoot)) - { - searchPaths.Add(userHelpRoot); - } - - var dirPath = Path.Combine(Utils.GetApplicationBase(Utils.DefaultPowerShellShellID), currentCulture); - searchPaths.Add(dirPath); - - var wordToComplete = context.WordToComplete + "*"; - var topicPattern = WildcardPattern.Get("about_*.help.txt", WildcardOptions.IgnoreCase); - List files = new List(); - - try + ArrayList helpProviders = context.ExecutionContext.HelpSystem.HelpProviders; + HelpFileHelpProvider helpFileProvider = null; + for (int i = helpProviders.Count - 1; i >= 0; i--) { - var wildcardPattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); - - foreach (var dir in searchPaths) + if (helpProviders[i] is HelpFileHelpProvider provider) { - foreach (var file in Directory.EnumerateFiles(dir)) - { - if (wildcardPattern.IsMatch(Path.GetFileName(file))) - { - files.Add(file); - } - } + helpFileProvider = provider; + break; } } - catch (Exception) + + if (helpFileProvider is null) { + return null; } - if (files != null) + List results = new(); + Collection filesMatched = MUIFileSearcher.SearchFiles($"{context.WordToComplete}*.help.txt", helpFileProvider.GetExtendedSearchPaths()); + foreach (string path in filesMatched) { - foreach (string file in files) + string fileName = Path.GetFileName(path); + if (fileName.StartsWith("about_", StringComparison.OrdinalIgnoreCase)) { - if (file == null) - { - continue; - } - - try - { - var fileName = Path.GetFileName(file); - if (fileName == null || !topicPattern.IsMatch(fileName)) - continue; - - // All topic files are ending with ".help.txt" - var completionText = fileName.Substring(0, fileName.Length - 9); - results.Add(new CompletionResult(completionText)); - } - catch (Exception) - { - continue; - } + string topicName = fileName.Substring(0, fileName.Length - ".help.txt".Length); + results.Add(new CompletionResult(topicName, topicName, CompletionResultType.ParameterValue, topicName)); } } @@ -6153,9 +7976,7 @@ internal static List CompleteStatementFlags(TokenKind kind, st bool withColon = wordToComplete.EndsWith(':'); wordToComplete = withColon ? wordToComplete.Remove(wordToComplete.Length - 1) : wordToComplete; - string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(SwitchFlags)); - string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; - string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); + string[] enumArray = LanguagePrimitives.EnumSingleTypeConverter.GetEnumNames(typeof(SwitchFlags)); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var enumList = new List(); @@ -6285,162 +8106,469 @@ internal static List CompleteHashtableKeyForDynamicKeyword( return results; } - internal static List CompleteHashtableKey(CompletionContext completionContext, HashtableAst hashtableAst) + private static PSTypeName GetNestedHashtableKeyType(TypeInferenceContext typeContext, PSTypeName parentType, IList nestedKeys) { - var typeAst = hashtableAst.Parent as ConvertExpressionAst; - if (typeAst != null) + var currentType = parentType; + // The nestedKeys list should have the outer most key as the last element, and the inner most key as the first element + // If we fail to resolve the type of any key we return null + for (int i = nestedKeys.Count - 1; i >= 0; i--) { - var result = new List(); - CompleteMemberByInferredType( - completionContext.TypeInferenceContext, AstTypeInference.InferTypeOf(typeAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval), - result, completionContext.WordToComplete + "*", IsWriteablePropertyMember, isStatic: false); - return result; + if (currentType is null) + { + return null; + } + + var typeMembers = typeContext.GetMembersByInferredType(currentType, false, null); + currentType = null; + foreach (var member in typeMembers) + { + if (member is PropertyInfo propertyInfo) + { + if (propertyInfo.Name.Equals(nestedKeys[i], StringComparison.OrdinalIgnoreCase)) + { + currentType = new PSTypeName(propertyInfo.PropertyType); + break; + } + } + else if (member is PropertyMemberAst memberAst && memberAst.Name.Equals(nestedKeys[i], StringComparison.OrdinalIgnoreCase)) + { + if (memberAst.PropertyType is null) + { + return null; + } + else + { + if (memberAst.PropertyType.TypeName is ArrayTypeName arrayType) + { + currentType = new PSTypeName(arrayType.ElementType); + } + else + { + currentType = new PSTypeName(memberAst.PropertyType.TypeName); + } + } + + break; + } + } } - // hashtable arguments sometimes have expected keys. Examples: - // new-object System.Drawing.Point -prop @{ X=1; Y=1 } - // dir | sort-object -prop @{Expression=... ; Ascending=... } - // format-table -Property - // Expression - // FormatString - // Label - // Width - // Alignment - // format-list -Property - // Expression - // FormatString - // Label - // format-custom -Property - // Expression - // Depth - // format-* -GroupBy - // Expression - // FormatString - // Label - // + return currentType; + } + + internal static List CompleteHashtableKey(CompletionContext completionContext, HashtableAst hashtableAst) + { + Ast previousAst = hashtableAst; + Ast parentAst = hashtableAst.Parent; + string parameterName = null; + var nestedHashtableKeys = new List(); + + // This loop determines if it's a nested hashtable and what the outermost hashtable is used for (Dynamic keyword, command argument, etc.) + // Note this also considers hashtables with arrays of hashtables to be nested to support scenarios like this: + // class Level1 + // { + // [Level2[]] $Prop1 + // } + // class Level2 + // { + // [string] $Prop2 + // } + // [Level1] @{ + // Prop1 = @( + // @{Prop2="Hello"} + // @{Pro} + // ) + // } + while (parentAst is not null) + { + switch (parentAst) + { + case HashtableAst parentTable: + foreach (var pair in parentTable.KeyValuePairs) + { + if (pair.Item2 == previousAst) + { + // Try to get the value of the hashtable key in the nested hashtable. + // If we fail to get the value then return early because we can't generate any useful completions + if (SafeExprEvaluator.TrySafeEval(pair.Item1, completionContext.ExecutionContext, out object value)) + { + if (value is not string stringValue) + { + return null; + } + + nestedHashtableKeys.Add(stringValue); + break; + } + else + { + return null; + } + } + } + break; + + case DynamicKeywordStatementAst dynamicKeyword: + return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeyword, hashtableAst); + + case CommandParameterAst cmdParam: + parameterName = cmdParam.ParameterName; + parentAst = cmdParam.Parent; + goto ExitWhileLoop; + + case AssignmentStatementAst assignment: + if (assignment.Left is MemberExpressionAst or ConvertExpressionAst) + { + parentAst = assignment.Left; + } + goto ExitWhileLoop; + + case CommandAst: + case ConvertExpressionAst: + case UsingStatementAst: + goto ExitWhileLoop; + + case CommandExpressionAst: + case PipelineAst: + case StatementBlockAst: + case ArrayExpressionAst: + case ArrayLiteralAst: + break; + + default: + return null; + } - // Find out if we are in a command argument. Consider the following possibilities: - // cmd @{} - // cmd -foo @{} - // cmd -foo:@{} - // cmd @{},@{} - // cmd -foo @{},@{} - // cmd -foo:@{},@{} + previousAst = parentAst; + parentAst = parentAst.Parent; + } - var ast = hashtableAst.Parent; + ExitWhileLoop: - // Handle completion for hashtable within DynamicKeyword statement - var dynamicKeywordStatementAst = ast as DynamicKeywordStatementAst; - if (dynamicKeywordStatementAst != null) + bool hashtableIsNested = nestedHashtableKeys.Count > 0; + int cursorOffset = completionContext.CursorPosition.Offset; + string wordToComplete = completionContext.WordToComplete; + var excludedKeys = new HashSet(StringComparer.OrdinalIgnoreCase); + // Filters out keys that have already been defined in the hashtable, except the one the cursor is at + foreach (var keyPair in hashtableAst.KeyValuePairs) { - return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeywordStatementAst, hashtableAst); + if (!(cursorOffset >= keyPair.Item1.Extent.StartOffset && cursorOffset <= keyPair.Item1.Extent.EndOffset)) + { + excludedKeys.Add(keyPair.Item1.Extent.Text); + } } - if (ast is ArrayLiteralAst) + if (parentAst is UsingStatementAst usingStatement) { - ast = ast.Parent; + if (hashtableIsNested || usingStatement.UsingStatementKind != UsingStatementKind.Module) + { + return null; + } + + var result = new List(); + foreach (string key in s_requiresModuleSpecKeys) + { + if (excludedKeys.Contains(key) + || (wordToComplete is not null && !key.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) + || (key.Equals("RequiredVersion") && (excludedKeys.Contains("ModuleVersion") || excludedKeys.Contains("MaximumVersion"))) + || ((key.Equals("ModuleVersion") || key.Equals("MaximumVersion")) && excludedKeys.Contains("RequiredVersion"))) + { + continue; + } + + string toolTip = GetRequiresModuleSpecKeysToolTip(key); + + result.Add(new CompletionResult(key, key, CompletionResultType.Property, toolTip)); + } + + return result; } - if (ast is CommandParameterAst) + if (parentAst is MemberExpressionAst or ConvertExpressionAst) { - ast = ast.Parent; + IEnumerable inferredTypes; + if (hashtableIsNested) + { + var nestedType = GetNestedHashtableKeyType( + completionContext.TypeInferenceContext, + AstTypeInference.InferTypeOf(parentAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval)[0], + nestedHashtableKeys); + if (nestedType is null) + { + return null; + } + + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes(new PSTypeName[] { nestedType }); + } + else + { + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes( + AstTypeInference.InferTypeOf(parentAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval)); + } + + var result = new List(); + CompleteMemberByInferredType( + completionContext.TypeInferenceContext, + inferredTypes, + result, + wordToComplete + "*", + IsWriteablePropertyMember, + isStatic: false, + excludedKeys, + ignoreTypesWithoutDefaultConstructor: true); + return result; } - var commandAst = ast as CommandAst; - if (commandAst != null) + if (parentAst is CommandAst commandAst) { var binding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, bindingType: PseudoParameterBinder.BindingType.ArgumentCompletion); - if (binding == null) + if (binding is null) { return null; } - string parameterName = null; - foreach (var boundArg in binding.BoundArguments) + if (parameterName is null) { - var astPair = boundArg.Value as AstPair; - if (astPair != null) + foreach (var boundArg in binding.BoundArguments) { - if (astPair.Argument == hashtableAst) + if (boundArg.Value is AstPair pair && pair.Argument == previousAst) { parameterName = boundArg.Key; - break; } - - continue; - } - - var astArrayPair = boundArg.Value as AstArrayPair; - if (astArrayPair != null) - { - if (astArrayPair.Argument.Contains(hashtableAst)) + else if (boundArg.Value is AstArrayPair arrayPair && arrayPair.Argument.Contains(previousAst)) { parameterName = boundArg.Key; - break; } - - continue; } } - if (parameterName != null) + if (parameterName is not null) { + List results; if (parameterName.Equals("GroupBy", StringComparison.OrdinalIgnoreCase)) { - switch (binding.CommandName) + if (!hashtableIsNested) { - case "Format-Table": - case "Format-List": - case "Format-Wide": - case "Format-Custom": - return GetSpecialHashTableKeyMembers("Expression", "FormatString", "Label"); + switch (binding.CommandName) + { + case "Format-Table": + case "Format-List": + case "Format-Wide": + case "Format-Custom": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); + } } return null; } if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) + { + if (!hashtableIsNested) + { + switch (binding.CommandName) + { + case "New-Object": + var inferredType = AstTypeInference.InferTypeOf(commandAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); + results = new List(); + CompleteMemberByInferredType( + completionContext.TypeInferenceContext, inferredType, + results, completionContext.WordToComplete + "*", IsWriteablePropertyMember, isStatic: false, excludedKeys); + return results; + case "Select-Object": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Name", "Expression"); + case "Sort-Object": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Ascending", "Descending"); + case "Group-Object": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression"); + case "Format-Table": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label", "Width", "Alignment"); + case "Format-List": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); + case "Format-Wide": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString"); + case "Format-Custom": + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Depth"); + case "Set-CimInstance": + case "New-CimInstance": + results = new List(); + NativeCompletionCimCommands(parameterName, binding.BoundArguments, results, commandAst, completionContext, excludedKeys, binding.CommandName); + // this method adds a null CompletionResult to the list but we don't want that here. + if (results.Count > 1) + { + results.RemoveAt(results.Count - 1); + return results; + } + return null; + } + return null; + } + } + + if (parameterName.Equals("FilterHashtable", StringComparison.OrdinalIgnoreCase)) { switch (binding.CommandName) { - case "New-Object": - var inferredType = AstTypeInference.InferTypeOf(commandAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); - var result = new List(); - CompleteMemberByInferredType( - completionContext.TypeInferenceContext, inferredType, - result, completionContext.WordToComplete + "*", IsWriteablePropertyMember, isStatic: false); - return result; - case "Select-Object": - return GetSpecialHashTableKeyMembers("Name", "Expression"); - case "Sort-Object": - return GetSpecialHashTableKeyMembers("Expression", "Ascending", "Descending"); - case "Group-Object": - return GetSpecialHashTableKeyMembers("Expression"); - case "Format-Table": - return GetSpecialHashTableKeyMembers("Expression", "FormatString", "Label", "Width", "Alignment"); - case "Format-List": - return GetSpecialHashTableKeyMembers("Expression", "FormatString", "Label"); - case "Format-Wide": - return GetSpecialHashTableKeyMembers("Expression", "FormatString"); - case "Format-Custom": - return GetSpecialHashTableKeyMembers("Expression", "Depth"); + case "Get-WinEvent": + if (nestedHashtableKeys.Count == 1 + && nestedHashtableKeys[0].Equals("SuppressHashFilter", StringComparison.OrdinalIgnoreCase) + && hashtableAst.Parent.Parent.Parent is HashtableAst) + { + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "LogName", "ProviderName", "Path", "Keywords", "ID", "Level", + "StartTime", "EndTime", "UserID", "Data"); + } + else if (!hashtableIsNested) + { + return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "LogName", "ProviderName", "Path", "Keywords", "ID", "Level", + "StartTime", "EndTime", "UserID", "Data", "SuppressHashFilter"); + } + + return null; + } + } + + if (parameterName.Equals("Arguments", StringComparison.OrdinalIgnoreCase)) + { + if (!hashtableIsNested) + { + switch (binding.CommandName) + { + case "Invoke-CimMethod": + results = new List(); + NativeCompletionCimCommands(parameterName, binding.BoundArguments, results, commandAst, completionContext, excludedKeys, binding.CommandName); + // this method adds a null CompletionResult to the list but we don't want that here. + if (results.Count > 1) + { + results.RemoveAt(results.Count - 1); + return results; + } + return null; + } + } + return null; + } + + IEnumerable inferredTypes; + if (hashtableIsNested) + { + var nestedType = GetNestedHashtableKeyType( + completionContext.TypeInferenceContext, + new PSTypeName(binding.BoundParameters[parameterName].Parameter.Type), + nestedHashtableKeys); + if (nestedType is null) + { + return null; + } + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes(new PSTypeName[] { nestedType }); + } + else + { + inferredTypes = TypeInferenceVisitor.GetInferredEnumeratedTypes(new PSTypeName[] { new PSTypeName(binding.BoundParameters[parameterName].Parameter.Type) }); + } + + results = new List(); + CompleteMemberByInferredType( + completionContext.TypeInferenceContext, + inferredTypes, + results, + $"{wordToComplete}*", + IsWriteablePropertyMember, + isStatic: false, + excludedKeys, + ignoreTypesWithoutDefaultConstructor: true); + return results; + } + } + else if (!hashtableIsNested && parentAst is AssignmentStatementAst assignment && assignment.Left is VariableExpressionAst assignmentVar) + { + var firstSplatUse = completionContext.RelatedAsts[0].Find( + currentAst => + currentAst.Extent.StartOffset > hashtableAst.Extent.EndOffset + && currentAst is VariableExpressionAst splatVar + && splatVar.Splatted + && splatVar.VariablePath.UserPath.Equals(assignmentVar.VariablePath.UserPath, StringComparison.OrdinalIgnoreCase), + searchNestedScriptBlocks: true) as VariableExpressionAst; + + if (firstSplatUse is not null && firstSplatUse.Parent is CommandAst command) + { + var binding = new PseudoParameterBinder() + .DoPseudoParameterBinding( + command, + pipeArgumentType: null, + paramAstAtCursor: null, + PseudoParameterBinder.BindingType.ParameterCompletion); + + if (binding is null) + { + return null; + } + + var results = new List(); + foreach (var parameter in binding.UnboundParameters) + { + if (!excludedKeys.Contains(parameter.Parameter.Name) + && (wordToComplete is null || parameter.Parameter.Name.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))) + { + results.Add(new CompletionResult(parameter.Parameter.Name, parameter.Parameter.Name, CompletionResultType.ParameterName, $"[{parameter.Parameter.Type.Name}]")); } } + + if (results.Count > 0) + { + return results; + } } } return null; } - private static List GetSpecialHashTableKeyMembers(params string[] keys) + private static List GetSpecialHashTableKeyMembers(HashSet excludedKeys, string wordToComplete, params string[] keys) { - // Resources were removed because they missed the deadline for loc. - // return keys.Select(key => new CompletionResult(key, key, CompletionResultType.Property, - // ResourceManagerCache.GetResourceString(typeof(CompletionCompleters).Assembly, - // "TabCompletionStrings", key + "HashKeyDescription"))).ToList(); - return keys.Select(key => new CompletionResult(key, key, CompletionResultType.Property, key)).ToList(); + var result = new List(); + foreach (string key in keys) + { + if ((string.IsNullOrEmpty(wordToComplete) || key.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) && !excludedKeys.Contains(key)) + { + string toolTip = GetHashtableKeyDescriptionToolTip(key); + + result.Add(new CompletionResult(key, key, CompletionResultType.Property, toolTip)); + } + } + + if (result.Count == 0) + { + return null; + } + + return result; } + private static string GetHashtableKeyDescriptionToolTip(string name) => name switch + { + "Alignment" => TabCompletionStrings.AlignmentHashtableKeyDescription, + "Ascending" => TabCompletionStrings.AscendingHashtableKeyDescription, + "Data" => TabCompletionStrings.DataHashtableKeyDescription, + "Depth" => TabCompletionStrings.DepthHashtableKeyDescription, + "Descending" => TabCompletionStrings.DescendingHashtableKeyDescription, + "EndTime" => TabCompletionStrings.EndTimeHashtableKeyDescription, + "Expression" => TabCompletionStrings.ExpressionHashtableKeyDescription, + "FormatString" => TabCompletionStrings.FormatStringHashtableKeyDescription, + "ID" => TabCompletionStrings.IDHashtableKeyDescription, + "Keywords" => TabCompletionStrings.KeywordsHashtableKeyDescription, + "Label" => TabCompletionStrings.LabelHashtableKeyDescription, + "Level" => TabCompletionStrings.LevelHashtableKeyDescription, + "LogName" => TabCompletionStrings.LogNameHashtableKeyDescription, + "Name" => TabCompletionStrings.NameHashtableKeyDescription, + "Path" => TabCompletionStrings.PathHashtableKeyDescription, + "ProviderName" => TabCompletionStrings.ProviderNameHashtableKeyDescription, + "StartTime" => TabCompletionStrings.StartTimeHashtableKeyDescription, + "SuppressHashFilter" => TabCompletionStrings.SuppressHashFilterHashtableKeyDescription, + "UserID" => TabCompletionStrings.UserIDHashtableKeyDescription, + "Width" => TabCompletionStrings.WidthHashtableKeyDescription, + _ => string.Empty + }; + #endregion Hashtable Keys #region Helpers @@ -6460,7 +8588,7 @@ internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expand var varValues = new List(); foreach (ExpressionAst nestedAst in expandableStringAst.NestedExpressions) { - if (!(nestedAst is VariableExpressionAst variableAst)) { return false; } + if (nestedAst is not VariableExpressionAst variableAst) { return false; } string strValue = CombineVariableWithPartialPath(variableAst, null, executionContext); if (strValue != null) @@ -6483,66 +8611,69 @@ internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expand internal static string CombineVariableWithPartialPath(VariableExpressionAst variableAst, string extraText, ExecutionContext executionContext) { var varPath = variableAst.VariablePath; - if (varPath.IsVariable || varPath.DriveName.Equals("env", StringComparison.OrdinalIgnoreCase)) + if (!varPath.IsVariable && !varPath.DriveName.Equals("env", StringComparison.OrdinalIgnoreCase)) { - try - { - // We check the strict mode inside GetVariableValue - object value = VariableOps.GetVariableValue(varPath, executionContext, variableAst); - var strValue = (value == null) ? string.Empty : value as string; + return null; + } - if (strValue == null) - { - object baseObj = PSObject.Base(value); - if (baseObj is string || baseObj.GetType().IsPrimitive) - { - strValue = LanguagePrimitives.ConvertTo(value); - } - } + if (varPath.UnqualifiedPath.Equals(SpecialVariables.PSScriptRoot, StringComparison.OrdinalIgnoreCase) + && !string.IsNullOrEmpty(variableAst.Extent.File)) + { + return Path.GetDirectoryName(variableAst.Extent.File) + extraText; + } + + try + { + // We check the strict mode inside GetVariableValue + object value = VariableOps.GetVariableValue(varPath, executionContext, variableAst); + var strValue = (value == null) ? string.Empty : value as string; - if (strValue != null) + if (strValue == null) + { + object baseObj = PSObject.Base(value); + if (baseObj is string || baseObj?.GetType()?.IsPrimitive is true) { - return strValue + extraText; + strValue = LanguagePrimitives.ConvertTo(value); } } - catch (Exception) + + if (strValue != null) { + return strValue + extraText; } } + catch (Exception) + { + } return null; } - internal static string HandleDoubleAndSingleQuote(ref string wordToComplete) + /// + /// Calls Get-Command to get command info objects. + /// + /// The fake bound parameters. + /// The parameters to add. + /// Collection of command info objects. + internal static Collection GetCommandInfo( + IDictionary fakeBoundParameters, + params string[] parametersToAdd) { - string quote = string.Empty; + using var ps = PowerShell.Create(RunspaceMode.CurrentRunspace); - if (!string.IsNullOrEmpty(wordToComplete) && (wordToComplete[0].IsSingleQuote() || wordToComplete[0].IsDoubleQuote())) - { - char frontQuote = wordToComplete[0]; - int length = wordToComplete.Length; + ps.AddCommand("Get-Command"); - if (length == 1) - { - wordToComplete = string.Empty; - quote = frontQuote.IsSingleQuote() ? "'" : "\""; - } - else if (length > 1) + foreach (string parameter in parametersToAdd) + { + if (fakeBoundParameters.Contains(parameter)) { - if ((wordToComplete[length - 1].IsDoubleQuote() && frontQuote.IsDoubleQuote()) || (wordToComplete[length - 1].IsSingleQuote() && frontQuote.IsSingleQuote())) - { - wordToComplete = wordToComplete.Substring(1, length - 2); - quote = frontQuote.IsSingleQuote() ? "'" : "\""; - } - else if (!wordToComplete[length - 1].IsDoubleQuote() && !wordToComplete[length - 1].IsSingleQuote()) - { - wordToComplete = wordToComplete.Substring(1); - quote = frontQuote.IsSingleQuote() ? "'" : "\""; - } + ps.AddParameter(parameter, fakeBoundParameters[parameter]); } } - return quote; + Collection commands = ps.Invoke(); + + return commands; } internal static bool IsSplattedVariable(Ast targetExpr) @@ -6585,7 +8716,7 @@ internal static void CompleteMemberHelper( IEnumerable members; if (@static) { - if (!(PSObject.Base(value) is Type type)) + if (PSObject.Base(value) is not Type type) { return; } @@ -6610,7 +8741,7 @@ internal static void CompleteMemberHelper( var completionText = memberInfo.Name; // Handle scenarios like this: $aa | add-member 'a b' 23; $aa.a - if (completionText.IndexOfAny(s_charactersRequiringQuotes) != -1) + if (ContainsCharactersRequiringQuotes(completionText)) { completionText = completionText.Replace("'", "''"); completionText = "'" + completionText + "'"; @@ -6651,13 +8782,13 @@ internal static void CompleteMemberHelper( var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (DictionaryEntry entry in dictionary) { - if (!(entry.Key is string key)) + if (entry.Key is not string key) continue; if (pattern.IsMatch(key)) { // Handle scenarios like this: $hashtable["abc#d"] = 100; $hashtable.ab - if (key.IndexOfAny(s_charactersRequiringQuotes) != -1) + if (ContainsCharactersRequiringQuotes(key)) { key = key.Replace("'", "''"); key = "'" + key + "'"; @@ -6715,32 +8846,6 @@ private static bool IsStaticTypeEnumerable(Type type) return false; } - private static bool CompletionRequiresQuotes(string completion, bool escape) - { - // If the tokenizer sees the completion as more than two tokens, or if there is some error, then - // some form of quoting is necessary (if it's a variable, we'd need ${}, filenames would need [], etc.) - - Language.Token[] tokens; - ParseError[] errors; - Language.Parser.ParseInput(completion, out tokens, out errors); - - char[] charToCheck = escape ? new[] { '$', '[', ']', '`' } : new[] { '$', '`' }; - - // Expect no errors and 2 tokens (1 is for our completion, the other is eof) - // Or if the completion is a keyword, we ignore the errors - bool requireQuote = !(errors.Length == 0 && tokens.Length == 2); - if ((!requireQuote && tokens[0] is StringToken) || - (tokens.Length == 2 && (tokens[0].TokenFlags & TokenFlags.Keyword) != 0)) - { - requireQuote = false; - var value = tokens[0].Text; - if (value.IndexOfAny(charToCheck) != -1) - requireQuote = true; - } - - return requireQuote; - } - private static bool ProviderSpecified(string path) { var index = path.IndexOf(':'); @@ -6807,7 +8912,7 @@ internal static bool IsAmpersandNeeded(CompletionContext context, bool defaultCh return defaultChoice; } - private class ItemPathComparer : IComparer + private sealed class ItemPathComparer : IComparer { public int Compare(PSObject x, PSObject y) { @@ -6842,7 +8947,7 @@ public int Compare(PSObject x, PSObject y) } } - private class CommandNameComparer : IComparer + private sealed class CommandNameComparer : IComparer { public int Compare(PSObject x, PSObject y) { @@ -6869,7 +8974,7 @@ public int Compare(PSObject x, PSObject y) } /// - /// This class is very similar to the restricted langauge checker, but it is meant to allow more things, yet still + /// This class is very similar to the restricted language checker, but it is meant to allow more things, yet still /// be considered "safe", at least in the sense that tab completion can rely on it to not do bad things. The primary /// use is for intellisense where you don't want to run arbitrary code, but you do want to know the values /// of various expressions so you can get the members. @@ -7125,7 +9230,7 @@ public PropertyNameCompleter() /// /// Initializes a new instance of the class. /// - /// The name of the property of the input object for witch to complete with property names. + /// The name of the property of the input object for which to complete with property names. public PropertyNameCompleter(string parameterNameOfInput) { _parameterNameOfInput = parameterNameOfInput; diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs new file mode 100644 index 00000000000..edf31e8e97a --- /dev/null +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionHelpers.cs @@ -0,0 +1,322 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Buffers; +using System.Collections.Generic; +using System.Management.Automation.Language; + +namespace System.Management.Automation +{ + /// + /// Shared helper class for common completion helper methods. + /// + internal static class CompletionHelpers + { + private static readonly SearchValues s_defaultCharsToCheck = SearchValues.Create("$`"); + + private const string SingleQuote = "'"; + private const string DoubleQuote = "\""; + + /// + /// Get matching completions from word to complete. + /// This makes it easier to handle different variations of completions with consideration of quotes. + /// + /// The word to complete. + /// The possible completion values to iterate. + /// The optional completion display info mapper delegate for tool tip and list item text. + /// The optional completion result type. Default is Text. + /// The optional match strategy delegate. + /// List of matching completion results. + internal static IEnumerable GetMatchingResults( + string wordToComplete, + IEnumerable possibleCompletionValues, + CompletionDisplayInfoMapper displayInfoMapper = null, + CompletionResultType resultType = CompletionResultType.Text, + MatchStrategy matchStrategy = null) + { + displayInfoMapper ??= DefaultDisplayInfoMapper; + matchStrategy ??= DefaultMatch; + + string quote = HandleDoubleAndSingleQuote(ref wordToComplete); + if (quote != SingleQuote) + { + wordToComplete = NormalizeToExpandableString(wordToComplete); + } + + foreach (string value in possibleCompletionValues) + { + if (matchStrategy(value, wordToComplete)) + { + string completionText = QuoteCompletionText(value, quote); + + (string toolTip, string listItemText) = displayInfoMapper(value); + + yield return new CompletionResult(completionText, listItemText, resultType, toolTip); + } + } + } + + /// + /// Provides the display information for a completion result. + /// This delegate is used to map a string value to its corresponding display information. + /// + /// The input value to be mapped + /// Completion display info containing tool tip and list item text. + internal delegate (string ToolTip, string ListItemText) CompletionDisplayInfoMapper(string value); + + /// + /// Provides the default display information for a completion result. + /// Defaults to using the input value for both the tool tip and list item text. + /// + /// Completion display info containing tool tip and list item text. + internal static readonly CompletionDisplayInfoMapper DefaultDisplayInfoMapper = value + => (value, value); + + /// + /// Normalizes the input string to an expandable string format for PowerShell. + /// + /// The input string to be normalized. + /// The normalized string with special characters replaced by their PowerShell escape sequences. + /// + /// This method replaces special characters in the input string with their PowerShell equivalent escape sequences: + /// + /// Replaces "\r" (carriage return) with "`r". + /// Replaces "\n" (newline) with "`n". + /// Replaces "\t" (tab) with "`t". + /// Replaces "\0" (null) with "`0". + /// Replaces "\a" (bell) with "`a". + /// Replaces "\b" (backspace) with "`b". + /// Replaces "\u001b" (escape character) with "`e". + /// Replaces "\f" (form feed) with "`f". + /// Replaces "\v" (vertical tab) with "`v". + /// + /// + internal static string NormalizeToExpandableString(string value) + => value + .Replace("\r", "`r") + .Replace("\n", "`n") + .Replace("\t", "`t") + .Replace("\0", "`0") + .Replace("\a", "`a") + .Replace("\b", "`b") + .Replace("\u001b", "`e") + .Replace("\f", "`f") + .Replace("\v", "`v"); + + /// + /// Defines a strategy for determining if a value matches a word or pattern. + /// + /// The input string to check for a match. + /// The word or pattern to match against. + /// + /// true if the value matches the specified word or pattern; otherwise, false. + /// + internal delegate bool MatchStrategy(string value, string wordToComplete); + + /// + /// Determines if the given value matches the specified word using a literal, case-insensitive prefix match. + /// + /// + /// true if the value starts with the word (case-insensitively); otherwise, false. + /// + internal static readonly MatchStrategy LiteralMatchOrdinalIgnoreCase = (value, wordToComplete) + => value.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase); + + /// + /// Determines if the given value matches the specified word using wildcard pattern matching. + /// + /// + /// true if the value matches the word as a wildcard pattern; otherwise, false. + /// + /// + /// Wildcard pattern matching allows for flexible matching, where wilcards can represent + /// multiple characters in the input. This strategy is case-insensitive. + /// + internal static readonly MatchStrategy WildcardPatternMatchIgnoreCase = (value, wordToComplete) + => WildcardPattern + .Get(wordToComplete + "*", WildcardOptions.IgnoreCase) + .IsMatch(value); + + /// + /// Determines if the given value matches the specified word considering wildcard characters literally. + /// + /// + /// true if the value matches either the literal normalized word or the wildcard pattern with escaping; + /// otherwise, false. + /// + /// + /// This strategy first attempts a literal prefix match for performance and, if unsuccessful, escapes the word to complete to + /// handle any problematic wildcard characters before performing a wildcard match. + /// + internal static readonly MatchStrategy WildcardPatternEscapeMatch = (value, wordToComplete) + => LiteralMatchOrdinalIgnoreCase(value, wordToComplete) || + WildcardPatternMatchIgnoreCase(value, WildcardPattern.Escape(wordToComplete)); + + /// + /// Determines if the given value matches the specified word taking into account wildcard characters. + /// + /// + /// true if the value matches either the literal normalized word or the wildcard pattern; otherwise, false. + /// + /// + /// This strategy attempts a literal match first for performance and, if unsuccessful, evaluates the word against a wildcard pattern. + /// + internal static readonly MatchStrategy DefaultMatch = (value, wordToComplete) + => LiteralMatchOrdinalIgnoreCase(value, wordToComplete) || + WildcardPatternMatchIgnoreCase(value, wordToComplete); + + /// + /// Removes wrapping quotes from a string and returns the quote used, if present. + /// + /// + /// The string to process, potentially surrounded by single or double quotes. + /// This parameter is updated in-place to exclude the removed quotes. + /// + /// + /// The type of quote detected (single or double), or an empty string if no quote is found. + /// + /// + /// This method checks for single or double quotes at the start and end of the string. + /// If wrapping quotes are detected and match, both are removed; otherwise, only the front quote is removed. + /// The string is updated in-place, and only matching front-and-back quotes are stripped. + /// If no quotes are detected or the input is empty, the original string remains unchanged. + /// + internal static string HandleDoubleAndSingleQuote(ref string wordToComplete) + { + if (string.IsNullOrEmpty(wordToComplete)) + { + return string.Empty; + } + + char frontQuote = wordToComplete[0]; + bool hasFrontSingleQuote = frontQuote.IsSingleQuote(); + bool hasFrontDoubleQuote = frontQuote.IsDoubleQuote(); + + if (!hasFrontSingleQuote && !hasFrontDoubleQuote) + { + return string.Empty; + } + + string quoteInUse = hasFrontSingleQuote ? SingleQuote : DoubleQuote; + + int length = wordToComplete.Length; + if (length == 1) + { + wordToComplete = string.Empty; + return quoteInUse; + } + + char backQuote = wordToComplete[length - 1]; + bool hasBackSingleQuote = backQuote.IsSingleQuote(); + bool hasBackDoubleQuote = backQuote.IsDoubleQuote(); + + bool hasBothFrontAndBackQuotes = + (hasFrontSingleQuote && hasBackSingleQuote) || (hasFrontDoubleQuote && hasBackDoubleQuote); + + if (hasBothFrontAndBackQuotes) + { + wordToComplete = wordToComplete.Substring(1, length - 2); + return quoteInUse; + } + + bool hasFrontQuoteAndNoBackQuote = + (hasFrontSingleQuote || hasFrontDoubleQuote) && !hasBackSingleQuote && !hasBackDoubleQuote; + + if (hasFrontQuoteAndNoBackQuote) + { + wordToComplete = wordToComplete.Substring(1); + return quoteInUse; + } + + return string.Empty; + } + + /// + /// Determines whether the specified completion string requires quotes. + /// Quoting is required if: + /// + /// There are parsing errors in the input string. + /// The parsed token count is not exactly two (the input token + EOF). + /// The first token is a string or a PowerShell keyword containing special characters. + /// The first token is a semi colon or comma token. + /// + /// + /// The input string to analyze for quoting requirements. + /// true if the string requires quotes, false otherwise. + internal static bool CompletionRequiresQuotes(string completion) + { + Parser.ParseInput(completion, out Token[] tokens, out ParseError[] errors); + + bool isExpectedTokenCount = tokens.Length == 2; + + bool requireQuote = errors.Length > 0 || !isExpectedTokenCount; + + Token firstToken = tokens[0]; + bool isStringToken = firstToken is StringToken; + bool isKeywordToken = (firstToken.TokenFlags & TokenFlags.Keyword) != 0; + bool isSemiToken = firstToken.Kind == TokenKind.Semi; + bool isCommaToken = firstToken.Kind == TokenKind.Comma; + + if ((!requireQuote && isStringToken) || (isExpectedTokenCount && isKeywordToken)) + { + requireQuote = ContainsCharsToCheck(firstToken.Text); + } + + else if (isExpectedTokenCount && (isSemiToken || isCommaToken)) + { + requireQuote = true; + } + + return requireQuote; + } + + /// + /// Determines whether the given text contains an escaped newline string. + /// + /// The input string to check for escaped newlines. + /// + /// true if the text contains the escaped Unix-style newline string ("`n") or + /// the Windows-style newline string ("`r`n"); otherwise, false. + /// + private static bool ContainsEscapedNewlineString(string text) + => text.Contains("`n", StringComparison.Ordinal); + + private static bool ContainsCharsToCheck(ReadOnlySpan text) + => text.ContainsAny(s_defaultCharsToCheck); + + /// + /// Quotes a given completion text. + /// + /// + /// The text to be quoted. + /// + /// + /// The quote character to use for enclosing the text. Defaults to a single quote if not provided. + /// + /// + /// The quoted . + /// + internal static string QuoteCompletionText(string completionText, string quote) + { + // Escaped newlines e.g. `r`n need be surrounded with double quotes + if (ContainsEscapedNewlineString(completionText)) + { + return DoubleQuote + completionText + DoubleQuote; + } + + if (!CompletionRequiresQuotes(completionText)) + { + return quote + completionText + quote; + } + + string quoteInUse = string.IsNullOrEmpty(quote) ? SingleQuote : quote; + + if (quoteInUse == SingleQuote) + { + completionText = CodeGeneration.EscapeSingleQuotedStringContent(completionText); + } + + return quoteInUse + completionText + quoteInUse; + } + } +} diff --git a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs index ffb09e2a50d..0554a52ba17 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/CompletionResult.cs @@ -168,26 +168,15 @@ internal static CompletionResult Null /// The text for the tooltip with details to be displayed about the object. public CompletionResult(string completionText, string listItemText, CompletionResultType resultType, string toolTip) { - if (string.IsNullOrEmpty(completionText)) - { - throw PSTraceSource.NewArgumentNullException(nameof(completionText)); - } - - if (string.IsNullOrEmpty(listItemText)) - { - throw PSTraceSource.NewArgumentNullException(nameof(listItemText)); - } + ArgumentException.ThrowIfNullOrEmpty(completionText); + ArgumentException.ThrowIfNullOrEmpty(listItemText); + ArgumentException.ThrowIfNullOrEmpty(toolTip); if (resultType < CompletionResultType.Text || resultType > CompletionResultType.DynamicKeyword) { throw PSTraceSource.NewArgumentOutOfRangeException(nameof(resultType), resultType); } - if (string.IsNullOrEmpty(toolTip)) - { - throw PSTraceSource.NewArgumentNullException(nameof(toolTip)); - } - _completionText = completionText; _listItemText = listItemText; _toolTip = toolTip; diff --git a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs index 777fc6c16f4..c63a8e7f92d 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/ExtensibleCompletion.cs @@ -32,7 +32,7 @@ public class ArgumentCompleterAttribute : Attribute /// The type must implement and have a default constructor. public ArgumentCompleterAttribute(Type type) { - if (type == null || (type.GetInterfaces().All(t => t != typeof(IArgumentCompleter)))) + if (type == null || (type.GetInterfaces().All(static t => t != typeof(IArgumentCompleter)))) { throw PSTraceSource.NewArgumentException(nameof(type)); } @@ -40,19 +40,40 @@ public ArgumentCompleterAttribute(Type type) Type = type; } + /// + /// Initializes a new instance of the class. + /// This constructor is used by derived attributes implementing . + /// + protected ArgumentCompleterAttribute() + { + if (this is not IArgumentCompleterFactory) + { + throw PSTraceSource.NewInvalidOperationException(); + } + } + /// /// This constructor is used primarily via PowerShell scripts. /// /// public ArgumentCompleterAttribute(ScriptBlock scriptBlock) { - if (scriptBlock == null) + if (scriptBlock is null) { throw PSTraceSource.NewArgumentNullException(nameof(scriptBlock)); } ScriptBlock = scriptBlock; } + + internal IArgumentCompleter CreateArgumentCompleter() + { + return Type != null + ? Activator.CreateInstance(Type) as IArgumentCompleter + : this is IArgumentCompleterFactory factory + ? factory.Create() + : null; + } } /// @@ -85,71 +106,176 @@ IEnumerable CompleteArgument( } #nullable restore + /// + /// Creates a new argument completer. + /// + /// + /// If an attribute that derives from implements this interface, + /// it will be used to create the , thus giving a way to parameterize a completer. + /// The derived attribute can have properties or constructor arguments that are used when creating the completer. + /// + /// + /// This example shows the intended usage of to pass arguments to an argument completer. + /// + /// public class NumberCompleterAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory { + /// private readonly int _from; + /// private readonly int _to; + /// + /// public NumberCompleterAttribute(int from, int to){ + /// _from = from; + /// _to = to; + /// } + /// + /// // use the attribute parameters to create a parameterized completer + /// IArgumentCompleter Create() => new NumberCompleter(_from, _to); + /// } + /// + /// class NumberCompleter : IArgumentCompleter { + /// private readonly int _from; + /// private readonly int _to; + /// + /// public NumberCompleter(int from, int to){ + /// _from = from; + /// _to = to; + /// } + /// + /// IEnumerable{CompletionResult} CompleteArgument(string commandName, string parameterName, string wordToComplete, + /// CommandAst commandAst, IDictionary fakeBoundParameters) { + /// for(int i = _from; i < _to; i++) { + /// yield return new CompletionResult(i.ToString()); + /// } + /// } + /// } + /// + /// + public interface IArgumentCompleterFactory + { + /// + /// Creates an instance of a class implementing the interface. + /// + /// An IArgumentCompleter instance. + IArgumentCompleter Create(); + } + + /// + /// Base class for parameterized argument completer attributes. + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] + public abstract class ArgumentCompleterFactoryAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory + { + /// + public abstract IArgumentCompleter Create(); + } + /// /// [Cmdlet(VerbsLifecycle.Register, "ArgumentCompleter", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=528576")] public class RegisterArgumentCompleterCommand : PSCmdlet { + private const string PowerShellSetName = "PowerShellSet"; + private const string NativeCommandSetName = "NativeCommandSet"; + private const string NativeFallbackSetName = "NativeFallbackSet"; + + // Use a key that is unlikely to be a file name or path to indicate the fallback completer for native commands. + internal const string FallbackCompleterKey = "___ps::@@___"; + /// + /// Gets or sets the command names for which the argument completer is registered. /// - [Parameter(ParameterSetName = "NativeSet", Mandatory = true)] - [Parameter(ParameterSetName = "PowerShellSet")] + [Parameter(ParameterSetName = NativeCommandSetName, Mandatory = true)] + [Parameter(ParameterSetName = PowerShellSetName)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CommandName { get; set; } /// + /// Gets or sets the name of the parameter for which the argument completer is registered. /// - [Parameter(ParameterSetName = "PowerShellSet", Mandatory = true)] + [Parameter(ParameterSetName = PowerShellSetName, Mandatory = true)] public string ParameterName { get; set; } /// + /// Gets or sets the script block that will be executed to provide argument completions. /// [Parameter(Mandatory = true)] [AllowNull()] public ScriptBlock ScriptBlock { get; set; } /// + /// Indicates the argument completer is for native commands. /// - [Parameter(ParameterSetName = "NativeSet")] + [Parameter(ParameterSetName = NativeCommandSetName)] public SwitchParameter Native { get; set; } + /// + /// Indicates the argument completer is a fallback for any native commands that don't have a completer registered. + /// + [Parameter(ParameterSetName = NativeFallbackSetName)] + public SwitchParameter NativeFallback { get; set; } + /// /// protected override void EndProcessing() { Dictionary completerDictionary; - if (ParameterName != null) + + if (ParameterSetName is NativeFallbackSetName) { - completerDictionary = Context.CustomArgumentCompleters ?? - (Context.CustomArgumentCompleters = new Dictionary(StringComparer.OrdinalIgnoreCase)); + completerDictionary = Context.NativeArgumentCompleters ??= new(StringComparer.OrdinalIgnoreCase); + + SetKeyValue(completerDictionary, FallbackCompleterKey, ScriptBlock); } - else + else if (ParameterSetName is NativeCommandSetName) { - completerDictionary = Context.NativeArgumentCompleters ?? - (Context.NativeArgumentCompleters = new Dictionary(StringComparer.OrdinalIgnoreCase)); - } + completerDictionary = Context.NativeArgumentCompleters ??= new(StringComparer.OrdinalIgnoreCase); - if (CommandName == null || CommandName.Length == 0) + foreach (string command in CommandName) + { + var key = command?.Trim(); + if (string.IsNullOrEmpty(key)) + { + continue; + } + + SetKeyValue(completerDictionary, key, ScriptBlock); + } + } + else if (ParameterSetName is PowerShellSetName) { - CommandName = new[] { string.Empty }; + completerDictionary = Context.CustomArgumentCompleters ??= new(StringComparer.OrdinalIgnoreCase); + + string paramName = ParameterName.Trim(); + if (paramName.Length is 0) + { + return; + } + + if (CommandName is null || CommandName.Length is 0) + { + SetKeyValue(completerDictionary, paramName, ScriptBlock); + return; + } + + foreach (string command in CommandName) + { + var key = command?.Trim(); + key = string.IsNullOrEmpty(key) + ? paramName + : $"{key}:{paramName}"; + + SetKeyValue(completerDictionary, key, ScriptBlock); + } } - for (int i = 0; i < CommandName.Length; i++) + static void SetKeyValue(Dictionary table, string key, ScriptBlock value) { - var key = CommandName[i]; - if (!string.IsNullOrWhiteSpace(ParameterName)) + if (value is null) { - if (!string.IsNullOrWhiteSpace(key)) - { - key = key + ":" + ParameterName; - } - else - { - key = ParameterName; - } + table.Remove(key); + } + else + { + table[key] = value; } - - completerDictionary[key] = ScriptBlock; } } } diff --git a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs index 0d195280239..2e7457cd812 100644 --- a/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs +++ b/src/System.Management.Automation/engine/CommandCompletion/PseudoParameterBinder.cs @@ -949,8 +949,9 @@ internal enum BindingType /// Indicate the type of the piped-in argument. /// The CommandParameterAst the cursor is pointing at. /// Indicates whether pseudo binding is for argument binding, argument completion, or parameter completion. + /// Indicates if the pseudo binding should bind positional parameters /// PseudoBindingInfo. - internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pipeArgumentType, CommandParameterAst paramAstAtCursor, BindingType bindingType) + internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pipeArgumentType, CommandParameterAst paramAstAtCursor, BindingType bindingType, bool bindPositional = true) { if (command == null) { @@ -981,7 +982,7 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip executionContext.LanguageMode = PSLanguageMode.ConstrainedLanguage; } - _bindingEffective = PrepareCommandElements(executionContext); + _bindingEffective = PrepareCommandElements(executionContext, paramAstAtCursor); } finally { @@ -1008,12 +1009,15 @@ internal PseudoBindingInfo DoPseudoParameterBinding(CommandAst command, Type pip unboundArguments = BindNamedParameters(); _bindingEffective = _currentParameterSetFlag != 0; - // positional binding - unboundArguments = BindPositionalParameter( - unboundArguments, - _currentParameterSetFlag, - _defaultParameterSetFlag, - bindingType); + if (bindPositional) + { + // positional binding + unboundArguments = BindPositionalParameter( + unboundArguments, + _currentParameterSetFlag, + _defaultParameterSetFlag, + bindingType); + } // VFRA/pipeline binding if the given command is a binary cmdlet or a script cmdlet if (!_function) @@ -1185,7 +1189,7 @@ private void InitializeMembers() _duplicateParameters.Clear(); } - private bool PrepareCommandElements(ExecutionContext context) + private bool PrepareCommandElements(ExecutionContext context, CommandParameterAst paramAtCursor) { int commandIndex = 0; bool dotSource = _commandAst.InvocationOperator == TokenKind.Dot; @@ -1194,7 +1198,7 @@ private bool PrepareCommandElements(ExecutionContext context) string commandName = null; try { - processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource); + processor = PrepareFromAst(context, out commandName) ?? context.CreateCommand(commandName, dotSource, forCompletion:true); } catch (RuntimeException) { @@ -1207,20 +1211,46 @@ private bool PrepareCommandElements(ExecutionContext context) bool implementsDynamicParameters = commandProcessor != null && commandProcessor.CommandInfo.ImplementsDynamicParameters; - var argumentsToGetDynamicParameters = implementsDynamicParameters - ? new List(_commandElements.Count) - : null; if (commandProcessor != null || scriptProcessor != null) { // Pre-processing the arguments -- command arguments for (commandIndex++; commandIndex < _commandElements.Count; commandIndex++) { + if (implementsDynamicParameters && _commandElements[commandIndex] == paramAtCursor) + { + // Commands with dynamic parameters will try to bind the command elements. + // A partially complete parameter will most likely cause a binding error and negatively affect the results. + continue; + } + var parameter = _commandElements[commandIndex] as CommandParameterAst; if (parameter != null) { - if (argumentsToGetDynamicParameters != null) + if (implementsDynamicParameters) { - argumentsToGetDynamicParameters.Add(parameter.Extent.Text); + CommandParameterInternal paramToAdd; + if (parameter.Argument is null) + { + paramToAdd = CommandParameterInternal.CreateParameter(parameter.ParameterName, parameter.Extent.Text); + } + else + { + object value; + if (!SafeExprEvaluator.TrySafeEval(parameter.Argument, context, out value)) + { + value = parameter.Argument.Extent.Text; + } + + paramToAdd = CommandParameterInternal.CreateParameterWithArgument( + parameterAst: null, + parameterName: parameter.ParameterName, + parameterText: parameter.Extent.Text, + argumentAst: null, + value: value, + spaceAfterParameter: false); + } + + commandProcessor.AddParameter(paramToAdd); } AstPair parameterArg = parameter.Argument != null @@ -1231,21 +1261,40 @@ private bool PrepareCommandElements(ExecutionContext context) } else { - var dash = _commandElements[commandIndex] as StringConstantExpressionAst; - if (dash != null && dash.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) + object valueToAdd; + ExpressionAst expressionToAdd; + if (_commandElements[commandIndex] is ConstantExpressionAst constant) { - // "-" is represented by StringConstantExpressionAst. Most likely the user type a tab here, - // and we don't want it be treated as an argument - continue; + if (constant.Extent.Text.Equals("-", StringComparison.Ordinal)) + { + // A value of "-" is most likely the user trying to tab here, + // and we don't want it be treated as an argument + continue; + } + + valueToAdd = constant.Value; + expressionToAdd = constant; } + else if (_commandElements[commandIndex] is ExpressionAst expression) + { + if (!SafeExprEvaluator.TrySafeEval(expression, context, out valueToAdd)) + { + valueToAdd = expression.Extent.Text; + } - var expressionArgument = _commandElements[commandIndex] as ExpressionAst; - if (expressionArgument != null) + expressionToAdd = expression; + } + else { - argumentsToGetDynamicParameters?.Add(expressionArgument.Extent.Text); + continue; + } - _arguments.Add(new AstPair(null, expressionArgument)); + if (implementsDynamicParameters) + { + commandProcessor.AddParameter(CommandParameterInternal.CreateArgument(valueToAdd)); } + + _arguments.Add(new AstPair(null, expressionToAdd)); } } } @@ -1255,7 +1304,6 @@ private bool PrepareCommandElements(ExecutionContext context) _function = false; if (implementsDynamicParameters) { - ParameterBinderController.AddArgumentsToCommandProcessor(commandProcessor, argumentsToGetDynamicParameters.ToArray()); bool retryWithNoArgs = false, alreadyRetried = false; do @@ -1358,7 +1406,6 @@ private CommandProcessorBase PrepareFromAst(ExecutionContext context, out string } ast.Visit(exportVisitor); - CommandProcessorBase commandProcessor = null; resolvedCommandName = _commandAst.GetCommandName(); @@ -1862,6 +1909,13 @@ private static AstParameterArgumentPair GetNextPositionalArgument( while (unboundArgumentsIndex < unboundArgumentsCollection.Count) { AstParameterArgumentPair argument = unboundArgumentsCollection[unboundArgumentsIndex++]; + if (argument is AstPair astPair + && astPair.Argument is VariableExpressionAst argumentVariable + && argumentVariable.Splatted) + { + continue; + } + if (!argument.ParameterSpecified) { result = argument; diff --git a/src/System.Management.Automation/engine/CommandCompletion/ScopeArgumentCompleter.cs b/src/System.Management.Automation/engine/CommandCompletion/ScopeArgumentCompleter.cs new file mode 100644 index 00000000000..444ccf79adb --- /dev/null +++ b/src/System.Management.Automation/engine/CommandCompletion/ScopeArgumentCompleter.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation.Language; + +namespace System.Management.Automation +{ + /// + /// Provides argument completion for Scope parameter. + /// + public class ScopeArgumentCompleter : IArgumentCompleter + { + private static readonly string[] s_Scopes = new string[] { "Global", "Local", "Script" }; + + /// + /// Returns completion results for scope 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_Scopes); + } +} diff --git a/src/System.Management.Automation/engine/CommandDiscovery.cs b/src/System.Management.Automation/engine/CommandDiscovery.cs index ee6e5943800..9ca87f4c834 100644 --- a/src/System.Management.Automation/engine/CommandDiscovery.cs +++ b/src/System.Management.Automation/engine/CommandDiscovery.cs @@ -55,7 +55,7 @@ internal CommandLookupEventArgs(string commandName, CommandOrigin commandOrigin, public bool StopSearch { get; set; } /// - /// The CommandInfo obejct for the command that was found. + /// The CommandInfo object for the command that was found. /// public CommandInfo Command { get; set; } @@ -262,6 +262,9 @@ internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry, b /// False if not. Null if command discovery should default to something reasonable /// for the command discovered. /// + /// + /// True if this for parameter completion and script requirements should be ignored. + /// /// /// /// @@ -271,14 +274,15 @@ internal void AddSessionStateCmdletEntryToCache(SessionStateCmdletEntry entry, b /// If the security manager is preventing the command from running. /// internal CommandProcessorBase LookupCommandProcessor(string commandName, - CommandOrigin commandOrigin, bool? useLocalScope) + CommandOrigin commandOrigin, bool? useLocalScope, bool forCompletion = false) { CommandProcessorBase processor = null; CommandInfo commandInfo = LookupCommandInfo(commandName, commandOrigin); if (commandInfo != null) { - processor = LookupCommandProcessor(commandInfo, commandOrigin, useLocalScope, null); + processor = LookupCommandProcessor(commandInfo, commandOrigin, useLocalScope, null, forCompletion); + // commandInfo.Name might be different than commandName - restore the original invocation name processor.Command.MyInvocation.InvocationName = commandName; } @@ -286,7 +290,7 @@ internal CommandProcessorBase LookupCommandProcessor(string commandName, return processor; } - internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, ExecutionContext context) + internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, ExecutionContext context, bool forCompletion = false) { // Check Required Modules if (scriptInfo.RequiresModules != null) @@ -301,12 +305,12 @@ internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, Execut moduleManifestPath: null, manifestProcessingFlags: ModuleCmdletBase.ManifestProcessingFlags.LoadElements | ModuleCmdletBase.ManifestProcessingFlags.WriteErrors, error: out error); - if (error != null) + if (!forCompletion && error is not null) { ScriptRequiresException scriptRequiresException = new ScriptRequiresException( scriptInfo.Name, - new Collection { requiredModule.Name }, + new Collection { requiredModule.GetRequiredModuleNotFoundVersionMessage() }, "ScriptRequiresMissingModules", false, error); @@ -316,113 +320,42 @@ internal static void VerifyRequiredModules(ExternalScriptInfo scriptInfo, Execut } } - private static Collection GetPSSnapinNames(IEnumerable PSSnapins) - { - Collection result = new Collection(); - - foreach (var PSSnapin in PSSnapins) - { - result.Add(BuildPSSnapInDisplayName(PSSnapin)); - } - - return result; - } - - private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState) + private CommandProcessorBase CreateScriptProcessorForSingleShell(ExternalScriptInfo scriptInfo, ExecutionContext context, bool useLocalScope, SessionStateInternal sessionState, bool forCompletion = false) { - VerifyScriptRequirements(scriptInfo, Context); + VerifyScriptRequirements(scriptInfo, Context, forCompletion); - IEnumerable requiresPSSnapIns = scriptInfo.RequiresPSSnapIns; - if (requiresPSSnapIns != null && requiresPSSnapIns.Any()) + if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) { - Collection requiresMissingPSSnapIns = null; - VerifyRequiredSnapins(requiresPSSnapIns, context, out requiresMissingPSSnapIns); - if (requiresMissingPSSnapIns != null) - { - ScriptRequiresException scriptRequiresException = - new ScriptRequiresException( - scriptInfo.Name, - requiresMissingPSSnapIns, - "ScriptRequiresMissingPSSnapIns", - true); - throw scriptRequiresException; - } - } - else - { - // If there were no PSSnapins required but there is a shellID required, then we need - // to error + ScriptRequiresException sre = + new ScriptRequiresException( + scriptInfo.Name, + string.Empty, + string.Empty, + "RequiresShellIDInvalidForSingleShell"); - if (!string.IsNullOrEmpty(scriptInfo.RequiresApplicationID)) - { - ScriptRequiresException sre = - new ScriptRequiresException( - scriptInfo.Name, - string.Empty, - string.Empty, - "RequiresShellIDInvalidForSingleShell"); - - throw sre; - } + throw sre; } return CreateCommandProcessorForScript(scriptInfo, Context, useLocalScope, sessionState); } - private static void VerifyRequiredSnapins(IEnumerable requiresPSSnapIns, ExecutionContext context, out Collection requiresMissingPSSnapIns) - { - requiresMissingPSSnapIns = null; - Dbg.Assert(context.InitialSessionState != null, "PowerShell should be hosted with InitialSessionState"); - - foreach (var requiresPSSnapIn in requiresPSSnapIns) - { - IEnumerable loadedPSSnapIns = null; - loadedPSSnapIns = context.InitialSessionState.GetPSSnapIn(requiresPSSnapIn.Name); - if (loadedPSSnapIns == null || !loadedPSSnapIns.Any()) - { - if (requiresMissingPSSnapIns == null) - { - requiresMissingPSSnapIns = new Collection(); - } - - requiresMissingPSSnapIns.Add(BuildPSSnapInDisplayName(requiresPSSnapIn)); - } - else - { - // the requires PSSnapin is loaded. now check the PSSnapin version - PSSnapInInfo loadedPSSnapIn = loadedPSSnapIns.First(); - Diagnostics.Assert(loadedPSSnapIn.Version != null, - string.Format( - CultureInfo.InvariantCulture, - "Version is null for loaded PSSnapin {0}.", loadedPSSnapIn)); - if (requiresPSSnapIn.Version != null) - { - if (!AreInstalledRequiresVersionsCompatible( - requiresPSSnapIn.Version, loadedPSSnapIn.Version)) - { - if (requiresMissingPSSnapIns == null) - { - requiresMissingPSSnapIns = new Collection(); - } - - requiresMissingPSSnapIns.Add(BuildPSSnapInDisplayName(requiresPSSnapIn)); - } - } - } - } - } - // This method verifies the following 3 elements of #Requires statement // #Requires -RunAsAdministrator // #Requires -PSVersion // #Requires -PSEdition // #Requires -Module - internal static void VerifyScriptRequirements(ExternalScriptInfo scriptInfo, ExecutionContext context) + internal static void VerifyScriptRequirements(ExternalScriptInfo scriptInfo, ExecutionContext context, bool forCompletion = false) { - VerifyElevatedPrivileges(scriptInfo); - VerifyPSVersion(scriptInfo); - VerifyPSEdition(scriptInfo); - VerifyRequiredModules(scriptInfo, context); + // When completing script parameters we don't care if these requirements are met. + // VerifyRequiredModules will attempt to load the required modules which is useful for completion (so the correct types are loaded). + if (!forCompletion) + { + VerifyElevatedPrivileges(scriptInfo); + VerifyPSVersion(scriptInfo); + VerifyPSEdition(scriptInfo); + } + + VerifyRequiredModules(scriptInfo, context, forCompletion); } internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) @@ -431,7 +364,7 @@ internal static void VerifyPSVersion(ExternalScriptInfo scriptInfo) // in single shell mode if (requiresPSVersion != null) { - if (!Utils.IsPSVersionSupported(requiresPSVersion)) + if (!PSVersionInfo.IsValidPSVersion(requiresPSVersion)) { ScriptRequiresException scriptRequiresException = new ScriptRequiresException( @@ -464,11 +397,11 @@ internal static void VerifyPSEdition(ExternalScriptInfo scriptInfo) // if (isRequiresPSEditionSpecified && !isCurrentEditionListed) { - var specifiedEditionsString = string.Join(",", scriptInfo.RequiresPSEditions); + var specifiedEditionsString = string.Join(',', scriptInfo.RequiresPSEditions); var message = StringUtil.Format(DiscoveryExceptions.RequiresPSEditionNotCompatible, scriptInfo.Name, specifiedEditionsString, - PSVersionInfo.PSEdition); + PSVersionInfo.PSEditionValue); var ex = new RuntimeException(message); ex.SetErrorId("ScriptRequiresUnmatchedPSEdition"); ex.SetTargetObject(scriptInfo.Name); @@ -491,32 +424,6 @@ internal static void VerifyElevatedPrivileges(ExternalScriptInfo scriptInfo) } } - /// - /// Used to determine compatibility between the versions in the requires statement and - /// the installed version. The version can be PSSnapin or msh. - /// - /// Versions in the requires statement. - /// Version installed. - /// - /// true if requires and installed's major version match and requires' minor version - /// is smaller than or equal to installed's - /// - /// - /// In PowerShell V2, script requiring PowerShell 1.0 will fail. - /// - private static bool AreInstalledRequiresVersionsCompatible(Version requires, Version installed) - { - return requires.Major == installed.Major && requires.Minor <= installed.Minor; - } - - private static string BuildPSSnapInDisplayName(PSSnapInSpecification PSSnapin) - { - return PSSnapin.Version == null ? - PSSnapin.Name : - StringUtil.Format(DiscoveryExceptions.PSSnapInNameVersion, - PSSnapin.Name, PSSnapin.Version); - } - /// /// Look up a command using a CommandInfo object and return its CommandProcessorBase. /// @@ -529,6 +436,9 @@ private static string BuildPSSnapInDisplayName(PSSnapInSpecification PSSnapin) /// False if not. Null if command discovery should default to something reasonable /// for the command discovered. /// + /// + /// True if this for parameter completion and script requirements should be ignored. + /// /// The session state the commandInfo should be run in. /// /// @@ -539,7 +449,7 @@ private static string BuildPSSnapInDisplayName(PSSnapInSpecification PSSnapin) /// If the security manager is preventing the command from running. /// internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, - CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState) + CommandOrigin commandOrigin, bool? useLocalScope, SessionStateInternal sessionState, bool forCompletion = false) { CommandProcessorBase processor = null; @@ -585,7 +495,7 @@ internal CommandProcessorBase LookupCommandProcessor(CommandInfo commandInfo, scriptInfo.SignatureChecked = true; try { - processor = CreateScriptProcessorForSingleShell(scriptInfo, Context, useLocalScope ?? true, sessionState); + processor = CreateScriptProcessorForSingleShell(scriptInfo, Context, useLocalScope ?? true, sessionState, forCompletion); } catch (ScriptRequiresSyntaxException reqSyntaxException) { @@ -819,10 +729,7 @@ internal static CommandInfo LookupCommandInfo( } // Otherwise, invoke the CommandNotFound handler - if (result == null) - { - result = InvokeCommandNotFoundHandler(commandName, context, originalCommandName, commandOrigin); - } + result ??= InvokeCommandNotFoundHandler(commandName, context, originalCommandName, commandOrigin); } while (false); } else @@ -1053,31 +960,26 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleAutoDiscoveryStart(commandName); CommandInfo result = null; - bool cleanupModuleAnalysisAppDomain = false; try { // If commandName had a slash, it was module-qualified or path-qualified. // In that case, we should not return anything (module-qualified is handled // by the previous call to TryModuleAutoLoading(). - int colonOrBackslash = commandName.IndexOfAny(Utils.Separators.ColonOrBackslash); + int colonOrBackslash = commandName.AsSpan().IndexOfAny('\\', ':'); if (colonOrBackslash != -1) return null; CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Get-Module"); - if ((commandOrigin == CommandOrigin.Internal) || - ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public))) + if (commandOrigin == CommandOrigin.Internal || cmdletInfo?.Visibility == SessionStateEntryVisibility.Public) { // Search for a module with a matching command, as long as the user would have the ability to // import the module. cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module"); - if (((commandOrigin == CommandOrigin.Internal) || - ((cmdletInfo != null) && (cmdletInfo.Visibility == SessionStateEntryVisibility.Public)))) + if (commandOrigin == CommandOrigin.Internal || cmdletInfo?.Visibility == SessionStateEntryVisibility.Public) { discoveryTracer.WriteLine("Executing non module-qualified search: {0}", commandName); context.CommandDiscovery.RegisterLookupCommandInfoAction("ActiveModuleSearch", commandName); - cleanupModuleAnalysisAppDomain = context.TakeResponsibilityForModuleAnalysisAppDomain(); - // Get the available module files, preferring modules from $PSHOME so that user modules don't // override system modules during auto-loading if (etwEnabled) CommandDiscoveryEventSource.Log.SearchingForModuleFilesStart(); @@ -1088,30 +990,33 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, { // WinBlue:69141 - We need to get the full path here because the module path might be C:\Users\User1\DOCUME~1 // While the exportedCommands are cached, they are cached with the full path - string expandedModulePath = IO.Path.GetFullPath(modulePath); - string moduleShortName = System.IO.Path.GetFileNameWithoutExtension(expandedModulePath); + string expandedModulePath = Path.GetFullPath(modulePath); + string moduleShortName = Path.GetFileNameWithoutExtension(expandedModulePath); var exportedCommands = AnalysisCache.GetExportedCommands(expandedModulePath, false, context); if (exportedCommands == null) { continue; } - CommandTypes exportedCommandTypes; // Skip if module only has class or other types and no commands. - if (exportedCommands.TryGetValue(commandName, out exportedCommandTypes)) + if (exportedCommands.TryGetValue(commandName, out CommandTypes exportedCommandTypes)) { - Exception exception; discoveryTracer.WriteLine("Found in module: {0}", expandedModulePath); - Collection matchingModule = AutoloadSpecifiedModule(expandedModulePath, context, + Collection matchingModule = AutoloadSpecifiedModule( + expandedModulePath, + context, cmdletInfo != null ? cmdletInfo.Visibility : SessionStateEntryVisibility.Private, - out exception); - lastError = exception; - if ((matchingModule == null) || (matchingModule.Count == 0)) + out lastError); + + if (matchingModule is null || matchingModule.Count == 0) { - string error = StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, moduleShortName); - CommandNotFoundException commandNotFound = new CommandNotFoundException( + string errorMessage = lastError is null + ? StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModule, commandName, moduleShortName) + : StringUtil.Format(DiscoveryExceptions.CouldNotAutoImportMatchingModuleWithErrorMessage, commandName, moduleShortName, lastError.Message); + + throw new CommandNotFoundException( originalCommandName, lastError, - "CouldNotAutoloadMatchingModule", error); - throw commandNotFound; + "CouldNotAutoloadMatchingModule", + errorMessage); } result = LookupCommandInfo(commandName, commandTypes, searchResolutionOptions, commandOrigin, context); @@ -1142,10 +1047,6 @@ private static CommandInfo TryModuleAutoDiscovery(string commandName, finally { context.CommandDiscovery.UnregisterLookupCommandInfoAction("ActiveModuleSearch", commandName); - if (cleanupModuleAnalysisAppDomain) - { - context.ReleaseResponsibilityForModuleAnalysisAppDomain(); - } } if (etwEnabled) CommandDiscoveryEventSource.Log.ModuleAutoDiscoveryStop(commandName); @@ -1158,7 +1059,7 @@ private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionCon CommandInfo result = null; // If commandName was module-qualified. In that case, we should load the module. - var colonOrBackslash = commandName.IndexOfAny(Utils.Separators.ColonOrBackslash); + var colonOrBackslash = commandName.AsSpan().IndexOfAny('\\', ':'); // If we don't see '\', there is no module specified, so no module to load. // If we see ':' before '\', then we probably have a drive qualified path, not a module name @@ -1169,7 +1070,7 @@ private static CommandInfo TryModuleAutoLoading(string commandName, ExecutionCon string moduleName; // Now we check if there exists the second '\' - var secondBackslash = moduleCommandName.IndexOfAny(Utils.Separators.Backslash); + var secondBackslash = moduleCommandName.IndexOf('\\'); if (secondBackslash == -1) { moduleName = commandName.Substring(0, colonOrBackslash); @@ -1263,10 +1164,8 @@ internal void RegisterLookupCommandInfoAction(string currentAction, string comma case "ActivePostCommand": currentActionSet = _activePostCommand; break; } - if (currentActionSet.Contains(command)) + if (!currentActionSet.Add(command)) throw new InvalidOperationException(); - else - currentActionSet.Add(command); } internal void UnregisterLookupCommandInfoAction(string currentAction, string command) @@ -1280,8 +1179,7 @@ internal void UnregisterLookupCommandInfoAction(string currentAction, string com case "ActivePostCommand": currentActionSet = _activePostCommand; break; } - if (currentActionSet.Contains(command)) - currentActionSet.Remove(command); + currentActionSet.Remove(command); } private readonly HashSet _activePreLookup = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -1325,7 +1223,7 @@ internal LookupPathCollection GetLookupDirectoryPaths() if (_pathCacheKey != null) { - string[] tokenizedPath = _pathCacheKey.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries); + string[] tokenizedPath = _pathCacheKey.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries); _cachedPath = new Collection(); foreach (string directory in tokenizedPath) @@ -1333,11 +1231,17 @@ internal LookupPathCollection GetLookupDirectoryPaths() string tempDir = directory.TrimStart(); if (tempDir.EqualsOrdinalIgnoreCase("~")) { - tempDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); + tempDir = Environment.GetFolderPath( + Environment.SpecialFolder.UserProfile, + Environment.SpecialFolderOption.DoNotVerify); } else if (tempDir.StartsWith("~" + Path.DirectorySeparatorChar)) { - tempDir = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + Path.DirectorySeparatorChar + tempDir.Substring(2); + tempDir = Environment.GetFolderPath( + Environment.SpecialFolder.UserProfile, + Environment.SpecialFolderOption.DoNotVerify) + + Path.DirectorySeparatorChar + + tempDir.Substring(2); } _cachedPath.Add(tempDir); @@ -1417,7 +1321,7 @@ private static void InitPathExtCache(string pathExt) lock (s_lockObject) { s_cachedPathExtCollection = pathExt != null - ? pathExt.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries) + ? pathExt.ToLower().Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries) : Array.Empty(); s_cachedPathExtCollectionWithPs1 = new string[s_cachedPathExtCollection.Length + 1]; s_cachedPathExtCollectionWithPs1[0] = StringLiterals.PowerShellScriptFileExtension; @@ -1489,7 +1393,7 @@ internal IEnumerator GetCmdletInfo(string cmdletName, bool searchAll } // The engine cmdlets get imported (via Import-Module) once when PowerShell starts and the cmdletInfo is added to PSSnapinHelpers._cmdletcache(static) with ModuleName // as "System.Management.Automation.dll" instead of the actual snapin name. The next time we load something in an InitialSessionState, we look at this _cmdletcache and - // if the the assembly is already loaded, we just return the cmdlets back. So, the CmdletInfo has moduleName has "System.Management.Automation.dll". So, when M3P Activity + // if the assembly is already loaded, we just return the cmdlets back. So, the CmdletInfo has moduleName has "System.Management.Automation.dll". So, when M3P Activity // tries to access Microsoft.PowerShell.Core\\Get-Command, it cannot. So, adding an additional check to return the correct cmdletInfo for cmdlets from core modules. else if (InitialSessionState.IsEngineModule(cmdletInfo.ModuleName)) { diff --git a/src/System.Management.Automation/engine/CommandInfo.cs b/src/System.Management.Automation/engine/CommandInfo.cs index 7538d9fb19f..eb5fbf70f3b 100644 --- a/src/System.Management.Automation/engine/CommandInfo.cs +++ b/src/System.Management.Automation/engine/CommandInfo.cs @@ -17,33 +17,27 @@ namespace System.Management.Automation { /// - /// Defines the types of commands that MSH can execute. + /// Defines the types of commands that PowerShell can execute. /// [Flags] public enum CommandTypes { /// /// Aliases create a name that refers to other command types. - /// - /// /// Aliases are only persisted within the execution of a single engine. - /// + /// Alias = 0x0001, /// /// Script functions that are defined by a script block. - /// - /// /// Functions are only persisted within the execution of a single engine. - /// + /// Function = 0x0002, /// /// Script filters that are defined by a script block. - /// - /// /// Filters are only persisted within the execution of a single engine. - /// + /// Filter = 0x0004, /// @@ -52,17 +46,15 @@ public enum CommandTypes Cmdlet = 0x0008, /// - /// An MSH script (*.ps1 file) + /// An PowerShell script (*.ps1 file) /// ExternalScript = 0x0010, /// /// Any existing application (can be console or GUI). - /// - /// /// An application can have any extension that can be executed either directly through CreateProcess /// or indirectly through ShellExecute. - /// + /// Application = 0x0020, /// @@ -77,11 +69,9 @@ public enum CommandTypes /// /// All possible command types. + /// NOTE: a CommandInfo instance will never specify All as its CommandType + /// but All can be used when filtering the CommandTypes. /// - /// - /// Note, a CommandInfo instance will never specify - /// All as its CommandType but All can be used when filtering the CommandTypes. - /// All = Alias | Function | Filter | Cmdlet | Script | ExternalScript | Application | Configuration, } @@ -110,10 +100,7 @@ internal CommandInfo(string name, CommandTypes type) // The name can be empty for functions and filters but it // can't be null - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); Name = name; CommandType = type; @@ -288,10 +275,7 @@ internal void SetCommandType(CommandTypes newType) /// internal void Rename(string newName) { - if (string.IsNullOrEmpty(newName)) - { - throw new ArgumentNullException(nameof(newName)); - } + ArgumentException.ThrowIfNullOrEmpty(newName); Name = newName; } @@ -467,11 +451,8 @@ private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely() processInCurrentThread: true, waitForCompletionInCurrentThread: true); - if (eventArgs.Exception != null) - { - // An exception happened on a different thread, rethrow it here on the correct thread. - eventArgs.Exception.Throw(); - } + // An exception happened on a different thread, rethrow it here on the correct thread. + eventArgs.Exception?.Throw(); return eventArgs.Result; } @@ -481,7 +462,7 @@ private MergedCommandParameterMetadata GetMergedCommandParameterMetadataSafely() return result; } - private class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs + private sealed class GetMergedCommandParameterMetadataSafelyEventArgs : EventArgs { public MergedCommandParameterMetadata Result; public ExceptionDispatchInfo Exception; @@ -529,7 +510,7 @@ private void GetMergedCommandParameterMetadata(out MergedCommandParameterMetadat processor = scriptCommand != null ? new CommandProcessor(scriptCommand, _context, useLocalScope: true, fromScriptFile: false, sessionState: scriptCommand.ScriptBlock.SessionStateInternal ?? Context.EngineSessionState) - : new CommandProcessor((CmdletInfo)this, _context) { UseLocalScope = true }; + : new CommandProcessor((CmdletInfo)this, _context); ParameterBinderController.AddArgumentsToCommandProcessor(processor, Arguments); CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor; @@ -928,7 +909,7 @@ public PSMemberNameAndType(string name, PSTypeName typeName, object value = null /// but can be used where a real type might not be available, in which case the name of the type can be used. /// The type encodes the members of dynamic objects in the type name. /// - internal class PSSyntheticTypeName : PSTypeName + internal sealed class PSSyntheticTypeName : PSTypeName { internal static PSSyntheticTypeName Create(string typename, IList membersTypes) => Create(new PSTypeName(typename), membersTypes); @@ -939,7 +920,7 @@ internal static PSSyntheticTypeName Create(PSTypeName typename, IList(); members.AddRange(membersTypes); - members.Sort((c1, c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase)); + members.Sort(static (c1, c2) => string.Compare(c1.Name, c2.Name, StringComparison.OrdinalIgnoreCase)); return new PSSyntheticTypeName(typeName, typename.Type, members); } @@ -980,7 +961,7 @@ private static string GetMemberTypeProjection(string typename, IList m.Name)) + foreach (var m in members.OrderBy(static m => m.Name)) { if (!IsPSTypeName(m)) { diff --git a/src/System.Management.Automation/engine/CommandMetadata.cs b/src/System.Management.Automation/engine/CommandMetadata.cs index eb59f9140a2..df767f714b0 100644 --- a/src/System.Management.Automation/engine/CommandMetadata.cs +++ b/src/System.Management.Automation/engine/CommandMetadata.cs @@ -847,45 +847,40 @@ internal string GetProxyCommand(string helpComment, bool generateDynamicParamete { if (string.IsNullOrEmpty(helpComment)) { - helpComment = string.Format(CultureInfo.InvariantCulture, @" -.ForwardHelpTargetName {0} -.ForwardHelpCategory {1} -", - _wrappedCommand, _wrappedCommandType); + helpComment = string.Create(CultureInfo.InvariantCulture, $@" +.ForwardHelpTargetName {_wrappedCommand} +.ForwardHelpCategory {_wrappedCommandType} +"); } string dynamicParamblock = string.Empty; if (generateDynamicParameters && this.ImplementsDynamicParameters) { - dynamicParamblock = string.Format(CultureInfo.InvariantCulture, @" + dynamicParamblock = string.Create(CultureInfo.InvariantCulture, $@" dynamicparam -{{{0}}} +{{{GetDynamicParamBlock()}}} -", GetDynamicParamBlock()); +"); } - string result = string.Format(CultureInfo.InvariantCulture, @"{0} -param({1}) + string result = string.Create(CultureInfo.InvariantCulture, $@"{GetDecl()} +param({GetParamBlock()}) -{2}begin -{{{3}}} +{dynamicParamblock}begin +{{{GetBeginBlock()}}} process -{{{4}}} +{{{GetProcessBlock()}}} end -{{{5}}} +{{{GetEndBlock()}}} + +clean +{{{GetCleanBlock()}}} <# -{6} +{CodeGeneration.EscapeBlockCommentContent(helpComment)} #> -", - GetDecl(), - GetParamBlock(), - dynamicParamblock, - GetBeginBlock(), - GetProcessBlock(), - GetEndBlock(), - CodeGeneration.EscapeBlockCommentContent(helpComment)); +"); return result; } @@ -1014,9 +1009,10 @@ internal string GetBeginBlock() commandOrigin = string.Empty; } + string wrappedCommand = CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand); if (_wrappedAnyCmdlet) { - result = string.Format(CultureInfo.InvariantCulture, @" + result = string.Create(CultureInfo.InvariantCulture, $@" try {{ $outBuffer = $null if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer)) @@ -1024,38 +1020,30 @@ internal string GetBeginBlock() $PSBoundParameters['OutBuffer'] = 1 }} - $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{wrappedCommand}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} - $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) + $steppablePipeline = $scriptCmd.GetSteppablePipeline({commandOrigin}) $steppablePipeline.Begin($PSCmdlet) }} catch {{ throw }} -", - CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), - _wrappedCommandType, - commandOrigin - ); +"); } else { - result = string.Format(CultureInfo.InvariantCulture, @" + result = string.Create(CultureInfo.InvariantCulture, $@" try {{ - $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}) + $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('{wrappedCommand}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}) $PSBoundParameters.Add('$args', $args) $scriptCmd = {{& $wrappedCmd @PSBoundParameters }} - $steppablePipeline = $scriptCmd.GetSteppablePipeline({2}) + $steppablePipeline = $scriptCmd.GetSteppablePipeline({commandOrigin}) $steppablePipeline.Begin($myInvocation.ExpectingInput, $ExecutionContext) }} catch {{ throw }} -", - CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), - _wrappedCommandType, - commandOrigin - ); +"); } return result; @@ -1063,6 +1051,11 @@ internal string GetBeginBlock() internal string GetProcessBlock() { + // The reason we wrap scripts in 'try { } catch { throw }' (here and elsewhere) is to turn + // an exception that could be thrown from .NET method invocation into a terminating error + // that can be propagated up. + // By default, an exception thrown from .NET method is not terminating, but when enclosed + // in try/catch, it will be turned into a terminating error. return @" try { $steppablePipeline.Process($_) @@ -1074,9 +1067,10 @@ internal string GetProcessBlock() internal string GetDynamicParamBlock() { - return string.Format(CultureInfo.InvariantCulture, @" + string wrappedCommand = CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand); + return string.Create(CultureInfo.InvariantCulture, $@" try {{ - $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{0}', [System.Management.Automation.CommandTypes]::{1}, $PSBoundParameters) + $targetCmd = $ExecutionContext.InvokeCommand.GetCommand('{wrappedCommand}', [System.Management.Automation.CommandTypes]::{_wrappedCommandType}, $PSBoundParameters) $dynamicParams = @($targetCmd.Parameters.GetEnumerator() | Microsoft.PowerShell.Core\Where-Object {{ $_.Value.IsDynamic }}) if ($dynamicParams.Length -gt 0) {{ @@ -1097,9 +1091,7 @@ internal string GetDynamicParamBlock() }} catch {{ throw }} -", - CodeGeneration.EscapeSingleQuotedStringContent(_wrappedCommand), - _wrappedCommandType); +"); } internal string GetEndBlock() @@ -1113,6 +1105,18 @@ internal string GetEndBlock() "; } + internal string GetCleanBlock() + { + // Here we don't need to enclose the script in a 'try/catch' like elsewhere, because + // 1. the 'Clean' block doesn't propagate up any exception (terminating error); + // 2. only one expression in the script, so nothing else needs to be stopped when invoking the method fails. + return @" + if ($null -ne $steppablePipeline) { + $steppablePipeline.Clean() + } +"; + } + #endregion #region Helper methods for restricting commands needed by implicit and interactive remoting @@ -1228,7 +1232,7 @@ private static CommandMetadata GetRestrictedGetHelp() // This should only be called with 1 valid category ParameterMetadata categoryParameter = new ParameterMetadata("Category", typeof(string[])); - categoryParameter.Attributes.Add(new ValidateSetAttribute(Enum.GetNames(typeof(HelpCategory)))); + categoryParameter.Attributes.Add(new ValidateSetAttribute(Enum.GetNames())); categoryParameter.Attributes.Add(new ValidateCountAttribute(0, 1)); return GetRestrictedCmdlet("Get-Help", null, "https://go.microsoft.com/fwlink/?LinkID=113316", nameParameter, categoryParameter); diff --git a/src/System.Management.Automation/engine/CommandParameter.cs b/src/System.Management.Automation/engine/CommandParameter.cs index e6752ff023b..1c58bb87e29 100644 --- a/src/System.Management.Automation/engine/CommandParameter.cs +++ b/src/System.Management.Automation/engine/CommandParameter.cs @@ -12,14 +12,14 @@ namespace System.Management.Automation [DebuggerDisplay("{ParameterName}")] internal sealed class CommandParameterInternal { - private class Parameter + private sealed class Parameter { internal Ast ast; internal string parameterName; internal string parameterText; } - private class Argument + private sealed class Argument { internal Ast ast; internal object value; @@ -124,10 +124,7 @@ internal bool ArgumentToBeSplatted /// internal void SetArgumentValue(Ast ast, object value) { - if (_argument == null) - { - _argument = new Argument(); - } + _argument ??= new Argument(); _argument.value = value; _argument.ast = ast; diff --git a/src/System.Management.Automation/engine/CommandPathSearch.cs b/src/System.Management.Automation/engine/CommandPathSearch.cs index c00d02c5af2..12c494ad8ea 100644 --- a/src/System.Management.Automation/engine/CommandPathSearch.cs +++ b/src/System.Management.Automation/engine/CommandPathSearch.cs @@ -37,17 +37,17 @@ internal class CommandPathSearch : IEnumerable, IEnumerator /// /// The patterns to search for in the paths. /// - /// - /// Use likely relevant search. + /// + /// The fuzzy matcher to use for fuzzy searching. /// internal CommandPathSearch( string commandName, LookupPathCollection lookupPaths, ExecutionContext context, Collection? acceptableCommandNames, - bool useFuzzyMatch) + FuzzyMatcher? fuzzyMatcher) { - _useFuzzyMatch = useFuzzyMatch; + _fuzzyMatcher = fuzzyMatcher; string[] commandPatterns; if (acceptableCommandNames != null) { @@ -110,7 +110,17 @@ private void ResolveCurrentDirectoryInLookupPaths() sessionState.CurrentDrive.Provider.NameEquals(fileSystemProviderName) && sessionState.IsProviderLoaded(fileSystemProviderName); - string environmentCurrentDirectory = Directory.GetCurrentDirectory(); + string? environmentCurrentDirectory = null; + + try + { + environmentCurrentDirectory = Directory.GetCurrentDirectory(); + } + catch (FileNotFoundException) + { + // This can happen if the current working directory is deleted by another process on non-Windows + // In this case, we'll just ignore it and continue on with the current directory as null + } LocationGlobber pathResolver = _context.LocationGlobber; @@ -346,9 +356,12 @@ public bool MoveNext() /// public void Reset() { + _lookupPathsEnumerator.Dispose(); _lookupPathsEnumerator = _lookupPaths.GetEnumerator(); + _patternEnumerator.Dispose(); _patternEnumerator = _patterns.GetEnumerator(); _currentDirectoryResults = Array.Empty(); + _currentDirectoryResultsEnumerator.Dispose(); _currentDirectoryResultsEnumerator = _currentDirectoryResults.GetEnumerator(); _justReset = true; } @@ -421,13 +434,13 @@ private void GetNewDirectoryResults(string pattern, string directory) // to forcefully use null if pattern is "." if (pattern.Length != 1 || pattern[0] != '.') { - if (_useFuzzyMatch) + if (_fuzzyMatcher is not null) { var files = new List(); var matchingFiles = Directory.EnumerateFiles(directory); foreach (string file in matchingFiles) { - if (FuzzyMatcher.IsFuzzyMatch(Path.GetFileName(file), pattern)) + if (_fuzzyMatcher.IsFuzzyMatch(Path.GetFileName(file), pattern)) { files.Add(file); } @@ -490,8 +503,7 @@ private void GetNewDirectoryResults(string pattern, string directory) if (name.Equals(baseNames[i], StringComparison.OrdinalIgnoreCase) || (!Platform.IsWindows && Platform.NonWindowsIsExecutable(name))) { - if (result == null) - result = new Collection(); + result ??= new Collection(); result.Add(fileNames[i]); break; } @@ -517,8 +529,7 @@ private void GetNewDirectoryResults(string pattern, string directory) if (fileName.EndsWith(allowedExt, StringComparison.OrdinalIgnoreCase) || (!Platform.IsWindows && Platform.NonWindowsIsExecutable(fileName))) { - if (result == null) - result = new Collection(); + result ??= new Collection(); result.Add(fileName); } } @@ -578,7 +589,7 @@ private void GetNewDirectoryResults(string pattern, string directory) private readonly string[] _orderedPathExt; private readonly Collection? _acceptableCommandNames; - private readonly bool _useFuzzyMatch = false; + private readonly FuzzyMatcher? _fuzzyMatcher; #endregion private members } diff --git a/src/System.Management.Automation/engine/CommandProcessor.cs b/src/System.Management.Automation/engine/CommandProcessor.cs index fb1fe81fc54..c0765ca18b6 100644 --- a/src/System.Management.Automation/engine/CommandProcessor.cs +++ b/src/System.Management.Automation/engine/CommandProcessor.cs @@ -101,7 +101,7 @@ internal CommandProcessor(IScriptCommandInfo scriptCommandInfo, ExecutionContext /// internal ParameterBinderController NewParameterBinderController(InternalCommand command) { - if (!(command is Cmdlet cmdlet)) + if (command is not Cmdlet cmdlet) { throw PSTraceSource.NewArgumentException(nameof(command)); } @@ -227,6 +227,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) Context.LanguageMode = scriptCmdletInfo.ScriptBlock.LanguageMode.Value; // If it's from ConstrainedLanguage to FullLanguage, indicate the transition before parameter binding takes place. + // When transitioning to FullLanguage mode, we don't want any ConstrainedLanguage restrictions or incorrect Audit messages. if (oldLanguageMode == PSLanguageMode.ConstrainedLanguage && Context.LanguageMode == PSLanguageMode.FullLanguage) { oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding; @@ -309,13 +310,11 @@ internal override void DoBegin() internal override void ProcessRecord() { // Invoke the Command method with the request object - if (!this.RanBeginAlready) { RanBeginAlready = true; try { - // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) { if (Context._debuggingMode > 0 && Command is not PSScriptCmdlet) @@ -326,12 +325,9 @@ internal override void ProcessRecord() Command.DoBeginProcessing(); } } - // 2004/03/18-JonN This is understood to be - // an FXCOP violation, cleared by KCwalina. - catch (Exception e) // Catch-all OK, 3rd party callout. + catch (Exception e) { - // This cmdlet threw an exception, so - // wrap it and bubble it up. + // This cmdlet threw an exception, so wrap it and bubble it up. throw ManageInvocationException(e); } } @@ -366,6 +362,7 @@ internal override void ProcessRecord() // NOTICE-2004/06/08-JonN 959638 using (commandRuntime.AllowThisCommandToWrite(true)) + using (ParameterBinderBase.bindingTracer.TraceScope("CALLING ProcessRecord")) { if (CmdletParameterBinderController.ObsoleteParameterWarningList != null && CmdletParameterBinderController.ObsoleteParameterWarningList.Count > 0) @@ -400,14 +397,13 @@ internal override void ProcessRecord() } catch (LoopFlowException) { - // Win8:84066 - Don't wrap LoopFlowException, we incorrectly raise a PipelineStoppedException + // Don't wrap LoopFlowException, we incorrectly raise a PipelineStoppedException // which gets caught by a script try/catch if we wrap here. throw; } - // 2004/03/18-JonN This is understood to be - // an FXCOP violation, cleared by KCwalina. - catch (Exception e) // Catch-all OK, 3rd party callout. + catch (Exception e) { + // Catch-all OK, 3rd party callout. exceptionToThrow = e; } finally @@ -691,7 +687,7 @@ private static Cmdlet ConstructInstance(Type type) /// If the constructor for the cmdlet threw an exception. /// /// - /// The type referenced by refered to an + /// The type referenced by referred to an /// abstract type or them member was invoked via a late-binding mechanism. /// /// @@ -782,9 +778,11 @@ private void Init(IScriptCommandInfo scriptCommandInfo) InitCommon(); // If the script has been dotted, throw an error if it's from a different language mode. - if (!this.UseLocalScope) + // Unless it was a script loaded through -File, in which case the danger of dotting other + // language modes (getting internal functions in the user's state) isn't a danger. + if (!this.UseLocalScope && !scriptCmdlet.ShouldRethrowExitException) { - ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context.LanguageMode, Command.MyInvocation); + ValidateCompatibleLanguageMode(scriptCommandInfo.ScriptBlock, _context, Command.MyInvocation); } } diff --git a/src/System.Management.Automation/engine/CommandProcessorBase.cs b/src/System.Management.Automation/engine/CommandProcessorBase.cs index c6825cc6925..ddadf9f7516 100644 --- a/src/System.Management.Automation/engine/CommandProcessorBase.cs +++ b/src/System.Management.Automation/engine/CommandProcessorBase.cs @@ -4,9 +4,8 @@ using System.Collections; using System.Collections.ObjectModel; using System.Management.Automation.Internal; -using System.Management.Automation.Language; - -using Dbg = System.Management.Automation.Diagnostics; +using System.Management.Automation.Security; +using System.Runtime.InteropServices; namespace System.Management.Automation { @@ -46,6 +45,7 @@ internal CommandProcessorBase(CommandInfo commandInfo) string errorTemplate = expAttribute.ExperimentAction == ExperimentAction.Hide ? DiscoveryExceptions.ScriptDisabledWhenFeatureOn : DiscoveryExceptions.ScriptDisabledWhenFeatureOff; + string errorMsg = StringUtil.Format(errorTemplate, expAttribute.ExperimentName); ErrorRecord errorRecord = new ErrorRecord( new InvalidOperationException(errorMsg), @@ -54,6 +54,8 @@ internal CommandProcessorBase(CommandInfo commandInfo) commandInfo); throw new CmdletInvocationException(errorRecord); } + + HasCleanBlock = scriptCommand.ScriptBlock.HasCleanBlock; } CommandInfo = commandInfo; @@ -87,6 +89,11 @@ internal bool AddedToPipelineAlready /// internal CommandInfo CommandInfo { get; set; } + /// + /// Gets whether the command has a 'Clean' block defined. + /// + internal bool HasCleanBlock { get; } + /// /// This indicates whether this command processor is created from /// a script file. @@ -187,11 +194,11 @@ internal bool UseLocalScope /// be used when a script block is being dotted. /// /// The script block being dotted. - /// The current language mode. + /// The current execution context. /// The invocation info about the command. protected static void ValidateCompatibleLanguageMode( ScriptBlock scriptBlock, - PSLanguageMode languageMode, + ExecutionContext context, InvocationInfo invocationInfo) { // If we are in a constrained language mode (Core or Restricted), block it. @@ -200,10 +207,11 @@ protected static void ValidateCompatibleLanguageMode( // functions that were never designed to handle untrusted data. // This function won't be called for NoLanguage mode so the only direction checked is trusted // (FullLanguage mode) script running in a constrained/restricted session. - if ((scriptBlock.LanguageMode.HasValue) && - (scriptBlock.LanguageMode != languageMode) && - ((languageMode == PSLanguageMode.RestrictedLanguage) || - (languageMode == PSLanguageMode.ConstrainedLanguage))) + var languageMode = context.LanguageMode; + if (scriptBlock.LanguageMode.HasValue && + scriptBlock.LanguageMode != languageMode && + (languageMode == PSLanguageMode.RestrictedLanguage || + languageMode == PSLanguageMode.ConstrainedLanguage)) { // Finally check if script block is really just PowerShell commands plus parameters. // If so then it is safe to dot source across language mode boundaries. @@ -219,14 +227,24 @@ protected static void ValidateCompatibleLanguageMode( if (!isSafeToDotSource) { - ErrorRecord errorRecord = new ErrorRecord( - new NotSupportedException( - DiscoveryExceptions.DotSourceNotSupported), - "DotSourceNotSupported", - ErrorCategory.InvalidOperation, - null); - errorRecord.SetInvocationInfo(invocationInfo); - throw new CmdletInvocationException(errorRecord); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ErrorRecord errorRecord = new ErrorRecord( + new NotSupportedException(DiscoveryExceptions.DotSourceNotSupported), + "DotSourceNotSupported", + ErrorCategory.InvalidOperation, + targetObject: null); + errorRecord.SetInvocationInfo(invocationInfo); + throw new CmdletInvocationException(errorRecord); + } + + string scriptBlockId = scriptBlock.GetFileName() ?? string.Empty; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: CommandBaseStrings.WDACLogTitle, + message: StringUtil.Format(CommandBaseStrings.WDACLogMessage, scriptBlockId, scriptBlock.LanguageMode, languageMode), + fqid: "ScriptBlockDotSourceNotAllowed", + dropIntoDebugger: true); } } } @@ -345,10 +363,7 @@ internal void SetCurrentScopeToExecutionScope() // Make sure we have a session state instance for this command. // If one hasn't been explicitly set, then use the session state // available on the engine execution context... - if (CommandSessionState == null) - { - CommandSessionState = Context.EngineSessionState; - } + CommandSessionState ??= Context.EngineSessionState; // Store off the current scope _previousScope = CommandSessionState.CurrentScope; @@ -371,13 +386,10 @@ internal void RestorePreviousScope() Context.EngineSessionState = _previousCommandSessionState; - if (_previousScope != null) - { - // Restore the scope but use the same session state instance we - // got it from because the command may have changed the execution context - // session state... - CommandSessionState.CurrentScope = _previousScope; - } + // Restore the scope but use the same session state instance we + // got it from because the command may have changed the execution context + // session state... + CommandSessionState.CurrentScope = _previousScope; } private SessionStateScope _previousScope; @@ -452,16 +464,14 @@ internal void DoPrepare(IDictionary psDefaultParameterValues) HandleObsoleteCommand(ObsoleteAttribute); } } - catch (Exception) + catch (InvalidComObjectException e) { - if (_useLocalScope) - { - // If we had an exception during Prepare, we're done trying to execute the command - // so the scope we created needs to release any resources it hold.s - CommandSessionState.RemoveScope(CommandScope); - } + // This type of exception could be thrown from parameter binding. + string msg = StringUtil.Format(ParserStrings.InvalidComObjectException, e.Message); + var newEx = new RuntimeException(msg, e); - throw; + newEx.SetErrorId("InvalidComObjectException"); + throw newEx; } finally { @@ -508,26 +518,23 @@ internal virtual void DoBegin() // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // - if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) + if (RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { - _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; + _context.ShellFunctionErrorOutputPipe = commandRuntime.ErrorOutputPipe; } _context.CurrentCommandProcessor = this; + SetCurrentScopeToExecutionScope(); + using (commandRuntime.AllowThisCommandToWrite(true)) + using (ParameterBinderBase.bindingTracer.TraceScope("CALLING BeginProcessing")) { - using (ParameterBinderBase.bindingTracer.TraceScope( - "CALLING BeginProcessing")) + if (Context._debuggingMode > 0 && Command is not PSScriptCmdlet) { - SetCurrentScopeToExecutionScope(); - - if (Context._debuggingMode > 0 && Command is not PSScriptCmdlet) - { - Context.Debugger.CheckCommand(this.Command.MyInvocation); - } - - Command.DoBeginProcessing(); + Context.Debugger.CheckCommand(Command.MyInvocation); } + + Command.DoBeginProcessing(); } } catch (Exception e) @@ -589,20 +596,14 @@ internal virtual void Complete() try { using (commandRuntime.AllowThisCommandToWrite(true)) + using (ParameterBinderBase.bindingTracer.TraceScope("CALLING EndProcessing")) { - using (ParameterBinderBase.bindingTracer.TraceScope( - "CALLING EndProcessing")) - { - this.Command.DoEndProcessing(); - } + this.Command.DoEndProcessing(); } } - // 2004/03/18-JonN This is understood to be - // an FXCOP violation, cleared by KCwalina. catch (Exception e) { - // This cmdlet threw an exception, so - // wrap it and bubble it up. + // This cmdlet threw an exception, wrap it as needed and bubble it up. throw ManageInvocationException(e); } } @@ -631,46 +632,121 @@ internal void DoComplete() // The RedirectShellErrorOutputPipe flag is used by the V2 hosting API to force the // redirection. // - if (this.RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe != null) + if (RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { - _context.ShellFunctionErrorOutputPipe = this.commandRuntime.ErrorOutputPipe; + _context.ShellFunctionErrorOutputPipe = commandRuntime.ErrorOutputPipe; } _context.CurrentCommandProcessor = this; - SetCurrentScopeToExecutionScope(); Complete(); } finally { - OnRestorePreviousScope(); - _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; _context.CurrentCommandProcessor = oldCurrentCommandProcessor; - // Destroy the local scope at this point if there is one... - if (_useLocalScope && CommandScope != null) - { - CommandSessionState.RemoveScope(CommandScope); - } + RestorePreviousScope(); + } + } - // and the previous scope... - if (_previousScope != null) + protected virtual void CleanResource() + { + try + { + using (commandRuntime.AllowThisCommandToWrite(permittedToWriteToPipeline: true)) + using (ParameterBinderBase.bindingTracer.TraceScope("CALLING CleanResource")) { - // Restore the scope but use the same session state instance we - // got it from because the command may have changed the execution context - // session state... - CommandSessionState.CurrentScope = _previousScope; + Command.DoCleanResource(); } + } + catch (HaltCommandException) + { + throw; + } + catch (FlowControlException) + { + throw; + } + catch (Exception e) + { + // This cmdlet threw an exception, so wrap it and bubble it up. + throw ManageInvocationException(e); + } + } + + internal void DoCleanup() + { + // The property 'PropagateExceptionsToEnclosingStatementBlock' controls whether a general exception + // (an exception thrown from a .NET method invocation, or an expression like '1/0') will be turned + // into a terminating error, which will be propagated up and thus stop the rest of the running script. + // It is usually used by TryStatement and TrapStatement, which makes the general exception catch-able. + // + // For the 'Clean' block, we don't want to bubble up the general exception when the command is enclosed + // in a TryStatement or has TrapStatement accompanying, because no exception can escape from 'Clean' and + // thus it's pointless to bubble up the general exception in this case. + // + // Therefore we set this property to 'false' here to mask off the previous setting that could be from a + // TryStatement or TrapStatement. Example: + // PS:1> function b { end {} clean { 1/0; Write-Host 'clean' } } + // PS:2> b + // RuntimeException: Attempted to divide by zero. + // clean + // ## Note that, outer 'try/trap' doesn't affect the general exception happens in 'Clean' block. + // ## so its behavior is consistent regardless of whether the command is enclosed by 'try/catch' or not. + // PS:3> try { b } catch { 'outer catch' } + // RuntimeException: Attempted to divide by zero. + // clean + // + // Be noted that, this doesn't affect the TryStatement/TrapStatement within the 'Clean' block. Example: + // ## 'try/trap' within 'Clean' block makes the general exception catch-able. + // PS:3> function a { end {} clean { try { 1/0; Write-Host 'clean' } catch { Write-Host "caught: $_" } } } + // PS:4> a + // caught: Attempted to divide by zero. + bool oldExceptionPropagationState = _context.PropagateExceptionsToEnclosingStatementBlock; + _context.PropagateExceptionsToEnclosingStatementBlock = false; + + Pipe oldErrorOutputPipe = _context.ShellFunctionErrorOutputPipe; + CommandProcessorBase oldCurrentCommandProcessor = _context.CurrentCommandProcessor; - // Restore the previous session state - if (_previousCommandSessionState != null) + try + { + if (RedirectShellErrorOutputPipe || _context.ShellFunctionErrorOutputPipe is not null) { - Context.EngineSessionState = _previousCommandSessionState; + _context.ShellFunctionErrorOutputPipe = commandRuntime.ErrorOutputPipe; } + + _context.CurrentCommandProcessor = this; + SetCurrentScopeToExecutionScope(); + CleanResource(); + } + finally + { + _context.PropagateExceptionsToEnclosingStatementBlock = oldExceptionPropagationState; + _context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; + _context.CurrentCommandProcessor = oldCurrentCommandProcessor; + + RestorePreviousScope(); } } + internal void ReportCleanupError(Exception exception) + { + var error = exception is IContainsErrorRecord icer + ? icer.ErrorRecord + : new ErrorRecord(exception, "Clean.ReportException", ErrorCategory.NotSpecified, targetObject: null); + + PSObject errorWrap = PSObject.AsPSObject(error); + errorWrap.WriteStream = WriteStreamType.Error; + + var errorPipe = commandRuntime.ErrorMergeTo == MshCommandRuntime.MergeDataStream.Output + ? commandRuntime.OutputPipe + : commandRuntime.ErrorOutputPipe; + + errorPipe.Add(errorWrap); + _context.QuestionMarkVariableValue = false; + } + /// /// For diagnostic purposes. /// @@ -777,23 +853,16 @@ internal PipelineStoppedException ManageInvocationException(Exception e) { do // false loop { - ProviderInvocationException pie = e as ProviderInvocationException; - if (pie != null) + if (e is ProviderInvocationException pie) { - // If a ProviderInvocationException occurred, - // discard the ProviderInvocationException and - // re-wrap in CmdletProviderInvocationException - e = new CmdletProviderInvocationException( - pie, - Command.MyInvocation); + // If a ProviderInvocationException occurred, discard the ProviderInvocationException + // and re-wrap it in CmdletProviderInvocationException. + e = new CmdletProviderInvocationException(pie, Command.MyInvocation); break; } - // 1021203-2005/05/09-JonN - // HaltCommandException will cause the command - // to stop, but not be reported as an error. - // 906445-2005/05/16-JonN - // FlowControlException should not be wrapped + // HaltCommandException will cause the command to stop, but not be reported as an error. + // FlowControlException should not be wrapped. if (e is PipelineStoppedException || e is CmdletInvocationException || e is ActionPreferenceStopException @@ -813,9 +882,7 @@ internal PipelineStoppedException ManageInvocationException(Exception e) } // wrap all other exceptions - e = new CmdletInvocationException( - e, - Command.MyInvocation); + e = new CmdletInvocationException(e, Command.MyInvocation); } while (false); // commandRuntime.ManageException will always throw PipelineStoppedException @@ -943,15 +1010,27 @@ public void Dispose() private void Dispose(bool disposing) { if (_disposed) + { return; + } if (disposing) { - // 2004/03/05-JonN Look into using metadata to check - // whether IDisposable is implemented, in order to avoid - // this expensive reflection cast. - IDisposable id = Command as IDisposable; - if (id != null) + if (UseLocalScope) + { + // Clean up the PS drives that are associated with this local scope. + // This operation may be needed at multiple stages depending on whether the 'clean' block is declared: + // 1. when there is a 'clean' block, it needs to be done only after 'clean' block runs, because the scope + // needs to be preserved until the 'clean' block finish execution. + // 2. when there is no 'clean' block, it needs to be done when + // (1) there is any exception thrown from 'DoPrepare()', 'DoBegin()', 'DoExecute()', or 'DoComplete'; + // (2) OR, the command runs to the end successfully; + // Doing this cleanup at those multiple stages is cumbersome. Since we will always dispose the command in + // the end, doing this cleanup here will cover all the above cases. + CommandSessionState.RemoveScope(CommandScope); + } + + if (Command is IDisposable id) { id.Dispose(); } diff --git a/src/System.Management.Automation/engine/CommandSearcher.cs b/src/System.Management.Automation/engine/CommandSearcher.cs index 9745d2aa9ad..638ccd4ac79 100644 --- a/src/System.Management.Automation/engine/CommandSearcher.cs +++ b/src/System.Management.Automation/engine/CommandSearcher.cs @@ -9,6 +9,7 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Management.Automation.Internal; +using System.Management.Automation.Security; using Dbg = System.Management.Automation.Diagnostics; @@ -24,29 +25,20 @@ internal class CommandSearcher : IEnumerable, IEnumerator - /// - /// The name of the command to look for. - /// - /// - /// Determines which types of commands glob resolution of the name will take place on. - /// - /// - /// The types of commands to look for. - /// - /// - /// The execution context for this engine instance... - /// - /// - /// If is null. - /// - /// - /// If is null or empty. - /// + /// The name of the command to look for. + /// Determines which types of commands glob resolution of the name will take place on. + /// The types of commands to look for. + /// The execution context for this engine instance. + /// The fuzzy matcher to use for fuzzy searching. + /// + /// If is null. + /// If is null or empty. internal CommandSearcher( string commandName, SearchResolutionOptions options, CommandTypes commandTypes, - ExecutionContext context) + ExecutionContext context, + FuzzyMatcher? fuzzyMatcher = null) { Diagnostics.Assert(context != null, "caller to verify context is not null"); Diagnostics.Assert(!string.IsNullOrEmpty(commandName), "caller to verify commandName is valid"); @@ -55,6 +47,7 @@ internal CommandSearcher( _context = context; _commandResolutionOptions = options; _commandTypes = commandTypes; + _fuzzyMatcher = fuzzyMatcher; // Initialize the enumerators this.Reset(); @@ -158,7 +151,7 @@ public bool MoveNext() } else { - // Ok see it it's in the applications list + // Ok, see if it's in the applications list foreach (string path in _context.EngineSessionState.Applications) { if (checkPath(path, _commandName)) @@ -705,8 +698,7 @@ private static bool checkPath(string path, string commandName) foreach (KeyValuePair aliasEntry in _context.EngineSessionState.GetAliasTable()) { if (aliasMatcher.IsMatch(aliasEntry.Key) || - (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName))) + (_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(aliasEntry.Key, _commandName))) { matchingAliases.Add(aliasEntry.Value); } @@ -785,8 +777,7 @@ private static bool checkPath(string path, string commandName) foreach ((string functionName, FunctionInfo functionInfo) in _context.EngineSessionState.GetFunctionTable()) { if (functionMatcher.IsMatch(functionName) || - (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(functionName, _commandName))) + (_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(functionName, _commandName))) { matchingFunction.Add(functionInfo); } @@ -849,11 +840,21 @@ private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInf return false; } - // Don't return untrusted commands to trusted functions - if ((result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage) && - (executionContext.LanguageMode == PSLanguageMode.FullLanguage)) + // Don't return untrusted commands to trusted functions. + if (result.DefiningLanguageMode == PSLanguageMode.ConstrainedLanguage && executionContext.LanguageMode == PSLanguageMode.FullLanguage) { - return true; + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + return true; + } + + // This audit log message is to inform the user that an expected command will not be available because it is not trusted + // when the machine is in policy enforcement mode. + SystemPolicy.LogWDACAuditMessage( + context: executionContext, + title: CommandBaseStrings.SearcherWDACLogTitle, + message: StringUtil.Format(CommandBaseStrings.SearcherWDACLogMessage, result.Name, result.ModuleName ?? string.Empty), + fqid: "CommandSearchFailureForUntrustedCommand"); } // Don't allow invocation of trusted functions from debug breakpoints. @@ -928,10 +929,7 @@ private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInf } } - if (module == null) - { - module = modules[0]; - } + module ??= modules[0]; } return module; @@ -953,24 +951,13 @@ private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInf if (result != null) { - if (result is FilterInfo) + var formatString = result switch { - CommandDiscovery.discoveryTracer.WriteLine( - "Filter found: {0}", - function); - } - else if (result is ConfigurationInfo) - { - CommandDiscovery.discoveryTracer.WriteLine( - "Configuration found: {0}", - function); - } - else - { - CommandDiscovery.discoveryTracer.WriteLine( - "Function found: {0} {1}", - function); - } + FilterInfo => "Filter found: {0}", + ConfigurationInfo => "Configuration found: {0}", + _ => "Function found: {0}", + }; + CommandDiscovery.discoveryTracer.WriteLine(formatString, function); } else { @@ -1021,10 +1008,8 @@ private static bool ShouldSkipCommandResolutionForConstrainedLanguage(CommandInf { foreach (CmdletInfo cmdlet in cmdletList) { - if (cmdletMatcher != null && - cmdletMatcher.IsMatch(cmdlet.Name) || - (_commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch) && - FuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) + if ((cmdletMatcher is not null && cmdletMatcher.IsMatch(cmdlet.Name)) || + (_fuzzyMatcher is not null && _fuzzyMatcher.IsFuzzyMatch(cmdlet.Name, _commandName))) { if (string.IsNullOrEmpty(moduleName) || moduleName.Equals(cmdlet.ModuleName, StringComparison.OrdinalIgnoreCase)) { @@ -1454,7 +1439,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) // If the command contains any path separators, we can't // do the path lookup - if (possiblePath.IndexOfAny(Utils.Separators.Directory) != -1) + if (possiblePath.AsSpan().IndexOfAny('\\', '/') != -1) { result = CanDoPathLookupResult.DirectorySeparator; break; @@ -1463,7 +1448,7 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) // If the command contains any invalid path characters, we can't // do the path lookup - if (possiblePath.IndexOfAny(Path.GetInvalidPathChars()) != -1) + if (PathUtils.ContainsInvalidPathChars(possiblePath)) { result = CanDoPathLookupResult.IllegalCharacters; break; @@ -1499,6 +1484,11 @@ private static CanDoPathLookupResult CanDoPathLookup(string possiblePath) /// private readonly ExecutionContext _context; + /// + /// The fuzzy matcher to use for fuzzy searching. + /// + private readonly FuzzyMatcher? _fuzzyMatcher; + /// /// A routine to initialize the path searcher... /// @@ -1531,7 +1521,7 @@ private void setupPathSearcher() _context.CommandDiscovery.GetLookupDirectoryPaths(), _context, acceptableCommandNames: null, - useFuzzyMatch: _commandResolutionOptions.HasFlag(SearchResolutionOptions.FuzzyMatch)); + _fuzzyMatcher); } else { @@ -1547,7 +1537,7 @@ private void setupPathSearcher() _context.CommandDiscovery.GetLookupDirectoryPaths(), _context, ConstructSearchPatternsFromName(_commandName, commandDiscovery: true), - useFuzzyMatch: false); + fuzzyMatcher: null); } else if (_canDoPathLookupResult == CanDoPathLookupResult.PathIsRooted) { @@ -1571,7 +1561,7 @@ private void setupPathSearcher() directoryCollection, _context, ConstructSearchPatternsFromName(fileName, commandDiscovery: true), - useFuzzyMatch: false); + fuzzyMatcher: null); } else { @@ -1611,7 +1601,7 @@ private void setupPathSearcher() directoryCollection, _context, ConstructSearchPatternsFromName(fileName, commandDiscovery: true), - useFuzzyMatch: false); + fuzzyMatcher: null); } else { @@ -1730,17 +1720,14 @@ internal enum SearchResolutionOptions CommandNameIsPattern = 0x04, SearchAllScopes = 0x08, - /// Use fuzzy matching. - FuzzyMatch = 0x10, - /// /// Enable searching for cmdlets/functions by abbreviation expansion. /// - UseAbbreviationExpansion = 0x20, + UseAbbreviationExpansion = 0x10, /// /// Enable resolving wildcard in paths. /// - ResolveLiteralThenPathPatterns = 0x40 + ResolveLiteralThenPathPatterns = 0x20 } } diff --git a/src/System.Management.Automation/engine/CommonCommandParameters.cs b/src/System.Management.Automation/engine/CommonCommandParameters.cs index 376b9d0adbf..9dc92d817aa 100644 --- a/src/System.Management.Automation/engine/CommonCommandParameters.cs +++ b/src/System.Management.Automation/engine/CommonCommandParameters.cs @@ -59,7 +59,7 @@ public SwitchParameter Verbose /// /// /// This parameter tells the command to provide Programmer/Support type - /// messages to understand what is really occuring and give the user the + /// messages to understand what is really occurring and give the user the /// opportunity to stop or debug the situation. /// [Parameter] @@ -123,6 +123,27 @@ public ActionPreference InformationAction set { _commandRuntime.InformationPreference = value; } } + /// + /// Gets or sets the value of the ProgressAction parameter for the cmdlet. + /// + /// + /// This parameter tells the command what to do when a progress record occurs. + /// + /// + [Parameter] + [Alias("proga")] + public ActionPreference ProgressAction + { + get { return _commandRuntime.ProgressPreference; } + + set { _commandRuntime.ProgressPreference = value; } + } + /// /// Gets or sets the value of the ErrorVariable parameter for the cmdlet. /// @@ -204,7 +225,7 @@ public string OutVariable /// This parameter configures the number of objects to buffer before calling the downstream Cmdlet /// [Parameter] - [ValidateRangeAttribute(0, Int32.MaxValue)] + [ValidateRange(0, Int32.MaxValue)] [Alias("ob")] public int OutBuffer { diff --git a/src/System.Management.Automation/engine/CompiledCommandParameter.cs b/src/System.Management.Automation/engine/CompiledCommandParameter.cs index dc74210bda5..d2ca1aedd91 100644 --- a/src/System.Management.Automation/engine/CompiledCommandParameter.cs +++ b/src/System.Management.Automation/engine/CompiledCommandParameter.cs @@ -440,8 +440,7 @@ private void ProcessAttribute( ValidateArgumentsAttribute validateAttr = attribute as ValidateArgumentsAttribute; if (validateAttr != null) { - if (validationAttributes == null) - validationAttributes = new Collection(); + validationAttributes ??= new Collection(); validationAttributes.Add(validateAttr); if ((attribute is ValidateNotNullAttribute) || (attribute is ValidateNotNullOrEmptyAttribute)) { @@ -473,8 +472,7 @@ private void ProcessAttribute( ArgumentTransformationAttribute argumentAttr = attribute as ArgumentTransformationAttribute; if (argumentAttr != null) { - if (argTransformationAttributes == null) - argTransformationAttributes = new Collection(); + argTransformationAttributes ??= new Collection(); argTransformationAttributes.Add(argumentAttr); return; } @@ -649,7 +647,7 @@ internal ParameterCollectionTypeInformation(Type type) // to an ICollection is via reflected calls to Add(T), // but the advantage over plain IList is that we can typecast the elements. Type interfaceICollection = - Array.Find(interfaces, i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)); + Array.Find(interfaces, static i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICollection<>)); if (interfaceICollection != null) { // We only deal with the first type for which ICollection is implemented diff --git a/src/System.Management.Automation/engine/CoreAdapter.cs b/src/System.Management.Automation/engine/CoreAdapter.cs index 48077bbafd4..136083d04d7 100644 --- a/src/System.Management.Automation/engine/CoreAdapter.cs +++ b/src/System.Management.Automation/engine/CoreAdapter.cs @@ -38,7 +38,7 @@ namespace System.Management.Automation internal abstract class Adapter { /// - /// Tracer for this and derivate classes. + /// Tracer for this and derivative classes. /// [TraceSource("ETS", "Extended Type System")] protected static PSTraceSource tracer = PSTraceSource.GetTracer("ETS", "Extended Type System"); @@ -833,7 +833,7 @@ private static Type GetArgumentType(object argument, bool isByRefParameter) return GetArgumentType(PSObject.Base(psref.Value), isByRefParameter: false); } - return argument.GetType(); + return GetObjectType(argument, debase: false); } internal static ConversionRank GetArgumentConversionRank(object argument, Type parameterType, bool isByRef, bool allowCastingToByRefLikeType) @@ -1157,8 +1157,8 @@ private static int CompareTypeSpecificity(OverloadCandidate candidate1, Overload return 0; } - Type[] params1 = GetGenericMethodDefinitionIfPossible(candidate1.method.method).GetParameters().Select(p => p.ParameterType).ToArray(); - Type[] params2 = GetGenericMethodDefinitionIfPossible(candidate2.method.method).GetParameters().Select(p => p.ParameterType).ToArray(); + Type[] params1 = GetGenericMethodDefinitionIfPossible(candidate1.method.method).GetParameters().Select(static p => p.ParameterType).ToArray(); + Type[] params2 = GetGenericMethodDefinitionIfPossible(candidate2.method.method).GetParameters().Select(static p => p.ParameterType).ToArray(); return CompareTypeSpecificity(params1, params2); } @@ -1177,7 +1177,7 @@ private static MethodBase GetGenericMethodDefinitionIfPossible(MethodBase method } [DebuggerDisplay("OverloadCandidate: {method.methodDefinition}")] - private class OverloadCandidate + private sealed class OverloadCandidate { internal MethodInformation method; internal ParameterInformation[] parameters; @@ -1363,7 +1363,7 @@ internal static MethodInformation FindBestMethod( Type targetType = methodInfo.method.DeclaringType; if (targetType != invocationConstraints.MethodTargetType && targetType.IsSubclassOf(invocationConstraints.MethodTargetType)) { - var parameterTypes = methodInfo.method.GetParameters().Select(parameter => parameter.ParameterType).ToArray(); + var parameterTypes = methodInfo.method.GetParameters().Select(static parameter => parameter.ParameterType).ToArray(); var targetTypeMethod = invocationConstraints.MethodTargetType.GetMethod(methodInfo.method.Name, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, parameterTypes, null); if (targetTypeMethod != null && (targetTypeMethod.IsPublic || targetTypeMethod.IsFamily || targetTypeMethod.IsFamilyOrAssembly)) @@ -1377,6 +1377,27 @@ internal static MethodInformation FindBestMethod( return methodInfo; } + private static Type[] ResolveGenericTypeParameters(object[] genericTypeParameters) + { + if (genericTypeParameters is null || genericTypeParameters.Length == 0) + { + return null; + } + + Type[] genericParamTypes = new Type[genericTypeParameters.Length]; + for (int i = 0; i < genericTypeParameters.Length; i++) + { + genericParamTypes[i] = genericTypeParameters[i] switch + { + Type paramType => paramType, + ITypeName paramTypeName => TypeOps.ResolveTypeName(paramTypeName, paramTypeName.Extent), + _ => throw new ArgumentException("Unexpected value"), + }; + } + + return genericParamTypes; + } + private static MethodInformation FindBestMethodImpl( MethodInformation[] methods, PSMethodInvocationConstraints invocationConstraints, @@ -1394,59 +1415,84 @@ private static MethodInformation FindBestMethodImpl( // be turned into an array. // We also skip the optimization if the number of arguments and parameters is different // so we let the loop deal with possible optional parameters. - if ((methods.Length == 1) && - (!methods[0].hasVarArgs) && - (!methods[0].isGeneric) && - (methods[0].method == null || !(methods[0].method.DeclaringType.IsGenericTypeDefinition)) && + if (methods.Length == 1 + && !methods[0].hasVarArgs // generic methods need to be double checked in a loop below - generic methods can be rejected if type inference fails - (methods[0].parameters.Length == arguments.Length)) + && !methods[0].isGeneric + && (methods[0].method is null || !methods[0].method.DeclaringType.IsGenericTypeDefinition) + && methods[0].parameters.Length == arguments.Length) { return methods[0]; } - Type[] argumentTypes = arguments.Select(EffectiveArgumentType).ToArray(); - List candidates = new List(); + Type[] genericParamTypes = ResolveGenericTypeParameters(invocationConstraints?.GenericTypeParameters); + var candidates = new List(); + for (int i = 0; i < methods.Length; i++) { - MethodInformation method = methods[i]; + MethodInformation methodInfo = methods[i]; - if (method.method != null && method.method.DeclaringType.IsGenericTypeDefinition) + if (methodInfo.method?.DeclaringType.IsGenericTypeDefinition == true + || (!methodInfo.isGeneric && genericParamTypes is not null)) { - continue; // skip methods defined by an *open* generic type + // If method is defined by an *open* generic type, or + // if generic parameters were provided and this method isn't generic, skip it. + continue; } - if (method.isGeneric) + if (methodInfo.isGeneric) { - Type[] argumentTypesForTypeInference = new Type[argumentTypes.Length]; - Array.Copy(argumentTypes, argumentTypesForTypeInference, argumentTypes.Length); - if (invocationConstraints != null && invocationConstraints.ParameterTypes != null) + if (genericParamTypes is not null) + { + try + { + // This cast is safe, because + // 1. Only ConstructorInfo and MethodInfo derive from MethodBase + // 2. ConstructorInfo.IsGenericMethod is always false + var originalMethod = (MethodInfo)methodInfo.method; + methodInfo = new MethodInformation( + originalMethod.MakeGenericMethod(genericParamTypes), + parametersToIgnore: 0); + } + catch (ArgumentException) + { + // Just skip this possibility if the generic type parameters can't be used to make + // a valid generic method here. + continue; + } + } + else { - int parameterIndex = 0; - foreach (Type typeConstraintFromCallSite in invocationConstraints.ParameterTypes) + // Infer the generic method when generic parameter types are not specified. + Type[] argumentTypes = arguments.Select(EffectiveArgumentType).ToArray(); + Type[] paramConstraintTypes = invocationConstraints?.ParameterTypes; + + if (paramConstraintTypes is not null) { - if (typeConstraintFromCallSite != null) + for (int k = 0; k < paramConstraintTypes.Length; k++) { - argumentTypesForTypeInference[parameterIndex] = typeConstraintFromCallSite; + if (paramConstraintTypes[k] is not null) + { + argumentTypes[k] = paramConstraintTypes[k]; + } } - - parameterIndex++; } - } - method = TypeInference.Infer(method, argumentTypesForTypeInference); - if (method == null) - { - // Skip generic methods for which we cannot infer type arguments - continue; + methodInfo = TypeInference.Infer(methodInfo, argumentTypes); + if (methodInfo is null) + { + // Skip generic methods for which we cannot infer type arguments + continue; + } } } - if (!IsInvocationTargetConstraintSatisfied(method, invocationConstraints)) + if (!IsInvocationTargetConstraintSatisfied(methodInfo, invocationConstraints)) { continue; } - ParameterInformation[] parameters = method.parameters; + ParameterInformation[] parameters = methodInfo.parameters; if (arguments.Length != parameters.Length) { // Skip methods w/ an incorrect # of arguments. @@ -1454,7 +1500,7 @@ private static MethodInformation FindBestMethodImpl( if (arguments.Length > parameters.Length) { // If too many args,it's only OK if the method is varargs. - if (!method.hasVarArgs) + if (!methodInfo.hasVarArgs) { continue; } @@ -1462,12 +1508,12 @@ private static MethodInformation FindBestMethodImpl( else { // Too few args, OK if there are optionals, or varargs with the param array omitted - if (!method.hasOptional && (!method.hasVarArgs || (arguments.Length + 1) != parameters.Length)) + if (!methodInfo.hasOptional && (!methodInfo.hasVarArgs || (arguments.Length + 1) != parameters.Length)) { continue; } - if (method.hasOptional) + if (methodInfo.hasOptional) { // Count optionals. This code is rarely hit, mainly when calling code in the // assembly Microsoft.VisualBasic. If it were more frequent, the optional count @@ -1490,7 +1536,7 @@ private static MethodInformation FindBestMethodImpl( } } - OverloadCandidate candidate = new OverloadCandidate(method, arguments.Length); + OverloadCandidate candidate = new OverloadCandidate(methodInfo, arguments.Length); for (int j = 0; candidate != null && j < parameters.Length; j++) { ParameterInformation parameter = parameters[j]; @@ -1581,7 +1627,7 @@ private static MethodInformation FindBestMethodImpl( if (candidates.Count == 0) { - if ((methods.Length > 0) && (methods.All(m => m.method != null && m.method.DeclaringType.IsGenericTypeDefinition && m.method.IsStatic))) + if (methods.Length > 0 && methods.All(static m => m.method != null && m.method.DeclaringType.IsGenericTypeDefinition && m.method.IsStatic)) { errorId = "CannotInvokeStaticMethodOnUninstantiatedGenericType"; errorMsg = string.Format( @@ -1590,6 +1636,16 @@ private static MethodInformation FindBestMethodImpl( methods[0].method.DeclaringType.FullName); return null; } + else if (genericParamTypes is not null) + { + errorId = "MethodCountCouldNotFindBestGeneric"; + errorMsg = string.Format( + ExtendedTypeSystem.MethodGenericArgumentCountException, + methods[0].method.Name, + genericParamTypes.Length, + arguments.Length); + return null; + } else { errorId = "MethodCountCouldNotFindBest"; @@ -1614,18 +1670,21 @@ private static MethodInformation FindBestMethodImpl( internal static Type EffectiveArgumentType(object arg) { - if (arg != null) + arg = PSObject.Base(arg); + if (arg is null) + { + return typeof(LanguagePrimitives.Null); + } + + if (arg is object[] array && array.Length > 0) { - arg = PSObject.Base(arg); - object[] argAsArray = arg as object[]; - if (argAsArray != null && argAsArray.Length > 0 && PSObject.Base(argAsArray[0]) != null) + Type firstType = GetObjectType(array[0], debase: true); + if (firstType is not null) { - Type firstType = PSObject.Base(argAsArray[0]).GetType(); bool allSameType = true; - - for (int j = 1; j < argAsArray.Length; ++j) + for (int j = 1; j < array.Length; ++j) { - if (argAsArray[j] == null || firstType != PSObject.Base(argAsArray[j]).GetType()) + if (firstType != GetObjectType(array[j], debase: true)) { allSameType = false; break; @@ -1637,13 +1696,19 @@ internal static Type EffectiveArgumentType(object arg) return firstType.MakeArrayType(); } } - - return arg.GetType(); } - else + + return GetObjectType(arg, debase: false); + } + + internal static Type GetObjectType(object obj, bool debase) + { + if (debase) { - return typeof(LanguagePrimitives.Null); + obj = PSObject.Base(obj); } + + return obj == NullString.Value ? typeof(string) : obj?.GetType(); } internal static void SetReferences(object[] arguments, MethodInformation methodInformation, object[] originalArguments) @@ -1658,7 +1723,7 @@ internal static void SetReferences(object[] arguments, MethodInformation methodI // It still might be an PSObject wrapping an PSReference if (originalArgumentReference == null) { - if (!(originalArgument is PSObject originalArgumentObj)) + if (originalArgument is not PSObject originalArgumentObj) { continue; } @@ -1761,7 +1826,7 @@ internal static object[] GetMethodArgumentsBase(string methodName, } // We are going to put all the remaining arguments into an array - // and convert them to the propper type, if necessary to be the + // and convert them to the proper type, if necessary to be the // one argument for this last parameter int remainingArgumentCount = arguments.Length - parametersLength + 1; if (remainingArgumentCount == 1 && arguments[arguments.Length - 1] == null) @@ -1813,7 +1878,7 @@ internal static object[] GetMethodArgumentsBase(string methodName, } /// - /// Auxiliary method in MethodInvoke to set newArguments[index] with the propper value. + /// Auxiliary method in MethodInvoke to set newArguments[index] with the proper value. /// /// Used for the MethodException that might be thrown. /// The complete array of arguments. @@ -2165,7 +2230,7 @@ internal object Invoke(object target, object[] arguments) // be thrown when converting arguments to the ByRef-like parameter types. // // So when reaching here, we only care about (1) if the method return type is - // BeRef-like; (2) if it's a constrcutor of a ByRef-like type. + // BeRef-like; (2) if it's a constructor of a ByRef-like type. if (method is ConstructorInfo ctor) { @@ -2202,10 +2267,7 @@ internal object Invoke(object target, object[] arguments) if (!_useReflection) { - if (_methodInvoker == null) - { - _methodInvoker = GetMethodInvoker(methodInfo); - } + _methodInvoker ??= GetMethodInvoker(methodInfo); if (_methodInvoker != null) { @@ -2616,7 +2678,7 @@ internal class MethodCacheEntry : CacheEntry /// internal Func PSMethodCtor; - internal MethodCacheEntry(MethodBase[] methods) + internal MethodCacheEntry(IList methods) { methodInformationStructures = DotNetAdapter.GetMethodInformationArray(methods); } @@ -2773,7 +2835,7 @@ internal PropertyCacheEntry(PropertyInfo property) // Get the public or protected getter MethodInfo propertyGetter = property.GetGetMethod(true); - if (propertyGetter != null && (propertyGetter.IsPublic || propertyGetter.IsFamily)) + if (propertyGetter != null && (propertyGetter.IsPublic || propertyGetter.IsFamily || propertyGetter.IsFamilyOrAssembly)) { this.isStatic = propertyGetter.IsStatic; // Delegate is initialized later to avoid jit if it's not called @@ -2785,7 +2847,7 @@ internal PropertyCacheEntry(PropertyInfo property) // Get the public or protected setter MethodInfo propertySetter = property.GetSetMethod(true); - if (propertySetter != null && (propertySetter.IsPublic || propertySetter.IsFamily)) + if (propertySetter != null && (propertySetter.IsPublic || propertySetter.IsFamily || propertySetter.IsFamilyOrAssembly)) { this.isStatic = propertySetter.IsStatic; } @@ -2991,10 +3053,7 @@ internal override bool IsHidden { get { - if (_isHidden == null) - { - _isHidden = member.GetCustomAttributes(typeof(HiddenAttribute), inherit: false).Length != 0; - } + _isHidden ??= member.GetCustomAttributes(typeof(HiddenAttribute), inherit: false).Length != 0; return _isHidden.Value; } @@ -3075,9 +3134,8 @@ private static void AddOverload(List previousMethodEntry, MethodInfo private static void PopulateMethodReflectionTable(Type type, MethodInfo[] methods, CacheTable typeMethods) { - for (int i = 0; i < methods.Length; i++) + foreach (MethodInfo method in methods) { - MethodInfo method = methods[i]; if (method.DeclaringType == type) { string methodName = method.Name; @@ -3102,7 +3160,7 @@ private static void PopulateMethodReflectionTable(Type type, MethodInfo[] method private static void PopulateMethodReflectionTable(ConstructorInfo[] ctors, CacheTable typeMethods) { - foreach (var ctor in ctors) + foreach (ConstructorInfo ctor in ctors) { var previousMethodEntry = (List)typeMethods["new"]; if (previousMethodEntry == null) @@ -3127,26 +3185,14 @@ private static void PopulateMethodReflectionTable(ConstructorInfo[] ctors, Cache /// BindingFlags to use. private static void PopulateMethodReflectionTable(Type type, CacheTable typeMethods, BindingFlags bindingFlags) { - Type typeToGetMethod = type; - - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up - // the derivation chain to find the first public parent, and use reflection methods on the public parent. - if (!TypeResolver.IsPublic(type) && DisallowPrivateReflection(type)) - { - typeToGetMethod = GetFirstPublicParentType(type); - } + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (typeToGetMethod != null) - { - MethodInfo[] methods = typeToGetMethod.GetMethods(bindingFlags); - PopulateMethodReflectionTable(typeToGetMethod, methods, typeMethods); - } + MethodInfo[] methods = type.GetMethods(bindingFlags); + PopulateMethodReflectionTable(type, methods, typeMethods); Type[] interfaces = type.GetInterfaces(); - for (int interfaceIndex = 0; interfaceIndex < interfaces.Length; interfaceIndex++) + foreach (Type interfaceType in interfaces) { - var interfaceType = interfaces[interfaceIndex]; if (!TypeResolver.IsPublic(interfaceType)) { continue; @@ -3154,41 +3200,50 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth if (interfaceType.IsGenericType && type.IsArray) { - continue; // GetInterfaceMap is not supported in this scenario... not sure if we need to do something special here... + // A bit of background: Array doesn't directly support any generic interface at all. Instead, a stub class + // named 'SZArrayHelper' provides these generic interfaces at runtime for zero-based one-dimension arrays. + // This is why '[object[]].GetInterfaceMap([ICollection[object]])' throws 'ArgumentException'. + // (see https://stackoverflow.com/a/31883327) + // + // We had always been skipping generic interfaces for array types because 'GetInterfaceMap' doesn't work + // for it. Today, even though we don't use 'GetInterfaceMap' anymore, the same code is kept here because + // methods from generic interfaces of an array type could cause ambiguity in method overloads resolution. + // For example, "$objs = @(1,2,3,4); $objs.Contains(1)" would fail because there would be 2 overloads of + // the 'Contains' methods which are equally good matches for the call. + // bool IList.Contains(System.Object value) + // bool ICollection[Object].Contains(System.Object item) + continue; } - MethodInfo[] methods; - if (type.IsInterface) - { - methods = interfaceType.GetMethods(bindingFlags); - } - else - { - InterfaceMapping interfaceMapping = type.GetInterfaceMap(interfaceType); - methods = interfaceMapping.InterfaceMethods; - } + methods = interfaceType.GetMethods(bindingFlags); - for (int methodIndex = 0; methodIndex < methods.Length; methodIndex++) + foreach (MethodInfo interfaceMethod in methods) { - MethodInfo interfaceMethodDefinition = methods[methodIndex]; - - if ((!interfaceMethodDefinition.IsPublic) || - (interfaceMethodDefinition.IsStatic != ((BindingFlags.Static & bindingFlags) != 0))) + if (isStatic && interfaceMethod.IsVirtual) { + // Ignore static virtual/abstract methods on an interface because: + // 1. if it's implicitly implemented, which will be mostly the case, then the corresponding + // methods were already retrieved from the 'type.GetMethods' step above; + // 2. if it's explicitly implemented, we cannot call 'Invoke(null, args)' on the static method, + // but have to use 'type.GetInterfaceMap(interfaceType)' to get the corresponding target + // methods, and call 'Invoke(null, args)' on them. The target methods will be non-public + // in this case, which we always ignore. + // 3. The recommendation from .NET team is to ignore the static virtuals on interfaces, + // especially given that the APIs may change in .NET 7. continue; } - var previousMethodEntry = (List)typeMethods[interfaceMethodDefinition.Name]; + var previousMethodEntry = (List)typeMethods[interfaceMethod.Name]; if (previousMethodEntry == null) { - var methodEntry = new List { interfaceMethodDefinition }; - typeMethods.Add(interfaceMethodDefinition.Name, methodEntry); + var methodEntry = new List { interfaceMethod }; + typeMethods.Add(interfaceMethod.Name, methodEntry); } else { - if (!previousMethodEntry.Contains(interfaceMethodDefinition)) + if (!previousMethodEntry.Contains(interfaceMethod)) { - previousMethodEntry.Add(interfaceMethodDefinition); + previousMethodEntry.Add(interfaceMethod); } } } @@ -3211,7 +3266,7 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth for (int i = 0; i < typeMethods.memberCollection.Count; i++) { typeMethods.memberCollection[i] = - new MethodCacheEntry(((List)typeMethods.memberCollection[i]).ToArray()); + new MethodCacheEntry((List)typeMethods.memberCollection[i]); } } @@ -3224,38 +3279,24 @@ private static void PopulateMethodReflectionTable(Type type, CacheTable typeMeth /// BindingFlags to use. private static void PopulateEventReflectionTable(Type type, Dictionary typeEvents, BindingFlags bindingFlags) { - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up - // the derivation chain to find the first public parent, and use reflection events on the public parent. - if (!TypeResolver.IsPublic(type) && DisallowPrivateReflection(type)) - { - type = GetFirstPublicParentType(type); - } + EventInfo[] events = type.GetEvents(bindingFlags); + var tempTable = new Dictionary>(StringComparer.OrdinalIgnoreCase); - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (type != null) + foreach (EventInfo typeEvent in events) { - EventInfo[] events = type.GetEvents(bindingFlags); - var tempTable = new Dictionary>(StringComparer.OrdinalIgnoreCase); - for (int i = 0; i < events.Length; i++) + string eventName = typeEvent.Name; + if (!tempTable.TryGetValue(eventName, out List entryList)) { - var typeEvent = events[i]; - string eventName = typeEvent.Name; - List previousEntry; - if (!tempTable.TryGetValue(eventName, out previousEntry)) - { - var eventEntry = new List { typeEvent }; - tempTable.Add(eventName, eventEntry); - } - else - { - previousEntry.Add(typeEvent); - } + entryList = new List(); + tempTable.Add(eventName, entryList); } - foreach (var entry in tempTable) - { - typeEvents.Add(entry.Key, new EventCacheEntry(entry.Value.ToArray())); - } + entryList.Add(typeEvent); + } + + foreach (KeyValuePair> entry in tempTable) + { + typeEvents.Add(entry.Key, new EventCacheEntry(entry.Value.ToArray())); } } @@ -3270,9 +3311,8 @@ private static bool PropertyAlreadyPresent(List previousProperties ParameterInfo[] propertyParameters = property.GetIndexParameters(); int propertyIndexLength = propertyParameters.Length; - for (int propertyIndex = 0; propertyIndex < previousProperties.Count; propertyIndex++) + foreach (PropertyInfo previousProperty in previousProperties) { - var previousProperty = previousProperties[propertyIndex]; ParameterInfo[] previousParameters = previousProperty.GetIndexParameters(); if (previousParameters.Length == propertyIndexLength) { @@ -3308,79 +3348,81 @@ private static bool PropertyAlreadyPresent(List previousProperties /// BindingFlags to use. private static void PopulatePropertyReflectionTable(Type type, CacheTable typeProperties, BindingFlags bindingFlags) { + bool isStatic = bindingFlags.HasFlag(BindingFlags.Static); var tempTable = new Dictionary>(StringComparer.OrdinalIgnoreCase); - Type typeToGetPropertyAndField = type; - - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up the - // derivation chain to find the first public parent, and use reflection properties/fields on the public parent. - if (!TypeResolver.IsPublic(type) && DisallowPrivateReflection(type)) - { - typeToGetPropertyAndField = GetFirstPublicParentType(type); - } - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - PropertyInfo[] properties; - if (typeToGetPropertyAndField != null) + PropertyInfo[] properties = type.GetProperties(bindingFlags); + foreach (PropertyInfo property in properties) { - properties = typeToGetPropertyAndField.GetProperties(bindingFlags); - for (int i = 0; i < properties.Length; i++) - { - PopulateSingleProperty(type, properties[i], tempTable, properties[i].Name); - } + PopulateSingleProperty(type, property, tempTable, property.Name); } Type[] interfaces = type.GetInterfaces(); - for (int interfaceIndex = 0; interfaceIndex < interfaces.Length; interfaceIndex++) + foreach (Type interfaceType in interfaces) { - Type interfaceType = interfaces[interfaceIndex]; if (!TypeResolver.IsPublic(interfaceType)) { continue; } properties = interfaceType.GetProperties(bindingFlags); - for (int propertyIndex = 0; propertyIndex < properties.Length; propertyIndex++) + foreach (PropertyInfo property in properties) { - PopulateSingleProperty(type, properties[propertyIndex], tempTable, properties[propertyIndex].Name); + if (isStatic && + (property.GetMethod?.IsVirtual == true || property.SetMethod?.IsVirtual == true)) + { + // Ignore static virtual/abstract properties on an interface because: + // 1. if it's implicitly implemented, which will be mostly the case, then the corresponding + // properties were already retrieved from the 'type.GetProperties' step above; + // 2. if it's explicitly implemented, we cannot call 'GetValue(null)' on the static property, + // but have to use 'type.GetInterfaceMap(interfaceType)' to get the corresponding target + // get/set accessor methods, and call 'Invoke(null, args)' on them. The target methods will + // be non-public in this case, which we always ignore. + // 3. The recommendation from .NET team is to ignore the static virtuals on interfaces, + // especially given that the APIs may change in .NET 7. + continue; + } + + PopulateSingleProperty(type, property, tempTable, property.Name); } } - foreach (var pairs in tempTable) + foreach (KeyValuePair> entry in tempTable) { - var propertiesList = pairs.Value; + List propertiesList = entry.Value; PropertyInfo firstProperty = propertiesList[0]; if ((propertiesList.Count > 1) || (firstProperty.GetIndexParameters().Length != 0)) { - typeProperties.Add(pairs.Key, new ParameterizedPropertyCacheEntry(propertiesList)); + typeProperties.Add(entry.Key, new ParameterizedPropertyCacheEntry(propertiesList)); } else { - typeProperties.Add(pairs.Key, new PropertyCacheEntry(firstProperty)); + typeProperties.Add(entry.Key, new PropertyCacheEntry(firstProperty)); } } - // In CoreCLR, "GetFirstPublicParentType" may return null if 'type' is an interface - if (typeToGetPropertyAndField != null) + FieldInfo[] fields = type.GetFields(bindingFlags); + foreach (FieldInfo field in fields) { - FieldInfo[] fields = typeToGetPropertyAndField.GetFields(bindingFlags); - for (int i = 0; i < fields.Length; i++) + string fieldName = field.Name; + var previousMember = (PropertyCacheEntry)typeProperties[fieldName]; + if (previousMember == null) { - FieldInfo field = fields[i]; - string fieldName = field.Name; - var previousMember = (PropertyCacheEntry)typeProperties[fieldName]; - if (previousMember == null) - { - typeProperties.Add(fieldName, new PropertyCacheEntry(field)); - } - else - { - // A property/field declared with new in a derived class might appear twice - if (!string.Equals(previousMember.member.Name, fieldName)) - { - throw new ExtendedTypeSystemException("NotACLSComplaintField", null, - ExtendedTypeSystem.NotAClsCompliantFieldProperty, fieldName, type.FullName, previousMember.member.Name); - } - } + typeProperties.Add(fieldName, new PropertyCacheEntry(field)); + } + else if (!string.Equals(previousMember.member.Name, fieldName)) + { + // A property/field declared with 'new' in a derived class might appear twice, and it's OK to ignore + // the second property/field in that case. + // However, if the names of two properties/fields are different only in letter casing, then it's not + // CLS complaint and we throw an exception. + throw new ExtendedTypeSystemException( + "NotACLSComplaintField", + innerException: null, + ExtendedTypeSystem.NotAClsCompliantFieldProperty, + fieldName, + type.FullName, + previousMember.member.Name); } } } @@ -3411,66 +3453,6 @@ private static void PopulateSingleProperty(Type type, PropertyInfo property, Dic } } - #region Handle_Internal_Type_Reflection_In_CoreCLR - - /// - /// The dictionary cache about if an assembly supports reflection execution on its internal types. - /// - private static readonly ConcurrentDictionary s_disallowReflectionCache = - new ConcurrentDictionary(StringComparer.OrdinalIgnoreCase); - - /// - /// Check if the type is defined in an assembly that disallows reflection execution on internal types. - /// - .NET Framework assemblies don't support reflection execution on their internal types. - /// - internal static bool DisallowPrivateReflection(Type type) - { - bool disallowReflection = false; - Assembly assembly = type.Assembly; - if (s_disallowReflectionCache.TryGetValue(assembly.FullName, out disallowReflection)) - { - return disallowReflection; - } - - var productAttribute = assembly.GetCustomAttribute(); - if (productAttribute != null && string.Equals(productAttribute.Product, "Microsoft® .NET Framework", StringComparison.OrdinalIgnoreCase)) - { - disallowReflection = true; - } - else - { - // Check for 'DisablePrivateReflectionAttribute'. It's applied at the assembly level, and allow an assembly to opt-out of private/internal reflection. - var disablePrivateReflectionAttribute = assembly.GetCustomAttribute(); - disallowReflection = disablePrivateReflectionAttribute != null; - } - - s_disallowReflectionCache.TryAdd(assembly.FullName, disallowReflection); - return disallowReflection; - } - - /// - /// Walk up the derivation chain to find the first public parent type. - /// - internal static Type GetFirstPublicParentType(Type type) - { - Dbg.Assert(!TypeResolver.IsPublic(type), "type should not be public."); - Type parent = type.BaseType; - while (parent != null) - { - if (parent.IsPublic) - { - return parent; - } - - parent = parent.BaseType; - } - - // Return null when type is an interface - return null; - } - - #endregion Handle_Internal_Type_Reflection_In_CoreCLR - /// /// Called from GetProperty and GetProperties to populate the /// typeTable with all public properties and fields @@ -3878,7 +3860,7 @@ internal void AddAllDynamicMembers(object obj, PSMemberInfoInternalCollection private static bool PropertyIsStatic(PSProperty property) { - if (!(property.adapterData is PropertyCacheEntry entry)) + if (property.adapterData is not PropertyCacheEntry entry) { return false; } @@ -3886,6 +3868,33 @@ private static bool PropertyIsStatic(PSProperty property) return entry.isStatic; } + /// + /// Get the string representation of the default value of passed-in parameter. + /// + /// ParameterInfo containing the parameter's default value. + /// String representation of the parameter's default value. + private static string GetDefaultValueStringRepresentation(ParameterInfo parameterInfo) + { + var parameterType = parameterInfo.ParameterType; + var parameterDefaultValue = parameterInfo.DefaultValue; + + if (parameterDefaultValue == null) + { + return (parameterType.IsValueType || parameterType.IsGenericMethodParameter) + ? "default" + : "null"; + } + + if (parameterType.IsEnum) + { + return string.Create(CultureInfo.InvariantCulture, $"{parameterType}.{parameterDefaultValue}"); + } + + return (parameterDefaultValue is string) + ? string.Create(CultureInfo.InvariantCulture, $"\"{parameterDefaultValue}\"") + : parameterDefaultValue.ToString(); + } + #endregion auxiliary methods and classes #region virtual @@ -3911,11 +3920,11 @@ protected override ConsolidatedString GetInternedTypeNameHierarchy(object obj) /// /// Get the .NET member based on the given member name. /// - /// + /// /// Dynamic members of an object that implements IDynamicMetaObjectProvider are not included because /// 1. Dynamic members cannot be invoked via reflection; /// 2. Access to dynamic members is handled by the DLR for free. - /// + /// /// Object to retrieve the PSMemberInfo from. /// Name of the member to be retrieved. /// @@ -3948,10 +3957,10 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate /// In the case of the DirectoryEntry adapter, this could be a cache of the objectClass /// to the properties available in it. /// - /// + /// /// Dynamic members of an object that implements IDynamicMetaObjectProvider are included because /// we want to view the dynamic members via 'Get-Member' and be able to auto-complete those members. - /// + /// /// Object to get all the member information from. /// All members in obj. protected override PSMemberInfoInternalCollection GetMembers(object obj) @@ -4284,11 +4293,10 @@ internal static object AuxiliaryMethodInvoke(object target, object[] arguments, /// /// The methods to be converted. /// The MethodInformation[] corresponding to methods. - internal static MethodInformation[] GetMethodInformationArray(MethodBase[] methods) + internal static MethodInformation[] GetMethodInformationArray(IList methods) { - int methodCount = methods.Length; - MethodInformation[] returnValue = new MethodInformation[methodCount]; - for (int i = 0; i < methods.Length; i++) + var returnValue = new MethodInformation[methods.Count]; + for (int i = 0; i < methods.Count; i++) { returnValue[i] = new MethodInformation(methods[i], 0); } @@ -4357,7 +4365,7 @@ private static object InvokeResolvedConstructor(MethodInformation bestMethod, ob /// /// This is a flavor of MethodInvokeDotNet to deal with a peculiarity of property setters: - /// Tthe setValue is always the last parameter. This enables a parameter after a varargs or optional + /// The setValue is always the last parameter. This enables a parameter after a varargs or optional /// parameters and GetBestMethodAndArguments is not prepared for that. /// This method disregards the last parameter in its call to GetBestMethodAndArguments used in this case /// more for its "Arguments" side than for its "BestMethod" side, since there is only one method. @@ -4433,7 +4441,7 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method } builder.Append(memberName ?? methodEntry.Name); - if (methodEntry.IsGenericMethodDefinition) + if (methodEntry.IsGenericMethodDefinition || methodEntry.IsGenericMethod) { builder.Append('['); @@ -4479,6 +4487,13 @@ internal static string GetMethodInfoOverloadDefinition(string memberName, Method builder.Append(ToStringCodeMethods.Type(parameterType)); builder.Append(' '); builder.Append(parameter.Name); + + if (parameter.HasDefaultValue) + { + builder.Append(" = "); + builder.Append(GetDefaultValueStringRepresentation(parameter)); + } + builder.Append(", "); } @@ -4533,7 +4548,7 @@ protected override Collection MethodDefinitions(PSMethod method) MethodCacheEntry methodEntry = (MethodCacheEntry)method.adapterData; IList uniqueValues = methodEntry .methodInformationStructures - .Select(m => m.methodDefinition) + .Select(static m => m.methodDefinition) .Distinct(StringComparer.Ordinal) .ToList(); return new Collection(uniqueValues); @@ -4750,6 +4765,7 @@ protected override T GetFirstMemberOrDefault(object obj, MemberNamePredicate #endregion +#if !UNIX /// /// Used only to add a COM style type name to a COM interop .NET type. /// @@ -4780,6 +4796,8 @@ protected override ConsolidatedString GetInternedTypeNameHierarchy(object obj) return new ConsolidatedString(GetTypeNameHierarchy(obj), interned: true); } } +#endif + /// /// Adapter used for GetMember and GetMembers only. /// All other methods will not be called. @@ -5422,7 +5440,7 @@ private static object GetNodeObject(XmlNode node) } XmlNodeList nodeChildren = node.ChildNodes; - // nodeChildren will not be null as we already verified iff the node has children. + // nodeChildren will not be null as we already verified that the node has children. if ((nodeChildren.Count == 1) && (nodeChildren[0].NodeType == XmlNodeType.Text)) { return node.InnerText; @@ -5903,7 +5921,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, Type[] typesOfMethodAr } Type[] typeParameters = genericMethod.GetGenericArguments(); - Type[] typesOfMethodParameters = genericMethod.GetParameters().Select(p => p.ParameterType).ToArray(); + Type[] typesOfMethodParameters = genericMethod.GetParameters().Select(static p => p.ParameterType).ToArray(); MethodInfo inferredMethod = Infer(genericMethod, typeParameters, typesOfMethodParameters, typesOfMethodArguments); @@ -5944,7 +5962,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, ICollection type { s_tracer.WriteLine( "Types of method arguments: {0}", - string.Join(", ", typesOfMethodArguments.Select(t => t.ToString()).ToArray())); + string.Join(", ", typesOfMethodArguments.Select(static t => t.ToString()).ToArray())); } var typeInference = new TypeInference(typeParameters); @@ -5954,7 +5972,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, ICollection type } IEnumerable inferredTypeParameters = typeParameters.Select(typeInference.GetInferredType); - if (inferredTypeParameters.Any(inferredType => inferredType == null)) + if (inferredTypeParameters.Any(static inferredType => inferredType == null)) { return null; } @@ -5962,7 +5980,7 @@ private static MethodInfo Infer(MethodInfo genericMethod, ICollection type try { MethodInfo instantiatedMethod = genericMethod.MakeGenericMethod(inferredTypeParameters.ToArray()); - s_tracer.WriteLine("Inference succesful: {0}", instantiatedMethod); + s_tracer.WriteLine("Inference successful: {0}", instantiatedMethod); return instantiatedMethod; } catch (ArgumentException e) @@ -5990,7 +6008,7 @@ internal TypeInference(ICollection typeParameters) #endif _typeParameterIndexToSetOfInferenceCandidates = new HashSet[typeParameters.Count]; #if DEBUG - List listOfTypeParameterPositions = typeParameters.Select(t => t.GenericParameterPosition).ToList(); + List listOfTypeParameterPositions = typeParameters.Select(static t => t.GenericParameterPosition).ToList(); listOfTypeParameterPositions.Sort(); Dbg.Assert( listOfTypeParameterPositions.Count == listOfTypeParameterPositions.Distinct().Count(), @@ -6022,9 +6040,9 @@ internal Type GetInferredType(Type typeParameter) ICollection inferenceCandidates = _typeParameterIndexToSetOfInferenceCandidates[typeParameter.GenericParameterPosition]; - if ((inferenceCandidates != null) && (inferenceCandidates.Any(t => t == typeof(LanguagePrimitives.Null)))) + if ((inferenceCandidates != null) && (inferenceCandidates.Any(static t => t == typeof(LanguagePrimitives.Null)))) { - Type firstValueType = inferenceCandidates.FirstOrDefault(t => t.IsValueType); + Type firstValueType = inferenceCandidates.FirstOrDefault(static t => t.IsValueType); if (firstValueType != null) { s_tracer.WriteLine("Cannot reconcile null and {0} (a value type)", firstValueType); @@ -6033,7 +6051,7 @@ internal Type GetInferredType(Type typeParameter) } else { - inferenceCandidates = inferenceCandidates.Where(t => t != typeof(LanguagePrimitives.Null)).ToList(); + inferenceCandidates = inferenceCandidates.Where(static t => t != typeof(LanguagePrimitives.Null)).ToList(); if (inferenceCandidates.Count == 0) { inferenceCandidates = null; diff --git a/src/System.Management.Automation/engine/Credential.cs b/src/System.Management.Automation/engine/Credential.cs index 86557c922c6..c921b9a084d 100644 --- a/src/System.Management.Automation/engine/Credential.cs +++ b/src/System.Management.Automation/engine/Credential.cs @@ -10,13 +10,10 @@ using System.Security.Cryptography; using Microsoft.PowerShell; -// FxCop suppressions for resource strings: -[module: SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", Scope = "resource", Target = "Credential.resources", MessageId = "Cred")] - namespace System.Management.Automation { /// - /// Defines the valid types of MSH credentials. Used by PromptForCredential calls. + /// Defines the valid types of PSCredentials. Used by PromptForCredential calls. /// [Flags] public enum PSCredentialTypes @@ -85,7 +82,7 @@ public enum PSCredentialUIOptions /// Offers a centralized way to manage usernames, passwords, and /// credentials. /// - [Serializable()] + [Serializable] public sealed class PSCredential : ISerializable { /// diff --git a/src/System.Management.Automation/engine/DataStoreAdapter.cs b/src/System.Management.Automation/engine/DataStoreAdapter.cs index 9bf7611d7ff..07c7cef4d01 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapter.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapter.cs @@ -26,7 +26,7 @@ public class PSDriveInfo : IComparable /// using "SessionState" as the category. /// This is the same category as the SessionState tracer class. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "PSDriveInfo", "The namespace navigation tracer")] private static readonly Dbg.PSTraceSource s_tracer = @@ -289,7 +289,7 @@ protected PSDriveInfo(PSDriveInfo driveInfo) } /// - /// Constructs a drive that maps an MSH Path in + /// Constructs a drive that maps a PowerShell Path in /// the shell to a Cmdlet Provider. /// /// @@ -366,7 +366,7 @@ public PSDriveInfo( } /// - /// Constructs a drive that maps an MSH Path in + /// Constructs a drive that maps a PowerShell Path in /// the shell to a Cmdlet Provider. /// /// @@ -408,7 +408,7 @@ public PSDriveInfo( } /// - /// Constructs a drive that maps an MSH Path in + /// Constructs a drive that maps a PowerShell Path in /// the shell to a Cmdlet Provider. /// /// diff --git a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs index 69202e6d20e..3ea2fd00fff 100644 --- a/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs +++ b/src/System.Management.Automation/engine/DataStoreAdapterProvider.cs @@ -201,7 +201,7 @@ public Provider.ProviderCapabilities Capabilities /// /// /// The location can be either a fully qualified provider path - /// or an Msh path. This is the location that is substituted for the ~. + /// or a PowerShell path. This is the location that is substituted for the ~. /// public string Home { get; set; } @@ -368,7 +368,7 @@ internal ProviderInfo( /// The description of the provider. /// /// - /// The home path for the provider. This must be an MSH path. + /// The home path for the provider. This must be a PowerShell path. /// /// /// The help file for the provider. diff --git a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs index d45abaaffbc..746d809d831 100644 --- a/src/System.Management.Automation/engine/DefaultCommandRuntime.cs +++ b/src/System.Management.Automation/engine/DefaultCommandRuntime.cs @@ -21,8 +21,7 @@ internal class DefaultCommandRuntime : ICommandRuntime2 /// public DefaultCommandRuntime(List outputList) { - if (outputList == null) - throw new System.ArgumentNullException(nameof(outputList)); + ArgumentNullException.ThrowIfNull(outputList); _output = outputList; } @@ -65,7 +64,7 @@ public void WriteObject(object sendToPipeline) /// /// Default implementation of the enumerated WriteObject. Either way, the - /// objects are added to the list passed to this object in the constuctor. + /// objects are added to the list passed to this object in the constructor. /// /// Object to write. /// If true, the collection is enumerated, otherwise @@ -230,6 +229,7 @@ public PSTransactionContext CurrentPSTransaction /// if it exists, otherwise throw an invalid operation exception. /// /// The error record to throw. + [System.Diagnostics.CodeAnalysis.DoesNotReturn] public void ThrowTerminatingError(ErrorRecord errorRecord) { if (errorRecord.Exception != null) diff --git a/src/System.Management.Automation/engine/DriveInterfaces.cs b/src/System.Management.Automation/engine/DriveInterfaces.cs index 299faa8b76e..c93e47d8c1c 100644 --- a/src/System.Management.Automation/engine/DriveInterfaces.cs +++ b/src/System.Management.Automation/engine/DriveInterfaces.cs @@ -70,7 +70,7 @@ public PSDriveInfo Current #region New /// - /// Creates a new MSH drive in session state. + /// Creates a new PSDrive in session state. /// /// /// The drive to be created. diff --git a/src/System.Management.Automation/engine/EngineIntrinsics.cs b/src/System.Management.Automation/engine/EngineIntrinsics.cs index a492a5215fc..e2a63a527a9 100644 --- a/src/System.Management.Automation/engine/EngineIntrinsics.cs +++ b/src/System.Management.Automation/engine/EngineIntrinsics.cs @@ -35,10 +35,7 @@ private EngineIntrinsics() /// internal EngineIntrinsics(ExecutionContext context) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _context = context; _host = context.EngineHostInterface; diff --git a/src/System.Management.Automation/engine/ErrorPackage.cs b/src/System.Management.Automation/engine/ErrorPackage.cs index 7d6a1f2759f..6dfaf34fbec 100644 --- a/src/System.Management.Automation/engine/ErrorPackage.cs +++ b/src/System.Management.Automation/engine/ErrorPackage.cs @@ -18,7 +18,7 @@ namespace System.Management.Automation { /// - /// Errors reported by Monad will be in one of these categories. + /// Errors reported by PowerShell will be in one of these categories. /// /// /// Do not specify ErrorCategory.NotSpecified when creating an @@ -28,13 +28,15 @@ namespace System.Management.Automation public enum ErrorCategory { /// + /// /// No error category is specified, or the error category is invalid. - /// - /// + /// + /// /// Do not specify ErrorCategory.NotSpecified when creating an /// . /// Choose the best match from among the other values. - /// + /// + /// NotSpecified = 0, /// @@ -132,14 +134,16 @@ public enum ErrorCategory WriteError = 23, /// - /// A non-Monad command reported an error to its STDERR pipe. - /// - /// + /// + /// A native command reported an error to its STDERR pipe. + /// + /// /// The Engine uses this ErrorCategory when it executes a native /// console applications and captures the errors reported by the /// native application. Avoid using ErrorCategory.FromStdErr /// in other circumstances. - /// + /// + /// FromStdErr = 24, /// @@ -193,10 +197,7 @@ public class ErrorCategoryInfo #region ctor internal ErrorCategoryInfo(ErrorRecord errorRecord) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } @@ -526,7 +527,6 @@ internal static string Ellipsize(CultureInfo uiCultureInfo, string original) /// It is permitted to subclass /// but there is no established scenario for doing this, nor has it been tested. /// - [Serializable] public class ErrorDetails : ISerializable { #region Constructor @@ -562,7 +562,7 @@ public ErrorDetails(string message) /// /// /// - /// + /// /// insertion parameters /// /// @@ -584,7 +584,7 @@ public ErrorDetails(string message) /// by overriding virtual method /// . /// This constructor then inserts the specified args using - /// . + /// . /// public ErrorDetails( Cmdlet cmdlet, @@ -610,7 +610,7 @@ public ErrorDetails( /// /// /// - /// + /// /// insertion parameters /// /// @@ -637,7 +637,7 @@ public ErrorDetails( /// will implement /// . /// The constructor then inserts the specified args using - /// . + /// . /// public ErrorDetails( IResourceSupplier resourceSupplier, @@ -663,7 +663,7 @@ public ErrorDetails( /// /// /// - /// + /// /// insertion parameters /// /// @@ -678,7 +678,7 @@ public ErrorDetails( /// This constructor first loads a template string from the assembly using /// . /// The constructor then inserts the specified args using - /// . + /// . /// public ErrorDetails( System.Reflection.Assembly assembly, @@ -796,7 +796,7 @@ internal Exception TextLookupError #region ToString /// - /// As + /// As /// /// Developer-readable identifier. public override string ToString() @@ -985,7 +985,6 @@ private string BuildMessage( /// . /// rather than the actual exception, to avoid the mutual references. /// - [Serializable] public class ErrorRecord : ISerializable { #region Constructor @@ -1026,10 +1025,7 @@ public ErrorRecord( throw PSTraceSource.NewArgumentNullException(nameof(exception)); } - if (errorId == null) - { - errorId = string.Empty; - } + errorId ??= string.Empty; // targetObject may be null _error = exception; @@ -1669,7 +1665,7 @@ private string GetInvocationTypeName() return commandInfo.Name; } - if (!(commandInfo is CmdletInfo cmdletInfo)) + if (commandInfo is not CmdletInfo cmdletInfo) { return string.Empty; } @@ -1681,7 +1677,7 @@ private string GetInvocationTypeName() #region ToString /// - /// As + /// As /// /// Developer-readable identifier. public override string ToString() @@ -1693,12 +1689,7 @@ public override string ToString() if (Exception != null) { - if (!string.IsNullOrEmpty(Exception.Message)) - { - return Exception.Message; - } - - return Exception.ToString(); + return Exception.Message ?? Exception.ToString(); } return base.ToString(); @@ -1726,10 +1717,10 @@ public ErrorRecord(Exception exception, string errorId, ErrorCategory errorCateg /// information. /// /// - /// MSH defines certain exception classes which implement this interface. + /// PowerShell defines certain exception classes which implement this interface. /// This includes wrapper exceptions such as /// , - /// and also MSH engine errors such as + /// and also PowerShell engine errors such as /// . /// Cmdlets and providers should not define this interface; /// instead, they should use the @@ -1815,6 +1806,7 @@ public interface IContainsErrorRecord /// since the improved /// information about the error may help enable future scenarios. /// +#nullable enable public interface IResourceSupplier { /// @@ -1831,7 +1823,7 @@ public interface IResourceSupplier /// if you want more complex behavior. /// /// Insertions will be inserted into the string with - /// + /// /// to generate the final error message in /// . /// diff --git a/src/System.Management.Automation/engine/EventManager.cs b/src/System.Management.Automation/engine/EventManager.cs index fd30298669e..1c5de607321 100644 --- a/src/System.Management.Automation/engine/EventManager.cs +++ b/src/System.Management.Automation/engine/EventManager.cs @@ -44,6 +44,7 @@ protected int GetNextEventId() /// /// Creates a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -56,11 +57,11 @@ protected int GetNextEventId() /// /// Any additional data you wish to attach to the event /// - /// protected abstract PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData); /// /// Generate a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -73,7 +74,6 @@ protected int GetNextEventId() /// /// Any additional data you wish to attach to the event /// - /// public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { return this.GenerateEvent(sourceIdentifier, sender, args, extraData, false, false); @@ -81,6 +81,7 @@ public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[ /// /// Generate a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -100,7 +101,6 @@ public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[ /// /// Wait for the event and associated action to be processed and completed. /// - /// public PSEventArgs GenerateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData, bool processInCurrentThread, bool waitForCompletionInCurrentThread) { @@ -133,14 +133,15 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// /// Get the event subscription that corresponds to an identifier + /// /// /// The identifier that identifies the source of the events /// - /// public abstract IEnumerable GetEventSubscribers(string sourceIdentifier); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -162,12 +163,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -193,12 +194,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -220,12 +221,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -251,12 +252,12 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public abstract PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount); /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -286,7 +287,6 @@ protected internal virtual void ProcessNewEvent(PSEventArgs newEvent, bool proce /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// The default value is zero /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] internal virtual PSEventSubscriber SubscribeEvent(object source, string eventName, @@ -303,10 +303,10 @@ internal virtual PSEventSubscriber SubscribeEvent(object source, /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// - /// public abstract void UnsubscribeEvent(PSEventSubscriber subscriber); /// @@ -367,6 +367,7 @@ public override List Subscribers /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -388,7 +389,6 @@ public override List Subscribers /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent) { @@ -397,6 +397,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -422,7 +423,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -436,6 +436,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -465,7 +466,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// The default value is zero /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] internal override PSEventSubscriber SubscribeEvent(object source, string eventName, @@ -484,6 +484,7 @@ internal override PSEventSubscriber SubscribeEvent(object source, /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -505,7 +506,6 @@ internal override PSEventSubscriber SubscribeEvent(object source, /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent) { @@ -514,6 +514,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -539,7 +540,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -797,10 +797,10 @@ private void ProcessNewSubscriber(PSEventSubscriber subscriber, object source, s /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// - /// public override void UnsubscribeEvent(PSEventSubscriber subscriber) { UnsubscribeEvent(subscriber, false); @@ -808,19 +808,16 @@ public override void UnsubscribeEvent(PSEventSubscriber subscriber) /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// /// /// Indicate if we should skip draining /// - /// private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) { - if (subscriber == null) - { - throw new ArgumentNullException(nameof(subscriber)); - } + ArgumentNullException.ThrowIfNull(subscriber); Delegate existingSubscriber = null; lock (_eventSubscribers) @@ -862,10 +859,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) } // Stop the job - if (subscriber.Action != null) - { - subscriber.Action.NotifyJobStopped(); - } + subscriber.Action?.NotifyJobStopped(); lock (_eventSubscribers) { @@ -882,6 +876,7 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) /// /// Creates a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -894,7 +889,6 @@ private void UnsubscribeEvent(PSEventSubscriber subscriber, bool skipDraining) /// /// Any additional data you wish to attach to the event /// - /// protected override PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { return new PSEventArgs(null, _context.CurrentRunspace.InstanceId, GetNextEventId(), sourceIdentifier, sender, args, extraData); @@ -1293,10 +1287,10 @@ internal bool IsExecutingEventAction /// /// Get the event subscription that corresponds to an identifier + /// /// /// The identifier that identifies the source of the events /// - /// public override IEnumerable GetEventSubscribers(string sourceIdentifier) { return GetEventSubscribers(sourceIdentifier, false); @@ -1522,20 +1516,17 @@ public void Dispose() /// /// Stop the timer if it's not null. /// Unsubscribes from all events. + /// /// /// Whether to actually dispose the object. /// - /// public void Dispose(bool disposing) { if (disposing) { lock (_eventSubscribers) { - if (_timer != null) - { - _timer.Dispose(); - } + _timer?.Dispose(); foreach (PSEventSubscriber currentSubscriber in _eventSubscribers.Keys.ToArray()) { @@ -1589,6 +1580,7 @@ public override List Subscribers /// /// Creates a PowerShell event. + /// /// /// An optional identifier that identifies the source event /// @@ -1601,7 +1593,6 @@ public override List Subscribers /// /// Any additional data you wish to attach to the event /// - /// protected override PSEventArgs CreateEvent(string sourceIdentifier, object sender, object[] args, PSObject extraData) { // note that this is a local call, so we use null for the computer name @@ -1657,10 +1648,10 @@ protected internal override void ProcessNewEvent(PSEventArgs newEvent, /// /// Get the event subscription that corresponds to an identifier + /// /// /// The identifier that identifies the source of the events /// - /// public override IEnumerable GetEventSubscribers(string sourceIdentifier) { throw new NotSupportedException(EventingResources.RemoteOperationNotSupported); @@ -1668,6 +1659,7 @@ public override IEnumerable GetEventSubscribers(string source /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1689,7 +1681,6 @@ public override IEnumerable GetEventSubscribers(string source /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent) { @@ -1698,6 +1689,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1723,7 +1715,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, ScriptBlock action, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -1732,6 +1723,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1753,7 +1745,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Whether events in this subscriber should be forwarded to the client PowerShell during remote executions /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent) { @@ -1762,6 +1753,7 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Subscribes to an event on an object. + /// /// /// The source object that defines the event /// @@ -1787,7 +1779,6 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// Indicate how many times the subscriber should be triggered before auto-unregister it /// If the value is equal or less than zero, there is no limit on the number of times the event can be triggered without being unregistered /// - /// [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] public override PSEventSubscriber SubscribeEvent(object source, string eventName, string sourceIdentifier, PSObject data, PSEventReceivedEventHandler handlerDelegate, bool supportEvent, bool forwardEvent, int maxTriggerCount) { @@ -1796,10 +1787,10 @@ public override PSEventSubscriber SubscribeEvent(object source, string eventName /// /// Unsubscribes from an event on an object. + /// /// /// The subscriber associated with the event subscription /// - /// public override void UnsubscribeEvent(PSEventSubscriber subscriber) { throw new NotSupportedException(EventingResources.RemoteOperationNotSupported); @@ -1839,6 +1830,11 @@ private PSEngineEvent() { } /// public const string OnIdle = "PowerShell.OnIdle"; + /// + /// Called when Debug-Runspace has attached a debugger to the current runspace. + /// + public const string OnDebugAttach = "PowerShell.OnDebugAttach"; + /// /// Called during scriptblock invocation. /// @@ -1852,7 +1848,7 @@ private PSEngineEvent() { } /// /// A HashSet that contains all engine event names. /// - internal static readonly HashSet EngineEvents = new HashSet(StringComparer.OrdinalIgnoreCase) { Exiting, OnIdle, OnScriptBlockInvoke }; + internal static readonly HashSet EngineEvents = new HashSet(StringComparer.OrdinalIgnoreCase) { Exiting, OnIdle, OnDebugAttach, OnScriptBlockInvoke }; } /// @@ -2042,12 +2038,25 @@ private ScriptBlock CreateBoundScriptBlock(ScriptBlock scriptAction) #region IComparable Members + /// + /// Determines whether the specified object is equal to the current object. + /// + /// The object to compare with the current object. + /// + /// if the specified object is equal to the current object; + /// otherwise, . + /// + public override bool Equals(object obj) + { + return obj is PSEventSubscriber es && Equals(es); + } + /// /// Determines if two PSEventSubscriber instances are equal + /// /// /// The PSEventSubscriber to which to compare this instance /// - /// public bool Equals(PSEventSubscriber other) { if (other == null) @@ -2091,6 +2100,7 @@ public PSEventHandler() /// /// Creates a new instance of the PsEventHandler class for a given /// event manager, source identifier, and extra data + /// /// /// The event manager to which we forward events. /// @@ -2104,7 +2114,6 @@ public PSEventHandler() /// /// Any additional data you wish to attach to the event /// - /// public PSEventHandler(PSEventManager eventManager, object sender, string sourceIdentifier, PSObject extraData) { this.eventManager = eventManager; @@ -2361,10 +2370,7 @@ public class PSEventArgsCollection : IEnumerable /// Don't add events to the collection directly; use the EventManager instead internal void Add(PSEventArgs eventToAdd) { - if (eventToAdd == null) - { - throw new ArgumentNullException(nameof(eventToAdd)); - } + ArgumentNullException.ThrowIfNull(eventToAdd); _eventCollection.Add(eventToAdd); @@ -2459,6 +2465,7 @@ public class PSEventJob : Job { /// /// Creates a new instance of the PSEventJob class. + /// /// /// The event manager that controls the event subscriptions /// @@ -2471,7 +2478,6 @@ public class PSEventJob : Job /// /// The name of the job /// - /// public PSEventJob( PSEventManager eventManager, PSEventSubscriber subscriber, @@ -2479,10 +2485,9 @@ public PSEventJob( string name) : base(action?.ToString(), name) { - if (eventManager == null) - throw new ArgumentNullException(nameof(eventManager)); - if (subscriber == null) - throw new ArgumentNullException(nameof(subscriber)); + ArgumentNullException.ThrowIfNull(eventManager); + + ArgumentNullException.ThrowIfNull(subscriber); UsesResultsCollection = true; ScriptBlock = action; @@ -2549,13 +2554,13 @@ public override string Location /// /// Invoke the script block + /// /// /// The subscriber that generated this event /// /// /// The context of this event /// - /// internal void Invoke(PSEventSubscriber eventSubscriber, PSEventArgs eventArgs) { if (IsFinishedState(JobStateInfo.State)) diff --git a/src/System.Management.Automation/engine/ExecutionContext.cs b/src/System.Management.Automation/engine/ExecutionContext.cs index 3857de9ba38..ac39eade17b 100644 --- a/src/System.Management.Automation/engine/ExecutionContext.cs +++ b/src/System.Management.Automation/engine/ExecutionContext.cs @@ -53,22 +53,12 @@ internal ScriptDebugger Debugger /// internal void ResetManagers() { - if (_debugger != null) - { - _debugger.ResetDebugger(); - } - - if (Events != null) - { - Events.Dispose(); - } + _debugger?.ResetDebugger(); + Events?.Dispose(); Events = new PSLocalEventManager(this); - if (this.transactionManager != null) - { - this.transactionManager.Dispose(); - } + this.transactionManager?.Dispose(); this.transactionManager = new PSTransactionManager(); } /// @@ -114,10 +104,7 @@ internal bool PSDebugTraceStep // Helper for generated code to handle running w/ no execution context internal static bool IsStrictVersion(ExecutionContext context, int majorVersion) { - if (context == null) - { - context = LocalPipeline.GetExecutionContextFromTLS(); - } + context ??= LocalPipeline.GetExecutionContextFromTLS(); return (context != null) && context.IsStrictVersion(majorVersion); } @@ -205,40 +192,6 @@ internal bool ShouldTraceStatement /// internal string ModuleBeingProcessed { get; set; } - private bool _responsibilityForModuleAnalysisAppDomainOwned; - - internal bool TakeResponsibilityForModuleAnalysisAppDomain() - { - if (_responsibilityForModuleAnalysisAppDomainOwned) - { - return false; - } - - Diagnostics.Assert(AppDomainForModuleAnalysis == null, "Invalid module analysis app domain state"); - _responsibilityForModuleAnalysisAppDomainOwned = true; - return true; - } - - internal void ReleaseResponsibilityForModuleAnalysisAppDomain() - { - Diagnostics.Assert(_responsibilityForModuleAnalysisAppDomainOwned, "Invalid module analysis app domain state"); - - if (AppDomainForModuleAnalysis != null) - { - AppDomain.Unload(AppDomainForModuleAnalysis); - AppDomainForModuleAnalysis = null; - } - - _responsibilityForModuleAnalysisAppDomainOwned = false; - } - - /// - /// The AppDomain currently being used for module analysis. It should only be created if needed, - /// but various callers need to take responsibility for unloading the domain via - /// the TakeResponsibilityForModuleAnalysisAppDomain. - /// - internal AppDomain AppDomainForModuleAnalysis { get; set; } - /// /// Authorization manager for this runspace. /// @@ -253,10 +206,7 @@ internal ProviderNames ProviderNames { get { - if (_providerNames == null) - { - _providerNames = new SingleShellProviderNames(); - } + _providerNames ??= new SingleShellProviderNames(); return _providerNames; } @@ -413,8 +363,7 @@ internal static bool IsMarkedAsUntrusted(object value) var baseValue = PSObject.Base(value); if (baseValue != null && baseValue != NullString.Value) { - object unused; - result = UntrustedObjects.TryGetValue(baseValue, out unused); + result = UntrustedObjects.TryGetValue(baseValue, out _); } return result; @@ -430,7 +379,7 @@ internal static void MarkObjectAsUntrusted(object value) if (baseValue != null && baseValue != NullString.Value) { // It's actually setting a key value pair when the key doesn't exist - UntrustedObjects.GetValue(baseValue, key => null); + UntrustedObjects.GetValue(baseValue, static key => null); try { @@ -528,7 +477,6 @@ internal LocationGlobber LocationGlobber /// The assemblies that have been loaded for this runspace. /// internal Dictionary AssemblyCache { get; private set; } - #endregion Properties #region Engine State @@ -559,9 +507,7 @@ internal object GetVariableValue(VariablePath path) /// internal object GetVariableValue(VariablePath path, object defaultValue) { - CmdletProviderContext context; - SessionStateScope scope; - return EngineSessionState.GetVariableValue(path, out context, out scope) ?? defaultValue; + return EngineSessionState.GetVariableValue(path, out _, out _) ?? defaultValue; } /// @@ -646,19 +592,15 @@ private void CheckActionPreference(VariablePath preferenceVariablePath, ActionPr /// internal bool GetBooleanPreference(VariablePath preferenceVariablePath, bool defaultPref, out bool defaultUsed) { - CmdletProviderContext context = null; - SessionStateScope scope = null; - object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out context, out scope); - if (val == null) + object val = EngineSessionState.GetVariableValue(preferenceVariablePath, out _, out _); + if (val is null) { defaultUsed = true; return defaultPref; } - bool converted = defaultPref; - defaultUsed = !LanguagePrimitives.TryConvertTo - (val, out converted); - return (defaultUsed) ? defaultPref : converted; + defaultUsed = !LanguagePrimitives.TryConvertTo(val, out bool converted); + return defaultUsed ? defaultPref : converted; } #endregion GetSetVariable methods @@ -691,12 +633,13 @@ internal HelpSystem HelpSystem /// /// The name of the command to lookup. /// + /// /// The command processor object. - internal CommandProcessorBase CreateCommand(string command, bool dotSource) + internal CommandProcessorBase CreateCommand(string command, bool dotSource, bool forCompletion = false) { CommandOrigin commandOrigin = this.EngineSessionState.CurrentScope.ScopeOrigin; CommandProcessorBase commandProcessor = - CommandDiscovery.LookupCommandProcessor(command, commandOrigin, !dotSource); + CommandDiscovery.LookupCommandProcessor(command, commandOrigin, !dotSource, forCompletion); // Reset the command origin for script commands... // BUGBUG - dotting can get around command origin checks??? if (commandProcessor != null && commandProcessor is ScriptCommandProcessorBase) { @@ -823,11 +766,6 @@ internal Pipe RedirectErrorPipe(Pipe newPipe) return oldPipe; } - internal void RestoreErrorPipe(Pipe pipe) - { - ShellFunctionErrorOutputPipe = pipe; - } - /// /// Reset all of the redirection book keeping variables. This routine should be called when starting to /// execute a script. @@ -880,15 +818,13 @@ internal void ResetRedirection() internal void AppendDollarError(object obj) { ErrorRecord objAsErrorRecord = obj as ErrorRecord; - if (objAsErrorRecord == null && obj is not Exception) + if (objAsErrorRecord is null && obj is not Exception) { Diagnostics.Assert(false, "Object to append was neither an ErrorRecord nor an Exception in ExecutionContext.AppendDollarError"); return; } - object old = this.DollarErrorVariable; - ArrayList arraylist = old as ArrayList; - if (arraylist == null) + if (DollarErrorVariable is not ArrayList arraylist) { Diagnostics.Assert(false, "$error should be a global constant ArrayList"); return; @@ -1209,22 +1145,12 @@ internal void RunspaceClosingNotification() { EngineSessionState.RunspaceClosingNotification(); - if (_debugger != null) - { - _debugger.Dispose(); - } - - if (Events != null) - { - Events.Dispose(); - } + _debugger?.Dispose(); + Events?.Dispose(); Events = null; - if (this.transactionManager != null) - { - this.transactionManager.Dispose(); - } + this.transactionManager?.Dispose(); this.transactionManager = null; } @@ -1316,55 +1242,151 @@ internal PSTransactionManager TransactionManager internal PSTransactionManager transactionManager; - internal Assembly AddAssembly(string name, string filename, out Exception error) - { - Assembly loadedAssembly = LoadAssembly(name, filename, out error); - - if (loadedAssembly == null) - return null; - - if (AssemblyCache.ContainsKey(loadedAssembly.FullName)) + /// + /// This method is used for assembly loading requests stemmed from 'InitialSessionState' binding and module loading. + /// + /// Source of the assembly loading request, should be a module name when specified. + /// Name of the assembly to be loaded. + /// Path of the assembly to be loaded. + /// Exception that is caught when the loading fails. + internal Assembly AddAssembly(string source, string assemblyName, string filePath, out Exception error) + { + // Search the cache by the path, and return the assembly if we find it. + // It's common to have two loading requests for the same assembly when loading a module -- the first time for + // resolving a binary module path, and the second time for actually processing that module. + // + // That's not a problem when all the module assemblies are loaded into the default ALC. But in a scenario where + // a module tries to hide its nested/root binary modules in a custom ALC, that will become a problem. This is + // because: + // in that scenario, the module will usually setup a handler to load the specific assemblies to the custom ALC, + // and that will be how the first loading request gets served. However, after the module path is resolved with + // the first loading, the path will be used for the second loading upon real module processing. Since we prefer + // loading-by-path over loading-by-name in the 'LoadAssembly' call, we will end up loading the same assembly in + // the default ALC (because we use 'Assembly.LoadFrom' which always loads an assembly to the default ALC) if we + // do not search in the cache first. That will break the scenario, because the module means to isolate all its + // dependencies from the default ALC, and it failed to do so. + // + // Therefore, we need to search the cache first. The reason we use path as the key is to make sure the request + // is for exactly the same assembly. The same assembly file should not be loaded into different ALC's by module + // loading within the same PowerShell session (Runspace). + // + // An example module targeting the abovementioned scenario will likely have the following file structure: + // IsolatedModule + // │ IsolatedModule.psd1 (has 'NestedModules = @('Test.Isolated.Init.dll', 'Test.Isolated.Nested.dll')') + // │ Test.Isolated.Init.dll (contains the custom ALC and code to setup 'Resolving' handler) + // └───Dependencies (folder under module base) + // Newtonsoft.Json.dll (version 10.0.0.0 dependency) + // Test.Isolated.Nested.dll (nested binary module referencing the particular dependency) + // + // In this example, the following events will happen in sequence: + // 1. PowerShell is able to find 'Test.Isolated.Init.dll' under module base folder, so it will be loaded into + // the default ALC as expected and setup the 'Resolving' handler via the 'OnImport' call. + // 2. PowerShell cannot find 'Test.Isolated.Nested.dll' under the module base folder, so it will call the method + // 'FixFileName(.., bool canLoadAssembly)' to resolve the path of this binary module. + // This particular overload will attempt to load the assembly by name, which will be served by the 'Resolving' + // handler that was setup in the step 1. So, the assembly will be loaded into the custom ALC and insert to the + // assembly cache. + // 3. Path of the nested module 'Test.Isolated.Init.dll' now has been resolved by the step 2 (assembly.Location). + // Now it's time to actually load this binary module for processing in the method 'LoadBinaryModule', which + // will make a call to this method with the resolved assembly file path. + // At this poin, we will have to query the cache first, instead of calling 'LoadAssembly' directly, to make sure + // that the assembly instance loaded in the custom ALC in step 2 gets returned back. Otherwise, the same assembly + // file will be loaded in the default ALC because 'Assembly.LoadFrom' is used in 'LoadAssembly' and that API will + // always load an assembly file to the default ALC, and that will break this scenario. + if (TryGetFromAssemblyCache(source, filePath, out Assembly loadedAssembly)) { - // we should ignore this assembly. + error = null; return loadedAssembly; } - // We will cache the assembly by both full name and - // file name - AssemblyCache.Add(loadedAssembly.FullName, loadedAssembly); - if (AssemblyCache.ContainsKey(loadedAssembly.GetName().Name)) + // Attempt to load the requested assembly, first by path then by name. + loadedAssembly = LoadAssembly(assemblyName, filePath, out error); + if (loadedAssembly is not null) { - // we should ignore this assembly. - return loadedAssembly; + AddToAssemblyCache(source, loadedAssembly); } - AssemblyCache.Add(loadedAssembly.GetName().Name, loadedAssembly); return loadedAssembly; } - internal void RemoveAssembly(string name) + /// + /// Add a loaded assembly to the 'AssemblyCache'. + /// The is used as a prefix for the key to make it easy to remove all associated + /// assemblies from the cache when a module gets unloaded. + /// + /// The source where the assembly comes from, should be a module name when specified. + /// The assembly we try to cache. + internal void AddToAssemblyCache(string source, Assembly assembly) { - Assembly loadedAssembly; - if (AssemblyCache.TryGetValue(name, out loadedAssembly) && loadedAssembly != null) + // Try caching the assembly by its location if possible. + // When it's a dynamic assembly, we use it's full name. This could happen with 'Import-Module -Assembly'. + string key = string.IsNullOrEmpty(assembly.Location) ? assembly.FullName : assembly.Location; + + // When the assembly is from a module loading, we prefix the key with the source, + // so we can remove it from the cache when the module gets unloaded. + if (!string.IsNullOrEmpty(source)) { - AssemblyCache.Remove(name); + // Both 'source' and 'key' are of the string type, so no need to specify 'InvariantCulture'. + key = $"{source}@{key}"; + } - AssemblyCache.Remove(loadedAssembly.GetName().Name); + AssemblyCache.TryAdd(key, assembly); + } + + /// + /// Remove all cache entries that are associated with the specified source. + /// + internal void RemoveFromAssemblyCache(string source) + { + if (string.IsNullOrEmpty(source)) + { + return; } + + var keysToRemove = new List(); + string prefix = $"{source}@"; + + foreach (string key in AssemblyCache.Keys) + { + if (key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) + { + keysToRemove.Add(key); + } + } + + foreach (string key in keysToRemove) + { + AssemblyCache.Remove(key); + } + } + + /// + /// Try to get an assembly from the cache. + /// + private bool TryGetFromAssemblyCache(string source, string filePath, out Assembly assembly) + { + if (string.IsNullOrEmpty(filePath)) + { + assembly = null; + return false; + } + + // Both 'source' and 'filePath' are of the string type, so no need to specify 'InvariantCulture'. + string key = string.IsNullOrEmpty(source) ? filePath : $"{source}@{filePath}"; + return AssemblyCache.TryGetValue(key, out assembly); } - [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadWithPartialName")] - [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] - internal static Assembly LoadAssembly(string name, string filename, out Exception error) + private static Assembly LoadAssembly(string name, string filePath, out Exception error) { // First we try to load the assembly based on the filename Assembly loadedAssembly = null; error = null; - if (!string.IsNullOrEmpty(filename)) + if (!string.IsNullOrEmpty(filePath)) { try { - loadedAssembly = Assembly.LoadFrom(filename); + // codeql[cs/dll-injection-remote] - The dll is loaded during the initial state setup, which is expected behavior. This allows users hosting PowerShell to load additional C# types to enable their specific scenarios. + loadedAssembly = Assembly.LoadFrom(filePath); return loadedAssembly; } catch (FileNotFoundException fileNotFound) @@ -1451,9 +1473,17 @@ internal void ReportEngineStartupError(string resourceString, params object[] ar else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine( StringUtil.Format(resourceString, arguments)); } @@ -1481,9 +1511,17 @@ internal void ReportEngineStartupError(string error) else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine(error); } } @@ -1516,9 +1554,17 @@ internal void ReportEngineStartupError(Exception e) else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine(e.Message); } } @@ -1536,17 +1582,24 @@ internal void ReportEngineStartupError(ErrorRecord errorRecord) try { Cmdlet currentRunningModuleCommand; - string unused; - if (IsModuleCommandCurrentlyRunning(out currentRunningModuleCommand, out unused)) + if (IsModuleCommandCurrentlyRunning(out currentRunningModuleCommand, out _)) { currentRunningModuleCommand.WriteError(errorRecord); } else { PSHost host = EngineHostInterface; - if (host == null) return; + if (host == null) + { + return; + } + PSHostUserInterface ui = host.UI; - if (ui == null) return; + if (ui == null) + { + return; + } + ui.WriteErrorLine(errorRecord.ToString()); } } @@ -1602,23 +1655,6 @@ internal ExecutionContext(AutomationEngine engine, PSHost hostInterface, Initial private void InitializeCommon(AutomationEngine engine, PSHost hostInterface) { Engine = engine; -#if !CORECLR// System.AppDomain is not in CoreCLR - // Set the assembly resolve handler if it isn't already set... - if (!_assemblyEventHandlerSet) - { - // we only want to set the event handler once for the entire app domain... - lock (lockObject) - { - // Need to check again inside the lock due to possibility of a race condition... - if (!_assemblyEventHandlerSet) - { - AppDomain currentAppDomain = AppDomain.CurrentDomain; - currentAppDomain.AssemblyResolve += new ResolveEventHandler(PowerShellAssemblyResolveHandler); - _assemblyEventHandlerSet = true; - } - } - } -#endif Events = new PSLocalEventManager(this); transactionManager = new PSTransactionManager(); _debugger = new ScriptDebugger(this); @@ -1626,52 +1662,20 @@ private void InitializeCommon(AutomationEngine engine, PSHost hostInterface) EngineHostInterface = hostInterface as InternalHost ?? new InternalHost(hostInterface, this); // Hook up the assembly cache - AssemblyCache = new Dictionary(); + AssemblyCache = new Dictionary(StringComparer.OrdinalIgnoreCase); // Initialize the fixed toplevel session state and the current session state TopLevelSessionState = EngineSessionState = new SessionStateInternal(this); - if (AuthorizationManager == null) - { - // if authorizationmanager==null, this means the configuration - // explicitly asked for dummy authorization manager. - AuthorizationManager = new AuthorizationManager(null); - } + // if authorizationmanager==null, this means the configuration + // explicitly asked for dummy authorization manager. + AuthorizationManager ??= new AuthorizationManager(null); // Set up the module intrinsics Modules = new ModuleIntrinsics(this); } private static readonly object lockObject = new object(); - -#if !CORECLR // System.AppDomain is not in CoreCLR - private static bool _assemblyEventHandlerSet = false; - - /// - /// AssemblyResolve event handler that will look in the assembly cache to see - /// if the named assembly has been loaded. This is necessary so that assemblies loaded - /// with LoadFrom, which are in a different loaded context than Load, can still be used to - /// resolve types. - /// - /// The event sender. - /// The event args. - /// The resolve assembly or null if not found. - private static Assembly PowerShellAssemblyResolveHandler(object sender, ResolveEventArgs args) - { - ExecutionContext ecFromTLS = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); - if (ecFromTLS != null) - { - if (ecFromTLS.AssemblyCache != null) - { - Assembly assembly; - ecFromTLS.AssemblyCache.TryGetValue(args.Name, out assembly); - return assembly; - } - } - - return null; - } -#endif } /// diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs index 7a76a18ddb9..af09f427253 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/EnableDisableExperimentalFeatureCommand.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.ObjectModel; using System.Globalization; using System.Linq; using System.Management.Automation; @@ -112,26 +113,28 @@ public class ExperimentalFeatureNameCompleter : IArgumentCompleter /// The command AST. /// The fake bound parameters. /// List of Completion Results. - public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) + public IEnumerable CompleteArgument( + string commandName, + string parameterName, + string wordToComplete, + CommandAst commandAst, + IDictionary fakeBoundParameters) { - if (fakeBoundParameters == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(fakeBoundParameters)); - } - - var commandInfo = new CmdletInfo("Get-ExperimentalFeature", typeof(GetExperimentalFeatureCommand)); - var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace) - .AddCommand(commandInfo) - .AddParameter("Name", wordToComplete + "*"); + SortedSet expirmentalFeatures = new(StringComparer.OrdinalIgnoreCase); - HashSet names = new HashSet(); - var results = ps.Invoke(); - foreach (var result in results) + foreach (ExperimentalFeature feature in GetExperimentalFeatures()) { - names.Add(result.Name); + expirmentalFeatures.Add(feature.Name); } - return names.OrderBy(name => name).Select(name => new CompletionResult(name, name, CompletionResultType.Text, name)); + return CompletionHelpers.GetMatchingResults(wordToComplete, expirmentalFeatures); + } + + private static Collection GetExperimentalFeatures() + { + using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); + ps.AddCommand("Get-ExperimentalFeature"); + return ps.Invoke(); } } } diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs index 5eeaf814e10..7e17ec43137 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/ExperimentalFeature.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; @@ -21,7 +20,8 @@ public class ExperimentalFeature #region Const Members internal const string EngineSource = "PSEngine"; - internal const string PSAnsiProgressFeatureName = "PSAnsiProgress"; + internal const string PSSerializeJSONLongEnumAsNumber = nameof(PSSerializeJSONLongEnumAsNumber); + internal const string PSProfileDSCResource = "PSProfileDSCResource"; #endregion @@ -105,42 +105,22 @@ static ExperimentalFeature() description: "Replace the old FileSystemProvider with cleaner design and faster code"), */ new ExperimentalFeature( - name: "PSImplicitRemotingBatching", - description: "Batch implicit remoting proxy commands to improve performance"), + name: "PSLoadAssemblyFromNativeCode", + description: "Expose an API to allow assembly loading from native code"), new ExperimentalFeature( - name: "PSCommandNotFoundSuggestion", - description: "Recommend potential commands based on fuzzy search on a CommandNotFoundException"), -#if UNIX + name: PSSerializeJSONLongEnumAsNumber, + description: "Serialize enums based on long or ulong as an numeric value rather than the string representation when using ConvertTo-Json." + ), new ExperimentalFeature( - name: "PSUnixFileStat", - description: "Provide unix permission information for files and directories"), -#endif - new ExperimentalFeature( - name: "PSCultureInvariantReplaceOperator", - description: "Use culture invariant to-string convertor for lval in replace operator"), - new ExperimentalFeature( - name: "PSNativePSPathResolution", - description: "Convert PSPath to filesystem path, if possible, for native commands"), - new ExperimentalFeature( - name: "PSNotApplyErrorActionToStderr", - description: "Don't have $ErrorActionPreference affect stderr output"), - new ExperimentalFeature( - name: "PS7DscSupport", - description: "Support the cross-platform class-based DSC"), - new ExperimentalFeature( - name: "PSSubsystemPluginModel", - description: "A plugin model for registering and un-registering PowerShell subsystems"), - new ExperimentalFeature( - name: "PSAnsiRendering", - description: "Enable $PSStyle variable to control ANSI rendering of strings"), - new ExperimentalFeature( - name: PSAnsiProgressFeatureName, - description: "Enable lightweight progress bar that leverages ANSI codes for rendering"), + name: PSProfileDSCResource, + description: "DSC v3 resources for managing PowerShell profile." + ) }; + EngineExperimentalFeatures = new ReadOnlyCollection(engineFeatures); // Initialize the readonly dictionary 'EngineExperimentalFeatureMap'. - var engineExpFeatureMap = engineFeatures.ToDictionary(f => f.Name, StringComparer.OrdinalIgnoreCase); + var engineExpFeatureMap = engineFeatures.ToDictionary(static f => f.Name, StringComparer.OrdinalIgnoreCase); EngineExperimentalFeatureMap = new ReadOnlyDictionary(engineExpFeatureMap); // Initialize the readonly hashset 'EnabledExperimentalFeatureNames'. @@ -160,6 +140,20 @@ static ExperimentalFeature() EnabledExperimentalFeatureNames = ProcessEnabledFeatures(enabledFeatures); } + /// + /// We need to notify which features were not enabled. + /// + private static void SendTelemetryForDeactivatedFeatures(ReadOnlyBag enabledFeatures) + { + foreach (var feature in EngineExperimentalFeatures) + { + if (!enabledFeatures.Contains(feature.Name)) + { + ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ExperimentalEngineFeatureDeactivation, feature.Name); + } + } + } + /// /// Process the array of enabled feature names retrieved from configuration. /// Ignore invalid feature names and unavailable engine feature names, and @@ -167,7 +161,10 @@ static ExperimentalFeature() /// private static ReadOnlyBag ProcessEnabledFeatures(string[] enabledFeatures) { - if (enabledFeatures.Length == 0) { return ReadOnlyBag.Empty; } + if (enabledFeatures.Length == 0) + { + return ReadOnlyBag.Empty; + } var list = new List(enabledFeatures.Length); foreach (string name in enabledFeatures) @@ -198,7 +195,9 @@ private static ReadOnlyBag ProcessEnabledFeatures(string[] enabledFeatur } } - return new ReadOnlyBag(new HashSet(list, StringComparer.OrdinalIgnoreCase)); + ReadOnlyBag features = new(new HashSet(list, StringComparer.OrdinalIgnoreCase)); + SendTelemetryForDeactivatedFeatures(features); + return features; } /// diff --git a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs index d87669000de..38525cb54ef 100644 --- a/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs +++ b/src/System.Management.Automation/engine/ExperimentalFeature/GetExperimentalFeatureCommand.cs @@ -88,17 +88,26 @@ private IEnumerable GetValidModuleFiles(HashSet moduleNamesToFin foreach (string path in ModuleIntrinsics.GetModulePath(includeSystemModulePath: false, Context)) { string uniquePath = path.TrimEnd(Utils.Separators.Directory); - if (!modulePaths.Add(uniquePath)) { continue; } + if (!modulePaths.Add(uniquePath)) + { + continue; + } foreach (string moduleFile in ModuleUtils.GetDefaultAvailableModuleFiles(uniquePath)) { // We only care about module manifest files because that's where experimental features are declared. - if (!moduleFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) { continue; } + if (!moduleFile.EndsWith(StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) + { + continue; + } if (moduleNamesToFind != null) { string currentModuleName = ModuleIntrinsics.GetModuleName(moduleFile); - if (!moduleNamesToFind.Contains(currentModuleName)) { continue; } + if (!moduleNamesToFind.Contains(currentModuleName)) + { + continue; + } } yield return moduleFile; diff --git a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs index ac99127ab29..06271728e00 100644 --- a/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs +++ b/src/System.Management.Automation/engine/ExtendedTypeSystemException.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation /// /// Defines the exception thrown for all Extended type system related errors. /// - [Serializable] public class ExtendedTypeSystemException : RuntimeException { #region ctor @@ -36,7 +35,7 @@ public ExtendedTypeSystemException(string message) /// Initializes a new instance of ExtendedTypeSystemException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ExtendedTypeSystemException(string message, Exception innerException) : base(message, innerException) { @@ -67,8 +66,9 @@ internal ExtendedTypeSystemException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ExtendedTypeSystemException(SerializationInfo info, StreamingContext context) - : base(info, context) + : base(info, context) { } #endregion Serialization @@ -80,7 +80,6 @@ protected ExtendedTypeSystemException(SerializationInfo info, StreamingContext c /// /// Defines the exception thrown for Method related errors. /// - [Serializable] public class MethodException : ExtendedTypeSystemException { internal const string MethodArgumentCountExceptionMsg = "MethodArgumentCountException"; @@ -112,7 +111,7 @@ public MethodException(string message) /// Initializes a new instance of MethodException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public MethodException(string message, Exception innerException) : base(message, innerException) { @@ -140,9 +139,10 @@ internal MethodException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected MethodException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -153,7 +153,6 @@ protected MethodException(SerializationInfo info, StreamingContext context) /// /// Defines the exception thrown for Method invocation exceptions. /// - [Serializable] public class MethodInvocationException : MethodException { internal const string MethodInvocationExceptionMsg = "MethodInvocationException"; @@ -183,7 +182,7 @@ public MethodInvocationException(string message) /// Initializes a new instance of MethodInvocationException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public MethodInvocationException(string message, Exception innerException) : base(message, innerException) { @@ -211,9 +210,10 @@ internal MethodInvocationException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected MethodInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -224,7 +224,6 @@ protected MethodInvocationException(SerializationInfo info, StreamingContext con /// /// Defines the exception thrown for errors getting the value of properties. /// - [Serializable] public class GetValueException : ExtendedTypeSystemException { internal const string GetWithoutGetterExceptionMsg = "GetWithoutGetterException"; @@ -252,7 +251,7 @@ public GetValueException(string message) /// Initializes a new instance of GetValueException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public GetValueException(string message, Exception innerException) : base(message, innerException) { @@ -280,9 +279,10 @@ internal GetValueException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected GetValueException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -293,7 +293,6 @@ protected GetValueException(SerializationInfo info, StreamingContext context) /// /// Defines the exception thrown for errors getting the value of properties. /// - [Serializable] public class PropertyNotFoundException : ExtendedTypeSystemException { #region ctor @@ -319,7 +318,7 @@ public PropertyNotFoundException(string message) /// Initializes a new instance of GetValueException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public PropertyNotFoundException(string message, Exception innerException) : base(message, innerException) { @@ -347,12 +346,12 @@ internal PropertyNotFoundException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PropertyNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization - #endregion ctor } @@ -360,7 +359,6 @@ protected PropertyNotFoundException(SerializationInfo info, StreamingContext con /// /// Defines the exception thrown for exceptions thrown by property getters. /// - [Serializable] public class GetValueInvocationException : GetValueException { internal const string ExceptionWhenGettingMsg = "ExceptionWhenGetting"; @@ -388,7 +386,7 @@ public GetValueInvocationException(string message) /// Initializes a new instance of GetValueInvocationException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public GetValueInvocationException(string message, Exception innerException) : base(message, innerException) { @@ -416,9 +414,10 @@ internal GetValueInvocationException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected GetValueInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -429,7 +428,6 @@ protected GetValueInvocationException(SerializationInfo info, StreamingContext c /// /// Defines the exception thrown for errors setting the value of properties. /// - [Serializable] public class SetValueException : ExtendedTypeSystemException { #region ctor @@ -455,7 +453,7 @@ public SetValueException(string message) /// Initializes a new instance of SetValueException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public SetValueException(string message, Exception innerException) : base(message, innerException) { @@ -483,9 +481,10 @@ internal SetValueException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected SetValueException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -496,7 +495,6 @@ protected SetValueException(SerializationInfo info, StreamingContext context) /// /// Defines the exception thrown for exceptions thrown by property setters. /// - [Serializable] public class SetValueInvocationException : SetValueException { #region ctor @@ -522,7 +520,7 @@ public SetValueInvocationException(string message) /// Initializes a new instance of SetValueInvocationException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public SetValueInvocationException(string message, Exception innerException) : base(message, innerException) { @@ -550,9 +548,10 @@ internal SetValueInvocationException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected SetValueInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization @@ -563,40 +562,19 @@ protected SetValueInvocationException(SerializationInfo info, StreamingContext c /// /// Defines the exception thrown for type conversion errors. /// - [Serializable] public class PSInvalidCastException : InvalidCastException, IContainsErrorRecord { - #region Serialization - - /// - /// Populates a with the - /// data needed to serialize the PSInvalidCastException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } /// /// Initializes a new instance of PSInvalidCastException with serialization parameters. /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSInvalidCastException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); + throw new NotSupportedException(); } - #endregion Serialization - /// /// Initializes a new instance of PSInvalidCastException with the message set /// to typeof(PSInvalidCastException).FullName. @@ -617,7 +595,7 @@ public PSInvalidCastException(string message) /// Initializes a new instance of PSInvalidCastException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public PSInvalidCastException(string message, Exception innerException) : base(message, innerException) { @@ -647,14 +625,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.InvalidArgument, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.InvalidArgument, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/engine/ExternalScriptInfo.cs b/src/System.Management.Automation/engine/ExternalScriptInfo.cs index bbd49c76d36..e8c8c2b1d54 100644 --- a/src/System.Management.Automation/engine/ExternalScriptInfo.cs +++ b/src/System.Management.Automation/engine/ExternalScriptInfo.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation { /// - /// Provides information for MSH scripts that are directly executable by MSH + /// Provides information for scripts that are directly executable by PowerShell /// but are not built into the runspace configuration. /// public class ExternalScriptInfo : CommandInfo, IScriptCommandInfo @@ -103,14 +103,21 @@ private void CommonInitialization() // Get the lock down policy with no handle. This only impacts command discovery, // as the real language mode assignment will be done when we read the script // contents. - SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, null); - if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) + switch (SystemPolicy.GetLockdownPolicy(_path, null)) { - this.DefiningLanguageMode = PSLanguageMode.FullLanguage; - } - else - { - this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + case SystemEnforcementMode.None: + DefiningLanguageMode = PSLanguageMode.FullLanguage; + break; + + case SystemEnforcementMode.Audit: + // For policy audit mode, language mode is set to CL but audit messages are emitted to log + // instead of applying restrictions. + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemEnforcementMode.Enforce: + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; } } } @@ -188,7 +195,10 @@ public override SessionStateEntryVisibility Visibility { get { - if (Context == null) return SessionStateEntryVisibility.Public; + if (Context == null) + { + return SessionStateEntryVisibility.Public; + } return Context.EngineSessionState.CheckScriptVisibility(_path); } @@ -384,7 +394,7 @@ internal override bool ImplementsDynamicParameters // If we got here, there was some sort of parsing exception. We'll just // ignore it and assume the script does not implement dynamic parameters. - // Futhermore, we'll clear out the fields so that the next attempt to + // Furthermore, we'll clear out the fields so that the next attempt to // access ScriptBlock will result in an exception that doesn't get ignored. _scriptBlock = null; _scriptContents = null; @@ -455,15 +465,6 @@ internal uint PSVersionLineNumber get { return 0; } } - internal IEnumerable RequiresPSSnapIns - { - get - { - var data = GetRequiresData(); - return data?.RequiresPSSnapIns; - } - } - /// /// Gets the original contents of the script. /// @@ -515,33 +516,54 @@ private void ReadScriptContents() { using (FileStream readerStream = new FileStream(_path, FileMode.Open, FileAccess.Read)) { - Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); - Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; - - using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) + using (StreamReader scriptReader = new StreamReader(readerStream, Encoding.Default)) { _scriptContents = scriptReader.ReadToEnd(); _originalEncoding = scriptReader.CurrentEncoding; - // Check if this came from a trusted path. If so, set its language mode to FullLanguage. - if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.None) - { - SystemEnforcementMode scriptSpecificPolicy = SystemPolicy.GetLockdownPolicy(_path, safeFileHandle); - if (scriptSpecificPolicy != SystemEnforcementMode.Enforce) - { - this.DefiningLanguageMode = PSLanguageMode.FullLanguage; - } - else - { - this.DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; - } - } - else + // Check this file against any system wide enforcement policies. + SystemScriptFileEnforcement filePolicyEnforcement = SystemPolicy.GetFilePolicyEnforcement(_path, readerStream); + switch (filePolicyEnforcement) { - if (this.Context != null) - { - this.DefiningLanguageMode = this.Context.LanguageMode; - } + case SystemScriptFileEnforcement.None: + if (Context != null) + { + DefiningLanguageMode = Context.LanguageMode; + } + break; + + case SystemScriptFileEnforcement.Allow: + DefiningLanguageMode = PSLanguageMode.FullLanguage; + break; + + case SystemScriptFileEnforcement.AllowConstrained: + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemScriptFileEnforcement.AllowConstrainedAudit: + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: SecuritySupportStrings.ExternalScriptWDACLogTitle, + message: string.Format(Globalization.CultureInfo.CurrentUICulture, SecuritySupportStrings.ExternalScriptWDACLogMessage, _path), + fqid: "ScriptFileNotTrustedByPolicy"); + // We set the language mode to Constrained Language, even though in policy audit mode no restrictions are applied + // and instead an audit log message is generated wherever a restriction would be applied. + DefiningLanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemScriptFileEnforcement.Block: + throw new PSSecurityException( + string.Format( + Globalization.CultureInfo.CurrentUICulture, + SecuritySupportStrings.ScriptFileBlockedBySystemPolicy, + _path)); + + default: + throw new PSSecurityException( + string.Format( + Globalization.CultureInfo.CurrentUICulture, + SecuritySupportStrings.UnknownSystemScriptFileEnforcement, + filePolicyEnforcement)); } } } @@ -589,7 +611,6 @@ internal ScriptRequiresSyntaxException(string message) /// /// Defines the name and version tuple of a PSSnapin. /// - [Serializable] public class PSSnapInSpecification { internal PSSnapInSpecification(string psSnapinName) diff --git a/src/System.Management.Automation/engine/GetCommandCommand.cs b/src/System.Management.Automation/engine/GetCommandCommand.cs index 9007bed247c..10e8334021b 100644 --- a/src/System.Management.Automation/engine/GetCommandCommand.cs +++ b/src/System.Management.Automation/engine/GetCommandCommand.cs @@ -12,6 +12,7 @@ using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using static System.Management.Automation.Verbs; using Dbg = System.Management.Automation.Diagnostics; namespace Microsoft.PowerShell.Commands @@ -71,6 +72,7 @@ public string[] Name /// Gets or sets the verb parameter to the cmdlet. /// [Parameter(ValueFromPipelineByPropertyName = true, ParameterSetName = "CmdletSet")] + [ArgumentCompleter(typeof(VerbArgumentCompleter))] public string[] Verb { get @@ -80,10 +82,7 @@ public string[] Verb set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _verbs = value; _verbPatterns = null; @@ -106,10 +105,7 @@ public string[] Noun set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _nouns = value; _nounPatterns = null; @@ -132,10 +128,7 @@ public string[] Module set { - if (value == null) - { - value = Array.Empty(); - } + value ??= Array.Empty(); _modules = value; _modulePatterns = null; @@ -147,6 +140,28 @@ public string[] Module private string[] _modules = Array.Empty(); private bool _isModuleSpecified = false; + /// + /// Gets or sets the ExcludeModule parameter to the cmdlet. + /// + [Parameter()] + public string[] ExcludeModule + { + get + { + return _excludedModules; + } + + set + { + value ??= Array.Empty(); + + _excludedModules = value; + _excludedModulePatterns = null; + } + } + + private string[] _excludedModules = Array.Empty(); + /// /// Gets or sets the FullyQualifiedModule parameter to the cmdlet. /// @@ -287,10 +302,7 @@ public string[] ParameterName set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _parameterNames = value; _parameterNameWildcards = SessionStateUtilities.CreateWildcardsFromStrings( @@ -317,10 +329,7 @@ public PSTypeName[] ParameterType set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); // if '...CimInstance#Win32_Process' is specified, then exclude '...CimInstance' List filteredParameterTypes = new List(value.Length); @@ -353,7 +362,14 @@ public PSTypeName[] ParameterType [Parameter(ParameterSetName = "AllCommandSet")] public SwitchParameter UseFuzzyMatching { get; set; } - private readonly List _commandScores = new List(); + /// + /// Gets or sets the minimum fuzzy matching distance. + /// + [Parameter(ParameterSetName = "AllCommandSet")] + public uint FuzzyMinimumDistance { get; set; } = 5; + + private FuzzyMatcher _fuzzyMatcher; + private List _commandScores; /// /// Gets or sets the parameter that determines if return cmdlets based on abbreviation expansion. @@ -375,7 +391,11 @@ protected override void BeginProcessing() #if LEGACYTELEMETRY _timer.Start(); #endif - base.BeginProcessing(); + if (UseFuzzyMatching) + { + _fuzzyMatcher = new FuzzyMatcher(FuzzyMinimumDistance); + _commandScores = new List(); + } if (ShowCommandInfo.IsPresent && Syntax.IsPresent) { @@ -405,10 +425,8 @@ protected override void ProcessRecord() } // Initialize the module patterns - if (_modulePatterns == null) - { - _modulePatterns = SessionStateUtilities.CreateWildcardsFromStrings(Module, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - } + _modulePatterns ??= SessionStateUtilities.CreateWildcardsFromStrings(Module, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); + _excludedModulePatterns ??= SessionStateUtilities.CreateWildcardsFromStrings(ExcludeModule, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); switch (ParameterSetName) { @@ -487,7 +505,7 @@ protected override void EndProcessing() if ((_names == null) || (_nameContainsWildcard)) { // Use the stable sorting to sort the result list - _accumulatedResults = _accumulatedResults.OrderBy(a => a, new CommandInfoComparer()).ToList(); + _accumulatedResults = _accumulatedResults.Order(new CommandInfoComparer()).ToList(); } OutputResultsHelper(_accumulatedResults); @@ -514,17 +532,17 @@ protected override void EndProcessing() private void OutputResultsHelper(IEnumerable results) { - CommandOrigin origin = this.MyInvocation.CommandOrigin; + CommandOrigin origin = MyInvocation.CommandOrigin; if (UseFuzzyMatching) { - results = _commandScores.OrderBy(x => x.Score).Select(x => x.Command).ToList(); + _commandScores = _commandScores.OrderBy(static x => x.Score).ToList(); + results = _commandScores.Select(static x => x.Command); } int count = 0; foreach (CommandInfo result in results) { - count += 1; // Only write the command if it is visible to the requestor if (SessionState.IsVisible(origin, result)) { @@ -549,11 +567,21 @@ private void OutputResultsHelper(IEnumerable results) } else { - // Write output as normal command info object. - WriteObject(result); + if (UseFuzzyMatching) + { + PSObject obj = new PSObject(result); + obj.Properties.Add(new PSNoteProperty("Score", _commandScores[count].Score)); + WriteObject(obj); + } + else + { + WriteObject(result); + } } } } + + count += 1; } #if LEGACYTELEMETRY @@ -561,7 +589,7 @@ private void OutputResultsHelper(IEnumerable results) // No telemetry here - capturing the name of a command which we are not familiar with // may be confidential customer information - // We want telementry on commands people look for but don't exist - this should give us an idea + // We want telemetry on commands people look for but don't exist - this should give us an idea // what sort of commands people expect but either don't exist, or maybe should be installed by default. // The StartsWith is to avoid logging telemetry when suggestion mode checks the // current directory for scripts/exes in the current directory and '.' is not in the path. @@ -650,7 +678,7 @@ private PSObject GetSyntaxObject(CommandInfo command) /// /// The comparer to sort CommandInfo objects in the result list. /// - private class CommandInfoComparer : IComparer + private sealed class CommandInfoComparer : IComparer { /// /// Compare two CommandInfo objects first by their command types, and if they @@ -691,18 +719,19 @@ private bool IsNounVerbMatch(CommandInfo command) do // false loop { - if (_verbPatterns == null) - { - _verbPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Verb, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - } + _verbPatterns ??= SessionStateUtilities.CreateWildcardsFromStrings(Verb, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - if (_nounPatterns == null) - { - _nounPatterns = SessionStateUtilities.CreateWildcardsFromStrings(Noun, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - } + _nounPatterns ??= SessionStateUtilities.CreateWildcardsFromStrings(Noun, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); if (!string.IsNullOrEmpty(command.ModuleName)) { + if (_excludedModulePatterns is not null + && _excludedModulePatterns.Count > 0 + && SessionStateUtilities.MatchesAnyWildcardPattern(command.ModuleName, _excludedModulePatterns, true)) + { + break; + } + if (_isFullyQualifiedModuleSpecified) { if (!_moduleSpecifications.Any( @@ -788,11 +817,6 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) options |= SearchResolutionOptions.UseAbbreviationExpansion; } - if (UseFuzzyMatching) - { - options |= SearchResolutionOptions.FuzzyMatch; - } - if ((this.CommandType & CommandTypes.Alias) != 0) { options |= SearchResolutionOptions.ResolveAliasPatterns; @@ -865,24 +889,25 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) IEnumerable commands; if (UseFuzzyMatching) { - foreach (var commandScore in System.Management.Automation.Internal.ModuleUtils.GetFuzzyMatchingCommands( + foreach (var commandScore in ModuleUtils.GetFuzzyMatchingCommands( plainCommandName, - this.Context, - this.MyInvocation.CommandOrigin, + Context, + MyInvocation.CommandOrigin, + _fuzzyMatcher, rediscoverImportedModules: true, moduleVersionRequired: _isFullyQualifiedModuleSpecified)) { _commandScores.Add(commandScore); } - commands = _commandScores.Select(x => x.Command).ToList(); + commands = _commandScores.Select(static x => x.Command); } else { - commands = System.Management.Automation.Internal.ModuleUtils.GetMatchingCommands( + commands = ModuleUtils.GetMatchingCommands( plainCommandName, - this.Context, - this.MyInvocation.CommandOrigin, + Context, + MyInvocation.CommandOrigin, rediscoverImportedModules: true, moduleVersionRequired: _isFullyQualifiedModuleSpecified, useAbbreviationExpansion: UseAbbreviationExpansion); @@ -943,12 +968,12 @@ private void AccumulateMatchingCommands(IEnumerable commandNames) private bool FindCommandForName(SearchResolutionOptions options, string commandName, bool isPattern, bool emitErrors, ref int currentCount, out bool isDuplicate) { - CommandSearcher searcher = - new CommandSearcher( - commandName, - options, - this.CommandType, - this.Context); + var searcher = new CommandSearcher( + commandName, + options, + CommandType, + Context, + _fuzzyMatcher); bool resultFound = false; isDuplicate = false; @@ -1036,8 +1061,10 @@ private bool FindCommandForName(SearchResolutionOptions options, string commandN if (UseFuzzyMatching) { - int score = FuzzyMatcher.GetDamerauLevenshteinDistance(current.Name, commandName); - _commandScores.Add(new CommandScore(current, score)); + if (_fuzzyMatcher.IsFuzzyMatch(current.Name, commandName, out int score)) + { + _commandScores.Add(new CommandScore(current, score)); + } } _accumulatedResults.Add(current); @@ -1159,10 +1186,7 @@ private bool IsParameterMatch(CommandInfo commandInfo) return true; } - if (_matchedParameterNames == null) - { - _matchedParameterNames = new HashSet(StringComparer.OrdinalIgnoreCase); - } + _matchedParameterNames ??= new HashSet(StringComparer.OrdinalIgnoreCase); IEnumerable commandParameters = null; try @@ -1277,6 +1301,13 @@ private bool IsCommandMatch(ref CommandInfo current, out bool isDuplicate) } else { + if (_excludedModulePatterns is not null + && _excludedModulePatterns.Count > 0 + && SessionStateUtilities.MatchesAnyWildcardPattern(current.ModuleName, _excludedModulePatterns, true)) + { + return false; + } + if (_isFullyQualifiedModuleSpecified) { bool foundModuleMatch = false; @@ -1536,6 +1567,7 @@ private bool IsCommandInResult(CommandInfo command) private Collection _verbPatterns; private Collection _nounPatterns; private Collection _modulePatterns; + private Collection _excludedModulePatterns; #if LEGACYTELEMETRY private Stopwatch _timer = new Stopwatch(); @@ -1662,40 +1694,50 @@ private static PSObject GetParameterType(Type parameterType) } /// + /// Provides argument completion for Noun parameter. /// public class NounArgumentCompleter : IArgumentCompleter { + /// + /// Returns completion results for Noun 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: GetCommandNouns(fakeBoundParameters)); + /// + /// Get sorted set of command nouns using Get-Command. /// - public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) + /// The fake bound parameters. + /// Sorted set of command nouns. + private static SortedSet GetCommandNouns(IDictionary fakeBoundParameters) { - if (fakeBoundParameters == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(fakeBoundParameters)); - } - - var commandInfo = new CmdletInfo("Get-Command", typeof(GetCommandCommand)); - var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace) - .AddCommand(commandInfo) - .AddParameter("Noun", wordToComplete + "*"); - - if (fakeBoundParameters.Contains("Module")) - { - ps.AddParameter("Module", fakeBoundParameters["Module"]); - } + Collection commands = CompletionCompleters.GetCommandInfo(fakeBoundParameters, "Module", "Verb"); + SortedSet nouns = new(StringComparer.OrdinalIgnoreCase); - HashSet nouns = new HashSet(); - var results = ps.Invoke(); - foreach (var result in results) + foreach (CommandInfo command in commands) { - var dash = result.Name.IndexOf('-'); - if (dash != -1) + string commandName = command.Name; + int dashIndex = commandName.IndexOf('-'); + if (dashIndex != -1) { - nouns.Add(result.Name.Substring(dash + 1)); + string noun = commandName.Substring(dashIndex + 1); + nouns.Add(noun); } } - return nouns.OrderBy(noun => noun).Select(noun => new CompletionResult(noun, noun, CompletionResultType.Text, noun)); + return nouns; } } } diff --git a/src/System.Management.Automation/engine/ICommandRuntime.cs b/src/System.Management.Automation/engine/ICommandRuntime.cs index 6f0b3ce9d57..49b1104e047 100644 --- a/src/System.Management.Automation/engine/ICommandRuntime.cs +++ b/src/System.Management.Automation/engine/ICommandRuntime.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable + using System.Management.Automation.Host; namespace System.Management.Automation @@ -13,8 +15,8 @@ namespace System.Management.Automation /// When a cmdlet is instantiated and run directly, all calls to the stream APIs will be proxied /// through to an instance of this class. For example, when a cmdlet calls WriteObject, the /// WriteObject implementation on the instance of the class implementing this interface will be - /// called. The Monad implementation provides a default implementation of this class for use with - /// standalone cmdlets as well as the implementation provided for running in the monad engine itself. + /// called. PowerShell implementation provides a default implementation of this class for use with + /// standalone cmdlets as well as the implementation provided for running in the engine itself. /// /// If you do want to run Cmdlet instances standalone and capture their output with more /// fidelity than is provided for with the default implementation, then you should create your own @@ -26,7 +28,7 @@ public interface ICommandRuntime /// /// Returns an instance of the PSHost implementation for this environment. /// - PSHost Host { get; } + PSHost? Host { get; } #region Write /// /// Display debug information. @@ -65,7 +67,7 @@ public interface ICommandRuntime /// When the cmdlet wants to write a single object out, it will call this /// API. It is up to the implementation to decide what to do with these objects. /// - void WriteObject(object sendToPipeline); + void WriteObject(object? sendToPipeline); /// /// Called to write one or more objects to the output pipe. @@ -83,7 +85,7 @@ public interface ICommandRuntime /// When the cmdlet wants to write multiple objects out, it will call this /// API. It is up to the implementation to decide what to do with these objects. /// - void WriteObject(object sendToPipeline, bool enumerateCollection); + void WriteObject(object? sendToPipeline, bool enumerateCollection); /// /// Called by the cmdlet to display progress information. @@ -172,7 +174,7 @@ public interface ICommandRuntime /// pipeline execution log. /// /// If LogPipelineExecutionDetail is turned on, this information will be written - /// to monad log under log category "Pipeline execution detail" + /// to PowerShell log under log category "Pipeline execution detail" /// /// /// @@ -219,7 +221,7 @@ public interface ICommandRuntime /// /// /// - bool ShouldProcess(string target); + bool ShouldProcess(string? target); /// /// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes @@ -265,7 +267,7 @@ public interface ICommandRuntime /// /// /// - bool ShouldProcess(string target, string action); + bool ShouldProcess(string? target, string? action); /// /// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes @@ -319,7 +321,7 @@ public interface ICommandRuntime /// /// /// - bool ShouldProcess(string verboseDescription, string verboseWarning, string caption); + bool ShouldProcess(string? verboseDescription, string? verboseWarning, string? caption); /// /// Called by a cmdlet to confirm the operation with the user. Cmdlets which make changes @@ -379,7 +381,7 @@ public interface ICommandRuntime /// /// /// - bool ShouldProcess(string verboseDescription, string verboseWarning, string caption, out ShouldProcessReason shouldProcessReason); + bool ShouldProcess(string? verboseDescription, string? verboseWarning, string? caption, out ShouldProcessReason shouldProcessReason); /// /// Called by a cmdlet to confirm an operation or grouping of operations with the user. @@ -436,7 +438,7 @@ public interface ICommandRuntime /// /// /// - bool ShouldContinue(string query, string caption); + bool ShouldContinue(string? query, string? caption); /// /// Called to confirm an operation or grouping of operations with the user. @@ -455,11 +457,11 @@ public interface ICommandRuntime /// It may be displayed by some hosts, but not all. /// /// - /// true iff user selects YesToAll. If this is already true, + /// true if-and-only-if user selects YesToAll. If this is already true, /// ShouldContinue will bypass the prompt and return true. /// /// - /// true iff user selects NoToAll. If this is already true, + /// true if-and-only-if user selects NoToAll. If this is already true, /// ShouldContinue will bypass the prompt and return false. /// /// @@ -501,7 +503,7 @@ public interface ICommandRuntime /// /// /// - bool ShouldContinue(string query, string caption, ref bool yesToAll, ref bool noToAll); + bool ShouldContinue(string? query, string? caption, ref bool yesToAll, ref bool noToAll); #endregion Should @@ -515,7 +517,7 @@ public interface ICommandRuntime /// Gets an object that surfaces the current PowerShell transaction. /// When this object is disposed, PowerShell resets the active transaction. /// - PSTransactionContext CurrentPSTransaction { get; } + PSTransactionContext? CurrentPSTransaction { get; } #endregion Transaction Support #region Misc @@ -549,6 +551,7 @@ public interface ICommandRuntime /// if any information is to be added. It should encapsulate the /// error record into an exception and then throw that exception. /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] void ThrowTerminatingError(ErrorRecord errorRecord); #endregion ThrowTerminatingError #endregion misc @@ -560,7 +563,6 @@ public interface ICommandRuntime /// execute an instance of a Cmdlet. ICommandRuntime2 extends the ICommandRuntime interface /// by adding support for the informational data stream. /// -#nullable enable public interface ICommandRuntime2 : ICommandRuntime { /// @@ -590,11 +592,11 @@ public interface ICommandRuntime2 : ICommandRuntime /// the default option selected in the selection menu is 'No'. /// /// - /// true iff user selects YesToAll. If this is already true, + /// true if-and-only-if user selects YesToAll. If this is already true, /// ShouldContinue will bypass the prompt and return true. /// /// - /// true iff user selects NoToAll. If this is already true, + /// true if-and-only-if user selects NoToAll. If this is already true, /// ShouldContinue will bypass the prompt and return false. /// /// diff --git a/src/System.Management.Automation/engine/InformationRecord.cs b/src/System.Management.Automation/engine/InformationRecord.cs index 310c34a8809..87a3d9cda9d 100644 --- a/src/System.Management.Automation/engine/InformationRecord.cs +++ b/src/System.Management.Automation/engine/InformationRecord.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation /// which, according to host or user preference, forwards that information on to the host for rendering to the user. /// /// - [DataContract()] + [DataContract] public class InformationRecord { /// @@ -96,15 +96,13 @@ public string User { get { - if (this._user == null) - { - // domain\user on Windows, just user on Unix + // domain\user on Windows, just user on Unix + this._user ??= #if UNIX - this._user = Environment.UserName; + Environment.UserName; #else - this._user = Environment.UserDomainName + "\\" + Environment.UserName; + Environment.UserDomainName + "\\" + Environment.UserName; #endif - } return _user; } diff --git a/src/System.Management.Automation/engine/InitialSessionState.cs b/src/System.Management.Automation/engine/InitialSessionState.cs index 257cb79ce7b..a6d50f47443 100644 --- a/src/System.Management.Automation/engine/InitialSessionState.cs +++ b/src/System.Management.Automation/engine/InitialSessionState.cs @@ -44,22 +44,28 @@ internal static void Init() // We shouldn't create too many tasks. #if !UNIX - // Amsi initialize can be a little slow + // Amsi initialize can be a little slow. Task.Run(() => AmsiUtils.WinScanContent(content: string.Empty, sourceMetadata: string.Empty, warmUp: true)); #endif + // Initialize the types 'Compiler', 'CachedReflectionInfo', and 'ExpressionCache'. + // Their type initializers do a lot of reflection operations. + // We will access 'Compiler' members when creating the first session state. + Task.Run(() => _ = Compiler.DottedLocalsTupleType); // One other task for other stuff that's faster, but still a little slow. Task.Run(() => { - // Loading the resources for System.Management.Automation can be expensive, so force that to - // happen early on a background thread. + // Loading the resources for System.Management.Automation can be expensive, + // so force that to happen early on a background thread. _ = RunspaceInit.OutputEncodingDescription; // This will init some tables and could load some assemblies. - _ = TypeAccelerators.builtinTypeAccelerators; + // We will access 'LanguagePrimitives' when binding built-in variables for the Runspace. + LanguagePrimitives.GetEnumerator(null); // This will init some tables and could load some assemblies. - LanguagePrimitives.GetEnumerator(null); + // We will access 'TypeAccelerators' when auto-loading the PSReadLine module, which happens last. + _ = TypeAccelerators.builtinTypeAccelerators; }); } } @@ -410,7 +416,7 @@ public SessionStateAssemblyEntry(string name) /// The cloned object. public override InitialSessionStateEntry Clone() { - SessionStateAssemblyEntry entry = new SessionStateAssemblyEntry(Name, FileName); + var entry = new SessionStateAssemblyEntry(Name, FileName); entry.SetPSSnapIn(this.PSSnapIn); entry.SetModule(this.Module); return entry; @@ -646,7 +652,7 @@ public override InitialSessionStateEntry Clone() public string Description { get; } = string.Empty; /// - /// Options controling scope visibility and setability for this entry. + /// Options controlling scope visibility and setability for this entry. /// public ScopedItemOptions Options { get; } = ScopedItemOptions.None; } @@ -803,7 +809,7 @@ internal void SetHelpFile(string help) internal ScriptBlock ScriptBlock { get; set; } /// - /// Options controling scope visibility and setability for this entry. + /// Options controlling scope visibility and setability for this entry. /// public ScopedItemOptions Options { get; } = ScopedItemOptions.None; @@ -974,10 +980,7 @@ public InitialSessionStateEntryCollection() /// public InitialSessionStateEntryCollection(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); _internalCollection = new Collection(); @@ -1148,10 +1151,7 @@ public void Clear() /// The type of object to remove, can be null to remove any type. public void Remove(string name, object type) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); lock (_syncObject) { @@ -1186,10 +1186,7 @@ public void Remove(string name, object type) /// The item to add... public void Add(T item) { - if (item == null) - { - throw new ArgumentNullException(nameof(item)); - } + ArgumentNullException.ThrowIfNull(item); lock (_syncObject) { @@ -1203,10 +1200,7 @@ public void Add(T item) /// public void Add(IEnumerable items) { - if (items == null) - { - throw new ArgumentNullException(nameof(items)); - } + ArgumentNullException.ThrowIfNull(items); lock (_syncObject) { @@ -1312,7 +1306,7 @@ private static void MakeDisallowedEntriesPrivate(InitialSessionStateEntryColl /// Creates an initial session state from a PSSC configuration file. /// /// The path to the PSSC session configuration file. - /// + /// InitialSessionState object. public static InitialSessionState CreateFromSessionConfigurationFile(string path) { return CreateFromSessionConfigurationFile(path, null); @@ -1327,10 +1321,48 @@ public static InitialSessionState CreateFromSessionConfigurationFile(string path /// target session. If you have a WindowsPrincipal for a user, for example, create a Function that /// checks windowsPrincipal.IsInRole(). /// - /// - public static InitialSessionState CreateFromSessionConfigurationFile(string path, Func roleVerifier) + /// InitialSessionState object. + public static InitialSessionState CreateFromSessionConfigurationFile( + string path, + Func roleVerifier) + { + return CreateFromSessionConfigurationFile(path, roleVerifier, validateFile: false); + } + + /// + /// Creates an initial session state from a PSSC configuration file. + /// + /// The path to the PSSC session configuration file. + /// + /// The verifier that PowerShell should call to determine if groups in the Role entry apply to the + /// target session. If you have a WindowsPrincipal for a user, for example, create a Function that + /// checks windowsPrincipal.IsInRole(). + /// + /// Validates the file contents for supported SessionState options. + /// InitialSessionState object. + public static InitialSessionState CreateFromSessionConfigurationFile( + string path, + Func roleVerifier, + bool validateFile) { - Remoting.DISCPowerShellConfiguration discConfiguration = new Remoting.DISCPowerShellConfiguration(path, roleVerifier); + if (path is null) + { + throw new PSArgumentNullException(nameof(path)); + } + + if (!File.Exists(path)) + { + throw new PSInvalidOperationException( + StringUtil.Format(ConsoleInfoErrorStrings.ConfigurationFileDoesNotExist, path)); + } + + if (!path.EndsWith(".pssc", StringComparison.OrdinalIgnoreCase)) + { + throw new PSInvalidOperationException( + StringUtil.Format(ConsoleInfoErrorStrings.NotConfigurationFile, path)); + } + + Remoting.DISCPowerShellConfiguration discConfiguration = new Remoting.DISCPowerShellConfiguration(path, roleVerifier, validateFile); return discConfiguration.GetInitialSessionState(null); } @@ -1434,9 +1466,6 @@ private static InitialSessionState CreateRestrictedForRemoteServer() return iss; } - // Porting note: moved to Platform so we have one list to maintain - private static readonly string[] s_PSCoreFormatFileNames = Platform.FormatFileNames.ToArray(); - private static void IncludePowerShellCoreFormats(InitialSessionState iss) { string psHome = Utils.DefaultPowerShellAppBase; @@ -1446,7 +1475,7 @@ private static void IncludePowerShellCoreFormats(InitialSessionState iss) } iss.Formats.Clear(); - foreach (var coreFormat in s_PSCoreFormatFileNames) + foreach (var coreFormat in Platform.FormatFileNames) { iss.Formats.Add(new SessionStateFormatEntry(Path.Combine(psHome, coreFormat))); } @@ -1477,7 +1506,7 @@ public static InitialSessionState Create() // be causing test failures - i suspect due to lack test isolation - brucepay Mar 06/2008 #if false // Add the default variables and make them private... - iss.Variables.Add(BuiltInVariables); + iss.AddVariables(BuiltInVariables); foreach (SessionStateVariableEntry v in iss.Variables) { v.Visibility = SessionStateEntryVisibility.Private; @@ -1540,14 +1569,10 @@ public static InitialSessionState CreateDefault() string assembly = ss.Assemblies[i].FileName; if (!string.IsNullOrEmpty(assembly)) { - if (assemblyList.Contains(assembly)) + if (!assemblyList.Add(assembly)) { ss.Assemblies.RemoveItem(i); } - else - { - assemblyList.Add(assembly); - } } } @@ -1666,11 +1691,6 @@ public InitialSessionState Clone() ss.DisableFormatUpdates = this.DisableFormatUpdates; - foreach (var s in this.defaultSnapins) - { - ss.defaultSnapins.Add(s); - } - foreach (var s in ImportedSnapins) { ss.ImportedSnapins.Add(s.Key, s.Value); @@ -1834,10 +1854,7 @@ public Microsoft.PowerShell.ExecutionPolicy ExecutionPolicy /// public void ImportPSModule(params string[] name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); foreach (string n in name) { @@ -1862,10 +1879,7 @@ internal void ClearPSModules() /// public void ImportPSModule(IEnumerable modules) { - if (modules == null) - { - throw new ArgumentNullException(nameof(modules)); - } + ArgumentNullException.ThrowIfNull(modules); foreach (var moduleSpecification in modules) { @@ -1893,10 +1907,7 @@ public void ImportPSModulesFromPath(string path) /// internal void ImportPSCoreModule(string[] name) { - if (name == null) - { - throw new ArgumentNullException(nameof(name)); - } + ArgumentNullException.ThrowIfNull(name); foreach (string n in name) { @@ -2113,7 +2124,7 @@ public virtual HashSet StartupScripts } } - private HashSet _startupScripts = new HashSet(); + private HashSet _startupScripts; private readonly object _syncObject = new object(); @@ -2413,9 +2424,14 @@ private void Bind_LoadAssemblies(ExecutionContext context) // Load the assemblies and initialize the assembly cache... foreach (SessionStateAssemblyEntry ssae in Assemblies) { - if (etwEnabled) RunspaceEventSource.Log.LoadAssemblyStart(ssae.Name, ssae.FileName); - Exception error = null; - Assembly asm = context.AddAssembly(ssae.Name, ssae.FileName, out error); + if (etwEnabled) + { + RunspaceEventSource.Log.LoadAssemblyStart(ssae.Name, ssae.FileName); + } + + // Specify the source only if this is for module loading. + // The source is used for proper cleaning of the assembly cache when a module is unloaded. + Assembly asm = context.AddAssembly(ssae.Module?.Name, ssae.Name, ssae.FileName, out Exception error); if (asm == null || error != null) { @@ -2740,7 +2756,7 @@ private static void ProcessCommandModification(Hashtable commandModification, Co break; case "ValidatePattern": - string pattern = "^(" + string.Join("|", parameterValidationValues) + ")$"; + string pattern = "^(" + string.Join('|', parameterValidationValues) + ")$"; ValidatePatternAttribute validatePattern = new ValidatePatternAttribute(pattern); metadata.Parameters[parameterName].Attributes.Add(validatePattern); break; @@ -2844,7 +2860,7 @@ private string MakeUserNamePath() // Ensure that user name contains no invalid path characters. // MSDN indicates that logon names cannot contain any of these invalid characters, // but this check will ensure safety. - if (userName.IndexOfAny(System.IO.Path.GetInvalidPathChars()) > -1) + if (PathUtils.ContainsInvalidPathChars(userName)) { throw new PSInvalidOperationException(RemotingErrorIdStrings.InvalidUserDriveName); } @@ -2901,7 +2917,7 @@ private Exception ProcessPowerShellCommand(PowerShell psToInvoke, Runspace initi } finally { - // Restore the langauge mode, but not if it was altered by the startup script itself. + // Restore the language mode, but not if it was altered by the startup script itself. if (initializedRunspace.SessionStateProxy.LanguageMode == PSLanguageMode.FullLanguage) { initializedRunspace.SessionStateProxy.LanguageMode = originalLanguageMode; @@ -2946,13 +2962,20 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( HashSet unresolvedCmdsToExpose) { RunspaceOpenModuleLoadException exceptionToReturn = null; + List processedModules = new List(); foreach (object module in moduleList) { string moduleName = module as string; if (moduleName != null) { - exceptionToReturn = ProcessOneModule(initializedRunspace, moduleName, null, path, publicCommands); + exceptionToReturn = ProcessOneModule( + initializedRunspace: initializedRunspace, + name: moduleName, + moduleInfoToLoad: null, + path: path, + publicCommands: publicCommands, + processedModules: processedModules); } else { @@ -2963,7 +2986,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( { // if only name is specified in the module spec, just try import the module // ie., don't take the performance overhead of calling GetModule. - exceptionToReturn = ProcessOneModule(initializedRunspace, moduleSpecification.Name, null, path, publicCommands); + exceptionToReturn = ProcessOneModule( + initializedRunspace: initializedRunspace, + name: moduleSpecification.Name, + moduleInfoToLoad: null, + path: path, + publicCommands: publicCommands, + processedModules: processedModules); } else { @@ -2971,7 +3000,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( if (moduleInfos != null && moduleInfos.Count > 0) { - exceptionToReturn = ProcessOneModule(initializedRunspace, moduleSpecification.Name, moduleInfos[0], path, publicCommands); + exceptionToReturn = ProcessOneModule( + initializedRunspace: initializedRunspace, + name: moduleSpecification.Name, + moduleInfoToLoad: moduleInfos[0], + path: path, + publicCommands: publicCommands, + processedModules: processedModules); } else { @@ -3020,7 +3055,11 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( string commandToMakeVisible = Utils.ParseCommandName(unresolvedCommand, out moduleName); bool found = false; - foreach (CommandInfo cmd in LookupCommands(commandToMakeVisible, moduleName, initializedRunspace.ExecutionContext)) + foreach (CommandInfo cmd in LookupCommands( + commandPattern: commandToMakeVisible, + moduleName: moduleName, + context: initializedRunspace.ExecutionContext, + processedModules: processedModules)) { if (!found) { @@ -3071,11 +3110,13 @@ private RunspaceOpenModuleLoadException ProcessModulesToImport( /// /// /// + /// /// private static IEnumerable LookupCommands( string commandPattern, string moduleName, - ExecutionContext context) + ExecutionContext context, + List processedModules) { bool isWildCardPattern = WildcardPattern.ContainsWildcardCharacters(commandPattern); var searchOptions = isWildCardPattern ? @@ -3089,7 +3130,11 @@ private static IEnumerable LookupCommands( CommandOrigin cmdOrigin = CommandOrigin.Runspace; while (true) { - foreach (CommandInfo commandInfo in context.SessionState.InvokeCommand.GetCommands(commandPattern, CommandTypes.All, searchOptions, cmdOrigin)) + foreach (CommandInfo commandInfo in context.SessionState.InvokeCommand.GetCommands( + name: commandPattern, + commandTypes: CommandTypes.All, + options: searchOptions, + commandOrigin: cmdOrigin)) { // If module name is provided then use it to restrict returned results. if (haveModuleName && !moduleName.Equals(commandInfo.ModuleName, StringComparison.OrdinalIgnoreCase)) @@ -3119,13 +3164,43 @@ private static IEnumerable LookupCommands( // Next try internal search. cmdOrigin = CommandOrigin.Internal; } + + // If the command is associated with a module, try finding the command in the imported module list. + // The SessionState function table holds only one command name, and if two or more modules contain + // a command with the same name, only one of them will appear in the function table search above. + if (!found && haveModuleName) + { + var pattern = new WildcardPattern(commandPattern); + + foreach (PSModuleInfo moduleInfo in processedModules) + { + if (moduleInfo.Name.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) + { + foreach (var cmd in moduleInfo.ExportedCommands.Values) + { + if (pattern.IsMatch(cmd.Name)) + { + yield return cmd; + } + } + + break; + } + } + } } /// /// If is null, import module using . Otherwise, /// import module using /// - private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRunspace, string name, PSModuleInfo moduleInfoToLoad, string path, HashSet publicCommands) + private RunspaceOpenModuleLoadException ProcessOneModule( + Runspace initializedRunspace, + string name, + PSModuleInfo moduleInfoToLoad, + string path, + HashSet publicCommands, + List processedModules) { using (PowerShell pse = PowerShell.Create()) { @@ -3162,6 +3237,11 @@ private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRun c = new CmdletInfo("Out-Default", typeof(OutDefaultCommand), null, null, initializedRunspace.ExecutionContext); pse.AddCommand(new Command(c)); } + else + { + // For runspace init module processing, pass back the PSModuleInfo to the output pipeline. + cmd.Parameters.Add("PassThru"); + } pse.Runspace = initializedRunspace; // Module import should be run in FullLanguage mode since it is running in @@ -3170,7 +3250,10 @@ private RunspaceOpenModuleLoadException ProcessOneModule(Runspace initializedRun pse.Runspace.ExecutionContext.LanguageMode = PSLanguageMode.FullLanguage; try { - pse.Invoke(); + // For runspace init module processing, collect the imported PSModuleInfo returned in the output pipeline. + // In other cases, this collection will be empty. + Collection moduleInfos = pse.Invoke(); + processedModules.AddRange(moduleInfos); } finally { @@ -3365,8 +3448,7 @@ internal static void SetSessionStateDrive(ExecutionContext context, bool setLoca { // If we can't access the Environment.CurrentDirectory, we may be in an AppContainer. Set the // default drive to $pshome - System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess(); - string defaultPath = System.IO.Path.GetDirectoryName(PsUtils.GetMainModule(currentProcess).FileName); + string defaultPath = System.IO.Path.GetDirectoryName(Environment.ProcessPath); context.EngineSessionState.SetLocation(defaultPath, providerContext); } } @@ -3383,105 +3465,6 @@ internal static void CreateQuestionVariable(ExecutionContext context) context.EngineSessionState.SetVariableAtScope(qv, "global", true, CommandOrigin.Internal); } - /// - /// Remove anything that would have been bound by this ISS instance. - /// At this point, it removes assemblies and cmdlet entries at the top level. - /// It also removes types and formats. - /// The other entry types - functions, variables, aliases - /// are not removed by this function. - /// - /// - internal void Unbind(ExecutionContext context) - { - lock (_syncObject) - { - SessionStateInternal ss = context.EngineSessionState; - - // Remove the assemblies from the assembly cache... - foreach (SessionStateAssemblyEntry ssae in Assemblies) - { - context.RemoveAssembly(ssae.Name); - } - - // Remove all of the commands from the top-level session state. - foreach (SessionStateCommandEntry cmd in Commands) - { - SessionStateCmdletEntry ssce = cmd as SessionStateCmdletEntry; - if (ssce != null) - { - List matches; - if (context.TopLevelSessionState.GetCmdletTable().TryGetValue(ssce.Name, out matches)) - { - // Remove the name from the list... - for (int i = matches.Count - 1; i >= 0; i--) - { - if (matches[i].ModuleName.Equals(cmd.PSSnapIn.Name)) - { - string name = matches[i].Name; - matches.RemoveAt(i); - context.TopLevelSessionState.RemoveCmdlet(name, i, /*force*/ true); - } - } - // And remove the entry if the list is now empty... - if (matches.Count == 0) - { - context.TopLevelSessionState.RemoveCmdletEntry(ssce.Name, true); - } - } - - continue; - } - } - - // Remove all of the providers from the top-level provider table. - if (_providers != null && _providers.Count > 0) - { - Dictionary> providerTable = context.TopLevelSessionState.Providers; - - foreach (SessionStateProviderEntry sspe in _providers) - { - List pl; - if (providerTable.TryGetValue(sspe.Name, out pl)) - { - Diagnostics.Assert(pl != null, "There should never be a null list of entries in the provider table"); - // For each provider with the same name... - for (int i = pl.Count - 1; i >= 0; i--) - { - ProviderInfo pi = pl[i]; - - // If it was implemented by this entry, remove it - if (pi.ImplementingType == sspe.ImplementingType) - { - RemoveAllDrivesForProvider(pi, context.TopLevelSessionState); - pl.RemoveAt(i); - } - } - - // If there are no providers left with this name, remove the key. - if (pl.Count == 0) - { - providerTable.Remove(sspe.Name); - } - } - } - } - - List formatFilesToRemove = new List(); - if (this.Formats != null) - { - formatFilesToRemove.AddRange(this.Formats.Select(f => f.FileName)); - } - - List typeFilesToRemove = new List(); - if (this.Types != null) - { - typeFilesToRemove.AddRange(this.Types.Select(t => t.FileName)); - } - - RemoveTypesAndFormats(context, formatFilesToRemove, typeFilesToRemove); - } - } - internal static void RemoveTypesAndFormats(ExecutionContext context, IList formatFilesToRemove, IList typeFilesToRemove) { // The formats and types tables are implemented in such a way that @@ -3600,8 +3583,7 @@ internal void UpdateTypes(ExecutionContext context, bool updateOnly) moduleName = sste.PSSnapIn.Name; } - bool unused; - context.TypeTable.Update(moduleName, sste.FileName, errors, context.AuthorizationManager, context.EngineHostInterface, out unused); + context.TypeTable.Update(moduleName, sste.FileName, errors, context.AuthorizationManager, context.EngineHostInterface, out _); } } else if (sste.TypeTable != null) @@ -3792,7 +3774,7 @@ public PSSnapInInfo ImportPSSnapIn(string name, out PSSnapInException warning) // implementation and should be refactored. PSSnapInInfo newPSSnapIn = PSSnapInReader.Read("2", name); - if (!Utils.IsPSVersionSupported(newPSSnapIn.PSVersion.ToString())) + if (!PSVersionInfo.IsValidPSVersion(newPSSnapIn.PSVersion)) { s_PSSnapInTracer.TraceError("MshSnapin {0} and current monad engine's versions don't match.", name); @@ -3805,34 +3787,22 @@ public PSSnapInInfo ImportPSSnapIn(string name, out PSSnapInException warning) // Now actually load the snapin... PSSnapInInfo snapin = ImportPSSnapIn(newPSSnapIn, out warning); - if (snapin != null) - { - ImportedSnapins.Add(snapin.Name, snapin); - } return snapin; } internal PSSnapInInfo ImportCorePSSnapIn() { - // Load Microsoft.PowerShell.Core as a snapin + // Load Microsoft.PowerShell.Core as a snapin. PSSnapInInfo coreSnapin = PSSnapInReader.ReadCoreEngineSnapIn(); - this.defaultSnapins.Add(coreSnapin); - try - { - PSSnapInException warning; - this.ImportPSSnapIn(coreSnapin, out warning); - } - catch (PSSnapInException) - { - throw; - } - + ImportPSSnapIn(coreSnapin, out _); return coreSnapin; } internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInException warning) { + ArgumentNullException.ThrowIfNull(psSnapInInfo); + // See if the snapin is already loaded. If has been then there will be an entry in the // Assemblies list for it already... bool reload = true; @@ -3865,12 +3835,6 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce Dictionary> aliases = null; Dictionary providers = null; - if (psSnapInInfo == null) - { - ArgumentNullException e = new ArgumentNullException(nameof(psSnapInInfo)); - throw e; - } - Assembly assembly = null; string helpFile = null; @@ -3927,18 +3891,9 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce this.Formats.Add(formatEntry); } - SessionStateAssemblyEntry assemblyEntry = new SessionStateAssemblyEntry(psSnapInInfo.AssemblyName, psSnapInInfo.AbsoluteModulePath); - + var assemblyEntry = new SessionStateAssemblyEntry(psSnapInInfo.AssemblyName, psSnapInInfo.AbsoluteModulePath); assemblyEntry.SetPSSnapIn(psSnapInInfo); - - this.Assemblies.Add(assemblyEntry); - - // entry from types.ps1xml references a type (Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase) in this assembly - if (psSnapInInfo.Name.Equals(CoreSnapin, StringComparison.OrdinalIgnoreCase)) - { - assemblyEntry = new SessionStateAssemblyEntry("Microsoft.PowerShell.Security", null); - this.Assemblies.Add(assemblyEntry); - } + Assemblies.Add(assemblyEntry); if (cmdlets != null) { @@ -3989,37 +3944,18 @@ internal PSSnapInInfo ImportPSSnapIn(PSSnapInInfo psSnapInInfo, out PSSnapInExce } } + ImportedSnapins.Add(psSnapInInfo.Name, psSnapInInfo); return psSnapInInfo; } - internal List GetPSSnapIn(string psSnapinName) + internal PSSnapInInfo GetPSSnapIn(string psSnapinName) { - List loadedSnapins = null; - foreach (var defaultSnapin in defaultSnapins) - { - if (defaultSnapin.Name.Equals(psSnapinName, StringComparison.OrdinalIgnoreCase)) - { - if (loadedSnapins == null) - { - loadedSnapins = new List(); - } - - loadedSnapins.Add(defaultSnapin); - } - } - - PSSnapInInfo importedSnapin = null; - if (ImportedSnapins.TryGetValue(psSnapinName, out importedSnapin)) + if (ImportedSnapins.TryGetValue(psSnapinName, out PSSnapInInfo importedSnapin)) { - if (loadedSnapins == null) - { - loadedSnapins = new List(); - } - - loadedSnapins.Add(importedSnapin); + return importedSnapin; } - return loadedSnapins; + return null; } [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] @@ -4041,26 +3977,18 @@ internal static Assembly LoadAssemblyFromFile(string fileName) internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) { - if (assembly == null) - { - ArgumentNullException e = new ArgumentNullException(nameof(assembly)); - throw e; - } - - Dictionary cmdlets = null; - Dictionary> aliases = null; - Dictionary providers = null; + ArgumentNullException.ThrowIfNull(assembly); string assemblyPath = assembly.Location; - PSSnapInHelpers.AnalyzePSSnapInAssembly(assembly, assemblyPath, psSnapInInfo: null, module, out cmdlets, out aliases, out providers, helpFile: out _); - - // If this is an in-memory assembly, don't added it to the list of AssemblyEntries - // since it can't be loaded by path or name - if (!string.IsNullOrEmpty(assembly.Location)) - { - SessionStateAssemblyEntry assemblyEntry = new SessionStateAssemblyEntry(assembly.FullName, assemblyPath); - this.Assemblies.Add(assemblyEntry); - } + PSSnapInHelpers.AnalyzePSSnapInAssembly( + assembly, + assemblyPath, + psSnapInInfo: null, + module, + out Dictionary cmdlets, + out Dictionary> aliases, + out Dictionary providers, + helpFile: out _); if (cmdlets != null) { @@ -4109,8 +4037,10 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) #> [CmdletBinding(DefaultParameterSetName = 'ScriptInputSet')] +[OutputType([System.Management.Automation.CommandCompletion])] Param( [Parameter(ParameterSetName = 'ScriptInputSet', Mandatory = $true, Position = 0)] + [AllowEmptyString()] [string] $inputScript, [Parameter(ParameterSetName = 'ScriptInputSet', Position = 1)] @@ -4148,7 +4078,7 @@ internal void ImportCmdletsFromAssembly(Assembly assembly, PSModuleInfo module) <#options#> $options) } } - "; +"; /// /// This is the default function to use for clear-host. @@ -4183,16 +4113,16 @@ internal static string GetClearHostFunctionText() } } - /// - /// This is the default function to use for man/help. It uses - /// splatting to pass in the parameters. - /// - internal static string GetHelpPagingFunctionText() +#if UNIX + internal static string GetExecFunctionText() { - // We used to generate the text for this function so you could add a parameter - // to Get-Help and not worry about adding it here. That was a little slow at - // startup, so it's hard coded, with a test to make sure the parameters match. return @" +Switch-Process -WithCommand $args +"; + } +#endif + + internal const string WindowsHelpFunctionText = @" <# .FORWARDHELPTARGETNAME Get-Help .FORWARDHELPCATEGORY Cmdlet @@ -4266,14 +4196,132 @@ .FORWARDHELPCATEGORY Cmdlet elseif ($help -ne $null) { # By default use more on Windows and less on Linux. - if ($IsWindows) { - $pagerCommand = 'more.com' - $pagerArgs = $null + $pagerCommand = 'more.com' + $pagerArgs = $null + + # Respect PAGER environment variable which allows user to specify a custom pager. + # Ignore a pure whitespace PAGER value as that would cause the tokenizer to return 0 tokens. + if (![string]::IsNullOrWhitespace($env:PAGER)) { + if (Get-Command $env:PAGER -ErrorAction Ignore) { + # Entire PAGER value corresponds to a single command. + $pagerCommand = $env:PAGER + $pagerArgs = $null + } + else { + # PAGER value is not a valid command, check if PAGER command and arguments have been specified. + # Tokenize the specified $env:PAGER value. Ignore tokenizing errors since any errors may be valid + # argument syntax for the paging utility. + $errs = $null + $tokens = [System.Management.Automation.PSParser]::Tokenize($env:PAGER, [ref]$errs) + + $customPagerCommand = $tokens[0].Content + if (!(Get-Command $customPagerCommand -ErrorAction Ignore)) { + # Custom pager command is invalid, issue a warning. + Write-Warning ""Custom-paging utility command not found. Ignoring command specified in `$env:PAGER: $env:PAGER"" + } + else { + # This approach will preserve all the pagers args. + $pagerCommand = $customPagerCommand + $pagerArgs = if ($tokens.Count -gt 1) { + $env:PAGER.Substring($tokens[1].Start) + } + else { + $null + } + } + } + } + + $pagerCommandInfo = Get-Command -Name $pagerCommand -ErrorAction Ignore + if ($pagerCommandInfo -eq $null) { + $help + } + elseif ($pagerCommandInfo.CommandType -eq 'Application') { + # If the pager is an application, format the output width before sending to the app. + $consoleWidth = [System.Math]::Max([System.Console]::WindowWidth, 20) + + if ($pagerArgs) { + $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand $pagerArgs + } + else { + $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand + } } else { - $pagerCommand = 'less' - $pagerArgs = '-Ps""Page %db?B of %D:.\. Press h for help or q to quit\.$""' + # The pager command is a PowerShell function, script or alias, so pipe directly into it. + $help | & $pagerCommand $pagerArgs } + } +"; + + internal const string UnixHelpFunctionText = @" +<# +.FORWARDHELPTARGETNAME Get-Help +.FORWARDHELPCATEGORY Cmdlet +#> +[CmdletBinding(DefaultParameterSetName='AllUsersView', HelpUri='https://go.microsoft.com/fwlink/?LinkID=113316')] +param( + [Parameter(Position=0, ValueFromPipelineByPropertyName=$true)] + [string] + ${Name}, + + [string] + ${Path}, + + [ValidateSet('Alias','Cmdlet','Provider','General','FAQ','Glossary','HelpFile','ScriptCommand','Function','Filter','ExternalScript','All','DefaultHelp','DscResource','Class','Configuration')] + [string[]] + ${Category}, + + [Parameter(ParameterSetName='DetailedView', Mandatory=$true)] + [switch] + ${Detailed}, + + [Parameter(ParameterSetName='AllUsersView')] + [switch] + ${Full}, + + [Parameter(ParameterSetName='Examples', Mandatory=$true)] + [switch] + ${Examples}, + + [Parameter(ParameterSetName='Parameters', Mandatory=$true)] + [string[]] + ${Parameter}, + + [string[]] + ${Component}, + + [string[]] + ${Functionality}, + + [string[]] + ${Role}, + + [Parameter(ParameterSetName='Online', Mandatory=$true)] + [switch] + ${Online}) + + # Display the full help topic by default but only for the AllUsersView parameter set. + if (($psCmdlet.ParameterSetName -eq 'AllUsersView') -and !$Full) { + $PSBoundParameters['Full'] = $true + } + + # Linux need the default + $OutputEncoding = [System.Console]::OutputEncoding + + $help = Get-Help @PSBoundParameters + + # If a list of help is returned or AliasHelpInfo (because it is small), don't pipe to more + $psTypeNames = ($help | Select-Object -First 1).PSTypeNames + if ($psTypeNames -Contains 'HelpInfoShort' -Or $psTypeNames -Contains 'AliasHelpInfo') + { + $help + } + elseif ($help -ne $null) + { + # By default use more on Windows and less on Linux. + $pagerCommand = 'less' + $pagerArgs = '-s','-P','Page %db?B of %D:.\. Press h for help or q to quit\.' # Respect PAGER environment variable which allows user to specify a custom pager. # Ignore a pure whitespace PAGER value as that would cause the tokenizer to return 0 tokens. @@ -4312,10 +4360,7 @@ .FORWARDHELPCATEGORY Cmdlet $consoleWidth = [System.Math]::Max([System.Console]::WindowWidth, 20) if ($pagerArgs) { - # Supply pager arguments to an application without any PowerShell parsing of the arguments. - # Leave environment variable to help user debug arguments supplied in $env:PAGER. - $env:__PSPAGER_ARGS = $pagerArgs - $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand --% %__PSPAGER_ARGS% + $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand $pagerArgs } else { $help | Out-String -Stream -Width ($consoleWidth - 1) | & $pagerCommand @@ -4327,8 +4372,31 @@ .FORWARDHELPCATEGORY Cmdlet } } "; + + /// + /// This is the default function to use for man/help. It uses + /// splatting to pass in the parameters. + /// +#if !UNIX + internal static string GetHelpPagingFunctionText() + { + // We used to generate the text for this function so you could add a parameter + // to Get-Help and not worry about adding it here. That was a little slow at + // startup, so it's hard coded, with a test to make sure the parameters match. + return WindowsHelpFunctionText; } +#else + internal static string GetHelpPagingFunctionText() + { + // We used to generate the text for this function so you could add a parameter + // to Get-Help and not worry about adding it here. That was a little slow at + // startup, so it's hard coded, with a test to make sure the parameters match. + // This version removes the -ShowWindow parameter since it is not supported on Linux. + return UnixHelpFunctionText; + } +#endif + internal static string GetMkdirFunctionText() { return @" @@ -4432,154 +4500,199 @@ .ForwardHelpCategory Cmdlet internal const bool DefaultWhatIfPreference = false; internal const ConfirmImpact DefaultConfirmPreference = ConfirmImpact.High; - internal static readonly SessionStateVariableEntry[] BuiltInVariables = new SessionStateVariableEntry[] - { - // Engine variables that should be precreated before running profile - // Bug fix for Win7:2202228 Engine halts if initial command fulls up variable table - // Anytime a new variable that the engine depends on to run is added, this table - // must be updated... - new SessionStateVariableEntry(SpecialVariables.LastToken, null, string.Empty), - new SessionStateVariableEntry(SpecialVariables.FirstToken, null, string.Empty), - new SessionStateVariableEntry(SpecialVariables.StackTrace, null, string.Empty), - - // Variable which controls the output rendering - new SessionStateVariableEntry( - SpecialVariables.PSStyle, - PSStyle.Instance, - RunspaceInit.PSStyleDescription, - ScopedItemOptions.None), - - // Variable which controls the encoding for piping data to a NativeCommand - new SessionStateVariableEntry( - SpecialVariables.OutputEncoding, - Utils.utf8NoBom, - RunspaceInit.OutputEncodingDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(System.Text.Encoding))), - - // Preferences - // - // NTRAID#Windows Out Of Band Releases-931461-2006/03/13 - // ArgumentTypeConverterAttribute is applied to these variables, - // but this only reaches the global variable. If these are - // redefined in script scope etc, the type conversion - // is not applicable. - // - // Variables typed to ActionPreference - new SessionStateVariableEntry( - SpecialVariables.ConfirmPreference, - DefaultConfirmPreference, - RunspaceInit.ConfirmPreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ConfirmImpact))), - new SessionStateVariableEntry( - SpecialVariables.DebugPreference, - DefaultDebugPreference, - RunspaceInit.DebugPreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ActionPreference))), - new SessionStateVariableEntry( - SpecialVariables.ErrorActionPreference, - DefaultErrorActionPreference, - RunspaceInit.ErrorActionPreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ActionPreference))), - new SessionStateVariableEntry( - SpecialVariables.ProgressPreference, - DefaultProgressPreference, - RunspaceInit.ProgressPreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ActionPreference))), - new SessionStateVariableEntry( - SpecialVariables.VerbosePreference, - DefaultVerbosePreference, - RunspaceInit.VerbosePreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ActionPreference))), - new SessionStateVariableEntry( - SpecialVariables.WarningPreference, - DefaultWarningPreference, - RunspaceInit.WarningPreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ActionPreference))), - new SessionStateVariableEntry( - SpecialVariables.InformationPreference, - DefaultInformationPreference, - RunspaceInit.InformationPreferenceDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ActionPreference))), - new SessionStateVariableEntry( - SpecialVariables.ErrorView, - DefaultErrorView, - RunspaceInit.ErrorViewDescription, - ScopedItemOptions.None, - new ArgumentTypeConverterAttribute(typeof(ErrorView))), - new SessionStateVariableEntry( - SpecialVariables.NestedPromptLevel, - 0, - RunspaceInit.NestedPromptLevelDescription), - new SessionStateVariableEntry( - SpecialVariables.WhatIfPreference, - DefaultWhatIfPreference, - RunspaceInit.WhatIfPreferenceDescription), - new SessionStateVariableEntry( - FormatEnumerationLimit, - DefaultFormatEnumerationLimit, - RunspaceInit.FormatEnumerationLimitDescription), - - // variable for PSEmailServer - new SessionStateVariableEntry( - SpecialVariables.PSEmailServer, - string.Empty, - RunspaceInit.PSEmailServerDescription), - - // Start: Variables which control remoting behavior - new SessionStateVariableEntry( - Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION, - new System.Management.Automation.Remoting.PSSessionOption(), - RemotingErrorIdStrings.PSDefaultSessionOptionDescription, - ScopedItemOptions.None), - new SessionStateVariableEntry( - SpecialVariables.PSSessionConfigurationName, - "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", - RemotingErrorIdStrings.PSSessionConfigurationName, - ScopedItemOptions.None), - new SessionStateVariableEntry( - SpecialVariables.PSSessionApplicationName, - "wsman", - RemotingErrorIdStrings.PSSessionAppName, - ScopedItemOptions.None), - // End: Variables which control remoting behavior - - #region Platform - new SessionStateVariableEntry( - SpecialVariables.IsLinux, - Platform.IsLinux, - string.Empty, - ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), - - new SessionStateVariableEntry( - SpecialVariables.IsMacOS, - Platform.IsMacOS, - string.Empty, - ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), - - new SessionStateVariableEntry( - SpecialVariables.IsWindows, - Platform.IsWindows, - string.Empty, - ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), - - new SessionStateVariableEntry( - SpecialVariables.IsCoreCLR, - Platform.IsCoreCLR, - string.Empty, - ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), - #endregion - }; + static InitialSessionState() + { + var builtinVariables = new List() + { + // Engine variables that should be precreated before running profile + // Bug fix for Win7:2202228 Engine halts if initial command fulls up variable table + // Anytime a new variable that the engine depends on to run is added, this table + // must be updated... + new SessionStateVariableEntry(SpecialVariables.LastToken, null, string.Empty), + new SessionStateVariableEntry(SpecialVariables.FirstToken, null, string.Empty), + new SessionStateVariableEntry(SpecialVariables.StackTrace, null, string.Empty), + + // Variable which controls the output rendering + new SessionStateVariableEntry( + SpecialVariables.PSStyle, + PSStyle.Instance, + RunspaceInit.PSStyleDescription, + ScopedItemOptions.Constant), + + // Variable which controls the encoding for piping data to a NativeCommand + new SessionStateVariableEntry( + SpecialVariables.OutputEncoding, + Encoding.Default, + RunspaceInit.OutputEncodingDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(System.Text.Encoding))), + + // Variable which controls the encoding for decoding data from a NativeCommand + new SessionStateVariableEntry( + SpecialVariables.PSApplicationOutputEncoding, + null, + RunspaceInit.PSApplicationOutputEncodingDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(Encoding))), + + // Preferences + // + // NTRAID#Windows Out Of Band Releases-931461-2006/03/13 + // ArgumentTypeConverterAttribute is applied to these variables, + // but this only reaches the global variable. If these are + // redefined in script scope etc, the type conversion + // is not applicable. + // + // Variables typed to ActionPreference + new SessionStateVariableEntry( + SpecialVariables.ConfirmPreference, + DefaultConfirmPreference, + RunspaceInit.ConfirmPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ConfirmImpact))), + new SessionStateVariableEntry( + SpecialVariables.DebugPreference, + DefaultDebugPreference, + RunspaceInit.DebugPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ActionPreference))), + new SessionStateVariableEntry( + SpecialVariables.ErrorActionPreference, + DefaultErrorActionPreference, + RunspaceInit.ErrorActionPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ActionPreference))), + new SessionStateVariableEntry( + SpecialVariables.ProgressPreference, + DefaultProgressPreference, + RunspaceInit.ProgressPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ActionPreference))), + new SessionStateVariableEntry( + SpecialVariables.VerbosePreference, + DefaultVerbosePreference, + RunspaceInit.VerbosePreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ActionPreference))), + new SessionStateVariableEntry( + SpecialVariables.WarningPreference, + DefaultWarningPreference, + RunspaceInit.WarningPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ActionPreference))), + new SessionStateVariableEntry( + SpecialVariables.InformationPreference, + DefaultInformationPreference, + RunspaceInit.InformationPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ActionPreference))), + new SessionStateVariableEntry( + SpecialVariables.ErrorView, + DefaultErrorView, + RunspaceInit.ErrorViewDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(ErrorView))), + new SessionStateVariableEntry( + SpecialVariables.NestedPromptLevel, + 0, + RunspaceInit.NestedPromptLevelDescription), + new SessionStateVariableEntry( + SpecialVariables.WhatIfPreference, + DefaultWhatIfPreference, + RunspaceInit.WhatIfPreferenceDescription), + new SessionStateVariableEntry( + FormatEnumerationLimit, + DefaultFormatEnumerationLimit, + RunspaceInit.FormatEnumerationLimitDescription), + + // variable for PSEmailServer + new SessionStateVariableEntry( + SpecialVariables.PSEmailServer, + string.Empty, + RunspaceInit.PSEmailServerDescription), + + // Start: Variables which control remoting behavior + new SessionStateVariableEntry( + Microsoft.PowerShell.Commands.PSRemotingBaseCmdlet.DEFAULT_SESSION_OPTION, + new System.Management.Automation.Remoting.PSSessionOption(), + RemotingErrorIdStrings.PSDefaultSessionOptionDescription, + ScopedItemOptions.None), + new SessionStateVariableEntry( + SpecialVariables.PSSessionConfigurationName, + "http://schemas.microsoft.com/powershell/Microsoft.PowerShell", + RemotingErrorIdStrings.PSSessionConfigurationName, + ScopedItemOptions.None), + new SessionStateVariableEntry( + SpecialVariables.PSSessionApplicationName, + "wsman", + RemotingErrorIdStrings.PSSessionAppName, + ScopedItemOptions.None), + // End: Variables which control remoting behavior + + #region Platform + new SessionStateVariableEntry( + SpecialVariables.IsLinux, + Platform.IsLinux, + string.Empty, + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), + + new SessionStateVariableEntry( + SpecialVariables.IsMacOS, + Platform.IsMacOS, + string.Empty, + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), + + new SessionStateVariableEntry( + SpecialVariables.IsWindows, + Platform.IsWindows, + string.Empty, + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), + + new SessionStateVariableEntry( + SpecialVariables.IsCoreCLR, + Platform.IsCoreCLR, + string.Empty, + ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope), + #endregion + }; + + builtinVariables.Add( + new SessionStateVariableEntry( + SpecialVariables.PSNativeCommandUseErrorActionPreference, + value: false, + RunspaceInit.PSNativeCommandUseErrorActionPreferenceDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(bool)))); + + builtinVariables.Add( + new SessionStateVariableEntry( + SpecialVariables.NativeArgumentPassing, + GetPassingStyle(), + RunspaceInit.NativeCommandArgumentPassingDescription, + ScopedItemOptions.None, + new ArgumentTypeConverterAttribute(typeof(NativeArgumentPassingStyle)))); + + BuiltInVariables = builtinVariables.ToArray(); + } /// - /// Returns a new array of alias entries everytime it's called. This + /// Assigns the default behavior for native argument passing. + /// If the system is non-Windows, we will return Standard. + /// Otherwise, we will return Windows. + /// + private static NativeArgumentPassingStyle GetPassingStyle() + { +#if UNIX + return NativeArgumentPassingStyle.Standard; +#else + return NativeArgumentPassingStyle.Windows; +#endif + } + + internal static readonly SessionStateVariableEntry[] BuiltInVariables; + + /// + /// Returns a new array of alias entries every time it's called. This /// can't be static because the elements may be mutated in different session /// state objects so each session state must have a copy of the entry. /// @@ -4597,7 +4710,7 @@ internal static SessionStateAliasEntry[] BuiltInAliases const ScopedItemOptions ReadOnly_AllScope = ScopedItemOptions.ReadOnly | ScopedItemOptions.AllScope; const ScopedItemOptions ReadOnly = ScopedItemOptions.ReadOnly; - return new SessionStateAliasEntry[] { + var builtInAliases = new List { new SessionStateAliasEntry("foreach", "ForEach-Object", string.Empty, ReadOnly_AllScope), new SessionStateAliasEntry("%", "ForEach-Object", string.Empty, ReadOnly_AllScope), new SessionStateAliasEntry("where", "Where-Object", string.Empty, ReadOnly_AllScope), @@ -4628,7 +4741,7 @@ internal static SessionStateAliasEntry[] BuiltInAliases new SessionStateAliasEntry("gm", "Get-Member", string.Empty, ReadOnly), new SessionStateAliasEntry("gmo", "Get-Module", string.Empty, ReadOnly), new SessionStateAliasEntry("gp", "Get-ItemProperty", string.Empty, ReadOnly), - new SessionStateAliasEntry("gpv", "Get-ItemPropertyValue", string.Empty,ReadOnly), + new SessionStateAliasEntry("gpv", "Get-ItemPropertyValue", string.Empty, ReadOnly), new SessionStateAliasEntry("gps", "Get-Process", string.Empty, ReadOnly), new SessionStateAliasEntry("group", "Group-Object", string.Empty, ReadOnly), new SessionStateAliasEntry("gu", "Get-Unique", string.Empty, ReadOnly), @@ -4764,6 +4877,8 @@ internal static SessionStateAliasEntry[] BuiltInAliases // - do not use AllScope - this causes errors in profiles that set this somewhat commonly used alias. new SessionStateAliasEntry("sls", "Select-String"), }; + + return builtInAliases.ToArray(); } } @@ -4785,12 +4900,17 @@ internal static SessionStateAliasEntry[] BuiltInAliases // Functions that don't require full language mode SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd..", "Set-Location ..", isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd\\", "Set-Location \\", isProductCode: true, languageMode: systemLanguageMode), - // Win8: 320909. Retaining the original definition to ensure backward compatability. + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("cd~", "Set-Location ~", isProductCode: true, languageMode: systemLanguageMode), + // Win8: 320909. Retaining the original definition to ensure backward compatibility. SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Pause", - string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString),"'"), isProductCode: true, languageMode: systemLanguageMode), + string.Concat("$null = Read-Host '", CodeGeneration.EscapeSingleQuotedStringContent(RunspaceInit.PauseDefinitionString), "'"), isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("help", GetHelpPagingFunctionText(), isProductCode: true, languageMode: systemLanguageMode), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("prompt", DefaultPromptFunctionText, isProductCode: true, languageMode: systemLanguageMode), +#if UNIX + SessionStateFunctionEntry.GetDelayParsedFunctionEntry("exec", GetExecFunctionText(), isProductCode: true, languageMode: systemLanguageMode), +#endif + // Functions that require full language mode and are trusted SessionStateFunctionEntry.GetDelayParsedFunctionEntry("Clear-Host", GetClearHostFunctionText(), isProductCode: true, languageMode: PSLanguageMode.FullLanguage), SessionStateFunctionEntry.GetDelayParsedFunctionEntry("TabExpansion2", s_tabExpansionFunctionText, isProductCode: true, languageMode: PSLanguageMode.FullLanguage), @@ -4849,7 +4969,6 @@ internal static void RemoveAllDrivesForProvider(ProviderInfo pi, SessionStateInt internal static readonly string CoreSnapin = "Microsoft.PowerShell.Core"; internal static readonly string CoreModule = "Microsoft.PowerShell.Core"; - internal Collection defaultSnapins = new Collection(); // The list of engine modules to create warnings when you try to remove them internal static readonly HashSet EngineModules = new HashSet(StringComparer.OrdinalIgnoreCase) @@ -4998,10 +5117,8 @@ internal static void AnalyzePSSnapInAssembly( out string helpFile) { helpFile = null; - if (assembly == null) - { - throw new ArgumentNullException(nameof(assembly)); - } + + ArgumentNullException.ThrowIfNull(assembly); cmdlets = null; aliases = null; @@ -5262,7 +5379,11 @@ private static void AnalyzeModuleAssemblyWithReflection( // the users of the cmdlet, instead of the author, should have control of what options applied to an alias // ('ScopedItemOptions.ReadOnly' and/or 'ScopedItemOptions.AllScopes'). var aliasEntry = new SessionStateAliasEntry(alias, cmdletName, description: string.Empty, ScopedItemOptions.None); - if (psSnapInInfo != null) { aliasEntry.SetPSSnapIn(psSnapInInfo); } + + if (psSnapInInfo != null) + { + aliasEntry.SetPSSnapIn(psSnapInInfo); + } if (moduleInfo != null) { @@ -5333,7 +5454,6 @@ private static void InitializeCoreCmdletsAndProviders( { "Enable-PSSessionConfiguration", new SessionStateCmdletEntry("Enable-PSSessionConfiguration", typeof(EnablePSSessionConfigurationCommand), helpFile) }, { "Get-PSSessionCapability", new SessionStateCmdletEntry("Get-PSSessionCapability", typeof(GetPSSessionCapabilityCommand), helpFile) }, { "Get-PSSessionConfiguration", new SessionStateCmdletEntry("Get-PSSessionConfiguration", typeof(GetPSSessionConfigurationCommand), helpFile) }, - { "New-PSSessionConfigurationFile", new SessionStateCmdletEntry("New-PSSessionConfigurationFile", typeof(NewPSSessionConfigurationFileCommand), helpFile) }, { "Receive-PSSession", new SessionStateCmdletEntry("Receive-PSSession", typeof(ReceivePSSessionCommand), helpFile) }, { "Register-PSSessionConfiguration", new SessionStateCmdletEntry("Register-PSSessionConfiguration", typeof(RegisterPSSessionConfigurationCommand), helpFile) }, { "Unregister-PSSessionConfiguration", new SessionStateCmdletEntry("Unregister-PSSessionConfiguration", typeof(UnregisterPSSessionConfigurationCommand), helpFile) }, @@ -5358,6 +5478,7 @@ private static void InitializeCoreCmdletsAndProviders( { "Get-Module", new SessionStateCmdletEntry("Get-Module", typeof(GetModuleCommand), helpFile) }, { "Get-PSHostProcessInfo", new SessionStateCmdletEntry("Get-PSHostProcessInfo", typeof(GetPSHostProcessInfoCommand), helpFile) }, { "Get-PSSession", new SessionStateCmdletEntry("Get-PSSession", typeof(GetPSSessionCommand), helpFile) }, + { "Get-PSSubsystem", new SessionStateCmdletEntry("Get-PSSubsystem", typeof(Subsystem.GetPSSubsystemCommand), helpFile) }, { "Import-Module", new SessionStateCmdletEntry("Import-Module", typeof(ImportModuleCommand), helpFile) }, { "Invoke-Command", new SessionStateCmdletEntry("Invoke-Command", typeof(InvokeCommandCommand), helpFile) }, { "Invoke-History", new SessionStateCmdletEntry("Invoke-History", typeof(InvokeHistoryCommand), helpFile) }, @@ -5365,6 +5486,7 @@ private static void InitializeCoreCmdletsAndProviders( { "New-ModuleManifest", new SessionStateCmdletEntry("New-ModuleManifest", typeof(NewModuleManifestCommand), helpFile) }, { "New-PSRoleCapabilityFile", new SessionStateCmdletEntry("New-PSRoleCapabilityFile", typeof(NewPSRoleCapabilityFileCommand), helpFile) }, { "New-PSSession", new SessionStateCmdletEntry("New-PSSession", typeof(NewPSSessionCommand), helpFile) }, + { "New-PSSessionConfigurationFile", new SessionStateCmdletEntry("New-PSSessionConfigurationFile", typeof(NewPSSessionConfigurationFileCommand), helpFile) }, { "New-PSSessionOption", new SessionStateCmdletEntry("New-PSSessionOption", typeof(NewPSSessionOptionCommand), helpFile) }, { "New-PSTransportOption", new SessionStateCmdletEntry("New-PSTransportOption", typeof(NewPSTransportOptionCommand), helpFile) }, { "Out-Default", new SessionStateCmdletEntry("Out-Default", typeof(OutDefaultCommand), helpFile) }, @@ -5397,10 +5519,9 @@ private static void InitializeCoreCmdletsAndProviders( { "Format-Default", new SessionStateCmdletEntry("Format-Default", typeof(FormatDefaultCommand), helpFile) }, }; - if (ExperimentalFeature.IsEnabled("PSSubsystemPluginModel")) - { - cmdlets.Add("Get-PSSubsystem", new SessionStateCmdletEntry("Get-PSSubsystem", typeof(Subsystem.GetPSSubsystemCommand), helpFile)); - } +#if UNIX + cmdlets.Add("Switch-Process", new SessionStateCmdletEntry("Switch-Process", typeof(SwitchProcessCommand), helpFile)); +#endif foreach (var val in cmdlets.Values) { @@ -5443,7 +5564,7 @@ internal static IEnumerable GetAssemblyTypes(Assembly assembly, string nam try { // Return types that are public, non-abstract, non-interface and non-valueType. - return assembly.ExportedTypes.Where(t => !t.IsAbstract && !t.IsInterface && !t.IsValueType); + return assembly.ExportedTypes.Where(static t => !t.IsAbstract && !t.IsInterface && !t.IsValueType); } catch (ReflectionTypeLoadException e) { diff --git a/src/System.Management.Automation/engine/InternalCommands.cs b/src/System.Management.Automation/engine/InternalCommands.cs index b7b1d87cc82..4e50e2d130f 100644 --- a/src/System.Management.Automation/engine/InternalCommands.cs +++ b/src/System.Management.Automation/engine/InternalCommands.cs @@ -6,17 +6,19 @@ using System.Collections.Generic; using System.Dynamic; using System.Globalization; -using System.Linq; using System.Linq.Expressions; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.PSTasks; +using System.Management.Automation.Security; using System.Runtime.CompilerServices; using System.Text; using System.Threading; + using CommonParamSet = System.Management.Automation.Internal.CommonParameters; using Dbg = System.Management.Automation.Diagnostics; +using NotNullWhen = System.Diagnostics.CodeAnalysis.NotNullWhenAttribute; namespace Microsoft.PowerShell.Commands { @@ -381,24 +383,14 @@ public void Dispose() private Exception _taskCollectionException; private string _currentLocationPath; - // List of Foreach-Object command names and aliases. - // TODO: Look into using SessionState.Internal.GetAliasTable() to find all user created aliases. - // But update Alias command logic to maintain reverse table that lists all aliases mapping - // to a single command definition, for performance. - private static string[] forEachNames = new string[] - { - "ForEach-Object", - "foreach", - "%" - }; - private void InitParallelParameterSet() { // The following common parameters are not (yet) supported in this parameter set. - // ErrorAction, WarningAction, InformationAction, PipelineVariable. + // ErrorAction, WarningAction, InformationAction, ProgressAction, PipelineVariable. if (MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.ErrorAction)) || MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.WarningAction)) || MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.InformationAction)) || + MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.ProgressAction)) || MyInvocation.BoundParameters.ContainsKey(nameof(CommonParamSet.PipelineVariable))) { ThrowTerminatingError( @@ -422,15 +414,14 @@ private void InitParallelParameterSet() _usingValuesMap = ScriptBlockToPowerShellConverter.GetUsingValuesForEachParallel( scriptBlock: Parallel, isTrustedInput: allowUsingExpression, - context: this.Context, - foreachNames: forEachNames); + context: this.Context); // Validate using values map, which is a map of '$using:' variables referenced in the script. // Script block variables are not allowed since their behavior is undefined outside the runspace // in which they were created. foreach (object item in _usingValuesMap.Values) { - if (item is ScriptBlock) + if (item is ScriptBlock or PSObject { BaseObject: ScriptBlock }) { ThrowTerminatingError( new ErrorRecord( @@ -695,7 +686,10 @@ private void ProcessPropertyAndMethodParameterSet() else { // if inputObject is of IDictionary, get the value - if (GetValueFromIDictionaryInput()) { return; } + if (GetValueFromIDictionaryInput()) + { + return; + } PSMemberInfo member = null; if (WildcardPattern.ContainsWildcardCharacters(_propertyOrMethodName)) @@ -711,7 +705,7 @@ private void ProcessPropertyAndMethodParameterSet() StringBuilder possibleMatches = new StringBuilder(); foreach (PSMemberInfo item in members) { - possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); + possibleMatches.Append(CultureInfo.InvariantCulture, $" {item.Name}"); } WriteError(GenerateNameParameterError("Name", InternalCommandStrings.AmbiguousPropertyOrMethodName, @@ -930,17 +924,14 @@ private void ProcessScriptBlockParameterSet() // because it allows you to parameterize a command - for example you might allow // for actions before and after the main processing script. They could be null // by default and therefore ignored then filled in later... - if (_scripts[i] != null) - { - _scripts[i].InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: false, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: InputObject, - input: new object[] { InputObject }, - scriptThis: AutomationNull.Value, - args: Array.Empty()); - } + _scripts[i]?.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: false, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: InputObject, + input: new object[] { InputObject }, + scriptThis: AutomationNull.Value, + args: Array.Empty()); } } @@ -1032,7 +1023,7 @@ private void MethodCallWithArguments() StringBuilder possibleMatches = new StringBuilder(); foreach (PSMemberInfo item in methods) { - possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); + possibleMatches.Append(CultureInfo.InvariantCulture, $" {item.Name}"); } WriteError(GenerateNameParameterError( @@ -1062,7 +1053,7 @@ private void MethodCallWithArguments() StringBuilder arglist = new StringBuilder(GetStringRepresentation(_arguments[0])); for (int i = 1; i < _arguments.Length; i++) { - arglist.AppendFormat(CultureInfo.InvariantCulture, ", {0}", GetStringRepresentation(_arguments[i])); + arglist.Append(CultureInfo.InvariantCulture, $", {GetStringRepresentation(_arguments[i])}"); } string methodAction = string.Format(CultureInfo.InvariantCulture, @@ -1215,14 +1206,25 @@ private bool BlockMethodInLanguageMode(object inputObject) if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) { object baseObject = PSObject.Base(inputObject); + var objectType = baseObject.GetType(); - if (!CoreTypes.Contains(baseObject.GetType())) + if (!CoreTypes.Contains(objectType)) { - PSInvalidOperationException exception = - new PSInvalidOperationException(ParserStrings.InvokeMethodConstrainedLanguage); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + PSInvalidOperationException exception = + new PSInvalidOperationException(ParserStrings.InvokeMethodConstrainedLanguage); - WriteError(new ErrorRecord(exception, "MethodInvocationNotSupportedInConstrainedLanguage", ErrorCategory.InvalidOperation, null)); - return true; + WriteError(new ErrorRecord(exception, "MethodInvocationNotSupportedInConstrainedLanguage", ErrorCategory.InvalidOperation, null)); + return true; + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: InternalCommandStrings.WDACLogTitle, + message: StringUtil.Format(InternalCommandStrings.WDACLogMessage, objectType.FullName), + fqid: "ForEachObjectCmdletMethodInvocationNotAllowed", + dropIntoDebugger: true); } } @@ -1439,8 +1441,11 @@ public SwitchParameter EQ set { - _binaryOperator = TokenKind.Ieq; - _forceBooleanEvaluation = false; + if (value) + { + _binaryOperator = TokenKind.Ieq; + _forceBooleanEvaluation = false; + } } } @@ -1457,7 +1462,10 @@ public SwitchParameter CEQ set { - _binaryOperator = TokenKind.Ceq; + if (value) + { + _binaryOperator = TokenKind.Ceq; + } } } @@ -1475,7 +1483,10 @@ public SwitchParameter NE set { - _binaryOperator = TokenKind.Ine; + if (value) + { + _binaryOperator = TokenKind.Ine; + } } } @@ -1492,7 +1503,10 @@ public SwitchParameter CNE set { - _binaryOperator = TokenKind.Cne; + if (value) + { + _binaryOperator = TokenKind.Cne; + } } } @@ -1510,7 +1524,10 @@ public SwitchParameter GT set { - _binaryOperator = TokenKind.Igt; + if (value) + { + _binaryOperator = TokenKind.Igt; + } } } @@ -1527,7 +1544,10 @@ public SwitchParameter CGT set { - _binaryOperator = TokenKind.Cgt; + if (value) + { + _binaryOperator = TokenKind.Cgt; + } } } @@ -1545,12 +1565,15 @@ public SwitchParameter LT set { - _binaryOperator = TokenKind.Ilt; + if (value) + { + _binaryOperator = TokenKind.Ilt; + } } } /// - /// Gets -sets case sensitive binary operator -clt. + /// Gets or sets case sensitive binary operator -clt. /// [Parameter(Mandatory = true, ParameterSetName = "CaseSensitiveLessThanSet")] public SwitchParameter CLT @@ -1562,7 +1585,10 @@ public SwitchParameter CLT set { - _binaryOperator = TokenKind.Clt; + if (value) + { + _binaryOperator = TokenKind.Clt; + } } } @@ -1580,7 +1606,10 @@ public SwitchParameter GE set { - _binaryOperator = TokenKind.Ige; + if (value) + { + _binaryOperator = TokenKind.Ige; + } } } @@ -1597,7 +1626,10 @@ public SwitchParameter CGE set { - _binaryOperator = TokenKind.Cge; + if (value) + { + _binaryOperator = TokenKind.Cge; + } } } @@ -1615,7 +1647,10 @@ public SwitchParameter LE set { - _binaryOperator = TokenKind.Ile; + if (value) + { + _binaryOperator = TokenKind.Ile; + } } } @@ -1632,7 +1667,10 @@ public SwitchParameter CLE set { - _binaryOperator = TokenKind.Cle; + if (value) + { + _binaryOperator = TokenKind.Cle; + } } } @@ -1650,7 +1688,10 @@ public SwitchParameter Like set { - _binaryOperator = TokenKind.Ilike; + if (value) + { + _binaryOperator = TokenKind.Ilike; + } } } @@ -1667,7 +1708,10 @@ public SwitchParameter CLike set { - _binaryOperator = TokenKind.Clike; + if (value) + { + _binaryOperator = TokenKind.Clike; + } } } @@ -1685,7 +1729,10 @@ public SwitchParameter NotLike set { - _binaryOperator = TokenKind.Inotlike; + if (value) + { + _binaryOperator = TokenKind.Inotlike; + } } } @@ -1702,7 +1749,10 @@ public SwitchParameter CNotLike set { - _binaryOperator = TokenKind.Cnotlike; + if (value) + { + _binaryOperator = TokenKind.Cnotlike; + } } } @@ -1720,7 +1770,10 @@ public SwitchParameter Match set { - _binaryOperator = TokenKind.Imatch; + if (value) + { + _binaryOperator = TokenKind.Imatch; + } } } @@ -1737,7 +1790,10 @@ public SwitchParameter CMatch set { - _binaryOperator = TokenKind.Cmatch; + if (value) + { + _binaryOperator = TokenKind.Cmatch; + } } } @@ -1755,7 +1811,10 @@ public SwitchParameter NotMatch set { - _binaryOperator = TokenKind.Inotmatch; + if (value) + { + _binaryOperator = TokenKind.Inotmatch; + } } } @@ -1772,7 +1831,10 @@ public SwitchParameter CNotMatch set { - _binaryOperator = TokenKind.Cnotmatch; + if (value) + { + _binaryOperator = TokenKind.Cnotmatch; + } } } @@ -1790,7 +1852,10 @@ public SwitchParameter Contains set { - _binaryOperator = TokenKind.Icontains; + if (value) + { + _binaryOperator = TokenKind.Icontains; + } } } @@ -1807,7 +1872,10 @@ public SwitchParameter CContains set { - _binaryOperator = TokenKind.Ccontains; + if (value) + { + _binaryOperator = TokenKind.Ccontains; + } } } @@ -1825,7 +1893,10 @@ public SwitchParameter NotContains set { - _binaryOperator = TokenKind.Inotcontains; + if (value) + { + _binaryOperator = TokenKind.Inotcontains; + } } } @@ -1842,7 +1913,10 @@ public SwitchParameter CNotContains set { - _binaryOperator = TokenKind.Cnotcontains; + if (value) + { + _binaryOperator = TokenKind.Cnotcontains; + } } } @@ -1860,7 +1934,10 @@ public SwitchParameter In set { - _binaryOperator = TokenKind.In; + if (value) + { + _binaryOperator = TokenKind.In; + } } } @@ -1877,7 +1954,10 @@ public SwitchParameter CIn set { - _binaryOperator = TokenKind.Cin; + if (value) + { + _binaryOperator = TokenKind.Cin; + } } } @@ -1895,7 +1975,10 @@ public SwitchParameter NotIn set { - _binaryOperator = TokenKind.Inotin; + if (value) + { + _binaryOperator = TokenKind.Inotin; + } } } @@ -1912,7 +1995,10 @@ public SwitchParameter CNotIn set { - _binaryOperator = TokenKind.Cnotin; + if (value) + { + _binaryOperator = TokenKind.Cnotin; + } } } @@ -1929,7 +2015,10 @@ public SwitchParameter Is set { - _binaryOperator = TokenKind.Is; + if (value) + { + _binaryOperator = TokenKind.Is; + } } } @@ -1946,7 +2035,10 @@ public SwitchParameter IsNot set { - _binaryOperator = TokenKind.IsNot; + if (value) + { + _binaryOperator = TokenKind.IsNot; + } } } @@ -1963,7 +2055,10 @@ public SwitchParameter Not set { - _binaryOperator = TokenKind.Not; + if (value) + { + _binaryOperator = TokenKind.Not; + } } } @@ -2016,7 +2111,7 @@ private void CheckLanguageMode() private object GetLikeRHSOperand(object operand) { - if (!(operand is string val)) + if (operand is not string val) { return operand; } @@ -2368,7 +2463,7 @@ private object GetValue(ref bool error) StringBuilder possibleMatches = new StringBuilder(); foreach (PSMemberInfo item in members) { - possibleMatches.AppendFormat(CultureInfo.InvariantCulture, " {0}", item.Name); + possibleMatches.Append(CultureInfo.InvariantCulture, $" {item.Name}"); } WriteError( @@ -2647,46 +2742,19 @@ public SwitchParameter Off private SwitchParameter _off; /// - /// To make it easier to specify a version, we add some conversions that wouldn't happen otherwise: - /// * A simple integer, i.e. 2 - /// * A string without a dot, i.e. "2" - /// * The string 'latest', which we interpret to be the current version of PowerShell. + /// Handle 'latest', which we interpret to be the current version of PowerShell. /// - private sealed class ArgumentToVersionTransformationAttribute : ArgumentTransformationAttribute + private sealed class ArgumentToPSVersionTransformationAttribute : ArgumentToVersionTransformationAttribute { - public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) + protected override bool TryConvertFromString(string versionString, [NotNullWhen(true)] out Version version) { - object version = PSObject.Base(inputData); - - string versionStr = version as string; - if (versionStr != null) - { - if (versionStr.Equals("latest", StringComparison.OrdinalIgnoreCase)) - { - return PSVersionInfo.PSVersion; - } - - if (versionStr.Contains('.')) - { - // If the string contains a '.', let the Version constructor handle the conversion. - return inputData; - } - } - - if (version is double) - { - // The conversion to int below is wrong, but the usual conversions will turn - // the double into a string, so just return the original object. - return inputData; - } - - int majorVersion; - if (LanguagePrimitives.TryConvertTo(version, out majorVersion)) + if (string.Equals("latest", versionString, StringComparison.OrdinalIgnoreCase)) { - return new Version(majorVersion, 0); + version = PSVersionInfo.PSVersion; + return true; } - return inputData; + return base.TryConvertFromString(versionString, out version); } } @@ -2695,7 +2763,7 @@ private sealed class ValidateVersionAttribute : ValidateArgumentsAttribute protected override void Validate(object arguments, EngineIntrinsics engineIntrinsics) { Version version = arguments as Version; - if (version == null || !PSVersionInfo.IsValidPSVersion(version)) + if (!PSVersionInfo.IsValidPSVersion(version)) { // No conversion succeeded so throw and exception... throw new ValidationMetadataException( @@ -2711,7 +2779,8 @@ protected override void Validate(object arguments, EngineIntrinsics engineIntrin /// Gets or sets strict mode in the current scope. /// [Parameter(ParameterSetName = "Version", Mandatory = true)] - [ArgumentToVersionTransformation] + [ArgumentCompleter(typeof(StrictModeVersionArgumentCompleter))] + [ArgumentToPSVersionTransformation] [ValidateVersion] [Alias("v")] public Version Version @@ -2742,6 +2811,34 @@ protected override void EndProcessing() Context.EngineSessionState.CurrentScope.StrictModeVersion = _version; } } + + /// + /// Provides argument completion for StrictMode Version parameter. + /// + public class StrictModeVersionArgumentCompleter : IArgumentCompleter + { + private static readonly string[] s_strictModeVersions = new string[] { "Latest", "3.0", "2.0", "1.0" }; + + /// + /// Returns completion results for version 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_strictModeVersions); + } + #endregion Set-StrictMode #endregion Built-in cmdlets that are used by or require direct access to the engine. diff --git a/src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs b/src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs new file mode 100644 index 00000000000..072e5d1b18e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/AllocConsole.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("kernel32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool AllocConsole(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs b/src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs new file mode 100644 index 00000000000..7605420dab4 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/AssignProcessToJobObject.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool AssignProcessToJobObject( + SafeJobHandle hJob, + SafeProcessHandle hProcess); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs b/src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs new file mode 100644 index 00000000000..6832268272a --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CloseHandle.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("api-ms-win-core-handle-l1-1-0.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CloseHandle(nint hObject); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs b/src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs new file mode 100644 index 00000000000..a3eae4fd596 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CoInitializeEx.cs @@ -0,0 +1,18 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal const int COINIT_APARTMENTTHREADED = 0x2; + internal const int E_NOTIMPL = unchecked((int)0X80004001); + + [LibraryImport("api-ms-win-core-com-l1-1-0.dll")] + internal static partial int CoInitializeEx(nint reserve, int coinit); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs b/src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs new file mode 100644 index 00000000000..d872cf17f3e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CoUninitialize.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("api-ms-win-core-com-l1-1-0.dll")] + internal static partial void CoUninitialize(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs new file mode 100644 index 00000000000..fa1552c91c5 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateFile.cs @@ -0,0 +1,95 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.IO; +using System.Management.Automation; +using System.Runtime.InteropServices; + +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + // dwDesiredAccess of CreateFile + [Flags] + internal enum FileDesiredAccess : uint + { + GenericZero = 0, + GenericRead = 0x80000000, + GenericWrite = 0x40000000, + GenericExecute = 0x20000000, + GenericAll = 0x10000000, + } + + // dwFlagsAndAttributes + [Flags] + internal enum FileAttributes : uint + { + Readonly = 0x00000001, + Hidden = 0x00000002, + System = 0x00000004, + Archive = 0x00000020, + Encrypted = 0x00004000, + Write_Through = 0x80000000, + Overlapped = 0x40000000, + NoBuffering = 0x20000000, + RandomAccess = 0x10000000, + SequentialScan = 0x08000000, + DeleteOnClose = 0x04000000, + BackupSemantics = 0x02000000, + PosixSemantics = 0x01000000, + OpenReparsePoint = 0x00200000, + OpenNoRecall = 0x00100000, + SessionAware = 0x00800000, + Normal = 0x00000080 + } + + // WARNING: This method does not implicitly handle long paths. Use CreateFile. + [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static unsafe partial SafeFileHandle CreateFilePrivate( + string lpFileName, + uint dwDesiredAccess, + FileShare dwShareMode, + nint lpSecurityAttributes, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes, + IntPtr hTemplateFile); + + [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static unsafe partial nint CreateFileWithPipeHandlePrivate( + string lpFileName, + uint dwDesiredAccess, + FileShare dwShareMode, + nint lpSecurityAttributes, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes, + IntPtr hTemplateFile); + + internal static unsafe SafeFileHandle CreateFileWithSafeFileHandle( + string lpFileName, + FileAccess dwDesiredAccess, + FileShare dwShareMode, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes) + { + lpFileName = Path.TrimEndingDirectorySeparator(lpFileName); + lpFileName = PathUtils.EnsureExtendedPrefixIfNeeded(lpFileName); + + return CreateFilePrivate(lpFileName, (uint)dwDesiredAccess, dwShareMode, nint.Zero, dwCreationDisposition, dwFlagsAndAttributes, nint.Zero); + } + + internal static unsafe nint CreateFileWithPipeHandle( + string lpFileName, + FileAccess dwDesiredAccess, + FileShare dwShareMode, + FileMode dwCreationDisposition, + FileAttributes dwFlagsAndAttributes) + { + return CreateFileWithPipeHandlePrivate(lpFileName, (uint)dwDesiredAccess, dwShareMode, nint.Zero, dwCreationDisposition, dwFlagsAndAttributes, nint.Zero); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs new file mode 100644 index 00000000000..f27f095fc1a --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateHardLink.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateHardLinkW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool CreateHardLink(string name, string existingFileName, nint securityAttributes); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateIoCompletionPort.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateIoCompletionPort.cs new file mode 100644 index 00000000000..0b877fcdaea --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateIoCompletionPort.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal sealed class SafeIoCompletionPort : SafeHandle + { + public SafeIoCompletionPort() : base(invalidHandleValue: nint.Zero, ownsHandle: true) { } + + public override bool IsInvalid => handle == nint.Zero; + + protected override bool ReleaseHandle() + => Windows.CloseHandle(handle); + } + + [LibraryImport("kernel32.dll", SetLastError = true)] + private static partial SafeIoCompletionPort CreateIoCompletionPort( + nint FileHandle, + nint ExistingCompletionPort, + nint CompletionKey, + int NumberOfConcurrentThreads); + + internal static SafeIoCompletionPort CreateIoCompletionPort() + { + return CreateIoCompletionPort( + FileHandle: -1, + ExistingCompletionPort: nint.Zero, + CompletionKey: nint.Zero, + NumberOfConcurrentThreads: 1); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateJobObject.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateJobObject.cs new file mode 100644 index 00000000000..fee16b813aa --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateJobObject.cs @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal sealed class SafeJobHandle : SafeHandle + { + public SafeJobHandle() : base(invalidHandleValue: nint.Zero, ownsHandle: true) { } + + public override bool IsInvalid => handle == nint.Zero; + + protected override bool ReleaseHandle() + => Windows.CloseHandle(handle); + } + + [LibraryImport("kernel32.dll", EntryPoint = "CreateJobObjectW", SetLastError = true)] + private static partial SafeJobHandle CreateJobObject( + nint lpJobAttributes, + nint lpName); + + internal static SafeJobHandle CreateJobObject() + => CreateJobObject(nint.Zero, nint.Zero); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs b/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs new file mode 100644 index 00000000000..c6519f94ec4 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/CreateSymbolicLink.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [Flags] + internal enum SymbolicLinkFlags + { + File = 0, + Directory = 1, + AllowUnprivilegedCreate = 2, + } + + [LibraryImport("api-ms-win-core-file-l2-1-0.dll", EntryPoint = "CreateSymbolicLinkW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.I1)] + internal static partial bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/Errors.cs b/src/System.Management.Automation/engine/Interop/Windows/Errors.cs new file mode 100644 index 00000000000..bef9e172193 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/Errors.cs @@ -0,0 +1,19 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +internal static partial class Interop +{ + internal static partial class Windows + { + // List of error constants https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes + internal const int ERROR_SUCCESS = 0; + internal const int ERROR_FILE_NOT_FOUND = 2; + internal const int ERROR_GEN_FAILURE = 31; + internal const int ERROR_NOT_SUPPORTED = 50; + internal const int ERROR_NO_NETWORK = 1222; + internal const int ERROR_MORE_DATA = 234; + internal const int ERROR_CONNECTION_UNAVAIL = 1201; + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs b/src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs new file mode 100644 index 00000000000..8152a793149 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/EventActivityIdControl.cs @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +#if !UNIX +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal enum ActivityControl : uint + { + /// + /// Gets the ActivityId from thread local storage. + /// + Get = 1, + + /// + /// Sets the ActivityId in the thread local storage. + /// + Set = 2, + + /// + /// Creates a new activity id. + /// + Create = 3, + + /// + /// Sets the activity id in thread local storage and returns the previous value. + /// + GetSet = 4, + + /// + /// Creates a new activity id, sets thread local storage, and returns the previous value. + /// + CreateSet = 5 + } + + [LibraryImport("api-ms-win-eventing-provider-l1-1-0.dll")] + internal static unsafe partial int EventActivityIdControl(ActivityControl controlCode, Guid* activityId); + + internal static unsafe int GetEventActivityIdControl(ref Guid activityId) + { + fixed (Guid* guidPtr = &activityId) + { + return EventActivityIdControl(ActivityControl.Get, guidPtr); + } + } + } +} +#endif diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindClose.cs b/src/System.Management.Automation/engine/Interop/Windows/FindClose.cs new file mode 100644 index 00000000000..a5903c72c70 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/FindClose.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("api-ms-win-core-file-l1-1-0.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool FindClose(nint handle); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs b/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs new file mode 100644 index 00000000000..2184e57a519 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/FindExecutable.cs @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +#if !UNIX +using System; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + // The FindExecutable API is defined in shellapi.h as + // SHSTDAPI_(HINSTANCE) FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, __out_ecount(MAX_PATH) LPWSTR lpResult); + // HINSTANCE is void* so we need to use IntPtr (nint) as API return value. + [LibraryImport("shell32.dll", EntryPoint = "FindExecutableW", StringMarshalling = StringMarshalling.Utf16)] + internal static partial nint FindExecutableW(string fileName, string directoryPath, char* pathFound); + + internal static string? FindExecutable(string filename) + { + string? result = null; + + // HINSTANCE == PVOID == nint + nint resultCode = 0; + + Span buffer = stackalloc char[MAX_PATH]; + unsafe + { + fixed (char* lpBuffer = buffer) + { + resultCode = FindExecutableW(filename, string.Empty, lpBuffer); + + // If FindExecutable returns a result > 32, then it succeeded + // and we return the string that was found, otherwise we + // return null. + if (resultCode > 32) + { + result = Marshal.PtrToStringUni((IntPtr)lpBuffer); + return result; + } + } + } + + return null; + } + } +} +#endif diff --git a/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs b/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs new file mode 100644 index 00000000000..e53b0985cb6 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/FindFirstFile.cs @@ -0,0 +1,66 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Management.Automation; +using System.Runtime.InteropServices; + +using Microsoft.Win32.SafeHandles; + +internal static partial class Interop +{ + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Keep native struct names.")] + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Keep native struct names.")] + internal static unsafe partial class Windows + { + internal const int MAX_PATH = 260; + + internal struct FILE_TIME + { + public uint dwLowDateTime; + public uint dwHighDateTime; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + internal unsafe struct WIN32_FIND_DATA + { + internal uint dwFileAttributes; + internal FILE_TIME ftCreationTime; + internal FILE_TIME ftLastAccessTime; + internal FILE_TIME ftLastWriteTime; + internal uint nFileSizeHigh; + internal uint nFileSizeLow; + internal uint dwReserved0; + internal uint dwReserved1; + internal fixed char cFileName[MAX_PATH]; + internal fixed char cAlternateFileName[14]; + } + + internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid + { + // .NET 8 requires the default constructor to be public + public SafeFindHandle() : base(true) { } + + protected override bool ReleaseHandle() + { + return Interop.Windows.FindClose(this.handle); + } + } + + // We use 'FindFirstFileW' instead of 'FindFirstFileExW' because the latter doesn't work correctly with Unicode file names on FAT32. + // See https://github.com/PowerShell/PowerShell/issues/16804 + [LibraryImport("api-ms-win-core-file-l1-1-0.dll", EntryPoint = "FindFirstFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + private static partial SafeFindHandle FindFirstFileW(string lpFileName, ref WIN32_FIND_DATA lpFindFileData); + + internal static SafeFindHandle FindFirstFile(string lpFileName, ref WIN32_FIND_DATA lpFindFileData) + { + lpFileName = Path.TrimEndingDirectorySeparator(lpFileName); + lpFileName = PathUtils.EnsureExtendedPrefixIfNeeded(lpFileName); + + return FindFirstFileW(lpFileName, ref lpFindFileData); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs new file mode 100644 index 00000000000..60d9229ea64 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetConsoleWindow.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("Kernel32.dll")] + internal static partial nint GetConsoleWindow(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs b/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs new file mode 100644 index 00000000000..80a0c7a4c43 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetCurrentThreadId.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("api-ms-win-core-processthreads-l1-1-0.dll")] + internal static partial uint GetCurrentThreadId(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs new file mode 100644 index 00000000000..2ba57535162 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetForegroundWindow.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("user32.dll")] + internal static partial nint GetForegroundWindow(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs b/src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs new file mode 100644 index 00000000000..4267deb1167 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetOEMCP.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("api-ms-win-core-localization-l1-2-0.dll")] + internal static partial uint GetOEMCP(); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/GetQueuedCompletionStatus.cs b/src/System.Management.Automation/engine/Interop/Windows/GetQueuedCompletionStatus.cs new file mode 100644 index 00000000000..d23234e850b --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/GetQueuedCompletionStatus.cs @@ -0,0 +1,36 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + public const int INFINITE = -1; + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool GetQueuedCompletionStatus( + SafeIoCompletionPort CompletionPort, + out int lpNumberOfBytesTransferred, + out nint lpCompletionKey, + out nint lpOverlapped, + int dwMilliseconds); + + internal static bool GetQueuedCompletionStatus( + SafeIoCompletionPort completionPort, + int timeoutMilliseconds, + out int status) + { + return GetQueuedCompletionStatus( + completionPort, + out status, + lpCompletionKey: out _, + lpOverlapped: out _, + timeoutMilliseconds); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/NetApiBufferFree.cs b/src/System.Management.Automation/engine/Interop/Windows/NetApiBufferFree.cs new file mode 100644 index 00000000000..4f7d0541872 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/NetApiBufferFree.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + + [LibraryImport("Netapi32.dll")] + internal static partial uint NetApiBufferFree(nint Buffer); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs b/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs new file mode 100644 index 00000000000..7efad887f1a --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/NetShareEnum.cs @@ -0,0 +1,26 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal const int MAX_PREFERRED_LENGTH = -1; + internal const int STYPE_DISKTREE = 0; + internal const int STYPE_MASK = 0x000000FF; + + [LibraryImport("Netapi32.dll", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int NetShareEnum( + string serverName, + int level, + out nint bufptr, + int prefMaxLen, + out uint entriesRead, + out uint totalEntries, + ref uint resumeHandle); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs b/src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs new file mode 100644 index 00000000000..1a839529737 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/NtQueryInformationProcess.cs @@ -0,0 +1,31 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [StructLayout(LayoutKind.Sequential)] + internal struct PROCESS_BASIC_INFORMATION + { + public nint ExitStatus; + public nint PebBaseAddress; + public nint AffinityMask; + public nint BasePriority; + public nint UniqueProcessId; + public nint InheritedFromUniqueProcessId; + } + + [LibraryImport("ntdll.dll")] + internal static partial int NtQueryInformationProcess( + nint processHandle, + int processInformationClass, + out PROCESS_BASIC_INFORMATION processInformation, + int processInformationLength, + out int returnLength); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/PostQueuedCompletionStatus.cs b/src/System.Management.Automation/engine/Interop/Windows/PostQueuedCompletionStatus.cs new file mode 100644 index 00000000000..714eedcc3e5 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/PostQueuedCompletionStatus.cs @@ -0,0 +1,27 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool PostQueuedCompletionStatus( + SafeIoCompletionPort CompletionPort, + int lpNumberOfBytesTransferred, + nint lpCompletionKey, + nint lpOverlapped); + + internal static bool PostQueuedCompletionStatus( + SafeIoCompletionPort completionPort, + int status) + { + return PostQueuedCompletionStatus(completionPort, status, nint.Zero, nint.Zero); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs b/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs new file mode 100644 index 00000000000..d23899e8ef7 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/QueryDosDevice.cs @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Buffers; +using System.ComponentModel; +using System.Management.Automation; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport(PinvokeDllNames.QueryDosDeviceDllName, EntryPoint = "QueryDosDeviceW", StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + internal static partial int QueryDosDevice(Span lpDeviceName, Span lpTargetPath, uint ucchMax); + + internal static string GetDosDeviceForNetworkPath(char deviceName) + { + // By default buffer size is set to 300 which would generally be sufficient in most of the cases. + const int StartLength = +#if DEBUG + // In debug, validate ArrayPool growth. + 1; +#else + 300; +#endif + + Span buffer = stackalloc char[StartLength + 1]; + Span fullDeviceName = [deviceName, ':', '\0']; + char[]? rentedArray = null; + + try + { + while (true) + { + uint length = (uint)buffer.Length; + int retValue = QueryDosDevice(fullDeviceName, buffer, length); + if (retValue > 0) + { + if (buffer.StartsWith("\\??\\")) + { + // QueryDosDevice always return array of NULL-terminating strings with additional final NULL + // so the buffer has always two NULL-s on end. + // + // "\\??\\UNC\\localhost\\c$\\tmp\0\0" -> "UNC\\localhost\\c$\\tmp\0\0" + Span res = buffer.Slice(4); + if (res.StartsWith("UNC")) + { + // -> "C\\localhost\\c$\\tmp\0\0" -> "\\\\localhost\\c$\\tmp" + // + // We need to take only first null-terminated string as QueryDosDevice() docs say. + int i = 3; + for (; i < res.Length; i++) + { + if (res[i] == '\0') + { + break; + } + } + + Diagnostics.Assert(i < res.Length, "Broken QueryDosDevice() buffer."); + + res = res.Slice(2, i); + res[0] = '\\'; + + // If we want always to have terminating slash -> "\\\\localhost\\c$\\tmp\\" + // res = res.Slice(2, retValue - 3); + // res[0] = '\\'; + // res[^1] = '\\'; + } + // else if (res[^3] == ':') + // { + // Diagnostics.Assert(false, "Really it is a dead code since GetDosDevice() is called only if PSDrive.DriveType == DriveType.Network"); + + // // The substed path is the root path of a drive. For example: subst Y: C:\ + // // -> "C:\0\0" -> "C:\" + // res = res.Slice(0, retValue - 1); + // res[^1] = '\\'; + // } + else + { + throw new Exception("GetDosDeviceForNetworkPath() can be called only if PSDrive.DriveType == DriveType.Network."); + } + + return res.ToString(); + } + else + { + Diagnostics.Assert(false, "Really it is a dead code since GetDosDevice() is called only if PSDrive.DriveType == DriveType.Network"); + + // The drive name is not a substed path, then we return the root path of the drive + // "C:\0" -> "C:\\" + fullDeviceName[^1] = '\\'; + return fullDeviceName.ToString(); + } + } + + const int ERROR_INSUFFICIENT_BUFFER = 122; + int errorCode = Marshal.GetLastPInvokeError(); + if (errorCode != ERROR_INSUFFICIENT_BUFFER) + { + throw new Win32Exception((int)errorCode); + } + + char[]? toReturn = rentedArray; + buffer = rentedArray = ArrayPool.Shared.Rent(buffer.Length * 2); + if (toReturn is not null) + { + ArrayPool.Shared.Return(toReturn); + } + } + } + finally + { + if (rentedArray is not null) + { + ArrayPool.Shared.Return(rentedArray); + } + } + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs b/src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs new file mode 100644 index 00000000000..9e82f2c66c1 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/RtlQueryProcessPlaceholderCompatibilityMode.cs @@ -0,0 +1,25 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal const sbyte PHCM_APPLICATION_DEFAULT = 0; + internal const sbyte PHCM_DISGUISE_PLACEHOLDER = 1; + internal const sbyte PHCM_EXPOSE_PLACEHOLDERS = 2; + internal const sbyte PHCM_MAX = 2; + internal const sbyte PHCM_ERROR_INVALID_PARAMETER = -1; + internal const sbyte PHCM_ERROR_NO_TEB = -2; + + [LibraryImport("ntdll.dll")] + internal static partial sbyte RtlQueryProcessPlaceholderCompatibilityMode(); + + [LibraryImport("ntdll.dll")] + internal static partial sbyte RtlSetProcessPlaceholderCompatibilityMode(sbyte pcm); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs b/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs new file mode 100644 index 00000000000..a6deaa39c41 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/SHGetFileInfo.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Diagnostics.CodeAnalysis; +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1305:FieldNamesMustNotUseHungarianNotation", Justification = "Keep native struct names.")] + [SuppressMessage("StyleCop.CSharp.NamingRules", "SA1307:AccessibleFieldsMustBeginWithUpperCaseLetter", Justification = "Keep native struct names.")] + internal static partial class Windows + { + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct SHFILEINFO + { + internal nint hIcon; + internal int iIcon; + internal uint dwAttributes; + internal fixed char szDisplayName[260]; + internal fixed char szTypeName[80]; + + public static readonly uint s_Size = (uint)sizeof(SHFILEINFO); + } + + [LibraryImport("shell32.dll", EntryPoint = "SHGetFileInfoW", StringMarshalling = StringMarshalling.Utf16)] + internal static partial nint SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); + + internal static int SHGetFileInfo(string pszPath) + { + // flag used to ask to return exe type + const uint SHGFI_EXETYPE = 0x000002000; + var shinfo = new SHFILEINFO(); + return (int)SHGetFileInfo(pszPath, 0, ref shinfo, SHFILEINFO.s_Size, SHGFI_EXETYPE); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs new file mode 100644 index 00000000000..5945fac9608 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/SetForegroundWindow.cs @@ -0,0 +1,16 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool SetForegroundWindow(nint hWnd); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/SetInformationJobObject.cs b/src/System.Management.Automation/engine/Interop/Windows/SetInformationJobObject.cs new file mode 100644 index 00000000000..37d0e74f1f8 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/SetInformationJobObject.cs @@ -0,0 +1,46 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + internal const int JobObjectAssociateCompletionPortInformation = 7; + internal const int JOB_OBJECT_MSG_ACTIVE_PROCESS_ZERO = 4; + + [StructLayout(LayoutKind.Sequential)] + internal struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT + { + public nint CompletionKey; + public nint CompletionPort; + } + + [LibraryImport("kernel32.dll", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool SetInformationJobObject( + SafeJobHandle hJob, + int JobObjectInformationClass, + ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT lpJobObjectInformation, + int cbJobObjectInformationLength); + + internal static bool SetInformationJobObject( + SafeJobHandle jobHandle, + SafeIoCompletionPort completionPort) + { + JOBOBJECT_ASSOCIATE_COMPLETION_PORT objectInfo = new() + { + CompletionKey = jobHandle.DangerousGetHandle(), + CompletionPort = completionPort.DangerousGetHandle(), + }; + return SetInformationJobObject( + jobHandle, + JobObjectAssociateCompletionPortInformation, + ref objectInfo, + Marshal.SizeOf()); + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs b/src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs new file mode 100644 index 00000000000..d33b0a0e244 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/ShowWindow.cs @@ -0,0 +1,32 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + 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; + + [LibraryImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static partial bool ShowWindow(nint hWnd, int nCmdShow); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs b/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs new file mode 100644 index 00000000000..414a0912c81 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/VariantClear.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + [LibraryImport("oleaut32.dll")] + internal static partial void VariantClear(nint pVariant); + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs new file mode 100644 index 00000000000..df66e743897 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetAddConnection2.cs @@ -0,0 +1,73 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static partial class Windows + { + internal const int CONNECT_NOPERSIST = 0x00000000; + internal const int CONNECT_UPDATE_PROFILE = 0x00000001; + internal const int RESOURCE_GLOBALNET = 0x00000002; + internal const int RESOURCETYPE_ANY = 0x00000000; + internal const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; + internal const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; + + [StructLayout(LayoutKind.Sequential)] + internal unsafe struct NETRESOURCEW + { + public int Scope; + public int Type; + public int DisplayType; + public int Usage; + public char* LocalName; + public char* RemoteName; + public char* Comment; + public char* Provider; + } + + [LibraryImport("mpr.dll", EntryPoint = "WNetAddConnection2W", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WNetAddConnection2(ref NETRESOURCEW netResource, byte[] password, string userName, int flags); + + internal static unsafe int WNetAddConnection2(string localName, string remoteName, byte[] password, string userName, int connectType) + { + if (s_WNetApiNotAvailable) + { + return ERROR_NOT_SUPPORTED; + } + + int errorCode = ERROR_NO_NETWORK; + + fixed (char* pinnedLocalName = localName) + fixed (char* pinnedRemoteName = remoteName) + { + NETRESOURCEW resource = new NETRESOURCEW() + { + Comment = null, + DisplayType = RESOURCEDISPLAYTYPE_GENERIC, + LocalName = pinnedLocalName, + Provider = null, + RemoteName = pinnedRemoteName, + Scope = RESOURCE_GLOBALNET, + Type = RESOURCETYPE_ANY, + Usage = RESOURCEUSAGE_CONNECTABLE + }; + + try + { + errorCode = WNetAddConnection2(ref resource, password, userName, connectType); + } + catch (System.DllNotFoundException) + { + s_WNetApiNotAvailable = true; + return ERROR_NOT_SUPPORTED; + } + } + + return errorCode; + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs new file mode 100644 index 00000000000..0ff720ffd3e --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetCancelConnection2.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Runtime.InteropServices; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + [LibraryImport("mpr.dll", EntryPoint = "WNetCancelConnection2W", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WNetCancelConnection2W(string driveName, int flags, [MarshalAs(UnmanagedType.Bool)] bool force); + + internal static int WNetCancelConnection2(string driveName, int flags, bool force) + { + if (s_WNetApiNotAvailable) + { + return ERROR_NOT_SUPPORTED; + } + + int errorCode = ERROR_NO_NETWORK; + + try + { + errorCode = WNetCancelConnection2W(driveName, flags, force: true); + } + catch (System.DllNotFoundException) + { + s_WNetApiNotAvailable = true; + return ERROR_NOT_SUPPORTED; + } + + return errorCode; + } + } +} diff --git a/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs b/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs new file mode 100644 index 00000000000..01667fb4274 --- /dev/null +++ b/src/System.Management.Automation/engine/Interop/Windows/WNetGetConnection.cs @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Buffers; +using System.Runtime.InteropServices; +using System.Management.Automation.Internal; + +internal static partial class Interop +{ + internal static unsafe partial class Windows + { + private static bool s_WNetApiNotAvailable; + + [LibraryImport("mpr.dll", EntryPoint = "WNetGetConnectionW", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WNetGetConnection(ReadOnlySpan localName, Span remoteName, ref int remoteNameLength); + + internal static int GetUNCForNetworkDrive(char drive, out string? uncPath) + { + uncPath = null; + if (s_WNetApiNotAvailable) + { + return ERROR_NOT_SUPPORTED; + } + + ReadOnlySpan driveName = [drive, ':', '\0']; + int bufferSize = MAX_PATH; + Span uncBuffer = stackalloc char[MAX_PATH]; + if (InternalTestHooks.WNetGetConnectionBufferSize > 0 && InternalTestHooks.WNetGetConnectionBufferSize <= MAX_PATH) + { + bufferSize = InternalTestHooks.WNetGetConnectionBufferSize; + uncBuffer = uncBuffer.Slice(0, bufferSize); + } + + char[]? rentedArray = null; + while (true) + { + int errorCode; + try + { + try + { + errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize); + } + catch (DllNotFoundException) + { + s_WNetApiNotAvailable = true; + return ERROR_NOT_SUPPORTED; + } + + if (errorCode == ERROR_SUCCESS) + { + // Cannot rely on bufferSize as it's only set if + // the first call ended with ERROR_MORE_DATA, + // instead slice at the null terminator. + unsafe + { + fixed (char* uncBufferPtr = uncBuffer) + { + uncPath = new string(uncBufferPtr); + } + } + } + } + finally + { + if (rentedArray is not null) + { + ArrayPool.Shared.Return(rentedArray); + } + } + + if (errorCode == ERROR_MORE_DATA) + { + uncBuffer = rentedArray = ArrayPool.Shared.Rent(bufferSize); + } + else + { + return errorCode; + } + } + } + } +} diff --git a/src/System.Management.Automation/engine/InvocationInfo.cs b/src/System.Management.Automation/engine/InvocationInfo.cs index 6020b6e53a0..402d7c8d4a6 100644 --- a/src/System.Management.Automation/engine/InvocationInfo.cs +++ b/src/System.Management.Automation/engine/InvocationInfo.cs @@ -271,6 +271,18 @@ public string Line } } + /// + /// The full text of the invocation statement, may span multiple lines. + /// + /// Statement that was entered to invoke this command. + public string Statement + { + get + { + return ScriptPosition.Text; + } + } + /// /// Formatted message indicating where the cmdlet appeared /// in the line. @@ -440,11 +452,11 @@ internal void ToPSObjectForRemoting(PSObject psObject) if (extent != null) { extent.ToPSObjectForRemoting(psObject); - RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => true); + RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", static () => true); } else { - RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", () => false); + RemotingEncoder.AddNoteProperty(psObject, "SerializeExtent", static () => false); } RemoteCommandInfo.ToPSObjectForRemoting(this.MyCommand, psObject); diff --git a/src/System.Management.Automation/engine/LanguagePrimitives.cs b/src/System.Management.Automation/engine/LanguagePrimitives.cs index 83361fe9662..13d8f66e5e9 100644 --- a/src/System.Management.Automation/engine/LanguagePrimitives.cs +++ b/src/System.Management.Automation/engine/LanguagePrimitives.cs @@ -9,11 +9,11 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; -using System.Linq; using System.Linq.Expressions; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Numerics; using System.Reflection; using System.Reflection.Emit; @@ -21,12 +21,12 @@ using System.Text; using System.Text.RegularExpressions; using System.Xml; +using System.Security; using Dbg = System.Management.Automation.Diagnostics; using MethodCacheEntry = System.Management.Automation.DotNetAdapter.MethodCacheEntry; #if !UNIX using System.DirectoryServices; -using System.Management; #endif #pragma warning disable 1634, 1691 // Stops compiler from warning about unknown warnings @@ -202,7 +202,6 @@ public override object ConvertFrom(object sourceValue, Type destinationType, IFo string sourceAsString = (string)LanguagePrimitives.ConvertTo(sourceValue, typeof(string), formatProvider); return LanguagePrimitives.ConvertTo(sourceAsString, destinationType, formatProvider); } - /// /// Returns false, since this converter is not designed to be used to /// convert from the type associated with the converted to other types. @@ -311,9 +310,11 @@ public static class LanguagePrimitives internal static void CreateMemberNotFoundError(PSObject pso, DictionaryEntry property, Type resultType) { - string availableProperties = GetAvailableProperties(pso); + string settableProperties = GetSettableProperties(pso); - string message = StringUtil.Format(ExtendedTypeSystem.PropertyNotFound, property.Key.ToString(), resultType.FullName, availableProperties); + string message = settableProperties == string.Empty + ? StringUtil.Format(ExtendedTypeSystem.NoSettableProperty, property.Key.ToString(), resultType.FullName) + : StringUtil.Format(ExtendedTypeSystem.PropertyNotFound, property.Key.ToString(), resultType.FullName, settableProperties); typeConversion.WriteLine("Issuing an error message about not being able to create an object from hashtable."); throw new InvalidOperationException(message); @@ -339,12 +340,13 @@ internal static void UpdateTypeConvertFromTypeTable(string typeName) { lock (s_converterCache) { - var toRemove = s_converterCache.Keys.Where( - conv => string.Equals(conv.to.FullName, typeName, StringComparison.OrdinalIgnoreCase) || - string.Equals(conv.from.FullName, typeName, StringComparison.OrdinalIgnoreCase)).ToArray(); - foreach (var k in toRemove) + foreach (var key in s_converterCache.Keys) { - s_converterCache.Remove(k); + if (string.Equals(key.to.FullName, typeName, StringComparison.OrdinalIgnoreCase) + || string.Equals(key.from.FullName, typeName, StringComparison.OrdinalIgnoreCase)) + { + s_converterCache.Remove(key); + } } // Note we do not clear possibleTypeConverter even when removing. @@ -362,7 +364,7 @@ internal static void UpdateTypeConvertFromTypeTable(string typeName) /// implementation of an object when we can't use it's non-generic /// implementation. /// - private class EnumerableTWrapper : IEnumerable + private sealed class EnumerableTWrapper : IEnumerable { private readonly object _enumerable; private readonly Type _enumerableType; @@ -632,12 +634,9 @@ public static bool Equals(object first, object second, bool ignoreCase, IFormatP // If second can be converted to the type of the first, it does so and returns first.Equals(secondConverted) // Otherwise false is returned - if (formatProvider == null) - { - formatProvider = CultureInfo.InvariantCulture; - } + formatProvider ??= CultureInfo.InvariantCulture; - if (!(formatProvider is CultureInfo culture)) + if (formatProvider is not CultureInfo culture) { throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } @@ -779,12 +778,9 @@ public static int Compare(object first, object second, bool ignoreCase) /// public static int Compare(object first, object second, bool ignoreCase, IFormatProvider formatProvider) { - if (formatProvider == null) - { - formatProvider = CultureInfo.InvariantCulture; - } + formatProvider ??= CultureInfo.InvariantCulture; - if (!(formatProvider is CultureInfo culture)) + if (formatProvider is not CultureInfo culture) { throw PSTraceSource.NewArgumentException(nameof(formatProvider)); } @@ -899,10 +895,7 @@ public static bool TryCompare(object first, object second, bool ignoreCase, out public static bool TryCompare(object first, object second, bool ignoreCase, IFormatProvider formatProvider, out int result) { result = 0; - if (formatProvider == null) - { - formatProvider = CultureInfo.InvariantCulture; - } + formatProvider ??= CultureInfo.InvariantCulture; if (formatProvider is not CultureInfo culture) { @@ -1043,7 +1036,7 @@ internal static bool IsTrue(IList objectArray) // but since we don't want this to recurse indefinitely // we explicitly check the case where it would recurse // and deal with it. - if (!(PSObject.Base(objectArray[0]) is IList firstElement)) + if (PSObject.Base(objectArray[0]) is not IList firstElement) { return IsTrue(objectArray[0]); } @@ -1889,7 +1882,7 @@ public override object ConvertFrom(object sourceValue, Type destinationType, IFo internal class EnumSingleTypeConverter : PSTypeConverter { - private class EnumHashEntry + private sealed class EnumHashEntry { internal EnumHashEntry(string[] names, Array values, UInt64 allValues, bool hasNegativeValue, bool hasFlagsAttribute) { @@ -2083,6 +2076,22 @@ internal static string EnumValues(Type enumType) return string.Join(CultureInfo.CurrentUICulture.TextInfo.ListSeparator, enumHashEntry.names); } + /// + /// Returns all names for the provided enum type. + /// + /// The enum type to retrieve names from. + /// Array of enum names for the specified type. + internal static string[] GetEnumNames(Type enumType) + => EnumSingleTypeConverter.GetEnumHashEntry(enumType).names; + + /// + /// Returns all values for the provided enum type. + /// + /// The enum type to retrieve values from. + /// Array of enum values for the specified type. + internal static Array GetEnumValues(Type enumType) + => EnumSingleTypeConverter.GetEnumHashEntry(enumType).values; + public override object ConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase) { return EnumSingleTypeConverter.BaseConvertFrom(sourceValue, destinationType, formatProvider, ignoreCase, false); @@ -2091,7 +2100,7 @@ public override object ConvertFrom(object sourceValue, Type destinationType, IFo protected static object BaseConvertFrom(object sourceValue, Type destinationType, IFormatProvider formatProvider, bool ignoreCase, bool multipleValues) { Diagnostics.Assert(sourceValue != null, "the type converter has a special case for null source values"); - if (!(sourceValue is string sourceValueString)) + if (sourceValue is not string sourceValueString) { throw new PSInvalidCastException("InvalidCastEnumFromTypeNotAString", null, ExtendedTypeSystem.InvalidCastException, @@ -2153,7 +2162,7 @@ protected static object BaseConvertFrom(object sourceValue, Type destinationType } else { - sourceValueEntries = sourceValueString.Split(Utils.Separators.Comma); + sourceValueEntries = sourceValueString.Split(','); fromValuePatterns = new WildcardPattern[sourceValueEntries.Length]; for (int i = 0; i < sourceValueEntries.Length; i++) { @@ -2933,17 +2942,12 @@ private static object ConvertStringToInteger( return result; } - if (resultType == typeof(BigInteger)) - { - // Fallback for BigInteger: manual parsing using any common format. - NumberStyles style = NumberStyles.AllowLeadingSign - | NumberStyles.AllowDecimalPoint - | NumberStyles.AllowExponent - | NumberStyles.AllowHexSpecifier; + if (resultType == typeof(BigInteger)) + { + NumberStyles style = NumberStyles.Integer | NumberStyles.AllowThousands; return BigInteger.Parse(strToConvert, style, NumberFormatInfo.InvariantInfo); } - // Fallback conversion for regular numeric types. return GetIntegerSystemConverter(resultType).ConvertFrom(strToConvert); } @@ -3684,7 +3688,7 @@ private static object ConvertEnumerableToEnum(object valueToConvert, return ConvertStringToEnum(sbResult.ToString(), resultType, recursion, originalValueToConvert, formatProvider, backupTable); } - private class PSMethodToDelegateConverter + private sealed class PSMethodToDelegateConverter { // Index of the matching overload method. private readonly int _matchIndex; @@ -3744,7 +3748,7 @@ internal Delegate Convert(object valueToConvert, } } - private class ConvertViaParseMethod + private sealed class ConvertViaParseMethod { // TODO - use an ETS wrapper that generates a dynamic method internal MethodInfo parse; @@ -3810,7 +3814,7 @@ internal object ConvertWithoutCulture(object valueToConvert, } } - private class ConvertViaConstructor + private sealed class ConvertViaConstructor { internal Func TargetCtorLambda; @@ -3849,12 +3853,12 @@ internal object Convert(object valueToConvert, /// Create a IList to hold all elements, and use the IList to create the object of the resultType. /// The reason for using IList is that it can work on constructors that takes IEnumerable[T], ICollection[T] or IList[T]. /// - /// + /// /// When get to this method, we know the fromType and the toType meet the following two conditions: /// 1. toType is a closed generic type and it has a constructor that takes IEnumerable[T], ICollection[T] or IList[T] /// 2. fromType is System.Array, System.Object[] or it's the same as the element type of toType - /// - private class ConvertViaIEnumerableConstructor + /// + private sealed class ConvertViaIEnumerableConstructor { internal Func ListCtorLambda; internal Func TargetCtorLambda; @@ -3947,7 +3951,7 @@ internal object Convert(object valueToConvert, } } - private class ConvertViaNoArgumentConstructor + private sealed class ConvertViaNoArgumentConstructor { private readonly Func _constructor; @@ -3984,32 +3988,46 @@ internal object Convert(object valueToConvert, // - It's in FullLanguage but not because it's part of a parameter binding that is transitioning from ConstrainedLanguage to FullLanguage // When this is invoked from a parameter binding in transition from ConstrainedLanguage environment to FullLanguage command, we disallow // the property conversion because it's dangerous. - if (ecFromTLS == null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding)) + bool canProceedWithConversion = ecFromTLS == null || (ecFromTLS.LanguageMode == PSLanguageMode.FullLanguage && !ecFromTLS.LanguageModeTransitionInParameterBinding); + if (!canProceedWithConversion) { - result = _constructor(); - var psobject = valueToConvert as PSObject; - if (psobject != null) - { - // Use PSObject properties to perform conversion. - SetObjectProperties(result, psobject, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, formatProvider, recursion, ignoreUnknownMembers); - } - else + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) { - // Use provided property dictionary to perform conversion. - // 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 - IDictionary properties = valueToConvert as IDictionary; - SetObjectProperties(result, properties, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: false); + throw InterpreterError.NewInterpreterException( + valueToConvert, + typeof(RuntimeException), + errorPosition: null, + "HashtableToObjectConversionNotSupportedInDataSection", + ParserStrings.HashtableToObjectConversionNotSupportedInDataSection, + resultType.ToString()); } - typeConversion.WriteLine("Constructor result: \"{0}\".", result); + // When in audit mode, we report but don't enforce, so we will proceed with the conversion. + SystemPolicy.LogWDACAuditMessage( + context: ecFromTLS, + title: ExtendedTypeSystem.WDACHashTypeLogTitle, + message: StringUtil.Format(ExtendedTypeSystem.WDACHashTypeLogMessage, resultType.FullName), + fqid: "LanguageHashtableConversionNotAllowed", + dropIntoDebugger: true); + } + + result = _constructor(); + var psobject = valueToConvert as PSObject; + if (psobject != null) + { + // Use PSObject properties to perform conversion. + SetObjectProperties(result, psobject, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, formatProvider, recursion, ignoreUnknownMembers); } else { - RuntimeException rte = InterpreterError.NewInterpreterException(valueToConvert, typeof(RuntimeException), null, - "HashtableToObjectConversionNotSupportedInDataSection", ParserStrings.HashtableToObjectConversionNotSupportedInDataSection, resultType.ToString()); - throw rte; + // Use provided property dictionary to perform conversion. + // 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 + IDictionary properties = valueToConvert as IDictionary; + SetObjectProperties(result, properties, resultType, CreateMemberNotFoundError, CreateMemberSetValueError, enableMethodCall: false); } + typeConversion.WriteLine("Constructor result: \"{0}\".", result); + return result; } catch (TargetInvocationException ex) @@ -4050,7 +4068,7 @@ internal object Convert(object valueToConvert, } } - private class ConvertViaCast + private sealed class ConvertViaCast { internal MethodInfo cast; @@ -4130,7 +4148,7 @@ private static object ConvertNumericIConvertible(object valueToConvert, } } - private class ConvertCheckingForCustomConverter + private sealed class ConvertCheckingForCustomConverter { internal PSConverter tryfirstConverter; internal PSConverter fallbackConverter; @@ -4673,7 +4691,7 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T Type propType; if (TypeResolver.TryResolveType(property.TypeNameOfValue, out propType)) { - if (formatProvider == null) { formatProvider = CultureInfo.InvariantCulture; } + formatProvider ??= CultureInfo.InvariantCulture; try { @@ -4698,6 +4716,12 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T } } + // treat AutomationNull.Value as null for consistency + if (propValue == AutomationNull.Value) + { + propValue = null; + } + property.Value = propValue; } else @@ -4735,18 +4759,23 @@ internal static PSObject SetObjectProperties(object o, IDictionary properties, T return pso; } - private static string GetAvailableProperties(PSObject pso) + private static string GetSettableProperties(PSObject pso) { + if (pso is null || pso.Properties is null) + { + return string.Empty; + } + StringBuilder availableProperties = new StringBuilder(); bool first = true; - if (pso != null && pso.Properties != null) + foreach (PSPropertyInfo p in pso.Properties) { - foreach (PSPropertyInfo p in pso.Properties) + if (p.IsSettable) { if (!first) { - availableProperties.Append(" , "); + availableProperties.Append(", "); } availableProperties.Append("[" + p.Name + " <" + p.TypeNameOfValue + ">]"); @@ -4894,8 +4923,26 @@ internal static Tuple GetInvalidCastMessages(object valueToConve typeConversion.WriteLine("Type Conversion failed."); errorId = "ConvertToFinalInvalidCastException"; - errorMsg = StringUtil.Format(ExtendedTypeSystem.InvalidCastException, valueToConvert.ToString(), - ObjectToTypeNameString(valueToConvert), resultType.ToString()); + + string valueToConvertTypeName = ObjectToTypeNameString(valueToConvert); + string resultTypeName = resultType.ToString(); + + if (resultType == typeof(SecureString) || resultType == typeof(PSCredential)) + { + errorMsg = StringUtil.Format( + ExtendedTypeSystem.InvalidCastExceptionWithoutValue, + valueToConvertTypeName, + resultTypeName); + } + else + { + errorMsg = StringUtil.Format( + ExtendedTypeSystem.InvalidCastException, + valueToConvert.ToString(), + valueToConvertTypeName, + resultTypeName); + } + return Tuple.Create(errorId, errorMsg); } @@ -5633,33 +5680,33 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) PSConverter converter = null; ConversionRank rank = ConversionRank.None; - // If we've ever used ConstrainedLanguage, check if the target type is allowed + // If we've ever used ConstrainedLanguage, check if the target type is allowed. if (ExecutionContext.HasEverUsedConstrainedLanguage) { var context = LocalPipeline.GetExecutionContextFromTLS(); - - if ((context != null) && (context.LanguageMode == PSLanguageMode.ConstrainedLanguage)) + if (context?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if ((toType != typeof(object)) && - (toType != typeof(object[])) && - (!CoreTypes.Contains(toType))) + if (toType != typeof(object) && + toType != typeof(object[]) && + !CoreTypes.Contains(toType)) { - converter = ConvertNotSupportedConversion; - rank = ConversionRank.None; - return CacheConversion(fromType, toType, converter, rank); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + converter = ConvertNotSupportedConversion; + rank = ConversionRank.None; + return CacheConversion(fromType, toType, converter, rank); + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ExtendedTypeSystem.WDACTypeConversionLogTitle, + message: StringUtil.Format(ExtendedTypeSystem.WDACTypeConversionLogMessage, fromType.FullName, toType.FullName), + fqid: "LanguageTypeConversionNotAllowed", + dropIntoDebugger: true); } } } - // Assemblies in CoreCLR might not allow reflection execution on their internal types. - if (!TypeResolver.IsPublic(toType) && DotNetAdapter.DisallowPrivateReflection(toType)) - { - // If the type is non-public and reflection execution is not allowed on it, then we return - // 'ConvertNoConversion', because we won't be able to invoke constructor, methods or set - // properties on an instance of this type through reflection. - return CacheConversion(fromType, toType, ConvertNoConversion, ConversionRank.None); - } - PSConverter valueDependentConversion = null; ConversionRank valueDependentRank = ConversionRank.None; IConversionData conversionData = FigureLanguageConversion(fromType, toType, out valueDependentConversion, out valueDependentRank); @@ -5745,10 +5792,7 @@ internal static IConversionData FigureConversion(Type fromType, Type toType) } } - if (converter == null) - { - converter = FigurePropertyConversion(fromType, toType, ref rank); - } + converter ??= FigurePropertyConversion(fromType, toType, ref rank); if (TypeConverterPossiblyExists(fromType) || TypeConverterPossiblyExists(toType) || (converter != null && valueDependentConversion != null)) diff --git a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs index c591a6963ec..9b69ee168d7 100644 --- a/src/System.Management.Automation/engine/ManagementObjectAdapter.cs +++ b/src/System.Management.Automation/engine/ManagementObjectAdapter.cs @@ -172,7 +172,7 @@ protected override T GetMember(object obj, string memberName) { tracer.WriteLine("Getting member with name {0}", memberName); - if (!(obj is ManagementBaseObject mgmtObject)) + if (obj is not ManagementBaseObject mgmtObject) { return null; } @@ -364,7 +364,7 @@ protected override object PropertyGet(PSProperty property) /// Instructs the adapter to convert before setting, if the adapter supports conversion. protected override void PropertySet(PSProperty property, object setValue, bool convertIfPossible) { - if (!(property.baseObject is ManagementBaseObject mObj)) + if (property.baseObject is not ManagementBaseObject mObj) { throw new SetValueInvocationException("CannotSetNonManagementObjectMsg", null, @@ -454,7 +454,7 @@ protected static CacheTable GetInstanceMethodTable(ManagementBaseObject wmiObjec // unique identifier for identifying this ManagementObject's type ManagementPath classPath = wmiObject.ClassPath; - string key = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", classPath.Path, staticBinding.ToString()); + string key = string.Create(CultureInfo.InvariantCulture, $"{classPath.Path}#{staticBinding}"); typeTable = (CacheTable)s_instanceMethodCacheTable[key]; if (typeTable != null) @@ -577,8 +577,11 @@ protected static string GetEmbeddedObjectTypeName(PropertyData pData) try { string cimType = (string)pData.Qualifiers["cimtype"].Value; - result = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", - typeof(ManagementObject).FullName, cimType.Replace("object:", string.Empty)); + result = string.Format( + CultureInfo.InvariantCulture, + "{0}#{1}", + typeof(ManagementObject).FullName, + cimType.Replace("object:", string.Empty)); } catch (ManagementException) { @@ -1162,9 +1165,7 @@ protected override PSProperty DoGetProperty(ManagementBaseObject wmiObject, stri PSLevel.Informational, PSTask.None, PSKeyword.UseAlwaysOperational, - string.Format(CultureInfo.InvariantCulture, - "ManagementBaseObjectAdapter::DoGetProperty::PropertyName:{0}, Exception:{1}, StackTrace:{2}", - propertyName, e.Message, e.StackTrace), + string.Create(CultureInfo.InvariantCulture, $"ManagementBaseObjectAdapter::DoGetProperty::PropertyName:{propertyName}, Exception:{e.Message}, StackTrace:{e.StackTrace}"), string.Empty, string.Empty); // ignore the exception. diff --git a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs index f2d20c68ec9..d2b972a118d 100644 --- a/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs +++ b/src/System.Management.Automation/engine/MergedCommandParameterMetadata.cs @@ -163,6 +163,13 @@ internal Collection AddMetadataForBinder( /// private uint _nextAvailableParameterSetIndex; + /// + /// The maximum number of parameter sets allowed. Limit is set by the use + /// of a uint bitmask to store which parameter sets a parameter is included in. + /// See . + /// + private const uint MaxParameterSetCount = 32; + /// /// Gets the number of parameter sets that were declared for the command. /// @@ -228,7 +235,7 @@ private int AddParameterSetToMap(string parameterSetName) // A parameter set name should only be added once if (index == -1) { - if (_nextAvailableParameterSetIndex == uint.MaxValue) + if (_nextAvailableParameterSetIndex >= MaxParameterSetCount) { // Don't let the parameter set index overflow ParsingMetadataException parsingException = diff --git a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs index 084c8c4674e..8a5f29e2b16 100644 --- a/src/System.Management.Automation/engine/Modules/AnalysisCache.cs +++ b/src/System.Management.Automation/engine/Modules/AnalysisCache.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -33,13 +34,12 @@ internal static class AnalysisCache // This dictionary shouldn't see much use, so low concurrency and capacity private static readonly ConcurrentDictionary s_modulesBeingAnalyzed = - new ConcurrentDictionary( /*concurrency*/1, /*capacity*/2, StringComparer.OrdinalIgnoreCase); + new(concurrencyLevel: 1, capacity: 2, StringComparer.OrdinalIgnoreCase); - internal static readonly char[] InvalidCommandNameCharacters = new[] - { - '#', ',', '(', ')', '{', '}', '[', ']', '&', '/', '\\', '$', '^', ';', ':', - '"', '\'', '<', '>', '|', '?', '@', '`', '*', '%', '+', '=', '~' - }; + internal static readonly SearchValues InvalidCommandNameCharacters = SearchValues.Create("#,(){}[]&/\\$^;:\"'<>|?@`*%+=~"); + + internal static bool ContainsInvalidCommandNameCharacters(ReadOnlySpan text) + => text.ContainsAny(InvalidCommandNameCharacters); internal static ConcurrentDictionary GetExportedCommands(string modulePath, bool testOnly, ExecutionContext context) { @@ -194,7 +194,7 @@ internal static bool ModuleIsEditionIncompatible(string modulePath, Hashtable mo internal static bool ModuleAnalysisViaGetModuleRequired(object modulePathObj, bool hadCmdlets, bool hadFunctions, bool hadAliases) { - if (!(modulePathObj is string modulePath)) + if (modulePathObj is not string modulePath) return true; if (modulePath.EndsWith(StringLiterals.PowerShellModuleFileExtension, StringComparison.OrdinalIgnoreCase)) @@ -256,7 +256,7 @@ private static bool CheckModulesTypesInManifestAgainstExportedCommands(Hashtable return ModuleAnalysisViaGetModuleRequired(nestedModule, hadCmdlets, hadFunctions, hadAliases); } - if (!(nestedModules is object[] nestedModuleArray)) + if (nestedModules is not object[] nestedModuleArray) return true; foreach (var element in nestedModuleArray) @@ -345,7 +345,7 @@ private static ConcurrentDictionary AnalyzeScriptModule(st { if (SessionStateUtilities.MatchesAnyWildcardPattern(command, scriptAnalysisPatterns, true)) { - if (command.IndexOfAny(InvalidCommandNameCharacters) < 0) + if (!ContainsInvalidCommandNameCharacters(command)) { result[command] = CommandTypes.Function; } @@ -357,10 +357,10 @@ private static ConcurrentDictionary AnalyzeScriptModule(st { var commandName = pair.Key; // These are already filtered - if (commandName.IndexOfAny(InvalidCommandNameCharacters) < 0) + if (!ContainsInvalidCommandNameCharacters(commandName)) { result.AddOrUpdate(commandName, CommandTypes.Alias, - (_, existingCommandType) => existingCommandType | CommandTypes.Alias); + static (_, existingCommandType) => existingCommandType | CommandTypes.Alias); } } @@ -375,7 +375,7 @@ private static ConcurrentDictionary AnalyzeScriptModule(st { var command = Path.GetFileNameWithoutExtension(item); result.AddOrUpdate(command, CommandTypes.ExternalScript, - (_, existingCommandType) => existingCommandType | CommandTypes.ExternalScript); + static (_, existingCommandType) => existingCommandType | CommandTypes.ExternalScript); } } catch (UnauthorizedAccessException) @@ -384,8 +384,10 @@ private static ConcurrentDictionary AnalyzeScriptModule(st } } - var exportedClasses = new ConcurrentDictionary( /*concurrency*/ - 1, scriptAnalysis.DiscoveredClasses.Count, StringComparer.OrdinalIgnoreCase); + ConcurrentDictionary exportedClasses = new( + concurrencyLevel: 1, + capacity: scriptAnalysis.DiscoveredClasses.Count, + StringComparer.OrdinalIgnoreCase); foreach (var exportedClass in scriptAnalysis.DiscoveredClasses) { exportedClasses[exportedClass.Name] = exportedClass.TypeAttributes; @@ -640,7 +642,7 @@ private static bool GetModuleEntryFromCache(string modulePath, out DateTime last } } - internal class AnalysisCacheData + internal sealed class AnalysisCacheData { private static byte[] GetHeader() { @@ -662,6 +664,11 @@ private static byte[] GetHeader() public void QueueSerialization() { + if (string.IsNullOrEmpty(s_cacheStoreLocation)) + { + return; + } + // We expect many modules to rapidly call for serialization. // Instead of doing it right away, we'll queue a task that starts writing // after it seems like we've stopped adding stuff to write out. This is @@ -1090,7 +1097,7 @@ static AnalysisCacheData() // When multiple copies of pwsh are on the system, they should use their own copy of the cache. // Append hash of `$PSHOME` to cacheFileName. string hashString = CRC32Hash.ComputeHash(Utils.DefaultPowerShellAppBase); - cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString); + cacheFileName = string.Create(CultureInfo.InvariantCulture, $"{cacheFileName}-{hashString}"); if (ExperimentalFeature.EnabledExperimentalFeatureNames.Count > 0) { @@ -1116,10 +1123,10 @@ static AnalysisCacheData() // Use CRC32 because it's faster. // It's very unlikely to get collision from hashing the combinations of enabled features names. hashString = CRC32Hash.ComputeHash(allNames); - cacheFileName = string.Format(CultureInfo.InvariantCulture, "{0}-{1}", cacheFileName, hashString); + cacheFileName = string.Create(CultureInfo.InvariantCulture, $"{cacheFileName}-{hashString}"); } - s_cacheStoreLocation = Path.Combine(Platform.CacheDirectory, cacheFileName); + Platform.TryDeriveFromCache(cacheFileName, out s_cacheStoreLocation); } } diff --git a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs index 8520e39258b..3b47bc37f10 100644 --- a/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ExportModuleMemberCommand.cs @@ -6,6 +6,7 @@ using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; +using System.Management.Automation.Security; // // Now define the set of commands for manipulating modules. @@ -167,9 +168,19 @@ protected override void ProcessRecord() if (Context.EngineSessionState.Module?.LanguageMode != null && Context.LanguageMode != Context.EngineSessionState.Module.LanguageMode) { - var se = new PSSecurityException(Modules.CannotExportMembersAccrossLanguageBoundaries); - var er = new ErrorRecord(se, "Modules_CannotExportMembersAccrossLanguageBoundaries", ErrorCategory.SecurityError, this); - ThrowTerminatingError(er); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + var se = new PSSecurityException(Modules.CannotExportMembersAccrossLanguageBoundaries); + var er = new ErrorRecord(se, "Modules_CannotExportMembersAccrossLanguageBoundaries", ErrorCategory.SecurityError, this); + ThrowTerminatingError(er); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACExportModuleCommandLogTitle, + message: StringUtil.Format(Modules.WDACExportModuleCommandLogMessage, Context.EngineSessionState.Module.Name, Context.EngineSessionState.Module.LanguageMode, Context.LanguageMode), + fqid: "ExportModuleMemberCmdletNotAllowed", + dropIntoDebugger: true); } ModuleIntrinsics.ExportModuleMembers(this, diff --git a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs index 663e1f4b0fe..caf7527d73e 100644 --- a/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/GetModuleCommand.cs @@ -265,7 +265,7 @@ private IEnumerable GetAvailableViaCimSessionCore(IEnumerable remoteModuleInfos = remoteModules .Select(cimModule => this.ConvertCimModuleInfoToPSModuleInfo(cimModule, cimSession.ComputerName)) - .Where(moduleInfo => moduleInfo != null); + .Where(static moduleInfo => moduleInfo != null); return remoteModuleInfos; } @@ -297,29 +297,17 @@ protected override void StopProcessing() #region IDisposable Members /// - /// Releases resources associated with this object. + /// Release all resources. /// public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases resources associated with this object. - /// - private void Dispose(bool disposing) { if (_disposed) { return; } - if (disposing) - { - _cancellationTokenSource.Dispose(); - } - + _cancellationTokenSource.Dispose(); + _disposed = true; } @@ -382,8 +370,8 @@ protected override void ProcessRecord() FullyQualifiedName[modSpecIndex] = FullyQualifiedName[modSpecIndex].WithNormalizedName(Context, SessionState.Path.CurrentLocation.Path); } - moduleSpecTable = FullyQualifiedName.ToDictionary(moduleSpecification => moduleSpecification.Name, StringComparer.OrdinalIgnoreCase); - strNames.AddRange(FullyQualifiedName.Select(spec => spec.Name)); + moduleSpecTable = FullyQualifiedName.ToDictionary(static moduleSpecification => moduleSpecification.Name, StringComparer.OrdinalIgnoreCase); + strNames.AddRange(FullyQualifiedName.Select(static spec => spec.Name)); } string[] names = strNames.Count > 0 ? strNames.ToArray() : null; @@ -515,7 +503,7 @@ private IEnumerable FilterModulesForEditionAndSpecification( // Edition check only applies to Windows System32 module path if (!SkipEditionCheck && ListAvailable && !All) { - modules = modules.Where(module => module.IsConsideredEditionCompatible); + modules = modules.Where(static module => module.IsConsideredEditionCompatible); } #endif @@ -586,24 +574,25 @@ private static IEnumerable GetCandidateModuleSpecs( } /// - /// PSEditionArgumentCompleter for PowerShell Edition names. + /// Provides argument completion for PSEdition parameter. /// public class PSEditionArgumentCompleter : IArgumentCompleter { /// - /// CompleteArgument. + /// Returns completion results for PSEdition parameter. /// - public IEnumerable CompleteArgument(string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) - { - var wordToCompletePattern = WildcardPattern.Get(string.IsNullOrWhiteSpace(wordToComplete) ? "*" : wordToComplete + "*", WildcardOptions.IgnoreCase); - - foreach (var edition in Utils.AllowedEditionValues) - { - if (wordToCompletePattern.IsMatch(edition)) - { - yield return new CompletionResult(edition, edition, CompletionResultType.Text, edition); - } - } - } + /// 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: Utils.AllowedEditionValues); } } diff --git a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs index 365d6e7642c..532079d1a77 100644 --- a/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/ImportModuleCommand.cs @@ -548,32 +548,15 @@ private void ImportModule_ViaLocalModuleInfo(ImportModuleOptions importModuleOpt private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, Assembly suppliedAssembly) { bool moduleLoaded = false; + string moduleName = "dynamic_code_module_" + suppliedAssembly.FullName; + // Loop through Module Cache to ensure that the module is not already imported. - if (suppliedAssembly != null && Context.Modules.ModuleTable != null) + foreach (KeyValuePair pair in Context.Modules.ModuleTable) { - foreach (KeyValuePair pair in Context.Modules.ModuleTable) + if (pair.Value.Path == string.Empty) { - // if the module in the moduleTable is an assembly module without path, the moduleName is the key. - string moduleName = "dynamic_code_module_" + suppliedAssembly; - if (pair.Value.Path == string.Empty) - { - if (pair.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) - { - moduleLoaded = true; - if (BasePassThru) - { - WriteObject(pair.Value); - } - - break; - } - else - { - continue; - } - } - - if (pair.Value.Path.Equals(suppliedAssembly.Location, StringComparison.OrdinalIgnoreCase)) + // If the module in the moduleTable is an assembly module without path, the moduleName is the key. + if (pair.Key.Equals(moduleName, StringComparison.OrdinalIgnoreCase)) { moduleLoaded = true; if (BasePassThru) @@ -583,13 +566,26 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A break; } + + continue; + } + + if (pair.Value.Path.Equals(suppliedAssembly.Location, StringComparison.OrdinalIgnoreCase)) + { + moduleLoaded = true; + if (BasePassThru) + { + WriteObject(pair.Value); + } + + break; } } if (!moduleLoaded) { PSModuleInfo module = LoadBinaryModule( - trySnapInName: false, + parentModule: null, moduleName: null, fileName: null, suppliedAssembly, @@ -597,15 +593,13 @@ private void ImportModule_ViaAssembly(ImportModuleOptions importModuleOptions, A ss: null, importModuleOptions, ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - this.BasePrefix, - loadTypes: false, - loadFormats: false, + BasePrefix, out bool found); - if (found && module != null) + if (found && module is not null) { // Add it to all module tables ... - AddModuleToModuleTables(this.Context, this.TargetSessionState.Internal, module); + AddModuleToModuleTables(Context, TargetSessionState.Internal, module); if (BasePassThru) { WriteObject(module); @@ -625,7 +619,7 @@ private PSModuleInfo ImportModule_LocallyViaName_WithTelemetry(ImportModuleOptio // avoid double reporting for WinCompat modules that go through CommandDiscovery\AutoloadSpecifiedModule if (!foundModule.IsWindowsPowerShellCompatModule) { - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, foundModule.Name); + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, foundModule); #if LEGACYTELEMETRY TelemetryAPI.ReportModuleLoad(foundModule); #endif @@ -637,6 +631,8 @@ private PSModuleInfo ImportModule_LocallyViaName_WithTelemetry(ImportModuleOptio private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModuleOptions, string name) { + bool shallWriteError = !importModuleOptions.SkipSystem32ModulesAndSuppressError; + try { bool found = false; @@ -665,21 +661,18 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul } } - if (rootedPath == null) + // If null check for full-qualified paths - either absolute or relative + rootedPath ??= ResolveRootedFilePath(name, this.Context); + + bool alreadyLoaded = false; + var manifestProcessingFlags = ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.NullOnFirstError; + if (shallWriteError) { - // Check for full-qualified paths - either absolute or relative - rootedPath = ResolveRootedFilePath(name, this.Context); + manifestProcessingFlags |= ManifestProcessingFlags.WriteErrors; } - bool alreadyLoaded = false; if (!string.IsNullOrEmpty(rootedPath)) { - // TODO/FIXME: use IsModuleAlreadyLoaded to get consistent behavior - // TODO/FIXME: (for example checking ModuleType != Manifest below seems incorrect - cdxml modules also declare their own version) - // PSModuleInfo alreadyLoadedModule = null; - // TryGetFromModuleTable(rootedPath, out alreadyLoadedModule); - // if (!BaseForce && IsModuleAlreadyLoaded(alreadyLoadedModule)) - // If the module has already been loaded, just emit it and continue... if (!BaseForce && TryGetFromModuleTable(rootedPath, out PSModuleInfo module)) { @@ -726,9 +719,14 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul RemoveModule(moduleToRemove); } - foundModule = LoadModule(rootedPath, null, this.BasePrefix, null, ref importModuleOptions, - ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - out found); + foundModule = LoadModule( + fileName: rootedPath, + moduleBase: null, + prefix: BasePrefix, + ss: null, /*SessionState*/ + ref importModuleOptions, + manifestProcessingFlags, + out found); } else if (Directory.Exists(rootedPath)) { @@ -739,21 +737,24 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul } // Load the latest valid version if it is a multi-version module directory - foundModule = LoadUsingMultiVersionModuleBase(rootedPath, - ManifestProcessingFlags.LoadElements | - ManifestProcessingFlags.WriteErrors | - ManifestProcessingFlags.NullOnFirstError, - importModuleOptions, out found); + foundModule = LoadUsingMultiVersionModuleBase(rootedPath, manifestProcessingFlags, importModuleOptions, out found); if (!found) { // If the path is a directory, double up the end of the string // then try to load that using extensions... rootedPath = Path.Combine(rootedPath, Path.GetFileName(rootedPath)); - foundModule = LoadUsingExtensions(null, rootedPath, rootedPath, null, null, this.BasePrefix, /*SessionState*/ null, - importModuleOptions, - ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - out found); + foundModule = LoadUsingExtensions( + parentModule: null, + moduleName: rootedPath, + fileBaseName: rootedPath, + extension: null, + moduleBase: null, + prefix: BasePrefix, + ss: null, /*SessionState*/ + importModuleOptions, + manifestProcessingFlags, + out found); } } } @@ -763,7 +764,7 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul // Check if module could be a snapin. This was the case for PowerShell version 2 engine modules. if (InitialSessionState.IsEngineModule(name)) { - PSSnapInInfo snapin = ModuleCmdletBase.GetEngineSnapIn(Context, name); + PSSnapInInfo snapin = Context.CurrentRunspace.InitialSessionState.GetPSSnapIn(name); // Return the command if we found a module if (snapin != null) @@ -787,16 +788,28 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul // If there is no extension, we'll have to search using the extensions if (!string.IsNullOrEmpty(Path.GetExtension(name))) { - foundModule = LoadModule(name, null, this.BasePrefix, null, ref importModuleOptions, - ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - out found); + foundModule = LoadModule( + fileName: name, + moduleBase: null, + prefix: BasePrefix, + ss: null, /*SessionState*/ + ref importModuleOptions, + manifestProcessingFlags, + out found); } else { - foundModule = LoadUsingExtensions(null, name, name, null, null, this.BasePrefix, /*SessionState*/ null, - importModuleOptions, - ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - out found); + foundModule = LoadUsingExtensions( + parentModule: null, + moduleName: name, + fileBaseName: name, + extension: null, + moduleBase: null, + prefix: BasePrefix, + ss: null, /*SessionState*/ + importModuleOptions, + manifestProcessingFlags, + out found); } } else @@ -808,14 +821,17 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul this.AddToAppDomainLevelCache = true; } - found = LoadUsingModulePath(found, modulePath, name, /* SessionState*/ null, - importModuleOptions, - ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | ManifestProcessingFlags.NullOnFirstError, - out foundModule); + found = LoadUsingModulePath( + modulePath, + name, + ss: null, /* SessionState*/ + importModuleOptions, + manifestProcessingFlags, + out foundModule); } } - if (!found) + if (!found && shallWriteError) { ErrorRecord er = null; string message = null; @@ -857,8 +873,10 @@ private PSModuleInfo ImportModule_LocallyViaName(ImportModuleOptions importModul } catch (PSInvalidOperationException e) { - ErrorRecord er = new ErrorRecord(e.ErrorRecord, e); - WriteError(er); + if (shallWriteError) + { + WriteError(new ErrorRecord(e.ErrorRecord, e)); + } } return null; @@ -875,7 +893,7 @@ private PSModuleInfo ImportModule_LocallyViaFQName(ImportModuleOptions importMod if (foundModule != null) { - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, foundModule.Name); + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, foundModule); SetModuleBaseForEngineModules(foundModule.Name, this.Context); } @@ -917,7 +935,7 @@ private IList ImportModule_RemotelyViaPsrpSession( // Send telemetry on the imported modules foreach (PSModuleInfo moduleInfo in remotelyImportedModules) { - ApplicationInsightsTelemetry.SendTelemetryMetric(usingWinCompat ? TelemetryType.WinCompatModuleLoad : TelemetryType.ModuleLoad, moduleInfo.Name); + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(usingWinCompat ? TelemetryType.WinCompatModuleLoad : TelemetryType.ModuleLoad, moduleInfo); } return remotelyImportedModules; @@ -977,7 +995,7 @@ private IList ImportModule_RemotelyViaPsrpSession( string errorMessageTemplate = string.Format( CultureInfo.InvariantCulture, Modules.RemoteDiscoveryRemotePsrpCommandFailed, - string.Format(CultureInfo.InvariantCulture, "Import-Module -Name '{0}'", moduleName)); + string.Create(CultureInfo.InvariantCulture, $"Import-Module -Name '{moduleName}'")); remotelyImportedModules = RemoteDiscoveryHelper.InvokePowerShell( powerShell, this, @@ -1308,8 +1326,8 @@ private void ImportModule_RemotelyViaCimSession( this, this.CancellationToken).ToList(); - IEnumerable remotePsCimModules = remoteModules.Where(cimModule => cimModule.IsPsCimModule); - IEnumerable remotePsrpModuleNames = remoteModules.Where(cimModule => !cimModule.IsPsCimModule).Select(cimModule => cimModule.ModuleName); + IEnumerable remotePsCimModules = remoteModules.Where(static cimModule => cimModule.IsPsCimModule); + IEnumerable remotePsrpModuleNames = remoteModules.Where(static cimModule => !cimModule.IsPsCimModule).Select(static cimModule => cimModule.ModuleName); foreach (string psrpModuleName in remotePsrpModuleNames) { string errorMessage = string.Format( @@ -1327,7 +1345,7 @@ private void ImportModule_RemotelyViaCimSession( // // report an error if some modules were not found // - IEnumerable allFoundModuleNames = remoteModules.Select(cimModule => cimModule.ModuleName).ToList(); + IEnumerable allFoundModuleNames = remoteModules.Select(static cimModule => cimModule.ModuleName).ToList(); foreach (string requestedModuleName in moduleNames) { var wildcardPattern = WildcardPattern.Get(requestedModuleName, WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); @@ -1348,20 +1366,32 @@ private void ImportModule_RemotelyViaCimSession( foreach (RemoteDiscoveryHelper.CimModule remoteCimModule in remotePsCimModules) { ImportModule_RemotelyViaCimModuleData(importModuleOptions, remoteCimModule, cimSession); - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, remoteCimModule.ModuleName); + // we don't know the version of the module + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, remoteCimModule.ModuleName); } } - private bool IsPs1xmlFileHelper_IsPresentInEntries(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, IEnumerable manifestEntries) + private bool IsPs1xmlFileHelper_IsPresentInEntries(RemoteDiscoveryHelper.CimModuleFile cimModuleFile, List manifestEntries) { - if (manifestEntries.Any(s => s.EndsWith(cimModuleFile.FileName, StringComparison.OrdinalIgnoreCase))) + const string ps1xmlExt = ".ps1xml"; + string fileName = cimModuleFile.FileName; + + foreach (string entry in manifestEntries) { - return true; + if (entry.EndsWith(fileName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } } - if (manifestEntries.Any(s => FixupFileName(string.Empty, s, ".ps1xml", isImportingModule: true).EndsWith(cimModuleFile.FileName, StringComparison.OrdinalIgnoreCase))) + foreach (string entry in manifestEntries) { - return true; + string tempName = entry.EndsWith(ps1xmlExt, StringComparison.OrdinalIgnoreCase) ? entry : entry + ps1xmlExt; + string resolvedPath = ResolveRootedFilePath(tempName, Context); + if (resolvedPath is not null && resolvedPath.EndsWith(fileName, StringComparison.OrdinalIgnoreCase)) + { + return true; + } } return false; @@ -1380,10 +1410,7 @@ private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFil goodEntries = new List(); } - if (goodEntries == null) - { - goodEntries = new List(); - } + goodEntries ??= new List(); List badEntries; if (!this.GetListOfStringsFromData(manifestData, null, badKey, 0, out badEntries)) @@ -1391,10 +1418,7 @@ private bool IsPs1xmlFileHelper(RemoteDiscoveryHelper.CimModuleFile cimModuleFil badEntries = new List(); } - if (badEntries == null) - { - badEntries = new List(); - } + badEntries ??= new List(); bool presentInGoodEntries = IsPs1xmlFileHelper_IsPresentInEntries(cimModuleFile, goodEntries); bool presentInBadEntries = IsPs1xmlFileHelper_IsPresentInEntries(cimModuleFile, badEntries); @@ -1756,28 +1780,16 @@ protected override void StopProcessing() #region IDisposable Members /// - /// Releases resources associated with this object. + /// Release all resources. /// public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Releases resources associated with this object. - /// - private void Dispose(bool disposing) { if (_disposed) { return; } - if (disposing) - { - _cancellationTokenSource.Dispose(); - } + _cancellationTokenSource.Dispose(); _disposed = true; } @@ -1842,7 +1854,7 @@ protected override void ProcessRecord() // of doing Get-Module -list foreach (PSModuleInfo module in ModuleInfo) { - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, module.Name); + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, module); RemoteDiscoveryHelper.DispatchModuleInfoProcessing( module, localAction: () => @@ -1868,13 +1880,11 @@ protected override void ProcessRecord() else if (this.ParameterSetName.Equals(ParameterSet_Assembly, StringComparison.OrdinalIgnoreCase)) { // Now load all of the supplied assemblies... - if (Assembly != null) + foreach (Assembly suppliedAssembly in Assembly) { - foreach (Assembly suppliedAssembly in Assembly) - { - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, suppliedAssembly.GetName().Name); - ImportModule_ViaAssembly(importModuleOptions, suppliedAssembly); - } + // we don't know what the version of the module is. + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, suppliedAssembly.GetName().Name); + ImportModule_ViaAssembly(importModuleOptions, suppliedAssembly); } } else if (this.ParameterSetName.Equals(ParameterSet_Name, StringComparison.OrdinalIgnoreCase)) @@ -1904,7 +1914,7 @@ protected override void ProcessRecord() ImportModule_RemotelyViaPsrpSession(importModuleOptions, null, FullyQualifiedName, this.PSSession); foreach (ModuleSpecification modulespec in FullyQualifiedName) { - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ModuleLoad, modulespec.Name); + ApplicationInsightsTelemetry.SendModuleTelemetryMetric(TelemetryType.ModuleLoad, modulespec.Name); } } else if (this.ParameterSetName.Equals(ParameterSet_ViaWinCompat, StringComparison.OrdinalIgnoreCase) @@ -1946,27 +1956,26 @@ private bool IsModuleInDenyList(string[] moduleDenyList, string moduleName, Modu return match; } - private List FilterModuleCollection(IEnumerable moduleCollection) + private IEnumerable FilterModuleCollection(IEnumerable moduleCollection) { - List filteredModuleCollection = null; - if (moduleCollection != null) + if (moduleCollection is null) { - // the ModuleDeny list is cached in PowerShellConfig object - string[] moduleDenyList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityModuleDenyList(); - if (moduleDenyList?.Any() != true) - { - filteredModuleCollection = new List(moduleCollection); - } - else + return null; + } + + // The ModuleDeny list is cached in PowerShellConfig object + string[] moduleDenyList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityModuleDenyList(); + if (moduleDenyList is null || moduleDenyList.Length == 0) + { + return moduleCollection; + } + + var filteredModuleCollection = new List(); + foreach (var module in moduleCollection) + { + if (!IsModuleInDenyList(moduleDenyList, module as string, module as ModuleSpecification)) { - filteredModuleCollection = new List(); - foreach (var module in moduleCollection) - { - if (!IsModuleInDenyList(moduleDenyList, module as string, module as ModuleSpecification)) - { - filteredModuleCollection.Add(module); - } - } + filteredModuleCollection.Add(module); } } @@ -1978,38 +1987,73 @@ private void PrepareNoClobberWinCompatModuleImport(string moduleName, ModuleSpec Debug.Assert(string.IsNullOrEmpty(moduleName) ^ (moduleSpec == null), "Either moduleName or moduleSpec must be specified"); // moduleName can be just a module name and it also can be a full path to psd1 from which we need to extract the module name - string coreModuleToLoad = ModuleIntrinsics.GetModuleName(moduleSpec == null ? moduleName : moduleSpec.Name); + string moduleToLoad = ModuleIntrinsics.GetModuleName(moduleSpec is null ? moduleName : moduleSpec.Name); + + var isBuiltInModule = BuiltInModules.TryGetValue(moduleToLoad, out string normalizedName); + if (isBuiltInModule) + { + moduleToLoad = normalizedName; + } - var isModuleToLoadEngineModule = InitialSessionState.IsEngineModule(coreModuleToLoad); string[] noClobberModuleList = PowerShellConfig.Instance.GetWindowsPowerShellCompatibilityNoClobberModuleList(); - if (isModuleToLoadEngineModule || ((noClobberModuleList != null) && noClobberModuleList.Contains(coreModuleToLoad, StringComparer.OrdinalIgnoreCase))) + if (isBuiltInModule || noClobberModuleList?.Contains(moduleToLoad, StringComparer.OrdinalIgnoreCase) == true) { - // if it is one of engine modules - first try to load it from $PSHOME\Modules - // otherwise rely on $env:PSModulePath (in which WinPS module location has to go after CorePS module location) - if (isModuleToLoadEngineModule) + bool shouldLoadModuleLocally = true; + if (isBuiltInModule) { - string expectedCoreModulePath = Path.Combine(ModuleIntrinsics.GetPSHomeModulePath(), coreModuleToLoad); - if (Directory.Exists(expectedCoreModulePath)) + PSSnapInInfo loadedSnapin = Context.CurrentRunspace.InitialSessionState.GetPSSnapIn(moduleToLoad); + shouldLoadModuleLocally = loadedSnapin is null; + + if (shouldLoadModuleLocally) { - coreModuleToLoad = expectedCoreModulePath; + // If it is one of built-in modules, first try loading it from $PSHOME\Modules, otherwise rely on $env:PSModulePath. + string expectedCoreModulePath = Path.Combine(ModuleIntrinsics.GetPSHomeModulePath(), moduleToLoad); + if (Directory.Exists(expectedCoreModulePath)) + { + moduleToLoad = expectedCoreModulePath; + } } } - if (moduleSpec == null) + if (shouldLoadModuleLocally) { - ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, coreModuleToLoad); - } - else - { - ModuleSpecification tmpModuleSpec = new ModuleSpecification() + // Here we want to load a core-edition compatible version of the module, so the loading procedure will skip + // the 'System32' module path when searching. Also, we want to suppress writing out errors in case that a + // core-compatible version of the module cannot be found, because: + // 1. that's OK as long as it's not a PowerShell built-in module such as the 'Utility' moudle; + // 2. the error message will be confusing to the user. + bool savedValue = importModuleOptions.SkipSystem32ModulesAndSuppressError; + importModuleOptions.SkipSystem32ModulesAndSuppressError = true; + + PSModuleInfo moduleInfo = moduleSpec is null + ? ImportModule_LocallyViaName_WithTelemetry(importModuleOptions, moduleToLoad) + : ImportModule_LocallyViaFQName( + importModuleOptions, + new ModuleSpecification() + { + Guid = moduleSpec.Guid, + MaximumVersion = moduleSpec.MaximumVersion, + Version = moduleSpec.Version, + RequiredVersion = moduleSpec.RequiredVersion, + Name = moduleToLoad + }); + + // If we failed to load a core-compatible version of a built-in module, we should stop trying to load the + // module in 'WinCompat' mode and report an error. This could happen when a user didn't correctly deploy + // the built-in modules, which would result in very confusing errors when the module auto-loading silently + // attempts to load those built-in modules in 'WinCompat' mode from the 'System32' module path. + // + // If the loading failed but it's NOT a built-in module, then it's fine to ignore this failure and continue + // to load the module in 'WinCompat' mode. + if (moduleInfo is null && isBuiltInModule) { - Guid = moduleSpec.Guid, - MaximumVersion = moduleSpec.MaximumVersion, - Version = moduleSpec.Version, - RequiredVersion = moduleSpec.RequiredVersion, - Name = coreModuleToLoad - }; - ImportModule_LocallyViaFQName(importModuleOptions, tmpModuleSpec); + throw new InvalidOperationException( + StringUtil.Format( + Modules.CannotFindCoreCompatibleBuiltInModule, + moduleToLoad)); + } + + importModuleOptions.SkipSystem32ModulesAndSuppressError = savedValue; } importModuleOptions.NoClobberExportPSSession = true; @@ -2021,28 +2065,15 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable moduleProxyList = new List(); #if !UNIX // one of the two parameters can be passed: either ModuleNames (most of the time) or ModuleSpecifications (they are used in different parameter sets) - List filteredModuleNames = FilterModuleCollection(moduleNames); - List filteredModuleFullyQualifiedNames = FilterModuleCollection(moduleFullyQualifiedNames); + IEnumerable filteredModuleNames = FilterModuleCollection(moduleNames); + IEnumerable filteredModuleFullyQualifiedNames = FilterModuleCollection(moduleFullyQualifiedNames); // do not setup WinCompat resources if we have no modules to import - if ((filteredModuleNames?.Any() != true) && (filteredModuleFullyQualifiedNames?.Any() != true)) + if (filteredModuleNames?.Any() != true && filteredModuleFullyQualifiedNames?.Any() != true) { return moduleProxyList; } - var winPSVersionString = Utils.GetWindowsPowerShellVersionFromRegistry(); - if (!winPSVersionString.StartsWith("5.1", StringComparison.OrdinalIgnoreCase)) - { - string errorMessage = string.Format(CultureInfo.InvariantCulture, Modules.WinCompatRequredVersionError, winPSVersionString); - throw new InvalidOperationException(errorMessage); - } - - PSSession WindowsPowerShellCompatRemotingSession = CreateWindowsPowerShellCompatResources(); - if (WindowsPowerShellCompatRemotingSession == null) - { - return new List(); - } - // perform necessary preparations if module has to be imported with NoClobber mode if (filteredModuleNames != null) { @@ -2060,13 +2091,26 @@ internal override IList ImportModulesUsingWinCompat(IEnumerable(); + } + // perform the module import / proxy generation moduleProxyList = ImportModule_RemotelyViaPsrpSession(importModuleOptions, filteredModuleNames, filteredModuleFullyQualifiedNames, WindowsPowerShellCompatRemotingSession, usingWinCompat: true); foreach (PSModuleInfo moduleProxy in moduleProxyList) { moduleProxy.IsWindowsPowerShellCompatModule = true; - System.Threading.Interlocked.Increment(ref s_WindowsPowerShellCompatUsageCounter); + Interlocked.Increment(ref s_WindowsPowerShellCompatUsageCounter); string message = StringUtil.Format(Modules.WinCompatModuleWarning, moduleProxy.Name, WindowsPowerShellCompatRemotingSession.Name); WriteWarning(message); diff --git a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs index 7e7549c6589..0a1d0bfc04f 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleCmdletBase.cs @@ -16,6 +16,7 @@ using System.Management.Automation.Runspaces; using System.Management.Automation.Security; using System.Reflection; +using System.Runtime.InteropServices; using System.Text; using System.Xml; using System.Diagnostics; @@ -105,6 +106,12 @@ protected internal struct ImportModuleOptions /// Historically -AllowClobber in these scenarios was set as True. /// internal bool NoClobberExportPSSession; + + /// + /// Flag that controls skipping the System32 module path when searching a module in module paths. It also suppresses + /// writing out errors when specified. + /// + internal bool SkipSystem32ModulesAndSuppressError; } /// @@ -280,6 +287,21 @@ internal List MatchAll "ModuleVersion" }; + /// + /// List of PowerShell built-in modules that are shipped with PowerShell only, not on PS Gallery. + /// + protected static readonly HashSet BuiltInModules = new(StringComparer.OrdinalIgnoreCase) + { + "CimCmdlets", + "Microsoft.PowerShell.Diagnostics", + "Microsoft.PowerShell.Host", + "Microsoft.PowerShell.Management", + "Microsoft.PowerShell.Security", + "Microsoft.PowerShell.Utility", + "Microsoft.WSMan.Management", + "PSDiagnostics", + }; + /// /// When module manifests lack a CompatiblePSEditions field, /// they will be treated as if they have this value. @@ -307,14 +329,25 @@ internal List MatchAll private readonly Dictionary _currentlyProcessingModules = new Dictionary(); - internal bool LoadUsingModulePath(bool found, IEnumerable modulePath, string name, SessionState ss, - ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module) + internal bool LoadUsingModulePath( + IEnumerable modulePath, + string name, + SessionState ss, + ImportModuleOptions options, + ManifestProcessingFlags manifestProcessingFlags, + out PSModuleInfo module) { - return LoadUsingModulePath(null, found, modulePath, name, ss, options, manifestProcessingFlags, out module); + return LoadUsingModulePath(parentModule: null, modulePath, name, ss, options, manifestProcessingFlags, out module); } - internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumerable modulePath, string name, SessionState ss, - ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out PSModuleInfo module) + internal bool LoadUsingModulePath( + PSModuleInfo parentModule, + IEnumerable modulePath, + string name, + SessionState ss, + ImportModuleOptions options, + ManifestProcessingFlags manifestProcessingFlags, + out PSModuleInfo module) { string extension = Path.GetExtension(name); string fileBaseName; @@ -325,11 +358,18 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer extension = null; } else + { fileBaseName = name.Substring(0, name.Length - extension.Length); + } // Now search using the module path... + bool found = false; foreach (string path in modulePath) { + if (options.SkipSystem32ModulesAndSuppressError && ModuleUtils.IsOnSystem32ModulePath(path)) + { + continue; + } #if UNIX foreach (string folder in Directory.EnumerateDirectories(path)) { @@ -342,7 +382,7 @@ internal bool LoadUsingModulePath(PSModuleInfo parentModule, bool found, IEnumer module = LoadUsingMultiVersionModuleBase(qualifiedPath, manifestProcessingFlags, options, out found); if (!found) { - if (name.IndexOfAny(Utils.Separators.Directory) == -1) + if (name.AsSpan().IndexOfAny('\\', '/') == -1) { qualifiedPath = Path.Combine(qualifiedPath, fileBaseName); } @@ -643,9 +683,19 @@ private bool ValidateManifestHash( return result; } - private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, ModuleSpecification moduleSpecification, string moduleBase, bool searchModulePath, - string prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, bool loadTypes, - bool loadFormats, object privateData, out bool found, string shortModuleName, PSLanguageMode? manifestLanguageMode) + private PSModuleInfo LoadModuleNamedInManifest( + PSModuleInfo parentModule, + ModuleSpecification moduleSpecification, + string moduleBase, + bool searchModulePath, + string prefix, + SessionState ss, + ImportModuleOptions options, + ManifestProcessingFlags manifestProcessingFlags, + object privateData, + out bool found, + string shortModuleName, + PSLanguageMode? manifestLanguageMode) { PSModuleInfo module = null; PSModuleInfo tempModuleInfoFromVerification = null; @@ -659,11 +709,16 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module var importingModule = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.LoadElements); string extension = Path.GetExtension(moduleSpecification.Name); + // First check for fully-qualified paths - either absolute or relative string rootedPath = ResolveRootedFilePath(moduleSpecification.Name, this.Context); if (string.IsNullOrEmpty(rootedPath)) { - rootedPath = FixupFileName(moduleBase, moduleSpecification.Name, extension, importingModule); + // Use the name of the parent module if it's specified, otherwise, use the current module name. + // - If the current module is a nested module, then the parent module will be specified. + // - If the current module is a root module, then the parent module will not be specified. + string moduleName = parentModule?.Name ?? ModuleIntrinsics.GetModuleName(moduleSpecification.Name); + rootedPath = FixFileName(moduleName, moduleBase, moduleSpecification.Name, extension: null, canLoadAssembly: importingModule); } else { @@ -823,7 +878,7 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module } // Otherwise try the module path - found = LoadUsingModulePath(parentModule, found, modulePath, + found = LoadUsingModulePath(parentModule, modulePath, moduleSpecification.Name, ss, options, manifestProcessingFlags, out module); } @@ -836,11 +891,21 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module // Constrained Language session. if (module.LanguageMode != manifestLanguageMode) { - var languageModeError = PSTraceSource.NewInvalidOperationException( - Modules.MismatchedLanguageModes, - module.Name, manifestLanguageMode, module.LanguageMode); - languageModeError.SetErrorId("Modules_MismatchedLanguageModes"); - throw languageModeError; + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + var languageModeError = PSTraceSource.NewInvalidOperationException( + Modules.MismatchedLanguageModes, + module.Name, manifestLanguageMode, module.LanguageMode); + languageModeError.SetErrorId("Modules_MismatchedLanguageModes"); + throw languageModeError; + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACMismatchedLanguageModesTitle, + message: Modules.WDACMismatchedLanguageModesMessage, + fqid: "ModulesMismatchedLanguageModes", + dropIntoDebugger: true); } } @@ -878,7 +943,6 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module // At this point, we are already exhaust all possible ways to load the nested module. The last option is to load it as a binary module/snapin. module = LoadBinaryModule( parentModule, - trySnapInName: true, moduleSpecification.Name, fileName: null, assemblyToLoad: null, @@ -887,8 +951,6 @@ private PSModuleInfo LoadModuleNamedInManifest(PSModuleInfo parentModule, Module options, manifestProcessingFlags, prefix, - loadTypes, - loadFormats, out found, shortModuleName, disableFormatUpdates: false); @@ -963,7 +1025,7 @@ private IEnumerable GetModuleForRootedPaths(List modulePat { bool containsWildCards = false; - string modulePath = mp.TrimEnd(Utils.Separators.Backslash); + string modulePath = mp.TrimEnd('\\'); // If the given path contains wildcards, we won't throw error if no match module path is found. if (WildcardPattern.ContainsWildcardCharacters(modulePath)) @@ -986,9 +1048,8 @@ private IEnumerable GetModuleForRootedPaths(List modulePat PSModuleInfo module = CreateModuleInfoForGetModule(resolvedModulePath, refresh); if (module != null) { - if (!modules.Contains(resolvedModulePath)) + if (modules.Add(resolvedModulePath)) { - modules.Add(resolvedModulePath); yield return module; } } @@ -1017,9 +1078,8 @@ private IEnumerable GetModuleForRootedPaths(List modulePat foundModule = true; // We need to list all versions of the module. string subModulePath = Path.GetDirectoryName(file); - if (!modules.Contains(subModulePath)) + if (modules.Add(subModulePath)) { - modules.Add(subModulePath); yield return module; } } @@ -1056,35 +1116,27 @@ private IEnumerable GetModuleForNames(List names, bool all { IEnumerable allModules = null; HashSet modulePathSet = new HashSet(StringComparer.OrdinalIgnoreCase); - bool cleanupModuleAnalysisAppDomain = Context.TakeResponsibilityForModuleAnalysisAppDomain(); - try + foreach (string path in ModuleIntrinsics.GetModulePath(false, Context)) { - foreach (string path in ModuleIntrinsics.GetModulePath(false, Context)) - { - string uniquePath = path.TrimEnd(Utils.Separators.Directory); + string uniquePath = path.TrimEnd(Utils.Separators.Directory); - // Ignore repeated module path. - if (!modulePathSet.Add(uniquePath)) { continue; } + // Ignore repeated module path. + if (!modulePathSet.Add(uniquePath)) + { + continue; + } - try - { - IEnumerable modulesFound = GetModulesFromOneModulePath( - names, uniquePath, all, refresh).OrderBy(m => m.Name); - allModules = allModules == null ? modulesFound : allModules.Concat(modulesFound); - } - catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) - { - // ignore directories that can't be accessed - continue; - } + try + { + IEnumerable modulesFound = GetModulesFromOneModulePath( + names, uniquePath, all, refresh).OrderBy(static m => m.Name); + allModules = allModules == null ? modulesFound : allModules.Concat(modulesFound); } - } - finally - { - if (cleanupModuleAnalysisAppDomain) + catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) { - Context.ReleaseResponsibilityForModuleAnalysisAppDomain(); + // ignore directories that can't be accessed + continue; } } @@ -1146,7 +1198,7 @@ internal static Version GetMaximumVersion(string stringVersion) { stringVersion = stringVersion.Substring(0, stringVersion.Length - 1); stringVersion += maxRange; - int starNum = stringVersion.Count(x => x == '.'); + int starNum = stringVersion.Count(static x => x == '.'); for (int i = 0; i < (3 - starNum); i++) { stringVersion = stringVersion + '.' + maxRange; @@ -1494,6 +1546,7 @@ internal PSModuleInfo LoadModuleManifest( Dbg.Assert(moduleManifestPath != null, "moduleManifestPath for module (.psd1) can't be null"); string moduleBase = Path.GetDirectoryName(moduleManifestPath); + string moduleName = ModuleIntrinsics.GetModuleName(moduleManifestPath); if ((manifestProcessingFlags & (ManifestProcessingFlags.LoadElements | ManifestProcessingFlags.WriteErrors | @@ -1594,24 +1647,32 @@ internal PSModuleInfo LoadModuleManifest( invalidOperation.SetErrorId("Modules_WildCardNotAllowedInModuleToProcessAndInNestedModules"); throw invalidOperation; } + // See if this module is already loaded. Since the manifest entry may not // have an extension and the module table is indexed by full names, we // may have search through all the extensions. PSModuleInfo loadedModule = null; - string rootedPath = this.FixupFileName(moduleBase, actualRootModule, extension: null, importingModule); - string mtpExtension = Path.GetExtension(rootedPath); - if (!string.IsNullOrEmpty(mtpExtension) && ModuleIntrinsics.IsPowerShellModuleExtension(mtpExtension)) + string rootedPath = null; + + // For a root module, we use its own module name instead of the manifest module name when calling 'FixFileName'. + // This is because when actually loading the root module later, it won't have access to the parent manifest module, + // and we will use its own name to query for already loaded assemblies from 'Context.AssemblyCache'. + string rootModuleName = ModuleIntrinsics.GetModuleName(actualRootModule); + string extension = Path.GetExtension(actualRootModule); + if (!string.IsNullOrEmpty(extension) && ModuleIntrinsics.IsPowerShellModuleExtension(extension)) { + rootedPath = FixFileName(rootModuleName, moduleBase, actualRootModule, extension: null, canLoadAssembly: importingModule); TryGetFromModuleTable(rootedPath, out loadedModule); } else { foreach (string extensionToTry in ModuleIntrinsics.PSModuleExtensions) { - rootedPath = this.FixupFileName(moduleBase, actualRootModule, extensionToTry, importingModule); - TryGetFromModuleTable(rootedPath, out loadedModule); - if (loadedModule != null) + rootedPath = FixFileName(rootModuleName, moduleBase, actualRootModule, extensionToTry, canLoadAssembly: importingModule); + if (TryGetFromModuleTable(rootedPath, out loadedModule)) + { break; + } } } @@ -1860,9 +1921,12 @@ internal PSModuleInfo LoadModuleManifest( else if ((requiredProcessorArchitecture != ProcessorArchitecture.None) && (requiredProcessorArchitecture != ProcessorArchitecture.MSIL)) { - ProcessorArchitecture currentArchitecture = typeof(object).Assembly.GetName().ProcessorArchitecture; + Architecture currentArchitecture = RuntimeInformation.ProcessArchitecture; - if (currentArchitecture != requiredProcessorArchitecture) + if ((requiredProcessorArchitecture == ProcessorArchitecture.X86 && currentArchitecture != Architecture.X86) || + (requiredProcessorArchitecture == ProcessorArchitecture.Amd64 && currentArchitecture != Architecture.X64) || + (requiredProcessorArchitecture == ProcessorArchitecture.Arm && (currentArchitecture != Architecture.Arm && currentArchitecture != Architecture.Arm64)) || + requiredProcessorArchitecture == ProcessorArchitecture.IA64) { containedErrors = true; if (writingErrors) @@ -2017,7 +2081,6 @@ internal PSModuleInfo LoadModuleManifest( { bool nameMissingOrEmpty = false; var invalidNames = new List(); - string moduleName = ModuleIntrinsics.GetModuleName(moduleManifestPath); expFeatureList = new List(features.Length); foreach (Hashtable feature in features) @@ -2130,61 +2193,72 @@ internal PSModuleInfo LoadModuleManifest( // Indicates the ISS.Bind() should be called... bool doBind = false; - // Set up to load any required assemblies that have been specified... - List tmpAssemblyList; - List assemblyList = new List(); - List fixedUpAssemblyPathList = new List(); - - if ( - !GetListOfStringsFromData(data, moduleManifestPath, "RequiredAssemblies", manifestProcessingFlags, - out tmpAssemblyList)) + if (!GetListOfStringsFromData( + data, + moduleManifestPath, + "RequiredAssemblies", + manifestProcessingFlags, + out List assemblyList)) { containedErrors = true; - if (bailOnFirstError) return null; + if (bailOnFirstError) + { + return null; + } } - else + else if (assemblyList != null && importingModule) { - if (tmpAssemblyList != null && tmpAssemblyList.Count > 0) + foreach (string assembly in assemblyList) { - foreach (string assembly in tmpAssemblyList) + if (WildcardPattern.ContainsWildcardCharacters(assembly)) { - assemblyList.Add(assembly); + PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException( + Modules.WildCardNotAllowedInRequiredAssemblies, + moduleManifestPath); + invalidOperation.SetErrorId("Modules_WildCardNotAllowedInRequiredAssemblies"); + throw invalidOperation; } - } - - if ((assemblyList != null) && importingModule) - { - foreach (string assembly in assemblyList) + else { - if (WildcardPattern.ContainsWildcardCharacters(assembly)) + string fileName = null; + string ext = Path.GetExtension(assembly); + + // Note that we don't need to load the required assemblies eagerly because they will be loaded before + // processing type and format data. So, when calling 'FixupFileName', we only attempt to resolve the + // path, and avoid triggering the loading of the assembly. + if (ModuleIntrinsics.ProcessableAssemblyExtensions.Contains(ext, StringComparer.OrdinalIgnoreCase)) { - PSInvalidOperationException invalidOperation = PSTraceSource.NewInvalidOperationException( - Modules.WildCardNotAllowedInRequiredAssemblies, - moduleManifestPath); - invalidOperation.SetErrorId("Modules_WildCardNotAllowedInRequiredAssemblies"); - throw invalidOperation; + fileName = FixFileNameWithoutLoadingAssembly(moduleBase, assembly, extension: null); } else { - string fileName = FixupFileName(moduleBase, assembly, StringLiterals.PowerShellNgenAssemblyExtension, importingModule, out bool pathIsResolved); - if (!pathIsResolved) + bool isPathResolved = false; + foreach (string extToTry in ModuleIntrinsics.ProcessableAssemblyExtensions) { - fileName = FixupFileName(moduleBase, assembly, StringLiterals.PowerShellILAssemblyExtension, importingModule); + fileName = FixFileNameWithoutLoadingAssembly(moduleBase, assembly, extToTry, out isPathResolved); + if (isPathResolved) + { + break; + } } - string loadMessage = StringUtil.Format(Modules.LoadingFile, "Assembly", fileName); - WriteVerbose(loadMessage); - iss.Assemblies.Add(new SessionStateAssemblyEntry(assembly, fileName)); - fixedUpAssemblyPathList.Add(fileName); + if (!isPathResolved) + { + // We didn't resolve the assembly path, so remove the '.exe' extension that was added in the + // last iteration of the above loop. + int index = fileName.LastIndexOf('.'); + fileName = fileName.Substring(0, index); + } + } - fileName = FixupFileName(moduleBase, assembly, StringLiterals.PowerShellILExecutableExtension, importingModule); - loadMessage = StringUtil.Format(Modules.LoadingFile, "Executable", fileName); - WriteVerbose(loadMessage); - iss.Assemblies.Add(new SessionStateAssemblyEntry(assembly, fileName)); - fixedUpAssemblyPathList.Add(fileName); + WriteVerbose(StringUtil.Format(Modules.LoadingFile, "Assembly", fileName)); - doBind = true; - } + // Set a fake PSModuleInfo object to indicate the module it comes from. + var assemblyEntry = new SessionStateAssemblyEntry(assembly, fileName); + assemblyEntry.SetModule(new PSModuleInfo(moduleName, path: null, context: null, sessionState: null)); + + iss.Assemblies.Add(assemblyEntry); + doBind = true; } } } @@ -2221,8 +2295,7 @@ internal PSModuleInfo LoadModuleManifest( continue; } - string resolvedEntryFileName = ResolveRootedFilePath(entry.FileName, Context) ?? - entry.FileName; + string resolvedEntryFileName = ResolveRootedFilePath(entry.FileName, Context) ?? entry.FileName; if (resolvedEntryFileName.Equals(resolvedFileName, StringComparison.OrdinalIgnoreCase)) { isAlreadyLoaded = true; @@ -2345,7 +2418,7 @@ internal PSModuleInfo LoadModuleManifest( key: "FileList", manifestProcessingFlags, moduleBase, - extension: string.Empty, + extension: null, // Don't check file existence - don't want to change current behavior without feature team discussion. verifyFilesExist: false, out List fileList)) @@ -2384,17 +2457,13 @@ internal PSModuleInfo LoadModuleManifest( { if (importingModule) { - IList moduleProxies = ImportModulesUsingWinCompat(new string[] { moduleManifestPath }, null, options); + IList moduleProxies = ImportModulesUsingWinCompat( + moduleNames: new string[] { moduleManifestPath }, + moduleFullyQualifiedNames: null, + importModuleOptions: options); - // we are loading by a single ManifestPath so expect max of 1 - if (moduleProxies.Count > 0) - { - return moduleProxies[0]; - } - else - { - return null; - } + // We are loading by a single ManifestPath so expect max of 1 + return moduleProxies.Count > 0 ? moduleProxies[0] : null; } } else @@ -2489,38 +2558,27 @@ internal PSModuleInfo LoadModuleManifest( // If there is a session state, set up to import/export commands and variables if (ss != null) { - ss.Internal.SetVariable(SpecialVariables.PSScriptRootVarPath, Path.GetDirectoryName(moduleManifestPath), - true, CommandOrigin.Internal); - ss.Internal.SetVariable(SpecialVariables.PSCommandPathVarPath, moduleManifestPath, true, + ss.Internal.SetVariable( + SpecialVariables.PSScriptRootVarPath, + moduleBase, + asValue: true, CommandOrigin.Internal); + + ss.Internal.SetVariable( + SpecialVariables.PSCommandPathVarPath, + moduleManifestPath, + asValue: true, + CommandOrigin.Internal); + ss.Internal.Module = manifestInfo; // without ModuleToProcess a manifest will export everything by default // (otherwise we want to honour exports from ModuleToProcess) - if (exportedFunctions == null) - { - exportedFunctions = MatchAll; - } - - if (exportedCmdlets == null) - { - exportedCmdlets = MatchAll; - } - - if (exportedVariables == null) - { - exportedVariables = MatchAll; - } - - if (exportedAliases == null) - { - exportedAliases = MatchAll; - } - - if (exportedDscResources == null) - { - exportedDscResources = MatchAll; - } + exportedAliases ??= MatchAll; + exportedCmdlets ??= MatchAll; + exportedDscResources ??= MatchAll; + exportedFunctions ??= MatchAll; + exportedVariables ??= MatchAll; } manifestInfo.Description = description; @@ -2946,8 +3004,6 @@ internal PSModuleInfo LoadModuleManifest( ss: null, options: nestedModuleOptions, manifestProcessingFlags: manifestProcessingFlags, - loadTypes: true, - loadFormats: true, privateData: privateData, found: out found, shortModuleName: null, @@ -3049,8 +3105,6 @@ internal PSModuleInfo LoadModuleManifest( ss: ss, options: options, manifestProcessingFlags: manifestProcessingFlags, - loadTypes: (exportedTypeFiles == null || exportedTypeFiles.Count == 0), // If types files already loaded, don't load snapin files - loadFormats: (exportedFormatFiles == null || exportedFormatFiles.Count == 0), // if format files already loaded, don't load snapin files privateData: privateData, found: out found, shortModuleName: null, @@ -3155,16 +3209,10 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.RootModule == null) - { - newManifestInfo.RootModule = manifestInfo.RootModule; - } + newManifestInfo.RootModule ??= manifestInfo.RootModule; // If may be the case that a script has already set the PrivateData field in the module // info object, in which case we won't overwrite it. - if (newManifestInfo.PrivateData == null) - { - newManifestInfo.PrivateData = manifestInfo.PrivateData; - } + newManifestInfo.PrivateData ??= manifestInfo.PrivateData; // Assign the PowerShellGet related properties from the module manifest foreach (var tag in manifestInfo.Tags) @@ -3289,10 +3337,7 @@ internal PSModuleInfo LoadModuleManifest( } } - if (newManifestInfo.RootModuleForManifest == null) - { - newManifestInfo.RootModuleForManifest = manifestInfo.RootModuleForManifest; - } + newManifestInfo.RootModuleForManifest ??= manifestInfo.RootModuleForManifest; if (newManifestInfo.DeclaredCmdletExports == null || newManifestInfo.DeclaredCmdletExports.Count == 0) { @@ -3384,13 +3429,25 @@ internal PSModuleInfo LoadModuleManifest( if ((ss != null) && (!ss.Internal.UseExportList)) { // For cross language boundaries, implicitly import all functions only if - // this manifest *does* exort functions explicitly. + // this manifest *does* export functions explicitly. List fnMatchPattern = ( (manifestScriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) && (Context.LanguageMode != PSLanguageMode.FullLanguage) && (exportedFunctions == null) ) ? null : MatchAll; + // If the system is in WDAC policy AUDIT mode, then an export functions restriction should be reported but not applied. + if (fnMatchPattern == null && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACImplicitFunctionExportLogTitle, + message: StringUtil.Format(Modules.WDACImplicitFunctionExportLogMessage, manifestScriptInfo.ModuleName), + fqid: "ModuleImplicitFunctionExportNotAllowed", + dropIntoDebugger: true); + fnMatchPattern = MatchAll; + } + ModuleIntrinsics.ExportModuleMembers(cmdlet: this, sessionState: ss.Internal, functionPatterns: fnMatchPattern, @@ -3715,7 +3772,7 @@ internal static object IsModuleLoaded(ExecutionContext context, ModuleSpecificat // If the RequiredModule is one of the Engine modules, then they could have been loaded as snapins (using InitialSessionState.CreateDefault()) if (result == null && InitialSessionState.IsEngineModule(requiredModule.Name)) { - result = ModuleCmdletBase.GetEngineSnapIn(context, requiredModule.Name); + result = context.CurrentRunspace.InitialSessionState.GetPSSnapIn(requiredModule.Name); if (result != null) { loaded = true; @@ -4375,8 +4432,6 @@ private bool GetListOfFilesFromData( out List list) { list = null; - - bool importingModule = manifestProcessingFlags.HasFlag(ManifestProcessingFlags.LoadElements); if (!GetListOfStringsFromData(data, moduleManifestPath, key, manifestProcessingFlags, out List listOfStrings)) { return false; @@ -4398,7 +4453,7 @@ private bool GetListOfFilesFromData( { try { - string fixedFileName = FixupFileName(moduleBase, s, extension, importingModule, skipLoading: true); + string fixedFileName = FixFileNameWithoutLoadingAssembly(moduleBase, s, extension); var dir = Path.GetDirectoryName(fixedFileName); if (string.Equals(psHome, dir, StringComparison.OrdinalIgnoreCase) || @@ -4509,7 +4564,7 @@ internal static ModuleLoggingGroupPolicyStatus GetModuleLoggingInformation(out I /// /// Checks to see if the module manifest contains the specified key. /// If it does and it can be converted to the expected type, then it returns and sets to the value. - /// If the key is missing it returns and sets to default(). + /// If the key is missing it returns and sets to default(). /// If the key is invalid then it returns . /// /// The hashtable to look for the key in. @@ -4553,39 +4608,58 @@ internal bool GetScalarFromData( } } + private string FixFileNameWithoutLoadingAssembly(string moduleBase, string fileName, string extension) + { + return FixFileName(moduleName: null, moduleBase, fileName, extension, canLoadAssembly: false, pathIsResolved: out _); + } + + private string FixFileNameWithoutLoadingAssembly(string moduleBase, string fileName, string extension, out bool pathIsResolved) + { + return FixFileName(moduleName: null, moduleBase, fileName, extension, canLoadAssembly: false, out pathIsResolved); + } + /// /// A utility routine to fix up a file name so it's rooted and has an extension. /// - internal string FixupFileName(string moduleBase, string name, string extension, bool isImportingModule, bool skipLoading = false) + private string FixFileName(string moduleName, string moduleBase, string fileName, string extension, bool canLoadAssembly) { - return FixupFileName(moduleBase, name, extension, isImportingModule, pathIsResolved: out _, skipLoading); + return FixFileName(moduleName, moduleBase, fileName, extension, canLoadAssembly, pathIsResolved: out _); } /// /// A utility routine to fix up a file name so it's rooted and has an extension. /// /// - /// When fixing up an assembly file, this method loads the resovled assembly if it's in the process of actually loading a module. + /// When fixing up an assembly file, this method loads the resolved assembly if it's in the process of actually loading a module. /// Read the comments in the method for the detailed information. /// + /// Name of the module that we are processing, used for caching purpose when we need to load an assembly. /// The base path to use if the file is not rooted. - /// The file name to resolve. - /// The extension to use in case the given name has no extension. - /// Indicate if we are loading a module. + /// The file name to resolve. + /// The extension to use for the look up. + /// Indicate if we can load assembly for the resolution. /// Indicate if the returned path is fully resolved. - /// Indicate if the resolved module should be loaded. /// - /// The resolved file path. Or, the combined path of and when the file path cannot be resolved. + /// The resolved file path. Or, the combined path of and when the file path cannot be resolved. /// - internal string FixupFileName(string moduleBase, string name, string extension, bool isImportingModule, out bool pathIsResolved, bool skipLoading = false) + private string FixFileName(string moduleName, string moduleBase, string fileName, string extension, bool canLoadAssembly, out bool pathIsResolved) { pathIsResolved = false; - string originalName = name; - string originalExt = Path.GetExtension(name); - if (string.IsNullOrEmpty(originalExt)) + string originalName = fileName; + string originalExt = Path.GetExtension(fileName); + + if (string.IsNullOrEmpty(extension)) { - name += extension; + // When 'extension' is not explicitly specified, we honor the original extension. + extension = originalExt; + } + else if (!extension.Equals(originalExt, StringComparison.OrdinalIgnoreCase)) + { + // When 'extension' is explicitly specified, append it if the original extension is different. + // Note: the original extension could actually be part of the file name. For example, the name + // is `Microsoft.PowerShell.Command.Utility`, in which case the extension is `.Utility`. + fileName += extension; } // Try to get the resolved fully qualified path to the file. @@ -4597,24 +4671,24 @@ internal string FixupFileName(string moduleBase, string name, string extension, // Check for combinedPath in this case will get us the normalized rooted path 'C:\Windows\System32\WindowsPowerShell\v1.0\WSMan.format.ps1xml'. // The 'Microsoft.WSMan.Management' module in PowerShell was updated to not use the relative path for 'FormatsToProcess' entry, // but it's safer to keep the original behavior to avoid unexpected breaking changes. - string combinedPath = Path.Combine(moduleBase, name); - string resolvedPath = IsRooted(name) - ? ResolveRootedFilePath(name, Context) ?? ResolveRootedFilePath(combinedPath, Context) + string combinedPath = Path.Combine(moduleBase, fileName); + string resolvedPath = IsRooted(fileName) + ? ResolveRootedFilePath(fileName, Context) ?? ResolveRootedFilePath(combinedPath, Context) : ResolveRootedFilePath(combinedPath, Context); // Return the path if successfully resolved. - if (resolvedPath != null) + if (resolvedPath is not null) { - if (isImportingModule && resolvedPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) && !skipLoading) + if (canLoadAssembly && resolvedPath.EndsWith(".dll", StringComparison.OrdinalIgnoreCase)) { // If we are fixing up an assembly file path and we are actually loading the module, then we load the resolved assembly file here. - // This is because we process type/format ps1xml files before 'RootModule' and 'NestedModules' entries during the module loading. - // A types.ps1xml file could refer to a type defined in the assembly that is specified in the 'RootModule' or 'NestedModule', and - // in that case, processing the types.ps1xml file would fail because it happens before processing the 'RootModule', which loads - // the assembly. We cannot move the processing of types.ps1xml file after processing 'RootModule' either, because the 'RootModule' - // might refer to members defined in the types.ps1xml file. In order to make it work for this paradox, we have to load the resolved - // assembly when we are actually loading the module. However, when it's module analysis, there is no need to load the assembly. - ExecutionContext.LoadAssembly(name: null, filename: resolvedPath, error: out _); + // This is because we process type/format ps1xml files before 'RootModule' during the module loading. A types.ps1xml file could + // refer to a type defined in the assembly that is specified in the 'RootModule', and in that case, processing the types.ps1xml file + // would fail because it happens before processing the 'RootModule', which loads the assembly. + // We cannot move the processing of types.ps1xml file after processing 'RootModule' either, because the 'RootModule' might refer to + // members defined in the types.ps1xml file. In order to make it work for this paradox, we have to load the resolved assembly when + // we are actually loading the module. However, when it's module analysis, there is no need to load the assembly. + Context.AddAssembly(source: moduleName, assemblyName: null, filePath: resolvedPath, error: out _); } pathIsResolved = true; @@ -4627,12 +4701,12 @@ internal string FixupFileName(string moduleBase, string name, string extension, // For dlls, we cannot get the path from the provider. // We need to load the assembly and then get the path. // If the module is already loaded, this is not expensive since the assembly is already loaded in the AppDomain - if (!string.IsNullOrEmpty(extension) && + if (canLoadAssembly && !string.IsNullOrEmpty(extension) && (extension.Equals(StringLiterals.PowerShellILAssemblyExtension, StringComparison.OrdinalIgnoreCase) || - extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))) + extension.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase))) { - Assembly assembly = ExecutionContext.LoadAssembly(name: originalName, filename: null, error: out _); - if (assembly != null) + Assembly assembly = Context.AddAssembly(source: moduleName, assemblyName: originalName, filePath: null, error: out _); + if (assembly is not null) { pathIsResolved = true; result = assembly.Location; @@ -4887,12 +4961,12 @@ internal static void SyncCurrentLocationHandler(object sender, LocationChangedEv using var ps = System.Management.Automation.PowerShell.Create(RunspaceMode.CurrentRunspace); ps.AddCommand(new CmdletInfo("Invoke-Command", typeof(InvokeCommandCommand))); ps.AddParameter("Session", compatSession); - ps.AddParameter("ScriptBlock", ScriptBlock.Create(string.Format("Set-Location -Path '{0}'", args.NewPath.Path))); + ps.AddParameter("ScriptBlock", ScriptBlock.Create(string.Create(CultureInfo.InvariantCulture, $"Set-Location -Path '{args.NewPath.Path}'"))); ps.Invoke(); } } - internal static System.EventHandler SyncCurrentLocationDelegate; + internal static EventHandler SyncCurrentLocationDelegate; internal virtual IList ImportModulesUsingWinCompat(IEnumerable moduleNames, IEnumerable moduleFullyQualifiedNames, ImportModuleOptions importModuleOptions) { throw new System.NotImplementedException(); } @@ -4946,8 +5020,6 @@ internal void RemoveModule(PSModuleInfo module) /// Module name specified in the cmdlet. internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleCmdlet) { - bool isTopLevelModule = false; - // if the module path is empty string, means it is a dynamically generated assembly. // We have set the module path to be module name as key to make it unique, we need update here as well in case the module can be removed. if (module.Path == string.Empty) @@ -4955,7 +5027,7 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC module.Path = module.Name; } - bool shouldModuleBeRemoved = ShouldModuleBeRemoved(module, moduleNameInRemoveModuleCmdlet, out isTopLevelModule); + bool shouldModuleBeRemoved = ShouldModuleBeRemoved(module, moduleNameInRemoveModuleCmdlet, out bool isTopLevelModule); if (shouldModuleBeRemoved) { @@ -4963,17 +5035,14 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC if (Context.Modules.ModuleTable.ContainsKey(module.Path)) { // We should try to run OnRemove as the very first thing - if (module.OnRemove != null) - { - module.OnRemove.InvokeUsingCmdlet( - contextCmdlet: this, - useLocalScope: true, - errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, - dollarUnder: AutomationNull.Value, - input: AutomationNull.Value, - scriptThis: AutomationNull.Value, - args: new object[] { module }); - } + module.OnRemove?.InvokeUsingCmdlet( + contextCmdlet: this, + useLocalScope: true, + errorHandlingBehavior: ScriptBlock.ErrorHandlingBehavior.WriteToCurrentErrorPipe, + dollarUnder: AutomationNull.Value, + input: AutomationNull.Value, + scriptThis: AutomationNull.Value, + args: new object[] { module }); if (module.ImplementingAssembly != null && !module.ImplementingAssembly.IsDynamic) { @@ -5187,19 +5256,13 @@ internal void RemoveModule(PSModuleInfo module, string moduleNameInRemoveModuleC // And the appdomain level module path cache. PSModuleInfo.RemoveFromAppDomainLevelCache(module.Name); - // Update implicit module loaded property - if (Context.Modules.IsImplicitRemotingModuleLoaded) + // And remove the module assembly entries that may have been added from the assembly cache. + Context.RemoveFromAssemblyCache(source: module.Name); + if (module.ModuleType == ModuleType.Binary && !string.IsNullOrEmpty(module.RootModule)) { - Context.Modules.IsImplicitRemotingModuleLoaded = false; - foreach (var modInfo in Context.Modules.ModuleTable.Values) - { - var privateData = modInfo.PrivateData as Hashtable; - if ((privateData != null) && privateData.ContainsKey("ImplicitRemoting")) - { - Context.Modules.IsImplicitRemotingModuleLoaded = true; - break; - } - } + // We also need to clean up the cache entries that are possibly referenced by the root module in this case. + string rootModuleName = ModuleIntrinsics.GetModuleName(module.RootModule); + Context.RemoveFromAssemblyCache(source: rootModuleName); } } } @@ -5333,9 +5396,8 @@ internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule, string moduleName, string fileBaseName, string extension, string moduleBase, string prefix, SessionState ss, ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, out bool found) { - bool throwAwayModuleFileFound = false; return LoadUsingExtensions(parentModule, moduleName, fileBaseName, extension, moduleBase, prefix, ss, - options, manifestProcessingFlags, out found, out throwAwayModuleFileFound); + options, manifestProcessingFlags, out found, out _); } /// @@ -5436,7 +5498,6 @@ internal PSModuleInfo LoadUsingExtensions(PSModuleInfo parentModule, } else if (File.Exists(fileName)) { - moduleFileFound = true; // Win8: 325243 - Added the version check so that we do not unload modules with the same name but different version if (BaseForce && DoesAlreadyLoadedModuleSatisfyConstraints(module)) { @@ -5592,12 +5653,23 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str PSModuleInfo module = null; // Block ps1 files from being imported in constrained language. - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase)) + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + ext.Equals(StringLiterals.PowerShellScriptFileExtension, StringComparison.OrdinalIgnoreCase)) { - InvalidOperationException invalidOp = new InvalidOperationException(Modules.ImportPSFileNotAllowedInConstrainedLanguage); - ErrorRecord er = new ErrorRecord(invalidOp, "Modules_ImportPSFileNotAllowedInConstrainedLanguage", - ErrorCategory.PermissionDenied, null); - ThrowTerminatingError(er); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + InvalidOperationException invalidOp = new InvalidOperationException(Modules.ImportPSFileNotAllowedInConstrainedLanguage); + ErrorRecord er = new ErrorRecord(invalidOp, "Modules_ImportPSFileNotAllowedInConstrainedLanguage", + ErrorCategory.PermissionDenied, null); + ThrowTerminatingError(er); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACScriptFileImportLogTitle, + message: StringUtil.Format(Modules.WDACScriptFileImportLogMessage, fileName), + fqid: "ModuleImportScriptFilesNotAllowed", + dropIntoDebugger: true); } // If MinimumVersion/RequiredVersion/MaximumVersion has been specified, then only try to process manifest modules... @@ -5681,19 +5753,31 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str // If the script didn't call Export-ModuleMember explicitly, then // implicitly export functions and cmdlets. + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); if (!module.SessionState.Internal.UseExportList) { // For cross language boundaries don't implicitly export all functions, unless they are allowed nested modules. - // Implict function export is allowed when any of the following is true: + // Implicit function export is allowed when any of the following is true: // - Nested modules are allowed by module manifest // - The import context language mode is FullLanguage - // - This script module not running as trusted (FullLanguage) + // - This script module is not running as trusted (FullLanguage) module.ModuleAutoExportsAllFunctions = options.AllowNestedModuleFunctionsToExport || Context.LanguageMode == PSLanguageMode.FullLanguage || psm1ScriptInfo.DefiningLanguageMode != PSLanguageMode.FullLanguage; - List fnMatchPattern = module.ModuleAutoExportsAllFunctions ? MatchAll : null; + // If the system is in WDAC policy AUDIT mode, then an export functions restriction should be reported but not applied. + if (fnMatchPattern == null && systemLockdownPolicy == SystemEnforcementMode.Audit) + { + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACImplicitFunctionExportLogTitle, + message: StringUtil.Format(Modules.WDACImplicitFunctionExportLogMessage, module.Name), + fqid: "ModuleImplicitFunctionExportNotAllowed", + dropIntoDebugger: true); + fnMatchPattern = MatchAll; + } + ModuleIntrinsics.ExportModuleMembers( cmdlet: this, sessionState: module.SessionState.Internal, @@ -5703,8 +5787,8 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str variablePatterns: null, doNotExportCmdlets: null); } - else if ((SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && - (module.LanguageMode == PSLanguageMode.FullLanguage) && + else if ((systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) && + module.LanguageMode == PSLanguageMode.FullLanguage && module.SessionState.Internal.FunctionsExportedWithWildcard && !module.SessionState.Internal.ManifestWithExplicitFunctionExport) { @@ -5712,10 +5796,10 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str // exported functions only come from this module and not from any imported nested modules. // Unless there is a parent manifest that explicitly filters all exported functions (no wildcards). // This prevents unintended public exposure of imported functions running in FullLanguage. - ModuleIntrinsics.RemoveNestedModuleFunctions(module); + RemoveNestedModuleFunctions(Context, module, systemLockdownPolicy); } - CheckForDisallowedDotSourcing(module.SessionState, psm1ScriptInfo, options); + CheckForDisallowedDotSourcing(module, psm1ScriptInfo, options); // Add it to the all module tables ImportModuleMembers(module, prefix, options); @@ -5869,7 +5953,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str if (module != null) { - CheckForDisallowedDotSourcing(module.SessionState, psd1ScriptInfo, options); + CheckForDisallowedDotSourcing(module, psd1ScriptInfo, options); if (importingModule) { @@ -5892,7 +5976,7 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str ext.Equals(StringLiterals.PowerShellILExecutableExtension, StringComparison.OrdinalIgnoreCase)) { module = LoadBinaryModule( - trySnapInName: false, + parentModule, ModuleIntrinsics.GetModuleName(fileName), fileName, assemblyToLoad: null, @@ -5901,8 +5985,6 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str options, manifestProcessingFlags, prefix, - loadTypes: true, - loadFormats: true, out found); if (found && module != null) @@ -6036,25 +6118,28 @@ internal PSModuleInfo LoadModule(PSModuleInfo parentModule, string fileName, str } private void CheckForDisallowedDotSourcing( - SessionState ss, + PSModuleInfo moduleInfo, ExternalScriptInfo scriptInfo, ImportModuleOptions options) { - if (ss == null || ss.Internal == null) - { return; } + if (moduleInfo.SessionState == null || moduleInfo.SessionState.Internal == null) + { + return; + } // A manifest with explicit function export is detected through a shared session state or the nested module options, because nested // module processing does not use a shared session state. - var manifestWithExplicitFunctionExport = ss.Internal.ManifestWithExplicitFunctionExport || options.AllowNestedModuleFunctionsToExport; + var manifestWithExplicitFunctionExport = moduleInfo.SessionState.Internal.ManifestWithExplicitFunctionExport || options.AllowNestedModuleFunctionsToExport; // If system is in lock down mode, we disallow trusted modules that use the dotsource operator while simultaneously using // wild cards for exporting module functions, unless there is an overriding manifest that explicitly exports functions // without wild cards. // This is because dotsourcing brings functions into module scope and it is too easy to inadvertently or maliciously // expose harmful private functions that run in trusted (FullLanguage) mode. - if (!manifestWithExplicitFunctionExport && ss.Internal.FunctionsExportedWithWildcard && - (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) && - (scriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage)) + var systemLockdownPolicy = SystemPolicy.GetSystemLockdownPolicy(); + if (!manifestWithExplicitFunctionExport && moduleInfo.SessionState.Internal.FunctionsExportedWithWildcard && + (systemLockdownPolicy == SystemEnforcementMode.Enforce || systemLockdownPolicy == SystemEnforcementMode.Audit) && + scriptInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage) { var dotSourceOperator = scriptInfo.GetScriptBlockAst().FindAll(ast => { @@ -6065,15 +6150,50 @@ private void CheckForDisallowedDotSourcing( if (dotSourceOperator != null) { - var errorRecord = new ErrorRecord( - new PSSecurityException(Modules.CannotUseDotSourceWithWildCardFunctionExport), - "Modules_SystemLockDown_CannotUseDotSourceWithWildCardFunctionExport", - ErrorCategory.SecurityError, null); - ThrowTerminatingError(errorRecord); + if (systemLockdownPolicy != SystemEnforcementMode.Audit) + { + var errorRecord = new ErrorRecord( + new PSSecurityException(Modules.CannotUseDotSourceWithWildCardFunctionExport), + "Modules_SystemLockDown_CannotUseDotSourceWithWildCardFunctionExport", + ErrorCategory.SecurityError, null); + ThrowTerminatingError(errorRecord); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACModuleDotSourceLogTitle, + message: StringUtil.Format(Modules.WDACModuleDotSourceLogMessage, moduleInfo.Name), + fqid: "ModuleImportDotSourceNotAllowed", + dropIntoDebugger: true); } } } + private static void RemoveNestedModuleFunctions( + ExecutionContext context, + PSModuleInfo module, + SystemEnforcementMode systemLockdownPolicy) + { + var input = module.SessionState?.Internal?.ExportedFunctions; + if (input == null || input.Count == 0) + { + return; + } + + if (systemLockdownPolicy != SystemEnforcementMode.Audit) + { + input.RemoveAll(fnInfo => !module.Name.Equals(fnInfo.ModuleName, StringComparison.OrdinalIgnoreCase)); + return; + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: Modules.WDACModuleFnExportWithNestedModulesLogTitle, + message: StringUtil.Format(Modules.WDACModuleFnExportWithNestedModulesLogMessage, module.Name), + fqid: "ModuleExportWithWildcardCharactersNotAllowed", + dropIntoDebugger: true); + } + private static bool ShouldProcessScriptModule(PSModuleInfo parentModule, ref bool found) { bool shouldProcessModule = true; @@ -6117,7 +6237,6 @@ private static void ClearAnalysisCaches() private static readonly Dictionary> s_binaryAnalysisCache = new Dictionary>(); -#if CORECLR /// /// Analyze the module assembly to find out all cmdlets and aliases defined in that assembly. /// @@ -6157,155 +6276,6 @@ private static BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(str return resultToReturn; } -#else - /// - /// Analyze the module assembly to find out all cmdlets and aliases defined in that assembly. - /// - private BinaryAnalysisResult GetCmdletsFromBinaryModuleImplementation(string path, ManifestProcessingFlags manifestProcessingFlags, out Version assemblyVersion) - { - Tuple tuple = null; - - lock (s_lockObject) - { - s_binaryAnalysisCache.TryGetValue(path, out tuple); - } - - if (tuple != null) - { - assemblyVersion = tuple.Item2; - return tuple.Item1; - } - - assemblyVersion = new Version("0.0.0.0"); - - bool cleanupModuleAnalysisAppDomain = false; - AppDomain tempDomain = Context.AppDomainForModuleAnalysis; - if (tempDomain == null) - { - cleanupModuleAnalysisAppDomain = Context.TakeResponsibilityForModuleAnalysisAppDomain(); - tempDomain = Context.AppDomainForModuleAnalysis = AppDomain.CreateDomain("ReflectionDomain"); - } - - try - { - // create temp appdomain if one is not passed in - tempDomain.SetData("PathToProcess", path); - tempDomain.SetData("IsModuleLoad", 0 != (manifestProcessingFlags & ManifestProcessingFlags.LoadElements)); - - // reset DetectedCmdlets and AssemblyVersion from previous invocation - tempDomain.SetData("DetectedCmdlets", null); - tempDomain.SetData("DetectedAliases", null); - tempDomain.SetData("AssemblyVersion", assemblyVersion); - - tempDomain.DoCallBack(AnalyzeSnapinDomainHelper); - List detectedCmdlets = (List)tempDomain.GetData("DetectedCmdlets"); - List> detectedAliases = (List>)tempDomain.GetData("DetectedAliases"); - assemblyVersion = (Version)tempDomain.GetData("AssemblyVersion"); - - if ((detectedCmdlets.Count == 0) && (System.IO.Path.IsPathRooted(path))) - { - // If we couldn't load it from a file, try loading from the GAC - string assemblyname = Path.GetFileName(path); - BinaryAnalysisResult gacResult = GetCmdletsFromBinaryModuleImplementation(assemblyname, manifestProcessingFlags, out assemblyVersion); - detectedCmdlets = gacResult.DetectedCmdlets; - detectedAliases = gacResult.DetectedAliases; - } - - BinaryAnalysisResult result = new BinaryAnalysisResult(); - result.DetectedCmdlets = detectedCmdlets; - result.DetectedAliases = detectedAliases; - - lock (s_lockObject) - { - s_binaryAnalysisCache[path] = Tuple.Create(result, assemblyVersion); - } - - return result; - } - finally - { - if (cleanupModuleAnalysisAppDomain) - { - Context.ReleaseResponsibilityForModuleAnalysisAppDomain(); - } - } - } - - private static void AnalyzeSnapinDomainHelper() - { - string path = (string)AppDomain.CurrentDomain.GetData("PathToProcess"); - bool isModuleLoad = (bool)AppDomain.CurrentDomain.GetData("IsModuleLoad"); - Dictionary cmdlets = null; - Dictionary> aliases = null; - Dictionary providers = null; - string throwAwayHelpFile = null; - Version assemblyVersion = new Version("0.0.0.0"); - - try - { - Assembly assembly = null; - - try - { - // If this is a fully-qualified search, load it from the file - if (Path.IsPathRooted(path)) - { - assembly = InitialSessionState.LoadAssemblyFromFile(path); - } - else - { - // Otherwise, load it from the GAC - Exception ignored = null; - assembly = ExecutionContext.LoadAssembly(path, null, out ignored); - } - - if (assembly != null) - { - assemblyVersion = GetAssemblyVersionNumber(assembly); - } - } - // Catch-all OK, analyzing user code. - catch (Exception) - { - } - - if (assembly != null) - { - PSSnapInHelpers.AnalyzePSSnapInAssembly(assembly, assembly.Location, null, null, isModuleLoad, out cmdlets, out aliases, out providers, out throwAwayHelpFile); - } - } - // Catch-all OK, analyzing user code. - catch (Exception) - { - } - - List detectedCmdlets = new List(); - List> detectedAliases = new List>(); - - if (cmdlets != null) - { - foreach (SessionStateCmdletEntry cmdlet in cmdlets.Values) - { - detectedCmdlets.Add(cmdlet.Name); - } - } - - if (aliases != null) - { - foreach (List aliasList in aliases.Values) - { - foreach (SessionStateAliasEntry alias in aliasList) - { - detectedAliases.Add(new Tuple(alias.Name, alias.Definition)); - } - } - } - - AppDomain.CurrentDomain.SetData("DetectedCmdlets", detectedCmdlets); - AppDomain.CurrentDomain.SetData("DetectedAliases", detectedAliases); - AppDomain.CurrentDomain.SetData("AssemblyVersion", assemblyVersion); - } -#endif // Analyzes a script module implementation for its exports. private static readonly Dictionary s_scriptAnalysisCache = new Dictionary(); @@ -6435,7 +6405,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon // If this has an extension, and it's a relative path, // then we need to ensure it's a fully-qualified path - if ((moduleToProcess.IndexOfAny(Path.GetInvalidPathChars()) == -1) && + if ((!PathUtils.ContainsInvalidPathChars(moduleToProcess)) && Path.HasExtension(moduleToProcess) && (!Path.IsPathRooted(moduleToProcess))) { @@ -6524,7 +6494,7 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon /// /// Load a binary module. A binary module is an assembly that should contain cmdlets. /// - /// If true, then the registered snapins will also be searched when loading. + /// The parent module for which this module is a nested module. /// The name of the snapin or assembly to load. /// The path to the assembly to load. /// The assembly to load so no lookup need be done. @@ -6536,13 +6506,11 @@ private PSModuleInfo AnalyzeScriptFile(string filename, bool force, ExecutionCon /// /// The set of options that are used while importing a module. /// The manifest processing flags to use when processing the module. - /// Load the types files mentioned in the snapin registration. - /// Load the formst files mentioned in the snapin registration. /// Command name prefix. /// Sets this to true if an assembly was found. /// THe module info object that was created... internal PSModuleInfo LoadBinaryModule( - bool trySnapInName, + PSModuleInfo parentModule, string moduleName, string fileName, Assembly assemblyToLoad, @@ -6551,13 +6519,10 @@ internal PSModuleInfo LoadBinaryModule( ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, string prefix, - bool loadTypes, - bool loadFormats, out bool found) { return LoadBinaryModule( - parentModule: null, - trySnapInName, + parentModule, moduleName, fileName, assemblyToLoad, @@ -6566,8 +6531,6 @@ internal PSModuleInfo LoadBinaryModule( options, manifestProcessingFlags, prefix, - loadTypes, - loadFormats, out found, shortModuleName: null, disableFormatUpdates: false); @@ -6577,7 +6540,6 @@ internal PSModuleInfo LoadBinaryModule( /// Load a binary module. A binary module is an assembly that should contain cmdlets. /// /// The parent module for which this module is a nested module. - /// If true, then the registered snapins will also be searched when loading. /// The name of the snapin or assembly to load. /// The path to the assembly to load. /// The assembly to load so no lookup need be done. @@ -6590,15 +6552,12 @@ internal PSModuleInfo LoadBinaryModule( /// The set of options that are used while importing a module. /// The manifest processing flags to use when processing the module. /// Command name prefix. - /// Load the types files mentioned in the snapin registration. - /// Load the formst files mentioned in the snapin registration. /// Sets this to true if an assembly was found. /// Short name for module. /// /// THe module info object that was created... internal PSModuleInfo LoadBinaryModule( PSModuleInfo parentModule, - bool trySnapInName, string moduleName, string fileName, Assembly assemblyToLoad, @@ -6607,45 +6566,36 @@ internal PSModuleInfo LoadBinaryModule( ImportModuleOptions options, ManifestProcessingFlags manifestProcessingFlags, string prefix, - bool loadTypes, - bool loadFormats, out bool found, string shortModuleName, bool disableFormatUpdates) { - PSModuleInfo module = null; - if (string.IsNullOrEmpty(moduleName) && string.IsNullOrEmpty(fileName) && assemblyToLoad == null) + { throw PSTraceSource.NewArgumentNullException("moduleName,fileName,assemblyToLoad"); + } + + bool isParentEngineModule = parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name); // Load the dll and process any cmdlets it might contain... InitialSessionState iss = InitialSessionState.Create(); List detectedCmdlets = null; List> detectedAliases = null; Assembly assembly = null; - Exception error = null; - bool importSuccessful = false; string modulePath = string.Empty; Version assemblyVersion = new Version(0, 0, 0, 0); - var importingModule = (manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0; + bool importingModule = (manifestProcessingFlags & ManifestProcessingFlags.LoadElements) != 0; // See if we're loading a straight assembly... if (assemblyToLoad != null) { // Figure out what to use for a module path... - if (!string.IsNullOrEmpty(fileName)) - { - modulePath = fileName; - } - else - { - modulePath = assemblyToLoad.Location; - } + modulePath = string.IsNullOrEmpty(fileName) ? assemblyToLoad.Location : fileName; // And what to use for a module name... if (string.IsNullOrEmpty(moduleName)) { - moduleName = "dynamic_code_module_" + assemblyToLoad.GetName(); + moduleName = "dynamic_code_module_" + assemblyToLoad.FullName; } if (importingModule) @@ -6653,191 +6603,73 @@ internal PSModuleInfo LoadBinaryModule( // Passing module as a parameter here so that the providers can have the module property populated. // For engine providers, the module should point to top-level module name // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation - if (parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name)) - { - iss.ImportCmdletsFromAssembly(assemblyToLoad, parentModule); - } - else - { - iss.ImportCmdletsFromAssembly(assemblyToLoad, null); - } + iss.ImportCmdletsFromAssembly(assemblyToLoad, isParentEngineModule ? parentModule : null); } assemblyVersion = GetAssemblyVersionNumber(assemblyToLoad); assembly = assemblyToLoad; - // If this is an in-memory only assembly, add it directly to the assembly cache if - // it isn't already there. - if (string.IsNullOrEmpty(assembly.Location)) - { - if (!Context.AssemblyCache.ContainsKey(assembly.FullName)) - { - Context.AssemblyCache.Add(assembly.FullName, assembly); - } - } + + // Use the parent module name for caching if there is one. + string source = parentModule?.Name ?? moduleName; + // Add it to the assembly cache if it isn't already there. + Context.AddToAssemblyCache(source, assembly); } - else + else if (importingModule) { - // Avoid trying to import a PowerShell assembly as Snapin as it results in PSArgumentException - if ((moduleName != null) && Utils.IsPowerShellAssembly(moduleName)) - { - trySnapInName = false; - } + // Use the parent module name for caching if there is one. + string source = parentModule?.Name ?? moduleName; + assembly = Context.AddAssembly(source, moduleName, fileName, out Exception error); - if (trySnapInName && PSSnapInInfo.IsPSSnapinIdValid(moduleName)) + if (assembly == null) { - PSSnapInInfo snapin = null; - -#if !CORECLR - // Avoid trying to load SnapIns with Import-Module - PSSnapInException warning; - try + if (error != null) { - if (importingModule) - { - snapin = iss.ImportPSSnapIn(moduleName, out warning); - } - } - catch (PSArgumentException) - { - // BUGBUG - brucepay - probably want to have a verbose message here... + throw error; } -#endif - - if (snapin != null) - { - importSuccessful = true; - if (string.IsNullOrEmpty(fileName)) - modulePath = snapin.AbsoluteModulePath; - else - modulePath = fileName; - assemblyVersion = snapin.Version; - // If we're not supposed to load the types files from the snapin - // clear the iss member - if (!loadTypes) - { - iss.Types.Reset(); - } - // If we're not supposed to load the format files from the snapin, - // clear the iss member - if (!loadFormats) - { - iss.Formats.Reset(); - } - foreach (var a in ClrFacade.GetAssemblies()) - { - if (a.GetName().FullName.Equals(snapin.AssemblyName, StringComparison.Ordinal)) - { - assembly = a; - break; - } - } - } + found = false; + return null; } - if (!importSuccessful) - { - if (importingModule) - { - assembly = Context.AddAssembly(moduleName, fileName, out error); - - if (assembly == null) - { - if (error != null) - throw error; - - found = false; - return null; - } - - assemblyVersion = GetAssemblyVersionNumber(assembly); + assemblyVersion = GetAssemblyVersionNumber(assembly); + modulePath = string.IsNullOrEmpty(fileName) ? assembly.Location : fileName; - if (string.IsNullOrEmpty(fileName)) - modulePath = assembly.Location; - else - modulePath = fileName; - - // Passing module as a parameter here so that the providers can have the module property populated. - // For engine providers, the module should point to top-level module name - // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation - if (parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name)) - { - iss.ImportCmdletsFromAssembly(assembly, parentModule); - } - else - { - iss.ImportCmdletsFromAssembly(assembly, null); - } - } - else - { - string binaryPath = fileName; - modulePath = fileName; - if (binaryPath == null) - { - binaryPath = System.IO.Path.Combine(moduleBase, moduleName); - } + // Passing module as a parameter here so that the providers can have the module property populated. + // For engine providers, the module should point to top-level module name + // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation + iss.ImportCmdletsFromAssembly(assembly, isParentEngineModule ? parentModule : null); + } + else + { + string binaryPath = fileName; + modulePath = fileName; + binaryPath ??= System.IO.Path.Combine(moduleBase, moduleName); - BinaryAnalysisResult analysisResult = GetCmdletsFromBinaryModuleImplementation(binaryPath, manifestProcessingFlags, out assemblyVersion); - detectedCmdlets = analysisResult.DetectedCmdlets; - detectedAliases = analysisResult.DetectedAliases; - } - } + BinaryAnalysisResult analysisResult = GetCmdletsFromBinaryModuleImplementation(binaryPath, manifestProcessingFlags, out assemblyVersion); + detectedCmdlets = analysisResult.DetectedCmdlets; + detectedAliases = analysisResult.DetectedAliases; } found = true; - if (string.IsNullOrEmpty(shortModuleName)) - module = new PSModuleInfo(moduleName, modulePath, Context, ss); - else - module = new PSModuleInfo(shortModuleName, modulePath, Context, ss); + string nameToUse = string.IsNullOrEmpty(shortModuleName) ? moduleName : shortModuleName; + PSModuleInfo module = new PSModuleInfo(nameToUse, modulePath, Context, ss); module.SetModuleType(ModuleType.Binary); module.SetModuleBase(moduleBase); module.SetVersion(assemblyVersion); - module.ImplementingAssembly = assemblyToLoad ?? assembly; + module.ImplementingAssembly = assembly; if (importingModule) { SetModuleLoggingInformation(module); } - // Add the types table entries - List typesFileNames = new List(); - foreach (SessionStateTypeEntry sste in iss.Types) - { - typesFileNames.Add(sste.FileName); - } - - if (typesFileNames.Count > 0) - { - module.SetExportedTypeFiles(new ReadOnlyCollection(typesFileNames)); - } - - // Add the format file entries - List formatsFileNames = new List(); - foreach (SessionStateFormatEntry ssfe in iss.Formats) - { - formatsFileNames.Add(ssfe.FileName); - } - - if (formatsFileNames.Count > 0) - { - module.SetExportedFormatFiles(new ReadOnlyCollection(formatsFileNames)); - } - // Add the module info the providers... foreach (SessionStateProviderEntry sspe in iss.Providers) { // For engine providers, the module should point to top-level module name // For FileSystem, the module is Microsoft.PowerShell.Core and not System.Management.Automation - if (parentModule != null && InitialSessionState.IsEngineModule(parentModule.Name)) - { - sspe.SetModule(parentModule); - } - else - { - sspe.SetModule(module); - } + sspe.SetModule(isParentEngineModule ? parentModule : module); } // Add all of the exported cmdlets to the module object... @@ -6951,16 +6783,7 @@ internal PSModuleInfo LoadBinaryModule( iss.Bind(Context, updateOnly: true, module, options.NoClobber, options.Local, setLocation: false); // Scan all of the types in the assembly to register JobSourceAdapters. - IEnumerable allTypes = Array.Empty(); - if (assembly != null) - { - allTypes = assembly.ExportedTypes; - } - else if (assemblyToLoad != null) - { - allTypes = assemblyToLoad.ExportedTypes; - } - + IEnumerable allTypes = assembly?.ExportedTypes ?? Array.Empty(); foreach (Type type in allTypes) { // If it derives from JobSourceAdapter and it's not already registered, register it... @@ -7150,17 +6973,7 @@ internal static void AddModuleToModuleTables(ExecutionContext context, SessionSt targetSessionState.ModuleTableKeys.Add(moduleTableKey); } - if (targetSessionState.Module != null) - { - targetSessionState.Module.AddNestedModule(module); - } - - var privateDataHashTable = module.PrivateData as Hashtable; - if (!context.Modules.IsImplicitRemotingModuleLoaded && - privateDataHashTable != null && privateDataHashTable.ContainsKey("ImplicitRemoting")) - { - context.Modules.IsImplicitRemotingModuleLoaded = true; - } + targetSessionState.Module?.AddNestedModule(module); } /// @@ -7462,6 +7275,9 @@ private static void ImportFunctions(FunctionInfo func, SessionStateInternal targ CommandOrigin.Internal, targetSessionState.ExecutionContext); + // Note that the module 'func' and the function table 'functionInfo' instances are now linked + // together (see 'CopiedCommand' in CommandInfo class), so setting visibility on one also + // sets it on the other. SetCommandVisibility(isImportModulePrivate, functionInfo); functionInfo.Module = sourceModule; @@ -7611,29 +7427,6 @@ private static void ValidateCommandName(ModuleCmdletBase cmdlet, } } - /// - /// Search a PSSnapin with the specified name. - /// - internal static PSSnapInInfo GetEngineSnapIn(ExecutionContext context, string name) - { - HashSet snapinSet = new HashSet(); - List cmdlets = context.SessionState.InvokeCommand.GetCmdlets(); - foreach (CmdletInfo cmdlet in cmdlets) - { - PSSnapInInfo snapin = cmdlet.PSSnapIn; - if (snapin != null && !snapinSet.Contains(snapin)) - snapinSet.Add(snapin); - } - - foreach (PSSnapInInfo snapin in snapinSet) - { - if (string.Equals(snapin.Name, name, StringComparison.OrdinalIgnoreCase)) - return snapin; - } - - return null; - } - /// /// Returns the context cached ModuleTable module for import only if found and has safe language boundaries while /// exporting all functions by default. @@ -7646,7 +7439,7 @@ internal static PSSnapInInfo GetEngineSnapIn(ExecutionContext context, string na /// /// Note that module loading order is important with this check when the system is *locked down with DeviceGuard*. /// If a submodule that does not explicitly export any functions is imported from the command line, its useless - /// because no functions are exported (default fn export is explictly disallowed on locked down systems). + /// because no functions are exported (default fn export is explicitly disallowed on locked down systems). /// But if a parentmodule that imports the submodule is then imported, it will get the useless version of the /// module from the ModuleTable and the parent module will not work. /// $mSub = import-module SubModule # No functions exported, useless @@ -7654,7 +7447,7 @@ internal static PSSnapInInfo GetEngineSnapIn(ExecutionContext context, string na /// $mParent.DoSomething # This will likely be broken because SubModule functions are not accessible /// But this is not a realistic scenario because SubModule is useless with DeviceGuard lock down and must explicitly /// export its functions to become useful, at which point this check is no longer in effect and there is no issue. - /// $mSub = import-module SubModule # Explictly exports functions, useful + /// $mSub = import-module SubModule # Explicitly exports functions, useful /// $mParent = import-module ParentModule # This internally imports SubModule /// $mParent.DoSomething # This works because SubModule functions are exported and accessible. /// diff --git a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs index 9d5af609710..538c4775f0a 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleIntrinsics.cs @@ -10,9 +10,7 @@ using System.Management.Automation.Language; using System.Text; using System.Threading; - using Microsoft.PowerShell.Commands; -using Microsoft.Win32; using Dbg = System.Management.Automation.Diagnostics; @@ -39,30 +37,25 @@ public class ModuleIntrinsics private static readonly string s_windowsPowerShellPSHomeModulePath = Path.Combine(System.Environment.SystemDirectory, "WindowsPowerShell", "v1.0", "Modules"); + static ModuleIntrinsics() + { + // Initialize the module path. + SetModulePath(); + } + internal ModuleIntrinsics(ExecutionContext context) { _context = context; - - // And initialize the module path... - SetModulePath(); + ModuleTable = new Dictionary(StringComparer.OrdinalIgnoreCase); } private readonly ExecutionContext _context; // Holds the module collection... - internal Dictionary ModuleTable { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + internal Dictionary ModuleTable { get; } private const int MaxModuleNestingDepth = 10; - /// - /// Gets and sets boolean that indicates when an implicit remoting module is loaded. - /// - internal bool IsImplicitRemotingModuleLoaded - { - get; - set; - } - internal void IncrementModuleNestingDepth(PSCmdlet cmdlet, string path) { if (++ModuleNestingDepth > MaxModuleNestingDepth) @@ -150,10 +143,7 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object // script scope for the ss. // Allocate the session state instance for this module. - if (ss == null) - { - ss = new SessionState(_context, true, true); - } + ss ??= new SessionState(_context, true, true); // Now set up the module's session state to be the current session state SessionStateInternal oldSessionState = _context.EngineSessionState; @@ -188,11 +178,9 @@ private PSModuleInfo CreateModuleImplementation(string name, string path, object sb.SessionState = ss; } - else + else if (moduleCode is string sbText) { - var sbText = moduleCode as string; - if (sbText != null) - sb = ScriptBlock.Create(_context, sbText); + sb = ScriptBlock.Create(_context, sbText); } } @@ -279,7 +267,7 @@ internal List GetModules(string[] patterns, bool all) internal List GetExactMatchModules(string moduleName, bool all, bool exactMatch) { - if (moduleName == null) { moduleName = string.Empty; } + moduleName ??= string.Empty; return GetModuleCore(new string[] { moduleName }, all, exactMatch); } @@ -296,10 +284,7 @@ private List GetModuleCore(string[] patterns, bool all, bool exact } else { - if (patterns == null) - { - patterns = new string[] { "*" }; - } + patterns ??= new string[] { "*" }; foreach (string pattern in patterns) { @@ -358,7 +343,7 @@ private List GetModuleCore(string[] patterns, bool all, bool exact } } - return modulesMatched.OrderBy(m => m.Name).ToList(); + return modulesMatched.OrderBy(static m => m.Name).ToList(); } internal List GetModules(ModuleSpecification[] fullyQualifiedName, bool all) @@ -417,7 +402,7 @@ internal List GetModules(ModuleSpecification[] fullyQualifiedName, } } - return modulesMatched.OrderBy(m => m.Name).ToList(); + return modulesMatched.OrderBy(static m => m.Name).ToList(); } /// @@ -730,7 +715,7 @@ internal static bool MatchesModulePath(string modulePath, string requiredPath) string moduleDirPath = Path.GetDirectoryName(modulePath); // The module itself may be in a versioned directory (case 3) - if (Version.TryParse(Path.GetFileName(moduleDirPath), out Version unused)) + if (Version.TryParse(Path.GetFileName(moduleDirPath), out _)) { moduleDirPath = Path.GetDirectoryName(moduleDirPath); } @@ -874,7 +859,10 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath foreach (Hashtable feature in features) { string featureName = feature["Name"] as string; - if (string.IsNullOrEmpty(featureName)) { continue; } + if (string.IsNullOrEmpty(featureName)) + { + continue; + } if (ExperimentalFeature.IsModuleFeatureName(featureName, moduleName)) { @@ -894,25 +882,35 @@ internal static ExperimentalFeature[] GetExperimentalFeature(string manifestPath } // The extensions of all of the files that can be processed with Import-Module, put the ni.dll in front of .dll to have higher priority to be loaded. - internal static readonly string[] PSModuleProcessableExtensions = new string[] { - StringLiterals.PowerShellDataFileExtension, - StringLiterals.PowerShellScriptFileExtension, - StringLiterals.PowerShellModuleFileExtension, - StringLiterals.PowerShellCmdletizationFileExtension, - StringLiterals.PowerShellNgenAssemblyExtension, - StringLiterals.PowerShellILAssemblyExtension, - StringLiterals.PowerShellILExecutableExtension, - }; + internal static readonly string[] PSModuleProcessableExtensions = new string[] + { + StringLiterals.PowerShellDataFileExtension, + StringLiterals.PowerShellScriptFileExtension, + StringLiterals.PowerShellModuleFileExtension, + StringLiterals.PowerShellCmdletizationFileExtension, + StringLiterals.PowerShellNgenAssemblyExtension, + StringLiterals.PowerShellILAssemblyExtension, + StringLiterals.PowerShellILExecutableExtension, + }; // A list of the extensions to check for implicit module loading and discovery, put the ni.dll in front of .dll to have higher priority to be loaded. - internal static readonly string[] PSModuleExtensions = new string[] { - StringLiterals.PowerShellDataFileExtension, - StringLiterals.PowerShellModuleFileExtension, - StringLiterals.PowerShellCmdletizationFileExtension, - StringLiterals.PowerShellNgenAssemblyExtension, - StringLiterals.PowerShellILAssemblyExtension, - StringLiterals.PowerShellILExecutableExtension, - }; + internal static readonly string[] PSModuleExtensions = new string[] + { + StringLiterals.PowerShellDataFileExtension, + StringLiterals.PowerShellModuleFileExtension, + StringLiterals.PowerShellCmdletizationFileExtension, + StringLiterals.PowerShellNgenAssemblyExtension, + StringLiterals.PowerShellILAssemblyExtension, + StringLiterals.PowerShellILExecutableExtension, + }; + + // A list of the extensions to check for required assemblies. + internal static readonly string[] ProcessableAssemblyExtensions = new string[] + { + StringLiterals.PowerShellNgenAssemblyExtension, + StringLiterals.PowerShellILAssemblyExtension, + StringLiterals.PowerShellILExecutableExtension + }; /// /// Returns true if the extension is one of the module extensions... @@ -924,7 +922,9 @@ internal static bool IsPowerShellModuleExtension(string extension) foreach (string ext in PSModuleProcessableExtensions) { if (extension.Equals(ext, StringComparison.OrdinalIgnoreCase)) + { return true; + } } return false; @@ -967,7 +967,10 @@ internal static string GetPersonalModulePath() #if UNIX return Platform.SelectProductNameForDirectory(Platform.XDG_Type.USER_MODULES); #else - return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), Utils.ModuleDirectory); + string myDocumentsPath = InternalTestHooks.SetMyDocumentsSpecialFolderToBlank + ? string.Empty + : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.DoNotVerify); + return string.IsNullOrEmpty(myDocumentsPath) ? null : Path.Combine(myDocumentsPath, Utils.ModuleDirectory); #endif } @@ -985,20 +988,17 @@ internal static string GetPSHomeModulePath() try { string psHome = Utils.DefaultPowerShellAppBase; - if (!string.IsNullOrEmpty(psHome)) - { - // Win8: 584267 Powershell Modules are listed twice in x86, and cannot be removed - // This happens because ModuleTable uses Path as the key and CBS installer - // expands the path to include "SysWOW64" (for - // HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\PowerShell\3\PowerShellEngine ApplicationBase). - // Because of this, the module that is getting loaded during startup (through LocalRunspace) - // is using "SysWow64" in the key. Later, when Import-Module is called, it loads the - // module using ""System32" in the key. #if !UNIX - psHome = psHome.ToLowerInvariant().Replace("\\syswow64\\", "\\system32\\"); + // Win8: 584267 Powershell Modules are listed twice in x86, and cannot be removed. + // This happens because 'ModuleTable' uses Path as the key and x86 WinPS has "SysWOW64" in its $PSHOME. + // Because of this, the module that is getting loaded during startup (through LocalRunspace) is using + // "SysWow64" in the key. Later, when 'Import-Module' is called, it loads the module using ""System32" + // in the key. + // For the cross-platform PowerShell, a user can choose to install it under "C:\Windows\SysWOW64", and + // thus it may have the same problem as described above. So we keep this line of code. + psHome = psHome.ToLowerInvariant().Replace(@"\syswow64\", @"\system32\"); #endif - Interlocked.CompareExchange(ref s_psHomeModulePath, Path.Combine(psHome, "Modules"), null); - } + Interlocked.CompareExchange(ref s_psHomeModulePath, Path.Combine(psHome, "Modules"), null); } catch (System.Security.SecurityException) { @@ -1085,86 +1085,118 @@ internal static string GetExpandedEnvironmentVariable(string name, EnvironmentVa } /// - /// Checks if a particular string (path) is a member of 'combined path' string (like %Path% or %PSModulePath%) + /// Adds paths to a 'combined path' string (like %Path% or %PSModulePath%) if they are not already there. /// - /// 'Combined path' string to analyze; can not be null. - /// Path to search for; can not be another 'combined path' (semicolon-separated); can not be null. - /// Index of pathToLookFor in pathToScan; -1 if not found. - private static int PathContainsSubstring(string pathToScan, string pathToLookFor) + /// Path string (like %Path% or %PSModulePath%). + /// An individual path to add, or multiple paths separated by the path separator character. + /// -1 to append to the end; 0 to insert in the beginning of the string; etc... + /// Result string. + private static string UpdatePath(string basePath, string pathToAdd, ref int insertPosition) { // we don't support if any of the args are null - parent function should ensure this; empty values are ok - Diagnostics.Assert(pathToScan != null, "pathToScan should not be null according to contract of the function"); - Diagnostics.Assert(pathToLookFor != null, "pathToLookFor should not be null according to contract of the function"); + Dbg.Assert(basePath != null, "basePath should not be null according to contract of the function"); + Dbg.Assert(pathToAdd != null, "pathToAdd should not be null according to contract of the function"); + + // The 'pathToAdd' could be a 'combined path' (path-separator-separated). + string[] newPaths = pathToAdd.Split( + Path.PathSeparator, + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - int pos = 0; // position of the current substring in pathToScan - string[] substrings = pathToScan.Split(Utils.Separators.PathSeparator, StringSplitOptions.None); // we want to process empty entries - string goodPathToLookFor = pathToLookFor.Trim().TrimEnd(Path.DirectorySeparatorChar); // trailing backslashes and white-spaces will mess up equality comparison - foreach (string substring in substrings) + if (newPaths.Length is 0) { - string goodSubstring = substring.Trim().TrimEnd(Path.DirectorySeparatorChar); // trailing backslashes and white-spaces will mess up equality comparison + // The 'pathToAdd' doesn't really contain any paths to add. + return basePath; + } - // We have to use equality comparison on individual substrings (as opposed to simple 'string.IndexOf' or 'string.Contains') - // because of cases like { pathToScan="C:\Temp\MyDir\MyModuleDir", pathToLookFor="C:\Temp" } + var result = new StringBuilder(basePath, capacity: basePath.Length + pathToAdd.Length + newPaths.Length); + var addedPaths = new HashSet(StringComparer.OrdinalIgnoreCase); + string[] initialPaths = basePath.Split( + Path.PathSeparator, + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); - if (string.Equals(goodSubstring, goodPathToLookFor, StringComparison.OrdinalIgnoreCase)) + foreach (string p in initialPaths) + { + // Remove the trailing directory separators. + // Trailing white spaces were already removed by 'StringSplitOptions.TrimEntries'. + addedPaths.Add(Path.TrimEndingDirectorySeparator(p)); + } + + foreach (string subPathToAdd in newPaths) + { + // Remove the trailing directory separators. + // Trailing white spaces were already removed by 'StringSplitOptions.TrimEntries'. + string normalizedPath = Path.TrimEndingDirectorySeparator(subPathToAdd); + if (addedPaths.Contains(normalizedPath)) { - return pos; // match found - return index of it in the 'pathToScan' string + // The normalized sub path was already added - skip it. + continue; + } + + // The normalized sub path was not found - add it. + if (insertPosition is -1 || insertPosition >= result.Length) + { + // Append the normalized sub path to the end. + if (result.Length > 0 && result[^1] != Path.PathSeparator) + { + result.Append(Path.PathSeparator); + } + + result.Append(normalizedPath); + // Next insertion should happen at the end. + insertPosition = result.Length; } else { - pos += substring.Length + 1; // '1' is for trailing semicolon + // Insert at the requested location. + // This is used by the user-specific module path, the shared module path ( location), and the PSHome module path. + string strToInsert = normalizedPath + Path.PathSeparator; + result.Insert(insertPosition, strToInsert); + + // Next insertion should happen after the just inserted string. + insertPosition += strToInsert.Length; } + + // Add it to the set. + addedPaths.Add(normalizedPath); } - // if we are here, that means a match was not found - return -1; + + return result.ToString(); } /// - /// Adds paths to a 'combined path' string (like %Path% or %PSModulePath%) if they are not already there. + /// The available module path scopes. /// - /// Path string (like %Path% or %PSModulePath%). - /// Collection of individual paths to add. - /// -1 to append to the end; 0 to insert in the beginning of the string; etc... - /// Result string. - private static string AddToPath(string basePath, string pathToAdd, int insertPosition) + public enum PSModulePathScope { - // we don't support if any of the args are null - parent function should ensure this; empty values are ok - Diagnostics.Assert(basePath != null, "basePath should not be null according to contract of the function"); - Diagnostics.Assert(pathToAdd != null, "pathToAdd should not be null according to contract of the function"); + /// The users module path. + User, - StringBuilder result = new StringBuilder(basePath); + /// The Builtin module path. This is where PowerShell is installed (PSHOME). + Builtin, - if (!string.IsNullOrEmpty(pathToAdd)) // we don't want to append empty paths - { - foreach (string subPathToAdd in pathToAdd.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) // in case pathToAdd is a 'combined path' (semicolon-separated) - { - int position = PathContainsSubstring(result.ToString(), subPathToAdd); // searching in effective 'result' value ensures that possible duplicates in pathsToAdd are handled correctly - if (position == -1) // subPathToAdd not found - add it - { - if (insertPosition == -1) // append subPathToAdd to the end - { - bool endsWithPathSeparator = false; - if (result.Length > 0) endsWithPathSeparator = (result[result.Length - 1] == Path.PathSeparator); + /// The machine module path. This is the shared location for all users of the system. + Machine + } - if (endsWithPathSeparator) - result.Append(subPathToAdd); - else - result.Append(Path.PathSeparator + subPathToAdd); - } - else if (insertPosition > result.Length) - { - // handle case where path is a singleton with no path seperator already - result.Append(Path.PathSeparator).Append(subPathToAdd); - } - else // insert at the requested location (this is used by DSC ( location) and by 'user-specific location' (SpecialFolder.MyDocuments or EVT.User)) - { - result.Insert(insertPosition, subPathToAdd + Path.PathSeparator); - } - } - } + /// + /// Retrieve the current PSModulePath for the specified scope. + /// + /// The scope of module path to retrieve. This can be User, Builtin, or Machine. + /// The string representing the requested module path type. + public static string GetPSModulePath(PSModulePathScope scope) + { + if (scope == PSModulePathScope.User) + { + return GetPersonalModulePath(); + } + else if (scope == PSModulePathScope.Builtin) + { + return GetPSHomeModulePath(); + } + else + { + return GetSharedModulePath(); } - - return result.ToString(); } /// @@ -1177,7 +1209,7 @@ public static string GetModulePath(string currentProcessModulePath, string hklmM string psHomeModulePath = GetPSHomeModulePath(); // $PSHome\Modules location // If the variable isn't set, then set it to the default value - if (currentProcessModulePath == null) // EVT.Process does Not exist - really corner case + if (string.IsNullOrEmpty(currentProcessModulePath)) // EVT.Process does Not exist - really corner case { // Handle the default case... if (string.IsNullOrEmpty(hkcuUserModulePath)) // EVT.User does Not exist -> set to location @@ -1189,7 +1221,15 @@ public static string GetModulePath(string currentProcessModulePath, string hklmM currentProcessModulePath = hkcuUserModulePath; // = EVT.User } - currentProcessModulePath += Path.PathSeparator; + if (string.IsNullOrEmpty(currentProcessModulePath)) + { + currentProcessModulePath ??= string.Empty; + } + else + { + currentProcessModulePath += Path.PathSeparator; + } + if (string.IsNullOrEmpty(hklmMachineModulePath)) // EVT.Machine does Not exist { currentProcessModulePath += CombineSystemModulePaths(); // += (SharedModulePath + $PSHome\Modules) @@ -1210,11 +1250,12 @@ public static string GetModulePath(string currentProcessModulePath, string hklmM // personalModulePath // sharedModulePath // systemModulePath - currentProcessModulePath = AddToPath(currentProcessModulePath, personalModulePathToUse, 0); - int insertIndex = PathContainsSubstring(currentProcessModulePath, personalModulePathToUse) + personalModulePathToUse.Length + 1; - currentProcessModulePath = AddToPath(currentProcessModulePath, sharedModulePath, insertIndex); - insertIndex = PathContainsSubstring(currentProcessModulePath, sharedModulePath) + sharedModulePath.Length + 1; - currentProcessModulePath = AddToPath(currentProcessModulePath, systemModulePathToUse, insertIndex); + + int insertIndex = 0; + + currentProcessModulePath = UpdatePath(currentProcessModulePath, personalModulePathToUse, ref insertIndex); + currentProcessModulePath = UpdatePath(currentProcessModulePath, sharedModulePath, ref insertIndex); + currentProcessModulePath = UpdatePath(currentProcessModulePath, systemModulePathToUse, ref insertIndex); } return currentProcessModulePath; @@ -1233,7 +1274,7 @@ internal static string GetModulePath() #if !UNIX /// - /// Returns a PSModulePath suiteable for Windows PowerShell by removing PowerShell's specific + /// Returns a PSModulePath suitable for Windows PowerShell by removing PowerShell's specific /// paths from current PSModulePath. /// /// @@ -1258,24 +1299,23 @@ internal static string GetWindowsPowerShellModulePath() }; var modulePathList = new List(); - foreach (var path in currentModulePath.Split(';')) + foreach (var path in currentModulePath.Split(';', StringSplitOptions.TrimEntries)) { - var trimmedPath = path.Trim(); - if (!excludeModulePaths.Contains(trimmedPath)) + if (!excludeModulePaths.Contains(path)) { // make sure this module path is Not part of other PS Core installation - var possiblePwshDir = Path.GetDirectoryName(trimmedPath); + var possiblePwshDir = Path.GetDirectoryName(path); if (string.IsNullOrEmpty(possiblePwshDir)) { // i.e. module dir is in the drive root - modulePathList.Add(trimmedPath); + modulePathList.Add(path); } else { if (!File.Exists(Path.Combine(possiblePwshDir, "pwsh.dll"))) { - modulePathList.Add(trimmedPath); + modulePathList.Add(path); } } } @@ -1294,11 +1334,16 @@ private static string SetModulePath() { string currentModulePath = GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.Process); #if !UNIX - // if the current process and user env vars are the same, it means we need to append the machine one as it's incomplete - // otherwise, the user modified it and we should use the process one + // if the current process and user env vars are the same, it means we need to append the machine one as it's incomplete. + // Otherwise, the user modified it and we should use the process one. if (string.CompareOrdinal(GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.User), currentModulePath) == 0) { - currentModulePath = currentModulePath + Path.PathSeparator + GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.Machine); + string machineScopeValue = GetExpandedEnvironmentVariable(Constants.PSModulePathEnvVar, EnvironmentVariableTarget.Machine); + currentModulePath = string.IsNullOrEmpty(currentModulePath) + ? machineScopeValue + : string.IsNullOrEmpty(machineScopeValue) + ? currentModulePath + : string.Concat(currentModulePath, Path.PathSeparator, machineScopeValue); } #endif string allUsersModulePath = PowerShellConfig.Instance.GetModulePath(ConfigScope.AllUsers); @@ -1336,7 +1381,7 @@ internal static IEnumerable GetModulePath(bool includeSystemModulePath, if (!string.IsNullOrWhiteSpace(modulePathString)) { - foreach (string envPath in modulePathString.Split(Utils.Separators.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) + foreach (string envPath in modulePathString.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries)) { var processedPath = ProcessOneModulePath(context, envPath, processedPathSet); if (processedPath != null) @@ -1422,32 +1467,10 @@ private static string ProcessOneModulePath(ExecutionContext context, string envP return null; } - /// - /// Removes all functions not belonging to the parent module. - /// - /// Parent module. - internal static void RemoveNestedModuleFunctions(PSModuleInfo module) - { - var input = module.SessionState?.Internal?.ExportedFunctions; - if ((input == null) || (input.Count == 0)) - { return; } - - List output = new List(input.Count); - foreach (var fnInfo in input) - { - if (module.Name.Equals(fnInfo.ModuleName, StringComparison.OrdinalIgnoreCase)) - { - output.Add(fnInfo); - } - } - - input.Clear(); - input.AddRange(output); - } - +#nullable enable private static void SortAndRemoveDuplicates(List input, Func keyGetter) { - Dbg.Assert(input != null, "Caller should verify that input != null"); + Dbg.Assert(input is not null, "Caller should verify that input != null"); input.Sort( (T x, T y) => @@ -1458,24 +1481,19 @@ private static void SortAndRemoveDuplicates(List input, Func ke } ); - bool firstItem = true; - string previousKey = null; - List output = new List(input.Count); - foreach (T item in input) + string? previousKey = null; + input.RemoveAll(ShouldRemove); + + bool ShouldRemove(T item) { string currentKey = keyGetter(item); - if ((firstItem) || !currentKey.Equals(previousKey, StringComparison.OrdinalIgnoreCase)) - { - output.Add(item); - } - + bool match = previousKey is not null + && currentKey.Equals(previousKey, StringComparison.OrdinalIgnoreCase); previousKey = currentKey; - firstItem = false; + return match; } - - input.Clear(); - input.AddRange(output); } +#nullable restore /// /// Mark stuff to be exported from the current environment using the various patterns. @@ -1527,7 +1545,7 @@ internal static void ExportModuleMembers( } } - SortAndRemoveDuplicates(sessionState.ExportedFunctions, (FunctionInfo ci) => ci.Name); + SortAndRemoveDuplicates(sessionState.ExportedFunctions, static (FunctionInfo ci) => ci.Name); } if (cmdletPatterns != null) @@ -1582,7 +1600,7 @@ internal static void ExportModuleMembers( } } - SortAndRemoveDuplicates(sessionState.Module.CompiledExports, (CmdletInfo ci) => ci.Name); + SortAndRemoveDuplicates(sessionState.Module.CompiledExports, static (CmdletInfo ci) => ci.Name); } if (variablePatterns != null) @@ -1605,7 +1623,7 @@ internal static void ExportModuleMembers( } } - SortAndRemoveDuplicates(sessionState.ExportedVariables, (PSVariable v) => v.Name); + SortAndRemoveDuplicates(sessionState.ExportedVariables, static (PSVariable v) => v.Name); } if (aliasPatterns != null) @@ -1645,7 +1663,7 @@ internal static void ExportModuleMembers( } } - SortAndRemoveDuplicates(sessionState.ExportedAliases, (AliasInfo ci) => ci.Name); + SortAndRemoveDuplicates(sessionState.ExportedAliases, static (AliasInfo ci) => ci.Name); } } @@ -1711,10 +1729,11 @@ internal enum ModuleMatchFailure /// Module version was greater than the maximum version. MaximumVersion, - /// The module specifcation passed in was null. + /// The module specification passed in was null. NullModuleSpecification, } +#nullable enable /// /// Used by Modules/Snapins to provide a hook to the engine for startup initialization /// w.r.t compiled assembly loading. diff --git a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs index 315cf3aaf64..3c06ee856f3 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleSpecification.cs @@ -44,12 +44,10 @@ public ModuleSpecification() /// The module name. public ModuleSpecification(string moduleName) { - if (string.IsNullOrEmpty(moduleName)) - { - throw new ArgumentNullException(nameof(moduleName)); - } + ArgumentException.ThrowIfNullOrEmpty(moduleName); this.Name = moduleName; + // Alias name of miniumVersion this.Version = null; this.RequiredVersion = null; @@ -67,10 +65,7 @@ public ModuleSpecification(string moduleName) /// The module specification as a hashtable. public ModuleSpecification(Hashtable moduleSpecification) { - if (moduleSpecification == null) - { - throw new ArgumentNullException(nameof(moduleSpecification)); - } + ArgumentNullException.ThrowIfNull(moduleSpecification); var exception = ModuleSpecificationInitHelper(this, moduleSpecification); if (exception != null) @@ -130,7 +125,7 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu } } // catch all exceptions here, we are going to report them via return value. - // Example of catched exception: one of conversions to Version failed. + // Example of caught exception: one of conversions to Version failed. catch (Exception e) { return e; @@ -170,13 +165,53 @@ internal static Exception ModuleSpecificationInitHelper(ModuleSpecification modu return null; } - internal ModuleSpecification(PSModuleInfo moduleInfo) + internal string GetRequiredModuleNotFoundVersionMessage() { - if (moduleInfo == null) + if (RequiredVersion is not null) { - throw new ArgumentNullException(nameof(moduleInfo)); + return StringUtil.Format( + Modules.RequiredModuleNotFoundRequiredVersion, + Name, + RequiredVersion); } + bool hasVersion = Version is not null; + bool hasMaximumVersion = MaximumVersion is not null; + + if (hasVersion && hasMaximumVersion) + { + return StringUtil.Format( + Modules.RequiredModuleNotFoundModuleAndMaximumVersion, + Name, + Version, + MaximumVersion); + } + + if (hasVersion) + { + return StringUtil.Format( + Modules.RequiredModuleNotFoundModuleVersion, + Name, + Version); + } + + if (hasMaximumVersion) + { + return StringUtil.Format( + Modules.RequiredModuleNotFoundMaximumVersion, + Name, + MaximumVersion); + } + + return StringUtil.Format( + Modules.RequiredModuleNotFoundWithoutVersion, + Name); + } + + internal ModuleSpecification(PSModuleInfo moduleInfo) + { + ArgumentNullException.ThrowIfNull(moduleInfo); + this.Name = moduleInfo.Name; this.Version = moduleInfo.Version; this.Guid = moduleInfo.Guid; diff --git a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs index b2ee85a1b03..41bf4ac3521 100644 --- a/src/System.Management.Automation/engine/Modules/ModuleUtils.cs +++ b/src/System.Management.Automation/engine/Modules/ModuleUtils.cs @@ -13,22 +13,39 @@ namespace System.Management.Automation.Internal { internal static class ModuleUtils { + // These are documented members FILE_ATTRIBUTE, they just have not yet been + // added to System.IO.FileAttributes yet. + private const int FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS = 0x400000; + + private const int FILE_ATTRIBUTE_RECALL_ON_OPEN = 0x40000; + // Default option for local file system enumeration: // - Ignore files/directories when access is denied; // - Search top directory only. private static readonly System.IO.EnumerationOptions s_defaultEnumerationOptions = - new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden }; + new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributesToSkip }; + + private static readonly FileAttributes FileAttributesToSkip; // Default option for UNC path enumeration. Same as above plus a large buffer size. // For network shares, a large buffer may result in better performance as more results can be batched over the wire. // The buffer size 16K is recommended in the comment of the 'BufferSize' property: // "A "large" buffer, for example, would be 16K. Typical is 4K." private static readonly System.IO.EnumerationOptions s_uncPathEnumerationOptions = - new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributes.Hidden, BufferSize = 16384 }; + new System.IO.EnumerationOptions() { AttributesToSkip = FileAttributesToSkip, BufferSize = 16384 }; private static readonly string EnCulturePath = Path.DirectorySeparatorChar + "en"; private static readonly string EnUsCulturePath = Path.DirectorySeparatorChar + "en-us"; + static ModuleUtils() + { + FileAttributesToSkip = FileAttributes.Hidden + // Skip OneDrive files/directories that are not fully on disk. + | FileAttributes.Offline + | (FileAttributes)FILE_ATTRIBUTE_RECALL_ON_DATA_ACCESS + | (FileAttributes)FILE_ATTRIBUTE_RECALL_ON_OPEN; + } + /// /// Check if a directory is likely a localized resources folder. /// @@ -81,8 +98,7 @@ internal static IEnumerable GetAllAvailableModuleFiles(string topDirecto string directoryToCheck = directoriesToCheck.Dequeue(); try { - string[] subDirectories = Directory.GetDirectories(directoryToCheck, "*", options); - foreach (string toAdd in subDirectories) + foreach (string toAdd in Directory.EnumerateDirectories(directoryToCheck, "*", options)) { if (firstSubDirs || !IsPossibleResourceDirectory(toAdd)) { @@ -94,8 +110,7 @@ internal static IEnumerable GetAllAvailableModuleFiles(string topDirecto catch (UnauthorizedAccessException) { } firstSubDirs = false; - string[] files = Directory.GetFiles(directoryToCheck, "*", options); - foreach (string moduleFile in files) + foreach (string moduleFile in Directory.EnumerateFiles(directoryToCheck, "*", options)) { foreach (string ext in ModuleIntrinsics.PSModuleExtensions) { @@ -123,7 +138,7 @@ internal static bool IsPSEditionCompatible( #if UNIX return true; #else - if (!ModuleUtils.IsOnSystem32ModulePath(moduleManifestPath)) + if (!IsOnSystem32ModulePath(moduleManifestPath)) { return true; } @@ -278,6 +293,11 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(string topDir manifestPath += StringLiterals.PowerShellDataFileExtension; if (File.Exists(manifestPath)) { + if (HasSkippedFileAttribute(manifestPath)) + { + continue; + } + isModuleDirectory = true; yield return manifestPath; } @@ -290,6 +310,11 @@ internal static IEnumerable GetDefaultAvailableModuleFiles(string topDir string moduleFile = Path.Combine(directoryToCheck, proposedModuleName) + ext; if (File.Exists(moduleFile)) { + if (HasSkippedFileAttribute(moduleFile)) + { + continue; + } + isModuleDirectory = true; yield return moduleFile; @@ -332,14 +357,33 @@ internal static List GetModuleVersionSubfolders(string moduleBase) if (!string.IsNullOrWhiteSpace(moduleBase) && Directory.Exists(moduleBase)) { var options = Utils.PathIsUnc(moduleBase) ? s_uncPathEnumerationOptions : s_defaultEnumerationOptions; - string[] subdirectories = Directory.GetDirectories(moduleBase, "*", options); + IEnumerable subdirectories = Directory.EnumerateDirectories(moduleBase, "*", options); ProcessPossibleVersionSubdirectories(subdirectories, versionFolders); } return versionFolders; } - private static void ProcessPossibleVersionSubdirectories(string[] subdirectories, List versionFolders) + private static bool HasSkippedFileAttribute(string path) + { + try + { + FileAttributes attributes = File.GetAttributes(path); + if ((attributes & FileAttributesToSkip) is not 0) + { + return true; + } + } + catch + { + // Ignore failures so that we keep the current behavior of failing + // later in the search. + } + + return false; + } + + private static void ProcessPossibleVersionSubdirectories(IEnumerable subdirectories, List versionFolders) { foreach (string subdir in subdirectories) { @@ -352,7 +396,7 @@ private static void ProcessPossibleVersionSubdirectories(string[] subdirectories if (versionFolders.Count > 1) { - versionFolders.Sort((x, y) => y.CompareTo(x)); + versionFolders.Sort(static (x, y) => y.CompareTo(x)); } } @@ -387,15 +431,15 @@ internal static bool IsOnSystem32ModulePath(string path) /// Command pattern. /// Execution context. /// Command origin. + /// Fuzzy matcher to use. /// If true, rediscovers imported modules. /// Specific module version to be required. /// IEnumerable tuple containing the CommandInfo and the match score. - internal static IEnumerable GetFuzzyMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) + internal static IEnumerable GetFuzzyMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, FuzzyMatcher fuzzyMatcher, bool rediscoverImportedModules = false, bool moduleVersionRequired = false) { - foreach (CommandInfo command in GetMatchingCommands(pattern, context, commandOrigin, rediscoverImportedModules, moduleVersionRequired, useFuzzyMatching: true)) + foreach (CommandInfo command in GetMatchingCommands(pattern, context, commandOrigin, rediscoverImportedModules, moduleVersionRequired, fuzzyMatcher: fuzzyMatcher)) { - int score = FuzzyMatcher.GetDamerauLevenshteinDistance(command.Name, pattern); - if (score <= FuzzyMatcher.MinimumDistance) + if (fuzzyMatcher.IsFuzzyMatch(command.Name, pattern, out int score)) { yield return new CommandScore(command, score); } @@ -410,10 +454,10 @@ internal static IEnumerable GetFuzzyMatchingCommands(string patter /// Command origin. /// If true, rediscovers imported modules. /// Specific module version to be required. - /// Use fuzzy matching. + /// Fuzzy matcher for fuzzy searching. /// Use abbreviation expansion for matching. /// Returns matching CommandInfo IEnumerable. - internal static IEnumerable GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, bool useFuzzyMatching = false, bool useAbbreviationExpansion = false) + internal static IEnumerable GetMatchingCommands(string pattern, ExecutionContext context, CommandOrigin commandOrigin, bool rediscoverImportedModules = false, bool moduleVersionRequired = false, FuzzyMatcher fuzzyMatcher = null, bool useAbbreviationExpansion = false) { // Otherwise, if it had wildcards, just return the "AvailableCommand" // type of command info. @@ -437,7 +481,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe // 1. We continue to the next module path if we don't want to re-discover those imported modules // 2. If we want to re-discover the imported modules, but one or more commands from the module were made private, // then we don't do re-discovery - if (!rediscoverImportedModules || modules.Exists(module => module.ModuleHasPrivateMembers)) + if (!rediscoverImportedModules || modules.Exists(static module => module.ModuleHasPrivateMembers)) { continue; } @@ -451,7 +495,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe foreach (KeyValuePair entry in psModule.ExportedCommands) { if (commandPattern.IsMatch(entry.Value.Name) || - (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) || + (fuzzyMatcher is not null && fuzzyMatcher.IsFuzzyMatch(entry.Value.Name, pattern)) || (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(entry.Value.Name), StringComparison.OrdinalIgnoreCase))) { CommandInfo current = null; @@ -511,7 +555,7 @@ internal static IEnumerable GetMatchingCommands(string pattern, Exe CommandTypes commandTypes = pair.Value; if (commandPattern.IsMatch(commandName) || - (useFuzzyMatching && FuzzyMatcher.IsFuzzyMatch(commandName, pattern)) || + (fuzzyMatcher is not null && fuzzyMatcher.IsFuzzyMatch(commandName, pattern)) || (useAbbreviationExpansion && string.Equals(pattern, AbbreviateName(commandName), StringComparison.OrdinalIgnoreCase))) { bool shouldExportCommand = true; diff --git a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs index d47681166a0..ceb5dd3c2e3 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleCommand.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; +using System.Management.Automation.Security; // // Now define the set of commands for manipulating modules. @@ -168,15 +169,24 @@ protected override void EndProcessing() { // Check ScriptBlock language mode. If it is different than the context language mode // then throw error since private trusted script functions may be exposed. - if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && - _scriptBlock.LanguageMode == PSLanguageMode.FullLanguage) + if (Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && _scriptBlock.LanguageMode == PSLanguageMode.FullLanguage) { - this.ThrowTerminatingError( - new ErrorRecord( - new PSSecurityException(Modules.CannotCreateModuleWithScriptBlock), - "Modules_CannotCreateModuleWithFullLanguageScriptBlock", - ErrorCategory.SecurityError, - null)); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + this.ThrowTerminatingError( + new ErrorRecord( + new PSSecurityException(Modules.CannotCreateModuleWithScriptBlock), + "Modules_CannotCreateModuleWithFullLanguageScriptBlock", + ErrorCategory.SecurityError, + targetObject: null)); + } + + SystemPolicy.LogWDACAuditMessage( + context: Context, + title: Modules.WDACNewModuleCommandLogTitle, + message: Modules.WDACNewModuleCommandLogMessage, + fqid: "NewModuleCmdletWitFullLanguageScriptblockNotAllowed", + dropIntoDebugger: true); } string gs = System.Guid.NewGuid().ToString(); diff --git a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs index 30036e035e2..9346e7caa97 100644 --- a/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/NewModuleManifestCommand.cs @@ -160,7 +160,7 @@ public string Description [Parameter] public ProcessorArchitecture ProcessorArchitecture { - get { return _processorArchitecture.HasValue ? _processorArchitecture.Value : ProcessorArchitecture.None; } + get { return _processorArchitecture ?? ProcessorArchitecture.None; } set { _processorArchitecture = value; } } @@ -886,14 +886,12 @@ private List TryResolveFilePath(string filePath) /// private string ManifestFragment(string key, string resourceString, string value, StreamWriter streamWriter) { - return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}{3:19} = {4}{2}{2}", - _indent, resourceString, streamWriter.NewLine, key, value); + return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}{3:19} = {4}{2}{2}", _indent, resourceString, streamWriter.NewLine, key, value); } private string ManifestFragmentForNonSpecifiedManifestMember(string key, string resourceString, string value, StreamWriter streamWriter) { - return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}# {3:19} = {4}{2}{2}", - _indent, resourceString, streamWriter.NewLine, key, value); + return string.Format(CultureInfo.InvariantCulture, "{0}# {1}{2}{0}# {3:19} = {4}{2}{2}", _indent, resourceString, streamWriter.NewLine, key, value); } private static string ManifestComment(string insert, StreamWriter streamWriter) @@ -948,12 +946,9 @@ protected override void EndProcessing() // wildcards for exported commands that weren't specified on the command line. if (_rootModule != null || _nestedModules != null || _requiredModules != null) { - if (_exportedFunctions == null) - _exportedFunctions = new string[] { "*" }; - if (_exportedAliases == null) - _exportedAliases = new string[] { "*" }; - if (_exportedCmdlets == null) - _exportedCmdlets = new string[] { "*" }; + _exportedAliases ??= new string[] { "*" }; + _exportedCmdlets ??= new string[] { "*" }; + _exportedFunctions ??= new string[] { "*" }; } ValidateUriParameterValue(ProjectUri, "ProjectUri"); @@ -966,7 +961,7 @@ protected override void EndProcessing() if (CompatiblePSEditions != null && (CompatiblePSEditions.Distinct(StringComparer.OrdinalIgnoreCase).Count() != CompatiblePSEditions.Length)) { - string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(",", CompatiblePSEditions)); + string message = StringUtil.Format(Modules.DuplicateEntriesInCompatiblePSEditions, string.Join(',', CompatiblePSEditions)); var ioe = new InvalidOperationException(message); var er = new ErrorRecord(ioe, "Modules_DuplicateEntriesInCompatiblePSEditions", ErrorCategory.InvalidArgument, CompatiblePSEditions); ThrowTerminatingError(er); @@ -1030,8 +1025,7 @@ protected override void EndProcessing() result.Append(streamWriter.NewLine); result.Append(streamWriter.NewLine); - if (_rootModule == null) - _rootModule = string.Empty; + _rootModule ??= string.Empty; BuildModuleManifest(result, nameof(RootModule), Modules.RootModule, !string.IsNullOrEmpty(_rootModule), () => QuoteName(_rootModule), streamWriter); diff --git a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs index f8625697800..4315f8bcb2b 100644 --- a/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs +++ b/src/System.Management.Automation/engine/Modules/PSModuleInfo.cs @@ -453,7 +453,7 @@ internal void SetVersion(Version version) public ModuleType ModuleType { get; private set; } = ModuleType.Script; /// - /// This this module as being a compiled module... + /// This module as being a compiled module... /// internal void SetModuleType(ModuleType moduleType) { ModuleType = moduleType; } @@ -545,7 +545,10 @@ public Dictionary ExportedFunctions // If the module is not binary, it may also have functions... if (DeclaredFunctionExports != null) { - if (DeclaredFunctionExports.Count == 0) { return exports; } + if (DeclaredFunctionExports.Count == 0) + { + return exports; + } foreach (string fn in DeclaredFunctionExports) { @@ -661,16 +664,16 @@ internal void CreateExportedTypeDefinitions(ScriptBlockAst moduleContentScriptBl else { this._exportedTypeDefinitionsNoNested = new ReadOnlyDictionary( - moduleContentScriptBlockAsts.FindAll(a => (a is TypeDefinitionAst), false) + moduleContentScriptBlockAsts.FindAll(static a => (a is TypeDefinitionAst), false) .OfType() - .ToDictionary(a => a.Name, StringComparer.OrdinalIgnoreCase)); + .ToDictionary(static a => a.Name, StringComparer.OrdinalIgnoreCase)); } } internal void AddDetectedTypeExports(List typeDefinitions) { this._exportedTypeDefinitionsNoNested = new ReadOnlyDictionary( - typeDefinitions.ToDictionary(a => a.Name, StringComparer.OrdinalIgnoreCase)); + typeDefinitions.ToDictionary(static a => a.Name, StringComparer.OrdinalIgnoreCase)); } /// @@ -707,7 +710,10 @@ public Dictionary ExportedCmdlets if (DeclaredCmdletExports != null) { - if (DeclaredCmdletExports.Count == 0) { return exports; } + if (DeclaredCmdletExports.Count == 0) + { + return exports; + } foreach (string fn in DeclaredCmdletExports) { @@ -1302,10 +1308,7 @@ public object Invoke(ScriptBlock sb, params object[] args) /// public PSVariable GetVariableFromCallersModule(string variableName) { - if (string.IsNullOrEmpty(variableName)) - { - throw new ArgumentNullException(nameof(variableName)); - } + ArgumentException.ThrowIfNullOrEmpty(variableName); var context = LocalPipeline.GetExecutionContextFromTLS(); SessionState callersSessionState = null; @@ -1437,8 +1440,8 @@ internal void SetExportedTypeFiles(ReadOnlyCollection files) /// /// Implements deep copy of a PSModuleInfo instance. - /// A new PSModuleInfo instance. /// + /// A new PSModuleInfo instance. public PSModuleInfo Clone() { PSModuleInfo clone = (PSModuleInfo)this.MemberwiseClone(); diff --git a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs index c52a752c640..18e12541528 100644 --- a/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs +++ b/src/System.Management.Automation/engine/Modules/RemoteDiscoveryHelper.cs @@ -43,9 +43,9 @@ private static Collection RehydrateHashtableKeys(PSObject pso, string pr List list = hashtable .Keys .Cast() - .Where(k => k != null) - .Select(k => k.ToString()) - .Where(s => s != null) + .Where(static k => k != null) + .Select(static k => k.ToString()) + .Where(static s => s != null) .ToList(); return new Collection(list); } @@ -683,13 +683,13 @@ internal void FetchAllModuleFiles(CimSession cimSession, string cimNamespace, Ci "Dependent", operationOptions); - IEnumerable associatedFiles = associatedInstances.Select(i => new CimModuleImplementationFile(i)); + IEnumerable associatedFiles = associatedInstances.Select(static i => new CimModuleImplementationFile(i)); _moduleFiles = associatedFiles.ToList(); } private List _moduleFiles; - private class CimModuleManifestFile : CimModuleFile + private sealed class CimModuleManifestFile : CimModuleFile { internal CimModuleManifestFile(string fileName, byte[] rawFileData) { @@ -705,7 +705,7 @@ internal CimModuleManifestFile(string fileName, byte[] rawFileData) internal override byte[] RawFileDataCore { get; } } - private class CimModuleImplementationFile : CimModuleFile + private sealed class CimModuleImplementationFile : CimModuleFile { private readonly CimInstance _baseObject; @@ -795,7 +795,7 @@ private static IEnumerable GetCimModules( options); // TODO/FIXME: ETW for method results IEnumerable cimModules = syncResults - .Select(cimInstance => new CimModule(cimInstance)) + .Select(static cimInstance => new CimModule(cimInstance)) .Where(cimModule => wildcardPattern.IsMatch(cimModule.ModuleName)); if (!onlyManifests) diff --git a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs index 182e535604c..52fa4879f41 100644 --- a/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs +++ b/src/System.Management.Automation/engine/Modules/RemoveModuleCommand.cs @@ -291,7 +291,7 @@ private bool ModuleProvidesCurrentSessionDrive(PSModuleInfo module) return false; } - private void GetAllNestedModules(PSModuleInfo module, ref List nestedModulesWithNoCircularReference) + private static void GetAllNestedModules(PSModuleInfo module, ref List nestedModulesWithNoCircularReference) { List nestedModules = new List(); if (module.NestedModules != null && module.NestedModules.Count > 0) @@ -362,7 +362,7 @@ protected override void EndProcessing() hasWildcards = false; } - if (FullyQualifiedName != null && (FullyQualifiedName.Any(moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name)))) + if (FullyQualifiedName != null && (FullyQualifiedName.Any(static moduleSpec => !InitialSessionState.IsEngineModule(moduleSpec.Name)))) { isEngineModule = false; } diff --git a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs index f2005400c9d..892d7375387 100644 --- a/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs +++ b/src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs @@ -14,7 +14,6 @@ namespace System.Management.Automation /// /// Class describing a PowerShell module... /// - [Serializable] internal class ScriptAnalysis { internal static ScriptAnalysis Analyze(string path, ExecutionContext context) @@ -41,7 +40,7 @@ internal static ScriptAnalysis Analyze(string path, ExecutionContext context) // So eat the invalid operation } - string scriptContent = ReadScript(path); + string scriptContent = File.ReadAllText(path, Encoding.Default); ParseError[] errors; var moduleAst = (new Parser()).Parse(path, scriptContent, null, out errors, ParseMode.ModuleAnalysis); @@ -90,20 +89,6 @@ internal static ScriptAnalysis Analyze(string path, ExecutionContext context) return result; } - internal static string ReadScript(string path) - { - using (FileStream readerStream = new FileStream(path, FileMode.Open, FileAccess.Read)) - { - Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); - Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; - - using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) - { - return scriptReader.ReadToEnd(); - } - } - } - internal List DiscoveredExports { get; set; } internal Dictionary DiscoveredAliases { get; set; } @@ -279,10 +264,22 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a // - Exporting module members public override AstVisitAction VisitCommand(CommandAst commandAst) { - string commandName = - commandAst.GetCommandName() ?? - GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string; + string commandName = commandAst.GetCommandName(); + if (commandName is null) + { + // GetCommandName only works if the name is a string constant. GetSafeValueVistor can evaluate some safe dynamic expressions + try + { + commandName = GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string; + } + catch (ParseException) + { + // The script is invalid so we can't use GetSafeValue to get the name either. + } + } + // We couldn't get the name of the command. Either it's an anonymous scriptblock: & {"Some script"} + // Or it's a dynamic expression we couldn't safely resolve. if (commandName == null) return AstVisitAction.SkipChildren; @@ -433,9 +430,12 @@ public override AstVisitAction VisitCommand(CommandAst commandAst) return AstVisitAction.SkipChildren; } - private void ProcessCmdletArguments(object value, Action onEachArgument) + private static void ProcessCmdletArguments(object value, Action onEachArgument) { - if (value == null) return; + if (value == null) + { + return; + } var commandName = value as string; if (commandName != null) @@ -557,7 +557,7 @@ private static Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string private static readonly Dictionary s_parameterBindingInfoTable; - private class ParameterBindingInfo + private sealed class ParameterBindingInfo { internal ParameterInfo[] parameterInfo; } @@ -571,7 +571,6 @@ private struct ParameterInfo // Class to keep track of modules we need to import, and commands that should // be filtered out of them. - [Serializable] internal class RequiredModuleInfo { internal string Name { get; set; } diff --git a/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs new file mode 100644 index 00000000000..84d14939356 --- /dev/null +++ b/src/System.Management.Automation/engine/Modules/SwitchProcessCommand.cs @@ -0,0 +1,134 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Management.Automation; +using System.Runtime.InteropServices; + +using Dbg = System.Management.Automation.Diagnostics; + +#if UNIX + +namespace Microsoft.PowerShell.Commands +{ + /// + /// Implements a cmdlet that allows use of execv API. + /// + [Cmdlet(VerbsCommon.Switch, "Process", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2181448")] + public sealed class SwitchProcessCommand : PSCmdlet + { + /// + /// Get or set the command and arguments to replace the current pwsh process. + /// + [Parameter(Position = 0, Mandatory = false, ValueFromRemainingArguments = true)] + public string[] WithCommand { get; set; } = Array.Empty(); + + /// + /// Execute the command and arguments + /// + protected override void EndProcessing() + { + if (WithCommand.Length == 0) + { + return; + } + + // execv requires command to be full path so resolve command to first match + var command = this.SessionState.InvokeCommand.GetCommand(WithCommand[0], CommandTypes.Application); + if (command is null) + { + ThrowTerminatingError( + new ErrorRecord( + new CommandNotFoundException( + string.Format( + System.Globalization.CultureInfo.InvariantCulture, + CommandBaseStrings.NativeCommandNotFound, + WithCommand[0] + ) + ), + "CommandNotFound", + ErrorCategory.InvalidArgument, + WithCommand[0] + ) + ); + } + + var execArgs = new string?[WithCommand.Length + 1]; + + // execv convention is the first arg is the program name + execArgs[0] = command.Name; + + for (int i = 1; i < WithCommand.Length; i++) + { + execArgs[i] = WithCommand[i]; + } + + // need null terminator at end + execArgs[execArgs.Length - 1] = null; + + var env = Environment.GetEnvironmentVariables(); + var envBlock = new string?[env.Count + 1]; + int j = 0; + foreach (DictionaryEntry entry in env) + { + envBlock[j++] = entry.Key + "=" + entry.Value; + } + + envBlock[envBlock.Length - 1] = null; + + // setup termios for a child process as .NET modifies termios dynamically for use with ReadKey() + ConfigureTerminalForChildProcess(true); + int exitCode = Exec(command.Source, execArgs, envBlock); + if (exitCode < 0) + { + ConfigureTerminalForChildProcess(false); + ThrowTerminatingError( + new ErrorRecord( + new Exception( + string.Format( + System.Globalization.CultureInfo.InvariantCulture, + CommandBaseStrings.ExecFailed, + Marshal.GetLastPInvokeError(), + string.Join(' ', WithCommand) + ) + ), + "ExecutionFailed", + ErrorCategory.InvalidOperation, + WithCommand + ) + ); + } + } + + /// + /// The `execv` POSIX syscall we use to exec /bin/sh. + /// + /// The path to the executable to exec. + /// + /// The arguments to send through to the executable. + /// Array must have its final element be null. + /// + /// + /// The environment variables to send through to the executable in the form of "key=value". + /// Array must have its final element be null. + /// + /// An exit code if exec failed, but if successful the calling process will be overwritten. + /// + [DllImport("libc", + EntryPoint = "execve", + CallingConvention = CallingConvention.Cdecl, + CharSet = CharSet.Ansi, + SetLastError = true)] + private static extern int Exec(string path, string?[] args, string?[] env); + + // leverage .NET runtime's native library which abstracts the need to handle different OS and architectures for termios api + [DllImport("libSystem.Native", EntryPoint = "SystemNative_ConfigureTerminalForChildProcess")] + private static extern void ConfigureTerminalForChildProcess([MarshalAs(UnmanagedType.Bool)] bool childUsesTerminal); + } +} + +#endif diff --git a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs index 265287a010f..650588c32e4 100644 --- a/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs +++ b/src/System.Management.Automation/engine/Modules/TestModuleManifestCommand.cs @@ -294,7 +294,7 @@ protected override void ProcessRecord() // All module extensions except ".psd1" are valid RootModule extensions private static readonly IReadOnlyList s_validRootModuleExtensions = ModuleIntrinsics.PSModuleExtensions - .Where(ext => !string.Equals(ext, StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) + .Where(static ext => !string.Equals(ext, StringLiterals.PowerShellDataFileExtension, StringComparison.OrdinalIgnoreCase)) .ToArray(); /// @@ -374,7 +374,9 @@ private bool IsValidFilePath(string path, PSModuleInfo module, bool verifyPathSc ThrowTerminatingError(er); } - path = pathInfos[0].Path; + // `Path` returns the PSProviderPath which is fully qualified to the provider and the filesystem APIs + // don't understand this. Instead `ProviderPath` returns the path that the FileSystemProvider understands. + path = pathInfos[0].ProviderPath; // First, we validate if the path does exist. if (!File.Exists(path) && !Directory.Exists(path)) diff --git a/src/System.Management.Automation/engine/MshCmdlet.cs b/src/System.Management.Automation/engine/MshCmdlet.cs index a2a7023b2d0..40095ad1472 100644 --- a/src/System.Management.Automation/engine/MshCmdlet.cs +++ b/src/System.Management.Automation/engine/MshCmdlet.cs @@ -14,6 +14,7 @@ namespace System.Management.Automation { #region Auxiliary + /// /// An interface that a /// or @@ -31,6 +32,7 @@ namespace System.Management.Automation /// /// /// +#nullable enable public interface IDynamicParameters { /// @@ -62,8 +64,10 @@ public interface IDynamicParameters /// may not be set at the time this method is called, /// even if the parameters are mandatory. /// - object GetDynamicParameters(); + object? GetDynamicParameters(); } +#nullable restore + /// /// Type used to define a parameter on a cmdlet script of function that /// can only be used as a switch. @@ -112,7 +116,7 @@ public bool ToBool() /// Construct a SwitchParameter instance with a particular value. /// /// - /// If true, it indicates that the switch is present, flase otherwise. + /// If true, it indicates that the switch is present, false otherwise. /// public SwitchParameter(bool isPresent) { @@ -279,8 +283,7 @@ public bool HasErrors /// public string ExpandString(string source) { - if (_cmdlet != null) - _cmdlet.ThrowIfStopping(); + _cmdlet?.ThrowIfStopping(); return _context.Engine.Expand(source); } @@ -359,7 +362,7 @@ public CommandInfo GetCommand(string commandName, CommandTypes type, object[] ar public System.EventHandler PostCommandLookupAction { get; set; } /// - /// Gets or sets the action that is invoked everytime the runspace location (cwd) is changed. + /// Gets or sets the action that is invoked every time the runspace location (cwd) is changed. /// public System.EventHandler LocationChangedAction { get; set; } @@ -670,40 +673,46 @@ internal IEnumerable GetCommands(string name, CommandTypes commandT } /// - /// Executes a piece of text as a script synchronously. + /// Executes a piece of text as a script synchronously in the caller's session state. + /// The given text will be executed in a child scope rather than dot-sourced. /// /// The script text to evaluate. - /// A collection of MshCobjects generated by the script. + /// A collection of PSObjects generated by the script. Never null, but may be empty. /// Thrown if there was a parsing error in the script. /// Represents a script-level exception. /// public Collection InvokeScript(string script) { - return InvokeScript(script, true, PipelineResultTypes.None, null); + return InvokeScript(script, useNewScope: true, PipelineResultTypes.None, input: null); } /// - /// Executes a piece of text as a script synchronously. + /// Executes a piece of text as a script synchronously in the caller's session state. + /// The given text will be executed in a child scope rather than dot-sourced. /// /// The script text to evaluate. - /// The arguments to the script. - /// A collection of MshCobjects generated by the script. + /// The arguments to the script, available as $args. + /// A collection of PSObjects generated by the script. Never null, but may be empty. /// Thrown if there was a parsing error in the script. /// Represents a script-level exception. /// public Collection InvokeScript(string script, params object[] args) { - return InvokeScript(script, true, PipelineResultTypes.None, null, args); + return InvokeScript(script, useNewScope: true, PipelineResultTypes.None, input: null, args); } /// + /// Executes a given scriptblock synchronously in the given session state. + /// The scriptblock will be executed in the calling scope (dot-sourced) rather than in a new child scope. /// - /// - /// - /// - /// + /// The session state in which to execute the scriptblock. + /// The scriptblock to execute. + /// The arguments to the scriptblock, available as $args. + /// A collection of the PSObjects emitted by the executing scriptblock. Never null, but may be empty. public Collection InvokeScript( - SessionState sessionState, ScriptBlock scriptBlock, params object[] args) + SessionState sessionState, + ScriptBlock scriptBlock, + params object[] args) { if (scriptBlock == null) { @@ -735,13 +744,18 @@ public Collection InvokeScript( /// /// Invoke a scriptblock in the current runspace, controlling if it gets a new scope. /// - /// If true, a new scope will be created. + /// If true, executes the scriptblock in a new child scope, otherwise the scriptblock is dot-sourced into the calling scope. /// The scriptblock to execute. - /// Optionall input to the command. + /// Optional input to the command. /// Arguments to pass to the scriptblock. - /// The result of the evaluation. + /// + /// A collection of the PSObjects generated by executing the script. Never null, but may be empty. + /// public Collection InvokeScript( - bool useLocalScope, ScriptBlock scriptBlock, IList input, params object[] args) + bool useLocalScope, + ScriptBlock scriptBlock, + IList input, + params object[] args) { if (scriptBlock == null) { @@ -767,24 +781,27 @@ public Collection InvokeScript( /// /// The script to evaluate. /// If true, evaluate the script in its own scope. - /// If false, the script will be evaluated in the current scope i.e. it will be "dotted" + /// If false, the script will be evaluated in the current scope i.e. it will be dot-sourced. /// If set to Output, all output will be streamed /// to the output pipe of the calling cmdlet. If set to None, the result will be returned /// to the caller as a collection of PSObjects. No other flags are supported at this time and /// will result in an exception if used. /// The list of objects to use as input to the script. - /// The array of arguments to the command. - /// A collection of MshCobjects generated by the script. This will be - /// empty if output was redirected. + /// The array of arguments to the command, available as $args. + /// A collection of PSObjects generated by the script. This will be + /// empty if output was redirected. Never null. /// Thrown if there was a parsing error in the script. /// Represents a script-level exception. /// Thrown if any redirect other than output is attempted. /// - public Collection InvokeScript(string script, bool useNewScope, - PipelineResultTypes writeToPipeline, IList input, params object[] args) + public Collection InvokeScript( + string script, + bool useNewScope, + PipelineResultTypes writeToPipeline, + IList input, + params object[] args) { - if (script == null) - throw new ArgumentNullException(nameof(script)); + ArgumentNullException.ThrowIfNull(script); // Compile the script text into an executable script block. ScriptBlock sb = ScriptBlock.Create(_context, script); @@ -792,11 +809,14 @@ public Collection InvokeScript(string script, bool useNewScope, return InvokeScript(sb, useNewScope, writeToPipeline, input, args); } - private Collection InvokeScript(ScriptBlock sb, bool useNewScope, - PipelineResultTypes writeToPipeline, IList input, params object[] args) + private Collection InvokeScript( + ScriptBlock sb, + bool useNewScope, + PipelineResultTypes writeToPipeline, + IList input, + params object[] args) { - if (_cmdlet != null) - _cmdlet.ThrowIfStopping(); + _cmdlet?.ThrowIfStopping(); Cmdlet cmdletToUse = null; ScriptBlock.ErrorHandlingBehavior errorHandlingBehavior = ScriptBlock.ErrorHandlingBehavior.WriteToExternalErrorPipe; @@ -887,8 +907,7 @@ private Collection InvokeScript(ScriptBlock sb, bool useNewScope, /// public ScriptBlock NewScriptBlock(string scriptText) { - if (_commandRuntime != null) - _commandRuntime.ThrowIfStopping(); + _commandRuntime?.ThrowIfStopping(); ScriptBlock result = ScriptBlock.Create(_context, scriptText); return result; diff --git a/src/System.Management.Automation/engine/MshCommandRuntime.cs b/src/System.Management.Automation/engine/MshCommandRuntime.cs index e43e49631aa..e674cb1c5eb 100644 --- a/src/System.Management.Automation/engine/MshCommandRuntime.cs +++ b/src/System.Management.Automation/engine/MshCommandRuntime.cs @@ -390,6 +390,9 @@ public void WriteProgress( WriteProgress(sourceId, progressRecord, false); } + internal bool IsWriteProgressEnabled() + => WriteHelper_ShouldWrite(ProgressPreference, lastProgressContinueStatus); + internal void WriteProgress( Int64 sourceId, ProgressRecord progressRecord, @@ -472,6 +475,9 @@ public void WriteDebug(string text) WriteDebug(new DebugRecord(text)); } + internal bool IsWriteDebugEnabled() + => WriteHelper_ShouldWrite(DebugPreference, lastDebugContinueStatus); + /// /// Display debug information. /// @@ -566,6 +572,9 @@ public void WriteVerbose(string text) WriteVerbose(new VerboseRecord(text)); } + internal bool IsWriteVerboseEnabled() + => WriteHelper_ShouldWrite(VerbosePreference, lastVerboseContinueStatus); + /// /// Display verbose information. /// @@ -660,6 +669,9 @@ public void WriteWarning(string text) WriteWarning(new WarningRecord(text)); } + internal bool IsWriteWarningEnabled() + => WriteHelper_ShouldWrite(WarningPreference, lastWarningContinueStatus); + /// /// Display warning information. /// @@ -733,6 +745,9 @@ public void WriteInformation(InformationRecord informationRecord) WriteInformation(informationRecord, false); } + internal bool IsWriteInformationEnabled() + => WriteHelper_ShouldWrite(InformationPreference, lastInformationContinueStatus); + /// /// Display tagged object information. /// @@ -876,7 +891,7 @@ internal void WriteInformation(InformationRecord record, bool overrideInquire = /// pipeline execution log. /// /// If LogPipelineExecutionDetail is turned on, this information will be written - /// to monad log under log category "Pipeline execution detail" + /// to PowerShell log under log category "Pipeline execution detail" /// /// /// @@ -928,7 +943,8 @@ private bool InitShouldLogPipelineExecutionDetail() /// internal string PipelineVariable { get; set; } - private PSVariable _pipelineVarReference = null; + private PSVariable _pipelineVarReference; + private bool _shouldRemovePipelineVariable; internal void SetupOutVariable() { @@ -941,13 +957,10 @@ internal void SetupOutVariable() // Handle the creation of OutVariable in the case of Out-Default specially, // as it needs to handle much of its OutVariable support itself. - if ( - (!string.IsNullOrEmpty(this.OutVariable)) && - (!(this.OutVariable.StartsWith('+'))) && - string.Equals("Out-Default", _thisCommand.CommandInfo.Name, StringComparison.OrdinalIgnoreCase)) + if (!OutVariable.StartsWith('+') && + string.Equals("Out-Default", _commandInfo.Name, StringComparison.OrdinalIgnoreCase)) { - if (_state == null) - _state = new SessionState(Context.EngineSessionState); + _state ??= new SessionState(Context.EngineSessionState); IList oldValue = null; oldValue = PSObject.Base(_state.PSVariable.GetValue(this.OutVariable)) as IList; @@ -972,23 +985,34 @@ internal void SetupPipelineVariable() // This can't use the common SetupVariable implementation, as this needs to persist for an entire // pipeline. - if (string.IsNullOrEmpty(this.PipelineVariable)) + if (string.IsNullOrEmpty(PipelineVariable)) { return; } EnsureVariableParameterAllowed(); - if (_state == null) - _state = new SessionState(Context.EngineSessionState); + _state ??= new SessionState(Context.EngineSessionState); // Create the pipeline variable - _pipelineVarReference = new PSVariable(this.PipelineVariable); - _state.PSVariable.Set(_pipelineVarReference); + _pipelineVarReference = new PSVariable(PipelineVariable); + object varToUse = _state.Internal.SetVariable( + _pipelineVarReference, + force: false, + CommandOrigin.Internal); - // Get the reference again in case we re-used one from the - // same scope. - _pipelineVarReference = _state.PSVariable.Get(this.PipelineVariable); + if (ReferenceEquals(_pipelineVarReference, varToUse)) + { + // The returned variable is the exact same instance, which means we set a new variable. + // In this case, we will try removing the pipeline variable in the end. + _shouldRemovePipelineVariable = true; + } + else + { + // A variable with the same name already exists in the same scope and it was returned. + // In this case, we update the reference and don't remove the variable in the end. + _pipelineVarReference = (PSVariable)varToUse; + } if (_thisCommand is not PSScriptCmdlet) { @@ -996,6 +1020,15 @@ internal void SetupPipelineVariable() } } + internal void RemovePipelineVariable() + { + if (_shouldRemovePipelineVariable) + { + // Remove pipeline variable when a pipeline is being torn down. + _state.PSVariable.Remove(PipelineVariable); + } + } + /// /// Configures the number of objects to buffer before calling the downstream Cmdlet. /// @@ -1063,8 +1096,8 @@ internal int OutBuffer /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype1")] /// public class RemoveMyObjectType1 : PSCmdlet @@ -1086,7 +1119,7 @@ internal int OutBuffer /// } /// } /// } - /// + /// /// /// /// @@ -1157,8 +1190,8 @@ public bool ShouldProcess(string target) /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype2")] /// public class RemoveMyObjectType2 : PSCmdlet @@ -1180,7 +1213,7 @@ public bool ShouldProcess(string target) /// } /// } /// } - /// + /// /// /// /// @@ -1260,8 +1293,8 @@ public bool ShouldProcess(string target, string action) /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : PSCmdlet @@ -1277,8 +1310,8 @@ public bool ShouldProcess(string target, string action) /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file")) /// { /// // delete the object @@ -1286,7 +1319,7 @@ public bool ShouldProcess(string target, string action) /// } /// } /// } - /// + /// /// /// /// @@ -1375,8 +1408,8 @@ public bool ShouldProcess( /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : PSCmdlet @@ -1393,8 +1426,8 @@ public bool ShouldProcess( /// { /// ShouldProcessReason shouldProcessReason; /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file", /// out shouldProcessReason)) /// { @@ -1403,7 +1436,7 @@ public bool ShouldProcess( /// } /// } /// } - /// + /// /// /// /// @@ -1465,7 +1498,7 @@ private bool CanShouldProcessAutoConfirm() /// /// are returned. /// - /// true iff the action should be performed + /// true if-and-only-if the action should be performed /// /// The pipeline has already been terminated, or was terminated /// during the execution of this method. @@ -1681,8 +1714,8 @@ internal ShouldProcessPossibleOptimization CalculatePossibleShouldProcessOptimiz /// to ShouldProcess for the Cmdlet instance. /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType4 : PSCmdlet @@ -1706,14 +1739,14 @@ internal ShouldProcessPossibleOptimization CalculatePossibleShouldProcessOptimiz /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file")) /// ) /// { @@ -1725,7 +1758,7 @@ internal ShouldProcessPossibleOptimization CalculatePossibleShouldProcessOptimiz /// } /// } /// } - /// + /// /// /// /// @@ -1765,11 +1798,11 @@ public bool ShouldContinue(string query, string caption) /// the default option selected in the selection menu is 'No'. /// /// - /// true iff user selects YesToAll. If this is already true, + /// true if-and-only-if user selects YesToAll. If this is already true, /// ShouldContinue will bypass the prompt and return true. /// /// - /// true iff user selects NoToAll. If this is already true, + /// true if-and-only-if user selects NoToAll. If this is already true, /// ShouldContinue will bypass the prompt and return false. /// /// @@ -1812,11 +1845,11 @@ public bool ShouldContinue( /// It may be displayed by some hosts, but not all. /// /// - /// true iff user selects YesToAll. If this is already true, + /// true if-and-only-if user selects YesToAll. If this is already true, /// ShouldContinue will bypass the prompt and return true. /// /// - /// true iff user selects NoToAll. If this is already true, + /// true if-and-only-if user selects NoToAll. If this is already true, /// ShouldContinue will bypass the prompt and return false. /// /// @@ -1863,8 +1896,8 @@ public bool ShouldContinue( /// to ShouldProcess for the Cmdlet instance. /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType5 : PSCmdlet @@ -1891,14 +1924,14 @@ public bool ShouldContinue( /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file"), /// ref yesToAll, /// ref noToAll @@ -1912,7 +1945,7 @@ public bool ShouldContinue( /// } /// } /// } - /// + /// /// /// /// @@ -2055,6 +2088,7 @@ public PSTransactionContext CurrentPSTransaction /// . /// etc. /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] public void ThrowTerminatingError(ErrorRecord errorRecord) { ThrowIfStopping(); @@ -2317,7 +2351,7 @@ internal IDisposable AllowThisCommandToWrite(bool permittedToWriteToPipeline) return new AllowWrite(_thisCommand, permittedToWriteToPipeline); } - private class AllowWrite : IDisposable + private sealed class AllowWrite : IDisposable { /// /// Begin the scope where WriteObject/WriteError is permitted. @@ -2326,7 +2360,7 @@ internal AllowWrite(InternalCommand permittedToWrite, bool permittedToWriteToPip { if (permittedToWrite == null) throw PSTraceSource.NewArgumentNullException(nameof(permittedToWrite)); - if (!(permittedToWrite.commandRuntime is MshCommandRuntime mcr)) + if (permittedToWrite.commandRuntime is not MshCommandRuntime mcr) throw PSTraceSource.NewArgumentNullException("permittedToWrite.CommandRuntime"); _pp = mcr.PipelineProcessor; if (_pp == null) @@ -2338,19 +2372,18 @@ internal AllowWrite(InternalCommand permittedToWrite, bool permittedToWriteToPip _pp._permittedToWriteToPipeline = permittedToWriteToPipeline; _pp._permittedToWriteThread = Thread.CurrentThread; } + /// - /// End the scope where WriteObject/WriteError is permitted. + /// Release all resources. /// - /// + /// + /// End the scope where WriteObject/WriteError is permitted. + /// public void Dispose() { _pp._permittedToWrite = _wasPermittedToWrite; _pp._permittedToWriteToPipeline = _wasPermittedToWriteToPipeline; _pp._permittedToWriteThread = _wasPermittedToWriteThread; - GC.SuppressFinalize(this); } // There is no finalizer, by design. This class relies on always @@ -2376,10 +2409,7 @@ public Exception ManageException(Exception e) if (e == null) throw PSTraceSource.NewArgumentNullException(nameof(e)); - if (PipelineProcessor != null) - { - PipelineProcessor.RecordFailure(e, _thisCommand); - } + PipelineProcessor?.RecordFailure(e, _thisCommand); // 1021203-2005/05/09-JonN // HaltCommandException will cause the command @@ -2403,7 +2433,6 @@ public Exception ManageException(Exception e) } // Log a command health event - MshLog.LogCommandHealthEvent( Context, e, @@ -2542,8 +2571,7 @@ internal void SetupVariable(VariableStreamKind streamKind, string variableName, EnsureVariableParameterAllowed(); - if (_state == null) - _state = new SessionState(Context.EngineSessionState); + _state ??= new SessionState(Context.EngineSessionState); if (variableName.StartsWith('+')) { @@ -2803,8 +2831,16 @@ private void DoWriteError(object obj) _WriteErrorSkipAllowCheck(errorRecord, preference); } - // NOTICE-2004/06/08-JonN 959638 - // Use this variant to skip the ThrowIfWriteNotPermitted check + /// + /// Write an error, skipping the ThrowIfWriteNotPermitted check. + /// + /// The error record to write. + /// The configured error action preference. + /// + /// True when this method is called to write from a native command's stderr stream. + /// When errors are written through a native stderr stream, they do not interact with the error preference system, + /// but must still present as errors in PowerShell. + /// /// /// The pipeline has already been terminated, or was terminated /// during the execution of this method. @@ -2818,7 +2854,7 @@ private void DoWriteError(object obj) /// but the command failure will ultimately be /// , /// - internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = null, bool isNativeError = false) + internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreference? actionPreference = null, bool isFromNativeStdError = false) { ThrowIfStopping(); @@ -2838,7 +2874,7 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc this.PipelineProcessor.LogExecutionError(_thisCommand.MyInvocation, errorRecord); } - if (!(ExperimentalFeature.IsEnabled("PSNotApplyErrorActionToStderr") && isNativeError)) + if (!isFromNativeStdError) { this.PipelineProcessor.ExecutionFailed = true; @@ -2904,7 +2940,7 @@ internal void _WriteErrorSkipAllowCheck(ErrorRecord errorRecord, ActionPreferenc // when tracing), so don't add the member again. // We don't add a note property on messages that comes from stderr stream. - if (!isNativeError) + if (!isFromNativeStdError) { errorWrap.WriteStream = WriteStreamType.Error; } @@ -2955,21 +2991,19 @@ internal ConfirmImpact ConfirmPreference { // WhatIf not relevant, it never gets this far in that case if (Confirm) - return ConfirmImpact.Low; - if (Debug) { - if (IsConfirmFlagSet) // -Debug -Confirm:$false - return ConfirmImpact.None; return ConfirmImpact.Low; } - if (IsConfirmFlagSet) // -Confirm:$false + if (IsConfirmFlagSet) + { + // -Confirm:$false return ConfirmImpact.None; + } if (!_isConfirmPreferenceCached) { - bool defaultUsed = false; - _confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, _confirmPreference, out defaultUsed); + _confirmPreference = Context.GetEnumPreference(SpecialVariables.ConfirmPreferenceVarPath, _confirmPreference, out _); _isConfirmPreferenceCached = true; } @@ -3204,7 +3238,7 @@ internal SwitchParameter UseTransaction private bool _debugFlag = false; /// - /// Debug tell the command system to provide Programmer/Support type messages to understand what is really occuring + /// Debug tell the command system to provide Programmer/Support type messages to understand what is really occurring /// and give the user the opportunity to stop or debug the situation. /// /// @@ -3241,8 +3275,7 @@ internal SwitchParameter WhatIf { if (!IsWhatIfFlagSet && !_isWhatIfPreferenceCached) { - bool defaultUsed = false; - _whatIfFlag = Context.GetBooleanPreference(SpecialVariables.WhatIfPreferenceVarPath, _whatIfFlag, out defaultUsed); + _whatIfFlag = Context.GetBooleanPreference(SpecialVariables.WhatIfPreferenceVarPath, _whatIfFlag, out _); _isWhatIfPreferenceCached = true; } @@ -3309,7 +3342,7 @@ internal ActionPreference ProgressPreference { get { - if (_isProgressPreferenceSet) + if (IsProgressActionSet) return _progressPreference; if (!_isProgressPreferenceCached) @@ -3330,12 +3363,14 @@ internal ActionPreference ProgressPreference } _progressPreference = value; - _isProgressPreferenceSet = true; + IsProgressActionSet = true; } } private ActionPreference _progressPreference = InitialSessionState.DefaultProgressPreference; - private bool _isProgressPreferenceSet = false; + + internal bool IsProgressActionSet { get; private set; } = false; + private bool _isProgressPreferenceCached = false; /// @@ -3735,8 +3770,10 @@ internal void SetVariableListsInPipe() { Diagnostics.Assert(_thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); - if (_outVarList != null) + if (_outVarList != null && !OutputPipe.IgnoreOutVariableList) { + // A null pipe is used when executing the 'Clean' block of a PSScriptCmdlet. + // In such a case, we don't capture output to the out variable list. this.OutputPipe.AddVariableList(VariableStreamKind.Output, _outVarList); } @@ -3757,26 +3794,13 @@ internal void SetVariableListsInPipe() if (this.PipelineVariable != null) { - // _state can be null if the current script block is dynamicparam, etc. - if (_state != null) - { - // Create the pipeline variable - _state.PSVariable.Set(_pipelineVarReference); - - // Get the reference again in case we re-used one from the - // same scope. - _pipelineVarReference = _state.PSVariable.Get(this.PipelineVariable); - } - this.OutputPipe.SetPipelineVariable(_pipelineVarReference); } } internal void RemoveVariableListsInPipe() { - // Diagnostics.Assert(thisCommand is PSScriptCmdlet, "this is only done for script cmdlets"); - - if (_outVarList != null) + if (_outVarList != null && !OutputPipe.IgnoreOutVariableList) { this.OutputPipe.RemoveVariableList(VariableStreamKind.Output, _outVarList); } @@ -3799,9 +3823,6 @@ internal void RemoveVariableListsInPipe() if (this.PipelineVariable != null) { this.OutputPipe.RemovePipelineVariable(); - // '_state' could be null when a 'DynamicParam' block runs because the 'DynamicParam' block runs in 'DoPrepare', - // before 'PipelineProcessor.SetupParameterVariables' is called, where '_state' is initialized. - _state?.PSVariable.Remove(this.PipelineVariable); } } } diff --git a/src/System.Management.Automation/engine/MshMemberInfo.cs b/src/System.Management.Automation/engine/MshMemberInfo.cs index 73ee243f6e8..4bde286d165 100644 --- a/src/System.Management.Automation/engine/MshMemberInfo.cs +++ b/src/System.Management.Automation/engine/MshMemberInfo.cs @@ -28,8 +28,8 @@ namespace System.Management.Automation /// /// Enumerates all possible types of members. /// - [TypeConverterAttribute(typeof(LanguagePrimitives.EnumMultipleTypeConverter))] - [FlagsAttribute()] + [TypeConverter(typeof(LanguagePrimitives.EnumMultipleTypeConverter))] + [Flags] public enum PSMemberTypes { /// @@ -120,8 +120,8 @@ public enum PSMemberTypes /// /// Enumerator for all possible views available on a PSObject. /// - [TypeConverterAttribute(typeof(LanguagePrimitives.EnumMultipleTypeConverter))] - [FlagsAttribute()] + [TypeConverter(typeof(LanguagePrimitives.EnumMultipleTypeConverter))] + [Flags] public enum PSMemberViewTypes { /// @@ -148,7 +148,7 @@ public enum PSMemberViewTypes /// /// Match options. /// - [FlagsAttribute] + [Flags] internal enum MshMemberMatchOptions { /// @@ -1909,9 +1909,18 @@ internal class PSMethodInvocationConstraints internal PSMethodInvocationConstraints( Type methodTargetType, Type[] parameterTypes) + : this(methodTargetType, parameterTypes, genericTypeParameters: null) { - this.MethodTargetType = methodTargetType; - _parameterTypes = parameterTypes; + } + + internal PSMethodInvocationConstraints( + Type methodTargetType, + Type[] parameterTypes, + object[] genericTypeParameters) + { + MethodTargetType = methodTargetType; + ParameterTypes = parameterTypes; + GenericTypeParameters = genericTypeParameters; } /// @@ -1922,9 +1931,12 @@ internal PSMethodInvocationConstraints( /// /// If then there are no constraints /// - public IEnumerable ParameterTypes => _parameterTypes; + public Type[] ParameterTypes { get; } - private readonly Type[] _parameterTypes; + /// + /// Gets the generic type parameters for the method invocation. + /// + public object[] GenericTypeParameters { get; } internal static bool EqualsForCollection(ICollection xs, ICollection ys) { @@ -1946,8 +1958,6 @@ internal static bool EqualsForCollection(ICollection xs, ICollection ys return xs.SequenceEqual(ys); } - // TODO: IEnumerable genericTypeParameters { get; private set; } - public bool Equals(PSMethodInvocationConstraints other) { if (other is null) @@ -1965,7 +1975,12 @@ public bool Equals(PSMethodInvocationConstraints other) return false; } - if (!EqualsForCollection(_parameterTypes, other._parameterTypes)) + if (!EqualsForCollection(ParameterTypes, other.ParameterTypes)) + { + return false; + } + + if (!EqualsForCollection(GenericTypeParameters, other.GenericTypeParameters)) { return false; } @@ -1994,36 +2009,53 @@ public override bool Equals(object obj) } public override int GetHashCode() - { - // algorithm based on https://stackoverflow.com/questions/263400/what-is-the-best-algorithm-for-an-overridden-system-object-gethashcode - unchecked - { - int result = 61; - - result = result * 397 + (MethodTargetType != null ? MethodTargetType.GetHashCode() : 0); - result = result * 397 + ParameterTypes.SequenceGetHashCode(); - - return result; - } - } + => HashCode.Combine(MethodTargetType, ParameterTypes.SequenceGetHashCode(), GenericTypeParameters.SequenceGetHashCode()); public override string ToString() { StringBuilder sb = new StringBuilder(); string separator = string.Empty; - if (MethodTargetType != null) + if (MethodTargetType is not null) { sb.Append("this: "); sb.Append(ToStringCodeMethods.Type(MethodTargetType, dropNamespaces: true)); separator = " "; } - if (_parameterTypes != null) + if (GenericTypeParameters is not null) + { + sb.Append(separator); + sb.Append("genericTypeParams: "); + + separator = string.Empty; + foreach (object parameter in GenericTypeParameters) + { + sb.Append(separator); + + switch (parameter) + { + case Type paramType: + sb.Append(ToStringCodeMethods.Type(paramType, dropNamespaces: true)); + break; + case ITypeName paramTypeName: + sb.Append(paramTypeName.ToString()); + break; + default: + throw new ArgumentException("Unexpected value"); + } + + separator = ", "; + } + + separator = " "; + } + + if (ParameterTypes is not null) { sb.Append(separator); sb.Append("args: "); separator = string.Empty; - foreach (var p in _parameterTypes) + foreach (var p in ParameterTypes) { sb.Append(separator); sb.Append(ToStringCodeMethods.Type(p, dropNamespaces: true)); @@ -2244,10 +2276,7 @@ public override object Invoke(params object[] arguments) newArguments[i + 1] = arguments[i]; } - if (_codeReferenceMethodInformation == null) - { - _codeReferenceMethodInformation = DotNetAdapter.GetMethodInformationArray(new[] { CodeReference }); - } + _codeReferenceMethodInformation ??= DotNetAdapter.GetMethodInformationArray(new[] { CodeReference }); Adapter.GetBestMethodAndArguments(CodeReference.Name, _codeReferenceMethodInformation, newArguments, out object[] convertedArguments); @@ -2600,10 +2629,7 @@ internal static PSMethod Create(string name, DotNetAdapter dotNetInstanceAdapter return new PSMethod(name, dotNetInstanceAdapter, baseObject, method, isSpecial, isHidden); } - if (method.PSMethodCtor == null) - { - method.PSMethodCtor = CreatePSMethodConstructor(method.methodInformationStructures); - } + method.PSMethodCtor ??= CreatePSMethodConstructor(method.methodInformationStructures); return method.PSMethodCtor.Invoke(name, dotNetInstanceAdapter, baseObject, method, isSpecial, isHidden); } @@ -2659,7 +2685,7 @@ private static Type GetMethodGroupType(MethodInfo methodInfo) return DelegateHelpers.MakeDelegate(methodTypes); } - catch (TypeLoadException) + catch (Exception) { return typeof(Func); } @@ -3339,8 +3365,7 @@ internal override PSMemberInfoInternalCollection InternalMembers break; default: Diagnostics.Assert(false, - string.Format(CultureInfo.InvariantCulture, - "PSInternalMemberSet cannot process {0}", name)); + string.Create(CultureInfo.InvariantCulture, $"PSInternalMemberSet cannot process {name}")); break; } } @@ -5035,7 +5060,7 @@ internal struct Enumerator : IEnumerator private readonly PSMemberInfoInternalCollection _allMembers; /// - /// Constructs this instance to enumerate over members. + /// Initializes a new instance of the class to enumerate over members. /// /// Members we are enumerating. internal Enumerator(PSMemberInfoIntegratingCollection integratingCollection) @@ -5063,8 +5088,8 @@ internal Enumerator(PSMemberInfoIntegratingCollection integratingCollection) /// Moves to the next element in the enumeration. /// /// - /// false if there are no more elements to enumerate - /// true otherwise + /// If there are no more elements to enumerate, returns false. + /// Returns true otherwise. /// public bool MoveNext() { @@ -5093,7 +5118,7 @@ public bool MoveNext() } /// - /// Current PSMemberInfo in the enumeration. + /// Gets the current PSMemberInfo in the enumeration. /// /// For invalid arguments. T IEnumerator.Current diff --git a/src/System.Management.Automation/engine/MshObject.cs b/src/System.Management.Automation/engine/MshObject.cs index 7ea7ef1bd72..c5e8bbac443 100644 --- a/src/System.Management.Automation/engine/MshObject.cs +++ b/src/System.Management.Automation/engine/MshObject.cs @@ -44,7 +44,6 @@ namespace System.Management.Automation /// but there is no established scenario for doing this, nor has it been tested. /// [TypeDescriptionProvider(typeof(PSObjectTypeDescriptionProvider))] - [Serializable] public class PSObject : IFormattable, IComparable, ISerializable, IDynamicMetaObjectProvider { #region constructors @@ -490,6 +489,7 @@ internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable) if (result == null) { +#if !UNIX if (objectType.IsCOMObject) { // All WinRT types are COM types. @@ -526,6 +526,9 @@ internal static AdapterSet GetMappedAdapter(object obj, TypeTable typeTable) { result = PSObject.s_dotNetInstanceAdapterSet; } +#else + result = PSObject.s_dotNetInstanceAdapterSet; +#endif } var existingOrNew = s_adapterMapping.GetOrAdd(objectType, result); @@ -589,7 +592,7 @@ protected PSObject(SerializationInfo info, StreamingContext context) throw PSTraceSource.NewArgumentNullException(nameof(info)); } - if (!(info.GetValue("CliXml", typeof(string)) is string serializedData)) + if (info.GetValue("CliXml", typeof(string)) is not string serializedData) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -674,13 +677,10 @@ internal PSMemberInfoInternalCollection InstanceMembers { lock (_lockObject) { - if (_instanceMembers == null) - { - _instanceMembers = - s_instanceMembersResurrectionTable.GetValue( - GetKeyForResurrectionTables(this), - _ => new PSMemberInfoInternalCollection()); - } + _instanceMembers ??= + s_instanceMembersResurrectionTable.GetValue( + GetKeyForResurrectionTables(this), + _ => new PSMemberInfoInternalCollection()); } } @@ -721,10 +721,7 @@ private AdapterSet InternalAdapterSet { lock (_lockObject) { - if (_adapterSet == null) - { - _adapterSet = GetMappedAdapter(_immediateBaseObject, GetTypeTable()); - } + _adapterSet ??= GetMappedAdapter(_immediateBaseObject, GetTypeTable()); } } @@ -743,10 +740,7 @@ public PSMemberInfoCollection Members { lock (_lockObject) { - if (_members == null) - { - _members = new PSMemberInfoIntegratingCollection(this, s_memberCollection); - } + _members ??= new PSMemberInfoIntegratingCollection(this, s_memberCollection); } } @@ -765,10 +759,7 @@ public PSMemberInfoCollection Properties { lock (_lockObject) { - if (_properties == null) - { - _properties = new PSMemberInfoIntegratingCollection(this, s_propertyCollection); - } + _properties ??= new PSMemberInfoIntegratingCollection(this, s_propertyCollection); } } @@ -787,10 +778,7 @@ public PSMemberInfoCollection Methods { lock (_lockObject) { - if (_methods == null) - { - _methods = new PSMemberInfoIntegratingCollection(this, s_methodCollection); - } + _methods ??= new PSMemberInfoIntegratingCollection(this, s_methodCollection); } } @@ -992,7 +980,7 @@ public static implicit operator PSObject(bool valueToConvert) /// internal static object Base(object obj) { - if (!(obj is PSObject mshObj)) + if (obj is not PSObject mshObj) { return obj; } @@ -1076,7 +1064,7 @@ internal static PSObject AsPSObject(object obj, bool storeTypeNameAndInstanceMem /// internal static object GetKeyForResurrectionTables(object obj) { - if (!(obj is PSObject pso)) + if (obj is not PSObject pso) { return obj; } @@ -1623,7 +1611,7 @@ public virtual PSObject Copy() bool needToReAddInstanceMembersAndTypeNames = !object.ReferenceEquals(GetKeyForResurrectionTables(this), GetKeyForResurrectionTables(returnValue)); if (needToReAddInstanceMembersAndTypeNames) { - Diagnostics.Assert(!returnValue.InstanceMembers.Any(), "needToReAddInstanceMembersAndTypeNames should mean that the new object has a fresh/empty list of instance members"); + Diagnostics.Assert(returnValue.InstanceMembers.Count == 0, "needToReAddInstanceMembersAndTypeNames should mean that the new object has a fresh/empty list of instance members"); foreach (PSMemberInfo member in this.InstanceMembers) { if (member.IsHidden) @@ -1863,7 +1851,7 @@ internal static object GetNoteSettingValue(PSMemberSet settings, string noteName settings.ReplicateInstance(ownerObject); } - if (!(settings.Members[noteName] is PSNoteProperty note)) + if (settings.Members[noteName] is not PSNoteProperty note) { return defaultValue; } @@ -2059,7 +2047,7 @@ internal static void CopyDeserializerFields(PSObject source, PSObject target) /// /// Object which is set as core. /// If true, overwrite the type information. - ///This method is to be used only by Serialization code + /// This method is to be used only by Serialization code internal void SetCoreOnDeserialization(object value, bool overrideTypeInfo) { Diagnostics.Assert(this.ImmediateBaseObjectIsEmpty, "BaseObject should be PSCustomObject for deserialized objects"); diff --git a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs index 6e941b4c5f1..113161748c9 100644 --- a/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs +++ b/src/System.Management.Automation/engine/MshObjectTypeDescriptor.cs @@ -219,7 +219,7 @@ private static PSObject GetComponentPSObject(object component) PSObject mshObj = component as PSObject; if (mshObj == null) { - if (!(component is PSObjectTypeDescriptor descriptor)) + if (component is not PSObjectTypeDescriptor descriptor) { throw PSTraceSource.NewArgumentException(nameof(component), ExtendedTypeSystem.InvalidComponent, "component", @@ -410,10 +410,7 @@ private void CheckAndAddProperty(PSPropertyInfo propertyInfo, Attribute[] attrib } } - if (propertyAttributes == null) - { - propertyAttributes = new AttributeCollection(); - } + propertyAttributes ??= new AttributeCollection(); typeDescriptor.WriteLine("Adding property \"{0}\".", propertyInfo.Name); @@ -467,7 +464,7 @@ public override PropertyDescriptorCollection GetProperties(Attribute[] attribute /// True if the Instance property of is equal to the current Instance; otherwise, false. public override bool Equals(object obj) { - if (!(obj is PSObjectTypeDescriptor other)) + if (obj is not PSObjectTypeDescriptor other) { return false; } diff --git a/src/System.Management.Automation/engine/MshReference.cs b/src/System.Management.Automation/engine/MshReference.cs index a021e09f794..fa8b6f13583 100644 --- a/src/System.Management.Automation/engine/MshReference.cs +++ b/src/System.Management.Automation/engine/MshReference.cs @@ -8,7 +8,7 @@ namespace System.Management.Automation { /// - /// Define type for a reference object in Monad scripting language. + /// Define type for a reference object in PowerShell scripting language. /// /// /// This class is used to describe both kinds of references: diff --git a/src/System.Management.Automation/engine/MshSecurityException.cs b/src/System.Management.Automation/engine/MshSecurityException.cs index 6ba04e4af7c..07c70ec7317 100644 --- a/src/System.Management.Automation/engine/MshSecurityException.cs +++ b/src/System.Management.Automation/engine/MshSecurityException.cs @@ -8,7 +8,6 @@ namespace System.Management.Automation /// /// This is a wrapper for exception class SecurityException. /// - [Serializable] public class PSSecurityException : RuntimeException { #region ctor @@ -34,19 +33,11 @@ public PSSecurityException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSSecurityException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - "UnauthorizedAccess", - ErrorCategory.SecurityError, - null); - _errorRecord.ErrorDetails = new ErrorDetails(SessionStateStrings.CanNotRun); - _message = _errorRecord.ErrorDetails.Message; - // no fields, nothing more to serialize - // no need for a GetObjectData implementation + throw new NotSupportedException(); } /// @@ -93,14 +84,11 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - "UnauthorizedAccess", - ErrorCategory.SecurityError, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + "UnauthorizedAccess", + ErrorCategory.SecurityError, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs index a74cae5252d..b4cf7c16eef 100644 --- a/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs +++ b/src/System.Management.Automation/engine/MshSnapinQualifiedName.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation /// /// A class representing a name that is qualified by the PSSnapin name. /// - internal class PSSnapinQualifiedName + internal sealed class PSSnapinQualifiedName { private PSSnapinQualifiedName(string[] splitName) { @@ -68,7 +68,7 @@ private PSSnapinQualifiedName(string[] splitName) { if (name == null) return null; - string[] splitName = name.Split(Utils.Separators.Backslash); + string[] splitName = name.Split('\\'); if (splitName.Length == 0 || splitName.Length > 2) return null; var result = new PSSnapinQualifiedName(splitName); diff --git a/src/System.Management.Automation/engine/NativeCommand.cs b/src/System.Management.Automation/engine/NativeCommand.cs index 822d4cf82d9..80748605a98 100644 --- a/src/System.Management.Automation/engine/NativeCommand.cs +++ b/src/System.Management.Automation/engine/NativeCommand.cs @@ -26,8 +26,7 @@ internal override void DoStopProcessing() { try { - if (_myCommandProcessor != null) - _myCommandProcessor.StopProcessing(); + _myCommandProcessor?.StopProcessing(); } catch (Exception) { diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs index e0c643c3d3b..31ac506c86a 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinder.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections; +using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; @@ -82,7 +83,7 @@ internal void BindParameters(Collection parameters) if (parameter.ParameterNameSpecified) { Diagnostics.Assert(!parameter.ParameterText.Contains(' '), "Parameters cannot have whitespace"); - PossiblyGlobArg(parameter.ParameterText, StringConstantType.BareWord); + PossiblyGlobArg(parameter.ParameterText, parameter, usedQuotes: false); if (parameter.SpaceAfterParameter) { @@ -107,30 +108,22 @@ internal void BindParameters(Collection parameters) // windbg -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect // The parser produced an array of strings but marked the parameter so we // can properly reconstruct the correct command line. - StringConstantType stringConstantType = StringConstantType.BareWord; + bool usedQuotes = false; ArrayLiteralAst arrayLiteralAst = null; switch (parameter?.ArgumentAst) { case StringConstantExpressionAst sce: - stringConstantType = sce.StringConstantType; + usedQuotes = sce.StringConstantType != StringConstantType.BareWord; break; case ExpandableStringExpressionAst ese: - stringConstantType = ese.StringConstantType; + usedQuotes = ese.StringConstantType != StringConstantType.BareWord; break; case ArrayLiteralAst ala: arrayLiteralAst = ala; break; } - // Prior to PSNativePSPathResolution experimental feature, a single quote worked the same as a double quote - // so if the feature is not enabled, we treat any quotes as double quotes. When this feature is no longer - // experimental, this code here needs to be removed. - if (!ExperimentalFeature.IsEnabled("PSNativePSPathResolution") && stringConstantType == StringConstantType.SingleQuoted) - { - stringConstantType = StringConstantType.DoubleQuoted; - } - - AppendOneNativeArgument(Context, argValue, arrayLiteralAst, sawVerbatimArgumentMarker, stringConstantType); + AppendOneNativeArgument(Context, parameter, argValue, arrayLiteralAst, sawVerbatimArgumentMarker, usedQuotes); } } } @@ -151,6 +144,69 @@ internal string Arguments private readonly StringBuilder _arguments = new StringBuilder(); + internal string[] ArgumentList + { + get + { + return _argumentList.ToArray(); + } + } + + /// + /// Add an argument to the ArgumentList. + /// We may need to construct the argument out of the parameter text and the argument + /// in the case that we have a parameter that appears as "-switch:value". + /// + /// The parameter associated with the operation. + /// The value used with parameter. + internal void AddToArgumentList(CommandParameterInternal parameter, string argument) + { + if (parameter.ParameterNameSpecified && parameter.ParameterText.EndsWith(':')) + { + if (argument != parameter.ParameterText) + { + // Only combine the text and argument if there was no space after the parameter, + // otherwise, add the parameter and arguments as separate elements. + if (parameter.SpaceAfterParameter) + { + _argumentList.Add(parameter.ParameterText); + _argumentList.Add(argument); + } + else + { + _argumentList.Add(parameter.ParameterText + argument); + } + } + } + else + { + _argumentList.Add(argument); + } + } + + private readonly List _argumentList = new List(); + + /// + /// Gets a value indicating whether to use an ArgumentList or string for arguments when invoking a native executable. + /// + internal NativeArgumentPassingStyle ArgumentPassingStyle + { + get + { + try + { + var preference = LanguagePrimitives.ConvertTo( + Context.GetVariableValue(SpecialVariables.NativeArgumentPassingVarPath, NativeArgumentPassingStyle.Standard)); + return preference; + } + catch + { + // The value is not convertible send back Legacy + return NativeArgumentPassingStyle.Legacy; + } + } + } + #endregion internal members #region private members @@ -161,24 +217,27 @@ internal string Arguments /// each of which will be stringized. /// /// Execution context instance. + /// The parameter associated with the operation. /// The object to append. /// If the argument was an array literal, the Ast, otherwise null. /// True if the argument occurs after --%. - /// Bare, SingleQuoted, or DoubleQuoted. - private void AppendOneNativeArgument(ExecutionContext context, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, StringConstantType stringConstantType) + /// True if the argument was a quoted string (single or double). + private void AppendOneNativeArgument(ExecutionContext context, CommandParameterInternal parameter, object obj, ArrayLiteralAst argArrayAst, bool sawVerbatimArgumentMarker, bool usedQuotes) { IEnumerator list = LanguagePrimitives.GetEnumerator(obj); - Diagnostics.Assert((argArrayAst == null) || obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count, "array argument and ArrayLiteralAst differ in number of elements"); + Diagnostics.Assert((argArrayAst == null) || (obj is object[] && ((object[])obj).Length == argArrayAst.Elements.Count), "array argument and ArrayLiteralAst differ in number of elements"); int currentElement = -1; string separator = string.Empty; do { string arg; + object currentObj; if (list == null) { arg = PSObject.ToStringParser(context, obj); + currentObj = obj; } else { @@ -187,7 +246,8 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array break; } - arg = PSObject.ToStringParser(context, ParserOps.Current(null, list)); + currentObj = ParserOps.Current(null, list); + arg = PSObject.ToStringParser(context, currentObj); currentElement += 1; if (currentElement != 0) @@ -198,12 +258,16 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array if (!string.IsNullOrEmpty(arg)) { + // Only add the separator to the argument string rather than adding a separator to the ArgumentList. _arguments.Append(separator); if (sawVerbatimArgumentMarker) { arg = Environment.ExpandEnvironmentVariables(arg); _arguments.Append(arg); + + // we need to split the argument on spaces + _argumentList.AddRange(arg.Split(' ', StringSplitOptions.RemoveEmptyEntries)); } else { @@ -223,18 +287,11 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array if (NeedQuotes(arg)) { _arguments.Append('"'); - - if (stringConstantType == StringConstantType.DoubleQuoted) - { - _arguments.Append(ResolvePath(arg, Context)); - } - else - { - _arguments.Append(arg); - } + AddToArgumentList(parameter, arg); // need to escape all trailing backslashes so the native command receives it correctly // according to http://www.daviddeley.com/autohotkey/parameters/parameters.htm#WINCRULESDOC + _arguments.Append(arg); for (int i = arg.Length - 1; i >= 0 && arg[i] == '\\'; i--) { _arguments.Append('\\'); @@ -244,179 +301,149 @@ private void AppendOneNativeArgument(ExecutionContext context, object obj, Array } else { - PossiblyGlobArg(arg, stringConstantType); + if (argArrayAst != null && ArgumentPassingStyle != NativeArgumentPassingStyle.Legacy) + { + // We have a literal array, so take the extent, break it on spaces and add them to the argument list. + foreach (string element in argArrayAst.Extent.Text.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + PossiblyGlobArg(element, parameter, usedQuotes); + } + + break; + } + else + { + PossiblyGlobArg(arg, parameter, usedQuotes); + } } } } + else if (ArgumentPassingStyle != NativeArgumentPassingStyle.Legacy && currentObj != null) + { + // add empty strings to arglist, but not nulls + AddToArgumentList(parameter, arg); + } } while (list != null); } /// - /// On Windows, just append . + /// On Windows, do tilde expansion, otherwise just append . /// On Unix, do globbing as appropriate, otherwise just append . /// /// The argument that possibly needs expansion. - /// Bare, SingleQuoted, or DoubleQuoted. - private void PossiblyGlobArg(string arg, StringConstantType stringConstantType) + /// The parameter associated with the operation. + /// True if the argument was a quoted string (single or double). + private void PossiblyGlobArg(string arg, CommandParameterInternal parameter, bool usedQuotes) { var argExpanded = false; #if UNIX // On UNIX systems, we expand arguments containing wildcard expressions against // the file system just like bash, etc. - - if (stringConstantType == StringConstantType.BareWord) + if (!usedQuotes && WildcardPattern.ContainsWildcardCharacters(arg)) { - if (WildcardPattern.ContainsWildcardCharacters(arg)) + // See if the current working directory is a filesystem provider location + // We won't do the expansion if it isn't since native commands can only access the file system. + var cwdinfo = Context.EngineSessionState.CurrentLocation; + + // If it's a filesystem location then expand the wildcards + if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { - // See if the current working directory is a filesystem provider location - // We won't do the expansion if it isn't since native commands can only access the file system. - var cwdinfo = Context.EngineSessionState.CurrentLocation; + // On UNIX, paths starting with ~ or absolute paths are not normalized + bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/'); - // If it's a filesystem location then expand the wildcards - if (cwdinfo.Provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) + // See if there are any matching paths otherwise just add the pattern as the argument + Collection paths = null; + try { - // On UNIX, paths starting with ~ or absolute paths are not normalized - bool normalizePath = arg.Length == 0 || !(arg[0] == '~' || arg[0] == '/'); - - // See if there are any matching paths otherwise just add the pattern as the argument - Collection paths = null; - try - { - paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); - } - catch - { - // Fallthrough will append the pattern unchanged. - } + paths = Context.EngineSessionState.InvokeProvider.ChildItem.Get(arg, false); + } + catch + { + // Fallthrough will append the pattern unchanged. + } - // Expand paths, but only from the file system. - if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo)) + // Expand paths, but only from the file system. + if (paths?.Count > 0 && paths.All(p => p.BaseObject is FileSystemInfo)) + { + var sep = string.Empty; + foreach (var path in paths) { - var sep = string.Empty; - foreach (var path in paths) + _arguments.Append(sep); + sep = " "; + var expandedPath = (path.BaseObject as FileSystemInfo).FullName; + if (normalizePath) { - _arguments.Append(sep); - sep = " "; - var expandedPath = (path.BaseObject as FileSystemInfo).FullName; - if (normalizePath) - { - expandedPath = - Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); - } - // If the path contains spaces, then add quotes around it. - if (NeedQuotes(expandedPath)) - { - _arguments.Append('"'); - _arguments.Append(expandedPath); - _arguments.Append('"'); - } - else - { - _arguments.Append(expandedPath); - } - - argExpanded = true; + expandedPath = + Context.SessionState.Path.NormalizeRelativePath(expandedPath, cwdinfo.ProviderPath); + } + // If the path contains spaces, then add quotes around it. + if (NeedQuotes(expandedPath)) + { + _arguments.Append('"'); + _arguments.Append(expandedPath); + _arguments.Append('"'); + } + else + { + _arguments.Append(expandedPath); } + + AddToArgumentList(parameter, expandedPath); + argExpanded = true; } } } - else + } + else if (!usedQuotes) + { + // Even if there are no wildcards, we still need to possibly + // expand ~ into the filesystem provider home directory path + if (ExpandTilde(arg, parameter)) { - // Even if there are no wildcards, we still need to possibly - // expand ~ into the filesystem provider home directory path - ProviderInfo fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); - string home = fileSystemProvider.Home; - if (string.Equals(arg, "~")) - { - _arguments.Append(home); - argExpanded = true; - } - else if (arg.StartsWith("~/", StringComparison.OrdinalIgnoreCase)) - { - var replacementString = home + arg.Substring(1); - _arguments.Append(replacementString); - argExpanded = true; - } + argExpanded = true; } } -#endif // UNIX - - if (stringConstantType != StringConstantType.SingleQuoted) +#else + if (!usedQuotes && ExpandTilde(arg, parameter)) { - arg = ResolvePath(arg, Context); + argExpanded = true; } +#endif if (!argExpanded) { _arguments.Append(arg); + AddToArgumentList(parameter, arg); } } /// - /// Check if string is prefixed by psdrive, if so, expand it if filesystem path. + /// Replace tilde for unquoted arguments in the form ~ and ~/. For windows, ~\ is also expanded. /// - /// The potential PSPath to resolve. - /// The current ExecutionContext. - /// Resolved PSPath if applicable otherwise the original path - internal static string ResolvePath(string path, ExecutionContext context) + /// The argument that possibly needs expansion. + /// The parameter associated with the operation. + /// True if tilde expansion occurred. + private bool ExpandTilde(string arg, CommandParameterInternal parameter) { - if (ExperimentalFeature.IsEnabled("PSNativePSPathResolution")) + var fileSystemProvider = Context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); + var home = fileSystemProvider.Home; + if (string.Equals(arg, "~")) { -#if !UNIX - // on Windows, we need to expand ~ to point to user's home path - if (string.Equals(path, "~", StringComparison.Ordinal) || path.StartsWith(TildeDirectorySeparator, StringComparison.Ordinal) || path.StartsWith(TildeAltDirectorySeparator, StringComparison.Ordinal)) - { - try - { - ProviderInfo fileSystemProvider = context.EngineSessionState.GetSingleProvider(FileSystemProvider.ProviderName); - return new StringBuilder(fileSystemProvider.Home) - .Append(path.Substring(1)) - .Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar) - .ToString(); - } - catch - { - return path; - } - } - - // check if the driveName is an actual disk drive on Windows, if so, no expansion - if (path.Length >= 2 && path[1] == ':') - { - foreach (var drive in DriveInfo.GetDrives()) - { - if (drive.Name.StartsWith(new string(path[0], 1), StringComparison.OrdinalIgnoreCase)) - { - return path; - } - } - } -#endif - - if (path.Contains(':')) - { - LocationGlobber globber = new LocationGlobber(context.SessionState); - try - { - ProviderInfo providerInfo; - - // replace the argument with resolved path if it's a filesystem path - string pspath = globber.GetProviderPath(path, out providerInfo); - if (string.Equals(providerInfo.Name, FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) - { - path = pspath; - } - } - catch - { - // if it's not a provider path, do nothing - } - } + _arguments.Append(home); + AddToArgumentList(parameter, home); + return true; + } + else if (arg.StartsWith("~/") || (OperatingSystem.IsWindows() && arg.StartsWith(@"~\"))) + { + var replacementString = string.Concat(home, arg.AsSpan(1)); + _arguments.Append(replacementString); + AddToArgumentList(parameter, replacementString); + return true; } - return path; + return false; } /// @@ -446,7 +473,10 @@ internal static bool NeedQuotes(string stringToCheck) private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, int index) { - if (arrayLiteralAst == null) return " "; + if (arrayLiteralAst == null) + { + return " "; + } // index points to the *next* element, so we're looking for space between // it and the previous element. @@ -458,14 +488,25 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, var afterPrev = prev.Extent.EndOffset; var beforeNext = next.Extent.StartOffset - 1; - if (afterPrev == beforeNext) return ","; + if (afterPrev == beforeNext) + { + return ","; + } var arrayText = arrayExtent.Text; afterPrev -= arrayExtent.StartOffset; beforeNext -= arrayExtent.StartOffset; - if (arrayText[afterPrev] == ',') return ", "; - if (arrayText[beforeNext] == ',') return " ,"; + if (arrayText[afterPrev] == ',') + { + return ", "; + } + + if (arrayText[beforeNext] == ',') + { + return " ,"; + } + return " , "; } @@ -473,8 +514,6 @@ private static string GetEnumerableArgSeparator(ArrayLiteralAst arrayLiteralAst, /// The native command to bind to. /// private readonly NativeCommand _nativeCommand; - private static readonly string TildeDirectorySeparator = $"~{Path.DirectorySeparatorChar}"; - private static readonly string TildeAltDirectorySeparator = $"~{Path.AltDirectorySeparatorChar}"; #endregion private members } diff --git a/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs b/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs index ecdd4554abe..9a1dab71beb 100644 --- a/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs +++ b/src/System.Management.Automation/engine/NativeCommandParameterBinderController.cs @@ -38,6 +38,28 @@ internal string Arguments } } + /// + /// Gets the value of the command arguments as an array of strings. + /// + internal string[] ArgumentList + { + get + { + return ((NativeCommandParameterBinder)DefaultParameterBinder).ArgumentList; + } + } + + /// + /// Gets the value indicating what type of native argument binding to use. + /// + internal NativeArgumentPassingStyle ArgumentPassingStyle + { + get + { + return ((NativeCommandParameterBinder)DefaultParameterBinder).ArgumentPassingStyle; + } + } + /// /// Passes the binding directly through to the parameter binder. /// It does no verification against metadata. @@ -49,8 +71,7 @@ internal string Arguments /// Ignored. /// /// - /// True if the parameter was successfully bound. Any error condition - /// produces an exception. + /// True if the parameter was successfully bound. Any error condition produces an exception. /// internal override bool BindParameter( CommandParameterInternal argument, diff --git a/src/System.Management.Automation/engine/NativeCommandProcessor.cs b/src/System.Management.Automation/engine/NativeCommandProcessor.cs index 96ad84a6c46..145fe968fda 100644 --- a/src/System.Management.Automation/engine/NativeCommandProcessor.cs +++ b/src/System.Management.Automation/engine/NativeCommandProcessor.cs @@ -3,21 +3,26 @@ #pragma warning disable 1634, 1691 +using System.Collections; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.ComponentModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; -using System.ComponentModel; +using System.Linq; +using System.Management.Automation.Internal; +using System.Runtime.CompilerServices; +using System.Runtime.Serialization; using System.Text; -using System.Collections; using System.Threading; -using System.Management.Automation.Internal; +using System.Threading.Tasks; using System.Xml; -using System.Runtime.InteropServices; +using Microsoft.PowerShell.Commands; +using Microsoft.PowerShell.Telemetry; +using Microsoft.Win32; using Dbg = System.Management.Automation.Diagnostics; -using System.Runtime.Serialization; -using System.Globalization; -using System.Diagnostics.CodeAnalysis; -using System.Collections.Concurrent; -using System.Collections.Generic; namespace System.Management.Automation { @@ -130,11 +135,273 @@ internal ProcessOutputObject(object data, MinishellStream stream) } } +#nullable enable + /// + /// This exception is used by the NativeCommandProcessor to indicate an error + /// when a native command returns a non-zero exit code. + /// + public sealed class NativeCommandExitException : RuntimeException + { + // NOTE: + // When implementing the native error action preference integration, + // reusing ApplicationFailedException was rejected. + // Instead of reusing a type already used in another scenario + // it was decided instead to use a fresh type to avoid conflating the two scenarios: + // * ApplicationFailedException: PowerShell was not able to complete execution of the application. + // * NativeCommandExitException: the application completed execution but returned a non-zero exit code. + + #region Constructors + + /// + /// Initializes a new instance of the class with information on the native + /// command, a specified error message and a specified error ID. + /// + /// The full path of the native command. + /// The exit code returned by the native command. + /// The process ID of the process before it ended. + /// The error message. + /// The PowerShell runtime error ID. + internal NativeCommandExitException(string path, int exitCode, int processId, string message, string errorId) + : base(message) + { + SetErrorId(errorId); + SetErrorCategory(ErrorCategory.NotSpecified); + Path = path; + ExitCode = exitCode; + ProcessId = processId; + } + + #endregion Constructors + + /// + /// Gets the path of the native command. + /// + public string? Path { get; } + + /// + /// Gets the exit code returned by the native command. + /// + public int ExitCode { get; } + + /// + /// Gets the native command's process ID. + /// + public int ProcessId { get; } + + } +#nullable restore + /// /// Provides way to create and execute native commands. /// internal class NativeCommandProcessor : CommandProcessorBase { + /// + /// This is the list of files which will trigger Legacy behavior if 'PSNativeCommandArgumentPassing' is set to "Windows". + /// + private static readonly HashSet s_legacyFileExtensions = new(StringComparer.OrdinalIgnoreCase) + { + ".js", + ".wsf", + ".cmd", + ".bat", + ".vbs", + }; + + /// + /// This is the list of native commands that have non-standard behavior with regard to argument passing. + /// We use Legacy argument parsing for them when 'PSNativeCommandArgumentPassing' is set to "Windows". + /// + private static readonly HashSet s_legacyCommands = new(StringComparer.OrdinalIgnoreCase) + { + "cmd", + "cscript", + "find", + "sqlcmd", + "wscript", + }; + +#if !UNIX + /// + /// List of known package managers pulled from the registry. + /// + private static readonly HashSet s_knownPackageManagers = GetPackageManagerListFromRegistry(); + + /// + /// Indicates whether the Path Update feature is enabled in a given session. + /// PowerShell sessions could reuse the same thread, so we cannot cache the value with a thread static variable. + /// + private static readonly ConditionalWeakTable s_pathUpdateFeatureEnabled = new(); + + private readonly bool _isPackageManager; + private string _originalUserEnvPath; + private string _originalSystemEnvPath; + + /// + /// Gets the known package managers from the registry. + /// + private static HashSet GetPackageManagerListFromRegistry() + { + // We only account for the first 8 package managers. This is the same behavior as in CMD. + const int MaxPackageManagerCount = 8; + const string RegKeyPath = @"Software\Microsoft\Command Processor\KnownPackageManagers"; + + string[] subKeyNames = null; + HashSet retSet = null; + + try + { + using RegistryKey key = Registry.LocalMachine.OpenSubKey(RegKeyPath); + subKeyNames = key?.GetSubKeyNames(); + } + catch + { + return null; + } + + if (subKeyNames is { Length: > 0 }) + { + IEnumerable names = subKeyNames.Length <= MaxPackageManagerCount + ? subKeyNames + : subKeyNames.Take(MaxPackageManagerCount); + + retSet = new(names, StringComparer.OrdinalIgnoreCase); + } + + return retSet; + } + + /// + /// Check if the given name is a known package manager from the registry list. + /// + private static bool IsKnownPackageManager(string name) + { + if (s_knownPackageManagers is null) + { + return false; + } + + if (s_knownPackageManagers.Contains(name)) + { + return true; + } + + int lastDotIndex = name.LastIndexOf('.'); + if (lastDotIndex > 0) + { + string nameWithoutExt = name[..lastDotIndex]; + if (s_knownPackageManagers.Contains(nameWithoutExt)) + { + return true; + } + } + + return false; + } + + /// + /// Check if the Path Update feature is enabled for the given session. + /// + private static bool IsPathUpdateFeatureEnabled(ExecutionContext context) + { + // We check only once per session. + if (s_pathUpdateFeatureEnabled.TryGetValue(context, out string value)) + { + // The feature is enabled if the value is not null. + return value is { }; + } + + // Disable Path Update if 'EnvironmentProvider' is disabled in the current session, or the current session is restricted. + bool enabled = context.EngineSessionState.Providers.ContainsKey(EnvironmentProvider.ProviderName) + && !Utils.IsSessionRestricted(context); + + // - Use the static empty string instance to indicate that the feature is enabled. + // - Use the null value to indicate that the feature is disabled. + s_pathUpdateFeatureEnabled.TryAdd(context, enabled ? string.Empty : null); + return enabled; + } + + /// + /// Gets the added part of the new string compared to the old string. + /// + private static ReadOnlySpan GetAddedPartOfString(string oldString, string newString) + { + if (oldString.Length >= newString.Length) + { + // Nothing added or something removed. + return ReadOnlySpan.Empty; + } + + int index = newString.IndexOf(oldString); + if (index is -1) + { + // The new and old strings are drastically different. Stop trying in this case. + return ReadOnlySpan.Empty; + } + + if (index > 0) + { + // Found the old string at non-zero offset, so something was prepended to the old string. + return newString.AsSpan(0, index); + } + else + { + // Found the old string at the beginning of the new string, so something was appended to the old string. + return newString.AsSpan(oldString.Length); + } + } + + /// + /// Update the process-scope environment variable Path based on the changes in the user-scope and system-scope Path. + /// + /// The old value of the user-scope Path retrieved from registry. + /// The old value of the system-scope Path retrieved from registry. + private static void UpdateProcessEnvPath(string oldUserPath, string oldSystemPath) + { + string newUserEnvPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User); + string newSystemEnvPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); + string procEnvPath = Environment.GetEnvironmentVariable("Path"); + + ReadOnlySpan userPathChange = GetAddedPartOfString(oldUserPath, newUserEnvPath).Trim(';'); + ReadOnlySpan systemPathChange = GetAddedPartOfString(oldSystemPath, newSystemEnvPath).Trim(';'); + + // Add 2 to account for the path separators we may need to add. + int maxLength = procEnvPath.Length + userPathChange.Length + systemPathChange.Length + 2; + StringBuilder newPath = null; + + if (userPathChange.Length > 0) + { + CreateNewProcEnvPath(userPathChange); + } + + if (systemPathChange.Length > 0) + { + CreateNewProcEnvPath(systemPathChange); + } + + if (newPath is { Length: > 0 }) + { + // Update the process env Path. + Environment.SetEnvironmentVariable("Path", newPath.ToString()); + } + + // Helper method to create a new env Path string. + void CreateNewProcEnvPath(ReadOnlySpan newChange) + { + newPath ??= new StringBuilder(procEnvPath, capacity: maxLength); + + if (newPath.Length is 0 || newPath[^1] is ';') + { + newPath.Append(newChange); + } + else + { + newPath.Append(';').Append(newChange); + } + } + } +#endif + #region ctor/native command properties /// @@ -181,7 +448,11 @@ internal NativeCommandProcessor(ApplicationInfo applicationInfo, ExecutionContex // Create input writer for providing input to the process. _inputWriter = new ProcessInputWriter(Command); - _isTranscribing = this.Command.Context.EngineHostInterface.UI.IsTranscribing; + _isTranscribing = context.EngineHostInterface.UI.IsTranscribing; + +#if !UNIX + _isPackageManager = IsKnownPackageManager(_applicationInfo.Name) && IsPathUpdateFeatureEnabled(context); +#endif } /// @@ -221,16 +492,16 @@ private string Path } } + internal NativeCommandProcessor DownStreamNativeCommand { get; set; } + + internal bool UpstreamIsNativeCommand { get; set; } + + internal BytePipe StdOutDestination { get; set; } + #endregion ctor/native command properties #region parameter binder - /// - /// Variable which is set to true when prepare is called. - /// Parameter Binder should only be created after Prepare method is called. - /// - private bool _isPreparedCalled = false; - /// /// Parameter binder used by this command processor. /// @@ -247,8 +518,6 @@ private string Path /// internal ParameterBinderController NewParameterBinderController(InternalCommand command) { - Dbg.Assert(_isPreparedCalled, "parameter binder should not be created before prepared is called"); - if (_isMiniShell) { _nativeParameterBinderController = @@ -287,8 +556,6 @@ internal NativeCommandParameterBinderController NativeParameterBinderController /// internal override void Prepare(IDictionary psDefaultParameterValues) { - _isPreparedCalled = true; - // Check if the application is minishell _isMiniShell = IsMiniShell(); @@ -306,7 +573,7 @@ internal override void Prepare(IDictionary psDefaultParameterValues) catch (Exception) { // Do cleanup in case of exception - CleanUp(); + CleanUp(killBackgroundProcess: true); throw; } } @@ -318,9 +585,14 @@ internal override void ProcessRecord() { try { - while (Read()) + // If upstream is a native command it'll be writing directly to our stdin stream + // so we can skip reading here. + if (!UpstreamIsNativeCommand) { - _inputWriter.Add(Command.CurrentPipelineObject); + while (Read()) + { + _inputWriter.Add(Command.CurrentPipelineObject); + } } ConsumeAvailableNativeProcessOutput(blocking: false); @@ -328,7 +600,7 @@ internal override void ProcessRecord() catch (Exception) { // Do cleanup in case of exception - CleanUp(); + CleanUp(killBackgroundProcess: true); throw; } } @@ -336,7 +608,7 @@ internal override void ProcessRecord() /// /// Process object for the invoked application. /// - private System.Diagnostics.Process _nativeProcess; + private Process _nativeProcess; /// /// This is used for writing input to the process. @@ -357,7 +629,7 @@ internal override void ProcessRecord() /// /// Indicate if we have called 'NotifyBeginApplication()' on the host, so that - /// we can call the counterpart 'NotifyEndApplication' as approriate. + /// we can call the counterpart 'NotifyEndApplication' as appropriate. /// private bool _hasNotifiedBeginApplication; @@ -378,6 +650,59 @@ internal override void ProcessRecord() /// private readonly object _sync = new object(); + private SemaphoreSlim _processInitialized; + + internal async Task WaitForProcessInitializationAsync(CancellationToken cancellationToken) + { + SemaphoreSlim processInitialized = _processInitialized; + if (processInitialized is null) + { + lock (_sync) + { + processInitialized = _processInitialized ??= new SemaphoreSlim(0, 1); + } + } + + try + { + await processInitialized.WaitAsync(cancellationToken); + } + finally + { + processInitialized.Release(); + } + } + + /// + /// Creates a pipe representing the streaming of unprocessed bytes. + /// + /// + /// The stream that the pipe should represent. + /// for stdout, for stdin. + /// + /// A new byte pipe representing the specified stream. + internal BytePipe CreateBytePipe(bool stdout) => new NativeCommandProcessorBytePipe(this, stdout); + + /// + /// Gets the specified base for the underlying + /// . + /// + /// + /// The stream that should be retrieved. for + /// stdout, for stdin. + /// + /// The specified . + internal Stream GetStream(bool stdout) + { + Debug.Assert( + _nativeProcess is not null, + "Caller should verify that initialization has completed before attempting to get the underlying stream."); + + return stdout + ? _nativeProcess.StandardOutput.BaseStream + : _nativeProcess.StandardInput.BaseStream; + } + /// /// Executes the native command once all of the input has been gathered. /// @@ -409,6 +734,11 @@ private void InitNativeProcess() // Get the start info for the process. ProcessStartInfo startInfo = GetProcessStartInfo(redirectOutput, redirectError, redirectInput, soloCommand); + // Send Telemetry indicating what argument passing mode we are in. + ApplicationInsightsTelemetry.SendExperimentalUseData( + "PSWindowsNativeCommandArgPassing", + NativeParameterBinderController.ArgumentPassingStyle.ToString()); + #if !UNIX string commandPath = this.Path.ToLowerInvariant(); if (commandPath.EndsWith("powershell.exe") || commandPath.EndsWith("powershell_ise.exe")) @@ -420,6 +750,12 @@ private void InitNativeProcess() // must set UseShellExecute to false if we modify the environment block startInfo.UseShellExecute = false; } + + if (_isPackageManager) + { + _originalUserEnvPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.User); + _originalSystemEnvPath = Environment.GetEnvironmentVariable("Path", EnvironmentVariableTarget.Machine); + } #endif if (this.Command.Context.CurrentPipelineStopping) @@ -430,15 +766,14 @@ private void InitNativeProcess() Exception exceptionToRethrow = null; try { - // If this process is being run standalone, tell the host, which might want - // to save off the window title or other such state as might be tweaked by - // the native process + // Before start the executable, tell the host, which might want to save off the + // window title or other such state as might be tweaked by the native process. + Command.Context.EngineHostInterface.NotifyBeginApplication(); + _hasNotifiedBeginApplication = true; + if (_runStandAlone) { - this.Command.Context.EngineHostInterface.NotifyBeginApplication(); - _hasNotifiedBeginApplication = true; - - // Also, store the Raw UI coordinates so that we can scrape the screen after + // Store the Raw UI coordinates so that we can scrape the screen after // if we are transcribing. if (_isTranscribing && (s_supportScreenScrape == true)) { @@ -467,13 +802,20 @@ private void InitNativeProcess() } catch (Win32Exception) { - // On Unix platforms, nothing can be further done, so just throw +#if UNIX + // On Unix platforms, nothing can be further done, so just throw. + throw; +#else // On headless Windows SKUs, there is no shell to fall back to, so just throw - if (!Platform.IsWindowsDesktop) { throw; } + if (!Platform.IsWindowsDesktop) + { + throw; + } // on Windows desktops, see if there is a file association for this command. If so then we'll use that. - string executable = FindExecutable(startInfo.FileName); + string executable = Interop.Windows.FindExecutable(startInfo.FileName); bool notDone = true; + // check to see what mode we should be in for argument passing if (!string.IsNullOrEmpty(executable)) { isWindowsApplication = IsWindowsApplication(executable); @@ -485,7 +827,17 @@ private void InitNativeProcess() string oldArguments = startInfo.Arguments; string oldFileName = startInfo.FileName; - startInfo.Arguments = "\"" + startInfo.FileName + "\" " + startInfo.Arguments; + // Check to see whether this executable should be using Legacy mode argument parsing + bool useSpecialArgumentPassing = UseSpecialArgumentPassing(oldFileName); + if (useSpecialArgumentPassing) + { + // codeql[cs/microsoft/command-line-injection] - This is expected PowerShell behavior where user inputted paths are supported for the context of this method and the path portion of the argument is escaped. The user assumes trust for the file path specified on the user's system to start process for, and in the case of remoting, restricted remoting security guidelines should be used. + startInfo.Arguments = "\"" + oldFileName + "\" " + startInfo.Arguments; + } + else + { + startInfo.ArgumentList.Insert(0, oldFileName); + } startInfo.FileName = executable; try { @@ -495,7 +847,16 @@ private void InitNativeProcess() catch (Win32Exception) { // Restore the old filename and arguments to try shell execute last... - startInfo.Arguments = oldArguments; + if (useSpecialArgumentPassing) + { + startInfo.Arguments = oldArguments; + } + else + { + startInfo.ArgumentList.RemoveAt(0); + } + + // codeql[cs/microsoft/command-line-injection-shell-execution] - This is expected PowerShell behavior where user inputted paths are supported for the context of this method. The user assumes trust for the file path specified on the user's system to retrieve process info for, and in the case of remoting, restricted remoting security guidelines should be used. startInfo.FileName = oldFileName; } } @@ -517,6 +878,13 @@ private void InitNativeProcess() throw; } } +#endif + } + + if (UpstreamIsNativeCommand) + { + _processInitialized ??= new SemaphoreSlim(0, 1); + _processInitialized.Release(); } } @@ -550,7 +918,7 @@ private void InitNativeProcess() lock (_sync) { - if (!_stopped) + if (!_stopped && !UpstreamIsNativeCommand) { _inputWriter.Start(_nativeProcess, inputFormat); } @@ -599,6 +967,8 @@ private void InitNativeProcess() } } + private AsyncByteStreamTransfer _stdOutByteTransfer; + private void InitOutputQueue() { // if output is redirected, start reading output of process in queue. @@ -608,9 +978,32 @@ private void InitOutputQueue() { if (!_stopped) { + if (CommandRuntime.ErrorMergeTo is MshCommandRuntime.MergeDataStream.Output) + { + StdOutDestination = null; + if (DownStreamNativeCommand is not null) + { + DownStreamNativeCommand.UpstreamIsNativeCommand = false; + DownStreamNativeCommand = null; + } + } + _nativeProcessOutputQueue = new BlockingCollection(); // we don't assign the handler to anything, because it's used only for objects marshaling - new ProcessOutputHandler(_nativeProcess, _nativeProcessOutputQueue); + BytePipe stdOutDestination = StdOutDestination ?? DownStreamNativeCommand?.CreateBytePipe(stdout: false); + + BytePipe stdOutSource = null; + if (stdOutDestination is not null) + { + stdOutSource = CreateBytePipe(stdout: true); + } + + _ = new ProcessOutputHandler( + _nativeProcess, + _nativeProcessOutputQueue, + stdOutDestination, + stdOutSource, + out _stdOutByteTransfer); } } } @@ -641,12 +1034,9 @@ private ProcessOutputObject DequeueProcessOutput(bool blocking) return null; } - else - { - ProcessOutputObject record = null; - _nativeProcessOutputQueue.TryTake(out record); - return record; - } + + _nativeProcessOutputQueue.TryTake(out ProcessOutputObject record); + return record; } /// @@ -654,21 +1044,38 @@ private ProcessOutputObject DequeueProcessOutput(bool blocking) /// private void ConsumeAvailableNativeProcessOutput(bool blocking) { - if (!_isRunningInBackground) + if (_isRunningInBackground) + { + return; + } + + bool stdOutRedirected = _nativeProcess.StartInfo.RedirectStandardOutput; + bool stdErrRedirected = _nativeProcess.StartInfo.RedirectStandardError; + if (stdOutRedirected && _stdOutByteTransfer is not null) { - if (_nativeProcess.StartInfo.RedirectStandardOutput || _nativeProcess.StartInfo.RedirectStandardError) + if (blocking) { - ProcessOutputObject record; - while ((record = DequeueProcessOutput(blocking)) != null) - { - if (this.Command.Context.CurrentPipelineStopping) - { - this.StopProcessing(); - return; - } + _stdOutByteTransfer.EOF.GetAwaiter().GetResult(); + } + + if (!stdErrRedirected) + { + return; + } + } - ProcessOutputRecord(record); + if (stdOutRedirected || stdErrRedirected) + { + ProcessOutputObject record; + while ((record = DequeueProcessOutput(blocking)) != null) + { + if (this.Command.Context.CurrentPipelineStopping) + { + this.StopProcessing(); + return; } + + ProcessOutputRecord(record); } } } @@ -681,12 +1088,22 @@ internal override void Complete() if (!_isRunningInBackground) { // Wait for input writer to finish. - _inputWriter.Done(); + if (!UpstreamIsNativeCommand || _nativeProcess.StartInfo.RedirectStandardError) + { + _inputWriter.Done(); + } // read all the available output in the blocking way ConsumeAvailableNativeProcessOutput(blocking: true); _nativeProcess.WaitForExit(); +#if !UNIX + if (_isPackageManager) + { + UpdateProcessEnvPath(_originalUserEnvPath, _originalSystemEnvPath); + } +#endif + // Capture screen output if we are transcribing and running stand alone if (_isTranscribing && (s_supportScreenScrape == true) && _runStandAlone) { @@ -725,8 +1142,63 @@ internal override void Complete() } this.Command.Context.SetVariable(SpecialVariables.LastExitCodeVarPath, _nativeProcess.ExitCode); - if (_nativeProcess.ExitCode != 0) - this.commandRuntime.PipelineProcessor.ExecutionFailed = true; + if (_nativeProcess.ExitCode == 0) + { + return; + } + + this.commandRuntime.PipelineProcessor.ExecutionFailed = true; + + // We send telemetry information only if the feature is enabled. + // This shouldn't be done once, because it's a run-time check we should send telemetry every time. + // Report on the following conditions: + // - The variable is not present + // - The value is not set (variable is null) + // - The value is set to true or false + bool useDefaultSetting; + bool nativeErrorActionPreferenceSetting = Command.Context.GetBooleanPreference( + SpecialVariables.PSNativeCommandUseErrorActionPreferenceVarPath, + defaultPref: false, + out useDefaultSetting); + + // The variable is unset + if (useDefaultSetting) + { + ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandErrorActionPreference", "unset"); + return; + } + + // Send the value that was set. + ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandErrorActionPreference", nativeErrorActionPreferenceSetting.ToString()); + + // if it was explicitly set to false, return + if (!nativeErrorActionPreferenceSetting) + { + return; + } + + const string errorId = nameof(CommandBaseStrings.ProgramExitedWithNonZeroCode); +#if UNIX + string hexFormatStr = "0x{0:X2}"; +#else + string hexFormatStr = "0x{0:X8}"; +#endif + + string errorMsg = StringUtil.Format( + CommandBaseStrings.ProgramExitedWithNonZeroCode, + NativeCommandName, + _nativeProcess.ExitCode, + string.Format(CultureInfo.InvariantCulture, hexFormatStr, _nativeProcess.ExitCode)); + + var exception = new NativeCommandExitException( + Path, + _nativeProcess.ExitCode, + _nativeProcess.Id, + errorMsg, + errorId); + + var errorRecord = new ErrorRecord(exception, errorId, ErrorCategory.NotSpecified, targetObject: Path); + this.commandRuntime._WriteErrorSkipAllowCheck(errorRecord); } } catch (Win32Exception e) @@ -745,7 +1217,7 @@ internal override void Complete() finally { // Do some cleanup - CleanUp(); + CleanUp(killBackgroundProcess: false); } // An exception was thrown while attempting to run the program @@ -936,27 +1408,19 @@ private static void KillChildProcesses(int parentId, ProcessWithParentId[] curre /// /// /// - [ArchitectureSensitive] private static bool IsWindowsApplication(string fileName) { #if UNIX return false; #else - if (!Platform.IsWindowsDesktop) { return false; } - - // SHGetFileInfo() does not understand reparse points and returns 0 ("non exe or error") - // so we are trying to get a real path before. - // It is a workaround for Microsoft Store applications. - string realPath = Microsoft.PowerShell.Commands.InternalSymbolicLinkLinkCodeMethods.WinInternalGetTarget(fileName); - if (realPath is not null) + if (!Platform.IsWindowsDesktop) { - fileName = realPath; + return false; } - SHFILEINFO shinfo = new SHFILEINFO(); - IntPtr type = SHGetFileInfo(fileName, 0, ref shinfo, (uint)Marshal.SizeOf(shinfo), SHGFI_EXETYPE); + int type = Interop.Windows.SHGetFileInfo(fileName); - switch ((int)type) + switch (type) { case 0x0: // 0x0 = not an exe @@ -987,7 +1451,11 @@ internal void StopProcessing() { lock (_sync) { - if (_stopped) return; + if (_stopped) + { + return; + } + _stopped = true; } @@ -996,8 +1464,12 @@ internal void StopProcessing() if (!_runStandAlone) { // Stop input writer - _inputWriter.Stop(); + if (!UpstreamIsNativeCommand) + { + _inputWriter.Stop(); + } + _stdOutByteTransfer?.Dispose(); KillProcess(_nativeProcess); } } @@ -1008,21 +1480,34 @@ internal void StopProcessing() /// /// Aggressively clean everything up... /// - private void CleanUp() + /// If set, also terminate background process. + private void CleanUp(bool killBackgroundProcess) { // We need to call 'NotifyEndApplication' as appropriate during cleanup if (_hasNotifiedBeginApplication) { - this.Command.Context.EngineHostInterface.NotifyEndApplication(); + Command.Context.EngineHostInterface.NotifyEndApplication(); } try { - // Dispose the process if it's already created - if (_nativeProcess != null) + // on Unix, we need to kill the process (if not running in background) to ensure it terminates, + // as Dispose() merely closes the redirected streams and the process does not exit. + // However, on Windows, a winexe like notepad should continue running so we don't want to kill it. +#if UNIX + if (killBackgroundProcess || !_isRunningInBackground) { - _nativeProcess.Dispose(); + try + { + _nativeProcess?.Kill(); + } + catch + { + // Ignore all exceptions since it is cleanup. + } } +#endif + _nativeProcess?.Dispose(); } catch (Exception) { @@ -1038,7 +1523,7 @@ private void ProcessOutputRecord(ProcessOutputObject outputValue) ErrorRecord record = outputValue.Data as ErrorRecord; Dbg.Assert(record != null, "ProcessReader should ensure that data is ErrorRecord"); record.SetInvocationInfo(this.Command.MyInvocation); - this.commandRuntime._WriteErrorSkipAllowCheck(record, isNativeError: true); + this.commandRuntime._WriteErrorSkipAllowCheck(record, isFromNativeStdError: true); } else if (outputValue.Stream == MinishellStream.Output) { @@ -1096,56 +1581,83 @@ private void ProcessOutputRecord(ProcessOutputObject outputValue) } /// - /// Gets the start info for process. + /// Get whether we should treat this executable with special handling and use the legacy passing style. /// - /// - /// - /// - /// - /// - private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectError, bool redirectInput, bool soloCommand) + /// + private bool UseSpecialArgumentPassing(string filePath) => + NativeParameterBinderController.ArgumentPassingStyle switch + { + NativeArgumentPassingStyle.Legacy => true, + NativeArgumentPassingStyle.Windows => ShouldUseLegacyPassingStyle(filePath), + _ => false + }; + + /// + /// Gets the ProcessStartInfo for process. + /// + /// A boolean that indicates that, when true, output from the process is redirected to a stream, and otherwise is sent to stdout. + /// A boolean that indicates that, when true, error output from the process is redirected to a stream, and otherwise is sent to stderr. + /// A boolean that indicates that, when true, input to the process is taken from a stream, and otherwise is taken from stdin. + /// A boolean that indicates, when true, that the command to be executed is not part of a pipeline, and otherwise indicates that it is. + /// A ProcessStartInfo object which is the base of the native invocation. + private ProcessStartInfo GetProcessStartInfo( + bool redirectOutput, + bool redirectError, + bool redirectInput, + bool soloCommand) { - ProcessStartInfo startInfo = new ProcessStartInfo(); - startInfo.FileName = this.Path; + var startInfo = new ProcessStartInfo + { + // codeql[cs/microsoft/command-line-injection-shell-execution] - This is expected PowerShell behavior where user inputted paths are supported for the context of this method. The user assumes trust for the file path specified on the user's system to retrieve process info for, and in the case of remoting, restricted remoting security guidelines should be used. + FileName = this.Path + }; - if (IsExecutable(this.Path)) + if (!IsExecutable(this.Path)) { - startInfo.UseShellExecute = false; - if (redirectInput) + if (Platform.IsNanoServer || Platform.IsIoT) { - startInfo.RedirectStandardInput = true; + // Shell doesn't exist on headless SKUs, so documents cannot be associated with an application. + // Therefore, we cannot run document in this case. + throw InterpreterError.NewInterpreterException( + this.Path, + typeof(RuntimeException), + this.Command.InvocationExtent, + "CantActivateDocumentInPowerShellCore", + ParserStrings.CantActivateDocumentInPowerShellCore, + this.Path); } - if (redirectOutput) + // We only want to ShellExecute something that is standalone... + if (!soloCommand) { - startInfo.RedirectStandardOutput = true; - startInfo.StandardOutputEncoding = Console.OutputEncoding; + throw InterpreterError.NewInterpreterException( + this.Path, + typeof(RuntimeException), + this.Command.InvocationExtent, + "CantActivateDocumentInPipeline", + ParserStrings.CantActivateDocumentInPipeline, + this.Path); } - if (redirectError) - { - startInfo.RedirectStandardError = true; - startInfo.StandardErrorEncoding = Console.OutputEncoding; - } + startInfo.UseShellExecute = true; } else { - if (Platform.IsNanoServer || Platform.IsIoT) + startInfo.UseShellExecute = false; + startInfo.RedirectStandardInput = redirectInput; + + Encoding outputEncoding = GetOutputEncoding(); + if (redirectOutput) { - // Shell doesn't exist on headless SKUs, so documents cannot be associated with an application. - // Therefore, we cannot run document in this case. - throw InterpreterError.NewInterpreterException(this.Path, typeof(RuntimeException), - this.Command.InvocationExtent, "CantActivateDocumentInPowerShellCore", ParserStrings.CantActivateDocumentInPowerShellCore, this.Path); + startInfo.RedirectStandardOutput = true; + startInfo.StandardOutputEncoding = outputEncoding; } - // We only want to ShellExecute something that is standalone... - if (!soloCommand) + if (redirectError) { - throw InterpreterError.NewInterpreterException(this.Path, typeof(RuntimeException), - this.Command.InvocationExtent, "CantActivateDocumentInPipeline", ParserStrings.CantActivateDocumentInPipeline, this.Path); + startInfo.RedirectStandardError = true; + startInfo.StandardErrorEncoding = outputEncoding; } - - startInfo.UseShellExecute = true; } // For minishell value of -outoutFormat parameter depends on value of redirectOutput. @@ -1153,22 +1665,86 @@ private ProcessStartInfo GetProcessStartInfo(bool redirectOutput, bool redirectE if (_isMiniShell) { MinishellParameterBinderController mpc = (MinishellParameterBinderController)NativeParameterBinderController; - mpc.BindParameters(arguments, redirectOutput, this.Command.Context.EngineHostInterface.Name); + mpc.BindParameters(arguments, startInfo.RedirectStandardOutput, this.Command.Context.EngineHostInterface.Name); startInfo.CreateNoWindow = mpc.NonInteractive; } - startInfo.Arguments = NativeParameterBinderController.Arguments; - ExecutionContext context = this.Command.Context; + // We provide the user a way to select the new behavior via a new preference variable + using (ParameterBinderBase.bindingTracer.TraceScope("BIND NAMED native application line args [{0}]", this.Path)) + { + // We need to check if we're using legacy argument passing or it's a special case. + if (UseSpecialArgumentPassing(startInfo.FileName)) + { + using (ParameterBinderBase.bindingTracer.TraceScope("BIND argument [{0}]", NativeParameterBinderController.Arguments)) + { + // codeql[cs/microsoft/command-line-injection ] - This is intended PowerShell behavior as NativeParameterBinderController.Arguments is what the native parameter binder generates based on the user input when invoking the command and cannot be injected externally. + startInfo.Arguments = NativeParameterBinderController.Arguments; + } + } + else + { + // Use new API for running native application + int position = 0; + foreach (string nativeArgument in NativeParameterBinderController.ArgumentList) + { + if (nativeArgument != null) + { + using (ParameterBinderBase.bindingTracer.TraceScope("BIND cmd line arg [{0}] to position [{1}]", nativeArgument, position++)) + { + startInfo.ArgumentList.Add(nativeArgument); + } + } + } + } + } + // Start command in the current filesystem directory string rawPath = context.EngineSessionState.GetNamespaceCurrentLocation( context.ProviderNames.FileSystem).ProviderPath; - startInfo.WorkingDirectory = WildcardPattern.Unescape(rawPath); + + // Only set this if the PowerShell's current working directory still exists. + if (Directory.Exists(rawPath)) + { + startInfo.WorkingDirectory = WildcardPattern.Unescape(rawPath); + } + return startInfo; } +#nullable enable + /// + /// Gets the encoding to use for a process' output/error pipes. + /// + /// The encoding to use for the process output. + private Encoding GetOutputEncoding() + { + Encoding? applicationOutputEncoding = Context.GetVariableValue( + SpecialVariables.PSApplicationOutputEncodingVarPath) as Encoding; + + return applicationOutputEncoding ?? Console.OutputEncoding; + } +#nullable disable + + /// + /// Determine if we have a special file which will change the way native argument passing + /// is done on Windows. We use legacy behavior for cmd.exe, .bat, .cmd files. + /// + /// The file to use when checking how to pass arguments. + /// A boolean indicating what passing style should be used. + private static bool ShouldUseLegacyPassingStyle(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + return false; + } + + return s_legacyFileExtensions.Contains(IO.Path.GetExtension(filePath)) + || s_legacyCommands.Contains(IO.Path.GetFileNameWithoutExtension(filePath)); + } + private static bool IsDownstreamOutDefault(Pipe downstreamPipe) { Diagnostics.Assert(downstreamPipe != null, "Caller makes sure the passed-in parameter is not null."); @@ -1224,15 +1800,19 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect // $powershell.AddScript('ipconfig.exe') // $powershell.AddCommand('Out-Default') // $powershell.Invoke()) - // we should not count it as a redirection. - if (IsDownstreamOutDefault(this.commandRuntime.OutputPipe)) + // we should not count it as a redirection. Unless the native command has its stdout redirected + // for example: + // cmd.exe /c "echo test" > somefile.log + // in that case we want to keep output redirection even though Out-Default is the only + // downstream command. + if (IsDownstreamOutDefault(this.commandRuntime.OutputPipe) && StdOutDestination is null) { redirectOutput = false; } } // See if the error output stream has been redirected, either through an explicit 2> foo.txt or - // my merging error into output through 2>&1. + // by merging error into output through 2>&1. if (CommandRuntime.ErrorMergeTo != MshCommandRuntime.MergeDataStream.Output) { // If the error output pipe is the default outputter, for example, calling the native command from command-line host, @@ -1242,7 +1822,9 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect // $powershell.AddScript('ipconfig.exe') // $powershell.AddCommand('Out-Default') // $powershell.Invoke()) - // we should not count that as a redirection. + // we should not count that as a redirection. We do not need to worry + // about StdOutDestination here as if error is redirected then it's assumed + // to be text based and Out-File will be added to the pipeline instead. if (IsDownstreamOutDefault(this.commandRuntime.ErrorOutputPipe)) { redirectError = false; @@ -1290,6 +1872,9 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect { if (s_supportScreenScrape == null) { +#if UNIX + s_supportScreenScrape = false; +#else try { _startPosition = this.Command.Context.EngineHostInterface.UI.RawUI.CursorPosition; @@ -1301,6 +1886,7 @@ private void CalculateIORedirection(bool isWindowsApplication, out bool redirect { s_supportScreenScrape = false; } +#endif } // if screen scraping isn't supported, we enable redirection so that the output is still transcribed @@ -1336,7 +1922,7 @@ private bool IsExecutable(string path) } else { - extensionList = pathext.Split(Utils.Separators.Semicolon); + extensionList = pathext.Split(';'); } foreach (string extension in extensionList) @@ -1351,91 +1937,10 @@ private bool IsExecutable(string path) #endif } - #region Interop for FindExecutable... - - // Constant used to determine the buffer size for a path - // when looking for an executable. MAX_PATH is defined as 260 - // so this is much larger than what should be permitted - private const int MaxExecutablePath = 1024; - - // The FindExecutable API is defined in shellapi.h as - // SHSTDAPI_(HINSTANCE) FindExecutableW(LPCWSTR lpFile, LPCWSTR lpDirectory, __out_ecount(MAX_PATH) LPWSTR lpResult); - // HINSTANCE is void* so we need to use IntPtr as API return value. - - [DllImport("shell32.dll", EntryPoint = "FindExecutable")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "0")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "1")] - [SuppressMessage("Microsoft.Globalization", "CA2101:SpecifyMarshalingForPInvokeStringArguments", MessageId = "2")] - private static extern IntPtr FindExecutableW( - string fileName, string directoryPath, StringBuilder pathFound); - - [ArchitectureSensitive] - private static string FindExecutable(string filename) - { - // Preallocate a - StringBuilder objResultBuffer = new StringBuilder(MaxExecutablePath); - IntPtr resultCode = (IntPtr)0; - - try - { - resultCode = FindExecutableW(filename, string.Empty, objResultBuffer); - } - catch (System.IndexOutOfRangeException e) - { - // If we got an index-out-of-range exception here, it's because - // of a buffer overrun error so we fail fast instead of - // continuing to run in an possibly unstable environment.... - Environment.FailFast(e.Message, e); - } - - // If FindExecutable returns a result >= 32, then it succeeded - // and we return the string that was found, otherwise we - // return null. - if ((long)resultCode >= 32) - { - return objResultBuffer.ToString(); - } - - return null; - } - - #endregion - - #region Interop for SHGetFileInfo - - private const int SCS_32BIT_BINARY = 0; // A 32-bit Windows-based application - private const int SCS_DOS_BINARY = 1; // An MS-DOS - based application - private const int SCS_WOW_BINARY = 2; // A 16-bit Windows-based application - private const int SCS_PIF_BINARY = 3; // A PIF file that executes an MS-DOS - based application - private const int SCS_POSIX_BINARY = 4; // A POSIX - based application - private const int SCS_OS216_BINARY = 5; // A 16-bit OS/2-based application - private const int SCS_64BIT_BINARY = 6; // A 64-bit Windows-based application. - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - private struct SHFILEINFO - { - public IntPtr hIcon; - public int iIcon; - public uint dwAttributes; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] - public string szDisplayName; - - [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 80)] - public string szTypeName; - } - - private const uint SHGFI_EXETYPE = 0x000002000; // flag used to ask to return exe type - - [DllImport("shell32.dll", CharSet = CharSet.Unicode)] - private static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, - ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags); - - #endregion - #region Minishell Interop private bool _isMiniShell = false; + /// /// Returns true if native command being invoked is mini-shell. /// @@ -1478,7 +1983,19 @@ internal class ProcessOutputHandler private bool _isXmlCliError; private readonly string _processFileName; + private readonly AsyncByteStreamTransfer _stdOutDrainer; + public ProcessOutputHandler(Process process, BlockingCollection queue) + : this(process, queue, null, null, out _) + { + } + + public ProcessOutputHandler( + Process process, + BlockingCollection queue, + BytePipe stdOutDestination, + BytePipe stdOutSource, + out AsyncByteStreamTransfer stdOutDrainer) { Debug.Assert(process.StartInfo.RedirectStandardOutput || process.StartInfo.RedirectStandardError, "Caller should redirect at least one stream"); _refCount = 0; @@ -1487,19 +2004,17 @@ public ProcessOutputHandler(Process process, BlockingCollection public static bool AlwaysCaptureApplicationIO { get; set; } - [DllImport("Kernel32.dll")] - 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; - - /// - /// 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")] - internal static extern bool ShowWindow(IntPtr hWnd, int nCmdShow); - - /// - /// Code to allocate a console... - /// - /// True if a console was created... - [DllImport("kernel32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool AllocConsole(); - - /// - /// Called to save the foreground window before allocating a hidden console window. - /// - /// A handle to the foreground window. - [DllImport("user32.dll")] - private static extern IntPtr GetForegroundWindow(); - - /// - /// Called to restore the foreground window after allocating a hidden console window. - /// - /// A handle to the window that should be activated and brought to the foreground. - /// True if the window was brought to the foreground. - [DllImport("user32.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SetForegroundWindow(IntPtr hWnd); - /// /// If no console window is attached to this process, then allocate one, /// hide it and return true. If there's already a console window attached, then @@ -1983,90 +2476,55 @@ internal static class ConsoleVisibility /// internal static bool AllocateHiddenConsole() { +#if UNIX + return false; +#else // See if there is already a console attached. - IntPtr hwnd = ConsoleVisibility.GetConsoleWindow(); - if (hwnd != IntPtr.Zero) + IntPtr hwnd = Interop.Windows.GetConsoleWindow(); + if (hwnd != nint.Zero) { return false; } // save the foreground window since allocating a console window might remove focus from it - IntPtr savedForeground = ConsoleVisibility.GetForegroundWindow(); + IntPtr savedForeground = Interop.Windows.GetForegroundWindow(); // Since there is no console window, allocate and then hide it... // Suppress the PreFAST warning about not using Marshal.GetLastWin32Error() to // get the error code. -#pragma warning disable 56523 - ConsoleVisibility.AllocConsole(); - hwnd = ConsoleVisibility.GetConsoleWindow(); + Interop.Windows.AllocConsole(); + hwnd = Interop.Windows.GetConsoleWindow(); bool returnValue; - if (hwnd == IntPtr.Zero) + if (hwnd == nint.Zero) { returnValue = false; } else { returnValue = true; - ConsoleVisibility.ShowWindow(hwnd, ConsoleVisibility.SW_HIDE); + Interop.Windows.ShowWindow(hwnd, Interop.Windows.SW_HIDE); AlwaysCaptureApplicationIO = true; } - if (savedForeground != IntPtr.Zero && ConsoleVisibility.GetForegroundWindow() != savedForeground) + if (savedForeground != nint.Zero && Interop.Windows.GetForegroundWindow() != savedForeground) { - ConsoleVisibility.SetForegroundWindow(savedForeground); + Interop.Windows.SetForegroundWindow(savedForeground); } return returnValue; - } - - /// - /// If there is a console attached, then make it visible - /// and allow interactive console applications to be run. - /// - public static void Show() - { - IntPtr hwnd = GetConsoleWindow(); - if (hwnd != IntPtr.Zero) - { - ShowWindow(hwnd, SW_SHOW); - AlwaysCaptureApplicationIO = false; - } - else - { - throw PSTraceSource.NewInvalidOperationException(); - } - } - - /// - /// If there is a console attached, then hide it and always capture - /// output from the child process. - /// - public static void Hide() - { - IntPtr hwnd = GetConsoleWindow(); - if (hwnd != IntPtr.Zero) - { - ShowWindow(hwnd, SW_HIDE); - AlwaysCaptureApplicationIO = true; - } - else - { - throw PSTraceSource.NewInvalidOperationException(); - } +#endif } } /// /// Exception used to wrap the error coming from - /// remote instance of Msh. + /// remote instance of PowerShell. /// /// - /// This remote instance of Msh can be in a separate process, + /// This remote instance of PowerShell can be in a separate process, /// appdomain or machine. /// - [Serializable] - [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] public class RemoteException : RuntimeException { /// @@ -2142,9 +2600,10 @@ PSObject serializedRemoteInvocationInfo /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RemoteException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -2156,7 +2615,7 @@ protected RemoteException(SerializationInfo info, StreamingContext context) private readonly PSObject _serializedRemoteInvocationInfo; /// - /// Original Serialized Exception from remote msh. + /// Original Serialized Exception from remote PowerShell. /// /// This is the exception which was thrown in remote. /// @@ -2172,7 +2631,7 @@ public PSObject SerializedRemoteException /// InvocationInfo, if any, associated with the SerializedRemoteException. /// /// - /// This is the serialized InvocationInfo from the remote msh. + /// This is the serialized InvocationInfo from the remote PowerShell. /// public PSObject SerializedRemoteInvocationInfo { diff --git a/src/System.Management.Automation/engine/OrderedHashtable.cs b/src/System.Management.Automation/engine/OrderedHashtable.cs new file mode 100644 index 00000000000..fd41d0b3ffd --- /dev/null +++ b/src/System.Management.Automation/engine/OrderedHashtable.cs @@ -0,0 +1,236 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections; +using System.Collections.Specialized; +using System.Runtime.Serialization; + +#nullable enable + +namespace System.Management.Automation +{ + /// + /// OrderedHashtable is a hashtable that preserves the order of the keys. + /// + public sealed class OrderedHashtable : Hashtable, IEnumerable + { + private readonly OrderedDictionary _orderedDictionary; + + /// + /// Initializes a new instance of the class. + /// + public OrderedHashtable() + { + _orderedDictionary = new OrderedDictionary(); + } + + /// + /// Initializes a new instance of the class. + /// + /// The capacity. + public OrderedHashtable(int capacity) : base(capacity) + { + _orderedDictionary = new OrderedDictionary(capacity); + } + + /// + /// Initializes a new instance of the class. + /// + /// The dictionary to use for initialization. + public OrderedHashtable(IDictionary dictionary) + { + _orderedDictionary = new OrderedDictionary(dictionary.Count); + foreach (DictionaryEntry entry in dictionary) + { + _orderedDictionary.Add(entry.Key, entry.Value); + } + } + + /// + /// Get the number of items in the hashtable. + /// + public override int Count + { + get + { + return _orderedDictionary.Count; + } + } + + /// + /// Get if the hashtable is a fixed size. + /// + public override bool IsFixedSize + { + get + { + return false; + } + } + + /// + /// Get if the hashtable is read-only. + /// + public override bool IsReadOnly + { + get + { + return false; + } + } + + /// + /// Get if the hashtable is synchronized. + /// + public override bool IsSynchronized + { + get + { + return false; + } + } + + /// + /// Gets the keys in the hashtable. + /// + public override ICollection Keys + { + get + { + return _orderedDictionary.Keys; + } + } + + /// + /// Gets the values in the hashtable. + /// + public override ICollection Values + { + get + { + return _orderedDictionary.Values; + } + } + + /// + /// Gets or sets the value associated with the specified key. + /// + /// The key. + /// The value associated with the key. + public override object? this[object key] + { + get + { + return _orderedDictionary[key]; + } + + set + { + _orderedDictionary[key] = value; + } + } + + /// + /// Adds the specified key and value to the hashtable. + /// + /// The key. + /// The value. + public override void Add(object key, object? value) + { + _orderedDictionary.Add(key, value); + } + + /// + /// Removes all keys and values from the hashtable. + /// + public override void Clear() + { + _orderedDictionary.Clear(); + } + + /// + /// Get a shallow clone of the hashtable. + /// + /// A shallow clone of the hashtable. + public override object Clone() + { + return new OrderedHashtable(_orderedDictionary); + } + + /// + /// Determines whether the hashtable contains a specific key. + /// + /// The key to locate in the hashtable. + /// true if the hashtable contains an element with the specified key; otherwise, false. + public override bool Contains(object key) + { + return _orderedDictionary.Contains(key); + } + + /// + /// Determines whether the hashtable contains a specific key. + /// + /// The key to locate in the hashtable. + /// true if the hashtable contains an element with the specified key; otherwise, false. + public override bool ContainsKey(object key) + { + return _orderedDictionary.Contains(key); + } + + /// + /// Determines whether the hashtable contains a specific value. + /// + /// The value to locate in the hashtable. + /// true if the hashtable contains an element with the specified value; otherwise, false. + public override bool ContainsValue(object? value) + { + foreach (DictionaryEntry entry in _orderedDictionary) + { + if (Equals(entry.Value, value)) + { + return true; + } + } + + return false; + } + + /// + /// Copies the elements of the hashtable to an array of type object, starting at the specified array index. + /// + /// The one-dimensional array that is the destination of the elements copied from the hashtable. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public override void CopyTo(Array array, int arrayIndex) + { + _orderedDictionary.CopyTo(array, arrayIndex); + } + + /// + /// Get the enumerator. + /// + /// The enumerator. + public override IDictionaryEnumerator GetEnumerator() + { + return _orderedDictionary.GetEnumerator(); + } + + /// + /// Get the enumerator. + /// + /// The enumerator. + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + + /// + /// Removes the specified key from the hashtable. + /// + /// The key to remove. + public override void Remove(object key) + { + _orderedDictionary.Remove(key); + } + } +} diff --git a/src/System.Management.Automation/engine/PSClassInfo.cs b/src/System.Management.Automation/engine/PSClassInfo.cs index fd0ca8d8936..10b2cf1101d 100644 --- a/src/System.Management.Automation/engine/PSClassInfo.cs +++ b/src/System.Management.Automation/engine/PSClassInfo.cs @@ -61,8 +61,7 @@ public sealed class PSClassMemberInfo /// internal PSClassMemberInfo(string name, string memberType, string defaultValue) { - if (string.IsNullOrEmpty(name)) - throw new ArgumentNullException(nameof(name)); + ArgumentException.ThrowIfNullOrEmpty(name); this.Name = name; this.TypeName = memberType; diff --git a/src/System.Management.Automation/engine/PSConfiguration.cs b/src/System.Management.Automation/engine/PSConfiguration.cs index 16273979a69..419a4cae95f 100644 --- a/src/System.Management.Automation/engine/PSConfiguration.cs +++ b/src/System.Management.Automation/engine/PSConfiguration.cs @@ -89,7 +89,10 @@ private PowerShellConfig() // Note: This directory may or may not exist depending upon the execution scenario. // Writes will attempt to create the directory if it does not already exist. perUserConfigDirectory = Platform.ConfigDirectory; - perUserConfigFile = Path.Combine(perUserConfigDirectory, ConfigFileName); + if (!string.IsNullOrEmpty(perUserConfigDirectory)) + { + perUserConfigFile = Path.Combine(perUserConfigDirectory, ConfigFileName); + } emptyConfig = new JObject(); configRoots = new JObject[2]; @@ -181,6 +184,7 @@ private static string GetExecutionPolicySettingKey(string shellId) : string.Concat(shellId, ":", "ExecutionPolicy"); } + /// /// Get the names of experimental features enabled in the config file. /// internal string[] GetExperimentalFeatures() @@ -386,6 +390,11 @@ internal PSKeyword GetLogKeywords() private T ReadValueFromFile(ConfigScope scope, string key, T defaultValue = default) { string fileName = GetConfigFilePath(scope); + if (string.IsNullOrEmpty(fileName)) + { + return defaultValue; + } + JObject configData = configRoots[(int)scope]; if (configData == null) diff --git a/src/System.Management.Automation/engine/PSVersionInfo.cs b/src/System.Management.Automation/engine/PSVersionInfo.cs index 5830cdc7f02..eef9819a568 100644 --- a/src/System.Management.Automation/engine/PSVersionInfo.cs +++ b/src/System.Management.Automation/engine/PSVersionInfo.cs @@ -3,7 +3,6 @@ using System.Collections; using System.Globalization; -using System.Reflection; using System.Text; using System.Text.RegularExpressions; @@ -27,7 +26,7 @@ namespace System.Management.Automation /// The above statement retrieves the PowerShell edition. /// /// - public class PSVersionInfo + public static partial class PSVersionInfo { internal const string PSVersionTableName = "PSVersionTable"; internal const string PSRemotingProtocolVersionName = "PSRemotingProtocolVersion"; @@ -42,6 +41,18 @@ public class PSVersionInfo private static readonly PSVersionHashTable s_psVersionTable; + /* + The following constants are generated by the source generator 'PSVersionInfoGenerator': + + internal const string ProductVersion; + internal const string GitCommitId; + + private const int Version_Major + private const int Version_Minor; + private const int Version_Patch; + private const string Version_Label; + */ + /// /// A constant to track current PowerShell Version. /// @@ -53,19 +64,16 @@ public class PSVersionInfo /// For each later release of PowerShell, this constant needs to /// be updated to reflect the right version. /// - private static readonly Version s_psV1Version = new Version(1, 0); - private static readonly Version s_psV2Version = new Version(2, 0); - private static readonly Version s_psV3Version = new Version(3, 0); - private static readonly Version s_psV4Version = new Version(4, 0); - private static readonly Version s_psV5Version = new Version(5, 0); - private static readonly Version s_psV51Version = new Version(5, 1, NTVerpVars.PRODUCTBUILD, NTVerpVars.PRODUCTBUILD_QFE); - private static readonly SemanticVersion s_psV6Version = new SemanticVersion(6, 0, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV61Version = new SemanticVersion(6, 1, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV62Version = new SemanticVersion(6, 2, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV7Version = new SemanticVersion(7, 0, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psV71Version = new SemanticVersion(7, 1, 0, preReleaseLabel: null, buildLabel: null); - private static readonly SemanticVersion s_psSemVersion; + private static readonly Version s_psV1Version = new(1, 0); + private static readonly Version s_psV2Version = new(2, 0); + private static readonly Version s_psV3Version = new(3, 0); + private static readonly Version s_psV4Version = new(4, 0); + private static readonly Version s_psV5Version = new(5, 0); + private static readonly Version s_psV51Version = new(5, 1); + private static readonly Version s_psV6Version = new(6, 0); + private static readonly Version s_psV7Version = new(7, 0); private static readonly Version s_psVersion; + private static readonly SemanticVersion s_psSemVersion; /// /// A constant to track current PowerShell Edition. @@ -77,43 +85,18 @@ static PSVersionInfo() { s_psVersionTable = new PSVersionHashTable(StringComparer.OrdinalIgnoreCase); - Assembly currentAssembly = typeof(PSVersionInfo).Assembly; - string productVersion = currentAssembly.GetCustomAttribute().InformationalVersion; - - // Get 'GitCommitId' and 'PSVersion' from the 'productVersion' assembly attribute. - // - // The strings can be one of the following format examples: - // when powershell is built from a commit: - // productVersion = '6.0.0-beta.7 Commits: 29 SHA: 52c6b...' convert to GitCommitId = 'v6.0.0-beta.7-29-g52c6b...' - // PSVersion = '6.0.0-beta.7' - // when powershell is built from a release tag: - // productVersion = '6.0.0-beta.7 SHA: f1ec9...' convert to GitCommitId = 'v6.0.0-beta.7' - // PSVersion = '6.0.0-beta.7' - // when powershell is built from a release tag for RTM: - // productVersion = '6.0.0 SHA: f1ec9...' convert to GitCommitId = 'v6.0.0' - // PSVersion = '6.0.0' - string rawGitCommitId; - string mainVersion = productVersion.Substring(0, productVersion.IndexOf(' ')); - - if (productVersion.Contains(" Commits: ")) - { - rawGitCommitId = productVersion.Replace(" Commits: ", "-").Replace(" SHA: ", "-g"); - } - else - { - rawGitCommitId = mainVersion; - } - - s_psSemVersion = new SemanticVersion(mainVersion); + s_psSemVersion = Version_Label == string.Empty + ? new SemanticVersion(Version_Major, Version_Minor, Version_Patch) + : new SemanticVersion(Version_Major, Version_Minor, Version_Patch, Version_Label, buildLabel: null); s_psVersion = (Version)s_psSemVersion; - s_psVersionTable[PSVersionInfo.PSVersionName] = s_psSemVersion; - s_psVersionTable[PSVersionInfo.PSEditionName] = PSEditionValue; - s_psVersionTable[PSGitCommitIdName] = rawGitCommitId; - s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV61Version, s_psV62Version, s_psV7Version, s_psV71Version, s_psVersion }; - s_psVersionTable[PSVersionInfo.SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); - s_psVersionTable[PSVersionInfo.PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; - s_psVersionTable[PSVersionInfo.WSManStackVersionName] = GetWSManStackVersion(); + s_psVersionTable[PSVersionName] = s_psSemVersion; + s_psVersionTable[PSEditionName] = PSEditionValue; + s_psVersionTable[PSGitCommitIdName] = GitCommitId; + s_psVersionTable[PSCompatibleVersionsName] = new Version[] { s_psV1Version, s_psV2Version, s_psV3Version, s_psV4Version, s_psV5Version, s_psV51Version, s_psV6Version, s_psV7Version }; + s_psVersionTable[SerializationVersionName] = new Version(InternalSerializer.DefaultVersion); + s_psVersionTable[PSRemotingProtocolVersionName] = RemotingConstants.ProtocolVersion; + s_psVersionTable[WSManStackVersionName] = GetWSManStackVersion(); s_psVersionTable[PSPlatformName] = Environment.OSVersion.Platform.ToString(); s_psVersionTable[PSOSName] = Runtime.InteropServices.RuntimeInformation.OSDescription; } @@ -182,22 +165,6 @@ public static Version PSVersion } } - internal static string GitCommitId - { - get - { - return (string)s_psVersionTable[PSGitCommitIdName]; - } - } - - internal static Version[] PSCompatibleVersions - { - get - { - return (Version[])s_psVersionTable[PSCompatibleVersionsName]; - } - } - /// /// Gets the edition of PowerShell. /// @@ -205,7 +172,7 @@ public static string PSEdition { get { - return (string)s_psVersionTable[PSVersionInfo.PSEditionName]; + return PSEditionValue; } } @@ -217,21 +184,6 @@ internal static Version SerializationVersion } } - /// - /// - /// - /// For 2.0 PowerShell, we still use "1" as the registry version key. - /// For >=3.0 PowerShell, we still use "1" as the registry version key for - /// Snapin and Custom shell lookup/discovery. - /// - internal static string RegistryVersion1Key - { - get - { - return "1"; - } - } - /// /// /// @@ -267,76 +219,32 @@ internal static string GetRegistryVersionKeyForSnapinDiscovery(string majorVersi return null; } - internal static string FeatureVersionString - { - get - { - return string.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}.{1}", PSVersionInfo.PSVersion.Major, PSVersionInfo.PSVersion.Minor); - } - } - internal static bool IsValidPSVersion(Version version) { - if (version.Major == s_psSemVersion.Major) - { - return version.Minor == s_psSemVersion.Minor; - } - - if (version.Major == s_psV6Version.Major) + if (version is null) { - return version.Minor == s_psV6Version.Minor; - } - - if (version.Major == s_psV5Version.Major) - { - return (version.Minor == s_psV5Version.Minor || version.Minor == s_psV51Version.Minor); + return false; } - if (version.Major == s_psV4Version.Major) - { - return (version.Minor == s_psV4Version.Minor); - } - else if (version.Major == s_psV3Version.Major) - { - return version.Minor == s_psV3Version.Minor; - } - else if (version.Major == s_psV2Version.Major) - { - return version.Minor == s_psV2Version.Minor; - } - else if (version.Major == s_psV1Version.Major) + int minor = version.Minor; + switch (version.Major) { - return version.Minor == s_psV1Version.Minor; + case 1: + case 2: + case 3: + case 4: + return minor == 0; + case 5: + return minor == 0 || minor == 1; + case 6: + return minor >= 0 && minor <= 2; + case 7: + return minor >= 0 && minor <= s_psVersion.Minor; } return false; } - internal static Version PSV4Version - { - get { return s_psV4Version; } - } - - internal static Version PSV5Version - { - get { return s_psV5Version; } - } - - internal static Version PSV51Version - { - get { return s_psV51Version; } - } - - internal static SemanticVersion PSV6Version - { - get { return s_psV6Version; } - } - - internal static SemanticVersion PSV7Version - { - get { return s_psV7Version; } - } - internal static SemanticVersion PSCurrentVersion { get { return s_psSemVersion; } @@ -374,7 +282,7 @@ public override ICollection Keys } } - private class PSVersionTableComparer : IComparer + private sealed class PSVersionTableComparer : IComparer { public int Compare(object x, object y) { @@ -427,8 +335,9 @@ IEnumerator IEnumerable.GetEnumerator() public sealed class SemanticVersion : IComparable, IComparable, IEquatable { private const string VersionSansRegEx = @"^(?\d+)(\.(?\d+))?(\.(?\d+))?$"; - private const string LabelRegEx = @"^((?[0-9A-Za-z][0-9A-Za-z\-\.]*))?(\+(?[0-9A-Za-z][0-9A-Za-z\-\.]*))?$"; - private const string LabelUnitRegEx = @"^[0-9A-Za-z][0-9A-Za-z\-\.]*$"; + private const string LabelRegEx = @"^(?(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(?:\+(?[0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$"; + private const string LabelUnitRegEx = @"^((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*)$"; + private const string BuildUnitRegEx = @"^([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*)$"; private const string PreLabelPropertyName = "PSSemVerPreReleaseLabel"; private const string BuildLabelPropertyName = "PSSemVerBuildLabel"; private const string TypeNameForVersionWithLabel = "System.Version#IncludeLabel"; @@ -462,21 +371,27 @@ public SemanticVersion(string version) /// The build metadata for the version. /// /// If don't match 'LabelUnitRegEx'. - /// If don't match 'LabelUnitRegEx'. + /// If don't match 'BuildUnitRegEx'. /// public SemanticVersion(int major, int minor, int patch, string preReleaseLabel, string buildLabel) : this(major, minor, patch) { if (!string.IsNullOrEmpty(preReleaseLabel)) { - if (!Regex.IsMatch(preReleaseLabel, LabelUnitRegEx)) throw new FormatException(nameof(preReleaseLabel)); + if (!Regex.IsMatch(preReleaseLabel, LabelUnitRegEx)) + { + throw new FormatException(nameof(preReleaseLabel)); + } PreReleaseLabel = preReleaseLabel; } if (!string.IsNullOrEmpty(buildLabel)) { - if (!Regex.IsMatch(buildLabel, LabelUnitRegEx)) throw new FormatException(nameof(buildLabel)); + if (!Regex.IsMatch(buildLabel, BuildUnitRegEx)) + { + throw new FormatException(nameof(buildLabel)); + } BuildLabel = buildLabel; } @@ -496,13 +411,16 @@ public SemanticVersion(int major, int minor, int patch, string preReleaseLabel, public SemanticVersion(int major, int minor, int patch, string label) : this(major, minor, patch) { - // We presume the SymVer : + // We presume the SemVer : // 1) major.minor.patch-label // 2) 'label' starts with letter or digit. if (!string.IsNullOrEmpty(label)) { var match = Regex.Match(label, LabelRegEx); - if (!match.Success) throw new FormatException(nameof(label)); + if (!match.Success) + { + throw new FormatException(nameof(label)); + } PreReleaseLabel = match.Groups["preLabel"].Value; BuildLabel = match.Groups["buildLabel"].Value; @@ -520,9 +438,20 @@ public SemanticVersion(int major, int minor, int patch, string label) /// public SemanticVersion(int major, int minor, int patch) { - if (major < 0) throw PSTraceSource.NewArgumentException(nameof(major)); - if (minor < 0) throw PSTraceSource.NewArgumentException(nameof(minor)); - if (patch < 0) throw PSTraceSource.NewArgumentException(nameof(patch)); + if (major < 0) + { + throw PSTraceSource.NewArgumentException(nameof(major)); + } + + if (minor < 0) + { + throw PSTraceSource.NewArgumentException(nameof(minor)); + } + + if (patch < 0) + { + throw PSTraceSource.NewArgumentException(nameof(patch)); + } Major = major; Minor = minor; @@ -564,8 +493,15 @@ public SemanticVersion(int major) : this(major, 0, 0) { } /// public SemanticVersion(Version version) { - if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version)); - if (version.Revision > 0) throw PSTraceSource.NewArgumentException(nameof(version)); + if (version == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(version)); + } + + if (version.Revision > 0) + { + throw PSTraceSource.NewArgumentException(nameof(version)); + } Major = version.Major; Minor = version.Minor; @@ -633,12 +569,12 @@ public static implicit operator Version(SemanticVersion semver) public int Patch { get; } /// - /// PreReleaseLabel position in the SymVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'. + /// PreReleaseLabel position in the SemVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'. /// public string PreReleaseLabel { get; } /// - /// BuildLabel position in the SymVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'. + /// BuildLabel position in the SemVer string 'major.minor.patch-PreReleaseLabel+BuildLabel'. /// public string BuildLabel { get; } @@ -652,8 +588,15 @@ public static implicit operator Version(SemanticVersion semver) /// public static SemanticVersion Parse(string version) { - if (version == null) throw PSTraceSource.NewArgumentNullException(nameof(version)); - if (version == string.Empty) throw new FormatException(nameof(version)); + if (version == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(version)); + } + + if (version == string.Empty) + { + throw new FormatException(nameof(version)); + } var r = new VersionResult(); r.Init(true); @@ -701,7 +644,7 @@ private static bool TryParseVersion(string version, ref VersionResult result) string preLabel = null; string buildLabel = null; - // We parse the SymVer 'version' string 'major.minor.patch-PreReleaseLabel+BuildLabel'. + // We parse the SemVer 'version' string 'major.minor.patch-PreReleaseLabel+BuildLabel'. var dashIndex = version.IndexOf('-'); var plusIndex = version.IndexOf('+'); @@ -726,7 +669,7 @@ private static bool TryParseVersion(string version, ref VersionResult result) } else { - if (dashIndex == -1) + if (plusIndex == -1) { // Here dashIndex == plusIndex == -1 // No preLabel - preLabel == null; @@ -734,6 +677,13 @@ private static bool TryParseVersion(string version, ref VersionResult result) // Format is 'major.minor.patch' versionSansLabel = version; } + else if (dashIndex == -1) + { + // No PreReleaseLabel: preLabel == null + // Format is 'major.minor.patch+BuildLabel' + buildLabel = version.Substring(plusIndex + 1); + versionSansLabel = version.Substring(0, plusIndex); + } else { // Format is 'major.minor.patch-PreReleaseLabel+BuildLabel' @@ -780,7 +730,7 @@ private static bool TryParseVersion(string version, ref VersionResult result) } if (preLabel != null && !Regex.IsMatch(preLabel, LabelUnitRegEx) || - (buildLabel != null && !Regex.IsMatch(buildLabel, LabelUnitRegEx))) + (buildLabel != null && !Regex.IsMatch(buildLabel, BuildUnitRegEx))) { result.SetFailure(ParseFailureKind.FormatException); return false; @@ -799,7 +749,7 @@ public override string ToString() { StringBuilder result = new StringBuilder(); - result.Append(Major).Append(Utils.Separators.Dot).Append(Minor).Append(Utils.Separators.Dot).Append(Patch); + result.Append(Major).Append('.').Append(Minor).Append('.').Append(Patch); if (!string.IsNullOrEmpty(PreReleaseLabel)) { @@ -845,7 +795,7 @@ public int CompareTo(object version) return 1; } - if (!(version is SemanticVersion v)) + if (version is not SemanticVersion v) { throw PSTraceSource.NewArgumentException(nameof(version)); } @@ -855,7 +805,7 @@ public int CompareTo(object version) /// /// Implement . - /// Meets SymVer 2.0 p.11 https://semver.org/ + /// Meets SemVer 2.0 p.11 https://semver.org/ /// public int CompareTo(SemanticVersion value) { @@ -871,7 +821,7 @@ public int CompareTo(SemanticVersion value) if (Patch != value.Patch) return Patch > value.Patch ? 1 : -1; - // SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata). + // SemVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata). return ComparePreLabel(this.PreReleaseLabel, value.PreReleaseLabel); } @@ -888,7 +838,7 @@ public override bool Equals(object obj) /// public bool Equals(SemanticVersion other) { - // SymVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata). + // SemVer 2.0 standard requires to ignore 'BuildLabel' (Build metadata). return other != null && (Major == other.Major) && (Minor == other.Minor) && (Patch == other.Patch) && string.Equals(PreReleaseLabel, other.PreReleaseLabel, StringComparison.Ordinal); @@ -957,7 +907,7 @@ public override int GetHashCode() private static int ComparePreLabel(string preLabel1, string preLabel2) { - // Symver 2.0 standard p.9 + // SemVer 2.0 standard p.9 // Pre-release versions have a lower precedence than the associated normal version. // Comparing each dot separated identifier from left to right // until a difference is found as follows: @@ -966,9 +916,15 @@ private static int ComparePreLabel(string preLabel1, string preLabel2) // Numeric identifiers always have lower precedence than non-numeric identifiers. // A larger set of pre-release fields has a higher precedence than a smaller set, // if all of the preceding identifiers are equal. - if (string.IsNullOrEmpty(preLabel1)) { return string.IsNullOrEmpty(preLabel2) ? 0 : 1; } + if (string.IsNullOrEmpty(preLabel1)) + { + return string.IsNullOrEmpty(preLabel2) ? 0 : 1; + } - if (string.IsNullOrEmpty(preLabel2)) { return -1; } + if (string.IsNullOrEmpty(preLabel2)) + { + return -1; + } var units1 = preLabel1.Split('.'); var units2 = preLabel2.Split('.'); @@ -985,16 +941,28 @@ private static int ComparePreLabel(string preLabel1, string preLabel2) if (isNumber1 && isNumber2) { - if (number1 != number2) { return number1 < number2 ? -1 : 1; } + if (number1 != number2) + { + return number1 < number2 ? -1 : 1; + } } else { - if (isNumber1) { return -1; } + if (isNumber1) + { + return -1; + } - if (isNumber2) { return 1; } + if (isNumber2) + { + return 1; + } int result = string.CompareOrdinal(ac, bc); - if (result != 0) { return result; } + if (result != 0) + { + return result; + } } } diff --git a/src/System.Management.Automation/engine/ParameterBinderBase.cs b/src/System.Management.Automation/engine/ParameterBinderBase.cs index ee7028c3865..21868b1a28d 100644 --- a/src/System.Management.Automation/engine/ParameterBinderBase.cs +++ b/src/System.Management.Automation/engine/ParameterBinderBase.cs @@ -559,15 +559,13 @@ internal virtual bool BindParameter( parameterMetadata.ObsoleteAttribute.Message); var mshCommandRuntime = this.Command.commandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - // Write out warning only if we are in the context of MshCommandRuntime. - // This is because - // 1. The overload method WriteWarning(WarningRecord) is only available in MshCommandRuntime; - // 2. We write out warnings for obsolete commands and obsolete cmdlet parameters only when in - // the context of MshCommandRuntime. So we do it here to keep consistency. - mshCommandRuntime.WriteWarning(new WarningRecord(FQIDParameterObsolete, obsoleteWarning)); - } + + // Write out warning only if we are in the context of MshCommandRuntime. + // This is because + // 1. The overload method WriteWarning(WarningRecord) is only available in MshCommandRuntime; + // 2. We write out warnings for obsolete commands and obsolete cmdlet parameters only when in + // the context of MshCommandRuntime. So we do it here to keep consistency. + mshCommandRuntime?.WriteWarning(new WarningRecord(FQIDParameterObsolete, obsoleteWarning)); } // Finally bind the argument to the parameter @@ -772,7 +770,10 @@ private void ValidateNullOrEmptyArgument( // Note - we explicitly don't pass the context here because we don't want // the overhead of the calls that check for stopping. - if (ParserOps.MoveNext(null, null, ienum)) { isEmpty = false; } + if (ParserOps.MoveNext(null, null, ienum)) + { + isEmpty = false; + } // If the element of the collection is of value type, then no need to check for null // because a value-type value cannot be null. @@ -999,10 +1000,7 @@ private object CoerceTypeAsNeeded( // Construct the collection type information if it wasn't passed in. - if (collectionTypeInfo == null) - { - collectionTypeInfo = new ParameterCollectionTypeInformation(toType); - } + collectionTypeInfo ??= new ParameterCollectionTypeInformation(toType); object originalValue = currentValue; object result = currentValue; @@ -1246,8 +1244,9 @@ private object CoerceTypeAsNeeded( // However, we don't allow Hashtable-to-Object conversion (PSObject and IDictionary) because // those can lead to property setters that probably aren't expected. This is enforced by // setting 'Context.LanguageModeTransitionInParameterBinding' to true before the conversion. + var currentLanguageMode = Context.LanguageMode; bool changeLanguageModeForTrustedCommand = - Context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + currentLanguageMode == PSLanguageMode.ConstrainedLanguage && this.Command.CommandInfo.DefiningLanguageMode == PSLanguageMode.FullLanguage; bool oldLangModeTransitionStatus = Context.LanguageModeTransitionInParameterBinding; @@ -1265,7 +1264,7 @@ private object CoerceTypeAsNeeded( { if (changeLanguageModeForTrustedCommand) { - Context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + Context.LanguageMode = currentLanguageMode; Context.LanguageModeTransitionInParameterBinding = oldLangModeTransitionStatus; } } @@ -1452,7 +1451,7 @@ private object HandleNullParameterForSpecialTypes( /// could not be created. /// [SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode")] - [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Consider Simplyfing it")] + [SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "Consider Simplifying it")] private object EncodeCollection( CommandParameterInternal argument, string parameterName, diff --git a/src/System.Management.Automation/engine/ParameterBinderController.cs b/src/System.Management.Automation/engine/ParameterBinderController.cs index e6a7153a879..f9781a99435 100644 --- a/src/System.Management.Automation/engine/ParameterBinderController.cs +++ b/src/System.Management.Automation/engine/ParameterBinderController.cs @@ -616,7 +616,7 @@ protected Collection BindNamedParameters(uint paramete { // This named parameter from splatting is also explicitly specified by the user, // which was successfully bound, so we ignore the one from splatting because it - // is superceded by the explicit one. For example: + // is superseded by the explicit one. For example: // $splat = @{ Path = $path1 } // dir @splat -Path $path2 continue; @@ -1029,7 +1029,7 @@ protected void ThrowElaboratedBindingException(ParameterBindingException pbex) StringBuilder defaultParamsGetBound = new StringBuilder(); foreach (string paramName in BoundDefaultParameters) { - defaultParamsGetBound.AppendFormat(CultureInfo.InvariantCulture, " -{0}", paramName); + defaultParamsGetBound.Append(CultureInfo.InvariantCulture, $" -{paramName}"); } string resourceString = ParameterBinderStrings.DefaultBindingErrorElaborationSingle; diff --git a/src/System.Management.Automation/engine/ParameterSetInfo.cs b/src/System.Management.Automation/engine/ParameterSetInfo.cs index 74745fca6da..5d81b8553cf 100644 --- a/src/System.Management.Automation/engine/ParameterSetInfo.cs +++ b/src/System.Management.Automation/engine/ParameterSetInfo.cs @@ -246,15 +246,19 @@ private static void AppendFormatCommandParameterInfo(CommandParameterInfo parame if (parameter.IsMandatory) { - result.AppendFormat(CultureInfo.InvariantCulture, - parameter.Position != int.MinValue ? "[-{0}] <{1}>" : "-{0} <{1}>", - parameter.Name, parameterTypeString); + result.AppendFormat( + CultureInfo.InvariantCulture, + parameter.Position != int.MinValue ? "[-{0}] <{1}>" : "-{0} <{1}>", + parameter.Name, + parameterTypeString); } else { - result.AppendFormat(CultureInfo.InvariantCulture, - parameter.Position != int.MinValue ? "[[-{0}] <{1}>]" : "[-{0} <{1}>]", - parameter.Name, parameterTypeString); + result.AppendFormat( + CultureInfo.InvariantCulture, + parameter.Position != int.MinValue ? "[[-{0}] <{1}>]" : "[-{0} <{1}>]", + parameter.Name, + parameterTypeString); } } } @@ -284,7 +288,7 @@ internal static string GetParameterTypeString(Type type, IEnumerable parameterTypeString = typeName.PSTypeName; // Drop the namespace from the typename, if any. - var lastDotIndex = parameterTypeString.LastIndexOfAny(Utils.Separators.Dot); + var lastDotIndex = parameterTypeString.LastIndexOf('.'); if (lastDotIndex != -1 && lastDotIndex + 1 < parameterTypeString.Length) { parameterTypeString = parameterTypeString.Substring(lastDotIndex + 1); diff --git a/src/System.Management.Automation/engine/PathInterfaces.cs b/src/System.Management.Automation/engine/PathInterfaces.cs index 9a604829295..1cc9c6c173c 100644 --- a/src/System.Management.Automation/engine/PathInterfaces.cs +++ b/src/System.Management.Automation/engine/PathInterfaces.cs @@ -379,7 +379,7 @@ public PathInfoStack SetDefaultLocationStack(string stackName) /// characters which will get resolved. /// /// - /// An array of Msh paths that resolved from the given path. + /// An array of PowerShell paths that resolved from the given path. /// /// /// If is null. @@ -728,7 +728,7 @@ public string GetUnresolvedProviderPathFromPSPath(string path) /// The information for the provider for which the returned path should be used. /// /// - /// The drive of the Msh path that was used to convert the path. Note, this may be null + /// The drive of the PowerShell path that was used to convert the path. Note, this may be null /// if the was a provider-qualified path. /// /// @@ -834,7 +834,7 @@ internal string GetUnresolvedProviderPathFromPSPath( } /// - /// Determines if the give path is an Msh provider-qualified path. + /// Determines if the give path is a PowerShell provider-qualified path. /// /// /// The path to check. @@ -863,11 +863,11 @@ public bool IsProviderQualified(string path) /// The path to check. /// /// - /// If the path is an Msh absolute path then the returned value is + /// If the path is an absolute path then the returned value is /// the name of the drive that the path is absolute to. /// /// - /// True if the specified path is an Msh absolute drive-qualified path. + /// True if the specified path is an absolute drive-qualified path. /// False otherwise. /// /// @@ -1232,7 +1232,7 @@ internal string ParseChildName( /// as a relative path to the basePath that was passed. /// /// - /// An MSH path to an item. The item should exist + /// A PowerShell path to an item. The item should exist /// or the provider should write out an error. /// /// @@ -1312,7 +1312,7 @@ internal string NormalizeRelativePath( #region IsValid /// - /// Determines if the MSH path is a syntactically and semantically valid path for the provider. + /// Determines if the path is a syntactically and semantically valid path for the provider. /// /// /// The path to validate. diff --git a/src/System.Management.Automation/engine/Pipe.cs b/src/System.Management.Automation/engine/Pipe.cs index 8ee000a4faf..d43a0f96a5d 100644 --- a/src/System.Management.Automation/engine/Pipe.cs +++ b/src/System.Management.Automation/engine/Pipe.cs @@ -109,6 +109,13 @@ public override string ToString() /// internal int OutBufferCount { get; set; } = 0; + /// + /// Gets whether the out variable list should be ignored. + /// This is used for scenarios like the `clean` block, where writing to output stream is intentionally + /// disabled and thus out variables should also be ignored. + /// + internal bool IgnoreOutVariableList { get; set; } + /// /// If true, then all input added to this pipe will simply be discarded... /// @@ -226,34 +233,22 @@ internal void AddVariableList(VariableStreamKind kind, IList list) switch (kind) { case VariableStreamKind.Error: - if (_errorVariableList == null) - { - _errorVariableList = new List(); - } + _errorVariableList ??= new List(); _errorVariableList.Add(list); break; case VariableStreamKind.Warning: - if (_warningVariableList == null) - { - _warningVariableList = new List(); - } + _warningVariableList ??= new List(); _warningVariableList.Add(list); break; case VariableStreamKind.Output: - if (_outVariableList == null) - { - _outVariableList = new List(); - } + _outVariableList ??= new List(); _outVariableList.Add(list); break; case VariableStreamKind.Information: - if (_informationVariableList == null) - { - _informationVariableList = new List(); - } + _informationVariableList ??= new List(); _informationVariableList.Add(list); break; @@ -552,15 +547,28 @@ internal object Retrieve() else if (_enumeratorToProcess != null) { if (_enumeratorToProcessIsEmpty) - return AutomationNull.Value; - - if (!ParserOps.MoveNext(_context, null, _enumeratorToProcess)) { - _enumeratorToProcessIsEmpty = true; return AutomationNull.Value; } - return ParserOps.Current(null, _enumeratorToProcess); + while (true) + { + if (!ParserOps.MoveNext(_context, errorPosition: null, _enumeratorToProcess)) + { + _enumeratorToProcessIsEmpty = true; + return AutomationNull.Value; + } + + object retValue = ParserOps.Current(errorPosition: null, _enumeratorToProcess); + if (retValue == AutomationNull.Value) + { + // 'AutomationNull.Value' from the enumerator won't be sent to the pipeline. + // We try to get the next value in this case. + continue; + } + + return retValue; + } } else if (ExternalReader != null) { @@ -595,11 +603,7 @@ internal object Retrieve() /// /// Removes all the objects from the Pipe. /// - internal void Clear() - { - if (ObjectQueue != null) - ObjectQueue.Clear(); - } + internal void Clear() => ObjectQueue?.Clear(); /// /// Returns the currently queued items in the pipe. Note that this will diff --git a/src/System.Management.Automation/engine/ProcessCodeMethods.cs b/src/System.Management.Automation/engine/ProcessCodeMethods.cs index 604ac3787ad..68d47fbec71 100644 --- a/src/System.Management.Automation/engine/ProcessCodeMethods.cs +++ b/src/System.Management.Automation/engine/ProcessCodeMethods.cs @@ -61,32 +61,12 @@ internal static int GetParentPid(Process process) internal static int GetParentPid(Process process) { Diagnostics.Assert(process != null, "Ensure process is not null before calling"); - PROCESS_BASIC_INFORMATION pbi; + Interop.Windows.PROCESS_BASIC_INFORMATION pbi; int size; - var res = NtQueryInformationProcess(process.Handle, 0, out pbi, Marshal.SizeOf(), out size); + var res = Interop.Windows.NtQueryInformationProcess(process.Handle, 0, out pbi, Marshal.SizeOf(), out size); return res != 0 ? InvalidProcessId : pbi.InheritedFromUniqueProcessId.ToInt32(); } - - [StructLayout(LayoutKind.Sequential)] - private struct PROCESS_BASIC_INFORMATION - { - public IntPtr ExitStatus; - public IntPtr PebBaseAddress; - public IntPtr AffinityMask; - public IntPtr BasePriority; - public IntPtr UniqueProcessId; - public IntPtr InheritedFromUniqueProcessId; - } - - [DllImport("ntdll.dll", SetLastError = true)] - private static extern int NtQueryInformationProcess( - IntPtr processHandle, - int processInformationClass, - out PROCESS_BASIC_INFORMATION processInformation, - int processInformationLength, - out int returnLength); #endif - } } diff --git a/src/System.Management.Automation/engine/ProgressRecord.cs b/src/System.Management.Automation/engine/ProgressRecord.cs index b721b4003d9..b3139dc8e6e 100644 --- a/src/System.Management.Automation/engine/ProgressRecord.cs +++ b/src/System.Management.Automation/engine/ProgressRecord.cs @@ -15,7 +15,7 @@ namespace System.Management.Automation /// which, according to user preference, forwards that information on to the host for rendering to the user. /// /// - [DataContract()] + [DataContract] public class ProgressRecord { @@ -59,6 +59,25 @@ class ProgressRecord this.status = statusDescription; } + /// + /// Initializes a new instance of the ProgressRecord class and defines the activity Id. + /// + /// + /// A unique numeric key that identifies the activity to which this record applies. + /// + public + ProgressRecord(int activityId) + { + if (activityId < 0) + { + // negative Ids are reserved to indicate "no id" for parent Ids. + + throw PSTraceSource.NewArgumentOutOfRangeException(nameof(activityId), activityId, ProgressRecordStrings.ArgMayNotBeNegative, "activityId"); + } + + this.id = activityId; + } + /// /// Cloning constructor (all fields are value types - can treat our implementation of cloning as "deep" copy) /// @@ -230,7 +249,7 @@ internal ProgressRecord(ProgressRecord other) /// /// Normally displayed beside the progress bar, as "N seconds remaining." /// - /// + /// /// A value less than 0 means "don't display a time remaining." /// public @@ -274,7 +293,7 @@ internal ProgressRecord(ProgressRecord other) } /// - /// Overrides + /// Overrides /// /// /// "parent = a id = b act = c stat = d cur = e pct = f sec = g type = h" where @@ -360,15 +379,8 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD startTime.Kind == DateTimeKind.Utc, "DateTime arithmetic should always be done in utc mode [to avoid problems when some operands are calculated right before and right after switching to /from a daylight saving time"); - if (startTime > now) - { - throw new ArgumentOutOfRangeException(nameof(startTime)); - } - - if (expectedDuration <= TimeSpan.Zero) - { - throw new ArgumentOutOfRangeException(nameof(expectedDuration)); - } + ArgumentOutOfRangeException.ThrowIfGreaterThan(startTime, now); + ArgumentOutOfRangeException.ThrowIfLessThanOrEqual(expectedDuration, TimeSpan.Zero); /* * According to the spec of Checkpoint-Computer @@ -417,28 +429,28 @@ internal static int GetPercentageComplete(DateTime startTime, TimeSpan expectedD #region DO NOT REMOVE OR RENAME THESE FIELDS - it will break remoting compatibility with Windows PowerShell - [DataMemberAttribute()] + [DataMember] private readonly int id; - [DataMemberAttribute()] + [DataMember] private int parentId = -1; - [DataMemberAttribute()] + [DataMember] private string activity; - [DataMemberAttribute()] + [DataMember] private string status; - [DataMemberAttribute()] + [DataMember] private string currentOperation; - [DataMemberAttribute()] + [DataMember] private int percent = -1; - [DataMemberAttribute()] + [DataMember] private int secondsRemaining = -1; - [DataMemberAttribute()] + [DataMember] private ProgressRecordType type = ProgressRecordType.Processing; #endregion @@ -488,9 +500,13 @@ internal static ProgressRecord FromPSObjectForRemoting(PSObject progressAsPSObje /// This object as a PSObject property bag. internal PSObject ToPSObjectForRemoting() { + // Activity used to be mandatory but that's no longer the case. + // We ensure the string has a value to maintain compatibility with older versions. + string activity = string.IsNullOrEmpty(Activity) ? " " : Activity; + PSObject progressAsPSObject = RemotingEncoder.CreateEmptyPSObject(); - progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_Activity, this.Activity)); + progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_Activity, activity)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_ActivityId, this.ActivityId)); progressAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.ProgressRecord_StatusDescription, this.StatusDescription)); @@ -512,10 +528,11 @@ internal PSObject ToPSObjectForRemoting() public enum ProgressRecordType { - /// + /// + /// /// Operation just started or is not yet complete. - /// - /// + /// + /// /// A cmdlet can call WriteProgress with ProgressRecordType.Processing /// as many times as it wishes. However, at the end of the operation, /// it should call once more with ProgressRecordType.Completed. @@ -526,17 +543,20 @@ enum ProgressRecordType /// of the same Id, the host will update that display. /// Finally, when the host receives a 'completed' record /// for that activity, it will remove the progress indicator. - /// + /// + /// Processing, /// + /// /// Operation is complete. - /// - /// + /// + /// /// If a cmdlet uses WriteProgress, it should use /// ProgressRecordType.Completed exactly once, in the last call /// to WriteProgress. - /// + /// + /// Completed } } diff --git a/src/System.Management.Automation/engine/ProxyCommand.cs b/src/System.Management.Automation/engine/ProxyCommand.cs index 5703adec664..80d70377e87 100644 --- a/src/System.Management.Automation/engine/ProxyCommand.cs +++ b/src/System.Management.Automation/engine/ProxyCommand.cs @@ -247,6 +247,30 @@ public static string GetEnd(CommandMetadata commandMetadata) return commandMetadata.GetEndBlock(); } + /// + /// This method constructs a string representing the clean block of the command + /// specified by . The returned string only contains the + /// script, it is not enclosed in "clean { }". + /// + /// + /// An instance of CommandMetadata representing a command. + /// + /// + /// A string representing the end block of the command. + /// + /// + /// If is null. + /// + public static string GetClean(CommandMetadata commandMetadata) + { + if (commandMetadata == null) + { + throw PSTraceSource.NewArgumentNullException(nameof(commandMetadata)); + } + + return commandMetadata.GetCleanBlock(); + } + private static T GetProperty(PSObject obj, string property) where T : class { T result = null; @@ -352,10 +376,7 @@ private static void AppendType(StringBuilder sb, string section, PSObject parent /// When the help argument is not recognized as a HelpInfo object. public static string GetHelpComments(PSObject help) { - if (help == null) - { - throw new ArgumentNullException(nameof(help)); - } + ArgumentNullException.ThrowIfNull(help); bool isHelpObject = false; foreach (string typeName in help.InternalTypeNames) diff --git a/src/System.Management.Automation/engine/PseudoParameters.cs b/src/System.Management.Automation/engine/PseudoParameters.cs index 97b1d60e8ad..a3703a63d90 100644 --- a/src/System.Management.Automation/engine/PseudoParameters.cs +++ b/src/System.Management.Automation/engine/PseudoParameters.cs @@ -174,14 +174,20 @@ internal bool IsDisabled() { if (!hasSeenExpAttribute && attr is ExperimentalAttribute expAttribute) { - if (expAttribute.ToHide) { return true; } + if (expAttribute.ToHide) + { + return true; + } hasSeenExpAttribute = true; } else if (attr is ParameterAttribute paramAttribute) { hasParameterAttribute = true; - if (paramAttribute.ToHide) { continue; } + if (paramAttribute.ToHide) + { + continue; + } hasEnabledParamAttribute = true; } @@ -208,7 +214,6 @@ internal bool IsDisabled() /// /// /// - [Serializable] public class RuntimeDefinedParameterDictionary : Dictionary { /// diff --git a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs index 6488dbcee90..5ee84f4c42f 100644 --- a/src/System.Management.Automation/engine/ReflectionParameterBinder.cs +++ b/src/System.Management.Automation/engine/ReflectionParameterBinder.cs @@ -155,39 +155,39 @@ internal override void BindParameter(string name, object value, CompiledCommandP static ReflectionParameterBinder() { // Statically add delegates that we typically need on startup or every time we run PowerShell - this avoids the JIT - s_getterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), o => ((OutDefaultCommand)o).InputObject); - s_setterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), (o, v) => ((OutDefaultCommand)o).InputObject = (PSObject)v); + s_getterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), static o => ((OutDefaultCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(OutDefaultCommand), "InputObject"), static (o, v) => ((OutDefaultCommand)o).InputObject = (PSObject)v); - s_getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), o => ((OutLineOutputCommand)o).InputObject); - s_getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), o => ((OutLineOutputCommand)o).LineOutput); - s_setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), (o, v) => ((OutLineOutputCommand)o).InputObject = (PSObject)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), (o, v) => ((OutLineOutputCommand)o).LineOutput = v); + s_getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), static o => ((OutLineOutputCommand)o).InputObject); + s_getterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), static o => ((OutLineOutputCommand)o).LineOutput); + s_setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "InputObject"), static (o, v) => ((OutLineOutputCommand)o).InputObject = (PSObject)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(OutLineOutputCommand), "LineOutput"), static (o, v) => ((OutLineOutputCommand)o).LineOutput = v); - s_getterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), o => ((FormatDefaultCommand)o).InputObject); - s_setterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), (o, v) => ((FormatDefaultCommand)o).InputObject = (PSObject)v); + s_getterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), static o => ((FormatDefaultCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(FormatDefaultCommand), "InputObject"), static (o, v) => ((FormatDefaultCommand)o).InputObject = (PSObject)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Off"), (o, v) => ((SetStrictModeCommand)o).Off = (SwitchParameter)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Version"), (o, v) => ((SetStrictModeCommand)o).Version = (Version)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Off"), static (o, v) => ((SetStrictModeCommand)o).Off = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(SetStrictModeCommand), "Version"), static (o, v) => ((SetStrictModeCommand)o).Version = (Version)v); - s_getterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), o => ((ForEachObjectCommand)o).InputObject); - s_setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), (o, v) => ((ForEachObjectCommand)o).InputObject = (PSObject)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "Process"), (o, v) => ((ForEachObjectCommand)o).Process = (ScriptBlock[])v); + s_getterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), static o => ((ForEachObjectCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "InputObject"), static (o, v) => ((ForEachObjectCommand)o).InputObject = (PSObject)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ForEachObjectCommand), "Process"), static (o, v) => ((ForEachObjectCommand)o).Process = (ScriptBlock[])v); - s_getterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), o => ((WhereObjectCommand)o).InputObject); - s_setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), (o, v) => ((WhereObjectCommand)o).InputObject = (PSObject)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "FilterScript"), (o, v) => ((WhereObjectCommand)o).FilterScript = (ScriptBlock)v); + s_getterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), static o => ((WhereObjectCommand)o).InputObject); + s_setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "InputObject"), static (o, v) => ((WhereObjectCommand)o).InputObject = (PSObject)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(WhereObjectCommand), "FilterScript"), static (o, v) => ((WhereObjectCommand)o).FilterScript = (ScriptBlock)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Name"), (o, v) => ((ImportModuleCommand)o).Name = (string[])v); - s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "ModuleInfo"), (o, v) => ((ImportModuleCommand)o).ModuleInfo = (PSModuleInfo[])v); - s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Scope"), (o, v) => ((ImportModuleCommand)o).Scope = (string)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "PassThru"), (o, v) => ((ImportModuleCommand)o).PassThru = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Name"), static (o, v) => ((ImportModuleCommand)o).Name = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "ModuleInfo"), static (o, v) => ((ImportModuleCommand)o).ModuleInfo = (PSModuleInfo[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "Scope"), static (o, v) => ((ImportModuleCommand)o).Scope = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(ImportModuleCommand), "PassThru"), static (o, v) => ((ImportModuleCommand)o).PassThru = (SwitchParameter)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Name"), (o, v) => ((GetCommandCommand)o).Name = (string[])v); - s_setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Module"), (o, v) => ((GetCommandCommand)o).Module = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Name"), static (o, v) => ((GetCommandCommand)o).Name = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetCommandCommand), "Module"), static (o, v) => ((GetCommandCommand)o).Module = (string[])v); - s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "Name"), (o, v) => ((GetModuleCommand)o).Name = (string[])v); - s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "ListAvailable"), (o, v) => ((GetModuleCommand)o).ListAvailable = (SwitchParameter)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "FullyQualifiedName"), (o, v) => ((GetModuleCommand)o).FullyQualifiedName = (ModuleSpecification[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "Name"), static (o, v) => ((GetModuleCommand)o).Name = (string[])v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "ListAvailable"), static (o, v) => ((GetModuleCommand)o).ListAvailable = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(GetModuleCommand), "FullyQualifiedName"), static (o, v) => ((GetModuleCommand)o).FullyQualifiedName = (ModuleSpecification[])v); s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorAction"), (o, v) => @@ -207,14 +207,20 @@ static ReflectionParameterBinder() v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); ((CommonParameters)o).InformationAction = (ActionPreference)v; }); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Verbose"), (o, v) => ((CommonParameters)o).Verbose = (SwitchParameter)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Debug"), (o, v) => ((CommonParameters)o).Debug = (SwitchParameter)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorVariable"), (o, v) => ((CommonParameters)o).ErrorVariable = (string)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningVariable"), (o, v) => ((CommonParameters)o).WarningVariable = (string)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationVariable"), (o, v) => ((CommonParameters)o).InformationVariable = (string)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutVariable"), (o, v) => ((CommonParameters)o).OutVariable = (string)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutBuffer"), (o, v) => ((CommonParameters)o).OutBuffer = (int)v); - s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "PipelineVariable"), (o, v) => ((CommonParameters)o).PipelineVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ProgressAction"), + (o, v) => + { + v ??= LanguagePrimitives.ThrowInvalidCastException(null, typeof(ActionPreference)); + ((CommonParameters)o).ProgressAction = (ActionPreference)v; + }); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Verbose"), static (o, v) => ((CommonParameters)o).Verbose = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "Debug"), static (o, v) => ((CommonParameters)o).Debug = (SwitchParameter)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "ErrorVariable"), static (o, v) => ((CommonParameters)o).ErrorVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "WarningVariable"), static (o, v) => ((CommonParameters)o).WarningVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "InformationVariable"), static (o, v) => ((CommonParameters)o).InformationVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutVariable"), static (o, v) => ((CommonParameters)o).OutVariable = (string)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "OutBuffer"), static (o, v) => ((CommonParameters)o).OutBuffer = (int)v); + s_setterMethods.TryAdd(Tuple.Create(typeof(CommonParameters), "PipelineVariable"), static (o, v) => ((CommonParameters)o).PipelineVariable = (string)v); } private static readonly ConcurrentDictionary, Func> s_getterMethods diff --git a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs index 99b685e07d2..32bec9fd5a9 100644 --- a/src/System.Management.Automation/engine/ScriptCommandProcessor.cs +++ b/src/System.Management.Automation/engine/ScriptCommandProcessor.cs @@ -6,6 +6,7 @@ using System.Diagnostics; using System.Management.Automation.Internal; using System.Management.Automation.Language; +using System.Management.Automation.Runspaces; using System.Reflection; using Dbg = System.Management.Automation.Diagnostics; @@ -47,7 +48,7 @@ protected ScriptCommandProcessorBase(IScriptCommandInfo commandInfo, ExecutionCo protected bool _dontUseScopeCommandOrigin; /// - /// If true, then an exit exception will be rethrown to instead of caught and processed... + /// If true, then an exit exception will be rethrown instead of caught and processed... /// protected bool _rethrowExitException; @@ -121,7 +122,7 @@ protected void CommonInitialization(ScriptBlock scriptBlock, ExecutionContext co // language modes (getting internal functions in the user's state) isn't a danger if ((!this.UseLocalScope) && (!this._rethrowExitException)) { - ValidateCompatibleLanguageMode(_scriptBlock, context.LanguageMode, Command.MyInvocation); + ValidateCompatibleLanguageMode(_scriptBlock, context, Command.MyInvocation); } } @@ -142,9 +143,8 @@ internal override bool IsHelpRequested(out string helpTarget, out HelpCategory h if (parameter.IsDashQuestion()) { Dictionary scriptBlockTokenCache = new Dictionary(); - string unused; HelpInfo helpInfo = _scriptBlock.GetHelpInfo(context: Context, commandInfo: CommandInfo, - dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out unused, helpUriFromDotLink: out unused); + dontSearchOnRemoteComputer: false, scriptBlockTokenCache: scriptBlockTokenCache, helpFile: out _, helpUriFromDotLink: out _); if (helpInfo == null) { break; @@ -237,6 +237,7 @@ internal sealed class DlrScriptCommandProcessor : ScriptCommandProcessorBase private MutableTuple _localsTuple; private bool _runOptimizedCode; private bool _argsBound; + private bool _anyClauseExecuted; private FunctionContext _functionContext; internal DlrScriptCommandProcessor(ScriptBlock scriptBlock, ExecutionContext context, bool useNewScope, CommandOrigin origin, SessionStateInternal sessionState, object dollarUnderbar) @@ -327,8 +328,7 @@ internal override void DoBegin() ScriptBlock.LogScriptBlockStart(_scriptBlock, Context.CurrentRunspace.InstanceId); - // Even if there is no begin, we need to set up the execution scope for this - // script... + // Even if there is no begin, we need to set up the execution scope for this script... SetCurrentScopeToExecutionScope(); CommandProcessorBase oldCurrentCommandProcessor = Context.CurrentCommandProcessor; try @@ -410,6 +410,7 @@ internal override void Complete() if (_scriptBlock.HasEndBlock) { var endBlock = _runOptimizedCode ? _scriptBlock.EndBlock : _scriptBlock.UnoptimizedEndBlock; + if (this.CommandRuntime.InputPipe.ExternalReader == null) { if (IsPipelineInputExpected()) @@ -433,7 +434,33 @@ internal override void Complete() } finally { - ScriptBlock.LogScriptBlockEnd(_scriptBlock, Context.CurrentRunspace.InstanceId); + if (!_scriptBlock.HasCleanBlock) + { + ScriptBlock.LogScriptBlockEnd(_scriptBlock, Context.CurrentRunspace.InstanceId); + } + } + } + + protected override void CleanResource() + { + if (_scriptBlock.HasCleanBlock && _anyClauseExecuted) + { + // The 'Clean' block doesn't write to pipeline. + Pipe oldOutputPipe = _functionContext._outputPipe; + _functionContext._outputPipe = new Pipe { NullPipe = true }; + + try + { + RunClause( + clause: _runOptimizedCode ? _scriptBlock.CleanBlock : _scriptBlock.UnoptimizedCleanBlock, + dollarUnderbar: AutomationNull.Value, + inputToProcess: AutomationNull.Value); + } + finally + { + _functionContext._outputPipe = oldOutputPipe; + ScriptBlock.LogScriptBlockEnd(_scriptBlock, Context.CurrentRunspace.InstanceId); + } } } @@ -459,6 +486,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob { ExecutionContext.CheckStackDepth(); + _anyClauseExecuted = true; Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe; // If the script block has a different language mode than the current, @@ -553,7 +581,7 @@ private void RunClause(Action clause, object dollarUnderbar, ob } finally { - this.Context.RestoreErrorPipe(oldErrorOutputPipe); + Context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; if (oldLanguageMode.HasValue) { @@ -584,15 +612,12 @@ private void RunClause(Action clause, object dollarUnderbar, ob } catch (RuntimeException e) { - ManageScriptException(e); // always throws - // This quiets the compiler which wants to see a return value - // in all codepaths. - throw; + // This method always throws. + ManageScriptException(e); } catch (Exception e) { - // This cmdlet threw an exception, so - // wrap it and bubble it up. + // This cmdlet threw an exception, so wrap it and bubble it up. throw ManageInvocationException(e); } } diff --git a/src/System.Management.Automation/engine/ScriptInfo.cs b/src/System.Management.Automation/engine/ScriptInfo.cs index af91867c452..1abdc1424bf 100644 --- a/src/System.Management.Automation/engine/ScriptInfo.cs +++ b/src/System.Management.Automation/engine/ScriptInfo.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation { /// - /// The command information for MSH scripts that are directly executable by MSH. + /// The command information for scripts that are directly executable by PowerShell. /// public class ScriptInfo : CommandInfo, IScriptCommandInfo { diff --git a/src/System.Management.Automation/engine/SecurityManagerBase.cs b/src/System.Management.Automation/engine/SecurityManagerBase.cs index 31712949cf7..0e4f3359704 100644 --- a/src/System.Management.Automation/engine/SecurityManagerBase.cs +++ b/src/System.Management.Automation/engine/SecurityManagerBase.cs @@ -18,7 +18,7 @@ public enum CommandOrigin Runspace, /// - /// The command was dispatched by the msh engine as a result of + /// The command was dispatched by the engine as a result of /// a dispatch request from an already running command. /// Internal diff --git a/src/System.Management.Automation/engine/SessionState.cs b/src/System.Management.Automation/engine/SessionState.cs index e0bdbd23ee0..a53c211beb2 100644 --- a/src/System.Management.Automation/engine/SessionState.cs +++ b/src/System.Management.Automation/engine/SessionState.cs @@ -27,7 +27,7 @@ internal sealed partial class SessionStateInternal /// An instance of the PSTraceSource class used for trace output /// using "SessionState" as the category. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "SessionState", "SessionState Class")] private static readonly Dbg.PSTraceSource s_tracer = @@ -337,10 +337,9 @@ internal void InitializeFixedVariables() this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); // $PID - Process currentProcess = Process.GetCurrentProcess(); v = new PSVariable( SpecialVariables.PID, - currentProcess.Id, + Environment.ProcessId, ScopedItemOptions.Constant | ScopedItemOptions.AllScope, RunspaceInit.PIDDescription); this.GlobalScope.SetVariable(v.Name, v, asValue: false, force: true, this, CommandOrigin.Internal, fastPath: true); @@ -391,14 +390,27 @@ internal SessionStateEntryVisibility CheckApplicationVisibility(string applicati private static SessionStateEntryVisibility checkPathVisibility(List list, string path) { - if (list == null || list.Count == 0) return SessionStateEntryVisibility.Private; - if (string.IsNullOrEmpty(path)) return SessionStateEntryVisibility.Private; + if (list == null || list.Count == 0) + { + return SessionStateEntryVisibility.Private; + } + + if (string.IsNullOrEmpty(path)) + { + return SessionStateEntryVisibility.Private; + } + + if (list.Contains("*")) + { + return SessionStateEntryVisibility.Public; + } - if (list.Contains("*")) return SessionStateEntryVisibility.Public; foreach (string p in list) { if (string.Equals(p, path, StringComparison.OrdinalIgnoreCase)) + { return SessionStateEntryVisibility.Public; + } if (WildcardPattern.ContainsWildcardCharacters(p)) { diff --git a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs index f14c25f7420..5afa8f0169f 100644 --- a/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateCmdletAPIs.cs @@ -35,7 +35,7 @@ internal CmdletInfo GetCmdlet(string cmdletName) /// The name of the cmdlet value to retrieve. /// /// - /// The origin of hte command trying to retrieve this cmdlet. + /// The origin of the command trying to retrieve this cmdlet. /// /// /// The CmdletInfo representing the cmdlet. diff --git a/src/System.Management.Automation/engine/SessionStateContainer.cs b/src/System.Management.Automation/engine/SessionStateContainer.cs index ca7f03a42ca..fa8884b92e8 100644 --- a/src/System.Management.Automation/engine/SessionStateContainer.cs +++ b/src/System.Management.Automation/engine/SessionStateContainer.cs @@ -1324,8 +1324,8 @@ internal void GetChildItems( try { // If we're recursing, do some path fixups to match user - // expectations: - if (recurse) + // expectations, but only if the last part is a file and not a directory: + if (recurse && !path.EndsWith(Path.DirectorySeparatorChar) && !path.EndsWith(Path.AltDirectorySeparatorChar)) { string childName = GetChildName(path, context); @@ -1434,8 +1434,7 @@ internal void GetChildItems( return; } - int unUsedChildrenNotMatchingFilterCriteria = 0; - ProcessPathItems(providerInstance, providerPath, recurse, depth, context, out unUsedChildrenNotMatchingFilterCriteria, ProcessMode.Enumerate); + ProcessPathItems(providerInstance, providerPath, recurse, depth, context, out _, ProcessMode.Enumerate); } } else @@ -1496,12 +1495,11 @@ internal void GetChildItems( { // Do the recursion manually so that we can apply the // include and exclude filters - int unUsedChildrenNotMatchingFilterCriteria = 0; try { - // Temeporary set literal path as false to apply filter + // Temporary set literal path as false to apply filter context.SuppressWildcardExpansion = false; - ProcessPathItems(providerInstance, path, recurse, depth, context, out unUsedChildrenNotMatchingFilterCriteria, ProcessMode.Enumerate); + ProcessPathItems(providerInstance, path, recurse, depth, context, out _, ProcessMode.Enumerate); } finally { @@ -1841,7 +1839,7 @@ private void ProcessPathItems( return; } - if (!(childNameObjects[index].BaseObject is string childName)) + if (childNameObjects[index].BaseObject is not string childName) { continue; } @@ -2586,7 +2584,7 @@ private void DoGetChildNamesManually( return; } - if (!(result.BaseObject is string name)) + if (result.BaseObject is not string name) { continue; } @@ -2634,7 +2632,7 @@ private void DoGetChildNamesManually( return; } - if (!(result.BaseObject is string name)) + if (result.BaseObject is not string name) { continue; } @@ -3499,37 +3497,7 @@ internal void NewItem( throw PSTraceSource.NewArgumentNullException(nameof(content), SessionStateStrings.NewLinkTargetNotSpecified, path); } - ProviderInfo targetProvider = null; - CmdletProvider targetProviderInstance = null; - - var globbedTarget = Globber.GetGlobbedProviderPathsFromMonadPath( - targetPath, - allowNonexistingPath, - context, - out targetProvider, - out targetProviderInstance); - - if (!string.Equals(targetProvider.Name, "filesystem", StringComparison.OrdinalIgnoreCase)) - { - throw PSTraceSource.NewNotSupportedException(SessionStateStrings.MustBeFileSystemPath); - } - - if (globbedTarget.Count > 1) - { - throw PSTraceSource.NewInvalidOperationException(SessionStateStrings.PathResolvedToMultiple, targetPath); - } - - if (globbedTarget.Count == 0) - { - throw PSTraceSource.NewInvalidOperationException(SessionStateStrings.PathNotFound, targetPath); - } - - // If the original target was a relative path, we want to leave it as relative if it did not require - // globbing to resolve. - if (WildcardPattern.ContainsWildcardCharacters(targetPath)) - { - content = globbedTarget[0]; - } + content = targetPath; } NewItemPrivate(providerInstance, composedPath, type, content, context); @@ -4089,10 +4057,7 @@ internal Collection CopyItem(string[] paths, throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (copyPath == null) - { - copyPath = string.Empty; - } + copyPath ??= string.Empty; CmdletProviderContext context = new CmdletProviderContext(this.ExecutionContext); context.Force = force; @@ -4155,14 +4120,10 @@ internal void CopyItem( throw PSTraceSource.NewArgumentNullException(nameof(paths)); } - if (copyPath == null) - { - copyPath = string.Empty; - } + copyPath ??= string.Empty; // Get the provider specific path for the destination - PSDriveInfo unusedDrive = null; ProviderInfo destinationProvider = null; Microsoft.PowerShell.Commands.CopyItemDynamicParameters dynamicParams = context.DynamicParameters as Microsoft.PowerShell.Commands.CopyItemDynamicParameters; bool destinationIsRemote = false; @@ -4213,7 +4174,7 @@ internal void CopyItem( copyPath, context, out destinationProvider, - out unusedDrive); + out _); } else { @@ -4681,7 +4642,7 @@ internal object CopyItemDynamicParameters( } } - if (providerPath != null) + if (providerInstance != null) { // Get the dynamic parameters for the first resolved path return CopyItemDynamicParameters(providerInstance, providerPath, destination, recurse, newContext); @@ -4733,10 +4694,6 @@ private object CopyItemDynamicParameters( providerInstance != null, "Caller should validate providerInstance before calling this method"); - Dbg.Diagnostics.Assert( - path != null, - "Caller should validate path before calling this method"); - Dbg.Diagnostics.Assert( context != null, "Caller should validate context before calling this method"); diff --git a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs index b8a89b9b31f..d01d4c63f5d 100644 --- a/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateDriveAPIs.cs @@ -231,28 +231,12 @@ internal void NewDrive(PSDriveInfo drive, string scopeID, CmdletProviderContext private static bool IsValidDriveName(string name) { - bool result = true; + const string CharactersInvalidInDriveName = ":/\\.~"; - do - { - if (string.IsNullOrEmpty(name)) - { - result = false; - break; - } - - if (name.IndexOfAny(s_charactersInvalidInDriveName) >= 0) - { - result = false; - break; - } - } while (false); - - return result; + return !string.IsNullOrEmpty(name) + && name.AsSpan().IndexOfAny(CharactersInvalidInDriveName) < 0; } - private static readonly char[] s_charactersInvalidInDriveName = new char[] { ':', '/', '\\', '.', '~' }; - /// /// Tries to resolve the drive root as an MSH path. If it successfully resolves /// to a single path then the resolved provider internal path is returned. If it @@ -1450,4 +1434,3 @@ internal PSDriveInfo CurrentDrive } #pragma warning restore 56500 - diff --git a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs index f444f46d2c3..5ef285ddcec 100644 --- a/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateFunctionAPIs.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using Dbg = System.Management.Automation.Diagnostics; @@ -184,7 +185,7 @@ private bool IsFunctionVisibleInDebugger(FunctionInfo fnInfo, CommandOrigin orig // Early out. // Always allow built-in functions needed for command line debugging. - if ((this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage) || + if (this.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage || (fnInfo == null) || (fnInfo.Name.Equals("prompt", StringComparison.OrdinalIgnoreCase)) || (fnInfo.Name.Equals("TabExpansion2", StringComparison.OrdinalIgnoreCase)) || diff --git a/src/System.Management.Automation/engine/SessionStateItem.cs b/src/System.Management.Automation/engine/SessionStateItem.cs index 3d5262bf6c0..173043515ba 100644 --- a/src/System.Management.Automation/engine/SessionStateItem.cs +++ b/src/System.Management.Automation/engine/SessionStateItem.cs @@ -1375,4 +1375,3 @@ private object InvokeDefaultActionDynamicParameters( } #pragma warning restore 56500 - diff --git a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs index 6869f5071fb..56de07b8871 100644 --- a/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateLocationAPIs.cs @@ -316,10 +316,7 @@ internal PathInfo SetLocation(string path, CmdletProviderContext context, bool l } } - if (context == null) - { - context = new CmdletProviderContext(this.ExecutionContext); - } + context ??= new CmdletProviderContext(this.ExecutionContext); if (CurrentDrive != null) { diff --git a/src/System.Management.Automation/engine/SessionStateNavigation.cs b/src/System.Management.Automation/engine/SessionStateNavigation.cs index f6d1a28eb1c..d2d27ec2d83 100644 --- a/src/System.Management.Automation/engine/SessionStateNavigation.cs +++ b/src/System.Management.Automation/engine/SessionStateNavigation.cs @@ -1458,7 +1458,6 @@ internal void MoveItem( } else { - PSDriveInfo unusedPSDriveInfo = null; ProviderInfo destinationProvider = null; CmdletProviderContext destinationContext = new CmdletProviderContext(this.ExecutionContext); @@ -1472,7 +1471,7 @@ internal void MoveItem( providerDestinationPaths[0].Path, destinationContext, out destinationProvider, - out unusedPSDriveInfo); + out _); } else { @@ -1484,7 +1483,7 @@ internal void MoveItem( destination, destinationContext, out destinationProvider, - out unusedPSDriveInfo); + out _); } // Now verify the providers are the same. @@ -1749,4 +1748,3 @@ private object MoveItemDynamicParameters( } #pragma warning restore 56500 - diff --git a/src/System.Management.Automation/engine/SessionStateProperty.cs b/src/System.Management.Automation/engine/SessionStateProperty.cs index d4568d2ebb3..9f621fa2f7a 100644 --- a/src/System.Management.Automation/engine/SessionStateProperty.cs +++ b/src/System.Management.Automation/engine/SessionStateProperty.cs @@ -1116,4 +1116,3 @@ private object ClearPropertyDynamicParameters( } #pragma warning restore 56500 - diff --git a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs index a6a7d2efc7f..3ad2ed99e31 100644 --- a/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateProviderAPIs.cs @@ -350,7 +350,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(string providerId) throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } - if (!(GetProviderInstance(providerId) is DriveCmdletProvider driveCmdletProvider)) + if (GetProviderInstance(providerId) is not DriveCmdletProvider driveCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); @@ -382,7 +382,7 @@ internal DriveCmdletProvider GetDriveProviderInstance(ProviderInfo provider) throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (!(GetProviderInstance(provider) is DriveCmdletProvider driveCmdletProvider)) + if (GetProviderInstance(provider) is not DriveCmdletProvider driveCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); @@ -414,7 +414,7 @@ private static DriveCmdletProvider GetDriveProviderInstance(CmdletProvider provi throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } - if (!(providerInstance is DriveCmdletProvider driveCmdletProvider)) + if (providerInstance is not DriveCmdletProvider driveCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.DriveCmdletProvider_NotSupported); @@ -449,7 +449,7 @@ internal ItemCmdletProvider GetItemProviderInstance(string providerId) throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } - if (!(GetProviderInstance(providerId) is ItemCmdletProvider itemCmdletProvider)) + if (GetProviderInstance(providerId) is not ItemCmdletProvider itemCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); @@ -481,7 +481,7 @@ internal ItemCmdletProvider GetItemProviderInstance(ProviderInfo provider) throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (!(GetProviderInstance(provider) is ItemCmdletProvider itemCmdletProvider)) + if (GetProviderInstance(provider) is not ItemCmdletProvider itemCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); @@ -513,7 +513,7 @@ private static ItemCmdletProvider GetItemProviderInstance(CmdletProvider provide throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } - if (!(providerInstance is ItemCmdletProvider itemCmdletProvider)) + if (providerInstance is not ItemCmdletProvider itemCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ItemCmdletProvider_NotSupported); @@ -548,7 +548,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(string providerId) throw PSTraceSource.NewArgumentNullException(nameof(providerId)); } - if (!(GetProviderInstance(providerId) is ContainerCmdletProvider containerCmdletProvider)) + if (GetProviderInstance(providerId) is not ContainerCmdletProvider containerCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); @@ -580,7 +580,7 @@ internal ContainerCmdletProvider GetContainerProviderInstance(ProviderInfo provi throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (!(GetProviderInstance(provider) is ContainerCmdletProvider containerCmdletProvider)) + if (GetProviderInstance(provider) is not ContainerCmdletProvider containerCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); @@ -612,7 +612,7 @@ private static ContainerCmdletProvider GetContainerProviderInstance(CmdletProvid throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } - if (!(providerInstance is ContainerCmdletProvider containerCmdletProvider)) + if (providerInstance is not ContainerCmdletProvider containerCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.ContainerCmdletProvider_NotSupported); @@ -644,7 +644,7 @@ internal NavigationCmdletProvider GetNavigationProviderInstance(ProviderInfo pro throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (!(GetProviderInstance(provider) is NavigationCmdletProvider navigationCmdletProvider)) + if (GetProviderInstance(provider) is not NavigationCmdletProvider navigationCmdletProvider) { throw PSTraceSource.NewNotSupportedException(SessionStateStrings.NavigationCmdletProvider_NotSupported); @@ -960,10 +960,7 @@ internal void InitializeProvider( throw PSTraceSource.NewArgumentNullException(nameof(provider)); } - if (context == null) - { - context = new CmdletProviderContext(this.ExecutionContext); - } + context ??= new CmdletProviderContext(this.ExecutionContext); // Initialize the provider so that it can add any drives // that it needs. diff --git a/src/System.Management.Automation/engine/SessionStateScope.cs b/src/System.Management.Automation/engine/SessionStateScope.cs index fc5dff00784..03ab9bdfb4b 100644 --- a/src/System.Management.Automation/engine/SessionStateScope.cs +++ b/src/System.Management.Automation/engine/SessionStateScope.cs @@ -6,6 +6,7 @@ using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; namespace System.Management.Automation { @@ -421,7 +422,10 @@ internal PSVariable SetVariable(string name, object value, bool asValue, bool fo bool varExists = TryGetVariable(name, origin, true, out variable); // Initialize the private variable dictionary if it's not yet - if (_variables == null) { GetPrivateVariables(); } + if (_variables == null) + { + GetPrivateVariables(); + } if (!asValue && variableToSet != null) { @@ -1245,11 +1249,18 @@ internal FunctionInfo SetFunction( name != null, "The caller should verify the name"); - var functionInfos = GetFunctions(); - FunctionInfo existingValue; + Dictionary functionInfos = GetFunctions(); FunctionInfo result; - if (!functionInfos.TryGetValue(name, out existingValue)) + + // Functions are equal only if they have the same name and if they come from the same module (if any). + // If the function is not associated with a module then the info 'ModuleName' property is set to empty string. + // If the new function has the same name of an existing function, but different module names, then the + // existing table function is replaced with the new function. + if (!functionInfos.TryGetValue(name, out FunctionInfo existingValue) || + (originalFunction != null && + !existingValue.ModuleName.Equals(originalFunction.ModuleName, StringComparison.OrdinalIgnoreCase))) { + // Add new function info to function table and return. result = functionFactory(name, function, originalFunction, options, context, helpFile); functionInfos[name] = result; @@ -1257,81 +1268,78 @@ internal FunctionInfo SetFunction( { GetAllScopeFunctions()[name] = result; } - } - else - { - // Make sure the function isn't constant or readonly - SessionState.ThrowIfNotVisible(origin, existingValue); - - if (IsFunctionOptionSet(existingValue, ScopedItemOptions.Constant) || - (!force && IsFunctionOptionSet(existingValue, ScopedItemOptions.ReadOnly))) - { - SessionStateUnauthorizedAccessException e = - new SessionStateUnauthorizedAccessException( - name, - SessionStateCategory.Function, - "FunctionNotWritable", - SessionStateStrings.FunctionNotWritable); + return result; + } - throw e; - } + // Update the existing function. - // Ensure we are not trying to set the function to constant as this can only be - // done at creation time. + // Make sure the function isn't constant or readonly. + SessionState.ThrowIfNotVisible(origin, existingValue); - if ((options & ScopedItemOptions.Constant) != 0) - { - SessionStateUnauthorizedAccessException e = - new SessionStateUnauthorizedAccessException( - name, - SessionStateCategory.Function, - "FunctionCannotBeMadeConstant", - SessionStateStrings.FunctionCannotBeMadeConstant); + if (IsFunctionOptionSet(existingValue, ScopedItemOptions.Constant) || + (!force && IsFunctionOptionSet(existingValue, ScopedItemOptions.ReadOnly))) + { + SessionStateUnauthorizedAccessException e = + new SessionStateUnauthorizedAccessException( + name, + SessionStateCategory.Function, + "FunctionNotWritable", + SessionStateStrings.FunctionNotWritable); - throw e; - } + throw e; + } - // Ensure we are not trying to remove the AllScope option + // Ensure we are not trying to set the function to constant as this can only be + // done at creation time. + if ((options & ScopedItemOptions.Constant) != 0) + { + SessionStateUnauthorizedAccessException e = + new SessionStateUnauthorizedAccessException( + name, + SessionStateCategory.Function, + "FunctionCannotBeMadeConstant", + SessionStateStrings.FunctionCannotBeMadeConstant); - if ((options & ScopedItemOptions.AllScope) == 0 && - IsFunctionOptionSet(existingValue, ScopedItemOptions.AllScope)) - { - SessionStateUnauthorizedAccessException e = - new SessionStateUnauthorizedAccessException( - name, - SessionStateCategory.Function, - "FunctionAllScopeOptionCannotBeRemoved", - SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved); + throw e; + } - throw e; - } + // Ensure we are not trying to remove the AllScope option. + if ((options & ScopedItemOptions.AllScope) == 0 && + IsFunctionOptionSet(existingValue, ScopedItemOptions.AllScope)) + { + SessionStateUnauthorizedAccessException e = + new SessionStateUnauthorizedAccessException( + name, + SessionStateCategory.Function, + "FunctionAllScopeOptionCannotBeRemoved", + SessionStateStrings.FunctionAllScopeOptionCannotBeRemoved); - FunctionInfo existingFunction = existingValue; - FunctionInfo newValue = null; + throw e; + } - // If the function type changes (i.e.: function to workflow or back) - // then we need to blast what was there - newValue = functionFactory(name, function, originalFunction, options, context, helpFile); + FunctionInfo existingFunction = existingValue; - bool changesFunctionType = existingFunction.GetType() != newValue.GetType(); + // If the function type changes (i.e.: function to workflow or back) + // then we need to replace what was there. + FunctionInfo newValue = functionFactory(name, function, originalFunction, options, context, helpFile); - // Since the options are set after the script block, we have to - // forcefully apply the script block if the options will be - // set to not being ReadOnly - if (changesFunctionType || - ((existingFunction.Options & ScopedItemOptions.ReadOnly) != 0 && force)) - { - result = newValue; - functionInfos[name] = newValue; - } - else - { - bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0; + bool changesFunctionType = existingFunction.GetType() != newValue.GetType(); - existingFunction.Update(newValue, applyForce, options, helpFile); - result = existingFunction; - } + // Since the options are set after the script block, we have to + // forcefully apply the script block if the options will be + // set to not being ReadOnly. + if (changesFunctionType || + ((existingFunction.Options & ScopedItemOptions.ReadOnly) != 0 && force)) + { + result = newValue; + functionInfos[name] = newValue; + } + else + { + bool applyForce = force || (options & ScopedItemOptions.ReadOnly) == 0; + existingFunction.Update(newValue, applyForce, options, helpFile); + result = existingFunction; } return result; @@ -1628,19 +1636,21 @@ internal Language.TypeResolutionState TypeResolutionState internal void AddType(string name, Type type) { - if (TypeTable == null) - { - TypeTable = new Dictionary(StringComparer.OrdinalIgnoreCase); - } + TypeTable ??= new Dictionary(StringComparer.OrdinalIgnoreCase); TypeTable[name] = type; } internal Type LookupType(string name) { - if (TypeTable == null) return null; + if (TypeTable == null) + { + return null; + } + Type result; TypeTable.TryGetValue(name, out result); + return result; } @@ -1681,12 +1691,18 @@ private static FunctionInfo CreateFunction(string name, ScriptBlock function, Fu // Then use the creation constructors - workflows don't get here because the workflow info // is created during compilation. - else if (function.IsFilter) { newValue = new FilterInfo(name, function, options, context, helpFile); } + else if (function.IsFilter) + { + newValue = new FilterInfo(name, function, options, context, helpFile); + } else if (function.IsConfiguration) { newValue = new ConfigurationInfo(name, function, options, context, helpFile, function.IsMetaConfiguration()); } - else newValue = new FunctionInfo(name, function, options, context, helpFile); + else + { + newValue = new FunctionInfo(name, function, options, context, helpFile); + } return newValue; } @@ -1969,11 +1985,21 @@ private void CheckVariableChangeInConstrainedLanguage(PSVariable variable) var context = LocalPipeline.GetExecutionContextFromTLS(); if (context?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - if ((variable.Options & ScopedItemOptions.AllScope) == ScopedItemOptions.AllScope) + if (variable.Options.HasFlag(ScopedItemOptions.AllScope)) { - // Don't let people set AllScope variables in ConstrainedLanguage, as they can be used to - // interfere with the session state of trusted commands. - throw new PSNotSupportedException(); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + // Don't let people set AllScope variables in ConstrainedLanguage, as they can be used to + // interfere with the session state of trusted commands. + throw new PSNotSupportedException(); + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: SessionStateStrings.WDACSessionStateVarLogTitle, + message: StringUtil.Format(SessionStateStrings.WDACSessionStateVarLogMessage, variable.Name), + fqid: "AllScopeVariableNotAllowed", + dropIntoDebugger: true); } // Mark untrusted values for assignments to 'Global:' variables, and 'Script:' variables in diff --git a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs index 16ebe0fc3b5..08635c7efe1 100644 --- a/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs +++ b/src/System.Management.Automation/engine/SessionStateSecurityDescriptorInterface.cs @@ -35,7 +35,7 @@ internal static ISecurityDescriptorCmdletProvider GetPermissionProviderInstance( throw PSTraceSource.NewArgumentNullException(nameof(providerInstance)); } - if (!(providerInstance is ISecurityDescriptorCmdletProvider permissionCmdletProvider)) + if (providerInstance is not ISecurityDescriptorCmdletProvider permissionCmdletProvider) { throw PSTraceSource.NewNotSupportedException( diff --git a/src/System.Management.Automation/engine/SessionStateUtils.cs b/src/System.Management.Automation/engine/SessionStateUtils.cs index 754f228633a..6bdc29da198 100644 --- a/src/System.Management.Automation/engine/SessionStateUtils.cs +++ b/src/System.Management.Automation/engine/SessionStateUtils.cs @@ -151,10 +151,7 @@ internal static Collection ConvertArrayToCollection(T[] array) /// internal static bool CollectionContainsValue(IEnumerable collection, object value, IComparer comparer) { - if (collection == null) - { - throw new ArgumentNullException(nameof(collection)); - } + ArgumentNullException.ThrowIfNull(collection); bool result = false; diff --git a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs index 8cc9e4bafa4..336c2b77952 100644 --- a/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs +++ b/src/System.Management.Automation/engine/SessionStateVariableAPIs.cs @@ -352,8 +352,7 @@ internal object GetVariableValueFromProvider( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", @@ -368,8 +367,7 @@ internal object GetVariableValueFromProvider( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", @@ -407,8 +405,7 @@ internal object GetVariableValueFromProvider( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", @@ -445,8 +442,7 @@ internal object GetVariableValueFromProvider( { // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); ProviderInvocationException providerException = new ProviderInvocationException( @@ -741,8 +737,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", @@ -757,8 +752,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", @@ -796,8 +790,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", @@ -835,8 +828,7 @@ internal object GetVariableValueAtScope(string name, string scopeID) // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); ProviderInvocationException providerException = new ProviderInvocationException( @@ -1245,8 +1237,7 @@ internal object SetVariable( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", @@ -1261,8 +1252,7 @@ internal object SetVariable( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderCannotBeUsedAsVariable", @@ -1301,8 +1291,7 @@ internal object SetVariable( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); throw NewProviderInvocationException( "ProviderVariableSyntaxInvalid", @@ -1325,8 +1314,7 @@ internal object SetVariable( // First get the provider for the path. ProviderInfo providerInfo = null; - string unused = - this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); + _ = this.Globber.GetProviderPath(variablePath.QualifiedName, out providerInfo); ProviderInvocationException providerException = new ProviderInvocationException( @@ -1839,10 +1827,7 @@ private static void GetScopeVariableTable(SessionStateScope scope, Dictionary diff --git a/src/System.Management.Automation/engine/ShellVariable.cs b/src/System.Management.Automation/engine/ShellVariable.cs index 424be295346..8440845a32d 100644 --- a/src/System.Management.Automation/engine/ShellVariable.cs +++ b/src/System.Management.Automation/engine/ShellVariable.cs @@ -244,6 +244,14 @@ internal void DebuggerCheckVariableWrite() } } + /// + /// Gets the value without triggering debugger check. + /// + internal virtual object GetValueRaw() + { + return _value; + } + /// /// Gets or sets the value of the variable. /// @@ -796,6 +804,11 @@ public override object Value } } + internal override object GetValueRaw() + { + return _tuple.GetValue(_tupleSlot); + } + internal override void SetValueRaw(object newValue, bool preserveValueTypeSemantics) { if (preserveValueTypeSemantics) diff --git a/src/System.Management.Automation/engine/SpecialVariables.cs b/src/System.Management.Automation/engine/SpecialVariables.cs index ba757722e91..51419a0d5c2 100644 --- a/src/System.Management.Automation/engine/SpecialVariables.cs +++ b/src/System.Management.Automation/engine/SpecialVariables.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections.Generic; +using System.Management.Automation.Internal; namespace System.Management.Automation { @@ -40,6 +41,10 @@ internal static class SpecialVariables internal static readonly VariablePath OutputEncodingVarPath = new VariablePath(OutputEncoding); + internal const string PSApplicationOutputEncoding = nameof(PSApplicationOutputEncoding); + + internal static readonly VariablePath PSApplicationOutputEncodingVarPath = new VariablePath(PSApplicationOutputEncoding); + internal const string VerboseHelpErrors = "VerboseHelpErrors"; internal static readonly VariablePath VerboseHelpErrorsVarPath = new VariablePath(VerboseHelpErrors); @@ -204,6 +209,7 @@ internal static class SpecialVariables internal static readonly VariablePath PSModuleAutoLoadingPreferenceVarPath = new VariablePath("global:" + PSModuleAutoLoading); #region Platform Variables + internal const string IsLinux = "IsLinux"; internal static readonly VariablePath IsLinuxPath = new VariablePath("IsLinux"); @@ -221,6 +227,7 @@ internal static class SpecialVariables internal static readonly VariablePath IsCoreCLRPath = new VariablePath("IsCoreCLR"); #endregion + #region Preference Variables internal const string DebugPreference = "DebugPreference"; @@ -257,6 +264,16 @@ internal static class SpecialVariables #endregion Preference Variables + internal const string PSNativeCommandUseErrorActionPreference = nameof(PSNativeCommandUseErrorActionPreference); + + internal static readonly VariablePath PSNativeCommandUseErrorActionPreferenceVarPath = + new(PSNativeCommandUseErrorActionPreference); + + // Native command argument passing style + internal const string NativeArgumentPassing = "PSNativeCommandArgumentPassing"; + + internal static readonly VariablePath NativeArgumentPassingVarPath = new VariablePath(NativeArgumentPassing); + internal const string ErrorView = "ErrorView"; internal static readonly VariablePath ErrorViewVarPath = new VariablePath(ErrorView); @@ -316,46 +333,53 @@ internal static class SpecialVariables /* PSCommandPath */ typeof(string), }; - internal static readonly string[] PreferenceVariables = { - SpecialVariables.DebugPreference, - SpecialVariables.VerbosePreference, - SpecialVariables.ErrorActionPreference, - SpecialVariables.WhatIfPreference, - SpecialVariables.WarningPreference, - SpecialVariables.InformationPreference, - SpecialVariables.ConfirmPreference, - }; - - internal static readonly Type[] PreferenceVariableTypes = { - /* DebugPreference */ typeof(ActionPreference), - /* VerbosePreference */ typeof(ActionPreference), - /* ErrorPreference */ typeof(ActionPreference), - /* WhatIfPreference */ typeof(SwitchParameter), - /* WarningPreference */ typeof(ActionPreference), - /* InformationPreference */ typeof(ActionPreference), - /* ConfirmPreference */ typeof(ConfirmImpact), - }; + // This array and the one below it exist to optimize the way common parameters work in advanced functions. + // Common parameters work by setting preference variables in the scope of the function and restoring the old value afterward. + // Variables that don't correspond to common cmdlet parameters don't need to be added here. + internal static readonly string[] PreferenceVariables = + { + SpecialVariables.DebugPreference, + SpecialVariables.VerbosePreference, + SpecialVariables.ErrorActionPreference, + SpecialVariables.WhatIfPreference, + SpecialVariables.WarningPreference, + SpecialVariables.InformationPreference, + SpecialVariables.ConfirmPreference, + SpecialVariables.ProgressPreference, + }; + + internal static readonly Type[] PreferenceVariableTypes = + { + /* DebugPreference */ typeof(ActionPreference), + /* VerbosePreference */ typeof(ActionPreference), + /* ErrorPreference */ typeof(ActionPreference), + /* WhatIfPreference */ typeof(SwitchParameter), + /* WarningPreference */ typeof(ActionPreference), + /* InformationPreference */ typeof(ActionPreference), + /* ConfirmPreference */ typeof(ConfirmImpact), + /* ProgressPreference */ typeof(ActionPreference), + }; // The following variables are created in every session w/ AllScope. We avoid creating local slots when we // see an assignment to any of these variables so that they get handled properly (either throwing an exception // because they are constant/readonly, or having the value persist in parent scopes where the allscope variable // also exists. - internal static readonly string[] AllScopeVariables = { - SpecialVariables.Question, - SpecialVariables.ExecutionContext, - SpecialVariables.False, - SpecialVariables.Home, - SpecialVariables.Host, - SpecialVariables.PID, - SpecialVariables.PSCulture, - SpecialVariables.PSHome, - SpecialVariables.PSUICulture, - SpecialVariables.PSVersionTable, - SpecialVariables.PSEdition, - SpecialVariables.ShellId, - SpecialVariables.True, - SpecialVariables.EnabledExperimentalFeatures, - }; + internal static readonly Dictionary AllScopeVariables = new(StringComparer.OrdinalIgnoreCase) { + { Question, typeof(bool) }, + { ExecutionContext, typeof(EngineIntrinsics) }, + { False, typeof(bool) }, + { Home, typeof(string) }, + { Host, typeof(object) }, + { PID, typeof(int) }, + { PSCulture, typeof(string) }, + { PSHome, typeof(string) }, + { PSUICulture, typeof(string) }, + { PSVersionTable, typeof(PSVersionHashTable) }, + { PSEdition, typeof(string) }, + { ShellId, typeof(string) }, + { True, typeof(bool) }, + { EnabledExperimentalFeatures, typeof(ReadOnlyBag) } + }; private static readonly HashSet s_classMethodsAccessibleVariables = new HashSet ( @@ -368,6 +392,7 @@ internal static class SpecialVariables SpecialVariables.NestedPromptLevel, SpecialVariables.pwd, SpecialVariables.Matches, + SpecialVariables.PSApplicationOutputEncoding, }, StringComparer.OrdinalIgnoreCase ); @@ -401,5 +426,6 @@ internal enum PreferenceVariable Warning = 13, Information = 14, Confirm = 15, + Progress = 16, } } diff --git a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs deleted file mode 100644 index edc8fb272a2..00000000000 --- a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/CommandPrediction.cs +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Management.Automation.Internal; -using System.Management.Automation.Language; -using System.Threading; -using System.Threading.Tasks; - -namespace System.Management.Automation.Subsystem -{ - /// - /// The class represents the prediction result from a predictor. - /// - public sealed class PredictionResult - { - /// - /// Gets the Id of the predictor. - /// - public Guid Id { get; } - - /// - /// Gets the name of the predictor. - /// - public string Name { get; } - - /// - /// Gets the mini-session id that represents a specific invocation to the API of the predictor. - /// When it's not specified, it's considered by a client that the predictor doesn't expect feedback. - /// - public uint? Session { get; } - - /// - /// Gets the suggestions. - /// - public IReadOnlyList Suggestions { get; } - - internal PredictionResult(Guid id, string name, uint? session, List suggestions) - { - Id = id; - Name = name; - Session = session; - Suggestions = suggestions; - } - } - - /// - /// Provides a set of possible predictions for given input. - /// - public static class CommandPrediction - { - /// - /// Collect the predictive suggestions from registered predictors using the default timeout. - /// - /// Represents the client that initiates the call. - /// The object from parsing the current command line input. - /// The objects from parsing the current command line input. - /// A list of objects. - public static Task?> PredictInput(string client, Ast ast, Token[] astTokens) - { - return PredictInput(client, ast, astTokens, millisecondsTimeout: 20); - } - - /// - /// Collect the predictive suggestions from registered predictors using the specified timeout. - /// - /// Represents the client that initiates the call. - /// The object from parsing the current command line input. - /// The objects from parsing the current command line input. - /// The milliseconds to timeout. - /// A list of objects. - public static async Task?> PredictInput(string client, Ast ast, Token[] astTokens, int millisecondsTimeout) - { - Requires.Condition(millisecondsTimeout > 0, nameof(millisecondsTimeout)); - - var predictors = SubsystemManager.GetSubsystems(); - if (predictors.Count == 0) - { - return null; - } - - var context = new PredictionContext(ast, astTokens); - var tasks = new Task[predictors.Count]; - using var cancellationSource = new CancellationTokenSource(); - - for (int i = 0; i < predictors.Count; i++) - { - ICommandPredictor predictor = predictors[i]; - - tasks[i] = Task.Factory.StartNew( - state => - { - var predictor = (ICommandPredictor)state!; - SuggestionPackage pkg = predictor.GetSuggestion(client, context, cancellationSource.Token); - return pkg.SuggestionEntries?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, pkg.Session, pkg.SuggestionEntries) : null; - }, - predictor, - cancellationSource.Token, - TaskCreationOptions.DenyChildAttach, - TaskScheduler.Default); - } - - await Task.WhenAny( - Task.WhenAll(tasks), - Task.Delay(millisecondsTimeout, cancellationSource.Token)).ConfigureAwait(false); - cancellationSource.Cancel(); - - var resultList = new List(predictors.Count); - foreach (Task task in tasks) - { - if (task.IsCompletedSuccessfully) - { - PredictionResult? result = task.Result; - if (result != null) - { - resultList.Add(result); - } - } - } - - return resultList; - } - - /// - /// Allow registered predictors to do early processing when a command line is accepted. - /// - /// Represents the client that initiates the call. - /// History command lines provided as references for prediction. - public static void OnCommandLineAccepted(string client, IReadOnlyList history) - { - Requires.NotNull(history, nameof(history)); - - var predictors = SubsystemManager.GetSubsystems(); - if (predictors.Count == 0) - { - return; - } - - foreach (ICommandPredictor predictor in predictors) - { - if (predictor.SupportEarlyProcessing) - { - ThreadPool.QueueUserWorkItem( - state => state.StartEarlyProcessing(client, history), - predictor, - preferLocal: false); - } - } - } - - /// - /// Send feedback to a predictor when one or more suggestions from it were displayed to the user. - /// - /// Represents the client that initiates the call. - /// The identifier of the predictor whose prediction result was accepted. - /// The mini-session where the displayed suggestions came from. - /// - /// When the value is greater than 0, it's the number of displayed suggestions from the list returned in , starting from the index 0. - /// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value. - /// - public static void OnSuggestionDisplayed(string client, Guid predictorId, uint session, int countOrIndex) - { - var predictors = SubsystemManager.GetSubsystems(); - if (predictors.Count == 0) - { - return; - } - - foreach (ICommandPredictor predictor in predictors) - { - if (predictor.AcceptFeedback && predictor.Id == predictorId) - { - ThreadPool.QueueUserWorkItem( - state => state.OnSuggestionDisplayed(client, session, countOrIndex), - predictor, - preferLocal: false); - } - } - } - - /// - /// Send feedback to a predictor when a suggestion from it was accepted. - /// - /// Represents the client that initiates the call. - /// The identifier of the predictor whose prediction result was accepted. - /// The mini-session where the accepted suggestion came from. - /// The accepted suggestion text. - public static void OnSuggestionAccepted(string client, Guid predictorId, uint session, string suggestionText) - { - Requires.NotNullOrEmpty(suggestionText, nameof(suggestionText)); - - var predictors = SubsystemManager.GetSubsystems(); - if (predictors.Count == 0) - { - return; - } - - foreach (ICommandPredictor predictor in predictors) - { - if (predictor.AcceptFeedback && predictor.Id == predictorId) - { - ThreadPool.QueueUserWorkItem( - state => state.OnSuggestionAccepted(client, session, suggestionText), - predictor, - preferLocal: false); - } - } - } - } -} diff --git a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs deleted file mode 100644 index d55d37a90df..00000000000 --- a/src/System.Management.Automation/engine/Subsystem/CommandPrediction/ICommandPredictor.cs +++ /dev/null @@ -1,221 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Management.Automation.Internal; -using System.Management.Automation.Language; -using System.Threading; - -namespace System.Management.Automation.Subsystem -{ - /// - /// Interface for implementing a predictor plugin. - /// - public interface ICommandPredictor : ISubsystem - { - /// - /// Default implementation. No function is required for a predictor. - /// - Dictionary? ISubsystem.FunctionsToDefine => null; - - /// - /// Default implementation for `ISubsystem.Kind`. - /// - SubsystemKind ISubsystem.Kind => SubsystemKind.CommandPredictor; - - /// - /// Gets a value indicating whether the predictor supports early processing. - /// - bool SupportEarlyProcessing { get; } - - /// - /// Gets a value indicating whether the predictor accepts feedback about the previous suggestion. - /// - bool AcceptFeedback { get; } - - /// - /// A command line was accepted to execute. - /// The predictor can start processing early as needed with the latest history. - /// - /// Represents the client that initiates the call. - /// History command lines provided as references for prediction. - void StartEarlyProcessing(string clientId, IReadOnlyList history); - - /// - /// Get the predictive suggestions. It indicates the start of a suggestion rendering session. - /// - /// Represents the client that initiates the call. - /// The object to be used for prediction. - /// The cancellation token to cancel the prediction. - /// An instance of . - SuggestionPackage GetSuggestion(string clientId, PredictionContext context, CancellationToken cancellationToken); - - /// - /// One or more suggestions provided by the predictor were displayed to the user. - /// - /// Represents the client that initiates the call. - /// The mini-session where the displayed suggestions came from. - /// - /// When the value is greater than 0, it's the number of displayed suggestions from the list returned in , starting from the index 0. - /// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value. - /// - void OnSuggestionDisplayed(string clientId, uint session, int countOrIndex); - - /// - /// The suggestion provided by the predictor was accepted. - /// - /// Represents the client that initiates the call. - /// Represents the mini-session where the accepted suggestion came from. - /// The accepted suggestion text. - void OnSuggestionAccepted(string clientId, uint session, string acceptedSuggestion); - } - - /// - /// Context information about the user input. - /// - public class PredictionContext - { - /// - /// Gets the abstract syntax tree (AST) generated from parsing the user input. - /// - public Ast InputAst { get; } - - /// - /// Gets the tokens generated from parsing the user input. - /// - public IReadOnlyList InputTokens { get; } - - /// - /// Gets the cursor position, which is assumed always at the end of the input line. - /// - public IScriptPosition CursorPosition { get; } - - /// - /// Gets the token at the cursor. - /// - public Token? TokenAtCursor { get; } - - /// - /// Gets all ASTs that are related to the cursor position, - /// which is assumed always at the end of the input line. - /// - public IReadOnlyList RelatedAsts { get; } - - /// - /// Initializes a new instance of the class from the AST and tokens that represent the user input. - /// - /// The object from parsing the current command line input. - /// The objects from parsing the current command line input. - public PredictionContext(Ast inputAst, Token[] inputTokens) - { - Requires.NotNull(inputAst, nameof(inputAst)); - Requires.NotNull(inputTokens, nameof(inputTokens)); - - var cursor = inputAst.Extent.EndScriptPosition; - var astContext = CompletionAnalysis.ExtractAstContext(inputAst, inputTokens, cursor); - - InputAst = inputAst; - InputTokens = inputTokens; - CursorPosition = cursor; - TokenAtCursor = astContext.TokenAtCursor; - RelatedAsts = astContext.RelatedAsts; - } - - /// - /// Creates a context instance from the user input line. - /// - /// The user input. - /// A object. - public static PredictionContext Create(string input) - { - Requires.NotNullOrEmpty(input, nameof(input)); - - Ast ast = Parser.ParseInput(input, out Token[] tokens, out _); - return new PredictionContext(ast, tokens); - } - } - - /// - /// The class represents a predictive suggestion generated by a predictor. - /// - public sealed class PredictiveSuggestion - { - /// - /// Gets the suggestion. - /// - public string SuggestionText { get; } - - /// - /// Gets the tooltip of the suggestion. - /// - public string? ToolTip { get; } - - /// - /// Initializes a new instance of the class. - /// - /// The predictive suggestion text. - public PredictiveSuggestion(string suggestion) - : this(suggestion, toolTip: null) - { - } - - /// - /// Initializes a new instance of the class. - /// - /// The predictive suggestion text. - /// The tooltip of the suggestion. - public PredictiveSuggestion(string suggestion, string? toolTip) - { - Requires.NotNullOrEmpty(suggestion, nameof(suggestion)); - - SuggestionText = suggestion; - ToolTip = toolTip; - } - } - - /// - /// A package returned from . - /// - public struct SuggestionPackage - { - /// - /// Gets the mini-session that represents a specific invocation to . - /// When it's not specified, it's considered by a client that the predictor doesn't expect feedback. - /// - public uint? Session { get; } - - /// - /// Gets the suggestion entries returned from that mini-session. - /// - public List? SuggestionEntries { get; } - - /// - /// Initializes a new instance of the struct without providing a session id. - /// Note that, when a session id is not specified, it's considered by a client that the predictor doesn't expect feedback. - /// - /// The suggestions to return. - public SuggestionPackage(List suggestionEntries) - { - Requires.NotNullOrEmpty(suggestionEntries, nameof(suggestionEntries)); - - Session = null; - SuggestionEntries = suggestionEntries; - } - - /// - /// Initializes a new instance of the struct with the mini-session id and the suggestions. - /// - /// The mini-session where suggestions came from. - /// The suggestions to return. - public SuggestionPackage(uint session, List suggestionEntries) - { - Requires.NotNullOrEmpty(suggestionEntries, nameof(suggestionEntries)); - - Session = session; - SuggestionEntries = suggestionEntries; - } - } -} diff --git a/src/System.Management.Automation/engine/Subsystem/Commands/GetPSSubsystemCommand.cs b/src/System.Management.Automation/engine/Subsystem/Commands/GetPSSubsystemCommand.cs index 1ad79404f51..df828c724a2 100644 --- a/src/System.Management.Automation/engine/Subsystem/Commands/GetPSSubsystemCommand.cs +++ b/src/System.Management.Automation/engine/Subsystem/Commands/GetPSSubsystemCommand.cs @@ -8,7 +8,6 @@ namespace System.Management.Automation.Subsystem /// /// Implementation of 'Get-PSSubsystem' cmdlet. /// - [Experimental("PSSubsystemPluginModel", ExperimentAction.Show)] [Cmdlet(VerbsCommon.Get, "PSSubsystem", DefaultParameterSetName = AllSet)] [OutputType(typeof(SubsystemInfo))] public sealed class GetPSSubsystemCommand : PSCmdlet diff --git a/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs b/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs new file mode 100644 index 00000000000..d1fe2234309 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/DscSubsystem/ICrossPlatformDsc.cs @@ -0,0 +1,48 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.ObjectModel; +using System.Collections.Generic; +using System.Management.Automation.Language; + +namespace System.Management.Automation.Subsystem.DSC +{ + /// + /// Interface for implementing a cross platform desired state configuration component. + /// + public interface ICrossPlatformDsc : ISubsystem + { + /// + /// Default implementation. No function is required for this subsystem. + /// + Dictionary? ISubsystem.FunctionsToDefine => null; + + /// + /// DSC initializer function. + /// + void LoadDefaultKeywords(Collection errors); + + /// + /// Clear internal class caches. + /// + void ClearCache(); + + /// + /// Returns resource usage string. + /// + string GetDSCResourceUsageString(DynamicKeyword keyword); + + /// + /// Checks if a string is one of dynamic keywords that can be used in both configuration and meta configuration. + /// + bool IsSystemResourceName(string name); + + /// + /// Checks if a string matches default module name used for meta configuration resources. + /// + bool IsDefaultModuleNameForMetaConfigResource(string name); + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs new file mode 100644 index 00000000000..b1aa781fea7 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/FeedbackHub.cs @@ -0,0 +1,315 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; +using System.Management.Automation.Language; +using System.Management.Automation.Runspaces; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.PowerShell.Commands; + +namespace System.Management.Automation.Subsystem.Feedback +{ + /// + /// The class represents a result from a feedback provider. + /// + public class FeedbackResult + { + /// + /// Gets the Id of the feedback provider. + /// + public Guid Id { get; } + + /// + /// Gets the name of the feedback provider. + /// + public string Name { get; } + + /// + /// Gets the feedback item. + /// + public FeedbackItem Item { get; } + + internal FeedbackResult(Guid id, string name, FeedbackItem item) + { + Id = id; + Name = name; + Item = item; + } + } + + /// + /// Provides a set of feedbacks for given input. + /// + public static class FeedbackHub + { + /// + /// Collect the feedback from registered feedback providers using the default timeout. + /// + public static List? GetFeedback(Runspace runspace) + { + return GetFeedback(runspace, millisecondsTimeout: 1000); + } + + /// + /// Collect the feedback from registered feedback providers using the specified timeout. + /// + public static List? GetFeedback(Runspace runspace, int millisecondsTimeout) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(millisecondsTimeout); + + if (runspace is not LocalRunspace localRunspace) + { + return null; + } + + var providers = SubsystemManager.GetSubsystems(); + if (providers.Count is 0) + { + return null; + } + + ExecutionContext executionContext = localRunspace.ExecutionContext; + bool questionMarkValue = executionContext.QuestionMarkVariableValue; + + // The command line would have run successfully in most cases during an interactive use of the shell. + // So, we do a quick check to see whether we can skip proceeding, so as to avoid unneeded allocations + // from the 'TryGetFeedbackContext' call below. + if (questionMarkValue && CanSkip(providers)) + { + return null; + } + + // Get the last history item + HistoryInfo[] histories = localRunspace.History.GetEntries(id: 0, count: 1, newest: true); + if (histories.Length is 0) + { + return null; + } + + // Try creating the feedback context object. + if (!TryGetFeedbackContext(executionContext, questionMarkValue, histories[0], out FeedbackContext? feedbackContext)) + { + return null; + } + + int count = providers.Count; + IFeedbackProvider? generalFeedback = null; + List>? tasks = null; + CancellationTokenSource? cancellationSource = null; + Func? callBack = null; + + foreach (IFeedbackProvider provider in providers) + { + if (!provider.Trigger.HasFlag(feedbackContext.Trigger)) + { + continue; + } + + if (provider is GeneralCommandErrorFeedback) + { + // This built-in feedback provider needs to run on the target Runspace. + generalFeedback = provider; + continue; + } + + if (tasks is null) + { + tasks = new List>(capacity: count); + cancellationSource = new CancellationTokenSource(); + callBack = GetCallBack(feedbackContext, cancellationSource); + } + + // Other feedback providers will run on background threads in parallel. + tasks.Add(Task.Factory.StartNew( + callBack!, + provider, + cancellationSource!.Token, + TaskCreationOptions.DenyChildAttach, + TaskScheduler.Default)); + } + + Task? waitTask = null; + if (tasks is not null) + { + waitTask = Task.WhenAny( + Task.WhenAll(tasks), + Task.Delay(millisecondsTimeout, cancellationSource!.Token)); + } + + List? resultList = null; + if (generalFeedback is not null) + { + FeedbackResult? builtInResult = GetBuiltInFeedback(generalFeedback, localRunspace, feedbackContext, questionMarkValue); + if (builtInResult is not null) + { + resultList ??= new List(count); + resultList.Add(builtInResult); + } + } + + if (waitTask is not null) + { + try + { + waitTask.Wait(); + cancellationSource!.Cancel(); + + foreach (Task task in tasks!) + { + if (task.IsCompletedSuccessfully) + { + FeedbackResult? result = task.Result; + if (result is not null) + { + resultList ??= new List(count); + resultList.Add(result); + } + } + } + } + finally + { + cancellationSource!.Dispose(); + } + } + + return resultList; + } + + private static bool CanSkip(IEnumerable providers) + { + bool canSkip = true; + foreach (IFeedbackProvider provider in providers) + { + if (provider.Trigger.HasFlag(FeedbackTrigger.Success)) + { + canSkip = false; + break; + } + } + + return canSkip; + } + + private static FeedbackResult? GetBuiltInFeedback( + IFeedbackProvider builtInFeedback, + LocalRunspace localRunspace, + FeedbackContext feedbackContext, + bool questionMarkValue) + { + bool changedDefault = false; + Runspace? oldDefault = Runspace.DefaultRunspace; + + try + { + if (oldDefault != localRunspace) + { + changedDefault = true; + Runspace.DefaultRunspace = localRunspace; + } + + FeedbackItem? item = builtInFeedback.GetFeedback(feedbackContext, CancellationToken.None); + if (item is not null) + { + return new FeedbackResult(builtInFeedback.Id, builtInFeedback.Name, item); + } + } + finally + { + if (changedDefault) + { + Runspace.DefaultRunspace = oldDefault; + } + + // Restore $? for the target Runspace. + localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkValue; + } + + return null; + } + + private static bool TryGetFeedbackContext( + ExecutionContext executionContext, + bool questionMarkValue, + HistoryInfo lastHistory, + [NotNullWhen(true)] out FeedbackContext? feedbackContext) + { + feedbackContext = null; + Ast ast = Parser.ParseInput(lastHistory.CommandLine, out Token[] tokens, out _); + + FeedbackTrigger trigger; + ErrorRecord? lastError = null; + + if (IsPureComment(tokens)) + { + // Don't trigger anything in this case. + return false; + } + else if (questionMarkValue) + { + trigger = FeedbackTrigger.Success; + } + else if (TryGetLastError(executionContext, lastHistory, out lastError)) + { + trigger = lastError.FullyQualifiedErrorId is "CommandNotFoundException" + ? FeedbackTrigger.CommandNotFound + : FeedbackTrigger.Error; + } + else + { + return false; + } + + PathInfo cwd = executionContext.SessionState.Path.CurrentLocation; + feedbackContext = new(trigger, ast, tokens, cwd, lastError); + return true; + } + + private static bool IsPureComment(Token[] tokens) + { + return tokens.Length is 2 && tokens[0].Kind is TokenKind.Comment && tokens[1].Kind is TokenKind.EndOfInput; + } + + private static bool TryGetLastError(ExecutionContext context, HistoryInfo lastHistory, [NotNullWhen(true)] out ErrorRecord? lastError) + { + lastError = null; + ArrayList errorList = (ArrayList)context.DollarErrorVariable; + if (errorList.Count == 0) + { + return false; + } + + lastError = errorList[0] as ErrorRecord; + if (lastError is null && errorList[0] is RuntimeException rtEx) + { + lastError = rtEx.ErrorRecord; + } + + if (lastError?.InvocationInfo is null || lastError.InvocationInfo.HistoryId != lastHistory.Id) + { + return false; + } + + return true; + } + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no feedback provider is registered. + private static Func GetCallBack( + FeedbackContext feedbackContext, + CancellationTokenSource cancellationSource) + { + return state => + { + var provider = (IFeedbackProvider)state!; + var item = provider.GetFeedback(feedbackContext, cancellationSource.Token); + return item is null ? null : new FeedbackResult(provider.Id, provider.Name, item); + }; + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs new file mode 100644 index 00000000000..0af184f4e99 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/FeedbackSubsystem/IFeedbackProvider.cs @@ -0,0 +1,303 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System.Collections.Generic; +using System.IO; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Management.Automation.Runspaces; +using System.Threading; +using Microsoft.PowerShell.Telemetry; + +namespace System.Management.Automation.Subsystem.Feedback +{ + /// + /// Types of trigger for the feedback provider. + /// + [Flags] + public enum FeedbackTrigger + { + /// + /// The last command line executed successfully. + /// + Success = 0x0001, + + /// + /// The last command line failed due to a command-not-found error. + /// This is a special case of . + /// + CommandNotFound = 0x0002, + + /// + /// The last command line failed with an error record. + /// This includes the case of command-not-found error. + /// + Error = CommandNotFound | 0x0004, + + /// + /// All possible triggers. + /// + All = Success | Error + } + + /// + /// Layout for displaying the recommended actions. + /// + public enum FeedbackDisplayLayout + { + /// + /// Display one recommended action per row. + /// + Portrait, + + /// + /// Display all recommended actions in the same row. + /// + Landscape, + } + + /// + /// Context information about the last command line. + /// + public sealed class FeedbackContext + { + /// + /// Gets the feedback trigger. + /// + public FeedbackTrigger Trigger { get; } + + /// + /// Gets the last command line that was just executed. + /// + public string CommandLine { get; } + + /// + /// Gets the abstract syntax tree (AST) generated from parsing the last command line. + /// + public Ast CommandLineAst { get; } + + /// + /// Gets the tokens generated from parsing the last command line. + /// + public IReadOnlyList CommandLineTokens { get; } + + /// + /// Gets the current location of the default session. + /// + public PathInfo CurrentLocation { get; } + + /// + /// Gets the last error record generated from executing the last command line. + /// + public ErrorRecord? LastError { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The trigger of this feedback call. + /// The command line that was just executed. + /// The current location of the default session. + /// The error that was triggerd by the last command line. + public FeedbackContext(FeedbackTrigger trigger, string commandLine, PathInfo cwd, ErrorRecord? lastError) + { + ArgumentException.ThrowIfNullOrEmpty(commandLine); + ArgumentNullException.ThrowIfNull(cwd); + + Trigger = trigger; + CommandLine = commandLine; + CommandLineAst = Parser.ParseInput(commandLine, out Token[] tokens, out _); + CommandLineTokens = tokens; + LastError = lastError; + CurrentLocation = cwd; + } + + /// + /// Initializes a new instance of the class. + /// + /// The trigger of this feedback call. + /// The abstract syntax tree (AST) from parsing the last command line. + /// The tokens from parsing the last command line. + /// The current location of the default session. + /// The error that was triggerd by the last command line. + public FeedbackContext(FeedbackTrigger trigger, Ast commandLineAst, Token[] commandLineTokens, PathInfo cwd, ErrorRecord? lastError) + { + ArgumentNullException.ThrowIfNull(commandLineAst); + ArgumentNullException.ThrowIfNull(commandLineTokens); + ArgumentNullException.ThrowIfNull(cwd); + + Trigger = trigger; + CommandLine = commandLineAst.Extent.Text; + CommandLineAst = commandLineAst; + CommandLineTokens = commandLineTokens; + LastError = lastError; + CurrentLocation = cwd; + } + } + + /// + /// The class represents a feedback item generated by the feedback provider. + /// + public sealed class FeedbackItem + { + /// + /// Gets the description message about this feedback. + /// + public string Header { get; } + + /// + /// Gets the footer message about this feedback. + /// + public string? Footer { get; } + + /// + /// Gets the recommended actions -- command lines or even code snippets to run. + /// + public List? RecommendedActions { get; } + + /// + /// Gets the layout to use for displaying the recommended actions. + /// + public FeedbackDisplayLayout Layout { get; } + + /// + /// Gets or sets the next feedback item, if there is one. + /// + public FeedbackItem? Next { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// The description message (must be not null or empty). + /// The recommended actions to take (optional). + public FeedbackItem(string header, List? actions) + : this(header, actions, footer: null, FeedbackDisplayLayout.Portrait) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The description message (must be not null or empty). + /// The recommended actions to take (optional). + /// The layout for displaying the actions. + public FeedbackItem(string header, List? actions, FeedbackDisplayLayout layout) + : this(header, actions, footer: null, layout) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The description message (must be not null or empty). + /// The recommended actions to take (optional). + /// The footer message (optional). + /// The layout for displaying the actions. + public FeedbackItem(string header, List? actions, string? footer, FeedbackDisplayLayout layout) + { + ArgumentException.ThrowIfNullOrEmpty(header); + + Header = header; + RecommendedActions = actions; + Footer = footer; + Layout = layout; + } + } + + /// + /// Interface for implementing a feedback provider on command failures. + /// + public interface IFeedbackProvider : ISubsystem + { + /// + /// Default implementation. No function is required for a feedback provider. + /// + Dictionary? ISubsystem.FunctionsToDefine => null; + + /// + /// Gets the types of trigger for this feedback provider. + /// + /// + /// The default implementation triggers a feedback provider by only. + /// + FeedbackTrigger Trigger => FeedbackTrigger.CommandNotFound; + + /// + /// Gets feedback based on the given commandline and error record. + /// + /// The context for the feedback call. + /// The cancellation token to cancel the operation. + /// The feedback item. + FeedbackItem? GetFeedback(FeedbackContext context, CancellationToken token); + } + + internal sealed class GeneralCommandErrorFeedback : IFeedbackProvider + { + private readonly Guid _guid; + + internal GeneralCommandErrorFeedback() + { + _guid = new Guid("A3C6B07E-4A89-40C9-8BE6-2A9AAD2786A4"); + } + + public Guid Id => _guid; + + public string Name => "General Feedback"; + + public string Description => "The built-in general feedback source for command errors."; + + public FeedbackItem? GetFeedback(FeedbackContext context, CancellationToken token) + { + var rsToUse = Runspace.DefaultRunspace; + if (rsToUse is null) + { + return null; + } + + // This feedback provider is only triggered by 'CommandNotFound' error, so the + // 'LastError' property is guaranteed to be not null. + ErrorRecord lastError = context.LastError!; + SessionState sessionState = rsToUse.ExecutionContext.SessionState; + + var target = (string)lastError.TargetObject; + CommandInvocationIntrinsics invocation = sessionState.InvokeCommand; + + // See if target is actually an executable file in current directory. + var localTarget = Path.Combine(".", target); + var command = invocation.GetCommand( + localTarget, + CommandTypes.Application | CommandTypes.ExternalScript); + + if (command is not null) + { + return new FeedbackItem( + StringUtil.Format(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory, target), + new List { localTarget }); + } + + // Check fuzzy matching command names. + var pwsh = PowerShell.Create(RunspaceMode.CurrentRunspace); + var results = pwsh.AddCommand("Get-Command") + .AddParameter("UseFuzzyMatching") + .AddParameter("FuzzyMinimumDistance", 1) + .AddParameter("Name", target) + .AddCommand("Select-Object") + .AddParameter("First", 5) + .AddParameter("Unique") + .AddParameter("ExpandProperty", "Name") + .Invoke(); + + if (results.Count > 0) + { + ApplicationInsightsTelemetry.SendUseTelemetry("FuzzyMatching", "CommandNotFound"); + return new FeedbackItem( + SuggestionStrings.Suggestion_CommandNotFound, + new List(results), + FeedbackDisplayLayout.Landscape); + } + + return null; + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs index e19f37f06c7..72b8a55d148 100644 --- a/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs +++ b/src/System.Management.Automation/engine/Subsystem/ISubsystem.cs @@ -11,12 +11,26 @@ namespace System.Management.Automation.Subsystem /// /// Define the kinds of subsystems. /// - public enum SubsystemKind + /// + /// This enum uses power of 2 as the values for the enum elements, so as to make sure + /// the bitwise 'or' operation of the elements always results in an invalid value. + /// + public enum SubsystemKind : uint { /// /// Component that provides predictive suggestions to commandline input. /// CommandPredictor = 1, + + /// + /// Cross platform desired state configuration component. + /// + CrossPlatformDsc = 2, + + /// + /// Component that provides feedback when a command fails interactively. + /// + FeedbackProvider = 4, } /// @@ -24,12 +38,8 @@ public enum SubsystemKind /// The API contracts for specific subsystems are defined within the specific interfaces/abstract classes that implements this interface. /// /// - /// There are two purposes to have the internal member `Kind` declared in 'ISubsystem': - /// 1. Make the mapping from an `ISubsystem` implementation to the `SubsystemKind` easy; - /// 2. Make sure a user cannot directly implement 'ISubsystem', but have to derive from one of the concrete subsystem interface or abstract class. - /// - /// The internal member needs to have a default implementation defined by the specific subsystem interfaces or abstract class, - /// because it should be the same for a specific kind of subsystem. + /// A user should not directly implement , but instead should derive from one of the concrete subsystem interfaces or abstract classes. + /// The instance of a type that only implements 'ISubsystem' cannot be registered to the . /// public interface ISubsystem { @@ -53,10 +63,5 @@ public interface ISubsystem /// Key: function name; Value: function script. /// Dictionary? FunctionsToDefine { get; } - - /// - /// Gets the subsystem kind. - /// - internal SubsystemKind Kind { get; } } } diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs new file mode 100644 index 00000000000..edb46960612 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/CommandPrediction.cs @@ -0,0 +1,281 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Management.Automation.Language; +using System.Threading; +using System.Threading.Tasks; + +namespace System.Management.Automation.Subsystem.Prediction +{ + /// + /// The class represents the prediction result from a predictor. + /// + public sealed class PredictionResult + { + /// + /// Gets the Id of the predictor. + /// + public Guid Id { get; } + + /// + /// Gets the name of the predictor. + /// + public string Name { get; } + + /// + /// Gets the mini-session id that represents a specific invocation to the API of the predictor. + /// When it's not specified, it's considered by a client that the predictor doesn't expect feedback. + /// + public uint? Session { get; } + + /// + /// Gets the suggestions. + /// + public IReadOnlyList Suggestions { get; } + + internal PredictionResult(Guid id, string name, uint? session, List suggestions) + { + Id = id; + Name = name; + Session = session; + Suggestions = suggestions; + } + } + + /// + /// Provides a set of possible predictions for given input. + /// + public static class CommandPrediction + { + /// + /// Collect the predictive suggestions from registered predictors using the default timeout. + /// + /// Represents the client that initiates the call. + /// The object from parsing the current command line input. + /// The objects from parsing the current command line input. + /// A list of objects. + public static Task?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens) + { + return PredictInputAsync(client, ast, astTokens, millisecondsTimeout: 20); + } + + /// + /// Collect the predictive suggestions from registered predictors using the specified timeout. + /// + /// Represents the client that initiates the call. + /// The object from parsing the current command line input. + /// The objects from parsing the current command line input. + /// The milliseconds to timeout. + /// A list of objects. + public static async Task?> PredictInputAsync(PredictionClient client, Ast ast, Token[] astTokens, int millisecondsTimeout) + { + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(millisecondsTimeout); + + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return null; + } + + var context = new PredictionContext(ast, astTokens); + var tasks = new Task[predictors.Count]; + using var cancellationSource = new CancellationTokenSource(); + + Func callBack = GetCallBack(client, context, cancellationSource); + + for (int i = 0; i < predictors.Count; i++) + { + ICommandPredictor predictor = predictors[i]; + tasks[i] = Task.Factory.StartNew( + callBack, + predictor, + cancellationSource.Token, + TaskCreationOptions.DenyChildAttach, + TaskScheduler.Default); + } + + await Task.WhenAny( + Task.WhenAll(tasks), + Task.Delay(millisecondsTimeout, cancellationSource.Token)).ConfigureAwait(false); + cancellationSource.Cancel(); + + var resultList = new List(predictors.Count); + foreach (Task task in tasks) + { + if (task.IsCompletedSuccessfully) + { + PredictionResult? result = task.Result; + if (result != null) + { + resultList.Add(result); + } + } + } + + return resultList; + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no predictor is registered. + static Func GetCallBack( + PredictionClient client, + PredictionContext context, + CancellationTokenSource cancellationSource) + { + return state => + { + var predictor = (ICommandPredictor)state!; + SuggestionPackage pkg = predictor.GetSuggestion(client, context, cancellationSource.Token); + return pkg.SuggestionEntries?.Count > 0 ? new PredictionResult(predictor.Id, predictor.Name, pkg.Session, pkg.SuggestionEntries) : null; + }; + } + } + + /// + /// Allow registered predictors to do early processing when a command line is accepted. + /// + /// Represents the client that initiates the call. + /// History command lines provided as references for prediction. + public static void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) + { + ArgumentNullException.ThrowIfNull(history); + + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return; + } + + Action? callBack = null; + foreach (ICommandPredictor predictor in predictors) + { + if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.CommandLineAccepted)) + { + callBack ??= GetCallBack(client, history); + ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); + } + } + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no predictor is registered, or no registered predictor accepts this feedback. + static Action GetCallBack(PredictionClient client, IReadOnlyList history) + { + return predictor => predictor.OnCommandLineAccepted(client, history); + } + } + + /// + /// Allow registered predictors to know the execution result (success/failure) of the last accepted command line. + /// + /// Represents the client that initiates the call. + /// The last accepted command line. + /// Whether the execution of the last command line was successful. + public static void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) + { + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return; + } + + Action? callBack = null; + foreach (ICommandPredictor predictor in predictors) + { + if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.CommandLineExecuted)) + { + callBack ??= GetCallBack(client, commandLine, success); + ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); + } + } + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no predictor is registered, or no registered predictor accepts this feedback. + static Action GetCallBack(PredictionClient client, string commandLine, bool success) + { + return predictor => predictor.OnCommandLineExecuted(client, commandLine, success); + } + } + + /// + /// Send feedback to a predictor when one or more suggestions from it were displayed to the user. + /// + /// Represents the client that initiates the call. + /// The identifier of the predictor whose prediction result was accepted. + /// The mini-session where the displayed suggestions came from. + /// + /// When the value is greater than 0, it's the number of displayed suggestions from the list returned in , starting from the index 0. + /// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value. + /// + public static void OnSuggestionDisplayed(PredictionClient client, Guid predictorId, uint session, int countOrIndex) + { + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return; + } + + foreach (ICommandPredictor predictor in predictors) + { + if (predictor.Id == predictorId) + { + if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.SuggestionDisplayed)) + { + Action callBack = GetCallBack(client, session, countOrIndex); + ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); + } + + break; + } + } + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no predictor is registered, or no registered predictor accepts this feedback. + static Action GetCallBack(PredictionClient client, uint session, int countOrIndex) + { + return predictor => predictor.OnSuggestionDisplayed(client, session, countOrIndex); + } + } + + /// + /// Send feedback to a predictor when a suggestion from it was accepted. + /// + /// Represents the client that initiates the call. + /// The identifier of the predictor whose prediction result was accepted. + /// The mini-session where the accepted suggestion came from. + /// The accepted suggestion text. + public static void OnSuggestionAccepted(PredictionClient client, Guid predictorId, uint session, string suggestionText) + { + ArgumentException.ThrowIfNullOrEmpty(suggestionText); + + var predictors = SubsystemManager.GetSubsystems(); + if (predictors.Count == 0) + { + return; + } + + foreach (ICommandPredictor predictor in predictors) + { + if (predictor.Id == predictorId) + { + if (predictor.CanAcceptFeedback(client, PredictorFeedbackKind.SuggestionAccepted)) + { + Action callBack = GetCallBack(client, session, suggestionText); + ThreadPool.QueueUserWorkItem(callBack, predictor, preferLocal: false); + } + + break; + } + } + + // A local helper function to avoid creating an instance of the generated delegate helper class + // when no predictor is registered, or no registered predictor accepts this feedback. + static Action GetCallBack(PredictionClient client, uint session, string suggestionText) + { + return predictor => predictor.OnSuggestionAccepted(client, session, suggestionText); + } + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs new file mode 100644 index 00000000000..275dc1733b6 --- /dev/null +++ b/src/System.Management.Automation/engine/Subsystem/PredictionSubsystem/ICommandPredictor.cs @@ -0,0 +1,297 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Management.Automation.Internal; +using System.Management.Automation.Language; +using System.Threading; + +namespace System.Management.Automation.Subsystem.Prediction +{ + /// + /// Interface for implementing a predictor plugin. + /// + public interface ICommandPredictor : ISubsystem + { + /// + /// Default implementation. No function is required for a predictor. + /// + Dictionary? ISubsystem.FunctionsToDefine => null; + + /// + /// Get the predictive suggestions. It indicates the start of a suggestion rendering session. + /// + /// Represents the client that initiates the call. + /// The object to be used for prediction. + /// The cancellation token to cancel the prediction. + /// An instance of . + SuggestionPackage GetSuggestion(PredictionClient client, PredictionContext context, CancellationToken cancellationToken); + + /// + /// Gets a value indicating whether the predictor accepts a specific kind of feedback. + /// + /// Represents the client that initiates the call. + /// A specific type of feedback. + /// True or false, to indicate whether the specific feedback is accepted. + bool CanAcceptFeedback(PredictionClient client, PredictorFeedbackKind feedback) => false; + + /// + /// One or more suggestions provided by the predictor were displayed to the user. + /// + /// Represents the client that initiates the call. + /// The mini-session where the displayed suggestions came from. + /// + /// When the value is greater than 0, it's the number of displayed suggestions from the list returned in , starting from the index 0. + /// When the value is less than or equal to 0, it means a single suggestion from the list got displayed, and the index is the absolute value. + /// + void OnSuggestionDisplayed(PredictionClient client, uint session, int countOrIndex) { } + + /// + /// The suggestion provided by the predictor was accepted. + /// + /// Represents the client that initiates the call. + /// Represents the mini-session where the accepted suggestion came from. + /// The accepted suggestion text. + void OnSuggestionAccepted(PredictionClient client, uint session, string acceptedSuggestion) { } + + /// + /// A command line was accepted to execute. + /// The predictor can start processing early as needed with the latest history. + /// + /// Represents the client that initiates the call. + /// History command lines provided as references for prediction. + void OnCommandLineAccepted(PredictionClient client, IReadOnlyList history) { } + + /// + /// A command line was done execution. + /// + /// Represents the client that initiates the call. + /// The last accepted command line. + /// Shows whether the execution was successful. + void OnCommandLineExecuted(PredictionClient client, string commandLine, bool success) { } + } + + /// + /// Kinds of feedback a predictor can choose to accept. + /// + public enum PredictorFeedbackKind + { + /// + /// Feedback when one or more suggestions are displayed to the user. + /// + SuggestionDisplayed, + + /// + /// Feedback when a suggestion is accepted by the user. + /// + SuggestionAccepted, + + /// + /// Feedback when a command line is accepted by the user. + /// + CommandLineAccepted, + + /// + /// Feedback when the accepted command line finishes its execution. + /// + CommandLineExecuted, + } + + /// + /// Kinds of prediction clients. + /// + public enum PredictionClientKind + { + /// + /// A terminal client, representing the command-line experience. + /// + Terminal, + + /// + /// An editor client, representing the editor experience. + /// + Editor, + } + + /// + /// The class represents a client that interacts with predictors. + /// + public sealed class PredictionClient + { + /// + /// Gets the client name. + /// + public string Name { get; } + + /// + /// Gets the client kind. + /// + public PredictionClientKind Kind { get; } + + /// + /// Gets the current location of the default session. + /// It returns null if there is no default Runspace or if the default is a remote Runspace. + /// + public PathInfo? CurrentLocation { get; set; } + + /// + /// Initializes a new instance of the class. + /// + /// Name of the interactive client. + /// Kind of the interactive client. + public PredictionClient(string name, PredictionClientKind kind) + { + Name = name; + Kind = kind; + } + } + + /// + /// Context information about the user input. + /// + public sealed class PredictionContext + { + /// + /// Gets the abstract syntax tree (AST) generated from parsing the user input. + /// + public Ast InputAst { get; } + + /// + /// Gets the tokens generated from parsing the user input. + /// + public IReadOnlyList InputTokens { get; } + + /// + /// Gets the cursor position, which is assumed always at the end of the input line. + /// + public IScriptPosition CursorPosition { get; } + + /// + /// Gets the token at the cursor. + /// + public Token? TokenAtCursor { get; } + + /// + /// Gets all ASTs that are related to the cursor position, + /// which is assumed always at the end of the input line. + /// + public IReadOnlyList RelatedAsts { get; } + + /// + /// Initializes a new instance of the class from the AST and tokens that represent the user input. + /// + /// The object from parsing the current command line input. + /// The objects from parsing the current command line input. + public PredictionContext(Ast inputAst, Token[] inputTokens) + { + ArgumentNullException.ThrowIfNull(inputAst); + ArgumentNullException.ThrowIfNull(inputTokens); + + var cursor = inputAst.Extent.EndScriptPosition; + var astContext = CompletionAnalysis.ExtractAstContext(inputAst, inputTokens, cursor); + + InputAst = inputAst; + InputTokens = inputTokens; + CursorPosition = cursor; + TokenAtCursor = astContext.TokenAtCursor; + RelatedAsts = astContext.RelatedAsts; + } + + /// + /// Creates a context instance from the user input line. + /// + /// The user input. + /// A object. + public static PredictionContext Create(string input) + { + ArgumentException.ThrowIfNullOrEmpty(input); + + Ast ast = Parser.ParseInput(input, out Token[] tokens, out _); + return new PredictionContext(ast, tokens); + } + } + + /// + /// The class represents a predictive suggestion generated by a predictor. + /// + public sealed class PredictiveSuggestion + { + /// + /// Gets the suggestion. + /// + public string SuggestionText { get; } + + /// + /// Gets the tooltip of the suggestion. + /// + public string? ToolTip { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The predictive suggestion text. + public PredictiveSuggestion(string suggestion) + : this(suggestion, toolTip: null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The predictive suggestion text. + /// The tooltip of the suggestion. + public PredictiveSuggestion(string suggestion, string? toolTip) + { + ArgumentException.ThrowIfNullOrEmpty(suggestion); + + SuggestionText = suggestion; + ToolTip = toolTip; + } + } + + /// + /// A package returned from . + /// + public struct SuggestionPackage + { + /// + /// Gets the mini-session that represents a specific invocation to . + /// When it's not specified, it's considered by a client that the predictor doesn't expect feedback. + /// + public uint? Session { get; } + + /// + /// Gets the suggestion entries returned from that mini-session. + /// + public List? SuggestionEntries { get; } + + /// + /// Initializes a new instance of the struct without providing a session id. + /// Note that, when a session id is not specified, it's considered by a client that the predictor doesn't expect feedback. + /// + /// The suggestions to return. + public SuggestionPackage(List suggestionEntries) + { + Requires.NotNullOrEmpty(suggestionEntries, nameof(suggestionEntries)); + + Session = null; + SuggestionEntries = suggestionEntries; + } + + /// + /// Initializes a new instance of the struct with the mini-session id and the suggestions. + /// + /// The mini-session where suggestions came from. + /// The suggestions to return. + public SuggestionPackage(uint session, List suggestionEntries) + { + Requires.NotNullOrEmpty(suggestionEntries, nameof(suggestionEntries)); + + Session = session; + SuggestionEntries = suggestionEntries; + } + } +} diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs index 24adf990d9e..8756fd69c9b 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemInfo.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Management.Automation.Internal; +using Microsoft.PowerShell.Telemetry; namespace System.Management.Automation.Subsystem { @@ -18,22 +19,22 @@ public abstract class SubsystemInfo #region "Metadata of a Subsystem (public)" /// - /// The kind of a concrete subsystem. + /// Gets the kind of a concrete subsystem. /// public SubsystemKind Kind { get; } /// - /// The type of a concrete subsystem. + /// Gets the type of a concrete subsystem. /// public Type SubsystemType { get; } /// - /// Indicate whether the subsystem allows to unregister an implementation. + /// Gets a value indicating whether the subsystem allows to unregister an implementation. /// public bool AllowUnregistration { get; private set; } /// - /// Indicate whether the subsystem allows to have multiple implementations registered. + /// Gets a value indicating whether the subsystem allows to have multiple implementations registered. /// public bool AllowMultipleRegistration { get; private set; } @@ -96,6 +97,7 @@ private protected SubsystemInfo(SubsystemKind kind, Type subsystemType) internal void RegisterImplementation(ISubsystem impl) { AddImplementation(impl); + ApplicationInsightsTelemetry.SendUseTelemetry(ApplicationInsightsTelemetry.s_subsystemRegistration, impl.Name); } internal ISubsystem UnregisterImplementation(Guid id) @@ -159,10 +161,10 @@ internal static SubsystemInfo Create( /// public class ImplementationInfo { - internal ImplementationInfo(ISubsystem implementation) + internal ImplementationInfo(SubsystemKind kind, ISubsystem implementation) { Id = implementation.Id; - Kind = implementation.Kind; + Kind = kind; Name = implementation.Name; Description = implementation.Description; ImplementationType = implementation.GetType(); @@ -217,6 +219,7 @@ internal SubsystemInfoImpl(SubsystemKind kind) /// In the subsystem scenario, registration operations will be minimum, and in most cases, the registered /// implementation will never be unregistered, so optimization for reading is more important. /// + /// The subsystem implementation to be added. private protected override void AddImplementation(ISubsystem rawImpl) { lock (_syncObj) @@ -226,7 +229,7 @@ private protected override void AddImplementation(ISubsystem rawImpl) if (_registeredImpls.Count == 0) { _registeredImpls = new ReadOnlyCollection(new[] { impl }); - _cachedImplInfos = new ReadOnlyCollection(new[] { new ImplementationInfo(impl) }); + _cachedImplInfos = new ReadOnlyCollection(new[] { new ImplementationInfo(Kind, impl) }); return; } @@ -250,12 +253,17 @@ private protected override void AddImplementation(ISubsystem rawImpl) } } - var list = new List(_registeredImpls.Count + 1); - list.AddRange(_registeredImpls); - list.Add(impl); + int newCapacity = _registeredImpls.Count + 1; + var implList = new List(newCapacity); + implList.AddRange(_registeredImpls); + implList.Add(impl); - _registeredImpls = new ReadOnlyCollection(list); - _cachedImplInfos = new ReadOnlyCollection(list.ConvertAll(s => new ImplementationInfo(s))); + var implInfo = new List(newCapacity); + implInfo.AddRange(_cachedImplInfos); + implInfo.Add(new ImplementationInfo(Kind, impl)); + + _registeredImpls = new ReadOnlyCollection(implList); + _cachedImplInfos = new ReadOnlyCollection(implInfo); } } @@ -268,6 +276,8 @@ private protected override void AddImplementation(ISubsystem rawImpl) /// In the subsystem scenario, registration operations will be minimum, and in most cases, the registered /// implementation will never be unregistered, so optimization for reading is more important. /// + /// The id of the subsystem implementation to be removed. + /// The subsystem implementation that was removed. private protected override ISubsystem RemoveImplementation(Guid id) { if (!AllowUnregistration) @@ -314,7 +324,10 @@ private protected override ISubsystem RemoveImplementation(Guid id) } else { - var list = new List(_registeredImpls.Count - 1); + int newCapacity = _registeredImpls.Count - 1; + var implList = new List(newCapacity); + var implInfo = new List(newCapacity); + for (int i = 0; i < _registeredImpls.Count; i++) { if (index == i) @@ -322,11 +335,12 @@ private protected override ISubsystem RemoveImplementation(Guid id) continue; } - list.Add(_registeredImpls[i]); + implList.Add(_registeredImpls[i]); + implInfo.Add(_cachedImplInfos[i]); } - _registeredImpls = new ReadOnlyCollection(list); - _cachedImplInfos = new ReadOnlyCollection(list.ConvertAll(s => new ImplementationInfo(s))); + _registeredImpls = new ReadOnlyCollection(implList); + _cachedImplInfos = new ReadOnlyCollection(implInfo); } return target; diff --git a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs index 81a27f61279..e389040899e 100644 --- a/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs +++ b/src/System.Management.Automation/engine/Subsystem/SubsystemManager.cs @@ -6,8 +6,10 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Linq; using System.Management.Automation.Internal; +using System.Management.Automation.Subsystem.DSC; +using System.Management.Automation.Subsystem.Feedback; +using System.Management.Automation.Subsystem.Prediction; namespace System.Management.Automation.Subsystem { @@ -28,6 +30,16 @@ static SubsystemManager() SubsystemKind.CommandPredictor, allowUnregistration: true, allowMultipleRegistration: true), + + SubsystemInfo.Create( + SubsystemKind.CrossPlatformDsc, + allowUnregistration: true, + allowMultipleRegistration: false), + + SubsystemInfo.Create( + SubsystemKind.FeedbackProvider, + allowUnregistration: true, + allowMultipleRegistration: true), }; var subSystemTypeMap = new Dictionary(subsystems.Length); @@ -42,6 +54,9 @@ static SubsystemManager() s_subsystems = new ReadOnlyCollection(subsystems); s_subSystemTypeMap = new ReadOnlyDictionary(subSystemTypeMap); s_subSystemKindMap = new ReadOnlyDictionary(subSystemKindMap); + + // Register built-in suggestion providers. + RegisterSubsystem(SubsystemKind.FeedbackProvider, new GeneralCommandErrorFeedback()); } #region internal - Retrieve subsystem proxy object @@ -52,14 +67,14 @@ static SubsystemManager() /// /// /// Design point: - /// The implemnentation proxy object is not supposed to expose to users. + /// The implementation proxy object is not supposed to expose to users. /// Users shouldn't depend on a implementation proxy object directly, but instead should depend on PowerShell APIs. /// /// Example: if a user want to use prediction functionality, he/she should use the PowerShell prediction API instead of /// directly interacting with the implementation proxy object of `IPrediction`. /// /// The concrete subsystem base type. - /// The most recently registered implmentation object of the concrete subsystem. + /// The most recently registered implementation object of the concrete subsystem. internal static TConcreteSubsystem? GetSubsystem() where TConcreteSubsystem : class, ISubsystem { @@ -80,7 +95,7 @@ static SubsystemManager() /// Return an empty collection when the given subsystem is not registered. /// /// The concrete subsystem base type. - /// A readonly collection of all implmentation objects registered for the concrete subsystem. + /// A readonly collection of all implementation objects registered for the concrete subsystem. internal static ReadOnlyCollection GetSubsystems() where TConcreteSubsystem : class, ISubsystem { @@ -116,7 +131,7 @@ public static ReadOnlyCollection GetAllSubsystemInfo() /// The object that represents the concrete subsystem. public static SubsystemInfo GetSubsystemInfo(Type subsystemType) { - Requires.NotNull(subsystemType, nameof(subsystemType)); + ArgumentNullException.ThrowIfNull(subsystemType); if (s_subSystemTypeMap.TryGetValue(subsystemType, out SubsystemInfo? subsystemInfo)) { @@ -124,9 +139,12 @@ public static SubsystemInfo GetSubsystemInfo(Type subsystemType) } throw new ArgumentException( - StringUtil.Format( - SubsystemStrings.SubsystemTypeUnknown, - subsystemType.FullName)); + subsystemType == typeof(ISubsystem) + ? SubsystemStrings.MustUseConcreteSubsystemType + : StringUtil.Format( + SubsystemStrings.SubsystemTypeUnknown, + subsystemType.FullName), + nameof(subsystemType)); } /// @@ -144,7 +162,8 @@ public static SubsystemInfo GetSubsystemInfo(SubsystemKind kind) throw new ArgumentException( StringUtil.Format( SubsystemStrings.SubsystemKindUnknown, - kind.ToString())); + kind.ToString()), + nameof(kind)); } #endregion @@ -161,7 +180,7 @@ public static void RegisterSubsystem(TImple where TConcreteSubsystem : class, ISubsystem where TImplementation : class, TConcreteSubsystem { - Requires.NotNull(proxy, nameof(proxy)); + ArgumentNullException.ThrowIfNull(proxy); RegisterSubsystem(GetSubsystemInfo(typeof(TConcreteSubsystem)), proxy); } @@ -173,19 +192,20 @@ public static void RegisterSubsystem(TImple /// An instance of the implementation. public static void RegisterSubsystem(SubsystemKind kind, ISubsystem proxy) { - Requires.NotNull(proxy, nameof(proxy)); + ArgumentNullException.ThrowIfNull(proxy); - if (kind != proxy.Kind) + SubsystemInfo info = GetSubsystemInfo(kind); + if (!info.SubsystemType.IsAssignableFrom(proxy.GetType())) { throw new ArgumentException( StringUtil.Format( - SubsystemStrings.ImplementationMismatch, - proxy.Kind.ToString(), - kind.ToString()), + SubsystemStrings.ConcreteSubsystemNotImplemented, + kind.ToString(), + info.SubsystemType.Name), nameof(proxy)); } - RegisterSubsystem(GetSubsystemInfo(kind), proxy); + RegisterSubsystem(info, proxy); } private static void RegisterSubsystem(SubsystemInfo subsystemInfo, ISubsystem proxy) @@ -273,7 +293,14 @@ private static void UnregisterSubsystem(SubsystemInfo subsystemInfo, Guid id) ISubsystem impl = subsystemInfo.UnregisterImplementation(id); if (impl is IDisposable disposable) { - disposable.Dispose(); + try + { + disposable.Dispose(); + } + catch + { + // It's OK to ignore all exceptions when disposing the object. + } } } diff --git a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs index bde0c0f3483..d77e700e90e 100644 --- a/src/System.Management.Automation/engine/ThirdPartyAdapter.cs +++ b/src/System.Management.Automation/engine/ThirdPartyAdapter.cs @@ -296,10 +296,7 @@ public abstract class PSPropertyAdapter [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "object")] public virtual Collection GetTypeNameHierarchy(object baseObject) { - if (baseObject == null) - { - throw new ArgumentNullException(nameof(baseObject)); - } + ArgumentNullException.ThrowIfNull(baseObject); Collection types = new Collection(); diff --git a/src/System.Management.Automation/engine/TransactedString.cs b/src/System.Management.Automation/engine/TransactedString.cs deleted file mode 100644 index 948cf1d9d81..00000000000 --- a/src/System.Management.Automation/engine/TransactedString.cs +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Text; -using System.Transactions; - -namespace Microsoft.PowerShell.Commands.Management -{ - /// - /// Represents a a string that can be used in transactions. - /// - public class TransactedString : IEnlistmentNotification - { - private StringBuilder _value; - private StringBuilder _temporaryValue; - private Transaction _enlistedTransaction = null; - - /// - /// Constructor for the TransactedString class. - /// - public TransactedString() : this(string.Empty) - { - } - - /// - /// Constructor for the TransactedString class. - /// - /// The initial value of the transacted string. - /// - /// - public TransactedString(string value) - { - _value = new StringBuilder(value); - _temporaryValue = null; - } - - /// - /// Make the transacted changes permanent. - /// - void IEnlistmentNotification.Commit(Enlistment enlistment) - { - _value = new StringBuilder(_temporaryValue.ToString()); - _temporaryValue = null; - _enlistedTransaction = null; - enlistment.Done(); - } - - /// - /// Discard the transacted changes. - /// - void IEnlistmentNotification.Rollback(Enlistment enlistment) - { - _temporaryValue = null; - _enlistedTransaction = null; - enlistment.Done(); - } - - /// - /// Discard the transacted changes. - /// - void IEnlistmentNotification.InDoubt(Enlistment enlistment) - { - enlistment.Done(); - } - - void IEnlistmentNotification.Prepare(PreparingEnlistment preparingEnlistment) - { - preparingEnlistment.Prepared(); - } - - /// - /// Append text to the transacted string. - /// - /// The text to append. - /// - /// - public void Append(string text) - { - ValidateTransactionOrEnlist(); - - if (_enlistedTransaction != null) - { - _temporaryValue.Append(text); - } - else - { - _value.Append(text); - } - } - - /// - /// Remove text from the transacted string. - /// - /// The position in the string from which to start removing. - /// - /// - /// The length of text to remove. - /// - /// - public void Remove(int startIndex, int length) - { - ValidateTransactionOrEnlist(); - - if (_enlistedTransaction != null) - { - _temporaryValue.Remove(startIndex, length); - } - else - { - _value.Remove(startIndex, length); - } - } - - /// - /// Gets the length of the transacted string. If this is - /// called within the transaction, it returns the length of - /// the transacted value. Otherwise, it returns the length of - /// the original value. - /// - public int Length - { - get - { - // If we're not in a transaction, or we are in a different transaction than the one we - // enlisted to, return the publicly visible state. - if ( - (Transaction.Current == null) || - (_enlistedTransaction != Transaction.Current)) - { - return _value.Length; - } - else - { - return _temporaryValue.Length; - } - } - } - - /// - /// Gets the System.String that represents the transacted - /// transacted string. If this is called within the - /// transaction, it returns the transacted value. - /// Otherwise, it returns the original value. - /// - public override string ToString() - { - // If we're not in a transaction, or we are in a different transaction than the one we - // enlisted to, return the publicly visible state. - if ( - (Transaction.Current == null) || - (_enlistedTransaction != Transaction.Current)) - { - return _value.ToString(); - } - else - { - return _temporaryValue.ToString(); - } - } - - private void ValidateTransactionOrEnlist() - { - // We're in a transaction - if (Transaction.Current != null) - { - // We haven't yet been called inside of a transaction. So enlist - // in the transaction, and store our save point - if (_enlistedTransaction == null) - { - Transaction.Current.EnlistVolatile(this, EnlistmentOptions.None); - _enlistedTransaction = Transaction.Current; - - _temporaryValue = new StringBuilder(_value.ToString()); - } - // We're already enlisted in a transaction - else - { - // And we're in that transaction - if (Transaction.Current != _enlistedTransaction) - { - throw new InvalidOperationException("Cannot modify string. It has been modified by another transaction."); - } - } - } - // We're not in a transaction - else - { - // If we're not subscribed to a transaction, modify the underlying value - if (_enlistedTransaction != null) - { - throw new InvalidOperationException("Cannot modify string. It has been modified by another transaction."); - } - } - } - } -} - diff --git a/src/System.Management.Automation/engine/TransactionManager.cs b/src/System.Management.Automation/engine/TransactionManager.cs deleted file mode 100644 index bf86d90e812..00000000000 --- a/src/System.Management.Automation/engine/TransactionManager.cs +++ /dev/null @@ -1,709 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#pragma warning disable 1634, 1691 - -using System.Collections.Generic; -using System.Transactions; -using System.Management.Automation.Internal; - -namespace System.Management.Automation -{ - /// - /// The status of a PowerShell transaction. - /// - public enum PSTransactionStatus - { - /// - /// The transaction has been rolled back. - /// - RolledBack = 0, - - /// - /// The transaction has been committed. - /// - Committed = 1, - - /// - /// The transaction is currently active. - /// - Active = 2 - } - - /// - /// Represents an active transaction. - /// - public sealed class PSTransaction : IDisposable - { - /// - /// Initializes a new instance of the PSTransaction class. - /// - internal PSTransaction(RollbackSeverity rollbackPreference, TimeSpan timeout) - { - _transaction = new CommittableTransaction(timeout); - RollbackPreference = rollbackPreference; - _subscriberCount = 1; - } - - /// - /// Initializes a new instance of the PSTransaction class using a CommittableTransaction. - /// - internal PSTransaction(CommittableTransaction transaction, RollbackSeverity severity) - { - _transaction = transaction; - RollbackPreference = severity; - _subscriberCount = 1; - } - - private CommittableTransaction _transaction; - - /// - /// Gets the rollback preference for this transaction. - /// - public RollbackSeverity RollbackPreference { get; } - - /// - /// Gets the number of subscribers to this transaction. - /// - public int SubscriberCount - { - get - { - // Verify the transaction hasn't been rolled back beneath us - if (this.IsRolledBack) - { - this.SubscriberCount = 0; - } - - return _subscriberCount; - } - - set { _subscriberCount = value; } - } - - private int _subscriberCount; - - /// - /// Returns the status of this transaction. - /// - public PSTransactionStatus Status - { - get - { - if (IsRolledBack) - { - return PSTransactionStatus.RolledBack; - } - else if (IsCommitted) - { - return PSTransactionStatus.Committed; - } - else - { - return PSTransactionStatus.Active; - } - } - } - - /// - /// Activates the transaction held by this PSTransaction. - /// - internal void Activate() - { - Transaction.Current = _transaction; - } - - /// - /// Commits the transaction held by this PSTransaction. - /// - internal void Commit() - { - _transaction.Commit(); - IsCommitted = true; - } - - /// - /// Rolls back the transaction held by this PSTransaction. - /// - internal void Rollback() - { - _transaction.Rollback(); - _isRolledBack = true; - } - - /// - /// Determines whether this PSTransaction has been - /// rolled back or not. - /// - internal bool IsRolledBack - { - get - { - // Check if it's been aborted underneath us - if ( - (!_isRolledBack) && - (_transaction != null) && - (_transaction.TransactionInformation.Status == TransactionStatus.Aborted)) - { - _isRolledBack = true; - } - - return _isRolledBack; - } - - set - { - _isRolledBack = value; - } - } - - private bool _isRolledBack = false; - - /// - /// Determines whether this PSTransaction - /// has been committed or not. - /// - internal bool IsCommitted { get; set; } = false; - - /// - /// Destructor for the PSTransaction class. - /// - ~PSTransaction() - { - Dispose(false); - } - - /// - /// Disposes the PSTransaction object. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the PSTransaction object, which disposes the - /// underlying transaction. - /// - /// Whether to actually dispose the object. - /// - /// - public void Dispose(bool disposing) - { - if (disposing) - { - if (_transaction != null) - { - _transaction.Dispose(); - } - } - } - } - - /// - /// Supports the transaction management infrastructure for the PowerShell engine. - /// - public sealed class PSTransactionContext : IDisposable - { - /// - /// Initializes a new instance of the PSTransactionManager class. - /// - internal PSTransactionContext(PSTransactionManager transactionManager) - { - _transactionManager = transactionManager; - transactionManager.SetActive(); - } - - private PSTransactionManager _transactionManager; - - /// - /// Destructor for the PSTransactionManager class. - /// - ~PSTransactionContext() - { - Dispose(false); - } - - /// - /// Disposes the PSTransactionContext object. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the PSTransactionContext object, which resets the - /// active PSTransaction. - /// - /// Whether to actually dispose the object. - /// - /// - private void Dispose(bool disposing) - { - if (disposing) - { - _transactionManager.ResetActive(); - } - } - } - - /// - /// The severity of error that causes PowerShell to automatically - /// rollback the transaction. - /// - public enum RollbackSeverity - { - /// - /// Non-terminating errors or worse. - /// - Error, - - /// - /// Terminating errors or worse. - /// - TerminatingError, - - /// - /// Do not rollback the transaction on error. - /// - Never - } -} - -namespace System.Management.Automation.Internal -{ - /// - /// Supports the transaction management infrastructure for the PowerShell engine. - /// - internal sealed class PSTransactionManager : IDisposable - { - /// - /// Initializes a new instance of the PSTransactionManager class. - /// - internal PSTransactionManager() - { - _transactionStack = new Stack(); - _transactionStack.Push(null); - } - - /// - /// Called by engine APIs to ensure they are protected from - /// ambient transactions. - /// - internal static IDisposable GetEngineProtectionScope() - { - if (s_engineProtectionEnabled && (Transaction.Current != null)) - { - return new System.Transactions.TransactionScope( - System.Transactions.TransactionScopeOption.Suppress); - } - else - { - return null; - } - } - - /// - /// Called by the transaction manager to enable engine - /// protection the first time a transaction is activated. - /// Engine protection APIs remain protected from this point on. - /// - internal static void EnableEngineProtection() - { - s_engineProtectionEnabled = true; - } - - private static bool s_engineProtectionEnabled = false; - - /// - /// Gets the rollback preference for the active transaction. - /// - internal RollbackSeverity RollbackPreference - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionActive; - - // This is not an expected condition, and is just protective - // coding. -#pragma warning suppress 56503 - throw new InvalidOperationException(error); - } - - return currentTransaction.RollbackPreference; - } - } - - /// - /// Creates a new Transaction if none are active. Otherwise, increments - /// the subscriber count for the active transaction. - /// - internal void CreateOrJoin() - { - CreateOrJoin(RollbackSeverity.Error, TimeSpan.FromMinutes(1)); - } - - /// - /// Creates a new Transaction if none are active. Otherwise, increments - /// the subscriber count for the active transaction. - /// - internal void CreateOrJoin(RollbackSeverity rollbackPreference, TimeSpan timeout) - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - // There is a transaction on the stack - if (currentTransaction != null) - { - // If you are already in a transaction that has been aborted, or committed, - // create it. - if (currentTransaction.IsRolledBack || currentTransaction.IsCommitted) - { - // Clean up the "used" one - _transactionStack.Pop().Dispose(); - - // And add a new one to the stack - _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); - } - else - { - // This is a usable one. Add a subscriber to it. - currentTransaction.SubscriberCount++; - } - } - else - { - // Add a new transaction to the stack - _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); - } - } - - /// - /// Creates a new Transaction that should be managed independently of - /// any parent transactions. - /// - internal void CreateNew() - { - CreateNew(RollbackSeverity.Error, TimeSpan.FromMinutes(1)); - } - - /// - /// Creates a new Transaction that should be managed independently of - /// any parent transactions. - /// - internal void CreateNew(RollbackSeverity rollbackPreference, TimeSpan timeout) - { - _transactionStack.Push(new PSTransaction(rollbackPreference, timeout)); - } - - /// - /// Completes the current transaction. If only one subscriber is active, this - /// commits the transaction. Otherwise, it reduces the subscriber count by one. - /// - internal void Commit() - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - // Should not be able to commit a transaction that is not active - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionActiveForCommit; - throw new InvalidOperationException(error); - } - - // If you are already in a transaction that has been aborted - if (currentTransaction.IsRolledBack) - { - string error = TransactionStrings.TransactionRolledBackForCommit; - throw new TransactionAbortedException(error); - } - - // If you are already in a transaction that has been committed - if (currentTransaction.IsCommitted) - { - string error = TransactionStrings.CommittedTransactionForCommit; - throw new InvalidOperationException(error); - } - - if (currentTransaction.SubscriberCount == 1) - { - currentTransaction.Commit(); - currentTransaction.SubscriberCount = 0; - } - else - { - currentTransaction.SubscriberCount--; - } - - // Now that we've committed, go back to the last available transaction - while ((_transactionStack.Count > 2) && - (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) - { - _transactionStack.Pop().Dispose(); - } - } - - /// - /// Aborts the current transaction, no matter how many subscribers are part of it. - /// - internal void Rollback() - { - Rollback(false); - } - - /// - /// Aborts the current transaction, no matter how many subscribers are part of it. - /// - internal void Rollback(bool suppressErrors) - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - // Should not be able to roll back a transaction that is not active - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionActiveForRollback; - throw new InvalidOperationException(error); - } - - // If you are already in a transaction that has been aborted - if (currentTransaction.IsRolledBack) - { - if (!suppressErrors) - { - // Otherwise, you should not be able to roll it back. - string error = TransactionStrings.TransactionRolledBackForRollback; - throw new TransactionAbortedException(error); - } - } - - // See if they've already committed the transaction - if (currentTransaction.IsCommitted) - { - if (!suppressErrors) - { - string error = TransactionStrings.CommittedTransactionForRollback; - throw new InvalidOperationException(error); - } - } - - // Roll back the transaction if it hasn't been rolled back - currentTransaction.SubscriberCount = 0; - currentTransaction.Rollback(); - - // Now that we've rolled back, go back to the last available transaction - while ((_transactionStack.Count > 2) && - (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) - { - _transactionStack.Pop().Dispose(); - } - } - - /// - /// Sets the base transaction; any transactions created thereafter will be nested to this instance. - /// - internal void SetBaseTransaction(CommittableTransaction transaction, RollbackSeverity severity) - { - if (this.HasTransaction) - { - throw new InvalidOperationException(TransactionStrings.BaseTransactionMustBeFirst); - } - - PSTransaction currentTransaction = _transactionStack.Peek(); - - // If there is a "used" transaction at the top of the stack, clean it up - while (_transactionStack.Peek() != null && - (_transactionStack.Peek().IsRolledBack || _transactionStack.Peek().IsCommitted)) - { - _transactionStack.Pop().Dispose(); - } - - _baseTransaction = new PSTransaction(transaction, severity); - _transactionStack.Push(_baseTransaction); - } - - /// - /// Removes the transaction added by SetBaseTransaction. - /// - internal void ClearBaseTransaction() - { - if (_baseTransaction == null) - { - throw new InvalidOperationException(TransactionStrings.BaseTransactionNotSet); - } - - if (_transactionStack.Peek() != _baseTransaction) - { - throw new InvalidOperationException(TransactionStrings.BaseTransactionNotActive); - } - - _transactionStack.Pop().Dispose(); - _baseTransaction = null; - } - - private Stack _transactionStack; - private PSTransaction _baseTransaction; - - /// - /// Returns the current engine transaction. - /// - internal PSTransaction GetCurrent() - { - return _transactionStack.Peek(); - } - - /// - /// Activates the current transaction, both in the engine, and in the Ambient. - /// - internal void SetActive() - { - PSTransactionManager.EnableEngineProtection(); - - PSTransaction currentTransaction = _transactionStack.Peek(); - - // Should not be able to activate a transaction that is not active - if (currentTransaction == null) - { - string error = TransactionStrings.NoTransactionForActivation; - throw new InvalidOperationException(error); - } - - // If you are already in a transaction that has been aborted, you should - // not be able to activate it. - if (currentTransaction.IsRolledBack) - { - string error = TransactionStrings.NoTransactionForActivationBecauseRollback; - throw new TransactionAbortedException(error); - } - - _previousActiveTransaction = Transaction.Current; - currentTransaction.Activate(); - } - - private Transaction _previousActiveTransaction; - - /// - /// Deactivates the current transaction in the engine, and restores the - /// ambient transaction. - /// - internal void ResetActive() - { - // Even if you are in a transaction that has been aborted, you - // should still be able to restore the current transaction. - - Transaction.Current = _previousActiveTransaction; - _previousActiveTransaction = null; - } - - /// - /// Determines if you have a transaction that you can set active and work on. - /// - internal bool HasTransaction - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if ((currentTransaction != null) && - (!currentTransaction.IsCommitted) && - (!currentTransaction.IsRolledBack)) - { - return true; - } - else - { - return false; - } - } - } - - /// - /// Determines if the last transaction has been committed. - /// - internal bool IsLastTransactionCommitted - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if (currentTransaction != null) - { - return currentTransaction.IsCommitted; - } - else - { - return false; - } - } - } - - /// - /// Determines if the last transaction has been rolled back. - /// - internal bool IsLastTransactionRolledBack - { - get - { - PSTransaction currentTransaction = _transactionStack.Peek(); - - if (currentTransaction != null) - { - return currentTransaction.IsRolledBack; - } - else - { - return false; - } - } - } - - /// - /// Destructor for the PSTransactionManager class. - /// - ~PSTransactionManager() - { - Dispose(false); - } - - /// - /// Disposes the PSTransactionManager object. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Disposes the PSTransactionContext object, which resets the - /// active PSTransaction. - /// - /// Whether to actually dispose the object. - /// - /// - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed", MessageId = "baseTransaction", Justification = "baseTransaction should not be disposed since we do not own it - it belongs to the caller")] - public void Dispose(bool disposing) - { - if (disposing) - { - ResetActive(); - - while (_transactionStack.Peek() != null) - { - PSTransaction currentTransaction = _transactionStack.Pop(); - - if (currentTransaction != _baseTransaction) - { - currentTransaction.Dispose(); - } - } - } - } - } -} - diff --git a/src/System.Management.Automation/engine/TypeMetadata.cs b/src/System.Management.Automation/engine/TypeMetadata.cs index 31a6adeab73..926b07fb15a 100644 --- a/src/System.Management.Automation/engine/TypeMetadata.cs +++ b/src/System.Management.Automation/engine/TypeMetadata.cs @@ -761,6 +761,7 @@ internal bool IsMatchingType(PSTypeName psTypeName) private const string AliasesFormat = @"{0}[Alias({1})]"; private const string ValidateLengthFormat = @"{0}[ValidateLength({1}, {2})]"; private const string ValidateRangeRangeKindFormat = @"{0}[ValidateRange([System.Management.Automation.ValidateRangeKind]::{1})]"; + private const string ValidateRangeEnumFormat = @"{0}[ValidateRange([{3}]::{1}, [{3}]::{2})]"; private const string ValidateRangeFloatFormat = @"{0}[ValidateRange({1:R}, {2:R})]"; private const string ValidateRangeFormat = @"{0}[ValidateRange({1}, {2})]"; private const string ValidatePatternFormat = "{0}[ValidatePattern('{1}')]"; @@ -769,6 +770,7 @@ internal bool IsMatchingType(PSTypeName psTypeName) private const string ValidateSetFormat = @"{0}[ValidateSet({1})]"; private const string ValidateNotNullFormat = @"{0}[ValidateNotNull()]"; private const string ValidateNotNullOrEmptyFormat = @"{0}[ValidateNotNullOrEmpty()]"; + private const string ValidateNotNullOrWhiteSpaceFormat = @"{0}[ValidateNotNullOrWhiteSpace()]"; private const string AllowNullFormat = @"{0}[AllowNull()]"; private const string AllowEmptyStringFormat = @"{0}[AllowEmptyString()]"; private const string AllowEmptyCollectionFormat = @"{0}[AllowEmptyCollection()]"; @@ -931,6 +933,10 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) { format = ValidateRangeFloatFormat; } + else if (rangeType.IsEnum) + { + format = ValidateRangeEnumFormat; + } else { format = ValidateRangeFormat; @@ -941,7 +947,8 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) format, prefix, validRangeAttrib.MinRange, - validRangeAttrib.MaxRange); + validRangeAttrib.MaxRange, + rangeType.FullName); return result; } } @@ -976,7 +983,7 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) /* TODO: Validate Pattern dont support Options in ScriptCmdletText. StringBuilder regexOps = new System.Text.StringBuilder(); string or = string.Empty; - string[] regexOptionEnumValues = Enum.GetNames(typeof(System.Text.RegularExpressions.RegexOptions)); + string[] regexOptionEnumValues = Enum.GetNames(); foreach (string regexOption in regexOptionEnumValues) { @@ -1025,6 +1032,14 @@ private static string GetProxyAttributeData(Attribute attrib, string prefix) return result; } + ValidateNotNullOrWhiteSpaceAttribute notNullWhiteSpaceAttrib = attrib as ValidateNotNullOrWhiteSpaceAttribute; + if (notNullWhiteSpaceAttrib != null) + { + result = string.Format(CultureInfo.InvariantCulture, + ValidateNotNullOrWhiteSpaceFormat, prefix); + return result; + } + ValidateSetAttribute setAttrib = attrib as ValidateSetAttribute; if (setAttrib != null) { diff --git a/src/System.Management.Automation/engine/TypeTable.cs b/src/System.Management.Automation/engine/TypeTable.cs index 0e407d57ac4..a0eead95e23 100644 --- a/src/System.Management.Automation/engine/TypeTable.cs +++ b/src/System.Management.Automation/engine/TypeTable.cs @@ -139,17 +139,17 @@ private void UnknownNode(string node, string expectedNodes) else { _context.AddError(_readerLineInfo.LineNumber, TypesXmlStrings.UnknownNode, _reader.LocalName, expectedNodes); - SkipUntillNodeEnd(_reader.LocalName); + SkipUntilNodeEnd(_reader.LocalName); } } - private void SkipUntillNodeEnd(string nodeName) + private void SkipUntilNodeEnd(string nodeName) { while (_reader.Read()) { if (_reader.IsStartElement() && _reader.LocalName.Equals(nodeName)) { - SkipUntillNodeEnd(nodeName); + SkipUntilNodeEnd(nodeName); } else if ((_reader.NodeType == XmlNodeType.EndElement) && _reader.LocalName.Equals(nodeName)) { @@ -459,7 +459,7 @@ private TypeData Read_Type() { if (m.Name.Equals(TypeTable.DefaultDisplayProperty, StringComparison.OrdinalIgnoreCase)) { - CheckStandardNote(m, typeData, (t, v) => t.DefaultDisplayProperty = v, Converter); + CheckStandardNote(m, typeData, static (t, v) => t.DefaultDisplayProperty = v, Converter); } else if (m.Name.Equals(TypeTable.DefaultDisplayPropertySet, StringComparison.OrdinalIgnoreCase)) { @@ -477,11 +477,11 @@ private TypeData Read_Type() } else if (m.Name.Equals(TypeTable.SerializationMethodNode, StringComparison.OrdinalIgnoreCase)) { - CheckStandardNote(m, typeData, (t, v) => t.SerializationMethod = v, Converter); + CheckStandardNote(m, typeData, static (t, v) => t.SerializationMethod = v, Converter); } else if (m.Name.Equals(TypeTable.SerializationDepth, StringComparison.OrdinalIgnoreCase)) { - CheckStandardNote(m, typeData, (t, v) => t.SerializationDepth = v, Converter); + CheckStandardNote(m, typeData, static (t, v) => t.SerializationDepth = v, Converter); } else if (m.Name.Equals(TypeTable.StringSerializationSource, StringComparison.OrdinalIgnoreCase)) { @@ -504,11 +504,11 @@ private TypeData Read_Type() } else if (m.Name.Equals(TypeTable.InheritPropertySerializationSet, StringComparison.OrdinalIgnoreCase)) { - CheckStandardNote(m, typeData, (t, v) => t.InheritPropertySerializationSet = v, BoolConverter); + CheckStandardNote(m, typeData, static (t, v) => t.InheritPropertySerializationSet = v, BoolConverter); } else if (m.Name.Equals(TypeTable.TargetTypeForDeserialization, StringComparison.OrdinalIgnoreCase)) { - CheckStandardNote(m, typeData, (t, v) => t.TargetTypeForDeserialization = v, Converter); + CheckStandardNote(m, typeData, static (t, v) => t.TargetTypeForDeserialization = v, Converter); } else { @@ -771,10 +771,7 @@ private MemberSetData Read_MemberSet() } // Somewhat pointlessly (backcompat), we allow a missing Member node - if (members == null) - { - members = new Collection(); - } + members ??= new Collection(); if (_context.errors.Count != errorCount) { @@ -841,10 +838,7 @@ private PropertySetData Read_PropertySet() { if ((object)_reader.LocalName == (object)_idName) { - if (referencedProperties == null) - { - referencedProperties = new List(8); - } + referencedProperties ??= new List(8); referencedProperties.Add(ReadElementString(_idName)); } @@ -1683,7 +1677,7 @@ public ConsolidatedString(IEnumerable strings) internal static readonly IEqualityComparer EqualityComparer = new ConsolidatedStringEqualityComparer(); - private class ConsolidatedStringEqualityComparer : IEqualityComparer + private sealed class ConsolidatedStringEqualityComparer : IEqualityComparer { bool IEqualityComparer.Equals(ConsolidatedString x, ConsolidatedString y) { @@ -1747,9 +1741,8 @@ internal void AddError(string typeName, int errorLineNumber, string resourceStri /// /// This exception is used by TypeTable constructor to indicate errors - /// occured during construction time. + /// occurred during construction time. /// - [Serializable] public class TypeTableLoadException : RuntimeException { private readonly Collection _errors; @@ -1796,7 +1789,7 @@ public TypeTableLoadException(string message, Exception innerException) /// time. /// /// - /// The errors that occured + /// The errors that occurred /// internal TypeTableLoadException(ConcurrentBag loadErrors) : base(TypesXmlStrings.TypeTableLoadErrors) @@ -1811,56 +1804,14 @@ internal TypeTableLoadException(ConcurrentBag loadErrors) /// /// /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected TypeTableLoadException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - int errorCount = info.GetInt32("ErrorCount"); - if (errorCount > 0) - { - _errors = new Collection(); - for (int index = 0; index < errorCount; index++) - { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - _errors.Add(info.GetString(key)); - } - } + throw new NotSupportedException(); } #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - // If there are simple fields, serialize them with info.AddValue - if (_errors != null) - { - int errorCount = _errors.Count; - info.AddValue("ErrorCount", errorCount); - - for (int index = 0; index < errorCount; index++) - { - string key = string.Format(CultureInfo.InvariantCulture, "Error{0}", index); - info.AddValue(key, _errors[index]); - } - } - } - /// /// Set the default ErrorRecord. /// @@ -3042,7 +2993,7 @@ private static bool GetCheckMemberType(ConcurrentBag errors, string type /// /// Issue appropriate errors and remove members as necessary if: /// - The serialization settings do not fall into one of the combinations of the table below - /// - If the serialization settings notes' values cannot be converted to the propper type + /// - If the serialization settings notes' values cannot be converted to the proper type /// - If serialization settings members are of the wrong member type /// - DefaultDisplayPropertySet is not an PSPropertySet /// - DefaultDisplayProperty is not an PSPropertyInfo @@ -3724,10 +3675,7 @@ private void ProcessTypeDataToAdd(ConcurrentBag errors, TypeData typeDat if (hasStandardMembers) { - if (typeMembers == null) - { - typeMembers = _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); - } + typeMembers ??= _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); ProcessStandardMembers(errors, typeName, typeData.StandardMembers, propertySets, typeMembers, typeData.IsOverride); } @@ -3937,8 +3885,7 @@ internal TypeTable(IEnumerable typeFiles, AuthorizationManager authoriza throw PSTraceSource.NewArgumentException("typeFile", TypesXmlStrings.TypeFileNotRooted, typefile); } - bool unused; - Initialize(string.Empty, typefile, errors, authorizationManager, host, out unused); + Initialize(string.Empty, typefile, errors, authorizationManager, host, out _); _typeFileList.Add(typefile); } @@ -3975,7 +3922,7 @@ internal Collection GetSpecificProperties(ConsolidatedString types) } PSMemberSet settings = typeMembers[PSStandardMembers] as PSMemberSet; - if (!(settings?.Members[PropertySerializationSet] is PSPropertySet typeProperties)) + if (settings?.Members[PropertySerializationSet] is not PSPropertySet typeProperties) { continue; } @@ -4151,7 +4098,7 @@ internal PSObject.AdapterSet GetTypeAdapter(Type type) #endif } - private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) + private static TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) { var note = member as PSNoteProperty; if (note != null) @@ -4218,7 +4165,7 @@ private TypeMemberData GetTypeMemberDataFromPSMemberInfo(PSMemberInfo member) /// /// /// - private void LoadMembersToTypeData(PSMemberInfo member, TypeData typeData) + private static void LoadMembersToTypeData(PSMemberInfo member, TypeData typeData) { Dbg.Assert(member != null, "caller should guarantee that member is not null"); Dbg.Assert(typeData != null, "caller should guarantee that typeData is not null"); @@ -4254,7 +4201,7 @@ private static T GetParameterType(object sourceValue) /// /// Load the standard members into the passed-in TypeData. /// - private void LoadStandardMembersToTypeData(PSMemberSet memberSet, TypeData typeData) + private static void LoadStandardMembersToTypeData(PSMemberSet memberSet, TypeData typeData) { foreach (PSMemberInfo member in memberSet.InternalMembers) { @@ -4742,15 +4689,9 @@ internal void Update( PSHost host, out bool failToLoadFile) { - if (filePath == null) - { - throw new ArgumentNullException(nameof(filePath)); - } + ArgumentNullException.ThrowIfNull(filePath); - if (errors == null) - { - throw new ArgumentNullException(nameof(errors)); - } + ArgumentNullException.ThrowIfNull(errors); if (isShared) { @@ -4820,10 +4761,9 @@ internal void Update( ConcurrentBag errors, bool isRemove) { - if (type == null) - throw new ArgumentNullException(nameof(type)); - if (errors == null) - throw new ArgumentNullException(nameof(errors)); + ArgumentNullException.ThrowIfNull(type); + + ArgumentNullException.ThrowIfNull(errors); if (isShared) { diff --git a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs index 5a7133b7cd3..26e3621c240 100644 --- a/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs +++ b/src/System.Management.Automation/engine/TypeTable_Types_Ps1Xml.cs @@ -17,10 +17,7 @@ public sealed partial class TypeTable private static Func> GetValueFactoryBasedOnInitCapacity(int capacity) { - if (capacity <= 0) - { - throw new ArgumentOutOfRangeException(nameof(capacity)); - } + ArgumentOutOfRangeException.ThrowIfNegativeOrZero(capacity); if (capacity > ValueFactoryCacheCount) { @@ -568,9 +565,7 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) typeName, new PSScriptProperty( @"DisplayName", - GetScriptBlock(@"if ($this.Name.IndexOf('-') -lt 0) - { - if ($null -ne $this.ResolvedCommand) + GetScriptBlock(@"if ($null -ne $this.ResolvedCommand) { $this.Name + "" -> "" + $this.ResolvedCommand.Name } @@ -578,11 +573,7 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) { $this.Name + "" -> "" + $this.Definition } - } - else - { - $this.Name - }"), + "), setterScript: null, shouldCloneOnAccess: true), typeMembers, @@ -639,7 +630,7 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #region System.IO.DirectoryInfo typeName = @"System.IO.DirectoryInfo"; - typeMembers = _extendedMembers.GetOrAdd(typeName, key => new PSMemberInfoInternalCollection(capacity: 9)); + typeMembers = _extendedMembers.GetOrAdd(typeName, static key => new PSMemberInfoInternalCollection(capacity: 9)); // Process regular members. newMembers.Add(@"Mode"); @@ -676,17 +667,25 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) typeMembers, isOverride: false); - newMembers.Add(@"Target"); + newMembers.Add(@"ResolvedTarget"); AddMember( errors, typeName, new PSCodeProperty( - @"Target", - GetMethodInfo(typeof(Microsoft.PowerShell.Commands.InternalSymbolicLinkLinkCodeMethods), @"GetTarget"), + @"ResolvedTarget", + GetMethodInfo(typeof(Microsoft.PowerShell.Commands.InternalSymbolicLinkLinkCodeMethods), @"ResolvedTarget"), setterCodeReference: null), typeMembers, isOverride: false); + newMembers.Add(@"Target"); + AddMember( + errors, + typeName, + new PSAliasProperty(@"Target", @"LinkTarget", conversionType: null), + typeMembers, + isOverride: false); + newMembers.Add(@"LinkType"); AddMember( errors, @@ -755,7 +754,7 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #region System.IO.FileInfo typeName = @"System.IO.FileInfo"; - typeMembers = _extendedMembers.GetOrAdd(typeName, key => new PSMemberInfoInternalCollection(capacity: 10)); + typeMembers = _extendedMembers.GetOrAdd(typeName, static key => new PSMemberInfoInternalCollection(capacity: 10)); // Process regular members. newMembers.Add(@"Mode"); @@ -804,17 +803,25 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) typeMembers, isOverride: false); - newMembers.Add(@"Target"); + newMembers.Add(@"ResolvedTarget"); AddMember( errors, typeName, new PSCodeProperty( - @"Target", - GetMethodInfo(typeof(Microsoft.PowerShell.Commands.InternalSymbolicLinkLinkCodeMethods), @"GetTarget"), + @"ResolvedTarget", + GetMethodInfo(typeof(Microsoft.PowerShell.Commands.InternalSymbolicLinkLinkCodeMethods), @"ResolvedTarget"), setterCodeReference: null), typeMembers, isOverride: false); + newMembers.Add(@"Target"); + AddMember( + errors, + typeName, + new PSAliasProperty(@"Target", @"LinkTarget", conversionType: null), + typeMembers, + isOverride: false); + newMembers.Add(@"LinkType"); AddMember( errors, @@ -1047,7 +1054,7 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #region System.Diagnostics.Process typeName = @"System.Diagnostics.Process"; - typeMembers = _extendedMembers.GetOrAdd(typeName, key => new PSMemberInfoInternalCollection(capacity: 19)); + typeMembers = _extendedMembers.GetOrAdd(typeName, static key => new PSMemberInfoInternalCollection(capacity: 19)); // Process regular members. newMembers.Add(@"PSConfiguration"); @@ -1148,7 +1155,8 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) if ($IsWindows) { (Get-CimInstance Win32_Process -Filter ""ProcessId = $($this.Id)"").CommandLine } elseif ($IsLinux) { - Get-Content -LiteralPath ""/proc/$($this.Id)/cmdline"" + $rawCmd = Get-Content -LiteralPath ""/proc/$($this.Id)/cmdline"" + $rawCmd.Substring(0, $rawCmd.Length - 1) -replace ""`0"", "" "" } "), setterScript: null, @@ -4065,152 +4073,6 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #endregion System.Management.ManagementObject - #region System.Security.AccessControl.ObjectSecurity - - typeName = @"System.Security.AccessControl.ObjectSecurity"; - typeMembers = _extendedMembers.GetOrAdd(typeName, key => new PSMemberInfoInternalCollection(capacity: 7)); - Type securityDescriptorCommandsBaseType = TypeResolver.ResolveType("Microsoft.PowerShell.Commands.SecurityDescriptorCommandsBase", exception: out _); - - // Process regular members. - newMembers.Add(@"Path"); - AddMember( - errors, - typeName, - new PSCodeProperty( - @"Path", - GetMethodInfo(securityDescriptorCommandsBaseType, @"GetPath"), - setterCodeReference: null), - typeMembers, - isOverride: false); - - newMembers.Add(@"Owner"); - AddMember( - errors, - typeName, - new PSCodeProperty( - @"Owner", - GetMethodInfo(securityDescriptorCommandsBaseType, @"GetOwner"), - setterCodeReference: null), - typeMembers, - isOverride: false); - - newMembers.Add(@"Group"); - AddMember( - errors, - typeName, - new PSCodeProperty( - @"Group", - GetMethodInfo(securityDescriptorCommandsBaseType, @"GetGroup"), - setterCodeReference: null), - typeMembers, - isOverride: false); - - newMembers.Add(@"Access"); - AddMember( - errors, - typeName, - new PSCodeProperty( - @"Access", - GetMethodInfo(securityDescriptorCommandsBaseType, @"GetAccess"), - setterCodeReference: null), - typeMembers, - isOverride: false); - - newMembers.Add(@"Sddl"); - AddMember( - errors, - typeName, - new PSCodeProperty( - @"Sddl", - GetMethodInfo(securityDescriptorCommandsBaseType, @"GetSddl"), - setterCodeReference: null), - typeMembers, - isOverride: false); - - newMembers.Add(@"AccessToString"); - AddMember( - errors, - typeName, - new PSScriptProperty( - @"AccessToString", - GetScriptBlock(@"$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;"), - setterScript: null, - shouldCloneOnAccess: true), - typeMembers, - isOverride: false); - - newMembers.Add(@"AuditToString"); - AddMember( - errors, - typeName, - new PSScriptProperty( - @"AuditToString", - GetScriptBlock(@"$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;"), - setterScript: null, - shouldCloneOnAccess: true), - typeMembers, - isOverride: false); - - #endregion System.Security.AccessControl.ObjectSecurity - #region Microsoft.PowerShell.Commands.HistoryInfo typeName = @"Microsoft.PowerShell.Commands.HistoryInfo"; @@ -9227,45 +9089,42 @@ private void Process_Types_Ps1Xml(string filePath, ConcurrentBag errors) #if UNIX #region UnixStat - if (ExperimentalFeature.IsEnabled("PSUnixFileStat")) - { - typeName = @"System.IO.FileSystemInfo"; - typeMembers = _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); - - // Where we have a method to invoke below, first check to be sure that the object is present - // to avoid null reference issues - newMembers.Add(@"UnixMode"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"UnixMode", GetScriptBlock(@"if ($this.UnixStat) { $this.UnixStat.GetModeString() }")), - typeMembers, - isOverride: false); - - newMembers.Add(@"User"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"User", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetUserName() } ")), - typeMembers, - isOverride: false); - - newMembers.Add(@"Group"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"Group", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetGroupName() } ")), - typeMembers, - isOverride: false); - - newMembers.Add(@"Size"); - AddMember( - errors, - typeName, - new PSScriptProperty(@"Size", GetScriptBlock(@"$this.UnixStat.Size")), - typeMembers, - isOverride: false); - } + typeName = @"System.IO.FileSystemInfo"; + typeMembers = _extendedMembers.GetOrAdd(typeName, GetValueFactoryBasedOnInitCapacity(capacity: 1)); + + // Where we have a method to invoke below, first check to be sure that the object is present + // to avoid null reference issues + newMembers.Add(@"UnixMode"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"UnixMode", GetScriptBlock(@"if ($this.UnixStat) { $this.UnixStat.GetModeString() }")), + typeMembers, + isOverride: false); + + newMembers.Add(@"User"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"User", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetUserName() } ")), + typeMembers, + isOverride: false); + + newMembers.Add(@"Group"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"Group", GetScriptBlock(@" if ($this.UnixStat) { $this.UnixStat.GetGroupName() } ")), + typeMembers, + isOverride: false); + + newMembers.Add(@"Size"); + AddMember( + errors, + typeName, + new PSScriptProperty(@"Size", GetScriptBlock(@"$this.UnixStat.Size")), + typeMembers, + isOverride: false); #endregion #endif diff --git a/src/System.Management.Automation/engine/Utils.cs b/src/System.Management.Automation/engine/Utils.cs index 94957ced8b8..0de9fe0d5cc 100644 --- a/src/System.Management.Automation/engine/Utils.cs +++ b/src/System.Management.Automation/engine/Utils.cs @@ -5,21 +5,16 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.ComponentModel; -using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; -using System.Management.Automation.Language; using System.Management.Automation.Remoting; -using System.Management.Automation.Runspaces; using System.Management.Automation.Security; using System.Numerics; using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; #if !UNIX @@ -29,7 +24,6 @@ using System.Threading; using Microsoft.PowerShell.Commands; using Microsoft.Win32; -using Microsoft.Win32.SafeHandles; using TypeTable = System.Management.Automation.Runspaces.TypeTable; @@ -307,9 +301,9 @@ internal static int CombineHashCodes(int h1, int h2, int h3, int h4, int h5, int /// /// Helper fn to check byte[] arg for null. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckKeyArg(byte[] arg, string argName) { if (arg == null) @@ -334,9 +328,9 @@ internal static void CheckKeyArg(byte[] arg, string argName) /// Helper fn to check arg for empty or null. /// Throws ArgumentNullException on either condition. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckArgForNullOrEmpty(string arg, string argName) { if (arg == null) @@ -353,9 +347,9 @@ internal static void CheckArgForNullOrEmpty(string arg, string argName) /// Helper fn to check arg for null. /// Throws ArgumentNullException on either condition. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckArgForNull(object arg, string argName) { if (arg == null) @@ -367,9 +361,9 @@ internal static void CheckArgForNull(object arg, string argName) /// /// Helper fn to check arg for null. /// - /// arg to check - /// name of the arg - /// Does not return a value. + /// arg to check + /// name of the arg + /// Does not return a value. internal static void CheckSecureStringArg(SecureString arg, string argName) { if (arg == null) @@ -378,7 +372,6 @@ internal static void CheckSecureStringArg(SecureString arg, string argName) } } - [ArchitectureSensitive] internal static string GetStringFromSecureString(SecureString ss) { IntPtr p = IntPtr.Zero; @@ -488,9 +481,16 @@ internal static string GetWindowsPowerShellVersionFromRegistry() internal static string GetApplicationBase(string shellId) { - // Use the location of SMA.dll as the application base. - Assembly assembly = typeof(PSObject).Assembly; - return Path.GetDirectoryName(assembly.Location); + // Use the location of SMA.dll as the application base if it exists, + // otherwise, use the base directory from `AppContext`. + var baseDirectory = Path.GetDirectoryName(typeof(PSObject).Assembly.Location); + if (string.IsNullOrEmpty(baseDirectory)) + { + // Need to remove any trailing directory separator characters + baseDirectory = AppContext.BaseDirectory.TrimEnd(Path.DirectorySeparatorChar); + } + + return baseDirectory; } private static string[] s_productFolderDirectories; @@ -576,10 +576,7 @@ internal static bool IsWinPEHost() catch (ObjectDisposedException) { } finally { - if (winPEKey != null) - { - winPEKey.Dispose(); - } + winPEKey?.Dispose(); } #endif return false; @@ -645,41 +642,6 @@ internal static Version StringToVersion(string versionString) return null; } - /// - /// Checks whether current monad session supports version specified - /// by ver. - /// - /// Version to check. - /// True if supported, false otherwise. - internal static bool IsPSVersionSupported(string ver) - { - // Convert version to supported format ie., x.x - Version inputVersion = StringToVersion(ver); - return IsPSVersionSupported(inputVersion); - } - - /// - /// Checks whether current monad session supports version specified - /// by checkVersion. - /// - /// Version to check. - /// True if supported, false otherwise. - internal static bool IsPSVersionSupported(Version checkVersion) - { - if (checkVersion == null) - { - return false; - } - - foreach (Version compatibleVersion in PSVersionInfo.PSCompatibleVersions) - { - if (checkVersion.Major == compatibleVersion.Major && checkVersion.Minor <= compatibleVersion.Minor) - return true; - } - - return false; - } - /// /// Checks whether current PowerShell session supports edition specified /// by checkEdition. @@ -688,7 +650,7 @@ internal static bool IsPSVersionSupported(Version checkVersion) /// True if supported, false otherwise. internal static bool IsPSEditionSupported(string checkEdition) { - return PSVersionInfo.PSEdition.Equals(checkEdition, StringComparison.OrdinalIgnoreCase); + return PSVersionInfo.PSEditionValue.Equals(checkEdition, StringComparison.OrdinalIgnoreCase); } /// @@ -698,7 +660,7 @@ internal static bool IsPSEditionSupported(string checkEdition) /// True if the edition is supported by this runtime, false otherwise. internal static bool IsPSEditionSupported(IEnumerable editions) { - string currentPSEdition = PSVersionInfo.PSEdition; + string currentPSEdition = PSVersionInfo.PSEditionValue; foreach (string edition in editions) { if (currentPSEdition.Equals(edition, StringComparison.OrdinalIgnoreCase)) @@ -1069,10 +1031,7 @@ internal static void EnsureModuleLoaded(string module, ExecutionContext context) finally { context.AutoLoadingModuleInProgress.Remove(module); - if (ps != null) - { - ps.Dispose(); - } + ps?.Dispose(); } } } @@ -1129,10 +1088,7 @@ internal static List GetModules(string module, ExecutionContext co } finally { - if (ps != null) - { - ps.Dispose(); - } + ps?.Dispose(); } return result; @@ -1190,10 +1146,7 @@ internal static List GetModules(ModuleSpecification fullyQualified } finally { - if (ps != null) - { - ps.Dispose(); - } + ps?.Dispose(); } return result; @@ -1283,7 +1236,7 @@ internal static bool IsReservedDeviceName(string destinationPath) return false; } - internal static bool PathIsUnc(string path) + internal static bool PathIsUnc(string path, bool networkOnly = false) { #if UNIX return false; @@ -1293,8 +1246,8 @@ internal static bool PathIsUnc(string path) return false; } - // handle special cases like \\wsl$\ubuntu which isn't a UNC path, but we can say it is so the filesystemprovider can use it - if (path.StartsWith(WslRootPath, StringComparison.OrdinalIgnoreCase)) + // handle special cases like '\\wsl$\ubuntu', '\\?\', and '\\.\pipe\' which aren't a UNC path, but we can say it is so the filesystemprovider can use it + if (!networkOnly && (path.StartsWith(WslRootPath, StringComparison.OrdinalIgnoreCase) || PathIsDevicePath(path))) { return true; } @@ -1304,6 +1257,16 @@ internal static bool PathIsUnc(string path) #endif } + internal static bool PathIsDevicePath(string path) + { +#if UNIX + return false; +#else + // device paths can be network paths, we would need windows to parse it. + return path.StartsWith(@"\\.\") || path.StartsWith(@"\\?\") || path.StartsWith(@"\\;"); +#endif + } + internal static readonly string PowerShellAssemblyStrongNameFormat = "{0}, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"; @@ -1397,9 +1360,6 @@ internal static bool Succeeded(int hresult) // Add-Member ScriptProperty Preamble { $this.GetEncoding().GetPreamble() -join "-" } -PassThru | // Format-Table -Auto - internal static readonly UTF8Encoding utf8NoBom = - new UTF8Encoding(encoderShouldEmitUTF8Identifier: false); - #if !UNIX /// /// Queues a CLR worker thread with impersonation of provided Windows identity. @@ -1447,7 +1407,7 @@ private static void WorkItemCallback(object callBackArgs) /// Command name and as appropriate Module name in out parameter. internal static string ParseCommandName(string commandName, out string moduleName) { - var names = commandName.Split(Separators.Backslash, 2); + var names = commandName.Split('\\', 2); if (names.Length == 2) { moduleName = names[0]; @@ -1474,22 +1434,8 @@ internal static class Separators internal static readonly char[] Backslash = new char[] { '\\' }; internal static readonly char[] Directory = new char[] { '\\', '/' }; internal static readonly char[] DirectoryOrDrive = new char[] { '\\', '/', ':' }; - - internal static readonly char[] Colon = new char[] { ':' }; - internal static readonly char[] Dot = new char[] { '.' }; - internal static readonly char[] Pipe = new char[] { '|' }; - internal static readonly char[] Comma = new char[] { ',' }; - internal static readonly char[] Semicolon = new char[] { ';' }; - internal static readonly char[] StarOrQuestion = new char[] { '*', '?' }; - internal static readonly char[] ColonOrBackslash = new char[] { '\\', ':' }; - internal static readonly char[] PathSeparator = new char[] { Path.PathSeparator }; - - internal static readonly char[] QuoteChars = new char[] { '\'', '"' }; - internal static readonly char[] Space = new char[] { ' ' }; - internal static readonly char[] QuotesSpaceOrTab = new char[] { ' ', '\t', '\'', '"' }; internal static readonly char[] SpaceOrTab = new char[] { ' ', '\t' }; - internal static readonly char[] Newline = new char[] { '\n' }; - internal static readonly char[] CrLf = new char[] { '\r', '\n' }; + internal static readonly char[] StarOrQuestion = new char[] { '*', '?' }; // (Copied from System.IO.Path so we can call TrimEnd in the same way that Directory.EnumerateFiles would on the search patterns). // Trim trailing white spaces, tabs etc but don't be aggressive in removing everything that has UnicodeCategory of trailing space. @@ -1528,535 +1474,146 @@ internal static bool IsComObject(object obj) /// NoLanguage -> NoLanguage. /// /// ExecutionContext. - /// Previous language mode or null for no language mode change. - internal static PSLanguageMode? EnforceSystemLockDownLanguageMode(ExecutionContext context) - { - PSLanguageMode? oldMode = null; - - if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) - { - switch (context.LanguageMode) - { - case PSLanguageMode.FullLanguage: - oldMode = context.LanguageMode; - context.LanguageMode = PSLanguageMode.ConstrainedLanguage; - break; - - case PSLanguageMode.RestrictedLanguage: - oldMode = context.LanguageMode; - context.LanguageMode = PSLanguageMode.NoLanguage; - break; - - case PSLanguageMode.ConstrainedLanguage: - case PSLanguageMode.NoLanguage: - break; - - default: - Diagnostics.Assert(false, "Unexpected PSLanguageMode"); - oldMode = context.LanguageMode; - context.LanguageMode = PSLanguageMode.NoLanguage; - break; - } - } - - return oldMode; - } - - #region Implicit Remoting Batching - - // Commands allowed to run on target remote session along with implicit remote commands - private static readonly HashSet AllowedCommands = new HashSet(StringComparer.OrdinalIgnoreCase) - { - "ForEach-Object", - "Measure-Command", - "Measure-Object", - "Sort-Object", - "Where-Object" - }; - - // Determines if the typed command invokes implicit remoting module proxy functions in such - // a way as to allow simple batching, to reduce round trips between client and server sessions. - // Requirements: - // a. All commands must be implicit remoting module proxy commands targeted to the same remote session - // b. Except for *allowed* commands that can be safely run on remote session rather than client session - // c. Commands must be in a simple pipeline - internal static bool TryRunAsImplicitBatch(string command, Runspace runspace) + /// The current ExecutionContext language mode. + internal static PSLanguageMode EnforceSystemLockDownLanguageMode(ExecutionContext context) { - using (var ps = System.Management.Automation.PowerShell.Create()) + switch (SystemPolicy.GetSystemLockdownPolicy()) { - ps.Runspace = runspace; - - try - { - var scriptBlock = ScriptBlock.Create(command); - if (!(scriptBlock.Ast is ScriptBlockAst scriptBlockAst)) - { - return false; - } - - // Make sure that this is a simple pipeline - string errorId; - string errorMsg; - scriptBlockAst.GetSimplePipeline(true, out errorId, out errorMsg); - if (errorId != null) - { - WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingNotASimplePipeline); - return false; - } - - // Run checker - var checker = new PipelineForBatchingChecker { ScriptBeingConverted = scriptBlockAst }; - scriptBlockAst.InternalVisit(checker); - - // If this is just a single command, there is no point in batching it - if (checker.Commands.Count < 2) - { - return false; - } - - // We have a valid batching candidate - - // Check commands - if (!TryGetCommandInfoList(ps, checker.Commands, out Collection cmdInfoList)) + case SystemEnforcementMode.Enforce: + switch (context.LanguageMode) { - return false; - } - - // All command modules must be implicit remoting modules from the same PSSession - var success = true; - var psSessionId = Guid.Empty; - foreach (var cmdInfo in cmdInfoList) - { - // Check for allowed command - string cmdName = (cmdInfo is AliasInfo aliasInfo) ? aliasInfo.ReferencedCommand.Name : cmdInfo.Name; - if (AllowedCommands.Contains(cmdName)) - { - continue; - } + case PSLanguageMode.FullLanguage: + context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; - // Commands must be from implicit remoting module - if (cmdInfo.Module == null || string.IsNullOrEmpty(cmdInfo.ModuleName)) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); - success = false; + case PSLanguageMode.RestrictedLanguage: + context.LanguageMode = PSLanguageMode.NoLanguage; break; - } - // Commands must be from modules imported into the same remote session - if (cmdInfo.Module.PrivateData is System.Collections.Hashtable privateData) - { - var sessionIdString = privateData["ImplicitSessionId"] as string; - if (string.IsNullOrEmpty(sessionIdString)) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); - success = false; - break; - } + case PSLanguageMode.ConstrainedLanguage: + case PSLanguageMode.NoLanguage: + break; - var sessionId = new Guid(sessionIdString); - if (psSessionId == Guid.Empty) - { - psSessionId = sessionId; - } - else if (psSessionId != sessionId) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingWrongSession, cmdInfo.Name)); - success = false; - break; - } - } - else - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingNotImplicitCommand, cmdInfo.Name)); - success = false; + default: + Diagnostics.Assert(false, "Unexpected PSLanguageMode"); + context.LanguageMode = PSLanguageMode.NoLanguage; break; - } } + break; - if (success) + case SystemEnforcementMode.Audit: + switch (context.LanguageMode) { - // - // Invoke command pipeline as entire pipeline on remote session - // - - // Update script to declare variables via Using keyword - if (checker.ValidVariables.Count > 0) - { - foreach (var variableName in checker.ValidVariables) - { - command = command.Replace(variableName, ("Using:" + variableName), StringComparison.OrdinalIgnoreCase); - } - - scriptBlock = ScriptBlock.Create(command); - } - - // Retrieve the PSSession runspace in which to run the batch script on - ps.Commands.Clear(); - ps.Commands.AddCommand("Get-PSSession").AddParameter("InstanceId", psSessionId); - var psSession = ps.Invoke().FirstOrDefault(); - if (psSession == null || (ps.Streams.Error.Count > 0) || (psSession.Availability != RunspaceAvailability.Available)) - { - WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingNoPSSession); - return false; - } - - WriteVerbose(ps, ParserStrings.ImplicitRemotingPipelineBatchingSuccess); - - // Create and invoke implicit remoting command pipeline - ps.Commands.Clear(); - ps.AddCommand("Invoke-Command").AddParameter("Session", psSession).AddParameter("ScriptBlock", scriptBlock).AddParameter("HideComputerName", true) - .AddCommand("Out-Default"); - foreach (var cmd in ps.Commands.Commands) - { - cmd.MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output); - } - - try - { - ps.Invoke(); - } - catch (Exception ex) - { - var errorRecord = new ErrorRecord(ex, "ImplicitRemotingBatchExecutionTerminatingError", ErrorCategory.InvalidOperation, null); - - ps.Commands.Clear(); - ps.AddCommand("Write-Error").AddParameter("InputObject", errorRecord).Invoke(); - } - - return true; + case PSLanguageMode.FullLanguage: + // Set to ConstrainedLanguage mode. But no restrictions are applied in audit mode + // and only audit messages will be emitted to logs. + context.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; } - } - catch (ImplicitRemotingBatchingNotSupportedException ex) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, "{0} : {1}", ex.Message, ex.ErrorId)); - } - catch (Exception ex) - { - WriteVerbose(ps, string.Format(CultureInfo.CurrentCulture, ParserStrings.ImplicitRemotingPipelineBatchingException, ex.Message)); - } + break; } - return false; + return context.LanguageMode; } - private static void WriteVerbose(PowerShell ps, string msg) + internal static string DisplayHumanReadableFileSize(long bytes) { - ps.Commands.Clear(); - ps.AddCommand("Write-Verbose").AddParameter("Message", msg).Invoke(); + return bytes switch + { + < 1024 and >= 0 => $"{bytes} Bytes", + < 1048576 and >= 1024 => $"{(bytes / 1024.0).ToString("0.0")} KB", + < 1073741824 and >= 1048576 => $"{(bytes / 1048576.0).ToString("0.0")} MB", + < 1099511627776 and >= 1073741824 => $"{(bytes / 1073741824.0).ToString("0.000")} GB", + < 1125899906842624 and >= 1099511627776 => $"{(bytes / 1099511627776.0).ToString("0.00000")} TB", + < 1152921504606847000 and >= 1125899906842624 => $"{(bytes / 1125899906842624.0).ToString("0.0000000")} PB", + >= 1152921504606847000 => $"{(bytes / 1152921504606847000.0).ToString("0.000000000")} EB", + _ => $"0 Bytes", + }; } - private const string WhereObjectCommandAlias = "?"; - - private static bool TryGetCommandInfoList(PowerShell ps, HashSet commandNames, out Collection cmdInfoList) + /// + /// Returns true if the current session is restricted (JEA or similar sessions) + /// + /// ExecutionContext. + /// True if the session is restricted. + internal static bool IsSessionRestricted(ExecutionContext context) { - if (commandNames.Count == 0) - { - cmdInfoList = null; - return false; - } - - bool specialCaseWhereCommandAlias = commandNames.Contains(WhereObjectCommandAlias); - if (specialCaseWhereCommandAlias) - { - commandNames.Remove(WhereObjectCommandAlias); - } - - // Use Get-Command to collect CommandInfo from candidate commands, with correct precedence so - // that implicit remoting proxy commands will appear when available. - ps.Commands.Clear(); - ps.Commands.AddCommand("Get-Command").AddParameter("Name", commandNames.ToArray()); - cmdInfoList = ps.Invoke(); - if (ps.Streams.Error.Count > 0) + CmdletInfo cmdletInfo = context.SessionState.InvokeCommand.GetCmdlet("Microsoft.PowerShell.Core\\Import-Module"); + // if import-module is visible, then the session is not restricted, + // because the user can load arbitrary code. + if (cmdletInfo != null && cmdletInfo.Visibility == SessionStateEntryVisibility.Public) { return false; } - - // For special case '?' alias don't use Get-Command to retrieve command info, and instead - // use the GetCommand API. - if (specialCaseWhereCommandAlias) - { - var cmdInfo = ps.Runspace.ExecutionContext.SessionState.InvokeCommand.GetCommand(WhereObjectCommandAlias, CommandTypes.Alias); - if (cmdInfo == null) - { - return false; - } - - cmdInfoList.Add(cmdInfo); - } - return true; } - internal static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTerminal) - { - var outputRendering = OutputRendering.Ansi; - - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - if (supportsVirtualTerminal != false) - { - switch (PSStyle.Instance.OutputRendering) - { - case OutputRendering.Automatic: - outputRendering = OutputRendering.Ansi; - break; - case OutputRendering.Host: - outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; - break; - default: - outputRendering = PSStyle.Instance.OutputRendering; - break; - } - } - } - - return outputRendering == OutputRendering.PlainText; - } - - internal static string GetOutputString(string s, bool isHost, bool? supportsVirtualTerminal = null, bool isOutputRedirected = false) + /// + /// Determine whether the environment variable is set and how. + /// + /// The name of the environment variable. + /// If the environment variable is not set, use this as the default value. + /// A boolean representing the value of the environment variable. + internal static bool GetEnvironmentVariableAsBool(string name, bool defaultValue) { - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + var str = Environment.GetEnvironmentVariable(name); + if (string.IsNullOrEmpty(str)) { - var sd = new ValueStringDecorated(s); - - if (sd.IsDecorated) - { - var outputRendering = OutputRendering.Ansi; - if (InternalTestHooks.BypassOutputRedirectionCheck) - { - isOutputRedirected = false; - } - - if (isOutputRedirected || ShouldOutputPlainText(isHost, supportsVirtualTerminal)) - { - outputRendering = OutputRendering.PlainText; - } - - s = sd.ToString(outputRendering); - } + return defaultValue; } - return s; - } + var boolStr = str.AsSpan(); - internal enum FormatStyle - { - Reset, - FormatAccent, - ErrorAccent, - Error, - Warning, - Verbose, - Debug, - } - - internal static string GetFormatStyleString(FormatStyle formatStyle) - { - // redirected console gets plaintext output to preserve existing behavior - if (!InternalTestHooks.BypassOutputRedirectionCheck && - ((PSStyle.Instance.OutputRendering == OutputRendering.PlainText) || - (formatStyle == FormatStyle.Error && Console.IsErrorRedirected) || - (formatStyle != FormatStyle.Error && Console.IsOutputRedirected))) + if (boolStr.Length == 1) { - return string.Empty; - } - - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) - { - PSStyle psstyle = PSStyle.Instance; - switch (formatStyle) + if (boolStr[0] == '1') { - case FormatStyle.Reset: - return psstyle.Reset; - case FormatStyle.FormatAccent: - return psstyle.Formatting.FormatAccent; - case FormatStyle.ErrorAccent: - return psstyle.Formatting.ErrorAccent; - case FormatStyle.Error: - return psstyle.Formatting.Error; - case FormatStyle.Warning: - return psstyle.Formatting.Warning; - case FormatStyle.Verbose: - return psstyle.Formatting.Verbose; - case FormatStyle.Debug: - return psstyle.Formatting.Debug; - default: - return string.Empty; + return true; } - } - - return string.Empty; - } - - #endregion - } - - #region ImplicitRemotingBatching - - // A visitor to walk an AST and validate that it is a candidate for implicit remoting batching. - // Based on ScriptBlockToPowerShellChecker. - internal class PipelineForBatchingChecker : AstVisitor - { - internal readonly HashSet ValidVariables = new HashSet(StringComparer.OrdinalIgnoreCase); - internal readonly HashSet Commands = new HashSet(StringComparer.OrdinalIgnoreCase); - - internal ScriptBlockAst ScriptBeingConverted { get; set; } - - public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) - { - if (!variableExpressionAst.VariablePath.IsAnyLocal()) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "VariableTypeNotSupported"), - variableExpressionAst); - } - - if (variableExpressionAst.VariablePath.UnqualifiedPath != "_") - { - ValidVariables.Add(variableExpressionAst.VariablePath.UnqualifiedPath); - } - - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitPipeline(PipelineAst pipelineAst) - { - if (pipelineAst.PipelineElements[0] is CommandExpressionAst) - { - // If the first element is a CommandExpression, this pipeline should be the value - // of a parameter. We want to avoid a scriptblock that contains only a pure expression. - // The check "pipelineAst.Parent.Parent == ScriptBeingConverted" guarantees we throw - // error on that kind of scriptblock. - // Disallow pure expressions at the "top" level, but allow them otherwise. - // We want to catch: - // 1 | echo - // But we don't want to error out on: - // echo $(1) - // See the comment in VisitCommand on why it's safe to check Parent.Parent, we - // know that we have at least: - // * a NamedBlockAst (the end block) - // * a ScriptBlockAst (the ast we're comparing to) - if (pipelineAst.GetPureExpression() == null || pipelineAst.Parent.Parent == ScriptBeingConverted) + if (boolStr[0] == '0') { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "PipelineStartingWithExpressionNotSupported"), - pipelineAst); + return false; } } - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitCommand(CommandAst commandAst) - { - if (commandAst.InvocationOperator == TokenKind.Dot) + if (boolStr.Length == 3 && + (boolStr[0] == 'y' || boolStr[0] == 'Y') && + (boolStr[1] == 'e' || boolStr[1] == 'E') && + (boolStr[2] == 's' || boolStr[2] == 'S')) { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "DotSourcingNotSupported"), - commandAst); - } - - /* - // Up front checking ensures that we have a simple script block, - // so we can safely assume that the parents are: - // * a PipelineAst - // * a NamedBlockAst (the end block) - // * a ScriptBlockAst (the ast we're comparing to) - // If that isn't the case, the conversion isn't allowed. It - // is also safe to assume that we have at least 3 parents, a script block can't be simpler. - if (commandAst.Parent.Parent.Parent != ScriptBeingConverted) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "CantConvertWithCommandInvocations not supported"), - commandAst); + return true; } - */ - if (commandAst.CommandElements[0] is ScriptBlockExpressionAst) + if (boolStr.Length == 2 && + (boolStr[0] == 'n' || boolStr[0] == 'N') && + (boolStr[1] == 'o' || boolStr[1] == 'O')) { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "ScriptBlockInvocationNotSupported"), - commandAst); + return false; } - var commandName = commandAst.GetCommandName(); - if (commandName != null) + if (boolStr.Length == 4 && + (boolStr[0] == 't' || boolStr[0] == 'T') && + (boolStr[1] == 'r' || boolStr[1] == 'R') && + (boolStr[2] == 'u' || boolStr[2] == 'U') && + (boolStr[3] == 'e' || boolStr[3] == 'E')) { - Commands.Add(commandName); + return true; } - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitMergingRedirection(MergingRedirectionAst redirectionAst) - { - if (redirectionAst.ToStream != RedirectionStream.Output) + if (boolStr.Length == 5 && + (boolStr[0] == 'f' || boolStr[0] == 'F') && + (boolStr[1] == 'a' || boolStr[1] == 'A') && + (boolStr[2] == 'l' || boolStr[2] == 'L') && + (boolStr[3] == 's' || boolStr[3] == 'S') && + (boolStr[4] == 'e' || boolStr[4] == 'E')) { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "MergeRedirectionNotSupported"), - redirectionAst); + return false; } - return AstVisitAction.Continue; - } - - public override AstVisitAction VisitFileRedirection(FileRedirectionAst redirectionAst) - { - ThrowError( - new ImplicitRemotingBatchingNotSupportedException( - "FileRedirectionNotSupported"), - redirectionAst); - - return AstVisitAction.Continue; - } - - /* - public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) - { - ThrowError(new ImplicitRemotingBatchingNotSupportedException( - "ScriptBlocks not supported"), - scriptBlockExpressionAst); - - return AstVisitAction.SkipChildren; - } - */ - - public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpressionAst) - { - // Using expressions are not expected in Implicit remoting commands. - ThrowError(new ImplicitRemotingBatchingNotSupportedException( - "UsingExpressionNotSupported"), - usingExpressionAst); - - return AstVisitAction.SkipChildren; - } - - internal static void ThrowError(ImplicitRemotingBatchingNotSupportedException ex, Ast ast) - { - InterpreterError.UpdateExceptionErrorRecordPosition(ex, ast.Extent); - throw ex; - } - } - - internal class ImplicitRemotingBatchingNotSupportedException : Exception - { - internal string ErrorId { get; } - - internal ImplicitRemotingBatchingNotSupportedException(string errorId) : base( - ParserStrings.ImplicitRemotingPipelineBatchingNotSupported) - { - ErrorId = errorId; + return defaultValue; } } - - #endregion } namespace System.Management.Automation.Internal @@ -2071,8 +1628,12 @@ public static class InternalTestHooks internal static bool BypassAppLockerPolicyCaching; internal static bool BypassOnlineHelpRetrieval; internal static bool ForcePromptForChoiceDefaultOption; - internal static bool BypassOutputRedirectionCheck; internal static bool NoPromptForPassword; + internal static bool ForceFormatListFixedLabelWidth; + + // Update-Help tests + internal static bool ThrowHelpCultureNotSupported; + internal static CultureInfo CurrentUICulture; // Stop/Restart/Rename Computer tests internal static bool TestStopComputer; @@ -2089,6 +1650,11 @@ public static class InternalTestHooks internal static bool SetConsoleWidthToZero; internal static bool SetConsoleHeightToZero; + // Simulate 'MyDocuments' returning empty string + internal static bool SetMyDocumentsSpecialFolderToBlank; + + internal static bool SetDate; + // A location to test PSEdition compatibility functionality for Windows PowerShell modules with // since we can't manipulate the System32 directory in a test internal static string TestWindowsPowerShellPSHomeLocation; @@ -2100,27 +1666,22 @@ public static class InternalTestHooks internal static bool ThrowExdevErrorOnMoveDirectory; + // To emulate OneDrive behavior we use the hard-coded symlink. + // If OneDriveTestRecurseOn is false then the symlink works as regular symlink. + // If OneDriveTestRecurseOn is true then we recurse into the symlink as OneDrive should work. + // OneDriveTestSymlinkName defines the symlink name used in tests. + internal static bool OneDriveTestOn; + internal static bool OneDriveTestRecurseOn; + internal static string OneDriveTestSymlinkName = "link-Beta"; + + // Test out smaller connection buffer size when calling WNetGetConnection. + internal static int WNetGetConnectionBufferSize = -1; + /// This member is used for internal test purposes. public static void SetTestHook(string property, object value) { var fieldInfo = typeof(InternalTestHooks).GetField(property, BindingFlags.Static | BindingFlags.NonPublic); - if (fieldInfo != null) - { - fieldInfo.SetValue(null, value); - } - } - - /// - /// Test hook used to test implicit remoting batching. A local runspace must be provided that has imported a - /// remote session, i.e., has run the Import-PSSession cmdlet. This hook will return true if the provided commandPipeline - /// is successfully batched and run in the remote session, and false if it is rejected for batching. - /// - /// Command pipeline to test. - /// Runspace with imported remote session. - /// True if commandPipeline is batched successfully. - public static bool TestImplicitRemotingBatching(string commandPipeline, System.Management.Automation.Runspaces.Runspace runspace) - { - return Utils.TryRunAsImplicitBatch(commandPipeline, runspace); + fieldInfo?.SetValue(null, value); } /// @@ -2258,10 +1819,7 @@ internal sealed class ReadOnlyBag : IEnumerable /// internal ReadOnlyBag(HashSet hashset) { - if (hashset == null) - { - throw new ArgumentNullException(nameof(hashset)); - } + ArgumentNullException.ThrowIfNull(hashset); _hashset = hashset; } @@ -2297,36 +1855,12 @@ internal ReadOnlyBag(HashSet hashset) /// internal static class Requires { - internal static void NotNull(object value, string paramName) - { - if (value == null) - { - throw new ArgumentNullException(paramName); - } - } - - internal static void NotNullOrEmpty(string value, string paramName) - { - if (string.IsNullOrEmpty(value)) - { - throw new ArgumentNullException(paramName); - } - } - internal static void NotNullOrEmpty(ICollection value, string paramName) { - if (value == null || value.Count == 0) + if (value is null || value.Count == 0) { throw new ArgumentNullException(paramName); } } - - internal static void Condition([DoesNotReturnIf(false)] bool precondition, string paramName) - { - if (!precondition) - { - throw new ArgumentException(paramName); - } - } } } diff --git a/src/System.Management.Automation/engine/WinRT/IInspectable.cs b/src/System.Management.Automation/engine/WinRT/IInspectable.cs index abc589b4875..28544d42af4 100644 --- a/src/System.Management.Automation/engine/WinRT/IInspectable.cs +++ b/src/System.Management.Automation/engine/WinRT/IInspectable.cs @@ -4,6 +4,7 @@ using System.Reflection; using System.Runtime.InteropServices; +#nullable enable namespace System.Management.Automation { /// diff --git a/src/System.Management.Automation/engine/cmdlet.cs b/src/System.Management.Automation/engine/cmdlet.cs index b049193fd87..db2233d44a9 100644 --- a/src/System.Management.Automation/engine/cmdlet.cs +++ b/src/System.Management.Automation/engine/cmdlet.cs @@ -10,7 +10,7 @@ using System.Reflection; using System.Resources; using System.Management.Automation.Internal; -using Dbg = System.Management.Automation.Diagnostics; +using System.Threading; namespace System.Management.Automation { @@ -23,7 +23,7 @@ namespace System.Management.Automation /// deriving from the PSCmdlet base class. The Cmdlet base class is the primary means by /// which users create their own Cmdlets. Extending this class provides support for the most /// common functionality, including object output and record processing. - /// If your Cmdlet requires access to the MSH Runtime (for example, variables in the session state, + /// If your Cmdlet requires access to the PowerShell Runtime (for example, variables in the session state, /// access to the host, or information about the current Cmdlet Providers,) then you should instead /// derive from the PSCmdlet base class. /// In both cases, users should first develop and implement an object model to accomplish their @@ -50,7 +50,7 @@ public static HashSet CommonParameters () => { return new HashSet(StringComparer.OrdinalIgnoreCase) { - "Verbose", "Debug", "ErrorAction", "WarningAction", "InformationAction", + "Verbose", "Debug", "ErrorAction", "WarningAction", "InformationAction", "ProgressAction", "ErrorVariable", "WarningVariable", "OutVariable", "OutBuffer", "PipelineVariable", "InformationVariable" }; } @@ -100,6 +100,11 @@ public bool Stopping } } + /// + /// Gets the CancellationToken that is signaled when the pipeline is stopping. + /// + public CancellationToken PipelineStopToken => StopToken; + /// /// The name of the parameter set in effect. /// @@ -453,6 +458,9 @@ public void WriteVerbose(string text) } } + internal bool IsWriteVerboseEnabled() + => commandRuntime is not MshCommandRuntime mshRuntime || mshRuntime.IsWriteVerboseEnabled(); + /// /// Display warning information. /// @@ -490,6 +498,9 @@ public void WriteWarning(string text) } } + internal bool IsWriteWarningEnabled() + => commandRuntime is not MshCommandRuntime mshRuntime || mshRuntime.IsWriteWarningEnabled(); + /// /// Write text into pipeline execution log. /// @@ -511,7 +522,7 @@ public void WriteWarning(string text) /// pipeline execution log. /// /// If LogPipelineExecutionDetail is turned on, this information will be written - /// to monad log under log category "Pipeline execution detail" + /// to PowerShell log under log category "Pipeline execution detail" /// /// /// @@ -598,6 +609,9 @@ internal void WriteProgress( throw new System.NotImplementedException("WriteProgress"); } + internal bool IsWriteProgressEnabled() + => commandRuntime is not MshCommandRuntime mshRuntime || mshRuntime.IsWriteProgressEnabled(); + /// /// Display debug information. /// @@ -641,6 +655,9 @@ public void WriteDebug(string text) } } + internal bool IsWriteDebugEnabled() + => commandRuntime is not MshCommandRuntime mshRuntime || mshRuntime.IsWriteDebugEnabled(); + /// /// Route information to the user or host. /// @@ -748,6 +765,9 @@ public void WriteInformation(InformationRecord informationRecord) } } + internal bool IsWriteInformationEnabled() + => commandRuntime is not MshCommandRuntime mshRuntime || mshRuntime.IsWriteInformationEnabled(); + #endregion Write #region ShouldProcess @@ -801,8 +821,8 @@ public void WriteInformation(InformationRecord informationRecord) /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype1")] /// public class RemoveMyObjectType1 : Cmdlet @@ -824,7 +844,7 @@ public void WriteInformation(InformationRecord informationRecord) /// } /// } /// } - /// + /// /// /// /// @@ -897,8 +917,8 @@ public bool ShouldProcess(string target) /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype2")] /// public class RemoveMyObjectType2 : Cmdlet @@ -920,7 +940,7 @@ public bool ShouldProcess(string target) /// } /// } /// } - /// + /// /// /// /// @@ -1001,8 +1021,8 @@ public bool ShouldProcess(string target, string action) /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : Cmdlet @@ -1018,8 +1038,8 @@ public bool ShouldProcess(string target, string action) /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file")) /// { /// // delete the object @@ -1027,7 +1047,7 @@ public bool ShouldProcess(string target, string action) /// } /// } /// } - /// + /// /// /// /// @@ -1117,8 +1137,8 @@ public bool ShouldProcess( /// , /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype3")] /// public class RemoveMyObjectType3 : Cmdlet @@ -1135,8 +1155,8 @@ public bool ShouldProcess( /// { /// ShouldProcessReason shouldProcessReason; /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}?", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}?"), /// "Delete file", /// out shouldProcessReason)) /// { @@ -1145,7 +1165,7 @@ public bool ShouldProcess( /// } /// } /// } - /// + /// /// /// /// @@ -1233,8 +1253,8 @@ public bool ShouldProcess( /// to ShouldProcess for the Cmdlet instance. /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType4 : Cmdlet @@ -1258,14 +1278,14 @@ public bool ShouldProcess( /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file")) /// ) /// { @@ -1277,7 +1297,7 @@ public bool ShouldProcess( /// } /// } /// } - /// + /// /// /// /// @@ -1311,11 +1331,11 @@ public bool ShouldContinue(string query, string caption) /// It may be displayed by some hosts, but not all. /// /// - /// true iff user selects YesToAll. If this is already true, + /// true if-and-only-if user selects YesToAll. If this is already true, /// ShouldContinue will bypass the prompt and return true. /// /// - /// true iff user selects NoToAll. If this is already true, + /// true if-and-only-if user selects NoToAll. If this is already true, /// ShouldContinue will bypass the prompt and return false. /// /// @@ -1362,8 +1382,8 @@ public bool ShouldContinue(string query, string caption) /// to ShouldProcess for the Cmdlet instance. /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType5 : Cmdlet @@ -1390,14 +1410,14 @@ public bool ShouldContinue(string query, string caption) /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file"), /// ref yesToAll, /// ref noToAll @@ -1411,7 +1431,7 @@ public bool ShouldContinue(string query, string caption) /// } /// } /// } - /// + /// /// /// /// @@ -1451,11 +1471,11 @@ public bool ShouldContinue( /// the default option selected in the selection menu is 'No'. /// /// - /// true iff user selects YesToAll. If this is already true, + /// true if-and-only-if user selects YesToAll. If this is already true, /// ShouldContinue will bypass the prompt and return true. /// /// - /// true iff user selects NoToAll. If this is already true, + /// true if-and-only-if user selects NoToAll. If this is already true, /// ShouldContinue will bypass the prompt and return false. /// /// @@ -1502,8 +1522,8 @@ public bool ShouldContinue( /// to ShouldProcess for the Cmdlet instance. /// /// - /// - /// namespace Microsoft.Samples.MSH.Cmdlet + /// + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet(VerbsCommon.Remove,"myobjecttype4")] /// public class RemoveMyObjectType5 : Cmdlet @@ -1530,14 +1550,14 @@ public bool ShouldContinue( /// public override void ProcessRecord() /// { /// if (ShouldProcess( - /// string.Format("Deleting file {0}",filename), - /// string.Format("Are you sure you want to delete file {0}", filename), + /// string.Format($"Deleting file {filename}"), + /// string.Format($"Are you sure you want to delete file {filename}"), /// "Delete file")) /// { /// if (IsReadOnly(filename)) /// { /// if (!Force && !ShouldContinue( - /// string.Format("File {0} is read-only. Are you sure you want to delete read-only file {0}?", filename), + /// string.Format($"File {filename} is read-only. Are you sure you want to delete read-only file {filename}?"), /// "Delete file"), /// ref yesToAll, /// ref noToAll @@ -1551,7 +1571,7 @@ public bool ShouldContinue( /// } /// } /// } - /// + /// /// /// /// @@ -1714,12 +1734,12 @@ public PSTransactionContext CurrentPSTransaction /// . /// etc. /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) { - if (errorRecord == null) - throw new ArgumentNullException(nameof(errorRecord)); + ArgumentNullException.ThrowIfNull(errorRecord); if (commandRuntime != null) { @@ -1820,14 +1840,16 @@ public enum ShouldProcessReason None = 0x0, /// + /// /// WhatIf behavior was requested. - /// - /// - /// In the MSH host, WhatIf behavior can be requested explicitly + /// + /// + /// In the host, WhatIf behavior can be requested explicitly /// for one cmdlet instance using the -WhatIf commandline parameter, /// or implicitly for all SupportsShouldProcess cmdlets with $WhatIfPreference. /// Other hosts may have other ways to request WhatIf behavior. - /// + /// + /// WhatIf = 0x1, } } diff --git a/src/System.Management.Automation/engine/debugger/Breakpoint.cs b/src/System.Management.Automation/engine/debugger/Breakpoint.cs index ca1c9818206..c4b699bd152 100644 --- a/src/System.Management.Automation/engine/debugger/Breakpoint.cs +++ b/src/System.Management.Automation/engine/debugger/Breakpoint.cs @@ -439,7 +439,7 @@ public override string ToString() internal BitArray BreakpointBitArray { get; set; } - private class CheckBreakpointInScript : AstVisitor + private sealed class CheckBreakpointInScript : AstVisitor { public static bool IsInNestedScriptBlock(Ast ast, LineBreakpoint breakpoint) { @@ -482,9 +482,6 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex { Diagnostics.Assert(SequencePointIndex == -1, "shouldn't be trying to set on a pending breakpoint"); - if (!scriptFile.Equals(this.Script, StringComparison.OrdinalIgnoreCase)) - return false; - // A quick check to see if the breakpoint is within the scriptblock. bool couldBeInNestedScriptBlock; var scriptBlock = functionContext._scriptBlock; @@ -531,15 +528,16 @@ internal bool TrySetBreakpoint(string scriptFile, FunctionContext functionContex // Not found. First, we check if the line/column is before any real code. If so, we'll // move the breakpoint to the first interesting sequence point (could be a dynamicparam, - // begin, process, or end block.) + // begin, process, end, or clean block.) if (scriptBlock != null) { var ast = scriptBlock.Ast; var bodyAst = ((IParameterMetadataProvider)ast).Body; - if ((bodyAst.DynamicParamBlock == null || bodyAst.DynamicParamBlock.Extent.IsAfter(Line, Column)) && - (bodyAst.BeginBlock == null || bodyAst.BeginBlock.Extent.IsAfter(Line, Column)) && - (bodyAst.ProcessBlock == null || bodyAst.ProcessBlock.Extent.IsAfter(Line, Column)) && - (bodyAst.EndBlock == null || bodyAst.EndBlock.Extent.IsAfter(Line, Column))) + if ((bodyAst.DynamicParamBlock == null || bodyAst.DynamicParamBlock.Extent.IsAfter(Line, Column)) + && (bodyAst.BeginBlock == null || bodyAst.BeginBlock.Extent.IsAfter(Line, Column)) + && (bodyAst.ProcessBlock == null || bodyAst.ProcessBlock.Extent.IsAfter(Line, Column)) + && (bodyAst.EndBlock == null || bodyAst.EndBlock.Extent.IsAfter(Line, Column)) + && (bodyAst.CleanBlock == null || bodyAst.CleanBlock.Extent.IsAfter(Line, Column))) { SetBreakpoint(functionContext, 0); return true; @@ -594,11 +592,11 @@ internal override bool RemoveSelf(ScriptDebugger debugger) var boundBreakPoints = debugger.GetBoundBreakpoints(this.SequencePoints); if (boundBreakPoints != null) { - Diagnostics.Assert(boundBreakPoints.Contains(this), + Diagnostics.Assert(boundBreakPoints[this.SequencePointIndex].Contains(this), "If we set _scriptBlock, we should have also added the breakpoint to the bound breakpoint list"); - boundBreakPoints.Remove(this); + boundBreakPoints[this.SequencePointIndex].Remove(this); - if (boundBreakPoints.All(breakpoint => breakpoint.SequencePointIndex != this.SequencePointIndex)) + if (boundBreakPoints[this.SequencePointIndex].All(breakpoint => breakpoint.SequencePointIndex != this.SequencePointIndex)) { // No other line breakpoints are at the same sequence point, so disable the breakpoint so // we don't go looking for breakpoints the next time we hit the sequence point. diff --git a/src/System.Management.Automation/engine/debugger/debugger.cs b/src/System.Management.Automation/engine/debugger/debugger.cs index 30e83c38f90..985d90ab3ec 100644 --- a/src/System.Management.Automation/engine/debugger/debugger.cs +++ b/src/System.Management.Automation/engine/debugger/debugger.cs @@ -790,6 +790,16 @@ internal virtual void Break(object triggerObject = null) throw new PSNotImplementedException(); } + /// + /// Returns script position message of current execution stack item. + /// This is used for WDAC audit mode logging for script information enhancement. + /// + /// Script position message string. + internal virtual string GetCurrentScriptPosition() + { + throw new PSNotImplementedException(); + } + /// /// Passes the debugger command to the internal script debugger command processor. This /// is used internally to handle debugger commands such as list, help, etc. @@ -971,7 +981,8 @@ internal ScriptDebugger(ExecutionContext context) _context = context; _inBreakpoint = false; _idToBreakpoint = new ConcurrentDictionary(); - _pendingBreakpoints = new ConcurrentDictionary(); + // The string key is function context file path. The int key is sequencePoint index. + _pendingBreakpoints = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); _boundBreakpoints = new ConcurrentDictionary>>(StringComparer.OrdinalIgnoreCase); _commandBreakpoints = new ConcurrentDictionary(); _variableBreakpoints = new ConcurrentDictionary>(StringComparer.OrdinalIgnoreCase); @@ -1057,12 +1068,9 @@ private bool IsLocalSession { get { - if (_isLocalSession == null) - { - // Remote debug sessions always have a ServerRemoteHost. Otherwise it is a local session. - _isLocalSession = !(((_context.InternalHost.ExternalHost != null) && - (_context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost))); - } + // Remote debug sessions always have a ServerRemoteHost. Otherwise it is a local session. + _isLocalSession ??= !((_context.InternalHost.ExternalHost != null) && + (_context.InternalHost.ExternalHost is System.Management.Automation.Remoting.ServerRemoteHost)); return _isLocalSession.Value; } @@ -1177,7 +1185,7 @@ internal void EnterScriptFunction(FunctionContext functionContext) private void SetupBreakpoints(FunctionContext functionContext) { var scriptDebugData = _mapScriptToBreakpoints.GetValue(functionContext._sequencePoints, - _ => Tuple.Create(new List(), + _ => Tuple.Create(new Dictionary>(), new BitArray(functionContext._sequencePoints.Length))); functionContext._boundBreakpoints = scriptDebugData.Item1; functionContext._breakPoints = scriptDebugData.Item2; @@ -1257,10 +1265,19 @@ private CommandBreakpoint AddCommandBreakpoint(CommandBreakpoint breakpoint) private LineBreakpoint AddLineBreakpoint(LineBreakpoint breakpoint) { AddBreakpointCommon(breakpoint); - _pendingBreakpoints[breakpoint.Id] = breakpoint; + AddPendingBreakpoint(breakpoint); + return breakpoint; } + private void AddPendingBreakpoint(LineBreakpoint breakpoint) + { + _pendingBreakpoints.AddOrUpdate( + breakpoint.Script, + new ConcurrentDictionary { [breakpoint.Id] = breakpoint }, + (_, dictionary) => { dictionary.TryAdd(breakpoint.Id, breakpoint); return dictionary; }); + } + private void AddNewBreakpoint(Breakpoint breakpoint) { LineBreakpoint lineBreakpoint = breakpoint as LineBreakpoint; @@ -1313,13 +1330,9 @@ private void UpdateBreakpoints(FunctionContext functionContext) return; } - foreach ((int breakpointId, LineBreakpoint item) in _pendingBreakpoints) + if (_pendingBreakpoints.TryGetValue(functionContext._file, out var dictionary) && !dictionary.IsEmpty) { - if (item.IsScriptBreakpoint && item.Script.Equals(functionContext._file, StringComparison.OrdinalIgnoreCase)) - { - SetPendingBreakpoints(functionContext); - break; - } + SetPendingBreakpoints(functionContext); } } } @@ -1345,7 +1358,11 @@ internal bool RemoveCommandBreakpoint(CommandBreakpoint breakpoint) => internal bool RemoveLineBreakpoint(LineBreakpoint breakpoint) { - bool removed = _pendingBreakpoints.Remove(breakpoint.Id, out _); + bool removed = false; + if (_pendingBreakpoints.TryGetValue(breakpoint.Script, out var dictionary)) + { + removed = dictionary.Remove(breakpoint.Id, out _); + } Tuple> value; if (_boundBreakpoints.TryGetValue(breakpoint.Script, out value)) @@ -1363,8 +1380,8 @@ internal bool RemoveLineBreakpoint(LineBreakpoint breakpoint) // The bit array is used to detect if a breakpoint is set or not for a given scriptblock. This bit array // is checked when hitting sequence points. Enabling/disabling a line breakpoint is as simple as flipping // the bit. - private readonly ConditionalWeakTable, BitArray>> _mapScriptToBreakpoints = - new ConditionalWeakTable, BitArray>>(); + private readonly ConditionalWeakTable>, BitArray>> _mapScriptToBreakpoints = + new ConditionalWeakTable>, BitArray>>(); /// /// Checks for command breakpoints. @@ -1465,9 +1482,9 @@ internal void TriggerVariableBreakpoints(List breakpoints) // Return the line breakpoints bound in a specific script block (used when a sequence point // is hit, to find which breakpoints are set on that sequence point.) - internal List GetBoundBreakpoints(IScriptExtent[] sequencePoints) + internal Dictionary> GetBoundBreakpoints(IScriptExtent[] sequencePoints) { - Tuple, BitArray> tuple; + Tuple>, BitArray> tuple; if (_mapScriptToBreakpoints.TryGetValue(sequencePoints, out tuple)) { return tuple.Item1; @@ -1519,7 +1536,16 @@ private List TriggerBreakpoints(List breakpoints) internal void OnSequencePointHit(FunctionContext functionContext) { - if (_context.ShouldTraceStatement && !_callStack.Last().IsFrameHidden && !functionContext._debuggerStepThrough) + // TraceLine uses ColumnNumber and expects it to be 1 based. For + // extents added by the engine and not user code the value can be + // set to 0 causing an exception. This skips those types of extents + // as tracing them wouldn't be useful for the end user anyway. + if (_context.ShouldTraceStatement && + !_callStack.Last().IsFrameHidden && + !functionContext._debuggerStepThrough && + functionContext.CurrentPosition is not EmptyScriptExtent && + (functionContext.CurrentPosition is InternalScriptExtent || + functionContext.CurrentPosition.StartColumnNumber > 0)) { TraceLine(functionContext.CurrentPosition); } @@ -1553,16 +1579,25 @@ internal void OnSequencePointHit(FunctionContext functionContext) { if (functionContext._breakPoints[functionContext._currentSequencePointIndex]) { - var breakpoints = (from breakpoint in functionContext._boundBreakpoints - where - breakpoint.SequencePointIndex == functionContext._currentSequencePointIndex && - breakpoint.Enabled - select breakpoint).ToList(); - - breakpoints = TriggerBreakpoints(breakpoints); - if (breakpoints.Count > 0) + if (functionContext._boundBreakpoints.TryGetValue(functionContext._currentSequencePointIndex, out var sequencePointBreakpoints)) { - StopOnSequencePoint(functionContext, breakpoints); + var enabledBreakpoints = new List(); + foreach (Breakpoint breakpoint in sequencePointBreakpoints) + { + if (breakpoint.Enabled) + { + enabledBreakpoints.Add(breakpoint); + } + } + + if (enabledBreakpoints.Count > 0) + { + enabledBreakpoints = TriggerBreakpoints(enabledBreakpoints); + if (enabledBreakpoints.Count > 0) + { + StopOnSequencePoint(functionContext, enabledBreakpoints); + } + } } } } @@ -1575,7 +1610,7 @@ internal void OnSequencePointHit(FunctionContext functionContext) #region private members [DebuggerDisplay("{FunctionContext.CurrentPosition}")] - private class CallStackInfo + private sealed class CallStackInfo { internal InvocationInfo InvocationInfo { get; set; } @@ -1676,7 +1711,7 @@ internal void Clear() } private readonly ExecutionContext _context; - private ConcurrentDictionary _pendingBreakpoints; + private readonly ConcurrentDictionary> _pendingBreakpoints; private readonly ConcurrentDictionary>> _boundBreakpoints; private readonly ConcurrentDictionary _commandBreakpoints; private readonly ConcurrentDictionary> _variableBreakpoints; @@ -1807,7 +1842,8 @@ private void OnDebuggerStop(InvocationInfo invocationInfo, List brea { // Fix up prompt. ++index; - string debugPrompt = "\"[DBG]: " + originalPromptString.Substring(index, originalPromptString.Length - index); + string debugPrompt = string.Concat("\"[DBG]: ", originalPromptString.AsSpan(index, originalPromptString.Length - index)); + defaultPromptInfo.Update( ScriptBlock.Create(debugPrompt), true, ScopedItemOptions.Unspecified); } @@ -1948,10 +1984,7 @@ private bool WaitForDebugStopSubscriber() if (_preserveUnhandledDebugStopEvent) { // Lazily create the event object. - if (_preserveDebugStopEvent == null) - { - _preserveDebugStopEvent = new ManualResetEventSlim(true); - } + _preserveDebugStopEvent ??= new ManualResetEventSlim(true); // Set the event handle to non-signaled. if (!_preserveDebugStopEvent.IsSet) @@ -1986,16 +2019,20 @@ private void UnbindBoundBreakpoints(List boundBreakpoints) foreach (var breakpoint in boundBreakpoints) { // Also remove unbound breakpoints from the script to breakpoint map. - Tuple, BitArray> lineBreakTuple; + Tuple>, BitArray> lineBreakTuple; if (_mapScriptToBreakpoints.TryGetValue(breakpoint.SequencePoints, out lineBreakTuple)) { - lineBreakTuple.Item1.Remove(breakpoint); + if (lineBreakTuple.Item1.TryGetValue(breakpoint.SequencePointIndex, out var lineBreakList)) + { + lineBreakList.Remove(breakpoint); + } } breakpoint.SequencePoints = null; breakpoint.SequencePointIndex = -1; breakpoint.BreakpointBitArray = null; - _pendingBreakpoints[breakpoint.Id] = breakpoint; + + AddPendingBreakpoint(breakpoint); } boundBreakpoints.Clear(); @@ -2003,23 +2040,24 @@ private void UnbindBoundBreakpoints(List boundBreakpoints) private void SetPendingBreakpoints(FunctionContext functionContext) { - if (_pendingBreakpoints.IsEmpty) - return; - - var newPendingBreakpoints = new Dictionary(); var currentScriptFile = functionContext._file; // If we're not in a file, we can't have any line breakpoints. if (currentScriptFile == null) return; + if (!_pendingBreakpoints.TryGetValue(currentScriptFile, out var breakpoints) || breakpoints.IsEmpty) + { + return; + } + // Normally we register a script file when the script is run or the module is imported, // but if there weren't any breakpoints when the script was run and the script was dotted, // we will end up here with pending breakpoints, but we won't have cached the list of // breakpoints in the script. RegisterScriptFile(currentScriptFile, functionContext.CurrentPosition.StartScriptPosition.GetFullScript()); - Tuple, BitArray> tuple; + Tuple>, BitArray> tuple; if (!_mapScriptToBreakpoints.TryGetValue(functionContext._sequencePoints, out tuple)) { Diagnostics.Assert(false, "If the script block is still alive, the entry should not be collected."); @@ -2027,7 +2065,7 @@ private void SetPendingBreakpoints(FunctionContext functionContext) Diagnostics.Assert(tuple.Item1 == functionContext._boundBreakpoints, "What's up?"); - foreach ((int breakpointId, LineBreakpoint breakpoint) in _pendingBreakpoints) + foreach ((int breakpointId, LineBreakpoint breakpoint) in breakpoints) { bool bound = false; if (breakpoint.TrySetBreakpoint(currentScriptFile, functionContext)) @@ -2038,7 +2076,15 @@ private void SetPendingBreakpoints(FunctionContext functionContext) } bound = true; - tuple.Item1.Add(breakpoint); + + if (tuple.Item1.TryGetValue(breakpoint.SequencePointIndex, out var list)) + { + list.Add(breakpoint); + } + else + { + tuple.Item1.Add(breakpoint.SequencePointIndex, new List { breakpoint }); + } // We need to keep track of any breakpoints that are bound in each script because they may // need to be rebound if the script changes. @@ -2046,13 +2092,16 @@ private void SetPendingBreakpoints(FunctionContext functionContext) boundBreakpoints[breakpoint.Id] = breakpoint; } - if (!bound) + if (bound) { - newPendingBreakpoints.Add(breakpoint.Id, breakpoint); + breakpoints.TryRemove(breakpointId, out _); } } - _pendingBreakpoints = new ConcurrentDictionary(newPendingBreakpoints); + // Here could check if all breakpoints for the current functionContext were bound, but because there is no atomic + // api for conditional removal we either need to lock, or do some trickery that has possibility of race conditions. + // Instead we keep the item in the dictionary with 0 breakpoint count. This should not be a big issue, + // because it is single entry per file that had breakpoints, so there won't be thousands of files in a session. } private void StopOnSequencePoint(FunctionContext functionContext, List breakpoints) @@ -2134,7 +2183,7 @@ private bool CanDisableDebugger { get { - // The debugger can be disbled if there are no breakpoints + // The debugger can be disabled if there are no breakpoints // left and if we are not currently stepping in the debugger. return _idToBreakpoint.IsEmpty && _currentDebuggerAction != DebuggerResumeAction.StepInto && @@ -2151,11 +2200,8 @@ private bool IsSystemLockedDown { lock (_syncObject) { - if (_isSystemLockedDown == null) - { - _isSystemLockedDown = (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == - System.Management.Automation.Security.SystemEnforcementMode.Enforce); - } + _isSystemLockedDown ??= (System.Management.Automation.Security.SystemPolicy.GetSystemLockdownPolicy() == + System.Management.Automation.Security.SystemEnforcementMode.Enforce); } } @@ -2322,7 +2368,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC // // Otherwise let root script debugger handle it. // - if (!(_context.CurrentRunspace is LocalRunspace localRunspace)) + if (_context.CurrentRunspace is not LocalRunspace localRunspace) { throw new PSInvalidOperationException( DebuggerStrings.CannotProcessDebuggerCommandNotStopped, @@ -2394,10 +2440,7 @@ public override void StopProcessCommand() } PowerShell ps = _psDebuggerCommand; - if (ps != null) - { - ps.BeginStop(null, null); - } + ps?.BeginStop(null, null); } /// @@ -2530,6 +2573,29 @@ internal override void Break(object triggerObject = null) } } + /// + /// Returns script position message of current execution stack item. + /// This is used for WDAC audit mode logging for script information enhancement. + /// + /// Script position message string. + internal override string GetCurrentScriptPosition() + { + using (IEnumerator enumerator = GetCallStack().GetEnumerator()) + { + if (enumerator.MoveNext()) + { + var functionContext = enumerator.Current.FunctionContext; + if (functionContext is not null) + { + var invocationInfo = new InvocationInfo(commandInfo: null, functionContext.CurrentPosition, _context); + return $"\n{invocationInfo.PositionMessage}"; + } + } + } + + return null; + } + /// /// Passes the debugger command to the internal script debugger command processor. This /// is used internally to handle debugger commands such as list, help, etc. @@ -3248,11 +3314,7 @@ private void SetRunspaceListToStep(bool enableStepping) try { Debugger nestedDebugger = item.NestedDebugger; - - if (nestedDebugger != null) - { - nestedDebugger.SetDebuggerStepMode(enableStepping); - } + nestedDebugger?.SetDebuggerStepMode(enableStepping); } catch (PSNotImplementedException) { } } @@ -3554,7 +3616,7 @@ private DebuggerCommandResults ProcessCommandForActiveDebugger(PSCommand command else if ((command.Commands.Count > 0) && (command.Commands[0].CommandText.IndexOf(".EnterNestedPrompt()", StringComparison.OrdinalIgnoreCase) > 0)) { - // Prevent a host EnterNestedPrompt() call from occuring in an active debugger. + // Prevent a host EnterNestedPrompt() call from occurring in an active debugger. // Host nested prompt makes no sense in this case and can cause host to stop responding depending on host implementation. throw new PSNotSupportedException(); } @@ -3767,7 +3829,7 @@ private void HandleMonitorRunningRSDebuggerStop(object sender, DebuggerStopEvent } // Get nested debugger runspace info. - if (!(senderDebugger is NestedRunspaceDebugger nestedDebugger)) { return; } + if (senderDebugger is not NestedRunspaceDebugger nestedDebugger) { return; } PSMonitorRunspaceType runspaceType = nestedDebugger.RunspaceType; @@ -4505,7 +4567,7 @@ protected virtual bool HandleListCommand(PSDataCollection output) /// /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for - /// cases where the debugged runspace is called inside a parent sccript, + /// cases where the debugged runspace is called inside a parent script, /// such as with script Invoke-Command cases. /// /// @@ -4544,10 +4606,7 @@ internal void CheckStateAndRaiseStopEvent() // If this is a remote server debugger then we want to convert the pending remote // debugger stop to a local debugger stop event for this Debug-Runspace to handle. ServerRemoteDebugger serverRemoteDebugger = this._wrappedDebugger as ServerRemoteDebugger; - if (serverRemoteDebugger != null) - { - serverRemoteDebugger.ReleaseAndRaiseDebugStopLocal(); - } + serverRemoteDebugger?.ReleaseAndRaiseDebugStopLocal(); } } @@ -4627,7 +4686,7 @@ protected override void HandleDebuggerStop(object sender, DebuggerStopEventArgs private object DrainAndBlockRemoteOutput() { // We do this only for remote runspaces. - if (!(_runspace is RemoteRunspace remoteRunspace)) { return null; } + if (_runspace is not RemoteRunspace remoteRunspace) { return null; } var runningPowerShell = remoteRunspace.GetCurrentBasePowerShell(); if (runningPowerShell != null) @@ -4779,7 +4838,7 @@ protected override bool HandleListCommand(PSDataCollection output) /// /// Attempts to fix up the debugger stop invocation information so that /// the correct stack and source can be displayed in the debugger, for - /// cases where the debugged runspace is called inside a parent sccript, + /// cases where the debugged runspace is called inside a parent script, /// such as with script Invoke-Command cases. /// /// Invocation information from debugger stop. @@ -4959,10 +5018,7 @@ private static void RestoreRemoteOutput(object runningCmd) else { Pipeline pipelineCommand = runningCmd as Pipeline; - if (pipelineCommand != null) - { - pipelineCommand.ResumeIncomingData(); - } + pipelineCommand?.ResumeIncomingData(); } } @@ -5322,10 +5378,9 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i for (int lineNumber = start; lineNumber <= _lines.Length && lineNumber < start + count; lineNumber++) { WriteLine( - lineNumber == invocationInfo.ScriptLineNumber ? - string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, _lines[lineNumber - 1]) - : - string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, _lines[lineNumber - 1]), + lineNumber == invocationInfo.ScriptLineNumber + ? string.Format(CultureInfo.CurrentCulture, "{0,5}:* {1}", lineNumber, _lines[lineNumber - 1]) + : string.Format(CultureInfo.CurrentCulture, "{0,5}: {1}", lineNumber, _lines[lineNumber - 1]), host, output); @@ -5337,47 +5392,29 @@ private void DisplayScript(PSHost host, IList output, InvocationInfo i private static void WriteLine(string line, PSHost host, IList output) { - if (host != null) - { - host.UI.WriteLine(line); - } + host?.UI.WriteLine(line); - if (output != null) - { - output.Add(new PSObject(line)); - } + output?.Add(new PSObject(line)); } private static void WriteCR(PSHost host, IList output) { - if (host != null) - { - host.UI.WriteLine(); - } + host?.UI.WriteLine(); - if (output != null) - { - output.Add(new PSObject(Crlf)); - } + output?.Add(new PSObject(Crlf)); } private static void WriteErrorLine(string error, PSHost host, IList output) { - if (host != null) - { - host.UI.WriteErrorLine(error); - } + host?.UI.WriteErrorLine(error); - if (output != null) - { - output.Add( - new PSObject( - new ErrorRecord( - new RuntimeException(error), - "DebuggerError", - ErrorCategory.InvalidOperation, - null))); - } + output?.Add( + new PSObject( + new ErrorRecord( + new RuntimeException(error), + "DebuggerError", + ErrorCategory.InvalidOperation, + null))); } } @@ -5686,7 +5723,7 @@ public static void StartMonitoringRunspace(Debugger debugger, PSMonitorRunspaceI } /// - /// End monitoring a runspace on the target degbugger. + /// End monitoring a runspace on the target debugger. /// /// Target debugger. /// PSMonitorRunspaceInfo. diff --git a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs index f1e57e6fe39..74bcefae2a8 100644 --- a/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs +++ b/src/System.Management.Automation/engine/hostifaces/AsyncResult.cs @@ -16,7 +16,7 @@ internal class AsyncResult : IAsyncResult #region Private Data private ManualResetEvent _completedWaitHandle; - // exception occured in the async thread. + // exception occurred in the async thread. // user supplied state object // Invoke on thread (remote debugging support). @@ -85,10 +85,7 @@ public WaitHandle AsyncWaitHandle { lock (SyncObject) { - if (_completedWaitHandle == null) - { - _completedWaitHandle = new ManualResetEvent(IsCompleted); - } + _completedWaitHandle ??= new ManualResetEvent(IsCompleted); } } @@ -125,7 +122,7 @@ public WaitHandle AsyncWaitHandle /// Marks the async operation as completed. /// /// - /// Exception occured. null if no exception occured + /// Exception occurred. null if no exception occurred /// internal void SetAsCompleted(Exception exception) { @@ -178,10 +175,7 @@ internal void SignalWaitHandle() { lock (SyncObject) { - if (_completedWaitHandle != null) - { - _completedWaitHandle.Set(); - } + _completedWaitHandle?.Set(); } } @@ -222,7 +216,7 @@ internal void EndInvoke() _invokeOnThreadEvent.Dispose(); _invokeOnThreadEvent = null; // Allow early GC - // Operation is done: if an exception occured, throw it + // Operation is done: if an exception occurred, throw it if (Exception != null) { throw Exception; diff --git a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs index 1b55485afdc..0cac1d02b6f 100644 --- a/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/ChoiceDescription.cs @@ -6,8 +6,8 @@ namespace System.Management.Automation.Host { /// - /// Provides a description of a choice for use by . - /// + /// Provides a description of a choice for use by . + /// /// public sealed class ChoiceDescription @@ -84,7 +84,7 @@ class ChoiceDescription /// /// Note that the special character & (ampersand) may be embedded in the label string to identify the next character in the label /// as a "hot key" (aka "keyboard accelerator") that the Console.PromptForChoice implementation may use to allow the user to - /// quickly set input focus to this choice. The implementation of + /// quickly set input focus to this choice. The implementation of /// is responsible for parsing the label string for this special character and rendering it accordingly. /// /// For examples, a choice named "Yes to All" might have "Yes to &All" as it's label. diff --git a/src/System.Management.Automation/engine/hostifaces/Command.cs b/src/System.Management.Automation/engine/hostifaces/Command.cs index 6d8cd526486..3de339ff112 100644 --- a/src/System.Management.Automation/engine/hostifaces/Command.cs +++ b/src/System.Management.Automation/engine/hostifaces/Command.cs @@ -662,7 +662,7 @@ internal PSObject ToPSObjectForRemoting(Version psRPVersion) commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeUnclaimedPreviousCommandResults, this.MergeUnclaimedPreviousCommandResults)); if (psRPVersion != null && - psRPVersion >= RemotingConstants.ProtocolVersionWin10RTM) + psRPVersion >= RemotingConstants.ProtocolVersion_2_3) { // V5 merge instructions commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeError, MergeInstructions[(int)MergeType.Error])); @@ -672,7 +672,7 @@ internal PSObject ToPSObjectForRemoting(Version psRPVersion) commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeInformation, MergeInstructions[(int)MergeType.Information])); } else if (psRPVersion != null && - psRPVersion >= RemotingConstants.ProtocolVersionWin8RTM) + psRPVersion >= RemotingConstants.ProtocolVersion_2_2) { // V3 merge instructions. commandAsPSObject.Properties.Add(new PSNoteProperty(RemoteDataNameStrings.MergeError, MergeInstructions[(int)MergeType.Error])); diff --git a/src/System.Management.Automation/engine/hostifaces/Connection.cs b/src/System.Management.Automation/engine/hostifaces/Connection.cs index 5af011adb82..ccb918c7dd9 100644 --- a/src/System.Management.Automation/engine/hostifaces/Connection.cs +++ b/src/System.Management.Automation/engine/hostifaces/Connection.cs @@ -19,7 +19,6 @@ namespace System.Management.Automation.Runspaces /// Exception thrown when state of the runspace is different from /// expected state of runspace. /// - [Serializable] public class InvalidRunspaceStateException : SystemException { /// @@ -96,9 +95,10 @@ RunspaceState expectedState /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidRunspaceStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -219,12 +219,9 @@ public enum PSThreadOptions ReuseThread = 2, /// - /// Doesn't create a new thread; the execution occurs on the - /// thread that calls Invoke. + /// Doesn't create a new thread; the execution occurs on the thread + /// that calls Invoke. This option is not valid for asynchronous calls. /// - /// - /// This option is not valid for asynchronous calls - /// UseCurrentThread = 3 } @@ -414,7 +411,7 @@ internal RunspaceAvailabilityEventArgs(RunspaceAvailability runspaceAvailability public enum RunspaceCapability { /// - /// No additional capabilities beyond a default runspace. + /// Legacy capabilities for WinRM only, from Win7 timeframe. /// Default = 0x0, @@ -436,13 +433,18 @@ public enum RunspaceCapability /// /// Runspace is based on SSH transport. /// - SSHTransport = 0x8 + SSHTransport = 0x8, + + /// + /// Runspace is based on open custom connection/transport support. + /// + CustomTransport = 0x100 } #endregion /// - /// Public interface to Msh Runtime. Provides APIs for creating pipelines, + /// Public interface to PowerShell Runtime. Provides APIs for creating pipelines, /// access session state etc. /// public abstract class Runspace : IDisposable @@ -698,7 +700,7 @@ public Guid InstanceId /// /// Runspace is not opened. /// - internal System.Management.Automation.ExecutionContext ExecutionContext + internal ExecutionContext ExecutionContext { get { @@ -759,6 +761,12 @@ public string Name /// Gets the Runspace Id. /// public int Id { get; } + + /// + /// Gets and sets a boolean indicating whether the runspace has a + /// debugger attached with Debug-Runspace. + /// + public bool IsRemoteDebuggerAttached { get; internal set; } /// /// Returns protocol version that the remote server uses for PS remoting. @@ -1508,7 +1516,10 @@ internal PowerShell PopRunningPowerShell() if (count > 0) { - if (count == 1) { _baseRunningPowerShell = null; } + if (count == 1) + { + _baseRunningPowerShell = null; + } return _runningPowerShells.Pop(); } @@ -1569,7 +1580,7 @@ protected virtual void Dispose(bool disposing) /// /// Gets the execution context. /// - internal abstract System.Management.Automation.ExecutionContext GetExecutionContext + internal abstract ExecutionContext GetExecutionContext { get; } @@ -1615,8 +1626,8 @@ public abstract PSEventManager Events /// /// Sets the base transaction for the runspace; any transactions created on this runspace will be nested to this instance. /// - ///The base transaction - ///This overload uses RollbackSeverity.Error; i.e. the transaction will be rolled back automatically on a non-terminating error or worse + /// The base transaction + /// This overload uses RollbackSeverity.Error; i.e. the transaction will be rolled back automatically on a non-terminating error or worse public void SetBaseTransaction(System.Transactions.CommittableTransaction transaction) { this.ExecutionContext.TransactionManager.SetBaseTransaction(transaction, RollbackSeverity.Error); @@ -1625,8 +1636,8 @@ public void SetBaseTransaction(System.Transactions.CommittableTransaction transa /// /// Sets the base transaction for the runspace; any transactions created on this runspace will be nested to this instance. /// - ///The base transaction - ///The severity of error that causes PowerShell to automatically rollback the transaction + /// The base transaction + /// The severity of error that causes PowerShell to automatically rollback the transaction public void SetBaseTransaction(System.Transactions.CommittableTransaction transaction, RollbackSeverity severity) { this.ExecutionContext.TransactionManager.SetBaseTransaction(transaction, severity); diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs index 99151b7b0d4..0969d7b08c6 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionBase.cs @@ -25,6 +25,28 @@ internal abstract class RunspaceBase : Runspace { #region constructors + /// + /// Initialize powershell AssemblyLoadContext and register the 'Resolving' event, if it's not done already. + /// If powershell is hosted by a native host such as DSC, then PS ALC may be initialized via 'SetPowerShellAssemblyLoadContext' before loading S.M.A. + /// + /// + /// We do this both here and during the initialization of the 'ClrFacade' type. + /// This is because we want to make sure the assembly/library resolvers are: + /// 1. registered before any script/cmdlet can run. + /// 2. registered before 'ClrFacade' gets used for assembly related operations. + /// + /// The 'ClrFacade' type may be used without a Runspace created, for example, by calling type conversion methods in the 'LanguagePrimitive' type. + /// And at the mean time, script or cmdlet may run without the 'ClrFacade' type initialized. + /// That's why we attempt to create the singleton of 'PowerShellAssemblyLoadContext' at both places. + /// + static RunspaceBase() + { + if (PowerShellAssemblyLoadContext.Instance is null) + { + PowerShellAssemblyLoadContext.InitializeSingleton(string.Empty, throwOnReentry: false); + } + } + /// /// Construct an instance of an Runspace using a custom /// implementation of PSHost. @@ -237,7 +259,11 @@ public override void OpenAsync() private void CoreOpen(bool syncCall) { bool etwEnabled = RunspaceEventSource.Log.IsEnabled(); - if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStart(); + if (etwEnabled) + { + RunspaceEventSource.Log.OpenRunspaceStart(); + } + lock (SyncRoot) { // Call fails if RunspaceState is not BeforeOpen. @@ -260,10 +286,13 @@ private void CoreOpen(bool syncCall) RaiseRunspaceStateEvents(); OpenHelper(syncCall); - if (etwEnabled) RunspaceEventSource.Log.OpenRunspaceStop(); + if (etwEnabled) + { + RunspaceEventSource.Log.OpenRunspaceStop(); + } #if LEGACYTELEMETRY - // We report startup telementry when opening the runspace - because this is the first time + // We report startup telemetry when opening the runspace - because this is the first time // we are really using PowerShell. This isn't the cleanest place though, because // sometimes there are many runspaces created - the callee ensures telemetry is only // reported once. Note that if the host implements IHostProvidesTelemetryData, we rely @@ -661,7 +690,7 @@ protected RunspaceState RunspaceState } /// - /// This is queue of all the state change event which have occured for + /// This is queue of all the state change event which have occurred for /// this runspace. RaiseRunspaceStateEvents raises event for each /// item in this queue. We don't raise events from with SetRunspaceState /// because SetRunspaceState is often called from with in the a lock. @@ -670,7 +699,7 @@ protected RunspaceState RunspaceState /// private Queue _runspaceEventQueue = new Queue(); - private class RunspaceEventQueueItem + private sealed class RunspaceEventQueueItem { public RunspaceEventQueueItem(RunspaceStateInfo runspaceStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability) { diff --git a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs index b812e8fe82b..45591ee2906 100644 --- a/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs +++ b/src/System.Management.Automation/engine/hostifaces/ConnectionFactory.cs @@ -476,58 +476,64 @@ connectionInfo is not VMConnectionInfo && #region Runspace - Remote Factory /// + /// Creates a remote Runspace. /// + /// It defines connection path to a remote runspace that needs to be created. + /// The explicit PSHost implementation. /// /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties + /// /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter /// - /// - /// - /// + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { return CreateRunspace(connectionInfo, host, typeTable, null, null); } /// + /// Creates a remote Runspace. /// + /// It defines connection path to a remote runspace that needs to be created. + /// The explicit PSHost implementation. /// /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties + /// /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter /// - /// - /// /// /// Application arguments the server can see in /// - /// + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments) { return CreateRunspace(connectionInfo, host, typeTable, applicationArguments, null); } /// + /// Creates a remote Runspace. /// - /// - /// + /// It defines connection path to a remote runspace that needs to be created. + /// The explicit PSHost implementation. /// /// The TypeTable to use while deserializing/serializing remote objects. /// TypeTable has the following information used by serializer: /// 1. SerializationMethod /// 2. SerializationDepth /// 3. SpecificSerializationProperties + /// /// TypeTable has the following information used by deserializer: /// 1. TargetTypeForDeserialization /// 2. TypeConverter @@ -536,19 +542,9 @@ public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSH /// Application arguments the server can see in /// /// Name for remote runspace. - /// + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable, PSPrimitiveDictionary applicationArguments, string name) { - if (connectionInfo is not WSManConnectionInfo && - connectionInfo is not NewProcessConnectionInfo && - connectionInfo is not NamedPipeConnectionInfo && - connectionInfo is not SSHConnectionInfo && - connectionInfo is not VMConnectionInfo && - connectionInfo is not ContainerConnectionInfo) - { - throw new NotSupportedException(); - } - if (connectionInfo is WSManConnectionInfo) { RemotingCommandUtil.CheckHostRemotingPrerequisites(); @@ -558,19 +554,21 @@ connectionInfo is not VMConnectionInfo && } /// + /// Creates a remote Runspace. /// - /// - /// - /// + /// The explicit PSHost implementation. + /// It defines connection path to a remote runspace that needs to be created. + /// A remote Runspace. public static Runspace CreateRunspace(PSHost host, RunspaceConnectionInfo connectionInfo) { return CreateRunspace(connectionInfo, host, null); } /// + /// Creates a remote Runspace. /// - /// - /// + /// It defines connection path to a remote runspace that needs to be created. + /// A remote Runspace. public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo) { return CreateRunspace(null, connectionInfo); @@ -581,9 +579,20 @@ public static Runspace CreateRunspace(RunspaceConnectionInfo connectionInfo) #region V3 Extensions /// + /// Creates an out-of-process remote Runspace. /// - /// - /// + /// + /// The TypeTable to use while deserializing/serializing remote objects. + /// TypeTable has the following information used by serializer: + /// 1. SerializationMethod + /// 2. SerializationDepth + /// 3. SpecificSerializationProperties + /// + /// TypeTable has the following information used by deserializer: + /// 1. TargetTypeForDeserialization + /// 2. TypeConverter + /// + /// An out-of-process remote Runspace. public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable) { NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null); @@ -592,10 +601,21 @@ public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable) } /// + /// Creates an out-of-process remote Runspace. /// - /// - /// - /// + /// + /// The TypeTable to use while deserializing/serializing remote objects. + /// TypeTable has the following information used by serializer: + /// 1. SerializationMethod + /// 2. SerializationDepth + /// 3. SpecificSerializationProperties + /// + /// TypeTable has the following information used by deserializer: + /// 1. TargetTypeForDeserialization + /// 2. TypeConverter + /// + /// It represents a PowerShell process that is used for an out-of-process remote Runspace + /// An out-of-process remote Runspace. public static Runspace CreateOutOfProcessRunspace(TypeTable typeTable, PowerShellProcessInstance processInstance) { NewProcessConnectionInfo connectionInfo = new NewProcessConnectionInfo(null) { Process = processInstance }; diff --git a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs index 75987cc463a..3f47fedb55e 100644 --- a/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs +++ b/src/System.Management.Automation/engine/hostifaces/FieldDescription.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation.Host { /// /// Provides a description of a field for use by . - /// + /// /// /// /// It is permitted to subclass @@ -89,7 +89,7 @@ public string Name /// /// /// If not already set by a call to , - /// will be used as the type. + /// will be used as the type. /// /// @@ -115,7 +115,7 @@ public string Name /// /// /// If not already set by a call to , - /// will be used as the type. + /// will be used as the type. /// /// @@ -144,7 +144,7 @@ public string Name /// to load the containing assembly to access the type information. AssemblyName is used for this purpose. /// /// If not already set by a call to , - /// will be used as the type. + /// will be used as the type. /// public string @@ -165,7 +165,7 @@ public string Name /// /// A short, human-presentable message to describe and identify the field. If supplied, a typical implementation of - /// will use this value instead of + /// will use this value instead of /// the field name to identify the field to the user. /// /// @@ -174,9 +174,9 @@ public string Name /// /// Note that the special character & (ampersand) may be embedded in the label string to identify the next /// character in the label as a "hot key" (aka "keyboard accelerator") that the - /// implementation may use + /// implementation may use /// to allow the user to quickly set input focus to this field. The implementation of - /// is responsible for parsing + /// is responsible for parsing /// the label string for this special character and rendering it accordingly. /// /// For example, a field named "SSN" might have "&Social Security Number" as it's label. @@ -256,15 +256,15 @@ public string Name } /// - /// Gets and sets the default value, if any, for the implementation of + /// Gets and sets the default value, if any, for the implementation of /// to pre-populate its UI with. This is a PSObject instance so that the value can be serialized, converted, /// manipulated like any pipeline object. /// - /// - /// It is up to the implementer of to decide if it + /// + /// It is up to the implementer of to decide if it /// can make use of the object in its presentation of the fields prompt. /// - /// + /// public PSObject DefaultValue @@ -283,8 +283,8 @@ public string Name } /// - /// Gets the Attribute classes that apply to the field. In the case that - /// is being called from the MSH engine, this will contain the set of prompting attributes that are attached to a + /// Gets the Attribute classes that apply to the field. In the case that + /// is being called from the engine, this will contain the set of prompting attributes that are attached to a /// cmdlet parameter declaration. /// public diff --git a/src/System.Management.Automation/engine/hostifaces/History.cs b/src/System.Management.Automation/engine/hostifaces/History.cs index e1100b97487..00a090d4b22 100644 --- a/src/System.Management.Automation/engine/hostifaces/History.cs +++ b/src/System.Management.Automation/engine/hostifaces/History.cs @@ -5,6 +5,7 @@ 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.Host; @@ -509,7 +510,7 @@ internal HistoryInfo[] GetEntries(WildcardPattern wildcardpattern, long count, S long id = _countEntriesAdded; for (long i = 0; i <= count - 1;) { - // if buffersize is changed,we have to loop from max entry to min entry thats not cleared + // if buffersize is changed,we have to loop from max entry to min entry that's not cleared if (_capacity != DefaultHistorySize) { if (_countEntriesAdded > _capacity) @@ -580,10 +581,10 @@ internal void ClearEntry(long id) } } - /// + /// /// gets the total number of entries added - /// - ///count of total entries added. + /// + /// count of total entries added. internal int Buffercapacity() { return _capacity; @@ -858,7 +859,7 @@ public class GetHistoryCommand : PSCmdlet /// /// [Parameter(Position = 0, ValueFromPipeline = true)] - [ValidateRangeAttribute((long)1, long.MaxValue)] + [ValidateRange((long)1, long.MaxValue)] public long[] Id { get @@ -886,7 +887,7 @@ public long[] Id /// No of History Entries (starting from last) that are to be displayed. /// [Parameter(Position = 1)] - [ValidateRangeAttribute(0, (int)Int16.MaxValue)] + [ValidateRange(0, (int)Int16.MaxValue)] public int Count { get @@ -1345,7 +1346,7 @@ public class AddHistoryCommand : PSCmdlet /// A Boolean that indicates whether history objects should be /// passed to the next element in the pipeline. /// - [Parameter()] + [Parameter] public SwitchParameter Passthru { get { return _passthru; } @@ -1435,7 +1436,7 @@ void ProcessRecord() } // Read CommandLine property - if (!(GetPropertyValue(mshObject, "CommandLine") is string commandLine)) + if (GetPropertyValue(mshObject, "CommandLine") is not string commandLine) { break; } @@ -1449,14 +1450,14 @@ void ProcessRecord() // Read StartExecutionTime property object temp = GetPropertyValue(mshObject, "StartExecutionTime"); - if (temp == null || !LanguagePrimitives.TryConvertTo(temp, out DateTime startExecutionTime)) + if (temp == null || !LanguagePrimitives.TryConvertTo(temp, CultureInfo.CurrentCulture, out DateTime startExecutionTime)) { break; } // Read EndExecutionTime property temp = GetPropertyValue(mshObject, "EndExecutionTime"); - if (temp == null || !LanguagePrimitives.TryConvertTo(temp, out DateTime endExecutionTime)) + if (temp == null || !LanguagePrimitives.TryConvertTo(temp, CultureInfo.CurrentCulture, out DateTime endExecutionTime)) { break; } @@ -1470,7 +1471,7 @@ void ProcessRecord() ); } while (false); - // If we are here, an error has occured. + // If we are here, an error has occurred. Exception ex = new InvalidDataException ( @@ -1503,9 +1504,9 @@ private static } } - /// + /// /// This Class implements the Clear History cmdlet - /// + /// [Cmdlet(VerbsCommon.Clear, "History", SupportsShouldProcess = true, DefaultParameterSetName = "IDParameter", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096691")] public class ClearHistoryCommand : PSCmdlet { @@ -1517,7 +1518,7 @@ public class ClearHistoryCommand : PSCmdlet /// [Parameter(ParameterSetName = "IDParameter", Position = 0, HelpMessage = "Specifies the ID of a command in the session history.Clear history clears only the specified command")] - [ValidateRangeAttribute((int)1, int.MaxValue)] + [ValidateRange((int)1, int.MaxValue)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public int[] Id { @@ -1541,7 +1542,7 @@ public int[] Id /// Command line name of an entry in the session history. /// [Parameter(ParameterSetName = "CommandLineParameter", HelpMessage = "Specifies the name of a command in the session history")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] CommandLine { @@ -1561,11 +1562,11 @@ public string[] CommandLine /// private string[] _commandline = null; - /// + /// /// Clears the specified number of history entries - /// + /// [Parameter(Mandatory = false, Position = 1, HelpMessage = "Clears the specified number of history entries")] - [ValidateRangeAttribute((int)1, int.MaxValue)] + [ValidateRange((int)1, int.MaxValue)] public int Count { get @@ -1650,8 +1651,8 @@ protected override void ProcessRecord() /// /// Clears the session history based on the id parameter /// takes no parameters - /// Nothing. /// + /// Nothing. private void ClearHistoryByID() { if (_countParameterSpecified && Count < 0) @@ -1758,8 +1759,8 @@ private void ClearHistoryByID() /// /// Clears the session history based on the Commandline parameter /// takes no parameters - /// Nothing. /// + /// Nothing. private void ClearHistoryByCmdLine() { // throw an exception for invalid count values @@ -1821,12 +1822,12 @@ private void ClearHistoryByCmdLine() /// /// Clears the session history based on the input parameter + /// + /// Nothing. /// Id of the entry to be cleared. /// Count of entries to be cleared. /// Cmdline string to be cleared. /// Order of the entries. - /// Nothing. - /// private void ClearHistoryEntries(long id, int count, string cmdline, SwitchParameter newest) { // if cmdline is null,use default parameter set notion. diff --git a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs index b3e29423a83..8e5d30be71f 100644 --- a/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs +++ b/src/System.Management.Automation/engine/hostifaces/HostUtilities.cs @@ -1,38 +1,19 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; -using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Management.Automation.Host; using System.Management.Automation.Internal; -using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Subsystem.Feedback; using System.Runtime.InteropServices; -using System.Security; using System.Text; -using System.Text.RegularExpressions; - -using Microsoft.PowerShell.Commands; using Microsoft.PowerShell.Commands.Internal.Format; namespace System.Management.Automation { - internal enum SuggestionMatchType - { - /// Match on a command. - Command = 0, - /// Match based on exception message. - Error = 1, - /// Match by running a script block. - Dynamic = 2, - - /// Match by fully qualified ErrorId. - ErrorId = 3 - } - #region Public HostUtilities Class /// @@ -42,81 +23,25 @@ public static class HostUtilities { #region Internal Access - private static readonly string s_checkForCommandInCurrentDirectoryScript = @" - [System.Diagnostics.DebuggerHidden()] - param() - - $foundSuggestion = $false - - if($lastError -and - ($lastError.Exception -is ""System.Management.Automation.CommandNotFoundException"")) - { - $escapedCommand = [System.Management.Automation.WildcardPattern]::Escape($lastError.TargetObject) - $foundSuggestion = @(Get-Command ($ExecutionContext.SessionState.Path.Combine(""."", $escapedCommand)) -ErrorAction Ignore).Count -gt 0 - } - - $foundSuggestion - "; - - private static readonly string s_createCommandExistsInCurrentDirectoryScript = @" - [System.Diagnostics.DebuggerHidden()] - param([string] $formatString) - - $formatString -f $lastError.TargetObject,"".\$($lastError.TargetObject)"" - "; - - private static readonly string s_getFuzzyMatchedCommands = @" - [System.Diagnostics.DebuggerHidden()] - param([string] $formatString) + private static readonly char s_actionIndicator = HostSupportUnicode() ? '\u27a4' : '>'; - $formatString -f [string]::Join(', ', (Get-Command $lastError.TargetObject -UseFuzzyMatch | Select-Object -First 10 -Unique -ExpandProperty Name)) - "; - - private static readonly List s_suggestions = InitializeSuggestions(); - - private static List InitializeSuggestions() + private static bool HostSupportUnicode() { - var suggestions = new List( - new Hashtable[] - { - NewSuggestion( - id: 1, - category: "Transactions", - matchType: SuggestionMatchType.Command, - rule: "^Start-Transaction", - suggestion: SuggestionStrings.Suggestion_StartTransaction, - enabled: true), - NewSuggestion( - id: 2, - category: "Transactions", - matchType: SuggestionMatchType.Command, - rule: "^Use-Transaction", - suggestion: SuggestionStrings.Suggestion_UseTransaction, - enabled: true), - NewSuggestion( - id: 3, - category: "General", - matchType: SuggestionMatchType.Dynamic, - rule: ScriptBlock.CreateDelayParsedScriptBlock(s_checkForCommandInCurrentDirectoryScript, isProductCode: true), - suggestion: ScriptBlock.CreateDelayParsedScriptBlock(s_createCommandExistsInCurrentDirectoryScript, isProductCode: true), - suggestionArgs: new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandExistsInCurrentDirectory) }, - enabled: true) - }); - - if (ExperimentalFeature.IsEnabled("PSCommandNotFoundSuggestion")) + // Reference: https://github.com/zkat/supports-unicode/blob/main/src/lib.rs + if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - suggestions.Add( - NewSuggestion( - id: 4, - category: "General", - matchType: SuggestionMatchType.ErrorId, - rule: "CommandNotFoundException", - suggestion: ScriptBlock.CreateDelayParsedScriptBlock(s_getFuzzyMatchedCommands, isProductCode: true), - suggestionArgs: new object[] { CodeGeneration.EscapeSingleQuotedStringContent(SuggestionStrings.Suggestion_CommandNotFound) }, - enabled: true)); + return Environment.GetEnvironmentVariable("WT_SESSION") is not null || + Environment.GetEnvironmentVariable("TERM_PROGRAM") is "vscode" || + Environment.GetEnvironmentVariable("ConEmuTask") is "{cmd:Cmder}" || + Environment.GetEnvironmentVariable("TERM") is "xterm-256color" or "alacritty"; } - return suggestions; + string ctype = Environment.GetEnvironmentVariable("LC_ALL") ?? + Environment.GetEnvironmentVariable("LC_CTYPE") ?? + Environment.GetEnvironmentVariable("LANG") ?? + string.Empty; + + return ctype.EndsWith("UTF8") || ctype.EndsWith("UTF-8"); } #region GetProfileCommands @@ -138,16 +63,6 @@ internal static PSObject GetDollarProfile(string allUsersAllHosts, string allUse return returnValue; } - /// - /// Gets an array of commands that can be run sequentially to set $profile and run the profile commands. - /// - /// The id identifying the host or shell used in profile file names. - /// - internal static PSCommand[] GetProfileCommands(string shellId) - { - return HostUtilities.GetProfileCommands(shellId, false); - } - /// /// Gets the object that serves as a value to $profile and the paths on it. /// @@ -233,10 +148,11 @@ internal static string GetFullProfileFileName(string shellId, bool forCurrentUse else { basePath = GetAllUsersFolderPath(shellId); - if (string.IsNullOrEmpty(basePath)) - { - return string.Empty; - } + } + + if (string.IsNullOrEmpty(basePath)) + { + return string.Empty; } string profileName = useTestProfile ? "profile_test.ps1" : "profile.ps1"; @@ -307,375 +223,6 @@ internal static string GetMaxLines(string source, int maxLines) return returnValue.ToString(); } - internal static List GetSuggestion(Runspace runspace) - { - if (!(runspace is LocalRunspace localRunspace)) { return new List(); } - - // Get the last value of $? - bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue; - - // Get the last history item - History history = localRunspace.History; - HistoryInfo[] entries = history.GetEntries(-1, 1, true); - - if (entries.Length == 0) - return new List(); - - HistoryInfo lastHistory = entries[0]; - - // Get the last error - ArrayList errorList = (ArrayList)localRunspace.GetExecutionContext.DollarErrorVariable; - object lastError = null; - - if (errorList.Count > 0) - { - lastError = errorList[0] as Exception; - ErrorRecord lastErrorRecord = null; - - // The error was an actual ErrorRecord - if (lastError == null) - { - lastErrorRecord = errorList[0] as ErrorRecord; - } - else if (lastError is RuntimeException) - { - lastErrorRecord = ((RuntimeException)lastError).ErrorRecord; - } - - // If we got information about the error invocation, - // we can be more careful with the errors we pass along - if ((lastErrorRecord != null) && (lastErrorRecord.InvocationInfo != null)) - { - if (lastErrorRecord.InvocationInfo.HistoryId == lastHistory.Id) - lastError = lastErrorRecord; - else - lastError = null; - } - } - - Runspace oldDefault = null; - bool changedDefault = false; - if (Runspace.DefaultRunspace != runspace) - { - oldDefault = Runspace.DefaultRunspace; - changedDefault = true; - Runspace.DefaultRunspace = runspace; - } - - List suggestions = null; - - try - { - suggestions = GetSuggestion(lastHistory, lastError, errorList); - } - finally - { - if (changedDefault) - { - Runspace.DefaultRunspace = oldDefault; - } - } - - // Restore $? - localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue; - return suggestions; - } - - [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly")] - internal static List GetSuggestion(HistoryInfo lastHistory, object lastError, ArrayList errorList) - { - var returnSuggestions = new List(); - - PSModuleInfo invocationModule = new PSModuleInfo(true); - invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory); - invocationModule.SessionState.PSVariable.Set("lastError", lastError); - - int initialErrorCount = 0; - - // Go through all of the suggestions - foreach (Hashtable suggestion in s_suggestions) - { - initialErrorCount = errorList.Count; - - // Make sure the rule is enabled - if (!LanguagePrimitives.IsTrue(suggestion["Enabled"])) - continue; - - SuggestionMatchType matchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo( - suggestion["MatchType"], - typeof(SuggestionMatchType), - CultureInfo.InvariantCulture); - - // If this is a dynamic match, evaluate the ScriptBlock - if (matchType == SuggestionMatchType.Dynamic) - { - object result = null; - - ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock; - if (evaluator == null) - { - suggestion["Enabled"] = false; - - throw new ArgumentException( - SuggestionStrings.RuleMustBeScriptBlock, "Rule"); - } - - try - { - result = invocationModule.Invoke(evaluator, null); - } - catch (Exception) - { - // Catch-all OK. This is a third-party call-out. - suggestion["Enabled"] = false; - continue; - } - - // If it returned results, evaluate its suggestion - if (LanguagePrimitives.IsTrue(result)) - { - string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule); - - if (!string.IsNullOrEmpty(suggestionText)) - { - string returnString = string.Format( - CultureInfo.CurrentCulture, - "Suggestion [{0},{1}]: {2}", - (int)suggestion["Id"], - (string)suggestion["Category"], - suggestionText); - - returnSuggestions.Add(returnString); - } - } - } - else - { - string matchText = string.Empty; - - // Otherwise, this is a Regex match against the - // command or error - if (matchType == SuggestionMatchType.Command) - { - matchText = lastHistory.CommandLine; - } - else if (matchType == SuggestionMatchType.Error) - { - if (lastError != null) - { - Exception lastException = lastError as Exception; - if (lastException != null) - { - matchText = lastException.Message; - } - else - { - matchText = lastError.ToString(); - } - } - } - else if (matchType == SuggestionMatchType.ErrorId) - { - if (lastError != null && lastError is ErrorRecord errorRecord) - { - matchText = errorRecord.FullyQualifiedErrorId; - } - } - else - { - suggestion["Enabled"] = false; - - throw new ArgumentException( - SuggestionStrings.InvalidMatchType, - "MatchType"); - } - - // If the text matches, evaluate the suggestion - if (Regex.IsMatch(matchText, (string)suggestion["Rule"], RegexOptions.IgnoreCase)) - { - string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule); - - if (!string.IsNullOrEmpty(suggestionText)) - { - string returnString = string.Format( - CultureInfo.CurrentCulture, - "Suggestion [{0},{1}]: {2}", - (int)suggestion["Id"], - (string)suggestion["Category"], - suggestionText); - - returnSuggestions.Add(returnString); - } - } - } - - // If the rule generated an error, disable it - if (errorList.Count != initialErrorCount) - { - suggestion["Enabled"] = false; - } - } - - return returnSuggestions; - } - - /// - /// Remove the GUID from the message if the message is in the pre-defined format. - /// - /// - /// - /// - internal static string RemoveGuidFromMessage(string message, out bool matchPattern) - { - matchPattern = false; - if (string.IsNullOrEmpty(message)) - return message; - - const string pattern = @"^([\d\w]{8}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{12}:).*"; - Match matchResult = Regex.Match(message, pattern); - if (matchResult.Success) - { - string partToRemove = matchResult.Groups[1].Captures[0].Value; - message = message.Remove(0, partToRemove.Length); - matchPattern = true; - } - - return message; - } - - internal static string RemoveIdentifierInfoFromMessage(string message, out bool matchPattern) - { - matchPattern = false; - if (string.IsNullOrEmpty(message)) - return message; - - const string pattern = @"^([\d\w]{8}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{4}\-[\d\w]{12}:\[.*\]:).*"; - Match matchResult = Regex.Match(message, pattern); - if (matchResult.Success) - { - string partToRemove = matchResult.Groups[1].Captures[0].Value; - message = message.Remove(0, partToRemove.Length); - matchPattern = true; - } - - return message; - } - - /// - /// Create suggestion with string rule and suggestion. - /// - /// Identifier for the suggestion. - /// Category for the suggestion. - /// Suggestion match type. - /// Rule to match. - /// Suggestion to return. - /// True if the suggestion is enabled. - /// Hashtable representing the suggestion. - private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, string rule, string suggestion, bool enabled) - { - Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase); - - result["Id"] = id; - result["Category"] = category; - result["MatchType"] = matchType; - result["Rule"] = rule; - result["Suggestion"] = suggestion; - result["Enabled"] = enabled; - - return result; - } - - /// - /// Create suggestion with string rule and scriptblock suggestion. - /// - /// Identifier for the suggestion. - /// Category for the suggestion. - /// Suggestion match type. - /// Rule to match. - /// Scriptblock to run that returns the suggestion. - /// Arguments to pass to suggestion scriptblock. - /// True if the suggestion is enabled. - /// Hashtable representing the suggestion. - private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, string rule, ScriptBlock suggestion, object[] suggestionArgs, bool enabled) - { - Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase); - - result["Id"] = id; - result["Category"] = category; - result["MatchType"] = matchType; - result["Rule"] = rule; - result["Suggestion"] = suggestion; - result["SuggestionArgs"] = suggestionArgs; - result["Enabled"] = enabled; - - return result; - } - - /// - /// Create suggestion with scriptblock rule and suggestion. - /// - private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, ScriptBlock rule, ScriptBlock suggestion, bool enabled) - { - Hashtable result = new Hashtable(StringComparer.CurrentCultureIgnoreCase); - - result["Id"] = id; - result["Category"] = category; - result["MatchType"] = matchType; - result["Rule"] = rule; - result["Suggestion"] = suggestion; - result["Enabled"] = enabled; - - return result; - } - - /// - /// Create suggestion with scriptblock rule and scriptblock suggestion with arguments. - /// - private static Hashtable NewSuggestion(int id, string category, SuggestionMatchType matchType, ScriptBlock rule, ScriptBlock suggestion, object[] suggestionArgs, bool enabled) - { - Hashtable result = NewSuggestion(id, category, matchType, rule, suggestion, enabled); - result.Add("SuggestionArgs", suggestionArgs); - - return result; - } - - /// - /// Get suggestion text from suggestion scriptblock. - /// - [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Need to keep this for legacy reflection based use")] - private static string GetSuggestionText(object suggestion, PSModuleInfo invocationModule) - { - return GetSuggestionText(suggestion, null, invocationModule); - } - - /// - /// Get suggestion text from suggestion scriptblock with arguments. - /// - private static string GetSuggestionText(object suggestion, object[] suggestionArgs, PSModuleInfo invocationModule) - { - if (suggestion is ScriptBlock) - { - ScriptBlock suggestionScript = (ScriptBlock)suggestion; - - object result = null; - try - { - result = invocationModule.Invoke(suggestionScript, suggestionArgs); - } - catch (Exception) - { - // Catch-all OK. This is a third-party call-out. - return string.Empty; - } - - return (string)LanguagePrimitives.ConvertTo(result, typeof(string), CultureInfo.CurrentCulture); - } - else - { - return (string)LanguagePrimitives.ConvertTo(suggestion, typeof(string), CultureInfo.CurrentCulture); - } - } - /// /// Returns the prompt used in remote sessions: "[machine]: basePrompt" /// @@ -696,47 +243,19 @@ runspace.ConnectionInfo is VMConnectionInfo || !string.IsNullOrEmpty(sshConnectionInfo.UserName) && !System.Environment.UserName.Equals(sshConnectionInfo.UserName, StringComparison.Ordinal)) { - return string.Format(CultureInfo.InvariantCulture, "[{0}@{1}]: {2}", sshConnectionInfo.UserName, sshConnectionInfo.ComputerName, basePrompt); - } - - return string.Format(CultureInfo.InvariantCulture, "[{0}]: {1}", runspace.ConnectionInfo.ComputerName, basePrompt); - } - - internal static bool IsProcessInteractive(InvocationInfo invocationInfo) - { -#if CORECLR - return false; -#else - // CommandOrigin != Runspace means it is in a script - if (invocationInfo.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 two seconds, - // 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; - - // Making it 2 seconds because of things like delayed prompt - if (idleTime.TotalSeconds > 2) - return true; - } - catch (System.ComponentModel.Win32Exception) - { - // Don't have access to the properties - return false; + return string.Format( + CultureInfo.InvariantCulture, + "[{0}@{1}]: {2}", + sshConnectionInfo.UserName, + sshConnectionInfo.ComputerName, + basePrompt); } - return false; -#endif + return string.Format( + CultureInfo.InvariantCulture, + "[{0}]: {1}", + runspace.ConnectionInfo.ComputerName, + basePrompt); } /// @@ -896,6 +415,189 @@ public static Collection InvokeOnRunspace(PSCommand command, Runspace #endregion + #region Feedback Rendering + + /// + /// Render the feedbacks to the specified host. + /// + /// The feedback results. + /// The host to render to. + public static void RenderFeedback(List feedbacks, PSHostUserInterface ui) + { + // Caption style is dimmed bright white with italic effect, used for fixed captions, such as '[' and ']'. + string captionStyle = "\x1b[97;2;3m"; + string italics = "\x1b[3m"; + string nameStyle = PSStyle.Instance.Formatting.FeedbackName; + string textStyle = PSStyle.Instance.Formatting.FeedbackText; + string actionStyle = PSStyle.Instance.Formatting.FeedbackAction; + string ansiReset = PSStyle.Instance.Reset; + + if (!ui.SupportsVirtualTerminal) + { + captionStyle = string.Empty; + italics = string.Empty; + nameStyle = string.Empty; + textStyle = string.Empty; + actionStyle = string.Empty; + ansiReset = string.Empty; + } + + var output = new StringBuilder(); + var chkset = new HashSet(); + + foreach (FeedbackResult entry in feedbacks) + { + output.AppendLine(); + output.Append($"{captionStyle}[{ansiReset}") + .Append($"{nameStyle}{italics}{entry.Name}{ansiReset}") + .Append($"{captionStyle}]{ansiReset}"); + + FeedbackItem item = entry.Item; + chkset.Add(item); + + do + { + RenderText(output, item.Header, textStyle, ansiReset, indent: 2, startOnNewLine: true); + RenderActions(output, item, textStyle, actionStyle, ansiReset); + RenderText(output, item.Footer, textStyle, ansiReset, indent: 2, startOnNewLine: true); + + // A feedback provider may return multiple feedback items, though that may be rare. + item = item.Next; + } + while (item is not null && chkset.Add(item)); + + ui.Write(output.ToString()); + output.Clear(); + chkset.Clear(); + } + + // Feedback section ends with a new line. + ui.WriteLine(); + } + + /// + /// Helper function to render feedback message. + /// + /// The output string builder to write to. + /// The text to be rendered. + /// The style to be used. + /// The ANSI code to reset. + /// The number of spaces for indentation. + /// Indicates whether to start writing from a new line. + internal static void RenderText(StringBuilder output, string text, string style, string ansiReset, int indent, bool startOnNewLine) + { + if (text is null) + { + return; + } + + if (startOnNewLine) + { + // Start writing the text on the next line. + output.AppendLine(); + } + + // Apply the style. + output.Append(style); + + int count = 0; + var trimChars = "\r\n".AsSpan(); + var span = text.AsSpan().Trim(trimChars); + + // This loop renders the text with minimal allocation. + while (true) + { + int index = span.IndexOf('\n'); + var line = index is -1 ? span : span.Slice(0, index); + + if (startOnNewLine || count > 0) + { + output.Append(' ', indent); + } + + output.Append(line.TrimEnd('\r')).AppendLine(); + + // Break out the loop if we are done with the last line. + if (index is -1) + { + break; + } + + // Point to the rest of feedback text. + span = span.Slice(index + 1); + count++; + } + + output.Append(ansiReset); + } + + /// + /// Helper function to render feedback actions. + /// + /// The output string builder to write to. + /// The feedback item to be rendered. + /// The style used for feedback messages. + /// The style used for feedback actions. + /// The ANSI code to reset. + internal static void RenderActions(StringBuilder output, FeedbackItem item, string textStyle, string actionStyle, string ansiReset) + { + if (item.RecommendedActions is null || item.RecommendedActions.Count is 0) + { + return; + } + + List actions = item.RecommendedActions; + if (item.Layout is FeedbackDisplayLayout.Landscape) + { + // Add 4-space indentation and write the indicator. + output.Append($" {textStyle}{s_actionIndicator}{ansiReset} "); + + // Then concatenate the action texts. + for (int i = 0; i < actions.Count; i++) + { + string action = actions[i]; + if (i > 0) + { + output.Append(", "); + } + + output.Append(actionStyle).Append(action).Append(ansiReset); + } + + output.AppendLine(); + } + else + { + int lastIndex = actions.Count - 1; + for (int i = 0; i < actions.Count; i++) + { + string action = actions[i]; + + // Add 4-space indentation and write the indicator, then write the action. + output.Append($" {textStyle}{s_actionIndicator}{ansiReset} "); + + if (action.Contains('\n')) + { + // If the action is a code snippet, properly render it with the right indentation. + RenderText(output, action, actionStyle, ansiReset, indent: 6, startOnNewLine: false); + + // Append an extra line unless it's the last action. + if (i != lastIndex) + { + output.AppendLine(); + } + } + else + { + output.Append(actionStyle).Append(action).Append(ansiReset) + .AppendLine(); + } + } + } + } + + #endregion + #endregion } diff --git a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs index 3fdba5569c3..f8196167c32 100644 --- a/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs +++ b/src/System.Management.Automation/engine/hostifaces/InformationalRecord.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation /// A PSInformationalRecord consists of a string Message and the InvocationInfo and pipeline state corresponding /// to the command that created the record. /// - [DataContract()] + [DataContract] public abstract class InformationalRecord { /// @@ -159,7 +159,7 @@ internal virtual void ToPSObjectForRemoting(PSObject psObject) } } - [DataMember()] + [DataMember] private string _message; private InvocationInfo _invocationInfo; @@ -170,7 +170,7 @@ internal virtual void ToPSObjectForRemoting(PSObject psObject) /// /// A warning record in the PSInformationalBuffers. /// - [DataContract()] + [DataContract] public class WarningRecord : InformationalRecord { /// @@ -226,7 +226,7 @@ public string FullyQualifiedWarningId /// /// A debug record in the PSInformationalBuffers. /// - [DataContract()] + [DataContract] public class DebugRecord : InformationalRecord { /// @@ -247,7 +247,7 @@ public DebugRecord(PSObject record) /// /// A verbose record in the PSInformationalBuffers. /// - [DataContract()] + [DataContract] public class VerboseRecord : InformationalRecord { /// diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs index e9a4b0e86e3..c60bff90303 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHost.cs @@ -448,7 +448,7 @@ public override void NotifyEndApplication() /// private IHostSupportsInteractiveSession GetIHostSupportsInteractiveSession() { - if (!(_externalHostRef.Value is IHostSupportsInteractiveSession host)) + if (_externalHostRef.Value is not IHostSupportsInteractiveSession host) { throw new PSNotImplementedException(); } @@ -537,7 +537,10 @@ internal void SetHostRef(PSHost psHost) internal void RevertHostRef() { // nothing to revert if Host reference is not set. - if (!IsHostRefSet) { return; } + if (!IsHostRefSet) + { + return; + } _externalHostRef.Revert(); _internalUIRef.Revert(); diff --git a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs index 57f3f675ffc..d8f2ef0bf90 100644 --- a/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/InternalHostUserInterface.cs @@ -209,7 +209,14 @@ public override return; } - _externalUI.Write(foregroundColor, backgroundColor, value); + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + _externalUI.Write(value); + } + else + { + _externalUI.Write(foregroundColor, backgroundColor, value); + } } /// @@ -303,7 +310,14 @@ public override return; } - _externalUI.WriteLine(foregroundColor, backgroundColor, value); + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + _externalUI.WriteLine(value); + } + else + { + _externalUI.WriteLine(foregroundColor, backgroundColor, value); + } } /// @@ -338,13 +352,7 @@ internal void WriteDebugRecord(DebugRecord record) /// Writes the DebugRecord to informational buffers. /// /// DebugRecord. - internal void WriteDebugInfoBuffers(DebugRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddDebug(record); - } - } + internal void WriteDebugInfoBuffers(DebugRecord record) => _informationalBuffers?.AddDebug(record); /// /// Helper function for WriteDebugLine. @@ -501,7 +509,7 @@ internal PSInformationalBuffers GetInformationalMessageBuffers() break; case 3: - // No to All means that we want to stop everytime WriteDebug is called. Since No throws an error, I + // No to All means that we want to stop every time WriteDebug is called. Since No throws an error, I // think that ordinarily, the caller will terminate. So I don't think the caller will ever get back // calling WriteDebug again, and thus "No to All" might not be a useful option to have. @@ -538,10 +546,7 @@ public override } // Write to Information Buffers - if (_informationalBuffers != null) - { - _informationalBuffers.AddProgress(record); - } + _informationalBuffers?.AddProgress(record); if (_externalUI == null) { @@ -588,13 +593,7 @@ internal void WriteVerboseRecord(VerboseRecord record) /// Writes the VerboseRecord to informational buffers. /// /// VerboseRecord. - internal void WriteVerboseInfoBuffers(VerboseRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddVerbose(record); - } - } + internal void WriteVerboseInfoBuffers(VerboseRecord record) => _informationalBuffers?.AddVerbose(record); /// /// See base class. @@ -631,13 +630,7 @@ internal void WriteWarningRecord(WarningRecord record) /// Writes the WarningRecord to informational buffers. /// /// WarningRecord. - internal void WriteWarningInfoBuffers(WarningRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddWarning(record); - } - } + internal void WriteWarningInfoBuffers(WarningRecord record) => _informationalBuffers?.AddWarning(record); /// /// @@ -657,13 +650,7 @@ internal void WriteInformationRecord(InformationRecord record) /// Writes the InformationRecord to informational buffers. /// /// WarningRecord. - internal void WriteInformationInfoBuffers(InformationRecord record) - { - if (_informationalBuffers != null) - { - _informationalBuffers.AddInformation(record); - } - } + internal void WriteInformationInfoBuffers(InformationRecord record) => _informationalBuffers?.AddInformation(record); internal static Type GetFieldType(FieldDescription field) { @@ -954,8 +941,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, defaultStr = hotkeysAndPlainLabels[1, defaultChoice]; } - defaultChoicesBuilder.Append(string.Format(Globalization.CultureInfo.InvariantCulture, - "{0}{1}", prepend, defaultStr)); + defaultChoicesBuilder.Append(Globalization.CultureInfo.InvariantCulture, $"{prepend}{defaultStr}"); prepend = ","; } @@ -963,8 +949,7 @@ private Collection EmulatePromptForMultipleChoice(string caption, if (defaultChoiceKeys.Count == 1) { - defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, - defaultChoicesStr); + defaultPrompt = StringUtil.Format(InternalHostUserInterfaceStrings.DefaultChoice, defaultChoicesStr); } else { diff --git a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs index 4723db9a1d7..aab1cb2e777 100644 --- a/src/System.Management.Automation/engine/hostifaces/ListModifier.cs +++ b/src/System.Management.Automation/engine/hostifaces/ListModifier.cs @@ -212,14 +212,11 @@ public void ApplyTo(IList collectionToUpdate) /// The collection to update. public void ApplyTo(object collectionToUpdate) { - if (collectionToUpdate == null) - { - throw new ArgumentNullException(nameof(collectionToUpdate)); - } + ArgumentNullException.ThrowIfNull(collectionToUpdate); collectionToUpdate = PSObject.Base(collectionToUpdate); - if (!(collectionToUpdate is IList list)) + if (collectionToUpdate is not IList list) { throw PSTraceSource.NewInvalidOperationException(PSListModifierStrings.UpdateFailed); } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs index 7f10b75525c..822dc552204 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalConnection.cs @@ -84,10 +84,7 @@ public override PSPrimitiveDictionary GetApplicationPrivateData() { lock (this.SyncRoot) { - if (_applicationPrivateData == null) - { - _applicationPrivateData = new PSPrimitiveDictionary(); - } + _applicationPrivateData ??= new PSPrimitiveDictionary(); } } @@ -240,7 +237,7 @@ protected override Pipeline CoreCreatePipeline(string command, bool addToHistory /// /// Gets the execution context. /// - internal override System.Management.Automation.ExecutionContext GetExecutionContext + internal override ExecutionContext GetExecutionContext { get { @@ -363,7 +360,7 @@ public override Debugger Debugger } } - private static readonly string s_debugPreferenceCachePath = Path.Combine(Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell"), "DebugPreference.clixml"); + private static readonly string s_debugPreferenceCachePath = Path.Combine(Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "WindowsPowerShell", "DebugPreference.clixml"); private static readonly object s_debugPreferenceLockObject = new object(); /// @@ -768,10 +765,7 @@ internal void LogEngineHealthEvent(Exception exception, /// internal PipelineThread GetPipelineThread() { - if (_pipelineThread == null) - { - _pipelineThread = new PipelineThread(this.ApartmentState); - } + _pipelineThread ??= new PipelineThread(this.ApartmentState); return _pipelineThread; } @@ -840,18 +834,14 @@ private void DoCloseHelper() if (executionContext != null) { PSHostUserInterface hostUI = executionContext.EngineHostInterface.UI; - if (hostUI != null) - { - hostUI.StopAllTranscribing(); - } + hostUI?.StopAllTranscribing(); } AmsiUtils.Uninitialize(); } // Generate the shutdown event - if (Events != null) - Events.GenerateEvent(PSEngineEvent.Exiting, null, Array.Empty(), null, true, false); + Events?.GenerateEvent(PSEngineEvent.Exiting, null, Array.Empty(), null, true, false); // Stop all running pipelines // Note:Do not perform the Cancel in lock. Reason is @@ -884,7 +874,7 @@ private void DoCloseHelper() return runspaces; }); - // Notify Engine components that that runspace is closing. + // Notify Engine components that runspace is closing. _engine.Context.RunspaceClosingNotification(); // Log engine lifecycle event. @@ -944,7 +934,10 @@ private void DoCloseHelper() private static void CloseOrDisconnectAllRemoteRunspaces(Func> getRunspaces) { List runspaces = getRunspaces(); - if (runspaces.Count == 0) { return; } + if (runspaces.Count == 0) + { + return; + } // whether the close of all remoterunspaces completed using (ManualResetEvent remoteRunspaceCloseCompleted = new ManualResetEvent(false)) @@ -969,7 +962,10 @@ private static void CloseOrDisconnectAllRemoteRunspaces(Func private void StopOrDisconnectAllJobs() { - if (JobRepository.Jobs.Count == 0) { return; } + if (JobRepository.Jobs.Count == 0) + { + return; + } List disconnectRunspaces = new List(); @@ -1242,8 +1238,6 @@ protected override void Dispose(bool disposing) RunspaceOpening = null; } - Platform.RemoveTemporaryDirectory(); - // Dispose the event manager if (this.ExecutionContext != null && this.ExecutionContext.Events != null) { @@ -1274,10 +1268,7 @@ public override void Close() base.Close(); // call base.Close() first to make it stop the pipeline - if (_pipelineThread != null) - { - _pipelineThread.Close(); - } + _pipelineThread?.Close(); } #endregion IDisposable Members @@ -1500,7 +1491,6 @@ private void RaiseOperationCompleteEvent() /// Defines the exception thrown an error loading modules occurs while opening the runspace. It /// contains a list of all of the module errors that have occurred. /// - [Serializable] public class RunspaceOpenModuleLoadException : RuntimeException { #region ctor @@ -1527,7 +1517,7 @@ public RunspaceOpenModuleLoadException(string message) /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public RunspaceOpenModuleLoadException(string message, Exception innerException) : base(message, innerException) { @@ -1567,27 +1557,11 @@ public PSDataCollection ErrorRecords /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RunspaceOpenModuleLoadException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } - - /// - /// Populates a with the - /// data needed to serialize the RunspaceOpenModuleLoadException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - } - #endregion Serialization } diff --git a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs index ab430decb50..a9a3a66b859 100644 --- a/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/LocalPipeline.cs @@ -12,9 +12,6 @@ #endif using System.Threading; using Microsoft.PowerShell.Commands; -using Microsoft.Win32; - -using Dbg = System.Management.Automation.Diagnostics; namespace System.Management.Automation.Runspaces { @@ -192,7 +189,7 @@ protected override void StartPipelineExecution() } #if !UNIX - if (apartmentState != ApartmentState.Unknown && !Platform.IsNanoServer && !Platform.IsIoT) + if (apartmentState != ApartmentState.Unknown && Platform.IsStaSupported) { invokeThread.SetApartmentState(apartmentState); } @@ -272,61 +269,60 @@ private void SetupInvokeThread(Thread invokeThread, bool changeName) } } - /// + /// /// Helper method for asynchronous invoke - ///Unhandled FlowControl exception if InvocationSettings.ExposeFlowControlExceptions is true. - /// + /// + /// Unhandled FlowControl exception if InvocationSettings.ExposeFlowControlExceptions is true. private FlowControlException InvokeHelper() { FlowControlException flowControlException = null; - PipelineProcessor pipelineProcessor = null; + try { -#if TRANSACTIONS_SUPPORTED - // 2004/11/08-JeffJon - // Transactions will not be supported for the Exchange release - - // Add the transaction to this thread - System.Transactions.Transaction.Current = this.LocalRunspace.ExecutionContext.CurrentTransaction; -#endif // Raise the event for Pipeline.Running RaisePipelineStateEvents(); // Add this pipeline to history RecordPipelineStartTime(); - // Add automatic transcription, but don't transcribe nested commands - if (this.AddToHistory || !IsNested) + // Add automatic transcription when it's NOT a pulse pipeline, but don't transcribe nested commands. + if (!IsPulsePipeline && (AddToHistory || !IsNested)) { - bool needToAddOutDefault = true; - CommandInfo outDefaultCommandInfo = new CmdletInfo("Out-Default", typeof(Microsoft.PowerShell.Commands.OutDefaultCommand), null, null, null); - - foreach (Command command in this.Commands) + foreach (Command command in Commands) { - if (command.IsScript && (!this.IsPulsePipeline)) + if (command.IsScript) { // Transcribe scripts, unless they are the pulse pipeline. - this.Runspace.GetExecutionContext.EngineHostInterface.UI.TranscribeCommand(command.CommandText, null); + Runspace.GetExecutionContext.EngineHostInterface.UI.TranscribeCommand(command.CommandText, invocation: null); } + } + + if (Runspace.GetExecutionContext.EngineHostInterface.UI.IsTranscribing) + { + bool needToAddOutDefault = true; + Command lastCommand = Commands[Commands.Count - 1]; // Don't need to add Out-Default if the pipeline already has it, or we've got a pipeline evaluating - // the PSConsoleHostReadLine command. - if ( - string.Equals(outDefaultCommandInfo.Name, command.CommandText, StringComparison.OrdinalIgnoreCase) || - string.Equals("PSConsoleHostReadLine", command.CommandText, StringComparison.OrdinalIgnoreCase) || - string.Equals("TabExpansion2", command.CommandText, StringComparison.OrdinalIgnoreCase) || - this.IsPulsePipeline) + // the PSConsoleHostReadLine or the TabExpansion2 commands. + if (string.Equals("Out-Default", lastCommand.CommandText, StringComparison.OrdinalIgnoreCase) || + string.Equals("PSConsoleHostReadLine", lastCommand.CommandText, StringComparison.OrdinalIgnoreCase) || + string.Equals("TabExpansion2", lastCommand.CommandText, StringComparison.OrdinalIgnoreCase) || + (lastCommand.CommandInfo is CmdletInfo cmdlet && cmdlet.ImplementingType == typeof(OutDefaultCommand))) { needToAddOutDefault = false; } - } - if (this.Runspace.GetExecutionContext.EngineHostInterface.UI.IsTranscribing) - { if (needToAddOutDefault) { - Command outDefaultCommand = new Command(outDefaultCommandInfo); + var outDefaultCommand = new Command( + new CmdletInfo( + "Out-Default", + typeof(OutDefaultCommand), + helpFile: null, + PSSnapin: null, + context: null)); + outDefaultCommand.Parameters.Add(new CommandParameter("Transcript", true)); outDefaultCommand.Parameters.Add(new CommandParameter("OutVariable", null)); @@ -491,10 +487,7 @@ private FlowControlException InvokeHelper() } PSLocalEventManager eventManager = LocalRunspace.Events as PSLocalEventManager; - if (eventManager != null) - { - eventManager.ProcessPendingActions(); - } + eventManager?.ProcessPendingActions(); // restore the trap state... this.LocalRunspace.ExecutionContext.PropagateExceptionsToEnclosingStatementBlock = oldTrapState; @@ -737,7 +730,7 @@ private void InvokeThreadProc() /// /// Stop the running pipeline. /// - /// If true pipeline is stoped synchronously + /// If true pipeline is stopped synchronously /// else asynchronously. protected override void ImplementStop(bool syncCall) { @@ -976,7 +969,7 @@ private void InitStreams() } /// - /// This method sets streams to their orignal states from execution context. + /// This method sets streams to their original states from execution context. /// This is done when Pipeline is completed/failed/stopped ie., termination state. /// private void ClearStreams() @@ -1074,9 +1067,9 @@ internal override void SetHistoryString(string historyString) /// ExecutionContext, if it available in TLS /// Null, if ExecutionContext is not available in TLS /// - internal static System.Management.Automation.ExecutionContext GetExecutionContextFromTLS() + internal static ExecutionContext GetExecutionContextFromTLS() { - System.Management.Automation.Runspaces.Runspace runspace = Runspace.DefaultRunspace; + Runspace runspace = Runspace.DefaultRunspace; if (runspace == null) { return null; @@ -1165,7 +1158,7 @@ internal PipelineThread(ApartmentState apartmentState) _closed = false; #if !UNIX - if (apartmentState != ApartmentState.Unknown && !Platform.IsNanoServer && !Platform.IsIoT) + if (apartmentState != ApartmentState.Unknown && Platform.IsStaSupported) { _worker.SetApartmentState(apartmentState); } diff --git a/src/System.Management.Automation/engine/hostifaces/MshHost.cs b/src/System.Management.Automation/engine/hostifaces/MshHost.cs index 7ee89d14b12..bfa79e89f13 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHost.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHost.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation.Host { /// - /// Defines the properties and facilities providing by an application hosting an MSH . /// /// @@ -15,7 +15,7 @@ namespace System.Management.Automation.Host /// overrides the abstract methods and properties. The hosting application creates an instance of its derived class and /// passes it to the CreateRunspace method. /// - /// From the moment that the instance of the derived class (the "host class") is passed to CreateRunspace, the MSH runtime + /// From the moment that the instance of the derived class (the "host class") is passed to CreateRunspace, the PowerShell runtime /// can call any of the methods of that class. The instance must not be destroyed until after the Runspace is closed. /// /// There is a 1:1 relationship between the instance of the host class and the Runspace instance to which it is passed. In @@ -64,9 +64,9 @@ protected PSHost() /// The name identifier of the hosting application. /// /// - /// + /// /// if ($Host.Name -ieq "ConsoleHost") { write-host "I'm running in the Console Host" } - /// + /// /// public abstract string Name { @@ -79,7 +79,7 @@ public abstract string Name /// /// /// When implementing this member, it should return the product version number for the product - /// that is hosting the Monad engine. + /// that is hosting the PowerShell engine. /// /// /// The version number of the hosting application. @@ -296,6 +296,11 @@ public interface IHostSupportsInteractiveSession /// /// Called by the engine to notify the host that a runspace push has been requested. /// + /// + /// The runspace to push. This runspace must be a remote runspace and + /// not a locally created runspace. + /// + /// The specified runspace is not a remote runspace. /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Runspace")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "runspace")] diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs index f4c3aedfb69..64b200b7d61 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostRawUserInterface.cs @@ -62,7 +62,7 @@ public int Y } /// - /// Overrides + /// Overrides /// /// /// "a,b" where a and b are the values of the X and Y properties. @@ -71,11 +71,11 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", X, Y); + return string.Create(CultureInfo.InvariantCulture, $"{X},{Y}"); } /// - /// Overrides + /// Overrides /// /// /// object to be compared for equality. @@ -99,7 +99,7 @@ public override } /// - /// Overrides + /// Overrides /// /// /// Hash code for this instance. @@ -248,7 +248,7 @@ public int Height } /// - /// Overloads + /// Overloads /// /// /// "a,b" where a and b are the values of the Width and Height properties. @@ -257,11 +257,11 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1}", Width, Height); + return string.Create(CultureInfo.InvariantCulture, $"{Width},{Height}"); } /// - /// Overrides + /// Overrides /// /// /// object to be compared for equality. @@ -285,7 +285,7 @@ public override } /// - /// Overrides + /// Overrides /// /// /// Hash code for this instance. @@ -557,7 +557,7 @@ bool keyDown } /// - /// Overloads + /// Overloads /// /// /// "a,b,c,d" where a, b, c, and d are the values of the VirtualKeyCode, Character, ControlKeyState, and KeyDown properties. @@ -566,10 +566,10 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", VirtualKeyCode, Character, ControlKeyState, KeyDown); + return string.Create(CultureInfo.InvariantCulture, $"{VirtualKeyCode},{Character},{ControlKeyState},{KeyDown}"); } /// - /// Overrides + /// Overrides /// /// /// object to be compared for equality. @@ -593,7 +593,7 @@ public override } /// - /// Overrides + /// Overrides /// /// /// Hash code for this instance. @@ -787,7 +787,7 @@ public int Bottom } /// - /// Overloads + /// Overloads /// /// /// "a,b ; c,d" where a, b, c, and d are values of the Left, Top, Right, and Bottom properties. @@ -796,11 +796,11 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0},{1} ; {2},{3}", Left, Top, Right, Bottom); + return string.Create(CultureInfo.InvariantCulture, $"{Left},{Top} ; {Right},{Bottom}"); } /// - /// Overrides + /// Overrides /// /// /// object to be compared for equality. @@ -824,7 +824,7 @@ public override } /// - /// Overrides + /// Overrides /// /// /// Hash code for this instance. @@ -1015,7 +1015,7 @@ public BufferCellType BufferCellType } /// - /// Overloads + /// Overloads /// /// /// "'a' b c d" where a, b, c, and d are the values of the Character, ForegroundColor, BackgroundColor, and Type properties. @@ -1024,11 +1024,11 @@ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "'{0}' {1} {2} {3}", Character, ForegroundColor, BackgroundColor, BufferCellType); + return string.Create(CultureInfo.InvariantCulture, $"'{Character}' {ForegroundColor} {BackgroundColor} {BufferCellType}"); } /// - /// Overrides + /// Overrides /// /// /// object to be compared for equality. @@ -1052,14 +1052,14 @@ public override } /// - /// Overrides + /// Overrides /// /// /// /// Hash code for this instance. /// - /// + /// public override int GetHashCode() @@ -1150,7 +1150,7 @@ public enum #endregion Ancillary types /// - /// Defines the lowest-level user interface functions that an interactive application hosting an MSH + /// Defines the lowest-level user interface functions that an interactive application hosting PowerShell /// can choose to implement if it wants to /// support any cmdlet that does character-mode interaction with the user. /// @@ -1340,9 +1340,9 @@ public abstract /// Key stroke when a key is pressed. /// /// - /// + /// /// $Host.UI.RawUI.ReadKey() - /// + /// /// /// /// @@ -1370,10 +1370,10 @@ public abstract /// Neither ReadKeyOptions.IncludeKeyDown nor ReadKeyOptions.IncludeKeyUp is specified. /// /// - /// + /// /// $option = [System.Management.Automation.Host.ReadKeyOptions]"IncludeKeyDown"; /// $host.UI.RawUI.ReadKey($option) - /// + /// /// /// /// @@ -1458,11 +1458,11 @@ public abstract /// Provided for clearing regions -- less chatty than passing an array of cells. /// /// - /// + /// /// using System; /// using System.Management.Automation; /// using System.Management.Automation.Host; - /// namespace Microsoft.Samples.MSH.Cmdlet + /// namespace Microsoft.Samples.Cmdlet /// { /// [Cmdlet("Clear","Screen")] /// public class ClearScreen : PSCmdlet @@ -1474,7 +1474,7 @@ public abstract /// } /// } /// } - /// + /// /// /// /// @@ -1687,7 +1687,7 @@ char source /// is null; /// Any string in is null or empty /// - /// + /// /// If a character C takes one BufferCell to display as determined by LengthInBufferCells, /// one BufferCell is allocated with its Character set to C and BufferCellType to BufferCell.Complete. /// On the other hand, if C takes two BufferCell, two adjacent BufferCells on a row in @@ -1701,7 +1701,7 @@ char source /// and , respectively. /// The resulting array is suitable for use with /// and . - /// + /// /// /// /// @@ -1784,7 +1784,7 @@ char source /// /// Creates a 2D array of BufferCells by examining .Character. - /// + /// /// /// /// The number of columns of the resulting array diff --git a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs index e6d40c72419..5f51ba15751 100644 --- a/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs +++ b/src/System.Management.Automation/engine/hostifaces/MshHostUserInterface.cs @@ -112,10 +112,10 @@ public abstract System.Management.Automation.Host.PSHostRawUserInterface RawUI /// /// The default implementation writes a carriage return to the screen buffer. - /// - /// - /// - /// + /// + /// + /// + /// /// public virtual void WriteLine() { @@ -170,10 +170,10 @@ public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgro /// /// Writes a line to the "error display" of the host, as opposed to the "output display," which is /// written to by the variants of - /// - /// - /// and - /// + /// + /// + /// and + /// /// /// /// The characters to be written. @@ -232,6 +232,147 @@ public virtual void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgro /// public virtual void WriteInformation(InformationRecord record) { } + private static bool ShouldOutputPlainText(bool isHost, bool? supportsVirtualTerminal) + { + var outputRendering = OutputRendering.PlainText; + + if (supportsVirtualTerminal != false) + { + switch (PSStyle.Instance.OutputRendering) + { + case OutputRendering.Host: + outputRendering = isHost ? OutputRendering.Ansi : OutputRendering.PlainText; + break; + default: + outputRendering = PSStyle.Instance.OutputRendering; + break; + } + } + + return outputRendering == OutputRendering.PlainText; + } + + /// + /// The format styles that are supported by the host. + /// + public enum FormatStyle + { + /// + /// Reset the formatting to the default. + /// + Reset, + + /// + /// Highlight text used in output formatting. + /// + FormatAccent, + + /// + /// Highlight for table headers. + /// + TableHeader, + + /// + /// Highlight for detailed error view. + /// + ErrorAccent, + + /// + /// Style for error messages. + /// + Error, + + /// + /// Style for warning messages. + /// + Warning, + + /// + /// Style for verbose messages. + /// + Verbose, + + /// + /// Style for debug messages. + /// + Debug, + } + + /// + /// Get the ANSI escape sequence for the given format style. + /// + /// + /// The format style to get the escape sequence for. + /// + /// + /// The ANSI escape sequence for the given format style. + /// + public static string GetFormatStyleString(FormatStyle formatStyle) + { + if (PSStyle.Instance.OutputRendering == OutputRendering.PlainText) + { + return string.Empty; + } + + PSStyle psstyle = PSStyle.Instance; + switch (formatStyle) + { + case FormatStyle.Reset: + return psstyle.Reset; + case FormatStyle.FormatAccent: + return psstyle.Formatting.FormatAccent; + case FormatStyle.TableHeader: + return psstyle.Formatting.TableHeader; + case FormatStyle.ErrorAccent: + return psstyle.Formatting.ErrorAccent; + case FormatStyle.Error: + return psstyle.Formatting.Error; + case FormatStyle.Warning: + return psstyle.Formatting.Warning; + case FormatStyle.Verbose: + return psstyle.Formatting.Verbose; + case FormatStyle.Debug: + return psstyle.Formatting.Debug; + default: + return string.Empty; + } + } + + /// + /// Get the appropriate output string based on different criteria. + /// + /// + /// The text to format. + /// + /// + /// True if the host supports virtual terminal. + /// + /// + /// The formatted text. + /// + public static string GetOutputString(string text, bool supportsVirtualTerminal) + { + return GetOutputString(text, isHost: true, supportsVirtualTerminal: supportsVirtualTerminal); + } + + internal static string GetOutputString(string text, bool isHost, bool? supportsVirtualTerminal = null) + { + var sd = new ValueStringDecorated(text); + + if (sd.IsDecorated) + { + var outputRendering = OutputRendering.Ansi; + if (ShouldOutputPlainText(isHost, supportsVirtualTerminal)) + { + outputRendering = OutputRendering.PlainText; + } + + text = sd.ToString(outputRendering); + } + + return text; + } + // Gets the state associated with PowerShell transcription. // // Ideally, this would be associated with the host instance, but remoting recycles host instances @@ -438,7 +579,7 @@ private void CheckSystemTranscript() { if (TranscriptionData.SystemTranscript == null) { - TranscriptionData.SystemTranscript = PSHostUserInterface.GetSystemTranscriptOption(TranscriptionData.SystemTranscript); + TranscriptionData.SystemTranscript = GetSystemTranscriptOption(TranscriptionData.SystemTranscript); if (TranscriptionData.SystemTranscript != null) { LogTranscriptHeader(null, TranscriptionData.SystemTranscript); @@ -620,13 +761,10 @@ internal void TranscribeResult(Runspace sourceRunspace, string resultText) resultText = resultText.TrimEnd(); - if (ExperimentalFeature.IsEnabled("PSAnsiRendering")) + var text = new ValueStringDecorated(resultText); + if (text.IsDecorated) { - var text = new ValueStringDecorated(resultText); - if (text.IsDecorated) - { - resultText = text.ToString(OutputRendering.PlainText); - } + resultText = text.ToString(OutputRendering.PlainText); } foreach (TranscriptionOption transcript in TranscriptionData.Transcripts.Prepend(TranscriptionData.SystemTranscript)) @@ -754,7 +892,7 @@ private void FlushPendingOutput() { // System transcripts can have high contention. Do exponential back-off on writing // if needed. - int delay = new Random().Next(10) + 1; + int delay = Random.Shared.Next(10) + 1; bool written = false; while (!written) @@ -952,10 +1090,7 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio // This way, multiple runspaces opened by the same process will share the same transcript. lock (s_systemTranscriptLock) { - if (systemTranscript == null) - { - systemTranscript = PSHostUserInterface.GetTranscriptOptionFromSettings(transcription, currentTranscript); - } + systemTranscript ??= PSHostUserInterface.GetTranscriptOptionFromSettings(transcription, currentTranscript); } } @@ -966,7 +1101,7 @@ internal static TranscriptionOption GetSystemTranscriptOption(TranscriptionOptio private static readonly object s_systemTranscriptLock = new object(); private static readonly Lazy s_transcriptionSettingCache = new Lazy( - () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), + static () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); private static TranscriptionOption GetTranscriptOptionFromSettings(Transcription transcriptConfig, TranscriptionOption currentTranscript) @@ -1021,6 +1156,11 @@ internal static string GetTranscriptPath(string baseDirectory, bool includeDate) } } + if (string.IsNullOrEmpty(baseDirectory)) + { + return string.Empty; + } + if (includeDate) { baseDirectory = Path.Combine(baseDirectory, DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture)); @@ -1032,8 +1172,8 @@ internal static string GetTranscriptPath(string baseDirectory, bool includeDate) // bytes of randomness (2^48 = 2.8e14) would take an attacker about 891 years to guess // a filename (assuming they knew the time the transcript was started). // (5 bytes = 3 years, 4 bytes = about a month) - byte[] randomBytes = new byte[6]; - System.Security.Cryptography.RandomNumberGenerator.Create().GetBytes(randomBytes); + Span randomBytes = stackalloc byte[6]; + System.Security.Cryptography.RandomNumberGenerator.Fill(randomBytes); string filename = string.Format( Globalization.CultureInfo.InvariantCulture, "PowerShell_transcript.{0}.{1}.{2:yyyyMMddHHmmss}.txt", @@ -1108,7 +1248,7 @@ internal void FlushContentToDisk() { static Encoding GetPathEncoding(string path) { - using StreamReader reader = new StreamReader(path, Utils.utf8NoBom, detectEncodingFromByteOrderMarks: true); + using StreamReader reader = new StreamReader(path, Encoding.Default, detectEncodingFromByteOrderMarks: true); _ = reader.Read(); return reader.CurrentEncoding; } @@ -1136,7 +1276,7 @@ static Encoding GetPathEncoding(string path) // file permissions. _contentWriter = new StreamWriter( new FileStream(this.Path, FileMode.Append, FileAccess.Write, FileShare.Read), - Utils.utf8NoBom); + Encoding.Default); } _contentWriter.AutoFlush = true; @@ -1159,7 +1299,10 @@ static Encoding GetPathEncoding(string path) /// public void Dispose() { - if (_disposed) { return; } + if (_disposed) + { + return; + } // Wait for any pending output to be flushed to disk so that Stop-Transcript // can be trusted to immediately have all content from that session in the file) @@ -1262,7 +1405,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch Text.StringBuilder splitLabel = new Text.StringBuilder(choices[i].Label.Substring(0, andPos), choices[i].Label.Length); if (andPos + 1 < choices[i].Label.Length) { - splitLabel.Append(choices[i].Label.Substring(andPos + 1)); + splitLabel.Append(choices[i].Label.AsSpan(andPos + 1)); hotkeysAndPlainLabels[0, i] = CultureInfo.CurrentCulture.TextInfo.ToUpper(choices[i].Label.AsSpan(andPos + 1, 1).Trim().ToString()); } @@ -1278,7 +1421,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch if (string.Equals(hotkeysAndPlainLabels[0, i], "?", StringComparison.Ordinal)) { Exception e = PSTraceSource.NewArgumentException( - string.Format(Globalization.CultureInfo.InvariantCulture, "choices[{0}].Label", i), + string.Create(Globalization.CultureInfo.InvariantCulture, $"choices[{i}].Label"), InternalHostUserInterfaceStrings.InvalidChoiceHotKeyError); throw e; } @@ -1295,7 +1438,7 @@ internal static void BuildHotkeysAndPlainLabels(Collection ch /// /// /// Returns the index into the choices array matching the response string, or -1 if there is no match. - /// + /// internal static int DetermineChoicePicked(string response, Collection choices, string[,] hotkeysAndPlainLabels) { Diagnostics.Assert(choices != null, "choices: expected a value"); diff --git a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs b/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs deleted file mode 100644 index 74306b822df..00000000000 --- a/src/System.Management.Automation/engine/hostifaces/NativeCultureResolver.cs +++ /dev/null @@ -1,489 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -/********************************************************************++ - -Description: - -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. So -the static methods in this class calculate appropriate UI Culture -natively. ConsoleHot uses this API to set correct Thread UICulture. - -Dependent on: -GetThreadPreferredUILanguages -SetThreadPreferredUILanguages - -These methods are available on Windows Vista and later. - ---********************************************************************/ - -using System; -using System.Globalization; -using System.Runtime.InteropServices; -using System.Text; -using Dbg = System.Management.Automation.Diagnostics; -using WORD = System.UInt16; - -namespace Microsoft.PowerShell -{ - /// - /// Custom culture. - /// - internal class VistaCultureInfo : CultureInfo - { - private string[] _fallbacks; - // Cache the immediate parent and immediate fallback - private VistaCultureInfo _parentCI = null; - private object _syncObject = new object(); - - /// - /// Constructs a CultureInfo that keeps track of fallbacks. - /// - /// Name of the culture to construct. - /// - /// ordered,null-delimited list of fallbacks - /// - public VistaCultureInfo(string name, - string[] fallbacks) - : base(name) - { - _fallbacks = fallbacks; - } - - /// - /// Returns Parent culture for the current CultureInfo. - /// If Parent.Name is null or empty, then chooses the immediate fallback - /// If it is not empty, otherwise just returns Parent. - /// - public override CultureInfo Parent - { - get - { - // First traverse the parent hierarchy as established by CLR. - // This is required because there is difference in the parent hierarchy - // between CLR and Windows for Chinese. Ex: Native windows has - // zh-CN->zh-Hans->neutral whereas CLR has zh-CN->zh-CHS->zh-Hans->neutral - if ((base.Parent != null) && (!string.IsNullOrEmpty(base.Parent.Name))) - { - return ImmediateParent; - } - - // Check whether we have any fallback specified - // MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK - // returns fallback cultures (specified by the user) - // and also adds neutral culture where appropriate. - // Ex: ja-jp ja en-us en - while ((_fallbacks != null) && (_fallbacks.Length > 0)) - { - string fallback = _fallbacks[0]; - string[] fallbacksForParent = null; - - if (_fallbacks.Length > 1) - { - fallbacksForParent = new string[_fallbacks.Length - 1]; - Array.Copy(_fallbacks, 1, fallbacksForParent, 0, _fallbacks.Length - 1); - } - - try - { - return new VistaCultureInfo(fallback, fallbacksForParent); - } - // if there is any exception constructing the culture..catch..and go to - // the next culture in the list. - catch (ArgumentException) - { - _fallbacks = fallbacksForParent; - } - } - - // no fallbacks..just return base parent - return base.Parent; - } - } - - /// - /// This is called to create the parent culture (as defined by CLR) - /// of the current culture. - /// - private VistaCultureInfo ImmediateParent - { - get - { - if (_parentCI == null) - { - lock (_syncObject) - { - if (_parentCI == null) - { - string parentCulture = base.Parent.Name; - // remove the parentCulture from the m_fallbacks list. - // ie., remove duplicates from the parent hierarchy. - string[] fallbacksForTheParent = null; - if (_fallbacks != null) - { - fallbacksForTheParent = new string[_fallbacks.Length]; - int currentIndex = 0; - foreach (string culture in _fallbacks) - { - if (!parentCulture.Equals(culture, StringComparison.OrdinalIgnoreCase)) - { - fallbacksForTheParent[currentIndex] = culture; - currentIndex++; - } - } - - // There is atleast 1 duplicate in m_fallbacks which was not added to - // fallbacksForTheParent array. Resize the array to take care of this. - if (_fallbacks.Length != currentIndex) - { - Array.Resize(ref fallbacksForTheParent, currentIndex); - } - } - - _parentCI = new VistaCultureInfo(parentCulture, fallbacksForTheParent); - } - } - } - - return _parentCI; - } - } - - /// - /// Clones the custom CultureInfo retaining the fallbacks. - /// - /// Cloned custom CultureInfo. - public override object Clone() - { - return new VistaCultureInfo(base.Name, _fallbacks); - } - } - - /// - /// Static wrappers to get User chosen UICulture (for Vista and later) - /// - internal static class NativeCultureResolver - { - private static CultureInfo s_uiCulture = null; - private static CultureInfo s_culture = null; - private static object s_syncObject = new object(); - - /// - /// Gets the UICulture to be used by console host. - /// - internal static CultureInfo UICulture - { - get - { - if (s_uiCulture == null) - { - lock (s_syncObject) - { - if (s_uiCulture == null) - { - s_uiCulture = GetUICulture(); - } - } - } - - return (CultureInfo)s_uiCulture.Clone(); - } - } - - internal static CultureInfo Culture - { - get - { - if (s_culture == null) - { - lock (s_syncObject) - { - if (s_culture == null) - { - s_culture = GetCulture(); - } - } - } - - return s_culture; - } - } - - internal static CultureInfo GetUICulture() - { - return GetUICulture(true); - } - - internal static CultureInfo GetCulture() - { - return GetCulture(true); - } - - internal static CultureInfo GetUICulture(bool filterOutNonConsoleCultures) - { - if (!IsVistaAndLater()) - { - s_uiCulture = EmulateDownLevel(); - return s_uiCulture; - } - - // We are running on Vista - string langBuffer = GetUserPreferredUILangs(filterOutNonConsoleCultures); - if (!string.IsNullOrEmpty(langBuffer)) - { - try - { - string[] fallbacks = langBuffer.Split('\0', StringSplitOptions.RemoveEmptyEntries); - string fallback = fallbacks[0]; - string[] fallbacksForParent = null; - - if (fallbacks.Length > 1) - { - fallbacksForParent = new string[fallbacks.Length - 1]; - Array.Copy(fallbacks, 1, fallbacksForParent, 0, fallbacks.Length - 1); - } - - s_uiCulture = new VistaCultureInfo(fallback, fallbacksForParent); - return s_uiCulture; - } - catch (ArgumentException) - { - } - } - - s_uiCulture = EmulateDownLevel(); - return s_uiCulture; - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "In XP and below GetUserDefaultLocaleName is not available")] - internal static CultureInfo GetCulture(bool filterOutNonConsoleCultures) - { - CultureInfo returnValue; - try - { - if (!IsVistaAndLater()) - { - int lcid = GetUserDefaultLCID(); - returnValue = new CultureInfo(lcid); - } - else - { - // Vista and above - StringBuilder name = new StringBuilder(16); - if (0 == GetUserDefaultLocaleName(name, 16)) - { - // ther is an error retrieving the culture, - // just use the current thread's culture - returnValue = CultureInfo.CurrentCulture; - } - else - { - returnValue = new CultureInfo(name.ToString().Trim()); - } - } - - if (filterOutNonConsoleCultures) - { - // filter out languages that console cannot display.. - // Sometimes GetConsoleFallbackUICulture returns neutral cultures - // like "en" on "ar-SA". However neutral culture cannot be - // assigned as CurrentCulture. CreateSpecificCulture fixes - // this problem. - returnValue = CultureInfo.CreateSpecificCulture( - returnValue.GetConsoleFallbackUICulture().Name); - } - } - catch (ArgumentException) - { - // if there is any exception retrieving the - // culture, just use the current thread's culture. - returnValue = CultureInfo.CurrentCulture; - } - - return returnValue; - } - - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] - internal static extern WORD GetUserDefaultUILanguage(); - - /// - /// Constructs CultureInfo object without considering any Vista and later - /// custom culture fallback logic. - /// - /// A CultureInfo object. - [System.Diagnostics.CodeAnalysis.SuppressMessage("GoldMan", "#pw17903:UseOfLCID", Justification = "This is only called In XP and below where GetUserDefaultLocaleName is not available, or as a fallback when GetThreadPreferredUILanguages fails")] - private static CultureInfo EmulateDownLevel() - { - // GetConsoleFallbackUICulture is not required. - // This is retained in order not to break existing code. - ushort langId = NativeCultureResolver.GetUserDefaultUILanguage(); - CultureInfo ci = new CultureInfo((int)langId); - return ci.GetConsoleFallbackUICulture(); - } - - /// - /// Checks if the current operating system is Vista or later. - /// - /// - /// true, if vista and above - /// false, otherwise. - /// - private static bool IsVistaAndLater() - { - // The version number is obtained from MSDN - // 4 - Windows NT 4.0, Windows Me, Windows 98, or Windows 95. - // 5 - Windows Server 2003 R2, Windows Server 2003, Windows XP, or Windows 2000. - // 6 - Windows Vista or Windows Server "Longhorn". - - if (Environment.OSVersion.Version.Major >= 6) - { - return true; - } - - return false; - } - - /// - /// This method is called on vista and above. - /// Using GetThreadPreferredUILanguages this method gets - /// the UI languages a user has chosen. - /// - /// - /// List of ThreadPreferredUILanguages. - /// - /// - /// This method will work only on Vista and later. - /// - private static string GetUserPreferredUILangs(bool filterOutNonConsoleCultures) - { - long numberLangs = 0; - int bufferSize = 0; - string returnval = string.Empty; - - if (filterOutNonConsoleCultures) - { - // Filter out languages that do not support console. - // The third parameter should be null otherwise this API will not - // set Console CodePage filter. - // The MSDN documentation does not call this out explicitly. Opened - // Bug 950 (Windows Developer Content) to track this. - if (!SetThreadPreferredUILanguages(s_MUI_CONSOLE_FILTER, null, IntPtr.Zero)) - { - return returnval; - } - } - - // calculate buffer size required - // MUI_MERGE_SYSTEM_FALLBACK | MUI_MERGE_USER_FALLBACK - // returns fallback cultures (specified by the user) - // and also adds neutral culture where appropriate. - // Ex: ja-jp ja en-us en - if (!GetThreadPreferredUILanguages( - s_MUI_LANGUAGE_NAME | s_MUI_MERGE_SYSTEM_FALLBACK | s_MUI_MERGE_USER_FALLBACK, - out numberLangs, - null, - out bufferSize)) - { - return returnval; - } - - // calculate space required to store output. - // StringBuilder will not work for this case as CLR - // does not copy the entire string if there are delimiter ('\0') - // in the middle of a string. - byte[] langBufferPtr = new byte[bufferSize * 2]; - - // Now get the actual value - if (!GetThreadPreferredUILanguages( - s_MUI_LANGUAGE_NAME | s_MUI_MERGE_SYSTEM_FALLBACK | s_MUI_MERGE_USER_FALLBACK, - out numberLangs, - langBufferPtr, // Pointer to a buffer in which this function retrieves an ordered, null-delimited list. - out bufferSize)) - { - return returnval; - } - - try - { - string langBuffer = Encoding.Unicode.GetString(langBufferPtr); - returnval = langBuffer.Trim().ToLowerInvariant(); - return returnval; - } - catch (ArgumentNullException) - { - } - catch (System.Text.DecoderFallbackException) - { - } - - return returnval; - } - - #region Dll Import data - - /// - /// Returns the locale identifier for the user default locale. - /// - /// - /// - /// This function can return data from custom locales. Locales are not - /// guaranteed to be the same from computer to computer or between runs - /// of an application. If your application must persist or transmit data, - /// see Using Persistent Locale Data. - /// Applications that are intended to run only on Windows Vista and later - /// should use GetUserDefaultLocaleName in preference to this function. - /// GetUserDefaultLocaleName provides good support for supplemental locales. - /// However, GetUserDefaultLocaleName is not supported for versions of Windows - /// prior to Windows Vista. - /// - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] - private static extern int GetUserDefaultLCID(); - - /// - /// Retrieves the user default locale name. - /// - /// - /// - /// - /// Returns the size of the buffer containing the locale name, including - /// the terminating null character, if successful. The function returns 0 - /// if it does not succeed. To get extended error information, the application - /// can call GetLastError. Possible returns from GetLastError - /// include ERR_INSUFFICIENT_BUFFER. - /// - /// - /// - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] - private static extern int GetUserDefaultLocaleName( - [MarshalAs(UnmanagedType.LPWStr)] - StringBuilder lpLocaleName, - int cchLocaleName); - - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] - private static extern bool SetThreadPreferredUILanguages(int dwFlags, - StringBuilder pwszLanguagesBuffer, - IntPtr pulNumLanguages); - - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] - private static extern bool GetThreadPreferredUILanguages(int dwFlags, - out long pulNumLanguages, - [MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 2)] - byte[] pwszLanguagesBuffer, - out int pcchLanguagesBuffer); - - [DllImport("kernel32.dll", SetLastError = false, CharSet = CharSet.Unicode)] - internal static extern Int16 SetThreadUILanguage(Int16 langId); - - // private static int MUI_LANGUAGE_ID = 0x4; - private static int s_MUI_LANGUAGE_NAME = 0x8; - private static int s_MUI_CONSOLE_FILTER = 0x100; - private static int s_MUI_MERGE_USER_FALLBACK = 0x20; - private static int s_MUI_MERGE_SYSTEM_FALLBACK = 0x10; - - #endregion - } -} diff --git a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs index 77bf704f383..6db40850381 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSCommand.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSCommand.cs @@ -77,7 +77,7 @@ internal PSCommand(Command command) /// current state. /// /// - /// A PSCommand instance with added. + /// A PSCommand instance with added. /// /// /// This method is not thread safe. @@ -89,13 +89,10 @@ public PSCommand AddCommand(string command) { if (command == null) { - throw PSTraceSource.NewArgumentNullException("cmdlet"); + throw PSTraceSource.NewArgumentNullException(nameof(command)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(command, false); _commands.Add(_currentCommand); @@ -136,10 +133,7 @@ public PSCommand AddCommand(string cmdlet, bool useLocalScope) throw PSTraceSource.NewArgumentNullException(nameof(cmdlet)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(cmdlet, false, useLocalScope); _commands.Add(_currentCommand); @@ -151,15 +145,15 @@ public PSCommand AddCommand(string cmdlet, bool useLocalScope) /// Add a piece of script to construct a command pipeline. /// For example, to construct a command string "get-process | foreach { $_.Name }" /// - /// PSCommand command = new PSCommand("get-process"). - /// AddCommand("foreach { $_.Name }", true); + /// PSCommand command = new PSCommand("get-process") + /// .AddScript("foreach { $_.Name }", true); /// /// /// /// A string representing the script. /// /// - /// A PSCommand instance with added. + /// A PSCommand instance with added. /// /// /// This method is not thread-safe. @@ -178,10 +172,7 @@ public PSCommand AddScript(string script) throw PSTraceSource.NewArgumentNullException(nameof(script)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(script, true); _commands.Add(_currentCommand); @@ -193,8 +184,8 @@ public PSCommand AddScript(string script) /// Add a piece of script to construct a command pipeline. /// For example, to construct a command string "get-process | foreach { $_.Name }" /// - /// PSCommand command = new PSCommand("get-process"). - /// AddCommand("foreach { $_.Name }", true); + /// PSCommand command = new PSCommand("get-process") + /// .AddScript("foreach { $_.Name }", true); /// /// /// @@ -204,7 +195,7 @@ public PSCommand AddScript(string script) /// if true local scope is used to run the script command. /// /// - /// A PSCommand instance with added. + /// A PSCommand instance with added. /// /// /// This method is not thread-safe. @@ -223,10 +214,7 @@ public PSCommand AddScript(string script, bool useLocalScope) throw PSTraceSource.NewArgumentNullException(nameof(script)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = new Command(script, true, useLocalScope); _commands.Add(_currentCommand); @@ -261,10 +249,7 @@ public PSCommand AddCommand(Command command) throw PSTraceSource.NewArgumentNullException(nameof(command)); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand = command; _commands.Add(_currentCommand); @@ -276,8 +261,9 @@ public PSCommand AddCommand(Command command) /// Add a parameter to the last added command. /// For example, to construct a command string "get-process | select-object -property name" /// - /// PSCommand command = new PSCommand("get-process"). - /// AddCommand("select-object").AddParameter("property","name"); + /// PSCommand command = new PSCommand("get-process") + /// .AddCommand("select-object") + /// .AddParameter("property", "name"); /// /// /// @@ -308,10 +294,7 @@ public PSCommand AddParameter(string parameterName, object value) new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(parameterName, value); return this; @@ -321,8 +304,9 @@ public PSCommand AddParameter(string parameterName, object value) /// Adds a switch parameter to the last added command. /// For example, to construct a command string "get-process | sort-object -descending" /// - /// PSCommand command = new PSCommand("get-process"). - /// AddCommand("sort-object").AddParameter("descending"); + /// PSCommand command = new PSCommand("get-process") + /// .AddCommand("sort-object") + /// .AddParameter("descending"); /// /// /// @@ -350,10 +334,7 @@ public PSCommand AddParameter(string parameterName) new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(parameterName, true); return this; @@ -370,10 +351,7 @@ internal PSCommand AddParameter(CommandParameter parameter) new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(parameter); return this; @@ -383,8 +361,9 @@ internal PSCommand AddParameter(CommandParameter parameter) /// Adds an argument to the last added command. /// For example, to construct a command string "get-process | select-object name" /// - /// PSCommand command = new PSCommand("get-process"). - /// AddCommand("select-object").AddParameter("name"); + /// PSCommand command = new PSCommand("get-process") + /// .AddCommand("select-object") + /// .AddArgument("name"); /// /// This will add the value "name" to the positional parameter list of "select-object" /// cmdlet. When the command is invoked, this value will get bound to positional parameter 0 @@ -412,10 +391,7 @@ public PSCommand AddArgument(object value) new object[] { "PSCommand" }); } - if (_owner != null) - { - _owner.AssertChangesAreAccepted(); - } + _owner?.AssertChangesAreAccepted(); _currentCommand.Parameters.Add(null, value); return this; diff --git a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs index d51c96a33e0..a0945e21df1 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSDataCollection.cs @@ -116,7 +116,6 @@ internal DataAddingEventArgs(Guid psInstanceId, object itemAdded) /// build /// Thread Safe buffer used with PowerShell Hosting interfaces. /// - [Serializable] public class PSDataCollection : IList, ICollection, IEnumerable, IList, ICollection, IEnumerable, IDisposable, ISerializable { #region Private Data @@ -336,7 +335,7 @@ protected PSDataCollection(SerializationInfo info, StreamingContext context) throw PSTraceSource.NewArgumentNullException(nameof(info)); } - if (!(info.GetValue("Data", typeof(IList)) is IList listToUse)) + if (info.GetValue("Data", typeof(IList)) is not IList listToUse) { throw PSTraceSource.NewArgumentNullException(nameof(info)); } @@ -553,11 +552,8 @@ public void Complete() // raise the events outside of the lock. if (raiseEvents) { - if (_readWaitHandle != null) - { - // unblock any readers waiting on the handle - _readWaitHandle.Set(); - } + // unblock any readers waiting on the handle + _readWaitHandle?.Set(); // A temporary variable is used as the Completed may // reach null (because of -='s) after the null check @@ -798,10 +794,7 @@ public void Clear() { lock (SyncObject) { - if (_data != null) - { - _data.Clear(); - } + _data?.Clear(); } } @@ -1322,12 +1315,9 @@ internal WaitHandle WaitHandle { lock (SyncObject) { - if (_readWaitHandle == null) - { - // Create the handle signaled if there are objects in the buffer - // or the buffer has been closed. - _readWaitHandle = new ManualResetEvent(_data.Count > 0 || !_isOpen); - } + // Create the handle signaled if there are objects in the buffer + // or the buffer has been closed. + _readWaitHandle ??= new ManualResetEvent(_data.Count > 0 || !_isOpen); } } @@ -1522,7 +1512,7 @@ internal void InternalAddRange(Guid psInstanceId, ICollection collection) { InsertItem(psInstanceId, _data.Count, (T)o); - // set raise events if atleast one item is + // set raise events if at least one item is // added. raiseEvents = true; } @@ -1557,14 +1547,14 @@ internal void DecrementRef() Dbg.Assert(_refCount > 0, "RefCount cannot be <= 0"); _refCount--; - if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) return; - - // release threads blocked on waithandle - if (_readWaitHandle != null) + if (_refCount != 0 && (!_blockingEnumerator || _refCount != 1)) { - _readWaitHandle.Set(); + return; } + // release threads blocked on waithandle + _readWaitHandle?.Set(); + // release any threads to notify refCount is 0. Enumerator // blocks on this syncObject and it needs to be notified // when the count becomes 0. @@ -1795,10 +1785,7 @@ protected void Dispose(bool disposing) _readWaitHandle = null; } - if (_data != null) - { - _data.Clear(); - } + _data?.Clear(); } } } @@ -2099,65 +2086,35 @@ internal PSDataCollection Debug /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddProgress(ProgressRecord item) - { - if (progress != null) - { - progress.InternalAdd(_psInstanceId, item); - } - } + internal void AddProgress(ProgressRecord item) => progress?.InternalAdd(_psInstanceId, item); /// /// Adds item to the verbose buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddVerbose(VerboseRecord item) - { - if (verbose != null) - { - verbose.InternalAdd(_psInstanceId, item); - } - } + internal void AddVerbose(VerboseRecord item) => verbose?.InternalAdd(_psInstanceId, item); /// /// Adds item to the debug buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddDebug(DebugRecord item) - { - if (debug != null) - { - debug.InternalAdd(_psInstanceId, item); - } - } + internal void AddDebug(DebugRecord item) => debug?.InternalAdd(_psInstanceId, item); /// /// Adds item to the warning buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddWarning(WarningRecord item) - { - if (Warning != null) - { - Warning.InternalAdd(_psInstanceId, item); - } - } + internal void AddWarning(WarningRecord item) => Warning?.InternalAdd(_psInstanceId, item); /// /// Adds item to the information buffer. /// The item is added to the buffer along with PowerShell InstanceId. /// /// - internal void AddInformation(InformationRecord item) - { - if (Information != null) - { - Information.InternalAdd(_psInstanceId, item); - } - } + internal void AddInformation(InformationRecord item) => Information?.InternalAdd(_psInstanceId, item); #endregion } diff --git a/src/System.Management.Automation/engine/hostifaces/PSTask.cs b/src/System.Management.Automation/engine/hostifaces/PSTask.cs index 5f05d267fcd..56bdabbff14 100644 --- a/src/System.Management.Automation/engine/hostifaces/PSTask.cs +++ b/src/System.Management.Automation/engine/hostifaces/PSTask.cs @@ -68,6 +68,7 @@ protected override void InitializePowershell() _powershell.Streams.Warning.DataAdded += (sender, args) => HandleWarningData(); _powershell.Streams.Verbose.DataAdded += (sender, args) => HandleVerboseData(); _powershell.Streams.Debug.DataAdded += (sender, args) => HandleDebugData(); + _powershell.Streams.Progress.DataAdded += (sender, args) => HandleProgressData(); _powershell.Streams.Information.DataAdded += (sender, args) => HandleInformationData(); // State change handler @@ -132,6 +133,15 @@ private void HandleInformationData() } } + private void HandleProgressData() + { + foreach (var item in _powershell.Streams.Progress.ReadAll()) + { + _dataStreamWriter.Add( + new PSStreamObject(PSStreamObjectType.Progress, item)); + } + } + #endregion #region Event handlers @@ -486,13 +496,7 @@ public void Start(Runspace runspace) /// /// Signals the running task to stop. /// - public void SignalStop() - { - if (_powershell != null) - { - _powershell.BeginStop(null, null); - } - } + public void SignalStop() => _powershell?.BeginStop(null, null); #endregion } @@ -908,7 +912,7 @@ private void CheckForComplete() private Runspace GetRunspace(int taskId) { - var runspaceName = string.Format(CultureInfo.InvariantCulture, "{0}:{1}", PSTask.RunspaceName, taskId); + var runspaceName = string.Create(CultureInfo.InvariantCulture, $"{PSTask.RunspaceName}:{taskId}"); if (_useRunspacePool && _runspacePool.TryDequeue(out Runspace runspace)) { @@ -932,8 +936,23 @@ private Runspace GetRunspace(int taskId) // Create and initialize a new Runspace var iss = InitialSessionState.CreateDefault2(); - iss.LanguageMode = (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Enforce) - ? PSLanguageMode.ConstrainedLanguage : PSLanguageMode.FullLanguage; + switch (SystemPolicy.GetSystemLockdownPolicy()) + { + case SystemEnforcementMode.Enforce: + iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemEnforcementMode.Audit: + // In audit mode, CL restrictions are not enforced and instead audit + // log entries are created. + iss.LanguageMode = PSLanguageMode.ConstrainedLanguage; + break; + + case SystemEnforcementMode.None: + iss.LanguageMode = PSLanguageMode.FullLanguage; + break; + } + runspace = RunspaceFactory.CreateRunspace(iss); runspace.Name = runspaceName; _activeRunspaces.TryAdd(runspace.Id, runspace); @@ -1526,12 +1545,9 @@ public Debugger Debugger { get { - if (_jobDebuggerWrapper == null) - { - _jobDebuggerWrapper = new PSTaskChildDebugger( - _task.Debugger, - this.Name); - } + _jobDebuggerWrapper ??= new PSTaskChildDebugger( + _task.Debugger, + this.Name); return _jobDebuggerWrapper; } diff --git a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs index 874691852cb..f7bca01fe7b 100644 --- a/src/System.Management.Automation/engine/hostifaces/Pipeline.cs +++ b/src/System.Management.Automation/engine/hostifaces/Pipeline.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation.Runspaces /// Defines exception which is thrown when state of the pipeline is different /// from expected state. /// - [Serializable] public class InvalidPipelineStateException : SystemException { /// @@ -86,9 +85,10 @@ internal InvalidPipelineStateException(string message, PipelineState currentStat /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] private InvalidPipelineStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -445,7 +445,7 @@ internal void SetHadErrors(bool status) /// /// This flag is used to force the redirection. By default it is false to maintain compatibility with /// V1, but the V2 hosting interface (PowerShell class) sets this flag to true to ensure the global - /// error output pipe is always set and $ErrorActionPreference when invoking the Pipeline. + /// error output pipe is always set and $ErrorActionPreference is checked when invoking the Pipeline. /// internal bool RedirectShellErrorOutputPipe { get; set; } = false; diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs index 3829634c8c8..3af978ea165 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShell.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShell.cs @@ -31,7 +31,6 @@ namespace System.Management.Automation /// Defines exception which is thrown when state of the PowerShell is different /// from the expected state. /// - [Serializable] public class InvalidPowerShellStateException : SystemException { /// @@ -97,10 +96,11 @@ internal InvalidPowerShellStateException(PSInvocationState currentState) /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidPowerShellStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -762,10 +762,7 @@ internal void InitForRemotePipeline(CommandCollection command, ObjectStreamBase // create the client remote powershell for remoting // communications - if (RemotePowerShell == null) - { - RemotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); - } + RemotePowerShell ??= new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); // If we get here, we don't call 'Invoke' or any of it's friends on 'this', instead we serialize 'this' in PowerShell.ToPSObjectForRemoting. // Without the following two steps, we'll be missing the 'ExtraCommands' on the serialized instance of 'this'. @@ -804,10 +801,7 @@ internal void InitForRemotePipelineConnect(ObjectStreamBase inputstream, ObjectS RedirectShellErrorOutputPipe = redirectShellErrorOutputPipe; - if (RemotePowerShell == null) - { - RemotePowerShell = new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); - } + RemotePowerShell ??= new ClientRemotePowerShell(this, ((RunspacePool)_rsConnection).RemoteRunspacePoolInternal); if (!RemotePowerShell.Initialized) { @@ -952,9 +946,11 @@ private static PowerShell Create(bool isNested, PSCommand psCommand, Collection< /// /// Add a cmdlet to construct a command pipeline. - /// For example, to construct a command string "get-process | sort-object", + /// For example, to construct a command string "Get-Process | Sort-Object", /// - /// PowerShell shell = PowerShell.Create("get-process").AddCommand("sort-object"); + /// PowerShell shell = PowerShell.Create() + /// .AddCommand("Get-Process") + /// .AddCommand("Sort-Object"); /// /// /// @@ -990,9 +986,11 @@ public PowerShell AddCommand(string cmdlet) /// /// Add a cmdlet to construct a command pipeline. - /// For example, to construct a command string "get-process | sort-object", + /// For example, to construct a command string "Get-Process | Sort-Object", /// - /// PowerShell shell = PowerShell.Create("get-process").AddCommand("sort-object"); + /// PowerShell shell = PowerShell.Create() + /// .AddCommand("Get-Process", true) + /// .AddCommand("Sort-Object", true); /// /// /// @@ -1031,10 +1029,10 @@ public PowerShell AddCommand(string cmdlet, bool useLocalScope) /// /// Add a piece of script to construct a command pipeline. - /// For example, to construct a command string "get-process | foreach { $_.Name }" + /// For example, to construct a command string "Get-Process | ForEach-Object { $_.Name }" /// - /// PowerShell shell = PowerShell.Create("get-process"). - /// AddCommand("foreach { $_.Name }", true); + /// PowerShell shell = PowerShell.Create() + /// .AddScript("Get-Process | ForEach-Object { $_.Name }"); /// /// /// @@ -1070,10 +1068,10 @@ public PowerShell AddScript(string script) /// /// Add a piece of script to construct a command pipeline. - /// For example, to construct a command string "get-process | foreach { $_.Name }" + /// For example, to construct a command string "Get-Process | ForEach-Object { $_.Name }" /// - /// PowerShell shell = PowerShell.Create("get-process"). - /// AddCommand("foreach { $_.Name }", true); + /// PowerShell shell = PowerShell.Create() + /// .AddScript("Get-Process | ForEach-Object { $_.Name }", true); /// /// /// @@ -1179,10 +1177,11 @@ public PowerShell AddCommand(CommandInfo commandInfo) /// /// Add a parameter to the last added command. - /// For example, to construct a command string "get-process | select-object -property name" + /// For example, to construct a command string "Get-Process | Select-Object -Property Name" /// - /// PowerShell shell = PowerShell.Create("get-process"). - /// AddCommand("select-object").AddParameter("property","name"); + /// PowerShell shell = PowerShell.Create() + /// .AddCommand("Get-Process") + /// .AddCommand("Select-Object").AddParameter("Property", "Name"); /// /// /// @@ -1370,7 +1369,7 @@ public PowerShell AddParameters(IDictionary parameters) foreach (DictionaryEntry entry in parameters) { - if (!(entry.Key is string parameterName)) + if (entry.Key is not string parameterName) { throw PSTraceSource.NewArgumentException(nameof(parameters), PowerShellStrings.KeyMustBeString); } @@ -1384,10 +1383,11 @@ public PowerShell AddParameters(IDictionary parameters) /// /// Adds an argument to the last added command. - /// For example, to construct a command string "get-process | select-object name" + /// For example, to construct a command string "Get-Process | Select-Object Name" /// - /// PowerShell shell = PowerShell.Create("get-process"). - /// AddCommand("select-object").AddParameter("name"); + /// PowerShell shell = PowerShell.Create() + /// .AddCommand("Get-Process") + /// .AddCommand("Select-Object").AddArgument("Name"); /// /// This will add the value "name" to the positional parameter list of "select-object" /// cmdlet. When the command is invoked, this value will get bound to positional parameter 0 @@ -2236,10 +2236,7 @@ internal void InvokeWithDebugger( { if (addToHistory) { - if (settings == null) - { - settings = new PSInvocationSettings(); - } + settings ??= new PSInvocationSettings(); settings.AddToHistory = true; } @@ -3079,6 +3076,10 @@ public IAsyncResult BeginInvoke(PSDataCollection input, /// /// Object is disposed. /// + /// + /// The running PowerShell pipeline was stopped. + /// This occurs when or is called. + /// public Task> InvokeAsync() => Task>.Factory.FromAsync(BeginInvoke(), _endInvokeMethod); @@ -3120,6 +3121,10 @@ public Task> InvokeAsync() /// /// Object is disposed. /// + /// + /// The running PowerShell pipeline was stopped. + /// This occurs when or is called. + /// public Task> InvokeAsync(PSDataCollection input) => Task>.Factory.FromAsync(BeginInvoke(input), _endInvokeMethod); @@ -3174,6 +3179,10 @@ public Task> InvokeAsync(PSDataCollection input /// /// Object is disposed. /// + /// + /// The running PowerShell pipeline was stopped. + /// This occurs when or is called. + /// public Task> InvokeAsync(PSDataCollection input, PSInvocationSettings settings, AsyncCallback callback, object state) => Task>.Factory.FromAsync(BeginInvoke(input, settings, callback, state), _endInvokeMethod); @@ -3222,6 +3231,14 @@ public Task> InvokeAsync(PSDataCollection input /// /// Object is disposed. /// + /// + /// The running PowerShell pipeline was stopped. + /// This occurs when or is called. + /// To collect partial output in this scenario, + /// supply a for the parameter, + /// and either add a handler for the event + /// or catch the exception and enumerate the object supplied for . + /// public Task> InvokeAsync(PSDataCollection input, PSDataCollection output) => Task>.Factory.FromAsync(BeginInvoke(input, output), _endInvokeMethod); @@ -3284,6 +3301,14 @@ public Task> InvokeAsync(PSDataColle /// /// Object is disposed. /// + /// + /// The running PowerShell pipeline was stopped. + /// This occurs when or is called. + /// To collect partial output in this scenario, + /// supply a for the parameter, + /// and either add a handler for the event + /// or catch the exception and use object supplied for . + /// public Task> InvokeAsync(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state) => Task>.Factory.FromAsync(BeginInvoke(input, output, settings, callback, state), _endInvokeMethod); @@ -3323,7 +3348,7 @@ public Task> InvokeAsync(PSDataColle /// private IAsyncResult BeginBatchInvoke(PSDataCollection input, PSDataCollection output, PSInvocationSettings settings, AsyncCallback callback, object state) { - if (!((object)output is PSDataCollection asyncOutput)) + if ((object)output is not PSDataCollection asyncOutput) { throw PSTraceSource.NewInvalidOperationException(); } @@ -3493,9 +3518,7 @@ private void BatchInvocationCallback(IAsyncResult result) ActionPreference preference; if (_batchInvocationSettings != null) { - preference = (_batchInvocationSettings.ErrorActionPreference.HasValue) ? - _batchInvocationSettings.ErrorActionPreference.Value - : ActionPreference.Continue; + preference = _batchInvocationSettings.ErrorActionPreference ?? ActionPreference.Continue; } else { @@ -3518,10 +3541,7 @@ private void BatchInvocationCallback(IAsyncResult result) break; } - if (objs == null) - { - objs = _batchAsyncResult.Output; - } + objs ??= _batchAsyncResult.Output; DoRemainingBatchCommands(objs); } @@ -3655,6 +3675,14 @@ private void AppendExceptionToErrorStream(Exception e) /// asyncResult object was not created by calling BeginInvoke /// on this PowerShell instance. /// + /// + /// The running PowerShell pipeline was stopped. + /// This occurs when or is called. + /// To collect partial output in this scenario, + /// supply a to for the parameter + /// and either add a handler for the event + /// or catch the exception and enumerate the object supplied. + /// public PSDataCollection EndInvoke(IAsyncResult asyncResult) { try @@ -3706,6 +3734,10 @@ public PSDataCollection EndInvoke(IAsyncResult asyncResult) /// /// Object is disposed. /// + /// + /// When used with , that call will return a partial result. + /// When used with , that call will throw a . + /// public void Stop() { try @@ -3762,6 +3794,10 @@ public IAsyncResult BeginStop(AsyncCallback callback, object state) /// asyncResult object was not created by calling BeginStop /// on this PowerShell instance. /// + /// + /// When used with , that call will return a partial result. + /// When used with , that call will throw a . + /// public void EndStop(IAsyncResult asyncResult) { if (asyncResult == null) @@ -3812,6 +3848,10 @@ public void EndStop(IAsyncResult asyncResult) /// /// Object is disposed. /// + /// + /// When used with , that call will return a partial result. + /// When used with , that call will throw a . + /// public Task StopAsync(AsyncCallback callback, object state) => Task.Factory.FromAsync(BeginStop(callback, state), _endStopMethod); @@ -3840,15 +3880,50 @@ private void PipelineStateChanged(object source, PipelineStateEventArgs stateEve #region IDisposable Overrides /// - /// Dispose all managed resources. This will suppress finalizer on the object from getting called by - /// calling System.GC.SuppressFinalize(this). + /// Release all resources. /// public void Dispose() { - Dispose(true); - // To prevent derived types with finalizers from having to re-implement System.IDisposable to call it, - // unsealed types without finalizers should still call SuppressFinalize. - System.GC.SuppressFinalize(this); + lock (_syncObject) + { + // if already disposed return + if (_isDisposed) + { + return; + } + } + + // Stop the currently running command outside of the lock + if (InvocationStateInfo.State == PSInvocationState.Running || + InvocationStateInfo.State == PSInvocationState.Stopping) + { + Stop(); + } + + lock (_syncObject) + { + _isDisposed = true; + } + + if (OutputBuffer != null && OutputBufferOwner) + { + OutputBuffer.Dispose(); + } + + if (_errorBuffer != null && ErrorBufferOwner) + { + _errorBuffer.Dispose(); + } + + if (IsRunspaceOwner) + { + _runspace.Dispose(); + } + + RemotePowerShell?.Dispose(); + + _invokeAsyncResult = null; + _stopAsyncResult = null; } #endregion @@ -4081,62 +4156,6 @@ private void AssertNotDisposed() } } - /// - /// Release all the resources. - /// - /// - /// if true, release all the managed objects. - /// - private void Dispose(bool disposing) - { - if (disposing) - { - lock (_syncObject) - { - // if already disposed return - if (_isDisposed) - { - return; - } - } - - // Stop the currently running command outside of the lock - if (InvocationStateInfo.State == PSInvocationState.Running || - InvocationStateInfo.State == PSInvocationState.Stopping) - { - Stop(); - } - - lock (_syncObject) - { - _isDisposed = true; - } - - if (OutputBuffer != null && OutputBufferOwner) - { - OutputBuffer.Dispose(); - } - - if (_errorBuffer != null && ErrorBufferOwner) - { - _errorBuffer.Dispose(); - } - - if (IsRunspaceOwner) - { - _runspace.Dispose(); - } - - if (RemotePowerShell != null) - { - RemotePowerShell.Dispose(); - } - - _invokeAsyncResult = null; - _stopAsyncResult = null; - } - } - /// /// Clear the internal elements. /// @@ -4144,10 +4163,7 @@ private void InternalClearSuppressExceptions() { lock (_syncObject) { - if (_worker != null) - { - _worker.InternalClearSuppressExceptions(); - } + _worker?.InternalClearSuppressExceptions(); } } @@ -4273,10 +4289,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) { if (RunningExtraCommands) { - if (tempInvokeAsyncResult != null) - { - tempInvokeAsyncResult.SetAsCompleted(InvocationStateInfo.Reason); - } + tempInvokeAsyncResult?.SetAsCompleted(InvocationStateInfo.Reason); RaiseStateChangeEvent(InvocationStateInfo.Clone()); } @@ -4284,16 +4297,10 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) { RaiseStateChangeEvent(InvocationStateInfo.Clone()); - if (tempInvokeAsyncResult != null) - { - tempInvokeAsyncResult.SetAsCompleted(InvocationStateInfo.Reason); - } + tempInvokeAsyncResult?.SetAsCompleted(InvocationStateInfo.Reason); } - if (tempStopAsyncResult != null) - { - tempStopAsyncResult.SetAsCompleted(null); - } + tempStopAsyncResult?.SetAsCompleted(null); } catch (Exception) { @@ -4305,7 +4312,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) } finally { - // takes care exception occured with invokeAsyncResult + // takes care exception occurred with invokeAsyncResult if (isExceptionOccured && (tempStopAsyncResult != null)) { tempStopAsyncResult.Release(); @@ -4332,10 +4339,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) // This object can be disconnected even if "BeginStop" was called if it is a remote object // and robust connections is retrying a failed network connection. // In this case release the stop wait handle to prevent not responding. - if (tempStopAsyncResult != null) - { - tempStopAsyncResult.SetAsCompleted(null); - } + tempStopAsyncResult?.SetAsCompleted(null); // Only raise the Disconnected state changed event if the PowerShell state // actually transitions to Disconnected from some other state. This condition @@ -4356,7 +4360,7 @@ internal void SetStateChanged(PSInvocationStateInfo stateInfo) } finally { - // takes care exception occured with invokeAsyncResult + // takes care exception occurred with invokeAsyncResult if (isExceptionOccured && (tempStopAsyncResult != null)) { tempStopAsyncResult.Release(); @@ -4401,10 +4405,7 @@ internal void ClearRemotePowerShell() { lock (_syncObject) { - if (RemotePowerShell != null) - { - RemotePowerShell.Clear(); - } + RemotePowerShell?.Clear(); } } @@ -5118,11 +5119,8 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st // cannot complete with this object. if (isDisconnected) { - if (_invokeAsyncResult != null) - { - // Since object is stopped, allow result wait to end. - _invokeAsyncResult.SetAsCompleted(null); - } + // Since object is stopped, allow result wait to end. + _invokeAsyncResult?.SetAsCompleted(null); _stopAsyncResult.SetAsCompleted(null); @@ -5183,10 +5181,7 @@ private IAsyncResult CoreStop(bool isSyncCall, AsyncCallback callback, object st private void ReleaseDebugger() { LocalRunspace localRunspace = _runspace as LocalRunspace; - if (localRunspace != null) - { - localRunspace.ReleaseDebugger(); - } + localRunspace?.ReleaseDebugger(); } /// @@ -5258,7 +5253,7 @@ private bool ServerSupportsBatchInvocation() if (_runspace != null) { return _runspace.RunspaceStateInfo.State != RunspaceState.BeforeOpen && - _runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersionWin8RTM; + _runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersion_2_2; } RemoteRunspacePoolInternal remoteRunspacePoolInternal = null; @@ -5272,7 +5267,7 @@ private bool ServerSupportsBatchInvocation() } return remoteRunspacePoolInternal != null && - remoteRunspacePoolInternal.PSRemotingProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM; + remoteRunspacePoolInternal.PSRemotingProtocolVersion >= RemotingConstants.ProtocolVersion_2_2; } /// @@ -5287,10 +5282,7 @@ private void AddToRemoteRunspaceRunningList() else { RemoteRunspacePoolInternal remoteRunspacePoolInternal = GetRemoteRunspacePoolInternal(); - if (remoteRunspacePoolInternal != null) - { - remoteRunspacePoolInternal.PushRunningPowerShell(this); - } + remoteRunspacePoolInternal?.PushRunningPowerShell(this); } } @@ -5306,10 +5298,7 @@ private void RemoveFromRemoteRunspaceRunningList() else { RemoteRunspacePoolInternal remoteRunspacePoolInternal = GetRemoteRunspacePoolInternal(); - if (remoteRunspacePoolInternal != null) - { - remoteRunspacePoolInternal.PopRunningPowerShell(); - } + remoteRunspacePoolInternal?.PopRunningPowerShell(); } } @@ -5678,10 +5667,7 @@ internal void InternalClearSuppressExceptions() else { RunspacePool pool = _shell._rsConnection as RunspacePool; - if (pool != null) - { - pool.ReleaseRunspace(CurrentlyRunningPipeline.Runspace); - } + pool?.ReleaseRunspace(CurrentlyRunningPipeline.Runspace); } CurrentlyRunningPipeline.Dispose(); @@ -5852,10 +5838,7 @@ internal void SuspendIncomingData() throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) - { - RemotePowerShell.DataStructureHandler.TransportManager.SuspendQueue(true); - } + RemotePowerShell.DataStructureHandler?.TransportManager.SuspendQueue(true); } /// @@ -5868,10 +5851,7 @@ internal void ResumeIncomingData() throw new PSNotSupportedException(); } - if (RemotePowerShell.DataStructureHandler != null) - { - RemotePowerShell.DataStructureHandler.TransportManager.ResumeQueue(); - } + RemotePowerShell.DataStructureHandler?.TransportManager.ResumeQueue(); } /// @@ -6165,15 +6145,9 @@ internal class PowerShellStopper : IDisposable internal PowerShellStopper(ExecutionContext context, PowerShell powerShell) { - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); - if (powerShell == null) - { - throw new ArgumentNullException(nameof(powerShell)); - } + ArgumentNullException.ThrowIfNull(powerShell); _powerShell = powerShell; diff --git a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs index 3f4dcf40744..f86d2c00a54 100644 --- a/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs +++ b/src/System.Management.Automation/engine/hostifaces/PowerShellProcessInstance.cs @@ -11,6 +11,7 @@ namespace System.Management.Automation.Runspaces { /// + /// This class represents a PowerShell process that is used for an out-of-process remote Runspace. /// public sealed class PowerShellProcessInstance : IDisposable { @@ -30,8 +31,6 @@ public sealed class PowerShellProcessInstance : IDisposable #region Constructors - /// - /// static PowerShellProcessInstance() { #if UNIX @@ -145,10 +144,10 @@ public PowerShellProcessInstance(Version powerShellVersion, PSCredential credent /// /// Initializes a new instance of the class. Initializes the underlying dotnet process class. /// - /// - /// - /// - /// + /// Specifies the version of powershell. + /// Specifies a user account credentials. + /// Specifies a script that will be executed when the powershell process is initialized. + /// Specifies if the powershell process will be 32-bit. public PowerShellProcessInstance(Version powerShellVersion, PSCredential credential, ScriptBlock initializationScript, bool useWow64) : this(powerShellVersion, credential, initializationScript, useWow64, workingDirectory: null) { } @@ -178,49 +177,49 @@ public bool HasExited #endregion Constructors #region Dispose - /// - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } /// + /// Release all resources. /// - /// - private void Dispose(bool disposing) + public void Dispose() { - if (_isDisposed) return; - lock (_syncObject) + if (_isDisposed) { - if (_isDisposed) return; - _isDisposed = true; + return; } - if (disposing) + lock (_syncObject) { - try - { - if (Process != null && !Process.HasExited) - Process.Kill(); - } - catch (InvalidOperationException) - { - } - catch (Win32Exception) - { - } - catch (NotSupportedException) + if (_isDisposed) { + return; } + + _isDisposed = true; + } + + try + { + if (Process != null && !Process.HasExited) + Process.Kill(); + } + catch (InvalidOperationException) + { + } + catch (Win32Exception) + { + } + catch (NotSupportedException) + { } } #endregion Dispose #region Public Properties + /// + /// Gets the process object of the remote target. /// public Process Process { get; } diff --git a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs b/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs deleted file mode 100644 index 25c611eba0e..00000000000 --- a/src/System.Management.Automation/engine/hostifaces/RunspaceInvoke.cs +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - using System; - using System.Collections; - using System.Collections.ObjectModel; - using System.Management.Automation.Runspaces; - - /// - /// Defines a class which allows simple execution of commands from CLR languages. - /// - public class RunspaceInvoke : IDisposable - { - #region constructors - - /// - /// Runspace on which commands are invoked. - /// - private Runspace _runspace; - - /// - /// Create a RunspaceInvoke for invoking commands. This uses - /// a runspace with default PSSnapins. - /// - public RunspaceInvoke() - { - _runspace = RunspaceFactory.CreateRunspace(); - _runspace.Open(); - if (Runspace.DefaultRunspace == null) - { - Runspace.DefaultRunspace = _runspace; - } - } - - /// - /// Create RunspaceInvoke for invoking command in specified - /// runspace. - /// - /// - /// Runspace must be opened state - public RunspaceInvoke(Runspace runspace) - { - if (runspace == null) - { - throw PSTraceSource.NewArgumentNullException("runspace"); - } - - _runspace = runspace; - if (Runspace.DefaultRunspace == null) - { - Runspace.DefaultRunspace = _runspace; - } - } - - #endregion constructors - - #region invoke - - /// - /// Invoke the specified script. - /// - /// Msh script to invoke. - /// Output of invocation. - public Collection Invoke(string script) - { - return Invoke(script, null); - } - - /// - /// Invoke the specified script and passes specified input to the script. - /// - /// Msh script to invoke. - /// Input to script. - /// Output of invocation. - public Collection Invoke(string script, IEnumerable input) - { - if (_disposed == true) - { - throw PSTraceSource.NewObjectDisposedException("runspace"); - } - - if (script == null) - { - throw PSTraceSource.NewArgumentNullException("script"); - } - - Pipeline p = _runspace.CreatePipeline(script); - return p.Invoke(input); - } - - /// - /// Invoke the specified script and passes specified input to the script. - /// - /// Msh script to invoke. - /// Input to script. - /// This gets errors from script. - /// Output of invocation. - /// - /// is the non-terminating error stream - /// from the command. - /// In this release, the objects read from this PipelineReader - /// are PSObjects wrapping ErrorRecords. - /// - public Collection Invoke(string script, IEnumerable input, out IList errors) - { - if (_disposed == true) - { - throw PSTraceSource.NewObjectDisposedException("runspace"); - } - - if (script == null) - { - throw PSTraceSource.NewArgumentNullException("script"); - } - - Pipeline p = _runspace.CreatePipeline(script); - Collection output = p.Invoke(input); - // 2004/06/30-JonN was ReadAll() which was non-blocking - errors = p.Error.NonBlockingRead(); - return output; - } - - #endregion invoke - - #region IDisposable Members - - /// - /// Set to true when object is disposed. - /// - private bool _disposed; - - /// - /// Dispose underlying Runspace. - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// Protected dispose which can be overridden by derived classes. - /// - /// - protected virtual void Dispose(bool disposing) - { - if (_disposed == false) - { - if (disposing) - { - _runspace.Close(); - _runspace = null; - } - } - - _disposed = true; - } - - #endregion IDisposable Members - } -} - diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs index 5f814e0428b..e7cfb888a88 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePool.cs @@ -16,7 +16,6 @@ namespace System.Management.Automation.Runspaces /// Exception thrown when state of the runspace pool is different from /// expected state of runspace pool. /// - [Serializable] public class InvalidRunspacePoolStateException : SystemException { /// @@ -91,10 +90,11 @@ RunspacePoolState expectedState /// The that contains /// contextual information about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidRunspacePoolStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -1003,7 +1003,7 @@ public Collection CreateDisconnectedPowerShells() return _internalPool.CreateDisconnectedPowerShells(this); } - /// + /// /// Returns RunspacePool capabilities. /// /// RunspacePoolCapability. @@ -1199,13 +1199,11 @@ public void EndClose(IAsyncResult asyncResult) } /// - /// Dispose the current runspacepool. + /// Release all resources. /// public void Dispose() { - _internalPool.Dispose(true); - - GC.SuppressFinalize(this); + _internalPool.Dispose(); } /// diff --git a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs index aac3acfbdf8..1b20fc4c85f 100644 --- a/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/hostifaces/RunspacePoolInternal.cs @@ -16,7 +16,7 @@ namespace System.Management.Automation.Runspaces.Internal /// /// Class which supports pooling local powerShell runspaces. /// - internal class RunspacePoolInternal + internal class RunspacePoolInternal : IDisposable { #region Private data @@ -231,10 +231,7 @@ internal virtual PSPrimitiveDictionary GetApplicationPrivateData() { lock (this.syncObject) { - if (_applicationPrivateData == null) - { - _applicationPrivateData = new PSPrimitiveDictionary(); - } + _applicationPrivateData ??= new PSPrimitiveDictionary(); } } @@ -816,13 +813,23 @@ public void ReleaseRunspace(Runspace runspace) } } + /// + /// Release all resources. + /// + public void Dispose() + { + Dispose(true); + + GC.SuppressFinalize(this); + } + /// /// Dispose off the current runspace pool. /// /// /// true to release all the internal resources. /// - public virtual void Dispose(bool disposing) + protected virtual void Dispose(bool disposing) { if (!_isDisposed) { @@ -1306,7 +1313,7 @@ protected void DestroyRunspace(Runspace runspace) /// /// Cleans the pool closing the runspaces that are idle. /// This method is called as part of a timer callback. - /// This method will make sure atleast minPoolSz number + /// This method will make sure at least minPoolSz number /// of Runspaces are active. /// /// diff --git a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs index 2d74430a40a..f144ff7f506 100644 --- a/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs +++ b/src/System.Management.Automation/engine/hostifaces/pipelinebase.cs @@ -282,7 +282,7 @@ public override void StopAsync() /// /// Stop the running pipeline. /// - /// If true pipeline is stoped synchronously + /// If true pipeline is stopped synchronously /// else asynchronously. private void CoreStop(bool syncCall) { @@ -298,7 +298,7 @@ private void CoreStop(bool syncCall) break; // If pipeline execution has failed or completed or - // stoped, return silently. + // stopped, return silently. case PipelineState.Stopped: case PipelineState.Completed: case PipelineState.Failed: @@ -331,7 +331,7 @@ private void CoreStop(bool syncCall) // Raise the event outside the lock RaisePipelineStateEvents(); - // A pipeline can be stoped before it is started. See NotStarted + // A pipeline can be stopped before it is started. See NotStarted // case in above switch statement. This is done to allow stoping a pipeline // in another thread before it has been started. lock (SyncRoot) @@ -515,7 +515,7 @@ private void CoreInvoke(IEnumerable input, bool syncCall) SyncInvokeCall = syncCall; // Create event which will be signalled when pipeline execution - // is completed/failed/stoped. + // is completed/failed/stopped. // Note:Runspace.Close waits for all the running pipeline // to finish. This Event must be created before pipeline is // added to list of running pipelines. This avoids the race condition @@ -760,7 +760,7 @@ protected bool IsPipelineFinished() } /// - /// This is queue of all the state change event which have occured for + /// This is queue of all the state change event which have occurred for /// this pipeline. RaisePipelineStateEvents raises event for each /// item in this queue. We don't raise the event with in SetPipelineState /// because often SetPipelineState is called with in a lock. @@ -768,7 +768,7 @@ protected bool IsPipelineFinished() /// private Queue _executionEventQueue = new Queue(); - private class ExecutionEventQueueItem + private sealed class ExecutionEventQueueItem { public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability) { @@ -891,7 +891,7 @@ protected void RaisePipelineStateEvents() /// /// ManualResetEvent which is signaled when pipeline execution is - /// completed/failed/stoped. + /// completed/failed/stopped. /// internal ManualResetEvent PipelineFinishedEvent { get; private set; } diff --git a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs index 08af974416c..1bae16783a9 100644 --- a/src/System.Management.Automation/engine/interpreter/BranchLabel.cs +++ b/src/System.Management.Automation/engine/interpreter/BranchLabel.cs @@ -110,10 +110,7 @@ internal void AddBranch(InstructionList instructions, int branchIndex) if (_targetIndex == UnknownIndex) { - if (_forwardBranchFixups == null) - { - _forwardBranchFixups = new List(); - } + _forwardBranchFixups ??= new List(); _forwardBranchFixups.Add(branchIndex); } diff --git a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs index 88ff4bc1357..f7173c745ff 100644 --- a/src/System.Management.Automation/engine/interpreter/CallInstruction.cs +++ b/src/System.Management.Automation/engine/interpreter/CallInstruction.cs @@ -222,7 +222,11 @@ private static bool IndexIsNotReturnType(int index, MethodInfo target, Parameter private static CallInstruction SlowCreate(MethodInfo info, ParameterInfo[] pis) { List types = new List(); - if (!info.IsStatic) types.Add(info.DeclaringType); + if (!info.IsStatic) + { + types.Add(info.DeclaringType); + } + foreach (ParameterInfo pi in pis) { types.Add(pi.ParameterType); diff --git a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs index 0fddd203346..5d994d934c5 100644 --- a/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/ControlFlowInstructions.cs @@ -157,10 +157,7 @@ public override Instruction[] Cache { get { - if (s_caches == null) - { - s_caches = new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; - } + s_caches ??= new Instruction[2][][] { new Instruction[2][], new Instruction[2][] }; return s_caches[ConsumedStack][ProducedStack] ?? (s_caches[ConsumedStack][ProducedStack] = new Instruction[CacheSize]); } @@ -509,7 +506,7 @@ public override int Run(InterpretedFrame frame) frame.PopPendingContinuation(); // If _pendingContinuation == -1 then we were getting into the finally block because an exception was thrown - // In this case we just return 1, and the the real instruction index will be calculated by GotoHandler later + // In this case we just return 1, and the real instruction index will be calculated by GotoHandler later if (!frame.IsJumpHappened()) { return 1; } // jump to goto target or to the next finally: return frame.YieldToPendingContinuation(); diff --git a/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs b/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs index ad10413f9d0..abe64c471af 100644 --- a/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs +++ b/src/System.Management.Automation/engine/interpreter/DynamicInstructions.Generated.cs @@ -22,7 +22,11 @@ namespace System.Management.Automation.Interpreter { internal partial class DynamicInstructionN { internal static Type GetDynamicInstructionType(Type delegateType) { Type[] argTypes = delegateType.GetGenericArguments(); - if (argTypes.Length == 0) return null; + if (argTypes.Length == 0) + { + return null; + } + Type genericType; Type[] newArgTypes = argTypes.Skip(1).ToArray(); switch (newArgTypes.Length) { diff --git a/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs b/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs index 49fbfdb0f8e..9f24d14fa14 100644 --- a/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs +++ b/src/System.Management.Automation/engine/interpreter/ILightCallSiteBinder.cs @@ -13,6 +13,7 @@ * * ***************************************************************************/ +#nullable enable #if !CLR2 #else using Microsoft.Scripting.Ast; diff --git a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs index 4a707201eb6..839ccd6f905 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionFactory.cs @@ -119,10 +119,7 @@ protected internal override Instruction NewArrayInit(int elementCount) { if (elementCount < MaxArrayInitElementCountCache) { - if (_newArrayInit == null) - { - _newArrayInit = new Instruction[MaxArrayInitElementCountCache]; - } + _newArrayInit ??= new Instruction[MaxArrayInitElementCountCache]; return _newArrayInit[elementCount] ?? (_newArrayInit[elementCount] = new NewArrayInitInstruction(elementCount)); } diff --git a/src/System.Management.Automation/engine/interpreter/InstructionList.cs b/src/System.Management.Automation/engine/interpreter/InstructionList.cs index 3c810d186e0..93946bfd2c3 100644 --- a/src/System.Management.Automation/engine/interpreter/InstructionList.cs +++ b/src/System.Management.Automation/engine/interpreter/InstructionList.cs @@ -95,7 +95,9 @@ internal sealed class InstructionList private List _labels; // list of (instruction index, cookie) sorted by instruction index: +#pragma warning disable IDE0044 // Add readonly modifier private List> _debugCookies = null; +#pragma warning restore IDE0044 // Variable is assigned when DEBUG is defined. #region Debug View @@ -231,10 +233,7 @@ private void UpdateStackDepth(Instruction instruction) public void SetDebugCookie(object cookie) { #if DEBUG - if (_debugCookies == null) - { - _debugCookies = new List>(); - } + _debugCookies ??= new List>(); Debug.Assert(Count > 0); _debugCookies.Add(new KeyValuePair(Count - 1, cookie)); @@ -273,7 +272,7 @@ internal Instruction GetInstruction(int index) static InstructionList() { AppDomain.CurrentDomain.ProcessExit += new EventHandler((_, __) => { PerfTrack.DumpHistogram(_executedInstructions); - Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, (sum, value) => sum + value)); + Console.WriteLine("-- Total executed: {0}", _executedInstructions.Values.Aggregate(0, static (sum, value) => sum + value)); Console.WriteLine("-----"); var referenced = new Dictionary(); @@ -370,10 +369,7 @@ public void EmitLoad(object value, Type type) int i = (int)value; if (i >= PushIntMinCachedValue && i <= PushIntMaxCachedValue) { - if (s_ints == null) - { - s_ints = new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; - } + s_ints ??= new Instruction[PushIntMaxCachedValue - PushIntMinCachedValue + 1]; i -= PushIntMinCachedValue; Emit(s_ints[i] ?? (s_ints[i] = new LoadObjectInstruction(value))); @@ -385,10 +381,7 @@ public void EmitLoad(object value, Type type) if (_objects == null) { _objects = new List(); - if (s_loadObjectCached == null) - { - s_loadObjectCached = new Instruction[CachedObjectCount]; - } + s_loadObjectCached ??= new Instruction[CachedObjectCount]; } if (_objects.Count < s_loadObjectCached.Length) @@ -449,10 +442,7 @@ internal void SwitchToBoxed(int index, int instructionIndex) public void EmitLoadLocal(int index) { - if (s_loadLocal == null) - { - s_loadLocal = new Instruction[LocalInstrCacheSize]; - } + s_loadLocal ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocal.Length) { @@ -471,10 +461,7 @@ public void EmitLoadLocalBoxed(int index) internal static Instruction LoadLocalBoxed(int index) { - if (s_loadLocalBoxed == null) - { - s_loadLocalBoxed = new Instruction[LocalInstrCacheSize]; - } + s_loadLocalBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocalBoxed.Length) { @@ -488,10 +475,7 @@ internal static Instruction LoadLocalBoxed(int index) public void EmitLoadLocalFromClosure(int index) { - if (s_loadLocalFromClosure == null) - { - s_loadLocalFromClosure = new Instruction[LocalInstrCacheSize]; - } + s_loadLocalFromClosure ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocalFromClosure.Length) { @@ -505,10 +489,7 @@ public void EmitLoadLocalFromClosure(int index) public void EmitLoadLocalFromClosureBoxed(int index) { - if (s_loadLocalFromClosureBoxed == null) - { - s_loadLocalFromClosureBoxed = new Instruction[LocalInstrCacheSize]; - } + s_loadLocalFromClosureBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_loadLocalFromClosureBoxed.Length) { @@ -522,10 +503,7 @@ public void EmitLoadLocalFromClosureBoxed(int index) public void EmitAssignLocal(int index) { - if (s_assignLocal == null) - { - s_assignLocal = new Instruction[LocalInstrCacheSize]; - } + s_assignLocal ??= new Instruction[LocalInstrCacheSize]; if (index < s_assignLocal.Length) { @@ -539,10 +517,7 @@ public void EmitAssignLocal(int index) public void EmitStoreLocal(int index) { - if (s_storeLocal == null) - { - s_storeLocal = new Instruction[LocalInstrCacheSize]; - } + s_storeLocal ??= new Instruction[LocalInstrCacheSize]; if (index < s_storeLocal.Length) { @@ -561,10 +536,7 @@ public void EmitAssignLocalBoxed(int index) internal static Instruction AssignLocalBoxed(int index) { - if (s_assignLocalBoxed == null) - { - s_assignLocalBoxed = new Instruction[LocalInstrCacheSize]; - } + s_assignLocalBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_assignLocalBoxed.Length) { @@ -583,10 +555,7 @@ public void EmitStoreLocalBoxed(int index) internal static Instruction StoreLocalBoxed(int index) { - if (s_storeLocalBoxed == null) - { - s_storeLocalBoxed = new Instruction[LocalInstrCacheSize]; - } + s_storeLocalBoxed ??= new Instruction[LocalInstrCacheSize]; if (index < s_storeLocalBoxed.Length) { @@ -600,10 +569,7 @@ internal static Instruction StoreLocalBoxed(int index) public void EmitAssignLocalToClosure(int index) { - if (s_assignLocalToClosure == null) - { - s_assignLocalToClosure = new Instruction[LocalInstrCacheSize]; - } + s_assignLocalToClosure ??= new Instruction[LocalInstrCacheSize]; if (index < s_assignLocalToClosure.Length) { @@ -645,10 +611,7 @@ internal void EmitInitializeParameter(int index) internal static Instruction Parameter(int index) { - if (s_parameter == null) - { - s_parameter = new Instruction[LocalInstrCacheSize]; - } + s_parameter ??= new Instruction[LocalInstrCacheSize]; if (index < s_parameter.Length) { @@ -660,10 +623,7 @@ internal static Instruction Parameter(int index) internal static Instruction ParameterBox(int index) { - if (s_parameterBox == null) - { - s_parameterBox = new Instruction[LocalInstrCacheSize]; - } + s_parameterBox ??= new Instruction[LocalInstrCacheSize]; if (index < s_parameterBox.Length) { @@ -675,10 +635,7 @@ internal static Instruction ParameterBox(int index) internal static Instruction InitReference(int index) { - if (s_initReference == null) - { - s_initReference = new Instruction[LocalInstrCacheSize]; - } + s_initReference ??= new Instruction[LocalInstrCacheSize]; if (index < s_initReference.Length) { @@ -690,10 +647,7 @@ internal static Instruction InitReference(int index) internal static Instruction InitImmutableRefBox(int index) { - if (s_initImmutableRefBox == null) - { - s_initImmutableRefBox = new Instruction[LocalInstrCacheSize]; - } + s_initImmutableRefBox ??= new Instruction[LocalInstrCacheSize]; if (index < s_initImmutableRefBox.Length) { @@ -1125,10 +1079,7 @@ private RuntimeLabel[] BuildRuntimeLabels() public BranchLabel MakeLabel() { - if (_labels == null) - { - _labels = new List(); - } + _labels ??= new List(); var label = new BranchLabel(); _labels.Add(label); diff --git a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs index 4b084ba72a8..977fee85803 100644 --- a/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs +++ b/src/System.Management.Automation/engine/interpreter/InterpretedFrame.cs @@ -27,23 +27,19 @@ namespace System.Management.Automation.Interpreter { internal sealed class InterpretedFrame { - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly ThreadLocal CurrentFrame = new ThreadLocal(); internal readonly Interpreter Interpreter; internal InterpretedFrame _parent; - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] private readonly int[] _continuations; private int _continuationIndex; private int _pendingContinuation; private object _pendingValue; - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly object[] Data; - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2105:ArrayFieldsShouldNotBeReadOnly")] public readonly StrongBox[] Closure; public int StackIndex; diff --git a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs index a8518099824..8d501987c3d 100644 --- a/src/System.Management.Automation/engine/interpreter/LabelInfo.cs +++ b/src/System.Management.Automation/engine/interpreter/LabelInfo.cs @@ -80,7 +80,7 @@ internal void Define(LabelScopeInfo block) { if (j.ContainsTarget(_node)) { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Label target already defined: {0}", _node.Name)); + throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture, $"Label target already defined: {_node.Name}")); } } @@ -132,12 +132,12 @@ private void ValidateJump(LabelScopeInfo reference) if (HasMultipleDefinitions) { - throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, "Ambiguous jump {0}", _node.Name)); + throw new InvalidOperationException(string.Create(CultureInfo.InvariantCulture, $"Ambiguous jump {_node.Name}")); } // We didn't find an outward jump. Look for a jump across blocks LabelScopeInfo def = FirstDefinition(); - LabelScopeInfo common = CommonNode(def, reference, b => b.Parent); + LabelScopeInfo common = CommonNode(def, reference, static b => b.Parent); // Validate that we aren't jumping across a finally for (LabelScopeInfo j = reference; j != common; j = j.Parent) @@ -176,10 +176,7 @@ internal void ValidateFinish() private void EnsureLabel(LightCompiler compiler) { - if (_label == null) - { - _label = compiler.Instructions.MakeLabel(); - } + _label ??= compiler.Instructions.MakeLabel(); } private bool DefinedIn(LabelScopeInfo scope) @@ -359,10 +356,7 @@ internal void AddLabelInfo(LabelTarget target, LabelInfo info) { Debug.Assert(CanJumpInto); - if (_labels == null) - { - _labels = new HybridReferenceDictionary(); - } + _labels ??= new HybridReferenceDictionary(); _labels[target] = info; } diff --git a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs index 85f97ee7d40..c117fbff33a 100644 --- a/src/System.Management.Automation/engine/interpreter/LightCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LightCompiler.cs @@ -68,7 +68,10 @@ public bool Matches(Type exceptionType) public bool IsBetterThan(ExceptionHandler other) { - if (other == null) return true; + if (other == null) + { + return true; + } Debug.Assert(StartIndex == other.StartIndex && EndIndex == other.EndIndex, "we only need to compare handlers for the same try block"); return HandlerStartIndex < other.HandlerStartIndex; @@ -92,11 +95,14 @@ internal bool IsInsideFinallyBlock(int index) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0} [{1}-{2}] [{3}->{4}]", - (IsFault ? "fault" : "catch(" + ExceptionType.Name + ")"), - StartIndex, EndIndex, - HandlerStartIndex, HandlerEndIndex - ); + return string.Format( + CultureInfo.InvariantCulture, + "{0} [{1}-{2}] [{3}->{4}]", + IsFault ? "fault" : "catch(" + ExceptionType.Name + ")", + StartIndex, + EndIndex, + HandlerStartIndex, + HandlerEndIndex); } } @@ -181,7 +187,6 @@ internal sealed class RethrowException : SystemException { } - [Serializable] internal class DebugInfo { // TODO: readonly @@ -192,7 +197,7 @@ internal class DebugInfo public bool IsClear; private static readonly DebugInfoComparer s_debugComparer = new DebugInfoComparer(); - private class DebugInfoComparer : IComparer + private sealed class DebugInfoComparer : IComparer { // We allow comparison between int and DebugInfo here int IComparer.Compare(DebugInfo d1, DebugInfo d2) @@ -242,7 +247,6 @@ public override string ToString() // TODO: [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1815:OverrideEqualsAndOperatorEqualsOnValueTypes")] - [Serializable] internal readonly struct InterpretedFrameInfo { public readonly string MethodName; @@ -1063,7 +1067,7 @@ private void CompileSwitchExpression(Expression expr) } // Test values must be constant - if (!node.Cases.All(c => c.TestValues.All(t => t is ConstantExpression))) + if (!node.Cases.All(static c => c.TestValues.All(t => t is ConstantExpression))) { throw new NotImplementedException(); } @@ -1132,10 +1136,7 @@ private void CompileLabelExpression(Expression expr) Debug.Assert(label != null); } - if (label == null) - { - label = DefineLabel(node.Target); - } + label ??= DefineLabel(node.Target); if (node.DefaultValue != null) { @@ -1297,7 +1298,7 @@ private bool TryPushLabelBlock(Expression node) private void DefineBlockLabels(Expression node) { - if (!(node is BlockExpression block)) + if (node is not BlockExpression block) { return; } @@ -1356,7 +1357,7 @@ private void CompileThrowUnaryExpression(Expression expr, bool asVoid) } // TODO: remove (replace by true fault support) - private bool EndsWithRethrow(Expression expr) + private static bool EndsWithRethrow(Expression expr) { if (expr.NodeType == ExpressionType.Throw) { @@ -1573,7 +1574,7 @@ private void CompileMethodCallExpression(Expression expr) // also could be a mutable value type, Delegate.CreateDelegate and MethodInfo.Invoke both can't handle this, we // need to generate code. var declaringType = node.Method.DeclaringType; - if (!parameters.TrueForAll(p => !p.ParameterType.IsByRef) || + if (!parameters.TrueForAll(static p => !p.ParameterType.IsByRef) || (!node.Method.IsStatic && declaringType.IsValueType && !declaringType.IsPrimitive)) { _forceCompile = true; @@ -1600,7 +1601,7 @@ private void CompileNewExpression(Expression expr) if (node.Constructor != null) { var parameters = node.Constructor.GetParameters(); - if (!parameters.TrueForAll(p => !p.ParameterType.IsByRef)) + if (!parameters.TrueForAll(static p => !p.ParameterType.IsByRef)) { _forceCompile = true; } diff --git a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs index 0df528b94bb..6f9497db987 100644 --- a/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs +++ b/src/System.Management.Automation/engine/interpreter/LightDelegateCreator.cs @@ -196,7 +196,7 @@ private static Type GetFuncOrAction(LambdaExpression lambda) // lambda.Parameters[0].IsByRef && lambda.Parameters[1].IsByRef) { // return typeof(ActionRef<,>).MakeGenericType(lambda.Parameters.Map(p => p.Type)); // } else { - Type[] types = lambda.Parameters.Map(p => p.IsByRef ? p.Type.MakeByRefType() : p.Type); + Type[] types = lambda.Parameters.Map(static p => p.IsByRef ? p.Type.MakeByRefType() : p.Type); if (isVoid) { if (Expression.TryGetActionType(types, out delegateType)) diff --git a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs index d52f1fc6840..0c1f6416741 100644 --- a/src/System.Management.Automation/engine/interpreter/LocalVariables.cs +++ b/src/System.Management.Automation/engine/interpreter/LocalVariables.cs @@ -163,10 +163,7 @@ public LocalDefinition DefineLocal(ParameterExpression variable, int start) if (_variables.TryGetValue(variable, out existing)) { newScope = new VariableScope(result, start, existing); - if (existing.ChildScopes == null) - { - existing.ChildScopes = new List(); - } + existing.ChildScopes ??= new List(); existing.ChildScopes.Add(newScope); } @@ -296,10 +293,7 @@ internal Dictionary ClosureVariables internal LocalVariable AddClosureVariable(ParameterExpression variable) { - if (_closureVariables == null) - { - _closureVariables = new Dictionary(); - } + _closureVariables ??= new Dictionary(); LocalVariable result = new LocalVariable(_closureVariables.Count, true, false); _closureVariables.Add(variable, result); diff --git a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs index 6ff0e36f5c3..78c5534a132 100644 --- a/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs +++ b/src/System.Management.Automation/engine/interpreter/LoopCompiler.cs @@ -374,10 +374,7 @@ private Expression VisitVariable(ParameterExpression node, ExpressionAccess acce private ParameterExpression AddTemp(ParameterExpression variable) { - if (_temps == null) - { - _temps = new List(); - } + _temps ??= new List(); _temps.Add(variable); return variable; diff --git a/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs b/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs index 926f558a72b..5592af6f526 100644 --- a/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs +++ b/src/System.Management.Automation/engine/interpreter/PowerShellInstructions.cs @@ -15,7 +15,7 @@ namespace System.Management.Automation.Interpreter { - internal class UpdatePositionInstruction : Instruction + internal sealed class UpdatePositionInstruction : Instruction { private readonly int _sequencePoint; private readonly bool _checkBreakpoints; diff --git a/src/System.Management.Automation/engine/interpreter/Utilities.cs b/src/System.Management.Automation/engine/interpreter/Utilities.cs index be7bb1935c7..0eef4728e46 100644 --- a/src/System.Management.Automation/engine/interpreter/Utilities.cs +++ b/src/System.Management.Automation/engine/interpreter/Utilities.cs @@ -147,7 +147,7 @@ internal static Type MakeDelegate(Type[] types) // Can only used predefined delegates if we have no byref types and // the arity is small enough to fit in Func<...> or Action<...> - if (types.Length > MaximumArity || types.Any(t => t.IsByRef)) + if (types.Length > MaximumArity || types.Any(static t => t.IsByRef)) { throw Assert.Unreachable; // return MakeCustomDelegate(types); @@ -1078,7 +1078,10 @@ internal static bool TrueForAll(this IEnumerable collection, Predicate foreach (T item in collection) { - if (!predicate(item)) return false; + if (!predicate(item)) + { + return false; + } } return true; diff --git a/src/System.Management.Automation/engine/lang/interface/PSToken.cs b/src/System.Management.Automation/engine/lang/interface/PSToken.cs index 048de2facac..306a64a0b61 100644 --- a/src/System.Management.Automation/engine/lang/interface/PSToken.cs +++ b/src/System.Management.Automation/engine/lang/interface/PSToken.cs @@ -370,223 +370,275 @@ public enum PSTokenType /// /// Unknown token. /// - /// - /// Unknown, /// + /// /// Command. - /// - /// + /// + /// /// For example, 'get-process' in /// - /// get-process -name foo - /// + /// get-process -name foo + /// + /// Command, /// + /// /// Command Parameter. - /// - /// + /// + /// /// For example, '-name' in /// - /// get-process -name foo - /// + /// get-process -name foo + /// + /// CommandParameter, /// + /// /// Command Argument. - /// - /// + /// + /// /// For example, 'foo' in /// - /// get-process -name foo - /// + /// get-process -name foo + /// + /// CommandArgument, /// + /// /// Number. - /// - /// + /// + /// /// For example, 12 in /// - /// $a=12 - /// + /// $a=12 + /// + /// Number, /// + /// /// String. - /// - /// + /// + /// /// For example, "12" in /// - /// $a="12" - /// + /// $a="12" + /// + /// String, /// + /// /// Variable. - /// + /// + /// /// /// For example, $a in /// - /// $a="12" - /// + /// $a="12" + /// + /// Variable, /// + /// /// Property name or method name. - /// - /// + /// + /// /// For example, Name in /// - /// $a.Name - /// + /// $a.Name + /// + /// Member, /// + /// /// Loop label. - /// - /// + /// + /// /// For example, :loop in /// + /// /// :loop /// foreach($a in $b) /// { /// $a /// } - /// + /// + /// LoopLabel, /// + /// /// Attributes. - /// - /// + /// + /// /// For example, Mandatory in /// - /// param([Mandatory] $a) - /// + /// param([Mandatory] $a) + /// + /// Attribute, /// + /// /// Types. - /// - /// + /// + /// /// For example, [string] in /// - /// $a = [string] 12 - /// + /// $a = [string] 12 + /// + /// Type, /// + /// /// Operators. - /// - /// + /// + /// /// For example, + in /// - /// $a = 1 + 2 - /// + /// $a = 1 + 2 + /// + /// Operator, /// + /// /// Group Starter. - /// - /// + /// + /// /// For example, { in /// + /// /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// GroupStart, /// + /// /// Group Ender. - /// - /// + /// + /// /// For example, } in /// + /// /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// GroupEnd, /// + /// /// Keyword. - /// - /// + /// + /// /// For example, if in /// + /// /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// Keyword, /// + /// /// Comment. - /// - /// + /// + /// /// For example, #here in /// + /// /// #here /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// Comment, /// + /// /// Statement separator. This is ';' - /// - /// + /// + /// /// For example, ; in /// + /// /// #here /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// StatementSeparator, /// + /// /// New line. This is '\n' - /// - /// + /// + /// /// For example, \n in /// + /// /// #here /// if ($a -gt 4) /// { /// $a++; /// } - /// + /// + /// + /// NewLine, /// + /// /// Line continuation. - /// - /// + /// + /// /// For example, ` in /// + /// /// get-command -name ` /// foo - /// + /// + /// + /// LineContinuation, /// + /// /// Position token. - /// - /// - /// Position token are bogus tokens generated for identifying a location + /// + /// + /// Position tokens are bogus tokens generated for identifying a location /// in the script. - /// + /// + /// Position } } diff --git a/src/System.Management.Automation/engine/lang/parserutils.cs b/src/System.Management.Automation/engine/lang/parserutils.cs index 52c64400ccd..184c82c6815 100644 --- a/src/System.Management.Automation/engine/lang/parserutils.cs +++ b/src/System.Management.Automation/engine/lang/parserutils.cs @@ -28,11 +28,6 @@ namespace System.Management.Automation public abstract class FlowControlException : SystemException { internal FlowControlException() { } - - internal FlowControlException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } /// @@ -45,11 +40,6 @@ internal LoopFlowException(string label) this.Label = label ?? string.Empty; } - internal LoopFlowException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - internal LoopFlowException() { } /// @@ -95,11 +85,6 @@ internal BreakException(string label, Exception innerException) : base(label) { } - - private BreakException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } /// @@ -121,11 +106,6 @@ internal ContinueException(string label, Exception innerException) : base(label) { } - - private ContinueException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } internal class ReturnException : FlowControlException @@ -156,12 +136,6 @@ internal ExitException(object argument) [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This exception should only be thrown from SMA.dll")] internal ExitException() { } - - [SuppressMessage("Microsoft.Design", "CA1032:ImplementStandardExceptionConstructors", Justification = "This exception should only be thrown from SMA.dll")] - private ExitException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } /// @@ -251,7 +225,7 @@ public enum SplitOptions internal delegate object PowerShellBinaryOperator(ExecutionContext context, IScriptExtent errorPosition, object lval, object rval); /// - /// A static class holding various operations specific to the msh interpreter such as + /// A static class holding various operations specific to the PowerShell interpreter such as /// various math operations, ToString() and a routine to extract the base object from an /// PSObject in a canonical fashion. /// @@ -969,15 +943,7 @@ internal static object ReplaceOperator(ExecutionContext context, IScriptExtent e IEnumerator list = LanguagePrimitives.GetEnumerator(lval); if (list == null) { - string lvalString; - if (ExperimentalFeature.IsEnabled("PSCultureInvariantReplaceOperator")) - { - lvalString = PSObject.ToStringParser(context, lval) ?? string.Empty; - } - else - { - lvalString = lval?.ToString() ?? string.Empty; - } + string lvalString = PSObject.ToStringParser(context, lval) ?? string.Empty; return replacer.Replace(lvalString); } @@ -1500,7 +1466,7 @@ internal static string GetTypeFullName(object obj) return string.Empty; } - if (!(obj is PSObject mshObj)) + if (obj is not PSObject mshObj) { return obj.GetType().FullName; } @@ -1518,7 +1484,7 @@ internal static string GetTypeFullName(object obj) /// methods and ScriptBlock notes. Native methods currently take precedence over notes... /// /// The position to use for error reporting. - /// The object to call the method on. It shouldn't be an msh object. + /// The object to call the method on. It shouldn't be a PSObject. /// The name of the method to call. /// Invocation constraints. /// The arguments to pass to the method. @@ -1604,7 +1570,7 @@ internal static object CallMethod( // not really a method call. if (valueToSet != AutomationNull.Value) { - if (!(targetMethod is PSParameterizedProperty propertyToSet)) + if (targetMethod is not PSParameterizedProperty propertyToSet) { throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), errorPosition, "ParameterizedPropertyAssignmentFailed", ParserStrings.ParameterizedPropertyAssignmentFailed, GetTypeFullName(target), methodName); @@ -1981,6 +1947,22 @@ internal static void UpdateExceptionErrorRecordPosition(Exception exception, ISc } } } + + internal static void UpdateExceptionErrorRecordHistoryId(RuntimeException exception, ExecutionContext context) + { + InvocationInfo invInfo = exception.ErrorRecord.InvocationInfo; + if (invInfo is not { HistoryId: -1 }) + { + return; + } + + if (context?.CurrentCommandProcessor is null) + { + return; + } + + invInfo.HistoryId = context.CurrentCommandProcessor.Command.MyInvocation.HistoryId; + } } #endregion InterpreterError diff --git a/src/System.Management.Automation/engine/lang/scriptblock.cs b/src/System.Management.Automation/engine/lang/scriptblock.cs index 765809be306..06fa66d0f7c 100644 --- a/src/System.Management.Automation/engine/lang/scriptblock.cs +++ b/src/System.Management.Automation/engine/lang/scriptblock.cs @@ -104,7 +104,7 @@ internal static ScriptBlock Create(ExecutionContext context, string script) /// /// The string to compile. public static ScriptBlock Create(string script) => Create( - parser: new Language.Parser(), + parser: new Parser(), fileName: null, fileContents: script); @@ -545,7 +545,7 @@ internal T InvokeAsMemberFunctionT(object instance, object[] args) // is a pipeline that emits nothing then result.Count will // be zero so we catch that and "convert" it to null. Note that // the return statement is still required in the method, it - // just recieves nothing from it's argument. + // just receives nothing from it's argument. if (result.Count == 0) { return default(T); @@ -778,7 +778,7 @@ internal Delegate CreateDelegate(Type delegateType) CachedReflectionInfo.ScriptBlock_InvokeAsDelegateHelper, dollarUnderExpr, dollarThisExpr, - Expression.NewArrayInit(typeof(object), parameterExprs.Select(p => p.Cast(typeof(object))))); + Expression.NewArrayInit(typeof(object), parameterExprs.Select(static p => p.Cast(typeof(object))))); if (returnsSomething) { call = DynamicExpression.Dynamic( @@ -1035,10 +1035,7 @@ internal void InvokeWithPipe( processInCurrentThread: true, waitForCompletionInCurrentThread: true); - if (scriptBlockInvocationEventArgs.Exception != null) - { - scriptBlockInvocationEventArgs.Exception.Throw(); - } + scriptBlockInvocationEventArgs.Exception?.Throw(); } } @@ -1099,15 +1096,9 @@ public sealed class SteppablePipeline : IDisposable { internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) { - if (pipeline == null) - { - throw new ArgumentNullException(nameof(pipeline)); - } + ArgumentNullException.ThrowIfNull(pipeline); - if (context == null) - { - throw new ArgumentNullException(nameof(context)); - } + ArgumentNullException.ThrowIfNull(context); _pipeline = pipeline; _context = context; @@ -1131,10 +1122,7 @@ internal SteppablePipeline(ExecutionContext context, PipelineProcessor pipeline) /// Context used to figure out how to route the output and errors. public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) { - if (contextToRedirectTo == null) - { - throw new ArgumentNullException(nameof(contextToRedirectTo)); - } + ArgumentNullException.ThrowIfNull(contextToRedirectTo); ExecutionContext executionContext = contextToRedirectTo.SessionState.Internal.ExecutionContext; CommandProcessorBase commandProcessor = executionContext.CurrentCommandProcessor; @@ -1150,7 +1138,7 @@ public void Begin(bool expectInput, EngineIntrinsics contextToRedirectTo) /// The command you're calling this from (i.e. instance of PSCmdlet or value of $PSCmdlet variable). public void Begin(InternalCommand command) { - if (command == null || command.MyInvocation == null) + if (command is null || command.MyInvocation is null) { throw new ArgumentNullException(nameof(command)); } @@ -1280,7 +1268,44 @@ public Array End() { // then pop this pipeline and dispose it... _context.PopPipelineProcessor(true); - _pipeline.Dispose(); + Dispose(); + } + } + + /// + /// Clean resources for script commands of this steppable pipeline. + /// + /// + /// + /// The way we handle 'Clean' blocks in a steppable pipeline makes sure that: + /// 1. The 'Clean' blocks get to run if any exception is thrown from 'Begin/Process/End'. + /// 2. The 'Clean' blocks get to run if 'End' finished successfully. + /// + /// However, this is not enough for a steppable pipeline, because the function, where the steppable + /// pipeline gets used, may fail (think about a proxy function). And that may lead to the situation + /// where "no exception was thrown from the steppable pipeline" but "the steppable pipeline didn't + /// run to the end". In that case, 'Clean' won't run unless it's triggered explicitly on the steppable + /// pipeline. This method allows a user to do that from the 'Clean' block of the proxy function. + /// + public void Clean() + { + if (_pipeline.Commands is null) + { + // The pipeline commands have been disposed. In this case, 'Clean' + // should have already been called on the pipeline processor. + return; + } + + try + { + _context.PushPipelineProcessor(_pipeline); + _pipeline.DoCleanup(); + } + finally + { + // then pop this pipeline and dispose it... + _context.PopPipelineProcessor(true); + Dispose(); } } @@ -1293,23 +1318,13 @@ public Array End() /// When this object is disposed, the contained pipeline should also be disposed. /// public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - private void Dispose(bool disposing) { if (_disposed) { return; } - if (disposing) - { - _pipeline.Dispose(); - } - + _pipeline.Dispose(); _disposed = true; } @@ -1320,7 +1335,6 @@ private void Dispose(bool disposing) /// Defines the exception thrown when conversion from ScriptBlock to PowerShell is forbidden /// (i.e. when the script block has undeclared variables or more than one statement) /// - [Serializable] public class ScriptBlockToPowerShellNotSupportedException : RuntimeException { #region ctor @@ -1347,7 +1361,7 @@ public ScriptBlockToPowerShellNotSupportedException(string message) /// Initializes a new instance of ScriptBlockToPowerShellNotSupportedException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ScriptBlockToPowerShellNotSupportedException(string message, Exception innerException) : base(message, innerException) { @@ -1374,9 +1388,10 @@ internal ScriptBlockToPowerShellNotSupportedException( /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptBlockToPowerShellNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/engine/parser/AstVisitor.cs b/src/System.Management.Automation/engine/parser/AstVisitor.cs index 5c09ee78dc6..03b234cf41f 100644 --- a/src/System.Management.Automation/engine/parser/AstVisitor.cs +++ b/src/System.Management.Automation/engine/parser/AstVisitor.cs @@ -10,195 +10,197 @@ namespace System.Management.Automation.Language { /// /// +#nullable enable public interface ICustomAstVisitor { /// - object DefaultVisit(Ast ast) => null; + object? DefaultVisit(Ast ast) => null; /// - object VisitErrorStatement(ErrorStatementAst errorStatementAst) => DefaultVisit(errorStatementAst); + object? VisitErrorStatement(ErrorStatementAst errorStatementAst) => DefaultVisit(errorStatementAst); /// - object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) => DefaultVisit(errorExpressionAst); + object? VisitErrorExpression(ErrorExpressionAst errorExpressionAst) => DefaultVisit(errorExpressionAst); #region Script Blocks /// - object VisitScriptBlock(ScriptBlockAst scriptBlockAst) => DefaultVisit(scriptBlockAst); + object? VisitScriptBlock(ScriptBlockAst scriptBlockAst) => DefaultVisit(scriptBlockAst); /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Param")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "param")] - object VisitParamBlock(ParamBlockAst paramBlockAst) => DefaultVisit(paramBlockAst); + object? VisitParamBlock(ParamBlockAst paramBlockAst) => DefaultVisit(paramBlockAst); /// - object VisitNamedBlock(NamedBlockAst namedBlockAst) => DefaultVisit(namedBlockAst); + object? VisitNamedBlock(NamedBlockAst namedBlockAst) => DefaultVisit(namedBlockAst); /// - object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) => DefaultVisit(typeConstraintAst); + object? VisitTypeConstraint(TypeConstraintAst typeConstraintAst) => DefaultVisit(typeConstraintAst); /// - object VisitAttribute(AttributeAst attributeAst) => DefaultVisit(attributeAst); + object? VisitAttribute(AttributeAst attributeAst) => DefaultVisit(attributeAst); /// - object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) => DefaultVisit(namedAttributeArgumentAst); + object? VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) => DefaultVisit(namedAttributeArgumentAst); /// - object VisitParameter(ParameterAst parameterAst) => DefaultVisit(parameterAst); + object? VisitParameter(ParameterAst parameterAst) => DefaultVisit(parameterAst); #endregion Script Blocks #region Statements /// - object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) => DefaultVisit(functionDefinitionAst); + object? VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) => DefaultVisit(functionDefinitionAst); /// - object VisitStatementBlock(StatementBlockAst statementBlockAst) => DefaultVisit(statementBlockAst); + object? VisitStatementBlock(StatementBlockAst statementBlockAst) => DefaultVisit(statementBlockAst); /// - object VisitIfStatement(IfStatementAst ifStmtAst) => DefaultVisit(ifStmtAst); + object? VisitIfStatement(IfStatementAst ifStmtAst) => DefaultVisit(ifStmtAst); /// - object VisitTrap(TrapStatementAst trapStatementAst) => DefaultVisit(trapStatementAst); + object? VisitTrap(TrapStatementAst trapStatementAst) => DefaultVisit(trapStatementAst); /// - object VisitSwitchStatement(SwitchStatementAst switchStatementAst) => DefaultVisit(switchStatementAst); + object? VisitSwitchStatement(SwitchStatementAst switchStatementAst) => DefaultVisit(switchStatementAst); /// - object VisitDataStatement(DataStatementAst dataStatementAst) => DefaultVisit(dataStatementAst); + object? VisitDataStatement(DataStatementAst dataStatementAst) => DefaultVisit(dataStatementAst); /// - object VisitForEachStatement(ForEachStatementAst forEachStatementAst) => DefaultVisit(forEachStatementAst); + object? VisitForEachStatement(ForEachStatementAst forEachStatementAst) => DefaultVisit(forEachStatementAst); /// - object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) => DefaultVisit(doWhileStatementAst); + object? VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) => DefaultVisit(doWhileStatementAst); /// - object VisitForStatement(ForStatementAst forStatementAst) => DefaultVisit(forStatementAst); + object? VisitForStatement(ForStatementAst forStatementAst) => DefaultVisit(forStatementAst); /// - object VisitWhileStatement(WhileStatementAst whileStatementAst) => DefaultVisit(whileStatementAst); + object? VisitWhileStatement(WhileStatementAst whileStatementAst) => DefaultVisit(whileStatementAst); /// - object VisitCatchClause(CatchClauseAst catchClauseAst) => DefaultVisit(catchClauseAst); + object? VisitCatchClause(CatchClauseAst catchClauseAst) => DefaultVisit(catchClauseAst); /// - object VisitTryStatement(TryStatementAst tryStatementAst) => DefaultVisit(tryStatementAst); + object? VisitTryStatement(TryStatementAst tryStatementAst) => DefaultVisit(tryStatementAst); /// - object VisitBreakStatement(BreakStatementAst breakStatementAst) => DefaultVisit(breakStatementAst); + object? VisitBreakStatement(BreakStatementAst breakStatementAst) => DefaultVisit(breakStatementAst); /// - object VisitContinueStatement(ContinueStatementAst continueStatementAst) => DefaultVisit(continueStatementAst); + object? VisitContinueStatement(ContinueStatementAst continueStatementAst) => DefaultVisit(continueStatementAst); /// - object VisitReturnStatement(ReturnStatementAst returnStatementAst) => DefaultVisit(returnStatementAst); + object? VisitReturnStatement(ReturnStatementAst returnStatementAst) => DefaultVisit(returnStatementAst); /// - object VisitExitStatement(ExitStatementAst exitStatementAst) => DefaultVisit(exitStatementAst); + object? VisitExitStatement(ExitStatementAst exitStatementAst) => DefaultVisit(exitStatementAst); /// - object VisitThrowStatement(ThrowStatementAst throwStatementAst) => DefaultVisit(throwStatementAst); + object? VisitThrowStatement(ThrowStatementAst throwStatementAst) => DefaultVisit(throwStatementAst); /// - object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) => DefaultVisit(doUntilStatementAst); + object? VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) => DefaultVisit(doUntilStatementAst); /// - object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) => DefaultVisit(assignmentStatementAst); + object? VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) => DefaultVisit(assignmentStatementAst); #endregion Statements #region Pipelines /// - object VisitPipeline(PipelineAst pipelineAst) => DefaultVisit(pipelineAst); + object? VisitPipeline(PipelineAst pipelineAst) => DefaultVisit(pipelineAst); /// - object VisitCommand(CommandAst commandAst) => DefaultVisit(commandAst); + object? VisitCommand(CommandAst commandAst) => DefaultVisit(commandAst); /// - object VisitCommandExpression(CommandExpressionAst commandExpressionAst) => DefaultVisit(commandExpressionAst); + object? VisitCommandExpression(CommandExpressionAst commandExpressionAst) => DefaultVisit(commandExpressionAst); /// - object VisitCommandParameter(CommandParameterAst commandParameterAst) => DefaultVisit(commandParameterAst); + object? VisitCommandParameter(CommandParameterAst commandParameterAst) => DefaultVisit(commandParameterAst); /// - object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) => DefaultVisit(fileRedirectionAst); + object? VisitFileRedirection(FileRedirectionAst fileRedirectionAst) => DefaultVisit(fileRedirectionAst); /// - object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) => DefaultVisit(mergingRedirectionAst); + object? VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) => DefaultVisit(mergingRedirectionAst); #endregion Pipelines #region Expressions /// - object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) => DefaultVisit(binaryExpressionAst); + object? VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) => DefaultVisit(binaryExpressionAst); /// - object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) => DefaultVisit(unaryExpressionAst); + object? VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) => DefaultVisit(unaryExpressionAst); /// - object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) => DefaultVisit(convertExpressionAst); + object? VisitConvertExpression(ConvertExpressionAst convertExpressionAst) => DefaultVisit(convertExpressionAst); /// - object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) => DefaultVisit(constantExpressionAst); + object? VisitConstantExpression(ConstantExpressionAst constantExpressionAst) => DefaultVisit(constantExpressionAst); /// - object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => DefaultVisit(stringConstantExpressionAst); + object? VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) => DefaultVisit(stringConstantExpressionAst); /// [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "SubExpression")] [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "subExpression")] - object VisitSubExpression(SubExpressionAst subExpressionAst) => DefaultVisit(subExpressionAst); + object? VisitSubExpression(SubExpressionAst subExpressionAst) => DefaultVisit(subExpressionAst); /// - object VisitUsingExpression(UsingExpressionAst usingExpressionAst) => DefaultVisit(usingExpressionAst); + object? VisitUsingExpression(UsingExpressionAst usingExpressionAst) => DefaultVisit(usingExpressionAst); /// - object VisitVariableExpression(VariableExpressionAst variableExpressionAst) => DefaultVisit(variableExpressionAst); + object? VisitVariableExpression(VariableExpressionAst variableExpressionAst) => DefaultVisit(variableExpressionAst); /// - object VisitTypeExpression(TypeExpressionAst typeExpressionAst) => DefaultVisit(typeExpressionAst); + object? VisitTypeExpression(TypeExpressionAst typeExpressionAst) => DefaultVisit(typeExpressionAst); /// - object VisitMemberExpression(MemberExpressionAst memberExpressionAst) => DefaultVisit(memberExpressionAst); + object? VisitMemberExpression(MemberExpressionAst memberExpressionAst) => DefaultVisit(memberExpressionAst); /// - object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) => DefaultVisit(invokeMemberExpressionAst); + object? VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) => DefaultVisit(invokeMemberExpressionAst); /// - object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) => DefaultVisit(arrayExpressionAst); + object? VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) => DefaultVisit(arrayExpressionAst); /// - object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) => DefaultVisit(arrayLiteralAst); + object? VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) => DefaultVisit(arrayLiteralAst); /// - object VisitHashtable(HashtableAst hashtableAst) => DefaultVisit(hashtableAst); + object? VisitHashtable(HashtableAst hashtableAst) => DefaultVisit(hashtableAst); /// - object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) => DefaultVisit(scriptBlockExpressionAst); + object? VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) => DefaultVisit(scriptBlockExpressionAst); /// [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Paren")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "paren")] - object VisitParenExpression(ParenExpressionAst parenExpressionAst) => DefaultVisit(parenExpressionAst); + object? VisitParenExpression(ParenExpressionAst parenExpressionAst) => DefaultVisit(parenExpressionAst); /// - object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) => DefaultVisit(expandableStringExpressionAst); + object? VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) => DefaultVisit(expandableStringExpressionAst); /// - object VisitIndexExpression(IndexExpressionAst indexExpressionAst) => DefaultVisit(indexExpressionAst); + object? VisitIndexExpression(IndexExpressionAst indexExpressionAst) => DefaultVisit(indexExpressionAst); /// - object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) => DefaultVisit(attributedExpressionAst); + object? VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) => DefaultVisit(attributedExpressionAst); /// - object VisitBlockStatement(BlockStatementAst blockStatementAst) => DefaultVisit(blockStatementAst); + object? VisitBlockStatement(BlockStatementAst blockStatementAst) => DefaultVisit(blockStatementAst); #endregion Expressions } +#nullable restore /// #nullable enable diff --git a/src/System.Management.Automation/engine/parser/Compiler.cs b/src/System.Management.Automation/engine/parser/Compiler.cs index 794b2834331..5ce6a6c6dc8 100644 --- a/src/System.Management.Automation/engine/parser/Compiler.cs +++ b/src/System.Management.Automation/engine/parser/Compiler.cs @@ -39,6 +39,9 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo ObjectList_ToArray = typeof(List).GetMethod(nameof(List.ToArray), Type.EmptyTypes); + internal static readonly MethodInfo ArrayOps_AddObject = + typeof(ArrayOps).GetMethod(nameof(ArrayOps.AddObjectArray), StaticFlags); + internal static readonly MethodInfo ArrayOps_GetMDArrayValue = typeof(ArrayOps).GetMethod(nameof(ArrayOps.GetMDArrayValue), StaticFlags); @@ -252,6 +255,9 @@ internal static class CachedReflectionInfo new Type[] { typeof(int), typeof(IEqualityComparer) }, null); + internal static readonly MethodInfo ByRefOps_GetByRefPropertyValue = + typeof(ByRefOps).GetMethod(nameof(ByRefOps.GetByRefPropertyValue), StaticFlags); + internal static readonly MethodInfo HashtableOps_Add = typeof(HashtableOps).GetMethod(nameof(HashtableOps.Add), StaticFlags); @@ -432,8 +438,8 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo PSInvokeMemberBinder_IsHeterogeneousArray = typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHeterogeneousArray), StaticFlags); - internal static readonly MethodInfo PSInvokeMemberBinder_IsHomogenousArray = - typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHomogenousArray), StaticFlags); + internal static readonly MethodInfo PSInvokeMemberBinder_IsHomogeneousArray = + typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.IsHomogeneousArray), StaticFlags); internal static readonly MethodInfo PSInvokeMemberBinder_TryGetInstanceMethod = typeof(PSInvokeMemberBinder).GetMethod(nameof(PSInvokeMemberBinder.TryGetInstanceMethod), StaticFlags); @@ -471,6 +477,9 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo PSSetMemberBinder_SetAdaptedValue = typeof(PSSetMemberBinder).GetMethod(nameof(PSSetMemberBinder.SetAdaptedValue), StaticFlags); + internal static readonly MethodInfo PSTraceSource_WriteLine = + typeof(PSTraceSource).GetMethod(nameof(PSTraceSource.WriteLine), InstanceFlags, new[] { typeof(string), typeof(object) }); + internal static readonly MethodInfo PSVariableAssignmentBinder_CopyInstanceMembersOfValueType = typeof(PSVariableAssignmentBinder).GetMethod(nameof(PSVariableAssignmentBinder.CopyInstanceMembersOfValueType), StaticFlags); @@ -639,7 +648,9 @@ internal static class CachedReflectionInfo internal static readonly MethodInfo ArgumentTransformationAttribute_Transform = typeof(ArgumentTransformationAttribute).GetMethod(nameof(ArgumentTransformationAttribute.Transform), InstancePublicFlags); - // ReSharper restore InconsistentNaming + + internal static readonly MethodInfo MemberInvocationLoggingOps_LogMemberInvocation = + typeof(MemberInvocationLoggingOps).GetMethod(nameof(MemberInvocationLoggingOps.LogMemberInvocation), StaticFlags); } internal static class ExpressionCache @@ -777,7 +788,7 @@ internal class FunctionContext internal ExecutionContext _executionContext; internal Pipe _outputPipe; internal BitArray _breakPoints; - internal List _boundBreakpoints; + internal Dictionary> _boundBreakpoints; internal int _currentSequencePointIndex; internal MutableTuple _localsTuple; internal List[], Type[]>> _traps = new List[], Type[]>>(); @@ -825,6 +836,14 @@ internal class Compiler : ICustomAstVisitor2 static Compiler() { + Diagnostics.Assert(SpecialVariables.AutomaticVariables.Length == (int)AutomaticVariable.NumberOfAutomaticVariables + && SpecialVariables.AutomaticVariableTypes.Length == (int)AutomaticVariable.NumberOfAutomaticVariables, + "The 'AutomaticVariable' enum length does not match both 'AutomaticVariables' and 'AutomaticVariableTypes' length."); + + Diagnostics.Assert(Enum.GetNames(typeof(PreferenceVariable)).Length == SpecialVariables.PreferenceVariables.Length + && Enum.GetNames(typeof(PreferenceVariable)).Length == SpecialVariables.PreferenceVariableTypes.Length, + "The 'PreferenceVariable' enum length does not match both 'PreferenceVariables' and 'PreferenceVariableTypes' length."); + s_functionContext = Expression.Parameter(typeof(FunctionContext), "funcContext"); s_executionContextParameter = Expression.Variable(typeof(ExecutionContext), "context"); @@ -1059,7 +1078,7 @@ internal static Expression CallSetVariable(Expression variablePath, Expression r internal Expression GetAutomaticVariable(VariableExpressionAst varAst) { - // Generate, in psuedo code: + // Generate, in pseudo code: // // return (localsTuple.IsValueSet(tupleIndex) // ? localsTuple.ItemXXX @@ -1069,7 +1088,7 @@ internal Expression GetAutomaticVariable(VariableExpressionAst varAst) // // * $PSCmdlet - always set if the script uses cmdletbinding. // * $_ - always set in process and end block, otherwise need dynamic checks. - // * $this - can never know if it's set, always need above psuedo code. + // * $this - can never know if it's set, always need above pseudo code. // * $input - also can never know - it's always set from a command process, but not necessarily set from ScriptBlock.Invoke. // // These optimizations are not yet performed. @@ -1105,10 +1124,7 @@ internal static Expression CallStringEquals(Expression left, Expression right, b internal static Expression IsStrictMode(int version, Expression executionContext = null) { - if (executionContext == null) - { - executionContext = ExpressionCache.NullExecutionContext; - } + executionContext ??= ExpressionCache.NullExecutionContext; return Expression.Call( CachedReflectionInfo.ExecutionContext_IsStrictVersion, @@ -1147,7 +1163,7 @@ private Expression UpdatePosition(Ast ast) internal ParameterExpression NewTemp(Type type, string name) { - return Expression.Variable(type, string.Format(CultureInfo.InvariantCulture, "{0}{1}", name, _tempCounter++)); + return Expression.Variable(type, string.Create(CultureInfo.InvariantCulture, $"{name}{_tempCounter++}")); } internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) @@ -1174,7 +1190,7 @@ internal static Type GetTypeConstraintForMethodResolution(ExpressionAst expr) internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type argType) { - if (targetType == null && argType == null) + if (targetType is null && argType is null) { return null; } @@ -1182,14 +1198,19 @@ internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodReso return new PSMethodInvocationConstraints(targetType, new[] { argType }); } - internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution(Type targetType, Type[] argTypes) + internal static PSMethodInvocationConstraints CombineTypeConstraintForMethodResolution( + Type targetType, + Type[] argTypes, + object[] genericArguments = null) { - if (targetType == null && (argTypes == null || argTypes.Length == 0)) + if (targetType is null + && (argTypes is null || argTypes.Length == 0) + && (genericArguments is null || genericArguments.Length == 0)) { return null; } - return new PSMethodInvocationConstraints(targetType, argTypes); + return new PSMethodInvocationConstraints(targetType, argTypes, genericArguments); } internal static Expression ConvertValue(TypeConstraintAst typeConstraint, Expression expr) @@ -1257,7 +1278,7 @@ internal static RuntimeDefinedParameterDictionary GetParameterMetaData(ReadOnlyC for (int index = 0; index < runtimeDefinedParamList.Count; index++) { var rdp = runtimeDefinedParamList[index]; - var paramAttribute = (ParameterAttribute)rdp.Attributes.First(attr => attr is ParameterAttribute); + var paramAttribute = (ParameterAttribute)rdp.Attributes.First(static attr => attr is ParameterAttribute); if (rdp.ParameterType != typeof(SwitchParameter)) { paramAttribute.Position = pos++; @@ -1558,7 +1579,15 @@ private static Attribute NewOutputTypeAttribute(AttributeAst ast) if (args[0] is Type) { - result = new OutputTypeAttribute(LanguagePrimitives.ConvertTo(args)); + // We avoid `ConvertTo(args)` here as CLM would throw due to `Type[]` + // being a "non-core" type. NOTE: This doesn't apply to `string[]`. + Type[] types = new Type[args.Length]; + for (int i = 0; i < args.Length; i++) + { + types[i] = LanguagePrimitives.ConvertTo(args[i]); + } + + result = new OutputTypeAttribute(types); } else { @@ -1719,7 +1748,7 @@ internal static Attribute GetAttribute(AttributeAst attributeAst) } var positionalArgCount = attributeAst.PositionalArguments.Count; - var argumentNames = attributeAst.NamedArguments.Select(name => name.ArgumentName).ToArray(); + var argumentNames = attributeAst.NamedArguments.Select(static name => name.ArgumentName).ToArray(); var totalArgCount = positionalArgCount + argumentNames.Length; var callInfo = new CallInfo(totalArgCount, argumentNames); @@ -1748,18 +1777,15 @@ internal static Attribute GetAttribute(AttributeAst attributeAst) // Unwrap the wrapped exception var innerException = tie.InnerException; var rte = innerException as RuntimeException; - if (rte == null) - { - rte = InterpreterError.NewInterpreterExceptionWithInnerException( - null, - typeof(RuntimeException), - attributeAst.Extent, - "ExceptionConstructingAttribute", - ExtendedTypeSystem.ExceptionConstructingAttribute, - innerException, - innerException.Message, - attributeAst.TypeName.FullName); - } + rte ??= InterpreterError.NewInterpreterExceptionWithInnerException( + null, + typeof(RuntimeException), + attributeAst.Extent, + "ExceptionConstructingAttribute", + ExtendedTypeSystem.ExceptionConstructingAttribute, + innerException, + innerException.Message, + attributeAst.TypeName.FullName); InterpreterError.UpdateExceptionErrorRecordPosition(rte, attributeAst.Extent); throw rte; @@ -2026,6 +2052,7 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) scriptBlock.BeginBlock = CompileTree(_beginBlockLambda, compileInterpretChoice); scriptBlock.ProcessBlock = CompileTree(_processBlockLambda, compileInterpretChoice); scriptBlock.EndBlock = CompileTree(_endBlockLambda, compileInterpretChoice); + scriptBlock.CleanBlock = CompileTree(_cleanBlockLambda, compileInterpretChoice); scriptBlock.LocalsMutableTupleType = LocalVariablesTupleType; scriptBlock.LocalsMutableTupleCreator = MutableTuple.TupleCreator(LocalVariablesTupleType); scriptBlock.NameToIndexMap = nameToIndexMap; @@ -2036,16 +2063,14 @@ internal void Compile(CompiledScriptBlockData scriptBlock, bool optimize) scriptBlock.UnoptimizedBeginBlock = CompileTree(_beginBlockLambda, compileInterpretChoice); scriptBlock.UnoptimizedProcessBlock = CompileTree(_processBlockLambda, compileInterpretChoice); scriptBlock.UnoptimizedEndBlock = CompileTree(_endBlockLambda, compileInterpretChoice); + scriptBlock.UnoptimizedCleanBlock = CompileTree(_cleanBlockLambda, compileInterpretChoice); scriptBlock.UnoptimizedLocalsMutableTupleType = LocalVariablesTupleType; scriptBlock.UnoptimizedLocalsMutableTupleCreator = MutableTuple.TupleCreator(LocalVariablesTupleType); } // The sequence points are identical optimized or not. Regardless, we want to ensure // that the list is unique no matter when the property is accessed, so make sure it is set just once. - if (scriptBlock.SequencePoints == null) - { - scriptBlock.SequencePoints = _sequencePoints.ToArray(); - } + scriptBlock.SequencePoints ??= _sequencePoints.ToArray(); } private static Action CompileTree(Expression> lambda, CompileInterpretChoice compileInterpretChoice) @@ -2114,10 +2139,7 @@ private static object GetExpressionValue( // Can't be exposed to untrusted input - invoking arbitrary code could result in remote code // execution. - if (lambda == null) - { - lambda = (new Compiler()).CompileSingleExpression(expressionAst, out sequencePoints, out localsTupleType); - } + lambda ??= (new Compiler()).CompileSingleExpression(expressionAst, out sequencePoints, out localsTupleType); SessionStateInternal oldSessionState = context.EngineSessionState; try @@ -2200,7 +2222,7 @@ private Func CompileSingleExpression(ExpressionAst expr return Expression.Lambda>(body, parameters).Compile(); } - private class LoopGotoTargets + private sealed class LoopGotoTargets { internal LoopGotoTargets(string label, LabelTarget breakLabel, LabelTarget continueLabel) { @@ -2221,6 +2243,7 @@ internal LoopGotoTargets(string label, LabelTarget breakLabel, LabelTarget conti private Expression> _beginBlockLambda; private Expression> _processBlockLambda; private Expression> _endBlockLambda; + private Expression> _cleanBlockLambda; private readonly List _loopTargets = new List(); private bool _generatingWhileOrDoLoop; @@ -2284,17 +2307,17 @@ private Expression CaptureAstResults( if (context == CaptureAstContext.AssignmentWithoutResultPreservation) { var catchExprs = new List - { - Expression.Call(CachedReflectionInfo.PipelineOps_ClearPipe, resultList), - Expression.Rethrow(), - Expression.Constant(null, typeof(object)) - }; + { + Expression.Call(CachedReflectionInfo.PipelineOps_ClearPipe, resultList), + Expression.Rethrow(), + Expression.Constant(null, typeof(object)) + }; catches.Add(Expression.Catch(typeof(RuntimeException), Expression.Block(typeof(object), catchExprs))); } - // PipelineResult might get skipped in some circumstances due to a FlowControlException thrown out, in which case - // we write to the oldPipe. This can happen in cases like: + // PipelineResult might get skipped in some circumstances due to an early return or a FlowControlException thrown out, + // in which case we write to the oldPipe. This can happen in cases like: // $(1;2;return 3) finallyExprs.Add(Expression.Call(CachedReflectionInfo.PipelineOps_FlushPipe, oldPipe, resultList)); break; @@ -2386,7 +2409,7 @@ private Expression CaptureStatementResults( // We do this after evaluating the condition so that you could do something like: // if ((dir file1,file2 -ea SilentlyContinue) -and $?) { <# files both exist, otherwise $? would be $false if 0 or 1 files existed #> } // - if (context == CaptureAstContext.Condition && AstSearcher.FindFirst(stmt, ast => ast is CommandAst, searchNestedScriptBlocks: false) != null) + if (context == CaptureAstContext.Condition && AstSearcher.FindFirst(stmt, static ast => ast is CommandAst, searchNestedScriptBlocks: false) != null) { var tmp = NewTemp(result.Type, "condTmp"); result = Expression.Block( @@ -2426,7 +2449,7 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) var funcDefn = scriptBlockAst.Parent as FunctionDefinitionAst; var funcName = (funcDefn != null) ? funcDefn.Name : ""; - var rootForDefiningTypesAndUsings = scriptBlockAst.Find(ast => ast is TypeDefinitionAst || ast is UsingStatementAst, true) != null + var rootForDefiningTypesAndUsings = scriptBlockAst.Find(static ast => ast is TypeDefinitionAst || ast is UsingStatementAst, true) != null ? scriptBlockAst : null; @@ -2463,6 +2486,13 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) } _endBlockLambda = CompileNamedBlock(scriptBlockAst.EndBlock, funcName, rootForDefiningTypesAndUsings); + rootForDefiningTypesAndUsings = null; + } + + if (scriptBlockAst.CleanBlock != null) + { + _cleanBlockLambda = CompileNamedBlock(scriptBlockAst.CleanBlock, funcName + "", rootForDefiningTypesAndUsings); + rootForDefiningTypesAndUsings = null; } return null; @@ -2566,7 +2596,7 @@ private Expression> CompileSingleLambda( // to the right place. We can avoid also avoid generating the catch if we know there aren't any traps. if (!_compilingTrap && ((traps != null && traps.Count > 0) - || statements.Any(stmt => AstSearcher.Contains(stmt, ast => ast is TrapStatementAst, searchNestedScriptBlocks: false)))) + || statements.Any(static stmt => AstSearcher.Contains(stmt, static ast => ast is TrapStatementAst, searchNestedScriptBlocks: false)))) { body = Expression.Block( new[] { s_executionContextParameter }, @@ -2605,12 +2635,12 @@ private static void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAn { if (rootForDefiningTypesAndUsings.UsingStatements.Count > 0) { - bool allUsingsAreNamespaces = rootForDefiningTypesAndUsings.UsingStatements.All(us => us.UsingStatementKind == UsingStatementKind.Namespace); + bool allUsingsAreNamespaces = rootForDefiningTypesAndUsings.UsingStatements.All(static us => us.UsingStatementKind == UsingStatementKind.Namespace); GenerateLoadUsings(rootForDefiningTypesAndUsings.UsingStatements, allUsingsAreNamespaces, exprs); } TypeDefinitionAst[] typeAsts = - rootForDefiningTypesAndUsings.FindAll(ast => ast is TypeDefinitionAst, true) + rootForDefiningTypesAndUsings.FindAll(static ast => ast is TypeDefinitionAst, true) .Cast() .ToArray(); @@ -2628,9 +2658,9 @@ private static void GenerateTypesAndUsings(ScriptBlockAst rootForDefiningTypesAn } Dictionary typesToAddToScope = - rootForDefiningTypesAndUsings.FindAll(ast => ast is TypeDefinitionAst, false) + rootForDefiningTypesAndUsings.FindAll(static ast => ast is TypeDefinitionAst, false) .Cast() - .ToDictionary(type => type.Name); + .ToDictionary(static type => type.Name); if (typesToAddToScope.Count > 0) { exprs.Add( @@ -2794,15 +2824,9 @@ private static Assembly LoadAssembly(string assemblyName, string scriptFileName) { if (!string.IsNullOrEmpty(scriptFileName) && !Path.IsPathRooted(assemblyFileName)) { - assemblyFileName = Path.GetDirectoryName(scriptFileName) + "\\" + assemblyFileName; + assemblyFileName = Path.Combine(Path.GetDirectoryName(scriptFileName), assemblyFileName); } -#if !CORECLR - if (!File.Exists(assemblyFileName)) - { - Microsoft.CodeAnalysis.GlobalAssemblyCache.ResolvePartialName(assemblyName, out assemblyFileName); - } -#endif if (File.Exists(assemblyFileName)) { assembly = Assembly.LoadFrom(assemblyFileName); @@ -3279,9 +3303,9 @@ private bool ShouldSetExecutionStatusToSuccess(StatementAst statementAst) /// True is the compiler should add the success setting, false otherwise. private bool ShouldSetExecutionStatusToSuccess(PipelineAst pipelineAst) { - ExpressionAst expressionAst = pipelineAst.GetPureExpression(); + ExpressionAst expressionAst = GetSingleExpressionFromPipeline(pipelineAst); - // If the pipeline is not a simple expression, it will set $? + // If the pipeline is not a single expression, it will set $? if (expressionAst == null) { return false; @@ -3291,6 +3315,22 @@ private bool ShouldSetExecutionStatusToSuccess(PipelineAst pipelineAst) return ShouldSetExecutionStatusToSuccess(expressionAst); } + /// + /// If the pipeline contains a single expression, the expression is returned, otherwise null is returned. + /// This method is different from in that it allows the single + /// expression to have redirections. + /// + private static ExpressionAst GetSingleExpressionFromPipeline(PipelineAst pipelineAst) + { + var pipelineElements = pipelineAst.PipelineElements; + if (pipelineElements.Count == 1 && pipelineElements[0] is CommandExpressionAst expr) + { + return expr.Expression; + } + + return null; + } + /// /// Determines whether an assignment statement must have an explicit setting /// for $? = $true after it by the compiler. @@ -3584,7 +3624,7 @@ public object VisitPipelineChain(PipelineChainAst pipelineChainAst) var dispatchTargets = new List(); var tryBodyExprs = new List() { - null, // Add a slot for the inital switch/case that we'll come back to + null, // Add a slot for the initial switch/case that we'll come back to }; // L0: dispatchIndex = 1; pipeline1 @@ -3778,20 +3818,20 @@ public object VisitPipeline(PipelineAst pipelineAst) // one dimension because each command may have multiple redirections. Here we create the array for // each command in the pipe, either a compile time constant or created at runtime if necessary. Expression redirectionExpr; - if (commandRedirections.Any(r => r is Expression)) + if (commandRedirections.Any(static r => r is Expression)) { // If any command redirections are non-constant, commandRedirections will have a Linq.Expression in it, // in which case we must create the array at runtime redirectionExpr = Expression.NewArrayInit( typeof(CommandRedirection[]), - commandRedirections.Select(r => (r as Expression) ?? Expression.Constant(r, typeof(CommandRedirection[])))); + commandRedirections.Select(static r => (r as Expression) ?? Expression.Constant(r, typeof(CommandRedirection[])))); } - else if (commandRedirections.Any(r => r != null)) + else if (commandRedirections.Any(static r => r != null)) { // There were redirections, but all were compile time constant, so build the array at compile time. redirectionExpr = - Expression.Constant(commandRedirections.Map(r => r as CommandRedirection[])); + Expression.Constant(commandRedirections.Map(static r => r as CommandRedirection[])); } else { @@ -3839,15 +3879,15 @@ private object GetCommandRedirections(CommandBaseAst command) } // If there were any non-constant expressions, we must generate the array at runtime. - if (compiledRedirections.Any(r => r is Expression)) + if (compiledRedirections.Any(static r => r is Expression)) { return Expression.NewArrayInit( typeof(CommandRedirection), - compiledRedirections.Select(r => (r as Expression) ?? Expression.Constant(r))); + compiledRedirections.Select(static r => (r as Expression) ?? Expression.Constant(r))); } // Otherwise, we can use a compile time constant array. - return compiledRedirections.Map(r => (CommandRedirection)r); + return compiledRedirections.Map(static r => (CommandRedirection)r); } // A redirected expression requires extra work because there is no CommandProcessor or PipelineProcessor @@ -3871,7 +3911,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo // funcContext.OutputPipe = oldPipe; // } // - // In the above psuedo-code, any of {outputFileRedirection, nonOutputFileRedirection, mergingRedirection} may + // In the above pseudo-code, any of {outputFileRedirection, nonOutputFileRedirection, mergingRedirection} may // not exist, but the order is preserved, so that file redirections go before merging redirections (so that // funcContext.OutputPipe has the correct value when setting up merging.) // @@ -3882,7 +3922,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo // For the output stream, we change funcContext.OutputPipe so all output goes to the file. // Currently output can only be redirected to a file stream. bool outputRedirected = - commandExpr.Redirections.Any(r => r is FileRedirectionAst && + commandExpr.Redirections.Any(static r => r is FileRedirectionAst && (r.FromStream == RedirectionStream.Output || r.FromStream == RedirectionStream.All)); ParameterExpression resultList = null; @@ -3910,10 +3950,7 @@ private Expression GetRedirectedExpression(CommandExpressionAst commandExpr, boo // This will simply return a Linq.Expression representing the redirection. var compiledRedirection = VisitFileRedirection(fileRedirectionAst); - if (extraFileRedirectExprs == null) - { - extraFileRedirectExprs = new List(commandExpr.Redirections.Count); - } + extraFileRedirectExprs ??= new List(commandExpr.Redirections.Count); // Hold the current 'FileRedirection' instance for later use var redirectionExpr = NewTemp(typeof(FileRedirection), "fileRedirection"); @@ -4277,7 +4314,7 @@ internal static Expression ThrowRuntimeError(string errorID, string resourceStri internal static Expression ThrowRuntimeError(Type exceptionType, string errorID, string resourceString, Type throwResultType, params Expression[] exceptionArgs) { var exceptionArgArray = exceptionArgs != null - ? Expression.NewArrayInit(typeof(object), exceptionArgs.Select(e => e.Cast(typeof(object)))) + ? Expression.NewArrayInit(typeof(object), exceptionArgs.Select(static e => e.Cast(typeof(object)))) : ExpressionCache.NullConstant; Expression[] argExprs = new Expression[] { @@ -5142,7 +5179,7 @@ public object VisitCatchClause(CatchClauseAst catchClauseAst) // If the automatic var has no value in the current frame, then we set the variable's value to $null // after leaving the stmt. // - // The psuedo-code: + // The pseudo-code: // // try { // oldValue = (localSet.Get(automaticVar)) ? locals.ItemNNN : null; @@ -5154,7 +5191,7 @@ public object VisitCatchClause(CatchClauseAst catchClauseAst) // } // // This is a little convoluted because an automatic variable isn't necessarily set. - private class AutomaticVarSaver + private sealed class AutomaticVarSaver { private readonly Compiler _compiler; private readonly int _automaticVar; @@ -5581,7 +5618,9 @@ public object VisitReturnStatement(ReturnStatementAst returnStatementAst) return Expression.Block(returnValue, returnExpr); } - return returnExpr; + return Expression.Block( + UpdatePosition(returnStatementAst), + returnExpr); } public object VisitExitStatement(ExitStatementAst exitStatementAst) @@ -6097,9 +6136,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { // We'll wrap the variable in a PSReference, but not the constant variables ($true, $false, $null) because those // can't be changed. - IEnumerable unused1; - bool unused2; - var varType = varExpr.GetVariableType(this, out unused1, out unused2); + var varType = varExpr.GetVariableType(this, out _, out _); return Expression.Call( CachedReflectionInfo.VariableOps_GetVariableAsRef, Expression.Constant(varExpr.VariablePath), @@ -6110,10 +6147,7 @@ public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) } } - if (childExpr == null) - { - childExpr = Compile(convertExpressionAst.Child); - } + childExpr ??= Compile(convertExpressionAst.Child); if (typeName.FullName.Equals("PSCustomObject", StringComparison.OrdinalIgnoreCase)) { @@ -6310,17 +6344,48 @@ public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(InvokeMemberExpressionAst invokeMemberExpressionAst) { - var arguments = invokeMemberExpressionAst.Arguments; + ReadOnlyCollection arguments = invokeMemberExpressionAst.Arguments; + Type[] argumentTypes = null; + if (arguments is not null) + { + argumentTypes = new Type[arguments.Count]; + for (var i = 0; i < arguments.Count; i++) + { + argumentTypes[i] = GetTypeConstraintForMethodResolution(arguments[i]); + } + } + var targetTypeConstraint = GetTypeConstraintForMethodResolution(invokeMemberExpressionAst.Expression); - return CombineTypeConstraintForMethodResolution( - targetTypeConstraint, - arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray()); + + ReadOnlyCollection genericArguments = invokeMemberExpressionAst.GenericTypeArguments; + object[] genericTypeArguments = null; + if (genericArguments is not null) + { + genericTypeArguments = new object[genericArguments.Count]; + for (var i = 0; i < genericArguments.Count; i++) + { + Type type = genericArguments[i].GetReflectionType(); + genericTypeArguments[i] = (object)type ?? genericArguments[i]; + } + } + + return CombineTypeConstraintForMethodResolution(targetTypeConstraint, argumentTypes, genericTypeArguments); } internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCtorInvokeMemberExpressionAst invokeMemberExpressionAst) { Type targetTypeConstraint = null; - var arguments = invokeMemberExpressionAst.Arguments; + ReadOnlyCollection arguments = invokeMemberExpressionAst.Arguments; + Type[] argumentTypes = null; + if (arguments is not null) + { + argumentTypes = new Type[arguments.Count]; + for (var i = 0; i < arguments.Count; i++) + { + argumentTypes[i] = GetTypeConstraintForMethodResolution(arguments[i]); + } + } + TypeDefinitionAst typeDefinitionAst = Ast.GetAncestorTypeDefinitionAst(invokeMemberExpressionAst); if (typeDefinitionAst != null) { @@ -6331,9 +6396,7 @@ internal static PSMethodInvocationConstraints GetInvokeMemberConstraints(BaseCto Diagnostics.Assert(false, "BaseCtorInvokeMemberExpressionAst must be used only inside TypeDefinitionAst"); } - return CombineTypeConstraintForMethodResolution( - targetTypeConstraint, - arguments?.Select(Compiler.GetTypeConstraintForMethodResolution).ToArray()); + return CombineTypeConstraintForMethodResolution(targetTypeConstraint, argumentTypes, genericArguments: null); } internal Expression InvokeMember( @@ -6705,8 +6768,8 @@ public Expression GetValue(Compiler compiler, List exprs, List Expression.Variable(arg.Type)).ToArray(); - exprs.AddRange(args.Zip(_argExprTemps, (arg, temp) => Expression.Assign(temp, arg))); + _argExprTemps = args.Select(static arg => Expression.Variable(arg.Type)).ToArray(); + exprs.AddRange(args.Zip(_argExprTemps, static (arg, temp) => Expression.Assign(temp, arg))); temps.Add(_targetExprTemp); int tempsIndex = temps.Count; @@ -6918,10 +6981,7 @@ public void AddInstructions(LightCompiler compiler) compiler.PopLabelBlock(LabelScopeKind.Statement); // If enterLoop is null, we will never JIT compile the loop. - if (enterLoop != null) - { - enterLoop.FinishLoop(compiler.Instructions.Count); - } + enterLoop?.FinishLoop(compiler.Instructions.Count); } } diff --git a/src/System.Management.Automation/engine/parser/ConstantValues.cs b/src/System.Management.Automation/engine/parser/ConstantValues.cs index a8ada5f96d5..d580148ddd2 100644 --- a/src/System.Management.Automation/engine/parser/ConstantValues.cs +++ b/src/System.Management.Automation/engine/parser/ConstantValues.cs @@ -148,8 +148,16 @@ public static bool IsConstant(Ast ast, out object constantValue, bool forAttribu public object VisitStatementBlock(StatementBlockAst statementBlockAst) { - if (statementBlockAst.Traps != null) return false; - if (statementBlockAst.Statements.Count > 1) return false; + if (statementBlockAst.Traps != null) + { + return false; + } + + if (statementBlockAst.Statements.Count > 1) + { + return false; + } + var pipeline = statementBlockAst.Statements.FirstOrDefault(); return pipeline != null && (bool)pipeline.Accept(this); } diff --git a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs index 69e8aae634b..cb280bdaf61 100644 --- a/src/System.Management.Automation/engine/parser/DebugViewWriter.cs +++ b/src/System.Management.Automation/engine/parser/DebugViewWriter.cs @@ -985,7 +985,7 @@ protected override Expression VisitBlock(BlockExpression node) { // Display if the type of the BlockExpression is different from the // last expression's type in the block. if (node.Type != node.Expressions[node.Expressions.Count - 1].Type) { - Out(string.Format(CultureInfo.CurrentCulture, "<{0}>", node.Type.ToString())); + Out(string.Create(CultureInfo.CurrentCulture, $"<{node.Type}>")); } VisitDeclarations(node.Variables); @@ -1124,7 +1124,7 @@ protected override Expression VisitIndex(IndexExpression node) { } protected override Expression VisitExtension(Expression node) { - Out(string.Format(CultureInfo.CurrentCulture, ".Extension<{0}>", node.GetType().ToString())); + Out(string.Create(CultureInfo.CurrentCulture, $".Extension<{node.GetType()}>")); if (node.CanReduce) { Out(Flow.Space, "{", Flow.NewLine); @@ -1151,13 +1151,13 @@ protected override Expression VisitDebugInfo(DebugInfoExpression node) { } private void DumpLabel(LabelTarget target) { - Out(string.Format(CultureInfo.CurrentCulture, ".LabelTarget {0}:", GetLabelTargetName(target))); + Out(string.Create(CultureInfo.CurrentCulture, $".LabelTarget {GetLabelTargetName(target)}:")); } private string GetLabelTargetName(LabelTarget target) { if (string.IsNullOrEmpty(target.Name)) { // Create the label target name as #Label1, #Label2, etc. - return string.Format(CultureInfo.CurrentCulture, "#Label{0}", GetLabelTargetId(target)); + return string.Create(CultureInfo.CurrentCulture, $"#Label{GetLabelTargetId(target)}"); } else { return GetDisplayName(target.Name); } @@ -1165,11 +1165,7 @@ private string GetLabelTargetName(LabelTarget target) { private void WriteLambda(LambdaExpression lambda) { Out( - string.Format( - CultureInfo.CurrentCulture, - ".Lambda {0}<{1}>", - GetLambdaName(lambda), - lambda.Type.ToString()) + string.Create(CultureInfo.CurrentCulture, $".Lambda {GetLambdaName(lambda)}<{lambda.Type}>") ); VisitDeclarations(lambda.Parameters); @@ -1205,7 +1201,7 @@ private static bool ContainsWhiteSpace(string name) { } private static string QuoteName(string name) { - return string.Format(CultureInfo.CurrentCulture, "'{0}'", name); + return string.Create(CultureInfo.CurrentCulture, $"'{name}'"); } private static string GetDisplayName(string name) { diff --git a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs b/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs deleted file mode 100644 index 79df05d09f4..00000000000 --- a/src/System.Management.Automation/engine/parser/FusionAssemblyIdentity.cs +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// Code in this file was copied from https://github.com/dotnet/roslyn - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Reflection; -using System.Runtime.InteropServices; - -#if !CORECLR -namespace Microsoft.CodeAnalysis -{ - internal sealed class FusionAssemblyIdentity - { - [Flags] - internal enum ASM_DISPLAYF - { - VERSION = 0x01, - CULTURE = 0x02, - PUBLIC_KEY_TOKEN = 0x04, - PUBLIC_KEY = 0x08, - CUSTOM = 0x10, - PROCESSORARCHITECTURE = 0x20, - LANGUAGEID = 0x40, - RETARGET = 0x80, - CONFIG_MASK = 0x100, - MVID = 0x200, - CONTENT_TYPE = 0x400, - FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE - } - - internal enum PropertyId - { - PUBLIC_KEY = 0, // 0 - PUBLIC_KEY_TOKEN, // 1 - HASH_VALUE, // 2 - NAME, // 3 - MAJOR_VERSION, // 4 - MINOR_VERSION, // 5 - BUILD_NUMBER, // 6 - REVISION_NUMBER, // 7 - CULTURE, // 8 - PROCESSOR_ID_ARRAY, // 9 - OSINFO_ARRAY, // 10 - HASH_ALGID, // 11 - ALIAS, // 12 - CODEBASE_URL, // 13 - CODEBASE_LASTMOD, // 14 - NULL_PUBLIC_KEY, // 15 - NULL_PUBLIC_KEY_TOKEN, // 16 - CUSTOM, // 17 - NULL_CUSTOM, // 18 - MVID, // 19 - FILE_MAJOR_VERSION, // 20 - FILE_MINOR_VERSION, // 21 - FILE_BUILD_NUMBER, // 22 - FILE_REVISION_NUMBER, // 23 - RETARGET, // 24 - SIGNATURE_BLOB, // 25 - CONFIG_MASK, // 26 - ARCHITECTURE, // 27 - CONTENT_TYPE, // 28 - MAX_PARAMS // 29 - } - - private static class CANOF - { - public const uint PARSE_DISPLAY_NAME = 0x1; - public const uint SET_DEFAULT_VALUES = 0x2; - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] - internal unsafe interface IAssemblyName - { - void SetProperty(PropertyId id, void* data, uint size); - - [PreserveSig] - int GetProperty(PropertyId id, void* data, ref uint size); - - [PreserveSig] - int Finalize(); - - [PreserveSig] - int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags); - - [PreserveSig] - int __BindToObject(/*...*/); - - [PreserveSig] - int __GetName(/*...*/); - - [PreserveSig] - int GetVersion(out uint versionHi, out uint versionLow); - - [PreserveSig] - int IsEqual(IAssemblyName pName, uint dwCmpFlags); - - [PreserveSig] - int Clone(out IAssemblyName pName); - } - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")] - internal interface IApplicationContext - { - } - - // NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner. - // Wrap all calls to this with a lock. - private static object s_assemblyIdentityGate = new object(); - private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved) - { - lock (s_assemblyIdentityGate) - { - return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved); - } - } - - [DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)] - private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)]string szAssemblyName, uint dwFlags, IntPtr pvReserved); - - private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A); - private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); - - internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags) - { - int hr; - uint characterCountIncludingTerminator = 0; - - hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags); - if (hr == 0) - { - return string.Empty; - } - - if (hr != ERROR_INSUFFICIENT_BUFFER) - { - Marshal.ThrowExceptionForHR(hr); - } - - byte[] data = new byte[(int)characterCountIncludingTerminator * 2]; - fixed (byte* p = data) - { - hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags); - Marshal.ThrowExceptionForHR(hr); - - return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1); - } - } - - internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId) - { - int hr; - uint size = 0; - - hr = nameObject.GetProperty(propertyId, null, ref size); - if (hr == 0) - { - return null; - } - - if (hr != ERROR_INSUFFICIENT_BUFFER) - { - Marshal.ThrowExceptionForHR(hr); - } - - byte[] data = new byte[(int)size]; - fixed (byte* p = data) - { - hr = nameObject.GetProperty(propertyId, p, ref size); - Marshal.ThrowExceptionForHR(hr); - } - - return data; - } - - internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) - { - byte[] data = GetPropertyBytes(nameObject, propertyId); - if (data == null) - { - return null; - } - - fixed (byte* p = data) - { - return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1); - } - } - - internal static unsafe Version GetVersion(IAssemblyName nameObject) - { - uint hi, lo; - int hr = nameObject.GetVersion(out hi, out lo); - if (hr != 0) - { - Debug.Assert(hr == FUSION_E_INVALID_NAME); - return null; - } - - return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff)); - } - - internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId) - { - uint result; - uint size = sizeof(uint); - int hr = nameObject.GetProperty(propertyId, &result, ref size); - Marshal.ThrowExceptionForHR(hr); - - if (size == 0) - { - return null; - } - - return result; - } - - internal static string GetCulture(IAssemblyName nameObject) - { - return GetPropertyString(nameObject, PropertyId.CULTURE); - } - - internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject) - { - return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0); - } - - /// - /// Creates object by parsing given display name. - /// - internal static IAssemblyName ToAssemblyNameObject(string displayName) - { - // CLR doesn't handle \0 in the display name well: - if (displayName.IndexOf('\0') >= 0) - { - return null; - } - - Debug.Assert(displayName != null); - IAssemblyName result; - int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); - if (hr != 0) - { - return null; - } - - Debug.Assert(result != null); - return result; - } - - /// - /// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided. - /// All candidates are assumed to have the same name and must include versions and cultures. - /// - internal static IAssemblyName GetBestMatch(IEnumerable candidates, string preferredCultureOpt) - { - IAssemblyName bestCandidate = null; - Version bestVersion = null; - string bestCulture = null; - foreach (var candidate in candidates) - { - if (bestCandidate != null) - { - Version candidateVersion = GetVersion(candidate); - Debug.Assert(candidateVersion != null); - - if (bestVersion == null) - { - bestVersion = GetVersion(bestCandidate); - Debug.Assert(bestVersion != null); - } - - int cmp = bestVersion.CompareTo(candidateVersion); - if (cmp == 0) - { - if (preferredCultureOpt != null) - { - string candidateCulture = GetCulture(candidate); - Debug.Assert(candidateCulture != null); - - if (bestCulture == null) - { - bestCulture = GetCulture(candidate); - Debug.Assert(bestCulture != null); - } - - // we have exactly the preferred culture or - // we have neutral culture and the best candidate's culture isn't the preferred one: - if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) || - candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt)) - { - bestCandidate = candidate; - bestVersion = candidateVersion; - bestCulture = candidateCulture; - } - } - } - else if (cmp < 0) - { - bestCandidate = candidate; - bestVersion = candidateVersion; - } - } - else - { - bestCandidate = candidate; - } - } - - return bestCandidate; - } - } -} -#endif // !CORECLR diff --git a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs b/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs deleted file mode 100644 index 3761c55d3dc..00000000000 --- a/src/System.Management.Automation/engine/parser/GlobalAssemblyCache.cs +++ /dev/null @@ -1,215 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// Code in this file was copied from https://github.com/dotnet/roslyn - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Globalization; -using System.IO; -using System.Linq; -using System.Reflection; -using System.Runtime.InteropServices; - -#if !CORECLR // Only enable/port what is needed by CORE CLR. -namespace Microsoft.CodeAnalysis -{ - /// - /// Provides APIs to enumerate and look up assemblies stored in the Global Assembly Cache. - /// - internal static class GlobalAssemblyCache - { - /// - /// Represents the current Processor architecture. - /// - public static readonly ProcessorArchitecture[] CurrentArchitectures = (IntPtr.Size == 4) - ? new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.X86 } - - : new[] { ProcessorArchitecture.None, ProcessorArchitecture.MSIL, ProcessorArchitecture.Amd64 }; - -#region Interop - - private const int MAX_PATH = 260; - - [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("21b8916c-f28e-11d2-a473-00c04f8ef448")] - private interface IAssemblyEnum - { - [PreserveSig] - int GetNextAssembly(out FusionAssemblyIdentity.IApplicationContext ppAppCtx, out FusionAssemblyIdentity.IAssemblyName ppName, uint dwFlags); - - [PreserveSig] - int Reset(); - - [PreserveSig] - int Clone(out IAssemblyEnum ppEnum); - } - - [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - private interface IAssemblyCache - { - void UninstallAssembly(); - - void QueryAssemblyInfo(uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref ASSEMBLY_INFO pAsmInfo); - - void CreateAssemblyCacheItem(); - void CreateAssemblyScavenger(); - void InstallAssembly(); - } - - [StructLayout(LayoutKind.Sequential)] - private unsafe struct ASSEMBLY_INFO - { - public uint cbAssemblyInfo; - public uint dwAssemblyFlags; - public ulong uliAssemblySizeInKB; - public char* pszCurrentAssemblyPathBuf; - public uint cchBuf; - } - - private enum ASM_CACHE - { - ZAP = 0x1, - GAC = 0x2, // C:\Windows\Assembly\GAC - DOWNLOAD = 0x4, - ROOT = 0x8, // C:\Windows\Assembly - GAC_MSIL = 0x10, - GAC_32 = 0x20, // C:\Windows\Assembly\GAC_32 - GAC_64 = 0x40, // C:\Windows\Assembly\GAC_64 - ROOT_EX = 0x80, // C:\Windows\Microsoft.NET\assembly - } - - [DllImport("clr", CharSet = CharSet.Auto, PreserveSig = true)] - private static extern int CreateAssemblyEnum(out IAssemblyEnum ppEnum, FusionAssemblyIdentity.IApplicationContext pAppCtx, FusionAssemblyIdentity.IAssemblyName pName, ASM_CACHE dwFlags, IntPtr pvReserved); - - [DllImport("clr", CharSet = CharSet.Auto, PreserveSig = false)] - private static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); - -#endregion - - private const int S_OK = 0; - private const int S_FALSE = 1; - - // Internal for testing. - internal static IEnumerable GetAssemblyObjects( - FusionAssemblyIdentity.IAssemblyName partialNameFilter, - ProcessorArchitecture[] architectureFilter) - { - IAssemblyEnum enumerator; - - int hr = CreateAssemblyEnum(out enumerator, null, partialNameFilter, ASM_CACHE.GAC, IntPtr.Zero); - if (hr == S_FALSE) - { - // no assembly found - yield break; - } - - if (hr != S_OK) - { - Exception e = Marshal.GetExceptionForHR(hr); - if (e is FileNotFoundException) - { - // invalid assembly name: - yield break; - } - - if (e != null) - { - throw e; - } - // for some reason it might happen that CreateAssemblyEnum returns non-zero HR that doesn't correspond to any exception: - throw new ArgumentException("Invalid assembly name"); - } - - while (true) - { - FusionAssemblyIdentity.IAssemblyName nameObject; - - FusionAssemblyIdentity.IApplicationContext applicationContext; - hr = enumerator.GetNextAssembly(out applicationContext, out nameObject, 0); - if (hr != 0) - { - if (hr < 0) - { - Marshal.ThrowExceptionForHR(hr); - } - - break; - } - - if (architectureFilter != null) - { - var assemblyArchitecture = FusionAssemblyIdentity.GetProcessorArchitecture(nameObject); - if (!architectureFilter.Contains(assemblyArchitecture)) - { - continue; - } - } - - yield return nameObject; - } - } - - /// - /// Looks up specified partial assembly name in the GAC and returns the best matching full assembly name/>. - /// - /// The display name of an assembly. - /// Full path name of the resolved assembly. - /// The optional processor architecture. - /// The optional preferred culture information. - /// An assembly identity or null, if can't be resolved. - /// is null. - public static unsafe string ResolvePartialName( - string displayName, - out string location, - ProcessorArchitecture[] architectureFilter = null, - CultureInfo preferredCulture = null) - { - if (displayName == null) - { - throw new ArgumentNullException("displayName"); - } - - location = null; - FusionAssemblyIdentity.IAssemblyName nameObject = FusionAssemblyIdentity.ToAssemblyNameObject(displayName); - if (nameObject == null) - { - return null; - } - - var candidates = GetAssemblyObjects(nameObject, architectureFilter); - string cultureName = (preferredCulture != null && !preferredCulture.IsNeutralCulture) ? preferredCulture.Name : null; - - var bestMatch = FusionAssemblyIdentity.GetBestMatch(candidates, cultureName); - if (bestMatch == null) - { - return null; - } - - string fullName = FusionAssemblyIdentity.GetDisplayName(bestMatch, FusionAssemblyIdentity.ASM_DISPLAYF.FULL); - - fixed (char* p = new char[MAX_PATH]) - { - ASSEMBLY_INFO info = new ASSEMBLY_INFO - { - cbAssemblyInfo = (uint)Marshal.SizeOf(typeof(ASSEMBLY_INFO)), - pszCurrentAssemblyPathBuf = p, - cchBuf = (uint)MAX_PATH - }; - - IAssemblyCache assemblyCacheObject; - CreateAssemblyCache(out assemblyCacheObject, 0); - assemblyCacheObject.QueryAssemblyInfo(0, fullName, ref info); - Debug.Assert(info.pszCurrentAssemblyPathBuf != null); - Debug.Assert(info.pszCurrentAssemblyPathBuf[info.cchBuf - 1] == '\0'); - - var result = Marshal.PtrToStringUni((IntPtr)info.pszCurrentAssemblyPathBuf, (int)info.cchBuf - 1); - Debug.Assert(result.IndexOf('\0') == -1); - location = result; - } - - return fullName; - } - } -} -#endif // !CORECLR diff --git a/src/System.Management.Automation/engine/parser/PSType.cs b/src/System.Management.Automation/engine/parser/PSType.cs index 7a60d06a6be..06f978a51ce 100644 --- a/src/System.Management.Automation/engine/parser/PSType.cs +++ b/src/System.Management.Automation/engine/parser/PSType.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Management.Automation.Internal; @@ -265,7 +266,7 @@ internal static void DefineCustomAttributes(EnumBuilder member, ReadOnlyCollecti } } - private class DefineTypeHelper + private sealed class DefineTypeHelper { private readonly Parser _parser; internal readonly TypeDefinitionAst _typeDefinitionAst; @@ -276,7 +277,7 @@ private class DefineTypeHelper internal readonly TypeBuilder _staticHelpersTypeBuilder; private readonly Dictionary _definedProperties; private readonly Dictionary>> _definedMethods; - private HashSet> _interfaceProperties; + private Dictionary, PropertyInfo> _abstractProperties; internal readonly List<(string fieldName, IParameterMetadataProvider bodyAst, bool isStatic)> _fieldsToInitForMemberFunctions; private bool _baseClassHasDefaultCtor; @@ -296,7 +297,7 @@ public DefineTypeHelper(Parser parser, ModuleBuilder module, TypeDefinitionAst t var baseClass = this.GetBaseTypes(parser, typeDefinitionAst, out interfaces); _typeBuilder = module.DefineType(typeName, Reflection.TypeAttributes.Class | Reflection.TypeAttributes.Public, baseClass, interfaces.ToArray()); - _staticHelpersTypeBuilder = module.DefineType(string.Format(CultureInfo.InvariantCulture, "{0}_", typeName), Reflection.TypeAttributes.Class); + _staticHelpersTypeBuilder = module.DefineType(string.Create(CultureInfo.InvariantCulture, $"{typeName}_"), Reflection.TypeAttributes.Class); DefineCustomAttributes(_typeBuilder, typeDefinitionAst.Attributes, _parser, AttributeTargets.Class); _typeDefinitionAst.Type = _typeBuilder; @@ -444,11 +445,11 @@ private Type GetBaseTypes(Parser parser, TypeDefinitionAst typeDefinitionAst, ou return baseClass ?? typeof(object); } - private bool ShouldImplementProperty(string name, Type type) + private bool ShouldImplementProperty(string name, Type type, [NotNullWhen(true)] out PropertyInfo interfaceProperty) { - if (_interfaceProperties == null) + if (_abstractProperties == null) { - _interfaceProperties = new HashSet>(); + _abstractProperties = new Dictionary, PropertyInfo>(); var allInterfaces = new HashSet(); // TypeBuilder.GetInterfaces() returns only the interfaces that was explicitly passed to its constructor. @@ -467,12 +468,23 @@ private bool ShouldImplementProperty(string name, Type type) { foreach (var property in interfaceType.GetProperties()) { - _interfaceProperties.Add(Tuple.Create(property.Name, property.PropertyType)); + _abstractProperties.Add(Tuple.Create(property.Name, property.PropertyType), property); + } + } + + if (_typeBuilder.BaseType.IsAbstract) + { + foreach (var property in _typeBuilder.BaseType.GetProperties()) + { + if (property.GetAccessors().Any(m => m.IsAbstract)) + { + _abstractProperties.Add(Tuple.Create(property.Name, property.PropertyType), property); + } } } } - return _interfaceProperties.Contains(Tuple.Create(name, type)); + return _abstractProperties.TryGetValue(Tuple.Create(name, type), out interfaceProperty); } public void DefineMembers() @@ -618,9 +630,19 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type // The property set and property get methods require a special set of attributes. var getSetAttributes = Reflection.MethodAttributes.SpecialName | Reflection.MethodAttributes.HideBySig; getSetAttributes |= propertyMemberAst.IsPublic ? Reflection.MethodAttributes.Public : Reflection.MethodAttributes.Private; - if (ShouldImplementProperty(propertyMemberAst.Name, type)) + MethodInfo implementingGetter = null; + MethodInfo implementingSetter = null; + if (ShouldImplementProperty(propertyMemberAst.Name, type, out PropertyInfo interfaceProperty)) { - getSetAttributes |= Reflection.MethodAttributes.Virtual; + if (propertyMemberAst.IsStatic) + { + implementingGetter = interfaceProperty.GetGetMethod(); + implementingSetter = interfaceProperty.GetSetMethod(); + } + else + { + getSetAttributes |= Reflection.MethodAttributes.Virtual; + } } if (propertyMemberAst.IsStatic) @@ -629,7 +651,7 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type getSetAttributes |= Reflection.MethodAttributes.Static; } // C# naming convention for backing fields. - string backingFieldName = string.Format(CultureInfo.InvariantCulture, "<{0}>k__BackingField", propertyMemberAst.Name); + string backingFieldName = string.Create(CultureInfo.InvariantCulture, $"<{propertyMemberAst.Name}>k__BackingField"); var backingField = _typeBuilder.DefineField(backingFieldName, type, backingFieldAttributes); bool hasValidateAttributes = false; @@ -666,6 +688,11 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type getIlGen.Emit(OpCodes.Ret); } + if (implementingGetter != null) + { + _typeBuilder.DefineMethodOverride(getMethod, implementingGetter); + } + // Define the "set" accessor method. MethodBuilder setMethod = _typeBuilder.DefineMethod(string.Concat("set_", propertyMemberAst.Name), getSetAttributes, null, new Type[] { type }); ILGenerator setIlGen = setMethod.GetILGenerator(); @@ -699,6 +726,11 @@ private PropertyBuilder EmitPropertyIl(PropertyMemberAst propertyMemberAst, Type setIlGen.Emit(OpCodes.Ret); + if (implementingSetter != null) + { + _typeBuilder.DefineMethodOverride(setMethod, implementingSetter); + } + // Map the two methods created above to our PropertyBuilder to // their corresponding behaviors, "get" and "set" respectively. property.SetGetMethod(getMethod); @@ -937,7 +969,7 @@ private void DefineMethodBody( Type returnType, Action parameterNameSetter) { - var wrapperFieldName = string.Format(CultureInfo.InvariantCulture, "<{0}>", metadataToken); + var wrapperFieldName = string.Create(CultureInfo.InvariantCulture, $"<{metadataToken}>"); var scriptBlockWrapperField = _staticHelpersTypeBuilder.DefineField(wrapperFieldName, typeof(ScriptBlockMemberMethodWrapper), FieldAttributes.Assembly | FieldAttributes.Static); @@ -1007,7 +1039,7 @@ private void DefineMethodBody( } } - private class DefineEnumHelper + private sealed class DefineEnumHelper { private readonly Parser _parser; private readonly TypeDefinitionAst _enumDefinitionAst; @@ -1082,7 +1114,7 @@ internal static List Sort(List defineEnumHel } // The expression may have multiple member expressions, e.g. [E]::e1 + [E]::e2 - foreach (var memberExpr in initExpr.FindAll(ast => ast is MemberExpressionAst, false)) + foreach (var memberExpr in initExpr.FindAll(static ast => ast is MemberExpressionAst, false)) { var typeExpr = ((MemberExpressionAst)memberExpr).Expression as TypeExpressionAst; if (typeExpr != null) @@ -1321,9 +1353,8 @@ internal static Assembly DefineTypes(Parser parser, Ast rootAst, TypeDefinitionA foreach (var typeDefinitionAst in typeDefinitions) { var typeName = GetClassNameInAssembly(typeDefinitionAst); - if (!definedTypes.Contains(typeName)) + if (definedTypes.Add(typeName)) { - definedTypes.Add(typeName); if ((typeDefinitionAst.TypeAttributes & TypeAttributes.Class) == TypeAttributes.Class) { defineTypeHelpers.Add(new DefineTypeHelper(parser, module, typeDefinitionAst, typeName)); @@ -1434,7 +1465,7 @@ private static string GetClassNameInAssembly(TypeDefinitionAst typeDefinitionAst nameParts.Reverse(); nameParts.Add(typeDefinitionAst.Name); - return string.Join(".", nameParts); + return string.Join('.', nameParts); } private static readonly OpCode[] s_ldc = @@ -1472,4 +1503,18 @@ private static void EmitLdarg(ILGenerator emitter, int c) } } } + + /// + /// The attribute for a PowerShell class to not affiliate with a particular Runspace\SessionState. + /// + [AttributeUsage(AttributeTargets.Class)] + public sealed class NoRunspaceAffinityAttribute : ParsingBaseAttribute + { + /// + /// Initializes a new instance of the attribute. + /// + public NoRunspaceAffinityAttribute() + { + } + } } diff --git a/src/System.Management.Automation/engine/parser/Parser.cs b/src/System.Management.Automation/engine/parser/Parser.cs index 5b8ca433454..1592d2e7e7d 100644 --- a/src/System.Management.Automation/engine/parser/Parser.cs +++ b/src/System.Management.Automation/engine/parser/Parser.cs @@ -9,6 +9,9 @@ using System.IO; using System.Linq; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; +using System.Management.Automation.Subsystem; +using System.Management.Automation.Subsystem.DSC; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading.Tasks; @@ -140,6 +143,8 @@ public static ScriptBlockAst ParseInput(string input, out Token[] tokens, out Pa /// The that represents the input script file. public static ScriptBlockAst ParseInput(string input, string fileName, out Token[] tokens, out ParseError[] errors) { + ArgumentNullException.ThrowIfNull(input); + Parser parser = new Parser(); List tokenList = new List(); ScriptBlockAst result; @@ -273,11 +278,10 @@ internal static ITypeName ScanType(string typename, bool ignoreErrors) var parser = new Parser(); var tokenizer = parser._tokenizer; tokenizer.Initialize(null, typename, null); - Token unused; - var result = parser.TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out unused); + var result = parser.TypeNameRule(allowAssemblyQualifiedNames: true, firstTypeNameToken: out _); SemanticChecks.CheckArrayTypeNameDepth(result, PositionUtilities.EmptyExtent, parser); - if (!ignoreErrors && parser.ErrorList.Count > 0) + if (!ignoreErrors && result is not null && (parser.ErrorList.Count > 0 || !result.Extent.Text.Equals(typename, StringComparison.OrdinalIgnoreCase))) { result = null; } @@ -437,8 +441,7 @@ private Token NextToken() private Token PeekToken() { Token token = _ungotToken ?? _tokenizer.NextToken(); - if (_ungotToken == null) - _ungotToken = token; + _ungotToken ??= token; return token; } @@ -717,12 +720,13 @@ internal static bool TryParseAsConstantHashtable(string input, out Hashtable res ParseError[] parseErrors; var ast = Parser.ParseInput(input, out throwAwayTokens, out parseErrors); - if ((ast == null) || - parseErrors.Length > 0 || - ast.BeginBlock != null || - ast.ProcessBlock != null || - ast.DynamicParamBlock != null || - ast.EndBlock.Traps != null) + if (ast == null + || parseErrors.Length > 0 + || ast.BeginBlock != null + || ast.ProcessBlock != null + || ast.CleanBlock != null + || ast.DynamicParamBlock != null + || ast.EndBlock.Traps != null) { return false; } @@ -816,10 +820,7 @@ private List UsingStatementsRule() SkipToken(); var statement = UsingStatementRule(token); SkipNewlinesAndSemicolons(); - if (result == null) - { - result = new List(); - } + result ??= new List(); var usingStatement = statement as UsingStatementAst; // otherwise returned statement is ErrorStatementAst. @@ -1346,11 +1347,11 @@ private ITypeName FinishTypeNameRule(Token typeName, bool unBracketedGenericArg case TokenKind.RBracket: case TokenKind.Comma: var elementType = new TypeName(typeName.Extent, typeName.Text); - return CompleteArrayTypeName(elementType, elementType, token); + return CompleteArrayTypeName(elementType, elementType, token, unBracketedGenericArg); case TokenKind.LBracket: case TokenKind.Identifier: - return GenericTypeArgumentsRule(typeName, token, unBracketedGenericArg); + return GenericTypeNameRule(typeName, token, unBracketedGenericArg); default: // ErrorRecovery: sync to ']', and return non-null to avoid cascading errors. @@ -1430,7 +1431,7 @@ private ITypeName GetSingleGenericArgument(Token firstToken) return typeName; } - private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstToken, bool unBracketedGenericArg) + private List GenericTypeArgumentsRule(Token firstToken, out Token lastToken) { Diagnostics.Assert(firstToken.Kind == TokenKind.Identifier || firstToken.Kind == TokenKind.LBracket, "unexpected first token"); RuntimeHelpers.EnsureSufficientExecutionStack(); @@ -1439,20 +1440,18 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok ITypeName typeName = GetSingleGenericArgument(firstToken); genericArguments.Add(typeName); - Token commaOrRBracketToken; - Token token; while (true) { SkipNewlines(); - commaOrRBracketToken = NextToken(); - if (commaOrRBracketToken.Kind != TokenKind.Comma) + lastToken = NextToken(); + if (lastToken.Kind != TokenKind.Comma) { break; } SkipNewlines(); - token = PeekToken(); + Token token = PeekToken(); if (token.Kind == TokenKind.Identifier || token.Kind == TokenKind.LBracket) { SkipToken(); @@ -1460,43 +1459,55 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok } else { - ReportIncompleteInput(After(commaOrRBracketToken), + ReportIncompleteInput( + After(lastToken), nameof(ParserStrings.MissingTypename), ParserStrings.MissingTypename); - typeName = new TypeName(commaOrRBracketToken.Extent, ":ErrorTypeName:"); + typeName = new TypeName(lastToken.Extent, ":ErrorTypeName:"); } genericArguments.Add(typeName); } - if (commaOrRBracketToken.Kind != TokenKind.RBracket) + return genericArguments; + } + + private ITypeName GenericTypeNameRule(Token genericTypeName, Token firstToken, bool unbracketedGenericArg) + { + List genericArguments = GenericTypeArgumentsRule(firstToken, out Token rBracketToken); + + if (rBracketToken.Kind != TokenKind.RBracket) { // ErrorRecovery: pretend we had the closing bracket and just continue on. - - UngetToken(commaOrRBracketToken); - ReportIncompleteInput(Before(commaOrRBracketToken), + UngetToken(rBracketToken); + ReportIncompleteInput( + Before(rBracketToken), nameof(ParserStrings.EndSquareBracketExpectedAtEndOfAttribute), ParserStrings.EndSquareBracketExpectedAtEndOfAttribute); - commaOrRBracketToken = null; + rBracketToken = null; } - var openGenericType = new TypeName(genericTypeName.Extent, genericTypeName.Text); - var result = new GenericTypeName(ExtentOf(genericTypeName.Extent, ExtentFromFirstOf(commaOrRBracketToken, genericArguments.LastOrDefault(), firstToken)), - openGenericType, genericArguments); - token = PeekToken(); + var openGenericType = new TypeName(genericTypeName.Extent, genericTypeName.Text, genericArguments.Count); + var result = new GenericTypeName( + ExtentOf(genericTypeName.Extent, ExtentFromFirstOf(rBracketToken, genericArguments.LastOrDefault(), firstToken)), + openGenericType, + genericArguments); + + Token token = PeekToken(); if (token.Kind == TokenKind.LBracket) { SkipToken(); - return CompleteArrayTypeName(result, openGenericType, NextToken()); + return CompleteArrayTypeName(result, openGenericType, NextToken(), unbracketedGenericArg); } - if (token.Kind == TokenKind.Comma && !unBracketedGenericArg) + if (token.Kind == TokenKind.Comma && !unbracketedGenericArg) { SkipToken(); string assemblyNameSpec = _tokenizer.GetAssemblyNameSpec(); if (string.IsNullOrEmpty(assemblyNameSpec)) { - ReportError(After(token), + ReportError( + After(token), nameof(ParserStrings.MissingAssemblyNameSpecification), ParserStrings.MissingAssemblyNameSpecification); } @@ -1509,7 +1520,7 @@ private ITypeName GenericTypeArgumentsRule(Token genericTypeName, Token firstTok return result; } - private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForAssemblyQualification, Token firstTokenAfterLBracket) + private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForAssemblyQualification, Token firstTokenAfterLBracket, bool unBracketedGenericArg) { while (true) { @@ -1527,6 +1538,25 @@ private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForA token = NextToken(); } while (token.Kind == TokenKind.Comma); + // The dimensions for an array must be less than or equal to 32. + // Search the doc for 'Type.MakeArrayType(int rank)' for more details. + if (dim > 32) + { + // If the next token is right bracket, we swallow it to make it easier to parse the rest of script. + // Otherwise, we unget the token for the subsequent parsing to consume. + if (token.Kind != TokenKind.RBracket) + { + UngetToken(token); + } + + ReportError( + ExtentOf(firstTokenAfterLBracket, lastComma), + nameof(ParserStrings.ArrayHasTooManyDimensions), + ParserStrings.ArrayHasTooManyDimensions, + arg: dim); + break; + } + if (token.Kind != TokenKind.RBracket) { // ErrorRecovery: just pretend we saw a ']'. @@ -1563,7 +1593,9 @@ private ITypeName CompleteArrayTypeName(ITypeName elementType, TypeName typeForA } token = PeekToken(); - if (token.Kind == TokenKind.Comma) + + // An array declared inside an unbracketed generic type argument cannot be assembly qualified + if (!unBracketedGenericArg && token.Kind == TokenKind.Comma) { SkipToken(); var assemblyName = _tokenizer.GetAssemblyNameSpec(); @@ -1706,9 +1738,9 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List NamedBlockAst beginBlock = null; NamedBlockAst processBlock = null; NamedBlockAst endBlock = null; - IScriptExtent startExtent = lCurly != null - ? lCurly.Extent - : paramBlockAst?.Extent; + NamedBlockAst cleanBlock = null; + + IScriptExtent startExtent = lCurly?.Extent ?? paramBlockAst?.Extent; IScriptExtent endExtent = null; IScriptExtent extent = null; IScriptExtent scriptBlockExtent = null; @@ -1750,13 +1782,11 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List case TokenKind.Begin: case TokenKind.Process: case TokenKind.End: + case TokenKind.Clean: break; } - if (startExtent == null) - { - startExtent = blockNameToken.Extent; - } + startExtent ??= blockNameToken.Extent; endExtent = blockNameToken.Extent; @@ -1790,6 +1820,10 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List { endBlock = new NamedBlockAst(extent, TokenKind.End, statementBlock, false); } + else if (blockNameToken.Kind == TokenKind.Clean && cleanBlock == null) + { + cleanBlock = new NamedBlockAst(extent, TokenKind.Clean, statementBlock, false); + } else if (blockNameToken.Kind == TokenKind.Dynamicparam && dynamicParamBlock == null) { dynamicParamBlock = new NamedBlockAst(extent, TokenKind.Dynamicparam, statementBlock, false); @@ -1811,7 +1845,14 @@ private ScriptBlockAst NamedBlockListRule(Token lCurly, List CompleteScriptBlockBody(lCurly, ref extent, out scriptBlockExtent); return_script_block_ast: - return new ScriptBlockAst(scriptBlockExtent, usingStatements, paramBlockAst, beginBlock, processBlock, endBlock, + return new ScriptBlockAst( + scriptBlockExtent, + usingStatements, + paramBlockAst, + beginBlock, + processBlock, + endBlock, + cleanBlock, dynamicParamBlock); } @@ -1886,10 +1927,7 @@ private IScriptExtent StatementListRule(List statements, List attr is not AttributeAst)) + foreach (var attr in attributes.Where(static attr => attr is not AttributeAst)) { ReportError(attr.Extent, nameof(ParserStrings.TypeNotAllowedBeforeStatement), @@ -2884,7 +2922,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom return null; } - if (configurationNameToken.Kind == TokenKind.EndOfInput) + if (configurationNameToken.Kind is TokenKind.EndOfInput or TokenKind.Comma) { UngetToken(configurationNameToken); @@ -2933,7 +2971,6 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom // Runspaces.Runspace localRunspace = null; bool topLevel = false; - bool useCrossPlatformSchema = false; try { // At this point, we'll need a runspace to use to hold the metadata for the parse. If there is no @@ -2947,13 +2984,34 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom Runspaces.Runspace.DefaultRunspace = localRunspace; } - // Configuration is not supported on ARM or in ConstrainedLanguage - if (PsUtils.IsRunningOnProcessorArchitectureARM() || Runspace.DefaultRunspace.ExecutionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) + // Configuration is not supported in ConstrainedLanguage + if (Runspace.DefaultRunspace?.ExecutionContext?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - ReportError(configurationToken.Extent, - nameof(ParserStrings.ConfigurationNotAllowedInConstrainedLanguage), - ParserStrings.ConfigurationNotAllowedInConstrainedLanguage, - configurationToken.Kind.Text()); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ReportError(configurationToken.Extent, + nameof(ParserStrings.ConfigurationNotAllowedInConstrainedLanguage), + ParserStrings.ConfigurationNotAllowedInConstrainedLanguage, + configurationToken.Kind.Text()); + return null; + } + + SystemPolicy.LogWDACAuditMessage( + context: Runspace.DefaultRunspace?.ExecutionContext, + title: ParserStrings.WDACParserConfigKeywordLogTitle, + message: ParserStrings.WDACParserConfigKeywordLogMessage, + fqid: "ConfigurationLanguageKeywordNotAllowed", + dropIntoDebugger: true); + } + + // Configuration is not supported for ARM or ARM64 process architecture. + if (PsUtils.IsRunningOnProcessArchitectureARM()) + { + ReportError( + configurationToken.Extent, + nameof(ParserStrings.ConfigurationNotAllowedOnArm64), + ParserStrings.ConfigurationNotAllowedOnArm64, + configurationToken.Kind.Text()); return null; } @@ -2996,38 +3054,13 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom { // Load the default CIM keywords Collection CIMKeywordErrors = new Collection(); - if (ExperimentalFeature.IsEnabled(Dsc.CrossPlatform.DscClassCache.DscExperimentalFeatureName)) - { - // In addition to checking if experimental feature is enabled - // also check if PSDesiredStateConfiguration is already loaded - // if pre-v3 is already loaded then use old mof-based APIs - // otherwise use json-based APIs - - p.AddCommand(new CmdletInfo("Get-Module", typeof(Microsoft.PowerShell.Commands.GetModuleCommand))); - p.AddParameter("Name", "PSDesiredStateConfiguration"); - - bool prev3IsLoaded = false; - foreach (PSModuleInfo moduleInfo in p.Invoke()) - { - if (moduleInfo.Version.Major < 3) - { - prev3IsLoaded = true; - break; - } - } - - p.Commands.Clear(); - - useCrossPlatformSchema = !prev3IsLoaded; - if (useCrossPlatformSchema) - { - Dsc.CrossPlatform.DscClassCache.LoadDefaultCimKeywords(CIMKeywordErrors); - } - else - { - Dsc.DscClassCache.LoadDefaultCimKeywords(CIMKeywordErrors); - } + // DscSubsystem is auto-registered when PSDesiredStateConfiguration v3 module is loaded + // so if DscSubsystem is registered that means user intention to use v3 APIs. + ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem(); + if (dscSubsystem != null) + { + dscSubsystem.LoadDefaultKeywords(CIMKeywordErrors); } else { @@ -3068,10 +3101,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom } finally { - if (p != null) - { - p.Dispose(); - } + p?.Dispose(); // // Put the parser back... @@ -3209,10 +3239,7 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom if (topLevel) { - if (_configurationKeywordsDefinedInThisFile == null) - { - _configurationKeywordsDefinedInThisFile = new Dictionary(); - } + _configurationKeywordsDefinedInThisFile ??= new Dictionary(); _configurationKeywordsDefinedInThisFile[keywordToAddForThisConfigurationStatement.Keyword] = keywordToAddForThisConfigurationStatement; } @@ -3274,9 +3301,10 @@ private StatementAst ConfigurationStatementRule(IEnumerable custom // Clear out all of the cached classes and keywords. // They will need to be reloaded when the generated function is actually run. // - if (useCrossPlatformSchema) + ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem(); + if (dscSubsystem != null) { - Dsc.CrossPlatform.DscClassCache.ClearCache(); + dscSubsystem.ClearCache(); } else { @@ -3566,10 +3594,7 @@ private StatementAst ForStatementRule(LabelToken labelToken, Token forToken) // ErrorRecovery: don't continue parsing the for statement. UngetToken(rParen); - if (endErrorStatement == null) - { - endErrorStatement = lParen.Extent; - } + endErrorStatement ??= lParen.Extent; ReportIncompleteInput(After(endErrorStatement), nameof(ParserStrings.MissingEndParenthesisAfterStatement), @@ -3878,10 +3903,7 @@ private StatementAst DynamicKeywordStatementRule(Token functionName, DynamicKeyw // we aren't expecting a name, we still do this so that the signature of the implementing function remains // the same. ExpressionAst originalInstanceName = instanceName; - if (instanceName == null) - { - instanceName = new StringConstantExpressionAst(nameToken.Extent, elementName, StringConstantType.BareWord); - } + instanceName ??= new StringConstantExpressionAst(nameToken.Extent, elementName, StringConstantType.BareWord); SkipNewlines(); @@ -4203,12 +4225,22 @@ private StatementAst ClassDefinitionRule(List customAttributes // PowerShell classes are not supported in ConstrainedLanguage if (Runspace.DefaultRunspace?.ExecutionContext?.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - ReportError(classToken.Extent, - nameof(ParserStrings.ClassesNotAllowedInConstrainedLanguage), - ParserStrings.ClassesNotAllowedInConstrainedLanguage, - classToken.Kind.Text()); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + ReportError(classToken.Extent, + nameof(ParserStrings.ClassesNotAllowedInConstrainedLanguage), + ParserStrings.ClassesNotAllowedInConstrainedLanguage, + classToken.Kind.Text()); - return null; + return null; + } + + SystemPolicy.LogWDACAuditMessage( + context: Runspace.DefaultRunspace?.ExecutionContext, + title: ParserStrings.WDACParserClassKeywordLogTitle, + message: ParserStrings.WDACParserClassKeywordLogMessage, + fqid: "ClassLanguageKeywordNotAllowed", + dropIntoDebugger: true); } SkipNewlines(); @@ -4241,11 +4273,10 @@ private StatementAst ClassDefinitionRule(List customAttributes this.SkipToken(); SkipNewlines(); ITypeName superClass; - Token unused; Token commaToken = null; while (true) { - superClass = this.TypeNameRule(allowAssemblyQualifiedNames: false, firstTypeNameToken: out unused); + superClass = this.TypeNameRule(allowAssemblyQualifiedNames: false, firstTypeNameToken: out _); if (superClass == null) { ReportIncompleteInput(After(ExtentFromFirstOf(commaToken, colonToken)), @@ -4299,10 +4330,7 @@ private StatementAst ClassDefinitionRule(List customAttributes if (astsOnError != null && astsOnError.Count > 0) { - if (nestedAsts == null) - { - nestedAsts = new List(); - } + nestedAsts ??= new List(); nestedAsts.AddRange(astsOnError); lastExtent = astsOnError.Last().Extent; @@ -4331,10 +4359,7 @@ private StatementAst ClassDefinitionRule(List customAttributes var classDefn = new TypeDefinitionAst(extent, name.Value, customAttributes?.OfType(), members, TypeAttributes.Class, superClassesList); if (customAttributes != null && customAttributes.OfType().Any()) { - if (nestedAsts == null) - { - nestedAsts = new List(); - } + nestedAsts ??= new List(); // no need to report error since the error is reported in method StatementRule nestedAsts.AddRange(customAttributes.OfType()); nestedAsts.Add(classDefn); @@ -4398,10 +4423,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) if (attribute != null) { lastAttribute = attribute; - if (startExtent == null) - { - startExtent = attribute.Extent; - } + startExtent ??= attribute.Extent; var attributeAst = attribute as AttributeAst; if (attributeAst != null) @@ -4421,10 +4443,7 @@ private MemberAst ClassMemberRule(string className, out List astsOnError) } token = PeekToken(); - if (startExtent == null) - { - startExtent = token.Extent; - } + startExtent ??= token.Extent; switch (token.Kind) { @@ -4639,10 +4658,7 @@ private static void RecordErrorAsts(Ast errAst, ref List astsOnError) return; } - if (astsOnError == null) - { - astsOnError = new List(); - } + astsOnError ??= new List(); astsOnError.Add(errAst); } @@ -4654,10 +4670,7 @@ private static void RecordErrorAsts(IEnumerable errAsts, ref List asts return; } - if (astsOnError == null) - { - astsOnError = new List(); - } + astsOnError ??= new List(); astsOnError.AddRange(errAsts); } @@ -4687,19 +4700,19 @@ private Token NextTypeIdentifierToken() private StatementAst EnumDefinitionRule(List customAttributes, Token enumToken) { - //G enum-statement: - //G 'enum' new-lines:opt enum-name '{' enum-member-list '}' - //G 'enum' new-lines:opt enum-name ':' enum-underlying-type '{' enum-member-list '}' - //G - //G enum-name: - //G simple-name - //G - //G enum-underlying-type: - //G new-lines:opt valid-type-name new-lines:opt - //G - //G enum-member-list: - //G enum-member new-lines:opt - //G enum-member-list enum-member + // G enum-statement: + // G 'enum' new-lines:opt enum-name '{' enum-member-list '}' + // G 'enum' new-lines:opt enum-name ':' enum-underlying-type '{' enum-member-list '}' + // G + // G enum-name: + // G simple-name + // G + // G enum-underlying-type: + // G new-lines:opt valid-type-name new-lines:opt + // G + // G enum-member-list: + // G enum-member new-lines:opt + // G enum-member-list enum-member const TypeCode ValidUnderlyingTypeCodes = TypeCode.Byte | TypeCode.Int16 | TypeCode.Int32 | TypeCode.Int64 | TypeCode.SByte | TypeCode.UInt16 | TypeCode.UInt32 | TypeCode.UInt64; @@ -4726,8 +4739,7 @@ private StatementAst EnumDefinitionRule(List customAttributes, this.SkipToken(); SkipNewlines(); ITypeName underlyingType; - Token unused; - underlyingType = this.TypeNameRule(allowAssemblyQualifiedNames: false, firstTypeNameToken: out unused); + underlyingType = this.TypeNameRule(allowAssemblyQualifiedNames: false, firstTypeNameToken: out _); if (underlyingType == null) { ReportIncompleteInput( @@ -4996,7 +5008,7 @@ private StatementAst UsingStatementRule(Token usingToken) SkipToken(); var aliasToken = NextToken(); - if (aliasToken.Kind == TokenKind.EndOfInput) + if (aliasToken.Kind is TokenKind.EndOfInput or TokenKind.NewLine or TokenKind.Semi) { UngetToken(aliasToken); ReportIncompleteInput(After(equalsToken), @@ -5005,6 +5017,12 @@ private StatementAst UsingStatementRule(Token usingToken) return new ErrorStatementAst(ExtentOf(usingToken, equalsToken)); } + if (aliasToken.Kind == TokenKind.Comma) + { + ReportError(aliasToken.Extent, nameof(ParserStrings.UnexpectedUnaryOperator), ParserStrings.UnexpectedUnaryOperator, aliasToken.Text); + return new ErrorStatementAst(ExtentOf(usingToken, aliasToken)); + } + var aliasAst = GetCommandArgument(CommandArgumentContext.CommandArgument, aliasToken); if (kind == UsingStatementKind.Module && aliasAst is HashtableAst) { @@ -5012,7 +5030,19 @@ private StatementAst UsingStatementRule(Token usingToken) } else if (aliasAst is not StringConstantExpressionAst) { - return new ErrorStatementAst(ExtentOf(usingToken, aliasAst), new Ast[] { itemAst, aliasAst }); + var errorExtent = ExtentFromFirstOf(aliasAst, aliasToken); + Ast[] nestedAsts; + if (aliasAst is null) + { + nestedAsts = new Ast[] { itemAst }; + } + else + { + nestedAsts = new Ast[] { itemAst, aliasAst }; + } + + ReportError(errorExtent, nameof(ParserStrings.InvalidValueForUsingItemName), ParserStrings.InvalidValueForUsingItemName, errorExtent.Text); + return new ErrorStatementAst(ExtentOf(usingToken, errorExtent), nestedAsts); } RequireStatementTerminator(); @@ -5114,15 +5144,8 @@ private StringConstantExpressionAst ResolveUsingAssembly(StringConstantExpressio workingDirectory = Path.GetDirectoryName(scriptFileName); } - assemblyFileName = workingDirectory + @"\" + assemblyFileName; + assemblyFileName = Path.Combine(workingDirectory, assemblyFileName); } - -#if !CORECLR - if (!File.Exists(assemblyFileName)) - { - GlobalAssemblyCache.ResolvePartialName(assemblyName, out assemblyFileName); - } -#endif } catch { @@ -5202,7 +5225,7 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class SkipToken(); // we don't allow syntax // : base{ script } - // as a short for for + // as a short for // : base( { script } ) baseCtorCallParams = InvokeParamParenListRule(lParen, out baseCallLastExtent); this.SkipNewlines(); @@ -5229,11 +5252,9 @@ private StatementAst MethodDeclarationRule(Token functionNameToken, string class SetTokenizerMode(oldTokenizerMode); } - if (baseCtorCallParams == null) - { + baseCtorCallParams ??= // Assuming implicit default ctor - baseCtorCallParams = new List(); - } + new List(); } Token lCurly = NextToken(); @@ -5522,10 +5543,7 @@ private CatchClauseAst CatchBlockRule(ref IScriptExtent endErrorStatement, ref L break; } - if (exceptionTypes == null) - { - exceptionTypes = new List(); - } + exceptionTypes ??= new List(); exceptionTypes.Add(typeConstraintAst); @@ -5766,7 +5784,7 @@ private PipelineBaseAst PipelineChainRule() // just look for pipelines as before. RuntimeHelpers.EnsureSufficientExecutionStack(); - // First look for assignment, since PipelineRule once handled that and this supercedes that. + // First look for assignment, since PipelineRule once handled that and this supersedes that. // We may end up with an expression here as a result, // in which case we hang on to it to pass it into the first pipeline rule call. Token assignToken = null; @@ -6028,10 +6046,7 @@ private PipelineBaseAst PipelineRule( { SkipToken(); - if (redirections == null) - { - redirections = new RedirectionAst[CommandBaseAst.MaxRedirections]; - } + redirections ??= new RedirectionAst[CommandBaseAst.MaxRedirections]; IScriptExtent unused = null; lastRedirection = RedirectionRule(redirectionToken, redirections, ref unused); @@ -6043,7 +6058,7 @@ private PipelineBaseAst PipelineRule( commandAst = new CommandExpressionAst( exprExtent, expr, - redirections?.Where(r => r != null)); + redirections?.Where(static r => r != null)); } else { @@ -6052,10 +6067,7 @@ private PipelineBaseAst PipelineRule( if (commandAst != null) { - if (startExtent == null) - { - startExtent = commandAst.Extent; - } + startExtent ??= commandAst.Extent; pipelineElements.Add(commandAst); } @@ -6408,10 +6420,7 @@ private ExpressionAst GetCommandArgument(CommandArgumentContext context, Token t } commaToken = token; - if (commandArgs == null) - { - commandArgs = new List(); - } + commandArgs ??= new List(); commandArgs.Add(exprAst); @@ -6579,10 +6588,7 @@ internal Ast CommandRule(bool forDynamicKeyword) case TokenKind.RedirectInStd: if ((context & CommandArgumentContext.CommandName) == 0) { - if (redirections == null) - { - redirections = new RedirectionAst[CommandBaseAst.MaxRedirections]; - } + redirections ??= new RedirectionAst[CommandBaseAst.MaxRedirections]; RedirectionRule((RedirectionToken)token, redirections, ref endExtent); } @@ -6674,7 +6680,7 @@ internal Ast CommandRule(bool forDynamicKeyword) return new CommandAst(ExtentOf(firstToken, endExtent), elements, dotSource || ampersand ? firstToken.Kind : TokenKind.Unknown, - redirections?.Where(r => r != null)); + redirections?.Where(static r => r != null)); } #endregion Pipelines @@ -6721,7 +6727,7 @@ private ExpressionAst ExpressionRule(bool endNumberOnTernaryOpChars = false) SkipToken(); SkipNewlines(); - // We have seen the ternary operator '?' and now expecting the 'IfFalse' expression. + // We have seen the ternary operator '?' and now expecting the 'IfTrue' expression. ExpressionAst ifTrue = ExpressionRule(endNumberOnTernaryOpChars: true); if (ifTrue == null) { @@ -7148,7 +7154,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false ParserStrings.UnexpectedAttribute, lastAttribute.TypeName.FullName); - return new ErrorExpressionAst(ExtentOf(token, lastAttribute)); + return new ErrorExpressionAst(ExtentOf(token, lastAttribute), attributes); } expr = new AttributedExpressionAst(ExtentOf(lastAttribute, child), lastAttribute, child); @@ -7184,10 +7190,7 @@ private ExpressionAst UnaryExpressionRule(bool endNumberOnTernaryOpChars = false } } - if (expr == null) - { - expr = new TypeExpressionAst(lastAttribute.Extent, lastAttribute.TypeName); - } + expr ??= new TypeExpressionAst(lastAttribute.Extent, lastAttribute.TypeName); } for (int i = attributes.Count - 2; i >= 0; --i) @@ -7733,34 +7736,128 @@ private ExpressionAst MemberAccessRule(ExpressionAst targetExpr, Token operatorT member = GetSingleCommandArgument(CommandArgumentContext.CommandArgument) ?? new ErrorExpressionAst(ExtentOf(targetExpr, operatorToken)); } - else + else if (_ungotToken == null) { + // Member name may be an incomplete token like `$a.$(Command-Name`, in which case, '_ungotToken != null'. + // We do not look for generic args or invocation token if the member name token is recognisably incomplete. + int resyncIndex = _tokenizer.GetRestorePoint(); + List genericTypeArguments = GenericMethodArgumentsRule(resyncIndex, out Token rBracket); Token lParen = NextInvokeMemberToken(); + if (lParen != null) { + // When we reach here, we either had a legit section of generic arguments (in which case, `rBracket` + // won't be null), or we saw `lParen` directly following the member token (in which case, `rBracket` + // will be null). + int endColumnNumber = rBracket is null ? member.Extent.EndColumnNumber : rBracket.Extent.EndColumnNumber; + Diagnostics.Assert(lParen.Kind == TokenKind.LParen || lParen.Kind == TokenKind.LCurly, "token kind incorrect"); - Diagnostics.Assert(member.Extent.EndColumnNumber == lParen.Extent.StartColumnNumber, - "member and paren must be adjacent"); - return MemberInvokeRule(targetExpr, lParen, operatorToken, member); + Diagnostics.Assert( + endColumnNumber == lParen.Extent.StartColumnNumber, + "member and paren must be adjacent when the method is not generic"); + return MemberInvokeRule(targetExpr, lParen, operatorToken, member, genericTypeArguments); + } + else if (rBracket != null) + { + // We had a legit section of generic arguments but no 'lParen' following that, so this is not a method + // invocation, but an invalid indexing operation. Resync the tokenizer back to before the generic arg + // parsing and then continue. + Resync(resyncIndex); } } return new MemberExpressionAst( - ExtentOf(targetExpr, member), - targetExpr, - member, - @static: operatorToken.Kind == TokenKind.ColonColon, - nullConditional: operatorToken.Kind == TokenKind.QuestionDot); + ExtentOf(targetExpr, member), + targetExpr, + member, + @static: operatorToken.Kind == TokenKind.ColonColon, + nullConditional: operatorToken.Kind == TokenKind.QuestionDot); } - private ExpressionAst MemberInvokeRule(ExpressionAst targetExpr, Token lBracket, Token operatorToken, CommandElementAst member) + private List GenericMethodArgumentsRule(int resyncIndex, out Token rBracketToken) + { + List genericTypes = null; + + Token lBracket = NextToken(); + rBracketToken = null; + + if (lBracket.Kind != TokenKind.LBracket) + { + // We cannot avoid this Resync(); if we use PeekToken() to try to avoid a Resync(), the method called + // after this [`NextInvokeMemberToken()` or `NextMemberAccessToken()`] will note that an _ungotToken + // is present and assume an error state. That will cause any property accesses or non-generic method + // calls to throw a parse error. + Resync(resyncIndex); + return null; + } + + // This is either a InvokeMember expression with generic type arguments, or some sort of collection index + // on a property. + TokenizerMode oldTokenizerMode = _tokenizer.Mode; + try + { + // Switch to typename mode to avoid aggressive argument tokenization. + SetTokenizerMode(TokenizerMode.TypeName); + + SkipNewlines(); + Token firstToken = NextToken(); + + // For method generic arguments, we only support the syntax `$var.Method[TypeName1 <, TypeName2 ...>]`, + // not the syntax `$var.Method[[TypeName1] <, [TypeName2] ...>]`. + // The latter syntax has been supported for type expression since the beginning, but it's ambiguous in + // this scenario because we could be looking at an indexing operation on a property like: + // `$var.Property[]` + // and the `` could start with a type expression like `[TypeName]::Method()`, or even just + // a single type expression acting as a key to a hashtable property. Such cases will cause ambiguities. + // + // It could be possible to write code that sorts out the ambiguity and continue to support the latter + // syntax for method generic arguments, and thus to allow assembly-qualified type names. But we choose + // not to do so because: + // 1. that will definitely increase the complexity of the parsing code and also make it fragile; + // 2. the latter syntax hurts readability a lot due to the number of opening/closing brackets. + // The downside is that the assembly-qualified type names won't be supported for method generic args, + // but that's likely not a problem in practice, and we can revisit if it turns out otherwise. + if (firstToken.Kind == TokenKind.Identifier) + { + resyncIndex = -1; + genericTypes = GenericTypeArgumentsRule(firstToken, out rBracketToken); + + if (rBracketToken.Kind != TokenKind.RBracket) + { + UngetToken(rBracketToken); + ReportIncompleteInput( + Before(rBracketToken), + nameof(ParserStrings.EndSquareBracketExpectedAtEndOfType), + ParserStrings.EndSquareBracketExpectedAtEndOfType); + rBracketToken = null; + } + } + } + finally + { + SetTokenizerMode(oldTokenizerMode); + + if (resyncIndex > 0) + { + Resync(resyncIndex); + } + } + + return genericTypes; + } + + private ExpressionAst MemberInvokeRule( + ExpressionAst targetExpr, + Token lBracket, + Token operatorToken, + CommandElementAst member, + IList genericTypes) { // G invocation-expression: target-expression passed as a parameter. lBracket can be '(' or '{'. // G target-expression member-name invoke-param-list // G invoke-param-list: // G '(' invoke-param-paren-list // G script-block - IScriptExtent lastExtent = null; List arguments; @@ -7771,6 +7868,7 @@ private ExpressionAst MemberInvokeRule(ExpressionAst targetExpr, Token lBracket, else { arguments = new List(); + // handle the construct $x.methodName{2+2} as through it had been written $x.methodName({2+2}) SkipNewlines(); ExpressionAst argument = ScriptBlockExpressionRule(lBracket); @@ -7784,7 +7882,8 @@ private ExpressionAst MemberInvokeRule(ExpressionAst targetExpr, Token lBracket, member, arguments, operatorToken.Kind == TokenKind.ColonColon, - operatorToken.Kind == TokenKind.QuestionDot); + operatorToken.Kind == TokenKind.QuestionDot, + genericTypes); } private List InvokeParamParenListRule(Token lParen, out IScriptExtent lastExtent) @@ -7874,7 +7973,18 @@ private ExpressionAst ElementAccessRule(ExpressionAst primaryExpression, Token l // G primary-expression '[' new-lines:opt expression new-lines:opt ']' SkipNewlines(); - ExpressionAst indexExpr = ExpressionRule(); + bool oldDisableCommaOperator = _disableCommaOperator; + _disableCommaOperator = false; + ExpressionAst indexExpr = null; + try + { + indexExpr = ExpressionRule(); + } + finally + { + _disableCommaOperator = oldDisableCommaOperator; + } + if (indexExpr == null) { // ErrorRecovery: hope we see a closing bracket. If we don't, we'll pretend we saw @@ -7979,7 +8089,7 @@ private static void AssertErrorIdCorrespondsToMsgString(string errorId, string e } } - Diagnostics.Assert(msgCorrespondsToString, string.Format("Parser error ID \"{0}\" must correspond to the error message \"{1}\"", errorId, errorMsg)); + Diagnostics.Assert(msgCorrespondsToString, $"Parser error ID \"{errorId}\" must correspond to the error message \"{errorMsg}\""); } private static object[] arrayOfOneArg diff --git a/src/System.Management.Automation/engine/parser/Position.cs b/src/System.Management.Automation/engine/parser/Position.cs index 54f4c3eccbe..9e1363e4a53 100644 --- a/src/System.Management.Automation/engine/parser/Position.cs +++ b/src/System.Management.Automation/engine/parser/Position.cs @@ -15,12 +15,13 @@ namespace System.Management.Automation.Language /// /// Represents a single point in a script. The script may come from a file or interactive input. /// +#nullable enable public interface IScriptPosition { /// /// The name of the file, or if the script did not come from a file, then null. /// - string File { get; } + string? File { get; } /// /// The line number of the position, with the value 1 being the first line. @@ -45,8 +46,9 @@ public interface IScriptPosition /// /// The complete script that this position is included in. /// - string GetFullScript(); + string? GetFullScript(); } +#nullable restore /// /// Represents the a span of text in a script. @@ -336,10 +338,7 @@ internal static bool IsAfter(this IScriptExtent extentToTest, IScriptExtent endE internal static bool IsWithin(this IScriptExtent extentToTest, IScriptExtent extent) { - return extentToTest.StartLineNumber >= extent.StartLineNumber && - extentToTest.EndLineNumber <= extent.EndLineNumber && - extentToTest.StartColumnNumber >= extent.StartColumnNumber && - extentToTest.EndColumnNumber <= extent.EndColumnNumber; + return extentToTest.StartOffset >= extent.StartOffset && extentToTest.EndOffset <= extent.EndOffset; } internal static bool IsAfter(this IScriptExtent extent, int line, int column) @@ -354,10 +353,18 @@ internal static bool ContainsLineAndColumn(this IScriptExtent extent, int line, { if (extent.StartLineNumber == line) { - if (column == 0) return true; + if (column == 0) + { + return true; + } + if (column >= extent.StartColumnNumber) { - if (extent.EndLineNumber != extent.StartLineNumber) return true; + if (extent.EndLineNumber != extent.StartLineNumber) + { + return true; + } + return (column < extent.EndColumnNumber); } @@ -764,9 +771,9 @@ public string Text _endPosition.ColumnNumber - _startPosition.ColumnNumber); } - return string.Format(CultureInfo.InvariantCulture, "{0}...{1}", - _startPosition.Line.Substring(_startPosition.ColumnNumber), - _endPosition.Line.Substring(0, _endPosition.ColumnNumber)); + var start = _startPosition.Line.AsSpan(_startPosition.ColumnNumber); + var end = _endPosition.Line.AsSpan(0, _endPosition.ColumnNumber); + return string.Create(CultureInfo.InvariantCulture, $"{start}...{end}"); } else { diff --git a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs index 33b2fadec64..675e53394c6 100644 --- a/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs +++ b/src/System.Management.Automation/engine/parser/PreOrderVisitor.cs @@ -6,7 +6,7 @@ namespace System.Management.Automation.Language { /// - /// Each Visit* method in returns one of these values to control + /// Each Visit* method in returns one of these values to control /// how visiting nodes in the AST should proceed. /// public enum AstVisitAction @@ -37,10 +37,7 @@ public abstract class AstVisitor internal AstVisitAction CheckForPostAction(Ast ast, AstVisitAction action) { var postActionHandler = this as IAstPostVisitHandler; - if (postActionHandler != null) - { - postActionHandler.PostVisit(ast); - } + postActionHandler?.PostVisit(ast); return action; } diff --git a/src/System.Management.Automation/engine/parser/SafeValues.cs b/src/System.Management.Automation/engine/parser/SafeValues.cs index a727ae1d287..38181168a66 100644 --- a/src/System.Management.Automation/engine/parser/SafeValues.cs +++ b/src/System.Management.Automation/engine/parser/SafeValues.cs @@ -47,11 +47,15 @@ public static bool IsAstSafe(Ast ast, GetSafeValueVisitor.SafeValueContext safeV internal IsSafeValueVisitor(GetSafeValueVisitor.SafeValueContext safeValueContext) { _safeValueContext = safeValueContext; + + bool skipSizeCheck = safeValueContext is GetSafeValueVisitor.SafeValueContext.SkipHashtableSizeCheck; + _maxVisitCount = skipSizeCheck ? uint.MaxValue : 5000; + _maxHashtableKeyCount = skipSizeCheck ? int.MaxValue : 500; } internal bool IsAstSafe(Ast ast) { - if ((bool)ast.Accept(this) && _visitCount < MaxVisitCount) + if ((bool)ast.Accept(this) && _visitCount < _maxVisitCount) { return true; } @@ -65,8 +69,8 @@ internal bool IsAstSafe(Ast ast) // This is a check of the number of visits private uint _visitCount = 0; - private const uint MaxVisitCount = 5000; - private const int MaxHashtableKeyCount = 500; + private readonly uint _maxVisitCount; + private readonly int _maxHashtableKeyCount; // Used to determine if we are being called within a GetPowerShell() context, // which does some additional security verification outside of the scope of @@ -330,7 +334,7 @@ public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) public object VisitHashtable(HashtableAst hashtableAst) { - if (hashtableAst.KeyValuePairs.Count > MaxHashtableKeyCount) + if (hashtableAst.KeyValuePairs.Count > _maxHashtableKeyCount) { return false; } @@ -356,7 +360,7 @@ public object VisitParenExpression(ParenExpressionAst parenExpressionAst) * except in the case of handling the unary operator * ExecutionContext is provided to ensure we can resolve variables */ - internal class GetSafeValueVisitor : ICustomAstVisitor2 + internal sealed class GetSafeValueVisitor : ICustomAstVisitor2 { internal enum SafeValueContext { @@ -373,7 +377,7 @@ public static object GetSafeValue(Ast ast, ExecutionContext context, SafeValueCo { t_context = context; - if (safeValueContext == SafeValueContext.SkipHashtableSizeCheck || IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) + if (IsSafeValueVisitor.IsAstSafe(ast, safeValueContext)) { return ast.Accept(new GetSafeValueVisitor()); } @@ -530,7 +534,8 @@ public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) // Get the value of the index and value and call the compiler var index = indexExpressionAst.Index.Accept(this); var target = indexExpressionAst.Target.Accept(this); - if (index == null || target == null) + + if (index is null || target is null) { throw new ArgumentNullException(nameof(indexExpressionAst)); } @@ -548,10 +553,7 @@ public object VisitExpandableStringExpression(ExpandableStringExpressionAst expa ofs = t_context.SessionState.PSVariable.GetValue("OFS") as string; } - if (ofs == null) - { - ofs = " "; - } + ofs ??= " "; for (int offset = 0; offset < safeValues.Length; offset++) { diff --git a/src/System.Management.Automation/engine/parser/SemanticChecks.cs b/src/System.Management.Automation/engine/parser/SemanticChecks.cs index 3afd10ff6e2..4a2a3bb626c 100644 --- a/src/System.Management.Automation/engine/parser/SemanticChecks.cs +++ b/src/System.Management.Automation/engine/parser/SemanticChecks.cs @@ -5,17 +5,20 @@ using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Linq; -using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; +using System.Text.RegularExpressions; using Microsoft.PowerShell; +using System.Management.Automation.Security; +using System.Management.Automation.Subsystem; +using System.Management.Automation.Subsystem.DSC; using Microsoft.PowerShell.DesiredStateConfiguration.Internal; namespace System.Management.Automation.Language { - internal class SemanticChecks : AstVisitor2, IAstPostVisitHandler + internal sealed partial class SemanticChecks : AstVisitor2, IAstPostVisitHandler { private readonly Parser _parser; @@ -87,20 +90,16 @@ private void CheckForDuplicateParameters(ReadOnlyCollection parame foreach (var parameter in parameters) { string parameterName = parameter.Name.VariablePath.UserPath; - if (parametersSet.Contains(parameterName)) + if (!parametersSet.Add(parameterName)) { _parser.ReportError(parameter.Name.Extent, nameof(ParserStrings.DuplicateFormalParameter), ParserStrings.DuplicateFormalParameter, parameterName); } - else - { - parametersSet.Add(parameterName); - } var voidConstraint = - parameter.Attributes.OfType().FirstOrDefault(t => typeof(void) == t.TypeName.GetReflectionType()); + parameter.Attributes.OfType().FirstOrDefault(static t => typeof(void) == t.TypeName.GetReflectionType()); if (voidConstraint != null) { @@ -239,7 +238,7 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) foreach (var namedArg in attributeAst.NamedArguments) { string name = namedArg.ArgumentName; - if (names.Contains(name)) + if (!names.Add(name)) { _parser.ReportError(namedArg.Extent, nameof(ParserStrings.DuplicateNamedArgument), @@ -248,8 +247,6 @@ public override AstVisitAction VisitAttribute(AttributeAst attributeAst) } else { - names.Add(name); - if (!namedArg.ExpressionOmitted && !IsValidAttributeArgument(namedArg.Argument, constantValueVisitor)) { var error = GetNonConstantAttributeArgErrorExpr(constantValueVisitor); @@ -404,10 +401,11 @@ public override AstVisitAction VisitFunctionMember(FunctionMemberAst functionMem ParserStrings.ParamBlockNotAllowedInMethod); } - if (body.BeginBlock != null || - body.ProcessBlock != null || - body.DynamicParamBlock != null || - !body.EndBlock.Unnamed) + if (body.BeginBlock != null + || body.ProcessBlock != null + || body.CleanBlock != null + || body.DynamicParamBlock != null + || !body.EndBlock.Unnamed) { _parser.ReportError(Parser.ExtentFromFirstOf(body.DynamicParamBlock, body.BeginBlock, body.ProcessBlock, body.EndBlock), nameof(ParserStrings.NamedBlockNotAllowedInMethod), @@ -530,7 +528,10 @@ public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEach public override AstVisitAction VisitTryStatement(TryStatementAst tryStatementAst) { - if (tryStatementAst.CatchClauses.Count <= 1) return AstVisitAction.Continue; + if (tryStatementAst.CatchClauses.Count <= 1) + { + return AstVisitAction.Continue; + } for (int i = 0; i < tryStatementAst.CatchClauses.Count - 1; ++i) { @@ -547,7 +548,10 @@ public override AstVisitAction VisitTryStatement(TryStatementAst tryStatementAst break; } - if (block2.IsCatchAll) continue; + if (block2.IsCatchAll) + { + continue; + } foreach (TypeConstraintAst typeLiteral1 in block1.CatchTypes) { @@ -917,6 +921,13 @@ public override AstVisitAction VisitConvertExpression(ConvertExpressionAst conve ParserStrings.OrderedAttributeOnlyOnHashLiteralNode, convertExpressionAst.Type.TypeName.FullName); } + + // Currently, the type name '[ordered]' is handled specially in PowerShell. + // When used in a conversion expression, it's only allowed on a hashliteral node, and it's + // always interpreted as an initializer for a case-insensitive + // 'System.Collections.Specialized.OrderedDictionary' by the compiler. + // So, we can return early from here. + return AstVisitAction.Continue; } if (typeof(PSReference) == convertExpressionAst.Type.TypeName.GetReflectionType()) @@ -1017,7 +1028,7 @@ public override AstVisitAction VisitUsingExpression(UsingExpressionAst usingExpr return AstVisitAction.Continue; } - private ExpressionAst CheckUsingExpression(ExpressionAst exprAst) + private static ExpressionAst CheckUsingExpression(ExpressionAst exprAst) { RuntimeHelpers.EnsureSufficientExecutionStack(); if (exprAst is VariableExpressionAst) @@ -1107,7 +1118,7 @@ public override AstVisitAction VisitHashtable(HashtableAst hashtableAst) if (keyStrAst != null) { var keyStr = keyStrAst.Value.ToString(); - if (keys.Contains(keyStr)) + if (!keys.Add(keyStr)) { string errorId; string errorMsg; @@ -1124,10 +1135,6 @@ public override AstVisitAction VisitHashtable(HashtableAst hashtableAst) _parser.ReportError(entry.Item1.Extent, errorId, errorMsg, keyStr); } - else - { - keys.Add(keyStr); - } } } @@ -1303,20 +1310,50 @@ public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionA public override AstVisitAction VisitUsingStatement(UsingStatementAst usingStatementAst) { - bool usingKindSupported = usingStatementAst.UsingStatementKind == UsingStatementKind.Namespace || - usingStatementAst.UsingStatementKind == UsingStatementKind.Assembly || - usingStatementAst.UsingStatementKind == UsingStatementKind.Module; - if (!usingKindSupported || - usingStatementAst.Alias != null) + UsingStatementKind kind = usingStatementAst.UsingStatementKind; + bool usingKindSupported = kind is UsingStatementKind.Namespace or UsingStatementKind.Assembly or UsingStatementKind.Module; + if (!usingKindSupported || usingStatementAst.Alias != null) { - _parser.ReportError(usingStatementAst.Extent, + _parser.ReportError( + usingStatementAst.Extent, nameof(ParserStrings.UsingStatementNotSupported), ParserStrings.UsingStatementNotSupported); } + if (kind is UsingStatementKind.Namespace) + { + Regex nsPattern = NamespacePattern(); + if (!nsPattern.IsMatch(usingStatementAst.Name.Value)) + { + _parser.ReportError( + usingStatementAst.Name.Extent, + nameof(ParserStrings.InvalidNamespaceValue), + ParserStrings.InvalidNamespaceValue); + } + } + return AstVisitAction.Continue; } + /// + /// This regular expression is for validating if a namespace string is valid. + /// + /// In C#, a legit namespace is defined as `identifier ('.' identifier)*` [see https://learn.microsoft.com/dotnet/csharp/language-reference/language-specification/namespaces#143-namespace-declarations]. + /// And `identifier` is defined in https://learn.microsoft.com/dotnet/csharp/fundamentals/coding-style/identifier-names#naming-rules, summarized below: + /// - Identifiers must start with a letter or underscore (_). + /// - Identifiers can contain + /// * Unicode letter characters (categories: Lu, Ll, Lt, Lm, Lo or Nl); + /// * decimal digit characters (category: Nd); + /// * Unicode connecting characters (category: Pc); + /// * Unicode combining characters (categories: Mn, Mc); + /// * Unicode formatting characters (category: Cf). + /// + /// For details about how Unicode categories are represented in regular expression, see the "Unicode Categories" section in the following article: + /// - https://www.regular-expressions.info/unicode.html + /// + [GeneratedRegex(@"^[\p{L}\p{Nl}_][\p{L}\p{Nl}\p{Nd}\p{Pc}\p{Mn}\p{Mc}\p{Cf}_]*(?:\.[\p{L}\p{Nl}_][\p{L}\p{Nl}\p{Nd}\p{Pc}\p{Mn}\p{Mc}\p{Cf}_]*)*$")] + private static partial Regex NamespacePattern(); + public override AstVisitAction VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) { // @@ -1386,7 +1423,7 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem else if (!keyword.Properties.ContainsKey(propName.Value)) { IOrderedEnumerable tableKeys = keyword.Properties.Keys - .OrderBy(key => key, StringComparer.OrdinalIgnoreCase); + .Order(StringComparer.OrdinalIgnoreCase); _parser.ReportError(propName.Extent, nameof(ParserStrings.InvalidInstanceProperty), @@ -1405,7 +1442,10 @@ public override AstVisitAction VisitDynamicKeywordStatement(DynamicKeywordStatem { StringConstantExpressionAst nameAst = dynamicKeywordStatementAst.CommandElements[0] as StringConstantExpressionAst; Diagnostics.Assert(nameAst != null, "nameAst should never be null"); - if (!DscClassCache.SystemResourceNames.Contains(nameAst.Extent.Text.Trim())) + var extentText = nameAst.Extent.Text.Trim(); + ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem(); + var extentTextIsASystemResourceName = (dscSubsystem != null) ? dscSubsystem.IsSystemResourceName(extentText) : DscClassCache.SystemResourceNames.Contains(extentText); + if (!extentTextIsASystemResourceName) { if (configAst.ConfigurationType == ConfigurationType.Meta && !dynamicKeywordStatementAst.Keyword.IsMetaDSCResource()) { @@ -1676,7 +1716,11 @@ private static void CheckGet(Parser parser, FunctionMemberAst functionMemberAst, /// True if it is a Test method with qualified return type and signature; otherwise, false. private static void CheckTest(FunctionMemberAst functionMemberAst, ref bool hasTest) { - if (hasTest) return; + if (hasTest) + { + return; + } + hasTest = (functionMemberAst.Name.Equals("Test", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0 && functionMemberAst.ReturnType != null && @@ -1689,7 +1733,11 @@ private static void CheckTest(FunctionMemberAst functionMemberAst, ref bool hasT /// True if it is a Set method with qualified return type and signature; otherwise, false. private static void CheckSet(FunctionMemberAst functionMemberAst, ref bool hasSet) { - if (hasSet) return; + if (hasSet) + { + return; + } + hasSet = (functionMemberAst.Name.Equals("Set", StringComparison.OrdinalIgnoreCase) && functionMemberAst.Parameters.Count == 0 && functionMemberAst.IsReturnTypeVoid()); @@ -1805,11 +1853,21 @@ internal static void CheckDataStatementLanguageModeAtRuntime(DataStatementAst da // we only need to check the language mode. if (executionContext.LanguageMode == PSLanguageMode.ConstrainedLanguage) { - var parser = new Parser(); - parser.ReportError(dataStatementAst.CommandsAllowed[0].Extent, - nameof(ParserStrings.DataSectionAllowedCommandDisallowed), - ParserStrings.DataSectionAllowedCommandDisallowed); - throw new ParseException(parser.ErrorList.ToArray()); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + var parser = new Parser(); + parser.ReportError(dataStatementAst.CommandsAllowed[0].Extent, + nameof(ParserStrings.DataSectionAllowedCommandDisallowed), + ParserStrings.DataSectionAllowedCommandDisallowed); + throw new ParseException(parser.ErrorList.ToArray()); + } + + SystemPolicy.LogWDACAuditMessage( + context: executionContext, + title: ParserStrings.WDACParserDSSupportedCommandLogTitle, + message: ParserStrings.WDACParserDSSupportedCommandLogMessage, + fqid: "SupportedCommandInDataSectionNotSupported", + dropIntoDebugger: true); } } diff --git a/src/System.Management.Automation/engine/parser/SymbolResolver.cs b/src/System.Management.Automation/engine/parser/SymbolResolver.cs index 2da38a4ed06..097bcabac3b 100644 --- a/src/System.Management.Automation/engine/parser/SymbolResolver.cs +++ b/src/System.Management.Automation/engine/parser/SymbolResolver.cs @@ -111,11 +111,8 @@ internal void AddTypeFromUsingModule(Parser parser, TypeDefinitionAst typeDefini TypeLookupResult result; if (_typeTable.TryGetValue(typeDefinitionAst.Name, out result)) { - if (result.ExternalNamespaces != null) - { - // override external type by the type defined in the current namespace - result.ExternalNamespaces.Add(moduleInfo.Name); - } + // override external type by the type defined in the current namespace + result.ExternalNamespaces?.Add(moduleInfo.Name); } else { @@ -179,7 +176,7 @@ internal void AddTypesInScope(Ast ast) // class C1 { [C2]$x } // class C2 { [C1]$c1 } - var types = ast.FindAll(x => x is TypeDefinitionAst, searchNestedScriptBlocks: false); + var types = ast.FindAll(static x => x is TypeDefinitionAst, searchNestedScriptBlocks: false); foreach (var type in types) { AddType((TypeDefinitionAst)type); @@ -275,7 +272,7 @@ public bool IsInMethodScope() } } - internal class SymbolResolver : AstVisitor2, IAstPostVisitHandler + internal sealed class SymbolResolver : AstVisitor2, IAstPostVisitHandler { private readonly SymbolResolvePostActionVisitor _symbolResolvePostActionVisitor; internal readonly SymbolTable _symbolTable; @@ -302,7 +299,7 @@ private static PowerShell UsingStatementResolvePowerShell InitialSessionState iss = InitialSessionState.Create(); iss.Commands.Add(new SessionStateCmdletEntry("Get-Module", typeof(GetModuleCommand), null)); var sessionStateProviderEntry = new SessionStateProviderEntry(FileSystemProvider.ProviderName, typeof(FileSystemProvider), null); - var snapin = PSSnapInReader.ReadEnginePSSnapIns().FirstOrDefault(snapIn => snapIn.Name.Equals("Microsoft.PowerShell.Core", StringComparison.OrdinalIgnoreCase)); + var snapin = PSSnapInReader.ReadEnginePSSnapIns().FirstOrDefault(static snapIn => snapIn.Name.Equals("Microsoft.PowerShell.Core", StringComparison.OrdinalIgnoreCase)); sessionStateProviderEntry.SetPSSnapIn(snapin); iss.Providers.Add(sessionStateProviderEntry); t_usingStatementResolvePowerShell = PowerShell.Create(iss); @@ -407,7 +404,7 @@ public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst a var typeAst = _symbolTable.GetCurrentTypeDefinitionAst(); Diagnostics.Assert(typeAst != null, "Method scopes can exist only inside type definitions."); - string typeString = string.Format(CultureInfo.InvariantCulture, "[{0}]::", typeAst.Name); + string typeString = string.Create(CultureInfo.InvariantCulture, $"[{typeAst.Name}]::"); _parser.ReportError(variableExpressionAst.Extent, nameof(ParserStrings.MissingTypeInStaticPropertyAssignment), ParserStrings.MissingTypeInStaticPropertyAssignment, diff --git a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs index 45f278b6b5a..a7744ac6411 100644 --- a/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs +++ b/src/System.Management.Automation/engine/parser/TypeInferenceVisitor.cs @@ -150,6 +150,8 @@ public TypeInferenceContext(PowerShell powerShell) public TypeDefinitionAst CurrentTypeDefinitionAst { get; set; } + public HashSet AnalyzedCommands { get; } = new HashSet(); + public TypeInferenceRuntimePermissions RuntimePermissions { get; set; } internal PowerShellExecutionHelper Helper { get; } @@ -195,7 +197,25 @@ internal IList GetMembersByInferredType(PSTypeName typename, bool isStat // Look in the type table first. if (!isStatic) { - var consolidatedString = new ConsolidatedString(new[] { typename.Name }); + // The Ciminstance type adapter adds the full typename with and without a namespace to the list of type names. + // So if we see one with a full typename we need to also get the types for the short version. + // For example: "CimInstance#root/standardcimv2/MSFT_NetFirewallRule" and "CimInstance#MSFT_NetFirewallRule" + int namespaceSeparator = typename.Name.LastIndexOf('/'); + ConsolidatedString consolidatedString; + if (namespaceSeparator != -1 + && typename.Name.StartsWith("Microsoft.Management.Infrastructure.CimInstance#", StringComparison.OrdinalIgnoreCase)) + { + consolidatedString = new ConsolidatedString(new[] + { + typename.Name, + string.Concat("Microsoft.Management.Infrastructure.CimInstance#", typename.Name.AsSpan(namespaceSeparator + 1)) + }); + } + else + { + consolidatedString = new ConsolidatedString(new[] { typename.Name }); + } + results.AddRange(ExecutionContext.TypeTable.GetMembers(consolidatedString)); } @@ -298,7 +318,7 @@ internal void AddMembersByInferredTypeDefinitionAst( else { var functionMember = (FunctionMemberAst)member; - add = functionMember.IsStatic == isStatic; + add = (functionMember.IsConstructor && isStatic) || (!functionMember.IsConstructor && functionMember.IsStatic == isStatic); foundConstructor |= functionMember.IsConstructor; } @@ -322,7 +342,18 @@ internal void AddMembersByInferredTypeDefinitionAst( } var baseTypeDefinitionAst = baseTypeName._typeDefinitionAst; - results.AddRange(GetMembersByInferredType(new PSTypeName(baseTypeDefinitionAst), isStatic, filterToCall)); + if (baseTypeDefinitionAst is null) + { + var baseReflectionType = baseTypeName.GetReflectionType(); + if (baseReflectionType is not null) + { + results.AddRange(GetMembersByInferredType(new PSTypeName(baseReflectionType), isStatic, filterToCall)); + } + } + else + { + results.AddRange(GetMembersByInferredType(new PSTypeName(baseTypeDefinitionAst), isStatic, filterToCall)); + } } // Add stuff from our base class System.Object. @@ -353,7 +384,22 @@ internal void AddMembersByInferredTypeDefinitionAst( filterToCall = filter; } - results.AddRange(GetMembersByInferredType(new PSTypeName(typeof(object)), isStatic, filterToCall)); + PSTypeName baseMembersType; + if (typename.TypeDefinitionAst.IsEnum) + { + if (!isStatic) + { + results.Add(new PSInferredProperty("value__", new PSTypeName(typeof(int)))); + } + + baseMembersType = new PSTypeName(typeof(Enum)); + } + else + { + baseMembersType = new PSTypeName(typeof(object)); + } + + results.AddRange(GetMembersByInferredType(baseMembersType, isStatic, filterToCall)); } internal void AddMembersByInferredTypeCimType(PSTypeName typename, List results, Func filterToCall) @@ -416,7 +462,29 @@ private static bool TryGetRepresentativeTypeNameFromValue(object value, out PSTy value = PSObject.Base(value); if (value != null) { - type = new PSTypeName(value.GetType()); + var typeObject = value.GetType(); + + if (typeObject.FullName.Equals("System.Management.Automation.PSObject", StringComparison.Ordinal)) + { + var psobjectPropertyList = new List(); + foreach (var property in ((PSObject)value).Properties) + { + if (property.IsHidden) + { + continue; + } + + var propertyTypeName = new PSTypeName(property.TypeNameOfValue); + psobjectPropertyList.Add(new PSMemberNameAndType(property.Name, propertyTypeName, property.Value)); + } + + type = PSSyntheticTypeName.Create(typeObject, psobjectPropertyList); + } + else + { + type = new PSTypeName(typeObject); + } + return true; } } @@ -536,11 +604,24 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) if (hashtableAst.KeyValuePairs.Count > 0) { var properties = new List(); + void AddInferredTypes(Ast ast, string keyName) + { + bool foundAnyTypes = false; + foreach (PSTypeName item in InferTypes(ast)) + { + foundAnyTypes = true; + properties.Add(new PSMemberNameAndType(keyName, item)); + } + + if (!foundAnyTypes) + { + properties.Add(new PSMemberNameAndType(keyName, new PSTypeName("System.Object"))); + } + } foreach (var kv in hashtableAst.KeyValuePairs) { string name = null; - string typeName = null; if (kv.Item1 is StringConstantExpressionAst stringConstantExpressionAst) { name = stringConstantExpressionAst.Value; @@ -554,32 +635,33 @@ object ICustomAstVisitor.VisitHashtable(HashtableAst hashtableAst) name = nameValue.ToString(); } - if (name != null) + if (name is not null) { - object value = null; if (kv.Item2 is PipelineAst pipelineAst && pipelineAst.GetPureExpression() is ExpressionAst expression) { - switch (expression) + object value; + if (expression is ConstantExpressionAst constant) { - case ConstantExpressionAst constantExpression: - value = constantExpression.Value; - break; - default: - typeName = InferTypes(kv.Item2).FirstOrDefault()?.Name; - if (typeName == null) - { - if (SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out object safeValue)) - { - value = safeValue; - } - } + value = constant.Value; + } + else + { + _ = SafeExprEvaluator.TrySafeEval(expression, _context.ExecutionContext, out value); + } - break; + if (value is null) + { + AddInferredTypes(expression, name); + continue; } - } - var pstypeName = value != null ? new PSTypeName(value.GetType()) : new PSTypeName(typeName ?? "System.Object"); - properties.Add(new PSMemberNameAndType(name, pstypeName, value)); + PSTypeName valueType = new(value.GetType()); + properties.Add(new PSMemberNameAndType(name, valueType, value)); + } + else + { + AddInferredTypes(kv.Item2, name); + } } } @@ -638,7 +720,176 @@ object ICustomAstVisitor.VisitMergingRedirection(MergingRedirectionAst mergingRe object ICustomAstVisitor.VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { - return InferTypes(binaryExpressionAst.Left); + switch (binaryExpressionAst.Operator) + { + case TokenKind.And: + case TokenKind.Ccontains: + case TokenKind.Cin: + case TokenKind.Cnotcontains: + case TokenKind.Cnotin: + case TokenKind.Icontains: + case TokenKind.Iin: + case TokenKind.Inotcontains: + case TokenKind.Inotin: + case TokenKind.Is: + case TokenKind.IsNot: + case TokenKind.Or: + case TokenKind.Xor: + // Always returns a bool + return BinaryExpressionAst.BoolTypeNameArray; + + case TokenKind.As: + // TODO: Handle other kinds of expressions on the right side. + if (binaryExpressionAst.Right is TypeExpressionAst typeExpression) + { + var type = typeExpression.TypeName.GetReflectionType(); + var psTypeName = type != null ? new PSTypeName(type) : new PSTypeName(typeExpression.TypeName.FullName); + return new[] { psTypeName }; + } + break; + + case TokenKind.Ceq: + case TokenKind.Cge: + case TokenKind.Cgt: + case TokenKind.Cle: + case TokenKind.Clike: + case TokenKind.Clt: + case TokenKind.Cmatch: + case TokenKind.Cne: + case TokenKind.Cnotlike: + case TokenKind.Cnotmatch: + case TokenKind.Ieq: + case TokenKind.Ige: + case TokenKind.Igt: + case TokenKind.Ile: + case TokenKind.Ilike: + case TokenKind.Ilt: + case TokenKind.Imatch: + case TokenKind.Ine: + case TokenKind.Inotlike: + case TokenKind.Inotmatch: + // Returns a bool or filtered output from the left hand side if it's enumerable + var comparisonOutput = new List() { new(typeof(bool)) }; + comparisonOutput.AddRange(InferTypes(binaryExpressionAst.Left)); + return comparisonOutput; + + case TokenKind.Creplace: + case TokenKind.Format: + case TokenKind.Ireplace: + case TokenKind.Join: + // Always returns a string + return BinaryExpressionAst.StringTypeNameArray; + + case TokenKind.Csplit: + case TokenKind.Isplit: + // Always returns a string array + return BinaryExpressionAst.StringArrayTypeNameArray; + + case TokenKind.QuestionQuestion: + // Can return left or right hand side + var nullCoalescingOutput = InferTypes(binaryExpressionAst.Left).ToList(); + nullCoalescingOutput.AddRange(InferTypes(binaryExpressionAst.Right)); + return nullCoalescingOutput.Distinct(); + + default: + break; + } + + List lhsTypes = InferTypes(binaryExpressionAst.Left).ToList(); + if (lhsTypes.Count == 0) + { + return lhsTypes; + } + + string methodName; + switch (binaryExpressionAst.Operator) + { + case TokenKind.Divide: + methodName = "op_Division"; + break; + + case TokenKind.Minus: + methodName = "op_Subtraction"; + break; + + case TokenKind.Multiply: + methodName = "op_Multiply"; + break; + + case TokenKind.Plus: + methodName = "op_Addition"; + break; + + case TokenKind.Rem: + methodName = "op_Modulus"; + break; + + case TokenKind.Shl: + methodName = "op_LeftShift"; + break; + + case TokenKind.Shr: + methodName = "op_RightShift"; + break; + + default: + return lhsTypes; + } + + List rhsTypes = InferTypes(binaryExpressionAst.Right).ToList(); + HashSet addedReturnTypes = new HashSet(); + List result = new List(); + foreach (PSTypeName lType in lhsTypes) + { + if (lType.Type is null) + { + continue; + } + + foreach (MethodInfo method in lType.Type.GetMethods(BindingFlags.Public | BindingFlags.Static)) + { + if (!method.Name.Equals(methodName, StringComparison.Ordinal)) + { + continue; + } + + if (rhsTypes.Count == 0) + { + if (addedReturnTypes.Add(method.ReturnType.FullName)) + { + result.Add(new PSTypeName(method.ReturnType)); + } + + continue; + } + + ParameterInfo[] methodParams = method.GetParameters(); + if (methodParams.Length != 2) + { + continue; + } + + foreach (PSTypeName rType in rhsTypes) + { + if (rType.Type is not null && rType.Type.IsAssignableTo(methodParams[1].ParameterType)) + { + if (addedReturnTypes.Add(method.ReturnType.FullName)) + { + result.Add(new PSTypeName(method.ReturnType)); + } + + break; + } + } + } + } + + if (result.Count == 0) + { + result.AddRange(lhsTypes); + } + + return result; } object ICustomAstVisitor.VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) @@ -655,6 +906,11 @@ object ICustomAstVisitor.VisitConvertExpression(ConvertExpressionAst convertExpr // [PSObject] @{ Key = "Value" } and the [PSCustomObject] @{ Key = "Value" } case. var type = convertExpressionAst.Type.TypeName.GetReflectionType(); + if (type is null && convertExpressionAst.Type.TypeName is TypeName unavailableType && unavailableType._typeDefinitionAst is not null) + { + return new[] { new PSTypeName(unavailableType._typeDefinitionAst) }; + } + if (type == typeof(PSObject) && convertExpressionAst.Child is HashtableAst hashtableAst) { if (InferTypes(hashtableAst).FirstOrDefault() is PSSyntheticTypeName syntheticTypeName) @@ -686,19 +942,28 @@ object ICustomAstVisitor.VisitSubExpression(SubExpressionAst subExpressionAst) object ICustomAstVisitor.VisitErrorStatement(ErrorStatementAst errorStatementAst) { var inferredTypes = new List(); - foreach (var ast in errorStatementAst.Conditions) + if (errorStatementAst.Conditions is not null) { - inferredTypes.AddRange(InferTypes(ast)); + foreach (var ast in errorStatementAst.Conditions) + { + inferredTypes.AddRange(InferTypes(ast)); + } } - foreach (var ast in errorStatementAst.Bodies) + if (errorStatementAst.Bodies is not null) { - inferredTypes.AddRange(InferTypes(ast)); + foreach (var ast in errorStatementAst.Bodies) + { + inferredTypes.AddRange(InferTypes(ast)); + } } - foreach (var ast in errorStatementAst.NestedAst) + if (errorStatementAst.NestedAst is not null) { - inferredTypes.AddRange(InferTypes(ast)); + foreach (var ast in errorStatementAst.NestedAst) + { + inferredTypes.AddRange(InferTypes(ast)); + } } return inferredTypes; @@ -749,9 +1014,20 @@ object ICustomAstVisitor.VisitParamBlock(ParamBlockAst paramBlockAst) object ICustomAstVisitor.VisitNamedBlock(NamedBlockAst namedBlockAst) { var inferredTypes = new List(); - for (var index = 0; index < namedBlockAst.Statements.Count; index++) + for (int index = 0; index < namedBlockAst.Statements.Count; index++) { - var ast = namedBlockAst.Statements[index]; + StatementAst ast = namedBlockAst.Statements[index]; + if (ast is AssignmentStatementAst + || (ast is PipelineAst pipe && pipe.PipelineElements.Count == 1 && pipe.PipelineElements[0] is CommandExpressionAst cmd + && cmd.Redirections.Count == 0 && cmd.Expression is UnaryExpressionAst unary + && unary.TokenKind is TokenKind.PostfixPlusPlus or TokenKind.PlusPlus or TokenKind.PostfixMinusMinus or TokenKind.MinusMinus)) + { + // Assignments don't output anything to the named block unless they are wrapped in parentheses. + // When they are wrapped in parentheses, they are seen as PipelineAst. + // Increment/decrement operators like $i++ also don't output anything unless there's a redirection, or they are wrapped in parentheses. + continue; + } + inferredTypes.AddRange(InferTypes(ast)); } @@ -820,8 +1096,19 @@ object ICustomAstVisitor.VisitFunctionDefinition(FunctionDefinitionAst functionD object ICustomAstVisitor.VisitStatementBlock(StatementBlockAst statementBlockAst) { var inferredTypes = new List(); - foreach (var ast in statementBlockAst.Statements) + foreach (StatementAst ast in statementBlockAst.Statements) { + if (ast is AssignmentStatementAst + || (ast is PipelineAst pipe && pipe.PipelineElements.Count == 1 && pipe.PipelineElements[0] is CommandExpressionAst cmd + && cmd.Redirections.Count == 0 && cmd.Expression is UnaryExpressionAst unary + && unary.TokenKind is TokenKind.PostfixPlusPlus or TokenKind.PlusPlus or TokenKind.PostfixMinusMinus or TokenKind.MinusMinus)) + { + // Assignments don't output anything to the statement block unless they are wrapped in parentheses. + // When they are wrapped in parentheses, they are seen as PipelineAst. + // Increment operators like $i++ also don't output anything unless there's a redirection, or they are wrapped in parentheses. + continue; + } + inferredTypes.AddRange(InferTypes(ast)); } @@ -929,6 +1216,11 @@ object ICustomAstVisitor.VisitContinueStatement(ContinueStatementAst continueSta object ICustomAstVisitor.VisitReturnStatement(ReturnStatementAst returnStatementAst) { + if (returnStatementAst.Pipeline is null) + { + return TypeInferenceContext.EmptyPSTypeNameArray; + } + return returnStatementAst.Pipeline.Accept(this); } @@ -949,7 +1241,18 @@ object ICustomAstVisitor.VisitDoUntilStatement(DoUntilStatementAst doUntilStatem object ICustomAstVisitor.VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { - return assignmentStatementAst.Left.Accept(this); + ExpressionAst child = assignmentStatementAst.Left; + while (child is AttributedExpressionAst attributeChild) + { + if (attributeChild is ConvertExpressionAst convert) + { + return new List() { new(convert.Type.TypeName) }; + } + + child = attributeChild.Child; + } + + return assignmentStatementAst.Right.Accept(this); } object ICustomAstVisitor.VisitPipeline(PipelineAst pipelineAst) @@ -980,13 +1283,111 @@ object ICustomAstVisitor.VisitFileRedirection(FileRedirectionAst fileRedirection return TypeInferenceContext.EmptyPSTypeNameArray; } - private void InferTypesFrom(CommandAst commandAst, List inferredTypes) + private void InferTypesFrom(CommandAst commandAst, List inferredTypes, bool forRedirection = false) { + if (commandAst.Redirections.Count > 0) + { + var mergedStreams = new HashSet(); + bool allStreamsMerged = false; + foreach (RedirectionAst streamRedirection in commandAst.Redirections) + { + if (streamRedirection is FileRedirectionAst fileRedirection) + { + if (!forRedirection && fileRedirection.FromStream is RedirectionStream.All or RedirectionStream.Output) + { + // command output is redirected so it returns nothing. + return; + } + } + else if (streamRedirection is MergingRedirectionAst mergeRedirection && mergeRedirection.ToStream == RedirectionStream.Output) + { + if (mergeRedirection.FromStream == RedirectionStream.All) + { + allStreamsMerged = true; + continue; + } + + _ = mergedStreams.Add(mergeRedirection.FromStream); + } + } + + if (allStreamsMerged) + { + inferredTypes.Add(new PSTypeName(typeof(ErrorRecord))); + inferredTypes.Add(new PSTypeName(typeof(WarningRecord))); + inferredTypes.Add(new PSTypeName(typeof(VerboseRecord))); + inferredTypes.Add(new PSTypeName(typeof(DebugRecord))); + inferredTypes.Add(new PSTypeName(typeof(InformationRecord))); + } + else + { + foreach (RedirectionStream value in mergedStreams) + { + switch (value) + { + case RedirectionStream.Error: + inferredTypes.Add(new PSTypeName(typeof(ErrorRecord))); + break; + + case RedirectionStream.Warning: + inferredTypes.Add(new PSTypeName(typeof(WarningRecord))); + break; + + case RedirectionStream.Verbose: + inferredTypes.Add(new PSTypeName(typeof(VerboseRecord))); + break; + + case RedirectionStream.Debug: + inferredTypes.Add(new PSTypeName(typeof(DebugRecord))); + break; + + case RedirectionStream.Information: + inferredTypes.Add(new PSTypeName(typeof(InformationRecord))); + break; + + default: + break; + } + } + } + } + + if (commandAst.CommandElements[0] is ScriptBlockExpressionAst scriptBlock) + { + // An anonymous function like: & {"Do Something"} + inferredTypes.AddRange(InferTypes(scriptBlock.ScriptBlock)); + return; + } + PseudoBindingInfo pseudoBinding = new PseudoParameterBinder() .DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ParameterCompletion); - if (pseudoBinding?.CommandInfo == null) + if (pseudoBinding?.CommandInfo is null) { + var commandName = commandAst.GetCommandName(); + if (string.IsNullOrEmpty(commandName)) + { + return; + } + + try + { + var foundCommand = CommandDiscovery.LookupCommandInfo( + commandName, + CommandTypes.Application, + SearchResolutionOptions.ResolveLiteralThenPathPatterns, + CommandOrigin.Internal, + _context.ExecutionContext); + + // There's no way to know whether or not an application outputs anything + // but when they do, PowerShell will treat it as string data. + inferredTypes.Add(new PSTypeName(typeof(string))); + } + catch + { + // The command wasn't found so we can't infer anything. + } + return; } @@ -1023,10 +1424,40 @@ private void InferTypesFrom(CommandAst commandAst, List inferredType inferredTypes.AddRange(inferTypesFromObjectCmdlets); return; } + + if (cmdletInfo.ImplementingType.FullName.EqualsOrdinalIgnoreCase("Microsoft.PowerShell.Commands.GetRandomCommand") + && pseudoBinding.BoundArguments.TryGetValue("InputObject", out var value)) + { + if (value.ParameterArgumentType == AstParameterArgumentType.PipeObject) + { + InferTypesFromPreviousCommand(commandAst, inferredTypes); + } + else if (value.ParameterArgumentType == AstParameterArgumentType.AstPair) + { + inferredTypes.AddRange(InferTypes(((AstPair)value).Argument)); + } + + return; + } + } + + if ((commandInfo.OutputType.Count == 0 + || (commandInfo.OutputType.Count == 1 + && (commandInfo.OutputType[0].Name.EqualsOrdinalIgnoreCase(typeof(PSObject).FullName) + || commandInfo.OutputType[0].Name.EqualsOrdinalIgnoreCase(typeof(object).FullName)))) + && commandInfo is IScriptCommandInfo scriptCommandInfo + && scriptCommandInfo.ScriptBlock.Ast is IParameterMetadataProvider scriptBlockWithParams + && _context.AnalyzedCommands.Add(scriptBlockWithParams)) + { + // This is a function without an output type defined (or it's too generic to be useful) + // We can analyze the code inside the function to find out what it actually outputs + // The purpose of the hashset is to avoid infinite loops with functions that call themselves. + inferredTypes.AddRange(InferTypes(scriptBlockWithParams.Body)); + return; } // The OutputType property ignores the parameter set specified in the OutputTypeAttribute. - // With psuedo-binding, we actually know the candidate parameter sets, so we could take + // With pseudo-binding, we actually know the candidate parameter sets, so we could take // advantage of it here, but I opted for the simpler code because so few cmdlets use // ParameterSetName in OutputType and of the ones I know about, it isn't that useful. inferredTypes.AddRange(commandInfo.OutputType); @@ -1177,7 +1608,7 @@ private void InferTypesFromGroupCommand(PseudoBindingInfo pseudoBinding, Command properties = new[] { stringConstant.Value }; break; case ArrayLiteralAst arrayLiteral: - properties = arrayLiteral.Elements.OfType().Select(c => c.Value).ToArray(); + properties = arrayLiteral.Elements.OfType().Select(static c => c.Value).ToArray(); scriptBlockProperty = arrayLiteral.Elements.OfType().Any(); break; case CommandElementAst _: @@ -1281,7 +1712,7 @@ private void InferTypesFromPreviousCommand(CommandAst commandAst, List 0) { - inferredTypes.AddRange(InferTypes(parentPipeline.PipelineElements[i - 1])); + inferredTypes.AddRange(GetInferredEnumeratedTypes(InferTypes(parentPipeline.PipelineElements[i - 1]))); } } } @@ -1292,7 +1723,7 @@ void InferFromSelectProperties(AstParameterArgumentPair astParameterArgumentPair { if (astParameterArgumentPair is AstPair astPair) { - object ToWildCardOrString(string value) => WildcardPattern.ContainsWildcardCharacters(value) ? (object)new WildcardPattern(value) : value; + static object ToWildCardOrString(string value) => WildcardPattern.ContainsWildcardCharacters(value) ? (object)new WildcardPattern(value) : value; object[] properties = null; switch (astPair.Argument) { @@ -1300,7 +1731,7 @@ void InferFromSelectProperties(AstParameterArgumentPair astParameterArgumentPair properties = new[] { ToWildCardOrString(stringConstant.Value) }; break; case ArrayLiteralAst arrayLiteral: - properties = arrayLiteral.Elements.OfType().Select(c => ToWildCardOrString(c.Value)).ToArray(); + properties = arrayLiteral.Elements.OfType().Select(static c => ToWildCardOrString(c.Value)).ToArray(); break; } @@ -1494,8 +1925,16 @@ private IEnumerable InferTypesFrom(MemberExpressionAst memberExpress return Array.Empty(); } + bool isInvokeMemberExpressionAst = false; var res = new List(10); - bool isInvokeMemberExpressionAst = memberExpressionAst is InvokeMemberExpressionAst; + IList genericTypeArguments = null; + + if (memberExpressionAst is InvokeMemberExpressionAst invokeMemberExpression) + { + isInvokeMemberExpressionAst = true; + genericTypeArguments = invokeMemberExpression.GenericTypeArguments; + } + var maybeWantDefaultCtor = isStatic && isInvokeMemberExpressionAst && memberAsStringConst.Value.EqualsOrdinalIgnoreCase("new"); @@ -1505,14 +1944,14 @@ private IEnumerable InferTypesFrom(MemberExpressionAst memberExpress var memberNameList = new List { memberAsStringConst.Value }; foreach (var type in exprType) { - if (type.Type == typeof(PSObject)) + if (type.Type == typeof(PSObject) && type is not PSSyntheticTypeName) { continue; } var members = _context.GetMembersByInferredType(type, isStatic, filter: null); - AddTypesOfMembers(type, memberNameList, members, ref maybeWantDefaultCtor, isInvokeMemberExpressionAst, res); + AddTypesOfMembers(type, memberNameList, members, ref maybeWantDefaultCtor, isInvokeMemberExpressionAst, genericTypeArguments, res); // We didn't find any constructors but they used [T]::new() syntax if (maybeWantDefaultCtor) @@ -1524,6 +1963,36 @@ private IEnumerable InferTypesFrom(MemberExpressionAst memberExpress return res; } + private static IEnumerable InferTypeFromRef(InvokeMemberExpressionAst invokeMember, ExpressionAst refArgument) + { + Type expressionClrType = (invokeMember.Expression as TypeExpressionAst)?.TypeName.GetReflectionType(); + string memberName = (invokeMember.Member as StringConstantExpressionAst)?.Value; + int argumentIndex = invokeMember.Arguments.IndexOf(refArgument); + if (expressionClrType is null || string.IsNullOrEmpty(memberName) || argumentIndex == -1) + { + yield break; + } + + foreach (MemberInfo memberInfo in expressionClrType.GetMember(memberName)) + { + if (memberInfo.MemberType == MemberTypes.Method) + { + var methodInfo = memberInfo as MethodInfo; + ParameterInfo[] methodParams = methodInfo.GetParameters(); + if (methodParams.Length < argumentIndex) + { + continue; + } + + ParameterInfo paramCandidate = methodParams[argumentIndex]; + if (paramCandidate.IsOut) + { + yield return new PSTypeName(paramCandidate.ParameterType.GetElementType()); + } + } + } + } + private void GetTypesOfMembers( PSTypeName thisType, string memberName, @@ -1533,7 +2002,7 @@ private void GetTypesOfMembers( List inferredTypes) { var memberNamesToCheck = new List { memberName }; - AddTypesOfMembers(thisType, memberNamesToCheck, members, ref maybeWantDefaultCtor, isInvokeMemberExpressionAst, inferredTypes); + AddTypesOfMembers(thisType, memberNamesToCheck, members, ref maybeWantDefaultCtor, isInvokeMemberExpressionAst, genericTypeArguments: null, inferredTypes); } private void AddTypesOfMembers( @@ -1542,6 +2011,7 @@ private void AddTypesOfMembers( IList members, ref bool maybeWantDefaultCtor, bool isInvokeMemberExpressionAst, + IList genericTypeArguments, List result) { for (int i = 0; i < memberNamesToCheck.Count; i++) @@ -1549,7 +2019,7 @@ private void AddTypesOfMembers( string memberNameToCheck = memberNamesToCheck[i]; foreach (var member in members) { - if (TryGetTypeFromMember(currentType, member, memberNameToCheck, ref maybeWantDefaultCtor, isInvokeMemberExpressionAst, result, memberNamesToCheck)) + if (TryGetTypeFromMember(currentType, member, memberNameToCheck, ref maybeWantDefaultCtor, isInvokeMemberExpressionAst, genericTypeArguments, result, memberNamesToCheck)) { break; } @@ -1563,6 +2033,7 @@ private bool TryGetTypeFromMember( string memberName, ref bool maybeWantDefaultCtor, bool isInvokeMemberExpressionAst, + IList genericTypeArguments, List result, List memberNamesToCheck) { @@ -1588,7 +2059,7 @@ private bool TryGetTypeFromMember( if (methodCacheEntry[0].method.Name.Equals(memberName, StringComparison.OrdinalIgnoreCase)) { maybeWantDefaultCtor = false; - AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); + AddTypesFromMethodCacheEntry(methodCacheEntry, genericTypeArguments, result, isInvokeMemberExpressionAst); return true; } @@ -1637,7 +2108,7 @@ private bool TryGetTypeFromMember( case PSMethod m: if (m.adapterData is DotNetAdapter.MethodCacheEntry methodCacheEntry) { - AddTypesFromMethodCacheEntry(methodCacheEntry, result, isInvokeMemberExpressionAst); + AddTypesFromMethodCacheEntry(methodCacheEntry, genericTypeArguments, result, isInvokeMemberExpressionAst); return true; } @@ -1701,21 +2172,63 @@ private bool TryGetTypeFromMember( private static void AddTypesFromMethodCacheEntry( DotNetAdapter.MethodCacheEntry methodCacheEntry, + IList genericTypeArguments, List result, bool isInvokeMemberExpressionAst) { if (isInvokeMemberExpressionAst) { - foreach (var method in methodCacheEntry.methodInformationStructures) + Type[] resolvedTypeArguments = null; + if (genericTypeArguments is not null) { - if (method.method is MethodInfo methodInfo && !methodInfo.ReturnType.ContainsGenericParameters) + resolvedTypeArguments = new Type[genericTypeArguments.Count]; + for (int i = 0; i < genericTypeArguments.Count; i++) { - result.Add(new PSTypeName(methodInfo.ReturnType)); + Type resolvedType = genericTypeArguments[i].GetReflectionType(); + if (resolvedType is null) + { + // If any generic type argument cannot be resolved yet, + // we simply assume this information is unavailable. + resolvedTypeArguments = null; + break; + } + + resolvedTypeArguments[i] = resolvedType; } } - return; - } + var tempResult = new HashSet(StringComparer.OrdinalIgnoreCase) { "System.Void" }; + foreach (var method in methodCacheEntry.methodInformationStructures) + { + if (method.method is MethodInfo methodInfo) + { + Type retType = null; + if (!methodInfo.ReturnType.ContainsGenericParameters) + { + retType = methodInfo.ReturnType; + } + else if (resolvedTypeArguments is not null) + { + try + { + retType = methodInfo.MakeGenericMethod(resolvedTypeArguments).ReturnType; + } + catch + { + // If we can't build the generic method then just skip it to retain other completion results. + continue; + } + } + + if (retType is not null && tempResult.Add(retType.FullName)) + { + result.Add(new PSTypeName(retType)); + } + } + } + + return; + } // Accessing a method as a property, we'd return a wrapper over the method. result.Add(new PSTypeName(typeof(PSMethod))); @@ -1769,245 +2282,247 @@ private void InferTypeFrom(VariableExpressionAst variableExpressionAst, List 0) + if (switchErrorStatement.Conditions?.Count > 0) { - foreach (TypeConstraintAst catchType in catchBlock.CatchTypes) + if (switchErrorStatement.Conditions[0].Extent.EndOffset < variableExpressionAst.Extent.StartOffset) { - Type exceptionType = catchType.TypeName.GetReflectionType(); - if (exceptionType != null && typeof(Exception).IsAssignableFrom(exceptionType)) - { - inferredTypes.Add(new PSTypeName(typeof(ErrorRecord<>).MakeGenericType(exceptionType))); - } + currentAst = switchErrorStatement.Conditions[0]; + break; + } + else + { + // $_ is inside the condition that is being declared, eg: Get-Process | Sort-Object -Property {switch ($_.Proc + currentAst = switchErrorStatement.Parent; + continue; } - } - else - { - inferredTypes.Add(new PSTypeName(typeof(ErrorRecord))); } - return; + break; } - - if (parent.Parent is CommandAst commandAst) + else if (currentAst is ScriptBlockExpressionAst) + { + hasSeenScriptBlock = true; + } + else if (hasSeenScriptBlock) { - // We found a command, see if there is a previous command in the pipeline. - PipelineAst pipelineAst = (PipelineAst)commandAst.Parent; - var previousCommandIndex = pipelineAst.PipelineElements.IndexOf(commandAst) - 1; - if (previousCommandIndex < 0) + if (currentAst is InvokeMemberExpressionAst invokeMember) { - return; + currentAst = invokeMember.Expression; + break; } - - foreach (var result in InferTypes(pipelineAst.PipelineElements[0])) + else if (currentAst is CommandAst cmdAst && cmdAst.Parent is PipelineAst pipeline && pipeline.PipelineElements.Count > 1) { - if (result.Type != null) + // We've found a pipeline with multiple commands, now we need to determine what command came before the command with the scriptblock: + // eg Get-Partition in this example: Get-Disk | Get-Partition | Where {$_} + var indexOfPreviousCommand = pipeline.PipelineElements.IndexOf(cmdAst) - 1; + if (indexOfPreviousCommand >= 0) { - // Assume (because we're looking at $_ and we're inside a script block that is an - // argument to some command) that the type we're getting is actually unrolled. - // This might not be right in all cases, but with our simple analysis, it's - // right more often than it's wrong. - if (result.Type.IsArray) - { - inferredTypes.Add(new PSTypeName(result.Type.GetElementType())); - continue; - } - - if (typeof(IEnumerable).IsAssignableFrom(result.Type)) - { - // We can't deduce much from IEnumerable, but we can if it's generic. - var enumerableInterfaces = result.Type.GetInterfaces(); - foreach (var t in enumerableInterfaces) - { - if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(IEnumerable<>)) - { - inferredTypes.Add(new PSTypeName(t.GetGenericArguments()[0])); - } - } - - continue; - } + currentAst = pipeline.PipelineElements[indexOfPreviousCommand]; + break; } - - inferredTypes.Add(result); } - - return; } + + currentAst = currentAst.Parent; } - } - // For certain variables, we always know their type, well at least we can assume we know. - if (astVariablePath.IsUnqualified) - { - var isThis = astVariablePath.UserPath.EqualsOrdinalIgnoreCase(SpecialVariables.This); - if (!isThis || (_context.CurrentTypeDefinitionAst == null && _context.CurrentThisType == null)) + if (currentAst is CatchClauseAst catchBlock) { - for (int i = 0; i < SpecialVariables.AutomaticVariables.Length; i++) + if (catchBlock.CatchTypes.Count > 0) { - if (!astVariablePath.UserPath.EqualsOrdinalIgnoreCase(SpecialVariables.AutomaticVariables[i])) + foreach (TypeConstraintAst catchType in catchBlock.CatchTypes) { - continue; + Type exceptionType = catchType.TypeName.GetReflectionType(); + if (typeof(Exception).IsAssignableFrom(exceptionType)) + { + inferredTypes.Add(new PSTypeName(typeof(ErrorRecord<>).MakeGenericType(exceptionType))); + } } + } - var type = SpecialVariables.AutomaticVariableTypes[i]; - if (type != typeof(object)) + // Either no type constraint was specified, or all the specified catch types were unavailable but we still know it's an error record. + if (inferredTypes.Count == 0) + { + inferredTypes.Add(new PSTypeName(typeof(ErrorRecord))); + } + } + else if (currentAst is TrapStatementAst trap) + { + if (trap.TrapType is not null) + { + Type exceptionType = trap.TrapType.TypeName.GetReflectionType(); + if (typeof(Exception).IsAssignableFrom(exceptionType)) { - inferredTypes.Add(new PSTypeName(type)); + inferredTypes.Add(new PSTypeName(typeof(ErrorRecord<>).MakeGenericType(exceptionType))); } - - break; + } + if (inferredTypes.Count == 0) + { + inferredTypes.Add(new PSTypeName(typeof(ErrorRecord))); } } - else + else if (currentAst is not null) { - var typeName = _context.CurrentThisType ?? new PSTypeName(_context.CurrentTypeDefinitionAst); - inferredTypes.Add(typeName); - return; + inferredTypes.AddRange(GetInferredEnumeratedTypes(InferTypes(currentAst))); } - } - else - { - inferredTypes.Add(new PSTypeName(_context.CurrentTypeDefinitionAst)); + return; } - // Look for our variable as a parameter or on the lhs of an assignment - hopefully we'll find either - // a type constraint or at least we can use the rhs to infer the type. - while (parent?.Parent != null) + // Process the well known variable $this + if (astVariablePath.IsUnqualified + && astVariablePath.UnqualifiedPath.EqualsOrdinalIgnoreCase(SpecialVariables.This) + && (_context.CurrentTypeDefinitionAst is not null || _context.CurrentThisType is not null)) { - parent = parent.Parent; + // $this is special in script properties and in PowerShell classes + PSTypeName typeName = _context.CurrentThisType ?? new PSTypeName(_context.CurrentTypeDefinitionAst); + inferredTypes.Add(typeName); + return; } - if (parent?.Parent is FunctionDefinitionAst) + // Process other well known variables like $true and $pshome + if (SpecialVariables.AllScopeVariables.TryGetValue(astVariablePath.UnqualifiedPath, out Type knownType)) { - parent = parent.Parent; - } - - int startOffset = variableExpressionAst.Extent.StartOffset; - var targetAsts = (List)AstSearcher.FindAll( - parent, - ast => + if (knownType == typeof(object)) { - if (ast is ParameterAst || ast is AssignmentStatementAst || ast is CommandAst) + if (_context.TryGetRepresentativeTypeNameFromExpressionSafeEval(variableExpressionAst, out var psType)) { - return variableExpressionAst.AstAssignsToSameVariable(ast) - && ast.Extent.EndOffset < startOffset; - } - - if (ast is ForEachStatementAst) - { - return variableExpressionAst.AstAssignsToSameVariable(ast) - && ast.Extent.StartOffset < startOffset; + inferredTypes.Add(psType); } + } + else + { + inferredTypes.Add(new PSTypeName(knownType)); + } - return false; - }, - searchNestedScriptBlocks: true); + return; + } - foreach (var ast in targetAsts) + // Process automatic variables like $MyInvocation and $PSBoundParameters + for (int i = 0; i < SpecialVariables.AutomaticVariables.Length; i++) { - if (ast is ParameterAst parameterAst) + if (!astVariablePath.UnqualifiedPath.EqualsOrdinalIgnoreCase(SpecialVariables.AutomaticVariables[i])) { - var currentCount = inferredTypes.Count; - inferredTypes.AddRange(InferTypes(parameterAst)); + continue; + } - if (inferredTypes.Count != currentCount) - { - return; - } + Type type = SpecialVariables.AutomaticVariableTypes[i]; + if (type != typeof(object)) + { + inferredTypes.Add(new PSTypeName(type)); } - } - var assignAsts = targetAsts.OfType().ToArray(); + return; + } - // If any of the assignments lhs use a type constraint, then we use that. - // Otherwise, we use the rhs of the "nearest" assignment - foreach (var assignAst in assignAsts) + // This visitor + loop finds the start of the current scope and traverses top to bottom to find the nearest variable assignment. + // Then repeats the process for each parent scope. + var assignmentVisitor = new VariableAssignmentVisitor() { - if (assignAst.Left is ConvertExpressionAst lhsConvert) + ScopeIsLocal = true, + LocalScopeOnly = variableExpressionAst.VariablePath.IsLocal || variableExpressionAst.VariablePath.IsPrivate, + StopSearchOffset = variableExpressionAst.Extent.StartOffset, + VariableTarget = variableExpressionAst + }; + while (currentAst is not null) + { + if (currentAst is IParameterMetadataProvider) { - inferredTypes.Add(new PSTypeName(lhsConvert.Type.TypeName)); - return; + if (currentAst is ScriptBlockAst && currentAst.Parent is FunctionDefinitionAst) + { + // If this scriptblock belongs to a function we want to visit that instead so we can get the parameters + // function X ($Param1){} + currentAst = currentAst.Parent; + } + + assignmentVisitor.ScopeDefinitionAst = currentAst; + currentAst.Visit(assignmentVisitor); + + if (assignmentVisitor.LocalScopeOnly + || assignmentVisitor.LastConstraint is not null + || ((assignmentVisitor.LastAssignment is not null || assignmentVisitor.LastAssignmentType is not null) + && (currentAst.Parent is not ScriptBlockExpressionAst scriptBlock || !scriptBlock.IsDotsourced()))) + { + // We only care about the parent scopes if no assignment has been made in the current scope + // or if it's a dot sourced scriptblock where an earlier defined type constraint could influence the final type + break; + } + + assignmentVisitor.ScopeIsLocal = false; + assignmentVisitor.StopSearchOffset = currentAst.Extent.StartOffset; } - } - var foreachAst = targetAsts.OfType().FirstOrDefault(); - if (foreachAst != null) - { - inferredTypes.AddRange( - GetInferredEnumeratedTypes(InferTypes(foreachAst.Condition))); - return; + currentAst = currentAst.Parent; } - var commandCompletionAst = targetAsts.OfType().FirstOrDefault(); - if (commandCompletionAst != null) + // The visitor is done finding the last assignment, now we need to infer the type of that assignment. + if (assignmentVisitor.LastConstraint is not null) { - inferredTypes.AddRange(InferTypes(commandCompletionAst)); - return; + inferredTypes.Add(new PSTypeName(assignmentVisitor.LastConstraint)); } - - int smallestDiff = int.MaxValue; - AssignmentStatementAst closestAssignment = null; - foreach (var assignAst in assignAsts) + else if (assignmentVisitor.LastAssignment is not null) { - var endOffset = assignAst.Extent.EndOffset; - if ((startOffset - endOffset) < smallestDiff) + if (assignmentVisitor.EnumerateAssignment) + { + inferredTypes.AddRange(GetInferredEnumeratedTypes(InferTypes(assignmentVisitor.LastAssignment))); + } + else { - smallestDiff = startOffset - endOffset; - closestAssignment = assignAst; + if (assignmentVisitor.LastAssignment is ConvertExpressionAst convertExpression + && convertExpression.IsRef()) + { + if (convertExpression.Parent is InvokeMemberExpressionAst memberInvoke) + { + inferredTypes.AddRange(InferTypeFromRef(memberInvoke, convertExpression)); + } + } + else if (assignmentVisitor.RedirectionAssignment && assignmentVisitor.LastAssignment is CommandAst cmdAst) + { + InferTypesFrom(cmdAst, inferredTypes, forRedirection: true); + } + else + { + inferredTypes.AddRange(InferTypes(assignmentVisitor.LastAssignment)); + } } } - - if (closestAssignment != null) + else if (assignmentVisitor.LastAssignmentType is not null) { - inferredTypes.AddRange(InferTypes(closestAssignment.Right)); + inferredTypes.Add(assignmentVisitor.LastAssignmentType); } if (_context.TryGetRepresentativeTypeNameFromExpressionSafeEval(variableExpressionAst, out var evalTypeName)) @@ -2193,6 +2708,16 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression bool foundAny = false; foreach (var psType in targetTypes) { + if (psType is PSSyntheticTypeName syntheticType) + { + foreach (var member in syntheticType.Members) + { + yield return member.PSTypeName; + } + + continue; + } + var type = psType.Type; if (type != null) { @@ -2202,6 +2727,17 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression continue; } + + if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(IList<>)) + { + var valueType = type.GetGenericArguments()[0]; + if (!valueType.ContainsGenericParameters) + { + foundAny = true; + yield return new PSTypeName(valueType); + } + continue; + } foreach (var iface in type.GetInterfaces()) { @@ -2257,7 +2793,7 @@ private IEnumerable InferTypeFrom(IndexExpressionAst indexExpression /// The potentially enumerable types to infer enumerated type from. /// /// The enumerated item types. - private static IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) + internal static IEnumerable GetInferredEnumeratedTypes(IEnumerable enumerableTypes) { foreach (PSTypeName maybeEnumerableType in enumerableTypes) { @@ -2332,7 +2868,7 @@ object ICustomAstVisitor2.VisitPipelineChain(PipelineChainAst pipelineChainAst) var types = new List(); types.AddRange(InferTypes(pipelineChainAst.LhsPipelineChain)); types.AddRange(InferTypes(pipelineChainAst.RhsPipeline)); - return GetArrayType(types); + return types.Distinct(); } private static CommandBaseAst GetPreviousPipelineCommand(CommandAst commandAst) @@ -2341,93 +2877,459 @@ private static CommandBaseAst GetPreviousPipelineCommand(CommandAst commandAst) var i = pipe.PipelineElements.IndexOf(commandAst); return i != 0 ? pipe.PipelineElements[i - 1] : null; } - } - internal static class TypeInferenceExtension - { - public static bool EqualsOrdinalIgnoreCase(this string s, string t) - { - return string.Equals(s, t, StringComparison.OrdinalIgnoreCase); - } + private sealed class VariableAssignmentVisitor : AstVisitor2 + { + /// + /// If set, we only look for local/private assignments in the scope of the variable we are inferring. + /// + internal bool LocalScopeOnly; + + /// + /// The current scope is local to the variable that is being inferred. + /// + internal bool ScopeIsLocal; + + /// + /// The variable that we are trying to determine the type of. + /// + internal VariableExpressionAst VariableTarget; + + /// + /// The last type constraint applied to the variable. This takes priority when determining the type of the variable. + /// + internal ITypeName LastConstraint; + + /// + /// The last ast that assigned a value to the variable. This determines the value of the variable unless a type constraint has been applied. + /// + internal Ast LastAssignment; + + /// + /// The inferred type from the most recent assignment. This is only used for stream redirections to variables, or the special OutVariable common parameters. + /// + internal PSTypeName LastAssignmentType; + + /// + /// Whether or not the types from the last assignment should be enumerated. + /// For assignments made by the PipelineVariable parameter or the foreach statement. + /// + internal bool EnumerateAssignment; + + /// + /// Whether or not the last assignment was via command redirection. + /// + internal bool RedirectionAssignment; + + /// + /// The Ast of the scope we are currently analyzing. + /// + internal Ast ScopeDefinitionAst; + internal int StopSearchOffset; + private int LastAssignmentOffset = -1; + + private void SetLastAssignment(Ast ast, bool enumerate = false, bool redirectionAssignment = false) + { + if (LastAssignmentOffset < ast.Extent.StartOffset && !VariableTarget.Extent.IsWithin(ast.Extent)) + { + // If the variable we are inferring the value of is inside this assignment then the assignment is invalid + // For example: $x = Get-Random; $x = $x.Where{$_.} here the value should be inferred based on Get-Random and not $x = $x... + ClearAssignmentData(); + LastAssignment = ast; + EnumerateAssignment = enumerate; + RedirectionAssignment = redirectionAssignment; + LastAssignmentOffset = ast.Extent.StartOffset; + } + } + + private void SetLastAssignmentType(PSTypeName typeName, IScriptExtent assignmentExtent) + { + if (LastAssignmentOffset < assignmentExtent.StartOffset && !VariableTarget.Extent.IsWithin(assignmentExtent)) + { + // If the variable we are inferring the value of is inside this assignment then the assignment is invalid + // For example: $x = 1..10; Get-Random 2>variable:x -InputObject ($x.) here the variable should be inferred based on the initial 1..10 assignment + // and not the error redirected variable. + ClearAssignmentData(); + LastAssignmentType = typeName; + LastAssignmentOffset = assignmentExtent.StartOffset; + } + } + + private void ClearAssignmentData() + { + LastAssignment = null; + LastAssignmentType = null; + EnumerateAssignment = false; + RedirectionAssignment = false; + } + + private bool AssignsToTargetVar(VariableExpressionAst foundVar) + { + if (!foundVar.VariablePath.UnqualifiedPath.EqualsOrdinalIgnoreCase(VariableTarget.VariablePath.UnqualifiedPath)) + { + return false; + } - public static IEnumerable GetGetterProperty(this Type type, string propertyName) - { - var res = new List(); - foreach (var m in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) + int scopeIndex = foundVar.VariablePath.UserPath.IndexOf(':'); + string scopeName = scopeIndex == -1 ? string.Empty : foundVar.VariablePath.UserPath.Remove(scopeIndex); + return AssignsToTargetScope(scopeName); + } + + private bool AssignsToTargetVar(string userPath) { - var name = m.Name; - if (name.Length == propertyName.Length + 4 - && name.StartsWith("get_") - && propertyName.IndexOf(name, 4, StringComparison.Ordinal) == 4) + if (string.IsNullOrEmpty(userPath)) { - res.Add(m); + return false; } + + string scopeName; + string varName; + int scopeIndex = userPath.IndexOf(':'); + if (scopeIndex == -1) + { + scopeName = string.Empty; + varName = userPath; + } + else + { + scopeName = userPath.Remove(scopeIndex); + varName = userPath.Substring(scopeIndex + 1); + } + + if (!varName.EqualsOrdinalIgnoreCase(VariableTarget.VariablePath.UnqualifiedPath)) + { + return false; + } + + return AssignsToTargetScope(scopeName); } - return res; - } + private bool AssignsToTargetScope(string scopeName) + => LocalScopeOnly + ? string.IsNullOrEmpty(scopeName) || scopeName.EqualsOrdinalIgnoreCase("Local") || scopeName.EqualsOrdinalIgnoreCase("Private") + : ScopeIsLocal || !(scopeName.EqualsOrdinalIgnoreCase("Local") || scopeName.EqualsOrdinalIgnoreCase("Private")); - public static bool AstAssignsToSameVariable(this VariableExpressionAst variableAst, Ast ast) - { - var parameterAst = ast as ParameterAst; - var variableAstVariablePath = variableAst.VariablePath; - if (parameterAst != null) + public override AstVisitAction DefaultVisit(Ast ast) { - return variableAstVariablePath.IsUnscopedVariable && - parameterAst.Name.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase); + if (ast.Extent.StartOffset >= StopSearchOffset) + { + // When visiting do while/until statements, the condition will be visited before the statement block + // The condition itself may not be interesting if it's after the cursor, but the statement block could be + // Example: + // do + // { + // $Var = gci + // $Var. + // } + // until($false) + return ast is PipelineBaseAst && ast.Parent is DoUntilStatementAst or DoWhileStatementAst + ? AstVisitAction.SkipChildren + : AstVisitAction.StopVisit; + } + + return AstVisitAction.Continue; } - if (ast is ForEachStatementAst foreachAst) + public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { - return variableAstVariablePath.IsUnscopedVariable && - foreachAst.Variable.VariablePath.UnqualifiedPath.Equals(variableAstVariablePath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase); + if (assignmentStatementAst.Extent.StartOffset >= StopSearchOffset) + { + return assignmentStatementAst.Parent is DoUntilStatementAst or DoWhileStatementAst + ? AstVisitAction.SkipChildren + : AstVisitAction.StopVisit; + } + + if (assignmentStatementAst.Left is AttributedExpressionAst attributedExpression) + { + var firstConvertExpression = attributedExpression as ConvertExpressionAst; + ExpressionAst child = attributedExpression.Child; + while (child is AttributedExpressionAst attributeChild) + { + if (firstConvertExpression is null && attributeChild is ConvertExpressionAst convertExpression) + { + // Multiple type constraint can be set on a variable like this: [int] [string] $Var1 = 1 + // But it's the left most type constraint that determines the final type. + firstConvertExpression = convertExpression; + } + + child = attributeChild.Child; + } + + if (child is VariableExpressionAst variableExpression && AssignsToTargetVar(variableExpression)) + { + if (firstConvertExpression is not null) + { + LastConstraint = firstConvertExpression.Type.TypeName; + } + else + { + SetLastAssignment(assignmentStatementAst.Right); + } + } + } + else if (assignmentStatementAst.Left is VariableExpressionAst variableExpression && AssignsToTargetVar(variableExpression)) + { + SetLastAssignment(assignmentStatementAst.Right); + } + + return AstVisitAction.Continue; } - if (ast is CommandAst commandAst) + public override AstVisitAction VisitCommand(CommandAst commandAst) { - string[] variableParameters = { "PV", "PipelineVariable", "OV", "OutVariable" }; - StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, variableParameters); + if (commandAst.Extent.StartOffset >= StopSearchOffset) + { + return AstVisitAction.StopVisit; + } - if (bindingResult != null) + string commandName = commandAst.GetCommandName(); + if (commandName is not null && CompletionCompleters.s_varModificationCommands.Contains(commandName)) { - foreach (string commandVariableParameter in variableParameters) + StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, resolve: false, CompletionCompleters.s_varModificationParameters); + if (bindingResult is not null + && bindingResult.BoundParameters.TryGetValue("Name", out ParameterBindingResult variableName) + && variableName.ConstantValue is string nameValue + && AssignsToTargetVar(nameValue) + && bindingResult.BoundParameters.TryGetValue("Value", out ParameterBindingResult variableValue)) { - if (bindingResult.BoundParameters.TryGetValue(commandVariableParameter, out ParameterBindingResult parameterBindingResult)) + SetLastAssignment(variableValue.Value); + return AstVisitAction.Continue; + } + } + + StaticBindingResult bindResult = StaticParameterBinder.BindCommand(commandAst, resolve: false); + if (bindResult is not null) + { + foreach (string parameterName in CompletionCompleters.s_outVarParameters) + { + if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult outVarBind) + && outVarBind.ConstantValue is string varName + && AssignsToTargetVar(varName)) { - if (string.Equals(variableAstVariablePath.UnqualifiedPath, (string)parameterBindingResult.ConstantValue, StringComparison.OrdinalIgnoreCase)) + // The *Variable parameters actually always results in an ArrayList + // But to make type inference of individual elements better, we say it's a generic list. + switch (parameterName) { - return true; + case "ErrorVariable": + case "ev": + SetLastAssignmentType(new PSTypeName(typeof(List)), commandAst.Extent); + break; + + case "WarningVariable": + case "wv": + SetLastAssignmentType(new PSTypeName(typeof(List)), commandAst.Extent); + break; + + case "InformationVariable": + case "iv": + SetLastAssignmentType(new PSTypeName(typeof(List)), commandAst.Extent); + break; + + case "OutVariable": + case "ov": + SetLastAssignment(commandAst); + break; + + default: + break; + } + + return AstVisitAction.Continue; + } + } + + if (commandAst.Parent is PipelineAst pipeline && pipeline.Extent.EndOffset > VariableTarget.Extent.StartOffset) + { + foreach (string parameterName in CompletionCompleters.s_pipelineVariableParameters) + { + if (bindResult.BoundParameters.TryGetValue(parameterName, out ParameterBindingResult pipeVarBind) + && pipeVarBind.ConstantValue is string varName + && AssignsToTargetVar(varName)) + { + SetLastAssignment(commandAst, enumerate: true); + return AstVisitAction.Continue; } } } } - return false; + foreach (RedirectionAst redirection in commandAst.Redirections) + { + if (redirection is FileRedirectionAst fileRedirection + && fileRedirection.Location is StringConstantExpressionAst redirectTarget + && redirectTarget.Value.StartsWith("variable:", StringComparison.OrdinalIgnoreCase) + && redirectTarget.Value.Length > "variable:".Length) + { + string varName = redirectTarget.Value.Substring("variable:".Length); + if (!AssignsToTargetVar(varName)) + { + continue; + } + + switch (fileRedirection.FromStream) + { + case RedirectionStream.Error: + SetLastAssignmentType(new PSTypeName(typeof(ErrorRecord)), commandAst.Extent); + break; + + case RedirectionStream.Warning: + SetLastAssignmentType(new PSTypeName(typeof(WarningRecord)), commandAst.Extent); + break; + + case RedirectionStream.Verbose: + SetLastAssignmentType(new PSTypeName(typeof(VerboseRecord)), commandAst.Extent); + break; + + case RedirectionStream.Debug: + SetLastAssignmentType(new PSTypeName(typeof(DebugRecord)), commandAst.Extent); + break; + + case RedirectionStream.Information: + SetLastAssignmentType(new PSTypeName(typeof(InformationRecord)), commandAst.Extent); + break; + + default: + SetLastAssignment(commandAst, redirectionAssignment: true); + break; + } + } + } + + return AstVisitAction.Continue; } - var assignmentAst = (AssignmentStatementAst)ast; - var lhs = assignmentAst.Left; - if (lhs is ConvertExpressionAst convertExpr) + public override AstVisitAction VisitParameter(ParameterAst parameterAst) { - lhs = convertExpr.Child; + if (parameterAst.Extent.StartOffset >= StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + if (AssignsToTargetVar(parameterAst.Name)) + { + foreach (AttributeBaseAst attribute in parameterAst.Attributes) + { + if (attribute is TypeConstraintAst typeConstraint) + { + LastConstraint = typeConstraint.TypeName; + return AstVisitAction.Continue; + } + } + } + + return AstVisitAction.Continue; } - if (lhs is not VariableExpressionAst varExpr) + public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { - return false; + if (forEachStatementAst.Extent.StartOffset >= StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + if (AssignsToTargetVar(forEachStatementAst.Variable) && forEachStatementAst.Condition.Extent.EndOffset < VariableTarget.Extent.StartOffset) + { + SetLastAssignment(forEachStatementAst.Condition, enumerate: true); + } + + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitConvertExpression(ConvertExpressionAst convertExpressionAst) + { + if (convertExpressionAst.IsRef() + && convertExpressionAst.Child is VariableExpressionAst varAst + && AssignsToTargetVar(varAst)) + { + SetLastAssignment(convertExpressionAst); + } + + return AstVisitAction.Continue; + } + + public override AstVisitAction VisitAttribute(AttributeAst attributeAst) + { + // Attributes can't assign values to variables so they aren't interesting. + return AstVisitAction.SkipChildren; + } + + public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) + { + return scriptBlockExpressionAst.IsDotsourced() + ? AstVisitAction.Continue + : AstVisitAction.SkipChildren; + } + + public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) + { + if (dataStatementAst.Extent.StartOffset >= StopSearchOffset) + { + return AstVisitAction.StopVisit; + } + + if (AssignsToTargetVar(dataStatementAst.Variable) && dataStatementAst.Extent.EndOffset < VariableTarget.Extent.StartOffset) + { + SetLastAssignment(dataStatementAst.Body); + } + + return AstVisitAction.SkipChildren; } - var candidateVarPath = varExpr.VariablePath; - if (candidateVarPath.UserPath.Equals(variableAstVariablePath.UserPath, StringComparison.OrdinalIgnoreCase)) + public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { - return true; + return functionDefinitionAst == ScopeDefinitionAst + ? AstVisitAction.Continue + : AstVisitAction.SkipChildren; } + } + } + + internal static class TypeInferenceExtension + { + public static bool EqualsOrdinalIgnoreCase(this string s, string t) + { + return string.Equals(s, t, StringComparison.OrdinalIgnoreCase); + } - // The following condition is making an assumption that at script scope, we didn't use $script:, but in the local scope, we did - // If we are searching anything other than script scope, this is wrong. - if (variableAstVariablePath.IsScript && variableAstVariablePath.UnqualifiedPath.Equals(candidateVarPath.UnqualifiedPath, StringComparison.OrdinalIgnoreCase)) + public static IEnumerable GetGetterProperty(this Type type, string propertyName) + { + var res = new List(); + foreach (var m in type.GetMethods(BindingFlags.Public | BindingFlags.Instance)) { - return true; + var name = m.Name; + // Equals without string allocation + if (name.Length == propertyName.Length + 4 + && name.StartsWith("get_") + && name.IndexOf(propertyName, 4, StringComparison.Ordinal) == 4) + { + res.Add(m); + } + } + + return res; + } + + public static bool IsDotsourced(this ScriptBlockExpressionAst scriptBlockExpressionAst) + { + Ast parent = scriptBlockExpressionAst.Parent; + + // This loop checks if the scriptblock is used as a dot sourced command + // or an argument for a command that uses the local scope eg: ForEach-Object -Process {$Var1 = "Hello"}, {Var2 = $true} + while (parent is not null) + { + if (parent is CommandAst cmdAst) + { + string cmdName = cmdAst.GetCommandName(); + return CompletionCompleters.s_localScopeCommandNames.Contains(cmdName) + || (cmdAst.CommandElements[0] is ScriptBlockExpressionAst && cmdAst.InvocationOperator == TokenKind.Dot); + } + + if (parent is not CommandExpressionAst and not PipelineAst and not StatementBlockAst and not ArrayExpressionAst and not ArrayLiteralAst) + { + break; + } + + parent = parent.Parent; } return false; diff --git a/src/System.Management.Automation/engine/parser/TypeResolver.cs b/src/System.Management.Automation/engine/parser/TypeResolver.cs index 8843ff5cd31..73d44e94fbe 100644 --- a/src/System.Management.Automation/engine/parser/TypeResolver.cs +++ b/src/System.Management.Automation/engine/parser/TypeResolver.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Collections.Specialized; #if !UNIX using System.DirectoryServices; #endif @@ -79,7 +80,10 @@ private static Type LookForTypeInAssemblies(TypeName typeName, foreach (Assembly assembly in assemblies) { // Skip the assemblies that we already searched and found no matching type. - if (searchedAssemblies.Contains(assembly)) { continue; } + if (searchedAssemblies.Contains(assembly)) + { + continue; + } try { @@ -370,10 +374,7 @@ internal static Type ResolveTypeNameWithContext(TypeName typeName, out Exception return typeName._typeDefinitionAst.Type; } - if (context == null) - { - context = LocalPipeline.GetExecutionContextFromTLS(); - } + context ??= LocalPipeline.GetExecutionContextFromTLS(); // Use the explicitly passed-in assembly list when it's specified by the caller. // Otherwise, retrieve all currently loaded assemblies. @@ -582,10 +583,7 @@ private TypeResolutionState(TypeResolutionState other, HashSet typesDefi internal static TypeResolutionState GetDefaultUsingState(ExecutionContext context) { - if (context == null) - { - context = LocalPipeline.GetExecutionContextFromTLS(); - } + context ??= LocalPipeline.GetExecutionContextFromTLS(); if (context != null) { @@ -673,7 +671,7 @@ public override int GetHashCode() internal static class TypeCache { - private class KeyComparer : IEqualityComparer> + private sealed class KeyComparer : IEqualityComparer> { public bool Equals(Tuple x, Tuple y) @@ -747,7 +745,7 @@ internal static class CoreTypes { typeof(Guid), new[] { "guid" } }, { typeof(Hashtable), new[] { "hashtable" } }, { typeof(int), new[] { "int", "int32" } }, - { typeof(Int16), new[] { "short", "int16" } }, + { typeof(short), new[] { "short", "int16" } }, { typeof(long), new[] { "long", "int64" } }, { typeof(CimInstance), new[] { "ciminstance" } }, { typeof(CimClass), new[] { "cimclass" } }, @@ -755,10 +753,12 @@ internal static class CoreTypes { typeof(CimConverter), new[] { "cimconverter" } }, { typeof(ModuleSpecification), null }, { typeof(IPEndPoint), new[] { "IPEndpoint" } }, + { typeof(NoRunspaceAffinityAttribute), new[] { "NoRunspaceAffinity" } }, { typeof(NullString), new[] { "NullString" } }, { typeof(OutputTypeAttribute), new[] { "OutputType" } }, { typeof(object[]), null }, { typeof(ObjectSecurity), new[] { "ObjectSecurity" } }, + { typeof(OrderedDictionary), new[] { "ordered" } }, { typeof(ParameterAttribute), new[] { "Parameter" } }, { typeof(PhysicalAddress), new[] { "PhysicalAddress" } }, { typeof(PSCredential), new[] { "pscredential" } }, @@ -778,15 +778,16 @@ internal static class CoreTypes { typeof(BigInteger), new[] { "bigint" } }, { typeof(SecureString), new[] { "securestring" } }, { typeof(TimeSpan), new[] { "timespan" } }, - { typeof(UInt16), new[] { "ushort", "uint16" } }, - { typeof(UInt32), new[] { "uint", "uint32" } }, - { typeof(UInt64), new[] { "ulong", "uint64" } }, + { typeof(ushort), new[] { "ushort", "uint16" } }, + { typeof(uint), new[] { "uint", "uint32" } }, + { typeof(ulong), new[] { "ulong", "uint64" } }, { typeof(Uri), new[] { "uri" } }, { typeof(ValidateCountAttribute), new[] { "ValidateCount" } }, { typeof(ValidateDriveAttribute), new[] { "ValidateDrive" } }, { typeof(ValidateLengthAttribute), new[] { "ValidateLength" } }, { typeof(ValidateNotNullAttribute), new[] { "ValidateNotNull" } }, { typeof(ValidateNotNullOrEmptyAttribute), new[] { "ValidateNotNullOrEmpty" } }, + { typeof(ValidateNotNullOrWhiteSpaceAttribute), new[] { "ValidateNotNullOrWhiteSpace" } }, { typeof(ValidatePatternAttribute), new[] { "ValidatePattern" } }, { typeof(ValidateRangeAttribute), new[] { "ValidateRange" } }, { typeof(ValidateScriptAttribute), new[] { "ValidateScript" } }, @@ -933,10 +934,7 @@ public static void Add(string typeName, Type type) public static bool Remove(string typeName) { userTypeAccelerators.Remove(typeName); - if (s_allTypeAccelerators != null) - { - s_allTypeAccelerators.Remove(typeName); - } + s_allTypeAccelerators?.Remove(typeName); return true; } diff --git a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs index 4cc8e98a2c0..8bf14d79aac 100644 --- a/src/System.Management.Automation/engine/parser/VariableAnalysis.cs +++ b/src/System.Management.Automation/engine/parser/VariableAnalysis.cs @@ -41,7 +41,7 @@ internal VariableAnalysisDetails() public List AssociatedAsts { get; } } - internal class FindAllVariablesVisitor : AstVisitor + internal sealed class FindAllVariablesVisitor : AstVisitor { private static readonly HashSet s_hashOfPessimizingCmdlets = new HashSet(StringComparer.OrdinalIgnoreCase); @@ -110,7 +110,7 @@ internal static Dictionary Visit(IParameterMeta visitor.VisitParameters(ast.Parameters); } - localsAllocated = visitor._variables.Count(details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed); + localsAllocated = visitor._variables.Count(static details => details.Value.LocalTupleIndex != VariableAnalysis.Unanalyzed); return visitor._variables; } @@ -185,8 +185,7 @@ private void VisitParameters(ReadOnlyCollection parameters) // valuetype because the parameter has no value yet. For example: // & { param([System.Reflection.MemberTypes]$m) ($null -eq $m) } - object unused; - if (!Compiler.TryGetDefaultParameterValue(analysisDetails.Type, out unused)) + if (!Compiler.TryGetDefaultParameterValue(analysisDetails.Type, out _)) { analysisDetails.LocalTupleIndex = VariableAnalysis.ForceDynamic; } @@ -338,7 +337,7 @@ internal class VariableAnalysis : ICustomAstVisitor2 // in these cases, we rely on the setter PSVariable.Value to handle those attributes. internal const int ForceDynamic = -2; - private class LoopGotoTargets + private sealed class LoopGotoTargets { internal LoopGotoTargets(string label, Block breakTarget, Block continueTarget) { @@ -354,7 +353,7 @@ internal LoopGotoTargets(string label, Block breakTarget, Block continueTarget) internal Block ContinueTarget { get; } } - private class Block + private sealed class Block { internal readonly List _asts = new List(); private readonly List _successors = new List(); @@ -439,7 +438,7 @@ private static void VisitDepthFirstOrder(Block block, List visitData) } } - private class AssignmentTarget : Ast + private sealed class AssignmentTarget : Ast { internal readonly ExpressionAst _targetAst; internal readonly string _variableName; @@ -502,7 +501,7 @@ internal static void NoteAllScopeVariable(string variableName) internal static bool AnyVariablesCouldBeAllScope(Dictionary variableNames) { - return variableNames.Any(keyValuePair => s_allScopeVariables.ContainsKey(keyValuePair.Key)); + return variableNames.Any(static keyValuePair => s_allScopeVariables.ContainsKey(keyValuePair.Key)); } private Dictionary _variables; @@ -581,7 +580,7 @@ internal static bool AnalyzeMemberFunction(FunctionMemberAst ast) { VariableAnalysis va = (new VariableAnalysis()); va.AnalyzeImpl(ast, false, false); - return va._exitBlock._predecessors.All(b => b._returns || b._throws || b._unreachable); + return va._exitBlock._predecessors.All(static b => b._returns || b._throws || b._unreachable); } private Tuple> AnalyzeImpl(IParameterMetadataProvider ast, bool disableOptimizations, bool scriptCmdlet) @@ -945,25 +944,11 @@ public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { _currentBlock = _entryBlock; - if (scriptBlockAst.DynamicParamBlock != null) - { - scriptBlockAst.DynamicParamBlock.Accept(this); - } - - if (scriptBlockAst.BeginBlock != null) - { - scriptBlockAst.BeginBlock.Accept(this); - } - - if (scriptBlockAst.ProcessBlock != null) - { - scriptBlockAst.ProcessBlock.Accept(this); - } - - if (scriptBlockAst.EndBlock != null) - { - scriptBlockAst.EndBlock.Accept(this); - } + scriptBlockAst.DynamicParamBlock?.Accept(this); + scriptBlockAst.BeginBlock?.Accept(this); + scriptBlockAst.ProcessBlock?.Accept(this); + scriptBlockAst.EndBlock?.Accept(this); + scriptBlockAst.CleanBlock?.Accept(this); _currentBlock.FlowsTo(_exitBlock); @@ -1317,10 +1302,7 @@ public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) public object VisitForStatement(ForStatementAst forStatementAst) { - if (forStatementAst.Initializer != null) - { - forStatementAst.Initializer.Accept(this); - } + forStatementAst.Initializer?.Accept(this); var generateCondition = forStatementAst.Condition != null ? () => forStatementAst.Condition.Accept(this) @@ -1456,22 +1438,19 @@ where t.Label.Equals(labelStrAst.Value, StringComparison.OrdinalIgnoreCase) public object VisitBreakStatement(BreakStatementAst breakStatementAst) { - BreakOrContinue(breakStatementAst.Label, t => t.BreakTarget); + BreakOrContinue(breakStatementAst.Label, static t => t.BreakTarget); return null; } public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { - BreakOrContinue(continueStatementAst.Label, t => t.ContinueTarget); + BreakOrContinue(continueStatementAst.Label, static t => t.ContinueTarget); return null; } private Block ControlFlowStatement(PipelineBaseAst pipelineAst) { - if (pipelineAst != null) - { - pipelineAst.Accept(this); - } + pipelineAst?.Accept(this); _currentBlock.FlowsTo(_exitBlock); var lastBlockInStatement = _currentBlock; @@ -1642,11 +1621,7 @@ public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) public object VisitCommandParameter(CommandParameterAst commandParameterAst) { - if (commandParameterAst.Argument != null) - { - commandParameterAst.Argument.Accept(this); - } - + commandParameterAst.Argument?.Accept(this); return null; } diff --git a/src/System.Management.Automation/engine/parser/ast.cs b/src/System.Management.Automation/engine/parser/ast.cs index 56693513b75..ba5c48a2752 100644 --- a/src/System.Management.Automation/engine/parser/ast.cs +++ b/src/System.Management.Automation/engine/parser/ast.cs @@ -36,8 +36,6 @@ internal interface ISupportsAssignment IAssignableValue GetAssignableValue(); } -#nullable restore - internal interface IAssignableValue { /// @@ -45,7 +43,7 @@ internal interface IAssignableValue /// It returns the expressions that holds the value of the ast. It may append the exprs or temps lists if the return /// value relies on temps and other expressions. /// - Expression GetValue(Compiler compiler, List exprs, List temps); + Expression? GetValue(Compiler compiler, List exprs, List temps); /// /// SetValue is called to set the result of an assignment (=) or to write back the result of @@ -53,6 +51,7 @@ internal interface IAssignableValue /// Expression SetValue(Compiler compiler, Expression rhs); } +#nullable restore internal interface IParameterMetadataProvider { @@ -321,20 +320,20 @@ internal bool IsInWorkflow() while (current != null && !stopScanning) { - ScriptBlockAst scriptBlock = current as ScriptBlockAst; - if (scriptBlock != null) + if (current is ScriptBlockAst scriptBlock) { // See if this uses the workflow keyword - FunctionDefinitionAst functionDefinition = scriptBlock.Parent as FunctionDefinitionAst; - if ((functionDefinition != null)) + if (scriptBlock.Parent is FunctionDefinitionAst functionDefinition) { stopScanning = true; - if (functionDefinition.IsWorkflow) { return true; } + if (functionDefinition.IsWorkflow) + { + return true; + } } } - CommandAst commandAst = current as CommandAst; - if (commandAst != null && + if (current is CommandAst commandAst && string.Equals(TokenKind.InlineScript.Text(), commandAst.GetCommandName(), StringComparison.OrdinalIgnoreCase) && this != commandAst) { @@ -389,8 +388,7 @@ internal static TypeDefinitionAst GetAncestorTypeDefinitionAst(Ast ast) // Nested function isn't really a member of the type so stop looking // Anonymous script blocks are though - var functionDefinitionAst = ast as FunctionDefinitionAst; - if (functionDefinitionAst != null && functionDefinitionAst.Parent is not FunctionMemberAst) + if (ast is FunctionDefinitionAst functionDefinitionAst && functionDefinitionAst.Parent is not FunctionMemberAst) break; ast = ast.Parent; } @@ -522,7 +520,7 @@ internal ErrorStatementAst(IScriptExtent extent, Token kind, IEnumerable - /// Indicate the kind of the ErrorStatement. e.g. Kind == Switch means that this error statment is generated + /// Indicate the kind of the ErrorStatement. e.g. Kind == Switch means that this error statement is generated /// when parsing a switch statement. /// public Token Kind { get; } @@ -755,14 +753,6 @@ public class ScriptRequirements /// public ReadOnlyCollection RequiredModules { get; internal set; } - /// - /// The snapins this script requires, specified like: - /// #requires -PSSnapin Snapin - /// #requires -PSSnapin Snapin -Version 2 - /// If no snapins are required, this property is an empty collection. - /// - public ReadOnlyCollection RequiresPSSnapIns { get; internal set; } - /// /// The assemblies this script requires, specified like: /// #requires -Assembly path\to\foo.dll @@ -800,7 +790,7 @@ public class ScriptBlockAst : Ast, IParameterMetadataProvider /// Construct a ScriptBlockAst that uses explicitly named begin/process/end blocks. /// /// The extent of the script block. - /// The list of using statments, may be null. + /// The list of using statements, may be null. /// The set of attributes for the script block. /// The ast for the param block, may be null. /// The ast for the begin block, may be null. @@ -819,6 +809,46 @@ public ScriptBlockAst(IScriptExtent extent, NamedBlockAst processBlock, NamedBlockAst endBlock, NamedBlockAst dynamicParamBlock) + : this( + extent, + usingStatements, + attributes, + paramBlock, + beginBlock, + processBlock, + endBlock, + cleanBlock: null, + dynamicParamBlock) + { + } + + /// + /// Initializes a new instance of the class. + /// This construction uses explicitly named begin/process/end/clean blocks. + /// + /// The extent of the script block. + /// The list of using statements, may be null. + /// The set of attributes for the script block. + /// The ast for the param block, may be null. + /// The ast for the begin block, may be null. + /// The ast for the process block, may be null. + /// The ast for the end block, may be null. + /// The ast for the clean block, may be null. + /// The ast for the dynamicparam block, may be null. + /// + /// If is null. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "param")] + public ScriptBlockAst( + IScriptExtent extent, + IEnumerable usingStatements, + IEnumerable attributes, + ParamBlockAst paramBlock, + NamedBlockAst beginBlock, + NamedBlockAst processBlock, + NamedBlockAst endBlock, + NamedBlockAst cleanBlock, + NamedBlockAst dynamicParamBlock) : base(extent) { SetUsingStatements(usingStatements); @@ -857,6 +887,12 @@ public ScriptBlockAst(IScriptExtent extent, SetParent(endBlock); } + if (cleanBlock != null) + { + this.CleanBlock = cleanBlock; + SetParent(cleanBlock); + } + if (dynamicParamBlock != null) { this.DynamicParamBlock = dynamicParamBlock; @@ -868,7 +904,7 @@ public ScriptBlockAst(IScriptExtent extent, /// Construct a ScriptBlockAst that uses explicitly named begin/process/end blocks. /// /// The extent of the script block. - /// The list of using statments, may be null. + /// The list of using statements, may be null. /// The ast for the param block, may be null. /// The ast for the begin block, may be null. /// The ast for the process block, may be null. @@ -889,6 +925,35 @@ public ScriptBlockAst(IScriptExtent extent, { } + /// + /// Initializes a new instance of the class. + /// This construction uses explicitly named begin/process/end/clean blocks. + /// + /// The extent of the script block. + /// The list of using statements, may be null. + /// The ast for the param block, may be null. + /// The ast for the begin block, may be null. + /// The ast for the process block, may be null. + /// The ast for the end block, may be null. + /// The ast for the clean block, may be null. + /// The ast for the dynamicparam block, may be null. + /// + /// If is null. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "param")] + public ScriptBlockAst( + IScriptExtent extent, + IEnumerable usingStatements, + ParamBlockAst paramBlock, + NamedBlockAst beginBlock, + NamedBlockAst processBlock, + NamedBlockAst endBlock, + NamedBlockAst cleanBlock, + NamedBlockAst dynamicParamBlock) + : this(extent, usingStatements, null, paramBlock, beginBlock, processBlock, endBlock, cleanBlock, dynamicParamBlock) + { + } + /// /// Construct a ScriptBlockAst that uses explicitly named begin/process/end blocks. /// @@ -912,11 +977,38 @@ public ScriptBlockAst(IScriptExtent extent, { } + /// + /// Initializes a new instance of the class. + /// This construction uses explicitly named begin/process/end/clean blocks. + /// + /// The extent of the script block. + /// The ast for the param block, may be null. + /// The ast for the begin block, may be null. + /// The ast for the process block, may be null. + /// The ast for the end block, may be null. + /// The ast for the clean block, may be null. + /// The ast for the dynamicparam block, may be null. + /// + /// If is null. + /// + [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "param")] + public ScriptBlockAst( + IScriptExtent extent, + ParamBlockAst paramBlock, + NamedBlockAst beginBlock, + NamedBlockAst processBlock, + NamedBlockAst endBlock, + NamedBlockAst cleanBlock, + NamedBlockAst dynamicParamBlock) + : this(extent, null, paramBlock, beginBlock, processBlock, endBlock, cleanBlock, dynamicParamBlock) + { + } + /// /// Construct a ScriptBlockAst that does not use explicitly named blocks. /// /// The extent of the script block. - /// The list of using statments, may be null. + /// The list of using statements, may be null. /// The ast for the param block, may be null. /// /// The statements that go in the end block if is false, or the @@ -975,7 +1067,7 @@ public ScriptBlockAst(IScriptExtent extent, ParamBlockAst paramBlock, StatementB /// Construct a ScriptBlockAst that does not use explicitly named blocks. /// /// The extent of the script block. - /// The list of using statments, may be null. + /// The list of using statements, may be null. /// The ast for the param block, may be null. /// /// The statements that go in the end block if is false, or the @@ -1017,7 +1109,7 @@ public ScriptBlockAst(IScriptExtent extent, IEnumerable attributes /// Construct a ScriptBlockAst that does not use explicitly named blocks. /// /// The extent of the script block. - /// The list of using statments, may be null. + /// The list of using statements, may be null. /// The attributes for the script block. /// The ast for the param block, may be null. /// @@ -1116,6 +1208,11 @@ private void SetUsingStatements(IEnumerable usingStatements) /// public NamedBlockAst EndBlock { get; } + /// + /// Gets the ast representing the clean block for a script block, or null if no clean block was specified. + /// + public NamedBlockAst CleanBlock { get; } + /// /// The ast representing the dynamicparam block for a script block, or null if no dynamicparam block was specified. /// @@ -1195,17 +1292,25 @@ public override Ast Copy() var newBeginBlock = CopyElement(this.BeginBlock); var newProcessBlock = CopyElement(this.ProcessBlock); var newEndBlock = CopyElement(this.EndBlock); + var newCleanBlock = CopyElement(this.CleanBlock); var newDynamicParamBlock = CopyElement(this.DynamicParamBlock); var newAttributes = CopyElements(this.Attributes); var newUsingStatements = CopyElements(this.UsingStatements); - var scriptBlockAst = new ScriptBlockAst(this.Extent, newUsingStatements, newAttributes, newParamBlock, newBeginBlock, newProcessBlock, - newEndBlock, newDynamicParamBlock) + return new ScriptBlockAst( + this.Extent, + newUsingStatements, + newAttributes, + newParamBlock, + newBeginBlock, + newProcessBlock, + newEndBlock, + newCleanBlock, + newDynamicParamBlock) { IsConfiguration = this.IsConfiguration, ScriptRequirements = this.ScriptRequirements }; - return scriptBlockAst; } internal string ToStringForSerialization() @@ -1249,7 +1354,7 @@ internal string ToStringForSerialization(Tuple, stri string script = this.ToString(); var newScript = new StringBuilder(); - foreach (var ast in astElements.OrderBy(ast => ast.Extent.StartOffset)) + foreach (var ast in astElements.OrderBy(static ast => ast.Extent.StartOffset)) { int astStartOffset = ast.Extent.StartOffset - indexOffset; int astEndOffset = ast.Extent.EndOffset - indexOffset; @@ -1259,10 +1364,10 @@ internal string ToStringForSerialization(Tuple, stri // We are done processing the section that we care about if (astStartOffset >= endOffset) { break; } - var varAst = ast as VariableExpressionAst; - if (varAst != null) + if (ast is VariableExpressionAst varAst) { - string varName = varAst.VariablePath.UserPath; + VariablePath varPath = varAst.VariablePath; + string varName = varPath.IsDriveQualified ? $"{varPath.DriveName}_{varPath.UnqualifiedPath}" : $"{varPath.UnqualifiedPath}"; string varSign = varAst.Splatted ? "@" : "$"; string newVarName = varSign + UsingExpressionAst.UsingPrefix + varName; @@ -1339,8 +1444,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) if (action == AstVisitAction.SkipChildren) return visitor.CheckForPostAction(this, AstVisitAction.Continue); - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { if (action == AstVisitAction.Continue) { @@ -1367,17 +1471,27 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) } } - if (action == AstVisitAction.Continue && ParamBlock != null) - action = ParamBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && DynamicParamBlock != null) - action = DynamicParamBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && BeginBlock != null) - action = BeginBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && ProcessBlock != null) - action = ProcessBlock.InternalVisit(visitor); - if (action == AstVisitAction.Continue && EndBlock != null) - action = EndBlock.InternalVisit(visitor); + if (action == AstVisitAction.Continue) + { + _ = VisitAndShallContinue(ParamBlock) && + VisitAndShallContinue(DynamicParamBlock) && + VisitAndShallContinue(BeginBlock) && + VisitAndShallContinue(ProcessBlock) && + VisitAndShallContinue(EndBlock) && + VisitAndShallContinue(CleanBlock); + } + return visitor.CheckForPostAction(this, action); + + bool VisitAndShallContinue(Ast ast) + { + if (ast is not null) + { + action = ast.InternalVisit(visitor); + } + + return action == AstVisitAction.Continue; + } } #endregion Visitors @@ -1514,9 +1628,7 @@ Tuple IParameterMetadataProvider.GetWithInputHandlingForInvokeCo private string GetWithInputHandlingForInvokeCommandImpl(Tuple, string> usingVariablesTuple) { // do not add "$input |" to complex pipelines - string unused1; - string unused2; - var pipelineAst = GetSimplePipeline(false, out unused1, out unused2); + var pipelineAst = GetSimplePipeline(false, out _, out _); if (pipelineAst == null) { return (usingVariablesTuple == null) @@ -1567,7 +1679,7 @@ bool IParameterMetadataProvider.UsesCmdletBinding() if (ParamBlock != null) { - usesCmdletBinding = this.ParamBlock.Attributes.Any(attribute => typeof(CmdletBindingAttribute) == attribute.TypeName.GetReflectionAttributeType()); + usesCmdletBinding = this.ParamBlock.Attributes.Any(static attribute => typeof(CmdletBindingAttribute) == attribute.TypeName.GetReflectionAttributeType()); if (!usesCmdletBinding) { usesCmdletBinding = ParamBlockAst.UsesCmdletBinding(ParamBlock.Parameters); @@ -1581,9 +1693,12 @@ bool IParameterMetadataProvider.UsesCmdletBinding() internal PipelineAst GetSimplePipeline(bool allowMultiplePipelines, out string errorId, out string errorMsg) { - if (BeginBlock != null || ProcessBlock != null || DynamicParamBlock != null) + if (BeginBlock != null + || ProcessBlock != null + || CleanBlock != null + || DynamicParamBlock != null) { - errorId = "CanConvertOneClauseOnly"; + errorId = nameof(AutomationExceptions.CanConvertOneClauseOnly); errorMsg = AutomationExceptions.CanConvertOneClauseOnly; return null; } @@ -1749,7 +1864,7 @@ internal static bool UsesCmdletBinding(IEnumerable parameters) public class NamedBlockAst : Ast { /// - /// Construct the ast for a begin, process, end, or dynamic param block. + /// Construct the ast for a begin, process, end, clean, or dynamic param block. /// /// /// The extent of the block. If is false, the extent includes @@ -1761,6 +1876,7 @@ public class NamedBlockAst : Ast /// /// /// + /// /// /// /// @@ -1779,8 +1895,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs { // Validate the block name. If the block is unnamed, it must be an End block (for a function) // or Process block (for a filter). - if (!blockName.HasTrait(TokenFlags.ScriptBlockBlockName) - || (unnamed && (blockName == TokenKind.Begin || blockName == TokenKind.Dynamicparam))) + if (HasInvalidBlockName(blockName, unnamed)) { throw PSTraceSource.NewArgumentException(nameof(blockName)); } @@ -1817,8 +1932,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs if (!unnamed) { - var statementsExtent = statementBlock.Extent as InternalScriptExtent; - if (statementsExtent != null) + if (statementBlock.Extent is InternalScriptExtent statementsExtent) { this.OpenCurlyExtent = new InternalScriptExtent(statementsExtent.PositionHelper, statementsExtent.StartOffset, statementsExtent.StartOffset + 1); this.CloseCurlyExtent = new InternalScriptExtent(statementsExtent.PositionHelper, statementsExtent.EndOffset - 1, statementsExtent.EndOffset); @@ -1838,6 +1952,7 @@ public NamedBlockAst(IScriptExtent extent, TokenKind blockName, StatementBlockAs /// /// /// + /// /// /// /// @@ -1877,6 +1992,14 @@ public override Ast Copy() return new NamedBlockAst(this.Extent, this.BlockKind, statementBlock, this.Unnamed); } + private static bool HasInvalidBlockName(TokenKind blockName, bool unnamed) + { + return !blockName.HasTrait(TokenFlags.ScriptBlockBlockName) + || (unnamed + && blockName != TokenKind.Process + && blockName != TokenKind.End); + } + // Used by the debugger for command breakpoints internal IScriptExtent OpenCurlyExtent { get; } @@ -2330,7 +2453,8 @@ internal string GetParamTextWithDollarUsingHandling(IEnumerator= endOffset) { break; } - string varName = varAst.VariablePath.UserPath; + VariablePath varPath = varAst.VariablePath; + string varName = varPath.IsDriveQualified ? $"{varPath.DriveName}_{varPath.UnqualifiedPath}" : $"{varPath.UnqualifiedPath}"; string varSign = varAst.Splatted ? "@" : "$"; string newVarName = varSign + UsingExpressionAst.UsingPrefix + varName; @@ -2684,8 +2808,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitTypeDefinition(this); if (action == AstVisitAction.SkipChildren) @@ -2932,8 +3055,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitUsingStatement(this); if (action != AstVisitAction.Continue) @@ -3160,8 +3282,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitPropertyMember(this); if (action == AstVisitAction.SkipChildren) @@ -3176,7 +3297,10 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { var attributeAst = Attributes[index]; action = attributeAst.InternalVisit(visitor); - if (action != AstVisitAction.Continue) break; + if (action != AstVisitAction.Continue) + { + break; + } } } @@ -3331,6 +3455,8 @@ public bool IsConstructor internal IScriptExtent NameExtent { get { return _functionDefinitionAst.NameExtent; } } + private string _toolTip; + /// /// Copy a function member ast. /// @@ -3345,28 +3471,56 @@ public override Ast Copy() internal override string GetTooltip() { - var sb = new StringBuilder(); - if (IsStatic) + if (!string.IsNullOrEmpty(_toolTip)) { - sb.Append("static "); + return _toolTip; } - sb.Append(IsReturnTypeVoid() ? "void" : ReturnType.TypeName.FullName); - sb.Append(' '); - sb.Append(Name); - sb.Append('('); - for (int i = 0; i < Parameters.Count; i++) + var sb = new StringBuilder(); + var classMembers = ((TypeDefinitionAst)Parent).Members; + for (int i = 0; i < classMembers.Count; i++) { - if (i > 0) + var methodMember = classMembers[i] as FunctionMemberAst; + if (methodMember is null || + !Name.Equals(methodMember.Name) || + IsStatic != methodMember.IsStatic) + { + continue; + } + + if (sb.Length > 0) { - sb.Append(", "); + sb.AppendLine(); } - sb.Append(Parameters[i].GetTooltip()); + if (methodMember.IsStatic) + { + sb.Append("static "); + } + + if (!methodMember.IsConstructor) + { + sb.Append(methodMember.IsReturnTypeVoid() ? "void" : methodMember.ReturnType.TypeName.FullName); + sb.Append(' '); + } + + sb.Append(methodMember.Name); + sb.Append('('); + for (int j = 0; j < methodMember.Parameters.Count; j++) + { + if (j > 0) + { + sb.Append(", "); + } + + sb.Append(methodMember.Parameters[j].GetTooltip()); + } + + sb.Append(')'); } - sb.Append(')'); - return sb.ToString(); + _toolTip = sb.ToString(); + return _toolTip; } #region Visitors @@ -3380,8 +3534,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitFunctionMember(this); if (action == AstVisitAction.SkipChildren) @@ -3392,7 +3545,10 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) { var attributeAst = Attributes[index]; action = attributeAst.InternalVisit(visitor); - if (action != AstVisitAction.Continue) break; + if (action != AstVisitAction.Continue) + { + break; + } } } @@ -3718,10 +3874,7 @@ public CommentHelpInfo GetHelpContent() /// public CommentHelpInfo GetHelpContent(Dictionary scriptBlockTokenCache) { - if (scriptBlockTokenCache == null) - { - throw new ArgumentNullException(nameof(scriptBlockTokenCache)); - } + ArgumentNullException.ThrowIfNull(scriptBlockTokenCache); var commentTokens = HelpCommentsParser.GetHelpCommentTokens(this, scriptBlockTokenCache); if (commentTokens != null) @@ -3754,7 +3907,7 @@ internal string GetParamTextFromParameterList(Tuple, Diagnostics.Assert( usingVariablesTuple.Item1 != null && usingVariablesTuple.Item1.Count > 0 && !string.IsNullOrEmpty(usingVariablesTuple.Item2), "Caller makes sure the value passed in is not null or empty."); - orderedUsingVars = usingVariablesTuple.Item1.OrderBy(varAst => varAst.Extent.StartOffset).GetEnumerator(); + orderedUsingVars = usingVariablesTuple.Item1.OrderBy(static varAst => varAst.Extent.StartOffset).GetEnumerator(); additionalNewUsingParams = usingVariablesTuple.Item2; } @@ -4041,7 +4194,7 @@ public DataStatementAst(IScriptExtent extent, { this.CommandsAllowed = new ReadOnlyCollection(commandsAllowed.ToArray()); SetParents(CommandsAllowed); - this.HasNonConstantAllowedCommand = CommandsAllowed.Any(ast => ast is not StringConstantExpressionAst); + this.HasNonConstantAllowedCommand = CommandsAllowed.Any(static ast => ast is not StringConstantExpressionAst); } else { @@ -4425,7 +4578,7 @@ public class DoWhileStatementAst : LoopStatementAst /// /// Construct a do/while statement. /// - /// The extent of the do/while statment from the label or do keyword to the closing curly brace. + /// The extent of the do/while statement from the label or do keyword to the closing curly brace. /// The optionally null label. /// The condition tested on each iteration of the loop. /// The body executed on each iteration of the loop. @@ -5411,15 +5564,9 @@ public PipelineChainAst( bool background = false) : base(extent) { - if (lhsChain == null) - { - throw new ArgumentNullException(nameof(lhsChain)); - } + ArgumentNullException.ThrowIfNull(lhsChain); - if (rhsPipeline == null) - { - throw new ArgumentNullException(nameof(rhsPipeline)); - } + ArgumentNullException.ThrowIfNull(rhsPipeline); if (chainOperator != TokenKind.AndAnd && chainOperator != TokenKind.OrOr) { @@ -5891,8 +6038,8 @@ public CommandAst(IScriptExtent extent, /// Returns the name of the command invoked by this ast. /// This command name may not be known statically, in which case null is returned. /// - /// For example, if the command name is in a variable: & $foo, then the parser cannot know which command is executed. - /// Similarly, if the command is being invoked in a module: & (gmo SomeModule) Bar, then the parser does not know the + /// For example, if the command name is in a variable: & $foo, then the parser cannot know which command is executed. + /// Similarly, if the command is being invoked in a module: & (gmo SomeModule) Bar, then the parser does not know the /// command name is Bar because the parser can't determine that the expression (gmo SomeModule) returns a module instead /// of a string. /// @@ -6258,19 +6405,13 @@ public AssignmentStatementAst(IScriptExtent extent, ExpressionAst left, TokenKin // If the assignment is just an expression and the expression is not backgrounded then // remove the pipeline wrapping the expression. - var pipelineAst = right as PipelineAst; - if (pipelineAst != null && !pipelineAst.Background) + if (right is PipelineAst pipelineAst + && !pipelineAst.Background + && pipelineAst.PipelineElements.Count == 1 + && pipelineAst.PipelineElements[0] is CommandExpressionAst commandExpressionAst) { - if (pipelineAst.PipelineElements.Count == 1) - { - var commandExpressionAst = pipelineAst.PipelineElements[0] as CommandExpressionAst; - - if (commandExpressionAst != null) - { - right = commandExpressionAst; - right.ClearParent(); - } - } + right = commandExpressionAst; + right.ClearParent(); } this.Operator = @operator; @@ -6319,8 +6460,7 @@ public override Ast Copy() /// All of the expressions assigned by the assignment statement. public IEnumerable GetAssignmentTargets() { - var arrayExpression = Left as ArrayLiteralAst; - if (arrayExpression != null) + if (Left is ArrayLiteralAst arrayExpression) { foreach (var element in arrayExpression.Elements) { @@ -6444,7 +6584,7 @@ public override Ast Copy() { LCurlyToken = this.LCurlyToken, ConfigurationToken = this.ConfigurationToken, - CustomAttributes = this.CustomAttributes?.Select(e => (AttributeAst)e.Copy()) + CustomAttributes = this.CustomAttributes?.Select(static e => (AttributeAst)e.Copy()) }; } @@ -6459,8 +6599,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitConfigurationDefinition(this); if (action == AstVisitAction.SkipChildren) @@ -6545,7 +6684,7 @@ internal PipelineAst GenerateSetItemPipelineAst() cea.Add(new CommandParameterAst(PositionUtilities.EmptyExtent, "ResourceModuleTuplesToImport", new ConstantExpressionAst(PositionUtilities.EmptyExtent, resourceModulePairsToImport), PositionUtilities.EmptyExtent)); var scriptBlockBody = new ScriptBlockAst(Body.Extent, - CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes?.Select(static att => (AttributeAst)att.Copy()).ToList(), null, new StatementBlockAst(Body.Extent, resourceBody, null), false, false); @@ -6578,9 +6717,9 @@ internal PipelineAst GenerateSetItemPipelineAst() // ) // var attribAsts = - ConfigurationBuildInParameterAttribAsts.Select(attribAst => (AttributeAst)attribAst.Copy()).ToList(); + ConfigurationBuildInParameterAttribAsts.Select(static attribAst => (AttributeAst)attribAst.Copy()).ToList(); - var paramAsts = ConfigurationBuildInParameters.Select(paramAst => (ParameterAst)paramAst.Copy()).ToList(); + var paramAsts = ConfigurationBuildInParameters.Select(static paramAst => (ParameterAst)paramAst.Copy()).ToList(); // the parameters defined in the configuration keyword will be combined with above parameters // it will be used to construct $ArgsToBody in the set-item created function boby using below statement @@ -6591,7 +6730,7 @@ internal PipelineAst GenerateSetItemPipelineAst() // $Outputpath = $psboundparameters[""Outputpath""] if (Body.ScriptBlock.ParamBlock != null) { - paramAsts.AddRange(Body.ScriptBlock.ParamBlock.Parameters.Select(parameterAst => (ParameterAst)parameterAst.Copy())); + paramAsts.AddRange(Body.ScriptBlock.ParamBlock.Parameters.Select(static parameterAst => (ParameterAst)parameterAst.Copy())); } var paramBlockAst = new ParamBlockAst(this.Extent, attribAsts, paramAsts); @@ -6599,12 +6738,12 @@ internal PipelineAst GenerateSetItemPipelineAst() var cmdAst = new CommandAst(this.Extent, cea, TokenKind.Unknown, null); var pipeLineAst = new PipelineAst(this.Extent, cmdAst, background: false); - var funcStatements = ConfigurationExtraParameterStatements.Select(statement => (StatementAst)statement.Copy()).ToList(); + var funcStatements = ConfigurationExtraParameterStatements.Select(static statement => (StatementAst)statement.Copy()).ToList(); funcStatements.Add(pipeLineAst); var statmentBlockAst = new StatementBlockAst(this.Extent, funcStatements, null); var funcBody = new ScriptBlockAst(Body.Extent, - CustomAttributes?.Select(att => (AttributeAst)att.Copy()).ToList(), + CustomAttributes?.Select(static att => (AttributeAst)att.Copy()).ToList(), paramBlockAst, statmentBlockAst, false, true); var funcBodyExp = new ScriptBlockExpressionAst(this.Extent, funcBody); @@ -6928,8 +7067,7 @@ internal override object Accept(ICustomAstVisitor visitor) internal override AstVisitAction InternalVisit(AstVisitor visitor) { var action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitDynamicKeywordStatement(this); if (action == AstVisitAction.SkipChildren) @@ -7031,7 +7169,6 @@ internal PipelineAst GenerateCommandCallPipelineAst() } ExpressionAst expr = BodyExpression; - HashtableAst hashtable = expr as HashtableAst; if (Keyword.DirectCall) { // If this keyword takes a name, then add it as the parameter -InstanceName @@ -7050,7 +7187,7 @@ internal PipelineAst GenerateCommandCallPipelineAst() // in the hash literal expression and map them to parameters. // We've already checked to make sure that they're all valid names. // - if (hashtable != null) + if (expr is HashtableAst hashtable) { bool isHashtableValid = true; // @@ -7126,7 +7263,7 @@ internal PipelineAst GenerateCommandCallPipelineAst() FunctionName.Extent, new TypeName( FunctionName.Extent, - typeof(System.Management.Automation.Language.DynamicKeyword).FullName)), + typeof(DynamicKeyword).FullName)), new StringConstantExpressionAst( FunctionName.Extent, "GetKeyword", @@ -7234,10 +7371,7 @@ protected ExpressionAst(IScriptExtent extent) /// internal virtual bool ShouldPreserveOutputInCaseOfException() { - var parenExpr = this as ParenExpressionAst; - var subExpr = this as SubExpressionAst; - - if (parenExpr == null && subExpr == null) + if (this is not ParenExpressionAst and not SubExpressionAst) { PSTraceSource.NewInvalidOperationException(); } @@ -7253,8 +7387,7 @@ internal virtual bool ShouldPreserveOutputInCaseOfException() return false; } - var parenExpressionAst = pipelineAst.Parent as ParenExpressionAst; - if (parenExpressionAst != null) + if (pipelineAst.Parent is ParenExpressionAst parenExpressionAst) { return parenExpressionAst.ShouldPreserveOutputInCaseOfException(); } @@ -7307,9 +7440,9 @@ public TernaryExpressionAst(IScriptExtent extent, ExpressionAst condition, Expre /// /// Copy the TernaryExpressionAst instance. /// - /// - /// Retirns a copy of the ast. - /// + /// + /// Returns a copy of the ast. + /// public override Ast Copy() { ExpressionAst newCondition = CopyElement(this.Condition); @@ -7458,6 +7591,8 @@ public override Type StaticType } internal static readonly PSTypeName[] BoolTypeNameArray = new PSTypeName[] { new PSTypeName(typeof(bool)) }; + internal static readonly PSTypeName[] StringTypeNameArray = new PSTypeName[] { new PSTypeName(typeof(string)) }; + internal static readonly PSTypeName[] StringArrayTypeNameArray = new PSTypeName[] { new PSTypeName(typeof(string[])) }; #region Visitors @@ -7804,7 +7939,7 @@ public override Ast Copy() /// /// The static type produced after the cast is normally the type named by , but in some cases - /// it may not be, in which, is assumed. + /// it may not be, in which, is assumed. /// public override Type StaticType { @@ -7836,8 +7971,7 @@ internal override AstVisitAction InternalVisit(AstVisitor visitor) IAssignableValue ISupportsAssignment.GetAssignableValue() { - var varExpr = Child as VariableExpressionAst; - if (varExpr != null && varExpr.TupleIndex >= 0) + if (Child is VariableExpressionAst varExpr && varExpr.TupleIndex >= 0) { // In the common case of a single cast on the lhs of an assignment, we may have saved the type of the // variable in the mutable tuple, so conversions will get generated elsewhere, and we can just use @@ -7863,7 +7997,7 @@ internal bool IsRef() public class MemberExpressionAst : ExpressionAst, ISupportsAssignment { /// - /// Construct an ast to reference a property. + /// Initializes a new instance of the class. /// /// /// The extent of the expression, starting with the expression before the operator '.' or '::' and ending after @@ -7939,7 +8073,13 @@ public override Ast Copy() { var newExpression = CopyElement(this.Expression); var newMember = CopyElement(this.Member); - return new MemberExpressionAst(this.Extent, newExpression, newMember, this.Static, this.NullConditional); + + return new MemberExpressionAst( + this.Extent, + newExpression, + newMember, + this.Static, + this.NullConditional); } #region Visitors @@ -7975,7 +8115,7 @@ IAssignableValue ISupportsAssignment.GetAssignableValue() public class InvokeMemberExpressionAst : MemberExpressionAst, ISupportsAssignment { /// - /// Construct an instance of a method invocation expression. + /// Initializes a new instance of the class. /// /// /// The extent of the expression, starting with the expression before the invocation operator and ending with the @@ -7987,10 +8127,17 @@ public class InvokeMemberExpressionAst : MemberExpressionAst, ISupportsAssignmen /// /// True if the invocation is for a static method, using '::', false if invoking a method on an instance using '.'. /// + /// The generic type arguments passed to the method. /// /// If is null. /// - public InvokeMemberExpressionAst(IScriptExtent extent, ExpressionAst expression, CommandElementAst method, IEnumerable arguments, bool @static) + public InvokeMemberExpressionAst( + IScriptExtent extent, + ExpressionAst expression, + CommandElementAst method, + IEnumerable arguments, + bool @static, + IList genericTypes) : base(extent, expression, method, @static) { if (arguments != null && arguments.Any()) @@ -7998,6 +8145,37 @@ public InvokeMemberExpressionAst(IScriptExtent extent, ExpressionAst expression, this.Arguments = new ReadOnlyCollection(arguments.ToArray()); SetParents(Arguments); } + + if (genericTypes != null && genericTypes.Count > 0) + { + this.GenericTypeArguments = new ReadOnlyCollection(genericTypes); + } + } + + /// + /// Initializes a new instance of the class. + /// + /// + /// The extent of the expression, starting with the expression before the invocation operator and ending with the + /// closing paren after the arguments. + /// + /// The expression before the invocation operator ('.', '::'). + /// The method to invoke. + /// The arguments to pass to the method. + /// + /// True if the invocation is for a static method, using '::', false if invoking a method on an instance using '.'. + /// + /// + /// If is null. + /// + public InvokeMemberExpressionAst( + IScriptExtent extent, + ExpressionAst expression, + CommandElementAst method, + IEnumerable arguments, + bool @static) + : this(extent, expression, method, arguments, @static, genericTypes: null) + { } /// @@ -8014,15 +8192,56 @@ public InvokeMemberExpressionAst(IScriptExtent extent, ExpressionAst expression, /// True if the invocation is for a static method, using '::', false if invoking a method on an instance using '.' or '?.'. /// /// True if the operator used is '?.'. + /// The generic type arguments passed to the method. /// /// If is null. /// - public InvokeMemberExpressionAst(IScriptExtent extent, ExpressionAst expression, CommandElementAst method, IEnumerable arguments, bool @static, bool nullConditional) - : this(extent, expression, method, arguments, @static) + public InvokeMemberExpressionAst( + IScriptExtent extent, + ExpressionAst expression, + CommandElementAst method, + IEnumerable arguments, + bool @static, + bool nullConditional, + IList genericTypes) + : this(extent, expression, method, arguments, @static, genericTypes) { this.NullConditional = nullConditional; } + /// + /// Initializes a new instance of the class. + /// + /// + /// The extent of the expression, starting with the expression before the invocation operator and ending with the + /// closing paren after the arguments. + /// + /// The expression before the invocation operator ('.', '::' or '?.'). + /// The method to invoke. + /// The arguments to pass to the method. + /// + /// True if the invocation is for a static method, using '::', false if invoking a method on an instance using '.' or '?.'. + /// + /// True if the operator used is '?.'. + /// + /// If is null. + /// + public InvokeMemberExpressionAst( + IScriptExtent extent, + ExpressionAst expression, + CommandElementAst method, + IEnumerable arguments, + bool @static, + bool nullConditional) + : this(extent, expression, method, arguments, @static, nullConditional, genericTypes: null) + { + } + + /// + /// Gets a list of generic type arguments passed to this method invocation. + /// + public ReadOnlyCollection GenericTypeArguments { get; } + /// /// The non-empty collection of arguments to pass when invoking the method, or null if no arguments were specified. /// @@ -8036,7 +8255,15 @@ public override Ast Copy() var newExpression = CopyElement(this.Expression); var newMethod = CopyElement(this.Member); var newArguments = CopyElements(this.Arguments); - return new InvokeMemberExpressionAst(this.Extent, newExpression, newMethod, newArguments, this.Static, this.NullConditional); + + return new InvokeMemberExpressionAst( + this.Extent, + newExpression, + newMethod, + newArguments, + this.Static, + this.NullConditional, + this.GenericTypeArguments); } #region Visitors @@ -8116,8 +8343,7 @@ public BaseCtorInvokeMemberExpressionAst(IScriptExtent baseKeywordExtent, IScrip internal override AstVisitAction InternalVisit(AstVisitor visitor) { AstVisitAction action = AstVisitAction.Continue; - var visitor2 = visitor as AstVisitor2; - if (visitor2 != null) + if (visitor is AstVisitor2 visitor2) { action = visitor2.VisitBaseCtorInvokeMemberExpression(this); if (action == AstVisitAction.SkipChildren) @@ -8139,6 +8365,7 @@ internal override object Accept(ICustomAstVisitor visitor) /// /// The name and attributes of a type. /// +#nullable enable public interface ITypeName { /// @@ -8154,7 +8381,7 @@ public interface ITypeName /// /// The name of the assembly, if specified, otherwise null. /// - string AssemblyName { get; } + string? AssemblyName { get; } /// /// Returns true if the type names an array, false otherwise. @@ -8169,20 +8396,21 @@ public interface ITypeName /// /// Returns the that this typename represents, if such a type exists, null otherwise. /// - Type GetReflectionType(); + Type? GetReflectionType(); /// /// Assuming the typename is an attribute, returns the that this typename represents. /// By convention, the typename may omit the suffix "Attribute". Lookup will attempt to resolve the type as is, /// and if that fails, the suffix "Attribute" will be appended. /// - Type GetReflectionAttributeType(); + Type? GetReflectionAttributeType(); /// /// The extent of the typename. /// IScriptExtent Extent { get; } } +#nullable restore #nullable enable internal interface ISupportsTypeCaching @@ -8196,9 +8424,11 @@ internal interface ISupportsTypeCaching /// public sealed class TypeName : ITypeName, ISupportsTypeCaching { - internal readonly string _name; - internal Type _type; - internal readonly IScriptExtent _extent; + private readonly string _name; + private readonly IScriptExtent _extent; + private readonly int _genericArgumentCount; + private Type _type; + internal TypeDefinitionAst _typeDefinitionAst; /// @@ -8225,8 +8455,7 @@ public TypeName(IScriptExtent extent, string name) throw PSTraceSource.NewArgumentException(nameof(name)); } - int backtick = name.IndexOf('`'); - if (backtick != -1) + if (name.Contains('`')) { name = name.Replace("``", "`"); } @@ -8258,6 +8487,23 @@ public TypeName(IScriptExtent extent, string name, string assembly) AssemblyName = assembly; } + /// + /// Construct a typename that represents a generic type definition. + /// + /// The extent of the typename. + /// The name of the type. + /// The number of generic arguments. + internal TypeName(IScriptExtent extent, string name, int genericArgumentCount) + : this(extent, name) + { + ArgumentOutOfRangeException.ThrowIfLessThan(genericArgumentCount, 0); + + if (genericArgumentCount > 0 && !_name.Contains('`')) + { + _genericArgumentCount = genericArgumentCount; + } + } + /// /// Returns the full name of the type. /// @@ -8305,8 +8551,7 @@ internal bool HasDefaultCtor() bool hasExplicitCtor = false; foreach (var member in _typeDefinitionAst.Members) { - var function = member as FunctionMemberAst; - if (function != null) + if (member is FunctionMemberAst function) { if (function.IsConstructor) { @@ -8335,8 +8580,25 @@ public Type GetReflectionType() { if (_type == null) { - Exception e; - Type type = _typeDefinitionAst != null ? _typeDefinitionAst.Type : TypeResolver.ResolveTypeName(this, out e); + Type type = _typeDefinitionAst != null ? _typeDefinitionAst.Type : TypeResolver.ResolveTypeName(this, out _); + + if (type is null && _genericArgumentCount > 0) + { + // We try an alternate name only if it failed to resolve with the original name. + // This is because for a generic type like `System.Tuple`, the original name `System.Tuple` + // can be resolved and hence `genericTypeName.TypeName.GetReflectionType()` in that case has always been + // returning the type `System.Tuple`. If we change to directly use the alternate name for resolution, the + // return value will become 'System.Tuple`1' in that case, and that's a breaking change. + TypeName newTypeName = new( + _extent, + string.Create(CultureInfo.InvariantCulture, $"{_name}`{_genericArgumentCount}")) + { + AssemblyName = AssemblyName + }; + + type = TypeResolver.ResolveTypeName(newTypeName, out _); + } + if (type != null) { try @@ -8371,7 +8633,11 @@ public Type GetReflectionAttributeType() var result = GetReflectionType(); if (result == null || !typeof(Attribute).IsAssignableFrom(result)) { - var attrTypeName = new TypeName(_extent, FullName + "Attribute"); + TypeName attrTypeName = new(_extent, $"{_name}Attribute", _genericArgumentCount) + { + AssemblyName = AssemblyName + }; + result = attrTypeName.GetReflectionType(); if (result != null && !typeof(Attribute).IsAssignableFrom(result)) { @@ -8664,8 +8930,13 @@ internal Type GetGenericType(Type generic) { if (!TypeName.FullName.Contains('`')) { - var newTypeName = new TypeName(Extent, - string.Format(CultureInfo.InvariantCulture, "{0}`{1}", TypeName.FullName, GenericArguments.Count)); + TypeName newTypeName = new( + Extent, + string.Create(CultureInfo.InvariantCulture, $"{TypeName.Name}`{GenericArguments.Count}")) + { + AssemblyName = TypeName.AssemblyName + }; + generic = newTypeName.GetReflectionType(); } } @@ -8691,8 +8962,13 @@ public Type GetReflectionAttributeType() { if (!TypeName.FullName.Contains('`')) { - var newTypeName = new TypeName(Extent, - string.Format(CultureInfo.InvariantCulture, "{0}Attribute`{1}", TypeName.FullName, GenericArguments.Count)); + TypeName newTypeName = new( + Extent, + string.Create(CultureInfo.InvariantCulture, $"{TypeName.Name}Attribute`{GenericArguments.Count}")) + { + AssemblyName = TypeName.AssemblyName + }; + generic = newTypeName.GetReflectionType(); } } @@ -9579,8 +9855,7 @@ public ExpandableStringExpressionAst(IScriptExtent extent, } var ast = Language.Parser.ScanString(value); - var expandableStringAst = ast as ExpandableStringExpressionAst; - if (expandableStringAst != null) + if (ast is ExpandableStringExpressionAst expandableStringAst) { this.FormatExpression = expandableStringAst.FormatExpression; this.NestedExpressions = expandableStringAst.NestedExpressions; @@ -10201,10 +10476,7 @@ public override Ast Copy() [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "We want to get the underlying variable only for the UsingExpressionAst.")] public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usingExpressionAst) { - if (usingExpressionAst == null) - { - throw new ArgumentNullException(nameof(usingExpressionAst)); - } + ArgumentNullException.ThrowIfNull(usingExpressionAst); return ExtractUsingVariableImpl(usingExpressionAst); } @@ -10216,10 +10488,9 @@ public static VariableExpressionAst ExtractUsingVariable(UsingExpressionAst usin /// private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expression) { - var usingExpr = expression as UsingExpressionAst; VariableExpressionAst variableExpr; - if (usingExpr != null) + if (expression is UsingExpressionAst usingExpr) { variableExpr = usingExpr.SubExpression as VariableExpressionAst; if (variableExpr != null) @@ -10230,8 +10501,7 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr return ExtractUsingVariableImpl(usingExpr.SubExpression); } - var indexExpr = expression as IndexExpressionAst; - if (indexExpr != null) + if (expression is IndexExpressionAst indexExpr) { variableExpr = indexExpr.Target as VariableExpressionAst; if (variableExpr != null) @@ -10242,8 +10512,7 @@ private static VariableExpressionAst ExtractUsingVariableImpl(ExpressionAst expr return ExtractUsingVariableImpl(indexExpr.Target); } - var memberExpr = expression as MemberExpressionAst; - if (memberExpr != null) + if (expression is MemberExpressionAst memberExpr) { variableExpr = memberExpr.Expression as VariableExpressionAst; if (variableExpr != null) diff --git a/src/System.Management.Automation/engine/parser/token.cs b/src/System.Management.Automation/engine/parser/token.cs index 893ec9fc8e0..3cee7580ff9 100644 --- a/src/System.Management.Automation/engine/parser/token.cs +++ b/src/System.Management.Automation/engine/parser/token.cs @@ -200,7 +200,7 @@ public enum TokenKind /// The addition operator '+'. Plus = 40, - /// The substraction operator '-'. + /// The subtraction operator '-'. Minus = 41, /// The assignment operator '='. @@ -588,6 +588,9 @@ public enum TokenKind /// The 'default' keyword Default = 169, + /// The 'clean' keyword. + Clean = 170, + #endregion Keywords } @@ -659,7 +662,7 @@ public enum TokenFlags Keyword = 0x00000010, /// - /// The token one of the keywords that is a part of a script block: 'begin', 'process', 'end', or 'dynamicparam'. + /// The token is one of the keywords that is a part of a script block: 'begin', 'process', 'end', 'clean', or 'dynamicparam'. /// ScriptBlockBlockName = 0x00000020, @@ -948,6 +951,7 @@ public static class TokenTraits /* Hidden */ TokenFlags.Keyword, /* Base */ TokenFlags.Keyword, /* Default */ TokenFlags.Keyword, + /* Clean */ TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName, #endregion Flags for keywords }; @@ -1147,6 +1151,7 @@ public static class TokenTraits /* Hidden */ "hidden", /* Base */ "base", /* Default */ "default", + /* Clean */ "clean", #endregion Text for keywords }; @@ -1154,10 +1159,12 @@ public static class TokenTraits #if DEBUG static TokenTraits() { - Diagnostics.Assert(s_staticTokenFlags.Length == ((int)TokenKind.Default + 1), - "Table size out of sync with enum - _staticTokenFlags"); - Diagnostics.Assert(s_tokenText.Length == ((int)TokenKind.Default + 1), - "Table size out of sync with enum - _tokenText"); + Diagnostics.Assert( + s_staticTokenFlags.Length == ((int)TokenKind.Clean + 1), + "Table size out of sync with enum - _staticTokenFlags"); + Diagnostics.Assert( + s_tokenText.Length == ((int)TokenKind.Clean + 1), + "Table size out of sync with enum - _tokenText"); // Some random assertions to make sure the enum and the traits are in sync Diagnostics.Assert(GetTraits(TokenKind.Begin) == (TokenFlags.Keyword | TokenFlags.ScriptBlockBlockName), "Table out of sync with enum - flags Begin"); @@ -1173,7 +1180,7 @@ static TokenTraits() #endif /// - /// Return all the flags for a given TokenKind. + /// Return all the flags for a given . /// public static TokenFlags GetTraits(this TokenKind kind) { @@ -1181,7 +1188,7 @@ public static TokenFlags GetTraits(this TokenKind kind) } /// - /// Return true if the TokenKind has the given trait. + /// Return true if the has the given trait. /// public static bool HasTrait(this TokenKind kind, TokenFlags flag) { @@ -1195,7 +1202,7 @@ internal static int GetBinaryPrecedence(this TokenKind kind) } /// - /// Return the text for a given TokenKind. + /// Return the text for a given . /// public static string Text(this TokenKind kind) { @@ -1264,7 +1271,7 @@ public override string ToString() internal virtual string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, "{0}{1}: <{2}>", StringUtil.Padding(indent), _kind, Text); + return string.Create(CultureInfo.InvariantCulture, $"{StringUtil.Padding(indent)}{_kind}: <{Text}>"); } } @@ -1283,8 +1290,14 @@ internal NumberToken(InternalScriptExtent scriptExtent, object value, TokenFlags internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <{2}> Value:<{3}> Type:<{4}>", StringUtil.Padding(indent), Kind, Text, _value, _value.GetType().Name); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <{2}> Value:<{3}> Type:<{4}>", + StringUtil.Padding(indent), + Kind, + Text, + _value, + _value.GetType().Name); } /// @@ -1325,8 +1338,13 @@ internal ParameterToken(InternalScriptExtent scriptExtent, string parameterName, internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <-{2}{3}>", StringUtil.Padding(indent), Kind, _parameterName, _usedColon ? ":" : string.Empty); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <-{2}{3}>", + StringUtil.Padding(indent), + Kind, + _parameterName, + _usedColon ? ":" : string.Empty); } } @@ -1353,8 +1371,13 @@ internal VariableToken(InternalScriptExtent scriptExtent, VariablePath path, Tok internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <{2}> Name:<{3}>", StringUtil.Padding(indent), Kind, Text, Name); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <{2}> Name:<{3}>", + StringUtil.Padding(indent), + Kind, + Text, + Name); } } @@ -1376,8 +1399,13 @@ internal StringToken(InternalScriptExtent scriptExtent, TokenKind kind, TokenFla internal override string ToDebugString(int indent) { - return string.Format(CultureInfo.InvariantCulture, - "{0}{1}: <{2}> Value:<{3}>", StringUtil.Padding(indent), Kind, Text, Value); + return string.Format( + CultureInfo.InvariantCulture, + "{0}{1}: <{2}> Value:<{3}>", + StringUtil.Padding(indent), + Kind, + Text, + Value); } } diff --git a/src/System.Management.Automation/engine/parser/tokenizer.cs b/src/System.Management.Automation/engine/parser/tokenizer.cs index 5ab09c0a40f..e2aed94cc98 100644 --- a/src/System.Management.Automation/engine/parser/tokenizer.cs +++ b/src/System.Management.Automation/engine/parser/tokenizer.cs @@ -12,6 +12,8 @@ using System.Text; using Microsoft.PowerShell.Commands; +using System.Management.Automation.Subsystem; +using System.Management.Automation.Subsystem.DSC; using Microsoft.PowerShell.DesiredStateConfiguration.Internal; namespace System.Management.Automation.Language @@ -312,7 +314,7 @@ public DynamicKeyword Copy() public bool HasReservedProperties { get; set; } /// - /// A list of the properties allowed for this constuctor. + /// A list of the properties allowed for this constructor. /// public Dictionary Properties { @@ -325,7 +327,7 @@ public Dictionary Properties private Dictionary _properties; /// - /// A list of the parameters allowed for this constuctor. + /// A list of the parameters allowed for this constructor. /// public Dictionary Parameters { @@ -361,7 +363,15 @@ internal static bool IsMetaDSCResource(this DynamicKeyword keyword) string implementingModule = keyword.ImplementingModule; if (implementingModule != null) { - return implementingModule.Equals(DscClassCache.DefaultModuleInfoForMetaConfigResource.Item1, StringComparison.OrdinalIgnoreCase); + ICrossPlatformDsc dscSubsystem = SubsystemManager.GetSubsystem(); + if (dscSubsystem != null) + { + dscSubsystem.IsDefaultModuleNameForMetaConfigResource(implementingModule); + } + else + { + return implementingModule.Equals(DscClassCache.DefaultModuleInfoForMetaConfigResource.Item1, StringComparison.OrdinalIgnoreCase); + } } return false; @@ -625,23 +635,23 @@ private static readonly Dictionary s_operatorTable /*A*/ "configuration", "public", "private", "static", /*A*/ /*B*/ "interface", "enum", "namespace", "module", /*B*/ /*C*/ "type", "assembly", "command", "hidden", /*C*/ - /*D*/ "base", "default", /*D*/ + /*D*/ "base", "default", "clean", /*D*/ }; private static readonly TokenKind[] s_keywordTokenKind = new TokenKind[] { - /*1*/ TokenKind.ElseIf, TokenKind.If, TokenKind.Else, TokenKind.Switch, /*1*/ - /*2*/ TokenKind.Foreach, TokenKind.From, TokenKind.In, TokenKind.For, /*2*/ - /*3*/ TokenKind.While, TokenKind.Until, TokenKind.Do, TokenKind.Try, /*3*/ - /*4*/ TokenKind.Catch, TokenKind.Finally, TokenKind.Trap, TokenKind.Data, /*4*/ - /*5*/ TokenKind.Return, TokenKind.Continue, TokenKind.Break, TokenKind.Exit, /*5*/ - /*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/ - /*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/ - /*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/ - /*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/ - /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ - /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace,TokenKind.Module, /*B*/ - /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ - /*D*/ TokenKind.Base, TokenKind.Default, /*D*/ + /*1*/ TokenKind.ElseIf, TokenKind.If, TokenKind.Else, TokenKind.Switch, /*1*/ + /*2*/ TokenKind.Foreach, TokenKind.From, TokenKind.In, TokenKind.For, /*2*/ + /*3*/ TokenKind.While, TokenKind.Until, TokenKind.Do, TokenKind.Try, /*3*/ + /*4*/ TokenKind.Catch, TokenKind.Finally, TokenKind.Trap, TokenKind.Data, /*4*/ + /*5*/ TokenKind.Return, TokenKind.Continue, TokenKind.Break, TokenKind.Exit, /*5*/ + /*6*/ TokenKind.Throw, TokenKind.Begin, TokenKind.Process, TokenKind.End, /*6*/ + /*7*/ TokenKind.Dynamicparam, TokenKind.Function, TokenKind.Filter, TokenKind.Param, /*7*/ + /*8*/ TokenKind.Class, TokenKind.Define, TokenKind.Var, TokenKind.Using, /*8*/ + /*9*/ TokenKind.Workflow, TokenKind.Parallel, TokenKind.Sequence, TokenKind.InlineScript, /*9*/ + /*A*/ TokenKind.Configuration, TokenKind.Public, TokenKind.Private, TokenKind.Static, /*A*/ + /*B*/ TokenKind.Interface, TokenKind.Enum, TokenKind.Namespace, TokenKind.Module, /*B*/ + /*C*/ TokenKind.Type, TokenKind.Assembly, TokenKind.Command, TokenKind.Hidden, /*C*/ + /*D*/ TokenKind.Base, TokenKind.Default, TokenKind.Clean, /*D*/ }; internal static readonly string[] _operatorText = new string[] { @@ -704,7 +714,7 @@ static Tokenizer() // The hash we compute is intentionally dumb, we want collisions to catch similar strings, // so we just sum up the characters. const string beginSig = "sig#beginsignatureblock"; - beginSig.Aggregate(0, (current, t) => current + t); + beginSig.Aggregate(0, static (current, t) => current + t); // Spot check to help make sure the arrays are in sync Diagnostics.Assert(s_keywordTable["using"] == TokenKind.Using, "Keyword table out of sync w/ enum"); @@ -1208,10 +1218,7 @@ private Token NewCommentToken() private T SaveToken(T token) where T : Token { - if (TokenList != null) - { - TokenList.Add(token); - } + TokenList?.Add(token); // Keep track of the first and last token even if we're not saving tokens // for the special variables $$ and $^. @@ -1224,10 +1231,7 @@ private T SaveToken(T token) where T : Token // Don't remember these tokens, they aren't useful in $$ and $^. break; default: - if (FirstToken == null) - { - FirstToken = token; - } + FirstToken ??= token; LastToken = token; break; @@ -1269,7 +1273,7 @@ private StringToken NewStringExpandableToken(string value, string formatString, } else if ((flags & TokenFlags.TokenInError) == 0) { - if (nestedTokens.Any(tok => tok.HasError)) + if (nestedTokens.Any(static tok => tok.HasError)) { flags |= TokenFlags.TokenInError; } @@ -1797,8 +1801,7 @@ private void ScanLineComment() } else if (matchedRequires && _nestedTokensAdjustment == 0) { - if (RequiresTokens == null) - RequiresTokens = new List(); + RequiresTokens ??= new List(); RequiresTokens.Add(token); } } @@ -1935,10 +1938,7 @@ internal ScriptRequirements GetScriptRequirements() PSSnapinToken.StartsWith(parameter.ParameterName, StringComparison.OrdinalIgnoreCase)) { snapinSpecified = true; - if (requiredSnapins == null) - { - requiredSnapins = new List(); - } + requiredSnapins ??= new List(); break; } @@ -1976,9 +1976,6 @@ internal ScriptRequirements GetScriptRequirements() RequiredPSEditions = requiredEditions != null ? new ReadOnlyCollection(requiredEditions) : ScriptRequirements.EmptyEditionCollection, - RequiresPSSnapIns = requiredSnapins != null - ? new ReadOnlyCollection(requiredSnapins) - : ScriptRequirements.EmptySnapinCollection, RequiredAssemblies = requiredAssemblies != null ? new ReadOnlyCollection(requiredAssemblies) : ScriptRequirements.EmptyAssemblyCollection, @@ -2204,8 +2201,7 @@ private void HandleRequiresParameter(CommandParameterAst parameter, return; } - if (requiredModules == null) - requiredModules = new List(); + requiredModules ??= new List(); requiredModules.Add(moduleSpecification); } } @@ -2228,8 +2224,7 @@ private List HandleRequiresAssemblyArgument(Ast argumentAst, object arg, } else { - if (requiredAssemblies == null) - requiredAssemblies = new List(); + requiredAssemblies ??= new List(); if (!requiredAssemblies.Contains((string)arg)) { @@ -2251,8 +2246,7 @@ private List HandleRequiresPSEditionArgument(Ast argumentAst, object arg } else { - if (requiredEditions == null) - requiredEditions = new List(); + requiredEditions ??= new List(); var edition = (string)arg; if (!Utils.IsValidPSEditionValue(edition)) @@ -2566,7 +2560,7 @@ private bool ScanDollarInStringExpandable(StringBuilder sb, StringBuilder format // Make sure we didn't consume anything because we didn't find // any nested tokens (no variable or subexpression.) - Diagnostics.Assert(PeekChar() == c1, "We accidently consumed a character we shouldn't have."); + Diagnostics.Assert(PeekChar() == c1, "We accidentally consumed a character we shouldn't have."); return false; } @@ -3913,7 +3907,8 @@ private Token ScanNumber(char firstChar) return ScanGenericToken(GetStringBuilder()); } - ReportError(_currentIndex, + ReportError( + NewScriptExtent(_tokenStart, _currentIndex), nameof(ParserStrings.BadNumericConstant), ParserStrings.BadNumericConstant, _script.Substring(_tokenStart, _currentIndex - _tokenStart)); diff --git a/src/System.Management.Automation/engine/pipeline.cs b/src/System.Management.Automation/engine/pipeline.cs index 14837fd1c5c..191f80e1d89 100644 --- a/src/System.Management.Automation/engine/pipeline.cs +++ b/src/System.Management.Automation/engine/pipeline.cs @@ -7,6 +7,7 @@ using System.Management.Automation.Tracing; using System.Reflection; using System.Runtime.ExceptionServices; +using System.Threading; using Microsoft.PowerShell.Telemetry; using Dbg = System.Management.Automation.Diagnostics; @@ -29,6 +30,7 @@ internal class PipelineProcessor : IDisposable { #region private_members + private readonly CancellationTokenSource _pipelineStopTokenSource = new CancellationTokenSource(); private List _commands = new List(); private List _redirectionPipes; private PipelineReader _externalInputPipe; @@ -43,6 +45,10 @@ internal class PipelineProcessor : IDisposable private bool _linkedSuccessOutput = false; private bool _linkedErrorOutput = false; + private NativeCommandProcessor _lastNativeCommand; + + private bool _haveReportedNativePipeUsage; + #if !CORECLR // Impersonation Not Supported On CSS // This is the security context when the pipeline was allocated internal System.Security.SecurityContext SecurityContext = @@ -66,7 +72,6 @@ internal class PipelineProcessor : IDisposable public void Dispose() { Dispose(true); - GC.SuppressFinalize(this); } private void Dispose(bool disposing) @@ -82,6 +87,7 @@ private void Dispose(bool disposing) _externalErrorOutput = null; _executionScope = null; _eventLogBuffer = null; + _pipelineStopTokenSource.Dispose(); #if !CORECLR // Impersonation Not Supported On CSS SecurityContext.Dispose(); SecurityContext = null; @@ -115,6 +121,11 @@ internal bool ExecutionFailed } } + /// + /// Gets the CancellationToken that is signaled when the pipeline is stopping. + /// + internal CancellationToken PipelineStopToken => _pipelineStopTokenSource.Token; + internal void LogExecutionInfo(InvocationInfo invocationInfo, string text) { string message = StringUtil.Format(PipelineStrings.PipelineExecutionInformation, GetCommand(invocationInfo), text); @@ -214,50 +225,36 @@ private void Log(string logElement, InvocationInfo invocation, PipelineExecution // Log the cmdlet invocation execution details if we didn't have an associated script line with it. if ((invocation == null) || string.IsNullOrEmpty(invocation.Line)) { - if (hostInterface != null) - { - hostInterface.TranscribeCommand(logElement, invocation); - } + hostInterface?.TranscribeCommand(logElement, invocation); } - if (!string.IsNullOrEmpty(logElement)) + if (_needToLog && !string.IsNullOrEmpty(logElement)) { + _eventLogBuffer ??= new List(); _eventLogBuffer.Add(logElement); } } - internal void LogToEventLog() - { - if (NeedToLog()) - { - // We check to see if the command is needs writing (or if there is anything in the buffer) - // before we flush it. Flushing the empty buffer causes a measurable performance degradation. - if (_commands == null || _commands.Count == 0 || _eventLogBuffer.Count == 0) - return; - - MshLog.LogPipelineExecutionDetailEvent(_commands[0].Command.Context, - _eventLogBuffer, - _commands[0].Command.MyInvocation); - } - } - - private bool NeedToLog() + private void LogToEventLog() { - if (_commands == null) - return false; - - foreach (CommandProcessorBase commandProcessor in _commands) + // We check to see if there is anything in the buffer before we flush it. + // Flushing the empty buffer causes a measurable performance degradation. + if (_commands?.Count > 0 && _eventLogBuffer?.Count > 0) { - MshCommandRuntime cmdRuntime = commandProcessor.Command.commandRuntime as MshCommandRuntime; - - if (cmdRuntime != null && cmdRuntime.LogPipelineExecutionDetail) - return true; + InternalCommand firstCmd = _commands[0].Command; + MshLog.LogPipelineExecutionDetailEvent( + firstCmd.Context, + _eventLogBuffer, + firstCmd.MyInvocation); } - return false; + // Clear the log buffer after writing the event. + _eventLogBuffer?.Clear(); } - private List _eventLogBuffer = new List(); + private bool _needToLog = false; + private List _eventLogBuffer; + #endregion #region public_methods @@ -272,15 +269,40 @@ private bool NeedToLog() /// internal int Add(CommandProcessorBase commandProcessor) { + if (commandProcessor is NativeCommandProcessor nativeCommand) + { + if (_lastNativeCommand is not null) + { + // Only report experimental feature usage once per pipeline. + if (!_haveReportedNativePipeUsage) + { + ApplicationInsightsTelemetry.SendExperimentalUseData("PSNativeCommandPreserveBytePipe", "p"); + _haveReportedNativePipeUsage = true; + } + + _lastNativeCommand.DownStreamNativeCommand = nativeCommand; + nativeCommand.UpstreamIsNativeCommand = true; + } + + _lastNativeCommand = nativeCommand; + } + else + { + _lastNativeCommand = null; + } + commandProcessor.CommandRuntime.PipelineProcessor = this; - return AddCommand(commandProcessor, _commands.Count, false); + return AddCommand(commandProcessor, _commands.Count, readErrorQueue: false); } internal void AddRedirectionPipe(PipelineProcessor pipelineProcessor) { - if (pipelineProcessor == null) throw PSTraceSource.NewArgumentNullException(nameof(pipelineProcessor)); - if (_redirectionPipes == null) - _redirectionPipes = new List(); + if (pipelineProcessor is null) + { + throw PSTraceSource.NewArgumentNullException(nameof(pipelineProcessor)); + } + + _redirectionPipes ??= new List(); _redirectionPipes.Add(pipelineProcessor); } @@ -306,7 +328,7 @@ internal void AddRedirectionPipe(PipelineProcessor pipelineProcessor) /// PipeAlreadyTaken: the downstream pipe of command /// is already taken /// - internal int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue) + private int AddCommand(CommandProcessorBase commandProcessor, int readFromCommand, bool readErrorQueue) { if (commandProcessor == null) { @@ -358,18 +380,15 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma } else { - CommandProcessorBase prevcommandProcessor = _commands[readFromCommand - 1] as CommandProcessorBase; - if (prevcommandProcessor == null || prevcommandProcessor.CommandRuntime == null) - { - // "PipelineProcessor.AddCommand(): previous request object == null" - throw PSTraceSource.NewInvalidOperationException(); - } + var prevcommandProcessor = _commands[readFromCommand - 1] as CommandProcessorBase; + ValidateCommandProcessorNotNull(prevcommandProcessor, errorMessage: null); + + Pipe UpstreamPipe = (readErrorQueue) + ? prevcommandProcessor.CommandRuntime.ErrorOutputPipe + : prevcommandProcessor.CommandRuntime.OutputPipe; - Pipe UpstreamPipe = (readErrorQueue) ? - prevcommandProcessor.CommandRuntime.ErrorOutputPipe : prevcommandProcessor.CommandRuntime.OutputPipe; if (UpstreamPipe == null) { - // "PipelineProcessor.AddCommand(): UpstreamPipe == null" throw PSTraceSource.NewInvalidOperationException(); } @@ -392,11 +411,8 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma for (int i = 0; i < _commands.Count; i++) { prevcommandProcessor = _commands[i]; - if (prevcommandProcessor == null || prevcommandProcessor.CommandRuntime == null) - { - // "PipelineProcessor.AddCommand(): previous request object == null" - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(prevcommandProcessor, errorMessage: null); + // check whether the error output is already claimed if (prevcommandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet != null) continue; @@ -412,6 +428,9 @@ internal int AddCommand(CommandProcessorBase commandProcessor, int readFromComma _commands.Add(commandProcessor); + // We will log event(s) about the pipeline execution details if any command in the pipeline requests that. + _needToLog |= commandProcessor.CommandRuntime.LogPipelineExecutionDetail; + // We give the Command a pointer back to the // PipelineProcessor so that it can check whether the // command has been stopped. @@ -478,192 +497,303 @@ internal Array SynchronousExecuteEnumerate(object input) throw new PipelineStoppedException(); } - ExceptionDispatchInfo toRethrowInfo; + bool pipelineSucceeded = false; + ExceptionDispatchInfo toRethrowInfo = null; + CommandProcessorBase commandRequestingUpstreamCommandsToStop = null; + try { - CommandProcessorBase commandRequestingUpstreamCommandsToStop = null; try { - // If the caller specified an input object array, - // we run assuming there is an incoming "stream" - // of objects. This will prevent the one default call - // to ProcessRecord on the first command. - Start(input != AutomationNull.Value); + try + { + // If the caller specified an input object array, we run assuming there is an incoming "stream" + // of objects. This will prevent the one default call to ProcessRecord on the first command. + Start(incomingStream: input != AutomationNull.Value); - // Start has already validated firstcommandProcessor - CommandProcessorBase firstCommandProcessor = _commands[0]; + // Start has already validated firstcommandProcessor + CommandProcessorBase firstCommandProcessor = _commands[0]; - // Add any input to the first command. - if (ExternalInput != null) + // Add any input to the first command. + if (ExternalInput is not null) + { + firstCommandProcessor.CommandRuntime.InputPipe.ExternalReader = ExternalInput; + } + + Inject(input, enumerate: true); + } + catch (PipelineStoppedException) { - firstCommandProcessor.CommandRuntime.InputPipe.ExternalReader - = ExternalInput; + if (_firstTerminatingError?.SourceException is StopUpstreamCommandsException exception) + { + _firstTerminatingError = null; + commandRequestingUpstreamCommandsToStop = exception.RequestingCommandProcessor; + } + else + { + throw; + } } - Inject(input, enumerate: true); + DoCompleteCore(commandRequestingUpstreamCommandsToStop); + pipelineSucceeded = true; } - catch (PipelineStoppedException) + finally { - StopUpstreamCommandsException stopUpstreamCommandsException = - _firstTerminatingError != null - ? _firstTerminatingError.SourceException as StopUpstreamCommandsException - : null; - if (stopUpstreamCommandsException == null) - { - throw; - } - else - { - _firstTerminatingError = null; - commandRequestingUpstreamCommandsToStop = stopUpstreamCommandsException.RequestingCommandProcessor; - } + // Clean up resources for script commands, no matter the pipeline succeeded or not. + // This method catches and handles all exceptions inside, so it will never throw. + Clean(); } - DoCompleteCore(commandRequestingUpstreamCommandsToStop); - - // By this point, we are sure all commandProcessors hosted by the current pipelineProcess are done execution, - // so if there are any redirection pipelineProcessors associated with any of those commandProcessors, we should - // call DoComplete on them. - if (_redirectionPipes != null) + if (pipelineSucceeded) { - foreach (PipelineProcessor redirectPipelineProcessor in _redirectionPipes) + // Now, we are sure all 'commandProcessors' hosted by the current 'pipelineProcessor' are done execution, + // so if there are any redirection 'pipelineProcessors' associated with any of those 'commandProcessors', + // they must have successfully executed 'StartStepping' and 'Step', and thus we should call 'DoComplete' + // on them for completeness. + if (_redirectionPipes is not null) { - redirectPipelineProcessor.DoCompleteCore(null); + foreach (PipelineProcessor redirectPipelineProcessor in _redirectionPipes) + { + // The 'Clean' block for each 'commandProcessor' might still write to a pipe that is associated + // with the redirection 'pipelineProcessor' (e.g. a redirected error pipe), which would trigger + // the call to 'pipelineProcessor.Step'. + // It's possible (though very unlikely) that the call to 'pipelineProcessor.Step' failed with an + // exception, and in such case, the 'pipelineProcessor' would have been disposed, and therefore + // the call to 'DoComplete' will simply return, because '_commands' was already set to null. + redirectPipelineProcessor.DoCompleteCore(null); + } } - } - return RetrieveResults(); + // The 'Clean' blocks write nothing to the output pipe, so the results won't be affected by them. + return RetrieveResults(); + } } catch (RuntimeException e) { - // The error we want to report is the first terminating error - // which occurred during pipeline execution, regardless - // of whether other errors occurred afterward. - toRethrowInfo = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); - this.LogExecutionException(toRethrowInfo.SourceException); - } - // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN - catch (System.Runtime.InteropServices.InvalidComObjectException comException) - { - // The error we want to report is the first terminating error - // which occurred during pipeline execution, regardless - // of whether other errors occurred afterward. - if (_firstTerminatingError != null) - { - toRethrowInfo = _firstTerminatingError; - } - else - { - string message = StringUtil.Format(ParserStrings.InvalidComObjectException, comException.Message); - var rte = new RuntimeException(message, comException); - rte.SetErrorId("InvalidComObjectException"); - toRethrowInfo = ExceptionDispatchInfo.Capture(rte); - } - - this.LogExecutionException(toRethrowInfo.SourceException); + toRethrowInfo = GetFirstError(e); } finally { DisposeCommands(); } - // By rethrowing the exception outside of the handler, - // we allow the CLR on X64/IA64 to free from the stack - // the exception records related to this exception. + // By rethrowing the exception outside of the handler, we allow the CLR on X64/IA64 to free from + // the stack the exception records related to this exception. - // The only reason we should get here is if - // an exception should be rethrown. + // The only reason we should get here is if an exception should be rethrown. Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure"); toRethrowInfo.Throw(); - return null; // UNREACHABLE + + // UNREACHABLE + return null; + } + + private ExceptionDispatchInfo GetFirstError(RuntimeException e) + { + // The error we want to report is the first terminating error which occurred during pipeline execution, + // regardless of whether other errors occurred afterward. + var firstError = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); + LogExecutionException(firstError.SourceException); + return firstError; + } + + private void ThrowFirstErrorIfExisting(bool logException) + { + if (_firstTerminatingError != null) + { + if (logException) + { + LogExecutionException(_firstTerminatingError.SourceException); + } + + _firstTerminatingError.Throw(); + } } private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamCommandsToStop) { - // Call DoComplete() for all the commands. DoComplete() will internally call Complete() + if (_commands is null) + { + // This could happen to a redirection pipeline, either for an expression (e.g. 1 > a.txt) + // or for a command (e.g. command > a.txt). + // An exception may be thrown from the call to 'StartStepping' or 'Step' on the pipeline, + // which causes the pipeline commands to be disposed. + return; + } + + // Call DoComplete() for all the commands, which will internally call Complete() MshCommandRuntime lastCommandRuntime = null; - if (_commands != null) + for (int i = 0; i < _commands.Count; i++) { - for (int i = 0; i < _commands.Count; i++) - { - CommandProcessorBase commandProcessor = _commands[i]; + CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor == null) - { - // "null command " + i - throw PSTraceSource.NewInvalidOperationException(); - } + if (commandProcessor is null) + { + // An internal error that should not happen. + throw PSTraceSource.NewInvalidOperationException(); + } - if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, commandProcessor)) - { - commandRequestingUpstreamCommandsToStop = null; - continue; // do not call DoComplete/EndProcessing on the command that initiated stopping - } + if (object.ReferenceEquals(commandRequestingUpstreamCommandsToStop, commandProcessor)) + { + // Do not call DoComplete/EndProcessing on the command that initiated stopping. + commandRequestingUpstreamCommandsToStop = null; + continue; + } - if (commandRequestingUpstreamCommandsToStop != null) - { - continue; // do not call DoComplete/EndProcessing on commands that were stopped upstream - } + if (commandRequestingUpstreamCommandsToStop is not null) + { + // Do not call DoComplete/EndProcessing on commands that were stopped upstream. + continue; + } - try + try + { + commandProcessor.DoComplete(); + } + catch (PipelineStoppedException) + { + if (_firstTerminatingError?.SourceException is StopUpstreamCommandsException exception) { - commandProcessor.DoComplete(); + _firstTerminatingError = null; + commandRequestingUpstreamCommandsToStop = exception.RequestingCommandProcessor; } - catch (PipelineStoppedException) + else { - StopUpstreamCommandsException stopUpstreamCommandsException = - _firstTerminatingError != null - ? _firstTerminatingError.SourceException as StopUpstreamCommandsException - : null; - if (stopUpstreamCommandsException == null) - { - throw; - } - else - { - _firstTerminatingError = null; - commandRequestingUpstreamCommandsToStop = stopUpstreamCommandsException.RequestingCommandProcessor; - } + throw; } + } - EtwActivity.SetActivityId(commandProcessor.PipelineActivityId); - - // Log a command stopped event - MshLog.LogCommandLifecycleEvent( - commandProcessor.Command.Context, - CommandState.Stopped, - commandProcessor.Command.MyInvocation); + EtwActivity.SetActivityId(commandProcessor.PipelineActivityId); - // Log the execution of a command (not script chunks, as they - // are not commands in and of themselves) - if (commandProcessor.CommandInfo.CommandType != CommandTypes.Script) - { - commandProcessor.CommandRuntime.PipelineProcessor.LogExecutionComplete( - commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name); - } + // Log a command stopped event + MshLog.LogCommandLifecycleEvent( + commandProcessor.Command.Context, + CommandState.Stopped, + commandProcessor.Command.MyInvocation); - lastCommandRuntime = commandProcessor.CommandRuntime; + // Log the execution of a command (not script chunks, as they are not commands in and of themselves). + if (commandProcessor.CommandInfo.CommandType != CommandTypes.Script) + { + LogExecutionComplete(commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name); } + + lastCommandRuntime = commandProcessor.CommandRuntime; } // Log the pipeline completion. - if (lastCommandRuntime != null) + if (lastCommandRuntime is not null) { // Only log the pipeline completion if this wasn't a nested pipeline, as // pipeline state in transcription is associated with the toplevel pipeline - if ((this.LocalPipeline == null) || (!this.LocalPipeline.IsNested)) + if (LocalPipeline is null || !LocalPipeline.IsNested) { lastCommandRuntime.PipelineProcessor.LogPipelineComplete(); } } // If a terminating error occurred, report it now. - if (_firstTerminatingError != null) + // This pipeline could have been stopped asynchronously, by 'Ctrl+c' manually or + // 'PowerShell.Stop' programatically. We need to check and see if that's the case. + // An example: + // - 'Start-Sleep' is running in this pipeline, and 'pipelineProcessor.Stop' gets + // called on a different thread, which sets a 'PipelineStoppedException' object + // to '_firstTerminatingError' and runs 'StopProcessing' on 'Start-Sleep'. + // - The 'StopProcessing' will cause 'Start-Sleep' to return from 'ProcessRecord' + // call, and thus the pipeline execution will move forward to run 'DoComplete' + // for the 'Start-Sleep' command and thus the code flow will reach here. + // For this given example, we need to check '_firstTerminatingError' and throw out + // the 'PipelineStoppedException' if the pipeline was indeed being stopped. + ThrowFirstErrorIfExisting(logException: true); + } + + /// + /// Clean up resources for script commands in this pipeline processor. + /// + /// + /// Exception from a 'Clean' block is not allowed to propagate up and terminate the pipeline + /// so that other 'Clean' blocks can run without being affected. Therefore, this method will + /// catch and handle all exceptions inside, and it will never throw. + /// + private void Clean() + { + if (!_executionStarted || _commands is null) { - this.LogExecutionException(_firstTerminatingError.SourceException); - _firstTerminatingError.Throw(); + // Simply return if the pipeline execution wasn't even started, or the commands of + // the pipeline have already been disposed. + return; } + + // So far, if '_firstTerminatingError' is not null, then it must be a terminating error + // thrown from one of 'Begin/Process/End' blocks. There can be terminating error thrown + // from 'Clean' block as well, which needs to be handled in this method. + // In order to capture the subsequent first terminating error thrown from 'Clean', we + // need to forget the previous '_firstTerminatingError' value before calling 'DoClean' + // on each command processor, so we have to save the old value here and restore later. + ExceptionDispatchInfo oldFirstTerminatingError = _firstTerminatingError; + + // Suspend a stopping pipeline by setting 'IsStopping' to false and restore it afterwards. + bool oldIsStopping = ExceptionHandlingOps.SuspendStoppingPipelineImpl(LocalPipeline); + + try + { + foreach (CommandProcessorBase commandProcessor in _commands) + { + if (commandProcessor is null || !commandProcessor.HasCleanBlock) + { + continue; + } + + try + { + // Forget the terminating error we saw before, so a terminating error thrown + // from the subsequent 'Clean' block can be recorded and handled properly. + _firstTerminatingError = null; + commandProcessor.DoCleanup(); + } + catch (RuntimeException e) + { + // Retrieve and report the terminating error that was thrown in the 'Clean' block. + ExceptionDispatchInfo firstError = GetFirstError(e); + commandProcessor.ReportCleanupError(firstError.SourceException); + } + catch (Exception ex) + { + // Theoretically, only 'RuntimeException' could be thrown out, but we catch + // all and log them here just to be safe. + // Skip special flow control exceptions and log others. + if (ex is not FlowControlException && ex is not HaltCommandException) + { + MshLog.LogCommandHealthEvent(commandProcessor.Context, ex, Severity.Warning); + } + } + } + } + finally + { + _firstTerminatingError = oldFirstTerminatingError; + ExceptionHandlingOps.RestoreStoppingPipelineImpl(LocalPipeline, oldIsStopping); + } + } + + /// + /// Clean up resources for the script commands of a steppable pipeline. + /// + /// + /// The way we handle 'Clean' blocks in 'StartStepping', 'Step', and 'DoComplete' makes sure that: + /// 1. The 'Clean' blocks get to run if any exception is thrown from the pipeline execution. + /// 2. The 'Clean' blocks get to run if the pipeline runs to the end successfully. + /// However, this is not enough for a steppable pipeline, because the function, where the steppable + /// pipeline gets used, may fail (think about a proxy function). And that may lead to the situation + /// where "no exception was thrown from the steppable pipeline" but "the steppable pipeline didn't + /// run to the end". In that case, 'Clean' won't run unless it's triggered explicitly on the steppable + /// pipeline. This method is how we will expose this functionality to 'SteppablePipeline'. + /// + internal void DoCleanup() + { + Clean(); + DisposeCommands(); } /// @@ -673,98 +803,79 @@ private void DoCompleteCore(CommandProcessorBase commandRequestingUpstreamComman /// The results of the execution. internal Array DoComplete() { - if (Stopping) - { - throw new PipelineStoppedException(); - } - if (!_executionStarted) { throw PSTraceSource.NewInvalidOperationException( PipelineStrings.PipelineNotStarted); } - ExceptionDispatchInfo toRethrowInfo; try { - DoCompleteCore(null); + if (Stopping) + { + throw new PipelineStoppedException(); + } - return RetrieveResults(); - } - catch (RuntimeException e) - { - // The error we want to report is the first terminating error - // which occurred during pipeline execution, regardless - // of whether other errors occurred afterward. - toRethrowInfo = _firstTerminatingError ?? ExceptionDispatchInfo.Capture(e); - this.LogExecutionException(toRethrowInfo.SourceException); - } - // NTRAID#Windows Out Of Band Releases-929020-2006/03/14-JonN - catch (System.Runtime.InteropServices.InvalidComObjectException comException) - { - // The error we want to report is the first terminating error - // which occurred during pipeline execution, regardless - // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + ExceptionDispatchInfo toRethrowInfo; + try { - toRethrowInfo = _firstTerminatingError; + DoCompleteCore(null); + return RetrieveResults(); } - else + catch (RuntimeException e) { - string message = StringUtil.Format(ParserStrings.InvalidComObjectException, comException.Message); - var rte = new RuntimeException(message, comException); - rte.SetErrorId("InvalidComObjectException"); - toRethrowInfo = ExceptionDispatchInfo.Capture(rte); + toRethrowInfo = GetFirstError(e); } - this.LogExecutionException(toRethrowInfo.SourceException); + // By rethrowing the exception outside of the handler, we allow the CLR on X64/IA64 to free from the stack + // the exception records related to this exception. + + // The only reason we should get here is an exception should be rethrown. + Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure"); + toRethrowInfo.Throw(); + + // UNREACHABLE + return null; } finally { + Clean(); DisposeCommands(); } - - // By rethrowing the exception outside of the handler, - // we allow the CLR on X64/IA64 to free from the stack - // the exception records related to this exception. - - // The only reason we should get here is if - // an exception should be rethrown. - Diagnostics.Assert(toRethrowInfo != null, "Alternate protocol path failure"); - toRethrowInfo.Throw(); - return null; // UNREACHABLE } /// - /// This routine starts the stepping process. It is optional to - /// call this but can be useful if you want the begin clauses - /// of the pipeline to be run even when there may not be any input - /// to process as is the case for I/O redirection into a file. We - /// still want the file opened, even if there was nothing to write to it. + /// This routine starts the stepping process. It is optional to call this but can be useful + /// if you want the begin clauses of the pipeline to be run even when there may not be any + /// input to process as is the case for I/O redirection into a file. We still want the file + /// opened, even if there was nothing to write to it. /// /// True if you want to write to this pipeline. internal void StartStepping(bool expectInput) { + bool startSucceeded = false; try { Start(expectInput); + startSucceeded = true; - // If a terminating error occurred, report it now. - if (_firstTerminatingError != null) - { - _firstTerminatingError.Throw(); - } + // Check if this pipeline is being stopped asynchronously. + ThrowFirstErrorIfExisting(logException: false); } - catch (PipelineStoppedException) + catch (Exception e) { + Clean(); DisposeCommands(); - // The error we want to report is the first terminating error - // which occurred during pipeline execution, regardless - // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + if (!startSucceeded && e is PipelineStoppedException) { - _firstTerminatingError.Throw(); + // When a terminating error happens during command execution, PowerShell will first save it + // to '_firstTerminatingError', and then throw a 'PipelineStoppedException' to tear down the + // pipeline. So when the caught exception here is 'PipelineStoppedException', it may not be + // the actual original terminating error. + // In this case, we want to report the first terminating error which occurred during pipeline + // execution, regardless of whether other errors occurred afterward. + ThrowFirstErrorIfExisting(logException: false); } throw; @@ -781,35 +892,37 @@ internal void Stop() // Only call StopProcessing if the pipeline is being stopped // for the first time - if (!RecordFailure(new PipelineStoppedException(), null)) + if (!RecordFailure(new PipelineStoppedException(), command: null)) + { return; + } // Retain copy of _commands in case Dispose() is called List commands = _commands; - if (commands == null) + if (commands is null) + { return; + } + + _pipelineStopTokenSource.Cancel(); // Call StopProcessing() for all the commands. - for (int i = 0; i < commands.Count; i++) + foreach (CommandProcessorBase commandProcessor in commands) { - CommandProcessorBase commandProcessor = commands[i]; - if (commandProcessor == null) { throw PSTraceSource.NewInvalidOperationException(); } -#pragma warning disable 56500 + try { commandProcessor.Command.DoStopProcessing(); } catch (Exception) { - // 2004/04/26-JonN We swallow exceptions - // which occur during StopProcessing. + // We swallow exceptions which occur during StopProcessing. continue; } -#pragma warning restore 56500 } } @@ -852,43 +965,35 @@ internal void Stop() /// internal Array Step(object input) { - if (Stopping) - { - throw new PipelineStoppedException(); - } - + bool injectSucceeded = false; try { Start(true); Inject(input, enumerate: false); + injectSucceeded = true; - // If a terminating error occurred, report it now. - if (_firstTerminatingError != null) - { - _firstTerminatingError.Throw(); - } - + // Check if this pipeline is being stopped asynchronously. + ThrowFirstErrorIfExisting(logException: false); return RetrieveResults(); } - catch (PipelineStoppedException) + catch (Exception e) { + Clean(); DisposeCommands(); - // The error we want to report is the first terminating error - // which occurred during pipeline execution, regardless - // of whether other errors occurred afterward. - if (_firstTerminatingError != null) + if (!injectSucceeded && e is PipelineStoppedException) { - _firstTerminatingError.Throw(); + // When a terminating error happens during command execution, PowerShell will first save it + // to '_firstTerminatingError', and then throw a 'PipelineStoppedException' to tear down the + // pipeline. So when the caught exception here is 'PipelineStoppedException', it may not be + // the actual original terminating error. + // In this case, we want to report the first terminating error which occurred during pipeline + // execution, regardless of whether other errors occurred afterward. + ThrowFirstErrorIfExisting(logException: false); } throw; } - catch (Exception) - { - DisposeCommands(); - throw; - } } /// @@ -935,7 +1040,9 @@ private void Start(bool incomingStream) } if (_executionStarted) + { return; + } if (_commands == null || _commands.Count == 0) { @@ -944,32 +1051,18 @@ private void Start(bool incomingStream) } CommandProcessorBase firstcommandProcessor = _commands[0]; - if (firstcommandProcessor == null - || firstcommandProcessor.CommandRuntime == null) - { - throw PSTraceSource.NewInvalidOperationException( - PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); - } + ValidateCommandProcessorNotNull(firstcommandProcessor, PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); // Set the execution scope using the current scope - if (_executionScope == null) - { - _executionScope = firstcommandProcessor.Context.EngineSessionState.CurrentScope; - } + _executionScope ??= firstcommandProcessor.Context.EngineSessionState.CurrentScope; // add ExternalSuccessOutput to the last command CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; - if (LastCommandProcessor == null - || LastCommandProcessor.CommandRuntime == null) - { - // "PipelineProcessor.Start(): LastCommandProcessor == null" - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(LastCommandProcessor, errorMessage: null); if (ExternalSuccessOutput != null) { - LastCommandProcessor.CommandRuntime.OutputPipe.ExternalWriter - = ExternalSuccessOutput; + LastCommandProcessor.CommandRuntime.OutputPipe.ExternalWriter = ExternalSuccessOutput; } // add ExternalErrorOutput to all commands whose error @@ -983,20 +1076,17 @@ private void Start(bool incomingStream) } // We want the value of PSDefaultParameterValues before possibly changing to the commands scopes. - // This ensures we use the value from the callers scope, not the callees scope. + // This ensures we use the value from the caller's scope, not the callee's scope. IDictionary psDefaultParameterValues = firstcommandProcessor.Context.GetVariableValue(SpecialVariables.PSDefaultParameterValuesVarPath, false) as IDictionary; _executionStarted = true; - // // Allocate the pipeline iteration array; note that the pipeline position for // each command starts at 1 so we need to allocate _commands.Count + 1 items. - // int[] pipelineIterationInfo = new int[_commands.Count + 1]; - // Prepare all commands from Engine's side, - // and make sure they are all valid + // Prepare all commands from Engine's side, and make sure they are all valid for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; @@ -1008,8 +1098,6 @@ private void Start(bool incomingStream) // Generate new Activity Id for the thread Guid pipelineActivityId = EtwActivity.CreateActivityId(); - - // commandProcess.PipelineActivityId = new Activity id EtwActivity.SetActivityId(pipelineActivityId); commandProcessor.PipelineActivityId = pipelineActivityId; @@ -1019,20 +1107,14 @@ private void Start(bool incomingStream) CommandState.Started, commandProcessor.Command.MyInvocation); - // Telemetry here - // the type of command should be sent along - // commandProcessor.CommandInfo.CommandType - ApplicationInsightsTelemetry.SendTelemetryMetric(TelemetryType.ApplicationType, commandProcessor.Command.CommandInfo.CommandType.ToString()); #if LEGACYTELEMETRY Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.TraceExecutedCommand(commandProcessor.Command.CommandInfo, commandProcessor.Command.CommandOrigin); #endif - // Log the execution of a command (not script chunks, as they - // are not commands in and of themselves) + // Log the execution of a command (not script chunks, as they are not commands in and of themselves) if (commandProcessor.CommandInfo.CommandType != CommandTypes.Script) { - commandProcessor.CommandRuntime.PipelineProcessor.LogExecutionInfo( - commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name); + LogExecutionInfo(commandProcessor.Command.MyInvocation, commandProcessor.CommandInfo.Name); } InvocationInfo myInfo = commandProcessor.Command.MyInvocation; @@ -1065,8 +1147,7 @@ private void Start(bool incomingStream) } /// - /// Add ExternalErrorOutput to all commands whose error - /// output is not yet claimed. + /// Add ExternalErrorOutput to all commands whose error output is not yet claimed. /// private void SetExternalErrorOutput() { @@ -1075,14 +1156,12 @@ private void SetExternalErrorOutput() for (int i = 0; i < _commands.Count; i++) { CommandProcessorBase commandProcessor = _commands[i]; - Pipe UpstreamPipe = - commandProcessor.CommandRuntime.ErrorOutputPipe; + Pipe errorPipe = commandProcessor.CommandRuntime.ErrorOutputPipe; // check whether a cmdlet is consuming the error pipe - if (!UpstreamPipe.IsRedirected) + if (!errorPipe.IsRedirected) { - UpstreamPipe.ExternalWriter = - ExternalErrorOutput; + errorPipe.ExternalWriter = ExternalErrorOutput; } } } @@ -1093,14 +1172,9 @@ private void SetExternalErrorOutput() /// private void SetupParameterVariables() { - for (int i = 0; i < _commands.Count; i++) + foreach (CommandProcessorBase commandProcessor in _commands) { - CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor == null || commandProcessor.CommandRuntime == null) - { - // "null command " + i - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(commandProcessor, errorMessage: null); commandProcessor.CommandRuntime.SetupOutVariable(); commandProcessor.CommandRuntime.SetupErrorVariable(); @@ -1110,6 +1184,16 @@ private void SetupParameterVariables() } } + private static void ValidateCommandProcessorNotNull(CommandProcessorBase commandProcessor, string errorMessage) + { + if (commandProcessor?.CommandRuntime is null) + { + throw errorMessage is null + ? PSTraceSource.NewInvalidOperationException() + : PSTraceSource.NewInvalidOperationException(errorMessage, Array.Empty()); + } + } + /// /// Partially execute the pipeline. The output remains in /// the pipes. @@ -1139,12 +1223,7 @@ private void Inject(object input, bool enumerate) { // Add any input to the first command. CommandProcessorBase firstcommandProcessor = _commands[0]; - if (firstcommandProcessor == null - || firstcommandProcessor.CommandRuntime == null) - { - throw PSTraceSource.NewInvalidOperationException( - PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); - } + ValidateCommandProcessorNotNull(firstcommandProcessor, PipelineStrings.PipelineExecuteRequiresAtLeastOneCommand); if (input != AutomationNull.Value) { @@ -1182,27 +1261,26 @@ private void Inject(object input, bool enumerate) /// private Array RetrieveResults() { + if (_commands is null) + { + // This could happen to an expression redirection pipeline (e.g. 1 > a.txt). + // An exception may be thrown from the call to 'StartStepping' or 'Step' on the pipeline, + // which causes the pipeline commands to be disposed. + return MshCommandRuntime.StaticEmptyArray; + } + // If the error queue has been linked, it's up to the link to // deal with the output. Don't do anything here... if (!_linkedErrorOutput) { - // Retrieve any accumulated error objects from each of the pipes - // and add them to the error results hash table. - for (int i = 0; i < _commands.Count; i++) + foreach (CommandProcessorBase commandProcessor in _commands) { - CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor == null - || commandProcessor.CommandRuntime == null) - { - // "null command or request or ErrorOutputPipe " + i - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(commandProcessor, errorMessage: null); Pipe ErrorPipe = commandProcessor.CommandRuntime.ErrorOutputPipe; if (ErrorPipe.DownstreamCmdlet == null && !ErrorPipe.Empty) { - // 2003/10/02-JonN - // Do not return the same error results more than once + // Clear the error pipe if it's not empty and will not be consumed. ErrorPipe.Clear(); } } @@ -1211,26 +1289,18 @@ private Array RetrieveResults() // If the success queue has been linked, it's up to the link to // deal with the output. Don't do anything here... if (_linkedSuccessOutput) + { return MshCommandRuntime.StaticEmptyArray; + } CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; - if (LastCommandProcessor == null - || LastCommandProcessor.CommandRuntime == null) - { - // "PipelineProcessor.RetrieveResults(): LastCommandProcessor == null" - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(LastCommandProcessor, errorMessage: null); - Array results = - LastCommandProcessor.CommandRuntime.GetResultsAsArray(); + Array results = LastCommandProcessor.CommandRuntime.GetResultsAsArray(); - // 2003/10/02-JonN // Do not return the same results more than once LastCommandProcessor.CommandRuntime.OutputPipe.Clear(); - - if (results == null) - return MshCommandRuntime.StaticEmptyArray; - return results; + return results is null ? MshCommandRuntime.StaticEmptyArray : results; } /// @@ -1244,12 +1314,7 @@ internal void LinkPipelineSuccessOutput(Pipe pipeToUse) Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null"); CommandProcessorBase LastCommandProcessor = _commands[_commands.Count - 1]; - if (LastCommandProcessor == null - || LastCommandProcessor.CommandRuntime == null) - { - // "PipelineProcessor.RetrieveResults(): LastCommandProcessor == null" - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(LastCommandProcessor, errorMessage: null); LastCommandProcessor.CommandRuntime.OutputPipe = pipeToUse; _linkedSuccessOutput = true; @@ -1259,15 +1324,9 @@ internal void LinkPipelineErrorOutput(Pipe pipeToUse) { Dbg.Assert(pipeToUse != null, "Caller should verify pipeToUse != null"); - for (int i = 0; i < _commands.Count; i++) + foreach (CommandProcessorBase commandProcessor in _commands) { - CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor == null - || commandProcessor.CommandRuntime == null) - { - // "null command or request or ErrorOutputPipe " + i - throw PSTraceSource.NewInvalidOperationException(); - } + ValidateCommandProcessorNotNull(commandProcessor, errorMessage: null); if (commandProcessor.CommandRuntime.ErrorOutputPipe.DownstreamCmdlet == null) { @@ -1288,62 +1347,65 @@ internal void LinkPipelineErrorOutput(Pipe pipeToUse) private void DisposeCommands() { // Note that this is not in a lock. - // We do not make Dispose() wait until StopProcessing() - // has completed. + // We do not make Dispose() wait until StopProcessing() has completed. _stopping = true; + if (_commands is null && _redirectionPipes is null) + { + // Commands were already disposed. + return; + } + LogToEventLog(); - if (_commands != null) + if (_commands is not null) { - for (int i = 0; i < _commands.Count; i++) + foreach (CommandProcessorBase commandProcessor in _commands) { - CommandProcessorBase commandProcessor = _commands[i]; - if (commandProcessor != null) + if (commandProcessor is null) { -#pragma warning disable 56500 - // If Dispose throws an exception, record it as a - // pipeline failure and continue disposing cmdlets. - try - { - commandProcessor.CommandRuntime.RemoveVariableListsInPipe(); - commandProcessor.Dispose(); - } - // 2005/04/13-JonN: The only vaguely plausible reason - // for a failure here is an exception in Command.Dispose. - // As such, this should be covered by the overall - // exemption. - catch (Exception e) // Catch-all OK, 3rd party callout. - { - InvocationInfo myInvocation = null; - if (commandProcessor.Command != null) - myInvocation = commandProcessor.Command.MyInvocation; + continue; + } - ProviderInvocationException pie = - e as ProviderInvocationException; - if (pie != null) + // If Dispose throws an exception, record it as a pipeline failure and continue disposing cmdlets. + try + { + // Only cmdlets can have variables defined via the common parameters. + // We handle the cleanup of those variables only if we need to. + if (commandProcessor is CommandProcessor) + { + if (commandProcessor.Command is not PSScriptCmdlet) { - e = new CmdletProviderInvocationException( - pie, - myInvocation); + // For script cmdlets, the variable lists were already removed when exiting a scope. + // So we only need to take care of binary cmdlets here. + commandProcessor.CommandRuntime.RemoveVariableListsInPipe(); } - else - { - e = new CmdletInvocationException( - e, - myInvocation); - // Log a command health event + // Remove the pipeline variable if we need to. + commandProcessor.CommandRuntime.RemovePipelineVariable(); + } - MshLog.LogCommandHealthEvent( - commandProcessor.Command.Context, - e, - Severity.Warning); - } + commandProcessor.Dispose(); + } + catch (Exception e) + { + // The only vaguely plausible reason for a failure here is an exception in 'Command.Dispose'. + // As such, this should be covered by the overall exemption. + InvocationInfo myInvocation = commandProcessor.Command?.MyInvocation; - RecordFailure(e, commandProcessor.Command); + if (e is ProviderInvocationException pie) + { + e = new CmdletProviderInvocationException(pie, myInvocation); } -#pragma warning restore 56500 + else + { + e = new CmdletInvocationException(e, myInvocation); + + // Log a command health event + MshLog.LogCommandHealthEvent(commandProcessor.Command.Context, e, Severity.Warning); + } + + RecordFailure(e, commandProcessor.Command); } } } @@ -1351,25 +1413,31 @@ private void DisposeCommands() _commands = null; // Now dispose any pipes that were used for redirection... - if (_redirectionPipes != null) + if (_redirectionPipes is not null) { foreach (PipelineProcessor redirPipe in _redirectionPipes) { -#pragma warning disable 56500 + if (redirPipe is null) + { + continue; + } + + // Clean resources for script commands. + // It is possible (though very unlikely) that the call to 'Step' on the redirection pipeline failed. + // In such a case, 'Clean' would have run and the 'pipelineProcessor' would have been disposed. + // Therefore, calling 'Clean' again will simply return, because '_commands' was already set to null. + redirPipe.Clean(); + // The complicated logic of disposing the commands is taken care // of through recursion, this routine should not be getting any // exceptions... try { - if (redirPipe != null) - { - redirPipe.Dispose(); - } + redirPipe.Dispose(); } catch (Exception) { } -#pragma warning restore 56500 } } @@ -1383,7 +1451,7 @@ private void DisposeCommands() /// /// Error which terminated the pipeline. /// Command against which to log SecondFailure. - /// True iff the pipeline was not already stopped. + /// True if-and-only-if the pipeline was not already stopped. internal bool RecordFailure(Exception e, InternalCommand command) { bool wasStopping = false; @@ -1393,11 +1461,9 @@ internal bool RecordFailure(Exception e, InternalCommand command) { _firstTerminatingError = ExceptionDispatchInfo.Capture(e); } - // 905900-2005/05/12 - // Drop5: Error Architecture: Log/trace second and subsequent RecordFailure - // Note that the pipeline could have been stopped asynchronously - // before hitting the error, therefore we check whether - // firstTerminatingError is PipelineStoppedException. + // Error Architecture: Log/trace second and subsequent RecordFailure. + // Note that the pipeline could have been stopped asynchronously before hitting the error, + // therefore we check whether '_firstTerminatingError' is 'PipelineStoppedException'. else if (_firstTerminatingError.SourceException is not PipelineStoppedException && command?.Context != null) { @@ -1416,11 +1482,10 @@ internal bool RecordFailure(Exception e, InternalCommand command) ex.GetType().Name, ex.StackTrace ); - InvalidOperationException ioe - = new InvalidOperationException(message, ex); + MshLog.LogCommandHealthEvent( command.Context, - ioe, + new InvalidOperationException(message, ex), Severity.Warning); } } diff --git a/src/System.Management.Automation/engine/regex.cs b/src/System.Management.Automation/engine/regex.cs index 3f827dc08f8..6e0ef9741d6 100644 --- a/src/System.Management.Automation/engine/regex.cs +++ b/src/System.Management.Automation/engine/regex.cs @@ -57,12 +57,12 @@ public sealed class WildcardPattern // The size is less than MaxShortPath = 260. private const int StackAllocThreshold = 256; + // chars that are considered special in a wildcard pattern + private const string SpecialChars = "*?[]`"; + // we convert a wildcard pattern to a predicate private Predicate _isMatch; - // chars that are considered special in a wildcard pattern - private static readonly char[] s_specialChars = new[] { '*', '?', '[', ']', '`' }; - // static match-all delegate that is shared by all WildcardPattern instances private static readonly Predicate s_matchAll = _ => true; @@ -73,18 +73,6 @@ public sealed class WildcardPattern // Default is WildcardOptions.None. internal WildcardOptions Options { get; } - /// - /// Wildcard pattern converted to regex pattern. - /// - internal string PatternConvertedToRegex - { - get - { - var patternRegex = WildcardPatternToRegexParser.Parse(this); - return patternRegex.ToString(); - } - } - /// /// Initializes and instance of the WildcardPattern class /// for the specified wildcard pattern. @@ -173,8 +161,8 @@ StringComparison GetStringComparison() return; } - int index = Pattern.IndexOfAny(s_specialChars); - if (index == -1) + int index = Pattern.AsSpan().IndexOfAny(SpecialChars); + if (index < 0) { // No special characters present in the pattern, so we can just do a string comparison. _isMatch = str => string.Equals(str, Pattern, GetStringComparison()); @@ -205,6 +193,35 @@ public bool IsMatch(string input) return input != null && _isMatch(input); } + /// + /// Converts the wildcard pattern to its regular expression equivalent. + /// + /// + /// A object that represents the regular expression equivalent of the wildcard pattern. + /// The regex is configured with options matching the wildcard pattern's options. + /// + /// + /// This method converts a wildcard pattern to a regular expression. + /// The conversion follows these rules: + /// + /// * (asterisk) converts to .* (matches any string) + /// ? (question mark) converts to . (matches any single character) + /// [abc] (bracket expression) converts to [abc] (matches any character in the set) + /// Literal characters are escaped as needed for regex + /// + /// + /// + /// + /// var pattern = new WildcardPattern("*.txt"); + /// Regex regex = pattern.ToRegex(); + /// // regex.ToString() returns: "\.txt$" + /// + /// + public Regex ToRegex() + { + return WildcardPatternToRegexParser.Parse(this); + } + /// /// Escape special chars, except for those specified in , in a string by replacing them with their escape codes. /// @@ -238,9 +255,9 @@ internal static string Escape(string pattern, char[] charsNotToEscape) char ch = pattern[i]; // - // if it is a wildcard char, escape it + // if it is a special char, escape it // - if (IsWildcardChar(ch) && !charsNotToEscape.Contains(ch)) + if (SpecialChars.Contains(ch) && !charsNotToEscape.Contains(ch)) { temp[tempIndex++] = escapeChar; } @@ -314,6 +331,43 @@ public static bool ContainsWildcardCharacters(string pattern) return result; } + /// + /// Checks if the string contains a left bracket "[" followed by a right bracket "]" after any number of characters. + /// + /// The string to check. + /// Returns true if the string contains both a left and right bracket "[" "]" and if the right bracket comes after the left bracket. + internal static bool ContainsRangeWildcard(string pattern) + { + if (string.IsNullOrEmpty(pattern)) + { + return false; + } + + bool foundStart = false; + bool result = false; + for (int index = 0; index < pattern.Length; ++index) + { + if (pattern[index] is '[') + { + foundStart = true; + continue; + } + + if (foundStart && pattern[index] is ']') + { + result = true; + break; + } + + if (pattern[index] == escapeChar) + { + ++index; + } + } + + return result; + } + /// /// Unescapes any escaped characters in the input string. /// @@ -432,7 +486,6 @@ public string ToWql() /// /// Thrown when a wildcard pattern is invalid. /// - [Serializable] public class WildcardPatternException : RuntimeException { /// @@ -447,10 +500,7 @@ public class WildcardPatternException : RuntimeException internal WildcardPatternException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } @@ -491,10 +541,11 @@ public WildcardPatternException(string message, /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected WildcardPatternException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } } @@ -1001,7 +1052,7 @@ internal bool IsMatch(string str) } } - private class PatternPositionsVisitor : IDisposable + private sealed class PatternPositionsVisitor : IDisposable { private readonly int _lengthOfPattern; @@ -1122,7 +1173,7 @@ public override void ProcessEndOfString( } } - private class LiteralCharacterElement : QuestionMarkElement + private sealed class LiteralCharacterElement : QuestionMarkElement { private readonly char _literalCharacter; @@ -1148,7 +1199,7 @@ public override void ProcessStringCharacter( } } - private class BracketExpressionElement : QuestionMarkElement + private sealed class BracketExpressionElement : QuestionMarkElement { private readonly Regex _regex; @@ -1173,7 +1224,7 @@ public override void ProcessStringCharacter( } } - private class AsterixElement : PatternElement + private sealed class AsterixElement : PatternElement { public override void ProcessStringCharacter( char currentStringCharacter, @@ -1197,7 +1248,7 @@ public override void ProcessEndOfString( } } - private class MyWildcardPatternParser : WildcardPatternParser + private sealed class MyWildcardPatternParser : WildcardPatternParser { private readonly List _patternElements = new List(); private CharacterNormalizer _characterNormalizer; diff --git a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs index 120ca07a5af..9d52bcb4dc9 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientMethodExecutor.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation.Remoting /// /// Executes methods on the client. /// - internal class ClientMethodExecutor + internal sealed class ClientMethodExecutor { /// /// Transport manager. @@ -133,7 +133,10 @@ internal static void Dispatch( /// private static bool IsRunspacePushed(PSHost host) { - if (!(host is IHostSupportsInteractiveSession host2)) { return false; } + if (host is not IHostSupportsInteractiveSession host2) + { + return false; + } // IsRunspacePushed can throw (not implemented exception) try @@ -159,10 +162,7 @@ internal void Execute(PSDataCollectionStream errorStream) { try { - if (_clientHost.UI != null) - { - _clientHost.UI.WriteErrorLine(errorRecord.ToString()); - } + _clientHost.UI?.WriteErrorLine(errorRecord.ToString()); } catch (Exception) { diff --git a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs index 4ea06ea2feb..631e49fc189 100644 --- a/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs +++ b/src/System.Management.Automation/engine/remoting/client/ClientRemotePowerShell.cs @@ -15,11 +15,11 @@ namespace System.Management.Automation.Runspaces.Internal /// PowerShell client side proxy base which handles invocation /// of powershell on a remote machine. /// - internal class ClientRemotePowerShell : IDisposable + internal sealed class ClientRemotePowerShell : IDisposable { #region Tracer - [TraceSourceAttribute("CRPS", "ClientRemotePowerShell")] + [TraceSource("CRPS", "ClientRemotePowerShell")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("CRPS", "ClientRemotePowerShellBase"); #endregion Tracer @@ -166,10 +166,7 @@ internal void UnblockCollections() outputstream.Close(); errorstream.Close(); - if (inputstream != null) - { - inputstream.Close(); - } + inputstream?.Close(); } /// @@ -902,28 +899,28 @@ private void HandleRobustConnectionNotification( #endregion Private Methods - #region Protected Members - - protected ObjectStreamBase inputstream; - protected ObjectStreamBase errorstream; - protected PSInformationalBuffers informationalBuffers; - protected PowerShell shell; - protected Guid clientRunspacePoolId; - protected bool noInput; - protected PSInvocationSettings settings; - protected ObjectStreamBase outputstream; - protected string computerName; - protected ClientPowerShellDataStructureHandler dataStructureHandler; - protected bool stopCalled = false; - protected PSHost hostToUse; - protected RemoteRunspacePoolInternal runspacePool; - - protected const string WRITE_DEBUG_LINE = "WriteDebugLine"; - protected const string WRITE_VERBOSE_LINE = "WriteVerboseLine"; - protected const string WRITE_WARNING_LINE = "WriteWarningLine"; - protected const string WRITE_PROGRESS = "WriteProgress"; - - protected bool initialized = false; + #region Private Fields + + private ObjectStreamBase inputstream; + private ObjectStreamBase errorstream; + private PSInformationalBuffers informationalBuffers; + private readonly PowerShell shell; + private readonly Guid clientRunspacePoolId; + private bool noInput; + private PSInvocationSettings settings; + private ObjectStreamBase outputstream; + private readonly string computerName; + private ClientPowerShellDataStructureHandler dataStructureHandler; + private bool stopCalled = false; + private PSHost hostToUse; + private readonly RemoteRunspacePoolInternal runspacePool; + + private const string WRITE_DEBUG_LINE = "WriteDebugLine"; + private const string WRITE_VERBOSE_LINE = "WriteVerboseLine"; + private const string WRITE_WARNING_LINE = "WriteWarningLine"; + private const string WRITE_PROGRESS = "WriteProgress"; + + private bool initialized = false; /// /// This queue is for the state change events that resulted in closing the underlying /// datastructure handler. We cannot send the state back to the upper layers until @@ -933,33 +930,20 @@ private void HandleRobustConnectionNotification( private PSConnectionRetryStatus _connectionRetryStatus = PSConnectionRetryStatus.None; - #endregion Protected Members + #endregion Private Fields #region IDisposable /// - /// Public interface for dispose. + /// Release all resources. /// public void Dispose() { - Dispose(true); - - GC.SuppressFinalize(this); + // inputstream.Dispose(); + // outputstream.Dispose(); + // errorstream.Dispose(); } - /// - /// Release all resources. - /// - /// If true, release all managed resources. - protected void Dispose(bool disposing) - { - if (disposing) - { - // inputstream.Dispose(); - // outputstream.Dispose(); - // errorstream.Dispose(); - } - } #endregion IDisposable } diff --git a/src/System.Management.Automation/engine/remoting/client/Job.cs b/src/System.Management.Automation/engine/remoting/client/Job.cs index 657b72bef7a..adf47d04cab 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job.cs @@ -93,7 +93,6 @@ public enum JobState /// Defines exception which is thrown when state of the PSJob is different /// from the expected state. /// - [Serializable] public class InvalidJobStateException : SystemException { /// @@ -191,10 +190,11 @@ internal InvalidJobStateException(JobState currentState) /// The that contains contextual information /// about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected InvalidJobStateException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -633,10 +633,7 @@ public IList ChildJobs { lock (syncObject) { - if (_childJobs == null) - { - _childJobs = new List(); - } + _childJobs ??= new List(); } } @@ -644,7 +641,7 @@ public IList ChildJobs } } - /// + /// /// Success status of the command execution. /// public abstract string StatusMessage { get; } @@ -755,10 +752,10 @@ private void WriteError(Cmdlet cmdlet, ErrorRecord errorRecord) private static Exception GetExceptionFromErrorRecord(ErrorRecord errorRecord) { - if (!(errorRecord.Exception is RuntimeException runtimeException)) + if (errorRecord.Exception is not RuntimeException runtimeException) return null; - if (!(runtimeException is RemoteException remoteException)) + if (runtimeException is not RemoteException remoteException) return null; PSPropertyInfo wasThrownFromThrow = @@ -1014,11 +1011,17 @@ protected virtual void DoUnloadJobStreams() /// public void LoadJobStreams() { - if (_jobStreamsLoaded) return; + if (_jobStreamsLoaded) + { + return; + } lock (syncObject) { - if (_jobStreamsLoaded) return; + if (_jobStreamsLoaded) + { + return; + } _jobStreamsLoaded = true; } @@ -1451,10 +1454,7 @@ internal void SetJobState(JobState state, Exception reason) { lock (syncObject) { - if (_finished != null) - { - _finished.Set(); - } + _finished?.Set(); } } #pragma warning restore 56500 @@ -1911,7 +1911,7 @@ internal List GetJobsForComputer(string computerName) foreach (Job j in ChildJobs) { - if (!(j is PSRemotingChildJob child)) continue; + if (j is not PSRemotingChildJob child) continue; if (string.Equals(child.Runspace.ConnectionInfo.ComputerName, computerName, StringComparison.OrdinalIgnoreCase)) { @@ -1934,7 +1934,7 @@ internal List GetJobsForRunspace(PSSession runspace) foreach (Job j in ChildJobs) { - if (!(j is PSRemotingChildJob child)) continue; + if (j is not PSRemotingChildJob child) continue; if (child.Runspace.InstanceId.Equals(runspace.InstanceId)) { returnJobList.Add(child); @@ -1957,7 +1957,7 @@ internal List GetJobsForOperation(IThrottleOperation operation) foreach (Job j in ChildJobs) { - if (!(j is PSRemotingChildJob child)) continue; + if (j is not PSRemotingChildJob child) continue; if (child.Helper.Equals(helper)) { returnJobList.Add(child); @@ -2048,7 +2048,7 @@ private static void SubmitAndWaitForConnect(List connectJobO /// /// Simple throttle operation class for connecting jobs. /// - private class ConnectJobOperation : IThrottleOperation + private sealed class ConnectJobOperation : IThrottleOperation { private readonly PSRemotingChildJob _psRemoteChildJob; @@ -2360,7 +2360,7 @@ private void SetStatusMessage() #region finish logic - // This variable is set to true if atleast one child job failed. + // This variable is set to true if at least one child job failed. private bool _atleastOneChildJobFailed = false; // count of number of child jobs which have finished @@ -3226,7 +3226,7 @@ protected virtual void HandleOperationComplete(object sender, OperationStateEven // no pipeline is created and no pipeline state changed event is raised. // We can wait for throttle complete, but it is raised only when all the // operations are completed and this means that status of job is not updated - // untill Operation Complete. + // until Operation Complete. ExecutionCmdletHelper helper = sender as ExecutionCmdletHelper; Dbg.Assert(helper != null, "Sender of OperationComplete has to be ExecutionCmdletHelper"); @@ -3313,8 +3313,7 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai errorId = "InvalidSessionState"; if (!string.IsNullOrEmpty(failureException.Source)) { - errorId = string.Format(System.Globalization.CultureInfo.InvariantCulture, - "{0},{1}", errorId, failureException.Source); + errorId = string.Create(System.Globalization.CultureInfo.InvariantCulture, $"{errorId},{failureException.Source}"); } } @@ -3371,13 +3370,10 @@ protected void ProcessJobFailure(ExecutionCmdletHelper helper, out Exception fai } } - if (failureException == null) - { - failureException = new RuntimeException( - PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, - runspace.RunspaceStateInfo.State)); - } + failureException ??= new RuntimeException( + PSRemotingErrorInvariants.FormatResourceString( + RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, + runspace.RunspaceStateInfo.State)); failureErrorRecord = new ErrorRecord(failureException, targetObject, fullyQualifiedErrorId, ErrorCategory.OpenError, @@ -3926,7 +3922,7 @@ public override void SetBreakpoints(IEnumerable breakpoints, int? ru /// /// Id of the breakpoint you want. /// The runspace id of the runspace you want to interact with. A null value will use the current runspace. - /// A a breakpoint with the specified id. + /// A breakpoint with the specified id. public override Breakpoint GetBreakpoint(int id, int? runspaceId) => _wrappedDebugger.GetBreakpoint(id, runspaceId); @@ -4080,10 +4076,7 @@ public override void SetDebuggerStepMode(bool enabled) internal void CheckStateAndRaiseStopEvent() { RemoteDebugger remoteDebugger = _wrappedDebugger as RemoteDebugger; - if (remoteDebugger != null) - { - remoteDebugger.CheckStateAndRaiseStopEvent(); - } + remoteDebugger?.CheckStateAndRaiseStopEvent(); } /// @@ -4131,13 +4124,7 @@ private Pipeline DrainAndBlockRemoteOutput() return null; } - private static void RestoreRemoteOutput(Pipeline runningCmd) - { - if (runningCmd != null) - { - runningCmd.ResumeIncomingData(); - } - } + private static void RestoreRemoteOutput(Pipeline runningCmd) => runningCmd?.ResumeIncomingData(); private void HandleBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e) { diff --git a/src/System.Management.Automation/engine/remoting/client/Job2.cs b/src/System.Management.Automation/engine/remoting/client/Job2.cs index ae5976ec9f8..a5ac9e5ec0b 100644 --- a/src/System.Management.Automation/engine/remoting/client/Job2.cs +++ b/src/System.Management.Automation/engine/remoting/client/Job2.cs @@ -93,8 +93,7 @@ public List StartParameters { lock (_syncobject) { - if (_parameters == null) - _parameters = new List(); + _parameters ??= new List(); } } @@ -506,7 +505,7 @@ public sealed class ContainerParentJob : Job2 private const int DisposedTrue = 1; private const int DisposedFalse = 0; - // This variable is set to true if atleast one child job failed. + // This variable is set to true if at least one child job failed. // count of number of child jobs which have finished private int _finishedChildJobsCount = 0; @@ -707,10 +706,8 @@ public ContainerParentJob(string command, string name, string jobType) public void AddChildJob(Job2 childJob) { AssertNotDisposed(); - if (childJob == null) - { - throw new ArgumentNullException(nameof(childJob)); - } + + ArgumentNullException.ThrowIfNull(childJob); _tracer.WriteMessage(TraceClassName, "AddChildJob", Guid.Empty, childJob, "Adding Child to Parent with InstanceId : ", InstanceId.ToString()); @@ -2022,11 +2019,8 @@ protected override void Dispose(bool disposing) job.Dispose(); } - if (_jobRunning != null) - _jobRunning.Dispose(); - - if (_jobSuspendedOrAborted != null) - _jobSuspendedOrAborted.Dispose(); + _jobRunning?.Dispose(); + _jobSuspendedOrAborted?.Dispose(); } finally { @@ -2038,7 +2032,7 @@ private string ConstructLocation() { if (ChildJobs == null || ChildJobs.Count == 0) return string.Empty; - string location = ChildJobs.Select((job) => job.Location).Aggregate((s1, s2) => s1 + ',' + s2); + string location = ChildJobs.Select(static (job) => job.Location).Aggregate((s1, s2) => s1 + ',' + s2); return location; } @@ -2112,7 +2106,6 @@ private void UnregisterAllJobEvents() /// Container exception for jobs that can map errors and exceptions /// to specific lines in their input. /// - [Serializable] public class JobFailedException : SystemException { /// @@ -2157,11 +2150,10 @@ public JobFailedException(Exception innerException, ScriptExtent displayScriptPo /// /// Serialization info. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected JobFailedException(SerializationInfo serializationInfo, StreamingContext streamingContext) - : base(serializationInfo, streamingContext) { - _reason = (Exception)serializationInfo.GetValue("Reason", typeof(Exception)); - _displayScriptPosition = (ScriptExtent)serializationInfo.GetValue("DisplayScriptPosition", typeof(ScriptExtent)); + throw new NotSupportedException(); } /// @@ -2178,22 +2170,6 @@ protected JobFailedException(SerializationInfo serializationInfo, StreamingConte private readonly ScriptExtent _displayScriptPosition; - /// - /// Gets the information for serialization. - /// - /// The standard SerializationInfo. - /// The standard StreaminContext. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - throw new ArgumentNullException(nameof(info)); - - base.GetObjectData(info, context); - - info.AddValue("Reason", _reason); - info.AddValue("DisplayScriptPosition", _displayScriptPosition); - } - /// /// Returns the reason for this exception. /// diff --git a/src/System.Management.Automation/engine/remoting/client/JobManager.cs b/src/System.Management.Automation/engine/remoting/client/JobManager.cs index f907cf922d8..3b2baec6654 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobManager.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobManager.cs @@ -158,7 +158,11 @@ internal static void SaveJobId(Guid instanceId, int id, string typeName) { lock (s_syncObject) { - if (s_jobIdsForReuse.ContainsKey(instanceId)) return; + if (s_jobIdsForReuse.ContainsKey(instanceId)) + { + return; + } + s_jobIdsForReuse.Add(instanceId, new KeyValuePair(id, typeName)); } } @@ -176,10 +180,7 @@ internal static void SaveJobId(Guid instanceId, int id, string typeName) /// public Job2 NewJob(JobDefinition definition) { - if (definition == null) - { - throw new ArgumentNullException(nameof(definition)); - } + ArgumentNullException.ThrowIfNull(definition); JobSourceAdapter sourceAdapter = GetJobSourceAdapter(definition); Job2 newJob; @@ -216,10 +217,7 @@ public Job2 NewJob(JobDefinition definition) /// public Job2 NewJob(JobInvocationInfo specification) { - if (specification == null) - { - throw new ArgumentNullException(nameof(specification)); - } + ArgumentNullException.ThrowIfNull(specification); if (specification.Definition == null) { @@ -593,7 +591,11 @@ private List GetFilteredJobs( } #pragma warning restore 56500 - if (jobs == null) continue; + if (jobs == null) + { + continue; + } + allJobs.AddRange(jobs); } } @@ -758,7 +760,10 @@ private Job2 GetJobThroughId(Guid guid, int id, Cmdlet cmdlet, bool writeErro WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobByInstanceIdError", sourceAdapter); } - if (job == null) continue; + if (job == null) + { + continue; + } if (writeObject) { @@ -934,12 +939,20 @@ internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, boo // sourceAdapter.GetJobByInstanceId() threw unknown exception. _tracer.TraceException(exception); - if (throwExceptions) throw; + if (throwExceptions) + { + throw; + } + WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterGetJobError", sourceAdapter); } #pragma warning restore 56500 - if (foundJob == null) continue; + if (foundJob == null) + { + continue; + } + jobFound = true; RemoveJobIdForReuse(foundJob); @@ -957,7 +970,11 @@ internal bool RemoveJob(Job2 job, Cmdlet cmdlet, bool writeErrorOnException, boo // sourceAdapter.RemoveJob() threw unknown exception. _tracer.TraceException(exception); - if (throwExceptions) throw; + if (throwExceptions) + { + throw; + } + WriteErrorOrWarning(writeErrorOnException, cmdlet, exception, "JobSourceAdapterRemoveJobError", sourceAdapter); } #pragma warning restore 56500 diff --git a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs index f5a5022d705..85cd6c7ba1f 100644 --- a/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs +++ b/src/System.Management.Automation/engine/remoting/client/JobSourceAdapter.cs @@ -20,7 +20,6 @@ namespace System.Management.Automation /// /// The actual implementation of this class will /// happen in M2 - [Serializable] public class JobDefinition : ISerializable { private string _name; @@ -172,7 +171,6 @@ public virtual void GetObjectData(SerializationInfo info, StreamingContext conte /// CommandParameterCollection adds a public /// constructor.The actual implementation of /// this class will happen in M2 - [Serializable] public class JobInvocationInfo : ISerializable { /// @@ -361,7 +359,7 @@ private static CommandParameterCollection ConvertDictionaryToParameterCollection return null; CommandParameterCollection paramCollection = new CommandParameterCollection(); foreach (CommandParameter paramItem in - parameters.Select(param => new CommandParameter(param.Key, param.Value))) + parameters.Select(static param => new CommandParameter(param.Key, param.Value))) { paramCollection.Add(paramItem); } @@ -415,7 +413,7 @@ public void StoreJobIdForReuse(Job2 job, bool recurse) duplicateDetector.Add(job.InstanceId, job.InstanceId); foreach (Job child in job.ChildJobs) { - if (!(child is Job2 childJob)) continue; + if (child is not Job2 childJob) continue; StoreJobIdForReuseHelper(duplicateDetector, childJob, true); } } @@ -431,7 +429,7 @@ private void StoreJobIdForReuseHelper(Hashtable duplicateDetector, Job2 job, boo if (!recurse || job.ChildJobs == null) return; foreach (Job child in job.ChildJobs) { - if (!(child is Job2 childJob)) continue; + if (child is not Job2 childJob) continue; StoreJobIdForReuseHelper(duplicateDetector, childJob, recurse); } } diff --git a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs index 94584c613f5..983180bd5ca 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemoteRunspacePoolInternal.cs @@ -23,7 +23,7 @@ namespace System.Management.Automation.Runspaces.Internal /// Class which supports pooling remote powerShell runspaces /// on the client. /// - internal class RemoteRunspacePoolInternal : RunspacePoolInternal, IDisposable + internal sealed class RemoteRunspacePoolInternal : RunspacePoolInternal { #region Constructor @@ -81,7 +81,7 @@ internal RemoteRunspacePoolInternal(int minRunspaces, minPoolSz.ToString(CultureInfo.InvariantCulture), maxPoolSz.ToString(CultureInfo.InvariantCulture)); - _connectionInfo = connectionInfo.InternalCopy(); + _connectionInfo = connectionInfo.Clone(); this.host = host; ApplicationArguments = applicationArguments; @@ -128,7 +128,7 @@ internal RemoteRunspacePoolInternal(Guid instanceId, string name, bool isDisconn if (connectionInfo is WSManConnectionInfo) { - _connectionInfo = connectionInfo.InternalCopy(); + _connectionInfo = connectionInfo.Clone(); } else { @@ -291,7 +291,7 @@ internal override bool ResetRunspaceState() // version 2.3 or greater. Version remoteProtocolVersionDeclaredByServer = PSRemotingProtocolVersion; if ((remoteProtocolVersionDeclaredByServer == null) || - (remoteProtocolVersionDeclaredByServer < RemotingConstants.ProtocolVersionWin10RTM)) + (remoteProtocolVersionDeclaredByServer < RemotingConstants.ProtocolVersion_2_3)) { throw PSTraceSource.NewInvalidOperationException(RunspacePoolStrings.ResetRunspaceStateNotSupportedOnServer); } @@ -347,7 +347,7 @@ internal override bool SetMaxRunspaces(int maxRunspaces) return true; } - // sending the message should be done withing the lock + // sending the message should be done within the lock // to ensure that multiple calls to SetMaxRunspaces // will be executed on the server in the order in which // they were called in the client @@ -410,7 +410,7 @@ internal override bool SetMinRunspaces(int minRunspaces) return true; } - // sending the message should be done withing the lock + // sending the message should be done within the lock // to ensure that multiple calls to SetMinRunspaces // will be executed on the server in the order in which // they were called in the client @@ -452,7 +452,7 @@ internal override int GetAvailableRunspaces() // return maxrunspaces if (stateInfo.State == RunspacePoolState.Opened) { - // sending the message should be done withing the lock + // sending the message should be done within the lock // to ensure that multiple calls to GetAvailableRunspaces // will be executed on the server in the order in which // they were called in the client @@ -733,7 +733,7 @@ internal bool CanDisconnect { // Disconnect/Connect support is currently only provided by the WSMan transport // that is running PSRP protocol version 2.2 and greater. - return (remoteProtocolVersionDeclaredByServer >= RemotingConstants.ProtocolVersionWin8RTM && + return (remoteProtocolVersionDeclaredByServer >= RemotingConstants.ProtocolVersion_2_2 && DataStructureHandler.EndpointSupportsDisconnect); } @@ -1215,7 +1215,7 @@ public override Collection CreateDisconnectedPowerShells(RunspacePoo return psCollection; } - /// + /// /// Returns RunspacePool capabilities. /// /// RunspacePoolCapability. @@ -1237,7 +1237,7 @@ public override RunspacePoolCapability GetCapabilities() internal static RunspacePool[] GetRemoteRunspacePools(RunspaceConnectionInfo connectionInfo, PSHost host, TypeTable typeTable) { - if (!(connectionInfo is WSManConnectionInfo wsmanConnectionInfoParam)) + if (connectionInfo is not WSManConnectionInfo wsmanConnectionInfoParam) { // Disconnect-Connect currently only supported by WSMan. throw new NotSupportedException(); @@ -1826,20 +1826,14 @@ private void ResetDisconnectedOnExpiresOn() { // Reset DisconnectedOn/ExpiresOn WSManConnectionInfo wsManConnectionInfo = _connectionInfo as WSManConnectionInfo; - if (wsManConnectionInfo != null) - { - wsManConnectionInfo.NullDisconnectedExpiresOn(); - } + wsManConnectionInfo?.NullDisconnectedExpiresOn(); } private void UpdateDisconnectedExpiresOn() { // Set DisconnectedOn/ExpiresOn for disconnected session. WSManConnectionInfo wsManConnectionInfo = _connectionInfo as WSManConnectionInfo; - if (wsManConnectionInfo != null) - { - wsManConnectionInfo.SetDisconnectedExpiresOnToNow(); - } + wsManConnectionInfo?.SetDisconnectedExpiresOnToNow(); } /// @@ -1899,21 +1893,11 @@ private void WaitAndRaiseConnectEventsProc(object state) #region IDisposable - /// - /// Public method for Dispose. - /// - public void Dispose() - { - Dispose(true); - - GC.SuppressFinalize(this); - } - /// /// Release all resources. /// /// If true, release all managed resources. - public override void Dispose(bool disposing) + protected override void Dispose(bool disposing) { // dispose the base class before disposing dataStructure handler. base.Dispose(disposing); @@ -2039,7 +2023,7 @@ internal static Collection GetRemoteCommands(Guid shellId, WSManConnec powerShell.AddCommand("Get-WSManInstance"); // Add parameters to enumerate commands. - string filterStr = string.Format(CultureInfo.InvariantCulture, "ShellId='{0}'", shellId.ToString().ToUpperInvariant()); + string filterStr = string.Create(CultureInfo.InvariantCulture, $"ShellId='{shellId.ToString().ToUpperInvariant()}'"); powerShell.AddParameter("ResourceURI", @"Shell/Command"); powerShell.AddParameter("Enumerate", true); powerShell.AddParameter("Dialect", "Selector"); diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs index 0de48ff6dfc..527bdcf9e21 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingErrorRecord.cs @@ -11,7 +11,6 @@ namespace System.Management.Automation.Runspaces /// /// Error record in remoting cases. /// - [Serializable] public class RemotingErrorRecord : ErrorRecord { /// @@ -57,32 +56,15 @@ private RemotingErrorRecord( #region ISerializable implementation - /// - /// Serializer method for class. - /// - /// Serializer information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("RemoteErrorRecord_OriginInfo", _originInfo); - } - /// /// Deserializer constructor. /// /// Serializer information. /// Streaming context. - protected RemotingErrorRecord(SerializationInfo info, StreamingContext context) - : base(info, context) + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected RemotingErrorRecord(SerializationInfo info, StreamingContext context) : base(info, context) { - _originInfo = (OriginInfo)info.GetValue("RemoteErrorRecord_OriginInfo", typeof(OriginInfo)); + throw new NotSupportedException(); } #endregion @@ -108,7 +90,7 @@ internal override ErrorRecord WrapException(Exception replaceParentContainsError /// /// Progress record containing origin information. /// - [DataContract()] + [DataContract] public class RemotingProgressRecord : ProgressRecord { /// @@ -119,7 +101,7 @@ public OriginInfo OriginInfo get { return _originInfo; } } - [DataMemberAttribute()] + [DataMember] private readonly OriginInfo _originInfo; /// @@ -149,7 +131,7 @@ public RemotingProgressRecord(ProgressRecord progressRecord, OriginInfo originIn private static ProgressRecord Validate(ProgressRecord progressRecord) { - if (progressRecord == null) throw new ArgumentNullException(nameof(progressRecord)); + ArgumentNullException.ThrowIfNull(progressRecord); return progressRecord; } } @@ -157,7 +139,7 @@ private static ProgressRecord Validate(ProgressRecord progressRecord) /// /// Warning record containing origin information. /// - [DataContract()] + [DataContract] public class RemotingWarningRecord : WarningRecord { /// @@ -168,7 +150,7 @@ public OriginInfo OriginInfo get { return _originInfo; } } - [DataMemberAttribute()] + [DataMember] private readonly OriginInfo _originInfo; /// @@ -199,7 +181,7 @@ internal RemotingWarningRecord( /// /// Debug record containing origin information. /// - [DataContract()] + [DataContract] public class RemotingDebugRecord : DebugRecord { /// @@ -210,7 +192,7 @@ public OriginInfo OriginInfo get { return _originInfo; } } - [DataMemberAttribute()] + [DataMember] private readonly OriginInfo _originInfo; /// @@ -228,7 +210,7 @@ public RemotingDebugRecord(string message, OriginInfo originInfo) /// /// Verbose record containing origin information. /// - [DataContract()] + [DataContract] public class RemotingVerboseRecord : VerboseRecord { /// @@ -239,7 +221,7 @@ public OriginInfo OriginInfo get { return _originInfo; } } - [DataMemberAttribute()] + [DataMember] private readonly OriginInfo _originInfo; /// @@ -257,7 +239,7 @@ public RemotingVerboseRecord(string message, OriginInfo originInfo) /// /// Information record containing origin information. /// - [DataContract()] + [DataContract] public class RemotingInformationRecord : InformationRecord { /// @@ -268,7 +250,7 @@ public OriginInfo OriginInfo get { return _originInfo; } } - [DataMemberAttribute()] + [DataMember] private readonly OriginInfo _originInfo; /// @@ -294,8 +276,7 @@ namespace System.Management.Automation.Remoting /// In case of output objects, the information /// should directly be added to the object as /// properties - [Serializable] - [DataContract()] + [DataContract] public class OriginInfo { /// @@ -311,7 +292,7 @@ public string PSComputerName } } - [DataMemberAttribute()] + [DataMember] private readonly string _computerName; /// @@ -326,7 +307,7 @@ public Guid RunspaceID } } - [DataMemberAttribute()] + [DataMember] private readonly Guid _runspaceID; /// @@ -346,7 +327,7 @@ public Guid InstanceID } } - [DataMemberAttribute()] + [DataMember] private Guid _instanceId; /// diff --git a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs index 8b8908b6e61..441a3f62fed 100644 --- a/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/client/RemotingProtocol2.cs @@ -19,7 +19,7 @@ namespace System.Management.Automation.Internal /// Handles all PowerShell data structure handler communication with the /// server side RunspacePool. /// - internal class ClientRunspacePoolDataStructureHandler : IDisposable + internal sealed class ClientRunspacePoolDataStructureHandler : IDisposable { private bool _reconnecting = false; @@ -275,10 +275,7 @@ internal void DispatchMessageToPowerShell(RemoteDataObject rcvdData) // if a data structure handler does not exist it means // the association has been removed - // discard messages - if (dsHandler != null) - { - dsHandler.ProcessReceivedData(rcvdData); - } + dsHandler?.ProcessReceivedData(rcvdData); } /// @@ -800,10 +797,7 @@ private void HandleReadyForDisconnect(object sender, EventArgs args) return; } - if (_preparingForDisconnectList.Contains(bcmdTM)) - { - _preparingForDisconnectList.Remove(bcmdTM); - } + _preparingForDisconnectList.Remove(bcmdTM); if (_preparingForDisconnectList.Count == 0) { @@ -813,7 +807,7 @@ private void HandleReadyForDisconnect(object sender, EventArgs args) // what thread this callback is made from. If it was made from a transport // callback event then a deadlock may occur when DisconnectAsync is called on // that same thread. - ThreadPool.QueueUserWorkItem(new WaitCallback(StartDisconnectAsync), RemoteSession); + ThreadPool.QueueUserWorkItem(new WaitCallback(StartDisconnectAsync)); } } } @@ -821,10 +815,18 @@ private void HandleReadyForDisconnect(object sender, EventArgs args) /// /// WaitCallback method to start an asynchronous disconnect. /// - /// - private void StartDisconnectAsync(object remoteSession) + /// + private void StartDisconnectAsync(object state) { - ((ClientRemoteSession)remoteSession).DisconnectAsync(); + var remoteSession = RemoteSession; + try + { + remoteSession?.DisconnectAsync(); + } + catch + { + // remoteSession may have already been disposed resulting in unexpected exceptions. + } } /// @@ -979,7 +981,7 @@ public void Dispose(bool disposing) /// Base class for ClientPowerShellDataStructureHandler to handle all /// references. /// - internal class ClientPowerShellDataStructureHandler + internal sealed class ClientPowerShellDataStructureHandler { #region Data Structure Handler events @@ -1150,8 +1152,8 @@ internal void SendHostResponseToServer(RemoteHostResponse hostResponse) RemoteDataObject dataToBeSent = RemoteDataObject.CreateFrom(RemotingDestination.Server, RemotingDataType.RemotePowerShellHostResponseData, - clientRunspacePoolId, - clientPowerShellId, + _clientRunspacePoolId, + _clientPowerShellId, hostResponse.Encode()); TransportManager.DataToBeSentCollection.Add(dataToBeSent, @@ -1173,7 +1175,7 @@ internal void SendInput(ObjectStreamBase inputstream) { // send input closed information to server SendDataAsync(RemotingEncoder.GeneratePowerShellInputEnd( - clientRunspacePoolId, clientPowerShellId)); + _clientRunspacePoolId, _clientPowerShellId)); } } else @@ -1202,10 +1204,10 @@ internal void SendInput(ObjectStreamBase inputstream) internal void ProcessReceivedData(RemoteDataObject receivedData) { // verify if this data structure handler is the intended recipient - if (receivedData.PowerShellId != clientPowerShellId) + if (receivedData.PowerShellId != _clientPowerShellId) { throw new PSRemotingDataStructureException(RemotingErrorIdStrings.PipelineIdsDoNotMatch, - receivedData.PowerShellId, clientPowerShellId); + receivedData.PowerShellId, _clientPowerShellId); } // decode the message and take appropriate action @@ -1425,7 +1427,7 @@ internal void ProcessDisconnect(RunspacePoolStateInfo rsStateInfo) /// /// This does not ensure that the corresponding session/runspacepool is in connected stated - /// Its the caller responsiblity to ensure that this is the case + /// It's the caller responsibility to ensure that this is the case /// At the protocols layers, this logic is delegated to the transport layer. /// WSMan transport ensures that WinRS commands cannot be reconnected when the parent shell is not in connected state. /// @@ -1468,13 +1470,6 @@ internal void ProcessRobustConnectionNotification( #endregion Data Structure Handler Methods - #region Protected Members - - protected Guid clientRunspacePoolId; - protected Guid clientPowerShellId; - - #endregion Protected Members - #region Constructors /// @@ -1491,8 +1486,8 @@ internal ClientPowerShellDataStructureHandler(BaseClientCommandTransportManager Guid clientRunspacePoolId, Guid clientPowerShellId) { TransportManager = transportManager; - this.clientRunspacePoolId = clientRunspacePoolId; - this.clientPowerShellId = clientPowerShellId; + _clientRunspacePoolId = clientRunspacePoolId; + _clientPowerShellId = clientPowerShellId; transportManager.SignalCompleted += OnSignalCompleted; } @@ -1508,7 +1503,7 @@ internal Guid PowerShellId { get { - return clientPowerShellId; + return _clientPowerShellId; } } @@ -1556,23 +1551,23 @@ private void HandleInputDataReady(object sender, EventArgs e) /// private void WriteInput(ObjectStreamBase inputstream) { - Collection inputObjects = inputstream.ObjectReader.NonBlockingRead(Int32.MaxValue); + Collection inputObjects = inputstream.ObjectReader.NonBlockingRead(int.MaxValue); foreach (object inputObject in inputObjects) { SendDataAsync(RemotingEncoder.GeneratePowerShellInput(inputObject, - clientRunspacePoolId, clientPowerShellId)); + _clientRunspacePoolId, _clientPowerShellId)); } if (!inputstream.IsOpen) { // Write any data written after the NonBlockingRead call above. - inputObjects = inputstream.ObjectReader.NonBlockingRead(Int32.MaxValue); + inputObjects = inputstream.ObjectReader.NonBlockingRead(int.MaxValue); foreach (object inputObject in inputObjects) { SendDataAsync(RemotingEncoder.GeneratePowerShellInput(inputObject, - clientRunspacePoolId, clientPowerShellId)); + _clientRunspacePoolId, _clientPowerShellId)); } // we are sending input end to the server. Ignore the future @@ -1581,7 +1576,7 @@ private void WriteInput(ObjectStreamBase inputstream) inputstream.DataReady -= HandleInputDataReady; // stream close: send end of input SendDataAsync(RemotingEncoder.GeneratePowerShellInputEnd( - clientRunspacePoolId, clientPowerShellId)); + _clientRunspacePoolId, _clientPowerShellId)); } } @@ -1603,6 +1598,9 @@ private void SetupTransportManager(bool inDisconnectMode) #region Private Members + private readonly Guid _clientRunspacePoolId; + private readonly Guid _clientPowerShellId; + // object for synchronizing input to be sent // to server powershell private readonly object _inputSyncObject = new object(); @@ -1621,7 +1619,7 @@ private enum connectionStates #endregion Private Members } - internal class InformationalMessage + internal sealed class InformationalMessage { internal object Message { get; } diff --git a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs index dfd1cd3bf7f..91cf4161a99 100644 --- a/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs +++ b/src/System.Management.Automation/engine/remoting/client/RunspaceRef.cs @@ -5,6 +5,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using System.Management.Automation.Runspaces.Internal; +using System.Management.Automation.Security; using Dbg = System.Management.Automation.Diagnostics; @@ -94,7 +95,22 @@ private PSCommand ParsePsCommandUsingScriptBlock(string line, bool? useLocalScop // to be parsed and evaluated on the remote session (not in the current local session). RemoteRunspace remoteRunspace = _runspaceRef.Value as RemoteRunspace; bool isConfiguredLoopback = remoteRunspace != null && remoteRunspace.IsConfiguredLoopBack; - bool isTrustedInput = !isConfiguredLoopback && (localRunspace.ExecutionContext.LanguageMode == PSLanguageMode.FullLanguage); + + bool inFullLanguage = context.LanguageMode == PSLanguageMode.FullLanguage; + if (context.LanguageMode == PSLanguageMode.ConstrainedLanguage + && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + // In audit mode, report but don't enforce. + inFullLanguage = true; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: RemotingErrorIdStrings.WDACGetPowerShellLogTitle, + message: RemotingErrorIdStrings.WDACGetPowerShellLogMessage, + fqid: "GetPowerShellMayFail", + dropIntoDebugger: true); + } + + bool isTrustedInput = !isConfiguredLoopback && inFullLanguage; // Create PowerShell from ScriptBlock. ScriptBlock scriptBlock = ScriptBlock.Create(context, line); @@ -208,12 +224,9 @@ internal Pipeline CreatePipeline(string line, bool addToHistory, bool useNestedP } // If that didn't work out fall-back to the traditional approach. - if (pipeline == null) - { - pipeline = useNestedPipelines ? - _runspaceRef.Value.CreateNestedPipeline(line, addToHistory) : - _runspaceRef.Value.CreatePipeline(line, addToHistory); - } + pipeline ??= useNestedPipelines ? + _runspaceRef.Value.CreateNestedPipeline(line, addToHistory) : + _runspaceRef.Value.CreatePipeline(line, addToHistory); // Add robust connection callback if this is a pushed runspace. RemotePipeline remotePipeline = pipeline as RemotePipeline; @@ -313,7 +326,7 @@ internal void Override(RemoteRunspace remoteRunspace, object syncObject, out boo powerShell.AddParameter("Name", new string[] { "Out-Default", "Exit-PSSession" }); powerShell.Runspace = _runspaceRef.Value; - bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersionWin7RC; + bool isReleaseCandidateBackcompatibilityMode = _runspaceRef.Value.GetRemoteProtocolVersion() == RemotingConstants.ProtocolVersion_2_0; powerShell.IsGetCommandMetadataSpecialPipeline = !isReleaseCandidateBackcompatibilityMode; int expectedNumberOfResults = isReleaseCandidateBackcompatibilityMode ? 2 : 3; @@ -353,7 +366,7 @@ internal void Override(RemoteRunspace remoteRunspace, object syncObject, out boo /// private void HandleHostCall(object sender, RemoteDataEventArgs eventArgs) { - System.Management.Automation.Runspaces.Internal.ClientRemotePowerShell.ExitHandler(sender, eventArgs); + ClientRemotePowerShell.ExitHandler(sender, eventArgs); } #region Robust Connection Support diff --git a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs index a00fdee17c2..59f4fb5135d 100644 --- a/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs +++ b/src/System.Management.Automation/engine/remoting/client/ThrottlingJob.cs @@ -53,11 +53,7 @@ protected override void Dispose(bool disposing) childJob.Dispose(); } - if (_jobResultsThrottlingSemaphore != null) - { - _jobResultsThrottlingSemaphore.Dispose(); - } - + _jobResultsThrottlingSemaphore?.Dispose(); _cancellationTokenSource.Dispose(); } } @@ -298,7 +294,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var jobGotEnqueued = new ManualResetEventSlim(initialState: false)) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); this.AddChildJobWithoutBlocking(childJob, flags, jobGotEnqueued.Set); jobGotEnqueued.Wait(); @@ -312,7 +308,7 @@ internal void AddChildJobAndPotentiallyBlock( { using (var forwardingCancellation = new CancellationTokenSource()) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); this.AddChildJobWithoutBlocking(childJob, flags, forwardingCancellation.Cancel); this.ForwardAllResultsToCmdlet(cmdlet, forwardingCancellation.Token); @@ -372,15 +368,26 @@ internal void DisableFlowControlForPendingCmdletActionsQueue() /// internal void AddChildJobWithoutBlocking(StartableJob childJob, ChildJobFlags flags, Action jobEnqueuedAction = null) { - if (childJob == null) throw new ArgumentNullException(nameof(childJob)); - if (childJob.JobStateInfo.State != JobState.NotStarted) throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); + ArgumentNullException.ThrowIfNull(childJob); + if (childJob.JobStateInfo.State != JobState.NotStarted) + { + throw new ArgumentException(RemotingErrorIdStrings.ThrottlingJobChildAlreadyRunning, nameof(childJob)); + } + this.AssertNotDisposed(); JobStateInfo newJobStateInfo = null; lock (_lockObject) { - if (this.IsEndOfChildJobs) throw new InvalidOperationException(RemotingErrorIdStrings.ThrottlingJobChildAddedAfterEndOfChildJobs); - if (_isStopping) { return; } + if (this.IsEndOfChildJobs) + { + throw new InvalidOperationException(RemotingErrorIdStrings.ThrottlingJobChildAddedAfterEndOfChildJobs); + } + + if (_isStopping) + { + return; + } if (_countOfAllChildJobs == 0) { @@ -541,10 +548,7 @@ private void StartChildJobIfPossible() } while (false); } - if (readyToRunChildJob != null) - { - readyToRunChildJob.StartJob(); - } + readyToRunChildJob?.StartJob(); } private void EnqueueReadyToRunChildJob(StartableJob childJob) @@ -784,7 +788,7 @@ public override bool HasMoreData { get { - return this.GetChildJobsSnapshot().Any(childJob => childJob.HasMoreData) || (this.Results.Count != 0); + return this.GetChildJobsSnapshot().Any(static childJob => childJob.HasMoreData) || (this.Results.Count != 0); } } @@ -846,7 +850,7 @@ internal override void ForwardAvailableResultsToCmdlet(Cmdlet cmdlet) } } - private class ForwardingHelper : IDisposable + private sealed class ForwardingHelper : IDisposable { // This is higher than 1000 used in // RxExtensionMethods+ToEnumerableObserver.BlockingCollectionCapacity @@ -1227,10 +1231,7 @@ public static void ForwardAllResultsToCmdlet(ThrottlingJob throttlingJob, Cmdlet } finally { - if (cancellationTokenRegistration != null) - { - cancellationTokenRegistration.Dispose(); - } + cancellationTokenRegistration?.Dispose(); } } finally diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs index 772beb61040..499062d7a18 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesession.cs @@ -55,7 +55,7 @@ internal class ClientRemoteSessionContext /// internal abstract class ClientRemoteSession : RemoteSession { - [TraceSourceAttribute("CRSession", "ClientRemoteSession")] + [TraceSource("CRSession", "ClientRemoteSession")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSession", "ClientRemoteSession"); #region Public_Method_API @@ -177,7 +177,7 @@ internal RemoteRunspacePoolInternal GetRunspacePool(Guid clientRunspacePoolId) /// internal class ClientRemoteSessionImpl : ClientRemoteSession, IDisposable { - [TraceSourceAttribute("CRSessionImpl", "ClientRemoteSessionImpl")] + [TraceSource("CRSessionImpl", "ClientRemoteSessionImpl")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionImpl", "ClientRemoteSessionImpl"); private PSRemotingCryptoHelperClient _cryptoHelper = null; @@ -505,20 +505,11 @@ private bool RunClientNegotiationAlgorithm(RemoteSessionCapability serverRemoteS _serverProtocolVersion = serverProtocolVersion; Version clientProtocolVersion = Context.ClientCapability.ProtocolVersion; - if ( - clientProtocolVersion.Equals(serverProtocolVersion) - || (clientProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM && - serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RC) - || (clientProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM && - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RC || - serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM - )) - || (clientProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM && - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RC || - serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM || - serverProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM - )) - ) + if (clientProtocolVersion == serverProtocolVersion || + serverProtocolVersion == RemotingConstants.ProtocolVersion_2_0 || + serverProtocolVersion == RemotingConstants.ProtocolVersion_2_1 || + serverProtocolVersion == RemotingConstants.ProtocolVersion_2_2 || + serverProtocolVersion == RemotingConstants.ProtocolVersion_2_3) { // passed negotiation check } diff --git a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs index d035ce6e820..2dea06d8ced 100644 --- a/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/client/clientremotesessionprotocolstatemachine.cs @@ -31,7 +31,7 @@ namespace System.Management.Automation.Remoting /// internal class ClientRemoteSessionDSHandlerStateMachine { - [TraceSourceAttribute("CRSessionFSM", "CRSessionFSM")] + [TraceSource("CRSessionFSM", "CRSessionFSM")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSessionFSM", "CRSessionFSM"); /// @@ -254,10 +254,7 @@ private void SetStateHandler(object sender, RemoteSessionStateMachineEventArgs e if (_state == RemoteSessionState.EstablishedAndKeySent) { Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) - { - tmp.Dispose(); - } + tmp?.Dispose(); _keyExchanged = true; SetState(RemoteSessionState.Established, eventArgs.Reason); @@ -339,10 +336,7 @@ private void HandleKeyExchangeTimeout(object sender) Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeySent, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) - { - tmp.Dispose(); - } + tmp?.Dispose(); PSRemotingDataStructureException exception = new PSRemotingDataStructureException(RemotingErrorIdStrings.ClientKeyExchangeFailed); @@ -456,7 +450,7 @@ internal ClientRemoteSessionDSHandlerStateMachine() _stateMachineHandle[(int)RemoteSessionState.EstablishedAndKeyRequested, (int)RemoteSessionEvent.KeySendFailed] += SetStateToClosedHandler; // TODO: All these are potential unexpected state transitions.. should have a way to track these calls.. - // should atleast put a dbg assert in this handler + // should at least put a dbg assert in this handler for (int i = 0; i < _stateMachineHandle.GetLength(0); i++) { for (int j = 0; j < _stateMachineHandle.GetLength(1); j++) diff --git a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs index c791d728809..cf476cec226 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotepipeline.cs @@ -34,7 +34,7 @@ internal class RemotePipeline : Pipeline private readonly ConnectCommandInfo _connectCmdInfo = null; /// - /// This is queue of all the state change event which have occured for + /// This is queue of all the state change event which have occurred for /// this pipeline. RaisePipelineStateEvents raises event for each /// item in this queue. We don't raise the event with in SetPipelineState /// because often SetPipelineState is called with in a lock. @@ -42,7 +42,7 @@ internal class RemotePipeline : Pipeline /// private Queue _executionEventQueue = new Queue(); - private class ExecutionEventQueueItem + private sealed class ExecutionEventQueueItem { public ExecutionEventQueueItem(PipelineStateInfo pipelineStateInfo, RunspaceAvailability currentAvailability, RunspaceAvailability newAvailability) { @@ -95,7 +95,7 @@ private RemotePipeline(RemoteRunspace runspace, bool addToHistory, bool isNested SetCommandCollection(_commands); // Create event which will be signalled when pipeline execution - // is completed/failed/stoped. + // is completed/failed/stopped. // Note:Runspace.Close waits for all the running pipeline // to finish. This Event must be created before pipeline is // added to list of running pipelines. This avoids the race condition @@ -599,7 +599,7 @@ private bool CanStopPipeline(out bool isAlreadyStopping) break; // If pipeline execution has failed or completed or - // stoped, return silently. + // stopped, return silently. case PipelineState.Stopped: case PipelineState.Completed: case PipelineState.Failed: @@ -1018,7 +1018,7 @@ private void Cleanup() /// /// ManualResetEvent which is signaled when pipeline execution is - /// completed/failed/stoped. + /// completed/failed/stopped. /// internal ManualResetEvent PipelineFinishedEvent { get; } diff --git a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs index 7ddd657872e..8448007025f 100644 --- a/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs +++ b/src/System.Management.Automation/engine/remoting/client/remoterunspace.cs @@ -48,7 +48,7 @@ internal class RemoteRunspace : Runspace, IDisposable private long _currentLocalPipelineId = 0; /// - /// This is queue of all the state change event which have occured for + /// This is queue of all the state change event which have occurred for /// this runspace. RaiseRunspaceStateEvents raises event for each /// item in this queue. We don't raise events from with SetRunspaceState /// because SetRunspaceState is often called from with in the a lock. @@ -137,8 +137,8 @@ internal RemoteRunspace(TypeTable typeTable, RunspaceConnectionInfo connectionIn PSTask.CreateRunspace, PSKeyword.UseAlwaysOperational, InstanceId.ToString()); - _connectionInfo = connectionInfo.InternalCopy(); - OriginalConnectionInfo = connectionInfo.InternalCopy(); + _connectionInfo = connectionInfo.Clone(); + OriginalConnectionInfo = connectionInfo.Clone(); RunspacePool = new RunspacePool(1, 1, typeTable, host, applicationArguments, connectionInfo, name); @@ -170,7 +170,7 @@ internal RemoteRunspace(RunspacePool runspacePool) RunspacePool.RemoteRunspacePoolInternal.SetMinRunspaces(1); RunspacePool.RemoteRunspacePoolInternal.SetMaxRunspaces(1); - _connectionInfo = runspacePool.ConnectionInfo.InternalCopy(); + _connectionInfo = runspacePool.ConnectionInfo.Clone(); // Update runspace DisconnectedOn and ExpiresOn property from WSManConnectionInfo UpdateDisconnectExpiresOn(); @@ -221,11 +221,7 @@ public override InitialSessionState InitialSessionState { get { -#pragma warning disable 56503 - throw PSTraceSource.NewNotImplementedException(); - -#pragma warning restore 56503 } } @@ -236,11 +232,7 @@ public override JobManager JobManager { get { -#pragma warning disable 56503 - throw PSTraceSource.NewNotImplementedException(); - -#pragma warning restore 56503 } } @@ -642,11 +634,8 @@ protected override void Dispose(bool disposing) // } - if (_remoteDebugger != null) - { - // Release RunspacePool event forwarding handlers. - _remoteDebugger.Dispose(); - } + // Release RunspacePool event forwarding handlers. + _remoteDebugger?.Dispose(); try { @@ -946,6 +935,11 @@ public override RunspaceCapability GetCapabilities() returnCaps |= RunspaceCapability.SupportsDisconnect; } + if (_connectionInfo is WSManConnectionInfo) + { + return returnCaps; + } + if (_connectionInfo is NamedPipeConnectionInfo) { returnCaps |= RunspaceCapability.NamedPipeTransport; @@ -958,16 +952,20 @@ public override RunspaceCapability GetCapabilities() { returnCaps |= RunspaceCapability.SSHTransport; } - else + else if (_connectionInfo is ContainerConnectionInfo containerConnectionInfo) { - ContainerConnectionInfo containerConnectionInfo = _connectionInfo as ContainerConnectionInfo; - if ((containerConnectionInfo != null) && (containerConnectionInfo.ContainerProc.RuntimeId == Guid.Empty)) { returnCaps |= RunspaceCapability.NamedPipeTransport; } } + else + { + // Unknown connection info type means a custom connection/transport, which at + // minimum supports remote runspace capability starting from PowerShell v7.x. + returnCaps |= RunspaceCapability.CustomTransport; + } return returnCaps; } @@ -1731,10 +1729,7 @@ internal void AbortOpen() System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager transportManager = RunspacePool.RemoteRunspacePoolInternal.DataStructureHandler.TransportManager as System.Management.Automation.Remoting.Client.NamedPipeClientSessionTransportManager; - if (transportManager != null) - { - transportManager.AbortConnect(); - } + transportManager?.AbortConnect(); } #endregion Internal Methods @@ -2785,8 +2780,8 @@ private void CheckForValidateState() { throw new PSInvalidOperationException( // The remote session to which you are connected does not support remote debugging. - // You must connect to a remote computer that is running PowerShell {0} or greater. - StringUtil.Format(RemotingErrorIdStrings.RemoteDebuggingEndpointVersionError, PSVersionInfo.PSV4Version), + // You must connect to a remote computer that is running PowerShell 4.0 or greater. + RemotingErrorIdStrings.RemoteDebuggingEndpointVersionError, null, "RemoteDebugger:RemoteDebuggingNotSupported", ErrorCategory.NotImplemented, @@ -2910,10 +2905,7 @@ private T InvokeRemoteBreakpointFunction(string functionName, Dictionary /// Static variable which is incremented to generate id. @@ -302,7 +303,8 @@ internal PSSession(RemoteRunspace remoteRunspace) break; default: - Dbg.Assert(false, "Invalid Runspace"); + // Default for custom connection and transports. + ComputerType = TargetMachineType.RemoteMachine; break; } } @@ -338,7 +340,7 @@ private string GetTransportName() return "VMBus"; default: - return "Unknown"; + return string.IsNullOrEmpty(_transportName) ? "Custom" : _transportName; } } @@ -359,6 +361,34 @@ private static string GetDisplayShellName(string shell) #region Static Methods + /// + /// Creates a PSSession object from the provided remote runspace object. + /// If psCmdlet argument is non-null, then the new PSSession object is added to the + /// session runspace repository (Get-PSSession). + /// + /// Runspace for the new PSSession. + /// Optional transport name. + /// Optional cmdlet associated with the PSSession creation. + public static PSSession Create( + Runspace runspace, + string transportName, + PSCmdlet psCmdlet) + { + if (runspace is not RemoteRunspace remoteRunspace) + { + throw new PSArgumentException(RemotingErrorIdStrings.InvalidPSSessionArgument); + } + + var psSession = new PSSession(remoteRunspace) + { + _transportName = transportName + }; + + psCmdlet?.RunspaceRepository.Add(psSession); + + return psSession; + } + /// /// Generates a unique runspace id. /// diff --git a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs index d8800311127..d36ddff8be3 100644 --- a/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs +++ b/src/System.Management.Automation/engine/remoting/client/remotingprotocolimplementation.cs @@ -13,9 +13,9 @@ namespace System.Management.Automation.Remoting /// /// Implements ServerRemoteSessionDataStructureHandler. /// - internal class ClientRemoteSessionDSHandlerImpl : ClientRemoteSessionDataStructureHandler, IDisposable + internal sealed class ClientRemoteSessionDSHandlerImpl : ClientRemoteSessionDataStructureHandler, IDisposable { - [TraceSourceAttribute("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl")] + [TraceSource("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("CRSDSHdlerImpl", "ClientRemoteSessionDSHandlerImpl"); private const string resBaseName = "remotingerroridstrings"; @@ -329,7 +329,7 @@ private void HandleStateChanged(object sender, RemoteSessionStateEventArgs arg) } /// - /// Clubing negotiation packet + runspace creation and then doing transportManager.ConnectAsync(). + /// Clubbing negotiation packet + runspace creation and then doing transportManager.ConnectAsync(). /// This will save us 2 network calls by doing all the work in one network call. /// private void HandleNegotiationSendingStateChange() @@ -735,26 +735,12 @@ internal void ProcessNonSessionMessages(RemoteDataObject rcvdData) #region IDisposable - /// - /// Public method for dispose. - /// - public void Dispose() - { - Dispose(true); - - GC.SuppressFinalize(this); - } - /// /// Release all resources. /// - /// If true, release all managed resources. - protected void Dispose(bool disposing) + public void Dispose() { - if (disposing) - { - _transportManager.Dispose(); - } + _transportManager.Dispose(); } #endregion IDisposable diff --git a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs index f58aa35632e..b7474fe34c2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ConnectPSSession.cs @@ -83,7 +83,7 @@ public class ConnectPSSessionCommand : PSRunspaceCmdlet, IDisposable /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, @@ -92,7 +92,10 @@ public class ConnectPSSessionCommand : PSRunspaceCmdlet, IDisposable ParameterSetName = ConnectPSSessionCommand.ComputerNameGuidParameterSet)] public string ApplicationName { - get { return _appName; } + get + { + return _appName; + } set { @@ -117,7 +120,10 @@ public string ApplicationName ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public string ConfigurationName { - get { return _shell; } + get + { + return _shell; + } set { @@ -199,10 +205,13 @@ public override string[] Name [Parameter(ParameterSetName = ConnectPSSessionCommand.ComputerNameGuidParameterSet)] [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriParameterSet)] [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] - [Credential()] + [Credential] public PSCredential Credential { - get { return _psCredential; } + get + { + return _psCredential; + } set { @@ -223,7 +232,10 @@ public PSCredential Credential [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public AuthenticationMechanism Authentication { - get { return _authentication; } + get + { + return _authentication; + } set { @@ -245,7 +257,10 @@ public AuthenticationMechanism Authentication [Parameter(ParameterSetName = ConnectPSSessionCommand.ConnectionUriGuidParameterSet)] public string CertificateThumbprint { - get { return _thumbprint; } + get + { + return _thumbprint; + } set { @@ -472,7 +487,7 @@ protected override void StopProcessing() /// /// Throttle class to perform a remoterunspace connect operation. /// - private class ConnectRunspaceOperation : IThrottleOperation + private sealed class ConnectRunspaceOperation : IThrottleOperation { private PSSession _session; private PSSession _oldSession; @@ -554,10 +569,7 @@ internal override void StartOperation() internal override void StopOperation() { - if (_queryRunspaces != null) - { - _queryRunspaces.StopAllOperations(); - } + _queryRunspaces?.StopAllOperations(); _session.Runspace.StateChanged -= StateCallBackHandler; SendStopComplete(); diff --git a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs index aa90fca60a4..1d88210e7b6 100644 --- a/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs +++ b/src/System.Management.Automation/engine/remoting/commands/CustomShellCommands.cs @@ -52,7 +52,8 @@ function Register-PSSessionConfiguration [system.security.securestring] $runAsPassword, [System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode] $accessMode, [bool] $isSddlSpecified, - [string] $configTableSddl + [string] $configTableSddl, + [bool] $noRestart ) begin @@ -139,7 +140,7 @@ function Register-PSSessionConfiguration ## Replace the SDDL with any groups or restrictions defined in the PSSessionConfigurationFile if($? -and $configTableSddl -and (-not $isSddlSpecified)) {{ - $null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $configTableSddl -Force:$force + $null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $configTableSddl -NoServiceRestart:$noRestart -Force:$force }} if ($? -and $shouldShowUI) @@ -227,11 +228,11 @@ function Register-PSSessionConfiguration if ($runAsUserName) {{ $runAsCredential = new-object system.management.automation.PSCredential($runAsUserName, $runAsPassword) - $null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $newSDDL -NoServiceRestart -force -WarningAction 0 -RunAsCredential $runAsCredential + $null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $newSDDL -NoServiceRestart:$noRestart -Force:$force -WarningAction 0 -RunAsCredential $runAsCredential }} else {{ - $null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $newSDDL -NoServiceRestart -force -WarningAction 0 + $null = Set-PSSessionConfiguration -Name $pluginName -SecurityDescriptorSddl $newSDDL -NoServiceRestart:$noRestart -Force:$force -WarningAction 0 }} }} catch {{ @@ -262,13 +263,13 @@ function Register-PSSessionConfiguration }} }} -if ($null -eq $args[14]) +if ($null -eq $args[15]) {{ - Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] + Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -noRestart $args[14] }} else {{ - Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -erroraction $args[14] + Register-PSSessionConfiguration -filepath $args[0] -pluginName $args[1] -shouldShowUI $args[2] -force $args[3] -whatif:$args[4] -confirm:$args[5] -restartWSManTarget $args[6] -restartWSManAction $args[7] -restartWSManRequired $args[8] -runAsUserName $args[9] -runAsPassword $args[10] -accessMode $args[11] -isSddlSpecified $args[12] -configTableSddl $args[13] -noRestart $args[14] -erroraction $args[15] }} "; @@ -348,7 +349,7 @@ static RegisterPSSessionConfigurationCommand() string localSDDL = GetLocalSddl(); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. string newPluginSbString = string.Format(CultureInfo.InvariantCulture, newPluginSbFormat, WSManNativeApi.ResourceURIPrefix, localSDDL, RemoteManagementUsersSID, InteractiveUsersSID); @@ -544,9 +545,7 @@ protected override void ProcessRecord() string restartServiceTarget = StringUtil.Format(RemotingErrorIdStrings.RestartWSManServiceTarget, "WinRM"); string restartWSManRequiredForUI = StringUtil.Format(RemotingErrorIdStrings.RestartWSManRequiredShowUI, - string.Format(CultureInfo.InvariantCulture, - "Set-PSSessionConfiguration {0} -ShowSecurityDescriptorUI", - shellName)); + string.Create(CultureInfo.InvariantCulture, $"Set-PSSessionConfiguration {shellName} -ShowSecurityDescriptorUI")); // gather -WhatIf, -Confirm parameter data and pass it to the script block bool whatIf = false; @@ -594,6 +593,7 @@ protected override void ProcessRecord() AccessMode, isSddlSpecified, _configTableSDDL, + noRestart, errorAction }); @@ -1373,7 +1373,7 @@ internal static PSCredential CreateGMSAAccountCredentials(string gmsaAccount) Dbg.Assert(!string.IsNullOrEmpty(gmsaAccount), "Should not be null or empty string."); // Validate account name form (must be DomainName\UserName) - var parts = gmsaAccount.Split(Utils.Separators.Backslash); + var parts = gmsaAccount.Split('\\'); if ((parts.Length != 2) || (string.IsNullOrEmpty(parts[0])) || (string.IsNullOrEmpty(parts[1])) @@ -1462,7 +1462,7 @@ internal static string GetRunAsVirtualAccountGroupsString(string[] groups) { if (groups == null) { return string.Empty; } - return string.Join(";", groups); + return string.Join(';', groups); } /// @@ -1753,7 +1753,7 @@ internal static string CreateConditionalACEFromConfig( } StringBuilder conditionalACE = new StringBuilder(); - if (!(configTable[ConfigFileConstants.RequiredGroups] is Hashtable requiredGroupsHash)) + if (configTable[ConfigFileConstants.RequiredGroups] is not Hashtable requiredGroupsHash) { throw new PSInvalidOperationException(RemotingErrorIdStrings.RequiredGroupsNotHashTable); } @@ -1962,7 +1962,10 @@ public string Name [Parameter(Position = 1, Mandatory = true, ParameterSetName = PSSessionConfigurationCommandBase.AssemblyNameParameterSetName)] public string AssemblyName { - get { return assemblyName; } + get + { + return assemblyName; + } set { @@ -1984,7 +1987,10 @@ public string AssemblyName [Parameter(ParameterSetName = AssemblyNameParameterSetName)] public string ApplicationBase { - get { return applicationBase; } + get + { + return applicationBase; + } set { @@ -2004,7 +2010,10 @@ public string ApplicationBase [Parameter(Position = 2, Mandatory = true, ParameterSetName = PSSessionConfigurationCommandBase.AssemblyNameParameterSetName)] public string ConfigurationTypeName { - get { return configurationTypeName; } + get + { + return configurationTypeName; + } set { @@ -2053,7 +2062,10 @@ public ApartmentState ThreadApartmentState return ApartmentState.Unknown; } - set { threadAptState = value; } + set + { + threadAptState = value; + } } internal ApartmentState? threadAptState; @@ -2074,7 +2086,10 @@ public PSThreadOptions ThreadOptions return PSThreadOptions.UseCurrentThread; } - set { threadOptions = value; } + set + { + threadOptions = value; + } } internal PSThreadOptions? threadOptions; @@ -2085,7 +2100,10 @@ public PSThreadOptions ThreadOptions [Parameter] public PSSessionConfigurationAccessMode AccessMode { - get { return _accessMode; } + get + { + return _accessMode; + } set { @@ -2124,7 +2142,10 @@ public SwitchParameter UseSharedProcess [Parameter()] public string StartupScript { - get { return configurationScript; } + get + { + return configurationScript; + } set { @@ -2144,7 +2165,10 @@ public string StartupScript [AllowNull] public double? MaximumReceivedDataSizePerCommandMB { - get { return maxCommandSizeMB; } + get + { + return maxCommandSizeMB; + } set { @@ -2171,7 +2195,10 @@ public double? MaximumReceivedDataSizePerCommandMB [AllowNull] public double? MaximumReceivedObjectSizeMB { - get { return maxObjectSizeMB; } + get + { + return maxObjectSizeMB; + } set { @@ -2198,7 +2225,10 @@ public double? MaximumReceivedObjectSizeMB [Parameter()] public string SecurityDescriptorSddl { - get { return sddl; } + get + { + return sddl; + } set { @@ -2228,7 +2258,10 @@ public string SecurityDescriptorSddl [Parameter()] public SwitchParameter ShowSecurityDescriptorUI { - get { return _showUI; } + get + { + return _showUI; + } set { @@ -2280,17 +2313,15 @@ public SwitchParameter NoServiceRestart [ValidateNotNullOrEmpty] public Version PSVersion { - get { return psVersion; } + get + { + return psVersion; + } set { - RemotingCommandUtil.CheckPSVersion(value); - - // Check if specified version of PowerShell is installed - RemotingCommandUtil.CheckIfPowerShellVersionIsInstalled(value); - - psVersion = value; - isPSVersionSpecified = true; + // PowerShell 7 remoting endpoints do not support PSVersion. + throw new PSNotSupportedException(RemotingErrorIdStrings.PowerShellVersionNotSupported); } } @@ -2589,7 +2620,7 @@ static UnregisterPSSessionConfigurationCommand() removePluginSbFormat, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_removePluginSb = ScriptBlock.Create(removePluginScript); s_removePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -2805,7 +2836,7 @@ static GetPSSessionConfigurationCommand() PSSessionConfigurationCommandUtilities.PSCustomShellTypeName, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_getPluginSb = ScriptBlock.Create(scriptToRun); s_getPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -3229,7 +3260,7 @@ static SetPSSessionConfigurationCommand() RemotingConstants.PSPluginDLLName, localSDDL, RemoteManagementUsersSID, InteractiveUsersSID); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_setPluginSb = ScriptBlock.Create(setPluginScript); s_setPluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -3962,7 +3993,7 @@ public sealed class EnablePSSessionConfigurationCommand : PSCmdlet function Test-WinRMQuickConfigNeeded {{ - # see issue #11005 - Function Test-WinRMQuickConfigNeeded needs to be updated: + # see issue #11005 - Function Test-WinRMQuickConfigNeeded needs to be updated: # 1) currently this function always returns $True # 2) checking for a firewall rule using Get-NetFirewallRule engages WinCompat code and has significant perf impact on Enable-PSRemoting; maybe change to Get-CimInstance -ClassName MSFT_NetFirewallRule return $True @@ -4179,7 +4210,7 @@ static EnablePSSessionConfigurationCommand() enablePluginSbFormat, setWSManConfigCommand, PSSessionConfigurationCommandBase.RemoteManagementUsersSID, PSSessionConfigurationCommandBase.InteractiveUsersSID); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_enablePluginSb = ScriptBlock.Create(enablePluginScript); s_enablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -4466,7 +4497,7 @@ static DisablePSSessionConfigurationCommand() disablePluginSbFormat); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_disablePluginSb = ScriptBlock.Create(disablePluginScript); s_disablePluginSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -4873,7 +4904,7 @@ static EnablePSRemotingCommand() RemotingConstants.MaxIdleTimeoutMS, RemotingConstants.PSPluginDLLName); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_enableRemotingSb = ScriptBlock.Create(enableRemotingScript); s_enableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -5097,7 +5128,7 @@ static DisablePSRemotingCommand() string disableRemotingScript = string.Format(CultureInfo.InvariantCulture, disablePSRemotingFormat, localSDDL); // compile the script block statically and reuse the same instance - // everytime the command is run..This will save on parsing time. + // every time the command is run..This will save on parsing time. s_disableRemotingSb = ScriptBlock.Create(disableRemotingScript); s_disableRemotingSb.LanguageMode = PSLanguageMode.FullLanguage; } @@ -5233,7 +5264,7 @@ protected override void BeginProcessing() } // The validator that will be applied to the role lookup - Func validator = (role) => true; + Func validator = static (role) => true; if (!string.IsNullOrEmpty(this.Username)) { @@ -5242,7 +5273,7 @@ protected override void BeginProcessing() validator = null; // Convert DOMAIN\user to the upn (user@DOMAIN) - string[] upnComponents = this.Username.Split(Utils.Separators.Backslash); + string[] upnComponents = this.Username.Split('\\'); if (upnComponents.Length == 2) { this.Username = upnComponents[1] + "@" + upnComponents[0]; diff --git a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs index 777f56807fe..ece0ce45dbf 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DebugJob.cs @@ -100,7 +100,6 @@ public Guid InstanceId /// /// Gets or sets a flag that tells PowerShell to automatically perform a BreakAll when the debugger is attached to the remote target. /// - [Experimental("Microsoft.PowerShell.Utility.PSManageBreakpointsInRunspace", ExperimentAction.Show)] [Parameter] public SwitchParameter BreakAll { get; set; } @@ -204,10 +203,7 @@ protected override void StopProcessing() // Unblock the data collection. PSDataCollection debugCollection = _debugCollection; - if (debugCollection != null) - { - debugCollection.Complete(); - } + debugCollection?.Complete(); } #endregion @@ -230,7 +226,10 @@ private bool CheckForDebuggableJob() foreach (var cJob in _job.ChildJobs) { debuggableJobFound = GetJobDebuggable(cJob); - if (debuggableJobFound) { break; } + if (debuggableJobFound) + { + break; + } } } @@ -261,10 +260,7 @@ private void WaitAndReceiveJobOutput() // or this command is cancelled. foreach (var streamItem in _debugCollection) { - if (streamItem != null) - { - streamItem.WriteStreamObject(this); - } + streamItem?.WriteStreamObject(this); } } catch (Exception) diff --git a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs index 0e2458daba0..74bcbac2c33 100644 --- a/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/DisconnectPSSession.cs @@ -392,7 +392,7 @@ private static string GetLocalhostWithNetworkAccessEnabled(Dictionary /// Throttle class to perform a remoterunspace disconnect operation. /// - private class DisconnectRunspaceOperation : IThrottleOperation + private sealed class DisconnectRunspaceOperation : IThrottleOperation { private readonly PSSession _remoteSession; private readonly ObjectStream _writeStream; diff --git a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs index 756250eb8d7..f7aef0530b8 100644 --- a/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/EnterPSHostProcessCommand.cs @@ -54,7 +54,7 @@ public sealed class EnterPSHostProcessCommand : PSCmdlet /// Process to enter. /// [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = EnterPSHostProcessCommand.ProcessParameterSet)] - [ValidateNotNull()] + [ValidateNotNull] public Process Process { get; @@ -76,7 +76,7 @@ public int Id /// Name of process to enter. An error will result if more than one such process exists. /// [Parameter(Position = 0, Mandatory = true, ParameterSetName = EnterPSHostProcessCommand.ProcessNameParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string Name { get; @@ -87,7 +87,7 @@ public string Name /// Host Process Info object that describes a connectible process. /// [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = EnterPSHostProcessCommand.PSHostProcessInfoParameterSet)] - [ValidateNotNull()] + [ValidateNotNull] public PSHostProcessInfo HostProcessInfo { get; @@ -212,10 +212,7 @@ protected override void EndProcessing() protected override void StopProcessing() { RemoteRunspace connectingRunspace = _connectingRemoteRunspace; - if (connectingRunspace != null) - { - connectingRunspace.AbortOpen(); - } + connectingRunspace?.AbortOpen(); } #endregion @@ -318,22 +315,19 @@ private static void PrepareRunspace(Runspace runspace) private Process GetProcessById(int procId) { - try - { - return Process.GetProcessById(procId); - } - catch (System.ArgumentException) + var process = PSHostProcessUtils.GetProcessById(procId); + if (process is null) { ThrowTerminatingError( - new ErrorRecord( - new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithId, procId)), - "EnterPSHostProcessNoProcessFoundWithId", - ErrorCategory.InvalidArgument, - this) - ); - - return null; + new ErrorRecord( + new PSArgumentException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoProcessFoundWithId, procId)), + "EnterPSHostProcessNoProcessFoundWithId", + ErrorCategory.InvalidArgument, + this) + ); } + + return process; } private Process GetProcessByHostProcessInfo(PSHostProcessInfo hostProcessInfo) @@ -403,7 +397,7 @@ private void VerifyProcess(Process process) { ThrowTerminatingError( new ErrorRecord( - new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoPowerShell, Process.ProcessName)), + new PSInvalidOperationException(StringUtil.Format(RemotingErrorIdStrings.EnterPSHostProcessNoPowerShell, Process.Id)), "EnterPSHostProcessNoPowerShell", ErrorCategory.InvalidOperation, this) @@ -506,7 +500,7 @@ public sealed class GetPSHostProcessInfoCommand : PSCmdlet /// [Parameter(Position = 0, ParameterSetName = GetPSHostProcessInfoCommand.ProcessNameParameterSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public string[] Name { get; @@ -518,7 +512,7 @@ public string[] Name /// [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = GetPSHostProcessInfoCommand.ProcessParameterSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public Process[] Process { get; @@ -530,7 +524,7 @@ public Process[] Process /// [Parameter(Position = 0, Mandatory = true, ParameterSetName = GetPSHostProcessInfoCommand.ProcessIdParameterSet)] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public int[] Id { get; @@ -599,9 +593,22 @@ private static int[] GetProcIdsFromNames(string[] names) WildcardPattern namePattern = WildcardPattern.Get(name, WildcardOptions.IgnoreCase); foreach (var proc in processes) { - if (namePattern.IsMatch(proc.ProcessName)) + // Skip processes that have already terminated. + if (proc.HasExited) { - returnIds.Add(proc.Id); + continue; + } + + try + { + if (namePattern.IsMatch(proc.ProcessName)) + { + returnIds.Add(proc.Id); + } + } + catch (InvalidOperationException) + { + // Ignore if process has exited in the mean time. } } } @@ -665,7 +672,10 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc } } - if (!found) { continue; } + if (!found) + { + continue; + } } } else @@ -681,10 +691,9 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc string pName = namedPipe.Substring(pNameIndex + 1); Process process = null; - try { - process = System.Diagnostics.Process.GetProcessById(id); + process = PSHostProcessUtils.GetProcessById(id); } catch (Exception) { @@ -704,10 +713,20 @@ internal static IReadOnlyCollection GetAppDomainNamesFromProc // best effort to cleanup } } - else if (process.ProcessName.Equals(pName, StringComparison.Ordinal)) + else { - // only add if the process name matches - procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName, namedPipe)); + try + { + if (process.ProcessName.Equals(pName, StringComparison.Ordinal)) + { + // only add if the process name matches + procAppDomainInfo.Add(new PSHostProcessInfo(pName, id, appDomainName, namedPipe)); + } + } + catch (InvalidOperationException) + { + // Ignore if process has exited in the mean time. + } } } } @@ -796,8 +815,8 @@ internal PSHostProcessInfo( MainWindowTitle = string.Empty; try { - var proc = Process.GetProcessById(processId); - MainWindowTitle = proc.MainWindowTitle ?? string.Empty; + var process = PSHostProcessUtils.GetProcessById(processId); + MainWindowTitle = process?.MainWindowTitle ?? string.Empty; } catch (ArgumentException) { @@ -831,4 +850,30 @@ public string GetPipeNameFilePath() } #endregion + + #region PSHostProcessUtils + + internal static class PSHostProcessUtils + { + /// + /// Return a System.Diagnostics.Process object by process Id, + /// or null if not found or process has exited. + /// + /// Process of Id to find. + /// Process object or null. + public static Process GetProcessById(int procId) + { + try + { + var process = Process.GetProcessById(procId); + return process.HasExited ? null : process; + } + catch (System.ArgumentException) + { + return null; + } + } + } + + #endregion } diff --git a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs index 17ee25c52cf..fe5946f44f0 100644 --- a/src/System.Management.Automation/engine/remoting/commands/GetJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/GetJob.cs @@ -110,7 +110,7 @@ protected override void ProcessRecord() { List jobList = FindJobs(); - jobList.Sort((x, y) => x != null ? x.Id.CompareTo(y != null ? y.Id : 1) : -1); + jobList.Sort(static (x, y) => x != null ? x.Id.CompareTo(y != null ? y.Id : 1) : -1); WriteObject(jobList, true); } @@ -256,7 +256,10 @@ private List FindChildJobs(List jobList) { foreach (Job childJob in job.ChildJobs) { - if (childJob.JobStateInfo.State != ChildJobState) continue; + if (childJob.JobStateInfo.State != ChildJobState) + { + continue; + } matches.Add(childJob); } diff --git a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs index b60f3131f24..e340a1acbdb 100644 --- a/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/InvokeCommandCommand.cs @@ -198,7 +198,7 @@ public override string[] ComputerName ParameterSetName = InvokeCommandCommand.FilePathVMIdParameterSet)] [Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true, ParameterSetName = InvokeCommandCommand.FilePathVMNameParameterSet)] - [Credential()] + [Credential] public override PSCredential Credential { get @@ -226,7 +226,7 @@ public override PSCredential Credential [Parameter(ParameterSetName = InvokeCommandCommand.ComputerNameParameterSet)] [Parameter(ParameterSetName = InvokeCommandCommand.FilePathComputerNameParameterSet)] [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] - [ValidateRange((int)1, (int)UInt16.MaxValue)] + [ValidateRange((int)1, (int)ushort.MaxValue)] public override int Port { get @@ -308,7 +308,7 @@ public override string ConfigurationName /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, @@ -702,7 +702,7 @@ public override SwitchParameter RunAsAdministrator ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] [Parameter(Mandatory = true, ParameterSetName = InvokeCommandCommand.FilePathSSHHostParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public override string[] HostName { get { return base.HostName; } @@ -715,7 +715,7 @@ public override string[] HostName /// [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] [Parameter(ParameterSetName = InvokeCommandCommand.FilePathSSHHostParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public override string UserName { get { return base.UserName; } @@ -728,7 +728,7 @@ public override string UserName /// [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] [Parameter(ParameterSetName = InvokeCommandCommand.FilePathSSHHostParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] [Alias("IdentityFilePath")] public override string KeyFilePath { @@ -737,6 +737,30 @@ public override string KeyFilePath set { base.KeyFilePath = value; } } + /// + /// Gets and sets a value for the SSH subsystem to use for the remote connection. + /// + [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] + [Parameter(ParameterSetName = InvokeCommandCommand.FilePathSSHHostParameterSet)] + public override string Subsystem + { + get { return base.Subsystem; } + + set { base.Subsystem = value; } + } + + /// + /// Gets and sets a value in milliseconds that limits the time allowed for an SSH connection to be established. + /// + [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] + [Parameter(ParameterSetName = InvokeCommandCommand.FilePathSSHHostParameterSet)] + public override int ConnectingTimeout + { + get { return base.ConnectingTimeout; } + + set { base.ConnectingTimeout = value; } + } + /// /// This parameter specifies that SSH is used to establish the remote /// connection and act as the remoting transport. By default WinRM is used @@ -761,13 +785,32 @@ public override SwitchParameter SSHTransport /// [Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostHashParameterSet, Mandatory = true)] [Parameter(ParameterSetName = InvokeCommandCommand.FilePathSSHHostHashParameterSet, Mandatory = true)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public override Hashtable[] SSHConnection { get; set; } + /// + /// Hashtable containing options to be passed to OpenSSH. + /// + [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] + [Parameter(ParameterSetName = InvokeCommandCommand.FilePathSSHHostParameterSet)] + [ValidateNotNullOrEmpty] + public override Hashtable Options + { + get + { + return base.Options; + } + + set + { + base.Options = value; + } + } + #endregion #region Remote Debug Parameters @@ -983,7 +1026,7 @@ protected override void BeginProcessing() { // In order to support foreach remoting properly ( icm | % { icm } ), the server must // be using protocol version 2.2. Otherwise, we skip this and assume the old behavior. - if (version >= RemotingConstants.ProtocolVersionWin8RTM) + if (version >= RemotingConstants.ProtocolVersion_2_2) { // Suppress collection behavior _needToCollect = false; @@ -1007,7 +1050,7 @@ protected override void BeginProcessing() // create collection of input writers here foreach (IThrottleOperation operation in Operations) { - if (!(operation is ExecutionCmdletHelperRunspace ecHelper)) + if (operation is not ExecutionCmdletHelperRunspace ecHelper) { // either all the operations will be of type ExecutionCmdletHelperRunspace // or not...there is no mix. @@ -1420,10 +1463,7 @@ private void HandleRunspaceDebugStop(object sender, StartRunspaceDebugProcessing operation.RunspaceDebugStop -= HandleRunspaceDebugStop; var hostDebugger = GetHostDebugger(); - if (hostDebugger != null) - { - hostDebugger.QueueRunspaceForDebug(args.Runspace); - } + hostDebugger?.QueueRunspaceForDebug(args.Runspace); } private void HandleJobStateChanged(object sender, JobStateEventArgs e) @@ -1440,10 +1480,7 @@ private void HandleJobStateChanged(object sender, JobStateEventArgs e) // Signal that this job has been disconnected, or has ended. lock (_jobSyncObject) { - if (_disconnectComplete != null) - { - _disconnectComplete.Set(); - } + _disconnectComplete?.Set(); } } } @@ -2047,11 +2084,8 @@ private void Dispose(bool disposing) if (!_asjob) { - if (_job != null) - { - // job will be null in the "InProcess" case - _job.Dispose(); - } + // job will be null in the "InProcess" case + _job?.Dispose(); _throttleManager.ThrottleComplete -= HandleThrottleComplete; _throttleManager.Dispose(); @@ -2133,10 +2167,7 @@ public void StartProgress( return; } - if (string.IsNullOrEmpty(computerName)) - { - throw new ArgumentNullException(nameof(computerName)); - } + ArgumentException.ThrowIfNullOrEmpty(computerName); lock (_syncObject) { diff --git a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs index 7bb52abcb1e..29d107a074f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs +++ b/src/System.Management.Automation/engine/remoting/commands/JobRepository.cs @@ -19,10 +19,7 @@ public abstract class Repository where T : class /// Object to add. public void Add(T item) { - if (item == null) - { - throw new ArgumentNullException(_identifier); - } + ArgumentNullException.ThrowIfNull(item, _identifier); lock (_syncObject) { @@ -45,10 +42,7 @@ public void Add(T item) /// Object to remove. public void Remove(T item) { - if (item == null) - { - throw new ArgumentNullException(_identifier); - } + ArgumentNullException.ThrowIfNull(item, _identifier); lock (_syncObject) { diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs index 56bd72e90d8..4e669e891f2 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionConfigurationFile.cs @@ -15,7 +15,6 @@ namespace Microsoft.PowerShell.Commands { -#if !UNIX /// /// New-PSSessionConfigurationFile command implementation /// @@ -49,7 +48,7 @@ public string Path /// /// Configuration file schema version. /// - [Parameter()] + [Parameter] [ValidateNotNull] public Version SchemaVersion { @@ -69,7 +68,7 @@ public Version SchemaVersion /// /// Configuration file GUID. /// - [Parameter()] + [Parameter] public Guid Guid { get @@ -88,7 +87,7 @@ public Guid Guid /// /// Author of the configuration file. /// - [Parameter()] + [Parameter] public string Author { get @@ -107,7 +106,7 @@ public string Author /// /// Description. /// - [Parameter()] + [Parameter] public string Description { get @@ -126,7 +125,7 @@ public string Description /// /// Company name. /// - [Parameter()] + [Parameter] public string CompanyName { get @@ -145,7 +144,7 @@ public string CompanyName /// /// Copyright information. /// - [Parameter()] + [Parameter] public string Copyright { get @@ -164,7 +163,7 @@ public string Copyright /// /// Specifies type of initial session state to use. /// - [Parameter()] + [Parameter] public SessionType SessionType { get @@ -183,7 +182,7 @@ public SessionType SessionType /// /// Specifies the directory for transcripts to be placed. /// - [Parameter()] + [Parameter] public string TranscriptDirectory { get @@ -202,13 +201,13 @@ public string TranscriptDirectory /// /// Specifies whether to run this configuration under a virtual account. /// - [Parameter()] + [Parameter] public SwitchParameter RunAsVirtualAccount { get; set; } /// /// Specifies groups a virtual account is part of. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] RunAsVirtualAccountGroups { get; set; } @@ -217,7 +216,7 @@ public string TranscriptDirectory /// The User drive is used with Copy-Item for file transfer when the FileSystem provider is /// not visible in the session. /// - [Parameter()] + [Parameter] public SwitchParameter MountUserDrive { get; @@ -229,7 +228,7 @@ public SwitchParameter MountUserDrive /// MountUserDrive parameter. /// If no maximum size is specified then the default drive maximum size is 50MB. /// - [Parameter()] + [Parameter] public long UserDriveMaximumSize { get; set; } // Temporarily removed until script input parameter validation is implemented. @@ -240,7 +239,7 @@ public SwitchParameter MountUserDrive /// If a MountUserDrive is specified for the PSSession then input parameter validation will be /// enabled automatically. /// - [Parameter()] + [Parameter] public SwitchParameter EnforceInputParameterValidation { get; set; } */ @@ -248,13 +247,13 @@ public SwitchParameter MountUserDrive /// Optional parameter that specifies a Group Managed Service Account name in which the configuration /// is run. /// - [Parameter()] + [Parameter] public string GroupManagedServiceAccount { get; set; } /// /// Scripts to process. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ScriptsToProcess { @@ -274,7 +273,7 @@ public string[] ScriptsToProcess /// /// Role definitions for this session configuration (Role name -> Role capability) /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary RoleDefinitions { @@ -294,7 +293,7 @@ public IDictionary RoleDefinitions /// /// Specifies account groups that are membership requirements for this session. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary RequiredGroups { @@ -308,7 +307,7 @@ public IDictionary RequiredGroups /// /// Language mode. /// - [Parameter()] + [Parameter] public PSLanguageMode LanguageMode { get @@ -329,7 +328,7 @@ public PSLanguageMode LanguageMode /// /// Execution policy. /// - [Parameter()] + [Parameter] public ExecutionPolicy ExecutionPolicy { get @@ -348,7 +347,7 @@ public ExecutionPolicy ExecutionPolicy /// /// PowerShell version. /// - [Parameter()] + [Parameter] public Version PowerShellVersion { get @@ -367,7 +366,7 @@ public Version PowerShellVersion /// /// A list of modules to import. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] ModulesToImport { @@ -387,7 +386,7 @@ public object[] ModulesToImport /// /// A list of visible aliases. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] VisibleAliases { @@ -407,7 +406,7 @@ public string[] VisibleAliases /// /// A list of visible cmdlets. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] VisibleCmdlets { @@ -427,7 +426,7 @@ public object[] VisibleCmdlets /// /// A list of visible functions. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] VisibleFunctions { @@ -447,7 +446,7 @@ public object[] VisibleFunctions /// /// A list of visible external commands (scripts and applications) /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] VisibleExternalCommands { @@ -467,7 +466,7 @@ public string[] VisibleExternalCommands /// /// A list of providers. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] VisibleProviders { @@ -487,7 +486,7 @@ public string[] VisibleProviders /// /// A list of aliases. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public IDictionary[] AliasDefinitions { @@ -507,7 +506,7 @@ public IDictionary[] AliasDefinitions /// /// A list of functions. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public IDictionary[] FunctionDefinitions { @@ -527,7 +526,7 @@ public IDictionary[] FunctionDefinitions /// /// A list of variables. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object VariableDefinitions { @@ -547,7 +546,7 @@ public object VariableDefinitions /// /// A list of environment variables. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary EnvironmentVariables @@ -568,7 +567,7 @@ public IDictionary EnvironmentVariables /// /// A list of types to process. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] TypesToProcess { @@ -588,7 +587,7 @@ public string[] TypesToProcess /// /// A list of format data to process. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] FormatsToProcess { @@ -608,7 +607,7 @@ public string[] FormatsToProcess /// /// A list of assemblies to load. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] AssembliesToLoad { @@ -629,7 +628,7 @@ public string[] AssembliesToLoad /// Gets or sets whether to include a full expansion of all possible session configuration /// keys as comments when creating the session configuration file. /// - [Parameter()] + [Parameter] public SwitchParameter Full { get; set; } #endregion @@ -1126,7 +1125,6 @@ private bool ShouldGenerateConfigurationSnippet(string parameterName) #endregion } -#endif /// /// New-PSRoleCapabilityFile command implementation @@ -1161,7 +1159,7 @@ public string Path /// /// Configuration file GUID. /// - [Parameter()] + [Parameter] public Guid Guid { get @@ -1180,7 +1178,7 @@ public Guid Guid /// /// Author of the configuration file. /// - [Parameter()] + [Parameter] public string Author { get @@ -1199,7 +1197,7 @@ public string Author /// /// Description. /// - [Parameter()] + [Parameter] public string Description { get @@ -1218,7 +1216,7 @@ public string Description /// /// Company name. /// - [Parameter()] + [Parameter] public string CompanyName { get @@ -1237,7 +1235,7 @@ public string CompanyName /// /// Copyright information. /// - [Parameter()] + [Parameter] public string Copyright { get @@ -1256,7 +1254,7 @@ public string Copyright /// /// A list of modules to import. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] ModulesToImport { @@ -1276,7 +1274,7 @@ public object[] ModulesToImport /// /// A list of visible aliases. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] VisibleAliases { @@ -1296,7 +1294,7 @@ public string[] VisibleAliases /// /// A list of visible cmdlets. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] VisibleCmdlets { @@ -1316,7 +1314,7 @@ public object[] VisibleCmdlets /// /// A list of visible functions. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object[] VisibleFunctions { @@ -1336,7 +1334,7 @@ public object[] VisibleFunctions /// /// A list of visible external commands (scripts and applications) /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] VisibleExternalCommands { @@ -1356,7 +1354,7 @@ public string[] VisibleExternalCommands /// /// A list of providers. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] VisibleProviders { @@ -1376,7 +1374,7 @@ public string[] VisibleProviders /// /// Scripts to process. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] ScriptsToProcess { @@ -1396,7 +1394,7 @@ public string[] ScriptsToProcess /// /// A list of aliases. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public IDictionary[] AliasDefinitions { @@ -1416,7 +1414,7 @@ public IDictionary[] AliasDefinitions /// /// A list of functions. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public IDictionary[] FunctionDefinitions { @@ -1436,7 +1434,7 @@ public IDictionary[] FunctionDefinitions /// /// A list of variables. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public object VariableDefinitions { @@ -1456,7 +1454,7 @@ public object VariableDefinitions /// /// A list of environment variables. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public IDictionary EnvironmentVariables @@ -1477,7 +1475,7 @@ public IDictionary EnvironmentVariables /// /// A list of types to process. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] TypesToProcess { @@ -1497,7 +1495,7 @@ public string[] TypesToProcess /// /// A list of format data to process. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] FormatsToProcess { @@ -1517,7 +1515,7 @@ public string[] FormatsToProcess /// /// A list of assemblies to load. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] AssembliesToLoad { @@ -1868,12 +1866,10 @@ internal static string ConfigFragment(string key, string resourceString, string if (isExample) { - return string.Format(CultureInfo.InvariantCulture, "# {0}{1}# {2:19} = {3}{4}{5}", - resourceString, nl, key, value, nl, nl); + return string.Format(CultureInfo.InvariantCulture, "# {0}{1}# {2:19} = {3}{4}{5}", resourceString, nl, key, value, nl, nl); } - return string.Format(CultureInfo.InvariantCulture, "# {0}{1}{2:19} = {3}{4}{5}", - resourceString, nl, key, value, nl, nl); + return string.Format(CultureInfo.InvariantCulture, "# {0}{1}{2:19} = {3}{4}{5}", resourceString, nl, key, value, nl, nl); } /// @@ -1884,7 +1880,10 @@ internal static string ConfigFragment(string key, string resourceString, string internal static string QuoteName(object name) { if (name == null) + { return "''"; + } + return "'" + System.Management.Automation.Language.CodeGeneration.EscapeSingleQuotedStringContent(name.ToString()) + "'"; } @@ -1944,7 +1943,7 @@ internal static string CombineHashtable(IDictionary table, StreamWriter writer, sb.Append("@{"); - var keys = table.Keys.Cast().OrderBy(x => x); + var keys = table.Keys.Cast().Order(); foreach (var key in keys) { sb.Append(writer.NewLine); diff --git a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs index 2a6dbc30679..bb7641d2e5b 100644 --- a/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/NewPSSessionOptionCommand.cs @@ -136,11 +136,13 @@ public int OpenTimeout { get { - return _openTimeout.HasValue ? _openTimeout.Value : - RunspaceConnectionInfo.DefaultOpenTimeout; + return _openTimeout ?? RunspaceConnectionInfo.DefaultOpenTimeout; } - set { _openTimeout = value; } + set + { + _openTimeout = value; + } } private int? _openTimeout; @@ -161,11 +163,13 @@ public int CancelTimeout { get { - return _cancelTimeout.HasValue ? _cancelTimeout.Value : - BaseTransportManager.ClientCloseTimeoutMs; + return _cancelTimeout ?? BaseTransportManager.ClientCloseTimeoutMs; } - set { _cancelTimeout = value; } + set + { + _cancelTimeout = value; + } } private int? _cancelTimeout; @@ -183,11 +187,13 @@ public int IdleTimeout { get { - return _idleTimeout.HasValue ? _idleTimeout.Value - : RunspaceConnectionInfo.DefaultIdleTimeout; + return _idleTimeout ?? RunspaceConnectionInfo.DefaultIdleTimeout; } - set { _idleTimeout = value; } + set + { + _idleTimeout = value; + } } private int? _idleTimeout; @@ -290,11 +296,13 @@ public int OperationTimeout { get { - return (_operationtimeout.HasValue ? _operationtimeout.Value : - BaseTransportManager.ClientDefaultOperationTimeoutMs); + return _operationtimeout ?? BaseTransportManager.ClientDefaultOperationTimeoutMs; } - set { _operationtimeout = value; } + set + { + _operationtimeout = value; + } } private int? _operationtimeout; @@ -308,7 +316,10 @@ public int OperationTimeout [Parameter] public SwitchParameter NoEncryption { - get { return _noencryption; } + get + { + return _noencryption; + } set { @@ -327,7 +338,10 @@ public SwitchParameter NoEncryption [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "UTF")] public SwitchParameter UseUTF16 { - get { return _useutf16; } + get + { + return _useutf16; + } set { diff --git a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs index 9fafd34eec4..ee06dc22130 100644 --- a/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs +++ b/src/System.Management.Automation/engine/remoting/commands/PSRemotingCmdlet.cs @@ -15,6 +15,7 @@ using System.Management.Automation.Remoting; using System.Management.Automation.Remoting.Client; using System.Management.Automation.Runspaces; +using System.Threading; using Dbg = System.Management.Automation.Diagnostics; @@ -202,7 +203,7 @@ internal string GetMessage(string resourceString, params object[] args) /// /// Default shellname. /// - protected const string DefaultPowerShellRemoteShellName = System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix + "Microsoft.PowerShell"; + protected const string DefaultPowerShellRemoteShellName = WSManNativeApi.ResourceURIPrefix + "Microsoft.PowerShell"; /// /// Default application name for the connection uri. @@ -285,6 +286,8 @@ internal struct SSHConnection public string KeyFilePath; public int Port; public string Subsystem; + public int ConnectingTimeout; + public Hashtable Options; } /// @@ -442,6 +445,37 @@ internal enum VMState FastSavingCritical, } +#nullable enable + /// + /// Get the State property from Get-VM result. + /// + /// The raw PSObject as returned by Get-VM. + /// The VMState value of the State property if present and parsable, otherwise null. + internal VMState? GetVMStateProperty(PSObject value) + { + object? rawState = value.Properties["State"].Value; + if (rawState is Enum enumState) + { + // If the Hyper-V module was directly importable we have the VMState enum + // value which we can just cast to our VMState type. + return (VMState)enumState; + } + else if (rawState is string stringState && Enum.TryParse(stringState, true, out VMState result)) + { + // If the Hyper-V module was imported through implicit remoting on old + // Windows versions we get a string back which we will try and parse + // as the enum label. + return result; + } + + // Unknown scenario, this should not happen. + string message = PSRemotingErrorInvariants.FormatResourceString( + RemotingErrorIdStrings.HyperVFailedToGetStateUnknownType, + rawState?.GetType()?.FullName ?? "null"); + throw new InvalidOperationException(message); + } +#nullable disable + #endregion #region Tracer @@ -572,7 +606,7 @@ public virtual PSCredential Credential /// [Parameter(ParameterSetName = PSRemotingBaseCmdlet.ComputerNameParameterSet)] [Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)] - [ValidateRange((int)1, (int)UInt16.MaxValue)] + [ValidateRange((int)1, (int)ushort.MaxValue)] public virtual int Port { get; set; } /// @@ -589,7 +623,7 @@ public virtual PSCredential Credential /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, @@ -761,6 +795,20 @@ public virtual string KeyFilePath set; } + /// + /// Gets or sets a value for the SSH subsystem to use for the remote connection. + /// + [Parameter(ValueFromPipelineByPropertyName = true, + ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)] + public virtual string Subsystem { get; set; } + + /// + /// Gets or sets a value in milliseconds that limits the time allowed for an SSH connection to be established. + /// Default timeout value is infinite. + /// + [Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)] + public virtual int ConnectingTimeout { get; set; } = Timeout.Infinite; + /// /// This parameter specifies that SSH is used to establish the remote /// connection and act as the remoting transport. By default WinRM is used @@ -790,11 +838,11 @@ public virtual Hashtable[] SSHConnection } /// - /// This parameter specifies the SSH subsystem to use for the remote connection. + /// Gets or sets the Hashtable containing options to be passed to OpenSSH. /// - [Parameter(ValueFromPipelineByPropertyName = true, - ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] - public virtual string Subsystem { get; set; } + [Parameter(ParameterSetName = InvokeCommandCommand.SSHHostParameterSet)] + [ValidateNotNullOrEmpty] + public virtual Hashtable Options { get; set; } #endregion @@ -856,6 +904,8 @@ internal static void ValidateSpecifiedAuthentication(PSCredential credential, st private const string IdentityFilePathAlias = "IdentityFilePath"; private const string PortParameter = "Port"; private const string SubsystemParameter = "Subsystem"; + private const string ConnectingTimeoutParameter = "ConnectingTimeout"; + private const string OptionsParameter = "Options"; #endregion @@ -902,7 +952,7 @@ protected void ParseSshHostName(string hostname, out string host, out string use /// Array of SSHConnection objects. internal SSHConnection[] ParseSSHConnectionHashTable() { - List connections = new List(); + List connections = new(); foreach (var item in this.SSHConnection) { if (item.ContainsKey(ComputerNameParameter) && item.ContainsKey(HostNameAlias)) @@ -915,7 +965,7 @@ internal SSHConnection[] ParseSSHConnectionHashTable() throw new PSArgumentException(RemotingErrorIdStrings.SSHConnectionDuplicateKeyPath); } - SSHConnection connectionInfo = new SSHConnection(); + SSHConnection connectionInfo = new(); foreach (var key in item.Keys) { string paramName = key as string; @@ -955,6 +1005,14 @@ internal SSHConnection[] ParseSSHConnectionHashTable() { connectionInfo.Subsystem = GetSSHConnectionStringParameter(item[paramName]); } + else if (paramName.Equals(ConnectingTimeoutParameter, StringComparison.OrdinalIgnoreCase)) + { + connectionInfo.ConnectingTimeout = GetSSHConnectionIntParameter(item[paramName]); + } + else if (paramName.Equals(OptionsParameter, StringComparison.OrdinalIgnoreCase)) + { + connectionInfo.Options = item[paramName] as Hashtable; + } else { throw new PSArgumentException( @@ -1448,9 +1506,9 @@ protected void CreateHelpersForSpecifiedSSHComputerNames() { ParseSshHostName(computerName, out string host, out string userName, out int port); - var sshConnectionInfo = new SSHConnectionInfo(userName, host, this.KeyFilePath, port, this.Subsystem); + var sshConnectionInfo = new SSHConnectionInfo(userName, host, KeyFilePath, port, Subsystem, ConnectingTimeout, Options); var typeTable = TypeTable.LoadDefaultTypeFiles(); - var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace; + var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, Host, typeTable) as RemoteRunspace; var pipeline = CreatePipeline(remoteRunspace); var operation = new ExecutionCmdletHelperComputerName(remoteRunspace, pipeline); @@ -1471,7 +1529,8 @@ protected void CreateHelpersForSpecifiedSSHHashComputerNames() sshConnection.ComputerName, sshConnection.KeyFilePath, sshConnection.Port, - sshConnection.Subsystem); + sshConnection.Subsystem, + sshConnection.ConnectingTimeout); var typeTable = TypeTable.LoadDefaultTypeFiles(); var remoteRunspace = RunspaceFactory.CreateRunspace(sshConnectionInfo, this.Host, typeTable) as RemoteRunspace; var pipeline = CreatePipeline(remoteRunspace); @@ -1630,7 +1689,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() { this.VMName[index] = (string)results[0].Properties["VMName"].Value; - if ((VMState)results[0].Properties["State"].Value == VMState.Running) + if (GetVMStateProperty(results[0]) == VMState.Running) { vmIsRunning[index] = true; } @@ -1679,7 +1738,7 @@ protected virtual void CreateHelpersForSpecifiedVMSession() this.VMId[index] = (Guid)results[0].Properties["VMId"].Value; this.VMName[index] = (string)results[0].Properties["VMName"].Value; - if ((VMState)results[0].Properties["State"].Value == VMState.Running) + if (GetVMStateProperty(results[0]) == VMState.Running) { vmIsRunning[index] = true; } @@ -1864,9 +1923,7 @@ internal Pipeline CreatePipeline(RemoteRunspace remoteRunspace) // the array-form using values if all UsingExpressions are in the same scope, otherwise, we handle the UsingExpression as // if the remote end is PSv2. string serverPsVersion = GetRemoteServerPsVersion(remoteRunspace); - System.Management.Automation.PowerShell powershellToUse = (serverPsVersion == PSv2) - ? GetPowerShellForPSv2() - : GetPowerShellForPSv3OrLater(serverPsVersion); + System.Management.Automation.PowerShell powershellToUse = GetPowerShellForPSv3OrLater(serverPsVersion); Pipeline pipeline = remoteRunspace.CreatePipeline(powershellToUse.Commands.Commands[0].CommandText, true); @@ -1887,9 +1944,9 @@ internal Pipeline CreatePipeline(RemoteRunspace remoteRunspace) /// private static string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) { - if (remoteRunspace.ConnectionInfo is NewProcessConnectionInfo) + if (remoteRunspace.ConnectionInfo is not WSManConnectionInfo) { - // This is for Start-Job. The remote end is actually a child local powershell process, so it must be PSv5 or later + // All transport types except for WSManConnectionInfo work with 5.1 or later. return PSv5OrLater; } @@ -1898,45 +1955,25 @@ private static string GetRemoteServerPsVersion(RemoteRunspace remoteRunspace) { // The remote runspace is not opened yet, or it's disconnected before the private data is retrieved. // In this case we cannot validate if the remote server is running PSv5 or later, so for safety purpose, - // we will handle the $using expressions as if the remote server is PSv2. - return PSv2; + // we will handle the $using expressions as if the remote server is PSv3Orv4. + return PSv3Orv4; } - // Unfortunately, the PSVersion value in the private data from PSv3 and PSv4 server is always 2.0. - // This got fixed in PSv5, so a PSv5 server will return 5.0. That means we need other way to tell - // if the remote server is PSv2 or PSv3+. After PSv3, remote runspace supports connect/disconnect, - // so we can use it to differentiate PSv2 from PSv3+. - if (remoteRunspace.CanDisconnect) - { - Version serverPsVersion = null; - PSPrimitiveDictionary.TryPathGet( - psApplicationPrivateData, - out serverPsVersion, - PSVersionInfo.PSVersionTableName, - PSVersionInfo.PSVersionName); - - if (serverPsVersion != null) - { - return serverPsVersion.Major >= 5 ? PSv5OrLater : PSv3Orv4; - } - - // The private data is available but we failed to get the server powershell version. - // This should never happen, but in case it happens, handle the $using expressions - // as if the remote server is PSv2. - Dbg.Assert(false, "Application private data is available but we failed to get the server powershell version. This should never happen."); - } + PSPrimitiveDictionary.TryPathGet( + psApplicationPrivateData, + out Version serverPsVersion, + PSVersionInfo.PSVersionTableName, + PSVersionInfo.PSVersionName); - return PSv2; + // PSv5 server will return 5.0 whereas older versions will always be 2.0. As we don't care about v2 + // anymore we can use a simple ternary check here to differenciate v5 using behaviour vs v3/4. + return serverPsVersion != null && serverPsVersion.Major >= 5 ? PSv5OrLater : PSv3Orv4; } /// /// Adds forwarded events to the local queue. /// - internal void OnRunspacePSEventReceived(object sender, PSEventArgs e) - { - if (this.Events != null) - this.Events.AddForwardedEvent(e); - } + internal void OnRunspacePSEventReceived(object sender, PSEventArgs e) => this.Events?.AddForwardedEvent(e); #endregion Private Methods @@ -2004,7 +2041,6 @@ private void WriteErrorCreateRemoteRunspaceFailed(Exception e, Uri uri) /// private const string PSv5OrLater = "PSv5OrLater"; private const string PSv3Orv4 = "PSv3Orv4"; - private const string PSv2 = "PSv2"; private System.Management.Automation.PowerShell _powershellV2; private System.Management.Automation.PowerShell _powershellV3; @@ -2254,7 +2290,7 @@ private System.Management.Automation.PowerShell GetPowerShellForPSv3OrLater(stri // Semantic checks on the using statement have already validated that there are no arbitrary expressions, // so we'll allow these expressions in everything but NoLanguage mode. - bool allowUsingExpressions = (Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage); + bool allowUsingExpressions = Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage; object[] usingValuesInArray = null; IDictionary usingValuesInDict = null; @@ -2308,7 +2344,7 @@ private System.Management.Automation.PowerShell ConvertToPowerShell() try { // This is trusted input as long as we're in FullLanguage mode - bool isTrustedInput = (Context.LanguageMode == PSLanguageMode.FullLanguage); + bool isTrustedInput = Context.LanguageMode == PSLanguageMode.FullLanguage; powershell = _scriptBlock.GetPowerShell(isTrustedInput, _args); } catch (ScriptBlockToPowerShellNotSupportedException) @@ -2359,7 +2395,8 @@ private string GetConvertedScript(out List newParameterNames, out List GetUsingVariableValues(List paramUsi // GetExpressionValue ensures that it only does variable access when supplied a VariableExpressionAst. // So, this is still safe to use in ConstrainedLanguage and will not result in arbitrary code // execution. - bool allowVariableAccess = (Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage); + bool allowVariableAccess = Context.SessionState.LanguageMode != PSLanguageMode.NoLanguage; foreach (var varAst in paramUsingVars) { @@ -2435,13 +2472,10 @@ private List GetUsingVariableValues(List paramUsi /// A list of UsingExpressionAsts ordered by the StartOffset. private static List GetUsingVariables(ScriptBlock localScriptBlock) { - if (localScriptBlock == null) - { - throw new ArgumentNullException(nameof(localScriptBlock), "Caller needs to make sure the parameter value is not null"); - } + ArgumentNullException.ThrowIfNull(localScriptBlock, "Caller needs to make sure the parameter value is not null"); var allUsingExprs = UsingExpressionAstSearcher.FindAllUsingExpressions(localScriptBlock.Ast); - return allUsingExprs.Select(usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); + return allUsingExprs.Select(static usingExpr => UsingExpressionAst.ExtractUsingVariable((UsingExpressionAst)usingExpr)).ToList(); } #endregion "UsingExpression Utilities" @@ -3452,10 +3486,7 @@ private void RaiseOperationCompleteEvent(EventArgs baseEventArgs) OperationState.StopComplete; operationStateEventArgs.BaseEvent = baseEventArgs; - if (OperationComplete != null) - { - OperationComplete.SafeInvoke(this, operationStateEventArgs); - } + OperationComplete?.SafeInvoke(this, operationStateEventArgs); } } @@ -3650,11 +3681,7 @@ private void HandlePipelineStateChanged(object sender, case PipelineState.Completed: case PipelineState.Stopped: case PipelineState.Failed: - if (RemoteRunspace != null) - { - RemoteRunspace.CloseAsync(); - } - + RemoteRunspace?.CloseAsync(); break; } } @@ -3925,9 +3952,9 @@ internal Collection GetDisconnectedSessions(Collection [Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true, ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public new string HostName { get; set; } + /// + /// Gets or sets the Hashtable containing options to be passed to OpenSSH. + /// + [Parameter(ParameterSetName = PSRemotingBaseCmdlet.SSHHostParameterSet)] + [ValidateNotNullOrEmpty] + public override Hashtable Options + { + get + { + return base.Options; + } + + set + { + base.Options = value; + } + } + #endregion /// @@ -152,7 +170,7 @@ public class EnterPSSessionCommand : PSRemotingBaseCmdlet ParameterSetName = VMIdParameterSet)] [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = VMNameParameterSet)] - [Credential()] + [Credential] public override PSCredential Credential { get { return base.Credential; } @@ -247,7 +265,7 @@ protected override void ProcessRecord() } // for the console host and Graphical PowerShell host - // we want to skip pushing into the the runspace if + // we want to skip pushing into the runspace if // the host is in a nested prompt System.Management.Automation.Internal.Host.InternalHost chost = this.Host as System.Management.Automation.Internal.Host.InternalHost; @@ -314,7 +332,10 @@ protected override void ProcessRecord() } // If runspace is null then the error record has already been written and we can exit. - if (remoteRunspace == null) { return; } + if (remoteRunspace == null) + { + return; + } // If the runspace is in a disconnected state try to connect. bool runspaceConnected = false; @@ -1004,7 +1025,7 @@ private RemoteRunspace GetRunspaceForVMSession() // // VM should be in running state. // - if ((VMState)results[0].Properties["State"].Value != VMState.Running) + if (GetVMStateProperty(results[0]) != VMState.Running) { WriteError( new ErrorRecord( @@ -1262,7 +1283,7 @@ private RemoteRunspace GetRunspaceForContainerSession() private RemoteRunspace GetRunspaceForSSHSession() { ParseSshHostName(HostName, out string host, out string userName, out int port); - var sshConnectionInfo = new SSHConnectionInfo(userName, host, this.KeyFilePath, port, this.Subsystem); + var sshConnectionInfo = new SSHConnectionInfo(userName, host, KeyFilePath, port, Subsystem, ConnectingTimeout, Options); var typeTable = TypeTable.LoadDefaultTypeFiles(); // Use the class _tempRunspace field while the runspace is being opened so that StopProcessing can be handled at that time. diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs index 97585f1de1b..b1759d6a88e 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceiveJob.cs @@ -171,7 +171,7 @@ public PSSession[] Session /// If the results need to be not removed from the store /// after being written. Default is results are removed. /// - [Parameter()] + [Parameter] public SwitchParameter Keep { get @@ -190,7 +190,7 @@ public SwitchParameter Keep /// /// - [Parameter()] + [Parameter] public SwitchParameter NoRecurse { get @@ -208,7 +208,7 @@ public SwitchParameter NoRecurse /// /// - [Parameter()] + [Parameter] public SwitchParameter Force { get; set; } @@ -245,7 +245,7 @@ public override string[] Command /// /// - [Parameter()] + [Parameter] public SwitchParameter Wait { get @@ -262,7 +262,7 @@ public SwitchParameter Wait /// /// - [Parameter()] + [Parameter] public SwitchParameter AutoRemoveJob { get @@ -278,7 +278,7 @@ public SwitchParameter AutoRemoveJob /// /// - [Parameter()] + [Parameter] public SwitchParameter WriteEvents { get @@ -294,7 +294,7 @@ public SwitchParameter WriteEvents /// /// - [Parameter()] + [Parameter] public SwitchParameter WriteJobInResults { get @@ -823,10 +823,7 @@ private void WriteJobResults(Job job) { if (v == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteVerbose(v, true); - } + mshCommandRuntime?.WriteVerbose(v, true); } Collection debugRecords = ReadAll(job.Debug); @@ -835,10 +832,7 @@ private void WriteJobResults(Job job) { if (d == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteDebug(d, true); - } + mshCommandRuntime?.WriteDebug(d, true); } Collection warningRecords = ReadAll(job.Warning); @@ -847,10 +841,7 @@ private void WriteJobResults(Job job) { if (w == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteWarning(w, true); - } + mshCommandRuntime?.WriteWarning(w, true); } Collection progressRecords = ReadAll(job.Progress); @@ -859,10 +850,7 @@ private void WriteJobResults(Job job) { if (p == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteProgress(p, true); - } + mshCommandRuntime?.WriteProgress(p, true); } Collection informationRecords = ReadAll(job.Information); @@ -871,10 +859,7 @@ private void WriteJobResults(Job job) { if (p == null) continue; MshCommandRuntime mshCommandRuntime = CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteInformation(p, true); - } + mshCommandRuntime?.WriteInformation(p, true); } } @@ -1065,10 +1050,7 @@ private void AggregateResultsFromJob(Job job) { lock (_syncObject) { - if (_outputProcessingNotification == null) - { - _outputProcessingNotification = new OutputProcessingState(); - } + _outputProcessingNotification ??= new OutputProcessingState(); } } @@ -1181,14 +1163,21 @@ private void Error_DataAdded(object sender, DataAddedEventArgs e) { lock (_syncObject) { - if (_isDisposed) return; + if (_isDisposed) + { + return; + } } _writeExistingData.WaitOne(); _resultsReaderWriterLock.EnterReadLock(); try { - if (!_results.IsOpen) return; + if (!_results.IsOpen) + { + return; + } + PSDataCollection errorRecords = sender as PSDataCollection; Diagnostics.Assert(errorRecords != null, "PSDataCollection is raising an inappropriate event"); ErrorRecord errorRecord = GetData(errorRecords, e.Index); diff --git a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs index 12cced4ae91..67477e5b36f 100644 --- a/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs +++ b/src/System.Management.Automation/engine/remoting/commands/ReceivePSSession.cs @@ -36,7 +36,7 @@ namespace Microsoft.PowerShell.Commands /// /// The user can specify how command output data is returned by using the public /// OutTarget enumeration (Host, Job). - /// The default actions of this cmdlet is to always direct ouput to host unless + /// The default actions of this cmdlet is to always direct output to host unless /// a job object already exists on the client that is associated with the running /// command. In this case the existing job object is connected to the running /// command and returned. @@ -116,7 +116,7 @@ public class ReceivePSSessionCommand : PSRemotingCmdlet /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, @@ -125,7 +125,10 @@ public class ReceivePSSessionCommand : PSRemotingCmdlet ParameterSetName = ReceivePSSessionCommand.ComputerInstanceIdParameterSet)] public string ApplicationName { - get { return _appName; } + get + { + return _appName; + } set { @@ -150,7 +153,10 @@ public string ApplicationName ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public string ConfigurationName { - get { return _shell; } + get + { + return _shell; + } set { @@ -254,10 +260,13 @@ public SwitchParameter AllowRedirection [Parameter(ParameterSetName = ReceivePSSessionCommand.ComputerSessionNameParameterSet)] [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriSessionNameParameterSet)] [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] - [Credential()] + [Credential] public PSCredential Credential { - get { return _psCredential; } + get + { + return _psCredential; + } set { @@ -278,7 +287,10 @@ public PSCredential Credential [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public AuthenticationMechanism Authentication { - get { return _authentication; } + get + { + return _authentication; + } set { @@ -300,7 +312,10 @@ public AuthenticationMechanism Authentication [Parameter(ParameterSetName = ReceivePSSessionCommand.ConnectionUriInstanceIdParameterSet)] public string CertificateThumbprint { - get { return _thumbprint; } + get + { + return _thumbprint; + } set { @@ -389,15 +404,8 @@ protected override void StopProcessing() tmpJob = _job; } - if (tmpPipeline != null) - { - tmpPipeline.StopAsync(); - } - - if (tmpJob != null) - { - tmpJob.StopJob(); - } + tmpPipeline?.StopAsync(); + tmpJob?.StopJob(); } #endregion @@ -438,9 +446,9 @@ private void QueryForAndConnectCommands(string name, Guid instanceId) string shellUri = null; if (!string.IsNullOrEmpty(ConfigurationName)) { - shellUri = (ConfigurationName.IndexOf( - System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) != -1) ? - ConfigurationName : System.Management.Automation.Remoting.Client.WSManNativeApi.ResourceURIPrefix + ConfigurationName; + shellUri = ConfigurationName.Contains(WSManNativeApi.ResourceURIPrefix, StringComparison.OrdinalIgnoreCase) + ? ConfigurationName + : WSManNativeApi.ResourceURIPrefix + ConfigurationName; } // Connect selected runspace/command and direct command output to host @@ -803,19 +811,13 @@ private void DisconnectAndStopRunningCmds(RemoteRunspace remoteRunspace) remoteRunspace.Disconnect(); - if (stopPipelineReceive != null) + try { - try - { - stopPipelineReceive.Set(); - } - catch (ObjectDisposedException) { } + stopPipelineReceive?.Set(); } + catch (ObjectDisposedException) { } - if (job != null) - { - job.StopJob(); - } + job?.StopJob(); } } @@ -849,7 +851,10 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) { Job childJob = job.ChildJobs[0]; job.ConnectJobs(); - if (CheckForDebugMode(session, true)) { return; } + if (CheckForDebugMode(session, true)) + { + return; + } do { @@ -861,10 +866,7 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) foreach (var result in childJob.ReadAll()) { - if (result != null) - { - result.WriteStreamObject(this); - } + result?.WriteStreamObject(this); } if (index == 0) @@ -922,7 +924,10 @@ private void ConnectSessionToHost(PSSession session, PSRemotingJob job = null) pipelineConnectedEvent = null; - if (CheckForDebugMode(session, true)) { return; } + if (CheckForDebugMode(session, true)) + { + return; + } // Wait for remote command to complete, while writing any available data. while (!_remotePipeline.Output.EndOfPipeline) @@ -1101,7 +1106,10 @@ private void ConnectSessionToJob(PSSession session, PSRemotingJob job = null) } } - if (CheckForDebugMode(session, true)) { return; } + if (CheckForDebugMode(session, true)) + { + return; + } // Write the job object to output. WriteObject(job); @@ -1158,7 +1166,7 @@ private static PSSession ConnectSession(PSSession session, out Exception ex) /// PSSession disconnected runspace object. private PSSession TryGetSessionFromServer(PSSession session) { - if (!(session.Runspace is RemoteRunspace remoteRunspace)) + if (session.Runspace is not RemoteRunspace remoteRunspace) { return null; } @@ -1325,7 +1333,7 @@ public enum OutTarget Host = 1, /// - /// Asynchronous mode. Receive-PSSession ouput data goes to returned job object. + /// Asynchronous mode. Receive-PSSession output data goes to returned job object. /// Job = 2 } diff --git a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs index f8c0a71a0df..af98749c4e5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/RemoveJob.cs @@ -61,12 +61,17 @@ internal List FindJobsMatchingByName( List matches = new List(); Hashtable duplicateDetector = new Hashtable(); - if (_names == null) return matches; + if (_names == null) + { + return matches; + } foreach (string name in _names) { if (string.IsNullOrEmpty(name)) + { continue; + } // search all jobs in repository. bool jobFound = false; @@ -94,7 +99,10 @@ internal List FindJobsMatchingByName( jobFound = jobFound || job2Found; // if a match is not found, write an error) - if (jobFound || !writeErrorOnNoMatch || WildcardPattern.ContainsWildcardCharacters(name)) continue; + if (jobFound || !writeErrorOnNoMatch || WildcardPattern.ContainsWildcardCharacters(name)) + { + continue; + } Exception ex = PSTraceSource.NewArgumentException(NameParameter, RemotingErrorIdStrings.JobWithSpecifiedNameNotFound, name); WriteError(new ErrorRecord(ex, "JobWithSpecifiedNameNotFound", ErrorCategory.ObjectNotFound, name)); @@ -191,7 +199,10 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, Hashtable duplicateDetector = new Hashtable(); - if (_instanceIds == null) return matches; + if (_instanceIds == null) + { + return matches; + } foreach (Guid id in _instanceIds) { @@ -217,7 +228,10 @@ internal List FindJobsMatchingByInstanceId(bool recurse, bool writeobject, jobFound = jobFound || job2Found; - if (jobFound || !writeErrorOnNoMatch) continue; + if (jobFound || !writeErrorOnNoMatch) + { + continue; + } Exception ex = PSTraceSource.NewArgumentException(InstanceIdParameter, RemotingErrorIdStrings.JobWithSpecifiedInstanceIdNotFound, @@ -306,7 +320,10 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b { List matches = new List(); - if (_sessionIds == null) return matches; + if (_sessionIds == null) + { + return matches; + } Hashtable duplicateDetector = new Hashtable(); @@ -331,7 +348,10 @@ internal List FindJobsMatchingBySessionId(bool recurse, bool writeobject, b jobFound = jobFound || job2Found; - if (jobFound || !writeErrorOnNoMatch) continue; + if (jobFound || !writeErrorOnNoMatch) + { + continue; + } Exception ex = PSTraceSource.NewArgumentException(SessionIdParameter, RemotingErrorIdStrings.JobWithSpecifiedSessionIdNotFound, id); WriteError(new ErrorRecord(ex, "JobWithSpecifiedSessionNotFound", ErrorCategory.ObjectNotFound, id)); @@ -408,7 +428,10 @@ internal List FindJobsMatchingByCommand( { List matches = new List(); - if (_commands == null) return matches; + if (_commands == null) + { + return matches; + } List jobs = new List(); @@ -476,7 +499,10 @@ internal List FindJobsMatchingByState( foreach (Job job in jobs) { - if (job.JobStateInfo.State != _jobstate) continue; + if (job.JobStateInfo.State != _jobstate) + { + continue; + } if (writeobject) { @@ -558,7 +584,10 @@ private static bool FindJobsMatchingByFilterHelper(List matches, List internal List CopyJobsToList(Job[] jobs, bool writeobject, bool checkIfJobCanBeRemoved) { List matches = new List(); - if (jobs == null) return matches; + if (jobs == null) + { + return matches; + } foreach (Job job in jobs) { @@ -890,10 +919,12 @@ protected override void ProcessRecord() // Now actually remove the jobs foreach (Job job in listOfJobsToRemove) { - string message = GetMessage(RemotingErrorIdStrings.StopPSJobWhatIfTarget, - job.Command, job.Id); + string message = GetMessage(RemotingErrorIdStrings.StopPSJobWhatIfTarget, job.Command, job.Id); - if (!ShouldProcess(message, VerbsCommon.Remove)) continue; + if (!ShouldProcess(message, VerbsCommon.Remove)) + { + continue; + } Job2 job2 = job as Job2; if (!job.IsFinishedState(job.JobStateInfo.State)) @@ -1037,7 +1068,11 @@ public void Dispose() /// protected void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + { + return; + } + foreach (var pair in _cleanUpActions) { pair.Key.StopJobCompleted -= pair.Value; diff --git a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs b/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs deleted file mode 100644 index 1b5fcd7bbe4..00000000000 --- a/src/System.Management.Automation/engine/remoting/commands/ResumeJob.cs +++ /dev/null @@ -1,280 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Management.Automation; -using System.Management.Automation.Remoting; -using System.Threading; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// This cmdlet resumes the jobs that are Job2. Errors are added for each Job that is not Job2. - /// -#if !CORECLR - [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] - [Cmdlet(VerbsLifecycle.Resume, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210611")] -#endif - [OutputType(typeof(Job))] - public class ResumeJobCommand : JobCmdletBase, IDisposable - { - #region Parameters - /// - /// Specifies the Jobs objects which need to be - /// suspended. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = JobParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Job[] Job - { - get - { - return _jobs; - } - - set - { - _jobs = value; - } - } - - private Job[] _jobs; - - /// - /// - public override string[] Command - { - get - { - return null; - } - } - - /// - /// Specifies whether to delay returning from the cmdlet until all jobs reach a running state. - /// This could take significant time due to workflow throttling. - /// - [Parameter(ParameterSetName = ParameterAttribute.AllParameterSets)] - public SwitchParameter Wait { get; set; } - - #endregion Parameters - - #region Overrides - - /// - /// Resume the Job. - /// - protected override void ProcessRecord() - { - // List of jobs to resume - List jobsToResume = null; - - switch (ParameterSetName) - { - case NameParameterSet: - { - jobsToResume = FindJobsMatchingByName(true, false, true, false); - } - - break; - - case InstanceIdParameterSet: - { - jobsToResume = FindJobsMatchingByInstanceId(true, false, true, false); - } - - break; - - case SessionIdParameterSet: - { - jobsToResume = FindJobsMatchingBySessionId(true, false, true, false); - } - - break; - - case StateParameterSet: - { - jobsToResume = FindJobsMatchingByState(false); - } - - break; - - case FilterParameterSet: - { - jobsToResume = FindJobsMatchingByFilter(false); - } - - break; - - default: - { - jobsToResume = CopyJobsToList(_jobs, false, false); - } - - break; - } - - _allJobsToResume.AddRange(jobsToResume); - - // Blue: 151804 When resuming a single suspended workflow job, Resume-job cmdlet doesn't wait for the job to be in running state - // Setting Wait to true so that this cmdlet will wait for the running job state. - if (_allJobsToResume.Count == 1) - Wait = true; - - foreach (Job job in jobsToResume) - { - var job2 = job as Job2; - - // If the job is not Job2, the resume operation is not supported. - if (job2 == null) - { - WriteError(new ErrorRecord(PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobResumeNotSupported, job.Id), "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); - continue; - } - - string targetString = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, job.Command, job.Id); - if (ShouldProcess(targetString, VerbsLifecycle.Resume)) - { - _cleanUpActions.Add(job2, HandleResumeJobCompleted); - job2.ResumeJobCompleted += HandleResumeJobCompleted; - - lock (_syncObject) - { - if (!_pendingJobs.Contains(job2.InstanceId)) - { - _pendingJobs.Add(job2.InstanceId); - } - } - - job2.ResumeJobAsync(); - } - } - } - - private bool _warnInvalidState = false; - private readonly HashSet _pendingJobs = new HashSet(); - private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); - private readonly Dictionary> _cleanUpActions = - new Dictionary>(); - private readonly List _errorsToWrite = new List(); - private readonly List _allJobsToResume = new List(); - private readonly object _syncObject = new object(); - private bool _needToCheckForWaitingJobs; - - private void HandleResumeJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) - { - Job job = sender as Job; - - if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) - { - _warnInvalidState = true; - } - - var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) - { - foreach ( - var e in - parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobResumeAsyncError") - ) - { - if (e.Exception is InvalidJobStateException) - { - // if any errors were invalid job state exceptions, warn the user. - // This is to support Get-Job | Resume-Job scenarios when many jobs - // are Completed, etc. - _warnInvalidState = true; - } - else - { - _errorsToWrite.Add(e); - } - } - - parentJob.ExecutionError.Clear(); - } - - bool releaseWait = false; - lock (_syncObject) - { - if (_pendingJobs.Contains(job.InstanceId)) - { - _pendingJobs.Remove(job.InstanceId); - } - - if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) - releaseWait = true; - } - // end processing has been called - // set waithandle if this is the last one - if (releaseWait) - _waitForJobs.Set(); - } - - /// - /// End Processing. - /// - protected override void EndProcessing() - { - bool jobsPending = false; - lock (_syncObject) - { - _needToCheckForWaitingJobs = true; - if (_pendingJobs.Count > 0) - jobsPending = true; - } - - if (Wait && jobsPending) - _waitForJobs.WaitOne(); - - if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.ResumeJobInvalidJobState); - foreach (var e in _errorsToWrite) WriteError(e); - foreach (var j in _allJobsToResume) WriteObject(j); - base.EndProcessing(); - } - - /// - /// - protected override void StopProcessing() - { - _waitForJobs.Set(); - } - - #endregion Overrides - - #region Dispose - - /// - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// - /// - protected void Dispose(bool disposing) - { - if (!disposing) return; - foreach (var pair in _cleanUpActions) - { - pair.Key.ResumeJobCompleted -= pair.Value; - } - - _waitForJobs.Dispose(); - } - #endregion Dispose - } -} diff --git a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs index 90e10bb8f44..9913ec64ced 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StartJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StartJob.cs @@ -222,7 +222,7 @@ public override string Subsystem [Parameter(ParameterSetName = StartJobCommand.FilePathComputerNameParameterSet)] [Parameter(ParameterSetName = StartJobCommand.ComputerNameParameterSet)] [Parameter(ParameterSetName = StartJobCommand.LiteralFilePathComputerNameParameterSet)] - [Credential()] + [Credential] public override PSCredential Credential { get @@ -277,7 +277,7 @@ public override string ConfigurationName /// /// Overriding to suppress this parameter. /// - public override Int32 ThrottleLimit + public override int ThrottleLimit { get { @@ -484,7 +484,7 @@ public virtual ScriptBlock InitializationScript /// Gets or sets an initial working directory for the powershell background job. /// [Parameter] - [ValidateNotNullOrEmpty] + [ValidateNotNullOrWhiteSpace] public string WorkingDirectory { get; set; } /// @@ -512,10 +512,12 @@ public virtual Version PSVersion set { - RemotingCommandUtil.CheckPSVersion(value); - - // Check if specified version of PowerShell is installed - RemotingCommandUtil.CheckIfPowerShellVersionIsInstalled(value); + // PSVersion value can only be 5.1 for Start-Job. + if (!(value.Major == 5 && value.Minor == 1)) + { + throw new ArgumentException( + StringUtil.Format(RemotingErrorIdStrings.PSVersionParameterOutOfRange, value, "PSVersion")); + } _psVersion = value; } @@ -599,7 +601,7 @@ protected override void BeginProcessing() ThrowTerminatingError(errorRecord); } - if (WorkingDirectory != null && !Directory.Exists(WorkingDirectory)) + if (WorkingDirectory != null && !InvokeProvider.Item.IsContainer(WorkingDirectory)) { string message = StringUtil.Format(RemotingErrorIdStrings.StartJobWorkingDirectoryNotFound, WorkingDirectory); var errorRecord = new ErrorRecord( @@ -644,7 +646,7 @@ protected override void CreateHelpersForSpecifiedComputerNames() { // If we're in ConstrainedLanguage mode and the system is in lockdown mode, // ensure that they haven't specified a ScriptBlock or InitScript - as - // we can't protect that boundary + // we can't protect that boundary. if ((Context.LanguageMode == PSLanguageMode.ConstrainedLanguage) && (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Enforce) && ((ScriptBlock != null) || (InitializationScript != null))) diff --git a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs index 7890bdc54f0..c298b495bb9 100644 --- a/src/System.Management.Automation/engine/remoting/commands/StopJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/StopJob.cs @@ -137,7 +137,11 @@ protected override void ProcessRecord() foreach (Job job in jobsToStop) { - if (this.Stopping) return; + if (this.Stopping) + { + return; + } + if (job.IsFinishedState(job.JobStateInfo.State)) { continue; @@ -280,7 +284,11 @@ public void Dispose() /// protected void Dispose(bool disposing) { - if (!disposing) return; + if (!disposing) + { + return; + } + foreach (var pair in _cleanUpActions) { pair.Key.StopJobCompleted -= pair.Value; diff --git a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs b/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs deleted file mode 100644 index 1c729d8df74..00000000000 --- a/src/System.Management.Automation/engine/remoting/commands/SuspendJob.cs +++ /dev/null @@ -1,374 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics.CodeAnalysis; -using System.Linq; -using System.Management.Automation; -using System.Management.Automation.Remoting; -using System.Threading; - -namespace Microsoft.PowerShell.Commands -{ - /// - /// This cmdlet suspends the jobs that are Job2. Errors are added for each Job that is not Job2. - /// -#if !CORECLR - [SuppressMessage("Microsoft.PowerShell", "PS1012:CallShouldProcessOnlyIfDeclaringSupport")] - [Cmdlet(VerbsLifecycle.Suspend, "Job", SupportsShouldProcess = true, DefaultParameterSetName = JobCmdletBase.SessionIdParameterSet, - HelpUri = "https://go.microsoft.com/fwlink/?LinkID=210613")] - [OutputType(typeof(Job))] -#endif - public class SuspendJobCommand : JobCmdletBase, IDisposable - { - #region Parameters - /// - /// Specifies the Jobs objects which need to be - /// suspended. - /// - [Parameter(Mandatory = true, - Position = 0, - ValueFromPipeline = true, - ValueFromPipelineByPropertyName = true, - ParameterSetName = JobParameterSet)] - [ValidateNotNullOrEmpty] - [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] - public Job[] Job - { - get - { - return _jobs; - } - - set - { - _jobs = value; - } - } - - private Job[] _jobs; - - /// - /// - public override string[] Command - { - get - { - return null; - } - } - - /// - /// If state of the job is running , this will forcefully suspend it. - /// - [Parameter(ParameterSetName = RemoveJobCommand.InstanceIdParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.JobParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.NameParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.SessionIdParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.FilterParameterSet)] - [Parameter(ParameterSetName = RemoveJobCommand.StateParameterSet)] - [Alias("F")] - public SwitchParameter Force - { - get - { - return _force; - } - - set - { - _force = value; - } - } - - private bool _force = false; - - /// - /// - [Parameter()] - public SwitchParameter Wait - { - get - { - return _wait; - } - - set - { - _wait = value; - } - } - - private bool _wait = false; - - #endregion Parameters - - #region Overrides - - /// - /// Suspend the Job. - /// - protected override void ProcessRecord() - { - // List of jobs to suspend - List jobsToSuspend = null; - - switch (ParameterSetName) - { - case NameParameterSet: - { - jobsToSuspend = FindJobsMatchingByName(true, false, true, false); - } - - break; - - case InstanceIdParameterSet: - { - jobsToSuspend = FindJobsMatchingByInstanceId(true, false, true, false); - } - - break; - - case SessionIdParameterSet: - { - jobsToSuspend = FindJobsMatchingBySessionId(true, false, true, false); - } - - break; - - case StateParameterSet: - { - jobsToSuspend = FindJobsMatchingByState(false); - } - - break; - - case FilterParameterSet: - { - jobsToSuspend = FindJobsMatchingByFilter(false); - } - - break; - - default: - { - jobsToSuspend = CopyJobsToList(_jobs, false, false); - } - - break; - } - - _allJobsToSuspend.AddRange(jobsToSuspend); - - foreach (Job job in jobsToSuspend) - { - var job2 = job as Job2; - - // If the job is not Job2, the suspend operation is not supported. - if (job2 == null) - { - WriteError( - new ErrorRecord( - PSTraceSource.NewNotSupportedException(RemotingErrorIdStrings.JobSuspendNotSupported, job.Id), - "Job2OperationNotSupportedOnJob", ErrorCategory.InvalidType, (object)job)); - continue; - } - - string targetString = - PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemovePSJobWhatIfTarget, - job.Command, job.Id); - if (ShouldProcess(targetString, VerbsLifecycle.Suspend)) - { - if (_wait) - { - _cleanUpActions.Add(job2, HandleSuspendJobCompleted); - } - else - { - if (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Stopping) - { - _warnInvalidState = true; - continue; - } - - if (job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended) - continue; - - job2.StateChanged += noWait_Job2_StateChanged; - } - - job2.SuspendJobCompleted += HandleSuspendJobCompleted; - - lock (_syncObject) - { - if (!_pendingJobs.Contains(job2.InstanceId)) - { - _pendingJobs.Add(job2.InstanceId); - } - } - - // there could be possibility that the job gets completed before or after the - // subscribing to nowait_job2_statechanged event so checking it again. - if (!_wait && (job2.IsFinishedState(job2.JobStateInfo.State) || job2.JobStateInfo.State == JobState.Suspending || job2.JobStateInfo.State == JobState.Suspended)) - { - this.ProcessExecutionErrorsAndReleaseWaitHandle(job2); - } - - job2.SuspendJobAsync(_force, RemotingErrorIdStrings.ForceSuspendJob); - } - } - } - - private bool _warnInvalidState = false; - private readonly HashSet _pendingJobs = new HashSet(); - private readonly ManualResetEvent _waitForJobs = new ManualResetEvent(false); - private readonly Dictionary> _cleanUpActions = - new Dictionary>(); - private readonly List _errorsToWrite = new List(); - private readonly List _allJobsToSuspend = new List(); - private readonly object _syncObject = new object(); - private bool _needToCheckForWaitingJobs; - - private void noWait_Job2_StateChanged(object sender, JobStateEventArgs e) - { - Job job = sender as Job; - - switch (e.JobStateInfo.State) - { - case JobState.Completed: - case JobState.Stopped: - case JobState.Failed: - case JobState.Suspended: - case JobState.Suspending: - this.ProcessExecutionErrorsAndReleaseWaitHandle(job); - break; - } - } - - private void HandleSuspendJobCompleted(object sender, AsyncCompletedEventArgs eventArgs) - { - Job job = sender as Job; - - if (eventArgs.Error != null && eventArgs.Error is InvalidJobStateException) - { - _warnInvalidState = true; - } - - this.ProcessExecutionErrorsAndReleaseWaitHandle(job); - } - - private void ProcessExecutionErrorsAndReleaseWaitHandle(Job job) - { - bool releaseWait = false; - lock (_syncObject) - { - if (_pendingJobs.Contains(job.InstanceId)) - { - _pendingJobs.Remove(job.InstanceId); - } - else - { - // there could be a possibility of race condition where this function is getting called twice - // so if job doesn't present in the _pendingJobs then just return - return; - } - - if (_needToCheckForWaitingJobs && _pendingJobs.Count == 0) - releaseWait = true; - } - - if (!_wait) - { - job.StateChanged -= noWait_Job2_StateChanged; - Job2 job2 = job as Job2; - if (job2 != null) - job2.SuspendJobCompleted -= HandleSuspendJobCompleted; - } - - var parentJob = job as ContainerParentJob; - if (parentJob != null && parentJob.ExecutionError.Count > 0) - { - foreach ( - var e in - parentJob.ExecutionError.Where(e => e.FullyQualifiedErrorId == "ContainerParentJobSuspendAsyncError") - ) - { - if (e.Exception is InvalidJobStateException) - { - // if any errors were invalid job state exceptions, warn the user. - // This is to support Get-Job | Resume-Job scenarios when many jobs - // are Completed, etc. - _warnInvalidState = true; - } - else - { - _errorsToWrite.Add(e); - } - } - } - - // end processing has been called - // set waithandle if this is the last one - if (releaseWait) - _waitForJobs.Set(); - } - - /// - /// End Processing. - /// - protected override void EndProcessing() - { - bool haveToWait = false; - lock (_syncObject) - { - _needToCheckForWaitingJobs = true; - if (_pendingJobs.Count > 0) - haveToWait = true; - } - - if (haveToWait) - _waitForJobs.WaitOne(); - - if (_warnInvalidState) WriteWarning(RemotingErrorIdStrings.SuspendJobInvalidJobState); - foreach (var e in _errorsToWrite) WriteError(e); - foreach (var j in _allJobsToSuspend) WriteObject(j); - base.EndProcessing(); - } - - /// - /// - protected override void StopProcessing() - { - _waitForJobs.Set(); - } - - #endregion Overrides - - #region Dispose - - /// - /// - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - - /// - /// - /// - protected void Dispose(bool disposing) - { - if (!disposing) return; - foreach (var pair in _cleanUpActions) - { - pair.Key.SuspendJobCompleted -= pair.Value; - } - - _waitForJobs.Dispose(); - } - #endregion Dispose - } -} diff --git a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs index 796e97513bd..6964a1154b5 100644 --- a/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs +++ b/src/System.Management.Automation/engine/remoting/commands/WaitJob.cs @@ -46,7 +46,7 @@ public class WaitJobCommand : JobCmdletBase, IDisposable /// [Parameter] [Alias("TimeoutSec")] - [ValidateRangeAttribute(-1, Int32.MaxValue)] + [ValidateRange(-1, int.MaxValue)] public int Timeout { get @@ -244,7 +244,7 @@ private Job GetOneBlockedJob() { lock (_jobTrackingLock) { - return _jobsToWaitFor.Find(j => j.JobStateInfo.State == JobState.Blocked); + return _jobsToWaitFor.Find(static j => j.JobStateInfo.State == JobState.Blocked); } } diff --git a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs index d1fc8ef531a..22af9adf9ff 100644 --- a/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/getrunspacecommand.cs @@ -8,6 +8,7 @@ using System.Management.Automation.Internal; using System.Management.Automation.Remoting; using System.Management.Automation.Runspaces; +using System.Runtime.InteropServices; using Dbg = System.Management.Automation.Diagnostics; @@ -69,7 +70,7 @@ public class GetPSSessionCommand : PSRunspaceCmdlet, IDisposable /// /// This parameters specifies the appname which identifies the connection /// end point on the remote machine. If this parameter is not specified - /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If thats + /// then the value specified in DEFAULTREMOTEAPPNAME will be used. If that's /// not specified as well, then "WSMAN" will be used. /// [Parameter(ValueFromPipelineByPropertyName = true, @@ -161,7 +162,7 @@ public SwitchParameter AllowRedirection [Parameter(ParameterSetName = GetPSSessionCommand.ContainerIdParameterSet)] [Parameter(ParameterSetName = GetPSSessionCommand.VMIdParameterSet)] [Parameter(ParameterSetName = GetPSSessionCommand.VMNameParameterSet)] - [ValidateNotNullOrEmpty()] + [ValidateNotNullOrEmpty] public override string[] Name { get { return base.Name; } @@ -202,7 +203,7 @@ public override Guid[] InstanceId [Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)] [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriParameterSet)] [Parameter(ParameterSetName = GetPSSessionCommand.ConnectionUriInstanceIdParameterSet)] - [Credential()] + [Credential] public PSCredential Credential { get @@ -282,7 +283,7 @@ public string CertificateThumbprint /// [Parameter(ParameterSetName = GetPSSessionCommand.ComputerNameParameterSet)] [Parameter(ParameterSetName = GetPSSessionCommand.ComputerInstanceIdParameterSet)] - [ValidateRange((int)1, (int)UInt16.MaxValue)] + [ValidateRange((int)1, (int)ushort.MaxValue)] public int Port { get; set; } /// @@ -341,12 +342,23 @@ public string CertificateThumbprint /// protected override void BeginProcessing() { - base.BeginProcessing(); - - if (ConfigurationName == null) +#if UNIX + if (ComputerName?.Length > 0) { - ConfigurationName = string.Empty; + ErrorRecord err = new( + new NotImplementedException( + PSRemotingErrorInvariants.FormatResourceString( + RemotingErrorIdStrings.UnsupportedOSForRemoteEnumeration, + RuntimeInformation.OSDescription)), + "PSSessionComputerNameUnix", + ErrorCategory.NotImplemented, + null); + ThrowTerminatingError(err); } +#endif + + base.BeginProcessing(); + ConfigurationName ??= string.Empty; } /// diff --git a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs index 625bb86fd64..60ca0c35e50 100644 --- a/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs +++ b/src/System.Management.Automation/engine/remoting/commands/newrunspacecommand.cs @@ -88,7 +88,7 @@ public class NewPSSessionCommand : PSRemotingBaseCmdlet, IDisposable [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = PSRemotingBaseCmdlet.VMNameParameterSet)] - [Credential()] + [Credential] public override PSCredential Credential { get @@ -129,7 +129,7 @@ public override PSSession[] Session /// /// Friendly names for the new PSSessions. /// - [Parameter()] + [Parameter] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public string[] Name { get; set; } @@ -267,7 +267,16 @@ protected override void ProcessRecord() case NewPSSessionCommand.UseWindowsPowerShellParameterSet: { - remoteRunspaces = CreateRunspacesForUseWindowsPowerShellParameterSet(); + if (UseWindowsPowerShell) + { + remoteRunspaces = CreateRunspacesForUseWindowsPowerShellParameterSet(); + } + else + { + // When -UseWindowsPowerShell:$false is explicitly specified, + // fall back to the default ComputerName parameter set behavior + goto case NewPSSessionCommand.ComputerNameParameterSet; + } } break; @@ -385,11 +394,7 @@ public void Dispose() /// /// Adds forwarded events to the local queue. /// - private void OnRunspacePSEventReceived(object sender, PSEventArgs e) - { - if (this.Events != null) - this.Events.AddForwardedEvent(e); - } + private void OnRunspacePSEventReceived(object sender, PSEventArgs e) => this.Events?.AddForwardedEvent(e); /// /// When the client remote session reports a URI redirection, this method will report the @@ -524,10 +529,7 @@ private void HandleRunspaceStateChanged(object sender, OperationStateEventArgs s } } - if (reason == null) - { - reason = new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); - } + reason ??= new RuntimeException(this.GetMessage(RemotingErrorIdStrings.RemoteRunspaceOpenUnknownState, state)); string fullyQualifiedErrorId = WSManTransportManagerUtils.GetFQEIDFromTransportError( transErrorCode, @@ -647,11 +649,11 @@ private List CreateRunspacesWhenRunspaceParameterSpecified() if (remoteRunspace.ConnectionInfo is VMConnectionInfo) { - newConnectionInfo = remoteRunspace.ConnectionInfo.InternalCopy(); + newConnectionInfo = remoteRunspace.ConnectionInfo.Clone(); } else if (remoteRunspace.ConnectionInfo is ContainerConnectionInfo) { - ContainerConnectionInfo newContainerConnectionInfo = remoteRunspace.ConnectionInfo.InternalCopy() as ContainerConnectionInfo; + ContainerConnectionInfo newContainerConnectionInfo = remoteRunspace.ConnectionInfo.Clone() as ContainerConnectionInfo; newContainerConnectionInfo.CreateContainerProcess(); newConnectionInfo = newContainerConnectionInfo; } @@ -939,7 +941,7 @@ private List CreateRunspacesWhenVMParameterSpecified() // // VM should be in running state. // - if ((VMState)results[0].Properties["State"].Value != VMState.Running) + if (GetVMStateProperty(results[0]) != VMState.Running) { WriteError( new ErrorRecord( @@ -1092,7 +1094,9 @@ private List CreateRunspacesForSSHHostParameterSet() host, this.KeyFilePath, port, - Subsystem); + Subsystem, + ConnectingTimeout, + Options); var typeTable = TypeTable.LoadDefaultTypeFiles(); string rsName = GetRunspaceName(index, out int rsIdUnused); index++; @@ -1118,7 +1122,9 @@ private List CreateRunspacesForSSHHostHashParameterSet() sshConnection.ComputerName, sshConnection.KeyFilePath, sshConnection.Port, - sshConnection.Subsystem); + sshConnection.Subsystem, + sshConnection.ConnectingTimeout, + sshConnection.Options); var typeTable = TypeTable.LoadDefaultTypeFiles(); string rsName = GetRunspaceName(index, out int rsIdUnused); index++; @@ -1388,7 +1394,7 @@ internal override event EventHandler OperationComplete /// /// There are two problems that need to be handled. /// 1) We need to make sure that the ThrottleManager StartComplete and StopComplete - /// operation events are called or the ThrottleManager will never end (will stop reponding). + /// operation events are called or the ThrottleManager will never end (will stop responding). /// 2) The HandleRunspaceStateChanged event handler remains in the Runspace /// StateChanged event call chain until this object is disposed. We have to /// disallow the HandleRunspaceStateChanged event from running and throwing diff --git a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs index 094dcedc6ad..3e2603a36fe 100644 --- a/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs +++ b/src/System.Management.Automation/engine/remoting/commands/remotingcommandutil.cs @@ -93,7 +93,7 @@ internal static void CheckRemotingCmdletPrerequisites() try { - // the following registry key defines WSMan compatability + // the following registry key defines WSMan compatibility // HKLM\Software\Microsoft\Windows\CurrentVersion\WSMAN\ServiceStackVersion string wsManStackValue = null; RegistryKey wsManKey = Registry.LocalMachine.OpenSubKey(WSManKeyPath); @@ -165,60 +165,5 @@ internal static void CheckHostRemotingPrerequisites() throw new InvalidOperationException(errorRecord.ToString()); } } - - internal static void CheckPSVersion(Version version) - { - // PSVersion value can only be 2.0, 3.0, 4.0, 5.0, or 5.1 - if (version != null) - { - // PSVersion value can only be 2.0, 3.0, 4.0, 5.0, or 5.1 - if (!(version.Major >= 2 && version.Major <= 4 && version.Minor == 0) && - !(version.Major == 5 && version.Minor <= 1)) - { - throw new ArgumentException( - StringUtil.Format(RemotingErrorIdStrings.PSVersionParameterOutOfRange, version, "PSVersion")); - } - } - } - - /// - /// Checks if the specified version of PowerShell is installed. - /// - /// - internal static void CheckIfPowerShellVersionIsInstalled(Version version) - { - // Check if PowerShell 2.0 is installed - if (version != null && version.Major == 2) - { -#if CORECLR - // PowerShell 2.0 is not available for CoreCLR - throw new ArgumentException( - PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.PowerShellNotInstalled, - version, "PSVersion")); -#else - // Because of app-compat issues, in Win8, we will have PS 2.0 installed by default but not .NET 2.0 - // In such a case, it is not enough if we check just PowerShell registry keys. We also need to check if .NET 2.0 is installed. - try - { - RegistryKey engineKey = PSSnapInReader.GetPSEngineKey(PSVersionInfo.RegistryVersion1Key); - // Also check for .NET 2.0 installation - if (!PsUtils.FrameworkRegistryInstallation.IsFrameworkInstalled(2, 0, 0)) - { - throw new ArgumentException( - PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.NetFrameWorkV2NotInstalled)); - } - } - catch (PSArgumentException) - { - throw new ArgumentException( - PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.PowerShellNotInstalled, - version, "PSVersion")); - } -#endif - } - } } } diff --git a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs index 5eb9c5fc338..989ad33e987 100644 --- a/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs +++ b/src/System.Management.Automation/engine/remoting/common/PSETWTracer.cs @@ -158,11 +158,17 @@ internal enum PSEventId : int Provider_Lifecycle = 0x1F03, Settings = 0x1F04, Engine_Trace = 0x1F06, + Amsi_Init = 0x4001, + WDAC_Query = 0x4002, + WDAC_Audit = 0x4003, // Experimental Features ExperimentalFeature_InvalidName = 0x3001, ExperimentalFeature_ReadConfig_Error = 0x3002, + // Windows Diagnostics And Usage Data Settings + Telemetry_Setting_Error = 0x3011, + // Scheduled Jobs ScheduledJob_Start = 0xD001, ScheduledJob_Complete = 0xD002, @@ -237,9 +243,13 @@ internal enum PSTask : int ProviderStop = 0x69, ExecutePipeline = 0x6A, ExperimentalFeature = 0x6B, + Telemetry = 0x6C, ScheduledJob = 0x6E, NamedPipe = 0x6F, - ISEOperation = 0x78 + ISEOperation = 0x78, + Amsi = 0X82, + WDAC = 0x83, + WDACAudit = 0x84 } /// diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs index 42d04a9e23e..8d53adf0ca8 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionHyperVSocket.cs @@ -7,12 +7,14 @@ using System.Net.Sockets; using System.Text; using System.Threading; +using System.Buffers; using Dbg = System.Diagnostics.Debug; +using SMA = System.Management.Automation; namespace System.Management.Automation.Remoting { - [SerializableAttribute] + [Serializable] internal class HyperVSocketEndPoint : EndPoint { #region Members @@ -53,7 +55,7 @@ public Guid ServiceId { get { return _serviceId; } - set { _vmId = value; } + set { _serviceId = value; } } #endregion @@ -140,6 +142,10 @@ internal sealed class RemoteSessionHyperVSocketServer : IDisposable private readonly object _syncObject; private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); + // This is to prevent persistent replay attacks. + // it is not meant to ensure all replay attacks are impossible. + private const int MAX_TOKEN_LIFE_MINUTES = 10; + #endregion #region Properties @@ -175,64 +181,74 @@ internal sealed class RemoteSessionHyperVSocketServer : IDisposable public RemoteSessionHyperVSocketServer(bool LoopbackMode) { - // TODO: uncomment below code when .NET supports Hyper-V socket duplication - /* - NamedPipeClientStream clientPipeStream; - byte[] buffer = new byte[1000]; - int bytesRead; - */ _syncObject = new object(); Exception ex = null; try { - // TODO: uncomment below code when .NET supports Hyper-V socket duplication - /* - if (!LoopbackMode) - { - // - // Create named pipe client. - // - using (clientPipeStream = new NamedPipeClientStream(".", - "PS_VMSession", - PipeDirection.InOut, - PipeOptions.None, - TokenImpersonationLevel.None)) - { - // - // Connect to named pipe server. - // - clientPipeStream.Connect(10*1000); - - // - // Read LPWSAPROTOCOL_INFO. - // - bytesRead = clientPipeStream.Read(buffer, 0, 1000); - } - } + Guid serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220"); // HV_GUID_VM_SESSION_SERVICE_ID_2 + Guid loopbackId = new Guid("e0e16197-dd56-4a10-9195-5ee7a155a838"); // HV_GUID_LOOPBACK + Guid parentId = new Guid("a42e7cda-d03f-480c-9cc2-a4de20abb878"); // HV_GUID_PARENT + Guid vmId = LoopbackMode ? loopbackId : parentId; + HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, vmId, serviceId); + + Socket listenSocket = new Socket(endpoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType)1); + listenSocket.Bind(endpoint); + + listenSocket.Listen(1); + HyperVSocket = listenSocket.Accept(); + + Stream = new NetworkStream(HyperVSocket, true); + + // Create reader/writer streams. + TextReader = new StreamReader(Stream); + TextWriter = new StreamWriter(Stream); + TextWriter.AutoFlush = true; // - // Create duplicate socket. + // listenSocket is not closed when it goes out of scope here. Sometimes it is + // closed later in this thread, while other times it is not closed at all. This will + // cause problem when we set up a second PowerShell Direct session. Let's + // explicitly close listenSocket here for safe. // - byte[] protocolInfo = new byte[bytesRead]; - Array.Copy(buffer, protocolInfo, bytesRead); + if (listenSocket != null) + { + try { listenSocket.Dispose(); } + catch (ObjectDisposedException) { } + } + } + catch (Exception e) + { + ex = e; + } - SocketInformation sockInfo = new SocketInformation(); - sockInfo.ProtocolInformation = protocolInfo; - sockInfo.Options = SocketInformationOptions.Connected; + if (ex != null) + { + Dbg.Fail("Unexpected error in RemoteSessionHyperVSocketServer."); - socket = new Socket(sockInfo); - if (socket == null) - { - Dbg.Assert(false, "Unexpected error in RemoteSessionHyperVSocketServer."); + // Unexpected error. + string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty; + _tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty, + "Unexpected error in constructor: {0}", errorMessage); - tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty, - "Unexpected error in constructor: {0}", "socket duplication failure"); - } - */ + throw new PSInvalidOperationException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketServerConstructorFailure), + ex, + nameof(PSRemotingErrorId.RemoteSessionHyperVSocketServerConstructorFailure), + ErrorCategory.InvalidOperation, + null); + } + } + + public RemoteSessionHyperVSocketServer(bool LoopbackMode, string token, DateTimeOffset tokenCreationTime) + { + _syncObject = new object(); + + Exception ex = null; - // TODO: remove below 6 lines of code when .NET supports Hyper-V socket duplication + try + { Guid serviceId = new Guid("a5201c21-2770-4c11-a68e-f182edb29220"); // HV_GUID_VM_SESSION_SERVICE_ID_2 HyperVSocketEndPoint endpoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, Guid.Empty, serviceId); @@ -242,6 +258,8 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) listenSocket.Listen(1); HyperVSocket = listenSocket.Accept(); + ValidateToken(HyperVSocket, token, tokenCreationTime, MAX_TOKEN_LIFE_MINUTES * 60); + Stream = new NetworkStream(HyperVSocket, true); // Create reader/writer streams. @@ -257,8 +275,13 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) // if (listenSocket != null) { - try { listenSocket.Dispose(); } - catch (ObjectDisposedException) { } + try + { + listenSocket.Dispose(); + } + catch (ObjectDisposedException) + { + } } } catch (Exception e) @@ -272,8 +295,12 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) // Unexpected error. string errorMessage = !string.IsNullOrEmpty(ex.Message) ? ex.Message : string.Empty; - _tracer.WriteMessage("RemoteSessionHyperVSocketServer", "RemoteSessionHyperVSocketServer", Guid.Empty, - "Unexpected error in constructor: {0}", errorMessage); + _tracer.WriteMessage( + "RemoteSessionHyperVSocketServer", + "RemoteSessionHyperVSocketServer", + Guid.Empty, + "Unexpected error in constructor: {0}", + errorMessage); throw new PSInvalidOperationException( PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketServerConstructorFailure), @@ -283,7 +310,6 @@ public RemoteSessionHyperVSocketServer(bool LoopbackMode) null); } } - #endregion #region IDisposable @@ -295,7 +321,10 @@ public void Dispose() { lock (_syncObject) { - if (IsDisposed) { return; } + if (IsDisposed) + { + return; + } IsDisposed = true; } @@ -330,6 +359,107 @@ public void Dispose() } #endregion + + /// + /// Validates the token received from the client over the HyperVSocket. + /// Throws PSDirectException if the token is invalid or not received in time. + /// + /// The connected HyperVSocket. + /// The expected token string. + /// The creation time of the token. + /// The maximum lifetime of the token in seconds. + internal static void ValidateToken(Socket socket, string token, DateTimeOffset tokenCreationTime, int maxTokenLifeSeconds) + { + TimeSpan timeout = TimeSpan.FromSeconds(maxTokenLifeSeconds); + DateTimeOffset timeoutExpiry = tokenCreationTime.Add(timeout); + DateTimeOffset now = DateTimeOffset.UtcNow; + + // Calculate remaining time and create cancellation token + TimeSpan remainingTime = timeoutExpiry - now; + + // Check if the token has already expired + if (remainingTime <= TimeSpan.Zero) + { + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential, "Token has expired")); + } + + // Create a cancellation token that will be cancelled when the timeout expires + using var cancellationTokenSource = new CancellationTokenSource(remainingTime); + CancellationToken cancellationToken = cancellationTokenSource.Token; + + // Set socket timeout for receive operations to prevent indefinite blocking + int timeoutMs = (int)remainingTime.TotalMilliseconds; + socket.ReceiveTimeout = timeoutMs; + socket.SendTimeout = timeoutMs; + + // Check for cancellation before starting validation + cancellationToken.ThrowIfCancellationRequested(); + + // We should move to this pattern and + // in the tests I found I needed to get a bigger buffer than the token length + // and test length of the received data similar to this pattern. + string responseString = RemoteSessionHyperVSocketClient.ReceiveResponse(socket, RemoteSessionHyperVSocketClient.VERSION_REQUEST.Length + 4); + if (string.IsNullOrEmpty(responseString) || responseString.Length != RemoteSessionHyperVSocketClient.VERSION_REQUEST.Length) + { + socket.Send("FAIL"u8); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Client", "Version Request: " + responseString)); + } + + cancellationToken.ThrowIfCancellationRequested(); + + socket.Send(Encoding.UTF8.GetBytes(RemoteSessionHyperVSocketClient.CLIENT_VERSION)); + responseString = RemoteSessionHyperVSocketClient.ReceiveResponse(socket, RemoteSessionHyperVSocketClient.CLIENT_VERSION.Length + 4); + + // In the future we may need to handle different versions, differently. + // For now, we are just checking that we exchanged versions correctly. + if (string.IsNullOrEmpty(responseString) || !responseString.StartsWith(RemoteSessionHyperVSocketClient.VERSION_PREFIX, StringComparison.Ordinal)) + { + socket.Send("FAIL"u8); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Client", "Version Response: " + responseString)); + } + + cancellationToken.ThrowIfCancellationRequested(); + + socket.Send("PASS"u8); + + // The client should send the token in the format TOKEN + // the token should be up to 256 bits, which is less than 50 characters. + // I'll double that to 100 characters to be safe, plus the "TOKEN " prefix. + // So we expect a response of length 6 + 100 = 106 characters. + responseString = RemoteSessionHyperVSocketClient.ReceiveResponse(socket, 110); + + // Final check if we got the token before the timeout + cancellationToken.ThrowIfCancellationRequested(); + + ReadOnlySpan responseBytes = Encoding.UTF8.GetBytes(responseString); + string responseToken = RemoteSessionHyperVSocketClient.ExtractToken(responseBytes); + + if (responseToken == null) + { + socket.Send("FAIL"u8); + // If the response is not in the expected format, we throw an exception. + // This is a failure to authenticate the client. + // don't send this response for risk of information disclosure. + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Client", "Token Response")); + } + + if (!string.Equals(responseToken, token, StringComparison.Ordinal)) + { + socket.Send("FAIL"u8); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential)); + } + + // Acknowledge the token is valid with "PASS". + socket.Send("PASS"u8); + + socket.ReceiveTimeout = 0; // Disable the timeout after successful validation + socket.SendTimeout = 0; + } } internal sealed class RemoteSessionHyperVSocketClient : IDisposable @@ -337,7 +467,15 @@ internal sealed class RemoteSessionHyperVSocketClient : IDisposable #region Members private readonly object _syncObject; - private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); + + #region tracer + /// + /// An instance of the PSTraceSource class used for trace output. + /// + [SMA.TraceSource("RemoteSessionHyperVSocketClient", "Class that has PowerShell Direct Client implementation")] + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("RemoteSessionHyperVSocketClient", "Class that has PowerShell Direct Client implementation"); + + #endregion tracer private static readonly ManualResetEvent s_connectDone = new ManualResetEvent(false); @@ -351,6 +489,14 @@ internal sealed class RemoteSessionHyperVSocketClient : IDisposable #endregion + #region version constants + + internal const string VERSION_REQUEST = "VERSION"; + internal const string CLIENT_VERSION = "VERSION_2"; + internal const string VERSION_PREFIX = "VERSION_"; + + #endregion + #region Properties /// @@ -361,7 +507,7 @@ internal sealed class RemoteSessionHyperVSocketClient : IDisposable /// /// Returns the Hyper-V socket object. /// - public Socket HyperVSocket { get; } + public Socket HyperVSocket { get; private set; } /// /// Returns the network stream object. @@ -378,6 +524,37 @@ internal sealed class RemoteSessionHyperVSocketClient : IDisposable /// public StreamWriter TextWriter { get; private set; } + /// + /// True if the client is a Hyper-V container. + /// + public bool IsContainer { get; } + + /// + /// True if the client is using backwards compatible mode. + /// This is used to determine if the client should use + /// the backwards compatible or not. + /// In modern mode, the vmicvmsession service will + /// hand off the socket to the PowerShell process + /// inside the VM automatically. + /// In backwards compatible mode, the vmicvmsession + /// service create a new socket to the PowerShell process + /// inside the VM. + /// + public bool UseBackwardsCompatibleMode { get; private set; } + + /// + /// The authentication token used for the session. + /// This token is provided by the broker and provided to the server to authenticate the server session. + /// This protocol uses two connections: + /// 1. The first is to the broker or vmicvmsession service to exchange credentials and configuration. + /// The broker will respond with an authentication token. The broker also launches a PowerShell + /// server process with the authentication token. + /// 2. The second is to the server process, that was launched by the broker, + /// inside the VM, which uses the authentication token to verify that the client is the same client + /// that connected to the broker. + /// + public string AuthenticationToken { get; private set; } + /// /// Returns true if object is currently disposed. /// @@ -390,7 +567,9 @@ internal sealed class RemoteSessionHyperVSocketClient : IDisposable internal RemoteSessionHyperVSocketClient( Guid vmId, bool isFirstConnection, - bool isContainer = false) + bool useBackwardsCompatibleMode = false, + bool isContainer = false, + string authenticationToken = null) { Guid serviceId; @@ -409,28 +588,16 @@ internal RemoteSessionHyperVSocketClient( EndPoint = new HyperVSocketEndPoint(HyperVSocketEndPoint.AF_HYPERV, vmId, serviceId); - HyperVSocket = new Socket(EndPoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType)1); + IsContainer = isContainer; - // - // We need to call SetSocketOption() in order to set up Hyper-V socket connection between container host and Hyper-V container. - // Here is the scenario: the Hyper-V container is inside a utility vm, which is inside the container host - // - if (isContainer) - { - var value = new byte[sizeof(uint)]; - value[0] = 1; + UseBackwardsCompatibleMode = useBackwardsCompatibleMode; - try - { - HyperVSocket.SetSocketOption((System.Net.Sockets.SocketOptionLevel)HV_PROTOCOL_RAW, - (System.Net.Sockets.SocketOptionName)HVSOCKET_CONTAINER_PASSTHRU, - (byte[])value); - } - catch - { - throw new PSDirectException( - PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure)); - } + if (!isFirstConnection && !useBackwardsCompatibleMode && !string.IsNullOrEmpty(authenticationToken)) + { + // If this is not the first connection and we are using backwards compatible mode, + // we should not set the authentication token here. + // The authentication token will be set during the Connect method. + AuthenticationToken = authenticationToken; } } @@ -445,7 +612,10 @@ public void Dispose() { lock (_syncObject) { - if (IsDisposed) { return; } + if (IsDisposed) + { + return; + } IsDisposed = true; } @@ -483,6 +653,81 @@ public void Dispose() #region Public Methods + private void ShutdownSocket() + { + if (HyperVSocket != null) + { + // Ensure the socket is disposed properly. + try + { + s_tracer.WriteLine("ShutdownSocket: Disposing of the HyperVSocket."); + HyperVSocket.Dispose(); + } + catch (Exception ex) + { + s_tracer.WriteLine("ShutdownSocket: Exception while disposing the socket: {0}", ex.Message); + } + } + + // Dispose of the existing stream if it exists. + if (Stream != null) + { + try + { + Stream.Dispose(); + } + catch (Exception ex) + { + s_tracer.WriteLine("ShutdownSocket: Exception while disposing the stream: {0}", ex.Message); + } + } + } + + /// + /// Recreates the HyperVSocket and connects it to the endpoint, updating the Stream if successful. + /// + private bool ConnectSocket() + { + HyperVSocket = new Socket(EndPoint.AddressFamily, SocketType.Stream, (System.Net.Sockets.ProtocolType)1); + + // + // We need to call SetSocketOption() in order to set up Hyper-V socket connection between container host and Hyper-V container. + // Here is the scenario: the Hyper-V container is inside a utility vm, which is inside the container host + // + if (IsContainer) + { + var value = new byte[sizeof(uint)]; + value[0] = 1; + + try + { + HyperVSocket.SetSocketOption( + (System.Net.Sockets.SocketOptionLevel)HV_PROTOCOL_RAW, + (System.Net.Sockets.SocketOptionName)HVSOCKET_CONTAINER_PASSTHRU, + value); + } + catch + { + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.RemoteSessionHyperVSocketClientConstructorSetSocketOptionFailure)); + } + } + + s_tracer.WriteLine("Connect: Client connecting, to {0}; isContainer: {1}.", EndPoint.ServiceId.ToString(), IsContainer); + HyperVSocket.Connect(EndPoint); + + // Check if the socket is connected. + // If it is connected, create a NetworkStream. + if (HyperVSocket.Connected) + { + s_tracer.WriteLine("Connect: Client connected, to {0}; isContainer: {1}.", EndPoint.ServiceId.ToString(), IsContainer); + Stream = new NetworkStream(HyperVSocket, true); + return true; + } + + return false; + } + /// /// Connect to Hyper-V socket server. This is a blocking call until a /// connection occurs or the timeout time has elapsed. @@ -510,100 +755,51 @@ public bool Connect( } } - HyperVSocket.Connect(EndPoint); - - if (HyperVSocket.Connected) + if (ConnectSocket()) { - _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty, - "Client connected."); - - Stream = new NetworkStream(HyperVSocket, true); - if (isFirstConnection) { - if (string.IsNullOrEmpty(networkCredential.Domain)) + var exchangeResult = ExchangeCredentialsAndConfiguration(networkCredential, configurationName, HyperVSocket, this.UseBackwardsCompatibleMode); + if (!exchangeResult.success) { - networkCredential.Domain = "localhost"; - } + // We will not block here for a container because a container does not have a broker. + if (IsRequirePsDirectAuthenticationEnabled(@"SOFTWARE\\Microsoft\\PowerShell", Microsoft.Win32.RegistryHive.LocalMachine)) + { + s_tracer.WriteLine("ExchangeCredentialsAndConfiguration: RequirePsDirectAuthentication is enabled, requiring latest transport version."); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVNegotiationFailed)); + } - bool emptyPassword = string.IsNullOrEmpty(networkCredential.Password); - bool emptyConfiguration = string.IsNullOrEmpty(configurationName); - - byte[] domain = Encoding.Unicode.GetBytes(networkCredential.Domain); - byte[] userName = Encoding.Unicode.GetBytes(networkCredential.UserName); - byte[] password = Encoding.Unicode.GetBytes(networkCredential.Password); - byte[] response = new byte[4]; // either "PASS" or "FAIL" - string responseString; - - // - // Send credential to VM so that PowerShell process inside VM can be - // created under the correct security context. - // - HyperVSocket.Send(domain); - HyperVSocket.Receive(response); - - HyperVSocket.Send(userName); - HyperVSocket.Receive(response); - - // - // We cannot simply send password because if it is empty, - // the vmicvmsession service in VM will block in recv method. - // - if (emptyPassword) - { - HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYPW")); - HyperVSocket.Receive(response); - responseString = Encoding.ASCII.GetString(response); + this.UseBackwardsCompatibleMode = true; + s_tracer.WriteLine("ExchangeCredentialsAndConfiguration: Using backwards compatible mode."); + + // If the first connection fails in modern mode, fall back to backwards compatible mode. + ShutdownSocket(); // will terminate the broker + ConnectSocket(); // restart the broker + exchangeResult = ExchangeCredentialsAndConfiguration(networkCredential, configurationName, HyperVSocket, this.UseBackwardsCompatibleMode); + if (!exchangeResult.success) + { + s_tracer.WriteLine("ExchangeCredentialsAndConfiguration: Failed to exchange credentials and configuration in backwards compatible mode."); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Broker", "Credential")); + } } else { - HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYPW")); - HyperVSocket.Receive(response); - - HyperVSocket.Send(password); - HyperVSocket.Receive(response); - responseString = Encoding.ASCII.GetString(response); + this.AuthenticationToken = exchangeResult.authenticationToken; } + } - // - // There are 3 cases for the responseString received above. - // - "FAIL": credential is invalid - // - "PASS": credential is valid, but PowerShell Direct in VM does not support configuration (Server 2016 TP4 and before) - // - "CONF": credential is valid, and PowerShell Direct in VM supports configuration (Server 2016 TP5 and later) - // - - // - // Credential is invalid. - // - if (string.Equals(responseString, "FAIL", StringComparison.Ordinal)) + if (!isFirstConnection) + { + if (!this.UseBackwardsCompatibleMode) { - HyperVSocket.Send(response); - - throw new PSDirectException( - PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential)); - } - - // - // If PowerShell Direct in VM supports configuration, send configuration name. - // - if (string.Equals(responseString, "CONF", StringComparison.Ordinal)) - { - if (emptyConfiguration) - { - HyperVSocket.Send(Encoding.ASCII.GetBytes("EMPTYCF")); - } - else - { - HyperVSocket.Send(Encoding.ASCII.GetBytes("NONEMPTYCF")); - HyperVSocket.Receive(response); - - byte[] configName = Encoding.Unicode.GetBytes(configurationName); - HyperVSocket.Send(configName); - } + s_tracer.WriteLine("Connect-Server: Performing transport version and token exchange for Hyper-V socket. isFirstConnection: {0}, UseBackwardsCompatibleMode: {1}", isFirstConnection, this.UseBackwardsCompatibleMode); + RemoteSessionHyperVSocketClient.PerformTransportVersionAndTokenExchange(HyperVSocket, this.AuthenticationToken); } else { - HyperVSocket.Send(response); + s_tracer.WriteLine("Connect-Server: Skipping transport version and token exchange for backwards compatible mode."); } } @@ -615,8 +811,7 @@ public bool Connect( } else { - _tracer.WriteMessage("RemoteSessionHyperVSocketClient", "Connect", Guid.Empty, - "Client unable to connect."); + s_tracer.WriteLine("Connect: Client unable to connect."); result = false; } @@ -624,12 +819,341 @@ public bool Connect( return result; } + /// + /// Performs the transport version and token exchange sequence for the Hyper-V socket connection. + /// Throws PSDirectException on failure. + /// + /// The socket to use for communication. + /// The authentication token to send. + public static void PerformTransportVersionAndTokenExchange(Socket socket, string authenticationToken) + { + if (string.IsNullOrEmpty(authenticationToken)) + { + s_tracer.WriteLine("PerformTransportVersionAndTokenExchange: Authentication token is null or empty. Aborting transport version and token exchange."); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential)); + } + + socket.Send(Encoding.UTF8.GetBytes(VERSION_REQUEST)); + string responseStr = ReceiveResponse(socket, 16); + + // Check if the response starts with the expected version prefix. + // We will rely on the broker to determine if the two can communicate. + // At least, for now. + if (!responseStr.StartsWith(VERSION_PREFIX, StringComparison.Ordinal)) + { + s_tracer.WriteLine("PerformTransportVersionAndTokenExchange: Server responded with an invalid response of {0}. Notifying the transport manager to downgrade if allowed.", responseStr); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Server", "TransportVersion")); + } + + socket.Send(Encoding.UTF8.GetBytes(CLIENT_VERSION)); + string response = ReceiveResponse(socket, 4); // either "PASS" or "FAIL" + + if (!string.Equals(response, "PASS", StringComparison.Ordinal)) + { + s_tracer.WriteLine( + "PerformTransportVersionAndTokenExchange: Transport version negotiation with server failed. Response: {0}", response); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Server", "TransportVersion")); + } + + byte[] tokenBytes = Encoding.UTF8.GetBytes("TOKEN " + authenticationToken); + socket.Send(tokenBytes); + + // This is the opportunity for the server to tell the client to go away. + string tokenResponse = ReceiveResponse(socket, 256); // either "PASS" or "FAIL", but get a little more buffer to allow for better error in the future + if (!string.Equals(tokenResponse, "PASS", StringComparison.Ordinal)) + { + s_tracer.WriteLine( + "PerformTransportVersionAndTokenExchange: Server Authentication Token exchange failed. Response: {0}", tokenResponse); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential)); + } + } + + /// + /// Checks if the registry key RequirePsDirectAuthentication is set to 1. + /// Returns true if fallback should be aborted. + /// Uses the 64-bit registry view on 64-bit systems to ensure consistent behavior regardless of process architecture. + /// On 32-bit systems, uses the default registry view since there is no WOW64 redirection. + /// + internal static bool IsRequirePsDirectAuthenticationEnabled(string keyPath, Microsoft.Win32.RegistryHive registryHive) + { + const string regValueName = "RequirePsDirectAuthentication"; + + try + { + Microsoft.Win32.RegistryView registryView = Environment.Is64BitOperatingSystem + ? Microsoft.Win32.RegistryView.Registry64 + : Microsoft.Win32.RegistryView.Default; + + using (Microsoft.Win32.RegistryKey baseKey = Microsoft.Win32.RegistryKey.OpenBaseKey( + registryHive, + registryView)) + { + using (Microsoft.Win32.RegistryKey key = baseKey.OpenSubKey(keyPath)) + { + if (key != null) + { + var value = key.GetValue(regValueName); + if (value is int intValue && intValue != 0) + { + return true; + } + } + + return false; + } + } + } + catch (Exception regEx) + { + s_tracer.WriteLine("IsRequirePsDirectAuthenticationEnabled: Exception while checking registry key: {0}", regEx.Message); + return false; // If we cannot read the registry, assume the feature is not enabled. + } + } + + /// + /// Handles credential and configuration exchange with the VM for the first connection. + /// + public static (bool success, string authenticationToken) ExchangeCredentialsAndConfiguration(NetworkCredential networkCredential, string configurationName, Socket HyperVSocket, bool useBackwardsCompatibleMode) + { + // Encoding for the Hyper-V socket communication + // To send the domain, username, password, and configuration name, use UTF-16 (Encoding.Unicode) + // All other sends use UTF-8 (Encoding.UTF8) + // Receiving uses ASCII encoding + // NOT CONFUSING AT ALL + + if (!useBackwardsCompatibleMode) + { + HyperVSocket.Send(Encoding.UTF8.GetBytes(VERSION_REQUEST)); + // vmicvmsession service in VM will respond with "VERSION_2" or newer + // Version 1 protocol will respond with "PASS" or "FAIL" + // Receive the response and check for VERSION_2 or newer + string responseStr = ReceiveResponse(HyperVSocket, 16); + if (!responseStr.StartsWith(VERSION_PREFIX, StringComparison.Ordinal)) + { + s_tracer.WriteLine("When asking for version the server responded with an invalid response of {0}.", responseStr); + s_tracer.WriteLine("Session is invalid, continuing session with a fake user to close the session with the broker for stability."); + // If not the new protocol, finish the conversation + // Send a fake user + // Use ? <> that are illegal in user names so no one can create the user + string probeUserName = "?"; // must be less than or equal to 20 characters for Windows Server 2016 + s_tracer.WriteLine("probeUserName (static): length: {0}", probeUserName.Length); + SendUserData(probeUserName, HyperVSocket); + responseStr = ReceiveResponse(HyperVSocket, 4); // either "PASS" or "FAIL" + s_tracer.WriteLine("When sending user {0}.", responseStr); + + // Send that the password is empty + HyperVSocket.Send("EMPTYPW"u8); + responseStr = ReceiveResponse(HyperVSocket, 4); // either "CONF", "PASS" or "FAIL" + s_tracer.WriteLine("When sending EMPTYPW: {0}.", responseStr); // server responds with FAIL so we respond with FAIL and the conversation is done + HyperVSocket.Send("FAIL"u8); + + s_tracer.WriteLine("Notifying the transport manager to downgrade if allowed."); + // end new code + return (false, null); + } + + HyperVSocket.Send(Encoding.UTF8.GetBytes(CLIENT_VERSION)); + ReceiveResponse(HyperVSocket, 4); // either "PASS" or "FAIL" + } + + if (string.IsNullOrEmpty(networkCredential.Domain)) + { + networkCredential.Domain = "localhost"; + } + + System.Security.SecureString securePassword = networkCredential.SecurePassword; + int passwordLength = securePassword.Length; + bool emptyPassword = (passwordLength <= 0); + bool emptyConfiguration = string.IsNullOrEmpty(configurationName); + + string responseString; + + // Send credential to VM so that PowerShell process inside VM can be + // created under the correct security context. + SendUserData(networkCredential.Domain, HyperVSocket); + ReceiveResponse(HyperVSocket, 4); // only "PASS" is expected + + SendUserData(networkCredential.UserName, HyperVSocket); + ReceiveResponse(HyperVSocket, 4); // only "PASS" is expected + + // We cannot simply send password because if it is empty, + // the vmicvmsession service in VM will block in recv method. + if (emptyPassword) + { + HyperVSocket.Send("EMPTYPW"u8); + responseString = ReceiveResponse(HyperVSocket, 4); // either "CONF", "PASS" or "FAIL" (note, "PASS" is not used in VERSION_2 or newer mode) + } + else + { + HyperVSocket.Send("NONEMPTYPW"u8); + ReceiveResponse(HyperVSocket, 4); // only "PASS" is expected + + // Get the password bytes from the SecureString, send them, and then zero out the byte array. + byte[] passwordBytes = Microsoft.PowerShell.SecureStringHelper.GetData(securePassword); + try + { + HyperVSocket.Send(passwordBytes); + } + finally + { + // Zero out the byte array for security + Array.Clear(passwordBytes); + } + + responseString = ReceiveResponse(HyperVSocket, 4); // either "CONF", "PASS" or "FAIL" (note, "PASS" is not used in VERSION_2 or newer mode) + } + + // Check for invalid response from server + if (!string.Equals(responseString, "FAIL", StringComparison.Ordinal) && + !string.Equals(responseString, "PASS", StringComparison.Ordinal) && + !string.Equals(responseString, "CONF", StringComparison.Ordinal)) + { + s_tracer.WriteLine("ExchangeCredentialsAndConfiguration: Server responded with an invalid response of {0} for credentials.", responseString); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Broker", "Credential")); + } + + // Credential is invalid. + if (string.Equals(responseString, "FAIL", StringComparison.Ordinal)) + { + HyperVSocket.Send("FAIL"u8); + // should we be doing this? Disabling the test for now + // HyperVSocket.Shutdown(SocketShutdown.Both); + s_tracer.WriteLine("ExchangeCredentialsAndConfiguration: Server responded with FAIL for credentials."); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidCredential)); + } + + // If PowerShell Direct in VM supports configuration, send configuration name. + if (string.Equals(responseString, "CONF", StringComparison.Ordinal)) + { + if (emptyConfiguration) + { + HyperVSocket.Send("EMPTYCF"u8); + } + else + { + HyperVSocket.Send("NONEMPTYCF"u8); + ReceiveResponse(HyperVSocket, 4); // only "PASS" is expected + + SendUserData(configurationName, HyperVSocket); + } + } + else + { + HyperVSocket.Send("PASS"u8); + } + + if (!useBackwardsCompatibleMode) + { + // Receive the token from the server + // Getting 1024 bytes because it is well above the expected token size + // The expected size at the time of writing this would be about 50 based64 characters, + // plus the 6 characters for the "TOKEN " prefix. + // The 50 character size is designed to last 10 years of cryptographic changes. + // Since the broker completely controls the cryptographic portion here, + // allowing a significant larger size, allows the broker to make almost arbitrary changes, + // without breaking the client. + string token = ReceiveResponse(HyperVSocket, 1024); // either "PASS" or "FAIL" + + ReadOnlySpan tokenResponseBytes = Encoding.UTF8.GetBytes(token); + string extractedToken = ExtractToken(tokenResponseBytes); + + if (extractedToken == null) + { + s_tracer.WriteLine("ExchangeCredentialsAndConfiguration: Server did not respond with a valid token. Response: {0}", token); + throw new PSDirectException( + PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.HyperVInvalidResponse, "Broker", "Token " + token)); + } + + token = extractedToken; + + HyperVSocket.Send("PASS"u8); // acknowledge the token + return (true, token); + } + + return (true, null); + } + public void Close() { Stream.Dispose(); HyperVSocket.Dispose(); } + /// + /// Receives a response from the socket and decodes it. + /// + /// The socket to receive from. + /// The size of the buffer to use for receiving data. + /// The decoded response string. + internal static string ReceiveResponse(Socket socket, int bufferSize) + { + System.Buffers.ArrayPool pool = System.Buffers.ArrayPool.Shared; + byte[] responseBuffer = pool.Rent(bufferSize); + int bytesReceived = 0; + try + { + bytesReceived = socket.Receive(responseBuffer); + if (bytesReceived == 0) + { + return null; + } + + string response = Encoding.ASCII.GetString(responseBuffer, 0, bytesReceived); + + // Handle null terminators and log if found + if (response.EndsWith('\0')) + { + int originalLength = response.Length; + response = response.TrimEnd('\0'); + // Cannot log actual response, because we don't know if it is sensitive + s_tracer.WriteLine( + "ReceiveResponse: Removed null terminator(s). Original length: {0}, New length: {1}", + originalLength, + response.Length); + } + + return response; + } + finally + { + pool.Return(responseBuffer); + } + } + + internal static string ExtractToken(ReadOnlySpan tokenResponse) + { + string token = Encoding.UTF8.GetString(tokenResponse); + + if (token == null || !token.StartsWith("TOKEN ", StringComparison.Ordinal)) + { + return null; // caller method will write trace (and determine when to expose token info as appropriate) + } + + token = token.Substring(6).Trim(); // remove "TOKEN " prefix + + if (token.Length == 0) + { + return null; + } + + return token; + } + + /// + /// Sends user data (domain, username, etc.) over the HyperVSocket using Unicode encoding. + /// + private static void SendUserData(string data, Socket socket) + { + // this encodes the data in UTF-16 (Unicode) + byte[] buffer = Encoding.Unicode.GetBytes(data); + socket.Send(buffer); + } #endregion } } diff --git a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs index 7593bbcc3b0..fc5226a007e 100644 --- a/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs +++ b/src/System.Management.Automation/engine/remoting/common/RemoteSessionNamedPipe.cs @@ -12,7 +12,6 @@ using System.Security.AccessControl; using System.Security.Principal; using System.Threading; -using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; @@ -110,7 +109,7 @@ internal static string CreateProcessPipeName( // There is a limit of 104 characters in total including the temp path to the named pipe file // on non-Windows systems, so we'll convert the starttime to hex and just take the first 8 characters. #if UNIX - .Append(proc.StartTime.ToFileTime().ToString("X8").Substring(1,8)) + .Append(proc.StartTime.ToFileTime().ToString("X8").AsSpan(1, 8)) #else .Append(proc.StartTime.ToFileTime().ToString(CultureInfo.InvariantCulture)) #endif @@ -190,26 +189,6 @@ internal static class NamedPipeNative internal const uint ERROR_IO_INCOMPLETE = 996; internal const uint ERROR_IO_PENDING = 997; - // File function constants - internal const uint GENERIC_READ = 0x80000000; - internal const uint GENERIC_WRITE = 0x40000000; - internal const uint GENERIC_EXECUTE = 0x20000000; - internal const uint GENERIC_ALL = 0x10000000; - - internal const uint CREATE_NEW = 1; - internal const uint CREATE_ALWAYS = 2; - internal const uint OPEN_EXISTING = 3; - internal const uint OPEN_ALWAYS = 4; - internal const uint TRUNCATE_EXISTING = 5; - - internal const uint SECURITY_IMPERSONATIONLEVEL_ANONYMOUS = 0; - internal const uint SECURITY_IMPERSONATIONLEVEL_IDENTIFICATION = 1; - internal const uint SECURITY_IMPERSONATIONLEVEL_IMPERSONATION = 2; - internal const uint SECURITY_IMPERSONATIONLEVEL_DELEGATION = 3; - - // Infinite timeout - internal const uint INFINITE = 0xFFFFFFFF; - #endregion #region Data structures @@ -265,28 +244,6 @@ internal static SECURITY_ATTRIBUTES GetSecurityAttributes(GCHandle securityDescr return securityAttributes; } - [DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode, CallingConvention = CallingConvention.StdCall)] - internal static extern SafePipeHandle CreateFile( - string lpFileName, - uint dwDesiredAccess, - uint dwShareMode, - IntPtr SecurityAttributes, - uint dwCreationDisposition, - uint dwFlagsAndAttributes, - IntPtr hTemplateFile); - - [DllImport(PinvokeDllNames.WaitNamedPipeDllName, SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool WaitNamedPipe(string lpNamedPipeName, uint nTimeOut); - - [DllImport(PinvokeDllNames.ImpersonateNamedPipeClientDllName, SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe); - - [DllImport(PinvokeDllNames.RevertToSelfDllName, SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool RevertToSelf(); - #endregion } @@ -496,7 +453,7 @@ private static NamedPipeServerStream CreateNamedPipe( SafePipeHandle pipeHandle = NamedPipeNative.CreateNamedPipe( fullPipeName, NamedPipeNative.PIPE_ACCESS_DUPLEX | NamedPipeNative.FILE_FLAG_FIRST_PIPE_INSTANCE | NamedPipeNative.FILE_FLAG_OVERLAPPED, - NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE, + NamedPipeNative.PIPE_TYPE_MESSAGE | NamedPipeNative.PIPE_READMODE_MESSAGE | NamedPipeNative.PIPE_REJECT_REMOTE_CLIENTS, 1, _namedPipeBufferSizeForRemoting, _namedPipeBufferSizeForRemoting, @@ -504,10 +461,7 @@ private static NamedPipeServerStream CreateNamedPipe( securityAttributes); int lastError = Marshal.GetLastWin32Error(); - if (securityDescHandle != null) - { - securityDescHandle.Value.Free(); - } + securityDescHandle?.Free(); if (pipeHandle.IsInvalid) { @@ -545,13 +499,14 @@ static RemoteSessionNamedPipeServer() { s_syncObject = new object(); - // All PowerShell instances will start with the named pipe - // and listener created and running. - IPCNamedPipeServerEnabled = true; - - CreateIPCNamedPipeServerSingleton(); + // Unless opt-out, all PowerShell instances will start with the named-pipe listener created and running. + IPCNamedPipeServerEnabled = !Utils.GetEnvironmentVariableAsBool(name: "POWERSHELL_DIAGNOSTICS_OPTOUT", defaultValue: false); - CreateProcessExitHandler(); + if (IPCNamedPipeServerEnabled) + { + CreateIPCNamedPipeServerSingleton(); + CreateProcessExitHandler(); + } } #endregion @@ -1009,8 +964,6 @@ internal class NamedPipeClientBase : IDisposable private NamedPipeClientStream _clientPipeStream; private readonly PowerShellTraceSource _tracer = PowerShellTraceSourceFactory.GetTraceSource(); - protected string _pipeName; - #endregion #region Properties @@ -1030,25 +983,30 @@ internal class NamedPipeClientBase : IDisposable /// public string PipeName { - get { return _pipeName; } + get; + internal set; } #endregion - #region Constructor - - public NamedPipeClientBase() - { } - - #endregion - #region IDisposable /// - /// Dispose. + /// Dispose object. /// public void Dispose() { + Dispose(true); + GC.SuppressFinalize(this); + } + + private void Dispose(bool disposing) + { + if (!disposing) + { + return; + } + if (TextReader != null) { try { TextReader.Dispose(); } @@ -1093,23 +1051,23 @@ public void Connect( TextWriter.AutoFlush = true; _tracer.WriteMessage("NamedPipeClientBase", "Connect", Guid.Empty, - "Connection started on pipe: {0}", _pipeName); + "Connection started on pipe: {0}", PipeName); } /// /// Closes the named pipe. /// - public void Close() - { - if (_clientPipeStream != null) - { - _clientPipeStream.Dispose(); - } - } + public void Close() => _clientPipeStream?.Dispose(); + /// + /// Abort connection attempt. + /// public virtual void AbortConnect() { } + /// + /// Begin connection attempt. + /// protected virtual NamedPipeClientStream DoConnect(int timeout) { return null; @@ -1166,7 +1124,7 @@ internal RemoteSessionNamedPipeClient( throw new PSArgumentNullException(nameof(pipeName)); } - _pipeName = pipeName; + PipeName = pipeName; // Defer creating the .Net NamedPipeClientStream object until we connect. // _clientPipeStream == null. @@ -1189,7 +1147,7 @@ internal RemoteSessionNamedPipeClient( if (coreName == null) { throw new PSArgumentNullException(nameof(coreName)); } - _pipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; + PipeName = @"\\" + serverName + @"\" + namespaceName + @"\" + coreName; // Defer creating the .Net NamedPipeClientStream object until we connect. // _clientPipeStream == null. @@ -1211,6 +1169,9 @@ public override void AbortConnect() #region Protected Methods + /// + /// Begin connection attempt. + /// protected override NamedPipeClientStream DoConnect(int timeout) { // Repeatedly attempt connection to pipe until timeout expires. @@ -1220,11 +1181,11 @@ protected override NamedPipeClientStream DoConnect(int timeout) NamedPipeClientStream namedPipeClientStream = new NamedPipeClientStream( serverName: ".", - pipeName: _pipeName, + pipeName: PipeName, direction: PipeDirection.InOut, options: PipeOptions.Asynchronous); - namedPipeClientStream.Connect(); + namedPipeClientStream.ConnectAsync(timeout); do { @@ -1275,7 +1236,7 @@ public ContainerSessionNamedPipeClient( // // Named pipe inside Windows Server container is under different name space. // - _pipeName = containerObRoot + @"\Device\NamedPipe\" + + PipeName = containerObRoot + @"\Device\NamedPipe\" + NamedPipeUtils.CreateProcessPipeName(procId, appDomainName); } @@ -1289,30 +1250,34 @@ public ContainerSessionNamedPipeClient( /// protected override NamedPipeClientStream DoConnect(int timeout) { +#if UNIX + // TODO: `CreateFileWithSafePipeHandle` pinvoke below clearly says + // that the code is only for Windows and we could exclude + // a lot of code from compilation on Unix. + throw new NotSupportedException(nameof(DoConnect)); +#else // // WaitNamedPipe API is not supported by Windows Server container now, so we need to repeatedly // attempt connection to pipe server until timeout expires. // int startTime = Environment.TickCount; int elapsedTime = 0; - SafePipeHandle pipeHandle = null; + nint handle; do { // Get handle to pipe. - pipeHandle = NamedPipeNative.CreateFile( - lpFileName: _pipeName, - dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - dwShareMode: 0, - SecurityAttributes: IntPtr.Zero, - dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, - dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, - hTemplateFile: IntPtr.Zero); - - int lastError = Marshal.GetLastWin32Error(); - if (pipeHandle.IsInvalid) + handle = Interop.Windows.CreateFileWithPipeHandle( + lpFileName: PipeName, + FileAccess.ReadWrite, + FileShare.None, + FileMode.Open, + Interop.Windows.FileAttributes.Overlapped); + + if (handle == nint.Zero || handle == (nint)(-1)) { - if (lastError == NamedPipeNative.ERROR_FILE_NOT_FOUND) + int lastError = Marshal.GetLastPInvokeError(); + if (lastError == Interop.Windows.ERROR_FILE_NOT_FOUND) { elapsedTime = unchecked(Environment.TickCount - startTime); Thread.Sleep(100); @@ -1330,19 +1295,21 @@ protected override NamedPipeClientStream DoConnect(int timeout) } } while (elapsedTime < timeout); + SafePipeHandle pipeHandle = null; try { + pipeHandle = new SafePipeHandle(handle, ownsHandle: true); return new NamedPipeClientStream( PipeDirection.InOut, - true, - true, + isAsync: true, pipeHandle); } catch (Exception) { - pipeHandle.Dispose(); + pipeHandle?.Dispose(); throw; } +#endif } #endregion diff --git a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs index ea8a9c1a9d0..475dc705674 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspaceConnectionInfo.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections; using System.Collections.Generic; using System.ComponentModel; // Win32Exception using System.Diagnostics; @@ -17,6 +18,7 @@ using System.Reflection; using System.Runtime.InteropServices; using System.Security.AccessControl; +using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; @@ -166,10 +168,7 @@ public CultureInfo Culture set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _culture = value; } @@ -189,10 +188,7 @@ public CultureInfo UICulture set { - if (value == null) - { - throw new ArgumentNullException("value"); - } + ArgumentNullException.ThrowIfNull(value); _uiCulture = value; } @@ -229,7 +225,7 @@ public int OpenTimeout // The timer constructor will throw an exception // for any value greater than Int32.MaxValue // hence this is the maximum possible limit - _openTimeout = Int32.MaxValue; + _openTimeout = int.MaxValue; } } } @@ -274,7 +270,7 @@ public int OpenTimeout /// The maximum allowed idle timeout duration (in ms) that can be set on a Runspace. This is a read-only property /// that is set once the Runspace is successfully created and opened. /// - public int MaxIdleTimeout { get; internal set; } = Int32.MaxValue; + public int MaxIdleTimeout { get; internal set; } = int.MaxValue; /// /// Populates session options from a PSSessionOption instance. @@ -282,10 +278,7 @@ public int OpenTimeout /// public virtual void SetSessionOptions(PSSessionOption options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if (options.Culture != null) { @@ -325,13 +318,33 @@ internal int TimeSpanToTimeOutMs(TimeSpan t) } } + /// + /// Validates port number is in range. + /// + /// Port number to validate. + internal virtual void ValidatePortInRange(int port) + { + if ((port < MinPort || port > MaxPort)) + { + string message = + PSRemotingErrorInvariants.FormatResourceString( + RemotingErrorIdStrings.PortIsOutOfRange, port); + ArgumentException e = new ArgumentException(message); + throw e; + } + } + + #endregion + + #region Public methods + /// /// Creates the appropriate client session transportmanager. /// /// Runspace/Pool instance Id. /// Session name. /// PSRemotingCryptoHelper. - internal virtual BaseClientSessionTransportManager CreateClientSessionTransportManager( + public virtual BaseClientSessionTransportManager CreateClientSessionTransportManager( Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) @@ -343,27 +356,11 @@ internal virtual BaseClientSessionTransportManager CreateClientSessionTransportM /// Create a copy of the connection info object. /// /// Copy of the connection info object. - internal virtual RunspaceConnectionInfo InternalCopy() + public virtual RunspaceConnectionInfo Clone() { throw new PSNotImplementedException(); } - /// - /// Validates port number is in range. - /// - /// Port number to validate. - internal virtual void ValidatePortInRange(int port) - { - if ((port < MinPort || port > MaxPort)) - { - string message = - PSRemotingErrorInvariants.FormatResourceString( - RemotingErrorIdStrings.PortIsOutOfRange, port); - ArgumentException e = new ArgumentException(message); - throw e; - } - } - #endregion #region Constants @@ -1023,10 +1020,7 @@ public WSManConnectionInfo(Uri uri) /// public override void SetSessionOptions(PSSessionOption options) { - if (options == null) - { - throw new ArgumentNullException(nameof(options)); - } + ArgumentNullException.ThrowIfNull(options); if ((options.ProxyAccessType == ProxyAccessType.None) && (options.ProxyCredential != null)) { @@ -1062,10 +1056,10 @@ public override void SetSessionOptions(PSSessionOption options) } /// - /// Shallow copy of the current instance. + /// Create a copy of the connection info object. /// - /// RunspaceConnectionInfo. - internal override RunspaceConnectionInfo InternalCopy() + /// Copy of the connection info object. + public override RunspaceConnectionInfo Clone() { return Copy(); } @@ -1133,7 +1127,14 @@ public WSManConnectionInfo Copy() #region Internal Methods - internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) + /// + /// Creates the appropriate client session transportmanager. + /// + /// Runspace/Pool instance Id. + /// Session name. + /// PSRemotingCryptoHelper instance. + /// Instance of WSManClientSessionTransportManager + public override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) { return new WSManClientSessionTransportManager( instanceId, @@ -1173,7 +1174,7 @@ private static string ResolveShellUri(string shell) internal static T ExtractPropertyAsWsManConnectionInfo(RunspaceConnectionInfo rsCI, string property, T defaultValue) { - if (!(rsCI is WSManConnectionInfo wsCI)) + if (rsCI is not WSManConnectionInfo wsCI) { return defaultValue; } @@ -1374,7 +1375,7 @@ private void UpdateUri(Uri uri) private string _appName = s_defaultAppName; private Uri _connectionUri = new Uri(LocalHostUriString); // uri of this connection private PSCredential _credential; // credentials to be used for this connection - private string _shellUri = DefaultShellUri; // shell thats specified by the user + private string _shellUri = DefaultShellUri; // shell that's specified by the user private string _thumbPrint; private AuthenticationMechanism _proxyAuthentication; private PSCredential _proxyCredential; @@ -1653,12 +1654,23 @@ public NewProcessConnectionInfo Copy() return result; } - internal override RunspaceConnectionInfo InternalCopy() + /// + /// Create a copy of the connection info object. + /// + /// Copy of the connection info object. + public override RunspaceConnectionInfo Clone() { return Copy(); } - internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) + /// + /// Creates the appropriate client session transportmanager. + /// + /// Runspace/Pool instance Id. + /// Session name. + /// PSRemotingCryptoHelper object. + /// Instance of OutOfProcessClientSessionTransportManager + public override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) { return new OutOfProcessClientSessionTransportManager( instanceId, @@ -1873,10 +1885,10 @@ public override string CertificateThumbprint } /// - /// Shallow copy of current instance. + /// Create a copy of the connection info object. /// - /// NamedPipeConnectionInfo. - internal override RunspaceConnectionInfo InternalCopy() + /// Copy of the connection info object. + public override RunspaceConnectionInfo Clone() { NamedPipeConnectionInfo newCopy = new NamedPipeConnectionInfo(); newCopy._authMechanism = this.AuthenticationMechanism; @@ -1889,7 +1901,14 @@ internal override RunspaceConnectionInfo InternalCopy() return newCopy; } - internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) + /// + /// Creates the appropriate client session transportmanager. + /// + /// Runspace/Pool instance Id. + /// Session name. + /// PSRemotingCryptoHelper object. + /// Instance of NamedPipeClientSessionTransportManager + public override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) { return new NamedPipeClientSessionTransportManager( this, @@ -1907,6 +1926,20 @@ internal override BaseClientSessionTransportManager CreateClientSessionTransport /// public sealed class SSHConnectionInfo : RunspaceConnectionInfo { + #region Constants + + /// + /// Default value for subsystem. + /// + private const string DefaultSubsystem = "powershell"; + + /// + /// Default value is infinite timeout. + /// + private const int DefaultConnectingTimeoutTime = Timeout.Infinite; + + #endregion + #region Properties /// @@ -1921,7 +1954,7 @@ public string UserName /// /// Key File Path. /// - private string KeyFilePath + public string KeyFilePath { get; set; @@ -1930,7 +1963,7 @@ private string KeyFilePath /// /// Port for connection. /// - private int Port + public int Port { get; set; @@ -1939,7 +1972,27 @@ private int Port /// /// Subsystem to use. /// - private string Subsystem + public string Subsystem + { + get; + set; + } + + /// + /// Gets or sets a time in milliseconds after which a connection attempt is terminated. + /// Default value (-1) never times out and a connection attempt waits indefinitely. + /// + public int ConnectingTimeout + { + get; + set; + } + + /// + /// The SSH options to pass to OpenSSH. + /// Gets or sets the SSH options to pass to OpenSSH. + /// + private Hashtable Options { get; set; @@ -1950,13 +2003,13 @@ private string Subsystem #region Constructors /// - /// Constructor. + /// Initializes a new instance of the class. /// private SSHConnectionInfo() { } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// User Name. /// Computer Name. @@ -1966,17 +2019,21 @@ public SSHConnectionInfo( string computerName, string keyFilePath) { - if (computerName == null) { throw new PSArgumentNullException(nameof(computerName)); } + if (computerName == null) + { + throw new PSArgumentNullException(nameof(computerName)); + } - this.UserName = userName; - this.ComputerName = computerName; - this.KeyFilePath = keyFilePath; - this.Port = 0; - this.Subsystem = DefaultSubsystem; + UserName = userName; + ComputerName = computerName; + KeyFilePath = keyFilePath; + Port = 0; + Subsystem = DefaultSubsystem; + ConnectingTimeout = DefaultConnectingTimeoutTime; } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// User Name. /// Computer Name. @@ -1989,12 +2046,11 @@ public SSHConnectionInfo( int port) : this(userName, computerName, keyFilePath) { ValidatePortInRange(port); - - this.Port = port; + Port = port; } /// - /// Constructor. + /// Initializes a new instance of the class. /// /// User Name. /// Computer Name. @@ -2006,12 +2062,51 @@ public SSHConnectionInfo( string computerName, string keyFilePath, int port, - string subsystem) : this(userName, computerName, keyFilePath) + string subsystem) : this(userName, computerName, keyFilePath, port) { - ValidatePortInRange(port); + Subsystem = string.IsNullOrEmpty(subsystem) ? DefaultSubsystem : subsystem; + } - this.Port = port; - this.Subsystem = (string.IsNullOrEmpty(subsystem)) ? DefaultSubsystem : subsystem; + /// + /// Initializes a new instance of SSHConnectionInfo. + /// + /// Name of user. + /// Name of computer. + /// Path of key file. + /// Port number for connection (default 22). + /// Subsystem to use (default 'powershell'). + /// Timeout time for terminating connection attempt. + public SSHConnectionInfo( + string userName, + string computerName, + string keyFilePath, + int port, + string subsystem, + int connectingTimeout) : this(userName, computerName, keyFilePath, port, subsystem) + { + ConnectingTimeout = connectingTimeout; + } + + /// + /// Initializes a new instance of the class. + /// + /// User Name. + /// Computer Name. + /// Key File Path. + /// Port number for connection (default 22). + /// Subsystem to use (default 'powershell'). + /// Timeout time for terminating connection attempt. + /// Options for the SSH connection. + public SSHConnectionInfo( + string userName, + string computerName, + string keyFilePath, + int port, + string subsystem, + int connectingTimeout, + Hashtable options) : this(userName, computerName, keyFilePath, port, subsystem, connectingTimeout) + { + Options = options; } #endregion @@ -2058,29 +2153,30 @@ public override string CertificateThumbprint } /// - /// Shallow copy of current instance. + /// Create a copy of the connection info object. /// - /// NamedPipeConnectionInfo. - internal override RunspaceConnectionInfo InternalCopy() + /// Copy of the connection info object. + public override RunspaceConnectionInfo Clone() { SSHConnectionInfo newCopy = new SSHConnectionInfo(); - newCopy.ComputerName = this.ComputerName; - newCopy.UserName = this.UserName; - newCopy.KeyFilePath = this.KeyFilePath; - newCopy.Port = this.Port; - newCopy.Subsystem = this.Subsystem; + newCopy.ComputerName = ComputerName; + newCopy.UserName = UserName; + newCopy.KeyFilePath = KeyFilePath; + newCopy.Port = Port; + newCopy.Subsystem = Subsystem; + newCopy.ConnectingTimeout = ConnectingTimeout; + newCopy.Options = Options; return newCopy; } /// - /// CreateClientSessionTransportManager. + /// Creates the appropriate client session transportmanager. /// - /// - /// - /// - /// - internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) + /// Runspace/Pool instance Id. + /// Session name. + /// PSRemotingCryptoHelper. + public override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) { return new SSHClientSessionTransportManager( this, @@ -2110,20 +2206,62 @@ internal int StartSSHProcess( var context = Runspaces.LocalPipeline.GetExecutionContextFromTLS(); if (context != null) { - var cmdInfo = context.CommandDiscovery.LookupCommandInfo(sshCommand, CommandOrigin.Internal) as ApplicationInfo; - if (cmdInfo != null) + var cmdInfo = CommandDiscovery.LookupCommandInfo( + sshCommand, + CommandTypes.Application, + SearchResolutionOptions.None, + CommandOrigin.Internal, + context); + + if (cmdInfo is ApplicationInfo appInfo) { - filePath = cmdInfo.Path; + filePath = appInfo.Path; + } + } + else + { + // A Runspace may not be present in the TLS in SDK hosted apps + // or if running in another thread without a Runspace. While + // 'ProcessStartInfo' can lookup the full path in PATH, it searches + // the process' working directory first. 'LookupCommandInfo' does + // not search the process' working directory and we want to keep that + // behavior. We also get the parent dir of the full path to set as the + // new WorkingDirectory. So, we do a manual lookup here only in PATH. + string[] entries = Environment.GetEnvironmentVariable("PATH")?.Split( + Path.PathSeparator, + StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) ?? []; + foreach (var path in entries) + { + if (!Path.IsPathFullyQualified(path)) + { + continue; + } + + var sshCommandPath = Path.Combine(path, sshCommand); + if (File.Exists(sshCommandPath)) + { + filePath = sshCommandPath; + break; + } } } + + if (string.IsNullOrEmpty(filePath)) + { + throw new CommandNotFoundException( + sshCommand, + null, + "CommandNotFoundException", + DiscoveryExceptions.CommandNotFoundException); + } - // Create a local ssh process (client) that conects to a remote sshd process (server) using a 'powershell' subsystem. + // Create a local ssh process (client) that connects to a remote sshd process (server) using a 'powershell' subsystem. // // Local ssh invoked as: // windows: - // ssh.exe [-i identity_file] [-l login_name] [-p port] -s + // ssh.exe [-i identity_file] [-l login_name] [-p port] [-o option] -s // linux|macos: - // ssh [-i identity_file] [-l login_name] [-p port] -s + // ssh [-i identity_file] [-l login_name] [-p port] [-o option] -s // where is interpreted as the subsystem due to the -s flag. // // Remote sshd configured for PowerShell Remoting Protocol (PSRP) over Secure Shell Protocol (SSH) @@ -2134,36 +2272,37 @@ internal int StartSSHProcess( // linux|macos: // Subsystem powershell /usr/local/bin/pwsh -SSHServerMode -NoLogo -NoProfile - System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(filePath); + // 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 specified, so any file executed in the runspace would be in the user's local system/process or a system they have access to in which case restricted remoting security guidelines should be used. + ProcessStartInfo startInfo = new(filePath); // pass "-i identity_file" command line argument to ssh if KeyFilePath is set // if KeyFilePath is not set, then ssh will use IdentityFile / IdentityAgent from ssh_config if defined else none by default if (!string.IsNullOrEmpty(this.KeyFilePath)) { - if (!System.IO.File.Exists(this.KeyFilePath)) + if (!File.Exists(this.KeyFilePath)) { throw new FileNotFoundException( StringUtil.Format(RemotingErrorIdStrings.KeyFileNotFound, this.KeyFilePath)); } - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-i ""{0}""", this.KeyFilePath)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-i ""{this.KeyFilePath}""")); } - // pass "-l login_name" commmand line argument to ssh if UserName is set + // pass "-l login_name" command line argument to ssh if UserName is set // if UserName is not set, then ssh will use User from ssh_config if defined else the environment user by default if (!string.IsNullOrEmpty(this.UserName)) { - var parts = this.UserName.Split(Utils.Separators.Backslash); + var parts = this.UserName.Split('\\'); if (parts.Length == 2) { // convert DOMAIN\user to user@DOMAIN var domainName = parts[0]; var userName = parts[1]; - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-l {0}@{1}", userName, domainName)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-l {userName}@{domainName}")); } else { - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-l {0}", this.UserName)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-l {this.UserName}")); } } @@ -2171,28 +2310,37 @@ internal int StartSSHProcess( // if Port is not set, then ssh will use Port from ssh_config if defined else 22 by default if (this.Port != 0) { - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-p {0}", this.Port)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-p {this.Port}")); + } + + // pass "-o option=value" command line argument to ssh if options are provided + if (this.Options != null) + { + foreach (DictionaryEntry pair in this.Options) + { + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-o {pair.Key}={pair.Value}")); + } } // pass "-s destination command" command line arguments to ssh where command is the subsystem to invoke on the destination // note that ssh expects IPv6 addresses to not be enclosed in square brackets so trim them if present - startInfo.ArgumentList.Add(string.Format(CultureInfo.InvariantCulture, @"-s {0} {1}", this.ComputerName.TrimStart('[').TrimEnd(']'), this.Subsystem)); + startInfo.ArgumentList.Add(string.Create(CultureInfo.InvariantCulture, $@"-s {this.ComputerName.TrimStart('[').TrimEnd(']')} {this.Subsystem}")); - startInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(filePath); + startInfo.WorkingDirectory = Path.GetDirectoryName(filePath); startInfo.CreateNoWindow = true; startInfo.UseShellExecute = false; return StartSSHProcessImpl(startInfo, out stdInWriterVar, out stdOutReaderVar, out stdErrReaderVar); } - #endregion - - #region Constants - /// - /// Default value for subsystem. + /// Terminates the SSH process by process Id. /// - private const string DefaultSubsystem = "powershell"; + /// Process id. + internal void KillSSHProcess(int pid) + { + KillSSHProcessImpl(pid); + } #endregion @@ -2232,6 +2380,16 @@ private static int StartSSHProcessImpl( return pid; } + private static void KillSSHProcessImpl(int pid) + { + // killing a zombie might or might not return ESRCH, so we ignore kill's return value + Platform.NonWindowsKillProcess(pid); + + // block while waiting for process to die + // shouldn't take long after SIGKILL + Platform.NonWindowsWaitPid(pid, false); + } + #region UNIX Create Process // @@ -2282,23 +2440,31 @@ internal static int StartSSHProcess( if (startInfo.RedirectStandardInput) { Debug.Assert(stdinFd >= 0, "Invalid Fd"); - standardInput = new StreamWriter(OpenStream(stdinFd, FileAccess.Write), - Utils.utf8NoBom, StreamBufferSize) + standardInput = new StreamWriter( + OpenStream(stdinFd, FileAccess.Write), + Encoding.Default, + StreamBufferSize) { AutoFlush = true }; } if (startInfo.RedirectStandardOutput) { Debug.Assert(stdoutFd >= 0, "Invalid Fd"); - standardOutput = new StreamReader(OpenStream(stdoutFd, FileAccess.Read), - startInfo.StandardOutputEncoding ?? Utils.utf8NoBom, true, StreamBufferSize); + standardOutput = new StreamReader( + OpenStream(stdoutFd, FileAccess.Read), + startInfo.StandardOutputEncoding ?? Encoding.Default, + detectEncodingFromByteOrderMarks: true, + StreamBufferSize); } if (startInfo.RedirectStandardError) { Debug.Assert(stderrFd >= 0, "Invalid Fd"); - standardError = new StreamReader(OpenStream(stderrFd, FileAccess.Read), - startInfo.StandardErrorEncoding ?? Utils.utf8NoBom, true, StreamBufferSize); + standardError = new StreamReader( + OpenStream(stderrFd, FileAccess.Read), + startInfo.StandardErrorEncoding ?? Encoding.Default, + detectEncodingFromByteOrderMarks: true, + StreamBufferSize); } return childPid; @@ -2339,7 +2505,7 @@ private static string[] ParseArgv(ProcessStartInfo psi) var argvList = new List(); argvList.Add(psi.FileName); - var argsToParse = String.Join(" ", psi.ArgumentList).Trim(); + var argsToParse = string.Join(' ', psi.ArgumentList).Trim(); var argsLength = argsToParse.Length; for (int i = 0; i < argsLength; ) { @@ -2414,7 +2580,7 @@ private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arr // Allocate the unmanaged array to hold each string pointer. // It needs to have an extra element to null terminate the array. arrPtr = (byte**)Marshal.AllocHGlobal(sizeof(IntPtr) * arrLength); - System.Diagnostics.Debug.Assert(arrPtr != null, "Invalid array ptr"); + Debug.Assert(arrPtr != null, "Invalid array ptr"); // Zero the memory so that if any of the individual string allocations fails, // we can loop through the array to free any that succeeded. @@ -2431,7 +2597,7 @@ private static unsafe void AllocNullTerminatedArray(string[] arr, ref byte** arr byte[] byteArr = System.Text.Encoding.UTF8.GetBytes(arr[i]); arrPtr[i] = (byte*)Marshal.AllocHGlobal(byteArr.Length + 1); // +1 for null termination - System.Diagnostics.Debug.Assert(arrPtr[i] != null, "Invalid array ptr"); + Debug.Assert(arrPtr[i] != null, "Invalid array ptr"); Marshal.Copy(byteArr, 0, (IntPtr)arrPtr[i], byteArr.Length); // copy over the data from the managed byte array arrPtr[i][byteArr.Length] = (byte)'\0'; // null terminate @@ -2475,13 +2641,13 @@ internal static extern unsafe int ForkAndExecProcess( /// P-Invoking native APIs. /// private static int StartSSHProcessImpl( - System.Diagnostics.ProcessStartInfo startInfo, + ProcessStartInfo startInfo, out StreamWriter stdInWriterVar, out StreamReader stdOutReaderVar, out StreamReader stdErrReaderVar) { Exception ex = null; - System.Diagnostics.Process sshProcess = null; + Process sshProcess = null; // // These std pipe handles are bound to managed Reader/Writer objects and returned to the transport // manager object, which uses them for PSRP communication. The lifetime of these handles are then @@ -2502,7 +2668,7 @@ private static int StartSSHProcessImpl( catch (InvalidOperationException e) { ex = e; } catch (ArgumentException e) { ex = e; } catch (FileNotFoundException e) { ex = e; } - catch (System.ComponentModel.Win32Exception e) { ex = e; } + catch (Win32Exception e) { ex = e; } if ((ex != null) || (sshProcess == null) || @@ -2527,9 +2693,9 @@ private static int StartSSHProcessImpl( { if (stdInWriterVar != null) { stdInWriterVar.Dispose(); } else { stdInPipeServer.Dispose(); } - if (stdOutReaderVar != null) { stdInWriterVar.Dispose(); } else { stdOutPipeServer.Dispose(); } + if (stdOutReaderVar != null) { stdOutReaderVar.Dispose(); } else { stdOutPipeServer.Dispose(); } - if (stdErrReaderVar != null) { stdInWriterVar.Dispose(); } else { stdErrPipeServer.Dispose(); } + if (stdErrReaderVar != null) { stdErrReaderVar.Dispose(); } else { stdErrPipeServer.Dispose(); } throw; } @@ -2537,6 +2703,17 @@ private static int StartSSHProcessImpl( return sshProcess.Id; } + private static void KillSSHProcessImpl(int pid) + { + using (var sshProcess = Process.GetProcessById(pid)) + { + if ((sshProcess != null) && (sshProcess.Handle != IntPtr.Zero) && !sshProcess.HasExited) + { + sshProcess.Kill(); + } + } + } + // Process creation flags private const int CREATE_NEW_PROCESS_GROUP = 0x00000200; private const int CREATE_SUSPENDED = 0x00000004; @@ -2556,10 +2733,10 @@ private static Process CreateProcessWithRedirectedStd( stdInPipeServer = null; stdOutPipeServer = null; stdErrPipeServer = null; - SafePipeHandle stdInPipeClient = null; - SafePipeHandle stdOutPipeClient = null; - SafePipeHandle stdErrPipeClient = null; - string randomName = System.IO.Path.GetFileNameWithoutExtension(System.IO.Path.GetRandomFileName()); + SafeFileHandle stdInPipeClient = null; + SafeFileHandle stdOutPipeClient = null; + SafeFileHandle stdErrPipeClient = null; + string randomName = Path.GetFileNameWithoutExtension(Path.GetRandomFileName()); try { @@ -2580,17 +2757,12 @@ private static Process CreateProcessWithRedirectedStd( } catch (Exception) { - if (stdInPipeServer != null) { stdInPipeServer.Dispose(); } - - if (stdInPipeClient != null) { stdInPipeClient.Dispose(); } - - if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); } - - if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); } - - if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); } - - if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); } + stdInPipeServer?.Dispose(); + stdInPipeClient?.Dispose(); + stdOutPipeServer?.Dispose(); + stdOutPipeClient?.Dispose(); + stdErrPipeServer?.Dispose(); + stdErrPipeClient?.Dispose(); throw; } @@ -2609,9 +2781,9 @@ private static Process CreateProcessWithRedirectedStd( startInfo.FileName, string.Join(' ', startInfo.ArgumentList)); - lpStartupInfo.hStdInput = new SafeFileHandle(stdInPipeClient.DangerousGetHandle(), false); - lpStartupInfo.hStdOutput = new SafeFileHandle(stdOutPipeClient.DangerousGetHandle(), false); - lpStartupInfo.hStdError = new SafeFileHandle(stdErrPipeClient.DangerousGetHandle(), false); + lpStartupInfo.hStdInput = stdInPipeClient; + lpStartupInfo.hStdOutput = stdOutPipeClient; + lpStartupInfo.hStdError = stdErrPipeClient; lpStartupInfo.dwFlags = 0x100; // No new window: Inherit the parent process's console window @@ -2656,45 +2828,23 @@ private static Process CreateProcessWithRedirectedStd( } catch (Exception) { - if (stdInPipeServer != null) { stdInPipeServer.Dispose(); } - - if (stdInPipeClient != null) { stdInPipeClient.Dispose(); } - - if (stdOutPipeServer != null) { stdOutPipeServer.Dispose(); } - - if (stdOutPipeClient != null) { stdOutPipeClient.Dispose(); } - - if (stdErrPipeServer != null) { stdErrPipeServer.Dispose(); } - - if (stdErrPipeClient != null) { stdErrPipeClient.Dispose(); } + stdInPipeServer?.Dispose(); + stdOutPipeServer?.Dispose(); + stdErrPipeServer?.Dispose(); throw; } finally { + lpStartupInfo.Dispose(); lpProcessInformation.Dispose(); } } - private static SafePipeHandle GetNamedPipeHandle(string pipeName) + private static SafeFileHandle GetNamedPipeHandle(string pipeName) { - // Get handle to pipe. - var fileHandle = PlatformInvokes.CreateFileW( - lpFileName: pipeName, - dwDesiredAccess: NamedPipeNative.GENERIC_READ | NamedPipeNative.GENERIC_WRITE, - dwShareMode: 0, - lpSecurityAttributes: new PlatformInvokes.SECURITY_ATTRIBUTES(), // Create an inheritable handle. - dwCreationDisposition: NamedPipeNative.OPEN_EXISTING, - dwFlagsAndAttributes: NamedPipeNative.FILE_FLAG_OVERLAPPED, // Open in asynchronous mode. - hTemplateFile: IntPtr.Zero); - - int lastError = Marshal.GetLastWin32Error(); - if (fileHandle == PlatformInvokes.INVALID_HANDLE_VALUE) - { - throw new System.ComponentModel.Win32Exception(lastError); - } - - return new SafePipeHandle(fileHandle, true); + SafeFileHandle sf = File.OpenHandle(pipeName, FileMode.Open, FileAccess.ReadWrite, FileShare.Inheritable, FileOptions.Asynchronous); + return sf; } private static SafePipeHandle CreateNamedPipe( @@ -2724,10 +2874,7 @@ private static SafePipeHandle CreateNamedPipe( securityAttributes); int lastError = Marshal.GetLastWin32Error(); - if (securityDescHandle != null) - { - securityDescHandle.Value.Free(); - } + securityDescHandle?.Free(); if (pipeHandle.IsInvalid) { @@ -2831,13 +2978,24 @@ public override PSCredential Credential /// public override string ComputerName { get; set; } - internal override RunspaceConnectionInfo InternalCopy() + /// + /// Create a copy of the connection info object. + /// + /// Copy of the connection info object. + public override RunspaceConnectionInfo Clone() { VMConnectionInfo result = new VMConnectionInfo(Credential, VMGuid, ComputerName, ConfigurationName); return result; } - internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) + /// + /// Creates the appropriate client session transportmanager. + /// + /// Runspace/Pool instance Id. + /// Session name. + /// PSRemotingCryptoHelper instance. + /// Instance of VMHyperVSocketClientSessionTransportManager. + public override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) { return new VMHyperVSocketClientSessionTransportManager( this, @@ -2964,13 +3122,24 @@ public override string ComputerName set { throw new PSNotSupportedException(); } } - internal override RunspaceConnectionInfo InternalCopy() + /// + /// Create a copy of the connection info object. + /// + /// Copy of the connection info object. + public override RunspaceConnectionInfo Clone() { ContainerConnectionInfo newCopy = new ContainerConnectionInfo(ContainerProc); return newCopy; } - internal override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) + /// + /// Creates the appropriate client session transportmanager. + /// + /// Runspace/Pool instance Id. + /// Session name. + /// PSRemotingCryptoHelper object. + /// Instance of ContainerHyperVSocketClientSessionTransportManager + public override BaseClientSessionTransportManager CreateClientSessionTransportManager(Guid instanceId, string sessionName, PSRemotingCryptoHelper cryptoHelper) { if (ContainerProc.RuntimeId != Guid.Empty) { diff --git a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs index e863a7c795e..fb4807351c3 100644 --- a/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs +++ b/src/System.Management.Automation/engine/remoting/common/RunspacePoolStateInfo.cs @@ -17,7 +17,7 @@ namespace System.Management.Automation public sealed class RunspacePoolStateInfo { /// - /// State of the runspace pool when this event occured. + /// State of the runspace pool when this event occurred. /// public RunspacePoolState State { get; } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs index d99fbe21126..e26f3421cda 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/EncodeAndDecode.cs @@ -4,6 +4,7 @@ using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.Management.Automation; using System.Management.Automation.Host; using System.Management.Automation.Internal; using System.Management.Automation.Remoting; @@ -73,12 +74,13 @@ public RemotingEncodingException(string message, Exception innerException, Error /// internal static class RemotingConstants { - internal static readonly Version HostVersion = new Version(1, 0, 0, 0); + internal static readonly Version HostVersion = PSVersionInfo.PSVersion; - internal static readonly Version ProtocolVersionWin7RC = new Version(2, 0); - internal static readonly Version ProtocolVersionWin7RTM = new Version(2, 1); - internal static readonly Version ProtocolVersionWin8RTM = new Version(2, 2); - internal static readonly Version ProtocolVersionWin10RTM = new Version(2, 3); + internal static readonly Version ProtocolVersion_2_0 = new(2, 0); // Window 7 RC + internal static readonly Version ProtocolVersion_2_1 = new(2, 1); // Window 7 RTM + internal static readonly Version ProtocolVersion_2_2 = new(2, 2); // Window 8 RTM + internal static readonly Version ProtocolVersion_2_3 = new(2, 3); // Window 10 RTM + internal static readonly Version ProtocolVersion_2_4 = new(2, 4); // PowerShell 7.6 // Minor will be incremented for each change in PSRP client/server stack and new versions will be // forked on early major release/drop changes history. @@ -86,7 +88,15 @@ internal static class RemotingConstants // 2.102 to 2.103 - Key exchange protocol changes in M3 // 2.103 to 2.2 - Final ship protocol version value, no change to protocol // 2.2 to 2.3 - Enabling informational stream - internal static readonly Version ProtocolVersionCurrent = new Version(2, 3); + // 2.3 to 2.4 - Deprecate the 'Session_Key' exchange. The following messages are obsolete when both server and client are v2.4+: + // - PUBLIC_KEY + // - PUBLIC_KEY_REQUEST + // - ENCRYPTED_SESSION_KEY + // The padding algorithm 'RSAEncryptionPadding.Pkcs1' used in the 'Session_Key' exchange is NOT secure, and therefore, + // PSRP needs to be used on top of a secure transport and the 'Session_Key' doesn't add any extra security. + // So, we decided to deprecate the 'Session_Key' exchange in PSRP and skip encryption and decryption for 'SecureString' + // objects. Instead, we require the transport to be secure for secure data transfer between PSRP clients and servers. + internal static readonly Version ProtocolVersionCurrent = new(2, 4); internal static readonly Version ProtocolVersion = ProtocolVersionCurrent; // Used by remoting commands to add remoting specific note properties. internal static readonly string ComputerNameNoteProperty = "PSComputerName"; @@ -124,234 +134,6 @@ internal static class RemoteDataNameStrings // to client to let client know if the negotiation succeeded. internal const string IsNegotiationSucceeded = "IsNegotiationSucceeded"; - #region "PSv2 Tab Expansion Function" - - internal const string PSv2TabExpansionFunction = "TabExpansion"; - - /// - /// This is the PSv2 function for tab expansion. It's only for legacy purpose - used in - /// an interactive remote session from a win7 machine to a win8 machine (or later). - /// - internal const string PSv2TabExpansionFunctionText = @" - param($line, $lastWord) - & { - function Write-Members ($sep='.') - { - Invoke-Expression ('$_val=' + $_expression) - - $_method = [Management.Automation.PSMemberTypes] ` - 'Method,CodeMethod,ScriptMethod,ParameterizedProperty' - if ($sep -eq '.') - { - $params = @{view = 'extended','adapted','base'} - } - else - { - $params = @{static=$true} - } - - foreach ($_m in ,$_val | Get-Member @params $_pat | - Sort-Object membertype,name) - { - if ($_m.MemberType -band $_method) - { - # Return a method... - $_base + $_expression + $sep + $_m.name + '(' - } - else { - # Return a property... - $_base + $_expression + $sep + $_m.name - } - } - } - - # If a command name contains any of these chars, it needs to be quoted - $_charsRequiringQuotes = ('`&@''#{}()$,;|<> ' + ""`t"").ToCharArray() - - # If a variable name contains any of these characters it needs to be in braces - $_varsRequiringQuotes = ('-`&@''#{}()$,;|<> .\/' + ""`t"").ToCharArray() - - switch -regex ($lastWord) - { - # Handle property and method expansion rooted at variables... - # e.g. $a.b. - '(^.*)(\$(\w|:|\.)+)\.([*\w]*)$' { - $_base = $matches[1] - $_expression = $matches[2] - $_pat = $matches[4] + '*' - Write-Members - break; - } - - # Handle simple property and method expansion on static members... - # e.g. [datetime]::n - '(^.*)(\[(\w|\.|\+)+\])(\:\:|\.){0,1}([*\w]*)$' { - $_base = $matches[1] - $_expression = $matches[2] - $_pat = $matches[5] + '*' - Write-Members $(if (! $matches[4]) {'::'} else {$matches[4]}) - break; - } - - # Handle complex property and method expansion on static members - # where there are intermediate properties... - # e.g. [datetime]::now.d - '(^.*)(\[(\w|\.|\+)+\](\:\:|\.)(\w+\.)+)([*\w]*)$' { - $_base = $matches[1] # everything before the expression - $_expression = $matches[2].TrimEnd('.') # expression less trailing '.' - $_pat = $matches[6] + '*' # the member to look for... - Write-Members - break; - } - - # Handle variable name expansion... - '(^.*\$)([*\w:]+)$' { - $_prefix = $matches[1] - $_varName = $matches[2] - $_colonPos = $_varname.IndexOf(':') - if ($_colonPos -eq -1) - { - $_varName = 'variable:' + $_varName - $_provider = '' - } - else - { - $_provider = $_varname.Substring(0, $_colonPos+1) - } - - foreach ($_v in Get-ChildItem ($_varName + '*') | sort Name) - { - $_nameFound = $_v.name - $(if ($_nameFound.IndexOfAny($_varsRequiringQuotes) -eq -1) {'{0}{1}{2}'} - else {'{0}{{{1}{2}}}'}) -f $_prefix, $_provider, $_nameFound - } - - break; - } - - # Do completion on parameters... - '^-([*\w0-9]*)' { - $_pat = $matches[1] + '*' - - # extract the command name from the string - # first split the string into statements and pipeline elements - # This doesn't handle strings however. - $_command = [regex]::Split($line, '[|;=]')[-1] - - # Extract the trailing unclosed block e.g. ls | foreach { cp - if ($_command -match '\{([^\{\}]*)$') - { - $_command = $matches[1] - } - - # Extract the longest unclosed parenthetical expression... - if ($_command -match '\(([^()]*)$') - { - $_command = $matches[1] - } - - # take the first space separated token of the remaining string - # as the command to look up. Trim any leading or trailing spaces - # so you don't get leading empty elements. - $_command = $_command.TrimEnd('-') - $_command,$_arguments = $_command.Trim().Split() - - # now get the info object for it, -ArgumentList will force aliases to be resolved - # it also retrieves dynamic parameters - try - { - $_command = @(Get-Command -type 'Alias,Cmdlet,Function,Filter,ExternalScript' ` - -Name $_command -ArgumentList $_arguments)[0] - } - catch - { - # see if the command is an alias. If so, resolve it to the real command - if(Test-Path alias:\$_command) - { - $_command = @(Get-Command -Type Alias $_command)[0].Definition - } - - # If we were unsuccessful retrieving the command, try again without the parameters - $_command = @(Get-Command -type 'Cmdlet,Function,Filter,ExternalScript' ` - -Name $_command)[0] - } - - # remove errors generated by the command not being found, and break - if(-not $_command) { $error.RemoveAt(0); break; } - - # expand the parameter sets and emit the matching elements - # need to use psbase.Keys in case 'keys' is one of the parameters - # to the cmdlet - foreach ($_n in $_command.Parameters.psbase.Keys) - { - if ($_n -like $_pat) { '-' + $_n } - } - - break; - } - - # Tab complete against history either # or # - '^#(\w*)' { - $_pattern = $matches[1] - if ($_pattern -match '^[0-9]+$') - { - Get-History -ea SilentlyContinue -Id $_pattern | ForEach-Object { $_.CommandLine } - } - else - { - $_pattern = '*' + $_pattern + '*' - Get-History -Count 32767 | Sort-Object -Descending Id| ForEach-Object { $_.CommandLine } | where { $_ -like $_pattern } - } - - break; - } - - # try to find a matching command... - default { - # parse the script... - $_tokens = [System.Management.Automation.PSParser]::Tokenize($line, - [ref] $null) - - if ($_tokens) - { - $_lastToken = $_tokens[$_tokens.count - 1] - if ($_lastToken.Type -eq 'Command') - { - $_cmd = $_lastToken.Content - - # don't look for paths... - if ($_cmd.IndexOfAny('/\:') -eq -1) - { - # handle parsing errors - the last token string should be the last - # string in the line... - if ($lastword.Length -ge $_cmd.Length -and - $lastword.substring($lastword.length-$_cmd.length) -eq $_cmd) - { - $_pat = $_cmd + '*' - $_base = $lastword.substring(0, $lastword.length-$_cmd.length) - - # get files in current directory first, then look for commands... - $( try {Resolve-Path -ea SilentlyContinue -Relative $_pat } catch {} ; - try { $ExecutionContext.InvokeCommand.GetCommandName($_pat, $true, $false) | - Sort-Object -Unique } catch {} ) | - # If the command contains non-word characters (space, ) ] ; ) etc.) - # then it needs to be quoted and prefixed with & - ForEach-Object { - if ($_.IndexOfAny($_charsRequiringQuotes) -eq -1) { $_ } - elseif ($_.IndexOf('''') -ge 0) {'& ''{0}''' -f $_.Replace('''','''''') } - else { '& ''{0}''' -f $_ }} | - ForEach-Object {'{0}{1}' -f $_base,$_ } - } - } - } - } - } - } - } - "; - - #endregion "PSv2 Tab Expansion Function" - #region Host Related Strings internal const string CallId = "ci"; @@ -1600,8 +1382,6 @@ internal static RemoteDataObject GenerateClientSessionCapability(RemoteSessionCa Guid runspacePoolId) { PSObject temp = GenerateSessionCapability(capability); - temp.Properties.Add( - new PSNoteProperty(RemoteDataNameStrings.TimeZone, RemoteSessionCapability.GetCurrentTimeZoneInByteFormat())); return RemoteDataObject.CreateFrom(capability.RemotingDestination, RemotingDataType.SessionCapability, runspacePoolId, Guid.Empty, temp); } @@ -2089,7 +1869,7 @@ internal static object GetPowerShellOutput(object data) /// PSInvocationInfo. internal static PSInvocationStateInfo GetPowerShellStateInfo(object data) { - if (!(data is PSObject dataAsPSObject)) + if (data is not PSObject dataAsPSObject) { throw new PSRemotingDataStructureException( RemotingErrorIdStrings.DecodingErrorForPowerShellStateInfo); @@ -2357,7 +2137,7 @@ internal static RemoteStreamOptions GetRemoteStreamOptions(object data) /// RemoteSessionCapability object. internal static RemoteSessionCapability GetSessionCapability(object data) { - if (!(data is PSObject dataAsPSObject)) + if (data is not PSObject dataAsPSObject) { throw new PSRemotingDataStructureException( RemotingErrorIdStrings.CantCastRemotingDataToPSObject, data.GetType().FullName); @@ -2372,24 +2152,6 @@ internal static RemoteSessionCapability GetSessionCapability(object data) RemotingDestination.InvalidDestination, protocolVersion, psVersion, serializationVersion); - if (dataAsPSObject.Properties[RemoteDataNameStrings.TimeZone] != null) - { - // Binary deserialization of timezone info via BinaryFormatter is unsafe, - // so don't deserialize any untrusted client data using this API. - // - // In addition, the binary data being sent by the client doesn't represent - // the client's current TimeZone unless they somehow accessed the - // StandardName and DaylightName. These properties are initialized lazily - // by the .NET Framework, and would be populated by the server with local - // values anyways. - // - // So just return the CurrentTimeZone. - -#if !CORECLR // TimeZone Not In CoreCLR - result.TimeZone = TimeZone.CurrentTimeZone; -#endif - } - return result; } @@ -2405,7 +2167,7 @@ internal static bool ServerSupportsBatchInvocation(Runspace runspace) return false; } - return (runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersionWin8RTM); + return (runspace.GetRemoteProtocolVersion() >= RemotingConstants.ProtocolVersion_2_2); } } } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs index ee993615029..2c670b1eaaa 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteDebuggingCapability.cs @@ -13,7 +13,7 @@ namespace System.Management.Automation.Remoting /// version on the server. These capabilities will be used in remote debugging sessions to /// determine what is supported by the server. /// - internal class RemoteDebuggingCapability + internal sealed class RemoteDebuggingCapability { private readonly HashSet _supportedCommands = new HashSet(); @@ -43,14 +43,14 @@ private RemoteDebuggingCapability(Version powerShellVersion) } // Commands added in v5 - if (PSVersion.Major >= PSVersionInfo.PSV5Version.Major) + if (PSVersion.Major >= 5) { _supportedCommands.Add(RemoteDebuggingCommands.SetDebuggerStepMode); _supportedCommands.Add(RemoteDebuggingCommands.SetUnhandledBreakpointMode); } // Commands added in v7 - if (PSVersion.Major >= PSVersionInfo.PSV7Version.Major) + if (PSVersion.Major >= 7) { _supportedCommands.Add(RemoteDebuggingCommands.GetBreakpoint); _supportedCommands.Add(RemoteDebuggingCommands.SetBreakpoint); diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs index c29be13487b..79b920c22b5 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHost.cs @@ -188,10 +188,7 @@ internal void ExecuteVoidMethod(PSHost clientHost) } finally { - if (remoteRunspaceToClose != null) - { - remoteRunspaceToClose.Close(); - } + remoteRunspaceToClose?.Close(); } } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs index 3ffc278a817..cdaceda1610 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteHostEncoder.cs @@ -7,6 +7,7 @@ using System.Globalization; using System.Management.Automation.Host; using System.Reflection; +using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security; @@ -87,7 +88,7 @@ private static PSObject EncodeClassOrStruct(object obj) /// private static object DecodeClassOrStruct(PSObject psObject, Type type) { - object obj = FormatterServices.GetUninitializedObject(type); + object obj = RuntimeHelpers.GetUninitializedObject(type); // Field values cannot be null - because for null fields we simply don't transport them. foreach (PSPropertyInfo propertyInfo in psObject.Properties) diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs index 0cddf7d8524..add424b8703 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemoteSessionCapability.cs @@ -5,7 +5,6 @@ using System.IO; using System.Management.Automation.Host; using System.Management.Automation.Internal.Host; -using System.Runtime.Serialization.Formatters.Binary; using Dbg = System.Management.Automation.Diagnostics; @@ -25,8 +24,6 @@ internal class RemoteSessionCapability private readonly Version _serversion; private Version _protocolVersion; private readonly RemotingDestination _remotingDestination; - private static byte[] _timeZoneInByteFormat; - private TimeZoneInfo _timeZone; #endregion @@ -91,64 +88,6 @@ internal static RemoteSessionCapability CreateServerCapability() { return new RemoteSessionCapability(RemotingDestination.Client); } - - /// - /// This is static property which gets Current TimeZone in byte format - /// by using ByteFormatter. - /// This is static to make client generate this only once. - /// - internal static byte[] GetCurrentTimeZoneInByteFormat() - { - if (_timeZoneInByteFormat == null) - { - Exception e = null; - try - { - BinaryFormatter formatter = new BinaryFormatter(); - using (MemoryStream stream = new MemoryStream()) - { -#pragma warning disable SYSLIB0011 - formatter.Serialize(stream, TimeZoneInfo.Local); -#pragma warning restore SYSLIB0011 - stream.Seek(0, SeekOrigin.Begin); - byte[] result = new byte[stream.Length]; - stream.Read(result, 0, (int)stream.Length); - _timeZoneInByteFormat = result; - } - } - catch (ArgumentNullException ane) - { - e = ane; - } - catch (System.Runtime.Serialization.SerializationException sre) - { - e = sre; - } - catch (System.Security.SecurityException se) - { - e = se; - } - - // if there is any exception serializing the timezone information - // ignore it and dont try to serialize again. - if (e != null) - { - _timeZoneInByteFormat = Array.Empty(); - } - } - - return _timeZoneInByteFormat; - } - - /// - /// Gets the TimeZone of the destination machine. This may be null. - /// - internal TimeZoneInfo TimeZone - { - get { return _timeZone; } - - set { _timeZone = value; } - } } /// @@ -171,7 +110,7 @@ internal enum HostDefaultDataId /// /// The HostDefaultData class. /// - internal class HostDefaultData + internal sealed class HostDefaultData { /// /// Data. @@ -448,12 +387,18 @@ private static void CheckHostChain(PSHost host, ref bool isHostNull, ref bool is isHostNull = false; // Verify that the UI is not null. - if (host.UI == null) { return; } + if (host.UI == null) + { + return; + } isHostUINull = false; // Verify that the raw UI is not null. - if (host.UI.RawUI == null) { return; } + if (host.UI.RawUI == null) + { + return; + } isHostRawUINull = false; } diff --git a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs index 0fed6cc759d..14cad7613b8 100644 --- a/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs +++ b/src/System.Management.Automation/engine/remoting/common/WireDataFormat/RemotingDataObject.cs @@ -7,11 +7,11 @@ namespace System.Management.Automation.Remoting { - /// + /// /// This is the object used by Runspace,pipeline,host to send data /// to remote end. Transport layer owns breaking this into fragments /// and sending to other end - /// + /// internal class RemoteDataObject { #region Private Members @@ -267,7 +267,7 @@ private static Guid DeserializeGuid(Stream serializedDataStream) #endregion } - internal class RemoteDataObject : RemoteDataObject + internal sealed class RemoteDataObject : RemoteDataObject { #region Constructors / Factory diff --git a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs index 8517fb059f5..c451ba32f45 100644 --- a/src/System.Management.Automation/engine/remoting/common/fragmentor.cs +++ b/src/System.Management.Automation/engine/remoting/common/fragmentor.cs @@ -432,7 +432,7 @@ internal static int GetBlobLength(byte[] fragmentBytes, int startIndex) /// internal class SerializedDataStream : Stream, IDisposable { - [TraceSourceAttribute("SerializedDataStream", "SerializedDataStream")] + [TraceSource("SerializedDataStream", "SerializedDataStream")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("SerializedDataStream", "SerializedDataStream"); #region Global Constants @@ -757,11 +757,11 @@ private void WriteCurrentFragmentAndReset() PSEtwLog.LogAnalyticVerbose( PSEventId.SentRemotingFragment, PSOpcode.Send, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - (Int64)(_currentFragment.ObjectId), - (Int64)(_currentFragment.FragmentId), + (long)(_currentFragment.ObjectId), + (long)(_currentFragment.FragmentId), _currentFragment.IsStartFragment ? 1 : 0, _currentFragment.IsEndFragment ? 1 : 0, - (UInt32)(_currentFragment.BlobLength), + (uint)(_currentFragment.BlobLength), new PSETWBinaryBlob(_currentFragment.Blob, 0, _currentFragment.BlobLength)); // finally write into memory stream diff --git a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs index 4e755893886..f97b2b21d1f 100644 --- a/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs +++ b/src/System.Management.Automation/engine/remoting/common/psstreamobject.cs @@ -120,10 +120,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) ErrorRecord errorRecord = (ErrorRecord)this.Value; errorRecord.PreserveInvocationInfoOnce = true; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteError(errorRecord, overrideInquire); - } + mshCommandRuntime?.WriteError(errorRecord, overrideInquire); } break; @@ -133,10 +130,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); - } + mshCommandRuntime?.WriteDebug(debugRecord, overrideInquire); } break; @@ -146,10 +140,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); - } + mshCommandRuntime?.WriteWarning(warningRecord, overrideInquire); } break; @@ -159,10 +150,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); - } + mshCommandRuntime?.WriteVerbose(verboseRecord, overrideInquire); } break; @@ -170,10 +158,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) case PSStreamObjectType.Progress: { MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteProgress((ProgressRecord)Value, overrideInquire); - } + mshCommandRuntime?.WriteProgress((ProgressRecord)Value, overrideInquire); } break; @@ -181,10 +166,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) case PSStreamObjectType.Information: { MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteInformation((InformationRecord)Value, overrideInquire); - } + mshCommandRuntime?.WriteInformation((InformationRecord)Value, overrideInquire); } break; @@ -193,10 +175,7 @@ public void WriteStreamObject(Cmdlet cmdlet, bool overrideInquire = false) { WarningRecord warningRecord = (WarningRecord)Value; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.AppendWarningVarList(warningRecord); - } + mshCommandRuntime?.AppendWarningVarList(warningRecord); } break; @@ -246,13 +225,22 @@ private static void GetIdentifierInfo(string message, out Guid jobInstanceId, ou jobInstanceId = Guid.Empty; computerName = string.Empty; - if (message == null) return; - string[] parts = message.Split(Utils.Separators.Colon, 3); + if (message == null) + { + return; + } + + string[] parts = message.Split(':', 3); - if (parts.Length != 3) return; + if (parts.Length != 3) + { + return; + } if (!Guid.TryParse(parts[0], out jobInstanceId)) + { jobInstanceId = Guid.Empty; + } computerName = parts[1]; } @@ -311,10 +299,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq errorRecord.PreserveInvocationInfoOnce = true; MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteError(errorRecord, overrideInquire); - } + mshCommandRuntime?.WriteError(errorRecord, overrideInquire); } break; @@ -324,10 +309,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq string warning = (string)Value; WarningRecord warningRecord = new WarningRecord(warning); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteWarning(warningRecord, overrideInquire); - } + mshCommandRuntime?.WriteWarning(warningRecord, overrideInquire); } break; @@ -337,10 +319,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq string verbose = (string)Value; VerboseRecord verboseRecord = new VerboseRecord(verbose); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteVerbose(verboseRecord, overrideInquire); - } + mshCommandRuntime?.WriteVerbose(verboseRecord, overrideInquire); } break; @@ -365,10 +344,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq } MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteProgress(progressRecord, overrideInquire); - } + mshCommandRuntime?.WriteProgress(progressRecord, overrideInquire); } break; @@ -378,10 +354,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq string debug = (string)Value; DebugRecord debugRecord = new DebugRecord(debug); MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteDebug(debugRecord, overrideInquire); - } + mshCommandRuntime?.WriteDebug(debugRecord, overrideInquire); } break; @@ -411,10 +384,7 @@ internal void WriteStreamObject(Cmdlet cmdlet, Guid instanceId, bool overrideInq } MshCommandRuntime mshCommandRuntime = cmdlet.CommandRuntime as MshCommandRuntime; - if (mshCommandRuntime != null) - { - mshCommandRuntime.WriteInformation(informationRecord, overrideInquire); - } + mshCommandRuntime?.WriteInformation(informationRecord, overrideInquire); } break; @@ -470,10 +440,7 @@ private static void InvokeCmdletMethodAndWaitForResults(CmdletMethodInvoker /// - /// Optional parameters required by the resource string formating information. + /// Optional parameters required by the resource string formatting information. /// /// /// The formatted localized string. @@ -282,7 +283,6 @@ internal static string FormatResourceString(string resourceString, params object /// /// This exception is used by remoting code to indicated a data structure handler related error. /// - [Serializable] public class PSRemotingDataStructureException : RuntimeException { #region Constructors @@ -297,7 +297,7 @@ public PSRemotingDataStructureException() } /// - /// This constuctor takes a localized string as the error message. + /// This constructor takes a localized string as the error message. /// /// /// A localized string as an error message. @@ -309,7 +309,7 @@ public PSRemotingDataStructureException(string message) } /// - /// This constuctor takes a localized string as the error message, and an inner exception. + /// This constructor takes a localized string as the error message, and an inner exception. /// /// /// A localized string as an error message. @@ -339,7 +339,7 @@ internal PSRemotingDataStructureException(string resourceString, params object[] } /// - /// This constuctor takes an inner exception and an error id. + /// This constructor takes an inner exception and an error id. /// /// /// Inner exception. @@ -361,9 +361,10 @@ internal PSRemotingDataStructureException(Exception innerException, string resou /// /// /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSRemotingDataStructureException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Constructors @@ -381,7 +382,6 @@ private void SetDefaultErrorRecord() /// /// This exception is used by remoting code to indicate an error condition in network operations. /// - [Serializable] public class PSRemotingTransportException : RuntimeException { private int _errorCode; @@ -445,7 +445,7 @@ internal PSRemotingTransportException(PSRemotingErrorId errorId, string resource } /// - /// This constuctor takes an inner exception and an error id. + /// This constructor takes an inner exception and an error id. /// /// /// Inner exception. @@ -470,38 +470,14 @@ internal PSRemotingTransportException(Exception innerException, string resourceS /// /// 1. info is null. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSRemotingTransportException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - _errorCode = info.GetInt32("ErrorCode"); - _transportMessage = info.GetString("TransportMessage"); + throw new NotSupportedException(); } #endregion Constructors - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - info.AddValue("ErrorCode", _errorCode); - info.AddValue("TransportMessage", _transportMessage); - } - /// /// Set the default ErrorRecord. /// @@ -548,7 +524,6 @@ public string TransportMessage /// This exception is used by PowerShell's remoting infrastructure to notify a URI redirection /// exception. /// - [Serializable] public class PSRemotingTransportRedirectException : PSRemotingTransportException { #region Constructor @@ -588,7 +563,7 @@ public PSRemotingTransportRedirectException(string message, Exception innerExcep } /// - /// This constuctor takes an inner exception and an error id. + /// This constructor takes an inner exception and an error id. /// /// /// Inner exception. @@ -612,15 +587,10 @@ internal PSRemotingTransportRedirectException(Exception innerException, string r /// /// 1. info is null. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSRemotingTransportRedirectException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - RedirectLocation = info.GetString("RedirectLocation"); + throw new NotSupportedException(); } /// @@ -646,27 +616,6 @@ internal PSRemotingTransportRedirectException(string redirectLocation, PSRemotin #endregion - #region Public overrides - - /// - /// Serializes the exception data. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - // If there are simple fields, serialize them with info.AddValue - info.AddValue("RedirectLocation", RedirectLocation); - } - - #endregion - #region Properties /// /// String specifying a redirect location. @@ -679,13 +628,12 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont /// /// This exception is used by PowerShell Direct errors. /// - [Serializable] public class PSDirectException : RuntimeException { #region Constructor /// - /// This constuctor takes a localized string as the error message. + /// This constructor takes a localized string as the error message. /// /// /// A localized string as an error message. diff --git a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs index afccc28362a..7d4a88e98bd 100644 --- a/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs +++ b/src/System.Management.Automation/engine/remoting/common/throttlemanager.cs @@ -117,7 +117,7 @@ internal abstract class IThrottleOperation /// need not be called on the operation (this can be when the /// operation has stop completed or stop has been called and is /// pending) - /// + /// internal bool IgnoreStop { get @@ -532,10 +532,7 @@ private void StartOneOperationFromQueue() } } - if (operation != null) - { - operation.StartOperation(); - } + operation?.StartOperation(); } /// diff --git a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs index 5d12914074c..c3cf3b278aa 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/BaseTransportManager.cs @@ -33,27 +33,81 @@ namespace System.Management.Automation.Remoting { #region TransportErrorOccuredEventArgs - internal enum TransportMethodEnum + /// + /// Transport method for error reporting. + /// + public enum TransportMethodEnum { + /// + /// CreateShellEx + /// CreateShellEx = 0, + + /// + /// RunShellCommandEx + /// RunShellCommandEx = 1, + + /// + /// SendShellInputEx + /// SendShellInputEx = 2, + + /// + /// ReceiveShellOutputEx + /// ReceiveShellOutputEx = 3, + + /// + /// CloseShellOperationEx + /// CloseShellOperationEx = 4, + + /// + /// CommandInputEx + /// CommandInputEx = 5, + + /// + /// ReceiveCommandOutputEx + /// ReceiveCommandOutputEx = 6, + + /// + /// DisconnectShellEx + /// DisconnectShellEx = 7, + + /// + /// ReconnectShellEx + /// ReconnectShellEx = 8, + + /// + /// ConnectShellEx + /// ConnectShellEx = 9, + + /// + /// ReconnectShellCommandEx + /// ReconnectShellCommandEx = 10, + + /// + /// ConnectShellCommandEx + /// ConnectShellCommandEx = 11, + + /// + /// Unknown + /// Unknown = 12, } /// - /// Event arguments passed to TransportErrorOccured handlers. + /// Event arguments passed to TransportErrorOccurred handlers. /// - internal class TransportErrorOccuredEventArgs : EventArgs + public sealed class TransportErrorOccuredEventArgs : EventArgs { /// /// Constructor. @@ -62,9 +116,10 @@ internal class TransportErrorOccuredEventArgs : EventArgs /// Error occurred. /// /// - /// The transport method that raised the error + /// The transport method that raised the error. /// - internal TransportErrorOccuredEventArgs(PSRemotingTransportException e, + public TransportErrorOccuredEventArgs( + PSRemotingTransportException e, TransportMethodEnum m) { Exception = e; @@ -136,11 +191,11 @@ internal CreateCompleteEventArgs( /// Contains implementation that is common to both client and server /// transport managers. /// - internal abstract class BaseTransportManager : IDisposable + public abstract class BaseTransportManager : IDisposable { #region tracer - [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] + [TraceSource("Transport", "Traces BaseWSManTransportManager")] private static readonly PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion @@ -158,7 +213,7 @@ internal abstract class BaseTransportManager : IDisposable // This value instructs the server to use whatever setting it has for idle timeout. internal const int UseServerDefaultIdleTimeout = -1; - internal const uint UseServerDefaultIdleTimeoutUInt = UInt32.MaxValue; + internal const uint UseServerDefaultIdleTimeoutUInt = uint.MaxValue; // Minimum allowed idle timeout time is 60 seconds. internal const int MinimumIdleTimeout = 60 * 1000; @@ -206,7 +261,7 @@ internal abstract class BaseTransportManager : IDisposable #region Constructor - protected BaseTransportManager(PSRemotingCryptoHelper cryptoHelper) + internal BaseTransportManager(PSRemotingCryptoHelper cryptoHelper) { CryptoHelper = cryptoHelper; // create a common fragmentor used by this transport manager to send and receive data. @@ -308,8 +363,9 @@ internal void ProcessRawData(byte[] data, if (!shouldProcess) { // we dont support this stream..so ignore the data - Dbg.Assert(false, - string.Format(CultureInfo.InvariantCulture, "Data should be from one of the streams : {0} or {1} or {2}", + Dbg.Assert(false, string.Format( + CultureInfo.InvariantCulture, + "Data should be from one of the streams : {0} or {1} or {2}", WSManNativeApi.WSMAN_STREAM_ID_STDIN, WSManNativeApi.WSMAN_STREAM_ID_STDOUT, WSManNativeApi.WSMAN_STREAM_ID_PROMPTRESPONSE)); @@ -334,9 +390,9 @@ internal void OnDataAvailableCallback(RemoteDataObject remoteObject) PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, remoteObject.RunspacePoolId.ToString(), remoteObject.PowerShellId.ToString(), - (UInt32)(remoteObject.Destination), - (UInt32)(remoteObject.DataType), - (UInt32)(remoteObject.TargetInterface)); + (uint)(remoteObject.Destination), + (uint)(remoteObject.DataType), + (uint)(remoteObject.TargetInterface)); // This might throw exceptions which the caller handles. PowerShellGuidObserver.SafeInvoke(remoteObject.PowerShellId, EventArgs.Empty); @@ -361,7 +417,7 @@ public void MigrateDataReadyEventHandlers(BaseTransportManager transportManager) /// Raise the error handlers. /// /// - internal virtual void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) + public virtual void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) { WSManTransportErrorOccured.SafeInvoke(this, eventArgs); } @@ -393,7 +449,10 @@ public void Dispose() System.GC.SuppressFinalize(this); } - internal virtual void Dispose(bool isDisposing) + /// + /// Dispose resources. + /// + protected virtual void Dispose(bool isDisposing) { if (isDisposing) { @@ -407,18 +466,21 @@ internal virtual void Dispose(bool isDisposing) namespace System.Management.Automation.Remoting.Client { - internal abstract class BaseClientTransportManager : BaseTransportManager, IDisposable + /// + /// Remoting base client transport manager. + /// + public abstract class BaseClientTransportManager : BaseTransportManager, IDisposable { #region Tracer - [TraceSourceAttribute("ClientTransport", "Traces ClientTransportManager")] - protected static PSTraceSource tracer = PSTraceSource.GetTracer("ClientTransport", "Traces ClientTransportManager"); + [TraceSource("ClientTransport", "Traces ClientTransportManager")] + internal static PSTraceSource tracer = PSTraceSource.GetTracer("ClientTransport", "Traces ClientTransportManager"); #endregion #region Data - protected bool isClosed; - protected object syncObject = new object(); - protected PrioritySendDataCollection dataToBeSent; + internal bool isClosed; + internal object syncObject = new object(); + internal PrioritySendDataCollection dataToBeSent; // used to handle callbacks from the server..these are used to synchronize received callbacks private readonly Queue _callbackNotificationQueue; private readonly ReceiveDataCollection.OnDataAvailableCallback _onDataAvailableCallback; @@ -429,13 +491,13 @@ internal abstract class BaseClientTransportManager : BaseTransportManager, IDisp // this is used log crimson messages. // keeps track of whether a receive request has been placed on transport - protected bool receiveDataInitiated; + internal bool receiveDataInitiated; #endregion #region Constructors - protected BaseClientTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) + internal BaseClientTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(cryptoHelper) { RunspacePoolInstanceId = runspaceId; @@ -933,14 +995,17 @@ internal class CallbackNotificationInformation #region Abstract / Virtual methods - internal abstract void CreateAsync(); + /// + /// Create the transport manager and initiate connection. + /// + public abstract void CreateAsync(); internal abstract void ConnectAsync(); /// /// The caller should make sure the call is synchronized. /// - internal virtual void CloseAsync() + public virtual void CloseAsync() { // Clear the send collection dataToBeSent.Clear(); @@ -998,7 +1063,10 @@ internal virtual void PrepareForConnect() } } - internal override void Dispose(bool isDisposing) + /// + /// Dispose resources. + /// + protected override void Dispose(bool isDisposing) { // clear event handlers this.CreateCompleted = null; @@ -1014,11 +1082,14 @@ internal override void Dispose(bool isDisposing) #endregion } - internal abstract class BaseClientSessionTransportManager : BaseClientTransportManager, IDisposable + /// + /// Remoting base client session transport manager. + /// + public abstract class BaseClientSessionTransportManager : BaseClientTransportManager, IDisposable { #region Constructors - protected BaseClientSessionTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) + internal BaseClientSessionTransportManager(Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) { } @@ -1167,7 +1238,7 @@ internal void RaiseSignalCompleted() #region Overrides - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); @@ -1289,10 +1360,7 @@ internal void SendDataToClient(RemoteDataObject data, bool flush, bool rep data.Data); if (_isSerializing) { - if (_dataToBeSentQueue == null) - { - _dataToBeSentQueue = new Queue>(); - } + _dataToBeSentQueue ??= new Queue>(); _dataToBeSentQueue.Enqueue(new Tuple(dataToBeSent, flush, reportPending)); return; @@ -1346,8 +1414,8 @@ private void OnDataAvailable(byte[] dataToSend, bool isEndFragment) _runspacePoolInstanceId.ToString(), _powerShellInstanceId.ToString(), dataToSend.Length.ToString(CultureInfo.InvariantCulture), - (UInt32)_dataType, - (UInt32)_targetInterface); + (uint)_dataType, + (uint)_targetInterface); SendDataToClient(dataToSend, isEndFragment && _shouldFlushData, _reportAsPending, isEndFragment); } diff --git a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs index 6cde06cea36..07e17e8b63a 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/InitialSessionStateProvider.cs @@ -22,6 +22,8 @@ namespace System.Management.Automation.Remoting { + #region WSMan endpoint configuration + /// /// This struct is used to represent contents from configuration xml. The /// XML is passed to plugins by WSMan API. @@ -56,6 +58,8 @@ internal class ConfigurationDataFromXML #endregion + #region Fields + internal string StartupScript; // this field is used only by an Out-Of-Process (IPC) server process internal string InitializationScriptForOutOfProcessRunspace; @@ -71,6 +75,10 @@ internal class ConfigurationDataFromXML internal PSSessionConfigurationData SessionConfigurationData; internal string ConfigFilePath; + #endregion + + #region Methods + /// /// Using optionName and optionValue updates the current object. /// @@ -278,15 +286,9 @@ internal static ConfigurationDataFromXML Create(string initializationParameters) } // assign defaults after parsing the xml content. - if (result.MaxReceivedObjectSizeMB == null) - { - result.MaxReceivedObjectSizeMB = BaseTransportManager.MaximumReceivedObjectSize; - } + result.MaxReceivedObjectSizeMB ??= BaseTransportManager.MaximumReceivedObjectSize; - if (result.MaxReceivedCommandSizeMB == null) - { - result.MaxReceivedCommandSizeMB = BaseTransportManager.MaximumReceivedDataSize; - } + result.MaxReceivedCommandSizeMB ??= BaseTransportManager.MaximumReceivedDataSize; return result; } @@ -324,6 +326,8 @@ internal PSSessionConfiguration CreateEndPointConfigurationInstance() throw PSTraceSource.NewArgumentException("typeToLoad", RemotingErrorIdStrings.UnableToLoadType, EndPointConfigurationTypeName, ConfigurationDataFromXML.INITPARAMETERSTOKEN); } + + #endregion } /// @@ -336,7 +340,7 @@ public abstract class PSSessionConfiguration : IDisposable /// /// Tracer for Server Remote session. /// - [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] + [TraceSource("ServerRemoteSession", "ServerRemoteSession")] private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); #endregion tracer @@ -450,7 +454,8 @@ protected virtual void Dispose(bool isDisposing) ... */ - internal static ConfigurationDataFromXML LoadEndPointConfiguration(string shellId, + internal static ConfigurationDataFromXML LoadEndPointConfiguration( + string shellId, string initializationParameters) { ConfigurationDataFromXML configData = null; @@ -798,6 +803,8 @@ private static string /// internal sealed class DefaultRemotePowerShellConfiguration : PSSessionConfiguration { + #region Method overrides + /// /// /// @@ -805,22 +812,23 @@ internal sealed class DefaultRemotePowerShellConfiguration : PSSessionConfigurat public override InitialSessionState GetInitialSessionState(PSSenderInfo senderInfo) { InitialSessionState result = InitialSessionState.CreateDefault2(); + // TODO: Remove this after RDS moved to $using - if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } + if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) + { + PSSessionConfigurationData.IsServerManager = true; + } return result; } public override InitialSessionState GetInitialSessionState(PSSessionConfigurationData sessionConfigurationData, PSSenderInfo senderInfo, string configProviderId) { - if (sessionConfigurationData == null) - throw new ArgumentNullException(nameof(sessionConfigurationData)); + ArgumentNullException.ThrowIfNull(sessionConfigurationData); - if (senderInfo == null) - throw new ArgumentNullException(nameof(senderInfo)); + ArgumentNullException.ThrowIfNull(senderInfo); - if (configProviderId == null) - throw new ArgumentNullException(nameof(configProviderId)); + ArgumentNullException.ThrowIfNull(configProviderId); InitialSessionState sessionState = InitialSessionState.CreateDefault2(); // now get all the modules in the specified path and import the same @@ -848,13 +856,22 @@ public override InitialSessionState GetInitialSessionState(PSSessionConfiguratio } // TODO: Remove this after RDS moved to $using - if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) { PSSessionConfigurationData.IsServerManager = true; } + if (senderInfo.ConnectionString != null && senderInfo.ConnectionString.Contains("MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8")) + { + PSSessionConfigurationData.IsServerManager = true; + } return sessionState; } + + #endregion } - #region Declarative Initial Session Configuration + #endregion + + #region Declarative InitialSession Configuration + + #region Supporting types /// /// Specifies type of initial session state to use. Valid values are Empty and Default. @@ -898,6 +915,10 @@ internal ConfigTypeEntry(string key, TypeValidationCallback callback) } } + #endregion + + #region ConfigFileConstants + /// /// Configuration file constants. /// @@ -949,41 +970,41 @@ internal static class ConfigFileConstants internal static readonly string VisibleExternalCommands = "VisibleExternalCommands"; internal static readonly ConfigTypeEntry[] ConfigFileKeys = new ConfigTypeEntry[] { - new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)), - new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(CompanyName, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(Copyright, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(Description, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(EnforceInputParameterValidation,new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), - new ConfigTypeEntry(EnvironmentVariables, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)), - new ConfigTypeEntry(ExecutionPolicy, new ConfigTypeEntry.TypeValidationCallback(ExecutionPolicyValidationCallback)), - new ConfigTypeEntry(FormatsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(FunctionDefinitions, new ConfigTypeEntry.TypeValidationCallback(FunctionDefinitionsTypeValidationCallback)), - new ConfigTypeEntry(GMSAAccount, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(Guid, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(LanguageMode, new ConfigTypeEntry.TypeValidationCallback(LanguageModeValidationCallback)), - new ConfigTypeEntry(ModulesToImport, new ConfigTypeEntry.TypeValidationCallback(StringOrHashtableArrayTypeValidationCallback)), - new ConfigTypeEntry(MountUserDrive, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), - new ConfigTypeEntry(PowerShellVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(RequiredGroups, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)), - new ConfigTypeEntry(RoleCapabilities, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(RoleCapabilityFiles, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(RoleDefinitions, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)), - new ConfigTypeEntry(RunAsVirtualAccount, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), - new ConfigTypeEntry(RunAsVirtualAccountGroups, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(SchemaVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(ScriptsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)), - new ConfigTypeEntry(TranscriptDirectory, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), - new ConfigTypeEntry(TypesToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(UserDriveMaxSize, new ConfigTypeEntry.TypeValidationCallback(IntegerTypeValidationCallback)), - new ConfigTypeEntry(VariableDefinitions, new ConfigTypeEntry.TypeValidationCallback(VariableDefinitionsTypeValidationCallback)), - new ConfigTypeEntry(VisibleAliases, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(VisibleCmdlets, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(VisibleFunctions, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(VisibleProviders, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), - new ConfigTypeEntry(VisibleExternalCommands, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(AliasDefinitions, new ConfigTypeEntry.TypeValidationCallback(AliasDefinitionsTypeValidationCallback)), + new ConfigTypeEntry(AssembliesToLoad, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(Author, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(CompanyName, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(Copyright, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(Description, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(EnforceInputParameterValidation, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), + new ConfigTypeEntry(EnvironmentVariables, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)), + new ConfigTypeEntry(ExecutionPolicy, new ConfigTypeEntry.TypeValidationCallback(ExecutionPolicyValidationCallback)), + new ConfigTypeEntry(FormatsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(FunctionDefinitions, new ConfigTypeEntry.TypeValidationCallback(FunctionDefinitionsTypeValidationCallback)), + new ConfigTypeEntry(GMSAAccount, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(Guid, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(LanguageMode, new ConfigTypeEntry.TypeValidationCallback(LanguageModeValidationCallback)), + new ConfigTypeEntry(ModulesToImport, new ConfigTypeEntry.TypeValidationCallback(StringOrHashtableArrayTypeValidationCallback)), + new ConfigTypeEntry(MountUserDrive, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), + new ConfigTypeEntry(PowerShellVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(RequiredGroups, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)), + new ConfigTypeEntry(RoleCapabilities, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(RoleCapabilityFiles, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(RoleDefinitions, new ConfigTypeEntry.TypeValidationCallback(HashtableTypeValidationCallback)), + new ConfigTypeEntry(RunAsVirtualAccount, new ConfigTypeEntry.TypeValidationCallback(BooleanTypeValidationCallback)), + new ConfigTypeEntry(RunAsVirtualAccountGroups, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(SchemaVersion, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(ScriptsToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(SessionType, new ConfigTypeEntry.TypeValidationCallback(ISSValidationCallback)), + new ConfigTypeEntry(TranscriptDirectory, new ConfigTypeEntry.TypeValidationCallback(StringTypeValidationCallback)), + new ConfigTypeEntry(TypesToProcess, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(UserDriveMaxSize, new ConfigTypeEntry.TypeValidationCallback(IntegerTypeValidationCallback)), + new ConfigTypeEntry(VariableDefinitions, new ConfigTypeEntry.TypeValidationCallback(VariableDefinitionsTypeValidationCallback)), + new ConfigTypeEntry(VisibleAliases, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(VisibleCmdlets, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(VisibleFunctions, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(VisibleProviders, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), + new ConfigTypeEntry(VisibleExternalCommands, new ConfigTypeEntry.TypeValidationCallback(StringArrayTypeValidationCallback)), }; /// @@ -1355,6 +1376,8 @@ private static bool StringOrHashtableArrayTypeValidationCallback(string key, obj } } + #endregion + #region DISC Utilities /// @@ -1681,6 +1704,8 @@ internal static void ValidateRoleDefinitions(IDictionary roleDefinitions) #endregion + #region DISCPowerShellConfiguration + /// /// Creates an initial session state based on the configuration language for PSSC files. /// @@ -1706,13 +1731,14 @@ internal Hashtable ConfigHash /// target session. If you have a WindowsPrincipal for a user, for example, create a Function that /// checks windowsPrincipal.IsInRole(). /// - internal DISCPowerShellConfiguration(string configFile, Func roleVerifier) + /// Validate file for supported configuration options. + internal DISCPowerShellConfiguration( + string configFile, + Func roleVerifier, + bool validateFile = false) { _configFile = configFile; - if (roleVerifier == null) - { - roleVerifier = (role) => false; - } + roleVerifier ??= static (role) => false; Runspace backupRunspace = Runspace.DefaultRunspace; @@ -1726,6 +1752,12 @@ internal DISCPowerShellConfiguration(string configFile, Func roleV configFile, out scriptName); _configHash = DISCUtils.LoadConfigFile(Runspace.DefaultRunspace.ExecutionContext, script); + + if (validateFile) + { + DISCFileValidation.ValidateContents(_configHash); + } + MergeRoleRulesIntoConfigHash(roleVerifier); MergeRoleCapabilitiesIntoConfigHash(); @@ -1901,13 +1933,13 @@ private static string GetRoleCapabilityPath(string roleCapability) string moduleName = "*"; if (roleCapability.Contains('\\')) { - string[] components = roleCapability.Split(Utils.Separators.Backslash, 2); + string[] components = roleCapability.Split('\\', 2); moduleName = components[0]; roleCapability = components[1]; } // Go through each directory in the module path - string[] modulePaths = ModuleIntrinsics.GetModulePath().Split(Utils.Separators.PathSeparator); + string[] modulePaths = ModuleIntrinsics.GetModulePath().Split(Path.PathSeparator); foreach (string path in modulePaths) { try @@ -2446,7 +2478,7 @@ private static void ProcessVisibleCommands(InitialSessionState iss, object[] com // Parameters = A dictionary of parameter names -> Modifications // Modifications = A dictionary of modification types (ValidatePattern, ValidateSet) to the interim value // for that attribute, as a HashSet of strings. For ValidateSet, this will be used as a collection of strings - // directly during proxy generation. For For ValidatePattern, it will be combined into a regex + // directly during proxy generation. For ValidatePattern, it will be combined into a regex // like: '^(Pattern1|Pattern2|Pattern3)$' during proxy generation. Dictionary commandModifications = new Dictionary(StringComparer.OrdinalIgnoreCase); @@ -2804,7 +2836,7 @@ internal static Hashtable[] TryGetHashtableArray(object hashObj) for (int i = 0; i < hashArray.Length; i++) { - if (!(objArray[i] is Hashtable hash)) + if (objArray[i] is not Hashtable hash) { return null; } @@ -2890,4 +2922,110 @@ internal static T[] TryGetObjectsOfType(object hashObj, IEnumerable typ } } #endregion + + #region DISCFileValidation + + internal static class DISCFileValidation + { + // Set of supported configuration options for a PowerShell InitialSessionState. +#if UNIX + private static readonly HashSet SupportedConfigOptions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "AliasDefinitions", + "AssembliesToLoad", + "Author", + "CompanyName", + "Copyright", + "Description", + "EnvironmentVariables", + "FormatsToProcess", + "FunctionDefinitions", + "GUID", + "LanguageMode", + "ModulesToImport", + "MountUserDrive", + "SchemaVersion", + "ScriptsToProcess", + "SessionType", + "TranscriptDirectory", + "TypesToProcess", + "UserDriveMaximumSize", + "VisibleAliases", + "VisibleCmdlets", + "VariableDefinitions", + "VisibleExternalCommands", + "VisibleFunctions", + "VisibleProviders" + }; +#else + private static readonly HashSet SupportedConfigOptions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "AliasDefinitions", + "AssembliesToLoad", + "Author", + "CompanyName", + "Copyright", + "Description", + "EnvironmentVariables", + "ExecutionPolicy", + "FormatsToProcess", + "FunctionDefinitions", + "GUID", + "LanguageMode", + "ModulesToImport", + "MountUserDrive", + "SchemaVersion", + "ScriptsToProcess", + "SessionType", + "TranscriptDirectory", + "TypesToProcess", + "UserDriveMaximumSize", + "VisibleAliases", + "VisibleCmdlets", + "VariableDefinitions", + "VisibleExternalCommands", + "VisibleFunctions", + "VisibleProviders" + }; +#endif + + // These are configuration options for WSMan (WinRM) endpoint configurations, that + // appear in .pssc files, but are not part of PowerShell InitialSessionState. + private static readonly HashSet UnsupportedConfigOptions = new HashSet(StringComparer.OrdinalIgnoreCase) + { + "GroupManagedServiceAccount", + "PowerShellVersion", + "RequiredGroups", + "RoleDefinitions", + "RunAsVirtualAccount", + "RunAsVirtualAccountGroups" + }; + + internal static void ValidateContents(Hashtable configHash) + { + foreach (var key in configHash.Keys) + { + if (key is not string keyName) + { + throw new PSInvalidOperationException(RemotingErrorIdStrings.DISCInvalidConfigKeyType); + } + + if (UnsupportedConfigOptions.Contains(keyName)) + { + throw new PSInvalidOperationException( + StringUtil.Format(RemotingErrorIdStrings.DISCUnsupportedConfigName, keyName)); + } + + if (!SupportedConfigOptions.Contains(keyName)) + { + throw new PSInvalidOperationException( + StringUtil.Format(RemotingErrorIdStrings.DISCUnknownConfigName, keyName)); + } + } + } + } + + #endregion + + #endregion } diff --git a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs index b8f6da13c17..47ff6270dba 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/OutOfProcTransportManager.cs @@ -75,7 +75,8 @@ static OutOfProcessUtils() internal static string CreateDataPacket(byte[] data, DataPriorityType streamType, Guid psGuid) { - string result = string.Format(CultureInfo.InvariantCulture, + string result = string.Format( + CultureInfo.InvariantCulture, "<{0} {1}='{2}' {3}='{4}'>{5}", PS_OUT_OF_PROC_DATA_TAG, PS_OUT_OF_PROC_STREAM_ATTRIBUTE, @@ -131,7 +132,8 @@ internal static string CreateSignalAckPacket(Guid psGuid) /// private static string CreatePSGuidPacket(string element, Guid psGuid) { - string result = string.Format(CultureInfo.InvariantCulture, + string result = string.Format( + CultureInfo.InvariantCulture, "<{0} {1}='{2}' />", element, PS_OUT_OF_PROC_PSGUID_ATTRIBUTE, @@ -412,6 +414,19 @@ internal class OutOfProcessTextWriter private readonly TextWriter _writer; private bool _isStopped; private readonly object _syncObject = new object(); + private const string _errorPrepend = "__NamedPipeError__:"; + + #endregion + + #region Properties + + /// + /// Prefix for transport error message. + /// + public static string ErrorPrefix + { + get => _errorPrepend; + } #endregion @@ -421,9 +436,13 @@ internal class OutOfProcessTextWriter /// Constructs the wrapper. /// /// - internal OutOfProcessTextWriter(TextWriter writerToWrap) + public OutOfProcessTextWriter(TextWriter writerToWrap) { - Dbg.Assert(writerToWrap != null, "Cannot wrap a null writer."); + if (writerToWrap is null) + { + throw new PSArgumentNullException(nameof(writerToWrap)); + } + _writer = writerToWrap; } @@ -435,7 +454,7 @@ internal OutOfProcessTextWriter(TextWriter writerToWrap) /// Calls writer.WriteLine() with data. /// /// - internal virtual void WriteLine(string data) + public virtual void WriteLine(string data) { if (_isStopped) { @@ -467,7 +486,10 @@ internal void StopWriting() namespace System.Management.Automation.Remoting.Client { - internal abstract class OutOfProcessClientSessionTransportManagerBase : BaseClientSessionTransportManager + /// + /// Client session transport manager abstract base class. + /// + public abstract class ClientSessionTransportManagerBase : BaseClientSessionTransportManager { #region Data @@ -477,15 +499,17 @@ internal abstract class OutOfProcessClientSessionTransportManagerBase : BaseClie private OutOfProcessUtils.DataProcessingDelegates _dataProcessingCallbacks; private readonly Dictionary _cmdTransportManagers; private readonly Timer _closeTimeOutTimer; - - protected OutOfProcessTextWriter stdInWriter; - protected PowerShellTraceSource _tracer; + internal PowerShellTraceSource _tracer; + internal OutOfProcessTextWriter _messageWriter; #endregion #region Constructor - internal OutOfProcessClientSessionTransportManagerBase( + /// + /// Constructor. + /// + protected ClientSessionTransportManagerBase( Guid runspaceId, PSRemotingCryptoHelper cryptoHelper) : base(runspaceId, cryptoHelper) @@ -505,7 +529,7 @@ internal OutOfProcessClientSessionTransportManagerBase( _dataProcessingCallbacks.ClosePacketReceived += new OutOfProcessUtils.ClosePacketReceived(OnClosePacketReceived); _dataProcessingCallbacks.CloseAckPacketReceived += new OutOfProcessUtils.CloseAckPacketReceived(OnCloseAckReceived); - dataToBeSent.Fragmentor = base.Fragmentor; + dataToBeSent.Fragmentor = Fragmentor; // session transport manager can receive unlimited data..however each object is limited // by maxRecvdObjectSize. this is to allow clients to use a session for an unlimited time.. // also the messages that can be sent to a session are limited and very controlled. @@ -546,7 +570,7 @@ internal override void ConnectAsync() /// /// Closes the server process. /// - internal override void CloseAsync() + public override void CloseAsync() { bool shouldRaiseCloseCompleted = false; lock (syncObject) @@ -560,7 +584,7 @@ internal override void CloseAsync() // will know that we are closing. isClosed = true; - if (stdInWriter == null) + if (_messageWriter == null) { // this will happen if CloseAsync() is called // before ConnectAsync()..in which case we @@ -586,12 +610,12 @@ internal override void CloseAsync() try { // send Close signal to the server and let it die gracefully. - stdInWriter.WriteLine(OutOfProcessUtils.CreateClosePacket(Guid.Empty)); + _messageWriter.WriteLine(OutOfProcessUtils.CreateClosePacket(Guid.Empty)); // start the timer..so client can fail deterministically _closeTimeOutTimer.Change(60 * 1000, Timeout.Infinite); } - catch (IOException) + catch (Exception ex) when (ex is IOException || ex is ObjectDisposedException) { // Cannot communicate with server. Allow client to complete close operation. shouldRaiseCloseCompleted = true; @@ -618,7 +642,7 @@ internal override BaseClientCommandTransportManager CreateClientCommandTransport Dbg.Assert(cmd != null, "Cmd cannot be null"); OutOfProcessClientCommandTransportManager result = new - OutOfProcessClientCommandTransportManager(cmd, noInput, this, stdInWriter); + OutOfProcessClientCommandTransportManager(cmd, noInput, this, _messageWriter); AddCommandTransportManager(cmd.InstanceId, result); return result; @@ -628,37 +652,14 @@ internal override BaseClientCommandTransportManager CreateClientCommandTransport /// Terminates the server process and disposes other resources. /// /// - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (isDisposing) { _cmdTransportManagers.Clear(); _closeTimeOutTimer.Dispose(); - - // Stop session processing thread. - try - { - _sessionMessageQueue.CompleteAdding(); - } - catch (ObjectDisposedException) - { - // Object already disposed. - } - - _sessionMessageQueue.Dispose(); - - // Stop command processing thread. - try - { - _commandMessageQueue.CompleteAdding(); - } - catch (ObjectDisposedException) - { - // Object already disposed. - } - - _commandMessageQueue.Dispose(); + DisposeMessageQueue(); } } @@ -716,6 +717,9 @@ private void OnCloseSessionCompleted() CleanupConnection(); } + /// + /// Optional additional connection clean up after a connection is closed. + /// protected abstract void CleanupConnection(); private void ProcessMessageProc(object state) @@ -754,6 +758,9 @@ private void ProcessMessageProc(object state) private const string SESSIONDMESSAGETAG = "PSGuid='00000000-0000-0000-0000-000000000000'"; + /// + /// Handles protocol output data from a transport. + /// protected void HandleOutputDataReceived(string data) { if (string.IsNullOrEmpty(data)) @@ -785,6 +792,9 @@ protected void HandleOutputDataReceived(string data) } } + /// + /// Handles protocol error data. + /// protected void HandleErrorDataReceived(string data) { lock (syncObject) @@ -801,57 +811,13 @@ protected void HandleErrorDataReceived(string data) RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, TransportMethodEnum.Unknown)); } - protected void OnExited(object sender, EventArgs e) - { - TransportMethodEnum transportMethod = TransportMethodEnum.Unknown; - lock (syncObject) - { - // There is no need to return when IsClosed==true here as in a legitimate case process exits - // after Close is called..In that legitimate case, Exit handler is removed before - // calling Exit..So, this Exit must have been called abnormally. - if (isClosed) - { - transportMethod = TransportMethodEnum.CloseShellOperationEx; - } - - // dont let the writer write new data as the process is exited. - // Not assigning null to stdInWriter to fix the race condition between OnExited() and CloseAsync() methods. - // - stdInWriter.StopWriting(); - } - - // Try to get details about why the process exited - // and if they're not available, give information as to why - string processDiagnosticMessage; - try - { - var jobProcess = (Process)sender; - processDiagnosticMessage = StringUtil.Format( - RemotingErrorIdStrings.ProcessExitInfo, - jobProcess.ExitCode, - jobProcess.StandardOutput.ReadToEnd(), - jobProcess.StandardError.ReadToEnd()); - } - catch (Exception exception) - { - processDiagnosticMessage = StringUtil.Format( - RemotingErrorIdStrings.ProcessInfoNotRecoverable, - exception.Message); - } - - string exitErrorMsg = StringUtil.Format( - RemotingErrorIdStrings.IPCServerProcessExited, - processDiagnosticMessage); - var psrte = new PSRemotingTransportException( - PSRemotingErrorId.IPCServerProcessExited, - exitErrorMsg); - RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, transportMethod)); - } - #endregion #region Sending Data related Methods + /// + /// Send any data packet in the queue. + /// protected void SendOneItem() { DataPriorityType priorityType; @@ -888,7 +854,7 @@ private void SendData(byte[] data, DataPriorityType priorityType) return; } - stdInWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, + _messageWriter.WriteLine(OutOfProcessUtils.CreateDataPacket(data, priorityType, Guid.Empty)); } @@ -931,13 +897,11 @@ private void OnDataPacketReceived(byte[] rawData, string stream, Guid psGuid) { // this is for a command OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) - { - // not throwing the exception in null case as the command might have already - // closed. The RS data structure handler does not wait for the close ack before - // it clears the command transport manager..so this might happen. - cmdTM.OnRemoteCmdDataReceived(rawData, streamTemp); - } + + // not throwing the exception in null case as the command might have already + // closed. The RS data structure handler does not wait for the close ack before + // it clears the command transport manager..so this might happen. + cmdTM?.OnRemoteCmdDataReceived(rawData, streamTemp); } } @@ -952,13 +916,11 @@ private void OnDataAckPacketReceived(Guid psGuid) { // this is for a command OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) - { - // not throwing the exception in null case as the command might have already - // closed. The RS data structure handler does not wait for the close ack before - // it clears the command transport manager..so this might happen. - cmdTM.OnRemoteCmdSendCompleted(); - } + + // not throwing the exception in null case as the command might have already + // closed. The RS data structure handler does not wait for the close ack before + // it clears the command transport manager..so this might happen. + cmdTM?.OnRemoteCmdSendCompleted(); } } @@ -986,7 +948,8 @@ private void OnCommandCreationAckReceived(Guid psGuid) private void OnSignalPacketReceived(Guid psGuid) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCUnknownElementReceived, + throw new PSRemotingTransportException( + PSRemotingErrorId.IPCUnknownElementReceived, RemotingErrorIdStrings.IPCUnknownElementReceived, OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_TAG); } @@ -995,17 +958,15 @@ private void OnSignalAckPacketReceived(Guid psGuid) { if (psGuid == Guid.Empty) { - throw new PSRemotingTransportException(PSRemotingErrorId.IPCNoSignalForSession, + throw new PSRemotingTransportException( + PSRemotingErrorId.IPCNoSignalForSession, RemotingErrorIdStrings.IPCNoSignalForSession, OutOfProcessUtils.PS_OUT_OF_PROC_SIGNAL_ACK_TAG); } else { OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) - { - cmdTM.OnRemoteCmdSignalCompleted(); - } + cmdTM?.OnRemoteCmdSignalCompleted(); } } @@ -1035,12 +996,10 @@ private void OnCloseAckReceived(Guid psGuid) _tracer.WriteMessage("OutOfProcessClientSessionTransportManager.OnCloseAckReceived, in progress command count should be greater than zero: " + commandCount + ", RunSpacePool Id : " + this.RunspacePoolInstanceId + ", psGuid : " + psGuid.ToString()); OutOfProcessClientCommandTransportManager cmdTM = GetCommandTransportManager(psGuid); - if (cmdTM != null) - { - // this might legitimately happen if cmd is already closed before we get an - // ACK back from server. - cmdTM.OnCloseCmdCompleted(); - } + + // this might legitimately happen if cmd is already closed before we get an + // ACK back from server. + cmdTM?.OnCloseCmdCompleted(); } } @@ -1055,9 +1014,71 @@ internal void OnCloseTimeOutTimerElapsed(object source) } #endregion + + #region Protected Methods + + /// + /// Standard handler for data received, to be used by custom transport implementations. + /// + /// Protocol text data received by custom transport. + protected void HandleDataReceived(string data) + { + if (data.StartsWith(OutOfProcessTextWriter.ErrorPrefix, StringComparison.OrdinalIgnoreCase)) + { + // Error message from the server. + string errorData = data.Substring(OutOfProcessTextWriter.ErrorPrefix.Length); + HandleErrorDataReceived(errorData); + } + else + { + // Normal output data. + HandleOutputDataReceived(data); + } + } + + /// + /// Creates the transport message writer from the provided TexWriter object. + /// + /// TextWriter object to be used in the message writer. + protected void SetMessageWriter(TextWriter textWriter) + { + _messageWriter = new OutOfProcessTextWriter(textWriter); + } + + /// + /// Disposes message queue components. + /// + protected void DisposeMessageQueue() + { + // Stop session processing thread. + try + { + _sessionMessageQueue.CompleteAdding(); + } + catch (ObjectDisposedException) + { + // Object already disposed. + } + + _sessionMessageQueue.Dispose(); + + // Stop command processing thread. + try + { + _commandMessageQueue.CompleteAdding(); + } + catch (ObjectDisposedException) + { + // Object already disposed. + } + + _commandMessageQueue.Dispose(); + } + + #endregion } - internal class OutOfProcessClientSessionTransportManager : OutOfProcessClientSessionTransportManagerBase + internal class OutOfProcessClientSessionTransportManager : ClientSessionTransportManagerBase { #region Private Data @@ -1085,14 +1106,14 @@ internal OutOfProcessClientSessionTransportManager(Guid runspaceId, /// /// Launch a new Process (pwsh -s) to perform remoting. This is used by *-Job cmdlets /// to support background jobs without depending on WinRM (WinRM has complex requirements like - /// elevation to support local machine remoting) + /// elevation to support local machine remoting). /// /// /// /// /// 1. There was an error in opening the associated file. /// - internal override void CreateAsync() + public override void CreateAsync() { if (_connectionInfo != null) { @@ -1133,8 +1154,8 @@ internal override void CreateAsync() _processInstance.Start(); StartRedirectionReaderThreads(_serverProcess); - stdInWriter = new OutOfProcessTextWriter(_serverProcess.StandardInput); - _processInstance.StdInWriter = stdInWriter; + SetMessageWriter(_serverProcess.StandardInput); + _processInstance.StdInWriter = _messageWriter; } } catch (System.ComponentModel.Win32Exception w32e) @@ -1244,7 +1265,7 @@ private void ProcessErrorData(object arg) /// Kills the server process and disposes other resources. /// /// - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (isDisposing) @@ -1308,10 +1329,57 @@ private void KillServerProcess() } } + private void OnExited(object sender, EventArgs e) + { + TransportMethodEnum transportMethod = TransportMethodEnum.Unknown; + lock (syncObject) + { + // There is no need to return when IsClosed==true here as in a legitimate case process exits + // after Close is called..In that legitimate case, Exit handler is removed before + // calling Exit..So, this Exit must have been called abnormally. + if (isClosed) + { + transportMethod = TransportMethodEnum.CloseShellOperationEx; + } + + // dont let the writer write new data as the process is exited. + // Not assigning null to stdInWriter to fix the race condition between OnExited() and CloseAsync() methods. + // + _messageWriter.StopWriting(); + } + + // Try to get details about why the process exited + // and if they're not available, give information as to why + string processDiagnosticMessage; + try + { + var jobProcess = (Process)sender; + processDiagnosticMessage = StringUtil.Format( + RemotingErrorIdStrings.ProcessExitInfo, + jobProcess.ExitCode, + jobProcess.StandardOutput.ReadToEnd(), + jobProcess.StandardError.ReadToEnd()); + } + catch (Exception exception) + { + processDiagnosticMessage = StringUtil.Format( + RemotingErrorIdStrings.ProcessInfoNotRecoverable, + exception.Message); + } + + string exitErrorMsg = StringUtil.Format( + RemotingErrorIdStrings.IPCServerProcessExited, + processDiagnosticMessage); + var psrte = new PSRemotingTransportException( + PSRemotingErrorId.IPCServerProcessExited, + exitErrorMsg); + RaiseErrorHandler(new TransportErrorOccuredEventArgs(psrte, transportMethod)); + } + #endregion } - internal abstract class HyperVSocketClientSessionTransportManagerBase : OutOfProcessClientSessionTransportManagerBase + internal abstract class HyperVSocketClientSessionTransportManagerBase : ClientSessionTransportManagerBase { #region Data @@ -1333,16 +1401,13 @@ internal HyperVSocketClientSessionTransportManagerBase( #region Overrides - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (isDisposing) { - if (_client != null) - { - _client.Dispose(); - } + _client?.Dispose(); } } @@ -1411,10 +1476,10 @@ protected void ProcessReaderThread(object state) { if (e is ArgumentOutOfRangeException) { - Dbg.Assert(false, "Need to adjust transport fragmentor to accomodate read buffer size."); + Dbg.Assert(false, "Need to adjust transport fragmentor to accommodate read buffer size."); } - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = e.Message ?? string.Empty; _tracer.WriteMessage("HyperVSocketClientSessionTransportManager", "StartReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); @@ -1477,10 +1542,11 @@ internal VMHyperVSocketClientSessionTransportManager( /// Create a Hyper-V socket connection to the target process and set up /// transport reader/writer. /// - internal override void CreateAsync() + public override void CreateAsync() { - _client = new RemoteSessionHyperVSocketClient(_vmGuid, true); - if (!_client.Connect(_networkCredential, _configurationName, true)) + // isFirstConnection: true - specifies to use VM_SESSION_SERVICE_ID socket. + _client = new RemoteSessionHyperVSocketClient(_vmGuid, useBackwardsCompatibleMode: false, isFirstConnection: true); + if (!_client.Connect(_networkCredential, _configurationName, isFirstConnection: true)) { _client.Dispose(); throw new PSInvalidOperationException( @@ -1490,11 +1556,14 @@ internal override void CreateAsync() ErrorCategory.InvalidOperation, null); } + bool useBackwardsCompatibleMode = _client.UseBackwardsCompatibleMode; + string token = _client.AuthenticationToken; - // TODO: remove below 3 lines when Hyper-V socket duplication is supported in .NET framework. _client.Dispose(); - _client = new RemoteSessionHyperVSocketClient(_vmGuid, false); - if (!_client.Connect(_networkCredential, _configurationName, false)) + + // isFirstConnection: false - specifies to use the SESSION_SERVICE_ID_2 socket. + _client = new RemoteSessionHyperVSocketClient(_vmGuid, useBackwardsCompatibleMode: useBackwardsCompatibleMode, isFirstConnection: false, authenticationToken: token); + if (!_client.Connect(_networkCredential, _configurationName, isFirstConnection: false)) { _client.Dispose(); throw new PSInvalidOperationException( @@ -1506,7 +1575,7 @@ internal override void CreateAsync() } // Create writer for Hyper-V socket. - stdInWriter = new OutOfProcessTextWriter(_client.TextWriter); + SetMessageWriter(_client.TextWriter); // Create reader thread for Hyper-V socket. StartReaderThread(_client.TextReader); @@ -1550,9 +1619,11 @@ internal ContainerHyperVSocketClientSessionTransportManager( /// Create a Hyper-V socket connection to the target process and set up /// transport reader/writer. /// - internal override void CreateAsync() + public override void CreateAsync() { - _client = new RemoteSessionHyperVSocketClient(_targetGuid, false, true); + // Container scenario is not working. + // When we fix it we need to setup the token in ContainerConnectionInfo and use it here. + _client = new RemoteSessionHyperVSocketClient(_targetGuid, isFirstConnection: false, useBackwardsCompatibleMode: false, isContainer: true); if (!_client.Connect(null, string.Empty, false)) { _client.Dispose(); @@ -1565,7 +1636,7 @@ internal override void CreateAsync() } // Create writer for Hyper-V socket. - stdInWriter = new OutOfProcessTextWriter(_client.TextWriter); + SetMessageWriter(_client.TextWriter); // Create reader thread for Hyper-V socket. StartReaderThread(_client.TextReader); @@ -1574,7 +1645,7 @@ internal override void CreateAsync() #endregion } - internal sealed class SSHClientSessionTransportManager : OutOfProcessClientSessionTransportManagerBase + internal sealed class SSHClientSessionTransportManager : ClientSessionTransportManagerBase { #region Data @@ -1584,6 +1655,7 @@ internal sealed class SSHClientSessionTransportManager : OutOfProcessClientSessi private StreamReader _stdOutReader; private StreamReader _stdErrReader; private bool _connectionEstablished; + private Timer _connectionTimer; private const string _threadName = "SSHTransport Reader Thread"; @@ -1606,7 +1678,7 @@ internal SSHClientSessionTransportManager( #region Overrides - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); @@ -1625,7 +1697,7 @@ protected override void CleanupConnection() /// Create an SSH connection to the target host and set up /// transport reader/writer. /// - internal override void CreateAsync() + public override void CreateAsync() { // Create the ssh client process with connection to host target. _sshProcessId = _connectionInfo.StartSSHProcess( @@ -1637,13 +1709,56 @@ internal override void CreateAsync() StartErrorThread(_stdErrReader); // Create writer for named pipe. - stdInWriter = new OutOfProcessTextWriter(_stdInWriter); + SetMessageWriter(_stdInWriter); // Create reader thread and send first PSRP message. StartReaderThread(_stdOutReader); + + if (_connectionInfo.ConnectingTimeout < 0) + { + return; + } + + // Start connection timeout timer if requested. + // Timer callback occurs only once after timeout time. + _connectionTimer = new Timer( + callback: (_) => + { + if (_connectionEstablished) + { + return; + } + + // Detect if SSH client process terminates prematurely. + bool sshTerminated = false; + try + { + using (var sshProcess = Process.GetProcessById(_sshProcessId)) + { + sshTerminated = sshProcess == null || sshProcess.Handle == IntPtr.Zero || sshProcess.HasExited; + } + } + catch + { + sshTerminated = true; + } + + var errorMessage = StringUtil.Format(RemotingErrorIdStrings.SSHClientConnectTimeout, _connectionInfo.ConnectingTimeout / 1000); + if (sshTerminated) + { + errorMessage += RemotingErrorIdStrings.SSHClientConnectProcessTerminated; + } + + // Report error and terminate connection attempt. + HandleSSHError( + new PSRemotingTransportException(errorMessage)); + }, + state: null, + dueTime: _connectionInfo.ConnectingTimeout, + period: Timeout.Infinite); } - internal override void CloseAsync() + public override void CloseAsync() { base.CloseAsync(); @@ -1660,14 +1775,20 @@ internal override void CloseAsync() private void CloseConnection() { + // Ensure message queue is disposed. + DisposeMessageQueue(); + + var connectionTimer = Interlocked.Exchange(ref _connectionTimer, null); + connectionTimer?.Dispose(); + var stdInWriter = Interlocked.Exchange(ref _stdInWriter, null); - if (stdInWriter != null) { stdInWriter.Dispose(); } + stdInWriter?.Dispose(); var stdOutReader = Interlocked.Exchange(ref _stdOutReader, null); - if (stdOutReader != null) { stdOutReader.Dispose(); } + stdOutReader?.Dispose(); var stdErrReader = Interlocked.Exchange(ref _stdErrReader, null); - if (stdErrReader != null) { stdErrReader.Dispose(); } + stdErrReader?.Dispose(); // The CloseConnection() method can be called multiple times from multiple places. // Set the _sshProcessId to zero here so that we go through the work of finding @@ -1677,11 +1798,7 @@ private void CloseConnection() { try { - var sshProcess = System.Diagnostics.Process.GetProcessById(sshProcessId); - if ((sshProcess != null) && (sshProcess.Handle != IntPtr.Zero) && !sshProcess.HasExited) - { - sshProcess.Kill(); - } + _connectionInfo.KillSSHProcess(sshProcessId); } catch (ArgumentException) { } catch (InvalidOperationException) { } @@ -1708,7 +1825,16 @@ private void ProcessErrorThread(object state) while (true) { - string error = ReadError(reader); + string error; + + // Blocking read from StdError stream + error = reader.ReadLine(); + + if (error == null) + { + // Stream is closed unexpectedly. + throw new PSInvalidOperationException(RemotingErrorIdStrings.SSHAbruptlyTerminated); + } if (error.Length == 0) { @@ -1716,12 +1842,15 @@ private void ProcessErrorThread(object state) continue; } - // Any SSH client error results in a broken session. - PSRemotingTransportException psrte = new PSRemotingTransportException( - PSRemotingErrorId.IPCServerProcessReportedError, - RemotingErrorIdStrings.IPCServerProcessReportedError, - StringUtil.Format(RemotingErrorIdStrings.SSHClientEndWithErrorMessage, error)); - HandleSSHError(psrte); + try + { + // Messages in error stream from ssh are unreliable, and may just be warnings or + // banner text. + // So just report the messages but don't act on them. + Console.WriteLine(error); + } + catch (IOException) + { } } } catch (ObjectDisposedException) @@ -1730,7 +1859,7 @@ private void ProcessErrorThread(object state) } catch (Exception e) { - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = e.Message ?? string.Empty; _tracer.WriteMessage("SSHClientSessionTransportManager", "ProcessErrorThread", Guid.Empty, "Transport manager error thread ended with error: {0}", errorMsg); @@ -1747,55 +1876,6 @@ private void HandleSSHError(PSRemotingTransportException psrte) CloseConnection(); } - private static string ReadError(StreamReader reader) - { - // Blocking read from StdError stream - string error = reader.ReadLine(); - - if (error == null) - { - // Stream is closed unexpectedly. - throw new PSInvalidOperationException(RemotingErrorIdStrings.SSHAbruptlyTerminated); - } - - if ((error.Length == 0) || - error.Contains("WARNING:", StringComparison.OrdinalIgnoreCase)) - { - // Handle as interactive warning message - Console.WriteLine(error); - return string.Empty; - } - - // SSH may return a multi-line error message. - // The StdError pipe stream is open ended causing StreamReader read operations to block - // if there is no incoming data. Since we don't know how many error message lines there - // will be we use an asynchronous read with timeout to prevent blocking indefinitely. - System.Text.StringBuilder sb = new Text.StringBuilder(error); - var running = true; - while (running) - { - try - { - var task = reader.ReadLineAsync(); - if (task.Wait(1000) && (task.Result != null)) - { - sb.Append(Environment.NewLine); - sb.Append(task.Result); - } - else - { - running = false; - } - } - catch (Exception) - { - running = false; - } - } - - return sb.ToString(); - } - private void StartReaderThread( StreamReader reader) { @@ -1827,10 +1907,10 @@ private void ProcessReaderThread(object state) break; } - if (data.StartsWith(System.Management.Automation.Remoting.Server.NamedPipeErrorTextWriter.ErrorPrepend, StringComparison.OrdinalIgnoreCase)) + if (data.StartsWith(OutOfProcessTextWriter.ErrorPrefix, StringComparison.OrdinalIgnoreCase)) { // Error message from the server. - string errorData = data.Substring(System.Management.Automation.Remoting.Server.NamedPipeErrorTextWriter.ErrorPrepend.Length); + string errorData = data.Substring(OutOfProcessTextWriter.ErrorPrefix.Length); HandleErrorDataReceived(errorData); } else @@ -1851,10 +1931,10 @@ private void ProcessReaderThread(object state) { if (e is ArgumentOutOfRangeException) { - Dbg.Assert(false, "Need to adjust transport fragmentor to accomodate read buffer size."); + Dbg.Assert(false, "Need to adjust transport fragmentor to accommodate read buffer size."); } - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = e.Message ?? string.Empty; _tracer.WriteMessage("SSHClientSessionTransportManager", "ProcessReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); } @@ -1863,7 +1943,7 @@ private void ProcessReaderThread(object state) #endregion } - internal abstract class NamedPipeClientSessionTransportManagerBase : OutOfProcessClientSessionTransportManagerBase + internal abstract class NamedPipeClientSessionTransportManagerBase : ClientSessionTransportManagerBase { #region Data @@ -1896,16 +1976,13 @@ internal NamedPipeClientSessionTransportManagerBase( #region Overrides - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (isDisposing) { - if (_clientPipe != null) - { - _clientPipe.Dispose(); - } + _clientPipe?.Dispose(); } } @@ -1957,17 +2034,7 @@ private void ProcessReaderThread(object state) break; } - if (data.StartsWith(System.Management.Automation.Remoting.Server.NamedPipeErrorTextWriter.ErrorPrepend, StringComparison.OrdinalIgnoreCase)) - { - // Error message from the server. - string errorData = data.Substring(System.Management.Automation.Remoting.Server.NamedPipeErrorTextWriter.ErrorPrepend.Length); - HandleErrorDataReceived(errorData); - } - else - { - // Normal output data. - HandleOutputDataReceived(data); - } + HandleDataReceived(data); } } catch (ObjectDisposedException) @@ -1981,7 +2048,7 @@ private void ProcessReaderThread(object state) Dbg.Assert(false, "Need to adjust transport fragmentor to accommodate read buffer size."); } - string errorMsg = (e.Message != null) ? e.Message : string.Empty; + string errorMsg = e.Message ?? string.Empty; _tracer.WriteMessage("NamedPipeClientSessionTransportManager", "StartReaderThread", Guid.Empty, "Transport manager reader thread ended with error: {0}", errorMsg); } @@ -2024,7 +2091,7 @@ internal NamedPipeClientSessionTransportManager( /// Create a named pipe connection to the target process and set up /// transport reader/writer. /// - internal override void CreateAsync() + public override void CreateAsync() { _clientPipe = string.IsNullOrEmpty(_connectionInfo.CustomPipeName) ? new RemoteSessionNamedPipeClient(_connectionInfo.ProcessId, _connectionInfo.AppDomainName) : @@ -2034,7 +2101,7 @@ internal override void CreateAsync() _clientPipe.Connect(_connectionInfo.OpenTimeout); // Create writer for named pipe. - stdInWriter = new OutOfProcessTextWriter(_clientPipe.TextWriter); + SetMessageWriter(_clientPipe.TextWriter); // Create reader thread for named pipe. StartReaderThread(_clientPipe.TextReader); @@ -2047,13 +2114,7 @@ internal override void CreateAsync() /// /// Aborts an existing connection attempt. /// - public void AbortConnect() - { - if (_clientPipe != null) - { - _clientPipe.AbortConnect(); - } - } + public void AbortConnect() => _clientPipe?.AbortConnect(); #endregion } @@ -2092,7 +2153,7 @@ internal ContainerNamedPipeClientSessionTransportManager( /// Create a named pipe connection to the target process in target container and set up /// transport reader/writer. /// - internal override void CreateAsync() + public override void CreateAsync() { _clientPipe = new ContainerSessionNamedPipeClient( _connectionInfo.ContainerProc.ProcessId, @@ -2103,7 +2164,7 @@ internal override void CreateAsync() _clientPipe.Connect(_connectionInfo.OpenTimeout); // Create writer for named pipe. - stdInWriter = new OutOfProcessTextWriter(_clientPipe.TextWriter); + SetMessageWriter(_clientPipe.TextWriter); // Create reader thread for named pipe. StartReaderThread(_clientPipe.TextReader); @@ -2142,7 +2203,7 @@ internal class OutOfProcessClientCommandTransportManager : BaseClientCommandTran internal OutOfProcessClientCommandTransportManager( ClientRemotePowerShell cmd, bool noInput, - OutOfProcessClientSessionTransportManagerBase sessnTM, + ClientSessionTransportManagerBase sessnTM, OutOfProcessTextWriter stdInWriter) : base(cmd, sessnTM.CryptoHelper, sessnTM) { _stdInWriter = stdInWriter; @@ -2160,7 +2221,7 @@ internal override void ConnectAsync() throw new NotImplementedException(RemotingErrorIdStrings.IPCTransportConnectError); } - internal override void CreateAsync() + public override void CreateAsync() { PSEtwLog.LogAnalyticInformational(PSEventId.WSManCreateCommand, PSOpcode.Connect, PSTask.CreateRunspace, @@ -2170,7 +2231,7 @@ internal override void CreateAsync() _stdInWriter.WriteLine(OutOfProcessUtils.CreateCommandPacket(powershellInstanceId)); } - internal override void CloseAsync() + public override void CloseAsync() { lock (syncObject) { @@ -2224,7 +2285,7 @@ internal override void SendStopSignal() _signalTimeOutTimer.Change(60 * 1000, Timeout.Infinite); } - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (isDisposing) @@ -2449,6 +2510,12 @@ internal OutOfProcessServerSessionTransportManager(OutOfProcessTextWriter outWri _stdOutWriter = outWriter; _stdErrWriter = errWriter; _cmdTransportManagers = new Dictionary(); + + this.WSManTransportErrorOccured += (object sender, TransportErrorOccuredEventArgs e) => + { + string msg = e.Exception.TransportMessage ?? e.Exception.InnerException?.Message ?? string.Empty; + _stdErrWriter.WriteLine(StringUtil.Format(RemotingErrorIdStrings.RemoteTransportError, msg)); + }; } #endregion diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs index 1341c9e0a83..b6a3f212b33 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSPrincipal.cs @@ -18,11 +18,9 @@ namespace System.Management.Automation.Remoting /// /// This class is used in the server side remoting scenarios. This class /// holds information about the incoming connection like: - /// (a) Client's TimeZone - /// (b) Connecting User information - /// (c) Connection String used by the user to connect to the server. + /// (a) Connecting User information + /// (b) Connection String used by the user to connect to the server. /// - [Serializable] public sealed class PSSenderInfo : ISerializable { #region Private Data @@ -81,8 +79,6 @@ private PSSenderInfo(SerializationInfo info, StreamingContext context) UserInfo = senderInfo.UserInfo; ConnectionString = senderInfo.ConnectionString; _applicationArguments = senderInfo._applicationArguments; - - ClientTimeZone = senderInfo.ClientTimeZone; } catch (Exception) { @@ -129,11 +125,7 @@ public PSPrincipal UserInfo /// /// Contains the TimeZone information from the client machine. /// - public TimeZoneInfo ClientTimeZone - { - get; - internal set; - } + public TimeZoneInfo ClientTimeZone => null; /// /// Connection string used by the client to connect to the server. This is diff --git a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs index 6da557cca40..1d5f6916981 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PSSessionConfigurationData.cs @@ -80,7 +80,10 @@ internal static PSSessionConfigurationData Create(string configurationData) { PSSessionConfigurationData configuration = new PSSessionConfigurationData(); - if (string.IsNullOrEmpty(configurationData)) return configuration; + if (string.IsNullOrEmpty(configurationData)) + { + return configuration; + } configurationData = Unescape(configurationData); @@ -224,8 +227,8 @@ private void Update(string optionName, string optionValue) private void CreateCollectionIfNecessary() { - if (_modulesToImport == null) _modulesToImport = new List(); - if (_modulesToImportInternal == null) _modulesToImportInternal = new List(); + _modulesToImport ??= new List(); + _modulesToImportInternal ??= new List(); } private const string SessionConfigToken = "SessionConfigurationData"; diff --git a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs index 7baebdc98ae..a0f38a78a07 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/PriorityCollection.cs @@ -98,7 +98,7 @@ internal Fragmentor Fragmentor Dbg.Assert(value != null, "Fragmentor cannot be null."); _fragmentor = value; // create serialized streams using fragment size. - string[] names = Enum.GetNames(typeof(DataPriorityType)); + string[] names = Enum.GetNames(); _dataToBeSent = new SerializedDataStream[names.Length]; _dataSyncObjects = new object[names.Length]; for (int i = 0; i < names.Length; i++) @@ -220,21 +220,29 @@ internal byte[] ReadOrRegisterCallback(OnDataAvailableCallback callback, lock (_readSyncObject) { priorityType = DataPriorityType.Default; - - // send data from which ever stream that has data directly. + // Send data from which ever stream that has data directly. byte[] result = null; - result = _dataToBeSent[(int)DataPriorityType.PromptResponse].ReadOrRegisterCallback(_onSendCollectionDataAvailable); - priorityType = DataPriorityType.PromptResponse; + SerializedDataStream promptDataToBeSent = _dataToBeSent[(int)DataPriorityType.PromptResponse]; + if (promptDataToBeSent is not null) + { + result = promptDataToBeSent.ReadOrRegisterCallback(_onSendCollectionDataAvailable); + priorityType = DataPriorityType.PromptResponse; + } if (result == null) { - result = _dataToBeSent[(int)DataPriorityType.Default].ReadOrRegisterCallback(_onSendCollectionDataAvailable); - priorityType = DataPriorityType.Default; + SerializedDataStream defaultDataToBeSent = _dataToBeSent[(int)DataPriorityType.Default]; + if (defaultDataToBeSent is not null) + { + result = defaultDataToBeSent.ReadOrRegisterCallback(_onSendCollectionDataAvailable); + priorityType = DataPriorityType.Default; + } } - // no data to return..so register the callback. + + // No data to return..so register the callback. if (result == null) { - // register callback. + // Register callback. _onDataAvailableCallback = callback; } @@ -293,7 +301,7 @@ internal class ReceiveDataCollection : IDisposable { #region tracer - [TraceSourceAttribute("Transport", "Traces BaseWSManTransportManager")] + [TraceSource("Transport", "Traces BaseWSManTransportManager")] private static readonly PSTraceSource s_baseTracer = PSTraceSource.GetTracer("Transport", "Traces BaseWSManTransportManager"); #endregion @@ -553,11 +561,11 @@ internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) PSEtwLog.LogAnalyticVerbose( PSEventId.ReceivedRemotingFragment, PSOpcode.Receive, PSTask.None, PSKeyword.Transport | PSKeyword.UseAlwaysAnalytic, - (Int64)objectId, - (Int64)fragmentId, + (long)objectId, + (long)fragmentId, sFlag ? 1 : 0, eFlag ? 1 : 0, - (UInt32)blobLength, + (uint)blobLength, new PSETWBinaryBlob(oneFragment, FragmentedRemoteObject.HeaderLength, blobLength)); byte[] extraData = null; @@ -676,10 +684,7 @@ internal void ProcessRawData(byte[] data, OnDataAvailableCallback callback) private void ResetReceiveData() { // reset resources used to store incoming data (for a single object) - if (_dataToProcessStream != null) - { - _dataToProcessStream.Dispose(); - } + _dataToProcessStream?.Dispose(); _currentObjectId = 0; _currentFrgId = 0; @@ -760,7 +765,7 @@ internal class PriorityReceiveDataCollection : IDisposable internal PriorityReceiveDataCollection(Fragmentor defragmentor, bool createdByClientTM) { _defragmentor = defragmentor; - string[] names = Enum.GetNames(typeof(DataPriorityType)); + string[] names = Enum.GetNames(); _recvdData = new ReceiveDataCollection[names.Length]; for (int index = 0; index < names.Length; index++) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs index 6dd3614a62f..d7bce634620 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManNativeAPI.cs @@ -304,7 +304,6 @@ internal struct WSManUserNameCredentialStruct /// /// Making password secure. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr password; } @@ -626,7 +625,6 @@ internal class WSManBinaryOrTextDataStruct { internal int bufferLength; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr data; } @@ -637,10 +635,8 @@ internal class WSManData_ManToUn : IDisposable { private readonly WSManDataStruct _internalData; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _marshalledObject = IntPtr.Zero; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _marshalledBuffer = IntPtr.Zero; /// @@ -933,7 +929,6 @@ internal struct WSManStreamIDSetStruct { internal int streamIDsCount; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr streamIDs; } @@ -1085,7 +1080,6 @@ internal struct WSManOptionSetStruct /// /// Pointer to an array of WSManOption objects. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr options; internal bool optionsMustUnderstand; @@ -1223,13 +1217,11 @@ internal struct WSManCommandArgSetInternal { internal int argsCount; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr args; } private WSManCommandArgSetInternal _internalData; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private MarshalledObject _data; #region Managed to Unmanaged @@ -1404,7 +1396,7 @@ internal struct WSManShellStartupInfoStruct /// /// Managed to unmanaged representation of WSMAN_SHELL_STARTUP_INFO. /// It converts managed values into an unmanaged compatible WSManShellStartupInfoStruct that - /// is marshaled into unmanaged memory. + /// is marshalled into unmanaged memory. /// internal struct WSManShellStartupInfo_ManToUn : IDisposable { @@ -1733,7 +1725,6 @@ internal struct WSManShellAsyncCallback // GC handle which prevents garbage collector from collecting this delegate. private GCHandle _gcHandle; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private readonly IntPtr _asyncCallback; internal WSManShellAsyncCallback(WSManShellCompletionFunction callback) @@ -2006,13 +1997,13 @@ private struct WSManBinaryDataInternal internal class WSManPluginRequest { /// - /// Unmarshaled WSMAN_SENDER_DETAILS struct. + /// Unmarshalled WSMAN_SENDER_DETAILS struct. /// internal WSManSenderDetails senderDetails; internal string locale; internal string resourceUri; /// - /// Unmarshaled WSMAN_OPERATION_INFO struct. + /// Unmarshalled WSMAN_OPERATION_INFO struct. /// internal WSManOperationInfo operationInfo; @@ -2100,7 +2091,7 @@ internal class WSManSenderDetails internal string senderName; internal string authenticationMechanism; internal WSManCertificateDetails certificateDetails; - internal IntPtr clientToken; // TODO: How should this be marshaled????? + internal IntPtr clientToken; // TODO: How should this be marshalled????? internal string httpUrl; /// diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs index 9382beb9b31..79d583e063f 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPlugin.cs @@ -306,10 +306,16 @@ internal void CreateShell( PSOpcode.Connect, PSTask.None, PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, requestDetails.ToString(), senderInfo.UserInfo.Identity.Name, requestDetails.resourceUri); - ServerRemoteSession remoteShellSession = ServerRemoteSession.CreateServerRemoteSession(senderInfo, - requestDetails.resourceUri, - extraInfo, - serverTransportMgr); + + ServerRemoteSession remoteShellSession = ServerRemoteSession.CreateServerRemoteSession( + senderInfo: senderInfo, + configurationProviderId: requestDetails.resourceUri, + initializationParameters: extraInfo, + transportManager: serverTransportMgr, + initialCommand: null, // Not used by WinRM endpoint. + configurationName: null, // Not used by WinRM endpoint, which has its own configuration. + configurationFile: null, // Same. + initialLocation: null); // Same. if (remoteShellSession == null) { diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs index e2679fcdf44..2d99a42cfb9 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginFacade.cs @@ -33,7 +33,7 @@ namespace System.Management.Automation.Remoting /// PCWSTR. /// WSMAN_SHELL_STARTUP_INFO*. /// WSMAN_DATA*. - internal delegate void WSMPluginShellDelegate( // TODO: Rename to WSManPluginShellDelegate once I remove the MC++ module. + internal delegate void WSManPluginShellDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -45,7 +45,7 @@ internal delegate void WSMPluginShellDelegate( // TODO: Rename to WSManPluginShe /// /// PVOID. /// PVOID. - internal delegate void WSMPluginReleaseShellContextDelegate( + internal delegate void WSManPluginReleaseShellContextDelegate( IntPtr pluginContext, IntPtr shellContext); @@ -57,7 +57,7 @@ internal delegate void WSMPluginReleaseShellContextDelegate( /// PVOID. /// PVOID optional. /// WSMAN_DATA* optional. - internal delegate void WSMPluginConnectDelegate( + internal delegate void WSManPluginConnectDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -73,7 +73,7 @@ internal delegate void WSMPluginConnectDelegate( /// PVOID. /// PCWSTR. /// WSMAN_COMMAND_ARG_SET*. - internal delegate void WSMPluginCommandDelegate( + internal delegate void WSManPluginCommandDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -85,7 +85,7 @@ internal delegate void WSMPluginCommandDelegate( /// Delegate that is passed to native layer for callback on operation shutdown notifications. /// /// IntPtr. - internal delegate void WSMPluginOperationShutdownDelegate( + internal delegate void WSManPluginOperationShutdownDelegate( IntPtr shutdownContext); /// @@ -93,7 +93,7 @@ internal delegate void WSMPluginOperationShutdownDelegate( /// PVOID. /// PVOID. /// PVOID. - internal delegate void WSMPluginReleaseCommandContextDelegate( + internal delegate void WSManPluginReleaseCommandContextDelegate( IntPtr pluginContext, IntPtr shellContext, IntPtr commandContext); @@ -107,7 +107,7 @@ internal delegate void WSMPluginReleaseCommandContextDelegate( /// PVOID. /// PCWSTR. /// WSMAN_DATA*. - internal delegate void WSMPluginSendDelegate( + internal delegate void WSManPluginSendDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -124,7 +124,7 @@ internal delegate void WSMPluginSendDelegate( /// PVOID. /// PVOID optional. /// WSMAN_STREAM_ID_SET* optional. - internal delegate void WSMPluginReceiveDelegate( + internal delegate void WSManPluginReceiveDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -140,7 +140,7 @@ internal delegate void WSMPluginReceiveDelegate( /// PVOID. /// PVOID optional. /// PCWSTR. - internal delegate void WSMPluginSignalDelegate( + internal delegate void WSManPluginSignalDelegate( IntPtr pluginContext, IntPtr requestDetails, int flags, @@ -160,7 +160,7 @@ internal delegate void WaitOrTimerCallbackDelegate( /// /// /// PVOID. - internal delegate void WSMShutdownPluginDelegate( + internal delegate void WSManShutdownPluginDelegate( IntPtr pluginContext); /// @@ -192,7 +192,7 @@ internal WSManPluginEntryDelegatesInternal UnmanagedStruct private GCHandle _pluginSignalGCHandle; private GCHandle _pluginConnectGCHandle; private GCHandle _shutdownPluginGCHandle; - private GCHandle _WSMPluginOperationShutdownGCHandle; + private GCHandle _WSManPluginOperationShutdownGCHandle; #endregion @@ -255,57 +255,57 @@ private void populateDelegates() // disposal. Using GCHandle without pinning reduces fragmentation potential // of the managed heap. { - WSMPluginShellDelegate pluginShell = new WSMPluginShellDelegate(WSManPluginManagedEntryWrapper.WSManPluginShell); + WSManPluginShellDelegate pluginShell = new WSManPluginShellDelegate(WSManPluginManagedEntryWrapper.WSManPluginShell); _pluginShellGCHandle = GCHandle.Alloc(pluginShell); // marshal the delegate to a unmanaged function pointer so that AppDomain reference is stored correctly. // Populate the outgoing structure so the caller has access to the entry points _unmanagedStruct.wsManPluginShellCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShell); } { - WSMPluginReleaseShellContextDelegate pluginReleaseShellContext = new WSMPluginReleaseShellContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseShellContext); + WSManPluginReleaseShellContextDelegate pluginReleaseShellContext = new WSManPluginReleaseShellContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseShellContext); _pluginReleaseShellContextGCHandle = GCHandle.Alloc(pluginReleaseShellContext); _unmanagedStruct.wsManPluginReleaseShellContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseShellContext); } { - WSMPluginCommandDelegate pluginCommand = new WSMPluginCommandDelegate(WSManPluginManagedEntryWrapper.WSManPluginCommand); + WSManPluginCommandDelegate pluginCommand = new WSManPluginCommandDelegate(WSManPluginManagedEntryWrapper.WSManPluginCommand); _pluginCommandGCHandle = GCHandle.Alloc(pluginCommand); _unmanagedStruct.wsManPluginCommandCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginCommand); } { - WSMPluginReleaseCommandContextDelegate pluginReleaseCommandContext = new WSMPluginReleaseCommandContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseCommandContext); + WSManPluginReleaseCommandContextDelegate pluginReleaseCommandContext = new WSManPluginReleaseCommandContextDelegate(WSManPluginManagedEntryWrapper.WSManPluginReleaseCommandContext); _pluginReleaseCommandContextGCHandle = GCHandle.Alloc(pluginReleaseCommandContext); _unmanagedStruct.wsManPluginReleaseCommandContextCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReleaseCommandContext); } { - WSMPluginSendDelegate pluginSend = new WSMPluginSendDelegate(WSManPluginManagedEntryWrapper.WSManPluginSend); + WSManPluginSendDelegate pluginSend = new WSManPluginSendDelegate(WSManPluginManagedEntryWrapper.WSManPluginSend); _pluginSendGCHandle = GCHandle.Alloc(pluginSend); _unmanagedStruct.wsManPluginSendCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSend); } { - WSMPluginReceiveDelegate pluginReceive = new WSMPluginReceiveDelegate(WSManPluginManagedEntryWrapper.WSManPluginReceive); + WSManPluginReceiveDelegate pluginReceive = new WSManPluginReceiveDelegate(WSManPluginManagedEntryWrapper.WSManPluginReceive); _pluginReceiveGCHandle = GCHandle.Alloc(pluginReceive); _unmanagedStruct.wsManPluginReceiveCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginReceive); } { - WSMPluginSignalDelegate pluginSignal = new WSMPluginSignalDelegate(WSManPluginManagedEntryWrapper.WSManPluginSignal); + WSManPluginSignalDelegate pluginSignal = new WSManPluginSignalDelegate(WSManPluginManagedEntryWrapper.WSManPluginSignal); _pluginSignalGCHandle = GCHandle.Alloc(pluginSignal); _unmanagedStruct.wsManPluginSignalCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginSignal); } { - WSMPluginConnectDelegate pluginConnect = new WSMPluginConnectDelegate(WSManPluginManagedEntryWrapper.WSManPluginConnect); + WSManPluginConnectDelegate pluginConnect = new WSManPluginConnectDelegate(WSManPluginManagedEntryWrapper.WSManPluginConnect); _pluginConnectGCHandle = GCHandle.Alloc(pluginConnect); _unmanagedStruct.wsManPluginConnectCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginConnect); } { - WSMShutdownPluginDelegate shutdownPlugin = new WSMShutdownPluginDelegate(WSManPluginManagedEntryWrapper.ShutdownPlugin); + WSManShutdownPluginDelegate shutdownPlugin = new WSManShutdownPluginDelegate(WSManPluginManagedEntryWrapper.ShutdownPlugin); _shutdownPluginGCHandle = GCHandle.Alloc(shutdownPlugin); _unmanagedStruct.wsManPluginShutdownPluginCallbackNative = Marshal.GetFunctionPointerForDelegate(shutdownPlugin); } if (!Platform.IsWindows) { - WSMPluginOperationShutdownDelegate pluginShutDownDelegate = new WSMPluginOperationShutdownDelegate(WSManPluginManagedEntryWrapper.WSManPSShutdown); - _WSMPluginOperationShutdownGCHandle = GCHandle.Alloc(pluginShutDownDelegate); + WSManPluginOperationShutdownDelegate pluginShutDownDelegate = new WSManPluginOperationShutdownDelegate(WSManPluginManagedEntryWrapper.WSManPSShutdown); + _WSManPluginOperationShutdownGCHandle = GCHandle.Alloc(pluginShutDownDelegate); _unmanagedStruct.wsManPluginShutdownCallbackNative = Marshal.GetFunctionPointerForDelegate(pluginShutDownDelegate); } } @@ -328,7 +328,7 @@ private void CleanUpDelegates() _shutdownPluginGCHandle.Free(); if (!Platform.IsWindows) { - _WSMPluginOperationShutdownGCHandle.Free(); + _WSManPluginOperationShutdownGCHandle.Free(); } } } @@ -343,61 +343,51 @@ internal class WSManPluginEntryDelegatesInternal /// /// WsManPluginShutdownPluginCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginShutdownPluginCallbackNative; /// /// WSManPluginShellCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginShellCallbackNative; /// /// WSManPluginReleaseShellContextCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginReleaseShellContextCallbackNative; /// /// WSManPluginCommandCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginCommandCallbackNative; /// /// WSManPluginReleaseCommandContextCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginReleaseCommandContextCallbackNative; /// /// WSManPluginSendCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginSendCallbackNative; /// /// WSManPluginReceiveCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginReceiveCallbackNative; /// /// WSManPluginSignalCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginSignalCallbackNative; /// /// WSManPluginConnectCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginConnectCallbackNative; /// /// WSManPluginCommandCallbackNative. /// - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] internal IntPtr wsManPluginShutdownCallbackNative; } } @@ -446,11 +436,7 @@ public static void ShutdownPlugin( IntPtr pluginContext) { WSManPluginInstance.PerformShutdown(pluginContext); - - if (workerPtrs != null) - { - workerPtrs.Dispose(); - } + workerPtrs?.Dispose(); } /// diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs index 51635922e0b..54a7b66d0c1 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManPluginShellSession.cs @@ -468,11 +468,12 @@ internal override void ExecuteConnect( _remoteSession.ExecuteConnect(inputData, out outputData); // construct Xml to send back - string responseData = string.Format(System.Globalization.CultureInfo.InvariantCulture, - "<{0} xmlns=\"{1}\">{2}", - WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, - WSManNativeApi.PS_XML_NAMESPACE, - Convert.ToBase64String(outputData)); + string responseData = string.Format( + System.Globalization.CultureInfo.InvariantCulture, + "<{0} xmlns=\"{1}\">{2}", + WSManNativeApi.PS_CONNECTRESPONSE_XML_TAG, + WSManNativeApi.PS_XML_NAMESPACE, + Convert.ToBase64String(outputData)); // TODO: currently using OperationComplete to report back the responseXml. This will need to change to use WSManReportObject // that is currently internal. @@ -769,7 +770,7 @@ internal bool ProcessArguments( internal void Stop( WSManNativeApi.WSManPluginRequest requestDetails) { - // stop the command..command will be stoped if we raise ClosingEvent on + // stop the command..command will be stopped if we raise ClosingEvent on // transport manager. transportMgr.PerformStop(); WSManPluginInstance.ReportWSManOperationComplete(requestDetails, null); diff --git a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs index 99b2d4848bd..d4ee779b5a2 100644 --- a/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs +++ b/src/System.Management.Automation/engine/remoting/fanin/WSManTransportManager.cs @@ -202,8 +202,7 @@ internal static string ParseEscapeWSManErrorMessage(string errorMessage) Collection tokens = PSParser.Tokenize(errorMessage, out parserErrors); if (parserErrors.Count > 0) { - tracer.WriteLine(string.Format(CultureInfo.InvariantCulture, - "There were errors parsing string '{0}'", errorMessage); + tracer.WriteLine(string.Create(CultureInfo.InvariantCulture, $"There were errors parsing string '{errorMessage}'"); return errorMessage; } @@ -305,7 +304,7 @@ private enum CompletionNotification #region CompletionEventArgs - private class CompletionEventArgs : EventArgs + private sealed class CompletionEventArgs : EventArgs { internal CompletionEventArgs(CompletionNotification notification) { @@ -318,18 +317,13 @@ internal CompletionEventArgs(CompletionNotification notification) #endregion #region Private Data + // operation handles are owned by WSMan - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManSessionHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManShellOperationHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManReceiveOperationHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManSendOperationHandle; + // this is used with WSMan callbacks to represent a session transport manager. private long _sessionContextID; @@ -926,7 +920,9 @@ internal override void ConnectAsync() { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format - string base64EncodedDataInXml = string.Format(CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}", + string base64EncodedDataInXml = string.Format( + CultureInfo.InvariantCulture, + "<{0} xmlns=\"{1}\">{2}", WSManNativeApi.PS_CONNECT_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, Convert.ToBase64String(additionalData)); @@ -1034,7 +1030,7 @@ internal override void StartReceivingData() /// /// WSManCreateShellEx failed. /// - internal override void CreateAsync() + public override void CreateAsync() { Dbg.Assert(!isClosed, "object already disposed"); Dbg.Assert(!string.IsNullOrEmpty(ConnectionInfo.ShellUri), "shell uri cannot be null or empty."); @@ -1097,7 +1093,9 @@ internal override void CreateAsync() { // WSMan expects the data to be in XML format (which is text + xml tags) // so convert byte[] into base64 encoded format - string base64EncodedDataInXml = string.Format(CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}", + string base64EncodedDataInXml = string.Format( + CultureInfo.InvariantCulture, + "<{0} xmlns=\"{1}\">{2}", WSManNativeApi.PS_CREATION_XML_TAG, WSManNativeApi.PS_XML_NAMESPACE, Convert.ToBase64String(additionalData)); @@ -1189,7 +1187,7 @@ internal override void CreateAsync() /// Closes the pending Create,Send,Receive operations and then closes the shell and release all the resources. /// The caller should make sure this method is called only after calling ConnectAsync. /// - internal override void CloseAsync() + public override void CloseAsync() { bool shouldRaiseCloseCompleted = false; // let other threads release the lock before we clean up the resources. @@ -1255,7 +1253,7 @@ internal override void CloseAsync() /// Server negotiated protocol version. internal void AdjustForProtocolVariations(Version serverProtocolVersion) { - if (serverProtocolVersion <= RemotingConstants.ProtocolVersionWin7RTM) + if (serverProtocolVersion <= RemotingConstants.ProtocolVersion_2_1) { int maxEnvSize; WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle, @@ -1399,7 +1397,8 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) if (string.IsNullOrEmpty(connectionUri.Query)) { // if there is no query string already, create one..see RFC 3986 - connectionStr = string.Format(CultureInfo.InvariantCulture, + connectionStr = string.Format( + CultureInfo.InvariantCulture, "{0}?PSVersion={1}{2}", // Trimming the last '/' as this will allow WSMan to // properly apply URLPrefix. @@ -1413,11 +1412,12 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) else { // if there is already a query string, append using & .. see RFC 3986 - connectionStr = string.Format(CultureInfo.InvariantCulture, - "{0};PSVersion={1}{2}", - connectionStr, - PSVersionInfo.PSVersion, - additionalUriSuffixString); + connectionStr = string.Format( + CultureInfo.InvariantCulture, + "{0};PSVersion={1}{2}", + connectionStr, + PSVersionInfo.PSVersion, + additionalUriSuffixString); } WSManNativeApi.BaseWSManAuthenticationCredentials authCredentials; @@ -1492,20 +1492,9 @@ private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo) finally { // release resources - if (proxyAuthCredentials != null) - { - proxyAuthCredentials.Dispose(); - } - - if (proxyInfo != null) - { - proxyInfo.Dispose(); - } - - if (authCredentials != null) - { - authCredentials.Dispose(); - } + proxyAuthCredentials?.Dispose(); + proxyInfo?.Dispose(); + authCredentials?.Dispose(); } if (result != 0) @@ -1640,7 +1629,7 @@ internal void ProcessWSManTransportError(TransportErrorOccuredEventArgs eventArg /// Log the error message in the Crimson logger and raise error handler. /// /// - internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) + public override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) { // Look for a valid stack trace. string stackTrace; @@ -1790,7 +1779,10 @@ internal IntPtr SessionHandle /// True if a session create retry has been started. private bool RetrySessionCreation(int sessionCreateErrorCode) { - if (_connectionRetryCount >= ConnectionInfo.MaxConnectionRetryCount) { return false; } + if (_connectionRetryCount >= ConnectionInfo.MaxConnectionRetryCount) + { + return false; + } bool retryConnect; switch (sessionCreateErrorCode) @@ -2543,7 +2535,7 @@ private void SendData(byte[] data, DataPriorityType priorityType) #region Dispose / Destructor pattern [SuppressMessage("Microsoft.Usage", "CA2213:DisposableFieldsShouldBeDisposed")] - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { tracer.WriteLine("Disposing session with session context: {0} Operation Context: {1}", _sessionContextID, _wsManShellOperationHandle); @@ -2623,7 +2615,10 @@ private void CloseSessionAndClearResources() private void DisposeWSManAPIDataAsync() { WSManAPIDataCommon tempWSManApiData = WSManAPIData; - if (tempWSManApiData == null) { return; } + if (tempWSManApiData == null) + { + return; + } WSManAPIData = null; @@ -2643,7 +2638,6 @@ private void DisposeWSManAPIDataAsync() /// internal class WSManAPIDataCommon : IDisposable { - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _handle; // if any private WSManNativeApi.WSManStreamIDSet_ManToUn _inputStreamSet; @@ -2726,7 +2720,10 @@ public void Dispose() { lock (_syncObject) { - if (_isDisposed) { return; } + if (_isDisposed) + { + return; + } _isDisposed = true; } @@ -2788,18 +2785,11 @@ internal sealed class WSManClientCommandTransportManager : BaseClientCommandTran // operation handles private readonly IntPtr _wsManShellOperationHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManCmdOperationHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _cmdSignalOperationHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManReceiveOperationHandle; - - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private IntPtr _wsManSendOperationHandle; + // this is used with WSMan callbacks to represent a command transport manager. private long _cmdContextId; @@ -2833,7 +2823,7 @@ internal sealed class WSManClientCommandTransportManager : BaseClientCommandTran private readonly string _cmdLine; private readonly WSManClientSessionTransportManager _sessnTm; - private class SendDataChunk + private sealed class SendDataChunk { public SendDataChunk(byte[] data, DataPriorityType type) { @@ -3013,11 +3003,12 @@ internal override void ConnectAsync() } /// + /// Begin connection creation. /// /// /// WSManRunShellCommandEx failed. /// - internal override void CreateAsync() + public override void CreateAsync() { byte[] cmdPart1 = serializedPipeline.ReadOrRegisterCallback(null); if (cmdPart1 != null) @@ -3146,7 +3137,7 @@ internal override void SendStopSignal() /// /// Closes the pending Create,Send,Receive operations and then closes the shell and release all the resources. /// - internal override void CloseAsync() + public override void CloseAsync() { tracer.WriteLine("Closing command with command context: {0} Operation Context {1}", _cmdContextId, _wsManCmdOperationHandle); @@ -3213,7 +3204,7 @@ internal void ProcessWSManTransportError(TransportErrorOccuredEventArgs eventArg /// Log the error message in the Crimson logger and raise error handler. /// /// - internal override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) + public override void RaiseErrorHandler(TransportErrorOccuredEventArgs eventArgs) { // Look for a valid stack trace. string stackTrace; @@ -4086,7 +4077,7 @@ internal override void StartReceivingData() #region Dispose / Destructor pattern - internal override void Dispose(bool isDisposing) + protected override void Dispose(bool isDisposing) { tracer.WriteLine("Disposing command with command context: {0} Operation Context: {1}", _cmdContextId, _wsManCmdOperationHandle); base.Dispose(isDisposing); diff --git a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs index 1c2728cc6d6..6c794e21b24 100644 --- a/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs +++ b/src/System.Management.Automation/engine/remoting/server/OutOfProcServerMediator.cs @@ -8,7 +8,6 @@ #if !UNIX using System.Security.Principal; #endif -using Microsoft.Win32.SafeHandles; using Dbg = System.Management.Automation.Diagnostics; @@ -73,14 +72,6 @@ protected void ProcessingThreadStart(object state) { try { -#if !CORECLR - // CurrentUICulture is not available in Thread Class in CSS - // WinBlue: 621775. Thread culture is not properly set - // for local background jobs causing experience differences - // between local console and local background jobs. - Thread.CurrentThread.CurrentUICulture = Microsoft.PowerShell.NativeCultureResolver.UICulture; - Thread.CurrentThread.CurrentCulture = Microsoft.PowerShell.NativeCultureResolver.Culture; -#endif string data = state as string; OutOfProcessUtils.ProcessData(data, callbacks); } @@ -209,10 +200,7 @@ protected void OnSignalPacketReceived(Guid psGuid) } // dont throw if there is no cmdTM as it might have legitimately closed - if (cmdTM != null) - { - cmdTM.Close(null); - } + cmdTM?.Close(null); } finally { @@ -253,12 +241,9 @@ protected void OnClosePacketReceived(Guid psGuid) { tracer.WriteMessage("OnClosePacketReceived, in progress commands count should be zero : " + _inProgressCommandsCount + ", psGuid : " + psGuid.ToString()); - if (sessionTM != null) - { - // it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests - // changing PSRP/IPC at this point is too risky, therefore protecting about this duplication - sessionTM.Close(null); - } + // it appears that when closing PowerShell ISE, therefore closing OutOfProcServerMediator, there are 2 Close command requests + // changing PSRP/IPC at this point is too risky, therefore protecting about this duplication + sessionTM?.Close(null); tracer.WriteMessage("END calling close on session transport manager"); sessionTM = null; @@ -277,10 +262,7 @@ protected void OnClosePacketReceived(Guid psGuid) } // dont throw if there is no cmdTM as it might have legitimately closed - if (cmdTM != null) - { - cmdTM.Close(null); - } + cmdTM?.Close(null); lock (_syncObject) { @@ -307,7 +289,11 @@ protected void OnCloseAckPacketReceived(Guid psGuid) #region Methods - protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager(string configurationName, PSRemotingCryptoHelperServer cryptoHelper, string workingDirectory) + protected OutOfProcessServerSessionTransportManager CreateSessionTransportManager( + string configurationName, + string configurationFile, + PSRemotingCryptoHelperServer cryptoHelper, + string workingDirectory) { PSSenderInfo senderInfo; #if !UNIX @@ -323,23 +309,38 @@ protected OutOfProcessServerSessionTransportManager CreateSessionTransportManage senderInfo = new PSSenderInfo(userPrincipal, "http://localhost"); #endif - OutOfProcessServerSessionTransportManager tm = new OutOfProcessServerSessionTransportManager(originalStdOut, originalStdErr, cryptoHelper); + var tm = new OutOfProcessServerSessionTransportManager( + originalStdOut, + originalStdErr, + cryptoHelper); ServerRemoteSession.CreateServerRemoteSession( - senderInfo, - _initialCommand, - tm, - configurationName, - workingDirectory); + senderInfo: senderInfo, + configurationProviderId: "Microsoft.PowerShell", + initializationParameters: string.Empty, + transportManager: tm, + initialCommand: _initialCommand, + configurationName: configurationName, + configurationFile: configurationFile, + initialLocation: workingDirectory); return tm; } - protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoHelper, string workingDirectory = null, string configurationName = null) + protected void Start( + string initialCommand, + PSRemotingCryptoHelperServer cryptoHelper, + string workingDirectory, + string configurationName, + string configurationFile) { _initialCommand = initialCommand; - sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper, workingDirectory); + sessionTM = CreateSessionTransportManager( + configurationName: configurationName, + configurationFile: configurationFile, + cryptoHelper: cryptoHelper, + workingDirectory: workingDirectory); try { @@ -348,10 +349,11 @@ protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoH string data = originalStdIn.ReadLine(); lock (_syncObject) { - if (sessionTM == null) - { - sessionTM = CreateSessionTransportManager(configurationName, cryptoHelper, workingDirectory); - } + sessionTM ??= CreateSessionTransportManager( + configurationName: configurationName, + configurationFile: configurationFile, + cryptoHelper: cryptoHelper, + workingDirectory: workingDirectory); } if (string.IsNullOrEmpty(data)) @@ -417,35 +419,13 @@ protected void Start(string initialCommand, PSRemotingCryptoHelperServer cryptoH } #endregion - - #region Static Methods - - internal static void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs args) - { - // args can never be null. - Exception exception = (Exception)args.ExceptionObject; - // log the exception to crimson event logs - PSEtwLog.LogOperationalError(PSEventId.AppDomainUnhandledException, - PSOpcode.Close, PSTask.None, - PSKeyword.UseAlwaysOperational, - exception.GetType().ToString(), exception.Message, - exception.StackTrace); - - PSEtwLog.LogAnalyticError(PSEventId.AppDomainUnhandledException_Analytic, - PSOpcode.Close, PSTask.None, - PSKeyword.ManagedPlugin | PSKeyword.UseAlwaysAnalytic, - exception.GetType().ToString(), exception.Message, - exception.StackTrace); - } - - #endregion } - internal sealed class OutOfProcessMediator : OutOfProcessMediatorBase + internal sealed class StdIOProcessMediator : OutOfProcessMediatorBase { #region Private Data - private static OutOfProcessMediator s_singletonInstance; + private static StdIOProcessMediator s_singletonInstance; #endregion @@ -453,10 +433,11 @@ internal sealed class OutOfProcessMediator : OutOfProcessMediatorBase /// /// The mediator will take actions from the StdIn stream and responds to them. - /// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null's. This is + /// It will replace StdIn,StdOut and StdErr stream with TextWriter.Null. This is /// to make sure these streams are totally used by our Mediator. /// - private OutOfProcessMediator() : base(true) + /// Redirects remoting errors to the Out stream. + private StdIOProcessMediator(bool combineErrOutStream) : base(exitProcessOnError: true) { // Create input stream reader from Console standard input stream. // We don't use the provided Console.In TextReader because it can have @@ -466,18 +447,22 @@ private OutOfProcessMediator() : base(true) // stream BOM as needed. originalStdIn = new StreamReader(Console.OpenStandardInput(), true); - // replacing StdIn with Null so that no other app messes with the - // original stream. - Console.SetIn(TextReader.Null); - - // replacing StdOut with Null so that no other app messes with the - // original stream + // Remoting errors can optionally be written to stdErr or stdOut with + // special formatting. originalStdOut = new OutOfProcessTextWriter(Console.Out); - Console.SetOut(TextWriter.Null); + if (combineErrOutStream) + { + originalStdErr = new FormattedErrorTextWriter(Console.Out); + } + else + { + originalStdErr = new OutOfProcessTextWriter(Console.Error); + } - // replacing StdErr with Null so that no other app messes with the - // original stream - originalStdErr = new OutOfProcessTextWriter(Console.Error); + // Replacing StdIn, StdOut, StdErr with Null so that no other app messes with the + // original streams. + Console.SetIn(TextReader.Null); + Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); } @@ -490,72 +475,15 @@ private OutOfProcessMediator() : base(true) /// /// Specifies the initialization script. /// Specifies the initial working directory. The working directory is set before the initial command. - internal static void Run(string initialCommand, string workingDirectory) - { - lock (SyncObject) - { - if (s_singletonInstance != null) - { - Dbg.Assert(false, "Run should not be called multiple times"); - return; - } - - s_singletonInstance = new OutOfProcessMediator(); - } - -#if !CORECLR // AppDomain is not available in CoreCLR - // Setup unhandled exception to log events - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException); -#endif - s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer(), workingDirectory); - } - - #endregion - } - - internal sealed class SSHProcessMediator : OutOfProcessMediatorBase - { - #region Private Data - - private static SSHProcessMediator s_singletonInstance; - - #endregion - - #region Constructors - - private SSHProcessMediator() : base(true) - { -#if !UNIX - var inputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Input); - originalStdIn = new StreamReader( - new FileStream(new SafeFileHandle(inputHandle, false), FileAccess.Read)); - - var outputHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Output); - originalStdOut = new OutOfProcessTextWriter( - new StreamWriter( - new FileStream(new SafeFileHandle(outputHandle, false), FileAccess.Write))); - - var errorHandle = PlatformInvokes.GetStdHandle((uint)PlatformInvokes.StandardHandleId.Error); - originalStdErr = new OutOfProcessTextWriter( - new StreamWriter( - new FileStream(new SafeFileHandle(errorHandle, false), FileAccess.Write))); -#else - originalStdIn = new StreamReader(Console.OpenStandardInput(), true); - originalStdOut = new OutOfProcessTextWriter( - new StreamWriter(Console.OpenStandardOutput())); - originalStdErr = new OutOfProcessTextWriter( - new StreamWriter(Console.OpenStandardError())); -#endif - } - - #endregion - - #region Static Methods - - /// - /// - /// - internal static void Run(string initialCommand) + /// Specifies an optional configuration name that configures the endpoint session. + /// Specifies an optional path to a configuration (.pssc) file for the session. + /// Specifies the option to write remoting errors to stdOut stream, with special formatting. + internal static void Run( + string initialCommand, + string workingDirectory, + string configurationName, + string configurationFile, + bool combineErrOutStream) { lock (SyncObject) { @@ -565,10 +493,15 @@ internal static void Run(string initialCommand) return; } - s_singletonInstance = new SSHProcessMediator(); + s_singletonInstance = new StdIOProcessMediator(combineErrOutStream); } - s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer()); + s_singletonInstance.Start( + initialCommand: initialCommand, + cryptoHelper: new PSRemotingCryptoHelperServer(), + workingDirectory: workingDirectory, + configurationName: configurationName, + configurationFile: configurationFile); } #endregion @@ -610,7 +543,7 @@ private NamedPipeProcessMediator( // Create transport reader/writers from named pipe. originalStdIn = namedPipeServer.TextReader; originalStdOut = new OutOfProcessTextWriter(namedPipeServer.TextWriter); - originalStdErr = new NamedPipeErrorTextWriter(namedPipeServer.TextWriter); + originalStdErr = new FormattedErrorTextWriter(namedPipeServer.TextWriter); #if !UNIX // Flow impersonation as needed. @@ -637,36 +570,22 @@ internal static void Run( s_singletonInstance = new NamedPipeProcessMediator(namedPipeServer); } -#if !CORECLR - // AppDomain is not available in CoreCLR - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException); -#endif - s_singletonInstance.Start(initialCommand, new PSRemotingCryptoHelperServer(), namedPipeServer.ConfigurationName); + s_singletonInstance.Start( + initialCommand: initialCommand, + cryptoHelper: new PSRemotingCryptoHelperServer(), + workingDirectory: null, + configurationName: namedPipeServer.ConfigurationName, + configurationFile: null); } #endregion } - internal sealed class NamedPipeErrorTextWriter : OutOfProcessTextWriter + internal sealed class FormattedErrorTextWriter : OutOfProcessTextWriter { - #region Private Members - - private const string _errorPrepend = "__NamedPipeError__:"; - - #endregion - - #region Properties - - internal static string ErrorPrepend - { - get { return _errorPrepend; } - } - - #endregion - #region Constructors - internal NamedPipeErrorTextWriter( + internal FormattedErrorTextWriter( TextWriter textWriter) : base(textWriter) { } @@ -674,9 +593,11 @@ internal NamedPipeErrorTextWriter( #region Base class overrides - internal override void WriteLine(string data) + // Write error data to stream with 'ErrorPrefix' prefix that will + // be interpreted by the client. + public override void WriteLine(string data) { - string dataToWrite = (data != null) ? _errorPrepend + data : null; + string dataToWrite = (data != null) ? ErrorPrefix + data : null; base.WriteLine(dataToWrite); } @@ -714,6 +635,16 @@ private HyperVSocketMediator() originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter); } + private HyperVSocketMediator(string token, + DateTimeOffset tokenCreationTime) + : base(false) + { + _hypervSocketServer = new RemoteSessionHyperVSocketServer(false, token: token, tokenCreationTime: tokenCreationTime); + + originalStdIn = _hypervSocketServer.TextReader; + originalStdOut = new OutOfProcessTextWriter(_hypervSocketServer.TextWriter); + originalStdErr = new HyperVSocketErrorTextWriter(_hypervSocketServer.TextWriter); + } #endregion #region Static Methods @@ -727,14 +658,32 @@ internal static void Run( s_instance = new HyperVSocketMediator(); } -#if !CORECLR - // AppDomain is not available in CoreCLR - AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomainUnhandledException); -#endif - - s_instance.Start(initialCommand, new PSRemotingCryptoHelperServer(), configurationName); + s_instance.Start( + initialCommand: initialCommand, + cryptoHelper: new PSRemotingCryptoHelperServer(), + workingDirectory: null, + configurationName: configurationName, + configurationFile: null); } + internal static void Run( + string initialCommand, + string configurationName, + string token, + DateTimeOffset tokenCreationTime) + { + lock (SyncObject) + { + s_instance = new HyperVSocketMediator(token, tokenCreationTime); + } + + s_instance.Start( + initialCommand: initialCommand, + cryptoHelper: new PSRemotingCryptoHelperServer(), + workingDirectory: null, + configurationName: configurationName, + configurationFile: null); + } #endregion } @@ -766,7 +715,7 @@ internal HyperVSocketErrorTextWriter( #region Base class overrides - internal override void WriteLine(string data) + public override void WriteLine(string data) { string dataToWrite = (data != null) ? _errorPrepend + data : null; base.WriteLine(dataToWrite); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs index 6a49d6f3a4a..ddeb81aae17 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerPowerShellDriver.cs @@ -427,7 +427,10 @@ private void HandlePowerShellInvocationStateChanged(object sender, if (LocalPowerShell.RunningExtraCommands) { // If completed successfully then allow extra commands to run. - if (state == PSInvocationState.Completed) { return; } + if (state == PSInvocationState.Completed) + { + return; + } // For failed or stopped state, extra commands cannot run and // we allow this command invocation to finish. @@ -798,11 +801,9 @@ private void HandleSessionConnected(object sender, EventArgs eventArgs) { // Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin - if (InputCollection != null) - { - // TODO: Post an ETW event - InputCollection.Complete(); - } + + // TODO: Post an ETW event + InputCollection?.Complete(); } /// diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs index ca7ff805c02..71dda0d0b7a 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHost.cs @@ -327,7 +327,7 @@ public override void PushRunspace(Runspace runspace) throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostAlreadyPushed); } - if (!(runspace is RemoteRunspace remoteRunspace)) + if (runspace is not RemoteRunspace remoteRunspace) { throw new PSInvalidOperationException(RemotingErrorIdStrings.ServerDriverRemoteHostNotRemoteRunspace); } @@ -352,10 +352,7 @@ public override void PopRunspace() { if (_pushedRunspace != null) { - if (_debugger != null) - { - _debugger.PopDebugger(); - } + _debugger?.PopDebugger(); if (_hostSupportsPSEdit) { @@ -410,7 +407,10 @@ internal bool PropagatePop private void AddPSEditForRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace.Events == null) { return; } + if (remoteRunspace.Events == null) + { + return; + } // Add event handler. remoteRunspace.Events.ReceivedEvents.PSEventReceived += HandleRemoteSessionForwardedEvent; @@ -430,7 +430,10 @@ private void AddPSEditForRunspace(RemoteRunspace remoteRunspace) private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace) { - if (remoteRunspace.Events == null) { return; } + if (remoteRunspace.Events == null) + { + return; + } // It is possible for the popped runspace to be in a bad state after an error. if ((remoteRunspace.RunspaceStateInfo.State != RunspaceState.Opened) || (remoteRunspace.RunspaceAvailability != RunspaceAvailability.Available)) @@ -456,7 +459,10 @@ private void RemovePSEditFromRunspace(RemoteRunspace remoteRunspace) private void HandleRemoteSessionForwardedEvent(object sender, PSEventArgs args) { - if ((Runspace == null) || (Runspace.Events == null)) { return; } + if ((Runspace == null) || (Runspace.Events == null)) + { + return; + } // Forward events from nested pushed session to parent session. try diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs index 05448d02d9b..34c10e0a9a0 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostRawUserInterface.cs @@ -343,10 +343,7 @@ public override void SetBufferContents(Coordinates origin, BufferCell[,] content // to keep the other overload in sync: LengthInBufferCells(string, int) public override int LengthInBufferCells(string source) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); return source.Length; } @@ -354,10 +351,7 @@ public override int LengthInBufferCells(string source) // more performant than the default implementation provided by PSHostRawUserInterface public override int LengthInBufferCells(string source, int offset) { - if (source == null) - { - throw new ArgumentNullException(nameof(source)); - } + ArgumentNullException.ThrowIfNull(source); Dbg.Assert(offset >= 0, "offset >= 0"); Dbg.Assert(string.IsNullOrEmpty(source) || (offset < source.Length), "offset < source.Length"); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs index 314fc25587f..76265089677 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemoteHostUserInterface.cs @@ -122,6 +122,7 @@ public override Dictionary Prompt(string caption, string messa /// public override void Write(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.Write1, new object[] { message }); } @@ -130,6 +131,7 @@ public override void Write(string message) /// public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.Write2, new object[] { foregroundColor, backgroundColor, message }); } @@ -146,6 +148,7 @@ public override void WriteLine() /// public override void WriteLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine2, new object[] { message }); } @@ -154,6 +157,7 @@ public override void WriteLine(string message) /// public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteLine3, new object[] { foregroundColor, backgroundColor, message }); } @@ -162,6 +166,7 @@ public override void WriteLine(ConsoleColor foregroundColor, ConsoleColor backgr /// public override void WriteErrorLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteErrorLine, new object[] { message }); } @@ -170,6 +175,7 @@ public override void WriteErrorLine(string message) /// public override void WriteDebugLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteDebugLine, new object[] { message }); } @@ -186,6 +192,7 @@ public override void WriteProgress(long sourceId, ProgressRecord record) /// public override void WriteVerboseLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteVerboseLine, new object[] { message }); } @@ -194,6 +201,7 @@ public override void WriteVerboseLine(string message) /// public override void WriteWarningLine(string message) { + message = GetOutputString(message, supportsVirtualTerminal: true); _serverMethodExecutor.ExecuteVoidMethod(RemoteHostMethodId.WriteWarningLine, new object[] { message }); } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs index f87f89b5bac..11761c25af8 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRemotingProtocol2.cs @@ -266,10 +266,7 @@ internal void DispatchMessageToPowerShell(RemoteDataObject rcvdData) // if data structure handler is not found, then association has already been // removed, discard message - if (dsHandler != null) - { - dsHandler.ProcessReceivedData(rcvdData); - } + dsHandler?.ProcessReceivedData(rcvdData); } /// @@ -351,7 +348,7 @@ internal TypeTable TypeTable /// /// Data to send. /// This overload takes a RemoteDataObject and should - /// be the one thats used to send data from within this + /// be the one that's used to send data from within this /// data structure handler class private void SendDataAsync(RemoteDataObject data) { @@ -788,7 +785,7 @@ internal Runspace RunspaceUsedToInvokePowerShell /// /// Data to send. /// This overload takes a RemoteDataObject and should - /// be the one thats used to send data from within this + /// be the one that's used to send data from within this /// data structure handler class private void SendDataAsync(RemoteDataObject data) { diff --git a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs index 2f2675e61d0..a5e0da4968e 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerRunspacePoolDriver.cs @@ -168,7 +168,7 @@ internal ServerRunspacePoolDriver( // The default server settings is to make new commands execute in the calling thread...this saves // thread switching time and thread pool pressure on the service. // Users can override the server settings only if they are administrators - PSThreadOptions serverThreadOptions = configData.ShellThreadOptions.HasValue ? configData.ShellThreadOptions.Value : PSThreadOptions.UseCurrentThread; + PSThreadOptions serverThreadOptions = configData.ShellThreadOptions ?? PSThreadOptions.UseCurrentThread; if (threadOptions == PSThreadOptions.Default || threadOptions == serverThreadOptions) { RunspacePool.ThreadOptions = serverThreadOptions; @@ -184,7 +184,7 @@ internal ServerRunspacePoolDriver( } // Set Thread ApartmentState for this RunspacePool - ApartmentState serverApartmentState = configData.ShellThreadApartmentState.HasValue ? configData.ShellThreadApartmentState.Value : Runspace.DefaultApartmentState; + ApartmentState serverApartmentState = configData.ShellThreadApartmentState ?? Runspace.DefaultApartmentState; if (apartmentState == ApartmentState.Unknown || apartmentState == serverApartmentState) { @@ -271,10 +271,7 @@ internal void Start() internal void SendApplicationPrivateDataToClient() { // Include Debug mode information. - if (_applicationPrivateData == null) - { - _applicationPrivateData = new PSPrimitiveDictionary(); - } + _applicationPrivateData ??= new PSPrimitiveDictionary(); if (_serverRemoteDebugger != null) { @@ -350,10 +347,7 @@ internal void Close() { Runspace runspaceToDispose = _remoteHost.PushedRunspace; _remoteHost.PopRunspace(); - if (runspaceToDispose != null) - { - runspaceToDispose.Dispose(); - } + runspaceToDispose?.Dispose(); } DisposeRemoteDebugger(); @@ -478,7 +472,7 @@ private void SetupRemoteDebugger(Runspace runspace) // Remote debugger is created only when client version is PSVersion (4.0) // or greater, and remote session supports debugging. if ((_driverNestedInvoker != null) && - (_clientPSVersion != null && _clientPSVersion >= PSVersionInfo.PSV4Version) && + (_clientPSVersion != null && _clientPSVersion.Major >= 4) && (runspace != null && runspace.Debugger != null)) { _serverRemoteDebugger = new ServerRemoteDebugger(this, runspace, runspace.Debugger); @@ -486,13 +480,7 @@ private void SetupRemoteDebugger(Runspace runspace) } } - private void DisposeRemoteDebugger() - { - if (_serverRemoteDebugger != null) - { - _serverRemoteDebugger.Dispose(); - } - } + private void DisposeRemoteDebugger() => _serverRemoteDebugger?.Dispose(); /// /// Invokes a script. @@ -561,7 +549,7 @@ private PSDataCollection InvokePowerShell(PowerShell powershell, Runsp Exception lastException = errorList[0] as Exception; if (lastException != null) { - exceptionThrown = (lastException.Message != null) ? lastException.Message : string.Empty; + exceptionThrown = lastException.Message ?? string.Empty; } else { @@ -728,7 +716,7 @@ private void HandleCreateAndInvokePowerShell(object _, RemoteDataEventArgs= RemotingConstants.ProtocolVersionWin8RTM) + if (_serverCapability.ProtocolVersion >= RemotingConstants.ProtocolVersion_2_2) { isNested = RemotingDecoder.GetIsNested(data.Data); } @@ -812,10 +800,7 @@ private void HandleCreateAndInvokePowerShell(object _, RemoteDataEventArgs publicGetCommandEntries = iss .Commands["Get-Command"] - .Where(entry => entry.Visibility == SessionStateEntryVisibility.Public); + .Where(static entry => entry.Visibility == SessionStateEntryVisibility.Public); SessionStateFunctionEntry getCommandProxy = publicGetCommandEntries.OfType().FirstOrDefault(); if (getCommandProxy != null) { @@ -1252,7 +1234,7 @@ private enum PreProcessCommandResult BreakpointManagement, } - private class DebuggerCommandArgument + private sealed class DebuggerCommandArgument { public DebugModes? Mode { get; set; } @@ -2004,10 +1986,7 @@ public override DebuggerCommandResults ProcessCommand(PSCommand command, PSDataC StringUtil.Format(DebuggerStrings.CannotProcessDebuggerCommandNotStopped)); } - if (_processCommandCompleteEvent == null) - { - _processCommandCompleteEvent = new ManualResetEventSlim(false); - } + _processCommandCompleteEvent ??= new ManualResetEventSlim(false); _threadCommandProcessing = new ThreadCommandProcessing(command, output, _wrappedDebugger.Value, _processCommandCompleteEvent); try @@ -2031,10 +2010,7 @@ public override void StopProcessCommand() } ThreadCommandProcessing threadCommandProcessing = _threadCommandProcessing; - if (threadCommandProcessing != null) - { - threadCommandProcessing.Stop(); - } + threadCommandProcessing?.Stop(); } /// @@ -2232,15 +2208,8 @@ public void Dispose() ExitDebugMode(DebuggerResumeAction.Stop); } - if (_nestedDebugStopCompleteEvent != null) - { - _nestedDebugStopCompleteEvent.Dispose(); - } - - if (_processCommandCompleteEvent != null) - { - _processCommandCompleteEvent.Dispose(); - } + _nestedDebugStopCompleteEvent?.Dispose(); + _processCommandCompleteEvent?.Dispose(); } #endregion @@ -2312,10 +2281,7 @@ public DebuggerCommandResults Invoke(ManualResetEventSlim startInvokeEvent) public void Stop() { Debugger debugger = _wrappedDebugger; - if (debugger != null) - { - debugger.StopProcessCommand(); - } + debugger?.StopProcessCommand(); } internal void DoInvoke() @@ -2420,7 +2386,10 @@ private void RemoveDebuggerCallbacks() private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) { // Ignore if we are in restricted mode. - if (!IsDebuggingSupported()) { return; } + if (!IsDebuggingSupported()) + { + return; + } if (LocalDebugMode) { @@ -2476,7 +2445,10 @@ private void HandleDebuggerStop(object sender, DebuggerStopEventArgs e) private void HandleBreakpointUpdated(object sender, BreakpointUpdatedEventArgs e) { // Ignore if we are in restricted mode. - if (!IsDebuggingSupported()) { return; } + if (!IsDebuggingSupported()) + { + return; + } if (LocalDebugMode) { @@ -2527,10 +2499,7 @@ private void EnterDebugMode(bool isNestedStop) { // Blocking call for nested debugger execution (Debug-Runspace) stop events. // The root debugger never makes two EnterDebugMode calls without an ExitDebugMode. - if (_nestedDebugStopCompleteEvent == null) - { - _nestedDebugStopCompleteEvent = new ManualResetEventSlim(false); - } + _nestedDebugStopCompleteEvent ??= new ManualResetEventSlim(false); _nestedDebugging = true; OnEnterDebugMode(_nestedDebugStopCompleteEvent); @@ -2799,7 +2768,10 @@ internal void PushDebugger(Debugger debugger) internal void PopDebugger() { - if (!_wrappedDebugger.IsOverridden) { return; } + if (!_wrappedDebugger.IsOverridden) + { + return; + } // Swap wrapped debugger. UnsubscribeWrappedDebugger(_wrappedDebugger.Value); diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs index 66fe9d92730..3a9388625e6 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineDriver.cs @@ -14,7 +14,7 @@ namespace System.Management.Automation /// /// Execution context used for stepping. /// - internal class ExecutionContextForStepping : IDisposable + internal sealed class ExecutionContextForStepping : IDisposable { private readonly ExecutionContext _executionContext; private PSInformationalBuffers _originalInformationalBuffers; @@ -241,10 +241,7 @@ internal void Start() _eventSubscriber.FireStartSteppablePipeline(this); - if (_powershellInput != null) - { - _powershellInput.Pulse(); - } + _powershellInput?.Pulse(); } #endregion Internal Methods @@ -262,20 +259,14 @@ internal void HandleInputEndReceived(object sender, EventArgs eventArgs) CheckAndPulseForProcessing(true); - if (_powershellInput != null) - { - _powershellInput.Pulse(); - } + _powershellInput?.Pulse(); } private void HandleSessionConnected(object sender, EventArgs eventArgs) { // Close input if its active. no need to synchronize as input stream would have already been processed // when connect call came into PS plugin - if (Input != null) - { - Input.Complete(); - } + Input?.Complete(); } /// @@ -302,10 +293,7 @@ private void HandleStopReceived(object sender, EventArgs eventArgs) PerformStop(); - if (_powershellInput != null) - { - _powershellInput.Pulse(); - } + _powershellInput?.Pulse(); } /// @@ -326,10 +314,7 @@ private void HandleInputReceived(object sender, RemoteDataEventArgs even CheckAndPulseForProcessing(false); - if (_powershellInput != null) - { - _powershellInput.Pulse(); - } + _powershellInput?.Pulse(); } } diff --git a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs index 328571647cb..cce8b0bbcd3 100644 --- a/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs +++ b/src/System.Management.Automation/engine/remoting/server/ServerSteppablePipelineSubscriber.cs @@ -162,7 +162,7 @@ private void HandleProcessRecord(object sender, PSEventArgs args) if (!driver.NoInput || isProcessCalled) { // if there is noInput then we - // need to call process atleast once + // need to call process at least once break; } } @@ -274,11 +274,8 @@ internal void FireStartSteppablePipeline(ServerSteppablePipelineDriver driver) { lock (_syncObject) { - if (_eventManager != null) - { - _eventManager.GenerateEvent(_startSubscriber.SourceIdentifier, this, - new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); - } + _eventManager?.GenerateEvent(_startSubscriber.SourceIdentifier, this, + new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); } } @@ -290,11 +287,8 @@ internal void FireHandleProcessRecord(ServerSteppablePipelineDriver driver) { lock (_syncObject) { - if (_eventManager != null) - { - _eventManager.GenerateEvent(_processSubscriber.SourceIdentifier, this, - new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); - } + _eventManager?.GenerateEvent(_processSubscriber.SourceIdentifier, this, + new object[1] { new ServerSteppablePipelineDriverEventArg(driver) }, null, true, false); } } diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs index 7b08c674301..b1e05909d2c 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesession.cs @@ -69,7 +69,7 @@ internal ServerRemoteSessionContext() /// internal class ServerRemoteSession : RemoteSession { - [TraceSourceAttribute("ServerRemoteSession", "ServerRemoteSession")] + [TraceSource("ServerRemoteSession", "ServerRemoteSession")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSession", "ServerRemoteSession"); private readonly PSSenderInfo _senderInfo; @@ -89,6 +89,10 @@ internal class ServerRemoteSession : RemoteSession // Creates a pushed remote runspace session created with this configuration name. private string _configurationName; + // Specifies an optional .pssc configuration file path for out-of-proc session use. + // The .pssc file is used to configure the runspace for the endpoint session. + private string _configurationFile; + // Specifies an initial location of the powershell session. private string _initialLocation; @@ -173,7 +177,9 @@ internal ServerRemoteSession(PSSenderInfo senderInfo, /// xml. /// /// + /// Optional initial command used for OutOfProc sessions. /// Optional configuration endpoint name for OutOfProc sessions. + /// Optional configuration file (.pssc) path for OutOfProc sessions. /// Optional configuration initial location of the powershell session. /// /// @@ -192,8 +198,10 @@ internal static ServerRemoteSession CreateServerRemoteSession( string configurationProviderId, string initializationParameters, AbstractServerSessionTransportManager transportManager, - string configurationName = null, - string initialLocation = null) + string initialCommand, + string configurationName, + string configurationFile, + string initialLocation) { Dbg.Assert( (senderInfo != null) && (senderInfo.UserInfo != null), @@ -215,7 +223,9 @@ internal static ServerRemoteSession CreateServerRemoteSession( initializationParameters, transportManager) { + _initScriptForOutOfProcRS = initialCommand, _configurationName = configurationName, + _configurationFile = configurationFile, _initialLocation = initialLocation }; @@ -226,33 +236,6 @@ internal static ServerRemoteSession CreateServerRemoteSession( return result; } - /// - /// Used by OutOfProcessServerMediator to create a remote session. - /// - /// - /// - /// - /// - /// - /// - internal static ServerRemoteSession CreateServerRemoteSession( - PSSenderInfo senderInfo, - string initializationScriptForOutOfProcessRunspace, - AbstractServerSessionTransportManager transportManager, - string configurationName, - string initialLocation) - { - ServerRemoteSession result = CreateServerRemoteSession( - senderInfo, - "Microsoft.PowerShell", - string.Empty, - transportManager, - configurationName: configurationName, - initialLocation: initialLocation); - result._initScriptForOutOfProcRS = initializationScriptForOutOfProcessRunspace; - return result; - } - #endregion #region Overrides @@ -723,13 +706,7 @@ internal void ExecuteConnect(byte[] connectData, out byte[] connectResponseData) } // pass on application private data when session is connected from new client - internal void HandlePostConnect() - { - if (_runspacePoolDriver != null) - { - _runspacePoolDriver.SendApplicationPrivateDataToClient(); - } - } + internal void HandlePostConnect() => _runspacePoolDriver?.SendApplicationPrivateDataToClient(); /// /// @@ -749,20 +726,12 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR RemoteDataObject rcvdData = createRunspaceEventArg.ReceivedData; Dbg.Assert(rcvdData != null, "rcvdData must be non-null"); - // set the PSSenderInfo sent in the first packets - // This is used by the initial session state configuration providers like Exchange. - if (Context != null) - { - _senderInfo.ClientTimeZone = Context.ClientCapability.TimeZone; - } - _senderInfo.ApplicationArguments = RemotingDecoder.GetApplicationArguments(rcvdData.Data); // Get Initial Session State from custom session config suppliers // like Exchange. ConfigurationDataFromXML configurationData = - PSSessionConfiguration.LoadEndPointConfiguration(_configProviderId, - _initParameters); + PSSessionConfiguration.LoadEndPointConfiguration(_configProviderId, _initParameters); // used by Out-Of-Proc (IPC) runspace. configurationData.InitializationScriptForOutOfProcessRunspace = _initScriptForOutOfProcRS; // start with data from configuration XML and then override with data @@ -770,8 +739,6 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR _maxRecvdObjectSize = configurationData.MaxReceivedObjectSizeMB; _maxRecvdDataSizeCommand = configurationData.MaxReceivedCommandSizeMB; - DISCPowerShellConfiguration discProvider = null; - if (string.IsNullOrEmpty(configurationData.ConfigFilePath)) { _sessionConfigProvider = configurationData.CreateEndPointConfigurationInstance(); @@ -779,11 +746,8 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR else { System.Security.Principal.WindowsPrincipal windowsPrincipal = new System.Security.Principal.WindowsPrincipal(_senderInfo.UserInfo.WindowsIdentity); - Func validator = (role) => windowsPrincipal.IsInRole(role); - - discProvider = new DISCPowerShellConfiguration(configurationData.ConfigFilePath, validator); - _sessionConfigProvider = discProvider; + _sessionConfigProvider = new DISCPowerShellConfiguration(configurationData.ConfigFilePath, validator); } // exchange of ApplicationArguments and ApplicationPrivateData is be done as early as possible @@ -794,6 +758,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR if (configurationData.SessionConfigurationData != null) { + // Use the provided WinRM endpoint runspace configuration information. try { rsSessionStateToUse = @@ -804,8 +769,21 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo); } } + else if (!string.IsNullOrEmpty(_configurationFile)) + { + // Use the optional _configurationFile parameter to create the endpoint runspace configuration. + // This parameter is only used by Out-Of-Proc transports (not WinRM transports). + var discConfiguration = new Remoting.DISCPowerShellConfiguration( + configFile: _configurationFile, + roleVerifier: null, + validateFile: true); + rsSessionStateToUse = discConfiguration.GetInitialSessionState(_senderInfo); + } else { + // Create a runspace configuration based on the provided PSSessionConfiguration provider. + // This can be either a 'default' configuration, or third party configuration PSSessionConfiguration provider object. + // So far, only Exchange provides a custom PSSessionConfiguration provider implementation. rsSessionStateToUse = _sessionConfigProvider.GetInitialSessionState(_senderInfo); } @@ -824,32 +802,14 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR RemotingErrorIdStrings.PSSenderInfoDescription), ScopedItemOptions.ReadOnly)); - // check if the current scenario is Win7(client) to Win8(server). Add back the PSv2 version TabExpansion - // function if necessary. + // Get client PS version from PSSenderInfo. Version psClientVersion = null; if (_senderInfo.ApplicationArguments != null && _senderInfo.ApplicationArguments.ContainsKey("PSversionTable")) { var value = PSObject.Base(_senderInfo.ApplicationArguments["PSversionTable"]) as PSPrimitiveDictionary; - if (value != null) + if (value != null && value.ContainsKey("PSVersion")) { - if (value.ContainsKey("WSManStackVersion")) - { - var wsmanStackVersion = PSObject.Base(value["WSManStackVersion"]) as Version; - if (wsmanStackVersion != null && wsmanStackVersion.Major < 3) - { - // The client side is PSv2. This is the Win7 to Win8 scenario. We need to add the PSv2 - // TabExpansion function back in to keep the tab expansion functionable on the client side. - rsSessionStateToUse.Commands.Add( - new SessionStateFunctionEntry( - RemoteDataNameStrings.PSv2TabExpansionFunction, - RemoteDataNameStrings.PSv2TabExpansionFunctionText)); - } - } - - if (value.ContainsKey("PSVersion")) - { - psClientVersion = PSObject.Base(value["PSVersion"]) as Version; - } + psClientVersion = PSObject.Base(value["PSVersion"]) as Version; } } @@ -907,7 +867,7 @@ private void HandleCreateRunspacePool(object sender, RemoteDataEventArgs createR } /// - /// This handler method runs the negotiation algorithm. It decides if the negotiation is succesful, + /// This handler method runs the negotiation algorithm. It decides if the negotiation is successful, /// or fails. /// /// @@ -961,10 +921,7 @@ private void HandleNegotiationReceived(object sender, RemoteSessionNegotiationEv /// private void HandleSessionDSHandlerClosing(object sender, EventArgs eventArgs) { - if (_runspacePoolDriver != null) - { - _runspacePoolDriver.Close(); - } + _runspacePoolDriver?.Close(); // dispose the session configuration object..this will let them // clean their resources. @@ -1016,35 +973,21 @@ private bool RunServerNegotiationAlgorithm(RemoteSessionCapability clientCapabil if (onConnect) { - bool connectSupported = false; - - // Win10 server can support reconstruct/reconnect for all 2.x protocol versions - // that support reconstruct/reconnect, Protocol 2.2+ - // Major protocol version differences (2.x -> 3.x) are not supported. - // A reconstruct can only be initiated by a client that understands disconnect (2.2+), - // so we only need to check major versions from client and this server for compatibility. - if (clientProtocolVersion.Major == RemotingConstants.ProtocolVersion.Major) + // PS v7.6 server can support reconstruct/reconnect for all 2.x protocol versions that support reconstruct/reconnect (v2.2+). + // Major protocol version differences (2.x -> 3.x) are not supported. A reconstruct can only be initiated by a client that understands disconnect (v2.2+). + if (clientProtocolVersion == RemotingConstants.ProtocolVersion_2_2 || + clientProtocolVersion == RemotingConstants.ProtocolVersion_2_3) { - if (clientProtocolVersion.Minor == RemotingConstants.ProtocolVersionWin8RTM.Minor) - { - // Report that server is Win8 version to the client - // Protocol: 2.2 - connectSupported = true; - serverProtocolVersion = RemotingConstants.ProtocolVersionWin8RTM; - Context.ServerCapability.ProtocolVersion = serverProtocolVersion; - } - else if (clientProtocolVersion.Minor > RemotingConstants.ProtocolVersionWin8RTM.Minor) - { - // All other minor versions are supported and the server returns its full capability - // Protocol: 2.3, 2.4, 2.5 ... - connectSupported = true; - } + // Report the server as the same version to the client. + // Client protocol: v2.2, v2.3 + serverProtocolVersion = clientProtocolVersion; + Context.ServerCapability.ProtocolVersion = serverProtocolVersion; } - - if (!connectSupported) + else if (!(clientProtocolVersion.Major == serverProtocolVersion.Major && + clientProtocolVersion.Minor >= serverProtocolVersion.Minor)) { // Throw for protocol versions 2.x that don't support disconnect/reconnect. - // Protocol: < 2.2 + // Client protocol: < 2.2 PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerConnectFailedOnNegotiation, RemoteDataNameStrings.PS_STARTUP_PROTOCOL_VERSION_NAME, @@ -1053,47 +996,23 @@ private bool RunServerNegotiationAlgorithm(RemoteSessionCapability clientCapabil RemotingConstants.ProtocolVersion); throw reasonOfFailure; } + + // All other minor versions are supported and the server returns its full capability. + // Client protocol: v2.4, v2.5 ... } else { - // Win10 server can support Win8 client - if (clientProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM && - ( - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM) - )) - { - // - report that server is Win8 version to the client - serverProtocolVersion = RemotingConstants.ProtocolVersionWin8RTM; - Context.ServerCapability.ProtocolVersion = serverProtocolVersion; - } - - // Win8, Win10 server can support Win7 client - if (clientProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM && - ( - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM) || - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM) - )) + if (clientProtocolVersion == RemotingConstants.ProtocolVersion_2_0 || + clientProtocolVersion == RemotingConstants.ProtocolVersion_2_1 || + clientProtocolVersion == RemotingConstants.ProtocolVersion_2_2 || + clientProtocolVersion == RemotingConstants.ProtocolVersion_2_3) { - // - report that server is Win7 version to the client - serverProtocolVersion = RemotingConstants.ProtocolVersionWin7RTM; + // We support the those client versions and report the server as the same version to the client. + serverProtocolVersion = clientProtocolVersion; Context.ServerCapability.ProtocolVersion = serverProtocolVersion; } - - // Win7, Win8, Win10 server can support Win7 RC client - if (clientProtocolVersion == RemotingConstants.ProtocolVersionWin7RC && - ( - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin7RTM) || - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin8RTM) || - (serverProtocolVersion == RemotingConstants.ProtocolVersionWin10RTM) - )) - { - // - report that server is RC version to the client - serverProtocolVersion = RemotingConstants.ProtocolVersionWin7RC; - Context.ServerCapability.ProtocolVersion = serverProtocolVersion; - } - - if (!((clientProtocolVersion.Major == serverProtocolVersion.Major) && - (clientProtocolVersion.Minor >= serverProtocolVersion.Minor))) + else if (!(clientProtocolVersion.Major == serverProtocolVersion.Major && + clientProtocolVersion.Minor >= serverProtocolVersion.Minor)) { PSRemotingDataStructureException reasonOfFailure = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerNegotiationFailed, diff --git a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs index 732e5a836ab..67d47ea404c 100644 --- a/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs +++ b/src/System.Management.Automation/engine/remoting/server/serverremotesessionstatemachine.cs @@ -31,7 +31,7 @@ namespace System.Management.Automation.Remoting /// internal class ServerRemoteSessionDSHandlerStateMachine { - [TraceSourceAttribute("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")] + [TraceSource("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("ServerRemoteSessionDSHandlerStateMachine", "ServerRemoteSessionDSHandlerStateMachine"); private readonly ServerRemoteSession _session; @@ -913,10 +913,7 @@ private void DoKeyExchange(object sender, RemoteSessionStateMachineEventArgs eve { // reset the timer Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) - { - tmp.Dispose(); - } + tmp?.Dispose(); } // the key import would have been done @@ -984,10 +981,7 @@ private void HandleKeyExchangeTimeout(object sender) Dbg.Assert(_state == RemoteSessionState.EstablishedAndKeyRequested, "timeout should only happen when waiting for a key"); Timer tmp = Interlocked.Exchange(ref _keyExchangeTimer, null); - if (tmp != null) - { - tmp.Dispose(); - } + tmp?.Dispose(); PSRemotingDataStructureException exception = new PSRemotingDataStructureException(RemotingErrorIdStrings.ServerKeyExchangeFailed); diff --git a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs index 275529b7b3f..027c4886380 100644 --- a/src/System.Management.Automation/engine/runtime/Binding/Binders.cs +++ b/src/System.Management.Automation/engine/runtime/Binding/Binders.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Buffers; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; @@ -12,6 +13,7 @@ using System.Linq.Expressions; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; @@ -94,7 +96,7 @@ internal static BindingRestrictions PSGetMethodArgumentRestriction(this DynamicM { var effectiveArgType = Adapter.EffectiveArgumentType(obj.Value); var methodInfo = effectiveArgType != typeof(object[]) - ? CachedReflectionInfo.PSInvokeMemberBinder_IsHomogenousArray.MakeGenericMethod(effectiveArgType.GetElementType()) + ? CachedReflectionInfo.PSInvokeMemberBinder_IsHomogeneousArray.MakeGenericMethod(effectiveArgType.GetElementType()) : CachedReflectionInfo.PSInvokeMemberBinder_IsHeterogeneousArray; BindingRestrictions restrictions; @@ -513,7 +515,7 @@ internal static BindingRestrictions GetOptionalVersionAndLanguageCheckForType(Dy /// The standard interop ConvertBinder is used to allow third party dynamic objects to get the first chance /// at the conversion in case they do support enumeration, but do not implement IEnumerable directly. /// - internal class PSEnumerableBinder : ConvertBinder + internal sealed class PSEnumerableBinder : ConvertBinder { private static readonly PSEnumerableBinder s_binder = new PSEnumerableBinder(); @@ -550,7 +552,7 @@ private DynamicMetaObject NullResult(DynamicMetaObject target) // The object is not enumerable from PowerShell's perspective. Rather than raise an exception, we let the // caller check for null and take the appropriate action. return new DynamicMetaObject( - MaybeDebase(this, e => ExpressionCache.NullEnumerator, target), + MaybeDebase(this, static e => ExpressionCache.NullEnumerator, target), GetRestrictions(target)); } @@ -599,7 +601,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna if (targetValue.GetType().IsArray) { return (new DynamicMetaObject( - MaybeDebase(this, e => Expression.Call(Expression.Convert(e, typeof(Array)), typeof(Array).GetMethod("GetEnumerator")), + MaybeDebase(this, static e => Expression.Call(Expression.Convert(e, typeof(Array)), typeof(Array).GetMethod("GetEnumerator")), target), GetRestrictions(target))).WriteToDebugLog(this); } @@ -674,7 +676,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna } return (new DynamicMetaObject( - MaybeDebase(this, e => Expression.Call(CachedReflectionInfo.EnumerableOps_GetEnumerator, Expression.Convert(e, typeof(IEnumerable))), + MaybeDebase(this, static e => Expression.Call(CachedReflectionInfo.EnumerableOps_GetEnumerator, Expression.Convert(e, typeof(IEnumerable))), target), GetRestrictions(target))).WriteToDebugLog(this); } @@ -683,7 +685,7 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna if (enumerator != null) { return (new DynamicMetaObject( - MaybeDebase(this, e => e.Cast(typeof(IEnumerator)), target), + MaybeDebase(this, static e => e.Cast(typeof(IEnumerator)), target), GetRestrictions(target))).WriteToDebugLog(this); } @@ -780,7 +782,7 @@ private static IEnumerator PSObjectStringRule(CallSite site, object obj) /// /// This binder is used for the @() operator. /// - internal class PSToObjectArrayBinder : DynamicMetaObjectBinder + internal sealed class PSToObjectArrayBinder : DynamicMetaObjectBinder { private static readonly PSToObjectArrayBinder s_binder = new PSToObjectArrayBinder(); @@ -825,7 +827,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje if (value is List) { return new DynamicMetaObject( - Expression.Call(PSEnumerableBinder.MaybeDebase(this, e => e.Cast(typeof(List)), target), CachedReflectionInfo.ObjectList_ToArray), + Expression.Call(PSEnumerableBinder.MaybeDebase(this, static e => e.Cast(typeof(List)), target), CachedReflectionInfo.ObjectList_ToArray), PSEnumerableBinder.GetRestrictions(target)).WriteToDebugLog(this); } @@ -836,7 +838,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } } - internal class PSPipeWriterBinder : DynamicMetaObjectBinder + internal sealed class PSPipeWriterBinder : DynamicMetaObjectBinder { private static readonly PSPipeWriterBinder s_binder = new PSPipeWriterBinder(); @@ -930,7 +932,7 @@ private static void AutomationNullRule(CallSite site, object obj, Pipe pipe, Exe /// The target in this binder is the RHS, the result expression is an IList where the Count matches the /// number of values assigned (_elements) on the left hand side of the assign. /// - internal class PSArrayAssignmentRHSBinder : DynamicMetaObjectBinder + internal sealed class PSArrayAssignmentRHSBinder : DynamicMetaObjectBinder { private static readonly List s_binders = new List(); private readonly int _elements; @@ -955,7 +957,7 @@ private PSArrayAssignmentRHSBinder(int elements) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "MultiAssignRHSBinder {0}", _elements); + return string.Create(CultureInfo.InvariantCulture, $"MultiAssignRHSBinder {_elements}"); } public override Type ReturnType { get { return typeof(IList); } } @@ -1043,13 +1045,13 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje /// This binder is used to convert objects to string in specific circumstances, including: /// /// * The LHS of a format expression. The arguments (the RHS objects) of the format - /// expression are not converted to string here, that is defered to string.Format which + /// expression are not converted to string here, that is deferred to string.Format which /// may have some custom formatting to apply. /// * The objects passed to the format expression as part of an expandable string. In this /// case, the format string is generated by the parser, so we know that there is no custom /// formatting to consider. /// - internal class PSToStringBinder : DynamicMetaObjectBinder + internal sealed class PSToStringBinder : DynamicMetaObjectBinder { private static readonly PSToStringBinder s_binder = new PSToStringBinder(); @@ -1114,7 +1116,7 @@ internal static Expression InvokeToString(Expression context, Expression target) /// /// This binder is used to optimize the conversion of the result. /// - internal class PSPipelineResultToBoolBinder : DynamicMetaObjectBinder + internal sealed class PSPipelineResultToBoolBinder : DynamicMetaObjectBinder { private static readonly PSPipelineResultToBoolBinder s_binder = new PSPipelineResultToBoolBinder(); @@ -1175,9 +1177,9 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } } - internal class PSInvokeDynamicMemberBinder : DynamicMetaObjectBinder + internal sealed class PSInvokeDynamicMemberBinder : DynamicMetaObjectBinder { - private class KeyComparer : IEqualityComparer + private sealed class KeyComparer : IEqualityComparer { public bool Equals(PSInvokeDynamicMemberBinderKeyType x, PSInvokeDynamicMemberBinderKeyType y) { @@ -1286,7 +1288,7 @@ public int GetHashCode(PSGetOrSetDynamicMemberBinderKeyType obj) } } - internal class PSGetDynamicMemberBinder : DynamicMetaObjectBinder + internal sealed class PSGetDynamicMemberBinder : DynamicMetaObjectBinder { private static readonly Dictionary s_binderCache = new Dictionary(new PSDynamicGetOrSetBinderKeyComparer()); @@ -1396,7 +1398,7 @@ internal static object GetIDictionaryMember(IDictionary hash, object key) } } - internal class PSSetDynamicMemberBinder : DynamicMetaObjectBinder + internal sealed class PSSetDynamicMemberBinder : DynamicMetaObjectBinder { private static readonly Dictionary s_binderCache = new Dictionary(new PSDynamicGetOrSetBinderKeyComparer()); @@ -1488,7 +1490,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } } - internal class PSSwitchClauseEvalBinder : DynamicMetaObjectBinder + internal sealed class PSSwitchClauseEvalBinder : DynamicMetaObjectBinder { // Increase this cache size if we add a new flag to the switch statement that: // - Influences evaluation of switch elements @@ -1608,7 +1610,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje // This class implements the standard binder CreateInstanceBinder, but this binder handles the CallInfo a little differently. // The ArgumentNames are not used to invoke a constructor, instead they are used to set properties/fields in the attribute. - internal class PSAttributeGenerator : CreateInstanceBinder + internal sealed class PSAttributeGenerator : CreateInstanceBinder { private static readonly Dictionary s_binderCache = new Dictionary(); @@ -1653,7 +1655,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe newConstructors, invocationConstraints: null, allowCastingToByRefLikeType: false, - args.Take(positionalArgCount).Select(arg => arg.Value).ToArray(), + args.Take(positionalArgCount).Select(static arg => arg.Value).ToArray(), ref errorId, ref errorMsg, out expandParamsOnBest, @@ -1789,7 +1791,7 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe } } - internal class PSCustomObjectConverter : DynamicMetaObjectBinder + internal sealed class PSCustomObjectConverter : DynamicMetaObjectBinder { private static readonly PSCustomObjectConverter s_binder = new PSCustomObjectConverter(); @@ -1825,7 +1827,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje } } - internal class PSDynamicConvertBinder : DynamicMetaObjectBinder + internal sealed class PSDynamicConvertBinder : DynamicMetaObjectBinder { private static readonly PSDynamicConvertBinder s_binder = new PSDynamicConvertBinder(); @@ -1863,7 +1865,7 @@ public override DynamicMetaObject Bind(DynamicMetaObject target, DynamicMetaObje /// /// This binder is used to copy mutable value types when assigning to variables, otherwise just assigning the target object directly. /// - internal class PSVariableAssignmentBinder : DynamicMetaObjectBinder + internal sealed class PSVariableAssignmentBinder : DynamicMetaObjectBinder { private static readonly PSVariableAssignmentBinder s_binder = new PSVariableAssignmentBinder(); internal static int s_mutableValueWithInstanceMemberVersion; @@ -2089,9 +2091,7 @@ internal static void NoteTypeHasInstanceMemberOrTypeName(Type type) internal static object CopyInstanceMembersOfValueType(T t, object boxedT) where T : struct { - PSMemberInfoInternalCollection unused1; - ConsolidatedString unused2; - if (PSObject.HasInstanceMembers(boxedT, out unused1) || PSObject.HasInstanceTypeName(boxedT, out unused2)) + if (PSObject.HasInstanceMembers(boxedT, out _) || PSObject.HasInstanceTypeName(boxedT, out _)) { var psobj = PSObject.AsPSObject(boxedT); return PSObject.Base(psobj.Copy()); @@ -2116,7 +2116,7 @@ internal static BindingRestrictions GetVersionCheck(int expectedVersionNumber) /// /// The binder for common binary operators. PowerShell specific binary operators are handled elsewhere. /// - internal class PSBinaryOperationBinder : BinaryOperationBinder + internal sealed class PSBinaryOperationBinder : BinaryOperationBinder { #region Constructors and factory methods @@ -2241,7 +2241,12 @@ public override DynamicMetaObject FallbackBinaryOperation(DynamicMetaObject targ public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSBinaryOperationBinder {0}{1} ver:{2}", GetOperatorText(), _scalarCompare ? " scalarOnly" : string.Empty, _version); + return string.Format( + CultureInfo.InvariantCulture, + "PSBinaryOperationBinder {0}{1} ver:{2}", + GetOperatorText(), + _scalarCompare ? " scalarOnly" : string.Empty, + _version); } internal static void InvalidateCache() @@ -2713,6 +2718,14 @@ private DynamicMetaObject BinaryAdd(DynamicMetaObject target, DynamicMetaObject lhsEnumerator.Expression.Cast(typeof(IEnumerator)), rhsEnumerator.Expression.Cast(typeof(IEnumerator))); } + else if (target.Value is object[] targetArray) + { + // Adding 1 item to an object[] + // This is an optimisation over the default EnumerableOps_AddObject. + call = Expression.Call(CachedReflectionInfo.ArrayOps_AddObject, + target.Expression.Cast(typeof(object[])), + arg.Expression.Cast(typeof(object))); + } else { // Adding 1 item to a list @@ -3187,7 +3200,7 @@ private DynamicMetaObject CompareLT(DynamicMetaObject target, } return BinaryComparisonCommon(enumerable, target, arg) - ?? BinaryComparison(target, arg, e => Expression.LessThan(e, ExpressionCache.Constant(0))); + ?? BinaryComparison(target, arg, static e => Expression.LessThan(e, ExpressionCache.Constant(0))); } private DynamicMetaObject CompareLE(DynamicMetaObject target, @@ -3207,7 +3220,7 @@ private DynamicMetaObject CompareLE(DynamicMetaObject target, } return BinaryComparisonCommon(enumerable, target, arg) - ?? BinaryComparison(target, arg, e => Expression.LessThanOrEqual(e, ExpressionCache.Constant(0))); + ?? BinaryComparison(target, arg, static e => Expression.LessThanOrEqual(e, ExpressionCache.Constant(0))); } private DynamicMetaObject CompareGT(DynamicMetaObject target, @@ -3229,7 +3242,7 @@ private DynamicMetaObject CompareGT(DynamicMetaObject target, } return BinaryComparisonCommon(enumerable, target, arg) - ?? BinaryComparison(target, arg, e => Expression.GreaterThan(e, ExpressionCache.Constant(0))); + ?? BinaryComparison(target, arg, static e => Expression.GreaterThan(e, ExpressionCache.Constant(0))); } private DynamicMetaObject CompareGE(DynamicMetaObject target, @@ -3251,7 +3264,7 @@ private DynamicMetaObject CompareGE(DynamicMetaObject target, } return BinaryComparisonCommon(enumerable, target, arg) - ?? BinaryComparison(target, arg, e => Expression.GreaterThanOrEqual(e, ExpressionCache.Constant(0))); + ?? BinaryComparison(target, arg, static e => Expression.GreaterThanOrEqual(e, ExpressionCache.Constant(0))); } private DynamicMetaObject BinaryComparison(DynamicMetaObject target, DynamicMetaObject arg, Func toResult) @@ -3411,7 +3424,7 @@ private DynamicMetaObject BinaryComparisonCommon(DynamicMetaObject targetAsEnume /// /// The binder for unary operators like !, -, or +. /// - internal class PSUnaryOperationBinder : UnaryOperationBinder + internal sealed class PSUnaryOperationBinder : UnaryOperationBinder { private static PSUnaryOperationBinder s_notBinder; private static PSUnaryOperationBinder s_bnotBinder; @@ -3490,7 +3503,7 @@ public override DynamicMetaObject FallbackUnaryOperation(DynamicMetaObject targe public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSUnaryOperationBinder {0}", this.Operation); + return string.Create(CultureInfo.InvariantCulture, $"PSUnaryOperationBinder {this.Operation}"); } internal DynamicMetaObject Not(DynamicMetaObject target, DynamicMetaObject errorSuggestion) @@ -3727,7 +3740,7 @@ private DynamicMetaObject IncrDecr(DynamicMetaObject target, int valueToAdd, Dyn /// /// The binder for converting a value, e.g. [int]"42" /// - internal class PSConvertBinder : ConvertBinder + internal sealed class PSConvertBinder : ConvertBinder { private static readonly Dictionary s_binderCache = new Dictionary(); internal int _version; @@ -3792,7 +3805,11 @@ public override DynamicMetaObject FallbackConvert(DynamicMetaObject target, Dyna public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSConvertBinder [{0}] ver:{1}", Microsoft.PowerShell.ToStringCodeMethods.Type(this.Type, true), _version); + return string.Format( + CultureInfo.InvariantCulture, + "PSConvertBinder [{0}] ver:{1}", + Microsoft.PowerShell.ToStringCodeMethods.Type(this.Type, true), + _version); } internal static void InvalidateCache() @@ -3926,7 +3943,7 @@ private static string StringToStringRule(CallSite site, object obj) /// /// The binder to get the value of an indexable object, e.g. $x[1] /// - internal class PSGetIndexBinder : GetIndexBinder + internal sealed class PSGetIndexBinder : GetIndexBinder { private static readonly Dictionary, PSGetIndexBinder> s_binderCache = new Dictionary, PSGetIndexBinder>(); @@ -3961,12 +3978,13 @@ private PSGetIndexBinder(Tuple tu public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, - "PSGetIndexBinder indexCount={0}{1}{2} ver:{3}", - this.CallInfo.ArgumentCount, - _allowSlicing ? string.Empty : " slicing disallowed", - _constraints == null ? string.Empty : " constraints: " + _constraints, - _version); + return string.Format( + CultureInfo.InvariantCulture, + "PSGetIndexBinder indexCount={0}{1}{2} ver:{3}", + this.CallInfo.ArgumentCount, + _allowSlicing ? string.Empty : " slicing disallowed", + _constraints == null ? string.Empty : " constraints: " + _constraints, + _version); } internal static void InvalidateCache() @@ -3983,13 +4001,13 @@ internal static void InvalidateCache() public override DynamicMetaObject FallbackGetIndex(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) { - if (!target.HasValue || indexes.Any(mo => !mo.HasValue)) + if (!target.HasValue || indexes.Any(static mo => !mo.HasValue)) { return Defer(indexes.Prepend(target).ToArray()).WriteToDebugLog(this); } if ((target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) || - indexes.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) + indexes.Any(static mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) { return this.DeferForPSObject(indexes.Prepend(target).ToArray()).WriteToDebugLog(this); } @@ -4084,7 +4102,7 @@ private DynamicMetaObject CannotIndexTarget(DynamicMetaObject target, DynamicMet bindingRestrictions = bindingRestrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); var call = Expression.Call(CachedReflectionInfo.ArrayOps_GetNonIndexable, target.Expression.Cast(typeof(object)), - Expression.NewArrayInit(typeof(object), indexes.Select(d => d.Expression.Cast(typeof(object))))); + Expression.NewArrayInit(typeof(object), indexes.Select(static d => d.Expression.Cast(typeof(object))))); return new DynamicMetaObject(call, bindingRestrictions); } @@ -4267,7 +4285,7 @@ private DynamicMetaObject GetIndexArray(DynamicMetaObject target, DynamicMetaObj new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), new DynamicMetaObject(indexAsInt, indexes[0].PSGetTypeRestriction()), target.LimitType.GetProperty("Length"), - (t, i) => Expression.ArrayIndex(t, i).Cast(typeof(object))); + static (t, i) => Expression.ArrayIndex(t, i).Cast(typeof(object))); } private DynamicMetaObject GetIndexMultiDimensionArray(DynamicMetaObject target, DynamicMetaObject[] indexes, DynamicMetaObject errorSuggestion) @@ -4313,7 +4331,7 @@ private DynamicMetaObject GetIndexMultiDimensionArray(DynamicMetaObject target, target.CombineRestrictions(indexes)); } - var intIndexes = indexes.Select(index => ConvertIndex(index, typeof(int))).Where(i => i != null).ToArray(); + var intIndexes = indexes.Select(static index => ConvertIndex(index, typeof(int))).Where(static i => i != null).ToArray(); if (intIndexes.Length != indexes.Length) { if (!_allowSlicing) @@ -4477,7 +4495,7 @@ private DynamicMetaObject InvokeSlicingIndexer(DynamicMetaObject target, Dynamic Expression.Call(CachedReflectionInfo.ArrayOps_SlicingIndex, target.Expression.Cast(typeof(object)), Expression.NewArrayInit(typeof(object), - indexes.Select(dmo => dmo.Expression.Cast(typeof(object)))), + indexes.Select(static dmo => dmo.Expression.Cast(typeof(object)))), Expression.Constant(GetNonSlicingIndexer())), target.CombineRestrictions(indexes)); } @@ -4517,7 +4535,7 @@ private Func GetNonSlicingIndexer() /// /// The binder for setting the value of an indexable element, like $x[1] = 5. /// - internal class PSSetIndexBinder : SetIndexBinder + internal sealed class PSSetIndexBinder : SetIndexBinder { private static readonly Dictionary, PSSetIndexBinder> s_binderCache = new Dictionary, PSSetIndexBinder>(); @@ -4550,8 +4568,12 @@ private PSSetIndexBinder(Tuple tuple) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "PSSetIndexBinder indexCnt={0}{1} ver:{2}", - CallInfo.ArgumentCount, _constraints == null ? string.Empty : " constraints: " + _constraints, _version); + return string.Format( + CultureInfo.InvariantCulture, + "PSSetIndexBinder indexCnt={0}{1} ver:{2}", + CallInfo.ArgumentCount, + _constraints == null ? string.Empty : " constraints: " + _constraints, + _version); } internal static void InvalidateCache() @@ -4572,13 +4594,13 @@ public override DynamicMetaObject FallbackSetIndex( DynamicMetaObject value, DynamicMetaObject errorSuggestion) { - if (!target.HasValue || indexes.Any(mo => !mo.HasValue) || !value.HasValue) + if (!target.HasValue || indexes.Any(static mo => !mo.HasValue) || !value.HasValue) { return Defer(indexes.Prepend(target).Append(value).ToArray()).WriteToDebugLog(this); } if (target.Value is PSObject && (PSObject.Base(target.Value) != target.Value) || - indexes.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) + indexes.Any(static mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) { return this.DeferForPSObject(indexes.Prepend(target).Append(value).ToArray()).WriteToDebugLog(this); } @@ -4794,7 +4816,7 @@ private DynamicMetaObject SetIndexArray(DynamicMetaObject target, ParserStrings.ArraySliceAssignmentFailed, Expression.Call(CachedReflectionInfo.ArrayOps_IndexStringMessage, Expression.NewArrayInit(typeof(object), - indexes.Select(i => i.Expression.Cast(typeof(object)))))); + indexes.Select(static i => i.Expression.Cast(typeof(object)))))); } var intIndex = PSGetIndexBinder.ConvertIndex(indexes[0], typeof(int)); @@ -4816,7 +4838,7 @@ private DynamicMetaObject SetIndexArray(DynamicMetaObject target, new DynamicMetaObject(target.Expression.Cast(target.LimitType), target.PSGetTypeRestriction()), new DynamicMetaObject(intIndex, indexes[0].PSGetTypeRestriction()), new DynamicMetaObject(valueExpr, value.PSGetTypeRestriction()), target.LimitType.GetProperty("Length"), - (t, i, v) => Expression.Assign(Expression.ArrayAccess(t, i), v)); + static (t, i, v) => Expression.Assign(Expression.ArrayAccess(t, i), v)); } private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, @@ -4859,7 +4881,7 @@ private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, ExpressionCache.Constant(array.Rank), Expression.Call(CachedReflectionInfo.ArrayOps_IndexStringMessage, Expression.NewArrayInit(typeof(object), - indexes.Select(i => i.Expression.Cast(typeof(object)))))); + indexes.Select(static i => i.Expression.Cast(typeof(object)))))); } var indexExprs = new Expression[indexes.Length]; @@ -4887,7 +4909,7 @@ private DynamicMetaObject SetIndexMultiDimensionArray(DynamicMetaObject target, /// internal class PSGetMemberBinder : GetMemberBinder { - private class KeyComparer : IEqualityComparer + private sealed class KeyComparer : IEqualityComparer { public bool Equals(PSGetMemberBinderKeyType x, PSGetMemberBinderKeyType y) { @@ -4911,7 +4933,7 @@ public int GetHashCode(PSGetMemberBinderKeyType obj) } } - private class ReservedMemberBinder : PSGetMemberBinder + private sealed class ReservedMemberBinder : PSGetMemberBinder { internal ReservedMemberBinder(string name, bool ignoreCase, bool @static) : base(name, null, ignoreCase, @static, nonEnumerating: false) { @@ -5007,7 +5029,7 @@ internal static void SetHasInstanceMember(string memberName) // This way, we can avoid the call to TryGetInstanceMember for binders when we know there aren't any instance // members, yet invalidate those rules once somebody adds an instance member. - var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, static _ => new List()); lock (binderList) { @@ -5038,7 +5060,7 @@ internal static void SetHasInstanceMember(string memberName) internal static void TypeTableMemberAdded(string memberName) { - var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, static _ => new List()); lock (binderList) { @@ -5061,7 +5083,7 @@ internal static void TypeTableMemberAdded(string memberName) internal static void TypeTableMemberPossiblyUpdated(string memberName) { - var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, static _ => new List()); lock (binderList) { @@ -5109,7 +5131,7 @@ private static PSGetMemberBinder Get(string memberName, Type classScope, bool @s result = new PSGetMemberBinder(memberName, classScope, true, @static, nonEnumerating); if (!@static) { - var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, _ => new List()); + var binderList = s_binderCacheIgnoringCase.GetOrAdd(memberName, static _ => new List()); lock (binderList) { if (binderList.Count > 0) @@ -5146,8 +5168,13 @@ private PSGetMemberBinder(string name, Type classScope, bool ignoreCase, bool @s public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "GetMember: {0}{1}{2} ver:{3}", - Name, _static ? " static" : string.Empty, _nonEnumerating ? " nonEnumerating" : string.Empty, _version); + return string.Format( + CultureInfo.InvariantCulture, + "GetMember: {0}{1}{2} ver:{3}", + Name, + _static ? " static" : string.Empty, + _nonEnumerating ? " nonEnumerating" : string.Empty, + _version); } public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion) @@ -5271,13 +5298,24 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy var propertyAccessor = adapterData.member as PropertyInfo; if (propertyAccessor != null) { - if (propertyAccessor.GetMethod.IsFamily && + var propertyGetter = propertyAccessor.GetMethod; + if ((propertyGetter.IsFamily || propertyGetter.IsFamilyOrAssembly) && (_classScope == null || !_classScope.IsSubclassOf(propertyAccessor.DeclaringType))) { return GenerateGetPropertyException(restrictions).WriteToDebugLog(this); } - expr = Expression.Property(targetExpr, propertyAccessor); + if (propertyAccessor.PropertyType.IsByRef) + { + expr = Expression.Call( + CachedReflectionInfo.ByRefOps_GetByRefPropertyValue, + targetExpr, + Expression.Constant(propertyAccessor)); + } + else + { + expr = Expression.Property(targetExpr, propertyAccessor); + } } else { @@ -5335,13 +5373,9 @@ public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, Dy if (!isGeneric || genericTypeArg != null) { var temp = Expression.Variable(typeof(object)); - if (expr == null) - { - // If expr is not null, it's the fallback when no member exists. If it is null, - // the fallback is the result from PropertyDoesntExist. - - expr = (errorSuggestion ?? PropertyDoesntExist(target, restrictions)).Expression; - } + // If expr is not null, it's the fallback when no member exists. If it is null, + // the fallback is the result from PropertyDoesntExist. + expr ??= (errorSuggestion ?? PropertyDoesntExist(target, restrictions)).Expression; var method = isGeneric ? CachedReflectionInfo.PSGetMemberBinder_TryGetGenericDictionaryValue.MakeGenericMethod(genericTypeArg) @@ -5407,18 +5441,6 @@ internal static Expression GetTargetExpr(DynamicMetaObject target, Type castToTy var type = castToType ?? ((value != null) ? value.GetType() : typeof(object)); - // Assemblies in CoreCLR might not allow reflection execution on their internal types. In such case, we walk up - // the derivation chain to find the first public parent, and use reflection methods on the public parent. - if (!TypeResolver.IsPublic(type) && DotNetAdapter.DisallowPrivateReflection(type)) - { - var publicType = DotNetAdapter.GetFirstPublicParentType(type); - if (publicType != null) - { - type = publicType; - } - // else we'll probably fail, but the error message might be more helpful than NullReferenceException - } - if (expr.Type != type) { // Unbox value types (or use Nullable.Value) to avoid a copy in case the value is mutated. @@ -5495,15 +5517,30 @@ private Expression ThrowPropertyNotFoundStrict() new object[] { Name }); } - internal static DynamicMetaObject EnsureAllowedInLanguageMode(ExecutionContext context, DynamicMetaObject target, object targetValue, + internal static DynamicMetaObject EnsureAllowedInLanguageMode(DynamicMetaObject target, object targetValue, string name, bool isStatic, DynamicMetaObject[] args, BindingRestrictions moreTests, string errorID, string resourceString) { - if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage) + var context = LocalPipeline.GetExecutionContextFromTLS(); + if (context == null) { - if (!IsAllowedInConstrainedLanguage(targetValue, name, isStatic)) + return null; + } + + if (context.LanguageMode == PSLanguageMode.ConstrainedLanguage && + !IsAllowedInConstrainedLanguage(targetValue, name, isStatic)) + { + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) { return target.ThrowRuntimeError(args, moreTests, errorID, resourceString); } + + string targetName = (targetValue as Type)?.FullName ?? targetValue?.GetType().FullName; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParameterBinderStrings.WDACBinderInvocationLogTitle, + message: StringUtil.Format(ParameterBinderStrings.WDACBinderInvocationLogMessage, name, targetName ?? string.Empty), + fqid: "MethodOrPropertyInvocationNotAllowed", + dropIntoDebugger: true); } return null; @@ -5625,8 +5662,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, canOptimize = false; - PSMemberInfo unused; - Diagnostics.Assert(!TryGetInstanceMember(target.Value, Name, out unused), + Diagnostics.Assert(!TryGetInstanceMember(target.Value, Name, out _), "shouldn't get here if there is an instance member"); PSMemberInfo memberInfo = null; @@ -5687,19 +5723,13 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, restrictions = versionRestriction; // When returning aliasRestrictions always include the version restriction - if (aliasRestrictions != null) - { - aliasRestrictions.Add(versionRestriction); - } + aliasRestrictions?.Add(versionRestriction); var alias = memberInfo as PSAliasProperty; if (alias != null) { aliasConversionType = alias.ConversionType; - if (aliasRestrictions == null) - { - aliasRestrictions = new List(); - } + aliasRestrictions ??= new List(); memberInfo = ResolveAlias(alias, target, aliases, aliasRestrictions); if (memberInfo == null) @@ -5729,8 +5759,8 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, var getMethod = propertyInfo.GetGetMethod(nonPublic: true); var setMethod = propertyInfo.GetSetMethod(nonPublic: true); - if ((getMethod == null || getMethod.IsFamily || getMethod.IsPublic) && - (setMethod == null || setMethod.IsFamily || setMethod.IsPublic)) + if ((getMethod == null || getMethod.IsPublic || getMethod.IsFamily || getMethod.IsFamilyOrAssembly) && + (setMethod == null || setMethod.IsPublic || setMethod.IsFamily || setMethod.IsFamilyOrAssembly)) { memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target.Value, new DotNetAdapter.PropertyCacheEntry(propertyInfo)); } @@ -5740,7 +5770,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, var fieldInfo = member as FieldInfo; if (fieldInfo != null) { - if (fieldInfo.IsFamily) + if (fieldInfo.IsFamily || fieldInfo.IsFamilyOrAssembly) { memberInfo = new PSProperty(this.Name, PSObject.DotNetInstanceAdapter, target.Value, new DotNetAdapter.PropertyCacheEntry(fieldInfo)); } @@ -5748,12 +5778,9 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, else { var methodInfo = member as MethodInfo; - if (methodInfo != null && (methodInfo.IsPublic || methodInfo.IsFamily)) + if (methodInfo != null && (methodInfo.IsPublic || methodInfo.IsFamily || methodInfo.IsFamilyOrAssembly)) { - if (candidateMethods == null) - { - candidateMethods = new List(); - } + candidateMethods ??= new List(); candidateMethods.Add(methodInfo); } @@ -5768,7 +5795,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, if (psMethodInfo != null) { var cacheEntry = (DotNetAdapter.MethodCacheEntry)psMethodInfo.adapterData; - candidateMethods.AddRange(cacheEntry.methodInformationStructures.Select(e => e.method)); + candidateMethods.AddRange(cacheEntry.methodInformationStructures.Select(static e => e.method)); memberInfo = null; } @@ -5779,7 +5806,7 @@ internal PSMemberInfo GetPSMemberInfo(DynamicMetaObject target, } else { - DotNetAdapter.MethodCacheEntry method = new DotNetAdapter.MethodCacheEntry(candidateMethods.ToArray()); + DotNetAdapter.MethodCacheEntry method = new DotNetAdapter.MethodCacheEntry(candidateMethods); memberInfo = PSMethod.Create(this.Name, PSObject.DotNetInstanceAdapter, null, method); } } @@ -5846,10 +5873,7 @@ internal static object GetAdaptedValue(object obj, string member) } var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); - if (memberInfo == null) - { - memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); - } + memberInfo ??= adapterSet.OriginalAdapter.BaseGetMember(obj, member); if (memberInfo == null && adapterSet.DotNetAdapter != null) { @@ -5936,7 +5960,7 @@ internal static bool TryGetGenericDictionaryValue(IDictionary hash /// internal class PSSetMemberBinder : SetMemberBinder { - private class KeyComparer : IEqualityComparer + private sealed class KeyComparer : IEqualityComparer { public bool Equals(PSSetMemberBinderKeyType x, PSSetMemberBinderKeyType y) { @@ -5998,7 +6022,12 @@ public PSSetMemberBinder(string name, bool ignoreCase, bool @static, Type classS public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "SetMember: {0}{1} ver:{2}", _static ? "static " : string.Empty, Name, _getMemberBinder._version); + return string.Format( + CultureInfo.InvariantCulture, + "SetMember: {0}{1} ver:{2}", + _static ? "static " : string.Empty, + Name, + _getMemberBinder._version); } private static Expression GetTransformedExpression(IEnumerable transformationAttributes, Expression originalExpression) @@ -6165,10 +6194,9 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy { restrictions = restrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); - // Validate that this is allowed in the current language mode - var context = LocalPipeline.GetExecutionContextFromTLS(); + // Validate that this is allowed in the current language mode. DynamicMetaObject runtimeError = PSGetMemberBinder.EnsureAllowedInLanguageMode( - context, target, targetValue, Name, _static, new[] { value }, restrictions, + target, targetValue, Name, _static, new[] { value }, restrictions, "PropertySetterNotSupportedInConstrainedLanguage", ParserStrings.PropertySetConstrainedLanguage); if (runtimeError != null) { @@ -6265,7 +6293,8 @@ public override DynamicMetaObject FallbackSetMember(DynamicMetaObject target, Dy var targetExpr = _static ? null : PSGetMemberBinder.GetTargetExpr(target, data.member.DeclaringType); if (propertyInfo != null) { - if (propertyInfo.SetMethod.IsFamily && + var propertySetter = propertyInfo.SetMethod; + if ((propertySetter.IsFamily || propertySetter.IsFamilyOrAssembly) && (_classScope == null || !_classScope.IsSubclassOf(propertyInfo.DeclaringType))) { return GeneratePropertyAssignmentException(restrictions).WriteToDebugLog(this); @@ -6450,10 +6479,7 @@ internal static object SetAdaptedValue(object obj, string member, object value) } var adapterSet = PSObject.GetMappedAdapter(obj, context?.TypeTable); - if (memberInfo == null) - { - memberInfo = adapterSet.OriginalAdapter.BaseGetMember(obj, member); - } + memberInfo ??= adapterSet.OriginalAdapter.BaseGetMember(obj, member); if (memberInfo == null && adapterSet.DotNetAdapter != null) { @@ -6508,8 +6534,23 @@ public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, Dynam } } - internal class PSInvokeMemberBinder : InvokeMemberBinder + internal sealed class PSInvokeMemberBinder : InvokeMemberBinder { + [TraceSource("MethodInvocation", "Traces the invocation of .NET methods.")] + internal static readonly PSTraceSource MethodInvocationTracer = + PSTraceSource.GetTracer( + "MethodInvocation", + "Traces the invocation of .NET methods.", + false); + + private static readonly SearchValues s_whereSearchValues = SearchValues.Create( + ["Where", "PSWhere"], + StringComparison.OrdinalIgnoreCase); + + private static readonly SearchValues s_foreachSearchValues = SearchValues.Create( + ["ForEach", "PSForEach"], + StringComparison.OrdinalIgnoreCase); + internal enum MethodInvocationType { Ordinary, @@ -6519,7 +6560,7 @@ internal enum MethodInvocationType NonVirtual, } - private class KeyComparer : IEqualityComparer + private sealed class KeyComparer : IEqualityComparer { public bool Equals(PSInvokeMemberBinderKeyType x, PSInvokeMemberBinderKeyType y) { @@ -6605,21 +6646,27 @@ private PSInvokeMemberBinder(string name, public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, - "PSInvokeMember: {0}{1}{2} ver:{3} args:{4} constraints:<{5}>", _static ? "static " : string.Empty, _propertySetter ? "propset " : string.Empty, - Name, _getMemberBinder._version, CallInfo.ArgumentCount, _invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty); + return string.Format( + CultureInfo.InvariantCulture, + "PSInvokeMember: {0}{1}{2} ver:{3} args:{4} constraints:<{5}>", + _static ? "static " : string.Empty, + _propertySetter ? "propset " : string.Empty, + Name, + _getMemberBinder._version, + CallInfo.ArgumentCount, + _invocationConstraints != null ? _invocationConstraints.ToString() : string.Empty); } public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { - if (!target.HasValue || args.Any(arg => !arg.HasValue)) + if (!target.HasValue || args.Any(static arg => !arg.HasValue)) { return Defer(args.Prepend(target).ToArray()); } // Defer COM objects or arguments wrapped in PSObjects if ((target.Value is PSObject && (PSObject.Base(target.Value) != target.Value)) || - args.Any(mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) + args.Any(static mo => mo.Value is PSObject && (PSObject.Base(mo.Value) != mo.Value))) { object baseObject = PSObject.Base(target.Value); if (baseObject != null && Marshal.IsComObject(baseObject)) @@ -6650,14 +6697,16 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, Expression.Call(Expression.NewArrayInit(typeof(object)), CachedReflectionInfo.IEnumerable_GetEnumerator), BindingRestrictions.GetInstanceRestriction(Expression.Call(CachedReflectionInfo.PSObject_Base, target.Expression), null)) .WriteToDebugLog(this); - BindingRestrictions argRestrictions = args.Aggregate(BindingRestrictions.Empty, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); + BindingRestrictions argRestrictions = args.Aggregate(BindingRestrictions.Empty, static (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); - if (string.Equals(Name, "Where", StringComparison.OrdinalIgnoreCase)) + // We need to pass the empty enumerator to the ForEach/Where operators, so that they can return an empty collection. + // The ForEach/Where operators will not be able to call the script block if the enumerator is empty. + if (s_whereSearchValues.Contains(Name)) { return InvokeWhereOnCollection(emptyEnumerator, args, argRestrictions).WriteToDebugLog(this); } - if (string.Equals(Name, "ForEach", StringComparison.OrdinalIgnoreCase)) + if (s_foreachSearchValues.Contains(Name)) { return InvokeForEachOnCollection(emptyEnumerator, args, argRestrictions).WriteToDebugLog(this); } @@ -6695,7 +6744,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, Expression.Call(CachedReflectionInfo.PSInvokeMemberBinder_TryGetInstanceMethod, target.Expression.Cast(typeof(object)), Expression.Constant(Name), methodInfoVar), Expression.Call(methodInfoVar, CachedReflectionInfo.PSMethodInfo_Invoke, - Expression.NewArrayInit(typeof(object), args.Select(dmo => dmo.Expression.Cast(typeof(object))))), + Expression.NewArrayInit(typeof(object), args.Select(static dmo => dmo.Expression.Cast(typeof(object))))), this.GetUpdateExpression(typeof(object))); return (new DynamicMetaObject(Expression.Block(new[] { methodInfoVar }, expr), @@ -6706,7 +6755,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, bool canOptimize; Type aliasConversionType; var methodInfo = _getMemberBinder.GetPSMemberInfo(target, out restrictions, out canOptimize, out aliasConversionType, MemberTypes.Method) as PSMethodInfo; - restrictions = args.Aggregate(restrictions, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); + restrictions = args.Aggregate(restrictions, static (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); // If the process has ever used ConstrainedLanguage, then we need to add the language mode // to the binding restrictions, and check whether it is allowed. We can't limit @@ -6715,10 +6764,9 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, { restrictions = restrictions.Merge(BinderUtils.GetLanguageModeCheckIfHasEverUsedConstrainedLanguage()); - // Validate that this is allowed in the current language mode - var context = LocalPipeline.GetExecutionContextFromTLS(); + // Validate that this is allowed in the current language mode. DynamicMetaObject runtimeError = PSGetMemberBinder.EnsureAllowedInLanguageMode( - context, target, targetValue, Name, _static, args, restrictions, + target, targetValue, Name, _static, args, restrictions, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); if (runtimeError != null) { @@ -6738,7 +6786,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, PSGetMemberBinder.GetTargetExpr(target, typeof(object)), Expression.Constant(Name), Expression.NewArrayInit(typeof(object), - args.Take(args.Length - 1).Select(arg => arg.Expression.Cast(typeof(object)))), + args.Take(args.Length - 1).Select(static arg => arg.Expression.Cast(typeof(object)))), args.Last().Expression.Cast(typeof(object))); } else @@ -6748,7 +6796,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, PSGetMemberBinder.GetTargetExpr(target, typeof(object)), Expression.Constant(Name), Expression.NewArrayInit(typeof(object), - args.Select(arg => arg.Expression.Cast(typeof(object))))); + args.Select(static arg => arg.Expression.Cast(typeof(object))))); } return new DynamicMetaObject(call, restrictions).WriteToDebugLog(this); @@ -6800,7 +6848,7 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, Expression.Constant(scriptMethod.Script), target.Expression.Cast(typeof(object)), Expression.NewArrayInit(typeof(object), - args.Select(e => e.Expression.Cast(typeof(object))))), + args.Select(static e => e.Expression.Cast(typeof(object))))), restrictions).WriteToDebugLog(this); } @@ -6838,12 +6886,12 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, if (!_static && !_nonEnumerating && target.Value != AutomationNull.Value) { // Invoking Where and ForEach operators on collections. - if (string.Equals(Name, "Where", StringComparison.OrdinalIgnoreCase)) + if (s_whereSearchValues.Contains(Name)) { return InvokeWhereOnCollection(target, args, restrictions).WriteToDebugLog(this); } - if (string.Equals(Name, "ForEach", StringComparison.OrdinalIgnoreCase)) + if (s_foreachSearchValues.Contains(Name)) { return InvokeForEachOnCollection(target, args, restrictions).WriteToDebugLog(this); } @@ -6915,6 +6963,17 @@ internal static DynamicMetaObject InvokeDotNetMethod( expr = Expression.Block(expr, ExpressionCache.AutomationNullConstant); } + if (MethodInvocationTracer.IsEnabled) + { + expr = Expression.Block( + Expression.Call( + Expression.Constant(MethodInvocationTracer), + CachedReflectionInfo.PSTraceSource_WriteLine, + Expression.Constant("Invoking method: {0}"), + Expression.Constant(result.methodDefinition)), + expr); + } + // If we're calling SteppablePipeline.{Begin|Process|End}, we don't want // to wrap exceptions - this is very much a special case to help error // propagation and ensure errors are attributed to the correct code (the @@ -6967,7 +7026,7 @@ public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicExpression.Dynamic( new PSInvokeBinder(CallInfo), typeof(object), - args.Prepend(target).Select(dmo => dmo.Expression) + args.Prepend(target).Select(static dmo => dmo.Expression) ), target.Restrictions.Merge(BindingRestrictions.Combine(args)) )); @@ -6995,7 +7054,7 @@ internal static MethodInfo FindBestMethod(DynamicMetaObject target, data.methodInformationStructures, invocationConstraints, allowCastingToByRefLikeType: true, - args.Select(arg => arg.Value == AutomationNull.Value ? null : arg.Value).ToArray(), + args.Select(static arg => arg.Value == AutomationNull.Value ? null : arg.Value).ToArray(), ref errorId, ref errorMsg, out expandParameters, @@ -7077,6 +7136,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, invocationType != MethodInvocationType.NonVirtual; var parameters = mi.GetParameters(); var argExprs = new Expression[parameters.Length]; + var argsToLog = new List(Math.Max(parameters.Length, args.Length)); for (int i = 0; i < parameters.Length; ++i) { @@ -7101,16 +7161,21 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, if (expandParameters) { - argExprs[i] = Expression.NewArrayInit( - paramElementType, - args.Skip(i).Select( - a => a.CastOrConvertMethodArgument( + IEnumerable elements = args + .Skip(i) + .Select(a => + a.CastOrConvertMethodArgument( paramElementType, paramName, mi.Name, allowCastingToByRefLikeType: false, temps, - initTemps))); + initTemps)) + .ToList(); + + argExprs[i] = Expression.NewArrayInit(paramElementType, elements); + // User specified the element arguments, so we log them instead of the compiler-created array. + argsToLog.AddRange(elements); } else { @@ -7121,16 +7186,35 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, allowCastingToByRefLikeType: false, temps, initTemps); + argExprs[i] = arg; + argsToLog.Add(arg); } } else if (i >= args.Length) { - Diagnostics.Assert(parameters[i].IsOptional, + // We don't log the default value for an optional parameter, as it's not specified by the user. + Diagnostics.Assert( + parameters[i].IsOptional, "if there are too few arguments, FindBestMethod should only succeed if parameters are optional"); + var argValue = parameters[i].DefaultValue; if (argValue == null) { + if (parameterType.IsByRef) + { + // When the default value is null for a ByRef parameter (e.g. an optional `in` parameter + // using `default`), expression trees cannot create Expression.Default for the T& type. + // In that case we switch to the element type and use Default(TElement) instead. + parameterType = parameterType.GetElementType(); + } + argExprs[i] = Expression.Default(parameterType); + } + else if (!parameters[i].HasDefaultValue && parameterType != typeof(object) && argValue == Type.Missing) + { + // If the method contains just [Optional] without a default value set then we cannot use + // Type.Missing as a placeholder. Instead we use the default value for that type. Only + // exception to this rule is when the parameter type is object. argExprs[i] = Expression.Default(parameterType); } else @@ -7158,17 +7242,25 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, var psRefValue = Expression.Property(args[i].Expression.Cast(typeof(PSReference)), CachedReflectionInfo.PSReference_Value); initTemps.Add(Expression.Assign(temp, psRefValue.Convert(temp.Type))); copyOutTemps.Add(Expression.Assign(psRefValue, temp.Cast(typeof(object)))); + argExprs[i] = temp; + argsToLog.Add(temp); } else { - argExprs[i] = args[i].CastOrConvertMethodArgument( + var convertedArg = args[i].CastOrConvertMethodArgument( parameterType, paramName, mi.Name, allowCastingToByRefLikeType, temps, initTemps); + + argExprs[i] = convertedArg; + // If the converted arg is a byref-like type, then we log the original arg. + argsToLog.Add(convertedArg.Type.IsByRefLike + ? args[i].Expression + : convertedArg); } } } @@ -7185,7 +7277,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, CachedReflectionInfo.ClassOps_CallBaseCtor, targetExpr, Expression.Constant(constructorInfo, typeof(ConstructorInfo)), - Expression.NewArrayInit(typeof(object), argExprs.Select(x => x.Cast(typeof(object))))); + Expression.NewArrayInit(typeof(object), argExprs.Select(static x => x.Cast(typeof(object))))); } else { @@ -7202,7 +7294,7 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, : CachedReflectionInfo.ClassOps_CallMethodNonVirtually, PSGetMemberBinder.GetTargetExpr(target, methodInfo.DeclaringType), Expression.Constant(methodInfo, typeof(MethodInfo)), - Expression.NewArrayInit(typeof(object), argExprs.Select(x => x.Cast(typeof(object))))); + Expression.NewArrayInit(typeof(object), argExprs.Select(static x => x.Cast(typeof(object))))); } else { @@ -7214,6 +7306,12 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, } } + // We need to add one expression to log the .NET invocation before actually invoking: + // - Log method invocation to AMSI Notifications (can throw PSSecurityException) + // - Invoke method + string targetName = mi.ReflectedType?.FullName ?? string.Empty; + string methodName = mi.Name is ".ctor" ? "new" : mi.Name; + if (temps.Count > 0) { if (call.Type != typeof(void) && copyOutTemps.Count > 0) @@ -7224,22 +7322,27 @@ internal static Expression InvokeMethod(MethodBase mi, DynamicMetaObject target, copyOutTemps.Add(retValue); } + AddMemberInvocationLogging(initTemps, targetName, methodName, argsToLog); call = Expression.Block(call.Type, temps, initTemps.Append(call).Concat(copyOutTemps)); } + else + { + call = AddMemberInvocationLogging(call, targetName, methodName, argsToLog); + } return call; } private DynamicMetaObject InvokeMemberOnCollection(DynamicMetaObject targetEnumerator, DynamicMetaObject[] args, Type typeForMessage, BindingRestrictions restrictions) { - var d = DynamicExpression.Dynamic(this, this.ReturnType, args.Select(a => a.Expression).Prepend(ExpressionCache.NullConstant)); + var d = DynamicExpression.Dynamic(this, this.ReturnType, args.Select(static a => a.Expression).Prepend(ExpressionCache.NullConstant)); return new DynamicMetaObject( Expression.Call(CachedReflectionInfo.EnumerableOps_MethodInvoker, Expression.Constant(this.GetNonEnumeratingBinder()), Expression.Constant(d.DelegateType, typeof(Type)), targetEnumerator.Expression, Expression.NewArrayInit(typeof(object), - args.Select(a => a.Expression.Cast(typeof(object)))), + args.Select(static a => a.Expression.Cast(typeof(object)))), Expression.Constant(typeForMessage, typeof(Type)) ), targetEnumerator.Restrictions.Merge(restrictions)); @@ -7248,14 +7351,11 @@ private DynamicMetaObject InvokeMemberOnCollection(DynamicMetaObject targetEnume private static DynamicMetaObject GetTargetAsEnumerable(DynamicMetaObject target) { var enumerableTarget = PSEnumerableBinder.IsEnumerable(target); - if (enumerableTarget == null) - { - // Wrap the target in an array. - enumerableTarget = PSEnumerableBinder.IsEnumerable( - new DynamicMetaObject( - Expression.NewArrayInit(typeof(object), target.Expression.Cast(typeof(object))), - target.GetSimpleTypeRestriction())); - } + // If null wrap the target in an array. + enumerableTarget ??= PSEnumerableBinder.IsEnumerable( + new DynamicMetaObject( + Expression.NewArrayInit(typeof(object), target.Expression.Cast(typeof(object))), + target.GetSimpleTypeRestriction())); return enumerableTarget; } @@ -7340,7 +7440,7 @@ private DynamicMetaObject InvokeForEachOnCollection(DynamicMetaObject targetEnum if (args.Length > 1) { argsToPass = Expression.NewArrayInit(typeof(object), - args.Skip(1).Select(a => a.Expression.Cast(typeof(object)))); + args.Skip(1).Select(static a => a.Expression.Cast(typeof(object)))); } else { @@ -7355,18 +7455,22 @@ private DynamicMetaObject InvokeForEachOnCollection(DynamicMetaObject targetEnum #region Runtime helpers - internal static bool IsHomogenousArray(object[] args) + internal static bool IsHomogeneousArray(object[] args) { if (args.Length == 0) { return false; } - return args.All(element => - { - var obj = PSObject.Base(element); - return obj != null && obj.GetType().Equals(typeof(T)); - }); + foreach (object element in args) + { + if (Adapter.GetObjectType(element, debase: true) != typeof(T)) + { + return false; + } + } + + return true; } internal static bool IsHeterogeneousArray(object[] args) @@ -7394,11 +7498,15 @@ internal static bool IsHeterogeneousArray(object[] args) return true; } - return args.Skip(1).Any(element => - { - var obj = PSObject.Base(element); - return obj == null || !firstType.Equals(obj.GetType()); - }); + for (int i = 1; i < args.Length; i++) + { + if (Adapter.GetObjectType(args[i], debase: true) != firstType) + { + return true; + } + } + + return false; } internal static object InvokeAdaptedMember(object obj, string methodName, object[] args) @@ -7420,7 +7528,7 @@ internal static object InvokeAdaptedMember(object obj, string methodName, object // As a last resort, we invoke 'Where' and 'ForEach' operators on singletons like // ([pscustomobject]@{ foo = 'bar' }).Foreach({$_}) // ([pscustomobject]@{ foo = 'bar' }).Where({1}) - if (string.Equals(methodName, "Where", StringComparison.OrdinalIgnoreCase)) + if (s_whereSearchValues.Contains(methodName)) { var enumerator = (new object[] { obj }).GetEnumerator(); switch (args.Length) @@ -7436,10 +7544,23 @@ internal static object InvokeAdaptedMember(object obj, string methodName, object } } - if (string.Equals(methodName, "Foreach", StringComparison.OrdinalIgnoreCase)) + if (s_foreachSearchValues.Contains(methodName)) { var enumerator = (new object[] { obj }).GetEnumerator(); - return EnumerableOps.ForEach(enumerator, args[0], Array.Empty()); + object[] argsToPass; + + if (args.Length > 1) + { + int length = args.Length - 1; + argsToPass = new object[length]; + Array.Copy(args, sourceIndex: 1, argsToPass, destinationIndex: 0, length: length); + } + else + { + argsToPass = Array.Empty(); + } + + return EnumerableOps.ForEach(enumerator, args[0], argsToPass); } throw InterpreterError.NewInterpreterException(methodName, typeof(RuntimeException), null, @@ -7499,6 +7620,55 @@ internal static void InvalidateCache() } } +#nullable enable + private static Expression AddMemberInvocationLogging( + Expression expr, + string targetName, + string name, + List args) + { +#if UNIX + // For efficiency this is a no-op on non-Windows platforms. + return expr; +#else + Expression[] invocationArgs = new Expression[args.Count]; + for (int i = 0; i < args.Count; i++) + { + invocationArgs[i] = args[i].Cast(typeof(object)); + } + + return Expression.Block( + Expression.Call( + CachedReflectionInfo.MemberInvocationLoggingOps_LogMemberInvocation, + Expression.Constant(targetName), + Expression.Constant(name), + Expression.NewArrayInit(typeof(object), invocationArgs)), + expr); +#endif + } + + private static void AddMemberInvocationLogging( + List exprs, + string targetName, + string name, + List args) + { +#if !UNIX + Expression[] invocationArgs = new Expression[args.Count]; + for (int i = 0; i < args.Count; i++) + { + invocationArgs[i] = args[i].Cast(typeof(object)); + } + + exprs.Add(Expression.Call( + CachedReflectionInfo.MemberInvocationLoggingOps_LogMemberInvocation, + Expression.Constant(targetName), + Expression.Constant(name), + Expression.NewArrayInit(typeof(object), invocationArgs))); +#endif + } +#nullable disable + #endregion } @@ -7509,7 +7679,7 @@ internal class PSCreateInstanceBinder : CreateInstanceBinder private readonly bool _publicTypeOnly; private int _version; - private class KeyComparer : IEqualityComparer> + private sealed class KeyComparer : IEqualityComparer> { public bool Equals(Tuple x, Tuple y) @@ -7569,13 +7739,17 @@ internal PSCreateInstanceBinder(CallInfo callInfo, PSMethodInvocationConstraints public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, - "PSCreateInstanceBinder: ver:{0} args:{1} constraints:<{2}>", _version, _callInfo.ArgumentCount, _constraints != null ? _constraints.ToString() : string.Empty); + return string.Format( + CultureInfo.InvariantCulture, + "PSCreateInstanceBinder: ver:{0} args:{1} constraints:<{2}>", + _version, + _callInfo.ArgumentCount, + _constraints != null ? _constraints.ToString() : string.Empty); } public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { - if (!target.HasValue || args.Any(arg => !arg.HasValue)) + if (!target.HasValue || args.Any(static arg => !arg.HasValue)) { return Defer(args.Prepend(target).ToArray()); } @@ -7636,10 +7810,21 @@ public override DynamicMetaObject FallbackCreateInstance(DynamicMetaObject targe var context = LocalPipeline.GetExecutionContextFromTLS(); if (context != null && context.LanguageMode == PSLanguageMode.ConstrainedLanguage && !CoreTypes.Contains(instanceType)) { - return target.ThrowRuntimeError(restrictions, "CannotCreateTypeConstrainedLanguage", ParserStrings.CannotCreateTypeConstrainedLanguage).WriteToDebugLog(this); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + return target.ThrowRuntimeError(restrictions, "CannotCreateTypeConstrainedLanguage", ParserStrings.CannotCreateTypeConstrainedLanguage).WriteToDebugLog(this); + } + + string targetName = instanceType?.FullName; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParameterBinderStrings.WDACBinderTypeCreationLogTitle, + message: StringUtil.Format(ParameterBinderStrings.WDACBinderTypeCreationLogMessage, targetName ?? string.Empty), + fqid: "TypeCreationNotAllowed", + dropIntoDebugger: true); } - restrictions = args.Aggregate(restrictions, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); + restrictions = args.Aggregate(restrictions, static (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); var newConstructors = DotNetAdapter.GetMethodInformationArray(ctors); return PSInvokeMemberBinder.InvokeDotNetMethod(_callInfo, "new", _constraints, PSInvokeMemberBinder.MethodInvocationType.Ordinary, target, args, restrictions, newConstructors, typeof(MethodException)).WriteToDebugLog(this); @@ -7687,7 +7872,7 @@ internal class PSInvokeBaseCtorBinder : InvokeMemberBinder private readonly CallInfo _callInfo; private readonly PSMethodInvocationConstraints _constraints; - private class KeyComparer : IEqualityComparer> + private sealed class KeyComparer : IEqualityComparer> { public bool Equals(Tuple x, Tuple y) @@ -7733,7 +7918,7 @@ internal PSInvokeBaseCtorBinder(CallInfo callInfo, PSMethodInvocationConstraints public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { - if (!target.HasValue || args.Any(arg => !arg.HasValue)) + if (!target.HasValue || args.Any(static arg => !arg.HasValue)) { return Defer(args.Prepend(target).ToArray()); } @@ -7743,8 +7928,8 @@ public override DynamicMetaObject FallbackInvokeMember(DynamicMetaObject target, var restrictions = target.Value is PSObject ? BindingRestrictions.GetTypeRestriction(target.Expression, target.Value.GetType()) : target.PSGetTypeRestriction(); - restrictions = args.Aggregate(restrictions, (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); - var newConstructors = DotNetAdapter.GetMethodInformationArray(ctors.Where(c => c.IsPublic || c.IsFamily).ToArray()); + restrictions = args.Aggregate(restrictions, static (current, arg) => current.Merge(arg.PSGetMethodArgumentRestriction())); + var newConstructors = DotNetAdapter.GetMethodInformationArray(ctors.Where(static c => c.IsPublic || c.IsFamily || c.IsFamilyOrAssembly).ToArray()); return PSInvokeMemberBinder.InvokeDotNetMethod(_callInfo, "new", _constraints, PSInvokeMemberBinder.MethodInvocationType.BaseCtor, target, args, restrictions, newConstructors, typeof(MethodException)); } @@ -7755,7 +7940,7 @@ public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, Dynam DynamicExpression.Dynamic( new PSInvokeBinder(CallInfo), typeof(object), - args.Prepend(target).Select(dmo => dmo.Expression) + args.Prepend(target).Select(static dmo => dmo.Expression) ), target.Restrictions.Merge(BindingRestrictions.Combine(args)) )); diff --git a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs index 6478e9b091d..8899c0e0c14 100644 --- a/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs +++ b/src/System.Management.Automation/engine/runtime/CompiledScriptBlock.cs @@ -10,13 +10,12 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; using System.Management.Automation.Tracing; using System.Reflection; -using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Security.Cryptography.X509Certificates; using System.Text; -using System.Threading.Tasks; #if LEGACYTELEMETRY using Microsoft.PowerShell.Telemetry.Internal; #endif @@ -35,6 +34,7 @@ internal enum ScriptBlockClauseToInvoke Begin, Process, End, + Clean, ProcessBlockOnly, } @@ -188,12 +188,15 @@ private void ReallyCompile(bool optimize) TelemetryAPI.ReportScriptTelemetry((Ast)_ast, !optimize, sw.ElapsedMilliseconds); } #endif - if (etwEnabled) ParserEventSource.Log.CompileStop(); + if (etwEnabled) + { + ParserEventSource.Log.CompileStop(); + } } private void PerformSecurityChecks() { - if (!(Ast is ScriptBlockAst scriptBlockAst)) + if (Ast is not ScriptBlockAst scriptBlockAst) { // Checks are only needed at the top level. return; @@ -247,6 +250,7 @@ bool IsScriptBlockInFactASafeHashtable() if (scriptBlockAst.BeginBlock != null || scriptBlockAst.ProcessBlock != null + || scriptBlockAst.CleanBlock != null || scriptBlockAst.ParamBlock != null || scriptBlockAst.DynamicParamBlock != null || scriptBlockAst.ScriptRequirements != null @@ -262,12 +266,12 @@ bool IsScriptBlockInFactASafeHashtable() return false; } - if (!(endBlock.Statements[0] is PipelineAst pipelineAst)) + if (endBlock.Statements[0] is not PipelineAst pipelineAst) { return false; } - if (!(pipelineAst.GetPureExpression() is HashtableAst hashtableAst)) + if (pipelineAst.GetPureExpression() is not HashtableAst hashtableAst) { return false; } @@ -316,6 +320,8 @@ private IParameterMetadataProvider DelayParseScriptText() internal Dictionary NameToIndexMap { get; set; } + #region Named Blocks + internal Action DynamicParamBlock { get; set; } internal Action UnoptimizedDynamicParamBlock { get; set; } @@ -332,6 +338,12 @@ private IParameterMetadataProvider DelayParseScriptText() internal Action UnoptimizedEndBlock { get; set; } + internal Action CleanBlock { get; set; } + + internal Action UnoptimizedCleanBlock { get; set; } + + #endregion Named Blocks + internal IScriptExtent[] SequencePoints { get; set; } private RuntimeDefinedParameterDictionary _runtimeDefinedParameterDictionary; @@ -358,10 +370,7 @@ internal bool IsProductCode { get { - if (_isProductCode == null) - { - _isProductCode = SecuritySupport.IsProductBinary(((Ast)_ast).Extent.File); - } + _isProductCode ??= SecuritySupport.IsProductBinary(((Ast)_ast).Extent.File); return _isProductCode.Value; } @@ -440,7 +449,7 @@ internal CmdletBindingAttribute CmdletBindingAttribute } return _usesCmdletBinding - ? (CmdletBindingAttribute)Array.Find(_attributes, attr => attr is CmdletBindingAttribute) + ? (CmdletBindingAttribute)Array.Find(_attributes, static attr => attr is CmdletBindingAttribute) : null; } } @@ -454,7 +463,7 @@ internal ObsoleteAttribute ObsoleteAttribute InitializeMetadata(); } - return (ObsoleteAttribute)Array.Find(_attributes, attr => attr is ObsoleteAttribute); + return (ObsoleteAttribute)Array.Find(_attributes, static attr => attr is ObsoleteAttribute); } } @@ -530,8 +539,7 @@ public override string ToString() } } - [Serializable] - public partial class ScriptBlock : ISerializable + public partial class ScriptBlock { private readonly CompiledScriptBlockData _scriptBlockData; @@ -564,6 +572,7 @@ private ScriptBlock(CompiledScriptBlockData scriptBlockData) /// /// Protected constructor to support ISerializable. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptBlock(SerializationInfo info, StreamingContext context) { } @@ -612,8 +621,8 @@ internal static void CacheScriptBlock(ScriptBlock scriptBlock, string fileName, // TODO(sevoroby): we can optimize it to ignore 'using' if there are no actual type usage in locally defined types. // using is always a top-level statements in scriptBlock, we don't need to search in child blocks. - if (scriptBlock.Ast.Find(ast => IsUsingTypes(ast), false) != null - || scriptBlock.Ast.Find(ast => IsDynamicKeyword(ast), true) != null) + if (scriptBlock.Ast.Find(static ast => IsUsingTypes(ast), false) != null + || scriptBlock.Ast.Find(static ast => IsDynamicKeyword(ast), true) != null) { return; } @@ -703,21 +712,6 @@ internal string ToStringWithDollarUsingHandling( return sbText; } - /// - /// Support for . - /// - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - string serializedContent = this.ToString(); - info.AddValue("ScriptText", serializedContent); - info.SetType(typeof(ScriptBlockSerializationHelper)); - } - internal PowerShell GetPowerShellImpl( ExecutionContext context, Dictionary variables, @@ -751,9 +745,9 @@ internal SteppablePipeline GetSteppablePipelineImpl(CommandOrigin commandOrigin, private PipelineAst GetSimplePipeline(Func errorHandler) { - errorHandler ??= (_ => null); + errorHandler ??= (static _ => null); - if (HasBeginBlock || HasProcessBlock) + if (HasBeginBlock || HasProcessBlock || HasCleanBlock) { return errorHandler(AutomationExceptions.CanConvertOneClauseOnly); } @@ -775,7 +769,7 @@ private PipelineAst GetSimplePipeline(Func errorHandler) return errorHandler(AutomationExceptions.CantConvertScriptBlockWithTrap); } - if (!(statements[0] is PipelineAst pipeAst)) + if (statements[0] is not PipelineAst pipeAst) { return errorHandler(AutomationExceptions.CanOnlyConvertOnePipeline); } @@ -891,7 +885,10 @@ public void CheckRestrictedLanguage( Parser parser = new Parser(); var ast = AstInternal; - if (HasBeginBlock || HasProcessBlock || ast.Body.ParamBlock != null) + if (HasBeginBlock + || HasProcessBlock + || HasCleanBlock + || ast.Body.ParamBlock is not null) { Ast errorAst = ast.Body.BeginBlock ?? (Ast)ast.Body.ProcessBlock ?? ast.Body.ParamBlock; parser.ReportError( @@ -974,6 +971,11 @@ internal void InvokeWithPipeImpl( InvocationInfo invocationInfo, params object[] args) { + if (clauseToInvoke == ScriptBlockClauseToInvoke.Clean) + { + throw new PSNotSupportedException(ParserStrings.InvokingCleanBlockNotSupported); + } + if ((clauseToInvoke == ScriptBlockClauseToInvoke.Begin && !HasBeginBlock) || (clauseToInvoke == ScriptBlockClauseToInvoke.Process && !HasProcessBlock) || (clauseToInvoke == ScriptBlockClauseToInvoke.End && !HasEndBlock)) @@ -991,7 +993,7 @@ internal void InvokeWithPipeImpl( throw new PipelineStoppedException(); } - // Validate at the arguments are consistent. The only public API that gets you here never sets createLocalScope to false... + // Validate that the arguments are consistent. The only public API that gets you here never sets createLocalScope to false... Diagnostics.Assert( createLocalScope || functionsToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'functionsToDefine' != null then 'createLocalScope' must be true"); @@ -999,10 +1001,7 @@ internal void InvokeWithPipeImpl( createLocalScope || variablesToDefine == null, "When calling ScriptBlock.InvokeWithContext(), if 'variablesToDefine' != null then 'createLocalScope' must be true"); - if (args == null) - { - args = Array.Empty(); - } + args ??= Array.Empty(); bool runOptimized = context._debuggingMode <= 0 && createLocalScope; var codeToInvoke = GetCodeToInvoke(ref runOptimized, clauseToInvoke); @@ -1011,11 +1010,8 @@ internal void InvokeWithPipeImpl( return; } - if (outputPipe == null) - { - // If we don't have a pipe to write to, we need to discard all results. - outputPipe = new Pipe { NullPipe = true }; - } + // If we don't have a pipe to write to, we need to discard all results. + outputPipe ??= new Pipe { NullPipe = true }; var locals = MakeLocalsTuple(runOptimized); @@ -1041,12 +1037,11 @@ internal void InvokeWithPipeImpl( var oldScopeOrigin = context.EngineSessionState.CurrentScope.ScopeOrigin; var oldSessionState = context.EngineSessionState; - // If the script block has a different language mode than the current, + // If the script block has a different language mode than the current context, // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if (this.LanguageMode.HasValue - && this.LanguageMode != context.LanguageMode) + if (this.LanguageMode.HasValue && this.LanguageMode != context.LanguageMode) { // Don't allow context: ConstrainedLanguage -> FullLanguage transition if // this is dot sourcing into the current scope, unless it is within a trusted module scope. @@ -1057,6 +1052,20 @@ internal void InvokeWithPipeImpl( oldLanguageMode = context.LanguageMode; newLanguageMode = this.LanguageMode; } + else if (SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + string scriptBlockId = this.GetFileName() ?? string.Empty; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: AutomationExceptions.WDACCompiledScriptBlockLogTitle, + message: StringUtil.Format(AutomationExceptions.WDACCompiledScriptBlockLogMessage, scriptBlockId, this.LanguageMode, context.LanguageMode), + fqid: "ScriptBlockDotSourceNotAllowed", + dropIntoDebugger: true); + + // Since we are in audit mode, go ahead and allow the language transition. + oldLanguageMode = context.LanguageMode; + newLanguageMode = this.LanguageMode; + } } Dictionary backupWhenDotting = null; @@ -1195,7 +1204,7 @@ internal void InvokeWithPipeImpl( _sequencePoints = SequencePoints, }; - ScriptBlock.LogScriptBlockStart(this, context.CurrentRunspace.InstanceId); + LogScriptBlockStart(this, context.CurrentRunspace.InstanceId); try { @@ -1203,7 +1212,7 @@ internal void InvokeWithPipeImpl( } finally { - ScriptBlock.LogScriptBlockEnd(this, context.CurrentRunspace.InstanceId); + LogScriptBlockEnd(this, context.CurrentRunspace.InstanceId); } } catch (TargetInvocationException tie) @@ -1362,7 +1371,7 @@ internal static void SetAutomaticVariable(AutomaticVariable variable, object val private Action GetCodeToInvoke(ref bool optimized, ScriptBlockClauseToInvoke clauseToInvoke) { if (clauseToInvoke == ScriptBlockClauseToInvoke.ProcessBlockOnly - && (HasBeginBlock || (HasEndBlock && HasProcessBlock))) + && (HasBeginBlock || HasCleanBlock || (HasEndBlock && HasProcessBlock))) { throw PSTraceSource.NewInvalidOperationException(AutomationExceptions.ScriptBlockInvokeOnOneClauseOnly); } @@ -1379,6 +1388,8 @@ private Action GetCodeToInvoke(ref bool optimized, ScriptBlockC return _scriptBlockData.ProcessBlock; case ScriptBlockClauseToInvoke.End: return _scriptBlockData.EndBlock; + case ScriptBlockClauseToInvoke.Clean: + return _scriptBlockData.CleanBlock; default: return HasProcessBlock ? _scriptBlockData.ProcessBlock : _scriptBlockData.EndBlock; } @@ -1392,6 +1403,8 @@ private Action GetCodeToInvoke(ref bool optimized, ScriptBlockC return _scriptBlockData.UnoptimizedProcessBlock; case ScriptBlockClauseToInvoke.End: return _scriptBlockData.UnoptimizedEndBlock; + case ScriptBlockClauseToInvoke.Clean: + return _scriptBlockData.UnoptimizedCleanBlock; default: return HasProcessBlock ? _scriptBlockData.UnoptimizedProcessBlock : _scriptBlockData.UnoptimizedEndBlock; } @@ -1438,7 +1451,7 @@ internal static void LogScriptBlockCreation(ScriptBlock scriptBlock, bool force) // But split the segments into random sizes (10k + between 0 and 10kb extra) // so that attackers can't creatively force their scripts to span well-known // segments (making simple rules less reliable). - int segmentSize = 10000 + (new Random()).Next(10000); + int segmentSize = 10000 + Random.Shared.Next(10000); int segments = (int)Math.Floor((double)(scriptBlockText.Length / segmentSize)) + 1; int currentLocation = 0; int currentSegmentSize = 0; @@ -1733,7 +1746,7 @@ private static bool GetAndValidateEncryptionRecipients( private static CmsMessageRecipient[] s_encryptionRecipients = null; private static readonly Lazy s_sbLoggingSettingCache = new Lazy( - () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), + static () => Utils.GetPolicySetting(Utils.SystemWideThenCurrentUserConfig), isThreadSafe: true); // Reset any static caches if the certificate has changed @@ -1957,7 +1970,7 @@ private static string LookupHash(uint h) /// /// If a hash matches, we ignore the possibility of a /// collision. If the hash is acceptable, collisions will - /// be infrequent and we'll just log an occasionaly script + /// be infrequent and we'll just log an occasional script /// that isn't really suspicious. /// /// The string matching the hash, or null. @@ -2022,7 +2035,7 @@ public static string Match(string text) continue; } - for (int j = Math.Min(i, runningHash.Length) - 1; j > 0; j--) + for (int j = Math.Min(i, runningHash.Length - 1); j > 0; j--) { // Say our input is: `Emit` (our shortest pattern, len 4). // Towards the end just before matching, we will: @@ -2043,7 +2056,10 @@ public static string Match(string text) if (++longestPossiblePattern >= 4) { var result = CheckForMatches(runningHash, longestPossiblePattern); - if (result != null) return result; + if (result != null) + { + return result; + } } } @@ -2147,46 +2163,17 @@ internal static void LogScriptBlockEnd(ScriptBlock scriptBlock, Guid runspaceId) internal Action UnoptimizedEndBlock { get => _scriptBlockData.UnoptimizedEndBlock; } + internal Action CleanBlock { get => _scriptBlockData.CleanBlock; } + + internal Action UnoptimizedCleanBlock { get => _scriptBlockData.UnoptimizedCleanBlock; } + internal bool HasBeginBlock { get => AstInternal.Body.BeginBlock != null; } internal bool HasProcessBlock { get => AstInternal.Body.ProcessBlock != null; } internal bool HasEndBlock { get => AstInternal.Body.EndBlock != null; } - } - - [Serializable] - internal class ScriptBlockSerializationHelper : ISerializable, IObjectReference - { - private readonly string _scriptText; - private ScriptBlockSerializationHelper(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new ArgumentNullException(nameof(info)); - } - - _scriptText = info.GetValue("ScriptText", typeof(string)) as string; - if (_scriptText == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - } - - /// - /// Returns a script block that corresponds to the version deserialized. - /// - /// The streaming context for this instance. - /// A script block that corresponds to the version deserialized. - public object GetRealObject(StreamingContext context) => ScriptBlock.Create(_scriptText); - - /// - /// Implements the ISerializable contract for serializing a scriptblock. - /// - /// Serialization information for this instance. - /// The streaming context for this instance. - public virtual void GetObjectData(SerializationInfo info, StreamingContext context) - => throw new NotSupportedException(); + internal bool HasCleanBlock { get => AstInternal.Body.CleanBlock != null; } } internal sealed class PSScriptCmdlet : PSCmdlet, IDynamicParameters, IDisposable @@ -2197,11 +2184,15 @@ internal sealed class PSScriptCmdlet : PSCmdlet, IDynamicParameters, IDisposable private readonly bool _useLocalScope; private readonly bool _runOptimized; private readonly bool _rethrowExitException; - private MshCommandRuntime _commandRuntime; private readonly MutableTuple _localsTuple; - private bool _exitWasCalled; private readonly FunctionContext _functionContext; + private MshCommandRuntime _commandRuntime; + private bool _exitWasCalled; + private bool _anyClauseExecuted; + + internal bool ShouldRethrowExitException => _rethrowExitException; + public PSScriptCmdlet(ScriptBlock scriptBlock, bool useNewScope, bool fromScriptFile, ExecutionContext context) { _scriptBlock = scriptBlock; @@ -2291,6 +2282,34 @@ internal override void DoEndProcessing() } } + internal override void DoCleanResource() + { + if (_scriptBlock.HasCleanBlock && _anyClauseExecuted) + { + // The 'Clean' block doesn't write any output to pipeline, so we use a 'NullPipe' here and + // disallow the output to be collected by an 'out' variable. However, the error, warning, + // and information records should still be collectable by the corresponding variables. + Pipe oldOutputPipe = _commandRuntime.OutputPipe; + _functionContext._outputPipe = _commandRuntime.OutputPipe = new Pipe + { + NullPipe = true, + IgnoreOutVariableList = true, + }; + + try + { + RunClause( + clause: _runOptimized ? _scriptBlock.CleanBlock : _scriptBlock.UnoptimizedCleanBlock, + dollarUnderbar: AutomationNull.Value, + inputToProcess: AutomationNull.Value); + } + finally + { + _functionContext._outputPipe = _commandRuntime.OutputPipe = oldOutputPipe; + } + } + } + private void EnterScope() { _commandRuntime.SetVariableListsInPipe(); @@ -2303,14 +2322,15 @@ private void ExitScope() private void RunClause(Action clause, object dollarUnderbar, object inputToProcess) { + _anyClauseExecuted = true; Pipe oldErrorOutputPipe = this.Context.ShellFunctionErrorOutputPipe; // If the script block has a different language mode than the current, // change the language mode. PSLanguageMode? oldLanguageMode = null; PSLanguageMode? newLanguageMode = null; - if (_scriptBlock.LanguageMode.HasValue - && _scriptBlock.LanguageMode != Context.LanguageMode) + if (_scriptBlock.LanguageMode.HasValue && + _scriptBlock.LanguageMode != Context.LanguageMode) { oldLanguageMode = Context.LanguageMode; newLanguageMode = _scriptBlock.LanguageMode; @@ -2356,9 +2376,9 @@ private void RunClause(Action clause, object dollarUnderbar, ob } finally { - this.Context.RestoreErrorPipe(oldErrorOutputPipe); + Context.ShellFunctionErrorOutputPipe = oldErrorOutputPipe; - // Set the language mode + // Restore the language mode if (oldLanguageMode.HasValue) { Context.LanguageMode = oldLanguageMode.Value; @@ -2471,6 +2491,11 @@ private void SetPreferenceVariables() _localsTuple.SetPreferenceVariable(PreferenceVariable.Information, _commandRuntime.InformationPreference); } + if (_commandRuntime.IsProgressActionSet) + { + _localsTuple.SetPreferenceVariable(PreferenceVariable.Progress, _commandRuntime.ProgressPreference); + } + if (_commandRuntime.IsWhatIfFlagSet) { _localsTuple.SetPreferenceVariable(PreferenceVariable.WhatIf, _commandRuntime.WhatIf); @@ -2518,9 +2543,6 @@ public void Dispose() commandRuntime = null; currentObjectInPipeline = null; _input.Clear(); - // _scriptBlock = null; - // _localsTuple = null; - // _functionContext = null; base.InternalDispose(true); _disposed = true; diff --git a/src/System.Management.Automation/engine/runtime/MutableTuple.cs b/src/System.Management.Automation/engine/runtime/MutableTuple.cs index e7ee0d615df..53c40ef3810 100644 --- a/src/System.Management.Automation/engine/runtime/MutableTuple.cs +++ b/src/System.Management.Automation/engine/runtime/MutableTuple.cs @@ -281,7 +281,11 @@ public static int GetSize(Type tupleType) // ContractUtils.RequiresNotNull(tupleType, "tupleType"); int count = 0; - lock (s_sizeDict) if (s_sizeDict.TryGetValue(tupleType, out count)) return count; + lock (s_sizeDict) if (s_sizeDict.TryGetValue(tupleType, out count)) + { + return count; + } + Stack types = new Stack(tupleType.GetGenericArguments()); while (types.Count != 0) @@ -298,7 +302,10 @@ public static int GetSize(Type tupleType) continue; } - if (t == typeof(DynamicNull)) continue; + if (t == typeof(DynamicNull)) + { + continue; + } count++; } @@ -369,7 +376,7 @@ internal static IEnumerable GetAccessProperties(Type tupleType, in foreach (int curIndex in GetAccessPath(size, index)) { - PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", curIndex)); + PropertyInfo pi = tupleType.GetProperty("Item" + string.Create(CultureInfo.InvariantCulture, $"{curIndex:D3}")); Diagnostics.Assert(pi != null, "reflection should always find Item"); yield return pi; tupleType = pi.PropertyType; @@ -440,7 +447,7 @@ private static MutableTuple MakeTuple(Func creator, Type tupleType for (int i = 0; i < size; i++) { - PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", i)); + PropertyInfo pi = tupleType.GetProperty("Item" + string.Create(CultureInfo.InvariantCulture, $"{i:D3}")); res.SetValueImpl(i, MakeTuple(pi.PropertyType, null, null)); } } @@ -504,7 +511,7 @@ public abstract int Capacity /// public static Expression Create(params Expression[] values) { - return CreateNew(MakeTupleType(values.Select(x => x.Type).ToArray()), 0, values.Length, values); + return CreateNew(MakeTupleType(values.Select(static x => x.Type).ToArray()), 0, values.Length, values); } private static int PowerOfTwoRound(int value) @@ -540,7 +547,7 @@ internal static Expression CreateNew(Type tupleType, int start, int end, Express int newStart = start + (i * multiplier); int newEnd = System.Math.Min(end, start + ((i + 1) * multiplier)); - PropertyInfo pi = tupleType.GetProperty("Item" + string.Format(CultureInfo.InvariantCulture, "{0:D3}", i)); + PropertyInfo pi = tupleType.GetProperty("Item" + string.Create(CultureInfo.InvariantCulture, $"{i:D3}")); newValues[i] = CreateNew(pi.PropertyType, newStart, newEnd, values); } @@ -564,7 +571,7 @@ internal static Expression CreateNew(Type tupleType, int start, int end, Express } } - return Expression.New(tupleType.GetConstructor(newValues.Select(x => x.Type).ToArray()), newValues); + return Expression.New(tupleType.GetConstructor(newValues.Select(static x => x.Type).ToArray()), newValues); } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs index fa4c2c2b565..4fd68cdd201 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ArrayOps.cs @@ -12,6 +12,15 @@ namespace System.Management.Automation { internal static class ArrayOps { + internal static object AddObjectArray(object[] lhs, object rhs) + { + int newIdx = lhs.Length; + Array.Resize(ref lhs, newIdx + 1); + lhs[newIdx] = rhs; + + return lhs; + } + internal static object[] SlicingIndex(object target, object[] indexes, Func indexer) { var result = new object[indexes.Length]; diff --git a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs index 5afe23a6362..2b741a29c31 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/ClassOps.cs @@ -22,7 +22,7 @@ namespace System.Management.Automation.Internal /// /// Every Runspace in one process contains SessionStateInternal per module (module SessionState). /// Every RuntimeType is associated to only one SessionState in the Runspace, which creates it: - /// it's ever global state or a module state. + /// it's either global state or a module state. /// In the former case, module can be imported from the different runspaces in the same process. /// And so runspaces will share RuntimeType. But in every runspace, Type is associated with just one SessionState. /// We want type methods to be able access $script: variables and module-specific methods. @@ -115,10 +115,10 @@ public class ScriptBlockMemberMethodWrapper /// We use WeakReference object to point to the default SessionState because if GC already collect the SessionState, /// or the Runspace it chains to is closed and disposed, then we cannot run the static method there anyways. /// - /// + /// /// The default SessionState is used only if a static method is called from a Runspace where the PowerShell class is /// never defined, or is called on a thread without a default Runspace. Usage like those should be rare. - /// + /// private readonly WeakReference _defaultSessionStateToUse; /// @@ -162,7 +162,7 @@ internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast) /// Initialization happens when the script that defines PowerShell class is executed. /// This initialization is required only if this wrapper is for a static method. /// - /// + /// /// When the same script file gets executed multiple times, the .NET type generated from the PowerShell class /// defined in the file will be shared in those executions, and thus this method will be called multiple times /// possibly in the contexts of different Runspace/SessionState. @@ -174,7 +174,7 @@ internal ScriptBlockMemberMethodWrapper(IParameterMetadataProvider ast) /// is declared, and thus we can always get the correct SessionState to use by querying the 'SessionStateKeeper'. /// The default SessionState is used only if a static method is called from a Runspace where the class is never /// defined, or is called on a thread without a default Runspace. - /// + /// internal void InitAtRuntime() { if (_isStatic) @@ -356,7 +356,7 @@ private static DynamicMethod CreateDynamicMethod(MethodInfo mi) { // Pass in the declaring type because instance method has a hidden parameter 'this' as the first parameter. var paramTypes = new List { mi.DeclaringType }; - paramTypes.AddRange(mi.GetParameters().Select(x => x.ParameterType)); + paramTypes.AddRange(mi.GetParameters().Select(static x => x.ParameterType)); var dm = new DynamicMethod("PSNonVirtualCall_" + mi.Name, mi.ReturnType, paramTypes.ToArray(), mi.DeclaringType); ILGenerator il = dm.GetILGenerator(); diff --git a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs index df8b36eb40f..d584666ab62 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/MiscOps.cs @@ -13,6 +13,8 @@ using System.Management.Automation.Internal.Host; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; +using System.Management.Automation.Security; +using System.Numerics; using System.Reflection; using System.Runtime.CompilerServices; using System.Text.RegularExpressions; @@ -53,13 +55,24 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, "CantInvokeInNonImportedModule", ParserStrings.CantInvokeInNonImportedModule, mi.Name); } - else if (((invocationToken == TokenKind.Ampersand) || (invocationToken == TokenKind.Dot)) && (mi.LanguageMode != context.LanguageMode)) + else if ((invocationToken == TokenKind.Ampersand || invocationToken == TokenKind.Dot) && mi.LanguageMode != context.LanguageMode) { - // Disallow FullLanguage "& (Get-Module MyModule) MyPrivateFn" from ConstrainedLanguage because it always - // runs "internal" origin and so has access to all functions, including non-exported functions. - // Otherwise we end up leaking non-exported functions that run in FullLanguage. - throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, - "CantInvokeCallOperatorAcrossLanguageBoundaries", ParserStrings.CantInvokeCallOperatorAcrossLanguageBoundaries); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + // Disallow FullLanguage "& (Get-Module MyModule) MyPrivateFn" from ConstrainedLanguage because it always + // runs "internal" origin and so has access to all functions, including non-exported functions. + // Otherwise we end up leaking non-exported functions that run in FullLanguage. + throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), null, + "CantInvokeCallOperatorAcrossLanguageBoundaries", ParserStrings.CantInvokeCallOperatorAcrossLanguageBoundaries); + } + + // In audit mode, report but don't enforce. + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParserStrings.WDACParserModuleScopeCallOperatorLogTitle, + message: ParserStrings.WDACParserModuleScopeCallOperatorLogMessage, + fqid: "ModuleScopeCallOperatorNotAllowed", + dropIntoDebugger: true); } commandSessionState = mi.SessionState.Internal; @@ -161,6 +174,7 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, (cmd is ScriptCommand || cmd is PSScriptCmdlet); bool isNativeCommand = commandProcessor is NativeCommandProcessor; + for (int i = commandIndex + 1; i < commandElements.Length; ++i) { var cpi = commandElements[i]; @@ -207,9 +221,24 @@ private static CommandProcessorBase AddCommand(PipelineProcessor pipe, bool redirectedInformation = false; if (redirections != null) { - foreach (var redirection in redirections) + if (isNativeCommand) { - redirection.Bind(pipe, commandProcessor, context); + foreach (CommandRedirection redirection in redirections) + { + if (redirection is MergingRedirection) + { + redirection.Bind(pipe, commandProcessor, context); + } + } + } + + foreach (CommandRedirection redirection in redirections) + { + if (!isNativeCommand || redirection is not MergingRedirection) + { + redirection.Bind(pipe, commandProcessor, context); + } + switch (redirection.FromStream) { case RedirectionStream.Error: @@ -426,10 +455,7 @@ internal static void InvokePipeline(object input, try { - if (context.Events != null) - { - context.Events.ProcessPendingActions(); - } + context.Events?.ProcessPendingActions(); if (input == AutomationNull.Value && !ignoreInput) { @@ -519,24 +545,17 @@ internal static void InvokePipelineInBackground( try { - if (context.Events != null) - { - context.Events.ProcessPendingActions(); - } + context.Events?.ProcessPendingActions(); CommandProcessorBase commandProcessor = null; // For background jobs rewrite the pipeline as a Start-Job command var scriptblockBodyString = pipelineAst.Extent.Text; var pipelineOffset = pipelineAst.Extent.StartOffset; - var variables = pipelineAst.FindAll(x => x is VariableExpressionAst, true); - - // Used to make sure that the job runs in the current directory - const string cmdPrefix = @"Microsoft.PowerShell.Management\Set-Location -LiteralPath $using:pwd ; "; + var variables = pipelineAst.FindAll(static x => x is VariableExpressionAst, true); - // Minimize allocations by initializing the stringbuilder to the size of the source string + prefix + space for ${using:} * 2 - System.Text.StringBuilder updatedScriptblock = new System.Text.StringBuilder(cmdPrefix.Length + scriptblockBodyString.Length + 18); - updatedScriptblock.Append(cmdPrefix); + // Minimize allocations by initializing the stringbuilder to the size of the source string + space for ${using:} * 2 + System.Text.StringBuilder updatedScriptblock = new System.Text.StringBuilder(scriptblockBodyString.Length + 18); int position = 0; // Prefix variables in the scriptblock with $using: @@ -568,14 +587,25 @@ internal static void InvokePipelineInBackground( var sb = ScriptBlock.Create(updatedScriptblock.ToString()); var commandInfo = new CmdletInfo("Start-Job", typeof(StartJobCommand)); commandProcessor = context.CommandDiscovery.LookupCommandProcessor(commandInfo, CommandOrigin.Internal, false, context.EngineSessionState); - var parameter = CommandParameterInternal.CreateParameterWithArgument( + + var workingDirectoryParameter = CommandParameterInternal.CreateParameterWithArgument( parameterAst: pipelineAst, - "ScriptBlock", - null, + parameterName: "WorkingDirectory", + parameterText: null, argumentAst: pipelineAst, - sb, - false); - commandProcessor.AddParameter(parameter); + value: context.SessionState.Path.CurrentLocation.Path, + spaceAfterParameter: false); + + var scriptBlockParameter = CommandParameterInternal.CreateParameterWithArgument( + parameterAst: pipelineAst, + parameterName: "ScriptBlock", + parameterText: null, + argumentAst: pipelineAst, + value: sb, + spaceAfterParameter: false); + + commandProcessor.AddParameter(workingDirectoryParameter); + commandProcessor.AddParameter(scriptBlockParameter); pipelineProcessor.Add(commandProcessor); pipelineProcessor.LinkPipelineSuccessOutput(outputPipe ?? new Pipe(new List())); @@ -684,6 +714,18 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, // of invoking it. So the trustworthiness is defined by the trustworthiness of the // script block's language mode. bool isTrusted = scriptBlock.LanguageMode == PSLanguageMode.FullLanguage; + if (scriptBlock.LanguageMode == PSLanguageMode.ConstrainedLanguage + && SystemPolicy.GetSystemLockdownPolicy() == SystemEnforcementMode.Audit) + { + // In audit mode, report but don't enforce. + isTrusted = true; + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParserStrings.WDACGetSteppablePipelineLogTitle, + message: ParserStrings.WDACGetSteppablePipelineLogMessage, + fqid: "GetSteppablePipelineMayFail", + dropIntoDebugger: true); + } foreach (var commandAst in pipelineAst.PipelineElements.Cast()) { @@ -699,7 +741,7 @@ internal static SteppablePipeline GetSteppablePipeline(PipelineAst pipelineAst, var exprAst = (ExpressionAst)commandElement; var argument = Compiler.GetExpressionValue(exprAst, isTrusted, context); - var splatting = (exprAst is VariableExpressionAst && ((VariableExpressionAst)exprAst).Splatted); + var splatting = exprAst is VariableExpressionAst && ((VariableExpressionAst)exprAst).Splatted; commandParameters.Add(CommandParameterInternal.CreateArgument(argument, exprAst, splatting)); } @@ -767,8 +809,8 @@ private static CommandParameterInternal GetCommandParameter(CommandParameterAst } object argumentValue = Compiler.GetExpressionValue(argumentAst, isTrusted, context); - bool spaceAfterParameter = (errorPos.EndLineNumber != argumentAst.Extent.StartLineNumber || - errorPos.EndColumnNumber != argumentAst.Extent.StartColumnNumber); + bool spaceAfterParameter = errorPos.EndLineNumber != argumentAst.Extent.StartLineNumber || + errorPos.EndColumnNumber != argumentAst.Extent.StartColumnNumber; return CommandParameterInternal.CreateParameterWithArgument(commandParameterAst, commandParameterAst.ParameterName, errorPos.Text, argumentAst, argumentValue, spaceAfterParameter); @@ -834,10 +876,7 @@ internal static ExitException GetExitException(object exitCodeObj) internal static void CheckForInterrupts(ExecutionContext context) { - if (context.Events != null) - { - context.Events.ProcessPendingActions(); - } + context.Events?.ProcessPendingActions(); if (context.CurrentPipelineStopping) { @@ -923,7 +962,7 @@ public override string ToString() { return FromStream == RedirectionStream.All ? "*>&1" - : string.Format(CultureInfo.InvariantCulture, "{0}>&1", (int)FromStream); + : string.Create(CultureInfo.InvariantCulture, $"{(int)FromStream}>&1"); } // private RedirectionStream ToStream { get; set; } @@ -1032,11 +1071,13 @@ internal FileRedirection(RedirectionStream from, bool appending, string file) public override string ToString() { - return string.Format(CultureInfo.InvariantCulture, "{0}> {1}", - FromStream == RedirectionStream.All - ? "*" - : ((int)FromStream).ToString(CultureInfo.InvariantCulture), - File); + return string.Format( + CultureInfo.InvariantCulture, + "{0}> {1}", + FromStream == RedirectionStream.All + ? "*" + : ((int)FromStream).ToString(CultureInfo.InvariantCulture), + File); } internal string File { get; } @@ -1049,6 +1090,25 @@ public override string ToString() // dir > out internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcessorBase commandProcessor, ExecutionContext context) { + // Check first to see if File is a variable path. If so, we'll not create the FileBytePipe + bool redirectToVariable = false; + + context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(File, out ProviderInfo p, out _); + if (p != null && p.NameEquals(context.ProviderNames.Variable)) + { + redirectToVariable = true; + } + + if (commandProcessor is NativeCommandProcessor nativeCommand + && nativeCommand.CommandRuntime.ErrorMergeTo is not MshCommandRuntime.MergeDataStream.Output + && FromStream is RedirectionStream.Output + && !string.IsNullOrWhiteSpace(File) + && !redirectToVariable) + { + nativeCommand.StdOutDestination = FileBytePipe.Create(File, Appending); + return; + } + Pipe pipe = GetRedirectionPipe(context, pipelineProcessor); switch (FromStream) @@ -1058,10 +1118,7 @@ internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcesso // Normally, context.CurrentCommandProcessor will not be null. But in legacy DRTs from ParserTest.cs, // a scriptblock may be invoked through 'DoInvokeReturnAsIs' using .NET reflection. In that case, // context.CurrentCommandProcessor will be null. We don't try passing along variable lists in such case. - if (context.CurrentCommandProcessor != null) - { - context.CurrentCommandProcessor.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); - } + context.CurrentCommandProcessor?.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); commandProcessor.CommandRuntime.OutputPipe = pipe; commandProcessor.CommandRuntime.ErrorOutputPipe = pipe; @@ -1072,10 +1129,7 @@ internal override void Bind(PipelineProcessor pipelineProcessor, CommandProcesso break; case RedirectionStream.Output: // Since a temp output pipe is going to be used, we should pass along the error and warning variable list. - if (context.CurrentCommandProcessor != null) - { - context.CurrentCommandProcessor.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); - } + context.CurrentCommandProcessor?.CommandRuntime.OutputPipe.SetVariableListForTemporaryPipe(pipe); commandProcessor.CommandRuntime.OutputPipe = pipe; break; @@ -1164,26 +1218,49 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par return new Pipe { NullPipe = true }; } - CommandProcessorBase commandProcessor = context.CreateCommand("out-file", false); - Diagnostics.Assert(commandProcessor != null, "CreateCommand returned null"); - - // Previously, we mandated Unicode encoding here - // Now, We can take what ever has been set if PSDefaultParameterValues - // Unicode is still the default, but now may be overridden + // determine whether we're trying to set a variable by inspecting the file path + // if we can determine that it's a variable, we'll use Set-Variable rather than Out-File + CommandProcessorBase commandProcessor; + var name = context.SessionState.Path.GetUnresolvedProviderPathFromPSPath(File, out ProviderInfo p, out _); - var cpi = CommandParameterInternal.CreateParameterWithArgument( - /*parameterAst*/null, "Filepath", "-Filepath:", - /*argumentAst*/null, File, - false); - commandProcessor.AddParameter(cpi); + if (p != null && p.NameEquals(context.ProviderNames.Variable)) + { + commandProcessor = context.CreateCommand("Set-Variable", false); + Diagnostics.Assert(commandProcessor != null, "CreateCommand returned null"); + var cpi = CommandParameterInternal.CreateParameterWithArgument( + /*parameterAst*/null, "Name", "-Name:", + /*argumentAst*/null, name, + false); + commandProcessor.AddParameter(cpi); - if (this.Appending) + if (this.Appending) + { + commandProcessor.AddParameter(CommandParameterInternal.CreateParameter("Append", "-Append", null)); + } + } + else { - cpi = CommandParameterInternal.CreateParameterWithArgument( - /*parameterAst*/null, "Append", "-Append:", - /*argumentAst*/null, true, + commandProcessor = context.CreateCommand("out-file", false); + Diagnostics.Assert(commandProcessor != null, "CreateCommand returned null"); + + // Previously, we mandated Unicode encoding here + // Now, We can take what ever has been set if PSDefaultParameterValues + // Unicode is still the default, but now may be overridden + + var cpi = CommandParameterInternal.CreateParameterWithArgument( + /*parameterAst*/null, "Filepath", "-Filepath:", + /*argumentAst*/null, File, false); commandProcessor.AddParameter(cpi); + + if (this.Appending) + { + cpi = CommandParameterInternal.CreateParameterWithArgument( + /*parameterAst*/null, "Append", "-Append:", + /*argumentAst*/null, true, + false); + commandProcessor.AddParameter(cpi); + } } PipelineProcessor = new PipelineProcessor(); @@ -1199,19 +1276,22 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par // is more specific tp the redirection operation... if (rte.ErrorRecord.Exception is System.ArgumentException) { - throw InterpreterError.NewInterpreterExceptionWithInnerException(null, - typeof(RuntimeException), null, "RedirectionFailed", ParserStrings.RedirectionFailed, - rte.ErrorRecord.Exception, File, rte.ErrorRecord.Exception.Message); + throw InterpreterError.NewInterpreterExceptionWithInnerException( + null, + typeof(RuntimeException), + null, + "RedirectionFailed", + ParserStrings.RedirectionFailed, + rte.ErrorRecord.Exception, + File, + rte.ErrorRecord.Exception.Message); } throw; } - if (parentPipelineProcessor != null) - { - // I think this is only necessary for calling Dispose on the commands in the redirection pipe. - parentPipelineProcessor.AddRedirectionPipe(PipelineProcessor); - } + // I think this is only necessary for calling Dispose on the commands in the redirection pipe. + parentPipelineProcessor?.AddRedirectionPipe(PipelineProcessor); return new Pipe(context, PipelineProcessor); } @@ -1220,17 +1300,14 @@ internal Pipe GetRedirectionPipe(ExecutionContext context, PipelineProcessor par /// After file redirection is done, we need to call 'DoComplete' on the pipeline processor, /// so that 'EndProcessing' of Out-File can be called to wrap up the file write operation. /// - /// + /// /// 'StartStepping' is called after creating the pipeline processor. /// 'Step' is called when an object is added to the pipe created with the pipeline processor. - /// + /// internal void CallDoCompleteForExpression() { // The pipe returned from 'GetRedirectionPipe' could be a NullPipe - if (PipelineProcessor != null) - { - PipelineProcessor.DoComplete(); - } + PipelineProcessor?.DoComplete(); } private bool _disposed; @@ -1248,10 +1325,7 @@ private void Dispose(bool disposing) if (disposing) { - if (PipelineProcessor != null) - { - PipelineProcessor.Dispose(); - } + PipelineProcessor?.Dispose(); } _disposed = true; @@ -1280,7 +1354,7 @@ internal static void DefineFunction(ExecutionContext context, } catch (Exception exception) { - if (!(exception is RuntimeException rte)) + if (exception is not RuntimeException rte) { throw ExceptionHandlingOps.ConvertToRuntimeException(exception, functionDefinitionAst.Extent); } @@ -1314,6 +1388,17 @@ internal ScriptBlock GetScriptBlock(ExecutionContext context, bool isFilter) } } + internal static class ByRefOps + { + /// + /// There is no way to directly work with ByRef type in the expression tree, so we turn to reflection in this case. + /// + internal static object GetByRefPropertyValue(object target, PropertyInfo property) + { + return property.GetValue(target); + } + } + internal static class HashtableOps { internal static void AddKeyValuePair(IDictionary hashtable, object key, object value, IScriptExtent errorExtent) @@ -1379,7 +1464,7 @@ internal class CatchAll { } /// /// Represent a handler search result. /// - private class HandlerSearchResult + private sealed class HandlerSearchResult { internal HandlerSearchResult() { @@ -1447,7 +1532,10 @@ private static void FindAndProcessHandler(Type[] types, int[] ranks, int handler = FindMatchingHandlerByType(exception.GetType(), types); // If no handler was found, return without changing the current result. - if (handler == -1) { return; } + if (handler == -1) + { + return; + } // New handler was found. // - If new-rank is less than current-rank -- meaning the new handler is more specific, @@ -1481,7 +1569,7 @@ internal static int FindMatchingHandler(MutableTuple tuple, RuntimeException rte do { - // Always assume no need to repeat the search for another interation + // Always assume no need to repeat the search for another iteration continueToSearch = false; // The 'ErrorRecord' of the current RuntimeException would be passed to $_ ErrorRecord errorRecordToPass = rte.ErrorRecord; @@ -1578,23 +1666,33 @@ private static int FindMatchingHandlerByType(Type exceptionType, Type[] types) internal static bool SuspendStoppingPipeline(ExecutionContext context) { - LocalPipeline lpl = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); - if (lpl != null) + var localPipeline = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); + return SuspendStoppingPipelineImpl(localPipeline); + } + + internal static void RestoreStoppingPipeline(ExecutionContext context, bool oldIsStopping) + { + var localPipeline = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); + RestoreStoppingPipelineImpl(localPipeline, oldIsStopping); + } + + internal static bool SuspendStoppingPipelineImpl(LocalPipeline localPipeline) + { + if (localPipeline is not null) { - bool oldIsStopping = lpl.Stopper.IsStopping; - lpl.Stopper.IsStopping = false; + bool oldIsStopping = localPipeline.Stopper.IsStopping; + localPipeline.Stopper.IsStopping = false; return oldIsStopping; } return false; } - internal static void RestoreStoppingPipeline(ExecutionContext context, bool oldIsStopping) + internal static void RestoreStoppingPipelineImpl(LocalPipeline localPipeline, bool oldIsStopping) { - LocalPipeline lpl = (LocalPipeline)context.CurrentRunspace.GetCurrentlyRunningPipeline(); - if (lpl != null) + if (localPipeline is not null) { - lpl.Stopper.IsStopping = oldIsStopping; + localPipeline.Stopper.IsStopping = oldIsStopping; } } @@ -1616,6 +1714,9 @@ internal static void CheckActionPreference(FunctionContext funcContext, Exceptio InterpreterError.UpdateExceptionErrorRecordPosition(rte, funcContext.CurrentPosition); } + // Update the history id if needed to associate the exception with the right history item. + InterpreterError.UpdateExceptionErrorRecordHistoryId(rte, funcContext._executionContext); + var context = funcContext._executionContext; var outputPipe = funcContext._outputPipe; @@ -1726,10 +1827,7 @@ private static ActionPreference ProcessTraps(FunctionContext funcContext, ErrorRecord err = rte.ErrorRecord; // CurrentCommandProcessor is normally not null, but it is null // when executing some unit tests through reflection. - if (context.CurrentCommandProcessor != null) - { - context.CurrentCommandProcessor.ForgetScriptException(); - } + context.CurrentCommandProcessor?.ForgetScriptException(); try { @@ -1923,10 +2021,7 @@ internal static void SetErrorVariables(IScriptExtent extent, RuntimeException rt if (rte is not PipelineStoppedException) { - if (outputPipe != null) - { - outputPipe.AppendVariableList(VariableStreamKind.Error, errRec); - } + outputPipe?.AppendVariableList(VariableStreamKind.Error, errRec); context.AppendDollarError(errRec); } @@ -2301,8 +2396,13 @@ internal static void InitPowerShellTypesAtRuntime(TypeDefinitionAst[] types) Diagnostics.Assert(t.Type != null, "TypeDefinitionAst.Type cannot be null"); if (t.IsClass) { - var helperType = - t.Type.Assembly.GetType(t.Type.FullName + "_"); + if (t.Type.IsDefined(typeof(NoRunspaceAffinityAttribute), inherit: true)) + { + // Skip the initialization for session state affinity. + continue; + } + + var helperType = t.Type.Assembly.GetType(t.Type.FullName + "_"); Diagnostics.Assert(helperType != null, "no corresponding " + t.Type.FullName + "_ type found"); foreach (var p in helperType.GetFields(BindingFlags.Static | BindingFlags.NonPublic)) { @@ -2773,10 +2873,8 @@ internal static object ForEach(IEnumerator enumerator, object expression, object { Diagnostics.Assert(enumerator != null, "The ForEach() operator should never receive a null enumerator value from the runtime."); Diagnostics.Assert(arguments != null, "The ForEach() operator should never receive a null value for the 'arguments' parameter from the runtime."); - if (expression == null) - { - throw new ArgumentNullException(nameof(expression)); - } + + ArgumentNullException.ThrowIfNull(expression); var context = Runspace.DefaultRunspace.ExecutionContext; @@ -2855,6 +2953,11 @@ internal static object ForEach(IEnumerator enumerator, object expression, object ScriptBlock sb = expression as ScriptBlock; if (sb != null) { + if (sb.HasCleanBlock) + { + throw new PSNotSupportedException(ParserStrings.ForEachNotSupportCleanBlock); + } + Pipe outputPipe = new Pipe(result); if (sb.HasBeginBlock) { @@ -2979,8 +3082,18 @@ internal static object ForEach(IEnumerator enumerator, object expression, object { if (!CoreTypes.Contains(basedCurrent.GetType())) { - throw InterpreterError.NewInterpreterException(current, typeof(PSInvalidOperationException), - null, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); + if (SystemPolicy.GetSystemLockdownPolicy() != SystemEnforcementMode.Audit) + { + throw InterpreterError.NewInterpreterException(current, typeof(PSInvalidOperationException), + null, "MethodInvocationNotSupportedInConstrainedLanguage", ParserStrings.InvokeMethodConstrainedLanguage); + } + + SystemPolicy.LogWDACAuditMessage( + context: context, + title: ParserStrings.WDACParserForEachOperatorLogTitle, + message: StringUtil.Format(ParserStrings.WDACParserForEachOperatorLogMessage, method.Name ?? string.Empty), + fqid: "ForEachOperatorMethodInvocationNotAllowed", + dropIntoDebugger: true); } } @@ -3497,10 +3610,7 @@ internal static void WriteEnumerableToPipe(IEnumerator enumerator, Pipe pipe, Ex if (dispose) { var disposable = enumerator as IDisposable; - if (disposable != null) - { - disposable.Dispose(); - } + disposable?.Dispose(); } } } @@ -3531,4 +3641,111 @@ internal static object[] GetSlice(IList list, int startIndex) return result; } } + + internal static class MemberInvocationLoggingOps + { +#if DEBUG + private static readonly Lazy DumpLogAMSIContent = new Lazy( + () => { + object result = Environment.GetEnvironmentVariable("__PSDumpAMSILogContent"); + if (result != null && LanguagePrimitives.TryConvertTo(result, out int value)) + { + return value == 1; + } + return false; + } + ); +#endif + + private static string ArgumentToString(object arg) + { + object baseObj = PSObject.Base(arg); + if (baseObj is null) + { + // The argument is null or AutomationNull.Value. + return "null"; + } + + // The comparisons below are ordered by the likelihood of arguments being of those types. + if (baseObj is string str) + { + return str; + } + + // Special case some types to call 'ToString' on the object. For the rest, we return its + // full type name to avoid calling a potentially expensive 'ToString' implementation. + Type baseType = baseObj.GetType(); + if (baseType.IsEnum || baseType.IsPrimitive + || baseType == typeof(Guid) + || baseType == typeof(Uri) + || baseType == typeof(Version) + || baseType == typeof(SemanticVersion) + || baseType == typeof(BigInteger) + || baseType == typeof(decimal)) + { + return baseObj.ToString(); + } + + return baseType.FullName; + } + + internal static void LogMemberInvocation(string targetName, string name, object[] args) + { + try + { + var contentName = "PowerShellMemberInvocation"; + var argsBuilder = new Text.StringBuilder(); + + for (int i = 0; i < args.Length; i++) + { + string value = ArgumentToString(args[i]); + + if (i > 0) + { + argsBuilder.Append(", "); + } + + argsBuilder.Append($"<{value}>"); + } + + string content = $"<{targetName}>.{name}({argsBuilder})"; + +#if DEBUG + if (DumpLogAMSIContent.Value) + { + Console.WriteLine("\n=== Amsi notification report content ==="); + Console.WriteLine(content); + } +#endif + + var success = AmsiUtils.ReportContent( + name: contentName, + content: content); + +#if DEBUG + if (DumpLogAMSIContent.Value) + { + Console.WriteLine($"=== Amsi notification report success: {success} ==="); + } +#endif + } + catch (PSSecurityException) + { + // ReportContent() will throw PSSecurityException if AMSI detects malware, which + // must be propagated. + throw; + } +#pragma warning disable CS0168 // variable declared but never used + catch (Exception ex) +#pragma warning restore CS0168 + { +#if DEBUG + if (DumpLogAMSIContent.Value) + { + Console.WriteLine($"!!! Amsi notification report exception: {ex} !!!"); + } +#endif + } + } + } } diff --git a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs index 0c4658cc14d..0ac1db53ff9 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/StringOps.cs @@ -28,11 +28,8 @@ internal static string Multiply(string s, int times) { Diagnostics.Assert(s != null, "caller to verify argument is not null"); - if (times < 0) - { - // TODO: this should be a runtime error. - throw new ArgumentOutOfRangeException(nameof(times)); - } + // TODO: this should be a runtime error. + ArgumentOutOfRangeException.ThrowIfNegative(times); if (times == 0 || s.Length == 0) { diff --git a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs index d337c56ab2b..72126c726c9 100644 --- a/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs +++ b/src/System.Management.Automation/engine/runtime/Operations/VariableOps.cs @@ -46,6 +46,13 @@ internal static object SetVariableValue(VariablePath variablePath, object value, : GetAttributeCollection(attributeAsts); var = new PSVariable(variablePath.UnqualifiedPath, value, ScopedItemOptions.None, attributes); + if (attributes.Count > 0) + { + // When there are any attributes, it's possible the value was converted/transformed. + // Use 'GetValueRaw' here so the debugger check won't be triggered. + value = var.GetValueRaw(); + } + // Marking untrusted values for assignments in 'ConstrainedLanguage' mode is done in // SessionStateScope.SetVariable. sessionState.SetVariable(variablePath, var, false, origin); @@ -81,7 +88,7 @@ internal static object SetVariableValue(VariablePath variablePath, object value, null, Metadata.InvalidValueFailure, var.Name, - ((value != null) ? value.ToString() : "$null")); + (value != null) ? value.ToString() : "$null"); throw e; } @@ -277,7 +284,7 @@ private static UsingResult GetUsingValueFromTuple(MutableTuple tuple, string usi return null; } - private class UsingResult + private sealed class UsingResult { public object Value { get; set; } } diff --git a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs index 93394be6808..defd87662e8 100644 --- a/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs +++ b/src/System.Management.Automation/engine/runtime/ScriptBlockToPowerShell.cs @@ -172,7 +172,7 @@ internal static void ThrowError(ScriptBlockToPowerShellNotSupportedException ex, } } - internal class UsingExpressionAstSearcher : AstSearcher + internal sealed class UsingExpressionAstSearcher : AstSearcher { internal static IEnumerable FindAllUsingExpressions(Ast ast) { @@ -207,7 +207,7 @@ public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst ast /// Converts a ScriptBlock to a PowerShell object by traversing the /// given Ast. /// - internal class ScriptBlockToPowerShellConverter + internal sealed class ScriptBlockToPowerShellConverter { private readonly PowerShell _powershell; private ExecutionContext _context; @@ -230,10 +230,7 @@ internal static PowerShell Convert(ScriptBlockAst body, { ExecutionContext.CheckStackDepth(); - if (args == null) - { - args = Array.Empty(); - } + args ??= Array.Empty(); // Perform validations on the ScriptBlock. GetSimplePipeline can allow for more than one // pipeline if the first parameter is true, but Invoke-Command doesn't yet support multiple @@ -324,16 +321,14 @@ internal static PowerShell Convert(ScriptBlockAst body, /// Scriptblock to search. /// True when input is trusted. /// Execution context. - /// List of foreach command names and aliases. /// Dictionary of using variable map. internal static Dictionary GetUsingValuesForEachParallel( ScriptBlock scriptBlock, bool isTrustedInput, - ExecutionContext context, - string[] foreachNames) + ExecutionContext context) { - // Using variables for Foreach-Object -Parallel use are restricted to be within the - // Foreach-Object -Parallel call scope. This will filter the using variable map to variables + // Using variables for Foreach-Object -Parallel use are restricted to be within the + // Foreach-Object -Parallel call scope. This will filter the using variable map to variables // only within the current (outer) Foreach-Object -Parallel call scope. var usingAsts = UsingExpressionAstSearcher.FindAllUsingExpressions(scriptBlock.Ast).ToList(); UsingExpressionAst usingAst = null; @@ -350,7 +345,7 @@ internal static Dictionary GetUsingValuesForEachParallel( for (int i = 0; i < usingAsts.Count; ++i) { usingAst = (UsingExpressionAst)usingAsts[i]; - if (IsInForeachParallelCallingScope(usingAst, foreachNames)) + if (IsInForeachParallelCallingScope(scriptBlock.Ast, usingAst)) { var value = Compiler.GetExpressionValue(usingAst.SubExpression, isTrustedInput, context); string usingAstKey = PsUtils.GetUsingExpressionKey(usingAst); @@ -363,11 +358,11 @@ internal static Dictionary GetUsingValuesForEachParallel( if (rte.ErrorRecord.FullyQualifiedErrorId.Equals("VariableIsUndefined", StringComparison.Ordinal)) { throw InterpreterError.NewInterpreterException( - targetObject: null, + targetObject: null, exceptionType: typeof(RuntimeException), - errorPosition: usingAst.Extent, + errorPosition: usingAst.Extent, resourceIdAndErrorId: "UsingVariableIsUndefined", - resourceString: AutomationExceptions.UsingVariableIsUndefined, + resourceString: AutomationExceptions.UsingVariableIsUndefined, args: rte.ErrorRecord.TargetObject); } } @@ -382,21 +377,65 @@ internal static Dictionary GetUsingValuesForEachParallel( return usingValueMap; } + // List of Foreach-Object command names and aliases. + // TODO: Look into using SessionState.Internal.GetAliasTable() to find all user created aliases. + // But update Alias command logic to maintain reverse table that lists all aliases mapping + // to a single command definition, for performance. + private static readonly string[] forEachNames = new string[] + { + "ForEach-Object", + "foreach", + "%" + }; + + private static bool FindForEachInCommand(CommandAst commandAst) + { + // Command name is always the first element in the CommandAst. + // e.g., 'foreach -parallel {}' + var commandNameElement = (commandAst.CommandElements.Count > 0) ? commandAst.CommandElements[0] : null; + if (commandNameElement is StringConstantExpressionAst commandName) + { + bool found = false; + foreach (var foreachName in forEachNames) + { + if (commandName.Value.Equals(foreachName, StringComparison.OrdinalIgnoreCase)) + { + found = true; + break; + } + } + + if (found) + { + // Verify this is foreach-object with parallel parameter set. + var bindingResult = StaticParameterBinder.BindCommand(commandAst); + if (bindingResult.BoundParameters.ContainsKey("Parallel")) + { + return true; + } + } + } + + return false; + } + /// /// Walks the using Ast to verify it is used within a foreach-object -parallel command /// and parameter set scope, and not from within a nested foreach-object -parallel call. /// + /// Scriptblock Ast containing this using Ast /// Using Ast to check. - /// List of foreach-object command names. /// True if using expression is in current call scope. private static bool IsInForeachParallelCallingScope( - UsingExpressionAst usingAst, - string[] foreachNames) + Ast scriptblockAst, + UsingExpressionAst usingAst) { + Diagnostics.Assert(usingAst != null, "usingAst argument cannot be null."); + /* Example: $Test1 = "Hello" - 1 | ForEach-Object -Parallel { + 1 | ForEach-Object -Parallel { $using:Test1 $Test2 = "Goodbye" 1 | ForEach-Object -Parallel { @@ -405,54 +444,23 @@ private static bool IsInForeachParallelCallingScope( } } */ - Diagnostics.Assert(usingAst != null, "usingAst argument cannot be null."); // Search up the parent Ast chain for 'Foreach-Object -Parallel' commands. Ast currentParent = usingAst.Parent; - int foreachNestedCount = 0; - while (currentParent != null) + while (currentParent != scriptblockAst) { // Look for Foreach-Object outer commands - if (currentParent is CommandAst commandAst) - { - foreach (var commandElement in commandAst.CommandElements) - { - if (commandElement is StringConstantExpressionAst commandName) - { - bool found = false; - foreach (var foreachName in foreachNames) - { - if (commandName.Value.Equals(foreachName, StringComparison.OrdinalIgnoreCase)) - { - found = true; - break; - } - } - - if (found) - { - // Verify this is foreach-object with parallel parameter set. - var bindingResult = StaticParameterBinder.BindCommand(commandAst); - if (bindingResult.BoundParameters.ContainsKey("Parallel")) - { - foreachNestedCount++; - break; - } - } - } - } - } - - if (foreachNestedCount > 1) + if (currentParent is CommandAst commandAst && + FindForEachInCommand(commandAst)) { - // This using expression Ast is outside the original calling scope. + // Using Ast is outside the invoking foreach scope. return false; } currentParent = currentParent.Parent; } - return foreachNestedCount == 1; + return true; } /// @@ -534,7 +542,7 @@ private static Tuple, object[]> GetUsingValues( if (variables != null) { - if (!(usingAst.SubExpression is VariableExpressionAst variableAst)) + if (usingAst.SubExpression is not VariableExpressionAst variableAst) { throw InterpreterError.NewInterpreterException(null, typeof(RuntimeException), usingAst.Extent, "CantGetUsingExpressionValueWithSpecifiedVariableDictionary", AutomationExceptions.CantGetUsingExpressionValueWithSpecifiedVariableDictionary, usingAst.Extent.Text); @@ -938,7 +946,7 @@ private void AddParameter(CommandParameterAst commandParameterAst, bool isTruste // first character in parameter name must be a dash _powershell.AddParameter( - string.Format(CultureInfo.InvariantCulture, "-{0}{1}", commandParameterAst.ParameterName, nameSuffix), + string.Create(CultureInfo.InvariantCulture, $"-{commandParameterAst.ParameterName}{nameSuffix}"), argument); } } diff --git a/src/System.Management.Automation/engine/serialization.cs b/src/System.Management.Automation/engine/serialization.cs index b4115de05cb..add0eab25dc 100644 --- a/src/System.Management.Automation/engine/serialization.cs +++ b/src/System.Management.Automation/engine/serialization.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Collections.Specialized; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; @@ -82,10 +83,8 @@ internal SerializationContext(int depth, SerializationOptions options, PSRemotin /// /// This class provides public functionality for serializing a PSObject. /// - public class PSSerializer + public static class PSSerializer { - internal PSSerializer() { } - /// /// Serializes an object into PowerShell CliXml. /// @@ -123,6 +122,45 @@ public static string Serialize(object source, int depth) return sb.ToString(); } + /// + /// Serializes list of objects into PowerShell CliXml. + /// + /// The input objects to serialize. + /// The depth of the members to serialize. + /// Enumerates input objects and serializes one at a time. + /// The serialized object, as CliXml. + internal static string Serialize(IList source, int depth, bool enumerate) + { + StringBuilder sb = new(); + + XmlWriterSettings xmlSettings = new() + { + CloseOutput = true, + Encoding = Encoding.Unicode, + Indent = true, + OmitXmlDeclaration = true + }; + + XmlWriter xw = XmlWriter.Create(sb, xmlSettings); + Serializer serializer = new(xw, depth, useDepthFromTypes: true); + + if (enumerate) + { + foreach (object item in source) + { + serializer.Serialize(item); + } + } + else + { + serializer.Serialize(source); + } + + serializer.Done(); + + return sb.ToString(); + } + /// /// Deserializes PowerShell CliXml into an object. /// @@ -734,7 +772,7 @@ internal static string MaskDeserializationPrefix(string typeName) /// /// Gets a new collection of typenames without "Deserialization." prefix - /// in the typename. This will allow to map type info/format info of the orignal type + /// in the typename. This will allow to map type info/format info of the original type /// for deserialized objects. /// /// @@ -1610,8 +1648,8 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c // ATTACH INSTANCE METADATA TO THE OBJECT BEING SERIALIZED List namesOfModifiedProperties = cimInstance .CimInstanceProperties - .Where(p => p.IsValueModified) - .Select(p => p.Name) + .Where(static p => p.IsValueModified) + .Select(static p => p.Name) .ToList(); if (namesOfModifiedProperties.Count != 0) { @@ -1633,7 +1671,7 @@ private void PrepareCimInstanceForSerialization(PSObject psObject, CimInstance c instanceMetadata.Properties.Add( new PSNoteProperty( InternalDeserializer.CimModifiedProperties, - string.Join(" ", namesOfModifiedProperties))); + string.Join(' ', namesOfModifiedProperties))); } } @@ -1980,7 +2018,7 @@ int depth foreach (PSMemberInfo info in propertyCollection) { - if (!(info is PSProperty prop)) + if (info is not PSProperty prop) { continue; } @@ -2160,7 +2198,10 @@ int depth } Dbg.Assert(key != null, "Dictionary keys should never be null"); - if (key == null) break; + if (key == null) + { + break; + } WriteStartElement(SerializationStrings.DictionaryEntryTag); WriteOneObject(key, null, SerializationStrings.DictionaryKey, depth); @@ -3332,28 +3373,28 @@ private CimClass RehydrateCimClass(PSPropertyInfo classMetadataProperty) PSObject psoDeserializedClass = PSObject.AsPSObject(deserializedClass); - if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] is PSPropertyInfo namespaceProperty)) + if (psoDeserializedClass.InstanceMembers[InternalDeserializer.CimNamespaceProperty] is not PSPropertyInfo namespaceProperty) { return null; } string cimNamespace = namespaceProperty.Value as string; - if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] is PSPropertyInfo classNameProperty)) + if (psoDeserializedClass.InstanceMembers[InternalDeserializer.CimClassNameProperty] is not PSPropertyInfo classNameProperty) { return null; } string cimClassName = classNameProperty.Value as string; - if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] is PSPropertyInfo computerNameProperty)) + if (psoDeserializedClass.InstanceMembers[InternalDeserializer.CimServerNameProperty] is not PSPropertyInfo computerNameProperty) { return null; } string computerName = computerNameProperty.Value as string; - if (!(psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] is PSPropertyInfo hashCodeProperty)) + if (psoDeserializedClass.InstanceMembers[InternalDeserializer.CimHashCodeProperty] is not PSPropertyInfo hashCodeProperty) { return null; } @@ -3458,7 +3499,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) if ((modifiedPropertiesProperty != null) && (modifiedPropertiesProperty.Value != null)) { string modifiedPropertiesString = modifiedPropertiesProperty.Value.ToString(); - foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(Utils.Separators.Space)) + foreach (string nameOfModifiedProperty in modifiedPropertiesString.Split(' ')) { namesOfModifiedProperties.Add(nameOfModifiedProperty); } @@ -3470,7 +3511,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) { foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.AdaptedMembers) { - if (!(deserializedMemberInfo is PSPropertyInfo deserializedProperty)) + if (deserializedMemberInfo is not PSPropertyInfo deserializedProperty) { continue; } @@ -3490,7 +3531,7 @@ private PSObject RehydrateCimInstance(PSObject deserializedObject) // process properties that were originally "extended" properties foreach (PSMemberInfo deserializedMemberInfo in deserializedObject.InstanceMembers) { - if (!(deserializedMemberInfo is PSPropertyInfo deserializedProperty)) + if (deserializedMemberInfo is not PSPropertyInfo deserializedProperty) { continue; } @@ -3670,7 +3711,7 @@ private PSObject ReadPSObject() else if (IsKnownContainerTag(out ct)) { s_trace.WriteLine("Found container node {0}", ct); - baseObject = ReadKnownContainer(ct); + baseObject = ReadKnownContainer(ct, dso.InternalTypeNames); } else if (IsNextElement(SerializationStrings.PSObjectTag)) { @@ -3934,12 +3975,12 @@ private bool IsKnownContainerTag(out ContainerType ct) return ct != ContainerType.None; } - private object ReadKnownContainer(ContainerType ct) + private object ReadKnownContainer(ContainerType ct, ConsolidatedString InternalTypeNames) { switch (ct) { case ContainerType.Dictionary: - return ReadDictionary(ct); + return ReadDictionary(ct, InternalTypeNames); case ContainerType.Enumerable: case ContainerType.List: @@ -3988,19 +4029,81 @@ private object ReadListContainer(ContainerType ct) return list; } + /// + /// Utility class for ReadDictionary(), supporting ordered or non-ordered Dictionary methods. + /// + private class PSDictionary + { + private IDictionary dict; + private readonly bool _isOrdered; + private int _keyClashFoundIteration = 0; + + public PSDictionary(bool isOrdered) { + _isOrdered = isOrdered; + + // By default use a non case-sensitive comparer + if (_isOrdered) { + dict = new OrderedDictionary(StringComparer.CurrentCultureIgnoreCase); + } else { + dict = new Hashtable(StringComparer.CurrentCultureIgnoreCase); + } + } + + public object DictionaryObject { get { return dict; } } + + public void Add(object key, object value) { + // On the first collision, copy the hash table to one that uses the `key` object's default comparer. + if (_keyClashFoundIteration == 0 && dict.Contains(key)) + { + _keyClashFoundIteration++; + IDictionary newDict = _isOrdered ? new OrderedDictionary(dict.Count) : new Hashtable(dict.Count); + + foreach (DictionaryEntry entry in dict) { + newDict.Add(entry.Key, entry.Value); + } + + dict = newDict; + } + + // win8: 389060. If there are still collisions even with case-sensitive default comparer, + // use an IEqualityComparer that does object ref equality. + if (_keyClashFoundIteration == 1 && dict.Contains(key)) + { + _keyClashFoundIteration++; + IEqualityComparer equalityComparer = new ReferenceEqualityComparer(); + IDictionary newDict = _isOrdered ? + new OrderedDictionary(dict.Count, equalityComparer) : + new Hashtable(dict.Count, equalityComparer); + + foreach (DictionaryEntry entry in dict) { + newDict.Add(entry.Key, entry.Value); + } + + dict = newDict; + } + + dict.Add(key, value); + } + } + /// /// Deserialize Dictionary. /// /// - private object ReadDictionary(ContainerType ct) + private object ReadDictionary(ContainerType ct, ConsolidatedString InternalTypeNames) { Dbg.Assert(ct == ContainerType.Dictionary, "Unrecognized ContainerType enum"); // We assume the hash table is a PowerShell hash table and hence uses // a case insensitive string comparer. If we discover a key collision, // we'll revert back to the default comparer. - Hashtable table = new Hashtable(StringComparer.CurrentCultureIgnoreCase); - int keyClashFoundIteration = 0; + + // Find whether original directory was ordered + bool isOrdered = InternalTypeNames.Count > 0 && + (Deserializer.MaskDeserializationPrefix(InternalTypeNames[0]) == typeof(OrderedDictionary).FullName); + + PSDictionary dictionary = new PSDictionary(isOrdered); + if (ReadStartElementAndHandleEmpty(SerializationStrings.DictionaryTag)) { while (_reader.NodeType == XmlNodeType.Element) @@ -4039,38 +4142,10 @@ private object ReadDictionary(ContainerType ct) object value = ReadOneObject(); - // On the first collision, copy the hash table to one that uses the default comparer. - if (table.ContainsKey(key) && (keyClashFoundIteration == 0)) - { - keyClashFoundIteration++; - Hashtable newHashTable = new Hashtable(); - foreach (DictionaryEntry entry in table) - { - newHashTable.Add(entry.Key, entry.Value); - } - - table = newHashTable; - } - - // win8: 389060. If there are still collisions even with case-sensitive default comparer, - // use an IEqualityComparer that does object ref equality. - if (table.ContainsKey(key) && (keyClashFoundIteration == 1)) - { - keyClashFoundIteration++; - IEqualityComparer equalityComparer = new ReferenceEqualityComparer(); - Hashtable newHashTable = new Hashtable(equalityComparer); - foreach (DictionaryEntry entry in table) - { - newHashTable.Add(entry.Key, entry.Value); - } - - table = newHashTable; - } - try { // Add entry to hashtable - table.Add(key, value); + dictionary.Add(key, value); } catch (ArgumentException e) { @@ -4083,7 +4158,7 @@ private object ReadDictionary(ContainerType ct) ReadEndElement(); } - return table; + return dictionary.DictionaryObject; } #endregion known containers @@ -4916,7 +4991,7 @@ private static string DecodeString(string s) #endregion misc - [TraceSourceAttribute("InternalDeserializer", "InternalDeserializer class")] + [TraceSource("InternalDeserializer", "InternalDeserializer class")] private static readonly PSTraceSource s_trace = PSTraceSource.GetTracer("InternalDeserializer", "InternalDeserializer class"); } @@ -5086,7 +5161,7 @@ internal TypeSerializationInfo(Type type, string itemTag, string propertyTag, Ty /// /// A class for identifying types which are treated as KnownType by Monad. - /// A KnownType is guranteed to be available on machine on which monad is + /// A KnownType is guaranteed to be available on machine on which monad is /// running. /// internal static class KnownTypes @@ -5639,7 +5714,7 @@ internal static object GetPropertyValueInThreadSafeManner(PSPropertyInfo propert /// type of dictionary values internal class WeakReferenceDictionary : IDictionary { - private class WeakReferenceEqualityComparer : IEqualityComparer + private sealed class WeakReferenceEqualityComparer : IEqualityComparer { public bool Equals(WeakReference x, WeakReference y) { @@ -5874,7 +5949,6 @@ IEnumerator IEnumerable.GetEnumerator() /// 2) values that can be serialized and deserialized during PowerShell remoting handshake /// (in major-version compatible versions of PowerShell remoting) /// - [Serializable] public sealed class PSPrimitiveDictionary : Hashtable { #region Constructors @@ -5900,10 +5974,7 @@ public PSPrimitiveDictionary() public PSPrimitiveDictionary(Hashtable other) : base(StringComparer.OrdinalIgnoreCase) { - if (other == null) - { - throw new ArgumentNullException(nameof(other)); - } + ArgumentNullException.ThrowIfNull(other); foreach (DictionaryEntry entry in other) { @@ -5975,7 +6046,7 @@ private static string VerifyKey(object key) typeof(PSPrimitiveDictionary) }; - private void VerifyValue(object value) + private static void VerifyValue(object value) { // null is a primitive type if (value == null) @@ -6033,7 +6104,7 @@ private void VerifyValue(object value) public override void Add(object key, object value) { string keyAsString = VerifyKey(key); - this.VerifyValue(value); + VerifyValue(value); base.Add(keyAsString, value); } @@ -6061,7 +6132,7 @@ public override object this[object key] set { string keyAsString = VerifyKey(key); - this.VerifyValue(value); + VerifyValue(value); base[keyAsString] = value; } } @@ -6089,7 +6160,7 @@ public object this[string key] set { - this.VerifyValue(value); + VerifyValue(value); base[key] = value; } } @@ -6493,7 +6564,7 @@ public void Add(string key, PSPrimitiveDictionary[] value) /// /// If originalHash contains PSVersionTable, then just returns the Cloned copy of - /// the original hash. Othewise, creates a clone copy and add PSVersionInfo.GetPSVersionTable + /// the original hash. Otherwise, creates a clone copy and add PSVersionInfo.GetPSVersionTable /// to the clone and returns. /// /// @@ -6595,7 +6666,6 @@ namespace Microsoft.PowerShell /// - PropertySerializationSet= /// - TargetTypeForDeserialization=DeserializingTypeConverter /// - Add a field of that type in unit tests / S.M.A.Test.SerializationTest+RehydratedType - /// (testsrc\admintest\monad\DRT\engine\UnitTests\SerializationTest.cs) /// --> public sealed class DeserializingTypeConverter : PSTypeConverter { @@ -7214,7 +7284,6 @@ internal static PSSenderInfo RehydratePSSenderInfo(PSObject pso) PSSenderInfo senderInfo = new PSSenderInfo(psPrincipal, GetPropertyValue(pso, "ConnectionString")); - senderInfo.ClientTimeZone = TimeZoneInfo.Local; senderInfo.ApplicationArguments = GetPropertyValue(pso, "ApplicationArguments"); return senderInfo; @@ -7223,7 +7292,9 @@ internal static PSSenderInfo RehydratePSSenderInfo(PSObject pso) private static System.Security.Cryptography.X509Certificates.X509Certificate2 RehydrateX509Certificate2(PSObject pso) { byte[] rawData = GetPropertyValue(pso, "RawData"); + #pragma warning disable SYSLIB0057 return new System.Security.Cryptography.X509Certificates.X509Certificate2(rawData); + #pragma warning restore SYSLIB0057 } private static System.Security.Cryptography.X509Certificates.X500DistinguishedName RehydrateX500DistinguishedName(PSObject pso) @@ -7274,7 +7345,7 @@ public static UInt32 GetParameterSetMetadataFlags(PSObject instance) throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (!(instance.BaseObject is ParameterSetMetadata parameterSetMetadata)) + if (instance.BaseObject is not ParameterSetMetadata parameterSetMetadata) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -7295,7 +7366,7 @@ public static PSObject GetInvocationInfo(PSObject instance) throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (!(instance.BaseObject is DebuggerStopEventArgs dbgStopEventArgs)) + if (instance.BaseObject is not DebuggerStopEventArgs dbgStopEventArgs) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } @@ -7554,7 +7625,7 @@ public static Guid GetFormatViewDefinitionInstanceId(PSObject instance) throw PSTraceSource.NewArgumentNullException(nameof(instance)); } - if (!(instance.BaseObject is FormatViewDefinition formatViewDefinition)) + if (instance.BaseObject is not FormatViewDefinition formatViewDefinition) { throw PSTraceSource.NewArgumentNullException(nameof(instance)); } diff --git a/src/System.Management.Automation/help/AliasHelpInfo.cs b/src/System.Management.Automation/help/AliasHelpInfo.cs index 57cb7fdd184..5d02e754397 100644 --- a/src/System.Management.Automation/help/AliasHelpInfo.cs +++ b/src/System.Management.Automation/help/AliasHelpInfo.cs @@ -8,7 +8,7 @@ namespace System.Management.Automation /// /// Stores help information related to Alias Commands. /// - internal class AliasHelpInfo : HelpInfo + internal sealed class AliasHelpInfo : HelpInfo { /// /// Initializes a new instance of the AliasHelpInfo class. @@ -40,8 +40,7 @@ private AliasHelpInfo(AliasInfo aliasInfo) } _fullHelpObject.TypeNames.Clear(); - _fullHelpObject.TypeNames.Add(string.Format(Globalization.CultureInfo.InvariantCulture, - "AliasHelpInfo#{0}", Name)); + _fullHelpObject.TypeNames.Add(string.Create(Globalization.CultureInfo.InvariantCulture, $"AliasHelpInfo#{Name}")); _fullHelpObject.TypeNames.Add("AliasHelpInfo"); _fullHelpObject.TypeNames.Add("HelpInfo"); } diff --git a/src/System.Management.Automation/help/AliasHelpProvider.cs b/src/System.Management.Automation/help/AliasHelpProvider.cs index f14f815891a..d93aa76b2f3 100644 --- a/src/System.Management.Automation/help/AliasHelpProvider.cs +++ b/src/System.Management.Automation/help/AliasHelpProvider.cs @@ -161,7 +161,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest)) { // Component/Role/Functionality match is done only for SearchHelp - // as "get-help * -category alias" should not forwad help to + // as "get-help * -category alias" should not forward help to // CommandHelpProvider..(ExactMatchHelp does forward help to // CommandHelpProvider) if (!Match(helpInfo, helpRequest)) @@ -208,7 +208,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest)) { // Component/Role/Functionality match is done only for SearchHelp - // as "get-help * -category alias" should not forwad help to + // as "get-help * -category alias" should not forward help to // CommandHelpProvider..(ExactMatchHelp does forward help to // CommandHelpProvider) if (!Match(helpInfo, helpRequest)) diff --git a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs index 0c70b815928..c24e45ee788 100644 --- a/src/System.Management.Automation/help/BaseCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/BaseCommandHelpInfo.cs @@ -214,8 +214,7 @@ internal Uri LookupUriFromCommandInfo() string commandToSearch = commandName; if (!string.IsNullOrEmpty(moduleName)) { - commandToSearch = string.Format(CultureInfo.InvariantCulture, - "{0}\\{1}", moduleName, commandName); + commandToSearch = string.Create(CultureInfo.InvariantCulture, $"{moduleName}\\{commandName}"); } ExecutionContext context = LocalPipeline.GetExecutionContextFromTLS(); @@ -252,7 +251,7 @@ internal Uri LookupUriFromCommandInfo() // Split the string based on (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. - string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); + string[] tempUriSplitArray = uriString.Split(' '); uriString = tempUriSplitArray[0]; } @@ -319,7 +318,7 @@ internal static Uri GetUriFromCommandPSObject(PSObject commandFullHelp) // Split the string based on (space). We decided to go with this approach as // UX localization authors use spaces. Correctly extracting only the wellformed URI // is out-of-scope for this fix. - string[] tempUriSplitArray = uriString.Split(Utils.Separators.Space); + string[] tempUriSplitArray = uriString.Split(' '); uriString = tempUriSplitArray[0]; } @@ -356,15 +355,9 @@ internal override bool MatchPatternInContent(WildcardPattern pattern) string synopsis = Synopsis; string detailedDescription = DetailedDescription; - if (synopsis == null) - { - synopsis = string.Empty; - } + synopsis ??= string.Empty; - if (detailedDescription == null) - { - detailedDescription = string.Empty; - } + detailedDescription ??= string.Empty; return pattern.IsMatch(synopsis) || pattern.IsMatch(detailedDescription); } @@ -462,7 +455,7 @@ internal string DetailedDescription return string.Empty; } - // I think every cmdlet description should atleast have 400 characters... + // I think every cmdlet description should at least have 400 characters... // so starting with this assumption..I did an average of all the cmdlet // help content available at the time of writing this code and came up // with this number. diff --git a/src/System.Management.Automation/help/CabinetNativeApi.cs b/src/System.Management.Automation/help/CabinetNativeApi.cs index 76e8fe853a4..fd369ca03be 100644 --- a/src/System.Management.Automation/help/CabinetNativeApi.cs +++ b/src/System.Management.Automation/help/CabinetNativeApi.cs @@ -70,10 +70,7 @@ protected override void Dispose(bool disposing) } // Free managed objects within 'if (disposing)' if needed - if (fdiContext != null) - { - fdiContext.Dispose(); - } + fdiContext?.Dispose(); // Free unmanaged objects here this.CleanUpDelegates(); @@ -546,7 +543,7 @@ internal static FileShare ConvertPermissionModeToFileShare(int pmode) #region IO classes, structures, and enums - [FlagsAttribute] + [Flags] internal enum PermissionMode : int { None = 0x0000, @@ -554,7 +551,7 @@ internal enum PermissionMode : int Read = 0x0100 } - [FlagsAttribute] + [Flags] internal enum OpFlags : int { RdOnly = 0x0000, diff --git a/src/System.Management.Automation/help/CommandHelpProvider.cs b/src/System.Management.Automation/help/CommandHelpProvider.cs index d5863f31819..15af80745db 100644 --- a/src/System.Management.Automation/help/CommandHelpProvider.cs +++ b/src/System.Management.Automation/help/CommandHelpProvider.cs @@ -879,7 +879,7 @@ private HelpInfo GetFromCommandCacheOrCmdletInfo(CmdletInfo cmdletInfo) /// /// Used to retrieve helpinfo by removing the prefix from the noun portion of a command name. /// Import-Module and Import-PSSession supports changing the name of a command - /// by suppling a custom prefix. In those cases, the help content is stored by using the + /// by supplying a custom prefix. In those cases, the help content is stored by using the /// original command name (without prefix) as the key. /// /// This method retrieves the help content by suppressing the prefix and then making a copy @@ -950,15 +950,21 @@ private void AddToCommandCache(string mshSnapInId, string cmdletName, MamlComman // Add snapin qualified type name for this command at the top.. // this will enable customizations of the help object. - helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, - "MamlCommandHelpInfo#{0}#{1}", mshSnapInId, cmdletName)); + helpInfo.FullHelp.TypeNames.Insert( + index: 0, + string.Create( + CultureInfo.InvariantCulture, + $"MamlCommandHelpInfo#{mshSnapInId}#{cmdletName}")); if (!string.IsNullOrEmpty(mshSnapInId)) { key = mshSnapInId + "\\" + key; // Add snapin name to the typenames of this object - helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, - "MamlCommandHelpInfo#{0}", mshSnapInId)); + helpInfo.FullHelp.TypeNames.Insert( + index: 1, + string.Create( + CultureInfo.InvariantCulture, + $"MamlCommandHelpInfo#{mshSnapInId}")); } AddCache(key, helpInfo); @@ -1075,10 +1081,7 @@ internal override IEnumerable SearchHelp(HelpRequest helpRequest, bool { // this command is not visible to the user (from CommandOrigin) so // dont show help topic for it. - if (!hiddenCommands.Contains(helpName)) - { - hiddenCommands.Add(helpName); - } + hiddenCommands.Add(helpName); continue; } @@ -1275,7 +1278,7 @@ internal override IEnumerable ProcessForwardedHelp(HelpInfo helpInfo, } catch (CommandNotFoundException) { - // ignore errors for aliases pointing to non-existant commands + // ignore errors for aliases pointing to non-existent commands } } @@ -1359,7 +1362,7 @@ internal virtual CommandSearcher GetCommandSearcherForSearch(string pattern, Exe /// Legally, user-defined Help Data should be within the same file as the corresponding /// commandHelp and it should appear after the commandHelp. /// - internal class UserDefinedHelpData + internal sealed class UserDefinedHelpData { private UserDefinedHelpData() { diff --git a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs index 34b1bd84cef..bce76b005a2 100644 --- a/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs +++ b/src/System.Management.Automation/help/DefaultCommandHelpObjectBuilder.cs @@ -57,8 +57,8 @@ internal static PSObject GetPSObjectFromCmdletInfo(CommandInfo input) PSObject obj = new PSObject(); obj.TypeNames.Clear(); - obj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#{1}#command", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName)); - obj.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#{1}", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp, commandInfo.ModuleName)); + obj.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp}#{commandInfo.ModuleName}#command")); + obj.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp}#{commandInfo.ModuleName}")); obj.TypeNames.Add(DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp); obj.TypeNames.Add("CmdletHelpInfo"); obj.TypeNames.Add("HelpInfo"); @@ -160,7 +160,7 @@ internal static void AddDetailsProperties(PSObject obj, string name, string noun PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#details", typeNameForHelp)); + mshObject.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{typeNameForHelp}#details")); mshObject.Properties.Add(new PSNoteProperty("name", name)); mshObject.Properties.Add(new PSNoteProperty("noun", noun)); @@ -192,7 +192,7 @@ internal static void AddSyntaxProperties(PSObject obj, string cmdletName, ReadOn PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#syntax", typeNameForHelp)); + mshObject.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{typeNameForHelp}#syntax")); AddSyntaxItemProperties(mshObject, cmdletName, parameterSets, common, typeNameForHelp); @@ -216,7 +216,7 @@ private static void AddSyntaxItemProperties(PSObject obj, string cmdletName, Rea PSObject mshObject = new PSObject(); mshObject.TypeNames.Clear(); - mshObject.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#syntaxItem", typeNameForHelp)); + mshObject.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{typeNameForHelp}#syntaxItem")); mshObject.Properties.Add(new PSNoteProperty("name", cmdletName)); mshObject.Properties.Add(new PSNoteProperty("CommonParameters", common)); @@ -263,7 +263,7 @@ private static void AddSyntaxParametersProperties(PSObject obj, IEnumerable attributes = new Collection(parameter.Attributes); @@ -339,7 +339,7 @@ private static void AddParameterValueGroupProperties(PSObject obj, string[] valu PSObject paramValueGroup = new PSObject(); paramValueGroup.TypeNames.Clear(); - paramValueGroup.TypeNames.Add(string.Format(CultureInfo.InvariantCulture, "{0}#parameterValueGroup", DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp)); + paramValueGroup.TypeNames.Add(string.Create(CultureInfo.InvariantCulture, $"{DefaultCommandHelpObjectBuilder.TypeNameForDefaultHelp}#parameterValueGroup")); ArrayList paramValue = new ArrayList(values); @@ -359,7 +359,7 @@ internal static void AddParametersProperties(PSObject obj, Dictionary GetHelpInfo(DscResourceSearcher searcher) } else if (!string.IsNullOrEmpty(moduleDir)) { - string[] splitPath = moduleDir.Split(Utils.Separators.Backslash); + string[] splitPath = moduleDir.Split('\\'); moduleName = splitPath[splitPath.Length - 1]; } @@ -279,7 +279,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier, string com } if (e != null) - s_tracer.WriteLine("Error occured in DscResourceHelpProvider {0}", e.Message); + s_tracer.WriteLine("Error occurred in DscResourceHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { diff --git a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs index d9ccee7bae6..8ab4fa37ca6 100644 --- a/src/System.Management.Automation/help/HelpCategoryInvalidException.cs +++ b/src/System.Management.Automation/help/HelpCategoryInvalidException.cs @@ -16,7 +16,6 @@ namespace Microsoft.PowerShell.Commands /// The exception that is thrown when there is no help category matching /// a specific input string. /// - [Serializable] public class HelpCategoryInvalidException : ArgumentException, IContainsErrorRecord { /// @@ -113,30 +112,11 @@ public override string Message /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HelpCategoryInvalidException(SerializationInfo info, - StreamingContext context) - : base(info, context) + StreamingContext context) { - _helpCategory = info.GetString("HelpCategory"); - CreateErrorRecord(); - } - - /// - /// Populates a with the - /// data needed to serialize the HelpCategoryInvalidException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("HelpCategory", this._helpCategory); + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/help/HelpCommands.cs b/src/System.Management.Automation/help/HelpCommands.cs index edf8d9e4355..3bed2a26820 100644 --- a/src/System.Management.Automation/help/HelpCommands.cs +++ b/src/System.Management.Automation/help/HelpCommands.cs @@ -231,8 +231,8 @@ public SwitchParameter ShowWindow // The following variable controls the view. private HelpView _viewTokenToAdd = HelpView.Default; - private readonly Stopwatch _timer = new Stopwatch(); #if LEGACYTELEMETRY + private readonly Stopwatch _timer = new Stopwatch(); private bool _updatedHelp; #endif @@ -245,7 +245,9 @@ public SwitchParameter ShowWindow /// protected override void BeginProcessing() { +#if LEGACYTELEMETRY _timer.Start(); +#endif } /// @@ -253,6 +255,17 @@ protected override void BeginProcessing() /// protected override void ProcessRecord() { +#if !UNIX + string fileSystemPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(this.Name); + string normalizedName = FileSystemProvider.NormalizePath(fileSystemPath); + // In a restricted session, do not allow help on network paths or device paths, because device paths can be used to bypass the restrictions. + if (Utils.IsSessionRestricted(this.Context) && (FileSystemProvider.PathIsNetworkPath(normalizedName) || Utils.PathIsDevicePath(normalizedName))) { + Exception e = new ArgumentException(HelpErrors.NoNetworkCommands, "Name"); + ErrorRecord errorRecord = new ErrorRecord(e, "CommandNameNotAllowed", ErrorCategory.InvalidArgument, null); + this.ThrowTerminatingError(errorRecord); + } +#endif + HelpSystem helpSystem = this.Context.HelpSystem; try { @@ -321,9 +334,9 @@ protected override void ProcessRecord() countOfHelpInfos++; } +#if LEGACYTELEMETRY _timer.Stop(); -#if LEGACYTELEMETRY if (!string.IsNullOrEmpty(Name)) Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.ReportGetHelpTelemetry(Name, countOfHelpInfos, _timer.ElapsedMilliseconds, _updatedHelp); #endif @@ -422,7 +435,7 @@ private PSObject TransformView(PSObject originalHelpObject) if (originalHelpObject.TypeNames.Count == 0) { - string typeToAdd = string.Format(CultureInfo.InvariantCulture, "HelpInfo#{0}", tokenToAdd); + string typeToAdd = string.Create(CultureInfo.InvariantCulture, $"HelpInfo#{tokenToAdd}"); objectToReturn.TypeNames.Add(typeToAdd); } else @@ -438,7 +451,7 @@ private PSObject TransformView(PSObject originalHelpObject) continue; } - string typeToAdd = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", typeName, tokenToAdd); + string typeToAdd = string.Create(CultureInfo.InvariantCulture, $"{typeName}#{tokenToAdd}"); s_tracer.WriteLine("Adding type {0}", typeToAdd); objectToReturn.TypeNames.Add(typeToAdd); } @@ -502,11 +515,11 @@ private void GetAndWriteParameterInfo(HelpInfo helpInfo) } /// - /// Validates input parameters. + /// Validates input parameters. /// /// Category specified by the user. /// - /// If the request cant be serviced. + /// If the request can't be serviced. /// private void ValidateAndThrowIfError(HelpCategory cat) { @@ -721,10 +734,8 @@ internal static void VerifyParameterForbiddenInRemoteRunspace(Cmdlet cmdlet, str #endregion #region trace - - [TraceSourceAttribute("GetHelpCommand ", "GetHelpCommand ")] - private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("GetHelpCommand ", "GetHelpCommand "); - + [TraceSource("GetHelpCommand", "GetHelpCommand")] + private static readonly PSTraceSource s_tracer = PSTraceSource.GetTracer("GetHelpCommand", "GetHelpCommand"); #endregion } @@ -735,8 +746,8 @@ public static class GetHelpCodeMethods { /// /// Checks whether the default runspace associated with the current thread has the standard Get-Help cmdlet. - /// - /// True if Get-Help is found, false otherwise. + /// + /// True if Get-Help is found, false otherwise. private static bool DoesCurrentRunspaceIncludeCoreHelpCmdlet() { InitialSessionState iss = Runspace.DefaultRunspace.InitialSessionState; @@ -819,8 +830,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) string cmdName = cmdInfo.Name; if (!string.IsNullOrEmpty(cmdInfo.ModuleName)) { - cmdName = string.Format(CultureInfo.InvariantCulture, - "{0}\\{1}", cmdInfo.ModuleName, cmdInfo.Name); + cmdName = string.Create(CultureInfo.InvariantCulture, $"{cmdInfo.ModuleName}\\{cmdInfo.Name}"); } if (DoesCurrentRunspaceIncludeCoreHelpCmdlet()) @@ -839,7 +849,7 @@ public static string GetHelpUri(PSObject commandInfoPSObject) foreach ( Uri result in currentContext.HelpSystem.ExactMatchHelp(helpRequest).Select( - helpInfo => helpInfo.GetUriForOnlineHelp()).Where(result => result != null)) + helpInfo => helpInfo.GetUriForOnlineHelp()).Where(static result => result != null)) { return result.OriginalString; } diff --git a/src/System.Management.Automation/help/HelpCommentsParser.cs b/src/System.Management.Automation/help/HelpCommentsParser.cs index 7b853381d4d..b4a21e04d69 100644 --- a/src/System.Management.Automation/help/HelpCommentsParser.cs +++ b/src/System.Management.Automation/help/HelpCommentsParser.cs @@ -20,7 +20,7 @@ namespace System.Management.Automation /// /// Parses help comments and turns them into HelpInfo objects. /// - internal class HelpCommentsParser + internal sealed class HelpCommentsParser { private HelpCommentsParser() { @@ -482,7 +482,7 @@ private void BuildSyntaxForParameterSet(XmlElement command, XmlElement syntax, M CompiledCommandParameter parameter = mergedParameter.Parameter; ParameterSetSpecificMetadata parameterSetData = parameter.GetParameterSetData(1u << i); string description = GetParameterDescription(parameter.Name); - bool supportsWildcards = parameter.CompiledAttributes.Any(attribute => attribute is SupportsWildcardsAttribute); + bool supportsWildcards = parameter.CompiledAttributes.Any(static attribute => attribute is SupportsWildcardsAttribute); XmlElement parameterElement = BuildXmlForParameter(parameter.Name, parameterSetData.IsMandatory, parameterSetData.ValueFromPipeline, parameterSetData.ValueFromPipelineByPropertyName, @@ -628,7 +628,7 @@ private static string GetSection(List commentLines, ref int i) start++; } - sb.Append(line.Substring(start)); + sb.Append(line.AsSpan(start)); sb.Append('\n'); } @@ -951,7 +951,7 @@ internal static bool IsCommentHelpText(List commentBlock) var result = new List(); // Any whitespace between the token and the first comment is allowed. - int nextMaxStartLine = Int32.MaxValue; + int nextMaxStartLine = int.MaxValue; for (int i = startIndex; i < tokens.Length; i++) { diff --git a/src/System.Management.Automation/help/HelpFileHelpInfo.cs b/src/System.Management.Automation/help/HelpFileHelpInfo.cs index adb2afac47f..104111777ef 100644 --- a/src/System.Management.Automation/help/HelpFileHelpInfo.cs +++ b/src/System.Management.Automation/help/HelpFileHelpInfo.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation /// Class HelpFileHelpInfo keeps track of help information to be returned by /// command help provider. /// - internal class HelpFileHelpInfo : HelpInfo + internal sealed class HelpFileHelpInfo : HelpInfo { /// /// Constructor for HelpFileHelpInfo. diff --git a/src/System.Management.Automation/help/HelpFileHelpProvider.cs b/src/System.Management.Automation/help/HelpFileHelpProvider.cs index 8900a7167b3..a6c21a3bacc 100644 --- a/src/System.Management.Automation/help/HelpFileHelpProvider.cs +++ b/src/System.Management.Automation/help/HelpFileHelpProvider.cs @@ -170,11 +170,7 @@ private Collection FilterToLatestModuleVersion(Collection filesM { string fileName = Path.GetFileName(file); - if (!fileNameHash.Contains(fileName)) - { - fileNameHash.Add(fileName); - } - else + if (!fileNameHash.Add(fileName)) { // If the file need to be removed, add it to matchedFilesToRemove, if not already present. if (!matchedFilesToRemove.Contains(file)) @@ -275,9 +271,8 @@ private static void GetModuleNameAndVersion(string psmodulePathRoot, string file if (filePath.StartsWith(psmodulePathRoot, StringComparison.OrdinalIgnoreCase)) { - var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length).TrimStart(Utils.Separators.Directory); + var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length); var pathParts = moduleRootSubPath.Split(Utils.Separators.Directory, StringSplitOptions.RemoveEmptyEntries); - moduleName = pathParts[0]; var potentialVersion = pathParts[1]; Version result; @@ -368,9 +363,9 @@ internal Collection GetExtendedSearchPaths() { // Get all the directories under the module path // * and SearchOption.AllDirectories gets all the version directories. - string[] directories = Directory.GetDirectories(psModulePath, "*", SearchOption.AllDirectories); + IEnumerable directories = Directory.EnumerateDirectories(psModulePath, "*", SearchOption.AllDirectories); - var possibleModuleDirectories = directories.Where(directory => !ModuleUtils.IsPossibleResourceDirectory(directory)); + var possibleModuleDirectories = directories.Where(static directory => !ModuleUtils.IsPossibleResourceDirectory(directory)); foreach (string directory in possibleModuleDirectories) { diff --git a/src/System.Management.Automation/help/HelpNotFoundException.cs b/src/System.Management.Automation/help/HelpNotFoundException.cs index 6008b4afbc1..109cd21dbd9 100644 --- a/src/System.Management.Automation/help/HelpNotFoundException.cs +++ b/src/System.Management.Automation/help/HelpNotFoundException.cs @@ -15,7 +15,6 @@ namespace Microsoft.PowerShell.Commands /// /// The exception that is thrown when there is no help found for a topic. /// - [Serializable] public class HelpNotFoundException : SystemException, IContainsErrorRecord { /// @@ -119,32 +118,13 @@ public override string Message /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HelpNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _helpTopic = info.GetString("HelpTopic"); - CreateErrorRecord(); + throw new NotSupportedException(); } - - /// - /// Populates a with the - /// data needed to serialize the HelpNotFoundException object. - /// - /// The to populate with data. - /// The destination for this serialization. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("HelpTopic", this._helpTopic); - } - + #endregion Serialization } } diff --git a/src/System.Management.Automation/help/HelpProvider.cs b/src/System.Management.Automation/help/HelpProvider.cs index 7e2adbe552f..3280a8d2540 100644 --- a/src/System.Management.Automation/help/HelpProvider.cs +++ b/src/System.Management.Automation/help/HelpProvider.cs @@ -226,8 +226,7 @@ internal string GetDefaultShellSearchPath() string shellID = this.HelpSystem.ExecutionContext.ShellID; // Beginning in PowerShell 6.0.0.12, the $pshome is no longer registry specified, we search the application base instead. // We use executing assemblies location in case registry entry not found - return Utils.GetApplicationBase(shellID) - ?? Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); + return Utils.GetApplicationBase(shellID) ?? Path.GetDirectoryName(Environment.ProcessPath); } /// diff --git a/src/System.Management.Automation/help/HelpSystem.cs b/src/System.Management.Automation/help/HelpSystem.cs index a7c86bd5ebd..8880e022cac 100644 --- a/src/System.Management.Automation/help/HelpSystem.cs +++ b/src/System.Management.Automation/help/HelpSystem.cs @@ -903,12 +903,12 @@ internal enum HelpCategory /// All = 0xFFFFF, - /// + /// /// Default Help. /// DefaultHelp = 0x1000, - /// + /// /// Help for a Configuration. /// Configuration = 0x4000, diff --git a/src/System.Management.Automation/help/HelpUtils.cs b/src/System.Management.Automation/help/HelpUtils.cs index d4f2abe255b..ab4a39f362a 100644 --- a/src/System.Management.Automation/help/HelpUtils.cs +++ b/src/System.Management.Automation/help/HelpUtils.cs @@ -41,7 +41,7 @@ internal static string GetModuleBaseForUserHelp(string moduleBase, string module // In case of other modules, the help is under moduleBase/ or // under moduleBase//. // The code below creates a similar layout for CurrentUser scope. - // If the the scope is AllUsers, then the help goes under moduleBase. + // If the scope is AllUsers, then the help goes under moduleBase. var userHelpPath = GetUserHomeHelpSearchPath(); string moduleBaseParent = Directory.GetParent(moduleBase).Name; diff --git a/src/System.Management.Automation/help/MUIFileSearcher.cs b/src/System.Management.Automation/help/MUIFileSearcher.cs index d6d3313b68d..dd437fa90c0 100644 --- a/src/System.Management.Automation/help/MUIFileSearcher.cs +++ b/src/System.Management.Automation/help/MUIFileSearcher.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation { - internal class MUIFileSearcher + internal sealed class MUIFileSearcher { /// /// Constructor. It is private so that MUIFileSearcher is used only internal for this class. @@ -57,6 +57,14 @@ private MUIFileSearcher(string target, Collection searchPaths) /// internal SearchMode SearchMode { get; } = SearchMode.Unique; + private static readonly System.IO.EnumerationOptions _enumerationOptions = new() + { + IgnoreInaccessible = false, + AttributesToSkip = 0, + MatchType = MatchType.Win32, + MatchCasing = MatchCasing.CaseInsensitive, + }; + private Collection _result = null; /// @@ -113,52 +121,11 @@ private void SearchForFiles() } } - private static string[] GetFiles(string path, string pattern) - { -#if UNIX - // On Linux, file names are case sensitive, so we need to add - // extra logic to select the files that match the given pattern. - var result = new List(); - string[] files = Directory.GetFiles(path); - - var wildcardPattern = WildcardPattern.ContainsWildcardCharacters(pattern) - ? WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase) - : null; - - foreach (string filePath in files) - { - if (filePath.Contains(pattern, StringComparison.OrdinalIgnoreCase)) - { - result.Add(filePath); - break; - } - - if (wildcardPattern != null) - { - string fileName = Path.GetFileName(filePath); - if (wildcardPattern.IsMatch(fileName)) - { - result.Add(filePath); - } - } - } - - return result.ToArray(); -#else - return Directory.GetFiles(path, pattern); -#endif - } - private void AddFiles(string muiDirectory, string directory, string pattern) { if (Directory.Exists(muiDirectory)) { - string[] files = GetFiles(muiDirectory, pattern); - - if (files == null) - return; - - foreach (string file in files) + foreach (string file in Directory.EnumerateFiles(muiDirectory, pattern, _enumerationOptions)) { string path = Path.Combine(muiDirectory, file); diff --git a/src/System.Management.Automation/help/MamlClassHelpInfo.cs b/src/System.Management.Automation/help/MamlClassHelpInfo.cs index 042ab21e703..579d72c87fe 100644 --- a/src/System.Management.Automation/help/MamlClassHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlClassHelpInfo.cs @@ -86,7 +86,7 @@ internal MamlClassHelpInfo Copy() internal MamlClassHelpInfo Copy(HelpCategory newCategoryToUse) { MamlClassHelpInfo result = new MamlClassHelpInfo(_fullHelpObject.Copy(), newCategoryToUse); - result.FullHelp.Properties["Category"].Value = newCategoryToUse; + result.FullHelp.Properties["Category"].Value = newCategoryToUse.ToString(); return result; } diff --git a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs index 774ef1fc1c0..8ae7b0a32cd 100644 --- a/src/System.Management.Automation/help/MamlCommandHelpInfo.cs +++ b/src/System.Management.Automation/help/MamlCommandHelpInfo.cs @@ -315,7 +315,7 @@ internal MamlCommandHelpInfo MergeProviderSpecificHelp(PSObject cmdletHelp, PSOb /// Name of the property for which text needs to be extracted. /// /// - private string ExtractTextForHelpProperty(PSObject psObject, string propertyName) + private static string ExtractTextForHelpProperty(PSObject psObject, string propertyName) { if (psObject == null) return string.Empty; @@ -336,14 +336,14 @@ private string ExtractTextForHelpProperty(PSObject psObject, string propertyName /// /// /// - private string ExtractText(PSObject psObject) + private static string ExtractText(PSObject psObject) { if (psObject == null) { return string.Empty; } - // I think every cmdlet description should atleast have 400 characters... + // I think every cmdlet description should at least have 400 characters... // so starting with this assumption..I did an average of all the cmdlet // help content available at the time of writing this code and came up // with this number. @@ -441,7 +441,7 @@ internal MamlCommandHelpInfo Copy() internal MamlCommandHelpInfo Copy(HelpCategory newCategoryToUse) { MamlCommandHelpInfo result = new MamlCommandHelpInfo(_fullHelpObject.Copy(), newCategoryToUse); - result.FullHelp.Properties["Category"].Value = newCategoryToUse; + result.FullHelp.Properties["Category"].Value = newCategoryToUse.ToString(); return result; } diff --git a/src/System.Management.Automation/help/MamlNode.cs b/src/System.Management.Automation/help/MamlNode.cs index fe4e803a294..ecf565c942b 100644 --- a/src/System.Management.Automation/help/MamlNode.cs +++ b/src/System.Management.Automation/help/MamlNode.cs @@ -123,7 +123,7 @@ internal PSObject PSObject /// /// In this case, an PSObject that wraps string "atomic xml text" will be returned with following properties /// attribute => name - /// 3. Composite xml, which is an xmlNode with structured child nodes, but not a special case for Maml formating. + /// 3. Composite xml, which is an xmlNode with structured child nodes, but not a special case for Maml formatting. /// /// /// single child node text @@ -209,7 +209,7 @@ private PSObject GetPSObject(XmlNode xmlNode) { mshObject = new PSObject(GetInsidePSObject(xmlNode)); // Add typeNames to this MSHObject and create views so that - // the ouput is readable. This is done only for complex nodes. + // the output is readable. This is done only for complex nodes. mshObject.TypeNames.Clear(); if (xmlNode.Attributes["type"] != null) @@ -321,7 +321,7 @@ private Hashtable GetInsideProperties(XmlNode xmlNode) /// /// Node whose children are verified for maml. /// - private void RemoveUnsupportedNodes(XmlNode xmlNode) + private static void RemoveUnsupportedNodes(XmlNode xmlNode) { // Start with the first child.. // We want to modify only children.. @@ -1109,7 +1109,7 @@ private static string GetPreformattedText(string text) // It is discouraged to use tab in preformatted text. string noTabText = text.Replace("\t", " "); - string[] lines = noTabText.Split(Utils.Separators.Newline); + string[] lines = noTabText.Split('\n'); string[] trimedLines = TrimLines(lines); if (trimedLines == null || trimedLines.Length == 0) @@ -1212,7 +1212,7 @@ private static int GetIndentation(string line) if (IsEmptyLine(line)) return 0; - string leftTrimedLine = line.TrimStart(Utils.Separators.Space); + string leftTrimedLine = line.TrimStart(' '); return line.Length - leftTrimedLine.Length; } diff --git a/src/System.Management.Automation/help/PSClassHelpProvider.cs b/src/System.Management.Automation/help/PSClassHelpProvider.cs index e4c74c6398a..2d80b2cc863 100644 --- a/src/System.Management.Automation/help/PSClassHelpProvider.cs +++ b/src/System.Management.Automation/help/PSClassHelpProvider.cs @@ -279,7 +279,7 @@ private void LoadHelpFile(string helpFile, string helpFileIdentifier, string com } if (e != null) - s_tracer.WriteLine("Error occured in PSClassHelpProvider {0}", e.Message); + s_tracer.WriteLine("Error occurred in PSClassHelpProvider {0}", e.Message); if (reportErrors && (e != null)) { diff --git a/src/System.Management.Automation/help/ProviderContext.cs b/src/System.Management.Automation/help/ProviderContext.cs index cb24ece0593..817e2b3f0e6 100644 --- a/src/System.Management.Automation/help/ProviderContext.cs +++ b/src/System.Management.Automation/help/ProviderContext.cs @@ -141,7 +141,7 @@ Runspaces.SessionStateProviderEntry sessionStateProvider in } } - // ok we have path and valid provider that supplys content..initialize the provider + // ok we have path and valid provider that supplies content..initialize the provider // and get the help content for the path. cmdletProvider.Start(providerInfo, cmdletProviderContext); // There should be exactly one resolved path. diff --git a/src/System.Management.Automation/help/ProviderHelpInfo.cs b/src/System.Management.Automation/help/ProviderHelpInfo.cs index e159892a73e..80859a2ddf8 100644 --- a/src/System.Management.Automation/help/ProviderHelpInfo.cs +++ b/src/System.Management.Automation/help/ProviderHelpInfo.cs @@ -10,7 +10,7 @@ namespace System.Management.Automation /// Class ProviderHelpInfo keeps track of help information to be returned by /// command help provider. /// - internal class ProviderHelpInfo : HelpInfo + internal sealed class ProviderHelpInfo : HelpInfo { /// /// Constructor for HelpProvider. @@ -101,7 +101,7 @@ internal string DetailedDescription return string.Empty; } - // I think every provider description should atleast have 400 characters... + // I think every provider description should at least have 400 characters... // so starting with this assumption..I did an average of all the help content // available at the time of writing this code and came up with this number. Text.StringBuilder result = new Text.StringBuilder(400); @@ -167,15 +167,9 @@ internal override bool MatchPatternInContent(WildcardPattern pattern) string synopsis = Synopsis; string detailedDescription = DetailedDescription; - if (synopsis == null) - { - synopsis = string.Empty; - } + synopsis ??= string.Empty; - if (detailedDescription == null) - { - detailedDescription = string.Empty; - } + detailedDescription ??= string.Empty; return pattern.IsMatch(synopsis) || pattern.IsMatch(detailedDescription); } diff --git a/src/System.Management.Automation/help/ProviderHelpProvider.cs b/src/System.Management.Automation/help/ProviderHelpProvider.cs index b28dcf86398..afc0c71c6c2 100644 --- a/src/System.Management.Automation/help/ProviderHelpProvider.cs +++ b/src/System.Management.Automation/help/ProviderHelpProvider.cs @@ -236,14 +236,20 @@ private void LoadHelpFile(ProviderInfo providerInfo) this.HelpSystem.TraceErrors(helpInfo.Errors); // Add snapin qualified type name for this command.. // this will enable customizations of the help object. - helpInfo.FullHelp.TypeNames.Insert(0, string.Format(CultureInfo.InvariantCulture, - "ProviderHelpInfo#{0}#{1}", providerInfo.PSSnapInName, helpInfo.Name)); + helpInfo.FullHelp.TypeNames.Insert( + index: 0, + string.Create( + CultureInfo.InvariantCulture, + $"ProviderHelpInfo#{providerInfo.PSSnapInName}#{helpInfo.Name}")); if (!string.IsNullOrEmpty(providerInfo.PSSnapInName)) { helpInfo.FullHelp.Properties.Add(new PSNoteProperty("PSSnapIn", providerInfo.PSSnapIn)); - helpInfo.FullHelp.TypeNames.Insert(1, string.Format(CultureInfo.InvariantCulture, - "ProviderHelpInfo#{0}", providerInfo.PSSnapInName)); + helpInfo.FullHelp.TypeNames.Insert( + index: 1, + string.Create( + CultureInfo.InvariantCulture, + $"ProviderHelpInfo#{providerInfo.PSSnapInName}")); } AddCache(providerInfo.PSSnapInName + "\\" + helpInfo.Name, helpInfo); diff --git a/src/System.Management.Automation/help/SaveHelpCommand.cs b/src/System.Management.Automation/help/SaveHelpCommand.cs index 94803728c99..5df8f974f5c 100644 --- a/src/System.Management.Automation/help/SaveHelpCommand.cs +++ b/src/System.Management.Automation/help/SaveHelpCommand.cs @@ -88,7 +88,7 @@ public string[] LiteralPath [Parameter(Position = 1, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, ParameterSetName = LiteralPathParameterSetName)] [Alias("Name")] [ValidateNotNull] - [ArgumentToModuleTransformationAttribute()] + [ArgumentToModuleTransformation] [SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")] public PSModuleInfo[] Module { get; set; } @@ -260,10 +260,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } finally { - if (helpInfoDrive != null) - { - helpInfoDrive.Dispose(); - } + helpInfoDrive?.Dispose(); } } @@ -407,10 +404,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } finally { - if (helpContentDrive != null) - { - helpContentDrive.Dispose(); - } + helpContentDrive?.Dispose(); } } } diff --git a/src/System.Management.Automation/help/SyntaxHelpInfo.cs b/src/System.Management.Automation/help/SyntaxHelpInfo.cs index 469ab94a913..261fdd7f849 100644 --- a/src/System.Management.Automation/help/SyntaxHelpInfo.cs +++ b/src/System.Management.Automation/help/SyntaxHelpInfo.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation /// Class HelpFileHelpInfo keeps track of help information to be returned by /// command help provider. /// - internal class SyntaxHelpInfo : BaseCommandHelpInfo + internal sealed class SyntaxHelpInfo : BaseCommandHelpInfo { /// /// Constructor for SyntaxHelpInfo. diff --git a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs index 49d1e67e5d9..687faa68246 100644 --- a/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs +++ b/src/System.Management.Automation/help/UpdatableHelpCommandBase.cs @@ -60,7 +60,11 @@ public CultureInfo[] UICulture set { - if (value == null) return; + if (value == null) + { + return; + } + _language = new string[value.Length]; for (int index = 0; index < value.Length; index++) { @@ -74,8 +78,8 @@ public CultureInfo[] UICulture /// /// Gets or sets the credential parameter. /// - [Parameter()] - [Credential()] + [Parameter] + [Credential] public PSCredential Credential { get { return _credential; } @@ -166,22 +170,22 @@ private void HandleProgressChanged(object sender, UpdatableHelpProgressEventArgs /// /// Static constructor /// - /// NOTE: FWLinks for core PowerShell modules are needed since they get loaded as snapins in a Remoting Endpoint. + /// NOTE: HelpInfoUri for core PowerShell modules are needed since they get loaded as snapins in a Remoting Endpoint. /// When we moved to modules in V3, we were not able to make this change as it was a risky change to make at that time. /// static UpdatableHelpCommandBase() { s_metadataCache = new Dictionary(StringComparer.OrdinalIgnoreCase); - // TODO: assign real TechNet addresses + // NOTE: The HelpInfoUri must be updated with each release. - s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://aka.ms/powershell71-help"); - s_metadataCache.Add("Microsoft.PowerShell.Core", "https://aka.ms/powershell71-help"); - s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://aka.ms/powershell71-help"); - s_metadataCache.Add("Microsoft.PowerShell.Host", "https://aka.ms/powershell71-help"); - s_metadataCache.Add("Microsoft.PowerShell.Management", "https://aka.ms/powershell71-help"); - s_metadataCache.Add("Microsoft.PowerShell.Security", "https://aka.ms/powershell71-help"); - s_metadataCache.Add("Microsoft.WSMan.Management", "https://aka.ms/powershell71-help"); + s_metadataCache.Add("Microsoft.PowerShell.Diagnostics", "https://aka.ms/powershell75-help"); + s_metadataCache.Add("Microsoft.PowerShell.Core", "https://aka.ms/powershell75-help"); + s_metadataCache.Add("Microsoft.PowerShell.Utility", "https://aka.ms/powershell75-help"); + s_metadataCache.Add("Microsoft.PowerShell.Host", "https://aka.ms/powershell75-help"); + s_metadataCache.Add("Microsoft.PowerShell.Management", "https://aka.ms/powershell75-help"); + s_metadataCache.Add("Microsoft.PowerShell.Security", "https://aka.ms/powershell75-help"); + s_metadataCache.Add("Microsoft.WSMan.Management", "https://aka.ms/powershell75-help"); } /// @@ -206,9 +210,7 @@ internal UpdatableHelpCommandBase(UpdatableHelpCommandType commandType) _exceptions = new Dictionary(); _helpSystem.OnProgressChanged += HandleProgressChanged; - Random rand = new Random(); - - activityId = rand.Next(); + activityId = Random.Shared.Next(); } #endregion @@ -443,7 +445,10 @@ internal void Process(IEnumerable moduleNames, IEnumerableModule objects given by the user. internal void Process(IEnumerable modules) { - if (modules == null || !modules.Any()) { return; } + if (modules == null || !modules.Any()) + { + return; + } var helpModules = new Dictionary, UpdatableHelpModuleInfo>(); @@ -509,6 +514,7 @@ private void ProcessModule(UpdatableHelpModuleInfo module) // Win8: 572882 When the system locale is English and the UI is JPN, // running "update-help" still downs English help content. var cultures = _language ?? _helpSystem.GetCurrentUICulture(); + UpdatableHelpSystemException implicitCultureNotSupported = null; foreach (string culture in cultures) { @@ -549,7 +555,8 @@ private void ProcessModule(UpdatableHelpModuleInfo module) #endif catch (UpdatableHelpSystemException e) { - if (e.FullyQualifiedErrorId == "HelpCultureNotSupported") + if (e.FullyQualifiedErrorId == "HelpCultureNotSupported" + || e.FullyQualifiedErrorId == "UnableToRetrieveHelpInfoXml") { installed = false; @@ -558,6 +565,12 @@ private void ProcessModule(UpdatableHelpModuleInfo module) // Display the error message only if we are not using the fallback chain ProcessException(module.ModuleName, culture, e); } + else + { + // Hold first exception, it will be displayed if fallback chain fails + WriteVerbose(StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupportedFallback, e.Message)); + implicitCultureNotSupported ??= e; + } } else { @@ -581,13 +594,19 @@ private void ProcessModule(UpdatableHelpModuleInfo module) } } - // If -Language is not specified, we only install + // If -UICulture is not specified, we only install // one culture from the fallback chain if (_language == null && installed) { - break; + return; } } + + // If the exception is not null and did not return early, then all of the fallback chain failed + if (implicitCultureNotSupported != null) + { + ProcessException(module.ModuleName, cultures.First(), implicitCultureNotSupported); + } } /// @@ -652,7 +671,7 @@ internal bool IsUpdateNecessary(UpdatableHelpModuleInfo module, UpdatableHelpInf } // Culture check - if (!newHelpInfo.IsCultureSupported(culture)) + if (!newHelpInfo.IsCultureSupported(culture.Name)) { throw new UpdatableHelpSystemException("HelpCultureNotSupported", StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, @@ -778,7 +797,7 @@ internal IEnumerable ResolvePath(string path, bool recurse, bool isLiter /// /// Path to resolve. /// A list of directories. - private IEnumerable RecursiveResolvePathHelper(string path) + private static IEnumerable RecursiveResolvePathHelper(string path) { if (System.IO.Directory.Exists(path)) { @@ -886,6 +905,7 @@ public enum UpdateHelpScope { /// /// Save the help content to the user directory. + /// CurrentUser, /// diff --git a/src/System.Management.Automation/help/UpdatableHelpInfo.cs b/src/System.Management.Automation/help/UpdatableHelpInfo.cs index 5af3fd57b6d..8170de90654 100644 --- a/src/System.Management.Automation/help/UpdatableHelpInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpInfo.cs @@ -1,9 +1,11 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; +using System.Linq; using System.Management.Automation.Internal; using System.Text; @@ -37,6 +39,44 @@ internal CultureSpecificUpdatableHelp(CultureInfo culture, Version version) /// Supported culture. /// internal CultureInfo Culture { get; set; } + + /// + /// Enumerates fallback chain (parents) of the culture, including itself. + /// + /// Culture to enumerate + /// + /// Examples: + /// en-GB => { en-GB, en } + /// zh-Hans-CN => { zh-Hans-CN, zh-Hans, zh }. + /// + /// An enumerable list of culture names. + internal static IEnumerable GetCultureFallbackChain(CultureInfo culture) + { + // We use just names instead because comparing two CultureInfo objects + // can fail if they are created using different means + while (culture != null) + { + if (string.IsNullOrEmpty(culture.Name)) + { + yield break; + } + + yield return culture.Name; + + culture = culture.Parent; + } + } + + /// + /// Checks if a culture is supported. + /// + /// Name of the culture to check. + /// True if supported, false if not. + internal bool IsCultureSupported(string cultureName) + { + Debug.Assert(cultureName != null, $"{nameof(cultureName)} may not be null"); + return GetCultureFallbackChain(Culture).Any(fallback => fallback == cultureName); + } } /// @@ -99,22 +139,12 @@ internal bool IsNewerVersion(UpdatableHelpInfo helpInfo, CultureInfo culture) /// /// Checks if a culture is supported. /// - /// Culture to check. + /// Name of the culture to check. /// True if supported, false if not. - internal bool IsCultureSupported(CultureInfo culture) + internal bool IsCultureSupported(string cultureName) { - Debug.Assert(culture != null); - - foreach (CultureSpecificUpdatableHelp updatableHelpItem in UpdatableHelpItems) - { - if (string.Equals(updatableHelpItem.Culture.Name, culture.Name, - StringComparison.OrdinalIgnoreCase)) - { - return true; - } - } - - return false; + Debug.Assert(cultureName != null, $"{nameof(cultureName)} may not be null"); + return UpdatableHelpItems.Any(item => item.IsCultureSupported(cultureName)); } /// diff --git a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs index b46717920f4..ccf0b95f0f6 100644 --- a/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs +++ b/src/System.Management.Automation/help/UpdatableHelpModuleInfo.cs @@ -28,7 +28,6 @@ internal class UpdatableHelpModuleInfo internal UpdatableHelpModuleInfo(string name, Guid guid, string path, string uri) { Debug.Assert(!string.IsNullOrEmpty(name)); - Debug.Assert(guid != Guid.Empty); Debug.Assert(!string.IsNullOrEmpty(path)); Debug.Assert(!string.IsNullOrEmpty(uri)); diff --git a/src/System.Management.Automation/help/UpdatableHelpSystem.cs b/src/System.Management.Automation/help/UpdatableHelpSystem.cs index 31fe5362d77..14edabf9613 100644 --- a/src/System.Management.Automation/help/UpdatableHelpSystem.cs +++ b/src/System.Management.Automation/help/UpdatableHelpSystem.cs @@ -28,7 +28,6 @@ namespace System.Management.Automation.Help /// /// Updatable help system exception. /// - [Serializable] internal class UpdatableHelpSystemException : Exception { /// @@ -294,19 +293,13 @@ internal IEnumerable GetCurrentUICulture() { CultureInfo culture = CultureInfo.CurrentUICulture; - while (culture != null) + // Allow tests to override system culture + if (InternalTestHooks.CurrentUICulture != null) { - if (string.IsNullOrEmpty(culture.Name)) - { - yield break; - } - - yield return culture.Name; - - culture = culture.Parent; + culture = InternalTestHooks.CurrentUICulture; } - yield break; + return CultureSpecificUpdatableHelp.GetCultureFallbackChain(culture); } #region Help Metadata Retrieval @@ -426,6 +419,7 @@ private string ResolveUri(string baseUri, bool verbose) using (HttpClient client = new HttpClient(handler)) { client.Timeout = new TimeSpan(0, 0, 30); // Set 30 second timeout + // codeql[cs/ssrf] - This is expected Poweshell behavior and the user assumes trust for the module they download and any URIs it references. The URIs are also not executables or scripts that would be invoked by this method. Task responseMessage = client.GetAsync(uri); using (HttpResponseMessage response = responseMessage.Result) { @@ -555,7 +549,10 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo } catch (XmlException e) { - if (ignoreValidationException) { return null; } + if (ignoreValidationException) + { + return null; + } throw new UpdatableHelpSystemException(HelpInfoXmlValidationFailure, e.Message, ErrorCategory.InvalidData, null, e); @@ -591,13 +588,9 @@ internal UpdatableHelpInfo CreateHelpInfo(string xml, string moduleName, Guid mo if (!string.IsNullOrEmpty(currentCulture)) { - IEnumerable patternList = SessionStateUtilities.CreateWildcardsFromStrings( - globPatterns: new[] { currentCulture }, - options: WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); - for (int i = 0; i < updatableHelpItem.Length; i++) { - if (SessionStateUtilities.MatchesAnyWildcardPattern(updatableHelpItem[i].Culture.Name, patternList, true)) + if (updatableHelpItem[i].IsCultureSupported(currentCulture)) { helpInfo.HelpContentUriCollection.Add(new UpdatableHelpUri(moduleName, moduleGuid, updatableHelpItem[i].Culture, uri)); } @@ -791,6 +784,7 @@ private bool DownloadHelpContentHttpClient(string uri, string fileName, Updatabl using (HttpClient client = new HttpClient(handler)) { client.Timeout = _defaultTimeout; + // codeql[cs/ssrf] - This is expected Poweshell behavior and the user assumes trust for the module they download and any URIs it references. The URIs are also not executables or scripts that would be invoked by this method. Task responseMsg = client.GetAsync(new Uri(uri), _cancelTokenSource.Token); // TODO: Should I use a continuation to write the stream to a file? @@ -1097,14 +1091,14 @@ internal void InstallHelpContent(UpdatableHelpCommandType commandType, Execution #if UNIX private static bool ExpandArchive(string source, string destination) { - bool sucessfulDecompression = false; + bool successfulDecompression = false; try { using (ZipArchive zipArchive = ZipFile.Open(source, ZipArchiveMode.Read)) { zipArchive.ExtractToDirectory(destination); - sucessfulDecompression = true; + successfulDecompression = true; } } catch (ArgumentException) { } @@ -1116,7 +1110,7 @@ private static bool ExpandArchive(string source, string destination) catch (UnauthorizedAccessException) { } catch (ObjectDisposedException) { } - return sucessfulDecompression; + return successfulDecompression; } #endif @@ -1137,9 +1131,9 @@ private static void UnzipHelpContent(ExecutionContext context, string srcPath, s } string sourceDirectory = Path.GetDirectoryName(srcPath); - bool sucessfulDecompression = false; + bool successfulDecompression = false; #if UNIX - sucessfulDecompression = ExpandArchive(Path.Combine(sourceDirectory, Path.GetFileName(srcPath)), destPath); + successfulDecompression = ExpandArchive(Path.Combine(sourceDirectory, Path.GetFileName(srcPath)), destPath); #else // Cabinet API doesn't handle the trailing back slash if (!sourceDirectory.EndsWith('\\')) @@ -1152,9 +1146,9 @@ private static void UnzipHelpContent(ExecutionContext context, string srcPath, s destPath += "\\"; } - sucessfulDecompression = CabinetExtractorFactory.GetCabinetExtractor().Extract(Path.GetFileName(srcPath), sourceDirectory, destPath); + successfulDecompression = CabinetExtractorFactory.GetCabinetExtractor().Extract(Path.GetFileName(srcPath), sourceDirectory, destPath); #endif - if (!sucessfulDecompression) + if (!successfulDecompression) { throw new UpdatableHelpSystemException("UnableToExtract", StringUtil.Format(HelpDisplayStrings.UnzipFailure), ErrorCategory.InvalidOperation, null, null); diff --git a/src/System.Management.Automation/help/UpdatableHelpUri.cs b/src/System.Management.Automation/help/UpdatableHelpUri.cs index 8b854e82a5d..82bbb4016fb 100644 --- a/src/System.Management.Automation/help/UpdatableHelpUri.cs +++ b/src/System.Management.Automation/help/UpdatableHelpUri.cs @@ -21,7 +21,6 @@ internal class UpdatableHelpUri internal UpdatableHelpUri(string moduleName, Guid moduleGuid, CultureInfo culture, string resolvedUri) { Debug.Assert(!string.IsNullOrEmpty(moduleName)); - Debug.Assert(moduleGuid != Guid.Empty); Debug.Assert(!string.IsNullOrEmpty(resolvedUri)); ModuleName = moduleName; diff --git a/src/System.Management.Automation/help/UpdateHelpCommand.cs b/src/System.Management.Automation/help/UpdateHelpCommand.cs index 01b17cbad7e..9df82699a32 100644 --- a/src/System.Management.Automation/help/UpdateHelpCommand.cs +++ b/src/System.Management.Automation/help/UpdateHelpCommand.cs @@ -7,6 +7,7 @@ using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; +using System.Linq; using System.Management.Automation; using System.Management.Automation.Help; using System.Management.Automation.Internal; @@ -181,6 +182,16 @@ protected override void ProcessRecord() _isInitialized = true; } + + // check if there is an UI, if not Throw out terminating error. + var cultures = _language ?? _helpSystem.GetCurrentUICulture(); + if (!cultures.Any()) + { + string cultureString = string.IsNullOrEmpty(CultureInfo.CurrentCulture.Name) ? CultureInfo.CurrentCulture.DisplayName : CultureInfo.CurrentCulture.Name; + string errMsg = StringUtil.Format(HelpDisplayStrings.FailedToUpdateHelpWithLocaleNoUICulture, cultureString); + ErrorRecord error = new ErrorRecord(new InvalidOperationException(errMsg), "FailedToUpdateHelpWithLocaleNoUICulture", ErrorCategory.InvalidOperation, targetObject: null); + ThrowTerminatingError(error); + } base.Process(_module, FullyQualifiedModule); @@ -214,6 +225,14 @@ protected override void ProcessRecord() /// True if the module has been processed, false if not. internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, string culture) { + // Simulate culture not found + if (InternalTestHooks.ThrowHelpCultureNotSupported) + { + throw new UpdatableHelpSystemException("HelpCultureNotSupported", + StringUtil.Format(HelpDisplayStrings.HelpCultureNotSupported, culture, "en-US"), + ErrorCategory.InvalidOperation, null, null); + } + UpdatableHelpInfo currentHelpInfo = null; UpdatableHelpInfo newHelpInfo = null; string helpInfoUri = null; @@ -322,10 +341,7 @@ internal override bool ProcessModuleWithCulture(UpdatableHelpModuleInfo module, } finally { - if (helpInfoDrive != null) - { - helpInfoDrive.Dispose(); - } + helpInfoDrive?.Dispose(); } } else diff --git a/src/System.Management.Automation/logging/LogProvider.cs b/src/System.Management.Automation/logging/LogProvider.cs index a46f181b262..e02807a38e8 100644 --- a/src/System.Management.Automation/logging/LogProvider.cs +++ b/src/System.Management.Automation/logging/LogProvider.cs @@ -102,6 +102,37 @@ internal LogProvider() /// internal abstract void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue); + /// + /// Provider interface function for logging AmsiUtil State event. + /// + /// This the action performed in AmsiUtil class, like init, scan, etc. + /// The amsiContext handled - Session pair. + internal abstract void LogAmsiUtilStateEvent(string state, string context); + + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal abstract void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult); + + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal abstract void LogWDACAuditEvent( + string title, + string message, + string fqid); + /// /// True if the log provider needs to use logging variables. /// @@ -169,9 +200,7 @@ protected static void AppendException(StringBuilder sb, Exception except) { sb.AppendLine(StringUtil.Format(EtwLoggingStrings.ErrorRecordMessage, except.Message)); - IContainsErrorRecord ier = except as IContainsErrorRecord; - - if (ier != null) + if (except is IContainsErrorRecord ier) { ErrorRecord er = ier.ErrorRecord; @@ -370,6 +399,43 @@ internal override void LogSettingsEvent(LogContext logContext, string variableNa { } + /// + /// Provider interface function for logging provider health event. + /// + /// This the action performed in AmsiUtil class, like init, scan, etc. + /// The amsiContext handled - Session pair. + internal override void LogAmsiUtilStateEvent(string state, string context) + { + } + + /// + /// Provider interface function for logging WDAC query event. + /// + /// Name of the WDAC query. + /// Name of script file for policy query. Can be null value. + /// Query call succeed code. + /// Result code of WDAC query. + internal override void LogWDACQueryEvent( + string queryName, + string fileName, + int querySuccess, + int queryResult) + { + } + + /// + /// Provider interface function for logging WDAC audit event. + /// + /// Title of WDAC audit event. + /// WDAC audit event message. + /// FullyQualifiedId of WDAC audit event. + internal override void LogWDACAuditEvent( + string title, + string message, + string fqid) + { + } + #endregion } } diff --git a/src/System.Management.Automation/logging/MshLog.cs b/src/System.Management.Automation/logging/MshLog.cs index 02a8990bc69..aae65271892 100644 --- a/src/System.Management.Automation/logging/MshLog.cs +++ b/src/System.Management.Automation/logging/MshLog.cs @@ -60,13 +60,13 @@ internal static class MshLog /// The value of this dictionary is never empty. A value of type DummyProvider means /// no logging. /// - private static ConcurrentDictionary> s_logProviders = + private static readonly ConcurrentDictionary> s_logProviders = new ConcurrentDictionary>(); private const string _crimsonLogProviderAssemblyName = "MshCrimsonLog"; private const string _crimsonLogProviderTypeName = "System.Management.Automation.Logging.CrimsonLogProvider"; - private static Collection s_ignoredCommands = new Collection(); + private static readonly Collection s_ignoredCommands = new Collection(); /// /// Static constructor. @@ -134,11 +134,6 @@ private static Collection CreateLogProvider(string shellId) try { -#if !CORECLR // TODO:CORECLR EventLogLogProvider not handled yet - LogProvider eventLogLogProvider = new EventLogLogProvider(shellId); - providers.Add(eventLogLogProvider); -#endif - #if UNIX LogProvider sysLogProvider = new PSSysLogProvider(); providers.Add(sysLogProvider); @@ -216,9 +211,11 @@ internal static void LogEngineHealthEvent(ExecutionContext executionContext, } InvocationInfo invocationInfo = null; - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null) + { invocationInfo = icer.ErrorRecord.InvocationInfo; + } + foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogEngineHealthEvent(provider, executionContext)) @@ -418,9 +415,11 @@ Severity severity } InvocationInfo invocationInfo = null; - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null) + { invocationInfo = icer.ErrorRecord.InvocationInfo; + } + foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogCommandHealthEvent(provider, executionContext)) @@ -610,9 +609,11 @@ Severity severity } InvocationInfo invocationInfo = null; - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (exception is IContainsErrorRecord icer && icer.ErrorRecord != null) + { invocationInfo = icer.ErrorRecord.InvocationInfo; + } + foreach (LogProvider provider in GetLogProvider(executionContext)) { if (NeedToLogProviderHealthEvent(provider, executionContext)) @@ -776,7 +777,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.HostId = (string)executionContext.EngineHostInterface.InstanceId.ToString(); } - logContext.HostApplication = string.Join(" ", Environment.GetCommandLineArgs()); + logContext.HostApplication = string.Join(' ', Environment.GetCommandLineArgs()); if (executionContext.CurrentRunspace != null) { @@ -809,9 +810,7 @@ private static LogContext GetLogContext(ExecutionContext executionContext, Invoc logContext.User = Logging.UnknownUserName; } - System.Management.Automation.Remoting.PSSenderInfo psSenderInfo = - executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") as System.Management.Automation.Remoting.PSSenderInfo; - if (psSenderInfo != null) + if (executionContext.SessionState.PSVariable.GetValue("PSSenderInfo") is System.Management.Automation.Remoting.PSSenderInfo psSenderInfo) { logContext.ConnectedUser = psSenderInfo.UserInfo.Identity.Name; } diff --git a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs b/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs deleted file mode 100644 index e6f301a04ac..00000000000 --- a/src/System.Management.Automation/logging/eventlog/EventLogLogProvider.cs +++ /dev/null @@ -1,684 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -using System.Collections; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Globalization; -using System.Resources; -using System.Text; -using System.Threading; - -namespace System.Management.Automation -{ - /// - /// EventLogLogProvider is a class to implement Msh Provider interface using EventLog technology. - /// - /// EventLogLogProvider will be the provider to use if Monad is running in early windows releases - /// from 2000 to 2003. - /// - /// EventLogLogProvider will be packaged in the same dll as Msh Log Engine since EventLog should - /// always be available. - /// - internal class EventLogLogProvider : LogProvider - { - /// - /// Constructor. - /// - /// - internal EventLogLogProvider(string shellId) - { - string source = SetupEventSource(shellId); - - _eventLog = new EventLog(); - _eventLog.Source = source; - - _resourceManager = new ResourceManager("System.Management.Automation.resources.Logging", System.Reflection.Assembly.GetExecutingAssembly()); - } - - internal string SetupEventSource(string shellId) - { - string source; - - // In case shellId == null, use the "Default" source. - if (string.IsNullOrEmpty(shellId)) - { - source = "Default"; - } - else - { - int index = shellId.LastIndexOf('.'); - - if (index < 0) - source = shellId; - else - source = shellId.Substring(index + 1); - - // There may be a situation where ShellId ends with a '.'. - // In that case, use the default source. - if (string.IsNullOrEmpty(source)) - source = "Default"; - } - - if (EventLog.SourceExists(source)) - { - return source; - } - - string message = string.Format(Thread.CurrentThread.CurrentCulture, "Event source '{0}' is not registered", source); - throw new InvalidOperationException(message); - } - - /// - /// This represent a handle to EventLog. - /// - private EventLog _eventLog; - private ResourceManager _resourceManager; - - #region Log Provider Api - - private const int EngineHealthCategoryId = 1; - private const int CommandHealthCategoryId = 2; - private const int ProviderHealthCategoryId = 3; - private const int EngineLifecycleCategoryId = 4; - private const int CommandLifecycleCategoryId = 5; - private const int ProviderLifecycleCategoryId = 6; - private const int SettingsCategoryId = 7; - private const int PipelineExecutionDetailCategoryId = 8; - - /// - /// Log engine health event. - /// - /// - /// - /// - /// - internal override void LogEngineHealthEvent(LogContext logContext, int eventId, Exception exception, Dictionary additionalInfo) - { - Hashtable mapArgs = new Hashtable(); - - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) - { - mapArgs["ExceptionClass"] = exception.GetType().Name; - mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; - mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - - if (icer.ErrorRecord.ErrorDetails != null) - { - mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; - } - else - { - mapArgs["ErrorMessage"] = exception.Message; - } - } - else - { - mapArgs["ExceptionClass"] = exception.GetType().Name; - mapArgs["ErrorCategory"] = string.Empty; - mapArgs["ErrorId"] = string.Empty; - mapArgs["ErrorMessage"] = exception.Message; - } - - FillEventArgs(mapArgs, logContext); - - FillEventArgs(mapArgs, additionalInfo); - - EventInstance entry = new EventInstance(eventId, EngineHealthCategoryId); - - entry.EntryType = GetEventLogEntryType(logContext); - - string detail = GetEventDetail("EngineHealthContext", mapArgs); - - LogEvent(entry, mapArgs["ErrorMessage"], detail); - } - - private static EventLogEntryType GetEventLogEntryType(LogContext logContext) - { - switch (logContext.Severity) - { - case "Critical": - case "Error": - return EventLogEntryType.Error; - case "Warning": - return EventLogEntryType.Warning; - default: - return EventLogEntryType.Information; - } - } - - /// - /// Log engine lifecycle event. - /// - /// - /// - /// - internal override void LogEngineLifecycleEvent(LogContext logContext, EngineState newState, EngineState previousState) - { - int eventId = GetEngineLifecycleEventId(newState); - - if (eventId == _invalidEventId) - return; - - Hashtable mapArgs = new Hashtable(); - - mapArgs["NewEngineState"] = newState.ToString(); - mapArgs["PreviousEngineState"] = previousState.ToString(); - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, EngineLifecycleCategoryId); - - entry.EntryType = EventLogEntryType.Information; - - string detail = GetEventDetail("EngineLifecycleContext", mapArgs); - - LogEvent(entry, newState, previousState, detail); - } - - private const int _baseEngineLifecycleEventId = 400; - private const int _invalidEventId = -1; - - /// - /// Get engine lifecycle event id based on engine state. - /// - /// - /// - private static int GetEngineLifecycleEventId(EngineState engineState) - { - switch (engineState) - { - case EngineState.None: - return _invalidEventId; - case EngineState.Available: - return _baseEngineLifecycleEventId; - case EngineState.Degraded: - return _baseEngineLifecycleEventId + 1; - case EngineState.OutOfService: - return _baseEngineLifecycleEventId + 2; - case EngineState.Stopped: - return _baseEngineLifecycleEventId + 3; - } - - return _invalidEventId; - } - - private const int _commandHealthEventId = 200; - - /// - /// Provider interface function for logging command health event. - /// - /// - /// - internal override void LogCommandHealthEvent(LogContext logContext, Exception exception) - { - int eventId = _commandHealthEventId; - - Hashtable mapArgs = new Hashtable(); - - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) - { - mapArgs["ExceptionClass"] = exception.GetType().Name; - mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; - mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - - if (icer.ErrorRecord.ErrorDetails != null) - { - mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; - } - else - { - mapArgs["ErrorMessage"] = exception.Message; - } - } - else - { - mapArgs["ExceptionClass"] = exception.GetType().Name; - mapArgs["ErrorCategory"] = string.Empty; - mapArgs["ErrorId"] = string.Empty; - mapArgs["ErrorMessage"] = exception.Message; - } - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, CommandHealthCategoryId); - - entry.EntryType = GetEventLogEntryType(logContext); - - string detail = GetEventDetail("CommandHealthContext", mapArgs); - - LogEvent(entry, mapArgs["ErrorMessage"], detail); - } - - /// - /// Log command life cycle event. - /// - /// - /// - internal override void LogCommandLifecycleEvent(Func getLogContext, CommandState newState) - { - LogContext logContext = getLogContext(); - - int eventId = GetCommandLifecycleEventId(newState); - - if (eventId == _invalidEventId) - return; - - Hashtable mapArgs = new Hashtable(); - - mapArgs["NewCommandState"] = newState.ToString(); - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, CommandLifecycleCategoryId); - - entry.EntryType = EventLogEntryType.Information; - - string detail = GetEventDetail("CommandLifecycleContext", mapArgs); - - LogEvent(entry, logContext.CommandName, newState, detail); - } - - private const int _baseCommandLifecycleEventId = 500; - - /// - /// Get command lifecycle event id based on command state. - /// - /// - /// - private static int GetCommandLifecycleEventId(CommandState commandState) - { - switch (commandState) - { - case CommandState.Started: - return _baseCommandLifecycleEventId; - case CommandState.Stopped: - return _baseCommandLifecycleEventId + 1; - case CommandState.Terminated: - return _baseCommandLifecycleEventId + 2; - } - - return _invalidEventId; - } - - private const int _pipelineExecutionDetailEventId = 800; - - /// - /// Log pipeline execution detail event. - /// - /// This may end of logging more than one event if the detail string is too long to be fit in 64K. - /// - /// - /// - internal override void LogPipelineExecutionDetailEvent(LogContext logContext, List pipelineExecutionDetail) - { - List details = GroupMessages(pipelineExecutionDetail); - - for (int i = 0; i < details.Count; i++) - { - LogPipelineExecutionDetailEvent(logContext, details[i], i + 1, details.Count); - } - } - - private const int MaxLength = 16000; - - private List GroupMessages(List messages) - { - List result = new List(); - - if (messages == null || messages.Count == 0) - return result; - - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < messages.Count; i++) - { - if (sb.Length + messages[i].Length < MaxLength) - { - sb.AppendLine(messages[i]); - continue; - } - - result.Add(sb.ToString()); - sb = new StringBuilder(); - sb.AppendLine(messages[i]); - } - - result.Add(sb.ToString()); - - return result; - } - - /// - /// Log one pipeline execution detail event. Detail message is already chopped up so that it will - /// fit in 64K. - /// - /// - /// - /// - /// - private void LogPipelineExecutionDetailEvent(LogContext logContext, string pipelineExecutionDetail, int detailSequence, int detailTotal) - { - int eventId = _pipelineExecutionDetailEventId; - - Hashtable mapArgs = new Hashtable(); - - mapArgs["PipelineExecutionDetail"] = pipelineExecutionDetail; - mapArgs["DetailSequence"] = detailSequence; - mapArgs["DetailTotal"] = detailTotal; - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, PipelineExecutionDetailCategoryId); - - entry.EntryType = EventLogEntryType.Information; - - string pipelineInfo = GetEventDetail("PipelineExecutionDetailContext", mapArgs); - - LogEvent(entry, logContext.CommandLine, pipelineInfo, pipelineExecutionDetail); - } - - private const int _providerHealthEventId = 300; - /// - /// Provider interface function for logging provider health event. - /// - /// - /// - /// - internal override void LogProviderHealthEvent(LogContext logContext, string providerName, Exception exception) - { - int eventId = _providerHealthEventId; - - Hashtable mapArgs = new Hashtable(); - - mapArgs["ProviderName"] = providerName; - - IContainsErrorRecord icer = exception as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) - { - mapArgs["ExceptionClass"] = exception.GetType().Name; - mapArgs["ErrorCategory"] = icer.ErrorRecord.CategoryInfo.Category; - mapArgs["ErrorId"] = icer.ErrorRecord.FullyQualifiedErrorId; - - if (icer.ErrorRecord.ErrorDetails != null - && !string.IsNullOrEmpty(icer.ErrorRecord.ErrorDetails.Message)) - { - mapArgs["ErrorMessage"] = icer.ErrorRecord.ErrorDetails.Message; - } - else - { - mapArgs["ErrorMessage"] = exception.Message; - } - } - else - { - mapArgs["ExceptionClass"] = exception.GetType().Name; - mapArgs["ErrorCategory"] = string.Empty; - mapArgs["ErrorId"] = string.Empty; - mapArgs["ErrorMessage"] = exception.Message; - } - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, ProviderHealthCategoryId); - - entry.EntryType = GetEventLogEntryType(logContext); - - string detail = GetEventDetail("ProviderHealthContext", mapArgs); - - LogEvent(entry, mapArgs["ErrorMessage"], detail); - } - - /// - /// Log provider lifecycle event. - /// - /// - /// - /// - internal override void LogProviderLifecycleEvent(LogContext logContext, string providerName, ProviderState newState) - { - int eventId = GetProviderLifecycleEventId(newState); - - if (eventId == _invalidEventId) - return; - - Hashtable mapArgs = new Hashtable(); - - mapArgs["ProviderName"] = providerName; - mapArgs["NewProviderState"] = newState.ToString(); - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, ProviderLifecycleCategoryId); - - entry.EntryType = EventLogEntryType.Information; - - string detail = GetEventDetail("ProviderLifecycleContext", mapArgs); - - LogEvent(entry, providerName, newState, detail); - } - - private const int _baseProviderLifecycleEventId = 600; - - /// - /// Get provider lifecycle event id based on provider state. - /// - /// - /// - private static int GetProviderLifecycleEventId(ProviderState providerState) - { - switch (providerState) - { - case ProviderState.Started: - return _baseProviderLifecycleEventId; - case ProviderState.Stopped: - return _baseProviderLifecycleEventId + 1; - } - - return _invalidEventId; - } - - private const int _settingsEventId = 700; - - /// - /// Log settings event. - /// - /// - /// - /// - /// - internal override void LogSettingsEvent(LogContext logContext, string variableName, string value, string previousValue) - { - int eventId = _settingsEventId; - - Hashtable mapArgs = new Hashtable(); - - mapArgs["VariableName"] = variableName; - mapArgs["NewValue"] = value; - mapArgs["PreviousValue"] = previousValue; - - FillEventArgs(mapArgs, logContext); - - EventInstance entry = new EventInstance(eventId, SettingsCategoryId); - - entry.EntryType = EventLogEntryType.Information; - - string detail = GetEventDetail("SettingsContext", mapArgs); - - LogEvent(entry, variableName, value, previousValue, detail); - } - - #endregion Log Provider Api - - #region EventLog helper functions - - /// - /// This is the helper function for logging an event with localizable message - /// to event log. It will trace all exception thrown by eventlog. - /// - /// - /// - private void LogEvent(EventInstance entry, params object[] args) - { - try - { - _eventLog.WriteEvent(entry, args); - } - catch (ArgumentException) - { - return; - } - catch (InvalidOperationException) - { - return; - } - catch (Win32Exception) - { - return; - } - } - - #endregion - - #region Event Arguments - - /// - /// Fill event arguments with logContext info. - /// - /// In EventLog Api, arguments are passed in as an array of objects. - /// - /// An ArrayList to contain the event arguments. - /// The log context containing the info to fill in. - private static void FillEventArgs(Hashtable mapArgs, LogContext logContext) - { - mapArgs["Severity"] = logContext.Severity; - mapArgs["SequenceNumber"] = logContext.SequenceNumber; - mapArgs["HostName"] = logContext.HostName; - mapArgs["HostVersion"] = logContext.HostVersion; - mapArgs["HostId"] = logContext.HostId; - mapArgs["HostApplication"] = logContext.HostApplication; - mapArgs["EngineVersion"] = logContext.EngineVersion; - mapArgs["RunspaceId"] = logContext.RunspaceId; - mapArgs["PipelineId"] = logContext.PipelineId; - mapArgs["CommandName"] = logContext.CommandName; - mapArgs["CommandType"] = logContext.CommandType; - mapArgs["ScriptName"] = logContext.ScriptName; - mapArgs["CommandPath"] = logContext.CommandPath; - mapArgs["CommandLine"] = logContext.CommandLine; - mapArgs["User"] = logContext.User; - mapArgs["Time"] = logContext.Time; - } - - /// - /// Fill event arguments with additionalInfo stored in a string dictionary. - /// - /// An arraylist to contain the event arguments. - /// A string dictionary to fill in. - private static void FillEventArgs(Hashtable mapArgs, Dictionary additionalInfo) - { - if (additionalInfo == null) - { - for (int i = 0; i < 3; i++) - { - string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture); - - mapArgs["AdditionalInfo_Name" + id] = string.Empty; - mapArgs["AdditionalInfo_Value" + id] = string.Empty; - } - - return; - } - - string[] keys = new string[additionalInfo.Count]; - string[] values = new string[additionalInfo.Count]; - - additionalInfo.Keys.CopyTo(keys, 0); - additionalInfo.Values.CopyTo(values, 0); - for (int i = 0; i < 3; i++) - { - string id = ((int)(i + 1)).ToString("d1", CultureInfo.CurrentCulture); - - if (i < keys.Length) - { - mapArgs["AdditionalInfo_Name" + id] = keys[i]; - mapArgs["AdditionalInfo_Value" + id] = values[i]; - } - else - { - mapArgs["AdditionalInfo_Name" + id] = string.Empty; - mapArgs["AdditionalInfo_Value" + id] = string.Empty; - } - } - - return; - } - - #endregion Event Arguments - - #region Event Message - - private string GetEventDetail(string contextId, Hashtable mapArgs) - { - return GetMessage(contextId, mapArgs); - } - - private string GetMessage(string messageId, Hashtable mapArgs) - { - if (_resourceManager == null) - return string.Empty; - - string messageTemplate = _resourceManager.GetString(messageId); - - if (string.IsNullOrEmpty(messageTemplate)) - return string.Empty; - - return FillMessageTemplate(messageTemplate, mapArgs); - } - - private static string FillMessageTemplate(string messageTemplate, Hashtable mapArgs) - { - StringBuilder message = new StringBuilder(); - - int cursor = 0; - - while (true) - { - int startIndex = messageTemplate.IndexOf('[', cursor); - - if (startIndex < 0) - { - message.Append(messageTemplate.Substring(cursor)); - return message.ToString(); - } - - int endIndex = messageTemplate.IndexOf(']', startIndex + 1); - - if (endIndex < 0) - { - message.Append(messageTemplate.Substring(cursor)); - return message.ToString(); - } - - message.Append(messageTemplate.Substring(cursor, startIndex - cursor)); - cursor = startIndex; - - string placeHolder = messageTemplate.Substring(startIndex + 1, endIndex - startIndex - 1); - - if (mapArgs.Contains(placeHolder)) - { - message.Append(mapArgs[placeHolder]); - cursor = endIndex + 1; - } - else - { - message.Append("["); - cursor++; - } - } - } - - #endregion Event Message - } -} diff --git a/src/System.Management.Automation/namespaces/AliasProvider.cs b/src/System.Management.Automation/namespaces/AliasProvider.cs index 8782a0d9bb5..c51d8e35128 100644 --- a/src/System.Management.Automation/namespaces/AliasProvider.cs +++ b/src/System.Management.Automation/namespaces/AliasProvider.cs @@ -194,11 +194,7 @@ internal override void SetSessionStateItem(string name, object value, bool write if (dynamicParametersSpecified) { item = (AliasInfo)GetSessionStateItem(name); - - if (item != null) - { - item.SetOptions(dynamicParameters.Options, Force); - } + item?.SetOptions(dynamicParameters.Options, Force); } else { diff --git a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs index cc3e0ac83e2..2a600097108 100644 --- a/src/System.Management.Automation/namespaces/ContainerProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ContainerProviderBase.cs @@ -840,7 +840,7 @@ protected virtual object RenameItemDynamicParameters(string path, string newName /// /// The parameter can be any type of object that the provider can use /// to create the item. It is recommended that the provider accept at a minimum strings, and an instance - /// of the type of object that would be returned from GetItem() for this path. + /// of the type of object that would be returned from GetItem() for this path. /// can be used to convert some types to the desired type. /// /// The default implementation of this method throws an . diff --git a/src/System.Management.Automation/namespaces/CoreCommandContext.cs b/src/System.Management.Automation/namespaces/CoreCommandContext.cs index 5446b6b71cb..cf8c43c4b3e 100644 --- a/src/System.Management.Automation/namespaces/CoreCommandContext.cs +++ b/src/System.Management.Automation/namespaces/CoreCommandContext.cs @@ -29,7 +29,7 @@ internal sealed class CmdletProviderContext /// An instance of the PSTraceSource class used for trace output /// using "CmdletProviderContext" as the category. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "CmdletProviderContext", "The context under which a core command is being run.")] private static readonly Dbg.PSTraceSource s_tracer = @@ -390,13 +390,8 @@ private void CopyFilters(CmdletProviderContext context) Filter = context.Filter; } - internal void RemoveStopReferral() - { - if (_copiedContext != null) - { - _copiedContext.StopReferrals.Remove(this); - } - } + internal void RemoveStopReferral() => _copiedContext?.StopReferrals.Remove(this); + #endregion Internal properties #region Public properties @@ -556,7 +551,7 @@ internal SwitchParameter Force /// /// Name of the target resource being acted upon /// - /// true iff the action should be performed + /// true if-and-only-if the action should be performed /// /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be @@ -582,7 +577,7 @@ internal bool ShouldProcess( /// Name of the target resource being acted upon /// /// What action was being performed. - /// true iff the action should be performed + /// true if-and-only-if the action should be performed /// /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be @@ -621,7 +616,7 @@ internal bool ShouldProcess( /// if the user is prompted whether or not to perform the action. /// It may be displayed by some hosts, but not all. /// - /// true iff the action should be performed + /// true if-and-only-if the action should be performed /// /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be @@ -670,7 +665,7 @@ internal bool ShouldProcess( /// /// are returned. /// - /// true iff the action should be performed + /// true if-and-only-if the action should be performed /// /// The ActionPreference.Stop or ActionPreference.Inquire policy /// triggered a terminating error. The pipeline failure will be @@ -774,13 +769,7 @@ internal bool ShouldContinue( /// /// The string that needs to be written. /// - internal void WriteVerbose(string text) - { - if (_command != null) - { - _command.WriteVerbose(text); - } - } + internal void WriteVerbose(string text) => _command?.WriteVerbose(text); /// /// Writes the object to the Warning pipe. @@ -788,21 +777,9 @@ internal void WriteVerbose(string text) /// /// The string that needs to be written. /// - internal void WriteWarning(string text) - { - if (_command != null) - { - _command.WriteWarning(text); - } - } + internal void WriteWarning(string text) => _command?.WriteWarning(text); - internal void WriteProgress(ProgressRecord record) - { - if (_command != null) - { - _command.WriteProgress(record); - } - } + internal void WriteProgress(ProgressRecord record) => _command?.WriteProgress(record); /// /// Writes a debug string. @@ -810,29 +787,11 @@ internal void WriteProgress(ProgressRecord record) /// /// The String that needs to be written. /// - internal void WriteDebug(string text) - { - if (_command != null) - { - _command.WriteDebug(text); - } - } + internal void WriteDebug(string text) => _command?.WriteDebug(text); - internal void WriteInformation(InformationRecord record) - { - if (_command != null) - { - _command.WriteInformation(record); - } - } + internal void WriteInformation(InformationRecord record) => _command?.WriteInformation(record); - internal void WriteInformation(object messageData, string[] tags) - { - if (_command != null) - { - _command.WriteInformation(messageData, tags); - } - } + internal void WriteInformation(object messageData, string[] tags) => _command?.WriteInformation(messageData, tags); #endregion User feedback mechanisms @@ -1154,14 +1113,10 @@ internal void StopProcessing() { Stopping = true; - if (_providerInstance != null) - { - // We don't need to catch any of the exceptions here because - // we are terminating the pipeline and any exception will - // be caught by the engine. - - _providerInstance.StopProcessing(); - } + // We don't need to catch any of the exceptions here because + // we are terminating the pipeline and any exception will + // be caught by the engine. + _providerInstance?.StopProcessing(); // Call the stop referrals if any diff --git a/src/System.Management.Automation/namespaces/DriveProviderBase.cs b/src/System.Management.Automation/namespaces/DriveProviderBase.cs index 91b47619be7..2fc44e50bdc 100644 --- a/src/System.Management.Automation/namespaces/DriveProviderBase.cs +++ b/src/System.Management.Automation/namespaces/DriveProviderBase.cs @@ -9,7 +9,7 @@ namespace System.Management.Automation.Provider #region DriveCmdletProvider /// - /// The base class for Cmdlet providers that can be exposed through MSH drives. + /// The base class for Cmdlet providers that can be exposed through PSDrives. /// /// /// Although it is possible to derive from this base class to implement a Cmdlet Provider, in most diff --git a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs index f5d299ecfd6..d0f8f08deab 100644 --- a/src/System.Management.Automation/namespaces/FileSystemContentStream.cs +++ b/src/System.Management.Automation/namespaces/FileSystemContentStream.cs @@ -35,7 +35,7 @@ internal class FileSystemContentReaderWriter : IContentReader, IContentWriter /// An instance of the PSTraceSource class used for trace output /// using "FileSystemContentStream" as the category. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "FileSystemContentStream", "The provider content reader and writer for the file system")] private static readonly Dbg.PSTraceSource s_tracer = @@ -413,7 +413,7 @@ public IList Read(long readCount) (e is UnauthorizedAccessException) || (e is ArgumentNullException)) { - // Exception contains specific message about the error occured and so no need for errordetails. + // Exception contains specific message about the error occurred and so no need for errordetails. _provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, _path)); return null; } @@ -567,7 +567,7 @@ internal void SeekItemsBackward(int backCount) (e is UnauthorizedAccessException) || (e is ArgumentNullException)) { - // Exception contains specific message about the error occured and so no need for errordetails. + // Exception contains specific message about the error occurred and so no need for errordetails. _provider.WriteError(new ErrorRecord(e, "GetContentReaderIOError", ErrorCategory.ReadError, _path)); } else @@ -709,7 +709,7 @@ private bool ReadDelimited(bool waitChanges, List blocks, bool readBackw // We've reached the end of file or end of line. if (_currentLineContent.Length > 0) { - // Add the block read to the ouptut array list, trimming a trailing delimiter, if present. + // Add the block read to the output array list, trimming a trailing delimiter, if present. // Note: If -Tail was specified, we get here in the course of 2 distinct passes: // - Once while reading backward simply to determine the appropriate *start position* for later forward reading, ignoring the content of the blocks read (in reverse). // - Then again during forward reading, for regular output processing; it is only then that trimming the delimiter is necessary. @@ -794,7 +794,7 @@ private bool ReadByteEncoded(bool waitChanges, List blocks, bool readBac // the changes if (waitChanges) { - WaitForChanges(_path, _mode, _access, _share, ClrFacade.GetDefaultEncoding()); + WaitForChanges(_path, _mode, _access, _share, Encoding.Default); byteRead = _stream.ReadByte(); } } @@ -987,9 +987,8 @@ private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileA // Seek to the place we last left off. _stream.Seek(_fileOffset, SeekOrigin.Begin); - if (_reader != null) { _reader.DiscardBufferedData(); } - - if (_backReader != null) { _backReader.DiscardBufferedData(); } + _reader?.DiscardBufferedData(); + _backReader?.DiscardBufferedData(); } /// @@ -1003,15 +1002,13 @@ private void WaitForChanges(string filePath, FileMode fileMode, FileAccess fileA /// public void Seek(long offset, SeekOrigin origin) { - if (_writer != null) { _writer.Flush(); } + _writer?.Flush(); _stream.Seek(offset, origin); - if (_writer != null) { _writer.Flush(); } - - if (_reader != null) { _reader.DiscardBufferedData(); } - - if (_backReader != null) { _backReader.DiscardBufferedData(); } + _writer?.Flush(); + _reader?.DiscardBufferedData(); + _backReader?.DiscardBufferedData(); } /// @@ -1135,14 +1132,10 @@ internal void Dispose(bool isDisposing) { if (isDisposing) { - if (_stream != null) - _stream.Dispose(); - if (_reader != null) - _reader.Dispose(); - if (_backReader != null) - _backReader.Dispose(); - if (_writer != null) - _writer.Dispose(); + _stream?.Dispose(); + _reader?.Dispose(); + _backReader?.Dispose(); + _writer?.Dispose(); } } } @@ -1180,39 +1173,9 @@ internal FileStreamBackReader(FileStream fileStream, Encoding encoding) private int _byteCount = 0; private int _charCount = 0; private long _currentPosition = 0; - private bool? _singleByteCharSet = null; - private const byte BothTopBitsSet = 0xC0; private const byte TopBitUnset = 0x80; - /// - /// If the given encoding is OEM or Default, check to see if the code page - /// is SBCS(single byte character set). - /// - /// - private bool IsSingleByteCharacterSet() - { - if (_singleByteCharSet != null) - return (bool)_singleByteCharSet; - - // Porting note: only UTF-8 is supported on Linux, which is not an SBCS - if ((_currentEncoding.Equals(_oemEncoding) || - _currentEncoding.Equals(_defaultAnsiEncoding)) - && Platform.IsWindows) - { - NativeMethods.CPINFO cpInfo; - if (NativeMethods.GetCPInfo((uint)_currentEncoding.CodePage, out cpInfo) && - cpInfo.MaxCharSize == 1) - { - _singleByteCharSet = true; - return true; - } - } - - _singleByteCharSet = false; - return false; - } - /// /// We don't support this method because it is not used by the ReadBackward method in FileStreamContentReaderWriter. /// @@ -1481,8 +1444,7 @@ private int RefillByteBuff() } else if (_currentEncoding is UnicodeEncoding || _currentEncoding is UTF32Encoding || - _currentEncoding is ASCIIEncoding || - IsSingleByteCharacterSet()) + _currentEncoding.IsSingleByte) { // Unicode -- two bytes per character // UTF-32 -- four bytes per character @@ -1513,36 +1475,6 @@ _currentEncoding is ASCIIEncoding || return _byteCount; } - - private static class NativeMethods - { - // Default values - private const int MAX_DEFAULTCHAR = 2; - private const int MAX_LEADBYTES = 12; - - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal struct CPINFO - { - [MarshalAs(UnmanagedType.U4)] - internal int MaxCharSize; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_DEFAULTCHAR)] - public byte[] DefaultChar; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_LEADBYTES)] - public byte[] LeadBytes; - } - - /// - /// Get information on a named code page. - /// - /// - /// - /// - [DllImport(PinvokeDllNames.GetCPInfoDllName, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool GetCPInfo(uint codePage, out CPINFO lpCpInfo); - } } /// diff --git a/src/System.Management.Automation/namespaces/FileSystemProvider.cs b/src/System.Management.Automation/namespaces/FileSystemProvider.cs index 9499bf95289..05c8fff76e0 100644 --- a/src/System.Management.Automation/namespaces/FileSystemProvider.cs +++ b/src/System.Management.Automation/namespaces/FileSystemProvider.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -18,6 +19,7 @@ using System.Security; using System.Security.AccessControl; using System.Text; +using System.Threading.Tasks; using System.Xml; using System.Xml.XPath; @@ -37,13 +39,14 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(FileSecurity), ProviderCmdlet = ProviderCmdlet.SetAcl)] [OutputType(typeof(string), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)] [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)] + [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PopLocation)] [OutputType(typeof(byte), typeof(string), ProviderCmdlet = ProviderCmdlet.GetContent)] [OutputType(typeof(FileInfo), ProviderCmdlet = ProviderCmdlet.GetItem)] [OutputType(typeof(FileInfo), typeof(DirectoryInfo), ProviderCmdlet = ProviderCmdlet.GetChildItem)] [OutputType(typeof(FileSecurity), typeof(DirectorySecurity), ProviderCmdlet = ProviderCmdlet.GetAcl)] [OutputType(typeof(bool), typeof(string), typeof(FileInfo), typeof(DirectoryInfo), ProviderCmdlet = ProviderCmdlet.GetItem)] [OutputType(typeof(bool), typeof(string), typeof(DateTime), typeof(System.IO.FileInfo), typeof(System.IO.DirectoryInfo), ProviderCmdlet = ProviderCmdlet.GetItemProperty)] - [OutputType(typeof(string), typeof(System.IO.FileInfo), ProviderCmdlet = ProviderCmdlet.NewItem)] + [OutputType(typeof(string), typeof(System.IO.FileInfo), typeof(DirectoryInfo), ProviderCmdlet = ProviderCmdlet.NewItem)] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This coupling is required")] public sealed partial class FileSystemProvider : NavigationCmdletProvider, IContentCmdletProvider, @@ -51,21 +54,15 @@ public sealed partial class FileSystemProvider : NavigationCmdletProvider, ISecurityDescriptorCmdletProvider, ICmdletProviderSupportsHelp { -#if UNIX - // This is the errno returned by the rename() syscall - // when an item is attempted to be renamed across filesystem mount boundaries. - private const int MOVE_FAILED_ERROR = 18; -#else - // 0x80070005 ACCESS_DENIED is returned when trying to move files across volumes like DFS - private const int MOVE_FAILED_ERROR = -2147024891; -#endif - // 4MB gives the best results without spiking the resources on the remote connection for file transfers between pssessions. // NOTE: The script used to copy file data from session (PSCopyFromSessionHelper) has a // maximum fragment size value for security. If FILETRANSFERSIZE changes make sure the - // copy script will accomodate the new value. + // copy script will accommodate the new value. private const int FILETRANSFERSIZE = 4 * 1024 * 1024; + private const int COPY_FILE_ACTIVITY_ID = 0; + private const int REMOVE_FILE_ACTIVITY_ID = 0; + // The name of the key in an exception's Data dictionary when attempting // to copy an item onto itself. private const string SelfCopyDataKey = "SelfCopy"; @@ -74,7 +71,7 @@ public sealed partial class FileSystemProvider : NavigationCmdletProvider, /// An instance of the PSTraceSource class used for trace output /// using "FileSystemProvider" as the category. /// - [Dbg.TraceSourceAttribute("FileSystemProvider", "The namespace navigation provider for the file system")] + [Dbg.TraceSource("FileSystemProvider", "The namespace navigation provider for the file system")] private static readonly Dbg.PSTraceSource s_tracer = Dbg.PSTraceSource.GetTracer("FileSystemProvider", "The namespace navigation provider for the file system"); @@ -109,7 +106,7 @@ public FileSystemProvider() /// /// The path with all / normalized to \ /// - private static string NormalizePath(string path) + internal static string NormalizePath(string path) { return GetCorrectCasedPath(path.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator)); } @@ -140,20 +137,21 @@ private static string GetCorrectCasedPath(string path) itemsToSkip = 4; } - foreach (string item in path.Split(StringLiterals.DefaultPathSeparator)) + var items = path.Split(StringLiterals.DefaultPathSeparator); + for (int i = 0; i < items.Length; i++) { if (itemsToSkip-- > 0) { // This handles the UNC server and share and 8.3 short path syntax - exactPath += item + StringLiterals.DefaultPathSeparator; + exactPath += items[i] + StringLiterals.DefaultPathSeparator; continue; } else if (string.IsNullOrEmpty(exactPath)) { // This handles the drive letter or / root path start - exactPath = item + StringLiterals.DefaultPathSeparator; + exactPath = items[i] + StringLiterals.DefaultPathSeparator; } - else if (string.IsNullOrEmpty(item)) + else if (string.IsNullOrEmpty(items[i]) && i == items.Length - 1) { // This handles the trailing slash case if (!exactPath.EndsWith(StringLiterals.DefaultPathSeparator)) @@ -163,17 +161,17 @@ private static string GetCorrectCasedPath(string path) break; } - else if (item.Contains('~')) + else if (items[i].Contains('~')) { // This handles short path names - exactPath += StringLiterals.DefaultPathSeparator + item; + exactPath += StringLiterals.DefaultPathSeparator + items[i]; } else { // Use GetFileSystemEntries to get the correct casing of this element try { - var entries = Directory.GetFileSystemEntries(exactPath, item); + var entries = Directory.GetFileSystemEntries(exactPath, items[i]); if (entries.Length > 0) { exactPath = entries[0]; @@ -478,13 +476,12 @@ protected override ProviderInfo Start(ProviderInfo providerInfo) #if !UNIX // The placeholder mode management APIs Rtl(Set|Query)(Process|Thread)PlaceholderCompatibilityMode // are only supported starting with Windows 10 version 1803 (build 17134) - Version minBuildForPlaceHolderAPIs = new Version(10, 0, 17134, 0); - if (Environment.OSVersion.Version >= minBuildForPlaceHolderAPIs) + if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 17134, 0)) { // let's be safe, don't change the PlaceHolderCompatibilityMode if the current one is not what we expect - if (NativeMethods.PHCM_DISGUISE_PLACEHOLDER == NativeMethods.RtlQueryProcessPlaceholderCompatibilityMode()) + if (Interop.Windows.RtlQueryProcessPlaceholderCompatibilityMode() == Interop.Windows.PHCM_DISGUISE_PLACEHOLDER) { - NativeMethods.RtlSetProcessPlaceholderCompatibilityMode(NativeMethods.PHCM_EXPOSE_PLACEHOLDERS); + Interop.Windows.RtlSetProcessPlaceholderCompatibilityMode(Interop.Windows.PHCM_EXPOSE_PLACEHOLDERS); } } #endif @@ -536,7 +533,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) { // MapNetworkDrive facilitates to map the newly // created PS Drive to a network share. - this.MapNetworkDrive(drive); + MapNetworkDrive(drive); } // The drive is valid if the item exists or the @@ -572,7 +569,7 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) if (driveIsFixed) { // Since the drive is fixed, ensure the root is valid. - validDrive = Directory.Exists(drive.Root); + validDrive = SafeDoesPathExist(drive.Root); } if (validDrive) @@ -595,35 +592,18 @@ protected override PSDriveInfo NewDrive(PSDriveInfo drive) /// MapNetworkDrive facilitates to map the newly created PS Drive to a network share. /// /// The PSDrive info that would be used to create a new PS drive. + [SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Justification = "Can be static on Unix but not on Windows.")] + private void MapNetworkDrive(PSDriveInfo drive) { +#if UNIX + throw new PlatformNotSupportedException(); +#else // Porting note: mapped network drives are only supported on Windows - if (Platform.IsWindows) - { - WinMapNetworkDrive(drive); - } - else - { - throw new PlatformNotSupportedException(); - } - } - - private static bool _WNetApiAvailable = true; - - private void WinMapNetworkDrive(PSDriveInfo drive) - { if (drive != null && !string.IsNullOrEmpty(drive.Root)) { - const int CONNECT_UPDATE_PROFILE = 0x00000001; - const int CONNECT_NOPERSIST = 0x00000000; - const int RESOURCE_GLOBALNET = 0x00000002; - const int RESOURCETYPE_ANY = 0x00000000; - const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000; - const int RESOURCEUSAGE_CONNECTABLE = 0x00000001; - const int ERROR_NO_NETWORK = 1222; - // By default the connection is not persisted. - int CONNECT_TYPE = CONNECT_NOPERSIST; + int connectType = Interop.Windows.CONNECT_NOPERSIST; string driveName = null; byte[] passwd = null; @@ -633,13 +613,12 @@ private void WinMapNetworkDrive(PSDriveInfo drive) { if (IsSupportedDriveForPersistence(drive)) { - CONNECT_TYPE = CONNECT_UPDATE_PROFILE; + connectType = Interop.Windows.CONNECT_UPDATE_PROFILE; driveName = drive.Name + ":"; drive.DisplayRoot = drive.Root; } else { - // error. ErrorRecord er = new ErrorRecord(new InvalidOperationException(FileSystemProviderStrings.InvalidDriveName), "DriveNameNotSupportedForPersistence", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } @@ -655,37 +634,15 @@ private void WinMapNetworkDrive(PSDriveInfo drive) try { - NetResource resource = new NetResource(); - resource.Comment = null; - resource.DisplayType = RESOURCEDISPLAYTYPE_GENERIC; - resource.LocalName = driveName; - resource.Provider = null; - resource.RemoteName = drive.Root; - resource.Scope = RESOURCE_GLOBALNET; - resource.Type = RESOURCETYPE_ANY; - resource.Usage = RESOURCEUSAGE_CONNECTABLE; - - int code = ERROR_NO_NETWORK; - - if (_WNetApiAvailable) - { - try - { - code = NativeMethods.WNetAddConnection2(ref resource, passwd, userName, CONNECT_TYPE); - } - catch (System.DllNotFoundException) - { - _WNetApiAvailable = false; - } - } + int errorCode = Interop.Windows.WNetAddConnection2(driveName, drive.Root, passwd, userName, connectType); - if (code != 0) + if (errorCode != Interop.Windows.ERROR_SUCCESS) { - ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive); + ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(errorCode), "CouldNotMapNetworkDrive", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } - if (CONNECT_TYPE == CONNECT_UPDATE_PROFILE) + if (connectType == Interop.Windows.CONNECT_UPDATE_PROFILE) { // Update the current PSDrive to be a persisted drive. drive.IsNetworkDrive = true; @@ -700,10 +657,11 @@ private void WinMapNetworkDrive(PSDriveInfo drive) // Clear the password in the memory. if (passwd != null) { - Array.Clear(passwd, 0, passwd.Length - 1); + Array.Clear(passwd); } } } +#endif } /// @@ -733,23 +691,14 @@ protected override PSDriveInfo RemoveDrive(PSDriveInfo drive) #if UNIX return drive; #else - return WinRemoveDrive(drive); -#endif - } - - private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) - { if (IsNetworkMappedDrive(drive)) { - const int CONNECT_UPDATE_PROFILE = 0x00000001; - const int ERROR_NO_NETWORK = 1222; - - int flags = 0; + int flags = Interop.Windows.CONNECT_NOPERSIST; string driveName; if (drive.IsNetworkDrive) { // Here we are removing only persisted network drives. - flags = CONNECT_UPDATE_PROFILE; + flags = Interop.Windows.CONNECT_UPDATE_PROFILE; driveName = drive.Name + ":"; } else @@ -760,28 +709,17 @@ private PSDriveInfo WinRemoveDrive(PSDriveInfo drive) } // You need to actually remove the drive. - int code = ERROR_NO_NETWORK; - - if (_WNetApiAvailable) - { - try - { - code = NativeMethods.WNetCancelConnection2(driveName, flags, true); - } - catch (System.DllNotFoundException) - { - _WNetApiAvailable = false; - } - } + int errorCode = Interop.Windows.WNetCancelConnection2(driveName, flags, force: true); - if (code != 0) + if (errorCode != Interop.Windows.ERROR_SUCCESS) { - ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(code), "CouldRemoveNetworkDrive", ErrorCategory.InvalidOperation, drive); + ErrorRecord er = new ErrorRecord(new System.ComponentModel.Win32Exception(errorCode), "CouldRemoveNetworkDrive", ErrorCategory.InvalidOperation, drive); ThrowTerminatingError(er); } } return drive; +#endif } /// @@ -819,57 +757,19 @@ internal static string GetUNCForNetworkDrive(string driveName) #if UNIX return driveName; #else - return WinGetUNCForNetworkDrive(driveName); -#endif - } - - private static string WinGetUNCForNetworkDrive(string driveName) - { - const int ERROR_NO_NETWORK = 1222; string uncPath = null; if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1) { - // By default buffer size is set to 300 which would generally be sufficient in most of the cases. - int bufferSize = 300; -#if DEBUG - // In Debug mode buffer size is initially set to 3 and if additional buffer is required, the - // required buffer size is allocated and the WNetGetConnection API is executed with the newly - // allocated buffer size. - bufferSize = 3; -#endif + int errorCode = Interop.Windows.GetUNCForNetworkDrive(driveName[0], out uncPath); - StringBuilder uncBuffer = new StringBuilder(bufferSize); - driveName += ':'; - - // Call the windows API - int errorCode = ERROR_NO_NETWORK; - - try - { - errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize); - } - catch (System.DllNotFoundException) - { - return null; - } - - // error code 234 is returned whenever the required buffer size is greater - // than the specified buffer size. - if (errorCode == 234) - { - uncBuffer = new StringBuilder(bufferSize); - errorCode = NativeMethods.WNetGetConnection(driveName, uncBuffer, ref bufferSize); - } - - if (errorCode != 0) + if (errorCode != Interop.Windows.ERROR_SUCCESS) { throw new System.ComponentModel.Win32Exception(errorCode); } - - uncPath = uncBuffer.ToString(); } return uncPath; +#endif } /// @@ -887,9 +787,9 @@ internal static string GetSubstitutedPathForNetworkDosDevice(string driveName) { #if UNIX throw new PlatformNotSupportedException(); + } #else return WinGetSubstitutedPathForNetworkDosDevice(driveName); -#endif } private static string WinGetSubstitutedPathForNetworkDosDevice(string driveName) @@ -897,76 +797,12 @@ private static string WinGetSubstitutedPathForNetworkDosDevice(string driveName) string associatedPath = null; if (!string.IsNullOrEmpty(driveName) && driveName.Length == 1) { - // By default buffer size is set to 300 which would generally be sufficient in most of the cases. - int bufferSize = 300; - var pathInfo = new StringBuilder(bufferSize); - driveName += ':'; - - // Call the windows API - while (true) - { - pathInfo.EnsureCapacity(bufferSize); - int retValue = NativeMethods.QueryDosDevice(driveName, pathInfo, bufferSize); - if (retValue > 0) - { - // If the drive letter is a substed path, the result will be in the format of - // - "\??\C:\RealPath" for local path - // - "\??\UNC\RealPath" for network path - associatedPath = pathInfo.ToString(); - if (associatedPath.StartsWith("\\??\\", StringComparison.OrdinalIgnoreCase)) - { - associatedPath = associatedPath.Remove(0, 4); - if (associatedPath.StartsWith("UNC", StringComparison.OrdinalIgnoreCase)) - { - associatedPath = associatedPath.Remove(0, 3); - associatedPath = "\\" + associatedPath; - } - else if (associatedPath.EndsWith(':')) - { - // The substed path is the root path of a drive. For example: subst Y: C:\ - associatedPath += Path.DirectorySeparatorChar; - } - } - else - { - // The drive name is not a substed path, then we return the root path of the drive - associatedPath = driveName + "\\"; - } - - break; - } - - // Windows API call failed - int errorCode = Marshal.GetLastWin32Error(); - if (errorCode != 122) - { - // ERROR_INSUFFICIENT_BUFFER = 122 - // For an error other than "insufficient buffer", throw it - throw new Win32Exception((int)errorCode); - } - - // We got the "insufficient buffer" error. In this case we extend - // the buffer size, unless it's unreasonably too large. - if (bufferSize >= 32767) - { - // "The Windows API has many functions that also have Unicode versions to permit - // an extended-length path for a maximum total path length of 32,767 characters" - // See https://msdn.microsoft.com/library/aa365247.aspx#maxpath - string errorMsg = StringUtil.Format(FileSystemProviderStrings.SubstitutePathTooLong, driveName); - throw new InvalidOperationException(errorMsg); - } - - // Extend the buffer size and try again. - bufferSize *= 10; - if (bufferSize > 32767) - { - bufferSize = 32767; - } - } + associatedPath = Interop.Windows.GetDosDeviceForNetworkPath(driveName[0]); } return associatedPath; } +#endif /// /// Get the root path for a network drive or MS-DOS device. @@ -1072,7 +908,7 @@ protected override Collection InitializeDefaultDrives() if (newDrive.DriveType == DriveType.Fixed) { - if (!newDrive.RootDirectory.Exists) + if (!SafeDoesPathExist(newDrive.RootDirectory.FullName)) { continue; } @@ -1245,6 +1081,20 @@ protected override bool IsValidPath(string path) } } + // .NET introduced a change where invalid characters are accepted https://learn.microsoft.com/en-us/dotnet/core/compatibility/2.1#path-apis-dont-throw-an-exception-for-invalid-characters + // We need to check for invalid characters ourselves. `Path.GetInvalidFileNameChars()` is a supserset of `Path.GetInvalidPathChars()` + + // Remove drive root first + string pathWithoutDriveRoot = path.Substring(Path.GetPathRoot(path).Length); + + foreach (string segment in pathWithoutDriveRoot.Split(Path.DirectorySeparatorChar)) + { + if (PathUtils.ContainsInvalidFileNameChars(segment)) + { + return false; + } + } + return true; } @@ -1367,7 +1217,7 @@ protected override void GetItem(string path) } catch (IOException ioError) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. ErrorRecord er = new ErrorRecord(ioError, "GetItemIOError", ErrorCategory.ReadError, path); WriteError(er); } @@ -1377,18 +1227,46 @@ protected override void GetItem(string path) } } + private static bool SafeDoesPathExist(string rootDirectory) + { + if (Directory.Exists(rootDirectory)) + { + return true; + } + + try + { + return (File.GetAttributes(rootDirectory) & FileAttributes.Directory) is not 0; + } + // In some scenarios (like AppContainers) direct access to the root directory may + // be prevented, but more specific paths may be accessible. + catch (UnauthorizedAccessException) + { + return true; + } + catch + { + return false; + } + } + private FileSystemInfo GetFileSystemItem(string path, ref bool isContainer, bool showHidden) { path = NormalizePath(path); FileInfo result = new FileInfo(path); - // FileInfo.Exists is always false for a directory path, so we check the attribute for existence. var attributes = result.Attributes; - if ((int)attributes == -1) { /* Path doesn't exist. */ return null; } - bool hidden = attributes.HasFlag(FileAttributes.Hidden); isContainer = attributes.HasFlag(FileAttributes.Directory); + // FileInfo allows for a file path to end in a trailing slash, but the resulting object + // is incomplete. A trailing slash should indicate a directory. So if the path ends in a + // trailing slash and is not a directory, return null + if (!isContainer && path.EndsWith(Path.DirectorySeparatorChar)) + { + return null; + } + FlagsExpression evaluator = null; FlagsExpression switchEvaluator = null; GetChildDynamicParameters fspDynamicParam = DynamicParameters as GetChildDynamicParameters; @@ -1469,6 +1347,7 @@ protected override void InvokeDefaultAction(string path) if (ShouldProcess(resource, action)) { var invokeProcess = new System.Diagnostics.Process(); + // 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. If there is concern for remoting, restricted remoting guidelines should be used. invokeProcess.StartInfo.FileName = path; #if UNIX bool useShellExecute = false; @@ -1790,7 +1669,7 @@ private void Dir( foreach (IEnumerable childList in target) { // On some systems, this is already sorted. For consistency, always sort again. - IEnumerable sortedChildList = childList.OrderBy(c => c.Name, StringComparer.CurrentCultureIgnoreCase); + IEnumerable sortedChildList = childList.OrderBy(static c => c.Name, StringComparer.CurrentCultureIgnoreCase); foreach (FileSystemInfo filesystemInfo in sortedChildList) { @@ -1899,9 +1778,14 @@ private void Dir( } bool hidden = false; + bool checkReparsePoint = true; if (!Force) { hidden = (recursiveDirectory.Attributes & FileAttributes.Hidden) != 0; + + // We've already taken the expense of initializing the Attributes property here, + // so we can use that to avoid needing to call IsReparsePointLikeSymlink() later. + checkReparsePoint = recursiveDirectory.Attributes.HasFlag(FileAttributes.ReparsePoint); } // if "Hidden" is explicitly specified anywhere in the attribute filter, then override @@ -1915,7 +1799,7 @@ private void Dir( // c) it is not a reparse point with a target (not OneDrive or an AppX link). if (tracker == null) { - if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointWithTarget(recursiveDirectory)) + if (checkReparsePoint && InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(recursiveDirectory)) { continue; } @@ -2042,15 +1926,16 @@ string ToModeString(FileSystemInfo fileSystemInfo) } } - bool isDirectory = fileAttributes.HasFlag(FileAttributes.Directory); - ReadOnlySpan mode = stackalloc char[] - { - isLink ? 'l' : isDirectory ? 'd' : '-', + ReadOnlySpan mode = + [ + isLink ? + 'l' : + fileAttributes.HasFlag(FileAttributes.Directory) ? 'd' : '-', fileAttributes.HasFlag(FileAttributes.Archive) ? 'a' : '-', fileAttributes.HasFlag(FileAttributes.ReadOnly) ? 'r' : '-', fileAttributes.HasFlag(FileAttributes.Hidden) ? 'h' : '-', fileAttributes.HasFlag(FileAttributes.System) ? 's' : '-', - }; + ]; return new string(mode); } @@ -2066,11 +1951,32 @@ string ToModeString(FileSystemInfo fileSystemInfo) /// Name if a file or directory, Name -> Target if symlink. public static string NameString(PSObject instance) { - return instance?.BaseObject is FileSystemInfo fileInfo - ? InternalSymbolicLinkLinkCodeMethods.IsReparsePointWithTarget(fileInfo) - ? $"{fileInfo.Name} -> {InternalSymbolicLinkLinkCodeMethods.GetTarget(instance)}" - : fileInfo.Name - : string.Empty; + if (instance?.BaseObject is FileSystemInfo fileInfo) + { + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(fileInfo)) + { + return $"{PSStyle.Instance.FileInfo.SymbolicLink}{fileInfo.Name}{PSStyle.Instance.Reset} -> {fileInfo.LinkTarget}"; + } + else if (fileInfo.Attributes.HasFlag(FileAttributes.Directory)) + { + return $"{PSStyle.Instance.FileInfo.Directory}{fileInfo.Name}{PSStyle.Instance.Reset}"; + } + else if (PSStyle.Instance.FileInfo.Extension.ContainsKey(fileInfo.Extension)) + { + return $"{PSStyle.Instance.FileInfo.Extension[fileInfo.Extension]}{fileInfo.Name}{PSStyle.Instance.Reset}"; + } + else if ((Platform.IsWindows && CommandDiscovery.PathExtensions.Contains(fileInfo.Extension.ToLower())) || + (!Platform.IsWindows && Platform.NonWindowsIsExecutable(fileInfo.FullName))) + { + return $"{PSStyle.Instance.FileInfo.Executable}{fileInfo.Name}{PSStyle.Instance.Reset}"; + } + else + { + return fileInfo.Name; + } + } + + return string.Empty; } /// @@ -2095,7 +2001,7 @@ public static string LengthString(PSObject instance) public static string LastWriteTimeString(PSObject instance) { return instance?.BaseObject is FileSystemInfo fileInfo - ? string.Format(CultureInfo.CurrentCulture, "{0,10:d} {0,8:t}", fileInfo.LastWriteTime) + ? string.Create(CultureInfo.CurrentCulture, $"{fileInfo.LastWriteTime,10:d} {fileInfo.LastWriteTime,8:t}") : string.Empty; } @@ -2221,7 +2127,7 @@ protected override void RenameItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "RenameItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -2240,7 +2146,7 @@ protected override void RenameItem( /// /// The path of the file or directory to create. /// - /// + /// /// Specify "file" to create a file. /// Specify "directory" or "container" to create a directory. /// @@ -2333,7 +2239,7 @@ protected override void NewItem( } catch (IOException exception) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(exception, "NewItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -2376,19 +2282,23 @@ protected override void NewItem( { exists = true; - var normalizedTargetPath = strTargetPath; - if (strTargetPath.StartsWith(".\\", StringComparison.OrdinalIgnoreCase) || - strTargetPath.StartsWith("./", StringComparison.OrdinalIgnoreCase)) - { - normalizedTargetPath = Path.Join(SessionState.Internal.CurrentLocation.ProviderPath, strTargetPath.AsSpan(2)); - } + // unify directory separators to be consistent with the rest of PowerShell even on non-Windows platforms; + // do this before resolving the target, otherwise e.g. `.\test` would break on Linux, since the combined + // path below would be something like `/path/to/cwd/.\test` + strTargetPath = strTargetPath.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); + // check if the target is a file or directory + var normalizedTargetPath = Path.Combine(Path.GetDirectoryName(path), strTargetPath); GetFileSystemInfo(normalizedTargetPath, out isDirectory); - - strTargetPath = strTargetPath.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); } else { + // for hardlinks we resolve the target to an absolute path + if (!IsAbsolutePath(strTargetPath)) + { + strTargetPath = SessionState.Path.GetUnresolvedProviderPathFromPSPath(strTargetPath); + } + exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; } } @@ -2431,6 +2341,13 @@ protected override void NewItem( if (Force) { + if (itemType == ItemType.HardLink && string.Equals(path, strTargetPath, StringComparison.OrdinalIgnoreCase)) + { + string message = StringUtil.Format(FileSystemProviderStrings.NewItemTargetIsSameAsLink, path); + WriteError(new ErrorRecord(new InvalidOperationException(message), "TargetIsSameAsLink", ErrorCategory.InvalidOperation, path)); + return; + } + try { if (!isSymLinkDirectory && symLinkExists) @@ -2487,7 +2404,7 @@ protected override void NewItem( #if UNIX success = Platform.NonWindowsCreateHardLink(path, strTargetPath); #else - success = WinCreateHardLink(path, strTargetPath); + success = Interop.Windows.CreateHardLink(path, strTargetPath, IntPtr.Zero); #endif } @@ -2554,6 +2471,13 @@ protected override void NewItem( bool exists = false; + // junctions require an absolute path + if (!Path.IsPathRooted(strTargetPath)) + { + WriteError(new ErrorRecord(new ArgumentException(FileSystemProviderStrings.JunctionAbsolutePath), "NotAbsolutePath", ErrorCategory.InvalidArgument, strTargetPath)); + return; + } + try { exists = GetFileSystemInfo(strTargetPath, out isDirectory) != null; @@ -2605,40 +2529,35 @@ protected override void NewItem( } // Junctions cannot have files - if (DirectoryInfoHasChildItems((DirectoryInfo)pathDirInfo)) + if (!Force && DirectoryInfoHasChildItems((DirectoryInfo)pathDirInfo)) { string message = StringUtil.Format(FileSystemProviderStrings.DirectoryNotEmpty, path); WriteError(new ErrorRecord(new IOException(message), "DirectoryNotEmpty", ErrorCategory.WriteError, path)); return; } - if (Force) + try { - try + pathDirInfo.Delete(); + } + catch (Exception exception) + { + if ((exception is DirectoryNotFoundException) || + (exception is UnauthorizedAccessException) || + (exception is System.Security.SecurityException) || + (exception is IOException)) { - pathDirInfo.Delete(); + WriteError(new ErrorRecord(exception, "NewItemDeleteIOError", ErrorCategory.WriteError, path)); } - catch (Exception exception) + else { - if ((exception is DirectoryNotFoundException) || - (exception is UnauthorizedAccessException) || - (exception is System.Security.SecurityException) || - (exception is IOException)) - { - WriteError(new ErrorRecord(exception, "NewItemDeleteIOError", ErrorCategory.WriteError, path)); - } - else - { - throw; - } + throw; } } } - else - { - CreateDirectory(path, false); - pathDirInfo = new DirectoryInfo(path); - } + + CreateDirectory(path, streamOutput: false); + pathDirInfo = new DirectoryInfo(path); try { @@ -2690,26 +2609,21 @@ protected override void NewItem( } } +#if !UNIX private static bool WinCreateSymbolicLink(string path, string strTargetPath, bool isDirectory) { // The new AllowUnprivilegedCreate is only available on Win10 build 14972 or newer - var flags = isDirectory ? NativeMethods.SymbolicLinkFlags.Directory : NativeMethods.SymbolicLinkFlags.File; + var flags = isDirectory ? Interop.Windows.SymbolicLinkFlags.Directory : Interop.Windows.SymbolicLinkFlags.File; - Version minBuildOfDeveloperMode = new Version(10, 0, 14972, 0); - if (Environment.OSVersion.Version >= minBuildOfDeveloperMode) + if (OperatingSystem.IsWindowsVersionAtLeast(10, 0, 14972, 0)) { - flags |= NativeMethods.SymbolicLinkFlags.AllowUnprivilegedCreate; + flags |= Interop.Windows.SymbolicLinkFlags.AllowUnprivilegedCreate; } - var created = NativeMethods.CreateSymbolicLink(path, strTargetPath, flags); + var created = Interop.Windows.CreateSymbolicLink(path, strTargetPath, flags); return created; } - - private static bool WinCreateHardLink(string path, string strTargetPath) - { - bool success = NativeMethods.CreateHardLink(path, strTargetPath, IntPtr.Zero); - return success; - } +#endif private static bool WinCreateJunction(string path, string strTargetPath) { @@ -2776,12 +2690,6 @@ private void CreateDirectory(string path, bool streamOutput) !string.IsNullOrEmpty(path), "The caller should verify path"); - // Get the parent path - string parentPath = GetParentPath(path, null); - - // The directory name - string childName = GetChildName(path); - ErrorRecord error = null; if (!Force && ItemExists(path, out error)) { @@ -2811,7 +2719,7 @@ private void CreateDirectory(string path, bool streamOutput) if (ShouldProcess(resource, action)) { - var result = Directory.CreateDirectory(Path.Combine(parentPath, childName)); + var result = Directory.CreateDirectory(path); if (streamOutput) { @@ -2826,10 +2734,17 @@ private void CreateDirectory(string path, bool streamOutput) } catch (IOException ioException) { - // Ignore the error if force was specified +#if UNIX if (!Force) +#else + // Windows error code for invalid characters in file or directory name + const int ERROR_INVALID_NAME = unchecked((int)0x8007007B); + + // Do not suppress IOException on Windows if it has the specific HResult for invalid characters in directory name + if (ioException.HResult == ERROR_INVALID_NAME || !Force) +#endif { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CreateDirectoryIOError", ErrorCategory.WriteError, path)); } } @@ -2904,7 +2819,7 @@ private bool CreateIntermediateDirectories(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CreateIntermediateDirectoriesIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -2983,6 +2898,19 @@ protected override void RemoveItem(string path, bool recurse) return; } + if (Context != null + && Context.ExecutionContext.SessionState.PSVariable.Get(SpecialVariables.ProgressPreferenceVarPath.UserPath).Value is ActionPreference progressPreference + && progressPreference == ActionPreference.Continue) + { + { + Task.Run(() => + { + GetTotalFiles(path, recurse); + }); + _removeStopwatch.Start(); + } + } + #if UNIX if (iscontainer) { @@ -3010,7 +2938,10 @@ protected override void RemoveItem(string path, bool recurse) foreach (AlternateStreamData stream in AlternateDataStreamUtilities.GetStreams(fsinfo.FullName)) { - if (!p.IsMatch(stream.Stream)) { continue; } + if (!p.IsMatch(stream.Stream)) + { + continue; + } foundStream = true; @@ -3043,11 +2974,21 @@ protected override void RemoveItem(string path, bool recurse) RemoveFileInfoItem((FileInfo)fsinfo, Force); } } + + if (Stopping || _removedFiles == _totalFiles) + { + _removeStopwatch.Stop(); + var progress = new ProgressRecord(REMOVE_FILE_ACTIVITY_ID, " ", " ") + { + RecordType = ProgressRecordType.Completed + }; + WriteProgress(progress); + } #endif } catch (IOException exception) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(exception, "RemoveItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -3107,22 +3048,31 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool continueRemoval = ShouldProcess(directory.FullName, action); } - if (directory.Attributes.HasFlag(FileAttributes.ReparsePoint)) + if (InternalSymbolicLinkLinkCodeMethods.IsReparsePointLikeSymlink(directory)) { + void WriteErrorHelper(Exception exception) + { + WriteError(new ErrorRecord(exception, errorId: "DeleteSymbolicLinkFailed", ErrorCategory.WriteError, directory)); + } + try { - // TODO: - // Different symlinks seem to vary by behavior. - // In particular, OneDrive symlinks won't remove without recurse, - // but the .NET API here does not allow us to distinguish them. - // We may need to revisit using p/Invokes here to get the right behavior - directory.Delete(); + if (InternalTestHooks.OneDriveTestOn) + { + WriteErrorHelper(new IOException()); + return; + } + else + { + // Name surrogates should just be detached. + directory.Delete(); + } } catch (Exception e) { string error = StringUtil.Format(FileSystemProviderStrings.CannotRemoveItem, directory.FullName, e.Message); var exception = new IOException(error, e); - WriteError(new ErrorRecord(exception, errorId: "DeleteSymbolicLinkFailed", ErrorCategory.WriteError, directory)); + WriteErrorHelper(exception); } return; @@ -3168,6 +3118,8 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool if (file != null) { + long fileBytesSize = file.Length; + if (recurse) { // When recurse is specified we need to confirm each @@ -3180,6 +3132,25 @@ private void RemoveDirectoryInfoItem(DirectoryInfo directory, bool recurse, bool // subitems without confirming with the user. RemoveFileSystemItem(file, force); } + + if (_totalFiles > 0) + { + _removedFiles++; + _removedBytes += fileBytesSize; + if (_removeStopwatch.Elapsed.TotalSeconds > ProgressBarDurationThreshold) + { + double speed = _removedBytes / 1024 / 1024 / _removeStopwatch.Elapsed.TotalSeconds; + var progress = new ProgressRecord( + REMOVE_FILE_ACTIVITY_ID, + StringUtil.Format(FileSystemProviderStrings.RemovingLocalFileActivity, _removedFiles, _totalFiles), + StringUtil.Format(FileSystemProviderStrings.RemovingLocalBytesStatus, Utils.DisplayHumanReadableFileSize(_removedBytes), Utils.DisplayHumanReadableFileSize(_totalBytes), speed) + ); + var percentComplete = _totalBytes != 0 ? (int)Math.Min(_removedBytes * 100 / _totalBytes, 100) : 100; + progress.PercentComplete = percentComplete; + progress.RecordType = ProgressRecordType.Processing; + WriteProgress(progress); + } + } } } @@ -3430,12 +3401,12 @@ private bool ItemExists(string path, out ErrorRecord error) if (itemExistsDynamicParameters.OlderThan.HasValue) { - result = lastWriteTime < itemExistsDynamicParameters.OlderThan.Value; + result &= lastWriteTime < itemExistsDynamicParameters.OlderThan.Value; } if (itemExistsDynamicParameters.NewerThan.HasValue) { - result = lastWriteTime > itemExistsDynamicParameters.NewerThan.Value; + result &= lastWriteTime > itemExistsDynamicParameters.NewerThan.Value; } } } @@ -3668,7 +3639,25 @@ protected override void CopyItem( } else // Copy-Item local { + if (Context != null && Context.ExecutionContext.SessionState.PSVariable.Get(SpecialVariables.ProgressPreferenceVarPath.UserPath).Value is ActionPreference progressPreference && progressPreference == ActionPreference.Continue) + { + { + Task.Run(() => + { + GetTotalFiles(path, recurse); + }); + _copyStopwatch.Start(); + } + } + CopyItemLocalOrToSession(path, destinationPath, recurse, Force, null); + if (Stopping || _copiedFiles == _totalFiles) + { + _copyStopwatch.Stop(); + var progress = new ProgressRecord(COPY_FILE_ACTIVITY_ID, " ", " "); + progress.RecordType = ProgressRecordType.Completed; + WriteProgress(progress); + } } } @@ -3676,27 +3665,68 @@ protected override void CopyItem( _excludeMatcher = null; } - private void CopyItemFromRemoteSession(string path, string destinationPath, bool recurse, bool force, PSSession fromSession) + private void GetTotalFiles(string path, bool recurse) { - using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) - { - ps.Runspace = fromSession.Runspace; - - InitializeFunctionPSCopyFileFromRemoteSession(ps); + bool isContainer = IsItemContainer(path); - try + try + { + if (isContainer) { - // get info on source - ps.AddCommand(CopyFileRemoteUtils.PSCopyFromSessionHelperName); - ps.AddParameter("getPathItems", path); - - Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); - if (op == null) + var enumOptions = new EnumerationOptions() { - Exception e = new IOException(string.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemRemotelyFailedToReadFile, path)); - WriteError(new ErrorRecord(e, "CopyItemRemotelyFailedToReadFile", ErrorCategory.WriteError, path)); - return; - } + IgnoreInaccessible = true, + AttributesToSkip = 0, + RecurseSubdirectories = recurse + }; + + var directory = new DirectoryInfo(path); + foreach (var file in directory.EnumerateFiles("*", enumOptions)) + { + if (!SessionStateUtilities.MatchesAnyWildcardPattern(file.Name, _excludeMatcher, defaultValue: false)) + { + _totalFiles++; + _totalBytes += file.Length; + } + } + } + else + { + var file = new FileInfo(path); + if (!SessionStateUtilities.MatchesAnyWildcardPattern(file.Name, _excludeMatcher, defaultValue: false)) + { + _totalFiles++; + _totalBytes += file.Length; + } + } + } + catch + { + // ignore exception + } + } + + private void CopyItemFromRemoteSession(string path, string destinationPath, bool recurse, bool force, PSSession fromSession) + { + using (System.Management.Automation.PowerShell ps = System.Management.Automation.PowerShell.Create()) + { + ps.Runspace = fromSession.Runspace; + + InitializeFunctionPSCopyFileFromRemoteSession(ps); + + try + { + // get info on source + ps.AddCommand(CopyFileRemoteUtils.PSCopyFromSessionHelperName); + ps.AddParameter("getPathItems", path); + + Hashtable op = SafeInvokeCommand.Invoke(ps, this, null); + if (op == null) + { + Exception e = new IOException(string.Format(CultureInfo.InvariantCulture, FileSystemProviderStrings.CopyItemRemotelyFailedToReadFile, path)); + WriteError(new ErrorRecord(e, "CopyItemRemotelyFailedToReadFile", ErrorCategory.WriteError, path)); + return; + } bool exists = (bool)(op["Exists"]); if (!exists) @@ -3887,7 +3917,7 @@ private void CopyDirectoryInfoItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CopyDirectoryInfoItemIOError", ErrorCategory.WriteError, file)); } catch (UnauthorizedAccessException accessException) @@ -3918,7 +3948,7 @@ private void CopyDirectoryInfoItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "CopyDirectoryInfoItemIOError", ErrorCategory.WriteError, childDir)); } catch (UnauthorizedAccessException accessException) @@ -3984,6 +4014,25 @@ private void CopyFileInfoItem(FileInfo file, string destinationPath, bool force, FileInfo result = new FileInfo(destinationPath); WriteItemObject(result, destinationPath, false); + + if (_totalFiles > 0) + { + _copiedFiles++; + _copiedBytes += file.Length; + if (_copyStopwatch.Elapsed.TotalSeconds > ProgressBarDurationThreshold) + { + double speed = (double)(_copiedBytes / 1024 / 1024) / _copyStopwatch.Elapsed.TotalSeconds; + var progress = new ProgressRecord( + COPY_FILE_ACTIVITY_ID, + StringUtil.Format(FileSystemProviderStrings.CopyingLocalFileActivity, _copiedFiles, _totalFiles), + StringUtil.Format(FileSystemProviderStrings.CopyingLocalBytesStatus, Utils.DisplayHumanReadableFileSize(_copiedBytes), Utils.DisplayHumanReadableFileSize(_totalBytes), speed) + ); + var percentComplete = _totalBytes != 0 ? (int)Math.Min(_copiedBytes * 100 / _totalBytes, 100) : 100; + progress.PercentComplete = percentComplete; + progress.RecordType = ProgressRecordType.Processing; + WriteProgress(progress); + } + } } else { @@ -4424,7 +4473,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf } } - // To accomodate empty files + // To accommodate empty files string content = string.Empty; if (op["b64Fragment"] != null) { @@ -4478,10 +4527,7 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf } finally { - if (wStream != null) - { - wStream.Dispose(); - } + wStream?.Dispose(); // If copying the file from the remote session failed, then remove it. if (errorWhileCopyRemoteFile && File.Exists(destinationFile.FullName)) @@ -4500,7 +4546,10 @@ private bool PerformCopyFileFromRemoteSession(string sourceFileFullName, FileInf private void InitializeFunctionsPSCopyFileToRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) + { + return; + } ps.AddScript(CopyFileRemoteUtils.AllCopyToRemoteScripts); SafeInvokeCommand.Invoke(ps, this, null, false); @@ -4508,7 +4557,10 @@ private void InitializeFunctionsPSCopyFileToRemoteSession(System.Management.Auto private void RemoveFunctionPSCopyFileToRemoteSession(System.Management.Automation.PowerShell ps) { - if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) { return; } + if ((ps == null) || !ValidRemoteSessionForScripting(ps.Runspace)) + { + return; + } const string remoteScript = @" Microsoft.PowerShell.Management\Remove-Item function:PSCopyToSessionHelper -ea SilentlyContinue -Force @@ -4761,10 +4813,7 @@ private bool CopyFileStreamToRemoteSession(FileInfo file, string destinationPath } finally { - if (fStream != null) - { - fStream.Dispose(); - } + fStream?.Dispose(); } return success; @@ -4914,6 +4963,17 @@ private bool PathIsReservedDeviceName(string destinationPath, string errorId) return pathIsReservedDeviceName; } + private long _totalFiles; + private long _totalBytes; + private long _copiedFiles; + private long _copiedBytes; + private readonly Stopwatch _copyStopwatch = new Stopwatch(); + + private long _removedBytes; + private long _removedFiles; + private readonly Stopwatch _removeStopwatch = new(); + + private const double ProgressBarDurationThreshold = 2.0; #endregion CopyItem #endregion ContainerCmdletProvider members @@ -4945,30 +5005,30 @@ protected override string GetParentPath(string path, string root) // make sure we return two backslashes so it still results in a UNC path parentPath = "\\\\"; } + + if (!parentPath.EndsWith(StringLiterals.DefaultPathSeparator) + && Utils.PathIsDevicePath(parentPath) + && parentPath.Length - parentPath.Replace(StringLiterals.DefaultPathSeparatorString, string.Empty).Length == 3) + { + // Device paths start with either "\\.\" or "\\?\" + // When referring to the root, like: "\\.\CDROM0\" then it needs the trailing separator to be valid. + parentPath += StringLiterals.DefaultPathSeparator; + } #endif + s_tracer.WriteLine("GetParentPath returning '{0}'", parentPath); return parentPath; } // Note: we don't use IO.Path.IsPathRooted as this deals with "invalid" i.e. unnormalized paths private static bool IsAbsolutePath(string path) { - bool result = false; - // check if we're on a single root filesystem and it's an absolute path if (LocationGlobber.IsSingleFileSystemAbsolutePath(path)) { return true; } - // Find the drive separator - int index = path.IndexOf(':'); - - if (index != -1) - { - result = true; - } - - return result; + return path.Contains(':'); } /// @@ -5075,10 +5135,7 @@ protected override string NormalizeRelativePath( throw PSTraceSource.NewArgumentException(nameof(path)); } - if (basePath == null) - { - basePath = string.Empty; - } + basePath ??= string.Empty; s_tracer.WriteLine("basePath = {0}", basePath); @@ -5145,7 +5202,7 @@ protected override string NormalizeRelativePath( #if UNIX // We don't use the Directory.EnumerateFiles() for Unix because the path // may contain additional globbing patterns such as '[ab]' - // which Directory.EnumerateFiles() processes, giving undesireable + // which Directory.EnumerateFiles() processes, giving undesirable // results in this context. if (!File.Exists(result) && !Directory.Exists(result)) { @@ -5216,7 +5273,7 @@ protected override string NormalizeRelativePath( } catch (IOException ioError) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioError, "NormalizeRelativePathIOError", ErrorCategory.ReadError, path)); break; } @@ -5267,10 +5324,7 @@ private string NormalizeRelativePathHelper(string path, string basePath) return string.Empty; } - if (basePath == null) - { - basePath = string.Empty; - } + basePath ??= string.Empty; s_tracer.WriteLine("basePath = {0}", basePath); @@ -5813,6 +5867,17 @@ protected override void MoveItem( destination = MakePath(destination, dir.Name); } + // Don't allow moving a directory into itself or its sub-directory. + string pathWithoutEndingSeparator = Path.TrimEndingDirectorySeparator(path); + if (destination.StartsWith(pathWithoutEndingSeparator + Path.DirectorySeparatorChar) + || destination.Equals(pathWithoutEndingSeparator, StringComparison.OrdinalIgnoreCase)) + { + string error = StringUtil.Format(FileSystemProviderStrings.TargetCannotBeSubdirectoryOfSource, destination); + var e = new IOException(error); + WriteError(new ErrorRecord(e, "MoveItemArgumentError", ErrorCategory.InvalidArgument, destination)); + return; + } + // Get the confirmation text string action = FileSystemProviderStrings.MoveItemActionDirectory; @@ -5860,7 +5925,7 @@ protected override void MoveItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveItemIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -5973,7 +6038,7 @@ private void MoveFileInfoItem( (exception is ArgumentNullException) || (exception is IOException)) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, destfile)); } else @@ -5982,13 +6047,13 @@ private void MoveFileInfoItem( } else { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, file)); } } else { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveFileInfoItemIOError", ErrorCategory.WriteError, file)); } } @@ -6059,7 +6124,7 @@ private void MoveDirectoryInfoItem( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "MoveDirectoryItemIOError", ErrorCategory.WriteError, directory)); } } @@ -6078,12 +6143,21 @@ private void MoveDirectoryInfoUnchecked(DirectoryInfo directory, string destinat { if (InternalTestHooks.ThrowExdevErrorOnMoveDirectory) { - throw new IOException("Invalid cross-device link", hresult: MOVE_FAILED_ERROR); + throw new IOException("Invalid cross-device link"); } directory.MoveTo(destinationPath); } - catch (IOException e) when (e.HResult == MOVE_FAILED_ERROR) +#if UNIX + // This is the errno returned by the rename() syscall + // when an item is attempted to be renamed across filesystem mount boundaries. + // 0x80131620 is returned if the source and destination do not have the same root path + catch (IOException e) when (e.HResult == 18 || e.HResult == -2146232800) +#else + // 0x80070005 ACCESS_DENIED is returned when trying to move files across volumes like DFS + // 0x80131620 is returned if the source and destination do not have the same root path + catch (IOException e) when (e.HResult == -2147024891 || e.HResult == -2146232800) +#endif { // Rather than try to ascertain whether we can rename a directory ahead of time, // it's both faster and more correct to try to rename it and fall back to copy/deleting it @@ -6189,10 +6263,7 @@ public void GetProperty(string path, Collection providerSpecificPickList if (member != null) { value = member.Value; - if (result == null) - { - result = new PSObject(); - } + result ??= new PSObject(); result.Properties.Add(new PSNoteProperty(property, value)); } @@ -6221,7 +6292,7 @@ public void GetProperty(string path, Collection providerSpecificPickList } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "GetPropertyIOError", ErrorCategory.ReadError, path)); } catch (UnauthorizedAccessException accessException) @@ -6521,7 +6592,7 @@ public void ClearProperty( } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "ClearPropertyIOError", ErrorCategory.WriteError, path)); } } @@ -6576,7 +6647,7 @@ public IContentReader GetContentReader(string path) // Defaults for the file read operation string delimiter = "\n"; - Encoding encoding = ClrFacade.GetDefaultEncoding(); + Encoding encoding = Encoding.Default; bool waitForChanges = false; bool streamTypeSpecified = false; @@ -6701,7 +6772,7 @@ public IContentReader GetContentReader(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "GetContentReaderIOError", ErrorCategory.ReadError, path)); } catch (System.Security.SecurityException securityException) @@ -6758,7 +6829,7 @@ public IContentWriter GetContentWriter(string path) // If this is true, then the content will be read as bytes bool usingByteEncoding = false; bool streamTypeSpecified = false; - Encoding encoding = ClrFacade.GetDefaultEncoding(); + Encoding encoding = Encoding.Default; const FileMode filemode = FileMode.OpenOrCreate; string streamName = null; bool suppressNewline = false; @@ -6841,7 +6912,7 @@ public IContentWriter GetContentWriter(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "GetContentWriterIOError", ErrorCategory.WriteError, path)); } catch (System.Security.SecurityException securityException) @@ -7007,7 +7078,7 @@ public void ClearContent(string path) } catch (IOException ioException) { - // IOException contains specific message about the error occured and so no need for errordetails. + // IOException contains specific message about the error occurred and so no need for errordetails. WriteError(new ErrorRecord(ioException, "ClearContentIOError", ErrorCategory.WriteError, path)); } catch (UnauthorizedAccessException accessException) @@ -7111,134 +7182,35 @@ internal static bool PathIsNetworkPath(string path) #endif } +#if !UNIX + /// + /// The API 'PathIsNetworkPath' is not available in CoreSystem. + /// This implementation is based on the 'PathIsNetworkPath' API. + /// + /// A file system path. + /// True if the path is a network path. internal static bool WinPathIsNetworkPath(string path) - { - return NativeMethods.PathIsNetworkPath(path); // call the native method - } - - private static class NativeMethods - { - /// - /// WNetAddConnection2 API makes a connection to a network resource - /// and can redirect a local device to the network resource. - /// This API simulates the "new Use" functionality used to connect to - /// network resource. - /// - /// - /// The netResource structure contains information - /// about a network resource. - /// - /// The password used to get connected to network resource. - /// - /// - /// The username used to get connected to network resource. - /// - /// - /// The flags parameter is used to indicate if the created network - /// resource has to be persisted or not. - /// - /// If connection is established to the network resource - /// then success is returned or else the error code describing the - /// type of failure that occured while establishing - /// the connection is returned. - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetAddConnection2(ref NetResource netResource, byte[] password, string username, int flags); - - /// - /// WNetCancelConnection2 function cancels an existing network connection. - /// - /// - /// PSDrive Name. - /// - /// - /// Connection Type. - /// - /// - /// Specifies whether the disconnection should occur if there are open files or jobs - /// on the connection. If this parameter is FALSE, the function fails - /// if there are open files or jobs. - /// - /// If connection is removed then success is returned or - /// else the error code describing the type of failure that occured while - /// trying to remove the connection is returned. - /// - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetCancelConnection2(string driveName, int flags, bool force); - - /// - /// WNetGetConnection function retrieves the name of the network resource associated with a local device. - /// - /// - /// Local name of the PSDrive. - /// - /// - /// The remote name to which the PSDrive is getting mapped to. - /// - /// - /// length of the remote name of the created PSDrive. - /// - /// - [DllImport("mpr.dll", CharSet = CharSet.Unicode)] - internal static extern int WNetGetConnection(string localName, StringBuilder remoteName, ref int remoteNameLength); - -#if CORECLR // TODO:CORECLR Win32 function 'PathIsNetworkPath' is in an extension API set which is currently not on CSS. - /// - /// Searches a path for a drive letter within the range of 'A' to 'Z' and returns the corresponding drive number. - /// - /// - /// Path of the file being executed - /// - /// Returns 0 through 25 (corresponding to 'A' through 'Z') if the path has a drive letter, or -1 otherwise. - [DllImport("api-ms-win-core-shlwapi-legacy-l1-1-0.dll", CharSet = CharSet.Unicode)] - internal static extern int PathGetDriveNumber(string path); - - private static bool _WNetApiAvailable = true; - - /// - /// The API 'PathIsNetworkPath' is not available in CoreSystem. - /// This implementation is based on the 'PathIsNetworkPath' API. - /// - /// - /// - internal static bool PathIsNetworkPath(string path) { if (string.IsNullOrEmpty(path)) { return false; } - if (Utils.PathIsUnc(path)) + if (Utils.PathIsUnc(path, networkOnly : true)) { return true; } - if (!_WNetApiAvailable) - { - return false; - } - - // 0 - 25 corresponding to 'A' - 'Z' - int driveId = PathGetDriveNumber(path); - if (driveId >= 0 && driveId < 26) + if (path.Length > 1 && path[1] == ':' && char.IsAsciiLetter(path[0])) { - string driveName = (char)('A' + driveId) + ":"; - - int bufferSize = 260; // MAX_PATH from EhStorIoctl.h - StringBuilder uncBuffer = new StringBuilder(bufferSize); - int errorCode = -1; - try - { - errorCode = WNetGetConnection(driveName, uncBuffer, ref bufferSize); - } - catch (System.DllNotFoundException) - { - _WNetApiAvailable = false; - return false; - } + // path[0] is ASCII letter, e.g. is in 'A'-'Z' or 'a'-'z'. + int errorCode = Interop.Windows.GetUNCForNetworkDrive(path[0], out string _); // From the 'IsNetDrive' API. // 0: success; 1201: connection closed; 31: device error - if (errorCode == 0 || errorCode == 1201 || errorCode == 31) + if (errorCode == Interop.Windows.ERROR_SUCCESS || + errorCode == Interop.Windows.ERROR_CONNECTION_UNAVAIL || + errorCode == Interop.Windows.ERROR_GEN_FAILURE) { return true; } @@ -7246,138 +7218,13 @@ internal static bool PathIsNetworkPath(string path) return false; } -#else - /// - /// Facilitates to validate if the supplied path exists locally or on the network share. - /// - /// - /// Path of the file being executed. - /// - /// True if the path is a network path or else returns false. - [DllImport("shlwapi.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool PathIsNetworkPath(string path); -#endif - - /// - /// The function can obtain the current mapping for a particular MS-DOS device name. - /// - /// If lpDeviceName is non-NULL, the function retrieves information about the particular MS-DOS device specified by lpDeviceName. - /// The first null-terminated string stored into the buffer is the current mapping for the device. - /// The other null-terminated strings represent undeleted prior mappings for the device. - /// - /// - /// The particular MS-DOS device name. - /// - /// - /// The buffer to receive the result of the query. - /// - /// - /// The maximum number of characters that can be stored into the buffer - /// - /// - [DllImport(PinvokeDllNames.QueryDosDeviceDllName, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern int QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax); - - /// - /// Creates a symbolic link using the native API. - /// - /// Path of the symbolic link. - /// Path of the target of the symbolic link. - /// Flag values from SymbolicLinkFlags enum. - /// 1 on successful creation. - [DllImport(PinvokeDllNames.CreateSymbolicLinkDllName, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.I1)] - internal static extern bool CreateSymbolicLink(string name, string destination, SymbolicLinkFlags symbolicLinkFlags); - - /// - /// Flags used when creating a symbolic link. - /// - [Flags] - internal enum SymbolicLinkFlags - { - /// - /// Symbolic link is a file. - /// - File = 0, - - /// - /// Symbolic link is a directory. - /// - Directory = 1, - - /// - /// Allow creation of symbolic link without elevation. Requires Developer mode. - /// - AllowUnprivilegedCreate = 2, - } - - /// - /// Creates a hard link using the native API. - /// - /// Name of the hard link. - /// Path to the target of the hard link. - /// - /// - [DllImport(PinvokeDllNames.CreateHardLinkDllName, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CreateHardLink(string name, string existingFileName, IntPtr SecurityAttributes); - - // OneDrive placeholder support -#if !UNIX - /// - /// Returns the placeholder compatibility mode for the current process. - /// - /// The process's placeholder compatibily mode (PHCM_xxx), or a negative value on error (PCHM_ERROR_xxx). - [DllImport("ntdll.dll")] - internal static extern sbyte RtlQueryProcessPlaceholderCompatibilityMode(); - - /// - /// Sets the placeholder compatibility mode for the current process. - /// - /// The placeholder compatibility mode to set. - /// The process's previous placeholder compatibily mode (PHCM_xxx), or a negative value on error (PCHM_ERROR_xxx). - [DllImport("ntdll.dll")] - internal static extern sbyte RtlSetProcessPlaceholderCompatibilityMode(sbyte pcm); - - internal const sbyte PHCM_APPLICATION_DEFAULT = 0; - internal const sbyte PHCM_DISGUISE_PLACEHOLDER = 1; - internal const sbyte PHCM_EXPOSE_PLACEHOLDERS = 2; - internal const sbyte PHCM_MAX = 2; - internal const sbyte PHCM_ERROR_INVALID_PARAMETER = -1; - internal const sbyte PHCM_ERROR_NO_TEB = -2; #endif - } - - /// - /// Managed equivalent of NETRESOURCE structure of WNet API. - /// - [StructLayout(LayoutKind.Sequential)] - private struct NetResource - { - public int Scope; - public int Type; - public int DisplayType; - public int Usage; - - [MarshalAs(UnmanagedType.LPWStr)] - public string LocalName; - - [MarshalAs(UnmanagedType.LPWStr)] - public string RemoteName; - - [MarshalAs(UnmanagedType.LPWStr)] - public string Comment; - - [MarshalAs(UnmanagedType.LPWStr)] - public string Provider; - } #region InodeTracker /// /// Tracks visited files/directories by caching their device IDs and inodes. /// - private class InodeTracker + private sealed class InodeTracker { private readonly HashSet<(UInt64, UInt64)> _visitations; @@ -7526,7 +7373,7 @@ internal sealed class GetChildDynamicParameters /// Gets or sets the filter directory flag. /// [Parameter] - [Alias("ad", "d")] + [Alias("ad")] public SwitchParameter Directory { get { return _attributeDirectory; } @@ -7610,8 +7457,8 @@ internal FileSystemContentDynamicParametersBase(FileSystemProvider provider) /// reading data from the file. /// [Parameter] - [ArgumentToEncodingTransformationAttribute()] - [ArgumentEncodingCompletionsAttribute] + [ArgumentToEncodingTransformation] + [ArgumentEncodingCompletions] [ValidateNotNullOrEmpty] public Encoding Encoding { @@ -7623,7 +7470,7 @@ public Encoding Encoding set { // Check for UTF-7 by checking for code page 65000 - // See: https://docs.microsoft.com/en-us/dotnet/core/compatibility/corefx#utf-7-code-paths-are-obsolete + // See: https://learn.microsoft.com/dotnet/core/compatibility/corefx#utf-7-code-paths-are-obsolete if (value != null && value.CodePage == 65000) { _provider.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); @@ -7634,7 +7481,7 @@ public Encoding Encoding } } - private Encoding _encoding = ClrFacade.GetDefaultEncoding(); + private Encoding _encoding = Encoding.Default; /// /// Return file contents as a byte stream or create file from a series of bytes. @@ -7836,15 +7683,8 @@ public class FileSystemProviderRemoveItemDynamicParameters /// /// Class to find the symbolic link target. /// - public static class InternalSymbolicLinkLinkCodeMethods + public static partial class InternalSymbolicLinkLinkCodeMethods { - // This size comes from measuring the size of the header of REPARSE_GUID_DATA_BUFFER - private const int REPARSE_GUID_DATA_BUFFER_HEADER_SIZE = 24; - - // Maximum reparse buffer info size. The max user defined reparse - // data is 16KB, plus there's a header. - private const int MAX_REPARSE_SIZE = (16 * 1024) + REPARSE_GUID_DATA_BUFFER_HEADER_SIZE; - private const int FSCTL_GET_REPARSE_POINT = 0x000900A8; private const int FSCTL_SET_REPARSE_POINT = 0x000900A4; @@ -7859,62 +7699,6 @@ public static class InternalSymbolicLinkLinkCodeMethods private const string NonInterpretedPathPrefix = @"\??\"; - private const int MAX_PATH = 260; - - [Flags] - // dwDesiredAccess of CreateFile - internal enum FileDesiredAccess : uint - { - GenericZero = 0, - GenericRead = 0x80000000, - GenericWrite = 0x40000000, - GenericExecute = 0x20000000, - GenericAll = 0x10000000, - } - - [Flags] - // dwShareMode of CreateFile - internal enum FileShareMode : uint - { - None = 0x00000000, - Read = 0x00000001, - Write = 0x00000002, - Delete = 0x00000004, - } - - // dwCreationDisposition of CreateFile - internal enum FileCreationDisposition : uint - { - New = 1, - CreateAlways = 2, - OpenExisting = 3, - OpenAlways = 4, - TruncateExisting = 5, - } - - [Flags] - // dwFlagsAndAttributes - internal enum FileAttributes : uint - { - Readonly = 0x00000001, - Hidden = 0x00000002, - System = 0x00000004, - Archive = 0x00000020, - Encrypted = 0x00004000, - Write_Through = 0x80000000, - Overlapped = 0x40000000, - NoBuffering = 0x20000000, - RandomAccess = 0x10000000, - SequentialScan = 0x08000000, - DeleteOnClose = 0x04000000, - BackupSemantics = 0x02000000, - PosixSemantics = 0x01000000, - OpenReparsePoint = 0x00200000, - OpenNoRecall = 0x00100000, - SessionAware = 0x00800000, - Normal = 0x00000080 - } - [StructLayout(LayoutKind.Sequential)] private struct REPARSE_DATA_BUFFER_SYMBOLICLINK { @@ -7946,25 +7730,13 @@ private struct REPARSE_DATA_BUFFER_MOUNTPOINT public byte[] PathBuffer; } - [StructLayout(LayoutKind.Sequential)] - private struct REPARSE_DATA_BUFFER_APPEXECLINK - { - public uint ReparseTag; - public ushort ReparseDataLength; - public ushort Reserved; - public uint StringCount; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)] - public byte[] StringList; - } - [StructLayout(LayoutKind.Sequential)] private struct BY_HANDLE_FILE_INFORMATION { public uint FileAttributes; - public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime; - public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime; - public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime; + public FILE_TIME CreationTime; + public FILE_TIME LastAccessTime; + public FILE_TIME LastWriteTime; public uint VolumeSerialNumber; public uint FileSizeHigh; public uint FileSizeLow; @@ -7973,113 +7745,58 @@ private struct BY_HANDLE_FILE_INFORMATION public uint FileIndexLow; } - [StructLayout(LayoutKind.Sequential)] - private struct GUID + internal struct FILE_TIME { - public uint Data1; - public ushort Data2; - public ushort Data3; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] - public char[] Data4; + public uint dwLowDateTime; + public uint dwHighDateTime; } - [StructLayout(LayoutKind.Sequential)] - private struct REPARSE_GUID_DATA_BUFFER - { - public uint ReparseTag; - public ushort ReparseDataLength; - public ushort Reserved; - public GUID ReparseGuid; - - [MarshalAs(UnmanagedType.ByValArray, SizeConst = MAX_REPARSE_SIZE)] - public char[] DataBuffer; - } - - [DllImport(PinvokeDllNames.DeviceIoControlDllName, CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = true)] - private static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, + [LibraryImport(PinvokeDllNames.DeviceIoControlDllName, StringMarshalling = StringMarshalling.Utf16, SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static partial bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr InBuffer, int nInBufferSize, IntPtr OutBuffer, int nOutBufferSize, out int pBytesReturned, IntPtr lpOverlapped); - [DllImport(PinvokeDllNames.GetFileInformationByHandleDllName, SetLastError = true, CharSet = CharSet.Unicode)] + [LibraryImport(PinvokeDllNames.GetFileInformationByHandleDllName)] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool GetFileInformationByHandle( + private static partial bool GetFileInformationByHandle( IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation); - [DllImport(PinvokeDllNames.CreateFileDllName, SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern IntPtr CreateFile( - string lpFileName, - FileDesiredAccess dwDesiredAccess, - FileShareMode dwShareMode, - IntPtr lpSecurityAttributes, - FileCreationDisposition dwCreationDisposition, - FileAttributes dwFlagsAndAttributes, - IntPtr hTemplateFile); - - internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid + /// + /// Gets the target of the specified reparse point. + /// + /// The object of FileInfo or DirectoryInfo type. + /// The target of the reparse point. + [Obsolete("This method is now obsolete. Please use the .NET API 'FileSystemInfo.LinkTarget'", error: true)] + public static string GetTarget(PSObject instance) { - private SafeFindHandle() : base(true) { } - - protected override bool ReleaseHandle() + if (instance.BaseObject is FileSystemInfo fileSysInfo) { - return FindClose(this.handle); - } - - [DllImport(PinvokeDllNames.FindCloseDllName)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool FindClose(IntPtr handle); - } - - // SetLastError is false as the use of this API doesn't not require GetLastError() to be called - [DllImport(PinvokeDllNames.FindFirstFileDllName, EntryPoint = "FindFirstFileExW", SetLastError = false, CharSet = CharSet.Unicode)] - private static extern SafeFindHandle FindFirstFileEx(string lpFileName, FINDEX_INFO_LEVELS fInfoLevelId, ref WIN32_FIND_DATA lpFindFileData, FINDEX_SEARCH_OPS fSearchOp, IntPtr lpSearchFilter, int dwAdditionalFlags); - - internal enum FINDEX_INFO_LEVELS : uint - { - FindExInfoStandard = 0x0u, - FindExInfoBasic = 0x1u, - FindExInfoMaxInfoLevel = 0x2u, - } + if (!fileSysInfo.Exists) + { + throw new ArgumentException( + StringUtil.Format(SessionStateStrings.PathNotFound, fileSysInfo.FullName)); + } - internal enum FINDEX_SEARCH_OPS : uint - { - FindExSearchNameMatch = 0x0u, - FindExSearchLimitToDirectories = 0x1u, - FindExSearchLimitToDevices = 0x2u, - FindExSearchMaxSearchOp = 0x3u, - } + return fileSysInfo.LinkTarget; + } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] - internal unsafe struct WIN32_FIND_DATA - { - internal uint dwFileAttributes; - internal System.Runtime.InteropServices.ComTypes.FILETIME ftCreationTime; - internal System.Runtime.InteropServices.ComTypes.FILETIME ftLastAccessTime; - internal System.Runtime.InteropServices.ComTypes.FILETIME ftLastWriteTime; - internal uint nFileSizeHigh; - internal uint nFileSizeLow; - internal uint dwReserved0; - internal uint dwReserved1; - internal fixed char cFileName[MAX_PATH]; - internal fixed char cAlternateFileName[14]; + return null; } /// - /// Gets the target of the specified reparse point. + /// Gets the target for a given file or directory, resolving symbolic links. /// - /// The object of FileInfo or DirectoryInfo type. - /// The target of the reparse point. - public static string GetTarget(PSObject instance) + /// The FileInfo or DirectoryInfo type. + /// The file path the instance points to. + public static string ResolvedTarget(PSObject instance) { if (instance.BaseObject is FileSystemInfo fileSysInfo) { -#if !UNIX - return WinInternalGetTarget(fileSysInfo.FullName); -#else - return UnixInternalGetTarget(fileSysInfo.FullName); -#endif + FileSystemInfo linkTarget = fileSysInfo.ResolveLinkTarget(true); + return linkTarget is null ? fileSysInfo.FullName : linkTarget.FullName; } return null; @@ -8102,45 +7819,24 @@ public static string GetLinkType(PSObject instance) return null; } -#if UNIX - private static string UnixInternalGetTarget(string filePath) - { - string link = Platform.NonWindowsInternalGetTarget(filePath); - - if (string.IsNullOrEmpty(link)) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - - return link; - } -#endif - private static string InternalGetLinkType(FileSystemInfo fileInfo) { - if (Platform.IsWindows) - { - return WinInternalGetLinkType(fileInfo.FullName); - } - else - { - return Platform.NonWindowsInternalGetLinkType(fileInfo); - } +#if UNIX + return Platform.NonWindowsInternalGetLinkType(fileInfo); +#else + return WinInternalGetLinkType(fileInfo.FullName); +#endif } +#if !UNIX [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] private static string WinInternalGetLinkType(string filePath) { - if (!Platform.IsWindows) - { - throw new PlatformNotSupportedException(); - } - // We set accessMode parameter to zero because documentation says: // If this parameter is zero, the application can query certain metadata // such as file, directory, or device attributes without accessing // that file or device, even if GENERIC_READ access would have been denied. - using (SafeFileHandle handle = OpenReparsePoint(filePath, FileDesiredAccess.GenericZero)) + using (SafeFileHandle handle = WinOpenReparsePoint(filePath, (FileAccess)0)) { int outBufferSize = Marshal.SizeOf(); @@ -8172,7 +7868,7 @@ private static string WinInternalGetLinkType(string filePath) if (!result) { // It's not a reparse point or the file system doesn't support reparse points. - return IsHardLink(ref dangerousHandle) ? "HardLink" : null; + return WinIsHardLink(ref dangerousHandle) ? "HardLink" : null; } REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = Marshal.PtrToStructure(outBuffer); @@ -8187,10 +7883,6 @@ private static string WinInternalGetLinkType(string filePath) linkType = "Junction"; break; - case IO_REPARSE_TAG_APPEXECLINK: - linkType = "AppExeCLink"; - break; - default: linkType = null; break; @@ -8209,13 +7901,28 @@ private static string WinInternalGetLinkType(string filePath) } } } +#endif internal static bool IsHardLink(FileSystemInfo fileInfo) { #if UNIX return Platform.NonWindowsIsHardLink(fileInfo); #else - return WinIsHardLink(fileInfo); + bool isHardLink = false; + + // only check for hard link if the item is not directory + if ((fileInfo.Attributes & System.IO.FileAttributes.Directory) != System.IO.FileAttributes.Directory) + { + SafeFileHandle handle = Interop.Windows.CreateFileWithSafeFileHandle(fileInfo.FullName, FileAccess.Read, FileShare.Read, FileMode.Open, Interop.Windows.FileAttributes.Normal); + + using (handle) + { + var dangerousHandle = handle.DangerousGetHandle(); + isHardLink = InternalSymbolicLinkLinkCodeMethods.WinIsHardLink(ref dangerousHandle); + } + } + + return isHardLink; #endif } @@ -8224,65 +7931,49 @@ internal static bool IsReparsePoint(FileSystemInfo fileInfo) return fileInfo.Attributes.HasFlag(System.IO.FileAttributes.ReparsePoint); } - internal static bool IsReparsePointWithTarget(FileSystemInfo fileInfo) + internal static bool IsReparsePointLikeSymlink(FileSystemInfo fileInfo) { - if (!IsReparsePoint(fileInfo)) +#if UNIX + // Reparse point on Unix is a symlink. + return IsReparsePoint(fileInfo); +#else + if (InternalTestHooks.OneDriveTestOn && fileInfo.Name == InternalTestHooks.OneDriveTestSymlinkName) { - return false; + return !InternalTestHooks.OneDriveTestRecurseOn; } -#if !UNIX - // It is a reparse point and we should check some reparse point tags. - var data = new WIN32_FIND_DATA(); - using (var handle = FindFirstFileEx(fileInfo.FullName, FINDEX_INFO_LEVELS.FindExInfoBasic, ref data, FINDEX_SEARCH_OPS.FindExSearchNameMatch, IntPtr.Zero, 0)) + + Interop.Windows.WIN32_FIND_DATA data = default; + using (Interop.Windows.SafeFindHandle handle = Interop.Windows.FindFirstFile(fileInfo.FullName, ref data)) { - // The name surrogate bit 0x20000000 is defined in https://docs.microsoft.com/windows/win32/fileio/reparse-point-tags - // Name surrogates (0x20000000) are reparse points that point to other named entities local to the filesystem - // (like symlinks and mount points). - // In the case of OneDrive, they are not name surrogates and would be safe to recurse into. - if (!handle.IsInvalid && (data.dwReserved0 & 0x20000000) == 0 && (data.dwReserved0 != IO_REPARSE_TAG_APPEXECLINK)) + if (handle.IsInvalid) { - return false; + // Our handle could be invalidated by something else touching the filesystem, + // so ensure we deal with that possibility here + int lastError = Marshal.GetLastWin32Error(); + throw new Win32Exception(lastError); } - } -#endif - return true; - } - - internal static bool WinIsHardLink(FileSystemInfo fileInfo) - { - bool isHardLink = false; - - // only check for hard link if the item is not directory - if ((fileInfo.Attributes & System.IO.FileAttributes.Directory) != System.IO.FileAttributes.Directory) - { - IntPtr nativeHandle = InternalSymbolicLinkLinkCodeMethods.CreateFile( - fileInfo.FullName, - InternalSymbolicLinkLinkCodeMethods.FileDesiredAccess.GenericRead, - InternalSymbolicLinkLinkCodeMethods.FileShareMode.Read, - IntPtr.Zero, - InternalSymbolicLinkLinkCodeMethods.FileCreationDisposition.OpenExisting, - InternalSymbolicLinkLinkCodeMethods.FileAttributes.Normal, - IntPtr.Zero); - using (SafeFileHandle handle = new SafeFileHandle(nativeHandle, true)) + // We already have the file attribute information from our Win32 call, + // so no need to take the expense of the FileInfo.FileAttributes call + const int FILE_ATTRIBUTE_REPARSE_POINT = 0x0400; + if ((data.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) == 0) { - bool success = false; + // Not a reparse point. + return false; + } - try - { - handle.DangerousAddRef(ref success); - IntPtr dangerousHandle = handle.DangerousGetHandle(); - isHardLink = InternalSymbolicLinkLinkCodeMethods.IsHardLink(ref dangerousHandle); - } - finally - { - if (success) - handle.DangerousRelease(); - } + // The name surrogate bit 0x20000000 is defined in https://learn.microsoft.com/windows/win32/fileio/reparse-point-tags + // Name surrogates (0x20000000) are reparse points that point to other named entities local to the filesystem + // (like symlinks and mount points). + // In the case of OneDrive, they are not name surrogates and would be safe to recurse into. + if ((data.dwReserved0 & 0x20000000) == 0 && (data.dwReserved0 != IO_REPARSE_TAG_APPEXECLINK)) + { + return false; } } - return isHardLink; + return true; +#endif } internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) @@ -8297,13 +7988,10 @@ internal static bool IsSameFileSystemItem(string pathOne, string pathTwo) #if !UNIX private static bool WinIsSameFileSystemItem(string pathOne, string pathTwo) { - const FileAccess access = FileAccess.Read; - const FileShare share = FileShare.Read; - const FileMode creation = FileMode.Open; - const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const Interop.Windows.FileAttributes Attributes = Interop.Windows.FileAttributes.BackupSemantics | Interop.Windows.FileAttributes.PosixSemantics; - using (var sfOne = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathOne, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) - using (var sfTwo = AlternateDataStreamUtilities.NativeMethods.CreateFile(pathTwo, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) + using (var sfOne = Interop.Windows.CreateFileWithSafeFileHandle(pathOne, FileAccess.Read, FileShare.Read, FileMode.Open, Attributes)) + using (var sfTwo = Interop.Windows.CreateFileWithSafeFileHandle(pathTwo, FileAccess.Read, FileShare.Read, FileMode.Open, Attributes)) { if (!sfOne.IsInvalid && !sfTwo.IsInvalid) { @@ -8336,12 +8024,9 @@ internal static bool GetInodeData(string path, out System.ValueTuple inodeData) { - const FileAccess access = FileAccess.Read; - const FileShare share = FileShare.Read; - const FileMode creation = FileMode.Open; - const FileAttributes attributes = FileAttributes.BackupSemantics | FileAttributes.PosixSemantics; + const Interop.Windows.FileAttributes Attributes = Interop.Windows.FileAttributes.BackupSemantics | Interop.Windows.FileAttributes.PosixSemantics; - using (var sf = AlternateDataStreamUtilities.NativeMethods.CreateFile(path, access, share, IntPtr.Zero, creation, (int)attributes, IntPtr.Zero)) + using (var sf = Interop.Windows.CreateFileWithSafeFileHandle(path, FileAccess.Read, FileShare.Read, FileMode.Open, Attributes)) { if (!sf.IsInvalid) { @@ -8360,17 +8045,10 @@ private static bool WinGetInodeData(string path, out System.ValueTuple 1); } -#if !UNIX - internal static string WinInternalGetTarget(string path) - { - // We set accessMode parameter to zero because documentation says: - // If this parameter is zero, the application can query certain metadata - // such as file, directory, or device attributes without accessing - // that file or device, even if GENERIC_READ access would have been denied. - using (SafeFileHandle handle = OpenReparsePoint(path, FileDesiredAccess.GenericZero)) - { - return WinInternalGetTarget(handle); - } - } - - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] - private static string WinInternalGetTarget(SafeFileHandle handle) + internal static bool CreateJunction(string path, string target) { - int outBufferSize = Marshal.SizeOf(); - - IntPtr outBuffer = Marshal.AllocHGlobal(outBufferSize); - bool success = false; +#if UNIX + return false; +#else + ArgumentException.ThrowIfNullOrEmpty(path); + ArgumentException.ThrowIfNullOrEmpty(target); - try + using (SafeHandle handle = WinOpenReparsePoint(path, FileAccess.Write)) { - int bytesReturned; + byte[] mountPointBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(target)); - // OACR warning 62001 about using DeviceIOControl has been disabled. - // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used. - handle.DangerousAddRef(ref success); + var mountPoint = new REPARSE_DATA_BUFFER_MOUNTPOINT(); + mountPoint.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; + mountPoint.ReparseDataLength = (ushort)(mountPointBytes.Length + 12); // Added space for the header and null endo + mountPoint.SubstituteNameOffset = 0; + mountPoint.SubstituteNameLength = (ushort)mountPointBytes.Length; + mountPoint.PrintNameOffset = (ushort)(mountPointBytes.Length + 2); // 2 as unicode null take 2 bytes. + mountPoint.PrintNameLength = 0; + mountPoint.PathBuffer = new byte[0x3FF0]; // Buffer for max size. + Array.Copy(mountPointBytes, mountPoint.PathBuffer, mountPointBytes.Length); - bool result = DeviceIoControl( - handle.DangerousGetHandle(), - FSCTL_GET_REPARSE_POINT, - InBuffer: IntPtr.Zero, - nInBufferSize: 0, - outBuffer, - outBufferSize, - out bytesReturned, - lpOverlapped: IntPtr.Zero); + int nativeBufferSize = Marshal.SizeOf(mountPoint); + IntPtr nativeBuffer = Marshal.AllocHGlobal(nativeBufferSize); + bool success = false; - if (!result) + try { - // It's not a reparse point or the file system doesn't support reparse points. - return null; - } - - string targetDir = null; + Marshal.StructureToPtr(mountPoint, nativeBuffer, false); - REPARSE_DATA_BUFFER_SYMBOLICLINK reparseDataBuffer = Marshal.PtrToStructure(outBuffer); + int bytesReturned = 0; - switch (reparseDataBuffer.ReparseTag) - { - case IO_REPARSE_TAG_SYMLINK: - targetDir = Encoding.Unicode.GetString(reparseDataBuffer.PathBuffer, reparseDataBuffer.SubstituteNameOffset, reparseDataBuffer.SubstituteNameLength); - break; - - case IO_REPARSE_TAG_MOUNT_POINT: - REPARSE_DATA_BUFFER_MOUNTPOINT reparseMountPointDataBuffer = Marshal.PtrToStructure(outBuffer); - targetDir = Encoding.Unicode.GetString(reparseMountPointDataBuffer.PathBuffer, reparseMountPointDataBuffer.SubstituteNameOffset, reparseMountPointDataBuffer.SubstituteNameLength); - break; + // OACR warning 62001 about using DeviceIOControl has been disabled. + // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used. + handle.DangerousAddRef(ref success); - case IO_REPARSE_TAG_APPEXECLINK: - REPARSE_DATA_BUFFER_APPEXECLINK reparseAppExeDataBuffer = Marshal.PtrToStructure(outBuffer); - // The target file is at index 2 - if (reparseAppExeDataBuffer.StringCount >= 3) - { - string temp = Encoding.Unicode.GetString(reparseAppExeDataBuffer.StringList); - targetDir = temp.Split('\0')[2]; - } - break; + bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT, nativeBuffer, mountPointBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); - default: - return null; - } + if (!result) + { + throw new Win32Exception(Marshal.GetLastWin32Error()); + } - if (targetDir != null && targetDir.StartsWith(NonInterpretedPathPrefix, StringComparison.OrdinalIgnoreCase)) - { - targetDir = targetDir.Substring(NonInterpretedPathPrefix.Length); + return result; } - - return targetDir; - } - finally - { - if (success) + finally { - handle.DangerousRelease(); - } - - Marshal.FreeHGlobal(outBuffer); - } - } -#endif - - internal static bool CreateJunction(string path, string target) - { - // this is a purely Windows specific feature, no feature flag - // used for that reason - if (Platform.IsWindows) - { - return WinCreateJunction(path, target); - } - else - { - return false; - } - } + Marshal.FreeHGlobal(nativeBuffer); - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] - private static bool WinCreateJunction(string path, string target) - { - if (!string.IsNullOrEmpty(path)) - { - if (!string.IsNullOrEmpty(target)) - { - using (SafeHandle handle = OpenReparsePoint(path, FileDesiredAccess.GenericWrite)) + if (success) { - byte[] mountPointBytes = Encoding.Unicode.GetBytes(NonInterpretedPathPrefix + Path.GetFullPath(target)); - - REPARSE_DATA_BUFFER_MOUNTPOINT mountPoint = new REPARSE_DATA_BUFFER_MOUNTPOINT(); - mountPoint.ReparseTag = IO_REPARSE_TAG_MOUNT_POINT; - mountPoint.ReparseDataLength = (ushort)(mountPointBytes.Length + 12); // Added space for the header and null endo - mountPoint.SubstituteNameOffset = 0; - mountPoint.SubstituteNameLength = (ushort)mountPointBytes.Length; - mountPoint.PrintNameOffset = (ushort)(mountPointBytes.Length + 2); // 2 as unicode null take 2 bytes. - mountPoint.PrintNameLength = 0; - mountPoint.PathBuffer = new byte[0x3FF0]; // Buffer for max size. - Array.Copy(mountPointBytes, mountPoint.PathBuffer, mountPointBytes.Length); - - int nativeBufferSize = Marshal.SizeOf(mountPoint); - IntPtr nativeBuffer = Marshal.AllocHGlobal(nativeBufferSize); - bool success = false; - - try - { - Marshal.StructureToPtr(mountPoint, nativeBuffer, false); - - int bytesReturned = 0; - - // OACR warning 62001 about using DeviceIOControl has been disabled. - // According to MSDN guidance DangerousAddRef() and DangerousRelease() have been used. - handle.DangerousAddRef(ref success); - - bool result = DeviceIoControl(handle.DangerousGetHandle(), FSCTL_SET_REPARSE_POINT, nativeBuffer, mountPointBytes.Length + 20, IntPtr.Zero, 0, out bytesReturned, IntPtr.Zero); - - if (!result) - { - throw new Win32Exception(Marshal.GetLastWin32Error()); - } - - return result; - } - finally - { - Marshal.FreeHGlobal(nativeBuffer); - - if (success) - { - handle.DangerousRelease(); - } - } + handle.DangerousRelease(); } } - else - { - throw new ArgumentNullException(nameof(target)); - } - } - else - { - throw new ArgumentNullException(nameof(path)); } - } - - private static SafeFileHandle OpenReparsePoint(string reparsePoint, FileDesiredAccess accessMode) - { -#if UNIX - throw new PlatformNotSupportedException(); -#else - return WinOpenReparsePoint(reparsePoint, accessMode); #endif } - private static SafeFileHandle WinOpenReparsePoint(string reparsePoint, FileDesiredAccess accessMode) +#if !UNIX + private static SafeFileHandle WinOpenReparsePoint(string reparsePoint, FileAccess accessMode) { - IntPtr nativeHandle = CreateFile(reparsePoint, accessMode, - FileShareMode.Read | FileShareMode.Write | FileShareMode.Delete, - IntPtr.Zero, FileCreationDisposition.OpenExisting, - FileAttributes.BackupSemantics | FileAttributes.OpenReparsePoint, - IntPtr.Zero); + const Interop.Windows.FileAttributes Attributes = Interop.Windows.FileAttributes.BackupSemantics | Interop.Windows.FileAttributes.OpenReparsePoint; - int lastError = Marshal.GetLastWin32Error(); + SafeFileHandle reparsePointHandle = Interop.Windows.CreateFileWithSafeFileHandle(reparsePoint, accessMode, FileShare.ReadWrite | FileShare.Delete, FileMode.Open, Attributes); - if (lastError != 0) + if (reparsePointHandle.IsInvalid) + { + // Save last error since Dispose() will do another pinvoke. + int lastError = Marshal.GetLastPInvokeError(); + reparsePointHandle.Dispose(); throw new Win32Exception(lastError); - - SafeFileHandle reparsePointHandle = new SafeFileHandle(nativeHandle, true); + } return reparsePointHandle; } +#endif } #endregion @@ -8615,7 +8170,7 @@ public class AlternateStreamData /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes", Justification = "Needed by both the FileSystem provider and Unblock-File cmdlet.")] - public static class AlternateDataStreamUtilities + public static partial class AlternateDataStreamUtilities { /// /// List all of the streams on a file. @@ -8624,7 +8179,7 @@ public static class AlternateDataStreamUtilities /// The list of streams (and their size) in the file. internal static List GetStreams(string path) { - if (path == null) throw new ArgumentNullException(nameof(path)); + ArgumentNullException.ThrowIfNull(path); List alternateStreams = new List(); @@ -8640,7 +8195,10 @@ internal static List GetStreams(string path) // Directories don't normally have alternate streams, so this is not an exceptional state. // If a directory has no alternate data streams, FindFirstStreamW returns ERROR_HANDLE_EOF. - if (error == NativeMethods.ERROR_HANDLE_EOF) + // If the file system (such as FAT32) does not support alternate streams, then + // ERROR_INVALID_PARAMETER is returned by FindFirstStreamW. See documentation: + // https://learn.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-findfirststreamw + if (error == NativeMethods.ERROR_HANDLE_EOF || error == NativeMethods.ERROR_INVALID_PARAMETER) { return alternateStreams; } @@ -8667,8 +8225,7 @@ internal static List GetStreams(string path) AlternateStreamData data = new AlternateStreamData(); data.Stream = findStreamData.Name; data.Length = findStreamData.Length; - data.FileName = path.Replace(data.Stream, string.Empty); - data.FileName = data.FileName.Trim(Utils.Separators.Colon); + data.FileName = path; alternateStreams.Add(data); findStreamData = new AlternateStreamNativeData(); @@ -8677,7 +8234,9 @@ internal static List GetStreams(string path) int lastError = Marshal.GetLastWin32Error(); if (lastError != NativeMethods.ERROR_HANDLE_EOF) + { throw new Win32Exception(lastError); + } } finally { handle.Dispose(); } @@ -8717,15 +8276,9 @@ internal static FileStream CreateFileStream(string path, string streamName, File /// True if the stream was successfully created, otherwise false. internal static bool TryCreateFileStream(string path, string streamName, FileMode mode, FileAccess access, FileShare share, out FileStream stream) { - if (path == null) - { - throw new ArgumentNullException(nameof(path)); - } + ArgumentNullException.ThrowIfNull(path); - if (streamName == null) - { - throw new ArgumentNullException(nameof(streamName)); - } + ArgumentNullException.ThrowIfNull(streamName); if (mode == FileMode.Append) { @@ -8752,11 +8305,12 @@ internal static bool TryCreateFileStream(string path, string streamName, FileMod /// The name of the alternate data stream to delete. internal static void DeleteFileStream(string path, string streamName) { - if (path == null) throw new ArgumentNullException(nameof(path)); - if (streamName == null) throw new ArgumentNullException(nameof(streamName)); + ArgumentNullException.ThrowIfNull(path); + + ArgumentNullException.ThrowIfNull(streamName); string adjustedStreamName = streamName.Trim(); - if (adjustedStreamName.IndexOf(':') != 0) + if (!adjustedStreamName.StartsWith(':')) { adjustedStreamName = ":" + adjustedStreamName; } @@ -8780,15 +8334,15 @@ internal static void SetZoneOfOrigin(string path, SecurityZone securityZone) // the code above seems cleaner and more robust than the IAttachmentExecute approach } - internal static class NativeMethods + internal static partial class NativeMethods { internal const int ERROR_HANDLE_EOF = 38; internal const int ERROR_INVALID_PARAMETER = 87; internal enum StreamInfoLevels { FindStreamInfoStandard = 0 } - [DllImport(PinvokeDllNames.CreateFileDllName, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern SafeFileHandle CreateFile(string lpFileName, + [LibraryImport(PinvokeDllNames.CreateFileDllName, EntryPoint = "CreateFileW", SetLastError = true, StringMarshalling = StringMarshalling.Utf16)] + internal static partial SafeFileHandle CreateFile(string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); @@ -8809,7 +8363,7 @@ internal static extern bool FindNextStreamW( AlternateStreamNativeData lpFindStreamData); } - internal sealed class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid + internal sealed partial class SafeFindHandle : SafeHandleZeroOrMinusOneIsInvalid { private SafeFindHandle() : base(true) { } @@ -8818,9 +8372,9 @@ protected override bool ReleaseHandle() return FindClose(this.handle); } - [DllImport(PinvokeDllNames.FindCloseDllName)] + [LibraryImport(PinvokeDllNames.FindCloseDllName)] [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool FindClose(IntPtr handle); + private static partial bool FindClose(IntPtr handle); } /// @@ -9211,7 +8765,7 @@ function PSRemoteDestinationPathIsFile # Return a hash table in the following format: # DirectoryPath is the directory to be created. - # PathExists is a bool to to keep track of whether the directory already exist. + # PathExists is a bool to keep track of whether the directory already exist. # # 1) If DirectoryPath already exists: # a) If -Force is specified, force create the directory. Set DirectoryPath to the created directory path. diff --git a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs index 97ab38158ae..9af94c2d604 100644 --- a/src/System.Management.Automation/namespaces/FileSystemSecurity.cs +++ b/src/System.Management.Automation/namespaces/FileSystemSecurity.cs @@ -141,7 +141,7 @@ public void SetSecurityDescriptor( // the solution is to: // // - First attempt to copy the entire security descriptor as we did in V1. - // This ensures backward compatability for administrator scripts that currently + // This ensures backward compatibility for administrator scripts that currently // work. // - If the attempt fails due to a PrivilegeNotHeld exception, try again with // an estimate of the minimum required subset. This is an estimate, since the @@ -168,13 +168,15 @@ public void SetSecurityDescriptor( { // Get the security descriptor of the destination path ObjectSecurity existingDescriptor = new FileInfo(path).GetAccessControl(); - Type ntAccountType = typeof(System.Security.Principal.NTAccount); + // Use SecurityIdentifier to avoid having the below comparison steps + // fail when dealing with an untranslatable SID in the SD + Type identityType = typeof(System.Security.Principal.SecurityIdentifier); AccessControlSections sections = AccessControlSections.All; // If they didn't modify any audit information, don't try to set // the audit section. - int auditRuleCount = sd.GetAuditRules(true, true, ntAccountType).Count; + int auditRuleCount = sd.GetAuditRules(true, true, identityType).Count; if ((auditRuleCount == 0) && (sd.AreAuditRulesProtected == existingDescriptor.AreAccessRulesProtected)) { @@ -182,13 +184,13 @@ public void SetSecurityDescriptor( } // If they didn't modify the owner, don't try to set that section. - if (sd.GetOwner(ntAccountType) == existingDescriptor.GetOwner(ntAccountType)) + if (sd.GetOwner(identityType) == existingDescriptor.GetOwner(identityType)) { sections &= ~AccessControlSections.Owner; } // If they didn't modify the group, don't try to set that section. - if (sd.GetGroup(ntAccountType) == existingDescriptor.GetGroup(ntAccountType)) + if (sd.GetGroup(identityType) == existingDescriptor.GetGroup(identityType)) { sections &= ~AccessControlSections.Group; } @@ -222,7 +224,7 @@ private void SetSecurityDescriptor(string path, ObjectSecurity sd, AccessControl // Transfer it to the new file / directory. // We keep these two code branches so that we can have more - // granular information when we ouput the object type via + // granular information when we output the object type via // WriteSecurityDescriptorObject. if (Directory.Exists(path)) { diff --git a/src/System.Management.Automation/namespaces/IContentReader.cs b/src/System.Management.Automation/namespaces/IContentReader.cs index 233d89b9b40..6046fee73ed 100644 --- a/src/System.Management.Automation/namespaces/IContentReader.cs +++ b/src/System.Management.Automation/namespaces/IContentReader.cs @@ -4,6 +4,7 @@ using System.Collections; using System.IO; +#nullable enable namespace System.Management.Automation.Provider { #region IContentReader diff --git a/src/System.Management.Automation/namespaces/IPermissionProvider.cs b/src/System.Management.Automation/namespaces/IPermissionProvider.cs index 13b41261a19..c4f548e08a7 100644 --- a/src/System.Management.Automation/namespaces/IPermissionProvider.cs +++ b/src/System.Management.Automation/namespaces/IPermissionProvider.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +#nullable enable using System.Security.AccessControl; namespace System.Management.Automation.Provider diff --git a/src/System.Management.Automation/namespaces/ItemProviderBase.cs b/src/System.Management.Automation/namespaces/ItemProviderBase.cs index eff6782f713..e282093de49 100644 --- a/src/System.Management.Automation/namespaces/ItemProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ItemProviderBase.cs @@ -8,15 +8,15 @@ namespace System.Management.Automation.Provider #region ItemCmdletProvider /// - /// The base class for Cmdlet providers that expose an item as an MSH path. + /// The base class for Cmdlet providers that expose an item as a PowerShell path. /// /// /// The ItemCmdletProvider class is a base class that a provider derives from to - /// inherit a set of methods that allows the Monad engine + /// inherit a set of methods that allows the PowerShell engine /// to provide a core set of commands for getting and setting of data on one or /// more items. A provider should derive from this class if they want /// to take advantage of the item core commands that are - /// already implemented by the Monad engine. This allows users to have common + /// already implemented by the engine. This allows users to have common /// commands and semantics across multiple providers. /// public abstract class ItemCmdletProvider : DriveCmdletProvider diff --git a/src/System.Management.Automation/namespaces/LocationGlobber.cs b/src/System.Management.Automation/namespaces/LocationGlobber.cs index e4ab1f3cfc5..65c28f1586d 100644 --- a/src/System.Management.Automation/namespaces/LocationGlobber.cs +++ b/src/System.Management.Automation/namespaces/LocationGlobber.cs @@ -22,7 +22,7 @@ internal sealed class LocationGlobber /// An instance of the PSTraceSource class used for trace output /// using "LocationGlobber" as the category. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "LocationGlobber", "The location globber converts PowerShell paths with glob characters to zero or more paths.")] private static readonly Dbg.PSTraceSource s_tracer = @@ -32,7 +32,7 @@ internal sealed class LocationGlobber /// /// User level tracing for path resolution. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "PathResolution", "Traces the path resolution algorithm.")] private static readonly Dbg.PSTraceSource s_pathResolutionTracer = @@ -1967,7 +1967,7 @@ CmdletProviderContext context string driveRoot = drive.Root.Replace(StringLiterals.AlternatePathSeparator, StringLiterals.DefaultPathSeparator); driveRoot = driveRoot.TrimEnd(StringLiterals.DefaultPathSeparator); - // Keep on lopping off children until the the remaining path + // Keep on lopping off children until the remaining path // is the drive root. while ((!string.IsNullOrEmpty(providerPath)) && (!providerPath.Equals(driveRoot, StringComparison.OrdinalIgnoreCase))) @@ -2065,7 +2065,10 @@ internal string GenerateRelativePath( driveRootRelativeWorkingPath = driveRootRelativeWorkingPath.Substring(drive.Root.Length); } - if (escapeCurrentLocation) { driveRootRelativeWorkingPath = WildcardPattern.Escape(driveRootRelativeWorkingPath); } + if (escapeCurrentLocation) + { + driveRootRelativeWorkingPath = WildcardPattern.Escape(driveRootRelativeWorkingPath); + } // These are static strings that we will parse and // interpret if they are leading the path. Otherwise @@ -4536,7 +4539,7 @@ internal static bool IsHomePath(string path) } } - if (path.IndexOf(StringLiterals.HomePath, StringComparison.Ordinal) == 0) + if (path.StartsWith(StringLiterals.HomePath, StringComparison.Ordinal)) { // Support the single "~" if (path.Length == 1) @@ -4635,7 +4638,7 @@ internal string GetHomeRelativePath(string path) } } - if (path.IndexOf(StringLiterals.HomePath, StringComparison.Ordinal) == 0) + if (path.StartsWith(StringLiterals.HomePath, StringComparison.Ordinal)) { // Strip of the ~ and the \ or / if present @@ -4704,7 +4707,7 @@ private static void TraceFilters(CmdletProviderContext context) StringBuilder includeString = new StringBuilder(); foreach (string includeFilter in context.Include) { - includeString.AppendFormat("{0} ", includeFilter); + includeString.Append($"{includeFilter} "); } s_pathResolutionTracer.WriteLine("Include: {0}", includeString.ToString()); @@ -4716,7 +4719,7 @@ private static void TraceFilters(CmdletProviderContext context) StringBuilder excludeString = new StringBuilder(); foreach (string excludeFilter in context.Exclude) { - excludeString.AppendFormat("{0} ", excludeFilter); + excludeString.Append($"{excludeFilter} "); } s_pathResolutionTracer.WriteLine("Exclude: {0}", excludeString.ToString()); diff --git a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs index da8a16869d1..cf656e633a3 100644 --- a/src/System.Management.Automation/namespaces/NavigationProviderBase.cs +++ b/src/System.Management.Automation/namespaces/NavigationProviderBase.cs @@ -515,10 +515,7 @@ internal string ContractRelativePath( return string.Empty; } - if (basePath == null) - { - basePath = string.Empty; - } + basePath ??= string.Empty; providerBaseTracer.WriteLine("basePath = {0}", basePath); diff --git a/src/System.Management.Automation/namespaces/PathInfo.cs b/src/System.Management.Automation/namespaces/PathInfo.cs index f49d478c5e1..0c5483ceffa 100644 --- a/src/System.Management.Automation/namespaces/PathInfo.cs +++ b/src/System.Management.Automation/namespaces/PathInfo.cs @@ -79,7 +79,7 @@ public string ProviderPath private readonly SessionState _sessionState; /// - /// Gets the MSH path that this object represents. + /// Gets the PowerShell path that this object represents. /// public string Path { @@ -94,10 +94,10 @@ public string Path private readonly string _path = string.Empty; /// - /// Gets a string representing the MSH path. + /// Gets a string representing the PowerShell path. /// /// - /// A string representing the MSH path. + /// A string representing the PowerShell path. /// public override string ToString() { diff --git a/src/System.Management.Automation/namespaces/ProviderBase.cs b/src/System.Management.Automation/namespaces/ProviderBase.cs index 4ffc26db093..4345ec9f8ec 100644 --- a/src/System.Management.Automation/namespaces/ProviderBase.cs +++ b/src/System.Management.Automation/namespaces/ProviderBase.cs @@ -15,10 +15,12 @@ namespace System.Management.Automation.Provider { + /// /// This interface needs to be implemented by providers that want users to see /// provider-specific help. /// +#nullable enable public interface ICmdletProviderSupportsHelp { /// @@ -37,7 +39,7 @@ public interface ICmdletProviderSupportsHelp [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Maml", Justification = "Maml is an acronym.")] string GetHelpMaml(string helpItemName, string path); } - +#nullable restore #region CmdletProvider /// @@ -74,7 +76,7 @@ public abstract partial class CmdletProvider : IResourceSupplier /// An instance of the PSTraceSource class used for trace output /// using "CmdletProviderClasses" as the category. /// - [TraceSourceAttribute( + [TraceSource( "CmdletProviderClasses", "The namespace provider base classes tracer")] internal static readonly PSTraceSource providerBaseTracer = PSTraceSource.GetTracer( @@ -221,7 +223,7 @@ internal object StartDynamicParameters(CmdletProviderContext cmdletProviderConte /// /// /// The context under which this method is being called. - /// + /// internal void Stop(CmdletProviderContext cmdletProviderContext) { Context = cmdletProviderContext; @@ -258,7 +260,7 @@ internal void GetProperty( { Context = cmdletProviderContext; - if (!(this is IPropertyCmdletProvider propertyProvider)) + if (this is not IPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -296,7 +298,7 @@ internal object GetPropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IPropertyCmdletProvider propertyProvider)) + if (this is not IPropertyCmdletProvider propertyProvider) { return null; } @@ -325,7 +327,7 @@ internal void SetProperty( { Context = cmdletProviderContext; - if (!(this is IPropertyCmdletProvider propertyProvider)) + if (this is not IPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -363,7 +365,7 @@ internal object SetPropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IPropertyCmdletProvider propertyProvider)) + if (this is not IPropertyCmdletProvider propertyProvider) { return null; } @@ -395,7 +397,7 @@ internal void ClearProperty( { Context = cmdletProviderContext; - if (!(this is IPropertyCmdletProvider propertyProvider)) + if (this is not IPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -433,7 +435,7 @@ internal object ClearPropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IPropertyCmdletProvider propertyProvider)) + if (this is not IPropertyCmdletProvider propertyProvider) { return null; } @@ -477,7 +479,7 @@ internal void NewProperty( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -522,7 +524,7 @@ internal object NewPropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } @@ -554,7 +556,7 @@ internal void RemoveProperty( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -591,7 +593,7 @@ internal object RemovePropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } @@ -627,7 +629,7 @@ internal void RenameProperty( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -668,7 +670,7 @@ internal object RenamePropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } @@ -708,7 +710,7 @@ internal void CopyProperty( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -753,7 +755,7 @@ internal object CopyPropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } @@ -793,7 +795,7 @@ internal void MoveProperty( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { throw PSTraceSource.NewNotSupportedException( @@ -838,7 +840,7 @@ internal object MovePropertyDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IDynamicPropertyCmdletProvider propertyProvider)) + if (this is not IDynamicPropertyCmdletProvider propertyProvider) { return null; } @@ -869,7 +871,7 @@ internal IContentReader GetContentReader( { Context = cmdletProviderContext; - if (!(this is IContentCmdletProvider contentProvider)) + if (this is not IContentCmdletProvider contentProvider) { throw PSTraceSource.NewNotSupportedException( @@ -902,7 +904,7 @@ internal object GetContentReaderDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IContentCmdletProvider contentProvider)) + if (this is not IContentCmdletProvider contentProvider) { return null; } @@ -929,7 +931,7 @@ internal IContentWriter GetContentWriter( { Context = cmdletProviderContext; - if (!(this is IContentCmdletProvider contentProvider)) + if (this is not IContentCmdletProvider contentProvider) { throw PSTraceSource.NewNotSupportedException( @@ -962,7 +964,7 @@ internal object GetContentWriterDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IContentCmdletProvider contentProvider)) + if (this is not IContentCmdletProvider contentProvider) { return null; } @@ -986,7 +988,7 @@ internal void ClearContent( { Context = cmdletProviderContext; - if (!(this is IContentCmdletProvider contentProvider)) + if (this is not IContentCmdletProvider contentProvider) { throw PSTraceSource.NewNotSupportedException( @@ -1019,7 +1021,7 @@ internal object ClearContentDynamicParameters( { Context = cmdletProviderContext; - if (!(this is IContentCmdletProvider contentProvider)) + if (this is not IContentCmdletProvider contentProvider) { return null; } @@ -1350,7 +1352,7 @@ public PSHost Host /// public virtual char AltItemSeparator => #if UNIX - Utils.Separators.Backslash[0]; + '\\'; #else Path.AltDirectorySeparatorChar; #endif @@ -1417,6 +1419,7 @@ public virtual string GetResourceString(string baseName, string resourceId) #region ThrowTerminatingError /// + [System.Diagnostics.CodeAnalysis.DoesNotReturn] public void ThrowTerminatingError(ErrorRecord errorRecord) { using (PSTransactionManager.GetEngineProtectionScope()) @@ -1820,11 +1823,11 @@ private PSObject WrapOutputInPSObject( #if UNIX // Add a commonstat structure to file system objects - if (ExperimentalFeature.IsEnabled("PSUnixFileStat") && ProviderInfo.ImplementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider)) + if (ProviderInfo.ImplementingType == typeof(Microsoft.PowerShell.Commands.FileSystemProvider)) { try { - // Use LStat because if you get a link, you want the information about the + // Use LStat because if you get a link, you want the information about the // link, not the file. var commonStat = Platform.Unix.GetLStat(path); result.AddOrSetProperty("UnixStat", commonStat); @@ -1981,4 +1984,3 @@ public void WriteError(ErrorRecord errorRecord) } #pragma warning restore 56506 - diff --git a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs index c232b769fb3..7bc738c4e49 100644 --- a/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs +++ b/src/System.Management.Automation/namespaces/ProviderBaseSecurity.cs @@ -7,7 +7,7 @@ namespace System.Management.Automation.Provider { /// /// Defines the base class for all of the classes the provide implementations for a particular - /// data store or item for the MSH core commands. + /// data store or item for the PowerShell core commands. /// public abstract partial class CmdletProvider { diff --git a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs index d0c7bd018a1..cd38b92c177 100644 --- a/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs +++ b/src/System.Management.Automation/namespaces/ProviderDeclarationAttribute.cs @@ -77,55 +77,63 @@ public enum ProviderCapabilities { /// /// The provider does not add any additional capabilities beyond what the - /// Monad engine provides. + /// PowerShell engine provides. /// None = 0x0, /// + /// /// The provider does the inclusion filtering for those commands that take an Include - /// parameter. The Monad engine should not try to do the filtering on behalf of this + /// parameter. The PowerShell engine should not try to do the filtering on behalf of this /// provider. - /// - /// - /// Note, the provider should make every effort to filter in a way that is consistent - /// with the Monad engine. This option is allowed because in many cases the provider + /// + /// + /// The implementer of the provider should make every effort to filter in a way that is consistent + /// with the PowerShell engine. This option is allowed because in many cases the provider /// can be much more efficient at filtering. - /// + /// + /// Include = 0x1, /// + /// /// The provider does the exclusion filtering for those commands that take an Exclude - /// parameter. The Monad engine should not try to do the filtering on behalf of this + /// parameter. The PowerShell engine should not try to do the filtering on behalf of this /// provider. - /// - /// - /// Note, the provider should make every effort to filter in a way that is consistent - /// with the Monad engine. This option is allowed because in many cases the provider + /// + /// + /// The implementer of the provider should make every effort to filter in a way that is consistent + /// with the PowerShell engine. This option is allowed because in many cases the provider /// can be much more efficient at filtering. - /// + /// + /// Exclude = 0x2, /// + /// /// The provider can take a provider specific filter string. - /// - /// - /// When this attribute is specified a provider specific filter can be passed from + /// + /// + /// For implementers of providers using this attribute, a provider specific filter can be passed from /// the Core Commands to the provider. This filter string is not interpreted in any - /// way by the Monad engine. - /// + /// way by the PowerShell engine. + /// + /// Filter = 0x4, /// - /// The provider does the wildcard matching for those commands that allow for it. The Monad + /// + /// The provider does the wildcard matching for those commands that allow for it. The PowerShell /// engine should not try to do the wildcard matching on behalf of the provider when this /// flag is set. - /// - /// - /// Note, the provider should make every effort to do the wildcard matching in a way that is consistent - /// with the Monad engine. This option is allowed because in many cases wildcard matching + /// + /// + /// The implementer of the provider should make every effort to do the wildcard matching in a way that is consistent + /// with the PowerShell engine. This option is allowed because in many cases wildcard matching /// cannot occur via the path name or because the provider can do the matching in a much more /// efficient manner. - /// + /// + /// ExpandWildcards = 0x8, /// diff --git a/src/System.Management.Automation/namespaces/RegistryProvider.cs b/src/System.Management.Automation/namespaces/RegistryProvider.cs index 1898c960620..4e3b84716cd 100644 --- a/src/System.Management.Automation/namespaces/RegistryProvider.cs +++ b/src/System.Management.Automation/namespaces/RegistryProvider.cs @@ -28,7 +28,7 @@ namespace Microsoft.PowerShell.Commands /// /// INSTALLATION: /// - /// Type the following at an msh prompt: + /// Type the following at a PowerShell prompt: /// /// new-PSProvider -Path "REG.cmdletprovider" -description "My registry navigation provider" /// @@ -61,6 +61,9 @@ namespace Microsoft.PowerShell.Commands [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.GetItem)] [OutputType(typeof(RegistryKey), typeof(string), typeof(Int32), typeof(Int64), ProviderCmdlet = ProviderCmdlet.GetItemProperty)] [OutputType(typeof(RegistryKey), ProviderCmdlet = ProviderCmdlet.NewItem)] + [OutputType(typeof(string), typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.ResolvePath)] + [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PushLocation)] + [OutputType(typeof(PathInfo), ProviderCmdlet = ProviderCmdlet.PopLocation)] public sealed partial class RegistryProvider : NavigationCmdletProvider, IPropertyCmdletProvider, @@ -783,7 +786,7 @@ private static string EscapeSpecialChars(string path) Dbg.Diagnostics.Assert( textEnumerator != null, - string.Format(CultureInfo.CurrentCulture, "Cannot get a text enumerator for name {0}", path)); + string.Create(CultureInfo.CurrentCulture, $"Cannot get a text enumerator for name {path}")); while (textEnumerator.MoveNext()) { @@ -798,7 +801,7 @@ private static string EscapeSpecialChars(string path) // should not be done. if (textElement.Contains(charactersThatNeedEscaping)) { - // This text element needs espacing + // This text element needs escaping result.Append('`'); } @@ -832,7 +835,7 @@ private static string EscapeChildName(string name) Dbg.Diagnostics.Assert( textEnumerator != null, - string.Format(CultureInfo.CurrentCulture, "Cannot get a text enumerator for name {0}", name)); + string.Create(CultureInfo.CurrentCulture, $"Cannot get a text enumerator for name {name}")); while (textEnumerator.MoveNext()) { @@ -847,7 +850,7 @@ private static string EscapeChildName(string name) // should not be done. if (textElement.Contains(charactersThatNeedEscaping)) { - // This text element needs espacing + // This text element needs escaping result.Append('`'); } @@ -1822,8 +1825,19 @@ public void GetProperty( notePropertyName = LocalizedDefaultToken; } - propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); - valueAdded = true; + try + { + propertyResults.Properties.Add(new PSNoteProperty(notePropertyName, key.GetValue(valueName))); + valueAdded = true; + } + catch (InvalidCastException invalidCast) + { + WriteError(new ErrorRecord( + invalidCast, + invalidCast.GetType().FullName, + ErrorCategory.ReadError, + path)); + } } key.Close(); @@ -2993,10 +3007,7 @@ private void GetFilteredRegistryKeyProperties(string path, // If properties were not specified, get all the values - if (propertyNames == null) - { - propertyNames = new Collection(); - } + propertyNames ??= new Collection(); if (propertyNames.Count == 0 && getAll) { diff --git a/src/System.Management.Automation/namespaces/RegistryWrapper.cs b/src/System.Management.Automation/namespaces/RegistryWrapper.cs index 0e8e0558312..ebdbe833839 100644 --- a/src/System.Management.Automation/namespaces/RegistryWrapper.cs +++ b/src/System.Management.Automation/namespaces/RegistryWrapper.cs @@ -17,11 +17,13 @@ namespace Microsoft.PowerShell.Commands { + +#nullable enable internal interface IRegistryWrapper { - void SetValue(string name, object value); + void SetValue(string? name, object value); - void SetValue(string name, object value, RegistryValueKind valueKind); + void SetValue(string? name, object value, RegistryValueKind valueKind); string[] GetValueNames(); @@ -29,17 +31,17 @@ internal interface IRegistryWrapper string[] GetSubKeyNames(); - IRegistryWrapper CreateSubKey(string subkey); + IRegistryWrapper? CreateSubKey(string subkey); - IRegistryWrapper OpenSubKey(string name, bool writable); + IRegistryWrapper? OpenSubKey(string name, bool writable); void DeleteSubKeyTree(string subkey); - object GetValue(string name); + object? GetValue(string? name); - object GetValue(string name, object defaultValue, RegistryValueOptions options); + object? GetValue(string? name, object? defaultValue, RegistryValueOptions options); - RegistryValueKind GetValueKind(string name); + RegistryValueKind GetValueKind(string? name); object RegistryKey { get; } @@ -53,6 +55,7 @@ internal interface IRegistryWrapper int SubKeyCount { get; } } +#nullable restore internal static class RegistryWrapperUtils { diff --git a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs b/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs deleted file mode 100644 index 5e76b7cb3f3..00000000000 --- a/src/System.Management.Automation/namespaces/SafeRegistryHandle.cs +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// Namespace: Microsoft.Win32.SafeHandles -// -/*============================================================ -** -** -** -** A wrapper for registry handles -** -** -===========================================================*/ - -using System; -using System.Management.Automation; -using System.Security; -using System.Runtime.InteropServices; -using System.Runtime.Versioning; -using Microsoft.Win32.SafeHandles; -using System.Runtime.ConstrainedExecution; -using System.Security.Permissions; - -namespace Microsoft.PowerShell.Commands.Internal -{ - internal sealed class SafeRegistryHandle : SafeHandleZeroOrMinusOneIsInvalid - { - // Note: Officially -1 is the recommended invalid handle value for - // registry keys, but we'll also get back 0 as an invalid handle from - // RegOpenKeyEx. - - internal SafeRegistryHandle() : base(true) { } - - internal SafeRegistryHandle(IntPtr preexistingHandle, bool ownsHandle) : base(ownsHandle) - { - SetHandle(preexistingHandle); - } - - [DllImport(PinvokeDllNames.RegCloseKeyDllName), - SuppressUnmanagedCodeSecurity, - ResourceExposure(ResourceScope.None)] - internal static extern int RegCloseKey(IntPtr hKey); - - protected override bool ReleaseHandle() - { - // Returns a Win32 error code, 0 for success - int r = RegCloseKey(handle); - return r == 0; - } - } -} diff --git a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs b/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs deleted file mode 100644 index 01cef7dce46..00000000000 --- a/src/System.Management.Automation/namespaces/SafeTransactionHandle.cs +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -#pragma warning disable 1634, 1691 - -namespace Microsoft.PowerShell.Commands.Internal -{ - using System; - using System.Runtime.InteropServices; - using System.Transactions; - using Microsoft.Win32.SafeHandles; - using System.Management.Automation; - - [Guid("79427A2B-F895-40e0-BE79-B57DC82ED231"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] - internal interface IKernelTransaction - { - int GetHandle(out IntPtr pHandle); - } - - [System.Security.SuppressUnmanagedCodeSecurity] - internal sealed class SafeTransactionHandle : SafeHandleZeroOrMinusOneIsInvalid - { - private const string resBaseName = "RegistryProviderStrings"; - - private SafeTransactionHandle(IntPtr handle) - : base(true) - { - this.handle = handle; - } - - internal static SafeTransactionHandle Create() - { - return SafeTransactionHandle.Create(Transaction.Current); - } - - internal static SafeTransactionHandle Create(Transaction managedTransaction) - { - if (managedTransaction == null) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NeedTransaction); - } - - // MSDTC is not available on WinPE machine. - // CommitableTransaction will use DTC APIs under the covers to get KTM transaction manager interface. - // KTM is kernel Transaction Manager to handle file, registry etc and MSDTC provides an integration support - // with KTM to handle transaction across kernel resources and MSDTC resources like SQL, MSMQ etc. - // We need KTMRM service as well. WinPE doesn't have these services installed - if (Utils.IsWinPEHost() || PsUtils.IsRunningOnProcessorArchitectureARM()) - { - throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); - } - - IDtcTransaction dtcTransaction = TransactionInterop.GetDtcTransaction(managedTransaction); - IKernelTransaction ktmInterface = dtcTransaction as IKernelTransaction; - if (ktmInterface == null) - { - throw new NotSupportedException(RegistryProviderStrings.NotSupported_KernelTransactions); - } - - IntPtr ktmTxHandle; - int hr = ktmInterface.GetHandle(out ktmTxHandle); - HandleError(hr); - - return new SafeTransactionHandle(ktmTxHandle); - } - - protected override bool ReleaseHandle() - { - // We don't care about the value of GetLastError. -#pragma warning suppress 56523 - return Win32Native.CloseHandle(this.handle); - } - - private static void HandleError(int error) - { - if (error != Win32Native.ERROR_SUCCESS) - { - throw new System.ComponentModel.Win32Exception(error); - } - } - } -} diff --git a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs index 3f0f52c942e..e4199291437 100644 --- a/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs +++ b/src/System.Management.Automation/namespaces/SessionStateProviderBase.cs @@ -26,7 +26,7 @@ public abstract class SessionStateProviderBase : ContainerCmdletProvider, IConte /// /// An instance of the PSTraceSource class used for trace output. /// - [Dbg.TraceSourceAttribute( + [Dbg.TraceSource( "SessionStateProvider", "Providers that produce a view of session state data.")] private static readonly Dbg.PSTraceSource s_tracer = diff --git a/src/System.Management.Automation/namespaces/TransactedRegistry.cs b/src/System.Management.Automation/namespaces/TransactedRegistry.cs deleted file mode 100644 index 56062e6de6c..00000000000 --- a/src/System.Management.Automation/namespaces/TransactedRegistry.cs +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\Microsoft\Win32\Registry.cs. -// Namespace: Microsoft.Win32 -// - -using BCLDebug = System.Diagnostics.Debug; - -namespace Microsoft.PowerShell.Commands.Internal -{ - using System.Runtime.InteropServices; - using System.Runtime.Versioning; - using System.Diagnostics.CodeAnalysis; - - /** - * Registry encapsulation. Contains members representing all top level system - * keys. - * - * @security(checkClassLinking=on) - */ - // This class contains only static members and does not need to be serializable. - [ComVisible(true)] - // Suppressed because these objects need to be accessed from CmdLets. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - internal static class TransactedRegistry - { - private const string resBaseName = "RegistryProviderStrings"; - /** - * Current User Key. - * - * This key should be used as the root for all user specific settings. - */ - /// TransactedRegistry.CurrentUser - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_CURRENT_USER. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - [ResourceExposure(ResourceScope.Machine)] - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey CurrentUser = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CURRENT_USER); - - /** - * Local Machine Key. - * - * This key should be used as the root for all machine specific settings. - */ - /// TransactedRegistry.LocalMachine - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_LOCAL_MACHINE. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - [ResourceExposure(ResourceScope.Machine)] - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey LocalMachine = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_LOCAL_MACHINE); - - /** - * Classes Root Key. - * - * This is the root key of class information. - */ - /// TransactedRegistry.ClassesRoot - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_CLASSES_ROOT. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - [ResourceExposure(ResourceScope.Machine)] - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey ClassesRoot = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CLASSES_ROOT); - - /** - * Users Root Key. - * - * This is the root of users. - */ - /// TransactedRegistry.Users - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_USERS. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - [ResourceExposure(ResourceScope.Machine)] - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey Users = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_USERS); - - /** - * Current Config Root Key. - * - * This is where current configuration information is stored. - */ - /// TransactedRegistry.CurrentConfig - /// This static method returns a TransactedRegistryKey object that represents the base - /// key HKEY_CURRENT_CONFIG. Because it is a base key, there is no transaction associated with - /// the returned TransactedRegistryKey. This means that values modified using the returned - /// TransactedRegistryKey are NOT modified within a transaction. - /// However, if the returned TransactedRegistryKey is used to create, open, or delete - /// subkeys, there must be a Transaction.Current and the resulting TransactedRegistryKey from those operations ARE associated with - /// the transaction. - /// - [ResourceExposure(ResourceScope.Machine)] - // The TransactedRegistryKey's members cannot be changed. - [SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] - internal static readonly TransactedRegistryKey CurrentConfig = TransactedRegistryKey.GetBaseKey(BaseRegistryKeys.HKEY_CURRENT_CONFIG); - } -} diff --git a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs b/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs deleted file mode 100644 index dac6f6c0897..00000000000 --- a/src/System.Management.Automation/namespaces/TransactedRegistryKey.cs +++ /dev/null @@ -1,2091 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\Microsoft\Win32\RegistryKey.cs. -// Namespace: Microsoft.Win32 -// -/* - Note on transaction support: - Eventually we will want to add support for NT's transactions to our - TransactedRegistryKey API's (possibly Whidbey M3?). When we do this, here's - the list of API's we need to make transaction-aware: - - RegCreateKeyEx - RegDeleteKey - RegDeleteValue - RegEnumKeyEx - RegEnumValue - RegOpenKeyEx - RegQueryInfoKey - RegQueryValueEx - RegSetValueEx - - We can ignore RegConnectRegistry (remote registry access doesn't yet have - transaction support) and RegFlushKey. RegCloseKey doesn't require any - additional work. . - */ - -/* - Note on ACL support: - The key thing to note about ACL's is you set them on a kernel object like a - registry key, then the ACL only gets checked when you construct handles to - them. So if you set an ACL to deny read access to yourself, you'll still be - able to read with that handle, but not with new handles. - - Another peculiarity is a Terminal Server app compatibility hack. The OS - will second guess your attempt to open a handle sometimes. If a certain - combination of Terminal Server app compat registry keys are set, then the - OS will try to reopen your handle with lesser permissions if you couldn't - open it in the specified mode. So on some machines, we will see handles that - may not be able to read or write to a registry key. It's very strange. But - the real test of these handles is attempting to read or set a value in an - affected registry key. - - For reference, at least two registry keys must be set to particular values - for this behavior: - HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Terminal Server\RegistryExtensionFlags, the least significant bit must be 1. - HKLM\SYSTEM\CurrentControlSet\Control\TerminalServer\TSAppCompat must be 1 - There might possibly be an interaction with yet a third registry key as well. - -*/ - -using BCLDebug = System.Diagnostics.Debug; - -namespace Microsoft.PowerShell.Commands.Internal -{ - using System; - using System.Collections.Generic; - using System.Security; - using System.Security.AccessControl; - using System.Security.Permissions; - using System.Text; - using System.IO; - using System.Runtime.InteropServices; - using Microsoft.Win32; - using System.Runtime.Versioning; - using System.Globalization; - using System.Transactions; - using System.Diagnostics.CodeAnalysis; - - // Putting this in a separate internal class to avoid OACR warning DoNotDeclareReadOnlyMutableReferenceTypes. - internal sealed class BaseRegistryKeys - { - // We could use const here, if C# supported ELEMENT_TYPE_I fully. - internal static readonly IntPtr HKEY_CLASSES_ROOT = new IntPtr(unchecked((int)0x80000000)); - internal static readonly IntPtr HKEY_CURRENT_USER = new IntPtr(unchecked((int)0x80000001)); - internal static readonly IntPtr HKEY_LOCAL_MACHINE = new IntPtr(unchecked((int)0x80000002)); - internal static readonly IntPtr HKEY_USERS = new IntPtr(unchecked((int)0x80000003)); - internal static readonly IntPtr HKEY_CURRENT_CONFIG = new IntPtr(unchecked((int)0x80000005)); - } - - /// - /// Registry encapsulation. To get an instance of a TransactedRegistryKey use the - /// Registry class's static members then call OpenSubKey. - /// - /// @see Registry - /// @security(checkDllCalls=off) - /// @security(checkClassLinking=on) - /// - [ComVisible(true)] - // Suppressed because these objects are written to the pipeline so need to be accessible. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistryKey : MarshalByRefObject, IDisposable - { - private const string resBaseName = "RegistryProviderStrings"; - - // Dirty indicates that we have munged data that should be potentially - // written to disk. - // - private const int STATE_DIRTY = 0x0001; - - // SystemKey indicates that this is a "SYSTEMKEY" and shouldn't be "opened" - // or "closed". - // - private const int STATE_SYSTEMKEY = 0x0002; - - // Access - // - private const int STATE_WRITEACCESS = 0x0004; - - // Names of keys. This array must be in the same order as the HKEY values listed above. - // - private static readonly string[] s_hkeyNames = new string[] { - "HKEY_CLASSES_ROOT", - "HKEY_CURRENT_USER", - "HKEY_LOCAL_MACHINE", - "HKEY_USERS", - "HKEY_PERFORMANCE_DATA", - "HKEY_CURRENT_CONFIG", - "HKEY_DYN_DATA" - }; - - // MSDN defines the following limits for registry key names & values: - // Key Name: 255 characters - // Value name: Win9x: 255 NT: 16,383 Unicode characters, or 260 ANSI chars - // Value: either 1 MB or current available memory, depending on registry format. - private const int MaxKeyLength = 255; - private const int MaxValueNameLength = 16383; - private const int MaxValueDataLength = 1024 * 1024; - - private SafeRegistryHandle _hkey = null; - private int _state = 0; - private string _keyName; - private RegistryKeyPermissionCheck _checkMode; - private System.Transactions.Transaction _myTransaction; - private SafeTransactionHandle _myTransactionHandle; - - // This is a wrapper around RegOpenKeyTransacted that implements a workaround - // to TxF bug number 181242 After calling RegOpenKeyTransacted, it calls RegQueryInfoKey. - // If that call fails with ERROR_INVALID_TRANSACTION, we have possibly run into bug 181242. To workaround - // this, we open the key without a transaction and then open it again with - // a transaction and return THAT hkey. - - // Suppressed because there is no way for arbitrary data to be passed. - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] - private int RegOpenKeyTransactedWrapper(SafeRegistryHandle hKey, string lpSubKey, - int ulOptions, int samDesired, out SafeRegistryHandle hkResult, - SafeTransactionHandle hTransaction, IntPtr pExtendedParameter) - { - int error = Win32Native.ERROR_SUCCESS; - SafeRegistryHandle hKeyToReturn = null; - - error = Win32Native.RegOpenKeyTransacted(_hkey, lpSubKey, ulOptions, samDesired, out hKeyToReturn, hTransaction, pExtendedParameter); - - if (Win32Native.ERROR_SUCCESS == error && !hKeyToReturn.IsInvalid) - { - // This is a check and workaround for TxR bug 181242. If we try to use the transacted hKey we just opened - // for a call to RegQueryInfoKey and get back a ERROR_INVALID_TRANSACTION error, then the key might be a symbolic link and TxR didn't - // do the open correctly. The workaround is to open it non-transacted, then open it again transacted without - // a subkey string. If we get some error other than ERROR_INVALID_TRANSACTION from RegQueryInfoKey, just ignore it for now. - int subkeyCount = 0; - int valueCount = 0; - error = Win32Native.RegQueryInfoKey(hKeyToReturn, - null, - null, - Win32Native.NULL, - ref subkeyCount, // subkeys - null, - null, - ref valueCount, // values - null, - null, - null, - null); - if (Win32Native.ERROR_INVALID_TRANSACTION == error) - { - SafeRegistryHandle nonTxKey = null; - SafeRegistryHandle txKey = null; - error = Win32Native.RegOpenKeyEx(_hkey, lpSubKey, ulOptions, samDesired, out nonTxKey); - // If we got some error on this open, just ignore it and continue on with the handle - // we got on the original RegOpenKeyTransacted. - if (Win32Native.ERROR_SUCCESS == error) - { - // Now do an RegOpenKeyTransacted with the non-transacted key and no "subKey" parameter. - error = Win32Native.RegOpenKeyTransacted(nonTxKey, null, ulOptions, samDesired, out txKey, hTransaction, pExtendedParameter); - if (Win32Native.ERROR_SUCCESS == error) - { - // Let's use this hkey instead. - hKeyToReturn.Dispose(); - hKeyToReturn = txKey; - } - - nonTxKey.Dispose(); - nonTxKey = null; - } - } - } - - hkResult = hKeyToReturn; - return error; - } - - /** - * Creates a TransactedRegistryKey. - * - * This key is bound to hkey, if writable is false then no write operations - * will be allowed. If systemkey is set then the hkey won't be released - * when the object is GC'ed. - */ - private TransactedRegistryKey(SafeRegistryHandle hkey, bool writable, bool systemkey, - System.Transactions.Transaction transaction, SafeTransactionHandle txHandle) - { - _hkey = hkey; - _keyName = string.Empty; - if (systemkey) - { - _state |= STATE_SYSTEMKEY; - } - - if (writable) - { - _state |= STATE_WRITEACCESS; - } - // We want to take our own clone so we can dispose it when we want and - // aren't susceptible to the caller disposing it. - if (transaction != null) - { - _myTransaction = transaction.Clone(); - _myTransactionHandle = txHandle; - } - else - { - _myTransaction = null; - _myTransactionHandle = null; - } - } - - private SafeTransactionHandle GetTransactionHandle() - { - SafeTransactionHandle safeTransactionHandle = null; - - // If myTransaction is not null and is not the same as Transaction.Current - // this is an invalid operation. The transaction within which the RegistryKey object was created - // needs to be the same as the transaction being used now. - if (_myTransaction != null) - { - if (!_myTransaction.Equals(Transaction.Current)) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction); - } - else - { - safeTransactionHandle = _myTransactionHandle; - } - } - else // we want to use Transaction.Current for the transaction. - { - safeTransactionHandle = SafeTransactionHandle.Create(); - } - - return safeTransactionHandle; - } - - /// TransactedRegistryKey.Close - /// Closes this key, flushes it to disk if the contents have been modified. - /// Utilizes Transaction.Current for its transaction. - /// - public void Close() - { - Dispose(true); - } - - private void Dispose(bool disposing) - { - if (_hkey != null) - { - if (!IsSystemKey()) - { - try - { - _hkey.Dispose(); - } - catch (IOException) - { - // we don't really care if the handle is invalid at this point - } - finally - { - _hkey = null; - } - } - } - - if (_myTransaction != null) - { - // Dispose the transaction because we cloned it. - try - { - _myTransaction.Dispose(); - } - catch (TransactionException) - { - // ignore. - } - finally - { - _myTransaction = null; - } - } - } - - /// TransactedRegistryKey.Flush - /// Flushes this key. Utilizes Transaction.Current for its transaction. - /// - public void Flush() - { - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - if (_hkey != null) - { - if (IsDirty()) - { - int ret = Win32Native.RegFlushKey(_hkey); - if (Win32Native.ERROR_SUCCESS != ret) - { - throw new IOException(Win32Native.GetMessage(ret), ret); - } - } - } - } - - /// TransactedRegistryKey.Dispose - /// Disposes this key. Utilizes Transaction.Current for its transaction. - /// - public void Dispose() - { - Dispose(true); - } - - /// - /// Creates a new subkey, or opens an existing one. - /// Utilizes Transaction.Current for its transaction. - /// Name or path to subkey to create or open. Cannot be null or an empty string, - /// otherwise an ArgumentException is thrown. - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey CreateSubKey(string subkey) - { - return CreateSubKey(subkey, _checkMode); - } - - /// - /// Creates a new subkey, or opens an existing one. - /// Utilizes Transaction.Current for its transaction. - /// Name or path to subkey to create or open. Cannot be null or an empty string, - /// otherwise an ArgumentException is thrown. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that - /// specifies whether the key is opened for read or read/write access. - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// - [ComVisible(false)] - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck) - { - return CreateSubKeyInternal(subkey, permissionCheck, (TransactedRegistrySecurity)null); - } - - /// - /// Creates a new subkey, or opens an existing one. - /// Utilizes Transaction.Current for its transaction. - /// Name or path to subkey to create or open. Cannot be null or an empty string, - /// otherwise an ArgumentException is thrown. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that - /// specifies whether the key is opened for read or read/write access. - /// A TransactedRegistrySecurity object that specifies the access control security for the new key. - /// A TransactedRegistryKey object for the subkey, which is associated with Transaction.Current. - /// returns null if the operation failed. - /// - [ComVisible(false)] - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public unsafe TransactedRegistryKey CreateSubKey(string subkey, RegistryKeyPermissionCheck permissionCheck, TransactedRegistrySecurity registrySecurity) - { - return CreateSubKeyInternal(subkey, permissionCheck, registrySecurity); - } - - [ComVisible(false)] - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private unsafe TransactedRegistryKey CreateSubKeyInternal(string subkey, RegistryKeyPermissionCheck permissionCheck, object registrySecurityObj) - { - ValidateKeyName(subkey); - // RegCreateKeyTransacted requires a non-empty key name, so let's deal with that here. - if (string.Empty == subkey) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrEmpty); - } - - ValidateKeyMode(permissionCheck); - EnsureWriteable(); - subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - - // only keys opened under read mode is not writable - TransactedRegistryKey existingKey = InternalOpenSubKey(subkey, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree)); - if (existingKey != null) - { // Key already exits - CheckSubKeyWritePermission(subkey); - CheckSubTreePermission(subkey, permissionCheck); - existingKey._checkMode = permissionCheck; - return existingKey; - } - - CheckSubKeyCreatePermission(subkey); - - Win32Native.SECURITY_ATTRIBUTES secAttrs = null; - TransactedRegistrySecurity registrySecurity = registrySecurityObj as TransactedRegistrySecurity; - // For ACL's, get the security descriptor from the RegistrySecurity. - if (registrySecurity != null) - { - secAttrs = new Win32Native.SECURITY_ATTRIBUTES(); - secAttrs.nLength = (int)Marshal.SizeOf(secAttrs); - - byte[] sd = registrySecurity.GetSecurityDescriptorBinaryForm(); - // We allocate memory on the stack to improve the speed. - // So this part of code can't be refactored into a method. - byte* pSecDescriptor = stackalloc byte[sd.Length]; - Microsoft.PowerShell.Commands.Internal.Buffer.memcpy(sd, 0, pSecDescriptor, 0, sd.Length); - secAttrs.pSecurityDescriptor = pSecDescriptor; - } - - int disposition = 0; - - // By default, the new key will be writable. - SafeRegistryHandle result = null; - int ret = 0; - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = Win32Native.RegCreateKeyTransacted(_hkey, - subkey, - 0, - null, - 0, - GetRegistryKeyAccess(permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), - secAttrs, - out result, - out disposition, - safeTransactionHandle, - IntPtr.Zero - ); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck != RegistryKeyPermissionCheck.ReadSubTree), false, - Transaction.Current, safeTransactionHandle); - CheckSubTreePermission(subkey, permissionCheck); - key._checkMode = permissionCheck; - - if (subkey.Length == 0) - key._keyName = _keyName; - else - key._keyName = _keyName + "\\" + subkey; - return key; - } - else if (ret != 0) // syscall failed, ret is an error code. - Win32Error(ret, _keyName + "\\" + subkey); // Access denied? - - BCLDebug.Assert(false, "Unexpected code path in RegistryKey::CreateSubKey"); - return null; - } - - /// - /// Deletes the specified subkey. Will throw an exception if the subkey has - /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. - /// Utilizes Transaction.Current for its transaction. - /// The subkey to delete. - /// Thrown if the subkey as child subkeys. - /// - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public void DeleteSubKey(string subkey) - { - DeleteSubKey(subkey, true); - } - - /// - /// Deletes the specified subkey. Will throw an exception if the subkey has - /// subkeys. To delete a tree of subkeys use, DeleteSubKeyTree. - /// Utilizes Transaction.Current for its transaction. - /// The subkey to delete. - /// Specify true if an ArgumentException should be thrown if - /// the specified subkey does not exist. If false is specified, a missing subkey does not throw - /// an exception. - /// Thrown if the subkey as child subkeys. - /// Thrown if true is specified for throwOnMissingSubKey and the - /// specified subkey does not exist. - /// - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public void DeleteSubKey(string subkey, bool throwOnMissingSubKey) - { - ValidateKeyName(subkey); - EnsureWriteable(); - subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - CheckSubKeyWritePermission(subkey); - - // Open the key we are deleting and check for children. Be sure to - // explicitly call close to avoid keeping an extra HKEY open. - // - TransactedRegistryKey key = InternalOpenSubKey(subkey, false); - if (key != null) - { - try - { - if (key.InternalSubKeyCount() > 0) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_RegRemoveSubKey); - } - } - finally - { - key.Close(); - } - - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - - if (ret != 0) - { - if (ret == Win32Native.ERROR_FILE_NOT_FOUND) - { - if (throwOnMissingSubKey) - { - throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); - } - } - else - Win32Error(ret, null); - } - } - else - { // there is no key which also means there is no subkey - if (throwOnMissingSubKey) - throw new ArgumentException(RegistryProviderStrings.ArgumentException_RegSubKeyAbsent); - } - } - - /// - /// Recursively deletes a subkey and any child subkeys. - /// Utilizes Transaction.Current for its transaction. - /// The subkey to delete. - /// - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public void DeleteSubKeyTree(string subkey) - { - ValidateKeyName(subkey); - - // Security concern: Deleting a hive's "" subkey would delete all - // of that hive's contents. Don't allow "". - if ((string.IsNullOrEmpty(subkey) || subkey.Length == 0) && IsSystemKey()) - { - throw new ArgumentException(RegistryProviderStrings.ArgRegKeyDelHive); - } - - EnsureWriteable(); - - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - subkey = FixupName(subkey); // Fixup multiple slashes to a single slash - CheckSubTreeWritePermission(subkey); - - TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) - { - try - { - if (key.InternalSubKeyCount() > 0) - { - string[] keys = key.InternalGetSubKeyNames(); - - for (int i = 0; i < keys.Length; i++) - { - key.DeleteSubKeyTreeInternal(keys[i]); - } - } - } - finally - { - key.Close(); - } - - ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - if (ret != 0) Win32Error(ret, null); - } - else - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyAbsent); - } - } - - // An internal version which does no security checks or argument checking. Skipping the - // security checks should give us a slight perf gain on large trees. - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private void DeleteSubKeyTreeInternal(string subkey) - { - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - TransactedRegistryKey key = InternalOpenSubKey(subkey, true); - if (key != null) - { - try - { - if (key.InternalSubKeyCount() > 0) - { - string[] keys = key.InternalGetSubKeyNames(); - - for (int i = 0; i < keys.Length; i++) - { - key.DeleteSubKeyTreeInternal(keys[i]); - } - } - } - finally - { - key.Close(); - } - - ret = Win32Native.RegDeleteKeyTransacted(_hkey, subkey, 0, 0, safeTransactionHandle, IntPtr.Zero); - if (ret != 0) Win32Error(ret, null); - } - else - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyAbsent); - } - } - - /// - /// Deletes the specified value from this key. - /// Utilizes Transaction.Current for its transaction. - /// Name of the value to delete. - /// - [ResourceExposure(ResourceScope.None)] - [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - public void DeleteValue(string name) - { - DeleteValue(name, true); - } - - /// - /// Deletes the specified value from this key. - /// Utilizes Transaction.Current for its transaction. - /// Name of the value to delete. - /// Specify true if an ArgumentException should be thrown if - /// the specified value does not exist. If false is specified, a missing value does not throw - /// an exception. - /// - [ResourceExposure(ResourceScope.None)] - [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] - public void DeleteValue(string name, bool throwOnMissingValue) - { - EnsureWriteable(); - CheckValueWritePermission(name); - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - int errorCode = Win32Native.RegDeleteValue(_hkey, name); - - // - // From windows 2003 server, if the name is too long we will get error code ERROR_FILENAME_EXCED_RANGE - // This still means the name doesn't exist. We need to be consistent with previous OS. - // - if (errorCode == Win32Native.ERROR_FILE_NOT_FOUND || errorCode == Win32Native.ERROR_FILENAME_EXCED_RANGE) - { - if (throwOnMissingValue) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSubKeyValueAbsent); - } - else - { - errorCode = Win32Native.ERROR_SUCCESS; - } - } - - if (Win32Native.ERROR_SUCCESS != errorCode) - { - Win32Error(errorCode, null); - } - } - - /** - * Retrieves a new TransactedRegistryKey that represents the requested key. Valid - * values are: - * - * HKEY_CLASSES_ROOT, - * HKEY_CURRENT_USER, - * HKEY_LOCAL_MACHINE, - * HKEY_USERS, - * HKEY_PERFORMANCE_DATA, - * HKEY_CURRENT_CONFIG, - * HKEY_DYN_DATA. - * - * @param hKey HKEY_* to open. - * - * @return the TransactedRegistryKey requested. - */ - internal static TransactedRegistryKey GetBaseKey(IntPtr hKey) - { - int index = ((int)hKey) & 0x0FFFFFFF; - BCLDebug.Assert(index >= 0 && index < s_hkeyNames.Length, "index is out of range!"); - BCLDebug.Assert((((int)hKey) & 0xFFFFFFF0) == 0x80000000, "Invalid hkey value!"); - - SafeRegistryHandle srh = new SafeRegistryHandle(hKey, false); - - // For Base keys, there is no transaction associated with the HKEY. - TransactedRegistryKey key = new TransactedRegistryKey(srh, true, true, null, null); - key._checkMode = RegistryKeyPermissionCheck.Default; - key._keyName = s_hkeyNames[index]; - return key; - } - - /// - /// Retrieves a subkey. If readonly is true, then the subkey is opened with - /// read-only access. - /// Utilizes Transaction.Current for its transaction. - /// Name or path of the subkey to open. - /// Set to true of you only need readonly access. - /// The subkey requested or null if the operation failed. - /// - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, bool writable) - { - ValidateKeyName(name); - EnsureNotDisposed(); - name = FixupName(name); // Fixup multiple slashes to a single slash - - CheckOpenSubKeyPermission(name, writable); - SafeRegistryHandle result = null; - int ret = 0; - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, GetRegistryKeyAccess(writable), out result, safeTransactionHandle, IntPtr.Zero); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle); - key._checkMode = GetSubKeyPermissionCheck(writable); - key._keyName = _keyName + "\\" + name; - return key; - } - - // Return null if we didn't find the key. - if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) - { - // We need to throw SecurityException here for compatibility reasons, - // although UnauthorizedAccessException will make more sense. - throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); - } - - return null; - } - - /// - /// Retrieves a subkey. - /// Utilizes Transaction.Current for its transaction. - /// Name or path of the subkey to open. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies - /// whether the key is opened for read or read/write access. - /// The subkey requested or null if the operation failed. - /// - [ComVisible(false)] - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck) - { - ValidateKeyMode(permissionCheck); - return InternalOpenSubKey(name, permissionCheck, GetRegistryKeyAccess(permissionCheck)); - } - - /// - /// Retrieves a subkey. - /// Utilizes Transaction.Current for its transaction. - /// Name or path of the subkey to open. - /// One of the Microsoft.Win32.RegistryKeyPermissionCheck values that specifies - /// whether the key is opened for read or read/write access. - /// A bitwise combination of Microsoft.Win32.RegistryRights values that specifies the desired security access. - /// The subkey requested or null if the operation failed. - /// - [ComVisible(false)] - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, RegistryRights rights) - { - return InternalOpenSubKey(name, permissionCheck, (int)rights); - } - - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private TransactedRegistryKey InternalOpenSubKey(string name, RegistryKeyPermissionCheck permissionCheck, int rights) - { - ValidateKeyName(name); - ValidateKeyMode(permissionCheck); - ValidateKeyRights(rights); - EnsureNotDisposed(); - name = FixupName(name); // Fixup multiple slashes to a single slash - - CheckOpenSubKeyPermission(name, permissionCheck); - SafeRegistryHandle result = null; - int ret = 0; - - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, rights, out result, safeTransactionHandle, IntPtr.Zero); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, (permissionCheck == RegistryKeyPermissionCheck.ReadWriteSubTree), false, - Transaction.Current, safeTransactionHandle); - key._keyName = _keyName + "\\" + name; - key._checkMode = permissionCheck; - return key; - } - - // Return null if we didn't find the key. - if (ret == Win32Native.ERROR_ACCESS_DENIED || ret == Win32Native.ERROR_BAD_IMPERSONATION_LEVEL) - { - // We need to throw SecurityException here for compatibility reason, - // although UnauthorizedAccessException will make more sense. - throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); - } - - return null; - } - - // This required no security checks. This is to get around the Deleting SubKeys which only require - // write permission. They call OpenSubKey which required read. Now instead call this function w/o security checks - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - internal TransactedRegistryKey InternalOpenSubKey(string name, bool writable) - { - ValidateKeyName(name); - EnsureNotDisposed(); - - int winAccess = GetRegistryKeyAccess(writable); - SafeRegistryHandle result = null; - int ret = 0; - SafeTransactionHandle safeTransactionHandle = GetTransactionHandle(); - - ret = RegOpenKeyTransactedWrapper(_hkey, name, 0, winAccess, out result, safeTransactionHandle, IntPtr.Zero); - - if (ret == 0 && !result.IsInvalid) - { - TransactedRegistryKey key = new TransactedRegistryKey(result, writable, false, Transaction.Current, safeTransactionHandle); - key._keyName = _keyName + "\\" + name; - return key; - } - - return null; - } - - /// - /// Retrieves a subkey for readonly access. - /// Utilizes Transaction.Current for its transaction. - /// Name or path of the subkey to open. - /// The subkey requested or null if the operation failed. - /// - [ResourceExposure(ResourceScope.Machine)] - [ResourceConsumption(ResourceScope.Machine)] - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public TransactedRegistryKey OpenSubKey(string name) - { - return OpenSubKey(name, false); - } - - /// - /// Retrieves the count of subkeys. - /// Utilizes Transaction.Current for its transaction. - /// The count of subkeys. - /// - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public int SubKeyCount - { - get - { - CheckKeyReadPermission(); - return InternalSubKeyCount(); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - internal int InternalSubKeyCount() - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - - int subkeys = 0; - int junk = 0; - int ret = Win32Native.RegQueryInfoKey(_hkey, - null, - null, - Win32Native.NULL, - ref subkeys, // subkeys - null, - null, - ref junk, // values - null, - null, - null, - null); - - if (ret != 0) - Win32Error(ret, null); - return subkeys; - } - - /// - /// Retrieves an array of strings containing all the subkey names. - /// Utilizes Transaction.Current for its transaction. - /// A string array containing all the subkey names. - /// - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - public string[] GetSubKeyNames() - { - CheckKeyReadPermission(); - return InternalGetSubKeyNames(); - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - internal string[] InternalGetSubKeyNames() - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - int subkeys = InternalSubKeyCount(); - string[] names = new string[subkeys]; // Returns 0-length array if empty. - - if (subkeys > 0) - { - StringBuilder name = new StringBuilder(256); - int namelen; - - for (int i = 0; i < subkeys; i++) - { - namelen = name.Capacity; // Don't remove this. The API's doesn't work if this is not properly initialised. - int ret = Win32Native.RegEnumKeyEx(_hkey, - i, - name, - out namelen, - null, - null, - null, - null); - if (ret != 0) - Win32Error(ret, null); - names[i] = name.ToString(); - } - } - - return names; - } - - /// - /// Retrieves the count of values. - /// Utilizes Transaction.Current for its transaction. - /// A count of values. - /// - public int ValueCount - { - get - { - CheckKeyReadPermission(); - return InternalValueCount(); - } - } - - internal int InternalValueCount() - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - int values = 0; - int junk = 0; - int ret = Win32Native.RegQueryInfoKey(_hkey, - null, - null, - Win32Native.NULL, - ref junk, // subkeys - null, - null, - ref values, // values - null, - null, - null, - null); - if (ret != 0) - Win32Error(ret, null); - return values; - } - - /// - /// Retrieves an array of strings containing all the value names. - /// Utilizes Transaction.Current for its transaction. - /// All the value names. - /// - public string[] GetValueNames() - { - CheckKeyReadPermission(); - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - - int values = InternalValueCount(); - string[] names = new string[values]; - - if (values > 0) - { - StringBuilder name = new StringBuilder(256); - int namelen; - int currentlen; - int ret; - - for (int i = 0; i < values; i++) - { - currentlen = name.Capacity; - ret = Win32Native.ERROR_MORE_DATA; - - // loop while we get error_more_data or until we have exceeded - // the max name length. - while (Win32Native.ERROR_MORE_DATA == ret) - { - namelen = currentlen; - ret = Win32Native.RegEnumValue(_hkey, - i, - name, - ref namelen, - Win32Native.NULL, - null, - null, - null); - - if (ret != 0) - { - if (ret != Win32Native.ERROR_MORE_DATA) - Win32Error(ret, null); - - // We got ERROR_MORE_DATA. Let's see if we can make the buffer - // bigger. - if (MaxValueNameLength == currentlen) - Win32Error(ret, null); - - currentlen = currentlen * 2; - if (MaxValueNameLength < currentlen) - currentlen = MaxValueNameLength; - - // Allocate a new buffer. - name = new StringBuilder(currentlen); - } - } - - names[i] = name.ToString(); - } - } - - return names; - } - - /// - /// Retrieves the specified value. null is returned if the value - /// doesn't exist. Utilizes Transaction.Current for its transaction. - /// Note that name can be null or "", at which point the - /// unnamed or default value of this Registry key is returned, if any. - /// Name of value to retrieve. - /// The data associated with the value. - /// - public object GetValue(string name) - { - CheckValueReadPermission(name); - return InternalGetValue(name, null, false, true); - } - - /// - /// Retrieves the specified value. null is returned if the value - /// doesn't exist. Utilizes Transaction.Current for its transaction. - /// Note that name can be null or "", at which point the - /// unnamed or default value of this Registry key is returned, if any. - /// Name of value to retrieve. - /// Value to return if name doesn't exist. - /// The data associated with the value. - /// - public object GetValue(string name, object defaultValue) - { - CheckValueReadPermission(name); - return InternalGetValue(name, defaultValue, false, true); - } - - /// - /// Retrieves the specified value. null is returned if the value - /// doesn't exist. Utilizes Transaction.Current for its transaction. - /// Note that name can be null or "", at which point the - /// unnamed or default value of this Registry key is returned, if any. - /// Name of value to retrieve. - /// Value to return if name doesn't exist. - /// One of the Microsoft.Win32.RegistryValueOptions values that specifies - /// optional processing of the retrieved value. - /// The data associated with the value. - /// - [ComVisible(false)] - public object GetValue(string name, object defaultValue, RegistryValueOptions options) - { - if (options < RegistryValueOptions.None || options > RegistryValueOptions.DoNotExpandEnvironmentNames) - { - string resourceTemplate = RegistryProviderStrings.Arg_EnumIllegalVal; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, options.ToString()); - throw new ArgumentException(resource); - } - - bool doNotExpand = (options == RegistryValueOptions.DoNotExpandEnvironmentNames); - CheckValueReadPermission(name); - return InternalGetValue(name, defaultValue, doNotExpand, true); - } - - internal object InternalGetValue(string name, object defaultValue, bool doNotExpand, bool checkSecurity) - { - if (checkSecurity) - { - // Name can be null! It's the most common use of RegQueryValueEx - EnsureNotDisposed(); - } - - // Don't require a transaction. We don't want to throw for "Base" keys. - - object data = defaultValue; - int type = 0; - int datasize = 0; - - int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - - if (ret != 0) - { - // For stuff like ERROR_FILE_NOT_FOUND, we want to return null (data). - // Some OS's returned ERROR_MORE_DATA even in success cases, so we - // want to continue on through the function. - if (ret != Win32Native.ERROR_MORE_DATA) - return data; - } - - switch (type) - { - case Win32Native.REG_DWORD_BIG_ENDIAN: - case Win32Native.REG_BINARY: - { - byte[] blob = new byte[datasize]; - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - data = blob; - } - - break; - case Win32Native.REG_QWORD: - { // also REG_QWORD_LITTLE_ENDIAN - if (datasize > 8) - { - // prevent an AV in the edge case that datasize is larger than sizeof(long) - goto case Win32Native.REG_BINARY; - } - - long blob = 0; - BCLDebug.Assert(datasize == 8, "datasize==8"); - // Here, datasize must be 8 when calling this - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); - - data = blob; - } - - break; - case Win32Native.REG_DWORD: - { // also REG_DWORD_LITTLE_ENDIAN - if (datasize > 4) - { - // prevent an AV in the edge case that datasize is larger than sizeof(int) - goto case Win32Native.REG_QWORD; - } - - int blob = 0; - BCLDebug.Assert(datasize == 4, "datasize==4"); - // Here, datasize must be four when calling this - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, ref blob, ref datasize); - - data = blob; - } - - break; - - case Win32Native.REG_SZ: - { - StringBuilder blob = new StringBuilder(datasize / 2); - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - data = blob.ToString(); - } - - break; - - case Win32Native.REG_EXPAND_SZ: - { - StringBuilder blob = new StringBuilder(datasize / 2); - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - if (doNotExpand) - data = blob.ToString(); - else - data = Environment.ExpandEnvironmentVariables(blob.ToString()); - } - - break; - case Win32Native.REG_MULTI_SZ: - { - IList strings = new List(); - - char[] blob = new char[datasize / 2]; - ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, blob, ref datasize); - - int cur = 0; - int len = blob.Length; - - while (ret == 0 && cur < len) - { - int nextNull = cur; - while (nextNull < len && blob[nextNull] != (char)0) - { - nextNull++; - } - - if (nextNull < len) - { - BCLDebug.Assert(blob[nextNull] == (char)0, "blob[nextNull] should be 0"); - if (nextNull - cur > 0) - { - strings.Add(new string(blob, cur, nextNull - cur)); - } - else - { - // we found an empty string. But if we're at the end of the data, - // it's just the extra null terminator. - if (nextNull != len - 1) - strings.Add(string.Empty); - } - } - else - { - strings.Add(new string(blob, cur, len - cur)); - } - - cur = nextNull + 1; - } - - data = new string[strings.Count]; - strings.CopyTo((string[])data, 0); - // data = strings.GetAllItems(String.class); - } - - break; - case Win32Native.REG_NONE: - case Win32Native.REG_LINK: - default: - break; - } - - return data; - } - - /// - /// Retrieves the registry data type of the value associated with the specified name. - /// Utilizes Transaction.Current for its transaction. - /// The value name whose data type is to be retrieved. - /// A RegistryValueKind value representing the registry data type of the value associated with name. - /// - [ComVisible(false)] - public RegistryValueKind GetValueKind(string name) - { - CheckValueReadPermission(name); - EnsureNotDisposed(); - - int type = 0; - int datasize = 0; - int ret = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - if (ret != 0) - Win32Error(ret, null); - - if (!Enum.IsDefined(typeof(RegistryValueKind), type)) - return RegistryValueKind.Unknown; - else - return (RegistryValueKind)type; - } - - /** - * Retrieves the current state of the dirty property. - * - * A key is marked as dirty if any operation has occured that modifies the - * contents of the key. - * - * @return true if the key has been modified. - */ - private bool IsDirty() - { - return (_state & STATE_DIRTY) != 0; - } - - private bool IsSystemKey() - { - return (_state & STATE_SYSTEMKEY) != 0; - } - - private bool IsWritable() - { - return (_state & STATE_WRITEACCESS) != 0; - } - - /// - /// Retrieves the name of the key. - /// The name of the key. - /// - public string Name - { - get - { - EnsureNotDisposed(); - return _keyName; - } - } - - private void SetDirty() - { - _state |= STATE_DIRTY; - } - - /// - /// Sets the specified value. Utilizes Transaction.Current for its transaction. - /// Name of value to store data in. - /// Data to store. - /// - public void SetValue(string name, object value) - { - SetValue(name, value, RegistryValueKind.Unknown); - } - - /// - /// Sets the specified value. Utilizes Transaction.Current for its transaction. - /// Name of value to store data in. - /// Data to store. - /// The registry data type to use when storing the data. - /// - [ComVisible(false)] - public unsafe void SetValue(string name, object value, RegistryValueKind valueKind) - { - if (value == null) - throw new ArgumentNullException(RegistryProviderStrings.Arg_Value); - - if (name != null && name.Length > MaxValueNameLength) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegValueNameStrLenBug); - } - - if (!Enum.IsDefined(typeof(RegistryValueKind), valueKind)) - throw new ArgumentException(RegistryProviderStrings.Arg_RegBadKeyKind); - - EnsureWriteable(); - - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - - if (ContainsRegistryValue(name)) - { // Existing key - CheckValueWritePermission(name); - } - else - { // Creating a new value - CheckValueCreatePermission(name); - } - - if (valueKind == RegistryValueKind.Unknown) - { - // this is to maintain compatibility with the old way of autodetecting the type. - // SetValue(string, object) will come through this codepath. - valueKind = CalculateValueKind(value); - } - - int ret = 0; - try - { - switch (valueKind) - { - case RegistryValueKind.ExpandString: - case RegistryValueKind.String: - { - string data = value.ToString(); - // divide by 2 to account for unicode. - if (MaxValueDataLength / 2 < data.Length) - { - throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); - } - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - valueKind, - data, - data.Length * 2 + 2); - break; - } - - case RegistryValueKind.MultiString: - { - // Other thread might modify the input array after we calculate the buffer length. - // Make a copy of the input array to be safe. - string[] dataStrings = (string[])(((string[])value).Clone()); - - int sizeInBytes = 0; - - // First determine the size of the array - // - for (int i = 0; i < dataStrings.Length; i++) - { - if (dataStrings[i] == null) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetStrArrNull); - } - - sizeInBytes += (dataStrings[i].Length + 1) * 2; - } - - sizeInBytes += 2; - - if (MaxValueDataLength < sizeInBytes) - { - throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); - } - - byte[] basePtr = new byte[sizeInBytes]; - fixed (byte* b = basePtr) - { - int totalBytesMoved = 0; - int currentBytesMoved = 0; - - // Write out the strings... - // - for (int i = 0; i < dataStrings.Length; i++) - { - currentBytesMoved = System.Text.Encoding.Unicode.GetBytes(dataStrings[i], 0, dataStrings[i].Length, basePtr, totalBytesMoved); - totalBytesMoved += currentBytesMoved; - basePtr[totalBytesMoved] = 0; - basePtr[totalBytesMoved + 1] = 0; - totalBytesMoved += 2; - } - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.MultiString, - basePtr, - sizeInBytes); - } - - break; - } - - case RegistryValueKind.Binary: - byte[] dataBytes = (byte[])value; - if (MaxValueDataLength < dataBytes.Length) - { - throw new ArgumentException(RegistryProviderStrings.Arg_ValueDataLenBug); - } - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.Binary, - dataBytes, - dataBytes.Length); - break; - - case RegistryValueKind.DWord: - { - // We need to use Convert here because we could have a boxed type cannot be - // unboxed and cast at the same time. I.e. ((int)(object)(short) 5) will fail. - int data = Convert.ToInt32(value, System.Globalization.CultureInfo.InvariantCulture); - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.DWord, - ref data, - 4); - break; - } - - case RegistryValueKind.QWord: - { - long data = Convert.ToInt64(value, System.Globalization.CultureInfo.InvariantCulture); - - ret = Win32Native.RegSetValueEx(_hkey, - name, - 0, - RegistryValueKind.QWord, - ref data, - 8); - break; - } - } - } - catch (OverflowException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - catch (InvalidOperationException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - catch (FormatException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - catch (InvalidCastException) - { - throw new ArgumentException(RegistryProviderStrings.Arg_RegSetMismatchedKind); - } - - if (ret == 0) - { - SetDirty(); - } - else - Win32Error(ret, null); - } - - private RegistryValueKind CalculateValueKind(object value) - { - // This logic matches what used to be in SetValue(string name, object value) in the v1.0 and v1.1 days. - // Even though we could add detection for an int64 in here, we want to maintain compatibility with the - // old behavior. - if (value is Int32) - return RegistryValueKind.DWord; - else if (value is Array) - { - if (value is byte[]) - return RegistryValueKind.Binary; - else if (value is string[]) - return RegistryValueKind.MultiString; - else - { - string resourceTemplate = RegistryProviderStrings.Arg_RegSetBadArrType; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, value.GetType().Name); - throw new ArgumentException(resource); - } - } - else - return RegistryValueKind.String; - } - - /** - * Retrieves a string representation of this key. - * - * @return a string representing the key. - */ - /// - /// Retrieves a string representation of this key. - /// A string representing the key. - /// - public override string ToString() - { - EnsureNotDisposed(); - return _keyName; - } - - /// - /// Returns the access control security for the current registry key. - /// Utilizes Transaction.Current for its transaction. - /// A TransactedRegistrySecurity object that describes the access control - /// permissions on the registry key represented by the current TransactedRegistryKey. - /// - public TransactedRegistrySecurity GetAccessControl() - { - return GetAccessControl(AccessControlSections.Access | AccessControlSections.Owner | AccessControlSections.Group); - } - - /// - /// Returns the access control security for the current registry key. - /// Utilizes Transaction.Current for its transaction. - /// A bitwise combination of AccessControlSections values that specifies the type of security information to get. - /// A TransactedRegistrySecurity object that describes the access control - /// permissions on the registry key represented by the current TransactedRegistryKey. - /// - public TransactedRegistrySecurity GetAccessControl(AccessControlSections includeSections) - { - EnsureNotDisposed(); - // Don't require a transaction. We don't want to throw for "Base" keys. - return new TransactedRegistrySecurity(_hkey, _keyName, includeSections); - } - - /// - /// Applies Windows access control security to an existing registry key. - /// Utilizes Transaction.Current for its transaction. - /// A TransactedRegistrySecurity object that specifies the access control security to apply to the current subkey. - /// - public void SetAccessControl(TransactedRegistrySecurity registrySecurity) - { - EnsureWriteable(); - if (registrySecurity == null) - throw new ArgumentNullException("registrySecurity"); - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - VerifyTransaction(); - - registrySecurity.Persist(_hkey, _keyName); - } - - /** - * After calling GetLastWin32Error(), it clears the last error field, - * so you must save the HResult and pass it to this method. This method - * will determine the appropriate exception to throw dependent on your - * error, and depending on the error, insert a string into the message - * gotten from the ResourceManager. - */ - internal void Win32Error(int errorCode, string str) - { - switch (errorCode) - { - case Win32Native.ERROR_ACCESS_DENIED: - if (str != null) - { - string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str); - throw new UnauthorizedAccessException(resource); - } - else - throw new UnauthorizedAccessException(); - - case Win32Native.ERROR_INVALID_HANDLE: - // ** - // * For normal RegistryKey instances we dispose the SafeRegHandle and throw IOException. - // * However, for HKEY_PERFORMANCE_DATA (on a local or remote machine) we avoid disposing the - // * SafeRegHandle and only throw the IOException. This is to workaround reentrancy issues - // * in PerformanceCounter.NextValue() where the API could throw {NullReference, ObjectDisposed, ArgumentNull}Exception - // * on reentrant calls because of this error code path in RegistryKey - // * - // * Normally we'd make our caller synchronize access to a shared RegistryKey instead of doing something like this, - // * however we shipped PerformanceCounter.NextValue() un-synchronized in v2.0RTM and customers have taken a dependency on - // * this behavior (being able to simultaneously query multiple remote-machine counters on multiple threads, instead of - // * having serialized access). - // * - // * FUTURE: Consider changing PerformanceCounterLib to handle its own Win32 RegistryKey API calls instead of depending - // * on Microsoft.Win32.RegistryKey, so that RegistryKey can be clean of special-cases for HKEY_PERFORMANCE_DATA. - // - _hkey.SetHandleAsInvalid(); - _hkey = null; - goto default; - - case Win32Native.ERROR_FILE_NOT_FOUND: - { - string resourceTemplate = RegistryProviderStrings.Arg_RegKeyNotFound; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, errorCode.ToString(System.Globalization.CultureInfo.InvariantCulture)); - throw new IOException(resource); - } - - default: - throw new IOException(Win32Native.GetMessage(errorCode), errorCode); - } - } - - internal static void Win32ErrorStatic(int errorCode, string str) - { - switch (errorCode) - { - case Win32Native.ERROR_ACCESS_DENIED: - if (str != null) - { - string resourceTemplate = RegistryProviderStrings.UnauthorizedAccess_RegistryKeyGeneric_Key; - string resource = string.Format(CultureInfo.CurrentCulture, resourceTemplate, str); - throw new UnauthorizedAccessException(resource); - } - else - throw new UnauthorizedAccessException(); - - default: - throw new IOException(Win32Native.GetMessage(errorCode), errorCode); - } - } - - internal static string FixupName(string name) - { - BCLDebug.Assert(name != null, "[FixupName]name!=null"); - if (name.Contains('\\')) - return name; - - StringBuilder sb = new StringBuilder(name); - FixupPath(sb); - int temp = sb.Length - 1; - if (sb[temp] == '\\') // Remove trailing slash - sb.Length = temp; - return sb.ToString(); - } - - private static void FixupPath(StringBuilder path) - { - int length = path.Length; - bool fixup = false; - char markerChar = (char)0xFFFF; - - int i = 1; - while (i < length - 1) - { - if (path[i] == '\\') - { - i++; - while (i < length) - { - if (path[i] == '\\') - { - path[i] = markerChar; - i++; - fixup = true; - } - else - break; - } - } - - i++; - } - - if (fixup) - { - i = 0; - int j = 0; - while (i < length) - { - if (path[i] == markerChar) - { - i++; - continue; - } - - path[j] = path[i]; - i++; - j++; - } - - path.Length += j - i; - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private void CheckOpenSubKeyPermission(string subkeyName, bool subKeyWritable) - { - // If the parent key is not opened under default mode, we have access already. - // If the parent key is opened under default mode, we need to check for permission. - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - CheckSubKeyReadPermission(subkeyName); - } - - if (subKeyWritable && (_checkMode == RegistryKeyPermissionCheck.ReadSubTree)) - { - CheckSubTreeReadWritePermission(subkeyName); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private void CheckOpenSubKeyPermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck) - { - if (subKeyCheck == RegistryKeyPermissionCheck.Default) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - CheckSubKeyReadPermission(subkeyName); - } - } - - CheckSubTreePermission(subkeyName, subKeyCheck); - } - - private void CheckSubTreePermission(string subkeyName, RegistryKeyPermissionCheck subKeyCheck) - { - if (subKeyCheck == RegistryKeyPermissionCheck.ReadSubTree) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - CheckSubTreeReadPermission(subkeyName); - } - } - else if (subKeyCheck == RegistryKeyPermissionCheck.ReadWriteSubTree) - { - if (_checkMode != RegistryKeyPermissionCheck.ReadWriteSubTree) - { - CheckSubTreeReadWritePermission(subkeyName); - } - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubKeyWritePermission(string subkeyName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!"); - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - // If we want to open a subkey of a read-only key as writeable, we need to do the check. - new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\.").Demand(); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubKeyReadPermission(string subkeyName) - { - BCLDebug.Assert(_checkMode == RegistryKeyPermissionCheck.Default, "Should be called from a key opened under default mode only!"); - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\.").Demand(); - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubKeyCreatePermission(string subkeyName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating sub key under read-only key!"); - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + subkeyName + "\\.").Demand(); - } - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubTreeReadPermission(string subkeyName) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + subkeyName + "\\").Demand(); - } - } - - // Suppressed because keyName and subkeyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubTreeWritePermission(string subkeyName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!"); - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + subkeyName + "\\").Demand(); - } - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckSubTreeReadWritePermission(string subkeyName) - { - // If we want to open a subkey of a read-only key as writeable, we need to do the check. - new RegistryPermission(RegistryPermissionAccess.Write | RegistryPermissionAccess.Read, - _keyName + "\\" + subkeyName).Demand(); - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckValueWritePermission(string valueName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow writing value to read-only key!"); - // skip the security check if the key is opened under write mode - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Write, _keyName + "\\" + valueName).Demand(); - } - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckValueCreatePermission(string valueName) - { - BCLDebug.Assert(_checkMode != RegistryKeyPermissionCheck.ReadSubTree, "We shouldn't allow creating value under read-only key!"); - // skip the security check if the key is opened under write mode - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - new RegistryPermission(RegistryPermissionAccess.Create, _keyName + "\\" + valueName).Demand(); - } - } - - // Suppressed because keyName and valueName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckValueReadPermission(string valueName) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - // only need to check for default mode (dynamic check) - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\" + valueName).Demand(); - } - } - - // Suppressed because keyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - private void CheckKeyReadPermission() - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - // only need to check for default mode (dynamic check) - new RegistryPermission(RegistryPermissionAccess.Read, _keyName + "\\.").Demand(); - } - } - - private bool ContainsRegistryValue(string name) - { - int type = 0; - int datasize = 0; - int retval = Win32Native.RegQueryValueEx(_hkey, name, null, ref type, (byte[])null, ref datasize); - return retval == 0; - } - - private void EnsureNotDisposed() - { - if (_hkey == null) - { - throw new ObjectDisposedException(_keyName, - RegistryProviderStrings.ObjectDisposed_RegKeyClosed); - } - } - - private void EnsureWriteable() - { - EnsureNotDisposed(); - if (!IsWritable()) - { - throw new UnauthorizedAccessException(RegistryProviderStrings.UnauthorizedAccess_RegistryNoWrite); - } - } - - private static int GetRegistryKeyAccess(bool isWritable) - { - int winAccess; - if (!isWritable) - { - winAccess = Win32Native.KEY_READ; - } - else - { - winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; - } - - return winAccess; - } - - private static int GetRegistryKeyAccess(RegistryKeyPermissionCheck mode) - { - int winAccess = 0; - switch (mode) - { - case RegistryKeyPermissionCheck.ReadSubTree: - case RegistryKeyPermissionCheck.Default: - winAccess = Win32Native.KEY_READ; - break; - - case RegistryKeyPermissionCheck.ReadWriteSubTree: - winAccess = Win32Native.KEY_READ | Win32Native.KEY_WRITE; - break; - - default: - BCLDebug.Assert(false, "unexpected code path"); - break; - } - - return winAccess; - } - - // Suppressed to be consistent with naming in Microsoft.Win32.RegistryKey - [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] - private RegistryKeyPermissionCheck GetSubKeyPermissionCheck(bool subkeyWritable) - { - if (_checkMode == RegistryKeyPermissionCheck.Default) - { - return _checkMode; - } - - if (subkeyWritable) - { - return RegistryKeyPermissionCheck.ReadWriteSubTree; - } - else - { - return RegistryKeyPermissionCheck.ReadSubTree; - } - } - - private static void ValidateKeyName(string name) - { - if (name == null) - { - throw new ArgumentNullException(RegistryProviderStrings.Arg_Name); - } - - int nextSlash = name.IndexOf('\\'); - int current = 0; - while (nextSlash != -1) - { - if ((nextSlash - current) > MaxKeyLength) - throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - - current = nextSlash + 1; - nextSlash = name.IndexOf('\\', current); - } - - if ((name.Length - current) > MaxKeyLength) - throw new ArgumentException(RegistryProviderStrings.Arg_RegKeyStrLenBug); - } - - private static void ValidateKeyMode(RegistryKeyPermissionCheck mode) - { - if (mode < RegistryKeyPermissionCheck.Default || mode > RegistryKeyPermissionCheck.ReadWriteSubTree) - { - throw new ArgumentException(RegistryProviderStrings.Argument_InvalidRegistryKeyPermissionCheck); - } - } - - private static void ValidateKeyRights(int rights) - { - if (0 != (rights & ~((int)RegistryRights.FullControl))) - { - // We need to throw SecurityException here for compatibility reason, - // although UnauthorizedAccessException will make more sense. - throw new SecurityException(RegistryProviderStrings.Security_RegistryPermission); - } - } - - private void VerifyTransaction() - { - // Require a transaction. This will throw for "Base" keys because they aren't associated with a transaction. - if (_myTransaction == null) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_NotAssociatedWithTransaction); - } - - if (!_myTransaction.Equals(Transaction.Current)) - { - throw new InvalidOperationException(RegistryProviderStrings.InvalidOperation_MustUseSameTransaction); - } - } - // Win32 constants for error handling - private const int FORMAT_MESSAGE_IGNORE_INSERTS = 0x00000200; - private const int FORMAT_MESSAGE_FROM_SYSTEM = 0x00001000; - private const int FORMAT_MESSAGE_ARGUMENT_ARRAY = 0x00002000; - } -} diff --git a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs b/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs deleted file mode 100644 index 46070ea27c8..00000000000 --- a/src/System.Management.Automation/namespaces/TransactedRegistrySecurity.cs +++ /dev/null @@ -1,456 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -// -// NOTE: A vast majority of this code was copied from BCL in -// ndp\clr\src\BCL\System\Security\AccessControl\RegistrySecurity.cs. -// Namespace: System.Security.AccessControl -// -/*============================================================ -** -** -** -** Purpose: Managed ACL wrapper for registry keys. -** -** -===========================================================*/ - -using System; -using System.Security.Permissions; -using System.Security.Principal; -using System.Runtime.InteropServices; -using System.IO; -using System.Security.AccessControl; -using System.Diagnostics.CodeAnalysis; - -namespace Microsoft.PowerShell.Commands.Internal -{ - /// - /// Represents a set of access rights allowed or denied for a user or group. This class cannot be inherited. - /// - // Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistryAccessRule : AccessRule - { - // Constructor for creating access rules for registry objects - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as - /// NTAccount that can be converted to type SecurityIdentifier. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// - internal TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, AccessControlType type) - : this(identity, (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) - { - } - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// The name of the user or group the rule applies to. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// - internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, AccessControlType type) - : this(new NTAccount(identity), (int)registryRights, false, InheritanceFlags.None, PropagationFlags.None, type) - { - } - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as - /// NTAccount that can be converted to type SecurityIdentifier. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects. - /// A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// - public TransactedRegistryAccessRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) - : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, type) - { - } - - /// - /// Initializes a new instance of the RegistryAccessRule class, specifying the user or group the rule applies to, - /// the access rights, and whether the specified access rights are allowed or denied. - /// The name of the user or group the rule applies to. - /// A bitwise combination of Microsoft.Win32.RegistryRights values indicating the rights allowed or denied. - /// A bitwise combination of InheritanceFlags flags specifying how access rights are inherited from other objects. - /// A bitwise combination of PropagationFlags flags specifying how access rights are propagated to other objects. - /// One of the AccessControlType values indicating whether the rights are allowed or denied. - /// - internal TransactedRegistryAccessRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) - : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, type) - { - } - - // - // Internal constructor to be called by public constructors - // and the access rule factory methods of {File|Folder}Security - // - internal TransactedRegistryAccessRule( - IdentityReference identity, - int accessMask, - bool isInherited, - InheritanceFlags inheritanceFlags, - PropagationFlags propagationFlags, - AccessControlType type) - : base( - identity, - accessMask, - isInherited, - inheritanceFlags, - propagationFlags, - type) - { - } - - /// - /// Gets the rights allowed or denied by the access rule. - /// - public RegistryRights RegistryRights - { - get { return (RegistryRights)base.AccessMask; } - } - } - - /// - /// Represents a set of access rights to be audited for a user or group. This class cannot be inherited. - /// - // Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistryAuditRule : AuditRule - { - /// - /// Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to - /// audit, whether to take inheritance into account, and whether to audit success, failure, or both. - /// The user or group the rule applies to. Must be of type SecurityIdentifier or a type such as - /// NTAccount that can be converted to type SecurityIdentifier. - /// A bitwise combination of RegistryRights values specifying the kinds of access to audit. - /// A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key. - /// A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key. - /// A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both. - /// - internal TransactedRegistryAuditRule(IdentityReference identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - : this(identity, (int)registryRights, false, inheritanceFlags, propagationFlags, flags) - { - } - - /// - /// Initializes a new instance of the RegistryAuditRule class, specifying the user or group to audit, the rights to - /// audit, whether to take inheritance into account, and whether to audit success, failure, or both. - /// The name of the user or group the rule applies to. - /// A bitwise combination of RegistryRights values specifying the kinds of access to audit. - /// A bitwise combination of InheritanceFlags values specifying whether the audit rule applies to subkeys of the current key. - /// A bitwise combination of PropagationFlags values that affect the way an inherited audit rule is propagated to subkeys of the current key. - /// A bitwise combination of AuditFlags values specifying whether to audit success, failure, or both. - /// - internal TransactedRegistryAuditRule(string identity, RegistryRights registryRights, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - : this(new NTAccount(identity), (int)registryRights, false, inheritanceFlags, propagationFlags, flags) - { - } - - internal TransactedRegistryAuditRule(IdentityReference identity, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - : base(identity, accessMask, isInherited, inheritanceFlags, propagationFlags, flags) - { - } - - /// - /// Gets the access rights affected by the audit rule. - /// - public RegistryRights RegistryRights - { - get { return (RegistryRights)base.AccessMask; } - } - } - - /// - /// Represents the Windows access control security for a registry key. This class cannot be inherited. - /// This class is specifically to be used with TransactedRegistryKey. - /// - // Suppressed because these are needed to manipulate TransactedRegistryKey, which is written to the pipeline. - [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] - public sealed class TransactedRegistrySecurity : NativeObjectSecurity - { - private const string resBaseName = "RegistryProviderStrings"; - - /// - /// Initializes a new instance of the TransactedRegistrySecurity class with default values. - /// - public TransactedRegistrySecurity() - : base(true, ResourceType.RegistryKey) - { - } - - /* - // The name of registry key must start with a predefined string, - // like CLASSES_ROOT, CURRENT_USER, MACHINE, and USERS. See - // MSDN's help for SetNamedSecurityInfo for details. - internal TransactedRegistrySecurity(string name, AccessControlSections includeSections) - : base(true, ResourceType.RegistryKey, HKeyNameToWindowsName(name), includeSections) - { - new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); - } - */ - - // Suppressed because the passed name and hkey won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - internal TransactedRegistrySecurity(SafeRegistryHandle hKey, string name, AccessControlSections includeSections) - : base(true, ResourceType.RegistryKey, hKey, includeSections, _HandleErrorCode, null) - { - new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.View, name).Demand(); - } - - private static Exception _HandleErrorCode(int errorCode, string name, SafeHandle handle, object context) - { - System.Exception exception = null; - - switch (errorCode) - { - case Win32Native.ERROR_FILE_NOT_FOUND: - exception = new IOException(RegistryProviderStrings.Arg_RegKeyNotFound); - break; - - case Win32Native.ERROR_INVALID_NAME: - exception = new ArgumentException(RegistryProviderStrings.Arg_RegInvalidKeyName); - break; - - case Win32Native.ERROR_INVALID_HANDLE: - exception = new ArgumentException(RegistryProviderStrings.AccessControl_InvalidHandle); - break; - - default: - break; - } - - return exception; - } - - /// - /// Creates a new access control rule for the specified user, with the specified access rights, access control, and flags. - /// An IdentityReference that identifies the user or group the rule applies to. - /// A bitwise combination of RegistryRights values specifying the access rights to allow or deny, cast to an integer. - /// A Boolean value specifying whether the rule is inherited. - /// A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys. - /// A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None. - /// One of the AccessControlType values specifying whether the rights are allowed or denied. - /// A TransactedRegistryAccessRule object representing the specified rights for the specified user. - /// - public override AccessRule AccessRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AccessControlType type) - { - return new TransactedRegistryAccessRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, type); - } - - /// - /// Creates a new audit rule, specifying the user the rule applies to, the access rights to audit, the inheritance and propagation of the - /// rule, and the outcome that triggers the rule. - /// An IdentityReference that identifies the user or group the rule applies to. - /// A bitwise combination of RegistryRights values specifying the access rights to audit, cast to an integer. - /// A Boolean value specifying whether the rule is inherited. - /// A bitwise combination of InheritanceFlags values specifying how the rule is inherited by subkeys. - /// A bitwise combination of PropagationFlags values that modify the way the rule is inherited by subkeys. Meaningless if the value of inheritanceFlags is InheritanceFlags.None. - /// A bitwise combination of AuditFlags values specifying whether to audit successful access, failed access, or both. - /// A TransactedRegistryAuditRule object representing the specified audit rule for the specified user, with the specified flags. - /// The return type of the method is the base class, AuditRule, but the return value can be cast safely to the derived class. - /// - public override AuditRule AuditRuleFactory(IdentityReference identityReference, int accessMask, bool isInherited, InheritanceFlags inheritanceFlags, PropagationFlags propagationFlags, AuditFlags flags) - { - return new TransactedRegistryAuditRule(identityReference, accessMask, isInherited, inheritanceFlags, propagationFlags, flags); - } - - internal AccessControlSections GetAccessControlSectionsFromChanges() - { - AccessControlSections persistRules = AccessControlSections.None; - if (AccessRulesModified) - persistRules = AccessControlSections.Access; - if (AuditRulesModified) - persistRules |= AccessControlSections.Audit; - if (OwnerModified) - persistRules |= AccessControlSections.Owner; - if (GroupModified) - persistRules |= AccessControlSections.Group; - return persistRules; - } - - // Suppressed because the passed keyName won't change. - [SuppressMessage("Microsoft.Security", "CA2103:ReviewImperativeSecurity")] - internal void Persist(SafeRegistryHandle hKey, string keyName) - { - new RegistryPermission(RegistryPermissionAccess.NoAccess, AccessControlActions.Change, keyName).Demand(); - - WriteLock(); - - try - { - AccessControlSections persistRules = GetAccessControlSectionsFromChanges(); - if (persistRules == AccessControlSections.None) - return; // Don't need to persist anything. - - base.Persist(hKey, persistRules); - OwnerModified = GroupModified = AuditRulesModified = AccessRulesModified = false; - } - finally - { - WriteUnlock(); - } - } - - /// - /// Searches for a matching access control with which the new rule can be merged. If none are found, adds the new rule. - /// The access control rule to add. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void AddAccessRule(TransactedRegistryAccessRule rule) - { - base.AddAccessRule(rule); - } - - /// - /// Removes all access control rules with the same user and AccessControlType (allow or deny) as the specified rule, and then adds the specified rule. - /// The TransactedRegistryAccessRule to add. The user and AccessControlType of this rule determine the rules to remove before this rule is added. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void SetAccessRule(TransactedRegistryAccessRule rule) - { - base.SetAccessRule(rule); - } - - /// - /// Removes all access control rules with the same user as the specified rule, regardless of AccessControlType, and then adds the specified rule. - /// The TransactedRegistryAccessRule to add. The user specified by this rule determines the rules to remove before this rule is added. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void ResetAccessRule(TransactedRegistryAccessRule rule) - { - base.ResetAccessRule(rule); - } - - /// - /// Searches for an access control rule with the same user and AccessControlType (allow or deny) as the specified access rule, and with compatible - /// inheritance and propagation flags; if such a rule is found, the rights contained in the specified access rule are removed from it. - /// A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for, and a set of inheritance - /// and propagation flags that a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public bool RemoveAccessRule(TransactedRegistryAccessRule rule) - { - return base.RemoveAccessRule(rule); - } - - /// - /// Searches for all access control rules with the same user and AccessControlType (allow or deny) as the specified rule and, if found, removes them. - /// A TransactedRegistryAccessRule that specifies the user and AccessControlType to search for. Any rights, inheritance flags, or - /// propagation flags specified by this rule are ignored. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAccessRuleAll(TransactedRegistryAccessRule rule) - { - base.RemoveAccessRuleAll(rule); - } - - /// - /// Searches for an access control rule that exactly matches the specified rule and, if found, removes it. - /// The TransactedRegistryAccessRule to remove. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAccessRuleSpecific(TransactedRegistryAccessRule rule) - { - base.RemoveAccessRuleSpecific(rule); - } - - /// - /// Searches for an audit rule with which the new rule can be merged. If none are found, adds the new rule. - /// The audit rule to add. The user specified by this rule determines the search. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void AddAuditRule(TransactedRegistryAuditRule rule) - { - base.AddAuditRule(rule); - } - - /// - /// Removes all audit rules with the same user as the specified rule, regardless of the AuditFlags value, and then adds the specified rule. - /// The TransactedRegistryAuditRule to add. The user specified by this rule determines the rules to remove before this rule is added. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void SetAuditRule(TransactedRegistryAuditRule rule) - { - base.SetAuditRule(rule); - } - - /// - /// Searches for an audit control rule with the same user as the specified rule, and with compatible inheritance and propagation flags; - /// if a compatible rule is found, the rights contained in the specified rule are removed from it. - /// A TransactedRegistryAuditRule that specifies the user to search for, and a set of inheritance and propagation flags that - /// a matching rule, if found, must be compatible with. Specifies the rights to remove from the compatible rule, if found. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public bool RemoveAuditRule(TransactedRegistryAuditRule rule) - { - return base.RemoveAuditRule(rule); - } - - /// - /// Searches for all audit rules with the same user as the specified rule and, if found, removes them. - /// A TransactedRegistryAuditRule that specifies the user to search for. Any rights, inheritance - /// flags, or propagation flags specified by this rule are ignored. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAuditRuleAll(TransactedRegistryAuditRule rule) - { - base.RemoveAuditRuleAll(rule); - } - - /// - /// Searches for an audit rule that exactly matches the specified rule and, if found, removes it. - /// The TransactedRegistryAuditRule to be removed. - /// - // Suppressed because we want to ensure TransactedRegistry* objects. - [SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters")] - public void RemoveAuditRuleSpecific(TransactedRegistryAuditRule rule) - { - base.RemoveAuditRuleSpecific(rule); - } - - /// - /// Gets the enumeration type that the TransactedRegistrySecurity class uses to represent access rights. - /// A Type object representing the RegistryRights enumeration. - /// - public override Type AccessRightType - { - get { return typeof(RegistryRights); } - } - - /// - /// Gets the type that the TransactedRegistrySecurity class uses to represent access rules. - /// A Type object representing the TransactedRegistryAccessRule class. - /// - public override Type AccessRuleType - { - get { return typeof(TransactedRegistryAccessRule); } - } - - /// - /// Gets the type that the TransactedRegistrySecurity class uses to represent audit rules. - /// A Type object representing the TransactedRegistryAuditRule class. - /// - public override Type AuditRuleType - { - get { return typeof(TransactedRegistryAuditRule); } - } - } -} diff --git a/src/System.Management.Automation/namespaces/Win32Native.cs b/src/System.Management.Automation/namespaces/Win32Native.cs index b9c7d8a7a71..4f2c65c49f5 100644 --- a/src/System.Management.Automation/namespaces/Win32Native.cs +++ b/src/System.Management.Automation/namespaces/Win32Native.cs @@ -27,7 +27,7 @@ namespace Microsoft.PowerShell.Commands.Internal // Remove the default demands for all N/Direct methods with this // global declaration on the class. // - [SuppressUnmanagedCodeSecurityAttribute()] + [SuppressUnmanagedCodeSecurity] internal static class Win32Native { #region Integer Const @@ -76,14 +76,14 @@ internal enum SID_NAME_USE #region Struct - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct SID_AND_ATTRIBUTES { internal IntPtr Sid; internal uint Attributes; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct TOKEN_USER { internal SID_AND_ATTRIBUTES User; @@ -106,8 +106,6 @@ internal struct TOKEN_USER /// /// [DllImport(PinvokeDllNames.LookupAccountSidDllName, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] - [ResourceExposure(ResourceScope.Machine)] - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [return: MarshalAs(UnmanagedType.Bool)] private static extern unsafe bool LookupAccountSid(string lpSystemName, IntPtr sid, @@ -139,8 +137,6 @@ internal static unsafe bool LookupAccountSid(string lpSystemName, } [DllImport(PinvokeDllNames.CloseHandleDllName, SetLastError = true)] - [ResourceExposure(ResourceScope.Machine)] - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool CloseHandle(IntPtr handle); @@ -152,8 +148,6 @@ internal static unsafe bool LookupAccountSid(string lpSystemName, /// Process token. /// The current process token. [DllImport(PinvokeDllNames.OpenProcessTokenDllName, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] - [ResourceExposure(ResourceScope.Machine)] - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool OpenProcessToken(IntPtr processHandle, uint desiredAccess, out IntPtr tokenHandle); @@ -168,8 +162,6 @@ internal static unsafe bool LookupAccountSid(string lpSystemName, /// /// [DllImport(PinvokeDllNames.GetTokenInformationDllName, CharSet = CharSet.Unicode, SetLastError = true, BestFitMapping = false)] - [ResourceExposure(ResourceScope.Machine)] - [SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool GetTokenInformation(IntPtr tokenHandle, TOKEN_INFORMATION_CLASS tokenInformationClass, diff --git a/src/System.Management.Automation/resources/Authenticode.resx b/src/System.Management.Automation/resources/Authenticode.resx index c196f2b0d65..f9015569644 100644 --- a/src/System.Management.Automation/resources/Authenticode.resx +++ b/src/System.Management.Automation/resources/Authenticode.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -142,7 +142,7 @@ Cannot sign code. The specified certificate is not suitable for code signing. - Cannot sign code. The TimeStamp server URL must be fully qualified, and in the format http://<server url>. + Cannot sign code. The TimeStamp server URL must be fully qualified, and in the format http://<server url> or https://<server url>. Cannot sign code. The hash algorithm is not supported. diff --git a/src/System.Management.Automation/resources/AuthorizationManagerBase.resx b/src/System.Management.Automation/resources/AuthorizationManagerBase.resx index 8f9d62fefec..1304e76763e 100644 --- a/src/System.Management.Automation/resources/AuthorizationManagerBase.resx +++ b/src/System.Management.Automation/resources/AuthorizationManagerBase.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/AutomationExceptions.resx b/src/System.Management.Automation/resources/AutomationExceptions.resx index 6c4c8fe0d92..9b48e92c0bc 100644 --- a/src/System.Management.Automation/resources/AutomationExceptions.resx +++ b/src/System.Management.Automation/resources/AutomationExceptions.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -201,4 +201,10 @@ Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + diff --git a/src/System.Management.Automation/resources/CatalogStrings.resx b/src/System.Management.Automation/resources/CatalogStrings.resx index 0d8ff0910ae..662b765652b 100644 --- a/src/System.Management.Automation/resources/CatalogStrings.resx +++ b/src/System.Management.Automation/resources/CatalogStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/CimInstanceTypeAdapterResources.resx b/src/System.Management.Automation/resources/CimInstanceTypeAdapterResources.resx index 52aede963c4..b286977066f 100644 --- a/src/System.Management.Automation/resources/CimInstanceTypeAdapterResources.resx +++ b/src/System.Management.Automation/resources/CimInstanceTypeAdapterResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/CmdletizationCoreResources.resx b/src/System.Management.Automation/resources/CmdletizationCoreResources.resx index a5835e380f5..39755172f09 100644 --- a/src/System.Management.Automation/resources/CmdletizationCoreResources.resx +++ b/src/System.Management.Automation/resources/CmdletizationCoreResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/CommandBaseStrings.resx b/src/System.Management.Automation/resources/CommandBaseStrings.resx index 656dc226f22..a5465c5b457 100644 --- a/src/System.Management.Automation/resources/CommandBaseStrings.resx +++ b/src/System.Management.Automation/resources/CommandBaseStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -156,6 +156,15 @@ Pause the current pipeline and return to the command prompt. Type "{0}" to resume the pipeline. + + + Program "{0}" ended with non-zero exit code: {1} ({2}). + Performing the operation "{0}" on target "{1}". @@ -213,4 +222,22 @@ Reviewed by TArcher on 2010-07-20 The {0} is obsolete. {1} + + Exec call failed with errorno {0} for command line: {1} + + + Command '{0}' was not found. The specified command must be an executable. + + + Script Block Processing Dot-Source Check + + + Dot-Source processing for script block '{0}' will fail in Constrained Language mode because its language mode '{1}' does not match the current language mode '{2}'. + + + Command Searcher + + + Command '{0}' in module '{1}' is untrusted and will not be accessible in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx b/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx index 201dde0e4ac..79de141ead6 100644 --- a/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx +++ b/src/System.Management.Automation/resources/ConsoleInfoErrorStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,63 +117,9 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Required element "PSConsoleFile" in {0} is missing or incorrect. - - - Required element "PSVersion" in {0} is missing or incorrect. - - - Required element "ConsoleSchemaVersion" in {0} is missing or incorrect. - - - The console file is not valid. Multiple entries were found for the element PSConsoleFile. Only one entry is supported for this version. - - - The console file is not valid because the element {0} is not valid. - - - The console file is not valid because the PowerShell snap-in name is missing. - - - Attempting to save a console file with no name. Use Export-Console with the Path parameter to save the console file. - - - Unknown element {0} found. "{1}" should have "{2}" and "{3}" elements only. - - - The console file is not valid. Only one occurrence of the element "{0}" is allowed. - - - The path {0} is not an absolute path. - - - The console file name extension is not valid. A console file name extension must be psc1. - Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. - - Cannot find any PowerShell snap-in information for {0}. - - - This is a system PowerShell snap-in that is loaded by PowerShell. - - - Cannot add PowerShell snap-in {0} because it is already added. Verify the name of the snap-in, and then try again. - - - Cannot remove the PowerShell snap-in {0} because it is not loaded. Verify the name of the snap-in that you want to remove, and then try again. - - - Cannot remove the PowerShell snap-in {0} because it is a system snap-in. Verify the name of the snap-in that you want to remove, and then try again. - - - Cannot load the PowerShell snap-in because an error occurred while reading the registry information for the snap-in. - - - An error occurred while attempting to load the system PowerShell snap-ins. Please contact Microsoft Customer Support Services. - The following errors occurred when loading console {0}: {1} @@ -195,43 +141,13 @@ PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. - - The cmdlet is not supported by the custom shell. - - - Cannot export to this file because file {0} is read-only. Change the read-only attribute of the file to read-write, or export to a different file. - File {0} already exists and {1} was specified. - - Cannot export to a console because no console is loaded or no name is specified. - - - Cmdlet {0} - - - Supply values for the following parameters: - - - Cannot export a console file because no console file has been specified. Do you want to continue with the export operation? - - - Cannot save the file because the file name format is not valid. Specify a file name using the command: export-console -path. - - - Cannot save the specified file. The Save operation was canceled. - - - Cannot save the console file because wildcard characters were used. Specify a console file without wildcard characters. - - - You can only save a file when you are working in a file provider. The current provider '{0}' is not a file provider. - - - Cannot set the ConsoleFileName variable to {0}. File {0} was saved. + + The provided configuration file '{0}' does not exist. - - The Save operation failed. Cannot remove the file {0}. + + The provided configuration file '{0}' must have a .pssc file extension. diff --git a/src/System.Management.Automation/resources/CoreClrStubResources.resx b/src/System.Management.Automation/resources/CoreClrStubResources.resx index a533d0ca195..7be2f9081f6 100644 --- a/src/System.Management.Automation/resources/CoreClrStubResources.resx +++ b/src/System.Management.Automation/resources/CoreClrStubResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/CoreMshSnapinResources.resx b/src/System.Management.Automation/resources/CoreMshSnapinResources.resx deleted file mode 100644 index 39cb1e1b628..00000000000 --- a/src/System.Management.Automation/resources/CoreMshSnapinResources.resx +++ /dev/null @@ -1,129 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 used to manage components of PowerShell. - - - Microsoft Corporation - - - Core PowerShell snap-in - - diff --git a/src/System.Management.Automation/resources/CredUI.resx b/src/System.Management.Automation/resources/CredUI.resx index dee868450e9..dbccf9af57f 100644 --- a/src/System.Management.Automation/resources/CredUI.resx +++ b/src/System.Management.Automation/resources/CredUI.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/Credential.resx b/src/System.Management.Automation/resources/Credential.resx index 63d780d1404..4f8c9419d13 100644 --- a/src/System.Management.Automation/resources/Credential.resx +++ b/src/System.Management.Automation/resources/Credential.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/CredentialAttributeStrings.resx b/src/System.Management.Automation/resources/CredentialAttributeStrings.resx index f496d90c988..06d124d178e 100644 --- a/src/System.Management.Automation/resources/CredentialAttributeStrings.resx +++ b/src/System.Management.Automation/resources/CredentialAttributeStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/DebuggerStrings.resx b/src/System.Management.Automation/resources/DebuggerStrings.resx index 466ee067ceb..51181c82c1e 100644 --- a/src/System.Management.Automation/resources/DebuggerStrings.resx +++ b/src/System.Management.Automation/resources/DebuggerStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/DescriptionsStrings.resx b/src/System.Management.Automation/resources/DescriptionsStrings.resx index dd8cb10c17e..5f3b0ef45c0 100644 --- a/src/System.Management.Automation/resources/DescriptionsStrings.resx +++ b/src/System.Management.Automation/resources/DescriptionsStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/DiscoveryExceptions.resx b/src/System.Management.Automation/resources/DiscoveryExceptions.resx index d3923969e8d..97cb5a61820 100644 --- a/src/System.Management.Automation/resources/DiscoveryExceptions.resx +++ b/src/System.Management.Automation/resources/DiscoveryExceptions.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -206,6 +206,10 @@ The #requires statement must be in one of the following formats: The '{0}' command was found in the module '{1}', but the module could not be loaded. For more information, run 'Import-Module {1}'. + + The '{0}' command was found in the module '{1}', but the module could not be loaded due to the following error: [{2}] +For more information, run 'Import-Module {1}'. + The module '{0}' could not be loaded. For more information, run 'Import-Module {0}'. diff --git a/src/System.Management.Automation/resources/EnumExpressionEvaluatorStrings.resx b/src/System.Management.Automation/resources/EnumExpressionEvaluatorStrings.resx index 277277ecd04..a6775fd7fc7 100644 --- a/src/System.Management.Automation/resources/EnumExpressionEvaluatorStrings.resx +++ b/src/System.Management.Automation/resources/EnumExpressionEvaluatorStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/ErrorCategoryStrings.resx b/src/System.Management.Automation/resources/ErrorCategoryStrings.resx index f03bb8d7d54..93a6d0139de 100644 --- a/src/System.Management.Automation/resources/ErrorCategoryStrings.resx +++ b/src/System.Management.Automation/resources/ErrorCategoryStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/ErrorPackage.resx b/src/System.Management.Automation/resources/ErrorPackage.resx index 04c0467ba71..b041f03c680 100644 --- a/src/System.Management.Automation/resources/ErrorPackage.resx +++ b/src/System.Management.Automation/resources/ErrorPackage.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/ErrorPackageRemoting.resx b/src/System.Management.Automation/resources/ErrorPackageRemoting.resx deleted file mode 100644 index add4b52ccf4..00000000000 --- a/src/System.Management.Automation/resources/ErrorPackageRemoting.resx +++ /dev/null @@ -1,120 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 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 - - diff --git a/src/System.Management.Automation/resources/EtwLoggingStrings.resx b/src/System.Management.Automation/resources/EtwLoggingStrings.resx index c6457e7d638..24d6f7c35d6 100644 --- a/src/System.Management.Automation/resources/EtwLoggingStrings.resx +++ b/src/System.Management.Automation/resources/EtwLoggingStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/EventResource.resx b/src/System.Management.Automation/resources/EventResource.resx index a4f245cde93..c25df6e48f5 100644 --- a/src/System.Management.Automation/resources/EventResource.resx +++ b/src/System.Management.Automation/resources/EventResource.resx @@ -5,8 +5,8 @@ To add or change logged events and the associated resources, edit PowerShell.Core.Instrumentation.man then rerun ResxGen.ps1 to produce an updated CS and Resx file. --> - - + + @@ -550,7 +550,7 @@ Parameters = {7} Test analytic message - Connection Paramters are + Connection Parameters are Connection URI: {0} Resource URI: {1} User: {2} @@ -640,7 +640,7 @@ Exception StackTrace: {2} Runspace Id: {0} Pipeline Id: {1}. Server is sending data of size {2} to client. DataType: {3} TargetInterface: {4} - Request {0}. Creating a server remote session. UserName: {1} Custome Shell Id: {2} + Request {0}. Creating a server remote session. UserName: {1} Custom Shell Id: {2} Reporting context for request: {0} Context Reported: {0} @@ -707,16 +707,16 @@ Exception StackTrace: {2} Type cast inner exception: {3} - Serialization depth has been overriden. + Serialization depth has been overridden. Serialized type name: {0} Original depth: {1} - Overriden depth: {2} + Overridden depth: {2} Current depth below top level: {3} - Serialization mode has been overriden. + Serialization mode has been overridden. Serialized type name: {0} - Overriden mode: {1} + Overridden mode: {1} Serialization of a script property has been skipped, because there is no runspace to use for evaluation of the property. diff --git a/src/System.Management.Automation/resources/EventingResources.resx b/src/System.Management.Automation/resources/EventingResources.resx index a501972cf60..edbccb5646b 100644 --- a/src/System.Management.Automation/resources/EventingResources.resx +++ b/src/System.Management.Automation/resources/EventingResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/ExperimentalFeatureStrings.resx b/src/System.Management.Automation/resources/ExperimentalFeatureStrings.resx index 9823f54d51b..eea0cb5c153 100644 --- a/src/System.Management.Automation/resources/ExperimentalFeatureStrings.resx +++ b/src/System.Management.Automation/resources/ExperimentalFeatureStrings.resx @@ -1,7 +1,7 @@ - - + + diff --git a/src/System.Management.Automation/resources/ExtendedTypeSystem.resx b/src/System.Management.Automation/resources/ExtendedTypeSystem.resx index 6a697cba888..3ff5b77fab4 100644 --- a/src/System.Management.Automation/resources/ExtendedTypeSystem.resx +++ b/src/System.Management.Automation/resources/ExtendedTypeSystem.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -156,6 +156,9 @@ Cannot find an overload for "{0}" and the argument count: "{1}". + + Could not find a suitable generic method overload for "{0}" with "{1}" type parameters, and the argument count: "{2}". + Multiple ambiguous overloads found for "{0}" and the argument count: "{1}". @@ -186,6 +189,9 @@ Cannot convert the "{0}" value of type "{1}" to type "{2}". + + Cannot convert the value of type "{0}" to type "{1}". + Cannot convert value "{0}" to type "{1}". Error: "{2}" @@ -349,7 +355,10 @@ "{0}" returned a null value. - The {0} property was not found for the {1} object. The available property is: {2} + The property '{0}' was not found for the '{1}' object. The settable properties are: {2}. + + + The property '{0}' was not found for the '{1}' object. There is no settable property available. Cannot create object of type "{0}". {1} @@ -382,4 +391,16 @@ PS> [System.Collections.Generic.Comparer``1]::get_Default() Cannot create an instance of the ByRef-like type "{0}". ByRef-like types are not supported in PowerShell. + + Extended Type System Hashtable Conversion + + + Type conversion from HashTable to '{0}' will not be allowed in ConstrainedLanguage mode. + + + Extended Type System Hashtable Conversion + + + Type conversion from '{0}' to '{1}' will not be allowed in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx index 1b4d1159e59..85a893f342d 100644 --- a/src/System.Management.Automation/resources/FileSystemProviderStrings.resx +++ b/src/System.Management.Automation/resources/FileSystemProviderStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -216,9 +216,6 @@ An item with the specified name {0} already exists. - - The path length is too short. The character length of a path cannot be less than the character length of the basePath. - A delimiter cannot be specified when reading the stream one byte at a time. @@ -276,9 +273,6 @@ The '{0}' and '{1}' parameters cannot be specified in the same command. - - The substitute path for the DOS device '{0}' is too long. It exceeds the maximum total path length (32,767 characters) that is valid for the Windows API. - A directory is required for the operation. The item '{0}' is not a directory. @@ -324,15 +318,9 @@ Failed to read remote file '{0}'. - - Failed to validate remote destination '{0}'. - Cannot validate if remote destination {0} is a file. - - Remote copy with {0} is not supported. - Failed to create directory '{0}' on remote destination. @@ -340,9 +328,30 @@ Maximum size for drive has been exceeded: {0}. - Cannot create symbolic link because the path {0} already exists. + Cannot create link because the path already exists: {0}. Skip already-visited directory {0}. + + Destination path cannot be a subdirectory of the source or the source itself: {0}. + + + The target and path cannot be the same. + + + Copied {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Removed {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Creating a junction requires an absolute path for the target. + diff --git a/src/System.Management.Automation/resources/FormatAndOutXmlLoadingStrings.resx b/src/System.Management.Automation/resources/FormatAndOutXmlLoadingStrings.resx index 90e85c19cee..154ad925e58 100644 --- a/src/System.Management.Automation/resources/FormatAndOutXmlLoadingStrings.resx +++ b/src/System.Management.Automation/resources/FormatAndOutXmlLoadingStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/FormatAndOut_MshParameter.resx b/src/System.Management.Automation/resources/FormatAndOut_MshParameter.resx index da5015d51dc..09d63693480 100644 --- a/src/System.Management.Automation/resources/FormatAndOut_MshParameter.resx +++ b/src/System.Management.Automation/resources/FormatAndOut_MshParameter.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/FormatAndOut_format_xxx.resx b/src/System.Management.Automation/resources/FormatAndOut_format_xxx.resx index 66cfdc8a25f..db5af6913bc 100644 --- a/src/System.Management.Automation/resources/FormatAndOut_format_xxx.resx +++ b/src/System.Management.Automation/resources/FormatAndOut_format_xxx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/FormatAndOut_out_xxx.resx b/src/System.Management.Automation/resources/FormatAndOut_out_xxx.resx index f5b1aa481f4..52ee1e71e2b 100644 --- a/src/System.Management.Automation/resources/FormatAndOut_out_xxx.resx +++ b/src/System.Management.Automation/resources/FormatAndOut_out_xxx.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/GetErrorText.resx b/src/System.Management.Automation/resources/GetErrorText.resx index 0fcdaf2ed20..6bc1b3117f9 100644 --- a/src/System.Management.Automation/resources/GetErrorText.resx +++ b/src/System.Management.Automation/resources/GetErrorText.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/HelpDisplayStrings.resx b/src/System.Management.Automation/resources/HelpDisplayStrings.resx index 8866eea8d61..5f4b7119ef9 100644 --- a/src/System.Management.Automation/resources/HelpDisplayStrings.resx +++ b/src/System.Management.Automation/resources/HelpDisplayStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -183,9 +183,6 @@ Content: - - Output: - PROVIDER NAME @@ -267,9 +264,6 @@ Cmdlets Supported: - - CMDLETS SUPPORTED - ALIASES @@ -306,6 +300,10 @@ The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + The ModuleBase directory cannot be found. Verify the directory and try again. @@ -357,9 +355,6 @@ Error extracting Help content. - - Error installing help content. - Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. @@ -397,6 +392,9 @@ English-US help content is available and can be saved using: Save-Help -UICultur Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + false diff --git a/src/System.Management.Automation/resources/HelpErrors.resx b/src/System.Management.Automation/resources/HelpErrors.resx index 851e457cf27..db9fa56e697 100644 --- a/src/System.Management.Automation/resources/HelpErrors.resx +++ b/src/System.Management.Automation/resources/HelpErrors.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -179,7 +179,7 @@ To update these Help topics, start PowerShell by using the "Run as Administrator" command, and try running Update-Help again. - To use the {0}, install Windows PowerShell ISE by using Server Manager, and then restart this application. ({1}) + To use the {0}, make sure your application uses 'Microsoft.NET.Sdk.WindowsDesktop' as the project SDK and the corresponding assembly 'Microsoft.PowerShell.GraphicalHost' is available. ({1}) {0} does not work in a remote session. @@ -187,4 +187,7 @@ To update these Help topics, start PowerShell by using the "Run as Administrator ForwardHelpTargetName cannot refer to the function itself. + + Cannot get help from a network location when in a restricted session. + diff --git a/src/System.Management.Automation/resources/HistoryStrings.resx b/src/System.Management.Automation/resources/HistoryStrings.resx index c20b5bc6855..4f7a4bcc72a 100644 --- a/src/System.Management.Automation/resources/HistoryStrings.resx +++ b/src/System.Management.Automation/resources/HistoryStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Cannot locate history. - The identifier {0} is not a valid value for a History identifier. Specify a positive number, and then try again. @@ -147,9 +144,6 @@ The identifier {0} is not valid. Specify a positive number, and then try again. - - Note: {0} entries were cleared from the session history. - This command will clear all the entries from the session history. diff --git a/src/System.Management.Automation/resources/HostInterfaceExceptionsStrings.resx b/src/System.Management.Automation/resources/HostInterfaceExceptionsStrings.resx index 4e4de9adaca..0dd66d88a53 100644 --- a/src/System.Management.Automation/resources/HostInterfaceExceptionsStrings.resx +++ b/src/System.Management.Automation/resources/HostInterfaceExceptionsStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/InternalCommandStrings.resx b/src/System.Management.Automation/resources/InternalCommandStrings.resx index 4f2705670bc..d368d449d20 100644 --- a/src/System.Management.Automation/resources/InternalCommandStrings.resx +++ b/src/System.Management.Automation/resources/InternalCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -184,4 +184,10 @@ ErrorAction, WarningAction, InformationAction, PipelineVariable An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/InternalHostStrings.resx b/src/System.Management.Automation/resources/InternalHostStrings.resx index 861c7609d05..2c0d07096ac 100644 --- a/src/System.Management.Automation/resources/InternalHostStrings.resx +++ b/src/System.Management.Automation/resources/InternalHostStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Cannot exit a nested prompt because no nested prompts exist. - EnterNestedPrompt has not been called as many times as ExitNestedPrompt. diff --git a/src/System.Management.Automation/resources/InternalHostUserInterfaceStrings.resx b/src/System.Management.Automation/resources/InternalHostUserInterfaceStrings.resx index 7a8882643da..b0e26009599 100644 --- a/src/System.Management.Automation/resources/InternalHostUserInterfaceStrings.resx +++ b/src/System.Management.Automation/resources/InternalHostUserInterfaceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/Logging.resx b/src/System.Management.Automation/resources/Logging.resx index c91871fe191..ef2390a1c10 100644 --- a/src/System.Management.Automation/resources/Logging.resx +++ b/src/System.Management.Automation/resources/Logging.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/Metadata.resx b/src/System.Management.Automation/resources/Metadata.resx index 61aad9f57b5..a9cdca1bc50 100644 --- a/src/System.Management.Automation/resources/Metadata.resx +++ b/src/System.Management.Automation/resources/Metadata.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -175,7 +175,7 @@ The character length ({1}) of the argument is too short. Specify an argument with a length that is greater than or equal to "{0}", and then try the command again. - The character length of the {1} argument is too long. Shorten the character length of the argument so it is fewer than or equal to "{0}" characters, and then try the command again. + The character length ({1}) of the argument is too long. Specify an argument with a length that is shorter than or equal to "{0}", and then try the command again. The argument "{0}" does not belong to the set "{1}" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. @@ -210,6 +210,12 @@ The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. + + The argument is null, empty, or consists of only white-space characters. Provide an argument that contains non white-space characters, and then try the command again. + + + An element of the argument collection is null, empty, or consists of only white-space characters. Supply a collection that does not contain any those values and then try the command again. + A parameter with the name '{0}' was defined multiple times for the command. @@ -252,4 +258,10 @@ Cannot process input. The argument "{0}" is not trusted. + + ValidateTrustedData Attribute Check Failure + + + The parameter argument '{0}' is not trusted and will fail the ValidateTrustedData parameter attribute check in Constrained Language mode. + diff --git a/src/System.Management.Automation/resources/MiniShellErrors.resx b/src/System.Management.Automation/resources/MiniShellErrors.resx index 152a8f7ad69..d3fa0e20f00 100644 --- a/src/System.Management.Automation/resources/MiniShellErrors.resx +++ b/src/System.Management.Automation/resources/MiniShellErrors.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/Modules.resx b/src/System.Management.Automation/resources/Modules.resx index 345811502b6..6319659f1a7 100644 --- a/src/System.Management.Automation/resources/Modules.resx +++ b/src/System.Management.Automation/resources/Modules.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -231,6 +231,21 @@ The required module '{1}' with MinimumVersion '{2}' and MaximumVersion '{3}' is not loaded. Load the module or remove the module from 'RequiredModules' in the file '{0}'. + + The module '{0}' cannot be found with ModuleVersion '{1}'. + + + The module '{0}' cannot be found with RequiredVersion '{1}'. + + + The module '{0}' cannot be found with MaximumVersion '{1}'. + + + The module '{0}' cannot be found with ModuleVersion '{1}' and MaximumVersion '{2}'. + + + The module '{0}' cannot be found. + No modules were removed. Verify that the specification of modules to remove is correct and those modules exist in the runspace. @@ -624,4 +639,49 @@ Cannot create new module while the session is in ConstrainedLanguage mode. + + Cannot find the built-in module '{0}' that is compatible with the 'Core' edition. Please make sure the PowerShell built-in modules are available. They usually come with the PowerShell package under the $PSHOME module path, and are required for PowerShell to function properly. + + + Export-ModuleMember Cmdlet + + + Export of module members will fail in Constrained Language mode because module '{0}', has a language mode '{1}' that is different from the current session '{2}'. + + + Module Implicit Function Export + + + Implicit function export for module '{0}' will be denied because it is trusted (runs in Full Language mode) but the session is not trusted (runs in Constrained Language mode). It is best practice to always export module functions individually by full name. + + + Importing Script File as Module + + + Importing the script file '{0}' as a module will be disallowed in ConstrainedLanguage mode. + + + Module Contains Dot-Source Operator + + + Module '{0}' import will in fail Constrained Language mode because it exports functions using wildcard characters while also using the dot-source operator. + + + "Module Exporting Functions + + + Module '{0}' exports functions using name wildcard characters. Any nested module function names will be removed when running in Constrained Language mode. + + + "New-Module Cmdlet + + + A new module from an untrusted Constrained Language session will be blocked from providing the FullLanguage script block. + + + "Module Mismatched Language Modes + + + A dependent module is being loaded that has a different language mode than the parent. This will be disallowed when in Constrained Language mode. + diff --git a/src/System.Management.Automation/resources/MshHostRawUserInterfaceStrings.resx b/src/System.Management.Automation/resources/MshHostRawUserInterfaceStrings.resx index a374f535a98..a2c2a743d1e 100644 --- a/src/System.Management.Automation/resources/MshHostRawUserInterfaceStrings.resx +++ b/src/System.Management.Automation/resources/MshHostRawUserInterfaceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/MshSignature.resx b/src/System.Management.Automation/resources/MshSignature.resx index 3285c83d5d1..ca58d166428 100644 --- a/src/System.Management.Automation/resources/MshSignature.resx +++ b/src/System.Management.Automation/resources/MshSignature.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/MshSnapInCmdletResources.resx b/src/System.Management.Automation/resources/MshSnapInCmdletResources.resx index 225ef930619..00ff366541c 100644 --- a/src/System.Management.Automation/resources/MshSnapInCmdletResources.resx +++ b/src/System.Management.Automation/resources/MshSnapInCmdletResources.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/MshSnapinInfo.resx b/src/System.Management.Automation/resources/MshSnapinInfo.resx index 916a4ea3891..4822e8e7c65 100644 --- a/src/System.Management.Automation/resources/MshSnapinInfo.resx +++ b/src/System.Management.Automation/resources/MshSnapinInfo.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/NativeCP.resx b/src/System.Management.Automation/resources/NativeCP.resx index 3d8a596f941..72618d9ce8c 100644 --- a/src/System.Management.Automation/resources/NativeCP.resx +++ b/src/System.Management.Automation/resources/NativeCP.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/PSCommandStrings.resx b/src/System.Management.Automation/resources/PSCommandStrings.resx index ba273e4ad20..19d64556b63 100644 --- a/src/System.Management.Automation/resources/PSCommandStrings.resx +++ b/src/System.Management.Automation/resources/PSCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/PSConfigurationStrings.resx b/src/System.Management.Automation/resources/PSConfigurationStrings.resx index a1671d7f9e8..26dff6b06fb 100644 --- a/src/System.Management.Automation/resources/PSConfigurationStrings.resx +++ b/src/System.Management.Automation/resources/PSConfigurationStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/PSDataBufferStrings.resx b/src/System.Management.Automation/resources/PSDataBufferStrings.resx index 2cfe484db12..0f5b9269f09 100644 --- a/src/System.Management.Automation/resources/PSDataBufferStrings.resx +++ b/src/System.Management.Automation/resources/PSDataBufferStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/PSListModifierStrings.resx b/src/System.Management.Automation/resources/PSListModifierStrings.resx index f40c61a21a9..c9d82870a7b 100644 --- a/src/System.Management.Automation/resources/PSListModifierStrings.resx +++ b/src/System.Management.Automation/resources/PSListModifierStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/PSStyleStrings.resx b/src/System.Management.Automation/resources/PSStyleStrings.resx new file mode 100644 index 00000000000..f8917325e88 --- /dev/null +++ b/src/System.Management.Automation/resources/PSStyleStrings.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 string contains printable content when it should only contain ANSI escape sequences: {0} + + + The MaxWidth for the Progress rendering must be at least 18 to render correctly. + + + When adding or removing extensions, the extension must start with a period. + + diff --git a/src/System.Management.Automation/resources/ParameterBinderStrings.resx b/src/System.Management.Automation/resources/ParameterBinderStrings.resx index 8c49becc278..23ee4865ff2 100644 --- a/src/System.Management.Automation/resources/ParameterBinderStrings.resx +++ b/src/System.Management.Automation/resources/ParameterBinderStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -174,9 +174,6 @@ Cannot retrieve the dynamic parameters for the cmdlet. {6} - - Cannot retrieve dynamic parameters for the cmdlet. Dynamic parameter '{1}' specified parameter set '{6}' which was not statically defined for this cmdlet. New parameter sets may not be defined as dynamic parameters, although dynamic parameters may join parameter sets which were statically defined. - Supply values for the following parameters: @@ -222,9 +219,6 @@ Multiple different default values are defined in $PSDefaultParameterValues for the parameter matching the following name or alias: {0}. These defaults have been ignored. - - The automatic variable $PSDefaultParameterValues was ignored because it is not a valid hashtable object. It must be of the type IDictionary. - The following name or alias defined in $PSDefaultParameterValues for this cmdlet resolves to multiple parameters: {0}. The default has been ignored. @@ -252,4 +246,16 @@ The key '{0}' has already been added to the dictionary. + + Method or Property Invocation Not Allowed + + + Invocation of Method or Property '{0}' on type '{1}' will not be allowed in Constrained Language mode for untrusted scripts. + + + Type Creation Not Allowed + + + Creation of Type '{0}' will not be allowed during parameter binding in Constrained Language mode for untrusted scripts. + diff --git a/src/System.Management.Automation/resources/ParserStrings.resx b/src/System.Management.Automation/resources/ParserStrings.resx index dd9ce1b8c55..680de71c01e 100644 --- a/src/System.Management.Automation/resources/ParserStrings.resx +++ b/src/System.Management.Automation/resources/ParserStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -123,9 +123,6 @@ Unable to find type [{0}]. Details: {1} - - Incomplete variable reference token. - Incomplete string token. @@ -141,9 +138,6 @@ The Unicode escape sequence contains more than the maximum of six hex digits between braces. - - A number cannot be both a long and floating point. - Cannot use [ref] with other types in a type constraint. @@ -183,14 +177,6 @@ Parameter '{0}' is not valid - - Ambiguous parameter '-{0}' -Possible matches are - - - - {0} ({1}) - Missing expression after '{0}' in pipeline element. @@ -227,15 +213,9 @@ Possible matches are An empty pipe element is not allowed. - - Unknown assignment operator '{0}'. - The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. - - Cannot expand the splatted variable '@{0}'. Splatted variables cannot be used as part of a property or array expression. Assign the result of the expression to a temporary variable then splat the temporary variable instead. - A hash table can only be added to another hash table. @@ -260,9 +240,6 @@ Possible matches are You must provide a value expression following the '{0}' operator. - - A regular expression that was provided to '{0}' is not valid: {1}. - The '{0}' operator works only on variables or on properties. @@ -275,9 +252,6 @@ Possible matches are Missing property name after reference operator. - - Property reference or expression is missing or not valid. - The property '{0}' cannot be found on this object. Verify that the property exists and can be set. @@ -296,8 +270,8 @@ Possible matches are Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. - - Array assignment to [{0}] failed: {1}. + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. Array assignment to [{0}] failed because assignment to slices is not supported. @@ -305,18 +279,9 @@ Possible matches are You cannot index into a {0} dimensional array with index [{1}]. - - Unable to assign to a dictionary of type {0} when the key is of type {1}. - - - Unable to assign to an index into an object of type {0}. - Array assignment failed because index '{0}' was out of range. - - Assigning to array element at index [{0}] failed: {1}. - Missing expression after '{0}'. @@ -347,15 +312,9 @@ Possible matches are An expression was expected after '('. - - Missing key before '=' in hash literal. - Missing '=' operator after key in hash literal. - - The "=" operator is missing after a named argument. - Missing statement after '=' in hash literal. @@ -389,9 +348,6 @@ Possible matches are The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. - - The switch statement was incomplete. - The {0} '-{1}' parameter is reserved for future use. @@ -410,9 +366,6 @@ Possible matches are A switch statement must have one of the following: '-file file_name' or '( expression )'. - - Missing expression after '(' in switch statement. - Missing condition in switch statement clause. @@ -457,15 +410,9 @@ The correct form is: foreach ($a in $b) {...} Options are not allowed on the -split operator with a predicate. - - The terminator '{0}' is missing from the multiline comment. - The token '{0}' is not a valid statement separator in this version. - - The 'from' keyword is not supported in this version of the language. - The '{0}' keyword is not supported in this version of the language. @@ -481,23 +428,17 @@ The correct form is: foreach ($a in $b) {...} Incomplete 'try' statement. A try statement requires a body. - - The character '{0}' is not valid. Labels can contain only alphanumeric characters, numbers, and underscores ('_'). - Parameter declarations are a comma-separated list of variable names with optional initializer expressions. Missing function body in function declaration. - - Could not process combined Begin/Process/End clauses with command text. A script or function can either have begin/process/end clauses or command text but not both. - Script command clause '{0}' has already been defined. - unexpected token '{0}', expected 'begin', 'process', 'end', or 'dynamicparam'. + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. Missing closing '}' in statement block or type definition. @@ -611,45 +552,18 @@ The correct form is: foreach ($a in $b) {...} At {0}:{1} char:{2} + {3} - - At char:{0} - {0,4}+ {1} - - ! Trap or Catch on matching exception [{0}] - - - ! Trap or Catch on [{0}]; subclass of exception [{1}] - - - ! Trap or Catch generic; caught [{0}] - - - ! SET-MULTIPLE ${0} assigned remaining {1} values. - - - ! SET-MULTIPLE ${0} = '{1}'. - ! SET ${0} = '{1}'. - - ! CALL scriptblock. - - - ! CALL script '{0}' - ! CALL function '{0}' ! CALL function '{0}' (defined in file '{1}') - - ! Setting parameterized property '{0}' - ! CALL method '{0}' @@ -662,42 +576,15 @@ The correct form is: foreach ($a in $b) {...} Missing ] at end of type token. - - Missing ) at end of subexpression. - Use `{ instead of { in variable names. - - Missing } at end of variable name. - - - Braced variable name cannot be empty. - The Data section is missing its statement block. - - Missing the opening brace "{" in the Data section. - - - Missing closing brace in the data section statement. - - - The body of the Data section is not valid. The Data section body can be only a convert-* command invocation optionally enclosed by an If statement. - The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. - - Expandable strings are not allowed in the list of supported commands for the Data section. - - - A token that is not valid was found in the list of supported commands for the Data section. - - - The Data section variable "{0}" has already been used for an existing variable or another Data section. - Array references are not allowed in restricted language mode or a Data section. @@ -707,9 +594,6 @@ The correct form is: foreach ($a in $b) {...} Redirection is not allowed in restricted language mode or a Data section. - - A command is referenced that is not allowed. Only convertfrom-* commands are supported in restricted language mode or a Data section. - The Do and While statements are not allowed in restricted language mode or a Data section. @@ -782,21 +666,12 @@ The correct form is: foreach ($a in $b) {...} Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. - - Cannot find an appropriate constructor to instantiate the custom attribute object for type '{0}'. - - - The custom attribute type '{0}' is not derived from System.Attribute. - Property '{0}' cannot be found for type '{1}'. Unexpected attribute '{0}'. - - Operator '{0}' is not supported for type '{1}'. - Missing ] at end of attribute or type literal. @@ -893,9 +768,6 @@ The correct form is: foreach ($a in $b) {...} error stream - - host stream - output stream @@ -956,12 +828,6 @@ The correct form is: foreach ($a in $b) {...} An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. - - The configuration name is missing or '{' was not found for a default definition. - - - The parameter {0} is not valid for the configuration statement. - The member '{0}' is not valid. Valid members are '{1}'. @@ -969,9 +835,6 @@ The correct form is: foreach ($a in $b) {...} Missing '{' in object definition. - - Parameter {0} can only be specified once for a configuration. - A required name or expression was missing. @@ -990,14 +853,6 @@ The correct form is: foreach ($a in $b) {...} The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. - - Missing argument to -Resources. The argument to the -Resource parameter must be a comma-separated list of names or constant strings naming modules to reference for resource type definitions. - -Required Resources should not be localized - - - Unexpected token '{0}'. The argument to the -Resource parameter must be a comma-separated list of names or constant strings naming modules to reference for resource type definitions. - -Resource parameter should not be localized - Could not find the module '{0}'. @@ -1126,6 +981,9 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + Script block with a 'clean' block is not supported by the 'ForEach' method. + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. @@ -1150,15 +1008,9 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Missing using directive - - Missing property name - Missing namespace alias - - Missing type alias - Missing '=' operator @@ -1377,6 +1229,9 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent This syntax of the 'using' statement is not supported. + + The specified namespace in the 'using' statement contains invalid characters. + information stream @@ -1455,33 +1310,9 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. - - PS7DscSupport experimental feature is disabled; use Enable-ExperimentalFeature or update powershell.config.json to enable this feature. - {0} - - Command pipeline not supported for implicit remoting batching. - - - Command is not a simple pipeline and cannot be batched. - - - The pipeline command '{0}' is not an implicit remoting command or an approved batching command. - - - The pipeline command '{0}' is for a different remote session and cannot be batched. - - - The implicit remoting PSSession for batching could not be retrieved. - - - Exception while checking the command for implicit remoting batching: {0} - - - Implicit remoting command pipeline has been batched for execution on remote target. - This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. @@ -1500,4 +1331,46 @@ ModuleVersion : Version of module to import. If used, ModuleName must represent Background operators can only be used at the end of a pipeline chain. + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + diff --git a/src/System.Management.Automation/resources/PathUtilsStrings.resx b/src/System.Management.Automation/resources/PathUtilsStrings.resx index 217f2522ac8..2af7f7ec9de 100644 --- a/src/System.Management.Automation/resources/PathUtilsStrings.resx +++ b/src/System.Management.Automation/resources/PathUtilsStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -138,6 +138,9 @@ The directory '{0}' already exists. Use the -Force parameter if you want to overwrite the directory and files within the directory. + + The user module path does not exist, and hence a module folder cannot be created for the provided module name '{0}'. + Cannot create the module {0} due to the following: {1}. Use a different argument for the -OutputModule parameter and retry. {StrContains="OutputModule"} diff --git a/src/System.Management.Automation/resources/PipelineStrings.resx b/src/System.Management.Automation/resources/PipelineStrings.resx index dd44966fc03..8262e72cd95 100644 --- a/src/System.Management.Automation/resources/PipelineStrings.resx +++ b/src/System.Management.Automation/resources/PipelineStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/PowerShellStrings.resx b/src/System.Management.Automation/resources/PowerShellStrings.resx index 230ac1b2685..efcf92e6740 100644 --- a/src/System.Management.Automation/resources/PowerShellStrings.resx +++ b/src/System.Management.Automation/resources/PowerShellStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -132,12 +132,6 @@ Cannot perform operation because the runspace is not in the '{0}' state. Current state of runspace is '{1}'. - - The runspace pool specified is not in an opened state. - - - This operation is currently not supported in the remoting scenario. - Nested PowerShell instances cannot be invoked asynchronously. Use the Invoke method. @@ -159,24 +153,6 @@ There is no Runspace available to run commands in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The command you attempted to invoke was: {0} - - GetJobForCommand is not supported when there is more than one command in the PowerShell instance. - - - The Command property of a PowerShell object cannot be empty. - - - A job cannot be started when it is already running. - - - Support for interactive jobs is not available - - - A job object can be used only once. - - - A job object cannot be reused. - This PowerShell object cannot be connected because it is not associated with a remote runspace or runspace pool. @@ -192,10 +168,6 @@ The connection attempt to the remote command failed. - - PSChildJobProxy does not support control methods. - PSChildJobProxy is the name of a class and should not be localized - The operation cannot be performed because a command is currently stopping. Wait for the command to complete stopping, and then try the operation again. diff --git a/src/System.Management.Automation/resources/ProgressRecordStrings.resx b/src/System.Management.Automation/resources/ProgressRecordStrings.resx index f2ac355ab0a..14752a0be59 100644 --- a/src/System.Management.Automation/resources/ProgressRecordStrings.resx +++ b/src/System.Management.Automation/resources/ProgressRecordStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/ProviderBaseSecurity.resx b/src/System.Management.Automation/resources/ProviderBaseSecurity.resx index f2c066caa4a..f0465e430d6 100644 --- a/src/System.Management.Automation/resources/ProviderBaseSecurity.resx +++ b/src/System.Management.Automation/resources/ProviderBaseSecurity.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/ProxyCommandStrings.resx b/src/System.Management.Automation/resources/ProxyCommandStrings.resx index 7c5450f9c50..bc921b07d8b 100644 --- a/src/System.Management.Automation/resources/ProxyCommandStrings.resx +++ b/src/System.Management.Automation/resources/ProxyCommandStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/RegistryProviderStrings.resx b/src/System.Management.Automation/resources/RegistryProviderStrings.resx index 046d28b3c10..3bd2e97959b 100644 --- a/src/System.Management.Automation/resources/RegistryProviderStrings.resx +++ b/src/System.Management.Automation/resources/RegistryProviderStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -132,9 +132,6 @@ New Item - - Item: {0} Type: {1} - Item: {0} @@ -174,24 +171,6 @@ Item: {0} Property: {1} - - Set Property Value At - - - Item: {0} Property: {1} At: {2} - - - Add Property Value At - - - Item: {0} Property: {1} At: {2} - - - Remove Property Value At - - - Item: {0} Property: {1} At: {2} - New Property @@ -222,9 +201,6 @@ Item: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} - - (default) - The operation was not processed. The location that was provided does not allow this operation. @@ -246,15 +222,6 @@ The operation cannot be performed because the destination path is subordinate to the source path. - - The at parameter must be an integer to index a specific property value. - - - The property is not a multi-valued property. To remove this property, use Remove-ItemProperty. - - - The property is not a multi-valued property and values cannot be added to it. To change the value use Set-ItemProperty. - The property already exists. @@ -330,24 +297,12 @@ The specified RegistryKeyPermissionCheck value is not valid. - - A transaction argument must be specified. - - - The specified SafeHandle value is not valid. - The registry key has subkeys; recursive removals are not supported by this method. - - Remote registry operations are not allowed with transactions. - Cannot create a KTM handle without a Transaction.Current or specified transaction. - - The object does not contain a security descriptor. - The specified transaction or Transaction.Current must match the transaction used to create or open this TransactedRegistryKey. @@ -357,21 +312,6 @@ Requested registry access is not allowed. - - The security identifier is not allowed to be the owner of this object. - - - The security identifier is not allowed to be the primary group of this object. - - - Method failed with unexpected error code {0}. - - - Unable to perform a security operation on an object that has no associated security. This can happen when trying to get an ACL of an anonymous kernel object. - - - Transaction related error {0} occurred. - Access to the registry key '{0}' is denied. @@ -387,15 +327,6 @@ Registry transactions are not supported on this platform. - - The specified permission name is not valid. - - - Incorrect thread for enabling or disabling a privilege. - - - The permission must be reverted before changing its state again. - The specified handle is not valid. diff --git a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx index b4f9dc40a89..029a7b47b6e 100644 --- a/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx +++ b/src/System.Management.Automation/resources/RemotingErrorIdStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -123,6 +123,9 @@ Out of process memory. + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". @@ -837,8 +840,7 @@ Note that 'Start-Job' is not supported by design in scenarios where PowerShell i A {1} job source adapter threw an exception with the following message: {0} - The value {0} is not valid for the {1} parameter. The available values are 2.0, 3.0, 4.0, 5.0, 5.1. - {StrContains="2.0"} {StrContains="3.0"} + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. The Wait and Keep parameters cannot be used together in the same command. @@ -846,8 +848,8 @@ Note that 'Start-Job' is not supported by design in scenarios where PowerShell i The WriteEvents parameter cannot be used without the Wait parameter. - - PowerShell {0} is not installed. Install PowerShell {0}, and then try again. + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. The following type cannot be instantiated because its constructor is not public: {0}. @@ -1361,7 +1363,7 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. - The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell {0} or greater. + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. @@ -1409,7 +1411,7 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. - Cannot enter process {0} because it has not loaded the PowerShell engine. + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. No process was found with Id: {0}. @@ -1625,6 +1627,13 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro The SSH client session has ended with error message: {0} + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. @@ -1696,4 +1705,31 @@ All WinRM sessions connected to PowerShell session configurations, such as Micro Unable to create Windows PowerShell process because Windows PowerShell could not be found on this machine. + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + diff --git a/src/System.Management.Automation/resources/RunspaceInit.resx b/src/System.Management.Automation/resources/RunspaceInit.resx index ac900465d7d..4065ee892ac 100644 --- a/src/System.Management.Automation/resources/RunspaceInit.resx +++ b/src/System.Management.Automation/resources/RunspaceInit.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -153,6 +153,9 @@ The text encoding used when piping text to a native executable file + + The text encoding used when reading output text from a native executable file + Configuration controlling how text is rendered. @@ -186,9 +189,15 @@ Dictates what type of prompt should be displayed for the current nesting level + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + If true, WhatIf is considered to be enabled for all commands. + + Dictates how arguments are passed to native executables. + Dictates the limit of enumeration on formatting IEnumerable objects diff --git a/src/System.Management.Automation/resources/RunspacePoolStrings.resx b/src/System.Management.Automation/resources/RunspacePoolStrings.resx index 515bcece698..56c21ec7c63 100644 --- a/src/System.Management.Automation/resources/RunspacePoolStrings.resx +++ b/src/System.Management.Automation/resources/RunspacePoolStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,9 +117,6 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - The runspace pool is closed. - The maximum pool size cannot be less than 1. @@ -150,9 +147,6 @@ This runspace does not support disconnect and connect operations. - - Cannot set the TypeTable data unless the runspace pool is in either the Disconnected or BeforeOpen states. Current state is {0}. - Cannot perform the operation because the runspace pool is in the Disconnected state. diff --git a/src/System.Management.Automation/resources/RunspaceStrings.resx b/src/System.Management.Automation/resources/RunspaceStrings.resx index fa98177bc95..e44f2d7a202 100644 --- a/src/System.Management.Automation/resources/RunspaceStrings.resx +++ b/src/System.Management.Automation/resources/RunspaceStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -162,9 +162,6 @@ A pipeline is already running. Concurrent SessionStateProxy method calls are not allowed. - - Parameter name or value must be specified. - This property cannot be changed after the runspace has been opened. @@ -207,9 +204,6 @@ Cannot connect the PSSession because the session is not in the Disconnected state, or is not available for connection. - - One or more errors occurred while processing the module '{0}' that is specified in the InitialSessionState object used to create this runspace. For a complete list of errors, see the ErrorRecords property. - Value for parameter cannot be PipelineResultTypes.None or PipelineResultTypes.Output. diff --git a/src/System.Management.Automation/resources/SecuritySupportStrings.resx b/src/System.Management.Automation/resources/SecuritySupportStrings.resx index cd8a65a5c90..c8ad9f45ef6 100644 --- a/src/System.Management.Automation/resources/SecuritySupportStrings.resx +++ b/src/System.Management.Automation/resources/SecuritySupportStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -153,4 +153,16 @@ Invalid session key data. + + Script file, '{0}', is blocked from running by system policy. + + + An unknown script file policy enforcement value was returned: {0}. + + + Script File Read + + + Script file '{0}' is not trusted by policy and will run in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/Serialization.resx b/src/System.Management.Automation/resources/Serialization.resx index ba06ef49e5d..97e7c25bbe9 100644 --- a/src/System.Management.Automation/resources/Serialization.resx +++ b/src/System.Management.Automation/resources/Serialization.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/SessionStateProviderBaseStrings.resx b/src/System.Management.Automation/resources/SessionStateProviderBaseStrings.resx index 66a09019c5d..d6065be343c 100644 --- a/src/System.Management.Automation/resources/SessionStateProviderBaseStrings.resx +++ b/src/System.Management.Automation/resources/SessionStateProviderBaseStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/SessionStateStrings.resx b/src/System.Management.Automation/resources/SessionStateStrings.resx index 39dd766d749..b106f073d7f 100644 --- a/src/System.Management.Automation/resources/SessionStateStrings.resx +++ b/src/System.Management.Automation/resources/SessionStateStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -138,9 +138,6 @@ Attempting to perform the ClearItem operation on the '{0}' provider failed for path '{1}'. {2} - - The dynamic parameters for the ClearItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} - Attempting to perform the InvokeDefaultAction operation on the '{0}' provider failed for path '{1}'. {2} @@ -159,15 +156,9 @@ Attempting to perform the IsItemContainer operation on the '{0}' provider failed for path '{1}'. {2} - - The dynamic parameters for the IsItemContainer cannot be retrieved from the '{0}' provider for path '{1}'. {2} - Attempting to perform the RemoveItem operation on the '{0}' provider failed for path '{1}'. {2} - - The dynamic parameters for the RemoveItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} - Attempting to perform the GetChildItems operation on the '{0}' provider failed for path '{1}'. {2} @@ -309,15 +300,9 @@ Attempting to perform the SetSecurityDescriptor operation on the '{0}' provider failed for path '{1}'. {2} - - This provider does not support security descriptor related operations. - Attempting to perform the Start operation on the '{0}' provider failed. {1} - - Attempting to perform the StartDynamicParameters operation on the '{0}' provider failed for the path '{1}'. {2} - Attempting to perform the InitializeDefaultDrives operation on the '{0}' provider failed. @@ -333,9 +318,6 @@ Drive '{0}' cannot be removed because the provider '{1}' prevented it. - - The path '{0}' is shorter than the base path '{1}'. - The path '{0}' referred to an item that was outside the base '{1}'. @@ -393,27 +375,15 @@ Alias {0} cannot be modified because it is read-only. - - Filter {0} cannot be modified because it is constant. - - - Filter {0} cannot be modified because it is read-only. - Cannot modify function {0} because it is constant. Cannot modify function {0} because it is read-only. - - Cannot modify variable {0} because it is a constant. - Alias {0} cannot be made constant after it has been created. Aliases can only be made constant at creation time. - - Existing filter {0} cannot be made constant. Filters can be made constant only at creation time. - Existing function {0} cannot be made constant. Functions can be made constant only at creation time. @@ -423,9 +393,6 @@ The AllScope option cannot be removed from the alias '{0}'. - - The AllScope option cannot be removed from the filter '{0}'. - The AllScope option cannot be removed from the function '{0}'. @@ -457,7 +424,7 @@ Cannot find alias because alias '{0}' does not exist. - Cannot set the location because path '{0}' resolved to multiple containers. You can only the set location to a single container at a time. + Cannot set the location because path '{0}' resolved to multiple containers. You can only set the location to a single container at a time. Cannot process variable because variable path '{0}' resolved to multiple items. You can get or set the variable value only one item at a time. @@ -507,9 +474,6 @@ Global scope cannot be removed. - - Too many scopes have been created. - The scope number '{0}' exceeds the number of active scopes. @@ -627,72 +591,18 @@ Drive that maps to the temporary directory path for the current user - - The path is not in the correct format. Paths can contain only provider and drive names separated by slashes or backslashes. - - - Cannot remove provider because removal of providers is not supported. - - - Cannot create provider because creation of new providers is not supported. - - - Drive that contains the list of loaded providers and their drives - - - The root of the drive '{0}' cannot be modified. - - - Cannot create a new provider because type '{0}' is not of type "provider". - - - Cannot set the new item value because the parameter "value" must be of the type ProviderInfo when "type" is specified as "provider". - - - Cannot create a new drive because type '{0}' is not of type "drive". - - - Cannot set new item value because the parameter "value" must be of type PSDriveInfo when "type" is specified as "drive". - - - Cannot create new drive because the name specified in the PSDriveInfo '{0}' does not match the drive name specified in the path '{1}'. - - - The provider name specified in the PSDriveInfo '{0}' does not match the provider name specified in the path '{1}'. - - - Cannot remove the drive root in this way. Use "Remove-PSDrive" to remove this drive. - - Link '{0}' cannot be created because Target was not specified. + Link '{0}' cannot be created because the target Value was not specified. References to the null variable always return the null value. Assignments have no effect. - - Maximum number of errors to retain in a session - - - Maximum number of drives allowed in a session - - - Maximum number of aliases allowed in a session - - - Maximum number of functions allowed in a session - - - Maximum number of variables allowed in a session - Maximum number of history objects to retain in a session Cannot rename function because function {0} is read-only or constant. - - Cannot rename filter because filter {0} is read-only or constant. - Cannot rename alias because alias {0} is read-only or constant. @@ -738,4 +648,10 @@ '{0}' parameter cannot be null or empty. + + Session State Variables + + + Changing or creating the variable '{0}' scope to AllScope will be prevented in ConstrainedLanguage mode. + diff --git a/src/System.Management.Automation/resources/StringDecoratedStrings.resx b/src/System.Management.Automation/resources/StringDecoratedStrings.resx new file mode 100644 index 00000000000..fc828f5284e --- /dev/null +++ b/src/System.Management.Automation/resources/StringDecoratedStrings.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Only 'ANSI' or 'PlainText' is supported for this method. + + diff --git a/src/System.Management.Automation/resources/SubsystemStrings.resx b/src/System.Management.Automation/resources/SubsystemStrings.resx index a2819da8682..94f767d0778 100644 --- a/src/System.Management.Automation/resources/SubsystemStrings.resx +++ b/src/System.Management.Automation/resources/SubsystemStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -135,11 +135,14 @@ The specified subsystem type '{0}' is unknown. + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + The specified subsystem kind '{0}' is unknown. - - The specified implementation instance implements the subsystem '{0}', which does not match the target subsystem '{1}'. + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. diff --git a/src/System.Management.Automation/resources/SuggestionStrings.resx b/src/System.Management.Automation/resources/SuggestionStrings.resx index cd44c33e759..b25d11103ae 100644 --- a/src/System.Management.Automation/resources/SuggestionStrings.resx +++ b/src/System.Management.Automation/resources/SuggestionStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -117,22 +117,13 @@ System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - Once a transaction is started, only commands that get called with the -UseTransaction flag become part of that transaction. - - - The Use-Transaction cmdlet is intended for scripting of transaction-enabled .NET objects. Its ScriptBlock should contain nothing else. - - The command {0} was not found, but does exist in the current location. PowerShell does not load commands from the current location by default. If you trust this command, instead type: "{1}". See "get-help about_Command_Precedence" for more details. + The command "{0}" was not found, but does exist in the current location. +PowerShell does not load commands from the current location by default (see 'Get-Help about_Command_Precedence'). + +If you trust this command, run the following command instead: - The most similar commands are: {0}. - - - Rule must be a ScriptBlock for dynamic match types. - - - MatchType must be 'Command', 'Error', or 'Dynamic'. + The most similar commands are: diff --git a/src/System.Management.Automation/resources/TabCompletionStrings.resx b/src/System.Management.Automation/resources/TabCompletionStrings.resx index 33710a77176..5e32821765a 100644 --- a/src/System.Management.Automation/resources/TabCompletionStrings.resx +++ b/src/System.Management.Automation/resources/TabCompletionStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -329,4 +329,282 @@ Shift Right bit operator. Inserts zero in the left-most bit position. For signed values, sign bit is preserved. + + [string] +Specifies the name of the property being created. + + + [string] +Specifies the name of the property being created. + + + [scriptblock] +A script block used to calculate the value of the new property. + + + [string] +Define how the values are displayed in a column. +Valid values are 'left', 'center', or 'right'. + + + [string] +Specifies a format string that defines how the value is formatted for output. + + + [int] +Specifies the maximum column width in a table when the value is displayed. +The value must be greater than 0. + + + [int] +The depth key specifies the depth of expansion per property. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [String[]] +Specifies the log names to get events from. +Supports wildcards. + + + [String[]] +Specifies the event log providers to get events from. +Supports wildcards. + + + [String[]] +Specifies file paths to log files to get events from. +Valid file formats are: .etl, .evt, and .evtx + + + [Long[]] +Selects events with the specified keyword bitmasks. +The following are standard keywords: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Selects events with the specified event IDs. + + + [int[]] +Selects events with the specified log levels. +The following log levels are valid: +1: Critical +2: Error +3: Warning +4: Informational +5: Verbose + + + [datetime] +Selects events created after the specified date and time. + + + [datetime] +Selects events created before the specified date and time. + + + [string] +Selects events generated by the specified user. +This can either be a string representation of a SID or a domain and username in the format DOMAIN\USERNAME or USERNAME@DOMAIN + + + [string[]] +Selects events with any of the specified values in the EventData section. + + + [hashtable] +Excludes events that match the values specified in the hashtable. + + + [string] or [hashtable] +Specifies an array of PowerShell modules that the script requires. +Each element can either be a string with the module name as value or a hashtable with the following keys: +Name: Name of the module +GUID: GUID of the module +One of the following: +ModuleVersion: Specifies a minimum acceptable version of the module. +RequiredVersion: Specifies an exact, required version of the module. +MaximumVersion: Specifies the maximum acceptable version of the module. + + + [string] +Specifies a PowerShell edition that the script requires. +Valid values are "Core" and "Desktop" + + + [switch] +Specifies that PowerShell must be running as administrator on Windows. +This must be the last parameter on the #requires statement line. + + + [version] +Specifies the minimum version of PowerShell that the script requires. + + + Specifies that the script requires PowerShell 7+ to run. + + + Specifies that the script requires Windows PowerShell 5.1 to run. + + + [string] +Required. Specifies the module name. + + + [string] +Optional. Specifies the GUID of the module. + + + [string] +Specifies a minimum acceptable version of the module. + + + [string] +Specifies an exact, required version of the module. + + + [string] +Specifies the maximum acceptable version of the module. + + + A brief description of the function or script. +This keyword can be used only once in each topic. + + + A detailed description of the function or script. +This keyword can be used only once in each topic. + + + .PARAMETER <Parameter-Name> +The description of a parameter. +Add a .PARAMETER keyword for each parameter in the function or script syntax. + + + A sample command that uses the function or script, optionally followed by sample output and a description. +Repeat this keyword for each example. + + + The .NET types of objects that can be piped to the function or script. +You can also include a description of the input objects. + + + The .NET type of the objects that the cmdlet returns. +You can also include a description of the returned objects. + + + Additional information about the function or script. + + + The name of a related topic. +Repeat the .LINK keyword for each related topic. +The .Link keyword content can also include a URI to an online version of the same help topic. + + + The name of the technology or feature that the function or script uses, or to which it is related. + + + The name of the user role for the help topic. + + + The keywords that describe the intended use of the function. + + + .FORWARDHELPTARGETNAME <Command-Name> +Redirects to the help topic for the specified command. + + + .FORWARDHELPCATEGORY <Category> +Specifies the help category of the item in .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Specifies a session that contains the help topic. +Enter a variable that contains a PSSession object. + + + .EXTERNALHELP <XML Help File> +The .ExternalHelp keyword is required when a function or script is documented in XML files. + + + Specifies the path to a .NET assembly to load. + +using assembly <.NET-assembly-path> + + + Specifies a PowerShell module to load classes from. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifies a .NET namespace to resolve types from or a namespace alias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifies an alias for a .NET Type. + +using type <AliasName> = <.NET-type> + + + A normal string. + + + A string that contains unexpanded references to environment variables that are expanded when the value is retrieved. + + + Binary data in any form. + + + A 32-bit binary number. + + + An array of strings. + + + A 64-bit binary number. + + + An unsupported registry data type. + + + ',' - Comma + + + ', ' - Comma-Space + + + ';' - Semi-Colon + + + '; ' - Semi-Colon-Space + + + {0} - Newline + + + '-' - Dash + + + ' ' - Space + diff --git a/src/System.Management.Automation/resources/TransactionStrings.resx b/src/System.Management.Automation/resources/TransactionStrings.resx index 62558fd797f..9dcefc352f9 100644 --- a/src/System.Management.Automation/resources/TransactionStrings.resx +++ b/src/System.Management.Automation/resources/TransactionStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/TypesXmlStrings.resx b/src/System.Management.Automation/resources/TypesXmlStrings.resx index 02c77e45424..25063241cd7 100644 --- a/src/System.Management.Automation/resources/TypesXmlStrings.resx +++ b/src/System.Management.Automation/resources/TypesXmlStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + @@ -126,9 +126,6 @@ Node "{0}" must occur only once under "{1}". The parent node, "{1}", will be ignored. - - Node "{0}" must have a maximum of one occurrence under "{1}". The parent node, "{1}", will be ignored. - The node {0} is not allowed. The following nodes are allowed: {1}. @@ -141,18 +138,6 @@ Node "{0}" was not found. It should occur only once under "{1}". The parent node, "{1}", will be ignored. - - Node "{0}" was not found. It should occur at least once under "{1}". The parent node, "{1}", will be ignored. - - - Expected XML tag "{0}" instead of node of type "{1}". - - - Node of type "{0}" was not expected. - - - Expected XML tag "{0}" instead of "{1}". - The "Type" node must have "Members", "TypeConverters", or "TypeAdapters". @@ -201,9 +186,6 @@ Node "{0}" should not have "{1}" attribute. - - Value should be "true" or "false" instead of "{0}" for "{1}" attribute. - {0}, {1}: The file was not found. @@ -261,12 +243,6 @@ "{0}" should not have null or an empty string in its property "{1}". - - More than one member with the name "{0}" is defined in the type file. - - - {0}: The file was skipped because it already occurred. - The type "{0}" was not found. The type name value must be the full name of the type. Verify the type name and run the command again. diff --git a/src/System.Management.Automation/resources/VerbDescriptionStrings.resx b/src/System.Management.Automation/resources/VerbDescriptionStrings.resx index beb07a0afc1..f772ad2e101 100644 --- a/src/System.Management.Automation/resources/VerbDescriptionStrings.resx +++ b/src/System.Management.Automation/resources/VerbDescriptionStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/WildcardPatternStrings.resx b/src/System.Management.Automation/resources/WildcardPatternStrings.resx index 2074b571ad9..42b8ee69442 100644 --- a/src/System.Management.Automation/resources/WildcardPatternStrings.resx +++ b/src/System.Management.Automation/resources/WildcardPatternStrings.resx @@ -59,8 +59,8 @@ : using a System.ComponentModel.TypeConverter : and then encoded with base64 encoding. --> - - + + diff --git a/src/System.Management.Automation/resources/cs/Authenticode.cs.resx b/src/System.Management.Automation/resources/cs/Authenticode.cs.resx new file mode 100644 index 00000000000..db05bb8aed2 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/Authenticode.cs.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 + + + Soubor {0} nelze načíst, protože jste se rozhodli tento software nyní nespouštět. + + + Soubor {0} nelze načíst, protože jste zvolili možnost nikdy nespouštět software od tohoto vydavatele. + + + Soubor {0} publikoval vydavatel {1}. Tento vydavatel není ve vašem systému výslovně důvěryhodný. Skript se v systému nespustí. Další informace získáte spuštěním příkazu get-help about_signing. + + + Soubor {0} nelze načíst, protože spuštěné skripty jsou v tomto systému zakázány. Další informace najdete viz about_Execution_Policies na https://go.microsoft.com/fwlink/?LinkID=135170. + + + Soubor {0} nelze načíst. {1}. + + + Soubor {0} nelze načíst, protože jeho operace je blokována zásadami omezení softwaru, jako jsou zásady vytvořené pomocí Zásad skupiny. + + + Soubor {0} nelze načíst, protože jeho obsah nelze přečíst. + + + Kód nejde podepsat. Zadaný certifikát není vhodný k podepisování kódu. + + + Kód nejde podepsat. Adresa URL serveru TimeStamp musí být plně kvalifikovaná a ve formátu http://<adresa URL serveru> nebo https://<adresa URL serveru>. + + + Kód nejde podepsat. Hashovací algoritmus se nepodporuje. + + + Chcete spustit software od tohoto nedůvěryhodného vydavatele? + + + Soubor {0} publikoval vydavatel {1} a není v systému důvěryhodný. Spouštějte pouze skripty od důvěryhodných vydavatelů. + + + Software {0} je publikován neznámým vydavatelem. Doporučujeme tento software nespouštět. + + + Upozornění zabezpečení + + + Spouštějte pouze skripty, kterým důvěřujete. Přestože skripty z internetu můžou být užitečné, může vám tento skript potenciálně poškodit počítač. Pokud tomuto skriptu důvěřujete, pomocí rutiny Unblock-File povolte spuštění skriptu bez této zprávy upozornění. Chcete spustit soubor {0}? + + + &Nikdy nespouštět + + + Nyní nespouštějte skript od tohoto vydavatele a nezobrazujte výzvu ke spuštění tohoto skriptu v budoucnu. Budoucí pokusy o spuštění tohoto skriptu způsobí tichou chybu. + + + &Nespouštět + + + Nespouštějte skript od tohoto vydavatele a pokračujte v zobrazování výzvy ke spuštění tohoto skriptu v budoucnu. + + + Spustit &jednou + + + Spusťte skript od tohoto vydavatele a pokračujte v zobrazování výzvy ke spuštění tohoto skriptu v budoucnu. + + + &Vždycky spouštět + + + Spusťte skript od tohoto vydavatele a nezobrazujte výzvu ke spuštění tohoto skriptu v budoucnu. + + + &Pozastavit + + + Pozastavit aktuální kanál a vrátit se na příkazový řádek. Po dokončení operace můžete pokračovat zadáním příkazu exit. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/AuthorizationManagerBase.cs.resx b/src/System.Management.Automation/resources/cs/AuthorizationManagerBase.cs.resx new file mode 100644 index 00000000000..afc9127c2ed --- /dev/null +++ b/src/System.Management.Automation/resources/cs/AuthorizationManagerBase.cs.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 + + + Selhala kontrola AuthorizationManager. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/AutomationExceptions.cs.resx b/src/System.Management.Automation/resources/cs/AutomationExceptions.cs.resx new file mode 100644 index 00000000000..b275efa4c55 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/AutomationExceptions.cs.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Argument nelze zpracovat, protože hodnota argumentu {0} není platná. Změňte hodnotu argumentu {0} a spusťte operaci znovu. + + + Argument nelze zpracovat, protože hodnota parametru {0} není platná. Platné hodnoty jsou Global, Local nebo Script, případně číslo relativní k aktuálnímu oboru (od 0 do počtu oborů, kde 0 představuje aktuální obor a 1 jeho nadřazený obor). Změňte hodnotu parametru {0} a spusťte operaci znovu. + + + Argument nelze zpracovat, protože hodnota argumentu {0} je null. Změňte hodnotu argumentu {0} na jinou než null. + + + Argument nelze zpracovat, protože hodnota argumentu {0} je mimo povolený rozsah. Změňte argument {0} na hodnotu v povoleném rozsahu. + + + Operaci nelze provést, protože operace {0} není platná. Odeberte operaci {0} nebo zjistěte, proč není platná. + + + Operaci nelze provést, protože operace {0} není implementována. + + + Operaci nelze provést, protože operace {0} není podporována. + + + Operaci nelze provést, protože objekt {0} už byl uvolněn. + + + Blok skriptu nelze vyvolat, protože obsahuje více než jednu klauzuli. Metodu Invoke() lze použít pouze u bloků skriptů, které obsahují jedinou klauzuli. + + + Blok skriptu nelze převést, protože obsahuje více než jednu klauzuli. Výrazy ani řídicí struktury nejsou povoleny. Ověřte, že blok skriptu obsahuje právě jeden kanál nebo příkaz. + + + Prázdný blok skriptu nelze převést. Ověřte, že blok skriptu obsahuje právě jeden kanál nebo příkaz. + + + Převést lze pouze blok skriptu, který obsahuje právě jeden kanál nebo příkaz. Výrazy ani řídicí struktury nejsou povoleny. Ověřte, že blok skriptu obsahuje právě jeden kanál nebo příkaz. + + + Blok skriptu obsahující příkaz trap nejvyšší úrovně nelze převést. + + + Pro blok ScriptBlock odkazující na proměnné, které nejsou deklarované v bloku param(...), nelze vytvořit objekt PowerShell. Název nedeklarované proměnné: {0} + + + Pro blok ScriptBlock, který vyhodnocuje nekonstantní výrazy, nelze vytvořit objekt PowerShell. Nekonstantní výraz: {0} + + + Pro blok ScriptBlock, který vyhodnocuje dynamické výrazy, nelze vytvořit objekt PowerShell. Dynamický výraz: {0} + + + Pro blok ScriptBlock, který se pokouší předat další bloky skriptů jako hodnoty argumentů, nelze vytvořit objekt PowerShell. + + + Pro blok ScriptBlock, který vyvolává kanály, příkazy nebo funkce za účelem vyhodnocení argumentů hlavního kanálu, nelze vytvořit objekt PowerShell. + + + Pro blok ScriptBlock, který používá dot-sourcing, nelze vytvořit objekt PowerShell. + + + Pro blok ScriptBlock, který vyvolává jiné bloky skriptů, nelze vytvořit objekt PowerShell. + + + Blok skriptu nelze převést na objekt PowerShell, protože obsahuje nepovolené operátory přesměrování. + + + Pro blok ScriptBlock, který nemá přidružený kontext operace, nelze vytvořit objekt PowerShell. + + + Příkaz byl zastaven uživatelem. + + + Objekt {0} není správného typu pro vrácení z bloku dynamicparam. Blok dynamicparam musí vrátit buď hodnotu $null, nebo objekt typu [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + Blok skriptu nelze převést na otevřený obecný typ. Definujte odpovídající uzavřený obecný typ a zkuste to znovu. + + + Pro blok ScriptBlock, který spouští kanál výrazem, nelze vytvořit objekt PowerShell. + + + Hodnotu proměnné using $using:{0} nelze načíst, protože v místní relaci nebyla nastavena. + + + Hodnotu výrazu Using {0} nelze získat ze zadaného slovníku proměnných. Při vytváření instance PowerShellu z bloku skriptu nesmí výraz Using obsahovat operaci indexování ani operaci přístupu ke členu. + + + Zkompilovaný blok skriptu načtený do aktuálního oboru platnosti (dot source) + + + Vyvolání bloku skriptu {0} do aktuálního oboru bude v režimu Constrained Language zakázáno. Režim jazyka skriptu: {1}, režim jazyka kontextu: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CatalogStrings.cs.resx b/src/System.Management.Automation/resources/cs/CatalogStrings.cs.resx new file mode 100644 index 00000000000..a7dfb6cfd04 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CatalogStrings.cs.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Soubor s definicí katalogu nejde vygenerovat. + + + Soubor {0} se přidává do katalogu. Relativní cesta souboru v katalogu je {1}. + + + Ověření souboru {0} z katalogu se přeskakuje. + + + V katalogu se našel soubor {0} s hodnotou hash {1}. + + + Cesty katalogu obsahují několik souborů se stejnou relativní cestou {0}. + + + Na disku se našel soubor {0} s hodnotou hash {1}. + + + Ověření souboru {0} z cesty se přeskakuje. + + + Nepovedlo se získat popisovač kontextu správce katalogu pro zadaný hashovací algoritmus {0}. + + + Pro soubor {0} nejde vytvořit hodnotu hash. + + + Soubor katalogu {0} nejde otevřít. + + + Verze katalogu není platná. Podporujeme jen katalog verze {0} a verze {1}. + + + Soubor s definicí katalogu nejde otevřít. + + + V katalogu se našlo několik položek člena souboru {0}. + + + Název souboru ani cesta pro člena katalogu {0} se nenašly. + + + Soubor {0} pro výpočet hodnoty hash se nenašel. + + + Soubor {0} nejde přečíst pro výpočet hodnoty hash. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CimInstanceTypeAdapterResources.cs.resx b/src/System.Management.Automation/resources/cs/CimInstanceTypeAdapterResources.cs.resx new file mode 100644 index 00000000000..61a9e49e0e3 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CimInstanceTypeAdapterResources.cs.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nelze převést „{0}“ na objekt typu „{1}“. + + + „{0}“ je vlastnost určená jen pro čtení. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CmdletizationCoreResources.cs.resx b/src/System.Management.Automation/resources/cs/CmdletizationCoreResources.cs.resx new file mode 100644 index 00000000000..629567f1361 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CmdletizationCoreResources.cs.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Rutiny nad třídou {0} + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + XML definice rutiny pro následující soubor nejde zpracovat: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Atribut ObjectModelWrapper nejde zpracovat. Typ {0} definuje několik sad parametrů. Ověřte, že XML definice rutiny určuje v atributu ObjectModelWrapper platný typ, a zkuste to znovu. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Atribut ObjectModelWrapper nejde zpracovat. Typ {0} je otevřený obecný typ. Ověřte, že XML definice rutiny určuje v atributu ObjectModelWrapper platný typ, a zkuste to znovu. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Atribut ObjectModelWrapper nejde zpracovat. Typ {0} není odvozený z následující třídy: {1}. Ověřte, že XML definice rutiny určuje v atributu ObjectModelWrapper platný typ, a zkuste to znovu. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Atribut ObjectModelWrapper nejde zpracovat. Typ {0} definuje parametr rutiny {1} s atributem parametru {2}, který se ignoruje. Ověřte, že XML definice rutiny určuje v atributu ObjectModelWrapper platný typ, a zkuste to znovu. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Parametr {0} pro rutinu {1} nejde definovat. Název parametru už je definovaný třídou {2}. Změňte název parametru v XML definice rutiny a zkuste to znovu. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Parametr {0} pro rutinu {1} nejde definovat. Název parametru už je definovaný v elementu XML {2}. Změňte název parametru v XML definice rutiny a zkuste to znovu. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + Hodnota atributu EnumName neodpovídá platnému identifikátoru jazyka C#: {0}. Ověřte atribut EnumName v XML definice rutiny a zkuste to znovu. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Element <Enum EnumName="{0}" ...> nejde zpracovat. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + Vzdálený počítač vrátil neplatný soubor CDXML. Následující adaptér rutiny není podporovaný pro import modulu CDXML ze vzdáleného počítače: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CommandBaseStrings.cs.resx b/src/System.Management.Automation/resources/cs/CommandBaseStrings.cs.resx new file mode 100644 index 00000000000..078d56b5f97 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CommandBaseStrings.cs.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Pokračovat v této operaci? + + + &Ano + + + Pokračovat jen dalším krokem operace. + + + An&o pro všechny + + + Pokračovat všemi kroky operace. + + + &Ne + + + Přeskočit tuto operaci a pokračovat další operací. + + + Ne pro vš&echny + + + Přeskočit tuto operaci a všechny následující operace. + + + Zastavit tento příkaz. + + + &Zastavit příkaz + + + &Pozastavit + + + Pozastavit aktuální kanál a vrátit se na příkazový řádek. Kanál obnovíte zadáním {0}. + + + + Program {0} skončil s nenulovým ukončovacím kódem: {1} ({2}). + + + Provádí se operace {0} u cíle {1}. + + + Co kdyby: {0} + + + Opravdu chcete provést tuto akci? +{0} + + + Potvrdit + + + Spuštěný příkaz se zastavil, protože proměnná předvoleb {0} nebo společný parametr mají nastavenou hodnotu Stop: {1} + + + Spuštěný příkaz se zastavil, protože proměnná předvoleb {0} nebo společný parametr mají nastavenou hodnotu Stop. + + + Spuštěný příkaz se zastavil, protože proměnná předvoleb {0} nebo společný parametr mají nastavenou následující neplatnou hodnotu: {1}. + + + Spuštěný příkaz se zastavil, protože uživatel vybral možnost Zastavit. + + + Spuštěný příkaz se zastavil, protože ho uživatel přerušil. + + + Rutiny odvozené z PSCmdlet nejde vyvolat přímo. + + + Rutina {0} nepodporuje ve vzdálené relaci parametr {1}. + + + Celkový počet: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Odhadovaný celkový počet: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Neznámý celkový počet + Reviewed by TArcher on 2010-07-20 + + + příkaz {0} + + + Objekt {0} je zastaralý. {1} + + + Volání Exec selhalo s číslem chyby {0} pro příkazový řádek: {1} + + + Příkaz {0} se nenašel. Zadaný příkaz musí být spustitelný soubor. + + + Kontrola zpracování bloku skriptu pomocí tečkové notace + + + Zpracování bloku skriptu {0} pomocí tečkové notace v režimu omezeného jazyka selže, protože jeho jazykový režim {1} neodpovídá aktuálnímu jazykovému režimu {2}. + + + Vyhledávač příkazů + + + Příkaz {0} v modulu {1} není důvěryhodný a v režimu ConstrainedLanguage nebude přístupný. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ConsoleInfoErrorStrings.cs.resx b/src/System.Management.Automation/resources/cs/ConsoleInfoErrorStrings.cs.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ConsoleInfoErrorStrings.cs.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CoreClrStubResources.cs.resx b/src/System.Management.Automation/resources/cs/CoreClrStubResources.cs.resx new file mode 100644 index 00000000000..22a5f3ea2d7 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CoreClrStubResources.cs.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Název proměnné prostředí nemůže obsahovat znak rovná se. + + + Název nebo hodnota proměnné prostředí je příliš dlouhá. + + + První znak v řetězci je nulový znak. + + + Řetězec nemůže mít nulovou délku. + + + Název počítače se nepovedlo získat. + + + Název domény aktuálního uživatele se nepovedlo získat. + + + Neznámá chyba {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CredUI.cs.resx b/src/System.Management.Automation/resources/cs/CredUI.cs.resx new file mode 100644 index 00000000000..a8d617a42f3 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CredUI.cs.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Žádost o přihlašovací údaje k PowerShellu + + + Zadejte vaše přihlašovací údaje. + + + Zadejte vaše přihlašovací údaje. + + + Maximální délka titulku je {0} znaků. + + + Maximální délka zprávy je {0} znaků. + + + Maximální délka hodnoty UserName je {0} znaků. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/Credential.cs.resx b/src/System.Management.Automation/resources/cs/Credential.cs.resx new file mode 100644 index 00000000000..75ad22a7587 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/Credential.cs.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 + + + Přihlašovací údaje nejdou serializovat. Pokud tento příkaz spouští pracovní postup, přihlašovací údaje nejde zachovat, protože proces, ve kterém se pracovní postup spouští, nemá oprávnění k serializaci přihlašovacích údajů. + +-- Pokud byl pracovní postup spuštěný v relaci PSSession k místnímu počítači, přidejte k příkazu, který relaci vytvořil, parametr EnableNetworkAccess. +-- Pokud byl pracovní postup spuštěný v relaci PSSession ke vzdálenému počítači, přidejte k příkazu, který relaci vytvořil, parametr Authentication s hodnotou CredSSP. Nebo se připojte ke konfiguraci relace, která má nastavenou vlastnost RunAsUser. + + + Hodnota UserName nemá správný formát. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/CredentialAttributeStrings.cs.resx b/src/System.Management.Automation/resources/cs/CredentialAttributeStrings.cs.resx new file mode 100644 index 00000000000..8ba661108e8 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/CredentialAttributeStrings.cs.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 + + + Žádost o přihlašovací údaje k PowerShellu + + + Zadejte vaše přihlašovací údaje. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/DebuggerStrings.cs.resx b/src/System.Management.Automation/resources/cs/DebuggerStrings.cs.resx new file mode 100644 index 00000000000..3b0aa10668e --- /dev/null +++ b/src/System.Management.Automation/resources/cs/DebuggerStrings.cs.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Zarážka proměnné na ${0} (přístup {1}) + + + Zarážka proměnné na {0}:${1} (přístup {2}) + + + Zarážka řádku na {0}:{1} + + + Zarážka řádku na {0}:{1}, {2} + + + Zarážka příkazu na {0} + + + Zarážka příkazu na {0}:{1} + + + Zarážka {0} nebude dosažena + + + {0}, {1,-16} Jeden krok (vstup do funkcí, skriptů atd.) + + + {0}, {1,-16} Přejít na další příkaz (krok nad přes funkce, skripty atd.). + + + {0}, {1,-16} Vystoupit z aktuální funkce, skriptu atd. + + + {0}, {1,-16} Pokračovat v operaci + + + {0}, {1,-16} Zastavit operaci a ukončit ladicí program + + + {0}, Get-PSCallStack Zobrazit zásobník volání + + + {0}, {1,-16} Vypsat zdrojový kód aktuálního skriptu. + + + Pomocí příkazu list začněte na aktuálním řádku, list <m>. + + + spustit od řádku <m> a pomocí příkazu list <m> <n> zobrazit <n> řádků + + + řádky od řádku <m> + + + <enter> Zopakovat poslední příkaz, pokud to byl {0}, {1} nebo {2}. + + + {0}, {1,-16} zobrazí tuto zprávu nápovědy. + + + Pokyny k přizpůsobení výzvy ladicího programu zobrazíte zadáním příkazu help about_prompt. + + + +Aktuální relace nepodporuje ladění. Operace bude pokračovat. + + + + + {0}: řádek {1} + + + Není k dispozici žádný zdrojový kód. + + + Počáteční číslo řádku musí být kladné celé číslo, které není větší než {0}. + + + Počet řádků musí být kladné celé číslo. + + + <Žádný soubor> + + + v {0}, {1}: řádek {2} + + + Ladicí program nemůže zpracovat příkazy, pokud není ve stavu Zastaveno. + + + Rutina SetDebugAction není implementována pro místní ladicí program skriptů. + + + Ladicí program nemůže nastavit akci pokračování, protože ladicí program ve vzdálené relaci není ve stavu Zastaveno. + + + Úlohu nelze ladit, protože je ladicí program momentálně zaneprázdněn. + + + Zadaná úloha a všechny podřízené úlohy byly prozkoumány, ale nebyly nalezeny žádné úlohy, které by bylo možné ladit. Aby bylo možné ladit úlohu nebo podřízenou úlohu, musí úloha podporovat ladění a musí být také ve spuštěném stavu. + + + Ladicí program nelze pro krokový režim povolit, protože je vypnutý a režim ladění je nastavený na None. + + + Prostředí runspace nelze ladit, protože ladicí program hostitele je momentálně zaneprázdněný. + + + Nelze ladit prostředí runspace. Ladicí program prostředí runspace je v tuto chvíli vypnutý (DebugMode je None). + + + Prostředí runspace, které není ve stavu Otevřeno, nelze ladit. Stav tohoto prostředí runspace je {0}. + + + Nelze ladit prostředí runspace. Prostředí Runspace {0} nemá žádný přidružený ladicí program. + + + Ladicí program je již přepsán. + + + Objekt ladicího programu nelze vložit do sebe sama. + + + Příkaz {0} není podporován pro vzdálené použití ve verzi PowerShellu spuštěné ve vzdáleném prostředí runspace. + + + Proces + + + {0}, {1,-16} Pokračujte v operaci a odpojte ladicí program. + + + Příkaz detach ladicího programu se nedá použít. Příkaz detach lze použít pouze při ladění úloh a prostředí runspace pomocí rutin Debug-Job nebo Debug-Runspace. + + + Neplatné ID prostředí runspace: {0} + + + Nelze získat prostředí runspace. + + + Musí být zadána zarážka nebo BreakpointList. + + + Seznam BreakpointList obsahoval položku, která nebyla zarážkou. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/DescriptionsStrings.cs.resx b/src/System.Management.Automation/resources/cs/DescriptionsStrings.cs.resx new file mode 100644 index 00000000000..c3d57e43c75 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/DescriptionsStrings.cs.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 + + + Vlastnost {0} nemůže být null nebo prázdná. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/DiscoveryExceptions.cs.resx b/src/System.Management.Automation/resources/cs/DiscoveryExceptions.cs.resx new file mode 100644 index 00000000000..df393fbf643 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/DiscoveryExceptions.cs.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 + + + Název rutiny {0} nejde ověřit, protože nemá správný formát. Názvy rutin musí obsahovat sloveso a podstatné jméno oddělené spojovníkem -, například Get-Process. + + + Parametr {0} je v sadě parametrů {1} deklarovaný vícekrát. + + + Alias {0} je deklarovaný vícekrát. + + + Parametr se nepovedlo deklarovat. Parametry jde deklarovat jen u polí a vlastností. + + + Rutinu nejde zpracovat. Název rutiny musí tvořit dvojice slovesa a podstatného jména oddělená spojovníkem -. + + + Výraz {0} nebyl rozpoznán jako název rutiny, funkce, souboru skriptu ani spustitelného programu. +Zkontrolujte pravopis názvu. Pokud jste zadali cestu, ověřte, že je správná, a zkuste to znovu. + + + Argument {0} nebyl rozpoznán jako rutina: {1} + + + Argument {0} nebyl rozpoznán jako rutina, pravděpodobně proto, že není odvozený od tříd Cmdlet ani PSCmdlet: {1} + + + Alias {0} nejde přeložit, protože odkazuje na výraz {1}, který nebyl rozpoznán jako rutina, funkce, spustitelný program ani soubor skriptu. Ověřte výraz a zkuste to znovu. + + + Parametr {0} s hodnotou {1} nejde zpracovat, protože nejde o rutinu a objekt CommandProcessor ho nedokáže zpracovat. + + + Rutina s názvem {0} už existuje. Názvy rutin musí být jedinečné. + + + Poskytovatel rutin s názvem {0} už existuje. Názvy poskytovatelů rutin musí být jedinečné. + + + Sestavení s názvem {0} už existuje. Názvy sestavení musí být jedinečné. + + + Skript s názvem {0} už existuje. Názvy skriptů musí být jedinečné. + + + Příkaz #requires nejde zpracovat, protože nemá správný formát. +Příkaz #requires musí mít jeden z následujících formátů: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + Skript {0} nejde spustit, protože obsahuje příkaz #requires s ID prostředí {1}, které není kompatibilní s aktuálním prostředím. Tento skript musíte spustit v prostředí umístěném v {2}. + + + Skript {0} nejde spustit, protože obsahuje příkaz #requires s ID prostředí {1}, které není kompatibilní s aktuálním prostředím. + + + Skript {0} nejde spustit, protože obsahuje příkaz #requires pro PowerShell {1}. Verze PowerShellu požadovaná skriptem neodpovídá aktuálně spuštěné verzi PowerShellu {2}. + + + Skript {0} nejde spustit, protože obsahuje příkaz #requires pro edice PowerShellu {1}. Edice PowerShellu požadovaná skriptem neodpovídá aktuálně spuštěné edici PowerShellu {2}. + + + Skript {0} nejde spustit, protože chybějí následující moduly snap-in zadané v příkazech #requires skriptu: {1}. + + + Příkaz #requires určuje pouze shellID. Při spuštění v PowerShellu musí příkazy #Requires určovat požadovaný modul snap-in PowerShellu. + + + Skript {0} nejde spustit, protože obsahuje příkaz #requires, který vyžaduje spuštění s oprávněními správce. Aktuální relace PowerShellu není spuštěná s oprávněními správce. Spusťte PowerShell pomocí možnosti Spustit jako správce a potom zkuste skript spustit znovu. + + + {0} (verze {1}) + + + Příkaz se nepovedlo načíst, protože parametr ArgumentList jde zadat jen při načítání jedné rutiny nebo skriptu. + + + Název parametru {0} je vyhrazený pro budoucí použití. + + + Skript {0} nejde spustit, protože chybějí následující moduly zadané v příkazech #requires skriptu: {1}. + + + Příkaz {0} byl nalezen v modulu {1}, ale modul se nepovedlo načíst. Další informace získáte spuštěním příkazu Import-Module {1}. + + + Příkaz {0} byl nalezen v modulu {1}, ale modul se nepovedlo načíst kvůli následující chybě: [{2}] +Další informace získáte spuštěním příkazu Import-Module {1}. + + + Modul {0} se nepovedlo načíst. Další informace získáte spuštěním příkazu Import-Module {0}. + + + Žádné odpovídající příkazy neobsahují parametr s názvem {0}. Zkontrolujte pravopis názvu parametru a zkuste to znovu. + + + Tento příkaz nejde načíst pomocí operátoru tečky, protože byl definovaný v jiném jazykovém režimu. Pokud chcete tento příkaz spustit bez importu jeho obsahu, vynechte operátor „.“. + + + Parametry ShowCommandInfo a Syntax nejde zadat současně. + + + Tento příkaz skriptu je zakázaný, když je zapnutá experimentální funkce {0}. + + + Tento příkaz skriptu je zakázaný, když je experimentální funkce {0} vypnutá. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/EnumExpressionEvaluatorStrings.cs.resx b/src/System.Management.Automation/resources/cs/EnumExpressionEvaluatorStrings.cs.resx new file mode 100644 index 00000000000..9eef353eb91 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/EnumExpressionEvaluatorStrings.cs.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Vstupní výraz nesmí být prázdný. V každém vstupním výrazu zadejte alespoň jeden název identifikátoru. + + + Nepodařilo se přiřadit prázdný název identifikátoru k platnému názvu enumerátoru. Zadejte některý z následujících názvů enumerátorů a zkuste to znovu: {0}. + + + Obecný typ zadaný pro výraz musí představovat výčet. Zadejte platný typ výčtu. + + + Název identifikátoru {0} nelze zpracovat, protože je příliš podobný nebo shodný s následujícími názvy enumerátorů: {1}. Použijte konkrétnější název identifikátoru. + + + Nepodařilo se přiřadit název identifikátoru {0} k platnému názvu enumerátoru. Zadejte některý z následujících názvů enumerátorů a zkuste to znovu: +{1} + + + Použití závorek není ve výrazu platné, protože seskupení identifikátorů není povoleno. Zkuste odebrat závorky, nebo pokud je dílčí výraz uzavřený, zkuste výraz rozšířit. + + + Výraz nelze analyzovat z důvodu neočekávaného tokenu. Za názvem identifikátoru se očekává pouze operátor OR (,) nebo operátor AND (+). + + + Nepodařilo se analyzovat výraz kvůli neočekávanému tokenu za operátorem NOT (!). Za operátorem NOT (!) se očekává název identifikátoru. + + + Výraz nelze analyzovat z důvodu neočekávaného tokenu. Na začátku výrazu nebo za operátorem OR (,) či operátorem AND (+) je očekáván název identifikátoru nebo operátor NOT (!). Výraz také nesmí končit operátorem OR (,), AND (+) nebo NOT (!). + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ErrorCategoryStrings.cs.resx b/src/System.Management.Automation/resources/cs/ErrorCategoryStrings.cs.resx new file mode 100644 index 00000000000..1643923e6d5 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ErrorCategoryStrings.cs.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Bylo zjištěno zablokování: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Nerozpoznaná kategorie chyby {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ErrorPackage.cs.resx b/src/System.Management.Automation/resources/cs/ErrorPackage.cs.resx new file mode 100644 index 00000000000..3666d98df4f --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ErrorPackage.cs.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 + + + {0}…{1} + + + Text chyby je prázdný pro chybu {0}: {1} + + + Objekt {0} je hlášen jako chyba. + + + Hodnota {0} není pro proměnnou ActionPreference podporována. Zadanou hodnotu lze použít pouze jako hodnotu parametru předvolby a byla nahrazena výchozí hodnotou. Další informace najdete v tématu nápovědy „about_Preference_Variables“. + + + Hodnota ActionPreference {0} je vyhrazena pro budoucí použití a v současné době není podporována. Další informace o proměnných předvoleb najdete v tématu nápovědy „about_Preference_Variables“. + + + Hodnota ActionPreference {0} je vyhrazena pro budoucí použití a v současné době není podporována. Hodnota byla v proměnné {1} nahrazena výchozí hodnotou {2}. Další informace o proměnných předvoleb najdete v tématu nápovědy „about_Preference_Variables“. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/EtwLoggingStrings.cs.resx b/src/System.Management.Automation/resources/cs/EtwLoggingStrings.cs.resx new file mode 100644 index 00000000000..a7a1f609ae0 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/EtwLoggingStrings.cs.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Příkaz {0} je {1}. + + + Stav prostředí se změnil z {0} na {1}. + + + Plně kvalifikované ID chyby = {0} + + + Chybová zpráva = {0} + + + Doporučená akce = {0} + + + Zásady spouštění + + + Příkaz úlohy = {0} + + + ID úlohy = {0} + + + ID instance úlohy = {0} + + + Umístění úlohy = {0} + + + Název úlohy = {0} + + + Stav úlohy = {0} + + + Název příkazu = + + + Cesta příkazu = + + + Typ příkazu = + + + Verze prostředí = + + + ID hostitele = + + + Název hostitele = + + + Hostitelská aplikace = + + + Verze hostitele = + + + ID kanálu = + + + ID runspace = + + + Název skriptu = + + + Pořadové číslo = + + + Závažnost = + + + ID prostředí Shell = + + + Čas = + + + Uživatel = + + + Připojený uživatel = + + + Úloha NULL + + + Název poskytovatele + + + Poskytovatel {0} změnil stav na {1}. + + + Spouštění skriptů je {0}. + + + Proměnná {0} se změnila z {1} na {2}. + + + Proměnná {0} se změnila na {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/EventResource.cs.resx b/src/System.Management.Automation/resources/cs/EventResource.cs.resx new file mode 100644 index 00000000000..b9589e7e4b0 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/EventResource.cs.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Pro ID události PowerShell.Core.Instrumentation.man nebyla nalezena žádná zpráva. + + + Naplánovaná úloha {0} spuštěna v {1} + + + + Naplánovaná úloha {0} byla dokončena v {1} se stavem {2} + + + + Výjimka naplánované úlohy {0}: + Zpráva: {1} + StackTrace: {2} + InnerException: {3} + + + + Inicializace experimentálních funkcí: Ignoruje experimentální funkci {0} z konfiguračního souboru.{1} + + + Inicializace experimentální funkce: Konfigurační soubor se nepodařilo načíst. + Výjimka: {0} + Zpráva: {1} + StackTrace: {2} + + + + Načetl se modul plug-in pracovního postupu. + EndpointName: {0} + Uživatel: {1} + HostingMode: {2} + Protokol: {3} + Konfigurace: + {4} + + + Spuštění pracovního postupu bylo zahájeno. + WorkflowId: {0} + ManagedNodes: {1} + + + Stav pracovního postupu se změnil. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + Pro modul plug-in pracovního postupu byl vyžádán proces vypnutí. + EndpointName: {0} + + + Modul plug-in pracovního postupu se restartoval. + EndpointName: {0} + + + Pracovní postup se obnovuje. + WorkflowId: {0} + + + Byl překročen limit kvóty nastavený pro koncový bod. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + Pracovní postup byl obnoven. + WorkflowId: {0} + + + Byl vytvořen fond prostředí runspace pro pracovní postup. + WorkflowId: {0} + ManagedNode: {1} + + + Aktivita byla zařazena do fronty pro spuštění. + WorkflowId: {0} + ActivityName: {1} + + + Spuštění aktivity bylo zahájeno. + ActivityName: {0} + ActivityTypeName: {1} + + + Pracovní postup se importuje ze souboru XAML. + WorkflowId: {0} + XamlFile: {1} + + + Pracovní postup byl importován ze souboru XAML. + WorkflowId: {0} + XamlFile: {1} + + + Pracovní postup se nepodařilo importovat ze souboru XAML kvůli chybě. + WorkflowId: {0} + ErrorDescription: {1} + + + Bylo zahájeno ověřování pracovního postupu. + WorkflowId: {0} + + + Ověření pracovního postupu proběhlo úspěšně. + WorkflowId: {0} + + + Ověření pracovního postupu se nezdařilo s chybou. + WorkflowId: {0} + + + Aktivita pracovního postupu se ověřila. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Aktivitu pracovního postupu nelze ověřit. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Spuštění aktivity se nezdařilo. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Změnila se dostupnost prostředí runspace. + RunspaceId: {0} + Dostupnost: {1} + + + Stav prostředí runspace se změnil. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Pracovní postup se načetl pro spuštění. + WorkflowId: {0} + + + Pracovní postup byl uvolněn. + WorkflowId: {0} + + + Provádění pracovního postupu bylo zrušeno. + WorkflowId: {0} + + + Provádění pracovního postupu bylo přerušeno. + WorkflowId: {0} + + + Operace vyčištění pracovního postupu byla provedena. + WorkflowId: {0} + + + Trvalý pracovní postup byl načten z disku. + WorkflowId: {0} + Cesta: {1} + + + Data pracovního postupu byla odstraněna z disku. + WorkflowId: {0} + Cesta: {1} + + + Spouští se úloha odebrání. + JobId: {0} + + + Stav úlohy se změnil. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Chyba úlohy + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Úloha vytvořená pro pracovní postup (podřízená úloha) + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Pro pracovní postup byla vytvořena nadřazená úloha. + JobId: {0} + + + Všechny požadované úlohy byly vytvořeny pro spuštění pracovního postupu. + JobId: {0} + WorkflowId: {1} + + + Pro pracovní postup byla odebrána podřízená úloha. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + Při odebírání úlohy došlo k chybě. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Chyba: {3}. + + + Načítá se pracovní postup pro spuštění. + WorkflowId: {0} + + + Provádění pracovního postupu bylo dokončeno. + WorkflowId: {0} + + + Ruší se provádění pracovního postupu. + WorkflowId: {0} + + + Přerušuje se provádění pracovního postupu. + WorkflowId: {0} + Důvod: {1} + + + Pracovní postup se uvolňuje. + WorkflowId: {0} + + + Vynucené vypnutí pracovního postupu bylo zahájeno. + WorkflowId: {0} + + + Vynucené vypnutí pracovního postupu bylo dokončeno. + WorkflowId: {0} + + + Při nuceném ukončování pracovního postupu došlo k chybě. + WorkflowId: {0} + ErrorDescription: {1} + + + Pracovní postup se ukládá na disk. + WorkflowId: {0} + PersistPath: {1} + + + Pracovní postup byl trvale uložen na disk. + WorkflowId: {0} + + + Provádění aktivity bylo dokončeno. + ActivityName: {0} + + + Chyba spuštění pracovního postupu + WorkflowId: {0} + ErrorDescription: {1} + + + Byl zaregistrován nový koncový bod PowerShellu. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Konfigurace koncového bodu se změnila. + EndpointName: {0} + ModifiedBy: {1} + + + Registrace konfigurace koncového bodu byla zrušena. + EndpointName: {0} + UnregisteredBy: {1} + + + Konfigurace koncového bodu je zakázaná. + EndpointName: {0} + DisabledBy: {1} + + + Konfigurace koncového bodu je povolená. + EndpointName: {0} + EnabledBy: {1} + + + Bylo spuštěno prostředí runspace mimo proces. + Příkaz: {0} + + + Během provádění pracovního postupu bylo provedeno rozbalení parametrů (splatting). + Parametry: {0} + Počítače: {1} + + + Modul pracovního postupu byl spuštěn. + EndpointName: {0} + + + Vytvoření instance služby Workflow Manager pomocí + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + Cesta: {3} + + + Název počítače $null nebo . se přeloží na LocalHost. + + + Překládá se na výchozí schéma http. + + + Název vzdáleného prostředí byl přeložen na výchozí PowerShellCore. + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + Vytváření textu Scriptblock ({0} z {1}): +{2} + +ScriptBlock ID: {3} +Cesta: {4} + + + Spuštění volání ScriptBlock s ID: {0} +ID prostředí runspace: {1} + + + Dokončilo se volání ScriptBlock s ID: {0} +ID prostředí runspace: {1} + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + {2} + +Kontext: +{0} + +Uživatelská data: +{1} + + + + Korelace ID aktivity + CurrentActivityId: {0} + ParentActivityId: {1} + + + Název třídy = {0} +Název metody = {1} +GUID pracovního postupu = {2} +Zpráva = {3} +{4} +Název aktivity = {5} +GUID aktivity = {6} +Parametry = {7} + + + Vytváření objektu prostředí runspace + ID instance: {0} + + + Vytváření objektu RunspacePool + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Otevírá se RunspacePool. + + + Úprava ID aktivity a korelace + + + Stav prostředí runspace se změnil na {0} + + + Probíhá pokus o opětovné vytvoření relace č. {0} pro kód chyby {1} v relaci s ID {2}. + + + Prostředí PowerShell spustilo vlákno naslouchání IPC v procesu: {0} v doméně aplikace: {1}. + + + Prostředí PowerShell ukončilo vlákno naslouchání IPC u procesu: {0} v doméně aplikace: {1}. + + + V procesu {0} v doméně AppDomain {1} došlo ve vlákně naslouchání PowerShell IPC k chybě. Chybová zpráva: {2}. + + + Připojení IPC PowerShellu u procesu: {0} v doméně aplikace: {1} pro uživatele: {2}. + + + Odpojení IPC PowerShellu u procesu: {0} v doméně aplikace: {1} pro uživatele: {2}. + + + Port se přeložil na {0} + + + AppName se přeložil na {0} + + + ComputerName se přeložil na {0} + + + Schéma je {0} + + + Testovací analytická zpráva + + + Parametry připojení jsou + Identifikátor URI připojení: {0} + Identifikátor URI prostředku: {1} + Uživatel: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Kryptografický otisk: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Úprava ID aktivity a korelace + + + Přijat objekt s ID prostředí runspace: {0}, ID příkazu: {1}, cílem: {2}, DataType: {3}, TargetInterface: {4} + + + V doméně aplikace došlo k neošetřené výjimce. +Typ výjimky: {0} +Zpráva o výjimce: {1} +Trasování zásobníku výjimky: {2} + + + ID prostředí runspace: {0} ID kanálu: {1}. Komponenta WSMan oznámila chybu s kódem: {2}. + Chybová zpráva: {3} + Trasování zásobníku: {4} + + + V doméně aplikace došlo k neošetřené výjimce. +Typ výjimky: {0} +Zpráva o výjimce: {1} +Trasování zásobníku výjimky: {2} + + + ID prostředí runspace: {0} ID kanálu: {1}. Komponenta WSMan oznámila chybu s kódem: {2}. + Chybová zpráva: {3} + Trasování zásobníku: {4} + + + ID prostředí runspace: {0} Navazuje se připojení pomocí WSMAN Create Shell. + + + ID prostředí runspace: {0} Pro WSMAN Create Shell bylo přijato zpětné volání. + + + ID prostředí runspace: {0} Uzavírá prostředí pomocí WSMANCloseShell. + + + ID prostředí runspace: {0} Bylo přijato zpětné volání pro WSManCloseShell. + + + ID prostředí runspace: {0} ID kanálu: {1}. Odesílání dat o velikosti {2} + + + ID prostředí runspace: {0} ID kanálu: {1}. Pro WSMANSendShellInputEx bylo přijato zpětné volání. + + + ID prostředí runspace: {0} ID kanálu: {1}. Probíhá vytvoření požadavku Receive pomocí WSManReceiveS.hellOutputEx + + + ID prostředí runspace: {0} ID kanálu: {1}. Přijata data o velikosti {2} + + + ID prostředí runspace: {0}, ID kanálu: {1}. Navazování připojení příkazu pomocí WSMANRunShellCommandEx + + + ID prostředí runspace: {0}, ID kanálu: {1}. Pro připojení příkazu bylo přijato zpětné volání. + + + ID prostředí runspace: {0}, ID kanálu: {1}. Ukončuje se transport pro příkaz + + + ID prostředí runspace: {0}, ID kanálu: {1}. Pro uzavření příkazu bylo přijato zpětné volání. + + + ID prostředí runspace: {0}, ID kanálu: {1}. Odesílá se signál s kódem {2} pomocí WSMANSignalShellEx. + + + ID prostředí runspace: {0}, ID kanálu: {1}. Pro WSMANSignalShellEx bylo přijato zpětné volání. + + + ID prostředí runspace: {0} Připojení se přesměrovává na identifikátor URI: {1} + + + ID prostředí runspace: {0} ID kanálu: {1}. Server odesílá klientovi data o velikosti {2}. Datový typ: {3} TargetInterface: {4} + + + Požadavek {0} Vytváří se vzdálená relace serveru. Uživatelské jméno: {1} Vlastní ID prostředí: {2} + + + Hlásí kontext pro požadavek: {0}. Nahlášený kontext: {0}. + + + Hlášení o dokončení operace pro požadavek: {0} + Kód chyby: {1} + Chybová zpráva: {2} + Trasování zásobníku: {3} + + + Kontext prostředí {0} ID požadavku {1} Vytváří příkazovou relaci pro spuštění příkazu. + + + Kontext prostředí {0} Kontext příkazu {1} ID požadavku {2}. Zastavuje se příkaz. + + + Kontext prostředí {0} Kontext příkazu {1} ID požadavku {2}. Byla přijata data z klienta. + + + Kontext prostředí {0} Kontext příkazu {1} ID požadavku {2}. Klient odeslal požadavek na příjem, aby server mohl odeslat data. + + + Shell Context {0} Command Context {1} IsReceiveOperation {2}. Přišel požadavek na zavření operace. + + + Načítání sestavení {0} pro vlastní prostředí s ID prostředí {1} + + + Načítá typ {0} pro vlastní prostředí s ID prostředí {1}. + + + Byl přijat fragment vzdálené komunikace. + ID objektu: {0} + ID fragmentu: {1} + Příznak začátku: {2} + Příznak konce: {3} + Délka datové části: {4} + Data datové části: {5} + + + Byl odeslán fragment vzdálené komunikace. + ID objektu: {0} + ID fragmentu: {1} + Příznak začátku: {2} + Příznak konce: {3} + Délka datové části: {4} + Data datové části: {5} + + + Vypíná se služba winrm. + + + Objekt byl úspěšně rehydrován. + Název deserializovaného typu: {0} + Rehydrováno přetypováním na typ: {1} + Rehydrovaný objekt je typu: {2} + + + Rehydratace objektu se nezdařila. + Název deserializovaného typu: {0} + Rehydrováno přetypováním na typ: {1} + Výjimka přetypování typu: {2} + Vnitřní výjimka při přetypování typu: {3} + + + Hloubka serializace byla přepsána. + Název serializovaného typu: {0} + Původní hloubka: {1} + Přepsaná hloubka: {2} + Aktuální hloubka pod nejvyšší úrovní: {3} + + + Režim serializace byl přepsán. + Název serializovaného typu: {0} + Přepsaný režim: {1} + + + Serializace vlastnosti skriptu byla přeskočena, protože není k dispozici žádné prostředí runspace pro vyhodnocení této vlastnosti. + Název vlastnosti: {0} + Název typu vlastníka vlastnosti: {1} + Skript getteru: {2} + + + Serializace vlastnosti byla přeskočena, protože getter vlastnosti selhal. + Název vlastnosti: {0} + Název typu vlastníka vlastnosti: {1} + Výjimka z metody getter vlastnosti: {2} + Vnitřní výjimka z metody getter vlastnosti: {3} + + + Serializace výčtového objektu nemusí být dokončena, protože objekt, který se prochází, vyvolal výjimku. + Typ výčtového objektu: {0} + Výjimka: {1} + + + Během serializace byla volána metoda ToString objektu, která selhala. + Typ objektu: {0} + Výjimka: {1} + + + Bylo dosaženo maximální hloubky pod nejvyšší úrovní, proto bude objekt serializován jako řetězec. + Typ objektu v maximální hloubce: {0} + Název vlastnosti v maximální hloubce: {1} + Hloubka: {2} + + + Deserializátor vyvolal výjimku XmlException (pravděpodobně kvůli nesprávnému formátu clixml). + Číslo řádku: {0} Pozice řádku: {1} + Výjimka: {2} + + + Serializace zadaných vlastností se nezdařila, protože jedna ze zadaných vlastností chyběla. + Typ objektu: {0} + Název vlastnosti: {1} + + + Spouští se konzola PowerShellu + + + Konzola PowerShellu je připravená pro uživatelský vstup + + + {0} + + + Trasování ErrorRecord: + Zpráva: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + Podrobnosti o výjimce: + Zpráva: {5} + Trasování zásobníku: {6} + InnerException {7} + + + + Výjimka: + Zpráva: {0} + StackTrace: {1} + InnerException : {2} + + + + Trasování PSObject + + + Úloha trasování: + Id: {0} + InstanceId: {1} + Název: {2} + Umístění: {3} + Stav: {4} + Příkaz: {5} + + + + Informace o trasování: + {0} + + + Informace o trasování: + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication. Spouští se vyvolání funkce pracovního postupu. GUID pro sledování: {0} + + + END ImportWorkflowCommand::StartWorkflowApplication. Ukončuje se volání funkce pracovního postupu. GUID pro sledování: {0} + + + BEGIN Vytváření nové úlohy v ImportWorkflowCommand::StartWorkflowApplication. GUID pro sledování: {0} + + + END Vytváření nové úlohy v ImportWorkflowCommand::StartWorkflowApplication. GUID pro sledování: {0} + + + END Vytváření nové úlohy v ImportWorkflowCommand::StartWorkflowApplication. GUID sledování {0} : GUID ContainerParentJob {1} + + + BEGIN JobLogic ContainerParentJob Guid {0} + + + END JobLogic ContainerParentJob Guid {0} + + + BEGIN WorkflowExecution ContainerParentJob Guid {0} + + + END WorkflowExecution ContainerParentJob Guid {0} + + + Úloha WorkflowJob s identifikátorem GUID {0} byla přidána do úlohy ContainerParentJob s identifikátorem GUID {1}. + + + Úloha ProxyJob s identifikátorem GUID {0} je přidružená ke vzdálené úloze ContainerParentJob s identifikátorem GUID {1}. + + + BEGIN Provádění ContainerParentJob s identifikátorem GUID {0} + + + END Provádění ContainerParentJob s identifikátorem GUID {0} + + + BEGIN Provádění úlohy proxy s GUID {0} + + + END Provádění úlohy proxy s GUID {0} + + + BEGIN Obslužná rutina události StateChanged pro proxy úlohu s identifikátorem GUID {0} + + + END Obslužná rutina události StateChanged pro proxy úlohu s identifikátorem GUID {0} + + + BEGIN Obslužná rutina události StateChanged pro podřízenou proxy úlohu s identifikátorem GUID {0} + + + END Obslužná rutina události StateChanged pro podřízenou proxy úlohu s identifikátorem GUID {0} + + + BEGIN Spuštění uvolňování paměti + + + END Spuštění uvolňování paměti + + + Úložiště trvalosti dosáhlo maximální zadané velikosti. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell začalo spouštět soubor skriptu {0}. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell zahájilo spouštění skriptu vybraného uživatelem ze souboru {0}. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell zastavuje aktuální příkaz. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell obnovuje běh ladicího programu. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell zastavuje ladicí program. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell krokuje s vnořením při ladění. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell krokuje nad při ladění. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell krokuje s vystoupením z ladění. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell povoluje všechny zarážky. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell zakazuje všechny zarážky. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell odebírá všechny zarážky. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell nastavuje zarážku na řádku č. {0} souboru {1}. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell odebírá zarážku na řádku č. {0} souboru {1}. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell povoluje zarážku na řádku č. {0} souboru {1}. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell zakazuje zarážku na řádku č. {0} souboru {1}. + + + Integrované skriptovací prostředí (ISE) v prostředí Windows PowerShell dosáhlo zarážky na řádku č. {0} souboru {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/EventingResources.cs.resx b/src/System.Management.Automation/resources/cs/EventingResources.cs.resx new file mode 100644 index 00000000000..962fef1cb13 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/EventingResources.cs.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Zadanou událost nejde zaregistrovat. Události, které vyžadují návratovou hodnotu, nejsou podporované. + + + Zadanou událost nejde zaregistrovat. Událost s názvem {0} neexistuje. + + + PowerShell se nemůže přihlásit k odběru událostí Windows RT. + + + Zadanou událost nejde zaregistrovat. Identifikátor zdroje události {0} je vyhrazený pro jádro PowerShellu. + + + Tato operace není podporovaná u vzdálených instancí. + + + Při předávání událostí není tato akce podporovaná. + + + K odběru zadané události se nejde přihlásit. Odběratel s identifikátorem zdroje {0} už existuje. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ExperimentalFeatureStrings.cs.resx b/src/System.Management.Automation/resources/cs/ExperimentalFeatureStrings.cs.resx new file mode 100644 index 00000000000..37ffdf01c6a --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ExperimentalFeatureStrings.cs.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nenašla se žádná experimentální funkce, která by odpovídala názvu {0}. + + + Povolení a zakázání experimentálních funkcí se projeví až po příštím spuštění PowerShellu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ExtendedTypeSystem.cs.resx b/src/System.Management.Automation/resources/cs/ExtendedTypeSystem.cs.resx new file mode 100644 index 00000000000..9c0ad1bfe55 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ExtendedTypeSystem.cs.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Člen {0} už existuje. + + + Člen {0} už existuje v souboru dat rozšířených typů. + + + Člen {0} neexistuje. + + + Při nastavování {0} došlo k výjimce: {1} + + + Při získávání {0} došlo k výjimce: {1} + + + Při procházení kolekce došlo k následující výjimce: {0}. + + + Ke členu {0} nejde přistupovat mimo objekt PSObject. + + + Člen vytvořený z konfigurace typu nejde změnit: {0}. + + + Název členu {0} je vyhrazený. + + + {0} nejde změnit. + + + Při volání {0} s tímto počtem argumentů: {1} došlo k výjimce: {2} + + + Při volání {0} za účelem získání obsahu objektu typu {1} došlo k výjimce: {2} + + + Pro {0} se nepovedlo najít přetížení s počtem argumentů {1}. + + + Pro {0} se nepovedlo najít vhodné přetížení obecné metody s parametry typu {1} a počtem argumentů {2}. + + + Pro {0} se našlo několik nejednoznačných přetížení s počtem argumentů {1}. + + + Argument {0} s hodnotou {1} pro {2} nejde převést na typ {3}: {4} + + + Přístupová metoda get vlastnosti {0} není k dispozici. + + + Přístupová metoda set vlastnosti {0} není k dispozici. + + + Metoda set musí být veřejná, statická, vracet void a mít dva parametry. První parametr musí být typu PSObject. Pokud je k dispozici také metoda get, je vyžadovaný druhý parametr. Musí být stejného typu jako návratový typ metody get. + + + Metoda get musí být veřejná, statická, nesmí vracet void a musí mít jeden parametr typu PSObject. + + + CodeProperty musí používat metodu get nebo set. + + + Metodu CodeMethod nejde vytvořit kvůli formátu metody. Metoda musí být veřejná, statická a mít jeden parametr typu PSObject. + + + Alias s názvem {0} obsahuje cyklus. + + + Hodnotu {0} typu {1} nejde převést na typ {2}. + + + Hodnotu typu {0} nejde převést na typ {1}. + + + Hodnotu {0} nejde převést na typ {1}. Chyba: {2} + + + Hodnotu {0} nejde převést na typ {1}, protože tento výčet nepovoluje čárky. + + + Hodnotu {0} nejde převést na typ {1} kvůli neplatným hodnotám výčtu. Zadejte jednu z následujících hodnot výčtu a zkuste to znovu. Možné hodnoty výčtu jsou {2}. + + + Hodnotu null nejde převést na typ {0} kvůli neplatným hodnotám výčtu. Zadejte jednu z následujících hodnot výčtu a zkuste to znovu. Možné hodnoty výčtu jsou {1}. + + + Hodnotu null nejde převést na typ {0}. + + + Hodnotu nejde převést na typ {0}. Chyba: {1} + + + Hodnotu nejde převést na typ System.String. + + + Argument musí být referenčního typu. + + + Hodnotu {0} nejde porovnat, protože neimplementuje rozhraní IComparable. + + + Hodnotu {0} se nepovedlo porovnat s {1}. Chyba: {2} + + + Hodnotu {0} nejde porovnat s {1}, protože objekty nejsou stejného typu nebo objekt {0} neimplementuje rozhraní {2}. + + + Hodnotu {0} nejde převést na typ {1}, protože se našly nejméně dvě shody ({2}, {3}) a tento výčet povoluje jen jednu shodu. + + + Hodnotu {0} nejde převést na typ {1}. Parametry typu Boolean přijímají jen logické hodnoty a čísla, například $True, $False, 1 nebo 0. + + + Hodnotu vlastnosti nejde získat, protože {0} je vlastnost jen pro zápis. + + + {0} je vlastnost jen pro čtení. + + + Hodnotu {0} nejde nastavit, protože jako hodnoty vlastností XmlNode jde použít jen řetězce. + + + Hodnotu {0} nejde nastavit, protože jde nastavit jen jedinečné atributy nebo jedinečné koncové uzly bez atributů. + + + Objekt typu PSProperty nebo PSMethod nejde přidat do této kolekce. + + + Při načítání souboru dat rozšířených typů došlo k následující chybě: {0} + + + Při načítání řetězce došlo k následující výjimce: {0} + + + Pole nebo vlastnost {0} typu {1} se od pole nebo vlastnosti {2} liší jen velikostí písmen. Typ musí být kompatibilní se specifikací Common Language Specification (CLS). + + + Při načítání hierarchie názvů typů došlo k následující výjimce: {0}. + + + Při načítání členu {1} došlo k následující výjimce: {0} + + + Při načítání členů došlo k následující výjimce: {0} + + + Při načítání stavu čtení vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání stavu zápisu vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání typu vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání řetězcové reprezentace vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání atributů vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání definic metody {1} došlo k následující výjimce: {0} + + + Při načítání řetězcové reprezentace metody {1} došlo k následující výjimce: {0} + + + Při načítání typu parametrizované vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání stavu čtení parametrizované vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání stavu zápisu parametrizované vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání definic parametrizované vlastnosti {1} došlo k následující výjimce: {0} + + + Při načítání řetězcové reprezentace parametrizované vlastnosti {1} došlo k následující výjimce: {0} + + + Vlastnost Value nejde nastavit u objektu PSMemberInfo typu {0}. + + + Argument {0} musí být {1}. Použijte {2}. + + + Argument {0} nesmí být {1}. Nepoužívejte {2}. + + + Vlastnost "{0}" nebyla nalezena. + + + Hodnotu vlastnosti nejde získat ani nastavit. Argument {0} musí být typu {1} nebo {2}. + + + Hodnotu vlastnosti {0} nejde nastavit, protože objekt je typu {1} místo {2}. + + + Při volání {0} došlo k výjimce: {1} + + + {0} není platná cesta ke třídě. + + + {0} není platná cesta. + + + Adaptér nedokáže určit, jestli jde vlastnost {0} změnit. + + + Adaptér nedokáže určit, jestli jde vlastnost {0} načíst. + + + Adaptér nemůže získat hodnotu vlastnosti {0}. + + + Adaptér nemůže nastavit hodnotu vlastnosti {0}. + + + Adaptér nemůže získat typ vlastnosti {0}. + + + Adaptér nemůže získat hierarchii typů objektu {0}. + + + Adaptér nemůže získat vlastnosti objektu {0}. + + + Adaptér nemůže získat vlastnost {0} pro {1}. + + + Výsledkem {0} byla hodnota null. + + + Vlastnost {0} se u objektu {1} nenašla. Nastavitelné vlastnosti: {2}. + + + Vlastnost {0} se u objektu {1} nenašla. Není k dispozici žádná nastavitelná vlastnost. + + + Objekt typu {0} nejde vytvořit. {1} + + + U otevřeného obecného typu {0} nejde vyvolat statické metody ani přistupovat ke statickým vlastnostem. Zadejte parametry typu a zkuste to znovu. Například místo [System.Collections.Generic.HashSet``1]::CreateSetComparer() použijte [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + Při vytváření atributu {1} došlo k následující výjimce: {0} + + + Hodnotu {0} nejde převést na pole řetězců. + + + Hodnotu nejde převést na typ {0}. V tomto jazykovém režimu se podporují jen základní typy. + + + Hodnotu nejde převést na typ podobný ByRef {0}. PowerShell nepodporuje typy podobné ByRef. + + + Vlastnost nebo pole {0} typu podobného ByRef {1} nejde získat ani nastavit. PowerShell nepodporuje typy podobné ByRef. + + + Metodu {0}, jejíž návratový typ {1} je podobný ByRef, nejde vyvolat. PowerShell nepodporuje typy podobné ByRef. + + + Instanci typu podobného ByRef {0} nejde vytvořit. PowerShell nepodporuje typy podobné ByRef. + + + Převod tabulky Hashtable v rozšířeném systému typů + + + V režimu ConstrainedLanguage nebude povolen převod typu HashTable na {0}. + + + Převod tabulky Hashtable v rozšířeném systému typů + + + V režimu ConstrainedLanguage nebude povolen převod typu {0} na {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/FileSystemProviderStrings.cs.resx b/src/System.Management.Automation/resources/cs/FileSystemProviderStrings.cs.resx new file mode 100644 index 00000000000..4420cda59a0 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/FileSystemProviderStrings.cs.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Vyvolat položku + + + Položka: {0} + + + Odebrat soubor + + + Odebrat adresář + + + Kopírovat soubor + + + Položka: {0} Cíl: {1} + + + Kopírovat adresář + + + Přejmenovat soubor + + + Přejmenovat adresář + + + Položka: {0} Cíl: {1} + + + Přesunout soubor + + + Přesunout adresář + + + Položka: {0} Cíl: {1} + + + Nastavit vlastnost souboru + + + Nastavit vlastnost adresáře + + + Položka: {0} Vlastnost: {1} Hodnota: {2} + + + Vymazat vlastnost souboru + + + Vymazat vlastnost adresáře + + + Položka: {0} Vlastnost: {1} + + + Vytvořit soubor + + + Vytvořit adresář + + + Cíl: {0} + + + Vymazat obsah + + + Položka: {0} + + + Položku {0} se nepovedlo najít. + + + Položku {0} nejde odebrat: {1} + + + Atributy položky {0} nejde obnovit: {1} + + + Objekt v zadané cestě {0} neexistuje. + + + Adresář {0} nejde odebrat, protože není prázdný. + + + Typ není známým typem pro systém souborů. Je možné zadat jen file, directory nebo symboliclink. + + + Cestu nejde zpracovat, protože zadaná cesta odkazuje na položku mimo basePath. + + + Zadaný kořen jednotky {0} buď neexistuje, nebo není složkou. + + + Položka se zadaným názvem {0} už existuje. + + + Při čtení proudu po jednom bajtu nejde zadat oddělovač. + + + Položku {0} nejde přepsat sama sebou. + + + Zadaný cíl nejde přejmenovat, protože představuje cestu nebo název zařízení. + + + Vlastnost {0} neexistuje nebo nebyla nalezena. + + + K provedení této operace nemáte dostatečná přístupová práva nebo je položka skrytá, systémová či jen pro čtení. + + + Atribut nejde nastavit, protože atributy nejsou podporované. Nastavit je možné jen tyto atributy: Archive, Hidden, Normal, ReadOnly nebo System. + + + Vlastnost nejde vymazat, protože není podporovaná. Vymazat je možné jen vlastnost Attributes. + + + Cestu {0} nejde zpracovat, protože cíl představuje rezervovaný název zařízení. + + + Při zadání -AsByteStream se kódování nepoužívá. + + + S kódováním po bajtech nejde pokračovat. Při použití kódování po bajtech musí být obsah typu byte. + + + Soubor nejde zpracovat, protože soubor {0} nebyl nalezen. + + + Adresář: + + + Kódování souboru nejde zjistit. Zadané kódování {0} není podporované při čtení obsahu v opačném pořadí. + + + Alternativní datový proud {0} souboru {1} se nepovedlo otevřít. + + + Proud {0} souboru {1}. + + + Parametry Raw a Wait nejde zadat ve stejném příkazu. + + + Pokud chcete použít přepínací parametr Persist, musí operační systém podporovat název jednotky (například písmena jednotek A–Z). + + + Při použití parametru Persist musí být kořen umístění systému souborů ve vzdáleném počítači. + + + Parametry {0} a {1} nejde zadat ve stejném příkazu. + + + Pro tuto operaci je vyžadován adresář. Položka {0} není adresář. + + + Vytvořit spojovací bod + + + Vytvořit symbolický odkaz + + + Tato operace vyžaduje oprávnění správce. + + + Vytvořit pevný odkaz + + + Pro tuto operaci je vyžadován soubor. Položka {0} není soubor. + + + Pro zadanou cestu nejsou podporované pevné odkazy. + + + Pro zadanou cestu nejsou podporované symbolické odkazy. + + + Kopírování {0} do {1} + + + Cílová cesta {0} je soubor, který už v cílovém umístění existuje. + + + Soubor {0} se nepovedlo zkopírovat do vzdáleného cílového umístění. + + + Z: {0} do: {1} + + + Adresář {0} nejde zkopírovat do souboru {0} + + + Nepovedlo se získat podřízené položky adresáře {0}. + + + Vzdálený soubor {0} se nepovedlo přečíst. + + + Nejde ověřit, jestli je vzdálený cíl {0} soubor. + + + Adresář {0} se ve vzdáleném cíli nepovedlo vytvořit. + + + Byla překročena maximální velikost jednotky: {0}. + + + Odkaz nejde vytvořit, protože cesta už existuje: {0}. + + + Přeskakuje se už navštívený adresář {0}. + + + Cílová cesta nemůže být podadresářem zdroje ani samotným zdrojem: {0}. + + + Cíl a cesta nemůžou být stejné. + + + Zkopírováno {0} z {1} souborů + + + {0} z {1} ({2:0.0} MB/s) + + + Odebráno {0} z {1} souborů + + + {0} z {1} ({2:0.0} MB/s) + + + Vytvoření spojovacího bodu vyžaduje absolutní cestu k cíli. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/FormatAndOutXmlLoadingStrings.cs.resx b/src/System.Management.Automation/resources/cs/FormatAndOutXmlLoadingStrings.cs.resx new file mode 100644 index 00000000000..e9d98a8937b --- /dev/null +++ b/src/System.Management.Automation/resources/cs/FormatAndOutXmlLoadingStrings.cs.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Chyba na cestě XPath {0} v souboru {1}: Element XML {2} nepovoluje atributy. + + + Chyba na cestě XPath {0} v souboru {1}: Uzel {2} nemůže obsahovat podřízené objekty. + + + Chyba na cestě XPath {0} v souboru {1}: Prvek {2} není platný. + + + Chyba na cestě XPath {0} v souboru {1}: Je vyžadovaná alespoň jedna výchozí položka {2}. + + + Chyba na cestě XPath {0} v souboru {1}: Může existovat nejvýše jedna výchozí položka {2}. + + + Chyba na cestě XPath {0} v souboru {1}: Název ovládacího prvku nesmí být null ani prázdný. + + + Chyba na cestě XPath {0} v souboru {1}: Zobrazení Out Of Band můžou obsahovat jen CustomControl nebo ListControl. + + + Chyba na cestě XPath {0} v souboru {1}: Zobrazení Out Of Band nemůže obsahovat GroupBy. + + + Chyba na cestě XPath {0} v souboru {1}: Zobrazení nejde načíst. + + + Chyba na cestě XPath {0} v souboru {1}: {2} není platná hodnota zarovnání. + + + Chyba na cestě XPath {0} v souboru {1}: Očekává se kladné celé číslo. + + + Chyba na cestě XPath {0} v souboru {1}: Definice záhlaví sloupců není platná. Všechna záhlaví se zahodí. + + + Chyba na cestě XPath {0} v souboru {1}: Počet položek řádku = {2} v alternativní sadě #{3} neodpovídá počtu položek výchozího řádku = {4}. + + + Chyba na cestě XPath {0} v souboru {1}: Počet položek záhlaví = {2} neodpovídá počtu položek výchozího řádku = {3}. + + + Chyba na cestě XPath {0} v souboru {1}: Musí být zadaná alespoň jedna položka zobrazení seznamu. + + + Chyba na cestě XPath {0} v souboru {1}: Položka vlastnosti není platná. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí seznam definic. + + + Chyba na cestě XPath {0} v souboru {1}: Očekává se logická hodnota. + + + Chyba na cestě XPath {0} v souboru {1}: Očekává se nezáporné celé číslo. + + + Chyba na cestě XPath {0} v souboru {1}: Očekává se celé číslo. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí hodnota vnitřního textu. + + + Chyba na cestě XPath {0} v souboru {1}: Seznam tokenů vlastního ovládacího prvku nesmí být prázdný. + + + Chyba na cestě XPath {0} v souboru {1}: Prvek {2} se nepovedlo načíst. + + + Chyba na cestě XPath {0} v souboru {1}: Prvek {2} nejde zadat bez výrazu. + + + Chyba na cestě XPath {0} v souboru {1}: Prvek {2} nejde zadat společně s výrazem. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí formátovací řetězec. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí text bloku skriptu. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí vlastnost. + + + Chyba na cestě XPath {0} v souboru {1}: Blok skriptu {2} není platný. + + + Chyba na cestě XPath {0} v souboru {1}: Řetězec {2} z prostředku {3} v sestavení {4} se nenašel. + + + Chyba na cestě XPath {0} v souboru {1}: Prostředek {2} v sestavení {3} se nenašel. + + + Chyba na cestě XPath {0} v souboru {1}: Sestavení {2} se nenašlo. + + + Chyba na cestě XPath {0} v souboru {1}: Uzel musí být typu XmlElement. + + + Chyba na cestě XPath {0} v souboru {1}: Očekává se výraz. + + + Chyba na cestě XPath {0} v souboru {1}: Bez výrazu nejde použít ovládací prvek ani Label. + + + Chyba na cestě XPath {0} v souboru {1}: Ovládací prvek a Label nejde použít současně. + + + Chyba na cestě XPath {0} v souboru {1}: SelectionSetName a TypeName nejde použít současně. + + + Chyba na cestě XPath {0} v souboru {1}: Není zadaný typ ani podmínka pro použití zobrazení. + + + Chyba na cestě XPath {0} v souboru {1}: Hodnota {2} není platná. + + + Chyba na cestě XPath {0} v souboru {1}: Existuje duplicitní uzel. + + + Chyba na cestě XPath {0} v souboru {1}: Prvky {2} a {3} se vzájemně vylučují. + + + Chyba na cestě XPath {0} v souboru {1}: Prvky {2}, {3} a {4} se vzájemně vylučují. + + + Chyba na cestě XPath {0} v souboru {1}: {2} je neznámý uzel. + + + Chyba na cestě XPath {0} v souboru {1}: {2} je neznámý atribut. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí atribut {2}. + + + Chyba na cestě XPath {0} v souboru {1}: Chybí uzel {2}. + + + Chyba na cestě XPath {0} v souboru {1}: V prvku {2} chybí uzel. + + + Chyba na cestě XPath {0} v souboru {1}: {2} je prázdný uzel. + + + Chyba na cestě XPath {0} v souboru {1}: {2} je prázdný atribut. + + + Chyba v souboru {0}: {1} + + + Soubor {0} obsahuje příliš mnoho chyb. + + + Při načítání souboru s daty formátování došlo k chybám: {0} + + + (Globální mezipaměť sestavení) {0} + + + {0}, {1} + + + Cesta {0} není plně kvalifikovaná. Zadejte plně kvalifikovanou cestu k souboru formátu. + + + Objekt FormatTable nejde aktualizovat, protože mohl být vytvořený mimo prostředí runspace. + + + Při načítání objektu FormatTable došlo k chybám. Podrobné chybové zprávy najdete v obsahu vlastnosti Errors. + + + Chyba v datech formátování {0}: {1} + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Počet položek záhlaví = {2} neodpovídá počtu položek výchozího řádku = {3}. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Data formátování {2} nejsou platná. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Blok skriptu {2} není platný. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Prvek {2} se nepovedlo načíst. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: TableControl smí obsahovat jen jeden prvek {2}. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Je vyžadovaná alespoň jedna výchozí položka {2}. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Musí být zadaná alespoň jedna položka zobrazení seznamu. + + + Chyba v datech zobrazení s názvem typu {0} na indexu {1}: Může existovat nejvýše jedna výchozí položka {2}. + + + Data formátování pro typ {0} obsahují příliš mnoho chyb. + + + Sdílenou tabulku formátování nejde aktualizovat více než jednou položkou. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/FormatAndOut_MshParameter.cs.resx b/src/System.Management.Automation/resources/cs/FormatAndOut_MshParameter.cs.resx new file mode 100644 index 00000000000..143b9a7a56c --- /dev/null +++ b/src/System.Management.Automation/resources/cs/FormatAndOut_MshParameter.cs.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 + + + Hodnotu {0} nejde převést na žádný z následujících typů: {1}. + + + Hodnota parametru byla null. Očekával se jeden z následujících typů: {0}. + + + Duplicitní klíč {0} je v konfliktu s klíčem {1}. + + + Klíč {0} má neplatný typ {1}. Očekávají se typy {2}. + + + Klíč {0} má neplatný typ {1}. Očekává se typ {2}. + + + Klíč {0} je nejednoznačný. Klíče {1} a {2} jsou v konfliktu. + + + Hodnota klíče nesmí být null. + + + Typ klíče {0} není platný. Klíč musí být řetězec. + + + Klíč {0} nemá žádnou hodnotu. + + + Chybí povinná položka pro {0}. + + + Klíč {0} není platný. + + + Hodnota {0} klíče {1} není platná. Platné hodnoty jsou {2}. + + + Hodnota {0} klíče {1} musí být větší než 0. + + + Klíč {0} nemůže mít prázdný formátovací řetězec. + + + Klíč {0} nemůže mít hodnotu prázdného řetězce. + + + Hodnota prázdného řetězce není povolená. + + + Klíč {0} nemůže v hodnotě {1} obsahovat zástupné znaky. + + + V hodnotě {0} nejsou povolené zástupné znaky. + + + Hodnota EnumerableExpansion není platná. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/FormatAndOut_format_xxx.cs.resx b/src/System.Management.Automation/resources/cs/FormatAndOut_format_xxx.cs.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/FormatAndOut_format_xxx.cs.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/FormatAndOut_out_xxx.cs.resx b/src/System.Management.Automation/resources/cs/FormatAndOut_out_xxx.cs.resx new file mode 100644 index 00000000000..4a0b834b92a --- /dev/null +++ b/src/System.Management.Automation/resources/cs/FormatAndOut_out_xxx.cs.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> další stránka, <CR> další řádek, Q konec + + + Hodnota LineOutput nesmí být null. + + + Typ {0} pro LineOutput nebyl očekáván. LineOutput očekává typ {1}. + + + Objekt typu {0} není platný nebo není ve správném pořadí. Pravděpodobně je to způsobeno uživatelsky zadaným příkazem {1}, který je v konfliktu s výchozím formátováním. + + + Nelze otevřít soubor{0}. + + + Výstup do souboru + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/GetErrorText.cs.resx b/src/System.Management.Automation/resources/cs/GetErrorText.cs.resx new file mode 100644 index 00000000000..46142eb889d --- /dev/null +++ b/src/System.Management.Automation/resources/cs/GetErrorText.cs.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nelze načíst prostředek se základním názvem {0}. + + + Nelze načíst řetězec prostředku s ID {0}. + + + Nastavení zásady zastavení brání spouštění příkazů. + + + Nelze načíst zprávu {0} {1} {2}, protože sestavení nebylo zaregistrováno. + + + Nelze načíst zprávu {0} {1} {2}. Formát řetězce šablony není platný v řetězci šablony {3}. + + + Nelze načíst zprávu {0} {1} {2}. Řetězec šablony existuje, ale jeho hodnota je prázdná nebo prázdná obsahuje jen mezery. + + + Kanál se zastavil. + + + Skript selhal kvůli přetečení hloubky volání. + + + Kanál selhal kvůli přetečení hloubky volání. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/HelpDisplayStrings.cs.resx b/src/System.Management.Automation/resources/cs/HelpDisplayStrings.cs.resx new file mode 100644 index 00000000000..5dff86b74e3 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/HelpDisplayStrings.cs.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NÁZEV + + + SYNOPSIS + + + DESCRIPTION + + + SYNTAX + + + PARAMETERS + + + INPUTS + + + OUTPUTS + + + TERMINATING ERRORS + + + NON-TERMINATING ERRORS + + + NOTES + + + EXAMPLES + + + Příklad + + + EXAMPLE + + + OUTPUT + + + RELATED LINKS + + + SHORT DESCRIPTION + + + Title: + + + Question: + + + Odpověď + + + Term: + + + Definition: + + + Content: + + + PROVIDER NAME + + + This cmdlet supports the common parameters: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. For more information, see + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Required? + + + Position? + + + Type: + + + Target Object Type: + + + Default value + + + Accept pipeline input? + + + Accept wildcard characters? + + + (Category: + + + Suggested Action: + + + For more information, type: + + + For technical information, type: + + + To see the examples, type: + + + For online help, type: + + + <CommonParameters> + + + REMARKS + + + true + + + Named + + + DRIVES + + + CAPABILITIES + + + TASKS + + + TASK: + + + FILTERS + + + DYNAMIC PARAMETERS + + + Cmdlets Supported: + + + ALIASES + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + -- To view the Help topic for this cmdlet online, type: "Get-Help {0} -Online" or + go to {1}. + + + Žádné + + + Aliases + + + Dynamic? + + + Parameter set name + + + Unable to retrieve the HelpInfo XML file for UI culture {0}. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + + + The ModuleBase directory cannot be found. Verify the directory and try again. + + + The path {0} is not a valid directory. Make sure the directory exists and retry. + + + A Help URI cannot contain more than 10 redirections. Specify a valid Help URI. + + + Updating Help + + + Connecting to Help Content... + + + Downloading Help Content... + + + Installing Help content... + + + Locating Help Content... + + + (All) + + + No PowerShell modules were found that match the following pattern: {0}. Verify the pattern and then try the command again. + + + No PowerShell modules were found that match the specified FullyQualifiedModule {0}. Verify the FullyQualifiedModule value and then try the command again. + + + Help content cannot be found. Make sure the server is available and the help content location is properly defined in the HelpInfo XML. + + + The Update-Help command failed because the specified module does not support updatable help. Use Get-Help -Online or look online for help for the commands in this module. + + + The following parameter must not be null or empty: Module. + + + The following parameter must not be null or empty: Path. + + + Update-Help has completed successfully. + + + Error extracting Help content. + + + Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. + + + The Help content at the specified location is not valid. Specify a location that contains valid Help Content. + + + The HelpInfo XML is not valid. Specify valid HelpInfo XML. + + + Help content was successfully saved to the following location: {0} + + + The Help content XSD file cannot be found in {0}. Verify that the XSD file exists at the specified location, and then retry the command. + + + Failed to update Help for the module(s) : +'{0}' +{1} + + + Saving Help + + + Help content contains files that are not valid. Only .txt and .xml files are supported. + + + Failed to save Help for the module(s) '{0}' : {1} + + + Failed to save Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be saved using: Save-Help -UICulture en-US. + + + Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + + + false + + + The -Recurse parameter is only available if a source path is specified. + + + The path {0} does not contain a FileSystem provider. Verify that the specified path contains the FileSystem provider, and then retry the command. + + + Searching Help for {0} ... + + + No UI culture was found that matches the following pattern: {0}. Verify the pattern and then try the command again. + + + Help was not saved for the module {0}, because the Save-Help command was run on this computer within the last 24 hours. +To save help again, add the Force parameter to your command. + + + Help was not updated for the module {0}, because the Update-Help command was run on this computer within the last 24 hours. +To update help again, add the Force parameter to your command. + + + The most current Help files are already installed. + + + {0}: {1}. Culture {2} Version {3} + + + Updated {0} + + + The value of the HelpInfoUri key in the module manifest must resolve to a container or root URL on a website where the help files are stored. The HelpInfoUri '{0}' does not resolve to a container. + + + Help content must be in the namespace {0}. + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + + + The most current Help files are already downloaded. + + + Saved {0} + + + The HelpInfoURI {0} does not start with HTTP. + + + The root level element of the help content must be "helpItems". + + + Saving Help for module {0} + + + Updating Help for module {0} + + + Resolving URI: "{0}" + + + Help URI: {0} + + + {0}, Current Version: {1}, Available Version: {2}, UICulture: {3} + + + PROPERTIES + + + METHODS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/HelpErrors.cs.resx b/src/System.Management.Automation/resources/cs/HelpErrors.cs.resx new file mode 100644 index 00000000000..7a5e9e89d2c --- /dev/null +++ b/src/System.Management.Automation/resources/cs/HelpErrors.cs.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help v této relaci nenašel {0} v žádném souboru nápovědy. Aktualizovaná témata nápovědy stáhnete zadáním příkazu Update-Help. Online nápovědu získáte vyhledáním tématu nápovědy v knihovně TechNet na adrese https://go.microsoft.com/fwlink/?LinkID=107116. + + + Kategorii nápovědy nejde zpracovat, protože {0} není platná kategorie nápovědy. + + + Soubor nápovědy {0} nejde načíst. Podrobnosti: {1}. + + + K souboru nápovědy {0} nejde získat přístup, protože aktuální uživatel nemá přístupová práva k souboru. Podrobnosti: {1}. + + + Soubor nápovědy {0} není platný dokument XML. Podrobnosti: {1}. + + + Při načítání obsahu nápovědy pro {0} ze souboru {1} došlo k chybě. Podrobnosti: {2}. Aktualizovaná témata nápovědy stáhnete spuštěním rutiny Update-Help. Online nápovědu získáte vyhledáním tématu nápovědy v knihovně TechNet na adrese https://go.microsoft.com/fwlink/?LinkID=107116. + + + Poskytovatele {0} nejde načíst. Podrobnosti: {1}. + + + Soubor nápovědy nejde načíst. Počet chyb: {1}. Došlo k nim při načítání souboru nápovědy {0}. + + + Uzel {0} nemůže mít jako podřízený uzel {1}. Cesta k uzlu: {2}. + + + Uzel {0} může mít nejvýše {2} podřízených uzlů typu {1}. Cesta k uzlu: {3}. + + + Klíč registru se nepovedlo najít: {0}{1}. K načtení souborů nápovědy se použije {2}. + + + Kritériím {0} neodpovídá žádný parametr. + + + Požadovaná kategorie nápovědy nepodporuje {0}. + + + Online verzi tohoto tématu nápovědy nejde zobrazit, protože internetová adresa (URI) tématu není zadaná v kódu příkazu ani v souboru nápovědy k příkazu. + + + Zadaný identifikátor URI {0} není platný. + + + Prohlížeč pro zobrazení online nápovědy se nepovedlo spustit. K otevření identifikátoru URI {0} není přidružený žádný program ani prohlížeč. + + + Protokol zadaný v identifikátoru URI {0} není podporovaný. Podporují se jen protokoly {1} a {2}. + + + Našlo se několik témat nápovědy. S možností -{0} použijte jen jedno téma nápovědy. + + + Nápovědu nejde získat ze vzdáleného prostředí runspace, protože toto prostředí ještě není otevřené. Otevřete prostředí runspace spuštěním příkazu implicitní vzdálené komunikace a potom zkuste příkaz pro získání nápovědy spustit znovu. + + + Přístup je odepřený. Příkaz nemohl aktualizovat témata nápovědy pro základní moduly PowerShellu ani pro žádné moduly v adresáři $pshome\Modules. +Pokud chcete tato témata nápovědy aktualizovat, spusťte PowerShell pomocí příkazu Spustit jako správce a zkuste Update-Help spustit znovu. + + + Pokud chcete používat {0}, ujistěte se, že vaše aplikace používá jako sadu SDK projektu Microsoft.NET.Sdk.WindowsDesktop a že je k dispozici odpovídající sestavení Microsoft.PowerShell.GraphicalHost. ({1}) + + + {0} ve vzdálené relaci nefunguje. + + + ForwardHelpTargetName nemůže odkazovat na samotnou funkci. + + + V omezené relaci nejde získat nápovědu ze síťového umístění. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/HistoryStrings.cs.resx b/src/System.Management.Automation/resources/cs/HistoryStrings.cs.resx new file mode 100644 index 00000000000..2c3d906d1f6 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/HistoryStrings.cs.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Identifikátor {0} není platnou hodnotou identifikátoru historie. Zadejte kladné číslo a zkuste to znovu. + + + Nepodařilo se najít historii pro ID {0}. + + + Parametr Count nelze kombinovat s více ID. + + + Nepodařilo se najít historii pro příkazový řádek {0}. + + + Nepodařilo se najít nejnovější historii. + + + Rutina Invoke-History je opakovaně volána ve smyčce. + + + Nelze zpracovat více příkazů historie. Pomocí Invoke-History můžete spustit pouze jeden příkaz. + + + Historii nelze přidat, protože vstupní objekt nemá platný formát. + + + Identifikátor {0} není platný. Zadejte kladné číslo a zkuste to znovu. + + + Tento příkaz vymaže všechny položky z historie relace. + + + Parametr Count nelze kombinovat s více parametry CommandLine. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/HostInterfaceExceptionsStrings.cs.resx b/src/System.Management.Automation/resources/cs/HostInterfaceExceptionsStrings.cs.resx new file mode 100644 index 00000000000..367553bcad4 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/HostInterfaceExceptionsStrings.cs.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 + + + Došlo k chybě typu {0}. + + + Příkaz s výzvou uživateli selhal, protože hostitelský program nebo typ příkazu nepodporuje interakci s uživatelem. Použijte hostitelský program, který podporuje interakci s uživatelem, například konzolu PowerShellu, a z typů příkazů, které interakci s uživatelem nepodporují, odeberte příkazy související s výzvami. + + + Příkaz s výzvou uživateli selhal, protože hostitelský program nebo typ příkazu nepodporuje interakci s uživatelem. Hostitel se pokoušel vyžádat potvrzení pomocí následující zprávy: {0} + + + Metodu nejde vyvolat, protože fond byl zavřený nebo selhal. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/InternalCommandStrings.cs.resx b/src/System.Management.Automation/resources/cs/InternalCommandStrings.cs.resx new file mode 100644 index 00000000000..377a1f19d70 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/InternalCommandStrings.cs.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched methods. Possible matches include:{1}. + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched members. Possible matches include:{1}. + + + Retrieve the value for key '{0}' + + + Invoke method '{0}' with arguments: {1} + + + Invoke method '{0}' + + + Retrieve the value for property '{0}' + + + InputObject: {0} + + + Cannot operate on a 'null' input object. + + + Input name "{0}" cannot be resolved to a method. + + + Cannot invoke a method in the restricted language mode. + + + The -WhatIf and -Confirm parameters are not supported for script blocks. + + + The '{0}' operation is not allowed in the RestrictedLanguage mode. + + + An operator is required to compare the two specified values. Include a valid operator in the command, and then try the command again. For example, Get-Process | Where-Object -Property Name -eq Idle + + + The input name "{0}" cannot be resolved to a property. + + + The input name "{0}" cannot be resolved to a member. + + + The specified operator requires both the -Property and -Value parameters. Provide values for both parameters, and then try the command again. + + + This method cannot be run on the current thread. It can only be called on the cmdlet thread. + + + A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + A ForEach-Object -Parallel piped input object cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + The 'TimeoutSeconds' parameter cannot be used with the 'AsJob' parameter. + + + The following common parameters are not currently supported in the Parallel parameter set: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/InternalHostStrings.cs.resx b/src/System.Management.Automation/resources/cs/InternalHostStrings.cs.resx new file mode 100644 index 00000000000..abd5522d79c --- /dev/null +++ b/src/System.Management.Automation/resources/cs/InternalHostStrings.cs.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 + + + Metoda EnterNestedPrompt nebyla volána tolikrát, kolikrát byla volána metoda ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/InternalHostUserInterfaceStrings.cs.resx b/src/System.Management.Automation/resources/cs/InternalHostUserInterfaceStrings.cs.resx new file mode 100644 index 00000000000..9a52e6c18b0 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/InternalHostUserInterfaceStrings.cs.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug se zastavilo, protože hodnota proměnné DebugPreference byla Stop. + + + Hodnota {0} není podporovaná hodnota ActionPreference. + + + Parametr {0} musí obsahovat alespoň jednu hodnotu. + + + &Ano + + + Pokračovat. + + + An&o pro všechny + + + Pokračovat a v této relaci se už znovu neptat, jestli chcete pokračovat. + + + &Ne + + + Ukončit operaci s chybou. + + + Ne pro vš&echny + + + Ukončit operaci s chybou. V této relaci nepožadovat obnovení operace. + + + &Pozastavit + + + Pozastavit aktuální operaci a přejít na příkazový řádek. Pozastavenou operaci obnovíte zadáním exit. + + + Pokračovat v této operaci? + + + (výchozí hodnota je {0}) + + + (výchozí volby jsou {0}) + + + Volba[{0}]: + + + {0} musí mít alespoň jeden prvek. + + + {0} musí být platný index do {1}. {2} není platný index. + + + Klávesovou zkratku nelze zpracovat, protože otazník (?) nelze použít jako klávesovou zkratku. + + + PODROBNÉ: {0} + + + UPOZORNĚNÍ: {0} + + + LADIT: {0} + + + Hostitel momentálně nezaznamenává přepis. + + + Čas spuštění příkazu: {0} + + + ********************** +Začátek přepisu PowerShellu +Čas zahájení: {0:yyyyMMddHHmmss} +Uživatelské jméno: {1} +Uživatel RunAs: {2} +Název konfigurace: {3} +Počítač: {4} ({5}) +Hostitelská aplikace: {6} +ID procesu: {7} +{8} +********************** + + + ********************** +Začátek přepisu PowerShellu +Čas zahájení: {0:yyyyMMddHHmmss} +********************** + + + ********************** +Konec přepisu PowerShellu +Čas ukončení: {0:yyyyMMddHHmmss} +********************** + + + Cesta k souboru {0} odkazuje na adresář. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/Logging.cs.resx b/src/System.Management.Automation/resources/cs/Logging.cs.resx new file mode 100644 index 00000000000..a92e498a54b --- /dev/null +++ b/src/System.Management.Automation/resources/cs/Logging.cs.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + TřídaVýjimky=[ExceptionClass] + KategorieChyby=[ErrorCategory] + IDChyby=[ErrorId] + ChybováZpráva=[ErrorMessage] + + Závažnost=[Severity] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + +DalšíInformace: + Název=[AdditionalInfo_Name1];Hodnota=[AdditionalInfo_Value1] + Název=[AdditionalInfo_Name2];Hodnota=[AdditionalInfo_Value2] + Název=[AdditionalInfo_Name3];Hodnota=[AdditionalInfo_Value3] + + + TřídaVýjimky=[ExceptionClass] + KategorieChyby=[ErrorCategory] + IDChyby=[ErrorId] + ChybováZpráva=[ErrorMessage] + + Závažnost=[Severity] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + + + NázevPoskytovatele=[ProviderName] + TřídaVýjimky=[ExceptionClass] + KategorieChyby=[ErrorCategory] + IDChyby=[ErrorId] + ChybováZpráva=[ErrorMessage] + + Závažnost=[Severity] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + + + NovýStavJádra=[NewEngineState] + PředchozíStavJádra=[PreviousEngineState] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + + + NovýStavPříkazu=[NewCommandState] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + + + NázevPoskytovatele=[ProviderName] + NovýStavPoskytovatele=[NewProviderState] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + + + NázevProměnné=[VariableName] + NováHodnota=[NewValue] + PředchozíHodnota=[PreviousValue] + + PořadovéČíslo=[SequenceNumber] + + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevPříkazu=[CommandName] + TypPříkazu=[CommandType] + NázevSkriptu=[ScriptName] + CestaKPříkazu=[CommandPath] + PříkazovýŘádek=[CommandLine] + + + PořadíPodrobností=[DetailSequence] + CelkemPodrobností=[DetailTotal] + + PořadovéČíslo=[SequenceNumber] + + IDUživatele=[User] + NázevHostitele=[HostName] + VerzeHostitele=[HostVersion] + IDHostitele=[HostId] + HostitelskáAplikace=[HostApplication] + VerzeJádra=[EngineVersion] + IDProstředíRunspace=[RunspaceId] + IDKanálu=[PipelineId] + NázevSkriptu=[ScriptName] + PříkazovýŘádek=[CommandLine] + + + NEZNÁMÉ + + + Experimentální funkce jádra {0} deklarovaná v konfiguračním souboru není v aktuálním PowerShellu zaregistrovaná. + + + Experimentální funkce {0} deklarovaná v konfiguračním souboru není platná. +Název experimentální funkce musí odpovídat následující konvenci: + Název funkce jádra: PS[FeatureName] + Název funkce modulu: [ModuleName].[FeatureName] + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/Metadata.cs.resx b/src/System.Management.Automation/resources/cs/Metadata.cs.resx new file mode 100644 index 00000000000..4d5ad4f8fb4 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/Metadata.cs.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Atributy pro {0} nejde inicializovat: {1} + + + Argument nejde ověřit, protože jeho typ {0} není stejný typ ({1}) jako maximální a minimální limity parametru. Ověřte, že je argument typu {1}, a potom příkaz zkuste znovu. + + + Argument {0} nejde ověřit, protože jeho hodnota není větší než nula. + + + Argument {0} nejde ověřit, protože jeho hodnota není větší nebo rovna nule. + + + Argument {0} nejde ověřit, protože jeho hodnota není menší než nula. + + + Argument {0} nejde ověřit, protože jeho hodnota není menší nebo rovna nule. + + + Zadaný minimální rozsah ({0}) nejde přijmout, protože není stejného typu jako zadaný maximální rozsah ({1}). Aktualizujte atribut ValidateRange pro parametr. + + + Typy parametrů MaxRange a MinRange nejde přijmout. Oba parametry musí být objekty implementující rozhraní IComparable. + + + Zadaný maximální rozsah nejde přijmout, protože je menší než zadaný minimální rozsah. Aktualizujte atribut ValidateRange pro parametr. + + + Argument {0} je větší než maximální povolený rozsah {1}. Zadejte argument menší nebo rovný {1} a potom příkaz zkuste znovu. + + + Argument {0} je menší než minimální povolený rozsah {1}. Zadejte argument větší nebo rovný {1} a potom příkaz zkuste znovu. + + + Argument {0} neodpovídá vzoru {1}. Zadejte argument odpovídající {1} a příkaz zkuste znovu. + + + Atribut ValidateCount nejde použít u parametru, který není pole. Buď atribut z parametru odeberte, nebo nastavte parametr jako pole. + + + Požadovaný počet hodnot parametru: {0}. Počet zadaných hodnot: {1}. + + + Parametr vyžaduje nejméně {0} a nejvýše {1} hodnot. Počet zadaných hodnot: {2}. + + + Zadaný maximální počet argumentů parametru je menší než zadaný minimální počet argumentů. Aktualizujte atribut ValidateCount pro parametr. + + + Zadaná maximální délka argumentu ve znacích je kratší než zadaná minimální délka argumentu ve znacích. Aktualizujte atribut ValidateLength pro parametr. + + + Atribut ValidateLength nejde použít u parametru, který není typu string nebo string[]. Nastavte parametr jako typ string nebo string[]. + + + Délka argumentu ve znacích ({1}) je příliš krátká. Zadejte argument s délkou větší nebo rovnou {0} a potom příkaz zkuste znovu. + + + Délka argumentu ve znacích ({1}) je příliš dlouhá. Zadejte argument s délkou menší nebo rovnou {0} a potom příkaz zkuste znovu. + + + Argument {0} nepatří do sady {1} zadané atributem ValidateSet. Zadejte argument, který je v sadě, a potom příkaz zkuste znovu. + + + Generátor platných hodnot vrátil hodnotu null. + + + {0} selhalo u vlastnosti {1} {2} + + + Příkaz nejde získat ani spustit. Byl překročen maximální počet sad parametrů pro tento příkaz. + + + Argument nejde zpracovat, protože jeho hodnota není řetězec. Hodnoty argumentů parametrů se zadaným atributem ArgumentTransformationAttribute by měly být řetězce. + + + Proměnnou nejde ověřit, protože hodnota {1} není platná hodnota pro proměnnou {0}. + + + Atribut nejde přidat, protože proměnná {0} s hodnotou {1} by už nebyla platná. + + + Argument je null. Zadejte platnou hodnotu argumentu a potom zkuste příkaz spustit znovu. + + + Argument má hodnotu null nebo kolekce argumentů obsahuje prvek s hodnotou null. Zadejte kolekci, která neobsahuje žádné hodnoty null, a potom příkaz zkuste znovu. + + + Argument je null nebo prázdný. Zadejte argument, který není null ani prázdný, a potom příkaz zkuste znovu. + + + Argument je null, prázdný nebo kolekce argumentů obsahuje prvek s hodnotou null. Zadejte kolekci, která neobsahuje žádné hodnoty null, a potom příkaz zkuste znovu. + + + Argument je null, prázdný nebo obsahuje jen prázdné znaky. Zadejte argument, který obsahuje jiné než prázdné znaky, a potom příkaz zkuste znovu. + + + Prvek kolekce argumentů je null, prázdný nebo obsahuje jen prázdné znaky. Zadejte kolekci, která neobsahuje žádnou z těchto hodnot, a potom příkaz zkuste znovu. + + + Parametr s názvem {0} byl pro příkaz definován několikrát. + + + Alias parametru nejde zadat, protože alias s názvem {0} už byl pro příkaz definován několikrát. + + + Parametr {0} nejde zadat, protože je v konfliktu s aliasem stejného názvu pro parametr {1}. + + + Ověřovací skript {1} pro argument s hodnotou {0} nevrátil výsledek True. Zjistěte, proč ověřovací skript selhal, a potom příkaz zkuste znovu. + + + Argument {0} neobsahuje platnou verzi PowerShellu. Zadejte platné číslo verze a potom příkaz zkuste znovu. + + + Argument {0} nejde ověřit, protože nejde o platný název proměnné. + + + Typ převodu úlohy musí být odvozený z IAstToScriptBlockConverter. + + + Argument cesty není platný. Zadejte argument cesty typu string. + + + Jednotka {0} v argumentu cesty nepatří do sady schválených jednotek: {1}. Zadejte argument cesty se schválenou jednotkou. + + + Argument cesty obsahuje neplatné znaky. + + + Argument cesty nemá kořenovou jednotku. Zadejte úplný argument cesty s kořenovou jednotkou. + + + Argument parametru {0} nemůže mít hodnotu null ani prázdný řetězec. + + + Člen výčtu {0} není platná hodnota parametru {1}. Zadejte jednoho z těchto členů a zkuste to znovu: {2}. + + + Vstup nejde zpracovat. Argument {0} není důvěryhodný. + + + Selhání kontroly atributu ValidateTrustedData + + + Argument parametru {0} není důvěryhodný a v režimu Constrained Language neprojde kontrolou atributu parametru ValidateTrustedData. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/MiniShellErrors.cs.resx b/src/System.Management.Automation/resources/cs/MiniShellErrors.cs.resx new file mode 100644 index 00000000000..4a6fdd8c299 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/MiniShellErrors.cs.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 + + + Aktualizace není podporována pro kategorii konfigurace prostředí runspace {0}. + + + Při aktualizaci seznamu sestavení pro prostředí runspace došlo k následujícím chybám: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/Modules.cs.resx b/src/System.Management.Automation/resources/cs/Modules.cs.resx new file mode 100644 index 00000000000..dc1ee22f194 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/Modules.cs.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Zadaný modul {0} nebyl načten, protože v žádném adresáři modulů nebyl nalezen platný soubor modulu. + + + Zadaný modul {0} verze {1} nebyl načten, protože v žádném adresáři modulů nebyl nalezen platný soubor modulu. + + + Zadaná hodnota MaximumVersion {0} nebyla správná. Pokud používáte *, MaximumVersion podporuje jen jeden znak * a ten musí být vždy na konci hodnoty MaximumVersion. + + + Zadaný modul {0} s MaximumVersion {1} nebyl načten, protože v žádném adresáři modulů nebyl nalezen platný soubor modulu. + + + Zadaný modul {0} s MinimumVersion {1} a MaximumVersion {2} nebyl načten, protože v žádném adresáři modulů nebyl nalezen platný soubor modulu. + + + MinimumVersion {0} by neměla být vyšší než MaximumVersion {1}. + + + Sestavení {0} nebylo načteno, protože nebylo nalezeno žádné sestavení s tímto názvem. Ověřte název sestavení a zkuste to znovu. + + + Modul ke zpracování {0}, uvedený v poli {1} manifestu modulu {2}, nebyl zpracován, protože v žádném adresáři modulů nebyl nalezen platný modul. + + + Pro modul {0} nebyl vrácen žádný vlastní objekt, protože parametr -AsCustomObject je možné použít jen s moduly skriptů. + + + Manifest modulu {0} se nepovedlo zpracovat, protože nejde o platný soubor manifestu modulu PowerShellu. Odeberte nepovolené prvky: {1} + + + Zpracováním souboru manifestu modulu {0} nevznikl platný objekt manifestu. Upravte soubor tak, aby obsahoval platný manifest modulu PowerShellu. Platný manifest můžete vytvořit pomocí rutiny New-ModuleManifest. + + + Modul {0} nejde importovat, protože jeho manifest obsahuje jednoho nebo více neplatných členů. Platní členové manifestu jsou ({1}). Odeberte neplatné členy ({2}) a potom zkuste modul importovat znovu. + + + Tabulka hash popisující modul obsahuje jednoho nebo více neplatných členů. Platní členové jsou ({0}). Odeberte neplatné členy ({1}) a zkuste to znovu. + + + Modul {0} nejde načíst, protože byl překročen limit vnoření modulů. Moduly je možné vnořit jen do {1} úrovní. Vyhodnoťte a změňte pořadí načítání modulů, aby se nepřekročil limit vnoření, a potom zkuste skript spustit znovu. + + + Člen ModuleVersion není v manifestu modulu přítomný. Tento člen musí existovat a musí mu být přiřazeno číslo verze ve tvaru :n.n.n.n:. Přidejte chybějící člen do souboru {0}. + + + Člen {0} není v souboru manifestu modulu {2} platný: {1} + + + Verze {0} modulu {1} nesplňuje požadavek na minimální verzi {2}. Ověřte, že je číslo verze podporované, a potom zkuste modul znovu načíst. + + + Verze PowerShellu v tomto počítači je {0}. Modul {1} vyžaduje ke spuštění minimálně PowerShell verze {2}. Ověřte, že máte nainstalovanou minimální požadovanou verzi PowerShellu, a potom to zkuste znovu. + + + Člen NestedModules manifestu modulu nejde použít, pokud je člen ModuleToProcess binární modul. Upravte soubor manifestu modulu v umístění {0} a potom to zkuste znovu. + + + Člen {0} v manifestu modulu není platný: {1}. Ověřte, že je pro toto pole v souboru {2} zadaná platná hodnota. + + + Cesta k manifestu modulu {0} není platná. Hodnota argumentu Path musí odkazovat na jeden soubor s příponou .psd1. Změňte hodnotu argumentu Path tak, aby odkazovala na platný soubor psd1, a potom to zkuste znovu. + + + Klíč ModuleVersion v manifestu modulu {0} určuje verzi modulu {1}, která neodpovídá názvu složky verze v umístění {2}. Změňte hodnotu klíče ModuleVersion tak, aby odpovídala názvu složky verze. + + + Zadaná položka NestedModule {0} v manifestu modulu {1} není platná. Po aktualizaci této položky platnými hodnotami to zkuste znovu. + + + Zadaná položka RequiredAssemblies {0} v manifestu modulu {1} není platná. Po aktualizaci této položky platnými hodnotami to zkuste znovu. + + + Zadaná položka FileList {0} v manifestu modulu {1} není platná. Po aktualizaci této položky platnými hodnotami to zkuste znovu. + + + Zadaná položka RequiredModules {0} v manifestu modulu {1} není platná. Po aktualizaci této položky platnými hodnotami to zkuste znovu. + + + Zadaná položka ModuleList {0} v manifestu modulu {1} není platná. Po aktualizaci této položky platnými hodnotami to zkuste znovu. + + + Manifest modulu {0} je zadaný s klíčem CompatiblePSEditions, který se podporuje jen v PowerShellu verze 5.1 nebo novější. Aktualizujte hodnotu klíče PowerShellVersion na 5.1 nebo novější a zkuste to znovu. + + + Zadaná hodnota {0} pro CompatiblePSEditions obsahuje duplicitní názvy edic PowerShellu. Po odebrání duplicitních názvů edic PowerShellu to zkuste znovu. + + + Verze zadaná v klíči ModuleVersion se shoduje s názvem složky verze. + + + Složka verze {0} pod modulem {1} se přeskakuje, protože neobsahuje platný soubor manifestu modulu. + + + Člen ModuleName v tabulce hash popisující tento modul neexistuje. + + + Členy ModuleVersion, MaximumVersion a RequiredVersion v tabulce hash popisující tento modul neexistují. Jeden z těchto tří členů musí existovat a musí mu být přiřazeno číslo verze ve formátu n.n.n.n. + + + Požadovaný modul {1} není načtený. Načtěte modul nebo ho odeberte z RequiredModules v souboru {0}. + + + Požadovaný modul {1} s GUID {2} není načtený. Načtěte modul nebo ho odeberte z RequiredModules v souboru {0}. + + + Požadovaný modul {1} verze {2} není načtený. Načtěte modul nebo ho odeberte z RequiredModules v souboru {0}. + + + Požadovaný modul {1} s MaximumVersion {2} není načtený. Načtěte modul nebo ho odeberte z RequiredModules v souboru {0}. + + + Požadovaný modul {1} s MinimumVersion {2} a MaximumVersion {3} není načtený. Načtěte modul nebo ho odeberte z RequiredModules v souboru {0}. + + + Modul {0} s ModuleVersion {1} nejde najít. + + + Modul {0} s RequiredVersion {1} nejde najít. + + + Modul {0} s MaximumVersion {1} nejde najít. + + + Modul {0} s ModuleVersion {1} a MaximumVersion {2} nejde najít. + + + Modul {0} nejde najít. + + + Nebyly odebrány žádné moduly. Ověřte, že je zadání modulů k odebrání správné a že tyto moduly v runspace existují. + + + Člen {0}, který byl importován z modulu {1}, nejde odebrat z tohoto důvodu: {2} + + + Modul {0} nejde odebrat, protože je jen pro čtení. Pokud chcete odebrat moduly jen pro čtení, přidejte do příkazu parametr Force. + + + Modul {0} nejde odebrat, protože je označený jako konstanta. Modul nejde odebrat, pokud je označený jako konstanta. + + + Modul {0} nejde odebrat, protože ho vyžaduje {1}. Pokud chcete modul odebrat, přidejte do příkazu parametr Force. + + + Rutinu Export-ModuleMember je možné volat jen z modulu. + + + Přípona {0} není platná přípona modulu. Podporované přípony modulů jsou .dll, .ps1, .psm1, .psd1 a .cdxml. Opravte příponu a potom zkuste soubor {1} přidat znovu. + + + Tuto operaci nejde provést s binárním modulem. Je možné ji provést jen s modulem skriptu. + + + Soubor {0} není povolený, protože nemá příponu .ps1. + + + Neznámá + + + (c) {0}. Všechna práva vyhrazena. + + + Odebírá se importovaná funkce {0}. + + + Odebírá se importovaný alias {0}. + + + Odebírá se importovaná proměnná {0}. + + + Načítá se modul z cesty {0}. + + + Načítá se {0} z cesty {1}. + + + Načítá se soubor skriptu {0} pomocí operátoru dot-source. + + + Importuje se funkce {0}. + + + Importuje se rutina {0}. + + + Importuje se alias {0}. + + + Importuje se proměnná {0}. + + + Exportuje se rutina {0}. + + + Exportuje se funkce {0}. + + + Exportuje se alias {0}. + + + Exportuje se proměnná {0}. + + + Názvy některých importovaných příkazů z modulu {0} obsahují neschválená slovesa, takže se můžou hůř vyhledávat. Příkazy s neschválenými slovesy najdete tak, že znovu spustíte příkaz Import-Module s parametrem Verbose. Seznam schválených sloves zobrazíte zadáním Get-Verb. + + + Příkaz {0} v modulu {1} byl importován, ale protože jeho název neobsahuje schválené sloveso, může se obtížně hledat. Seznam schválených sloves zobrazíte zadáním Get-Verb. + + + Příkaz {0} v modulu {2} byl importován, ale protože jeho název neobsahuje schválené sloveso, může se obtížně hledat. Navrhovaná alternativní slovesa jsou {1}. + + + Některé názvy importovaných příkazů obsahují jeden nebo více z těchto zakázaných znaků: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Název příkazu {0} z modulu {1} obsahuje jeden nebo více z těchto zakázaných znaků: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Vytváří se soubor manifestu modulu {0}. + + + {0} (Cesta: {1}) + + + Aktuální architektura procesoru je: {0}. Modul {1} vyžaduje tuto architekturu: {2}. + + + Název aktuálního hostitele PowerShellu je: {0}. Modul {1} vyžaduje tohoto hostitele PowerShellu: {2}. + + + Aktuální hostitel PowerShellu je: {0} (verze {1}). Modul {2} vyžaduje ke spuštění minimálně hostitele PowerShellu verze {3}. + + + Manifest modulu pro modul {0} + + + Vygeneroval(a): {0} + + + Vygenerováno: {0} + + + Soubor modulu skriptu nebo binárního modulu přidružený k tomuto manifestu. + + + Moduly, které se mají importovat jako vnořené moduly modulu zadaného v RootModule/ModuleToProcess + + + ID sloužící k jedinečné identifikaci tohoto modulu + + + Autor tohoto modulu + + + Společnost nebo dodavatel tohoto modulu + + + Prohlášení o autorských právech k tomuto modulu + + + Číslo verze tohoto modulu. + + + Popis funkcí poskytovaných tímto modulem + + + Minimální verze prostředí PowerShell, kterou tento modul vyžaduje + + + Minimální verze prostředí Common Language Runtime (CLR), kterou tento modul vyžaduje. {0} + + + Moduly, které se musí importovat do globálního prostředí před importem tohoto modulu + + + Soubory skriptů (.ps1), které se spustí v prostředí volajícího před importem tohoto modulu. + + + Soubory typů (.ps1xml), které se mají načíst při importu tohoto modulu + + + Soubory formátu (.ps1xml), které se mají načíst při importu tohoto modulu + + + Sestavení, která se musí načíst před importem tohoto modulu + + + Seznam všech souborů zahrnutých v tomto modulu + + + Soukromá data, která se mají předat modulu zadanému v RootModule/ModuleToProcess. Můžou obsahovat také tabulku hash PSData s dalšími metadaty modulu používanými PowerShellem. + + + Značky použité na tento modul. Pomáhají s vyhledáváním modulů v online galeriích. + + + Adresa URL hlavního webu tohoto projektu. + + + Adresa URL licence pro tento modul. + + + Adresa URL ikony představující tento modul. + + + Poznámky k verzi tohoto modulu + + + Řetězec předběžné verze tohoto modulu + + + Příznak určující, jestli modul vyžaduje výslovný souhlas uživatele s instalací, aktualizací nebo uložením + + + Externí závislé moduly tohoto modulu + + + Konec tabulky hash {0} + + + Pokud chcete vytvořit manifest modulu s hodnotami parametrů Tags, ProjectUri, LicenseUri, IconUri nebo ReleaseNotes, musí být hodnota parametru PrivateData tabulka hash. Odeberte hodnoty parametrů Tags, ProjectUri, LicenseUri, IconUri nebo ReleaseNotes, nebo obsah PrivateData uzavřete do tabulky hash. + + + PrivateData by měla být definována jako tabulka hash, ale tento manifest modulu ji definuje jako objekt. Zvažte uzavření obsahu PrivateData do tabulky hash. Díky tomu budete moct později přidat do manifestu modulu vlastnosti Tags, ProjectUri, LicenseUri, IconUri a ReleaseNotes. + + + Zadaná hodnota {0} není platná. Zkuste to znovu s platnou hodnotou. + + + Funkce, které se mají z tohoto modulu exportovat. Kvůli nejlepšímu výkonu nepoužívejte zástupné znaky ani položku neodstraňujte. Pokud se nemají exportovat žádné funkce, použijte prázdné pole. + + + Aliasy, které se mají z tohoto modulu exportovat. Kvůli nejlepšímu výkonu nepoužívejte zástupné znaky ani položku neodstraňujte. Pokud se nemají exportovat žádné aliasy, použijte prázdné pole. + + + Rutiny, které se mají z tohoto modulu exportovat. Kvůli nejlepšímu výkonu nepoužívejte zástupné znaky ani položku neodstraňujte. Pokud se nemají exportovat žádné rutiny, použijte prázdné pole. + + + Proměnné, které se mají z tohoto modulu exportovat + + + Prostředky DSC, které se mají z tohoto modulu exportovat + + + Podporované PSEditions + + + Architektura procesoru (None, X86, Amd64) vyžadovaná tímto modulem + + + Seznam všech modulů zahrnutých v tomto modulu + + + Minimální verze Microsoft .NET Frameworku, kterou tento modul vyžaduje. {0} + + + Název hostitele PowerShellu vyžadovaného tímto modulem + + + Minimální verze hostitele PowerShellu vyžadovaná tímto modulem + + + Identifikátor URI HelpInfo tohoto modulu + + + Protože modul {0} poskytuje v aktuální relaci PowerShellu jednotku PSDrive, nebyly odebrány žádné moduly. Změňte aktuálního poskytovatele PSDrive a potom zkuste moduly odebrat znovu. + + + Rutina {0} nebyla importována, protože v aktuálním oboru existuje člen se stejným názvem. + + + Alias {0} nebyl importován, protože v aktuálním oboru existuje člen se stejným názvem. + + + Funkce {0} nebyla importována, protože v aktuálním oboru existuje člen se stejným názvem. + + + Proměnná {0} nebyla importována, protože v aktuálním oboru existuje člen se stejným názvem. + + + Zástupné znaky nejsou v členech ModuleToProcess, RootModule ani NestedModules v manifestu modulu {0} povolené. + + + Modul {0} je základní modul PowerShellu. Pokud chcete odebrat základní moduly, přidejte do příkazu parametr Force. + + + Manifest modulu nemůže obsahovat současně členy ModuleToProcess a RootModule. V souboru manifestu modulu v umístění {0} odeberte jeden z těchto členů a potom to zkuste znovu. + + + Člen ModuleToProcess manifestu modulu je zastaralý. Místo něj použijte člen RootModule. + + + Výchozí předpona pro příkazy exportované z tohoto modulu. Výchozí předponu můžete přepsat pomocí Import-Module -Prefix. + + + Parametry Global a Scope nejde zadat současně. Odeberte jeden z těchto parametrů a potom zkuste příkaz spustit znovu. + + + Požadovaný modul {0} není načtený. Modul {0} má požadovaný modul {1} uvedený v manifestu modulu {2}, který odkazuje na cyklickou závislost. + + + Požadovaný modul {0} nebyl načten, protože v žádném adresáři modulů nebyl nalezen platný soubor modulu. + + + Některé příkazy z modulu {0} nejde importovat přes CimSession. Pokud chcete získat všechny příkazy, ověřte, že je na vzdáleném serveru povolená vzdálená správa PowerShellu, a potom zkuste přidat parametr PSSession do rutiny Import-Module. + + + Modul {0} je načtený ve Windows PowerShellu pomocí vzdálené relace {1}. Upozorňujeme, že veškerý vstup a výstup příkazů z tohoto modulu bude ve formě deserializovaných objektů. Pokud chcete tento modul načíst do PowerShellu, použijte syntaxi Import-Module -SkipEditionCheck. + + + Byla zjištěna verze Windows PowerShellu {0}. K načítání modulů pomocí funkce kompatibility s Windows PowerShellem je vyžadován Windows PowerShell 5.1. Nainstalujte Windows Management Framework (WMF) 5.1 z adresy https://aka.ms/WMF5Download a povolte tak tuto funkci. + + + Načtení modulu {0} pomocí funkce kompatibility s Windows PowerShellem blokuje nastavení WindowsPowerShellCompatibilityModuleDenyList v konfiguračním souboru PowerShellu. + + + Modul {0} nejde importovat přes CimSession. Zkuste použít parametr PSSession rutiny Import-Module. + + + Hodnota architektury procesoru {0} není podporovaná. Spusťte příkaz New-ModuleManifest znovu a pro architekturu procesoru zadejte jednu z těchto podporovaných hodnot výčtu: None, MSIL, X86, Amd64, Arm + + + Rutina Get-Module spuštěná vůči vzdálenému počítači může jen vypsat dostupné moduly. Přidejte do příkazu parametr ListAvailable a potom to zkuste znovu. + + + Modul {0} nebyl importován, protože modul snap-in {0} už byl importován. + + + Zástupné znaky nejsou v členu RequiredAssemblies v manifestu modulu {0} povolené. + + + Hodnota klíče {0} v {1} je {2} a modul má vnořené moduly. Když je kořenovým modulem soubor CDXML, příkaz Import-Module selže, protože příkazy ve vnořených modulech nejde exportovat. Přesuňte soubor CDXML do klíče NestedModules a zkuste příkaz znovu. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Chyba vzdáleného příkazu: {0}: {{0}} + + + Nepovedlo se vygenerovat proxy pro vzdálený modul {0}. {{0}} + + + Nepovedlo se zpracovat vzdálený modul {0}. {1} + + + Nepovedlo se přijmout data modulu ze vzdálené relace CimSession. {0} + + + Požadovaný modul {0} s GUID {1} a verzí {2} nebyl načten, protože v žádném adresáři modulů nebyl nalezen platný soubor modulu. + + + Na serveru CIM nebyl nalezen poskytovatel CIM pro zjišťování modulů. {0} + {0} is a placeholder for a more detailed error message + + + Verzi Microsoft .NET Frameworku {0} nejde ověřit, protože není uvedená v seznamu povolených verzí. + + + Analyzuje se {0}. + {0} should not be localized, is used to contain a file path. + + + Připravují se moduly pro první použití. + + + Hledají se dostupné moduly + + + Prohledává se sdílená složka UNC {0}. + {0} should not be localized, is used to contain a file path. + + + Rutinu Get-Module je možné spustit vůči vzdálenému počítači jen pro názvy modulů, které neobsahují cestu. Parametr Name obsahuje prvek {0}, který se překládá na cestu. Aktualizujte parametr Name tak, aby neobsahoval prvky cesty, a potom to zkuste znovu. + + + Spuštění rutiny Get-Module bez parametru ListAvailable není podporováno u názvů modulů, které obsahují cestu. Parametr Name obsahuje prvek {0}, který se překládá na cestu. Aktualizujte parametr Name tak, aby neobsahoval prvky cesty, a potom to zkuste znovu. + + + Zadaný modul {0} nebyl nalezen. Aktualizujte parametr Name tak, aby odkazoval na platnou cestu, a potom to zkuste znovu. + + + Vyplňuje se vlastnost RepositorySourceLocation pro modul {0}. + + + Modul ke zpracování {0}, uvedený v poli {1} manifestu modulu {2}, nebyl zpracován. {3} + + + Tento předpoklad platí jen pro edici PowerShell Desktop. + + + Modul {0} nepodporuje aktuální edici PowerShellu {1}. Podporované edice jsou {2}. Kompatibilitu tohoto modulu můžete ignorovat pomocí Import-Module -SkipEditionCheck. + + + Modul {0} podporuje edici PowerShellu {1} a nejde ho implicitně načíst pomocí funkce Kompatibilita s Windows, protože je v souboru nastavení zakázaná. Tento modul můžete načíst s Windows PowerShellem pomocí Import-Module -UseWindowsPowerShell nebo se ho pokusit načíst v aktuálním PowerShellu pomocí Import-Module -SkipEditionCheck. + + + Pro experimentální funkci deklarovanou v manifestu modulu zadejte neprázdnou řetězcovou hodnotu. + + + Byl nalezen jeden nebo více neplatných názvů experimentálních funkcí: {0}. Název experimentální funkce modulu by měl dodržovat tento formát: ModuleName.FeatureName. + + + Přepínací parametr -SkipEditionCheck nejde použít bez přepínacího parametru -ListAvailable. + + + Import souborů *.ps1 jako modulů není v režimu ConstrainedLanguage povolený. + + + Při načítání modulu skriptu {0} došlo k chybě, protože má jiný jazykový režim než manifest modulu. Jazykový režim manifestu je {1} a jazykový režim modulu je {2}. Ověřte, že jsou všechny soubory modulu podepsané nebo jinak zahrnuté v konfiguraci seznamu povolených aplikací. + + + Tento modul při exportu funkcí pomocí zástupných znaků používá operátor dot-source. To není povolené, pokud systém vynucuje ověřování aplikací. + + + Členy modulu nejde exportovat z modulu, který má jiný jazykový režim než spuštěná relace. + + + V režimu ConstrainedLanguage nejde vytvořit nový modul. + + + Nejde najít předdefinovaný modul {0}, který je kompatibilní s edicí Core. Ověřte, že jsou předdefinované moduly PowerShellu dostupné. Obvykle jsou součástí balíčku PowerShellu v cestě modulu $PSHOME a PowerShell je potřebuje ke správnému fungování. + + + Rutina Export-ModuleMember + + + Export členů modulu v režimu Constrained Language selže, protože modul {0} má jazykový režim {1}, který se liší od aktuální relace {2}. + + + Implicitní export funkcí modulu + + + Implicitní export funkcí modulu {0} bude zamítnut, protože modul je důvěryhodný (běží v režimu Full Language), ale relace důvěryhodná není (běží v režimu Constrained Language). Osvědčeným postupem je vždy exportovat funkce modulu jednotlivě pod úplným názvem. + + + Import souboru skriptu jako modulu + + + Import souboru skriptu {0} jako modulu nebude v režimu ConstrainedLanguage povolený. + + + Modul obsahuje operátor dot-source + + + Import modulu {0} v režimu ConstrainedLanguage selže, protože modul exportuje funkce pomocí zástupných znaků a zároveň používá operátor dot-source. + + + Funkce exportované modulem + + + Modul {0} exportuje funkce pomocí zástupných znaků v názvech. Při spuštění v režimu Constrained Language se odeberou všechny názvy funkcí vnořených modulů. + + + Rutina New-Module + + + Novému modulu z nedůvěryhodné relace Constrained Language bude zablokováno poskytování bloku skriptu FullLanguage. + + + Neshodné jazykové režimy modulu + + + Načítá se závislý modul, který má jiný jazykový režim než nadřazený modul. V režimu Constrained Language to nebude povolené. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/MshHostRawUserInterfaceStrings.cs.resx b/src/System.Management.Automation/resources/cs/MshHostRawUserInterfaceStrings.cs.resx new file mode 100644 index 00000000000..c34d5c5f02b --- /dev/null +++ b/src/System.Management.Automation/resources/cs/MshHostRawUserInterfaceStrings.cs.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}“ musí být větší než {1} nebo se musí této hodnotě rovnat. + + + „{0}“ musí být kladné číslo. + + + Všechny řetězce jsou null nebo prázdné. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/MshSignature.cs.resx b/src/System.Management.Automation/resources/cs/MshSignature.cs.resx new file mode 100644 index 00000000000..c8678bf0687 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/MshSignature.cs.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 + + + Podpis byl ověřený. + + + Soubor {0} není digitálně podepsaný. Tento skript nejde v aktuálním systému spustit. Další informace o spouštění skriptů a nastavení zásad spouštění najdete v tématu about_Execution_Policies na adrese https://go.microsoft.com/fwlink/?LinkID=135170 + + + Obsah souboru {0} mohla změnit neoprávněná osoba nebo proces, protože hodnota hash souboru neodpovídá hodnotě hash uložené v digitálním podpisu. Skript nejde v zadaném systému spustit. Další informace zobrazíte spuštěním Get-Help about_Signing. + + + Soubor {0} je podepsaný, ale podepisující osoba není v tomto systému důvěryhodná. + + + Soubor nejde podepsat, protože systém nepodporuje podepisování souborů typu {0}. + + + Soubor nejde podepsat, protože systém nepodporuje podepisování souborů bez přípony názvu souboru. + + + Podpis nejde ověřit, protože není kompatibilní s aktuálním systémem. + + + Podpis nejde ověřit, protože není kompatibilní s aktuálním systémem. Hashovací algoritmus není platný. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/MshSnapInCmdletResources.cs.resx b/src/System.Management.Automation/resources/cs/MshSnapInCmdletResources.cs.resx new file mode 100644 index 00000000000..89cbbc304d3 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/MshSnapInCmdletResources.cs.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 + + + Operaci nejde provést. Zadaná rutina není ve vlastním prostředí shellu podporovaná. + + + Nenašly se žádné moduly snap-in PowerShellu odpovídající vzoru {0}. Zkontrolujte vzor a spusťte příkaz znovu. + + + Formát zadaného názvu modulu snap-in není platný. Názvy modulů snap-in PowerShellu můžou obsahovat jen alfanumerické znaky, pomlčky, podtržítka a tečky. Opravte název a potom operaci zopakujte. + + + Modul snap-in PowerShellu {0} nejde přidat, protože jde o systémový modul PowerShellu. Načtěte modul pomocí Import-Module. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/MshSnapinInfo.cs.resx b/src/System.Management.Automation/resources/cs/MshSnapinInfo.cs.resx new file mode 100644 index 00000000000..bf9a824782a --- /dev/null +++ b/src/System.Management.Automation/resources/cs/MshSnapinInfo.cs.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 + + + K informacím registru PowerShellu nejde získat přístup. + + + K informacím registru jádra PowerShellu nejde získat přístup. + + + K informacím PublicKeyToken nejde získat přístup. + + + Verze PowerShellu {0} není v tomto počítači k dispozici. + + + Modul snap-in PowerShellu {0} není v tomto počítači nainstalovaný. + + + Povinná hodnota {0} není pro klíč registru {1} zadaná. + + + Povinná hodnota {0} nemá správný formát pro klíč registru {1}. Očekává se formát string. + + + Povinná hodnota {0} nemá správný formát pro klíč registru {1}. Očekává se formát multistring. + + + V registru se nenašly požadované informace nebo chybí soubory klíčů. Některé rutiny nejdou načíst. + + + Pro PowerShell verze {0} nejsou zaregistrované žádné moduly snap-in. + + + Řetězcový prostředek nejde načíst, protože čtečka byla uvolněna. + + + Hodnota verze {0} není zadaná nebo není správná pro klíč registru {1}. + + + Pro typ PowerShellu {0} se nenašel žádný atribut [PSVersion]. Přidejte k typu atribut PSVersion pomocí [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/NativeCP.cs.resx b/src/System.Management.Automation/resources/cs/NativeCP.cs.resx new file mode 100644 index 00000000000..8095274f0db --- /dev/null +++ b/src/System.Management.Automation/resources/cs/NativeCP.cs.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 + + + ScriptBlock by měl být zadaný jen jako hodnota parametru Command. + + + Pro parametr Command nebyla zadána žádná hodnota. + + + Neplatná hodnota ({6}) byla zadána pro parametr {7}. Platné hodnoty jsou Text a Xml. + + + Pro parametr InputFormat nebyla zadána žádná hodnota. Platné hodnoty jsou Text a Xml. + + + Pro parametr OutputFormat nebyla zadána žádná hodnota. Platné hodnoty jsou text a XML. + + + Parametr {6} vyžaduje řetězcovou hodnotu. + + + Pro parametr Args nebyla zadána žádná hodnota. + + + Parametr {6} už byl zadaný. + + + XML z proudu {0} objektu {1} nejde zpracovat: {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PSCommandStrings.cs.resx b/src/System.Management.Automation/resources/cs/PSCommandStrings.cs.resx new file mode 100644 index 00000000000..c621b08929b --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PSCommandStrings.cs.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 + + + K přidání parametru je nutný příkaz. Před přidáním parametru je nutné přidat příkaz do {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PSConfigurationStrings.cs.resx b/src/System.Management.Automation/resources/cs/PSConfigurationStrings.cs.resx new file mode 100644 index 00000000000..900b72e9fc1 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PSConfigurationStrings.cs.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 + + + PowerShell přestal fungovat kvůli problému se zabezpečením: Konfigurační soubor nejde přečíst: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PSDataBufferStrings.cs.resx b/src/System.Management.Automation/resources/cs/PSDataBufferStrings.cs.resx new file mode 100644 index 00000000000..0ce597bb9e5 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PSDataBufferStrings.cs.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 + + + Zadaný index je menší než nula nebo větší než počet položek ve vyrovnávací paměti. Index musí být v rozsahu {0}–{1}. + + + Odkaz s hodnotou null nejde převést na hodnotový typ. + + + Hodnotu typu {0} nejde převést na typ {1}. + + + Do zavřené vyrovnávací paměti nejde přidávat objekty. Aby operace Add a Insert proběhly úspěšně, musí být vyrovnávací paměť otevřená. + + + Vlastnost SerializeInput jde nastavit jen pro typ PSObject kolekce PSDataCollection. Nastavte vlastnost SerializeInput na false nebo změňte typ kolekce na PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PSListModifierStrings.cs.resx b/src/System.Management.Automation/resources/cs/PSListModifierStrings.cs.resx new file mode 100644 index 00000000000..2edb5f0c8de --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PSListModifierStrings.cs.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 + + + Zjistil se následující neznámý modifikátor seznamu: {0}. Platné modifikátory seznamu jsou Add, Remove a Replace. + + + Aktualizaci nejde použít, protože objekt není podporovaným typem kolekce. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PSStyleStrings.cs.resx b/src/System.Management.Automation/resources/cs/PSStyleStrings.cs.resx new file mode 100644 index 00000000000..ef47268d733 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PSStyleStrings.cs.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Zadaný řetězec obsahuje tisknutelný obsah, i když smí obsahovat jen řídicí sekvence ANSI: {0} + + + Aby se průběh vykreslil správně, musí být hodnota MaxWidth alespoň 18. + + + Při přidávání nebo odebírání přípon musí přípona začínat tečkou. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ParameterBinderStrings.cs.resx b/src/System.Management.Automation/resources/cs/ParameterBinderStrings.cs.resx new file mode 100644 index 00000000000..726cdb04f43 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ParameterBinderStrings.cs.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nenašel se parametr odpovídající názvu parametru {1}. + + + Nenašel se poziční parametr, který přijímá argument {1}. + + + Chybí argument parametru {1}. Zadejte parametr typu {2} a zkuste to znovu. + + + Parametr nejde zpracovat, protože název parametru {1} je nejednoznačný. Mezi možné shody patří:{6}. + + + Hodnotu {6} nejde převést na typ {2} požadovaný parametrem {1}. {7} + + + Parametr {1} nejde svázat. {6} + + + Poziční parametry {1} nejdou svázat. + + + Poziční parametry nejdou svázat, protože nebyly zadané žádné názvy. + + + Sadu parametrů nelze pomocí zadaných pojmenovaných parametrů rozlišit. Jeden nebo více zadaných parametrů nejde použít společně, případně nebyl zadán dostatečný počet parametrů. + + + Příkaz nejde zpracovat, protože chybí jeden nebo více povinných parametrů:{1}. + + + Parametr {1} nejde zadat v sadě parametrů {6}. + + + Parametr nejde svázat, protože parametr {1} je zadaný více než jednou. Chcete-li parametrům, které přijímají více hodnot, předat několik hodnot, použijte syntaxi pole. Například -parameter value1,value2,value3. + + + Parametr {1} nejde vyhodnotit, protože jeho argument je zadaný jako blok skriptu a není k dispozici žádný vstup. Blok skriptu nejde vyhodnotit bez vstupu. + + + Vstup bloku skriptu pro parametr {1} selhal. {6} + + + Parametr {1} nejde vyhodnotit, protože vstup jeho argumentu nevytvořil žádný výstup. + + + Vstupní objekt nejde svázat s žádným parametrem příkazu. Příkaz buď nepřijímá vstup z kanálu, nebo vstup a jeho vlastnosti neodpovídají žádnému parametru přijímajícímu vstup z kanálu. + + + Vstupní objekt nejde svázat, protože neobsahuje informace potřebné ke svázání všech povinných parametrů: {6} + + + Vstup z kanálu nejde zpracovat, protože se nepovedlo načíst výchozí hodnotu parametru {1}. {6} + + + Dynamické parametry rutiny nejde načíst. {6} + + + Zadejte hodnoty následujících parametrů: + + + Rutina {0} na pozici {1} v kanálu příkazů + + + Transformaci argumentu parametru {1} nejde zpracovat. {6} + + + {6} + + + Argument parametru {1} nejde ověřit. {6} + + + Parametr {1} nejde svázat s cílem. {6} + + + Argument nejde svázat s parametrem {1}, protože má hodnotu null. + + + Argument nejde svázat s parametrem {1}, protože jde o prázdný řetězec. + + + Argument nejde svázat s parametrem {1}, protože jde o prázdnou kolekci. + + + Argument nejde svázat s parametrem {1}, protože jde o prázdné pole. + + + Nepovedlo se zpracovat příkaz. Parametr {0} je definovaný vícekrát. + + + Rutinu {0} nejde svázat, protože parametr {1} je typu {2} a metodu Add() nejde určit, nebo existuje několik metod Add(). {6} + + + Rutinu {0} nejde svázat, protože parametr {1} definovaný za běhu byl přidán do RuntimeDefinedParameterDictionary s klíčem {6}. Klíč musí být stejný jako RuntimeDefinedParameter.Name. + + + Argument nejde svázat s parametrem {1}, protože hodnoty PSTypeNames argumentu neodpovídají hodnotě PSTypeName požadované parametrem: {6}. + + + V $PSDefaultParameterValues je pro parametr odpovídající následujícímu názvu nebo aliasu definováno několik různých výchozích hodnot: {0}. Tyto výchozí hodnoty byly ignorovány. + + + Následující název nebo alias definovaný pro tuto rutinu v $PSDefaultParameterValues odpovídá více parametrům: {0}. Výchozí hodnota byla ignorována. + + + {6} Tato chyba mohla být způsobená použitím výchozí vazby parametrů. Výchozí vazbu parametrů můžete v $PSDefaultParameterValues zakázat nastavením $PSDefaultParameterValues["Disabled"] na $true a potom to zkusit znovu. Při výskytu chyby byly pro tuto rutinu úspěšně svázány následující výchozí parametry:{7} + + + {6} Toto selhání mohlo být způsobené použitím výchozí vazby parametrů. Výchozí vazbu parametrů můžete v $PSDefaultParameterValues zakázat nastavením $PSDefaultParameterValues["Disabled"] na $true a potom akci zopakovat. Při výskytu chyby byl pro tuto rutinu úspěšně svázán následující výchozí parametr:{7} + + + Vazba výchozí hodnoty {0} na parametr {1} selhala: {2} + + + Klíč {0} nemá platný formát. Informace o správném formátu najdete v tématu about_Parameters_Default_Values na adrese https://go.microsoft.com/fwlink/?LinkId=228266. + + + Klíče {0} nemají platný formát. Informace o správném formátu najdete v tématu about_Parameters_Default_Values na adrese https://go.microsoft.com/fwlink/?LinkId=228266. + + + Parametr {0} je zastaralý. {1} + + + Klíč {0} typu {1} není řetězcová hodnota. DefaultParameterDictionary přijímá jen klíče s řetězcovou hodnotou. + + + Klíč {0} už byl přidán do slovníku. + + + Volání metody nebo vlastnosti není povolené + + + Volání metody nebo vlastnosti {0} u typu {1} nebude v režimu omezeného jazyka povolené pro nedůvěryhodné skripty. + + + Vytvoření typu není povolené + + + Vytvoření typu {0} nebude při vazbě parametrů v režimu omezeného jazyka povolené pro nedůvěryhodné skripty. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ParserStrings.cs.resx b/src/System.Management.Automation/resources/cs/ParserStrings.cs.resx new file mode 100644 index 00000000000..ad629ff5a40 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ParserStrings.cs.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Nejde načíst sestavení {0}. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PathUtilsStrings.cs.resx b/src/System.Management.Automation/resources/cs/PathUtilsStrings.cs.resx new file mode 100644 index 00000000000..cd247712a8d --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PathUtilsStrings.cs.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Kódování UTF-7 je zastaralé, použijte prosím UTF-8. + + + Soubor {0} již existuje a už bylo zadáno: {1}. + + + Soubor nejde otevřít, protože aktuální poskytovatel ({0}) nemůže otevřít soubor. + + + Operaci nelze provést, protože cesta byla přeložena na více než jeden soubor. Tento příkaz nemůže pracovat s více soubory. + + + Operaci nelze provést, protože cesta se zástupnými znaky {0} nebyla přeložena na soubor. + + + Neznámé kódování {0}; platné hodnoty jsou {1}. + + + Adresář {0} už existuje. Pokud chcete přepsat adresář a soubory v adresáři, použijte parametr -Force. + + + Cesta k uživatelskému modulu neexistuje, a proto nelze vytvořit složku modulu pro zadaný název modulu {0}. + + + Modul {0} nelze vytvořit z následujícího důvodu: {1}. Pro parametr -OutputModule použijte jiný argument a zkuste to znovu. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Modul nelze načíst, protože byl vygenerován s nekompatibilní verzí rutiny {0}. Vygenerujte modul pomocí rutiny {0} z aktuální relace a zkuste modul načíst znovu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PipelineStrings.cs.resx b/src/System.Management.Automation/resources/cs/PipelineStrings.cs.resx new file mode 100644 index 00000000000..4623ca17333 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PipelineStrings.cs.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Instanci rutiny nelze zpracovat, protože ji používá jiný kanál. Obraťte se na služby zákaznické podpory Microsoftu. + + + Operaci nelze provést, protože je kanál spuštěný. Zastavte kanál a zkuste operaci zopakovat. + + + V provádění rutiny nelze pokračovat, protože zásada Stop zabránila spouštění rutin. + + + Kanál nelze spustit, protože se první rutina v kanálu pokouší číst vstup z výsledků předchozí rutiny. Upravte první rutinu, odeberte první rutinu nebo do kanálu přidejte rutinu, jejíž výstup první rutina vyžaduje, a potom zkuste kanál spustit znovu. + + + Číslo rutiny nelze zpracovat. Funkce ReadFromCommand musí zadat ID rutiny, která už byla přidána do kanálu. Obraťte se na služby zákaznické podpory Microsoftu. + + + Výstup funkcí ReadFromCommand a ReadErrorQueue nelze číst, protože jej už čte jiná rutina. Obraťte se na služby zákaznické podpory Microsoftu. + + + Kanál nelze spustit, protože neobsahuje žádné příkazy. Přidejte do kanálu alespoň jeden příkaz a potom jej spusťte znovu. + + + Operaci kanálu nelze dokončit, protože ještě nebyla spuštěna. Před voláním metody End() u krokovatelného kanálu je nutné zavolat metodu Begin(). + + + Metody WriteObject a WriteError nelze volat mimo přepsané metody BeginProcessing, ProcessRecord a EndProcessing a lze je volat pouze ze stejného vlákna. Ověřte, že rutina tato volání provádí správně, nebo se obraťte na služby zákaznické podpory Microsoftu. + + + Po volání ThrowTerminatingError vyvolala rutina výjimku. +První výjimka byla {0} s trasováním zásobníku {1}. +Druhá výjimka byla {2} s trasováním zásobníku {3}. + + + Metody WriteObject a WriteError nelze volat po uzavření kanálu. Obraťte se na služby zákaznické podpory Microsoftu. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Při vytváření kanálu došlo k chybě. + + + Tento kanál nepodporuje sémantiku odpojení a opětovného připojení. + + + Tento kanál nelze připojit, protože není v odpojeném stavu. + + + Objekt prostředí runspace má přidružený vzdálený příkaz s hodnotou null. Odpojený objekt RemotePipeline nelze vytvořit, protože není zadán žádný vzdálený příkaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/PowerShellStrings.cs.resx b/src/System.Management.Automation/resources/cs/PowerShellStrings.cs.resx new file mode 100644 index 00000000000..f7592f422fc --- /dev/null +++ b/src/System.Management.Automation/resources/cs/PowerShellStrings.cs.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 + + + Stav aktuální instance PowerShellu není pro tuto operaci platný. + + + Operaci nejde provést, protože příkaz už byl spuštěný. Počkejte na dokončení příkazu nebo ho zastavte a potom operaci zopakujte. + + + Nejsou zadané žádné příkazy. + + + Instance PowerShellu není ve správném stavu pro vytvoření vnořené instance PowerShellu. Vnořené instance PowerShellu se mají vytvářet jen ve spuštěné instanci PowerShellu. + + + Operaci nejde provést, protože prostředí runspace není ve stavu {0}. Aktuální stav prostředí runspace je {1}. + + + Vnořené instance PowerShellu nejde vyvolat asynchronně. Použijte metodu Invoke. + + + Objekt {0} nebyl vytvořený voláním {1} v této instanci PowerShellu. + + + Když je prostředí runspace nastavené na opakované použití vlákna, musí stav apartmentu v nastavení vyvolání odpovídat prostředí runspace. + + + Když je prostředí runspace nastavené na použití aktuálního vlákna, musí stav apartmentu v nastavení vyvolání odpovídat aktuálnímu vláknu. + + + K přidání parametru je nutný příkaz. Před přidáním parametru je potřeba do instance PowerShellu přidat příkaz. + + + Klíče ve slovníku musí být řetězce. + + + V tomto vlákně není k dispozici žádné prostředí Runspace pro spouštění příkazů. Můžete ho zadat ve vlastnosti DefaultRunspace typu System.Management.Automation.Runspaces.Runspace. Pokusili jste se vyvolat tento příkaz: {0} + + + Tento objekt PowerShellu nejde připojit, protože není přidružený ke vzdálenému prostředí runspace ani fondu runspace. + + + Spuštěný příkaz byl odpojený, ale na vzdáleném serveru stále běží. Znovu se připojte, abyste získali stav operace příkazu a výstupní data. + + + Operaci nejde provést, protože aktuální relace PowerShellu je ve stavu Disconnected. Připojte tuto relaci PowerShellu a potom počkejte na dokončení příkazu nebo příkaz zastavte. + + + Operaci nejde provést, protože aktuální relace PowerShellu je ve stavu Disconnected. Připojte tuto relaci PowerShellu a zkuste to znovu. + + + Pokus o připojení ke vzdálenému příkazu selhal. + + + Operaci nejde provést, protože se příkaz právě zastavuje. Počkejte, až se příkaz zastaví, a potom operaci zopakujte. + + + V tomto vlákně není k dispozici žádné prostředí Runspace pro spouštění příkazů. Můžete ho zadat ve vlastnosti DefaultRunspace typu System.Management.Automation.Runspaces.Runspace. Aktuální instance PowerShellu neobsahuje žádný příkaz k vyvolání. + + + Objekt PowerShellu, který používá aktuální prostředí runspace, nejde vytvořit, protože žádné aktuální prostředí runspace není k dispozici. Aktuální prostředí runspace se možná spouští, například když bylo vytvořené s počátečním stavem relace. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ProgressRecordStrings.cs.resx b/src/System.Management.Automation/resources/cs/ProgressRecordStrings.cs.resx new file mode 100644 index 00000000000..2c1f6819199 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ProgressRecordStrings.cs.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Argument nejde zpracovat, protože hodnota {0} nemůže být záporná. + + + Argument nejde zpracovat, protože hodnota {0} nemůže být null ani prázdná. + + + Procento nejde nastavit, protože {0} nemůže být větší než 100. + + + ParentActivityId se nesmí shodovat s ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ProviderBaseSecurity.cs.resx b/src/System.Management.Automation/resources/cs/ProviderBaseSecurity.cs.resx new file mode 100644 index 00000000000..397f0645db2 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ProviderBaseSecurity.cs.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 + + + Rozhraní nelze použít, protože rozhraní ISecurityDescriptorCmdletProvider není tímto zprostředkovatelem podporováno. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/ProxyCommandStrings.cs.resx b/src/System.Management.Automation/resources/cs/ProxyCommandStrings.cs.resx new file mode 100644 index 00000000000..6abc59d7291 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/ProxyCommandStrings.cs.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 + + + Parametr help nebyl rozpoznán jako platný objekt HelpInfo vytvořený příkazem get-help. + + + Příkaz proxy nejde vygenerovat, protože CommandMetadata nemá název. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/RegistryProviderStrings.cs.resx b/src/System.Management.Automation/resources/cs/RegistryProviderStrings.cs.resx new file mode 100644 index 00000000000..93a4b974a2c --- /dev/null +++ b/src/System.Management.Automation/resources/cs/RegistryProviderStrings.cs.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nastavit položku + + + Položka: {0} Hodnota: {1} + + + Vymazat položku + + + Položka: {0} + + + Nová položka + + + Položka: {0} + + + Odebrat klíč + + + Položka: {0} + + + Kopírovat klíč + + + Položka: {0} Cíl: {1} + + + Přejmenovat položku + + + Položka: {0} Nový název: {1} + + + Přesunout položku + + + Položka: {0} Cíl: {1} + + + Nastavit vlastnost + + + Položka: {0} Vlastnost: {1} + + + Vymazat vlastnost + + + Položka: {0} Vlastnost: {1} + + + Nová vlastnost + + + Položka: {0} Vlastnost: {1} + + + Odebrat vlastnost + + + Položka: {0} Vlastnost: {1} + + + Přejmenovat vlastnost. + + + Položka: {0} Zdrojová vlastnost: {1} Cílová vlastnost: {2} + + + Kopírovat vlastnost + + + Položka: {0} Zdrojová vlastnost: {1} Cílová položka: {2} Cílová vlastnost: {3} + + + Přesunout vlastnost + + + Položka: {0} Zdrojová vlastnost: {1} Cílová položka: {2} Cílová vlastnost: {3} + + + Operace nebyla zpracována. Zadané umístění tuto operaci nepovoluje. + + + Operace není ve zdrojovém umístění povolená. + + + Operace není v cílovém umístění povolená. + + + Nastavení konfigurace pro místní počítač + + + Nastavení softwaru pro aktuálního uživatele + + + Klíč v této cestě už existuje. + + + Operaci nejde provést, protože cílová cesta je podřízená zdrojové cestě. + + + Vlastnost už existuje. + + + Vlastnost {0} na cestě {1} neexistuje. + + + Klíč registru na zadané cestě neexistuje. + + + Parametr Type se nepovedlo svázat. Hodnotu {0} se nepovedlo převést na {1}. Možné hodnoty výčtu jsou String, ExpandString, Binary, DWord, MultiString, QWord, Unknown. + + + Klíč {0} byl vytvořený, ale nepovedlo se nastavit výchozí hodnotu. + + + Jednotku se zadaným kořenovým adresářem nejde vytvořit. Kořenová cesta neexistuje. + + + Položku nejde přejmenovat, protože ve stejném kontejneru už existuje položka s tímto názvem. + + + Název klíče registru musí začínat platným názvem základního klíče. + + + Argument podklíče není platný. + + + Strom podklíčů nejde odstranit, protože podklíč neexistuje. + + + Hodnota s tímto názvem neexistuje. + + + Hodnota výčtu {0} není platná. + + + Musí být zadaný argument hodnoty. + + + Musí být zadaný argument názvu. + + + Zadaná hodnota RegistryValueKind není platná. + + + RegistryKey.SetValue nepovoluje String[], které obsahuje řetězcový odkaz s hodnotou null. + + + Podklíče registru nesmí být delší než 255 znaků. + + + Musí být zadaný neprázdný název podklíče. + + + Typ objektu hodnoty neodpovídá zadanému RegistryValueKind nebo objekt nejde správně převést. + + + RegistryKey.SetValue nepodporuje pole typu {0}. Podporují se jen Byte[] a String[]. + + + Zadaný klíč registru neexistuje. + + + Délka zadaného názvu hodnoty překračuje maximum 16383 znaků. + + + Velikost zadaných dat hodnoty překračuje maximum 1 MB. + + + Zadaný podklíč registru neexistuje. + + + Zadaná hodnota RegistryKeyPermissionCheck není platná. + + + Klíč registru obsahuje podklíče. Tato metoda nepodporuje rekurzivní odebrání. + + + Popisovač KTM nejde vytvořit bez Transaction.Current nebo zadané transakce. + + + Zadaná transakce nebo Transaction.Current musí odpovídat transakci použité k vytvoření nebo otevření objektu TransactedRegistryKey. + + + Objekt TransactedRegistryKey není přidružený k transakci, protože se vztahuje k předdefinovanému klíči. + + + Požadovaný přístup k registru není povolený. + + + Přístup ke klíči registru {0} byl odepřen. + + + Do klíče registru nejde zapisovat. + + + K zavřenému klíči registru nejde získat přístup. + + + Neznámá chyba: {0}. + + + Transakce registru nejsou na této platformě podporované. + + + Zadaný popisovač není platný. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/RemotingErrorIdStrings.cs.resx b/src/System.Management.Automation/resources/cs/RemotingErrorIdStrings.cs.resx new file mode 100644 index 00000000000..ffc292032d5 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/RemotingErrorIdStrings.cs.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Došlo k chybě typu {0}. + + + Nedostatek paměti pro procesy. + + + Výčet vzdálené relace PSSession s -ComputerName je podporován pouze ve Windows, nikoli v{0}. + + + ID kanálu {0} neodpovídá ID instance aktuálně spuštěného kanálu {1}. + + + ID kanálu „{0}“ nebylo na serveru nalezeno. + + + Vzdálený kanál byl zastaven. + + + Relace již existuje. Opětovné vytvoření relace se stejným InstanceId {0} není povoleno. + + + Zadaná hodnota InstanceId relace klienta „{0}“ neodpovídá hodnotě InstanceId existující relace "{1}". + + + Otevření vzdálené relace se nezdařilo. + + + Zadanou vzdálenou relaci s InstanceId klienta „{0}“ nelze najít. + + + Odpověď na výzvu obsahuje ID výzvy „{0}“, které nelze najít. + + + Volání vzdáleného hostitele {0} se nezdařilo. + + + Metoda vzdáleného hostitele {0} není implementována. + + + Kódování dat metody vzdáleného hostitele se pro typ {0}nepodporuje. + + + Dekódování dat metody vzdáleného hostitele se pro typ {0}nepodporuje. + + + Vytváření vnořených kanálů se nepodporuje. + + + Relativní identifikátory URI se při vytváření vzdálených relací nepodporují. + + + Při dekódování dat ze vzdáleného hostitele došlo k chybě. V síťových datech došlo k chybě. + + + Možnosti vlákna mohou vzdáleně přepsat pouze správci. + + + Žádost o přihlašovací údaje k PowerShellu: {0} + + + Upozornění: Skript nebo aplikace na vzdáleném počítači {0} požaduje vaše přihlašovací údaje. Přihlašovací údaje zadejte pouze v případě, že důvěřujete vzdálenému počítači a aplikaci nebo skriptu, který je požaduje. + +{1} + + + Skript nebo aplikace na vzdáleném počítači {0} žádá o bezpečné zadání jednoho řádku. Citlivé informace, jako jsou vaše přihlašovací údaje, zadejte pouze v případě, že důvěřujete vzdálenému počítači a aplikaci nebo skriptu, který o to žádá. + + + Skript nebo aplikace na vzdáleném počítači {0} se pokouší přečíst obsah vyrovnávací paměti na hostiteli PowerShellu. Z bezpečnostních důvodů to není povoleno; volání bylo potlačeno. + + + Skript nebo aplikace na vzdáleném počítači {0} odesílá požadavek na výzvu. Po zobrazení výzvy zadejte citlivé informace, jako jsou přihlašovací údaje nebo hesla, pouze pokud důvěřujete vzdálenému počítači a aplikaci nebo skriptu, který požaduje data. + + + Přijato nepodporované volání vzdáleného hostitele: {0}. + + + Byla přijata data vzdálené komunikace s nepodporovanou akcí: {0}. + + + Byla přijata data vzdálené komunikace s nepodporovaným datovým typem {0}. + + + V datech vzdálené komunikace chybí vlastnost destination. + + + V datech vzdálené komunikace chybí vlastnost cílového rozhraní. + + + V datech vzdálené komunikace chybí vlastnost InstanceId relace. + + + V datech vzdálené komunikace chybí vlastnost RemotingDataType. + + + V datech vzdálené komunikace chybí vlastnost CallId. + + + V datech vzdálené komunikace chybí vlastnost MethodName. + + + Pro první fragment není nastaven příznak IsStartFragment. + + + V datech vzdálené komunikace chybí vlastnost {0}. + + + Bylo přijato neočekávané ObjectId. K tomu může dojít v případě, že fragmenty nejsou správně sestaveny vzdáleným počítačem, nebo mohla být poškozena nebo změněna data. + + + ObjectId nemůže být menší nebo rovno 0. K tomu může dojít v případě, že fragmenty nejsou správně sestaveny vzdáleným počítačem nebo pokud byla data změněna neoprávněnými uživateli. + + + Identifikátory FragmentID stejného objektu musí být v pořadí a jejich hodnoty se musí postupně zvyšovat o 1. K tomu může dojít, pokud vzdálený počítač fragmenty nesestaví správně. Data mohla být také poškozena nebo změněna. + + + Data vzdálené komunikace jsou příliš velká a nelze je znovu sestavit z fragmentů. K tomu může dojít, pokud je délka dat ve fragmentu větší než Int32.Max. Může k tomu dojít také v případě, že data změnili neoprávnění uživatelé. + + + Pro poslední fragment není nastaven příznak IsEndFragment. K tomu může dojít v případě, že fragmenty nejsou správně sestaveny vzdáleným počítačem nebo pokud byla data poškozena nebo změněna. + + + Deserializovaná data vzdálené komunikace mají hodnotu null. + + + Délka objektu blob fragmentu je mimo rozsah: {0} + + + Chyba při dekódování hodnoty ErrorRecord. + + + Chyba při dekódování PipelineStateInfo. + + + Chyba při dekódování RunspaceStateInfo. + + + Byl přijat nepodporovaný typ RemotingTargetInterface: {0} + + + Metoda vzdáleného hostitele byla vyvolána pro neznámou cílovou třídu: {0} + + + Metoda vzdáleného hostitele byla vyvolána bez zadání cílové třídy. + + + Při dekódování runspacePoolStateInfo došlo k chybě. + + + Chyba při dekódování minimálního počtu prostředí runspace. + + + Chyba při dekódování maximálního počtu prostředí runspace. + + + Chyba při dekódování PowerShellStateInfo. + + + Neočekávaný typ vlastnosti {0} (očekáváno {1}, obdrženo {2}). + + + Neočekávaný typ dat vzdálené komunikace (očekáváno: PSObject; obdrženo: {0}). + + + Neočekávaný typ zakódovaného příkazu (očekáváno: PSObject; obdrženo: {0}). + + + Neočekávaný typ zakódovaného parametru příkazu (očekáváno: PSObject; obdrženo: {0}). + + + Při dekódování dat přijatých ze vzdáleného počítače došlo k chybě. Dekódování deserializovaného objektu přijatého ze vzdáleného počítače vyžaduje alespoň {0} bajtů dat. K tomu může dojít v případě, že fragmenty nejsou správně sestaveny vzdáleným počítačem nebo pokud byla data poškozena nebo změněna. + + + Přijatý paket není určen pro přihlášeného uživatele: uživatel = {0}, cíl paketu = {1}. + + + Časovač vyjednávání klienta vypršel. Časový limit vyjednávání je {0} ms. + + + Klient PowerShellu nepodporuje {0} {1} vyjednané serverem. Ujistěte se, že server je kompatibilní se sestavením {2} a verzí protokolu {3} PowerShellu. + + + {0}. Vyjednávání se serverem se nezdařilo. Ujistěte se, že server je kompatibilní se sestavením {1} a verzí protokolu {2} PowerShellu. + + + Cílový server odeslal požadavek na uzavření relace. + + + Server, na kterém běží PowerShell, nepodporuje {0} {1} vyjednané klientským počítačem. Ujistěte se, že server je kompatibilní se sestavením {2} a verzí protokolu {3} PowerShellu. + + + Server s PowerShellem nepodporuje operace připojení na {0} {1}, které vyjednal klientský počítač. Ujistěte se, že je klientský počítač kompatibilní se sestavením {2} a verzí protokolu {3} PowerShellu. + + + Server, na kterém běží Prostředí PowerShell, nemůže zpracovat operaci připojení, protože nebyly nalezeny nebo nejsou platné následující informace: Informace o schopnostech klienta a informace o fondu RunspacePool připojení. + + + Server, na kterém je spuštěný PowerShell, nemůže zpracovat operaci připojení, protože server buď nebyl spuštěn, nebo se vypíná. + + + Server, na kterém běží PowerShell, nemůže zpracovat operaci připojení, protože vlastnosti fondu runspace serveru neodpovídají zadaným vlastnostem klientského počítače. + + + {0}. Vyjednávání s klientem se nezdařilo. Ujistěte se, že je klient kompatibilní se sestavením {1} a verzí {2} protokolu PowerShellu. + + + Časovač vyjednávání serveru vypršel. Časový limit vyjednávání je {0} ms. + + + Klientský počítač odeslal žádost o ukončení relace. + + + Došlo k chybě, kterou PowerShell nemůže zpracovat. Vzdálená relace mohla být ukončena. + + + Server neodpověděl se šifrovaným klíčem relace v zadaném časovém limitu. + + + Klient neodpověděl pomocí veřejného klíče ve stanoveném časovém limitu. + + + Pokus o připojení se nezdařil. + + + Probíhá pokus o uzavření relace. + + + PowerShell nemůže správně zavřít vzdálenou relaci. Relace je v nedefinovaném stavu, protože se po odpojení neotevřela ani nepřipojila. PowerShell se pokusí vynutit ukončení relace na místním počítači, ale relace nemusí být ve vzdáleném počítači uzavřena. Chcete-li vzdálenou relaci správně zavřít, nejprve ji otevřete nebo připojte. + + + Relaci nelze zavřít. + + + Relace je uzavřena. + + + Typ popisovače čekání „{0}“ není podporován. + + + Přijatá data mají index ID datového proudu {0}. Je podporován pouze index ID standardního výstupního datového proudu „0“. + + + Popisovač standardního vstupu není otevřený. + + + Volání nativního rozhraní API WriteFile se nezdařilo. Kód chyby je {0}. + + + Volání nativního rozhraní API pro ReadFile se nezdařilo. Kód chyby je {0}. + + + {0} není platná hodnota schématu. Platné hodnoty jsou http a https. + + + Přijetí volání na straně klienta se nezdařilo. + + + Volání odeslání na straně klienta se nezdařilo. + + + Popisovač příkazu vrácený z rozhraní WINRS API WSManRunShellCommand má hodnotu null. + + + Popisovač standardního vstupu nelze nastavit na stav „no wait“. Kód systémové chyby je {0}. + + + Číslo portu {0} není v rozsahu platných hodnot. Rozsah platných hodnot je od 1 do 65535. + + + Proces serveru byl ukončen. + + + Volání rutiny GetStdHandle rozhraní API systému Windows pro získání popisovače standardního vstupu způsobilo kód chyby: {0}. + + + Volání rutiny GetStdHandle rozhraní API systému Windows pro získání popisovače Standardní výstup způsobilo kód chyby: {0}. + + + Volání rutiny GetStdHandle rozhraní API systému Windows pro získání popisovače standardní chyby způsobilo kód chyby: {0}. + + + Připojení ke vzdálenému serveru {0} se nezdařilo. + + + Připojení ke vzdálenému serveru {0} se nezdařilo s následující chybovou zprávou: {1} + + + Zavření instance prostředí vzdáleného serveru se nezdařilo s následující chybovou zprávou: {0} + + + Odeslání dat na vzdálený server {0} se nezdařilo. + + + Odeslání dat na vzdálený server {0} se nezdařilo s následující chybovou zprávou: {1} + + + Příjem dat ze vzdáleného serveru {0} se nezdařil. + + + Zpracování dat ze vzdáleného serveru {0} se nezdařilo s následující chybovou zprávou: {1} + + + Spuštění příkazu na vzdáleném serveru se nezdařilo. + + + Spuštění příkazu na vzdáleném serveru se nezdařilo s následující chybovou zprávou: {0} + + + Opětovné připojení k příkazu na vzdáleném serveru se nezdařilo s následující chybovou zprávou: {0} + + + Odeslání dat vzdálenému příkazu se nezdařilo. + + + Odeslání dat do vzdáleného příkazu se nezdařilo s následující chybovou zprávou: {0} + + + Příjem dat pro vzdálený příkaz se nezdařil. + + + Zpracování dat pro vzdálený příkaz se nezdařilo s následující chybovou zprávou: {0} + + + Při volání metody {1} došlo k chybě s kódem chyby {0}. + + + {0} Další informace najdete v tématu nápovědy about_Remote_Troubleshooting. + + + Odpojení od vzdáleného serveru {0} se nezdařilo. + + + Odpojení od vzdáleného serveru se nezdařilo s následující chybovou zprávou: {0} + + + Opětovné připojení ke vzdálenému serveru se nezdařilo. + + + Opětovné připojení ke vzdálenému serveru {0} se nezdařilo s následující chybovou zprávou: {1} + + + Přenos meziprocesové komunikace (IPC) nepodporuje operace připojení. + + + Konfigurace EndpointConfiguration s ID {0} na vzdáleném serveru neexistuje. Obraťte se na správce PowerShellu nebo vlastníka nebo autora konfigurace koncového bodu. + + + Konfigurace EndpointConfiguration s identifikátorem {0} není na vzdáleném počítači v platném počátečním stavu relace. Obraťte se na správce PowerShellu nebo vlastníka nebo autora konfigurace koncového bodu. + + + Pro klíč registru {1} není zadána povinná hodnota {0}. + + + Povinná hodnota {0} nemá správný formát pro klíč registru {1}. Očekávaný formát je řetězec. + + + „{0}“ musí určovat soubor skriptu PowerShellu, který končí příponou .ps1. + + + Parametr {0} je již zadán v oddílu {1}. Obraťte se na správce a ujistěte se, že {0} je zadán pouze jednou. + + + V elementu „{0}“ se očekávají atributy „{1}“ a „{2}“. + + + „{0}“, „{1}“ musí být zadány v oddílu „{2}“ pro dynamické načtení sestavení. + + + Sestavení „{0}“ zadané v oddílu „{1}“ nelze načíst. + + + Nelze načíst typ „{0}“ zadaný v oddílu „{1}“. + + + V části „{2}“ musí být zadáno „{1}“ i „{0}“. + + + Cíl „{0}“ požádal o přesměrování připojení na „{1}“. „{1}“ ale není správně formátovaný identifikátor URI. + + + {0}Nahlášené umístění přesměrování: {1}. + + + Vaše připojení bylo přesměrováno na následující identifikátor URI: „{0}“ + + + {0} Chcete-li se automaticky připojit k přesměrovanému identifikátoru URI, ověřte vlastnost {1} proměnné předvoleb relace {2} a v rutině použijte parametr {3}. + + + Aktuální velikost deserializovaného objektu dat přijatých ze vzdáleného serveru překročila povolenou maximální velikost objektu. Aktuální velikost deserializovaného objektu je {0}. Maximální povolená velikost objektu je {1}. + + + Celkové množství dat přijatých ze vzdáleného serveru překročilo povolené maximum. Povolené maximum je {0}. + + + Aktuální velikost deserializovaného objektu dat přijatých ze vzdáleného klientského počítače překročila povolenou maximální velikost objektu. Aktuální velikost deserializovaného objektu je {0}. Maximální povolená velikost objektu je {1}. + + + Celkové množství dat přijatých od vzdáleného klienta překročilo povolené maximum. Povolené maximum je {0}. + + + Spuštění spouštěcího skriptu vyvolalo chybu: {0}. + + + Zadané objekty RemoteRunspaceInfo mají duplicitní položky. + + + Zadané objekty RemoteRunspaceInfo překročily maximální povolený limit. + + + Otevření vzdálené relace se nezdařilo s neočekávaným stavem. Stav {0}. + + + Zadaný identifikátor URI {0} není platný. + + + Vzdálená relace pro identifikátor URI {0} byla uzavřena. + + + Vzdálená relace není pro ComputerName {0} k dispozici. + + + Vzdálená relace není pro {0} k dispozici. + + + Vzdálený příkaz: {0}, přidružený k úloze, která má ID „{1}“. + + + Parametr {0} nelze zadat, pokud je zadán parametr {1}. + + + Wildcard characters are not supported for the FilePath parameter. Specify a path without wildcard characters. + + + Cesta zadaná jako hodnota parametru FilePath nepochází od zprostředkovatele FileSystem. + + + Hodnota parametru FilePath musí být soubor skriptu PowerShellu. Zadejte cestu k souboru s příponou .ps1 a příkaz opakujte. + + + Jeden nebo více názvů počítačů není platných. Pokud se pokoušíte předat URI, použijte parametr -ConnectionUri nebo místo řetězců předejte objekty URI. + + + Stav aktuální instance úlohy není pro tuto operaci platný. + + + Příkaz nemůže úlohu najít, protože nebyl nalezen název úlohy {0}. Ověřte hodnotu parametru Name a příkaz zopakujte. + + + Příkaz nemůže najít úlohu s identifikátorem instance {0}. Ověřte hodnotu parametru InstanceId a příkaz zopakujte. + + + Příkaz nemůže najít úlohu s ID úlohy {0}. Ověřte hodnotu parametru ID a příkaz zopakujte. + + + Příkaz nemůže odebrat úlohu s ID úlohy {0} a názvem {1}, protože úloha nebyla dokončena. Pokud chcete úlohu odebrat, nejprve úlohu zastavte nebo použijte parametr Force. + + + Příkaz nemůže odebrat úlohu s ID úlohy {0}, protože úloha není dokončená. Pokud chcete úlohu odebrat, nejprve úlohu zastavte nebo použijte parametr Force. + + + Příkaz nemůže odebrat úlohu s ID úlohy {0} a identifikátorem instance {1}, protože úloha není dokončená. Pokud chcete úlohu odebrat, nejprve úlohu zastavte nebo použijte parametr Force. + + + Vzdálený příkaz: {0}, přidružený k úloze, která má ID „{1}“. + + + Příkaz nemůže načíst úlohy zadaných počítačů. Parametr ComputerName lze použít pouze s úlohami vytvořenými pomocí vzdálené komunikace PowerShellu. + + + Parametr Session lze použít pouze s objekty PSRemotingJob. + + + Vzdálená relace s názvem {0} není k dispozici. + + + Vzdálená relace s ID relace {0} není k dispozici. + + + {0} neobsahuje položku s ID {1}. + + + Příkaz nemůže odebrat úlohu, protože neexistuje nebo je podřízenou úlohou. Podřízené úlohy lze odebrat pouze odebráním nadřazené úlohy. + + + {0} není platná hodnota parametru {1}. Hodnota musí být větší než nebo rovna 0. + + + {0} nelze zadat jako mechanismus ověřování proxy serveru. Pro ověřování proxy serveru se podporují jenom {1}, {2} nebo {3}. + + + Při použití následujícího typu přístupu k proxy serveru nelze zadat přihlašovací údaje proxy serveru: {0}. Buď zadejte jiný typ přístupu, nebo nezadávejte přihlašovací údaje proxy serveru. + + + A {0} value must be specified for session option {1}. + + + Relace musí být otevřená. + + + Hostitel nepodporuje Enter-PSSession a Exit-PSSession. + + + Bylo nalezeno více shod pro ID relace {0}. + + + Bylo nalezeno více shod pro ID relace {0}. + + + Pro název {0} bylo nalezeno více shod. + + + Příkaz Enter-PSSession se nezdařil, protože vzdálená relace neposkytuje požadované příkazy. + + + Enter-PSSession nelze spustit z vnořené výzvy. + + + The maximum number of WS-Man URI redirections to allow while connecting to a remote computer + + + Výchozí možnosti relace pro nové vzdálené relace + + + Název konfigurace relace, která bude načtena do vzdáleného počítače + + + AppName, kde bude navázáno vzdálené připojení + + + Obsahuje informace o vzdáleném uživateli, který spouští vzdálenou relaci. Tato proměnná je k dispozici pouze ze vzdálené relace. + + + Buď musí být zadán „{0}“ i „{1}“, nebo nesmí být zadán ani jeden z nich. + + + Konfigurace relace „{0}“ nebyla nalezena. + + + Konfigurace relace „{0}“ není prostředí založené na PowerShellu. + + + Konfigurace relace „{0}“ je prostředí založené na PowerShellu. K úpravě použijte PowerShell 6+. + + + Konfigurace relace „{0}“ je prostředí založené na Windows PowerShell. K úpravě použijte Windows PowerShell. + + + Žádná konfigurace relace neodpovídá kritériím „{0}“. + + + {0} + + + Název: {0} + + + Název: {0}. To správcům umožňuje na tomto počítači vzdáleně spouštět příkazy PowerShellu. + + + Nelze odstranit dočasný soubor {0}. Důvod selhání: {1}. + + + Nové prostředí bylo úspěšně zaregistrováno, ale prostředí PowerShell nemůže odstranit dočasný soubor {0}. Důvod selhání: {1}. + + + Konfigurační data prostředí nelze zapsat do dočasného souboru {0}. Důvod selhání: {1}. + + + Spouští se příkaz „{0}“ pro vytvoření nové konfigurace relace. + + + Název: {0} SDDL: {1}. To umožňuje vybraným uživatelům vzdáleně spouštět příkazy PowerShellu v tomto počítači. + + + Spouští se příkaz „{0}“ k odebrání konfigurace relace. + + + Spouští se příkaz „{0}“ k získání konfigurací relací založených na PowerShellu. + + + Spouští se příkaz „{0}“ k aktualizaci vlastností konfigurace relace. + + + Název: {0} SDDL: {1} + + + Spouští se příkaz „{0}“ k povolení konfigurace relace. + + + Rychlá konfigurace WinRM + + + Spouští se příkaz „{0}“ k povolení vzdálené správy tohoto počítače pomocí služby Windows Remote Management (WinRM). + To zahrnuje: + 1. Spuštění nebo restartování služby WinRM, pokud už běží. + 2. Nastavení typu spuštění služby WinRM na Automaticky. + 3. Vytvoření naslouchacího procesu pro přijímání požadavků na libovolné IP adrese. + 4. Povolení výjimek příchozích pravidel brány Windows Firewall pro přenosy služby WS-Management (pouze pro protokol HTTP). + +Chcete pokračovat? + + + Provádění operace „{0}“. + + + Název: {0} SDDL: {1}. To umožňuje vybraným uživatelům vzdáleně spouštět příkazy PowerShellu v tomto počítači. + + + Spouští se příkaz „{0}“ k zakázání konfigurace relace. + + + Název: {0} SDDL: {1}. Tím se odepře přístup ke konfiguraci této relace pro všechny. + + + Zakázáním konfigurací relací nedojde k vrácení všech změn provedených rutinou Enable-PSRemoting nebo Enable-PSSessionConfiguration. Změny možná budete muset vrátit zpět ručně pomocí následujícího postupu: + 1. Zastavte a zakažte službu WinRM. + 2. Odstraňte naslouchací proces, který přijímá požadavky na libovolné IP adrese. + 3. Zakažte výjimky brány firewall pro komunikaci WS-Management. + 4. Obnovte hodnotu LocalAccountTokenFilterPolicy na hodnotu 0, která omezí vzdálený přístup na členy skupiny Administrators v počítači. + + + Přístup je odepřený. Pokud chcete tuto rutinu spustit, spusťte PowerShell s možností Spustit jako správce. + + + Restartování služby WinRM + + + „Restart-Service“ + + + Název: {0} + + + Před zobrazením uživatelského rozhraní pro výběr popisovače SecurityDescriptor je nutné restartovat službu WinRM. Restartujte službu WinRM a spusťte následující příkaz: „{0}“ + + + Registruje se konfigurace relace + + + Konfigurace relace {0} nebyla nalezena. Spouští se příkaz „{1}“ k vytvoření konfigurace relace „{0}“. Spuštění tohoto příkazu restartuje službu WinRM. + + + Parametry „{0}“ a „{1}“ nelze zadat společně. Zadejte buď parametr „{0}“, nebo „{1}“. + + + Tato operace může restartovat službu WinRM. Chcete pokračovat? + + + Nelze zpracovat element s typem uzlu „{0}“. Jsou podporovány pouze typy uzlů {1} a {2}. + + + Ke zpracování elementu {0} není k dispozici dostatek dat. + + + V elementu{2} byly očekávány pouze dva atributy s názvy „{0}“ a „{1}“. + + + Typ uzlu „{0}“ je v elementu {1} neznámý. V elementu {2} se očekává pouze typ uzlu „{1}“. + + + V elementu {0} byl očekáván pouze jeden atribut s názvem „{1}“. + + + Byl přijat neznámý element „{0}“. K tomu může dojít, pokud se vzdálený proces předčasně ukončil nebo skončil neočekávaně. + + + Zadaný mechanismus ověřování „{0}“ není podporován. Pro tuto operaci se podporuje jenom „{1}“. + + + Spustitelný soubor pwsh nebyl nalezen v „{0}“. +Všimněte si, že Start-Job se záměrně nepodporuje ve scénářích, ve kterých je PowerShell hostován v jiných aplikacích. Místo toho se v takových scénářích doporučuje použít modul ThreadJob. + + + Nelze spustit 32bitový proces pwsh z 64bitové instalace pwsh. Pokud potřebujete spustit PowerShell v 32bitovém procesu, nainstalujte 32bitovou verzi pwsh. + + + Proces na pozadí ohlásil chybu s následující zprávou: {0}. + + + Proces na pozadí byl neočekávaně uzavřen nebo ukončen: {0}. + + + Při zpracování dat z procesu na pozadí došlo k chybě. Nahlášená chyba: {0}. + + + Byla přijata data pro neaktivní příkaz s identifikátorem {0}. Přijatá data: {1}. + + + Zpráva {0} do relace není podporovaná. Zprávu {0} lze odeslat pouze příkazu. + + + Klient neobdržel odpověď na operaci signálu v zadaném časovém intervalu. K tomu může dojít, když příkaz včas nereaguje na zprávu Stop. + + + Klient neobdržel odpověď na operaci „Zavřít“ v zadaném časovém intervalu. K tomu může dojít, když příkaz včas nereaguje na zprávu Stop. + + + Při spouštění procesu na pozadí došlo k chybě. Nahlášená chyba: {0}. + + + Metoda ThrottlingJob.AddChildJob přijímá pouze podřízené úlohy ve stavu NotStarted. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + Metodu ThrottlingJob.AddChildJob nelze volat po volání metody ThrottlingJob.EndOfChildJobs. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} dokončeno + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Vyvolání vnořeného kanálu vyžaduje platné prostředí runspace. + + + Zdrojový adaptér úlohy {1} vyvolal výjimku s následující zprávou: {0} + + + Hodnota {0} není platná pro parametr {1}. Jediná povolená hodnota je 5.1. + + + Parametry Wait a Keep nelze použít společně ve stejném příkazu. + + + The WriteEvents parameter cannot be used without the Wait parameter. + + + Správa verzí koncového bodu vzdálené komunikace PowerShellu se v PowerShellu 7+ nepodporuje. + + + Následující typ nelze vytvořit jako instanci, protože jeho konstruktor není veřejný: {0}. + + + Operaci úlohy (Create, Get nebo Remove) nelze provést, protože typ JobSourceAdapter zadaný v definici JobDefinition není zaregistrován. Zaregistrujte typ JobSourceAdapter buď pomocí explicitního volání, nebo voláním rutiny Import-Module a zadáním sestavení. + + + Úlohu nelze vytvořit, protože objekt JobInvocationInfo neobsahuje JobDefinition. Spusťte JobInvocationInfo s JobDefinition. + + + Stav aktuální instance úlohy je {0}. Tento stav není platný pro požadovanou operaci. {1} + + + Úlohu {0} nelze připojit ke vzdálenému serveru. + + + Operace Disconnect-PSSession se nezdařila pro prostředí runspace s ID = {0}. + + + Operace připojení pro relaci {0} se nezdařila. Stav prostředí Runspace je {1} místo „Otevřeno“. + + + Dotaz na odpojenou relaci PSSession pro počítač „{0}“ se nezdařil. + + + Relaci PSSession „{0}“ nelze připojit, protože není ve stavu Odpojeno nebo není k dispozici pro připojení. + + + Připojení relace se pro PSSession „{0}“ na cílovém počítači „{1}“ nepodporuje, protože typ cílového počítače je „{2}“. + + + Relaci PSSession {0} nelze odpojit, protože není ve stavu Otevřeno. + + + Odpojení relace se pro PSSession „{0}“ na cílovém počítači „{1}“ nepodporuje, protože typ cílového počítače je „{2}“. + + + Receive-PSSession nepodporuje PSSession „{0}“ na cílovém počítači „{1}“, protože typ cílového počítače je "{2}". + + + Příkaz nelze dokončit, protože vlastnost ChildJobs obsahuje neplatnou hodnotu. + + + Úlohu s ID {0} nelze pozastavit. Pozastavení úloh není u některých typů úloh podporováno. Další informace o podpoře pozastavení úloh najdete v tématu nápovědy pro typ úlohy. + + + Nelze obnovit úlohu s ID {0}. Obnovení úloh není u některých typů úloh podporováno. Další informace o podpoře obnovení úloh najdete v tématu nápovědy pro typ úlohy. + + + Rutinu Invoke-Command nelze použít současně s parametry AsJob a Disconnected ve stejném příkazu. + + + Dotaz na vzdálenou relaci pro {0} se nezdařil s následující chybovou zprávou: {1} + + + Došlo k pokusu o vytvoření úlohy s ID {0}. Úlohu s tímto ID nyní nelze vytvořit. Ověřte, zda toto ID už bylo na tomto počítači jednou přiřazeno. + + + Nelze vytvořit úlohu s ID {0}; toto není platné ID. Zadejte celé číslo pro ID úlohy, které je větší než 0. + + + Zadaný identifikátor JobIdentifier nesmí mít hodnotu null. Zadejte platný identifikátor JobIdentifier. + + + Rutina Wait-Job nemůže dokončit činnost, protože jedna nebo více úloh je blokována a čeká na interakci uživatele. Zpracujte výstup interaktivní úlohy pomocí rutiny Receive-Job a zkuste to znovu. + + + Vzdálenou relaci {0} nelze připojit a nelze ji odebrat ze serveru. Objekt vzdálené relace klienta bude odebrán ze serveru, ale stav vzdálené relace na serveru je neznámý. + + + Operace Disconnect-PSSession se nezdařila pro prostředí runspace s ID = {0} z následujícího důvodu: {1} + + + Úlohu „{0}“ nelze připojit k serveru, a proto ji nelze zastavit. + + + Příkaz nemůže najít relaci PSSession s hodnotou InstanceId {0}. + + + Příkaz nemůže najít relaci PSSession s názvem {0}. + + + PowerShell remoting is not supported in the Windows Preinstallation Environment (WinPE). + + + Changes made by {0} cannot take effect until the WinRM service is restarted. + + + {0} may need to restart the WinRM service if a configuration using this name has recently been unregistered, certain system data structures may still be cached. In that case, a restart of WinRM may be required. +All WinRM sessions connected to PowerShell session configurations, such as Microsoft.PowerShell and session configurations that are created with the Register-PSSessionConfiguration cmdlet, are disconnected. + + + You are running in a remote session and have selected the Force option which means the WinRM service may restart.If the WinRM service restarts then this remote session will be terminated and you will need to create a new session to continue + + + Při pokusu o uložení identifikátorů měla úloha hodnotu null. Zadejte úlohu, aby bylo možné uložit její identifikátory. + + + Pro tuto relaci PSSession se nepodařilo najít spuštěný příkaz. + + + Prostředí Microsoft .NET Framework 2.0, které je vyžadováno pro Windows PowerShell 2.0, není nainstalováno. Nainstalujte .NET Framework 2.0 a zkuste to znovu. + + + Vzdálený kanál selhal. + + + Vzdálený kanál selhal z následujícího důvodu: {0} + + + Jednu nebo více úloh nelze obnovit, protože stav nebyl pro tuto operaci platný. + + + Pro vzdálené prostředí runspace, na kterém běží metoda na straně klienta, nebyl zadán žádný klientský počítač. + + + Název: {0} SDDL: {1}. Tím se odepře vzdálený přístup k této konfiguraci relace. + + + Povoleno: False. Tato možnost nakonfiguruje službu WS-Management tak, aby žádost o připojení odmítla. + + + Povoleno: True. Tato možnost nakonfiguruje službu WS-Management tak, aby žádost o připojení přijala. + + + Aliasy, které se mají definovat při použití v relaci + + + Sestavení, která se mají načíst při použití v relaci + + + Autor tohoto dokumentu + + + Verze modulu CLR, která se použije při použití v relaci + + + Společnost přidružená k tomuto dokumentu + + + Prohlášení o autorských právech pro tento dokument + + + Popis funkcí poskytovaných těmito nastaveními + + + Proměnné prostředí, které se mají definovat při použití v relaci + + + Zásady spouštění, které se použijí při použití v relaci + + + Formátujte soubory (.ps1xml), které se mají načíst při použití v relaci + + + Funkce, které se mají definovat při použití v relaci + + + ID použité k jedinečné identifikaci tohoto dokumentu + + + Pro tuto konfiguraci relace se použije výchozí typ relace. Může být RestrictedRemoteServer (doporučeno), Empty nebo Default + + + Adresář pro ukládání přepisů relací pro tuto konfiguraci relace + + + Určuje, jestli se má tato konfigurace relace spustit jako (virtuální) účet správce počítače + + + Jazykový režim, který se použije při použití v relaci. Může být NoLanguage (doporučeno), RestrictedLanguage, ConstrainedLanguage nebo FullLanguage + + + Moduly, které se mají importovat při použití v relaci + + + Verze modulu PowerShellu, která se použije při použití v relaci + + + Architektura procesoru, která se má použít při použití v relaci + + + Číslo verze schématu použitého pro tento dokument + + + Skripty, které se mají spustit při použití v relaci + + + Typy, které se mají přidat při použití v relaci + + + Zadejte soubory (.ps1xml), které se mají načíst při použití v relaci + + + Proměnné, které se mají definovat při použití v relaci + + + Role uživatelů (skupiny zabezpečení) a možnosti rolí, které se na ně mají použít při použití v relaci + + + Aliasy, které se mají zobrazit při použití v relaci + + + Rutiny, které se mají zobrazit při použití v relaci + + + Nepovedlo se parsovat viditelnou definici příkazu pro „{0}“. Viditelná definice příkazu musí být zatřiďovací tabulka s klíči Name a Parameters. Hodnota klíče Parameters musí být kolekce zatřiďovací tabulky s klíči Name a volitelně ValidateSet nebo ValidatePattern. + + + Funkce, které se mají zobrazit při použití v relaci + + + Poskytovatelé, kteří se mají zobrazit při použití v relaci + + + Externí příkazy (skripty a aplikace), které se mají zobrazit při použití v relaci + + + Cesta ke konfiguračnímu souboru PSSession „{0}“ není platná. Argument cesty se musí přeložit na jeden soubor v systému souborů s příponou .pssc. Opravte specifikaci cesty a zkuste to znovu. + + + Cesta k souboru schopností role „{0}“ není platná. Argument cesty se musí přeložit na jeden soubor v systému souborů s příponou .psrc. Opravte specifikaci cesty a zkuste to znovu. + + + Položka „Role“ musí být zatřiďovací tabulka, ale byla {0}. + + + Hodnotu položky role „{0}“ nelze převést na zatřiďovací tabulku. Položka „Role“ musí být zatřiďovací tabulka s názvy skupin pro klíče, kde hodnota přidružená ke každému klíči je další zatřiďovací tabulkou vlastností konfigurace relace pro danou roli. + + + Nepovedlo se najít možnost role „{0}“. Schopnost role musí být soubor s názvem „{1}“ v adresáři RoleCapabilities v modulu v aktuální cestě modulu. + + + Nelze najít cestu k modulu, který se má importovat. Hodnota parametru ModulesToImport {0} neexistuje nebo se nejedná o adresář modulu. Opravte hodnotu a opakujte příkaz. + + + Zadaný konfigurační soubor {0} nebyl načten, protože nebyl nalezen žádný platný konfigurační soubor. + + + Počítač {0} byl úspěšně odpojen. + + + Pokus o opětovné připojení k {0} se nezdařil. Probíhá pokus o odpojení relace... + + + Probíhá pokus o opětovné připojení k {0}... + + + Síťové připojení k {0} bylo ztraceno a pokus o opětovné připojení se nezdařil. Opravte síťové připojení a znovu se připojte pomocí connect-PSSession nebo Receive-PSSession. + + + Síťové připojení k {0} bylo přerušeno. Probíhá pokus o opětovné připojení po dobu až {1} min... + + + Síťové připojení k {0} bylo obnoveno. + + + Ověřování {0} vyžaduje explicitní uživatelské jméno a heslo. Zadejte uživatelské jméno a heslo pomocí parametru -Credential a příkaz opakujte. + + + Základní ověřování není v systému Unix přes HTTP podporováno. + + + Nelze najít naplánovanou úlohu s názvem {0}. + {0} is the job definition name + + + Byla nalezena více než jedna definice úlohy s názvem {0}. Zkuste do Start-Job přidat parametr -DefinitionType, aby se hledání definice úlohy zúžilo na jediný zdrojový adaptér úlohy. + + + Člen SchemaVersion se v konfiguračním souboru nenachází. Tento člen musí existovat a musí mu být přiřazeno číslo verze ve tvaru :n.n.n.n:. Přidejte chybějícího člena do souboru {0}. + + + Člen „{0}“ musí být řetězec. Změňte člena na správný typ v souboru {1}. + + + Člen {0} musí být pole řetězců. Změňte člena na správný typ v souboru {1}. + + + Člen „{0}“ musí být zatřiďovací tabulka. Změňte člena na správný typ v souboru {1}. + + + Člen „{0}“ musí být pole zatřiďovací tabulky. Změňte člena na správný typ v souboru {1}. + + + Člen {0} není platný klíč. Změňte člena na platný klíč v souboru {1}. + + + Člen „{0}“ musí být platný typ výčtu „{1}“. Platné hodnoty výčtu jsou „{2}“. Změňte člena na správný typ v souboru {3}. + + + Při analýze konfiguračního souboru {0} došlo k chybě s následující zprávou: {1} + + + The -WriteJobInResults parameter cannot be used without the -Wait parameter + + + Člen {0} není absolutní cesta {1}. Změňte člena na absolutní cestu v souboru {2}. + + + Klíč „{0}“ v členovi „{1}“ není platný. Změňte klíč v souboru {2}. + + + Člen {0} musí obsahovat požadovaný klíč {1}. Přidejte požadovaný klíč do souboru {2}. + + + Klíč „{0}“ obsahuje neplatné rozšíření {1}. Zadejte rozšíření z následujícího seznamu: {{{2}}}. + + + Klíč {0} v členovi {1} musí být blok skriptu. Změňte klíč na správný typ v souboru {2}. + + + Konfigurační soubor relace {0} není platný. Zadejte platný konfigurační soubor relace a opakujte příkaz. + + + Síťové připojení přerušeno + + + Probíhá pokus o opětovné připojení k {0}... + + + Pro opětovné připojení byla vytvořena úloha {0}. + + + Relace {0} s ID instance {1} na počítači {2} byla úspěšně odpojena. + + + Relace {0} s ID instance {1} byla vytvořena pro opětovné připojení. + + + Parametr SessionName lze použít pouze s přepínačem Disconnected. + + + Při pokusu o připojení relace PSSession došlo k chybě. + + + Při pokusu o připojení k cílovému virtuálnímu počítači došlo k chybě. + + + Při pokusu o připojení k cílovému kontejneru došlo k chybě. + + + PSSession je v odpojeném stavu a není k dispozici pro připojení. + + + Modul Hyper-V pro PowerShell není na tomto počítači k dispozici. + + + Nepovedlo se spustit proces PowerShellu ({1}) uvnitř kontejneru s ID {0} s chybou: {2}. + + + Na tomto počítači možná není povolená funkce Kontejnery. + + + Nepovedlo se ukončit proces PowerShellu s ID {0} uvnitř kontejneru s ID {1}. + + + Vstupní ContainerId {0} neexistuje nebo odpovídající kontejner není spuštěný. + + + Vstupní parametr VMId se nepřekládá na jeden virtuální počítač. + + + Vstupní VMId {0} se nepřekládá na jeden virtuální počítač. + + + Vstupní parametr VMName se nepřekládá na žádný virtuální počítač. + + + Vstupní parametr VMName se překládá na více virtuálních počítačů. + + + Vstupní VMName {0} se nepřekládá na jeden virtuální počítač. + + + Virtuální počítač {0} není ve spuštěném stavu. + + + Přihlašovací údaje jsou neplatné. + + + Vstupní uživatelské jméno nemůže být prázdné. + + + Nelze zadat {0} relace, protože není v odpojeném stavu nebo není k dispozici pro připojení. Načtěte vzdálenou relaci pomocí příkazu Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Nelze zadat {0} relace, protože není v odpojeném stavu nebo není k dispozici pro připojení. Znovu se připojte pomocí Connect-PSSession nebo Receive-PSSession. + + + Síťové připojení k {0} bylo ztraceno a pokus o opětovné připojení se nezdařil. Opravte síťové připojení a znovu se připojte pomocí connect-PSSession nebo Receive-PSSession. + + + Nepodařilo se vytvořit instanci RemoteSessionHyperVSocketClient kvůli chybě SetSocketOption. + + + Nepodařilo se vytvořit instanci RemoteSessionHyperVSocketServer. + + + Pokus o opětovné připojení byl zrušen. Opravte síťové připojení a znovu se připojte pomocí connect-PSSession nebo Receive-PSSession. + + + Jednu nebo více úloh nelze pozastavit, protože stav nebyl pro tuto operaci platný. + + + Parametr -AutoRemoveJob nelze použít bez parametru -Wait + + + Služba WS-Management nemůže požadavek zpracovat. Konfiguraci relace {0} nelze najít na jednotce WSMan: v počítači {1}. Další informace najdete v tématu nápovědy about_Remote_Troubleshooting. + + + Ze specifikace {0} nelze vytvořit úlohu, protože zadané prostředí runspace není místní prostředí runspace. Zkuste to znovu pomocí místního prostředí runspace nebo zadejte argument RunspaceMode. + + + Relaci {0} nelze odpojit, protože zadaná hodnota časového limitu nečinnosti {1} (sekund) je buď větší než maximální povolená hodnota serveru {2} (sekund), nebo menší než minimální povolená hodnota {3} (sekund). Zadejte hodnotu časového limitu nečinnosti, která je v povoleném rozsahu, a zkuste to znovu. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + Zadaná možnost relace IdleTimeout {0} (sekundy) není platný interval. Zadejte hodnotu IdleTimeout, která je větší nebo rovna minimálně povolené hodnotě {1} (sekundy). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + Rutina „{0}“ nebo alias „{1}“ nemůže být přítomna, pokud jsou v konfiguračním souboru relace zadány klíče „{2}“, „{3}“, „{4}“ nebo „{5}“. + + + Možnost přenosu není platná. Parametr „{0}“ může být nenulový pouze v případě, že je parametr „{1}“ nastavený na True. + + + Člen „{0}“ musí být pole složené buď z řetězců, nebo z prvků typu zatřiďovací tabulka. + + + Člen „{0}“ musí být pole složené buď z řetězců, nebo z prvků typu zatřiďovací tabulka. Změňte člena na správný typ v souboru {1}. + + + Nelze načíst definici úlohy {0}, protože cesta {1} odkazuje na cestu zprostředkovatele {2}. Změňte parametr cesty na cestu systému souborů. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Nejde načíst definici úlohy {0}, protože cesta {1} se překládá na více cest k souborům. Změňte parametr cesty tak, aby obsahoval jen jednu cestu. + {0} is job definition name +{1} is the user provided path + + + Nelze najít naplánovanou úlohu s typem {0} a názvem {1}. + {0} is the job definition type and {1} is the job definition name. + + + Nelze najít cestu WorkingDirectory {0}. + + + Nelze se připojit k relaci {0}. Relace už na počítači {1} neexistuje. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + Operace připojení pro relaci {0} se nezdařila s následující chybovou zprávou: {1} + + + Parametr -Force nelze použít bez parametru -Wait. + + + Nejméně jedna úloha je v pozastaveném nebo odpojeném stavu a nemůže pokračovat bez dalšího zásahu uživatele. Zadejte parametr -Force, chcete-li pokračovat do dokončeného, neúspěšného nebo zastaveného stavu. + + + Pokud je v konfiguraci relace PowerShellu povolená funkce RunAs, model zabezpečení Windows nemůže vynutit hranici zabezpečení mezi různými uživatelskými relacemi vytvořenými pomocí tohoto koncového bodu. Ověřte, zda je konfigurace prostředí PowerShell runspace omezena pouze na nezbytnou sadu rutin a funkcí. + + + Úloha byla úspěšně pozastavena přidáním parametru Force. + + + Konfigurační soubor relace {0} není platný. Zadejte platný konfigurační soubor relace a opakujte příkaz. Při analýze konfiguračního souboru došlo k chybě: {1}. + + + Register-PSSessionConfiguration: Klíč „{0}“ v {1}. Konfigurační soubor relace obsahuje neplatnou hodnotu. Opravte soubor a příkaz opakujte. + + + Odpojené relace jsou podporovány pouze v případě, že vzdálený počítač používá PowerShell 3.0 nebo novější verzi PowerShellu. + + + Využití paměti rutiny překročilo úroveň upozornění. Abyste se této situaci vyhnuli, zkuste jednu z následujících věcí: 1) Snižte rychlost, jakou operace CIM vytvářejí data (například předáním nízké hodnoty parametru ThrottleLimit), 2) Zvyšte rychlost, jakou jsou data spotřebovávat podřízenými rutinami, nebo 3) Pomocí rutiny Invoke-Command spusťte na serveru celý kanál. Rutina, která překročila úroveň upozornění pro využití paměti, byla spuštěna následujícím příkazovým řádkem: {0} + + + Relace PSSession {0} byla vytvořena pomocí parametru EnableNetworkAccess a lze ji znovu připojit pouze z místního počítače. + + + Nelze spustit úlohu. Jazykový režim této relace není kompatibilní se systémovým jazykovým režimem. + + + Nelze vytvořit prostředí runspace. Jazykový režim této konfigurace není kompatibilní se systémovým jazykovým režimem. + + + Vnořený kanál nelze ukončit, protože není ve vnořeném stavu. + + + Relace serveru PowerShell není v platném stavu pro spouštění vnořených příkazů. V této relaci nelze spustit žádné vnořené příkazy. + + + Ve vzdálené relaci nelze vyvolat vnořený příkaz, protože vnořený příkaz už běží. + + + Vzdálená relace nemohla vyvolat příkaz {0} s chybou: {1}. + + + Příkaz vzdálené relace je aktuálně zastaven v ladicím programu. Pomocí rutiny Enter-PSSession se interaktivně připojte ke vzdálené relaci a automaticky vstupte do ladicího programu konzoly. + + + Vzdálená relace, ke které jste připojeni, nepodporuje vzdálené ladění. Musíte se připojit ke vzdálenému počítači s PowerShellem 4.0 nebo novějším. + + + Protože stav relace pro relaci {0}, {1}, {2} není Otevřeno, nelze v relaci spustit příkaz. Stav relace je {3}. + + + Nebyly zadány žádné platné relace. Ujistěte se, že zadáváte platné relace, které jsou ve stavu Otevřeno a jsou k dispozici pro spouštění příkazů. + + + Relace {0}, {1}, {2} není k dispozici pro spouštění příkazů. Dostupnost relace je {3}. + + + Příkaz nelze spustit, protože vlastnost ChildJobs je prázdná. + + + Úlohu nelze ladit, protože není k dispozici žádný ladicí program hostitele PowerShellu. Ujistěte se, že tento příkaz spouštíte v hostiteli, který podporuje ladění. + + + Nelze najít úlohu s ID {0}. + + + Nelze najít úlohu s ID instance {0}. + + + Nelze najít úlohu s názvem {0}. + + + Úlohu nelze ladit, protože není k dispozici žádné uživatelské rozhraní hostitele. Ujistěte se, že tento příkaz spouštíte v hostiteli PowerShellu, který implementuje PSHostUserInterface. + + + Úlohu nelze ladit, protože režim ladicího programu hostitele je nastaven na None nebo Default. Režim ladicího programu hostitele musí být LocalScript nebo RemoteScript. + + + Bylo nalezeno více úloh s ID {0}. Debug-Job může ladit pouze jednu úlohu současně. + + + Bylo nalezeno více úloh s názvem {0}. Debug-Job může ladit pouze jednu úlohu současně. + + + Naslouchací proces serveru pojmenovaného kanálu, který se používá pro připojení procesu, už běží. + + + Enter-PSHostProcess nepodporuje vstup do stejné relace PowerShellu, ve které běží. + + + Bylo nalezeno více procesů s tímto názvem {0}. Pomocí ID procesu určete jeden proces, který chcete zadat. + + + Nelze zadat procese s ID „{0}“, protože nenačetl modul PowerShell nebo byl naslouchací proces pojmenovaného kanálu zakázán. + + + Nebyl nalezen žádný proces s ID: {0}. + + + Nebyl nalezen žádný proces s názvem %1 {0}. + + + Nebyl nalezen žádný pojmenovaný kanál s CustomPipeName: {0}. + + + Příkaz nelze zpracovat, protože zadaný název pipeName je příliš dlouhý. Názvy kanálů na této platformě mohou mít až {0} znaků. Název kanálu {1} má {2} znaků. + + + Aktuální hostitel nepodporuje rutinu Enter-PSHostProcess. + + + „Cílový proces pojmenovaného kanálu byl ukončen.“ + + + „Cílový proces soketu Hyper-V byl ukončen.“ + + + {0}[Proces:{1}]: {2} + + + {0}[{1}]: {2} + + + Nelze se připojit k názvu aplikační domény {0} procesu {1}. Chyba: {2}. + + + Nelze se připojit ke kanálu s názvem {0}. Chyba: {1}. + + + Modul plug-in PowerShellu nemůže zpracovat operaci připojení, protože požadované informace o vyjednávání buď chybí, nebo nejsou úplné. + + + Modulu plug-in PowerShellu se nepodařilo zpracovat operaci připojení. + + + Zadaný kontext modulu plug-in není platný. + + + Modul plug-in PowerShellu zjistil závažnou chybu při zpracování argumentů ({0}). + + + Zadaný kontext příkazu není platný. + + + Zadaná vstupní data nejsou platná. Podporována jsou pouze vstupní data typu {0}. + + + The supplied input stream is not valid. Only {0} is supported as input stream. + + + The supplied output stream set is not valid. Only {0} is supported as output stream. + + + Zadaná hodnota WSMAN_SENDER_DETAILS není platná. Nelze zpracovat WSMAN_SENDER_DETAILS s hodnotou null. + + + The supplied shell context is not valid. + + + {0} + + + NULL value is not allowed for {0} with the plugin method {1}. + + + NULL value is not allowed for input stream and output stream sets. {0} and {1} are the supported input and output streams. + + + NULL value is not allowed for {0} with the plugin method {1}. + + + NULL value is not allowed for {0} with the plugin method {1}. + + + PowerShell plugin operation is shutting down. This may happen if the hosting service or application is shutting down. + + + PowerShell plugin does not understand the option {0}. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + Od klienta je očekávána možnost s názvem {0}. Ujistěte se, že je klient kompatibilní se sestavením {1} a verzí {2} protokolu PowerShellu. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Powershell plugin does not support the protocol version {2} requested by client.</PSProtocolVersionError> + + + Powershell plugin encountered a fatal error while reporting context to WSMan service. + + + Nelze vytvořit relaci na spravovaném serveru. + + + Powershell plugin encountered a fatal error registering a wait handle for shutdown notification. + + + Nelze zadat prostředí Runspace, protože prostředí Runspace je již v této relaci použito. + + + Nelze zadat prostředí Runspace, protože není k dispozici žádný vzdálený ladicí program serveru. + + + Nelze zadat Runspace, protože se nejedná o vzdálené prostředí Runspace. + + + Chyba vzdáleného přenosu: {0} + + + Nepovedlo se otevřít připojení kanálu pro PowerShell v kontejneru. Kód chyby: {0}. + + + Nepovedlo se vytvořit pojmenovaný kanál PowerShell IPC. Kód chyby: {0}. + + + Vypršel časový limit, než bylo možné vytvořit připojení k pojmenovanému kanálu. + + + Inicializace nástroje WSMan se nezdařila. Kód chyby: {0}. + + + Server pojmenovaného kanálu nelze spustit v režimu serveru. + + + Nelze udělit vzdálený přístup k „{0}“:„{1}“. Konfigurace relace byla zaregistrována, ale tato skupina nemá přístup. Chcete-li tuto chybu vyřešit, zadejte platný název skupiny a znovu zaregistrujte konfiguraci relace. + + + Nepodařilo se získat možnosti relace pro konfiguraci relace{0}: Tato konfigurace nebyla zaregistrována v konfiguračním souboru relace (.pssc), například v konfiguraci vytvořené rutinou New-PSSessionConfigurationFile. + + + Nepovedlo se přeložit uživatelské jméno „{0}“. Ověřte uživatelské jméno a zkuste to znovu. + + + Skupiny přidružené k (virtuálnímu) účtu správce počítače + + + Nelze vytvořit nebo otevřít relaci konfigurace {0}. + + + Vynutí ověřování vstupního parametru skriptu. Tato možnost se automaticky povolí, když se zadá MountUserDrive. + + + Vytvoří v relaci PSDrive User pro použití s copy-item, když není viditelný zprostředkovatel systému souborů. + + + Člen „{0}“ musí být logická hodnota. Změňte člena na správný typ v souboru {1}. + + + Člen {0} musí být celé číslo. Změňte člena na správný typ v souboru {1}. + + + Při zpracování jednotky uživatele došlo k chybě {0}. + + + Volitelná maximální velikost v bajtech uživatelského disku vytvořeného pomocí parametru MountUserDrive. Výchozí maximální velikost uživatelského disku je 50 MB. + + + Nelze najít zprostředkovatele systému souborů. + + + Název skupinového účtu spravované služby, pod kterým se konfigurace spustí + + + Neplatný název skupinového účtu spravované služby. Název účtu musí mít tvar „DomainName\UserName“. + + + Skupinové účty, u kterých je pro použití relace nutné členství. + + + Řetězec sddl nelze analyzovat, protože obsahuje neshodné závorky: {0}. + + + Zatřiďovací tabulka vlastnosti RequiredGroups musí obsahovat pouze jeden klíč. + + + Vlastnost RequiredGroups není ve formátu zatřiďovací tabulky páru název/hodnota. Musí to být zatřiďovací tabulka formuláře (pomocí syntaxe PowerShellu): RequiredGroups = @{ Or = 'Administrators' }. + + + Neznámý klíč v konfiguraci požadovaných skupin. Zatřiďovací tabulka požadovaných skupin může obsahovat pouze hashovací klíče And a Or pro logické seskupení členství. + + + Neznámá hodnota v konfiguraci požadovaných skupin. Zatřiďovací tabulka požadovaných skupin může obsahovat jen hodnoty, které jsou buď názvy skupin, nebo jiná logická zatřiďovací tabulka. + + + Chybné ACE {0}. Běžné ACE musí mít přesně 6 oddílů. + + + Nelze vytvořit jednotku uživatele relace, protože aktuální uživatelské jméno obsahuje neplatné znaky cesty k souboru. + + + Neplatný klíč schopnosti role: {0}. Ujistěte se, že je název schopnosti role napsaný správně a že jde o platnou vlastnost konfigurace relace. + + + Neplatný typ klíče schopnosti role: {0}. Klíče schopností role musí být řetězce, které identifikují platnou vlastnost konfigurace relace. + + + Neplatný typ klíče role: {0}. Klíče role musí být řetězce, které identifikují skupinu zabezpečení. + + + Další možná příčina: + – Název domény nebo počítače nebyl součástí zadaných přihlašovacích údajů, například: DOMÉNA\Uživatelské_jméno nebo POČÍTAČ\Uživatelské_jméno. + + + Nepodařilo se spustit proces klienta SSH potřebný pro připojení vzdálené komunikace s chybou: {0}. + + + Zadaný soubor klíče {0} nebyl nalezen. + + + Relace klienta SSH skončila s chybovou zprávou: {0} + + + Pokus o připojení SSH se nezdařil po vypršení časového limitu: {0} s. + + + +Proces klienta SSH se ukončil dříve, než bylo možné navázat připojení. + + + V zadané zatřiďovací tabulce SSHConnection chybí požadovaný parametr ComputerName nebo HostName. + + + Zadaný název parametru nebo prvek v zatřiďovací tabulce SSHConnection má hodnotu null nebo je prázdný. + + + Zadaný parametr {0} zatřiďovací tabulky SSHConnection se nepodporuje. + + + Zadaná zatřiďovací tabulka SSHConnection obsahuje parametr ComputerName i HostName. Lze zadat pouze jeden. + + + Zadaná zatřiďovací tabulka SSHConnection obsahuje parametr KeyFilePath i IdentityFilePath. Lze zadat pouze jeden. + + + Nepovedlo se najít poskytnutý soubor možností role {0}. + + + Zadaný soubor schopností role {0} nemá požadovanou příponu .psrc. + + + Proces přenosu SSH byl náhle ukončen, což způsobilo přerušení této vzdálené relace. + + + PowerShell 6+ nepodporuje WOW64. Binární soubor musí odpovídat architektuře procesoru. + + + The "{0}" executable file was not found. Verify that the WOW64 feature is installed. + + + Nelze nainstalovat modul plug-in {0} do adresáře {1}. + + + Chybí knihovna DLL modulu plug-in WinRM {0} pro PowerShell. Spusťte Enable-PSRemoting a pak opakujte tento příkaz. + + + Tato sada parametrů vyžaduje WSMan a nebyla nalezena žádná podporovaná klientská knihovna WSMan. Služba WSMan není pro tento systém nainstalována nebo není k dispozici. + + + + Ukončovací kód: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Informace o procesu nelze přečíst: {0}. + + + Hostitelský systém nemá správnou verzi schématu Hyper-V. + + + Protokol HTTPS v systému Unix v současné době nepodporuje kontroly certifikační autority nebo CN. Použijte PSSessionOption -SkipCACheck a -SkipCNCheck, pokud si jste jisti, že důvěřujete serveru, ke kterému se připojujete, i síti mezi vámi. + + + Vzdálená komunikace PowerShellu je zakázaná jenom pro konfigurace PowerShellu 6+ a nemá vliv na konfigurace vzdálené komunikace Windows PowerShellu. Spuštěním této rutiny ve Windows PowerShellu ovlivníte všechny konfigurace vzdálené komunikace PowerShellu. + + + + Vzdálená komunikace PowerShellu je povolená jenom pro konfigurace PowerShellu 6+ a nemá vliv na konfigurace vzdálené komunikace Windows PowerShellu. Spuštěním této rutiny ve Windows PowerShellu ovlivníte všechny konfigurace vzdálené komunikace PowerShellu. + + + Rutina Enter-PSHostProcess je zakázaná, protože jsou vynucovány zásady řízení aplikací, například AppLocker nebo Řízení aplikací v Microsoft Defenderu. + + + Výjimka vzdáleného ladicího programu: {0}, chybová zpráva: {1} + + + Unable to create Windows PowerShell process because Windows PowerShell could not be found on this machine. + + + Argument prostředí Runspace, které se má vytvořit, musí být objekt RemoteRunspace, který není null. + + + Zatřiďovací tabulka konfigurace relace obsahuje neplatný typ klíče. Klíče by měly být řetězcové typy. + + + Konfigurační soubor relace obsahuje nepodporovanou možnost konfigurace: {0}. Jde o možnost konfigurace koncového bodu vzdálené správy, která se nevztahuje na stav relace PowerShellu. + + + Konfigurační soubor relace obsahuje neznámou možnost konfigurace: {0}. + + + Vyhodnocení výrazu může selhat + + + Vytvoření objektu PowerShellu z bloku skriptu může vyžadovat vyhodnocení některých výrazů uvnitř bloku skriptu. Vyhodnocení výrazu v tichém režimu selže a vrátí hodnotu null v režimu omezeného jazyka, pokud výraz nepředstavuje konstantní hodnotu. + + + Nepovedlo se získat stav virtuálního počítače Hyper-V. Hodnota byla typu {0}, ale očekávala se hodnota Microsoft.HyperV.PowerShell.VMState nebo System.String. + + + Technologie Hyper-V {0} během vyjednávání připojení odeslala neplatnou odpověď {1}. + + + Vyjednávání zabezpečeného připojení k Hyper-V se nezdařilo. Ujistěte se, že hostitel i host jsou aktualizováni o všechny relevantní aktualizace Microsoftu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/RunspaceInit.cs.resx b/src/System.Management.Automation/resources/cs/RunspaceInit.cs.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/RunspaceInit.cs.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/RunspacePoolStrings.cs.resx b/src/System.Management.Automation/resources/cs/RunspacePoolStrings.cs.resx new file mode 100644 index 00000000000..c0f3e507732 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/RunspacePoolStrings.cs.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Maximální velikost fondu nemůže být menší než 1. + + + Minimální velikost fondu nemůže být menší než 1. + + + Minimální velikost fondu nemůže být větší než maximální velikost fondu. + + + Stav fondu prostředí runspace není pro tuto operaci platný. + + + Operaci nelze provést, protože fond prostředí runspace není ve stavu {0}. Aktuální stav je {1}. + + + Operaci otevření fondu prostředí runspace nelze provést, protože není ve stavu BeforeOpen. Aktuální stav je {0}. + + + Objekt {0} nebyl vytvořen voláním {1} pro aktuální instanci RunspacePool. + + + Prostředí runspace nelze uvolnit do aktuálního fondu, protože do něj nepatří. + + + Tuto vlastnost nelze po otevření fondu prostředí runspace změnit. + + + Toto prostředí runspace nepodporuje operace připojení a odpojení. + + + Operaci nelze provést, protože fond prostředí runspace je ve stavu Odpojeno. + + + Operace Odpojit není na serveru podporována. Aby bylo podporováno odpojení vzdáleného fondu prostředí runspace, musí být na serveru spuštěný PowerShell 3.0 nebo novější. + + + Fond prostředí runspace {0} není nakonfigurován tak, aby poskytoval odpojené objekty PowerShellu pro příkazy spuštěné na vzdáleném serveru. Použijte statickou metodu GetRunspacePools() třídy RunspacePool k dotazování serveru a vracení objektů fondu prostředí runspace, které jsou nakonfigurovány pro tuto operaci. + + + Tento fond prostředí runspace nelze připojit, protože odpovídající fond prostředí runspace na straně serveru je připojen k jinému klientovi. + + + ResetRunspaceState se na serveru nepodporuje. Na serveru musí být spuštěný PowerShell 5.0 nebo novější. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/RunspaceStrings.cs.resx b/src/System.Management.Automation/resources/cs/RunspaceStrings.cs.resx new file mode 100644 index 00000000000..c2274ab7ed1 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/RunspaceStrings.cs.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 runspace state is not valid for this operation. + + + Cannot open the runspace because the runspace is not in the BeforeOpen state. Current state of the runspace is '{0}'. + + + Cannot perform the operation because the runspace is not in the Opened state. Current state of the runspace is '{0}'. + + + Cannot invoke the pipeline because the runspace is not in the Opened state. Current state of the runspace is '{0}'. + + + The pipeline state is not valid for this operation. + + + Cannot invoke pipeline because it has already been invoked. + + + The valid value for the parameter is PipelineResultTypes.Output. + + + The pipeline does not contain a command. + + + The pipeline was not run because a pipeline is already running. Pipelines cannot be run concurrently. + + + A nested pipeline cannot be invoked asynchronously. Use the Invoke method. + + + You should only run a nested pipeline from within a running pipeline. + + + Runspace cannot be closed while a SessionStateProxy method call is in progress. + + + Pipeline cannot be invoked while a SessionStateProxy method call is in progress. + + + A SessionStateProxy method call is in progress. Concurrent SessionStateProxy method calls are not allowed. + + + A pipeline is already running. Concurrent SessionStateProxy method calls are not allowed. + + + This property cannot be changed after the runspace has been opened. + + + One or more errors occurred processing the module '{0}' specified in the InitialSessionState object used to create this runspace. See the ErrorRecords property for a complete list of errors. The first error was: {1} + + + The thread options can only be changed if the apartment state is multithreaded apartment (MTA), the current options are UseNewThread or UseCurrentThread, and the new value is ReuseThread. + + + {0} cannot be false when language mode is {1} or {2}. + + + You cannot disconnect a local-only runspace. + + + The Connect operation is not supported on local runspaces. + + + The session is busy. You will be connected to the session as soon as it is available. To cancel the Enter-PSSession command, press Ctrl-C. + + + The command cannot be completed. Script invocation is not supported in this session configuration. This can occur if the session configuration is in no-language mode. + + + You cannot use Disconnect and Connect operations on local runspaces. + + + Cannot connect the pipeline because the runspace is not in the Opened state. Current state of runspace is '{0}'. + + + Cannot construct a RemoteRunspace. The provided RunspacePool object is not valid. + + + There is no disconnected command associated with this runspace. + + + The disconnection operation is not supported on the remote computer. To support disconnecting, the remote computer must be running Windows PowerShell 3.0 or a later version of Windows PowerShell and using the WSMan transport. + + + Cannot connect the PSSession because the session is not in the Disconnected state, or is not available for connection. + + + Value for parameter cannot be PipelineResultTypes.None or PipelineResultTypes.Output. + + + Valid values for the parameter are PipelineResultTypes.Output or PipelineResultTypes.Null. + + + Debug stream redirection is not supported on the targeted remote computer. + + + Verbose stream redirection is not supported on the targeted remote computer. + + + Warning stream redirection is not supported on the targeted remote computer. + + + Information stream redirection is not supported on the targeted remote computer. + + + You have entered a session that is busy running a command or script. Because output is routed to job "{0}", you will not see output in the console. You can wait for the running command to finish, or cancel the command and get an input prompt by pressing Ctrl-C. + + + + You have entered a session that is busy running a command or script and output will be displayed in the console. You can wait for the running command to finish or cancel it and get an input prompt by pressing Ctrl-C. + + + + You have entered a session that is currently stopped at a debug breakpoint inside a running command or script. Use the PowerShell command line debugger to continue debugging. + + + + DefaultRunspace must be a LocalRunspace + + + The static PrimaryRunspace property can only be set once, and has already been set. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/SecuritySupportStrings.cs.resx b/src/System.Management.Automation/resources/cs/SecuritySupportStrings.cs.resx new file mode 100644 index 00000000000..130d1dff600 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/SecuritySupportStrings.cs.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Certifikát nelze načíst. Hodnota {0} se musí přeložit na cestu v systému souborů. + + + Certifikát {0} nelze použít k šifrování. Certifikáty používané k šifrování musí mít nastavené použití klíče šifrování dat nebo šifrování klíče a obsahovat rozšířené použití klíče šifrování dokumentů ({1}). + + + Nelze načíst certifikát. Identifikátor {0} odpovídá více certifikátům. Pokud chcete zašifrovat data pro více příjemců, zadejte do parametru {1} více konkrétních hodnot místo zástupného znaku, který odpovídá více certifikátům. + + + Certifikát pro šifrování nelze načíst. Nastavení certifikátu {0} nepředstavuje platný certifikát kódovaný pomocí Base64 ani platný certifikát zadaný souborem, adresářem, kryptografickým otiskem nebo názvem subjektu. + + + UPOZORNĚNÍ: Certifikát {0} obsahuje privátní klíč. Certifikáty pro protokolování chráněných událostí používané k šifrování by měly obsahovat pouze veřejný klíč. + + + CHYBA: Zprávu protokolu událostí {0} nelze chránit: {1} + + + CHYBA: Nelze najít nebo použít certifikát: {0} + + + Klíč relace není k dispozici pro šifrování zabezpečeného řetězce. + + + Neplatný posun ve vyrovnávací paměti + + + Neplatná data veřejného klíče + + + Nelze importovat veřejný klíč. + + + Neplatná data klíče relace + + + Spuštění souboru skriptu {0} je blokováno systémovou zásadou. + + + Byla vrácena neznámá hodnota vynucení zásad souboru skriptu: {0}. + + + Čtení souboru skriptu + + + Soubor skriptu {0} není podle zásad důvěryhodný a bude spuštěn v režimu ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/Serialization.cs.resx b/src/System.Management.Automation/resources/cs/Serialization.cs.resx new file mode 100644 index 00000000000..a84788dad23 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/Serialization.cs.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Byl očekáván atribut {0}. + + + Značka XML {0} nebyla rozpoznána. + + + Pro referenceId {0} nebyl nalezen žádný objekt + + + Atribut Name pro klíč slovníku je nesprávně zadán. + + + Atribut Name pro hodnotu slovníku je nesprávně zadán. + + + Verze objektu PSObject není platná. + + + Verze příchozího objektu PSObject je {0}. Očekávaná hodnota je 1. + + + Nelze zpracovat názvy, protože pro identifikátor referenceId {0} nebyly nalezeny žádné názvy TypeNames. + + + Hodnota parametru hloubky musí být větší nebo rovna 1. + + + Aktuální typ uzlu je {0}. Očekávaný typ je {1}. + + + Není zadán klíč pro položku slovníku. + + + Není zadána hodnota pro položku slovníku. + + + Neexistují žádné další objekty, které by bylo možné deserializovat. + + + Hodnota null je zadána jako klíč slovníku. + + + Obsah typu primitiva {0} není platný. + + + Serializovaný kód XML je vnořený příliš hluboko. + + + Serializátor byl zavřen. + + + Data v příkazu překročila maximální velikost povolenou konfigurací relace. Povolené maximum je {0} MB. Změňte vstup, použijte jinou konfiguraci relace nebo změňte vlastnosti konfigurace relace „{1}“ a „{2}“ ve vzdáleném počítači. + + + Deserializace šifrovaného zabezpečeného řetězce se nezdařila + + + Typ klíče {0} není platný. Třída PSPrimitiveDictionary přijímá pouze klíče typu System.String. + + + Typ hodnoty {0} není platný. Třída PSPrimitiveDictionary přijímá pouze hodnoty typů, které jsou plně serializovatelné přes vzdálenou komunikaci PowerShellu. Seznam plně serializovatelných typů najdete v tématu nápovědy about_Remoting. + + + Nepovedlo se dešifrovat data. Data nebyla tímto klíčem šifrována. + + + Hodnota parametru {0} není platný šifrovaný řetězec. + + + Zadaný {0} není platný. Platné nastavení délky pro {0} je 128 bitů, 192 bitů nebo 256 bitů. + + + Deserializace SecureString je aktuálně podporována pouze ve Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/SessionStateProviderBaseStrings.cs.resx b/src/System.Management.Automation/resources/cs/SessionStateProviderBaseStrings.cs.resx new file mode 100644 index 00000000000..7ddc2d81f77 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/SessionStateProviderBaseStrings.cs.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nastavit položku + + + Položka: {0} Hodnota: {1} + + + Vymazat položku + + + Položka: {0} + + + Odebrat položku + + + Položka: {0} + + + Nová položka + + + Položka: {0} Typ: {1} Hodnota: {2} + + + Kopírovat položku + + + Položka: {0} Cíl: {1} + + + Přejmenovat položku + + + Položka: {0} Nový název: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/SessionStateStrings.cs.resx b/src/System.Management.Automation/resources/cs/SessionStateStrings.cs.resx new file mode 100644 index 00000000000..67360500c67 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/SessionStateStrings.cs.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 the returned information because the information returned from the provider's Start method was for a different provider than the one passed. + + + Cannot process the returned information because the information returned from the provider's Start method was null. + + + Attempting to perform the GetItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the SetItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the SetItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the ClearItem operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the InvokeDefaultAction operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the InvokeDefaultAction operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the ItemExists operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the ItemExists operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the IsValidPath operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the IsItemContainer operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the RemoveItem operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the GetChildItems operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetChildItems operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetChildNames operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetChildNames operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the RenameItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the RenameItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the NewItem operation on the '{0}' provider failed for the path '{1}'. {2} + + + The dynamic parameters for the NewItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the HasChildItems operation on the '{0}' provider failed for the path '{1}'. {2} + + + Attempting to perform the CopyItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the CopyItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetParentPath operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the NormalizeRelativePath operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the MakePath operation operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the GetChildName operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the MoveItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the MoveItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the SetProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the SetProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the ClearProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the ClearProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the NewProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the NewProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the RemoveProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the RemoveProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the CopyProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the CopyProperty operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the MoveProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the MoveProperty operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the RenameProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + Dynamic parameters for RenameProperty cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Content reader cannot be retrieved for the '{0}' provider for the path '{1}'. {2} + + + The dynamic parameters for the GetContentReader operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Content writer cannot be retrieved for the '{0}' provider for the path '{1}'. {2} + + + The dynamic parameters for the GetContentWriter operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Unable to get content because it is a directory: '{0}'. Please use 'Get-ChildItem' instead. + + + Unable to write content because it is a directory: '{0}'. + + + There is no location history left to navigate backwards. + + + There is no location history left to navigate forwards. + + + The BoundedStack is empty. + + + Attempting to perform the ClearContent operation on the '{0}' provider failed for path '{1}'. {2} + + + Unable to clear content of '{0}' because it is a directory. Clear-Content is only supported on files. + + + The dynamic parameters for the ClearContent operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetSecurityDescriptor operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the SetSecurityDescriptor operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the Start operation on the '{0}' provider failed. {1} + + + Attempting to perform the InitializeDefaultDrives operation on the '{0}' provider failed. + + + Attempting to perform the NewDrive operation on the '{0}' provider failed for the drive with root '{1}'. {2} + + + Dynamic parameters for NewDrive cannot be retrieved for the '{0}' provider. {1} + + + The invocation of RemoveDrive on the '{0}' provider failed. {1} + + + Drive '{0}' cannot be removed because the provider '{1}' prevented it. + + + The path '{0}' referred to an item that was outside the base '{1}'. + + + The invocation of Seek on the '{0}' provider's content writer failed for path '{1}'. {2} + + + The invocation of Close on the '{0}' provider's content reader or writer failed for path '{1}'. {2} + + + The invocation of Read on the '{0}' provider's content reader failed for path '{1}'. {2} + + + The invocation of Write on the '{0}' provider's content writer failed for path '{1}'. {2} + + + The provider '{0}' cannot be used to get or set data using the variable syntax. {2} + + + The variable syntax cannot be used to get or set data in the provider. {2} + + + Alias is not writeable because alias {0} is read-only or constant and cannot be written to. + + + Cannot write to function {0} because it is read-only or constant. + + + Cannot overwrite variable {0} because it is read-only or constant. + + + Cannot access the variable '${0}' because it is a private variable. + + + Cannot access the command '{0}' because it is a private command. + + + Cannot access the command because it is a private command. + + + Cannot access the session state resource because it is a private resource. + + + Alias was not removed because alias {0} is constant or read-only. + + + Cannot remove function {0} because it is constant. + + + Cannot remove variable {0} because it is constant or read-only. If the variable is read-only, try the operation again specifying the Force option. + + + Alias {0} cannot be modified because it is constant. + + + Alias {0} cannot be modified because it is read-only. + + + Cannot modify function {0} because it is constant. + + + Cannot modify function {0} because it is read-only. + + + Alias {0} cannot be made constant after it has been created. Aliases can only be made constant at creation time. + + + Existing function {0} cannot be made constant. Functions can be made constant only at creation time. + + + Existing variable {0} cannot be made constant. Variables can be made constant only at creation time. + + + The AllScope option cannot be removed from the alias '{0}'. + + + The AllScope option cannot be removed from the function '{0}'. + + + The AllScope option cannot be removed from the variable '{0}'. + + + The function definition '{0}' contained a scope qualifier but no function name. + + + Cannot remove provider {0}. All drives associated with provider {0} must be removed before provider {0} can be removed. + + + Cannot process the drive name because the drive name contains one or more of the following characters that are not valid: ; ~ / \ . : + + + New drive creation failed because the provider does not allow the creation of the new drive. + + + The provided value '{0}' resolved to more than one location stack. + + + Cannot find location stack '{0}'. It does not exist or it is not a container. + + + Cannot find path '{0}' because it does not exist. + + + Cannot find alias because alias '{0}' does not exist. + + + Cannot set the location because path '{0}' resolved to multiple containers. You can only set the location to a single container at a time. + + + Cannot process variable because variable path '{0}' resolved to multiple items. You can get or set the variable value only one item at a time. + + + Cannot find drive. A drive with the name '{0}' does not exist. + + + Cannot find a provider with the name '{0}'. + + + Cannot find a provider with the name '{0}'. The name is not in the proper format. A provider name can only be alphanumeric characters, or a PowerShell snap-in name that is followed by a single '\', followed by alphanumeric characters. + + + '{0}' resolved to more than one provider name. Possible matches include:{1}. + + + An error occurred attempting to create an instance of the provider. The provider type name of '{0}' could not be found in the assembly. + + + The specified provider name '{0}' cannot be used because it contains one or more of the following characters that are not valid: \ [ ] ? * : + + + An error occurred attempting to create an instance of the provider '{0}'. {1} + + + Cannot find a variable with the name '{0}'. + + + Cannot find a trace source with the name '{0}'. + + + A drive with the name '{0}' already exists. + + + A variable with name '{0}' already exists. + + + The alias is not allowed, because an alias with the name '{0}' already exists. + + + Cannot register the cmdlet provider because a cmdlet provider with the name '{0}' already exists. + + + The path does not refer to a file system path. + + + Global scope cannot be removed. + + + The scope number '{0}' exceeds the number of active scopes. + + + Cannot compare PSDriveInfo. A PSDriveInfo instance can be compared only to another PSDriveInfo instance. + + + The cmdlet provider cannot stream the results because no cmdlet was specified through which to stream the output. + + + The cmdlet provider cannot stream the results because no cmdlet was specified through which to stream the error. + + + Home location for this provider is not set. To set the home location, call "(get-psprovider '{0}').Home = 'path'". + + + The path is not in the correct format. Provider paths must contain a provider Id, followed by "::", followed by a provider specific path. + + + Cannot move the item because the destination path can resolve only to a single path. + + + Cannot move the item because the source and destination paths did not resolve to the same provider. + + + Cannot move the item because the source path points to one or more items and the destination path is not a container. Validate that the destination path is a container and try again. + + + Cannot move the item because the destination resolved to multiple paths. Specify a destination path that resolves to a single destination and try again. + + + Container cannot be copied onto existing leaf item. + + + Container cannot be copied to another container. The -Recurse or -Container parameter is not specified. + + + Source and destination path did not resolve to the same provider. + + + Cannot rename item because the path resolved to multiple items. Only one item can be renamed at a time. + + + The provider '{0}' cannot be used to resolve the path '{1}' because of an error in the provider. + + + Cannot use interface. The IContentCmdletProvider interface is not implemented by this provider. + + + Cannot use interface. The IPropertyCmdletProvider interface is not supported by this provider. + + + Cannot use interface. The IDynamicPropertyCmdletProvider interface is not implemented by this provider. + + + The NavigationCmdletProvider methods are not supported by this provider. + + + Provider methods not processed. The ContainerCmdletProvider methods are not supported by this provider. + + + Cannot call methods. The ItemCmdletProvider methods are not supported by this provider. + + + DriveCmdletProvider methods are not supported by this provider. + + + Provider operation stopped because the provider does not support this operation. + + + Provider operation stopped because the provider does not support the 'Depth' parameter. + + + Cannot call method. The content Seek method is not supported by this provider. + + + Cannot perform the ClearContent operation. The ClearContent operation is not supported by this provider. + + + The provider does not support the use of credentials. Perform the operation again without specifying credentials. + + + The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying credentials. + + + The provider does not support transactions. Perform the operation again without the -UseTransaction parameter. + + + Cannot call method. The provider does not support the use of filters. + + + Cannot create drive. The provider does not support the use of credentials. + + + The item at path '{0}' already exists. + + + Cannot copy item. Item at the path '{0}' does not exist. + + + The item at the path '{0}' does not exist. + + + Drive that contains a view of the aliases stored in a session state + + + Drive that contains a view of the environment variables for the process + + + Drive that contains a view of the functions stored in a session state + + + Drive that contains a view of those variables stored in a session state + + + Drive that maps to the temporary directory path for the current user + + + Link '{0}' cannot be created because the target Value was not specified. + + + References to the null variable always return the null value. Assignments have no effect. + + + Maximum number of history objects to retain in a session + + + Cannot rename function because function {0} is read-only or constant. + + + Cannot rename alias because alias {0} is read-only or constant. + + + Cannot rename variable because variable {0} is read-only or constant. + + + Cannot set options on the local variable {0}. Use New-Variable to create a variable that allows options to be set. + + + Cmdlet {0} cannot be modified because it is read-only. + + + Cannot remove variable {0} because the variable has been optimized and is not removable. Try using the Remove-Variable cmdlet (without any aliases), or dot-sourcing the command that you are using to remove the variable. + + + Cannot overwrite variable {0} because the variable has been optimized. Try using the New-Variable or Set-Variable cmdlet (without any aliases), or dot-source the command that you are using to set the variable. + + + The parameters {0} and {1} cannot be used together. Please specify only one parameter. + + + The Tail parameter currently is supported only for the FileSystem provider. + + + The alias is not allowed, because a command with the name '{0}' and command type '{1}' already exists. + + + Cannot run software. Permission is denied. + + + '-{0}' and '-{1}' are mutually exclusive and cannot be specified at the same time. + + + The path '{0}' is not valid. Only absolute paths are supported on remote copy operations. + + + Cannot validate remote path '{0}'. + + + Cannot perform operation because the session {0} is set to {1}. + + + '{0}' parameter cannot be null or empty. + + + Session State Variables + + + Changing or creating the variable '{0}' scope to AllScope will be prevented in ConstrainedLanguage mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/StringDecoratedStrings.cs.resx b/src/System.Management.Automation/resources/cs/StringDecoratedStrings.cs.resx new file mode 100644 index 00000000000..94c131b1401 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/StringDecoratedStrings.cs.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Tato metoda podporuje pouze hodnoty ANSI a PlainText. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/SubsystemStrings.cs.resx b/src/System.Management.Automation/resources/cs/SubsystemStrings.cs.resx new file mode 100644 index 00000000000..ebffc2a5733 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/SubsystemStrings.cs.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 + + + Subsystém {0} neumožňuje registrovat více než jednu implementaci. + + + Implementace s ID {0} už je pro subsystém {1} zaregistrovaná. + + + Subsystém {0} neumožňuje zrušení registrace implementace. + + + Pro subsystém {0} nebyla zaregistrována žádná implementace. + + + Registrovaná implementace s ID {0} nebyla nalezena. + + + Zadaný typ subsystému {0} není znám. + + + Místo základního rozhraní ISubsystem musíte zadat konkrétní typ subsystému. + + + Zadaný druh subsystému {0} není znám. + + + Pro cílový druh subsystému {0} musí zadaná instance subsystému implementovat odpovídající konkrétní rozhraní nebo abstraktní třídu {1}. + + + Deklarovaná metadata pro druh subsystému {0} nejsou platná. Subsystém, který vyžaduje definování rutin nebo funkcí, nemůže povolit více registrací, protože by to vedlo k tomu, že by jedna implementace přepsala příkazy definované jinou implementací. + + + Vlastnost Id implementace pro subsystém {0} nesmí být prázdný identifikátor GUID. + + + Vlastnost Name implementace pro subsystém {0} nesmí mít hodnotu null ani být prázdným řetězcem. + + + Vlastnost Description implementace pro subsystém {0} nesmí mít hodnotu null ani být prázdným řetězcem. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/SuggestionStrings.cs.resx b/src/System.Management.Automation/resources/cs/SuggestionStrings.cs.resx new file mode 100644 index 00000000000..f44a97269e4 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/SuggestionStrings.cs.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 + + + Příkaz {0} se nenašel, ale v aktuálním umístění existuje. +PowerShell ve výchozím nastavení nenačítá příkazy z aktuálního umístění (viz Get-Help about_Command_Precedence). + +Pokud tomuto příkazu důvěřujete, spusťte místo něj následující příkaz: + + + Nejpodobnější příkazy: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/TabCompletionStrings.cs.resx b/src/System.Management.Automation/resources/cs/TabCompletionStrings.cs.resx new file mode 100644 index 00000000000..2d3ad82b2f0 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/TabCompletionStrings.cs.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Výsledek dokončování tabulátorem nelze správně deserializovat, protože vzdálené prostředí runspace neobsahuje instanci TypeTable. + + + Nelze získat přístup k vlastnostem instance null typu CompletionResult. + + + Bitový operátor NOT + + + Logická hodnota Ne. Neguje výrok, který za ním následuje. + + + Rovná se – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které se rovnají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud se levý operand rovná pravému operandu. + + + Rovná se – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které se rovnají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud se levý operand rovná pravému operandu. + + + Rovná se – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které se rovnají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud se levý operand rovná pravému operandu. + + + Nerovná se – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které se nerovnají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud se levý operand nerovná pravému operandu. + + + Nerovná se – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které se nerovnají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud se levý operand nerovná pravému operandu. + + + Nerovná se – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které se nerovnají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud se levý operand nerovná pravému operandu. + + + Větší nebo rovno – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou větší než nebo rovny pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud je levý operand větší než nebo roven pravému operandu. + + + Větší nebo rovno – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou větší než nebo rovny pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud je levý operand větší než nebo roven pravému operandu. + + + Větší nebo rovno – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou větší než nebo rovny pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud je levý operand větší než nebo roven pravému operandu. + + + Větší než – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou větší než pravý operand. V opačném případě vrátí hodnotu TRUE, pokud je levý operand větší než pravý operand. + + + Větší než – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou větší než pravý operand. V opačném případě vrátí hodnotu TRUE, pokud je levý operand větší než pravý operand. + + + Větší než – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou větší než pravý operand. V opačném případě vrátí hodnotu TRUE, pokud je levý operand větší než pravý operand. + + + Menší než – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou menší než pravý operand. V opačném případě vrátí hodnotu TRUE, pokud je levý operand menší než pravý operand. + + + Menší než – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou menší než pravý operand. V opačném případě vrátí hodnotu TRUE, pokud je levý operand menší než pravý operand. + + + Menší než – rozlišují se malá a velká písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou menší než pravý operand. V opačném případě vrátí hodnotu TRUE, pokud je levý operand menší než pravý operand. + + + Menší nebo rovno – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou menší než nebo rovny pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud je levý operand menší než nebo roven pravému operandu. + + + Menší nebo rovno – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou menší než nebo rovny pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud je levý operand menší než nebo roven pravému operandu. + + + Menší nebo rovno – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které jsou menší než nebo rovny pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud je levý operand menší než nebo roven pravému operandu. + + + Operátor porovnávání se zástupnými znaky – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které odpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand odpovídá pravému operandu. + + + Operátor porovnávání se zástupnými znaky – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které odpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand odpovídá pravému operandu. + + + Operátor porovnávání pomocí zástupných znaků – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které odpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand odpovídá pravému operandu. + + + Operátor porovnávání se zástupnými znaky – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které neodpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand neodpovídá pravému operandu. + + + Operátor porovnávání se zástupnými znaky – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které neodpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand neodpovídá pravému operandu. + + + Operátor porovnávání pomocí zástupných znaků – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které neodpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand neodpovídá pravému operandu. + + + Operátor porovnávání regulárních výrazů – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které odpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand odpovídá pravému operandu. + + + Operátor porovnávání regulárních výrazů – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které odpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand odpovídá pravému operandu. + + + Operátor porovnávání regulárních výrazů – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které odpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand odpovídá pravému operandu. + + + Operátor porovnávání regulárních výrazů – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které neodpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand neodpovídá pravému operandu. + + + Operátor porovnávání regulárních výrazů – nerozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které neodpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand neodpovídá pravému operandu. + + + Operátor porovnávání regulárních výrazů – rozlišují se velká a malá písmena. Pokud je levý operand kolekcí, vrátí hodnoty z kolekce, které neodpovídají pravému operandu. V opačném případě vrátí hodnotu TRUE, pokud levý operand neodpovídá pravému operandu. + + + Operátor nahrazení – nerozlišují se velká a malá písmena. Změní levý operand. Příklad: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operátor nahrazení – nerozlišují se velká a malá písmena. Změní levý operand. Příklad: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operátor nahrazení – rozlišují se velká a malá písmena Změní levý operand. Příklad: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (pravý operand) přesně odpovídá alespoň jedné z hodnot v levém operandu. + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (pravý operand) přesně odpovídá alespoň jedné z hodnot v levém operandu. + + + Operátor zahrnutí – rozlišují se velká a malá písmena. Vrátí hodnotu TRUE pouze v případě, že testovaná hodnota (pravý operand) přesně odpovídá alespoň jedné z hodnot v levém operandu. + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (pravý operand) přesně neodpovídá žádné z hodnot v levém operandu. + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (pravý operand) přesně neodpovídá žádné z hodnot v levém operandu. + + + Operátor zahrnutí – rozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (pravý operand) přesně neodpovídá žádné z hodnot v levém operandu. + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (levý operand) přesně odpovídá alespoň jedné z hodnot v pravém operandu. + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (levý operand) přesně odpovídá alespoň jedné z hodnot v pravém operandu. + + + Operátor zahrnutí – rozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (levý operand) přesně odpovídá alespoň jedné z hodnot v pravém operandu. + + + Operátor zahrnutí – rozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (levý operand) přesně neodpovídá žádné z hodnot v pravém operandu. + + + Operátor zahrnutí – nerozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (levý operand) přesně neodpovídá žádné z hodnot v pravém operandu. + + + Operátor zahrnutí – rozlišují se velká a malá písmena. Vrátí hodnotu TRUE, pokud testovaná hodnota (levý operand) přesně neodpovídá žádné z hodnot v pravém operandu. + + + Rozdělení – nerozlišují se velká a malá písmena. Rozdělí jeden nebo více řetězců na podřetězce. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Rozdělení – nerozlišují se velká a malá písmena. Rozdělí jeden nebo více řetězců na podřetězce. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Rozdělení – rozlišují se velká a malá písmena. Rozdělí jeden nebo více řetězců na podřetězce. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Vrátí hodnotu TRUE, pokud levý operand není instancí zadaného typu .NET Framework (pravý operand). + + + Vrátí hodnotu TRUE, pokud levý operand je instancí zadaného typu .NET Framework (pravý operand). + + + Převede levý operand na zadaný typ .NET Framework (pravý operand). + + + Formátuje řetězce pomocí metody Format objektů String. + + + Logické A Vrátí hodnotu TRUE, pokud jsou oba výroky pravdivé. + + + Bitový operátor AND + + + Logické NEBO TRUE, pokud jsou jeden nebo oba výroky TRUE. + + + Bitový operátor OR (včetně) + + + Logické XOR Vrátí hodnotu TRUE, pokud jeden z příkazů vrátí hodnotu TRUE a druhý hodnotu FALSE. + + + Bitový operátor OR (výhradní) + + + Spojení – zkombinujte více řetězců do jednoho řetězce. +-Join <Řetězec[]> +<Řetězec[]> -Join <Oddělovač> + + + Bitový operátor Posun doleva Vloží nulu do nejvíce vpravo umístěné pozice. + + + Bitový operátor Posun doprava Vloží nulu do nejvíce vlevo umístěné pozice. U hodnot se znaménkem se zachová znaménkový bit. + + + [string] +Určuje název vytvářené vlastnosti. + + + [string] +Určuje název vytvářené vlastnosti. + + + [scriptblock] +Blok skriptu použitý k výpočtu hodnoty nové vlastnosti + + + [string] +Definuje způsob zobrazení hodnot ve sloupci. +Platné hodnoty jsou left, center nebo right. + + + [string] +Určuje formátovací řetězec, který definuje způsob formátování hodnoty pro výstup. + + + [int] +Určuje maximální šířku sloupce v tabulce při zobrazení hodnoty. +Hodnota musí být větší než 0. + + + [int] +Klíč depth určuje hloubku rozbalení jednotlivých vlastností. + + + [bool] +Určuje pořadí řazení pro jednu nebo více vlastností. + + + [bool] +Určuje pořadí řazení pro jednu nebo více vlastností. + + + [String[]] +Určuje názvy protokolů, ze kterých se načítají události. +Podporuje zástupné znaky. + + + [String[]] +Určuje poskytovatele protokolů událostí, ze kterých se načítají události. +Podporuje zástupné znaky. + + + [String[]] +Určuje cesty k souborům protokolů, ze kterých se načítají události. +Platné formáty souborů jsou: .etl, .evt a .evtx + + + [Long[]] +Vybere události se zadanými bitovými maskami klíčových slov. +Následují standardní klíčová slova: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Vybere události se zadanými ID událostí. + + + [int[]] +Vybere události se zadanými úrovněmi protokolování. +Platné úrovně protokolování jsou: +1: Kritická +2: Chyba +3: Upozornění +4: Informační +5: Podrobné + + + [datetime] +Vybere události vytvořené po zadaném datu a čase. + + + [datetime] +Vybere události vytvořené před zadaným datem a časem. + + + [string] +Vybere události vygenerované zadaným uživatelem. +Může to být buď řetězcová reprezentace identifikátoru SID, nebo doména a uživatelské jméno ve formátu DOMÉNA\UŽIVATELSKÉ_JMÉNO nebo UŽIVATELSKÉ_JMÉNO@DOMÉNA. + + + [string[]] +Vybere události s některou ze zadaných hodnot v oddílu EventData. + + + [hashtable] +Vyloučí události, které odpovídají hodnotám zadaným v zatřiďovací tabulce. + + + [string] nebo [hashtable] +Určuje pole modulů PowerShellu, které skript vyžaduje. +Každý prvek může být buď řetězec obsahující název modulu jako hodnotu, nebo zatřiďovací tabulka s následujícími klíči: +Název: Název modulu +GUID: GUID modulu +Jedna z následujících možností: +ModuleVersion: Určuje minimální přijatelnou verzi modulu. +RequiredVersion: Určuje přesnou požadovanou verzi modulu. +MaximumVersion: Určuje nejvyšší přípustnou verzi modulu. + + + [string] +Určuje edici PowerShellu, kterou skript vyžaduje. +Platné hodnoty jsou Core a Desktop. + + + [switch] +Určuje, že PowerShell musí být spuštěný jako správce ve Windows. +Toto musí být poslední parametr na řádku příkazu #requires. + + + [version] +Určuje minimální verzi PowerShellu, kterou skript vyžaduje. + + + Určuje, že skript vyžaduje ke spuštění PowerShell 7+. + + + Určuje, že skript ke spuštění vyžaduje Windows PowerShell 5.1. + + + [string] +Povinné. Určuje název modulu. + + + [string] +Volitelné. Určuje identifikátor GUID modulu. + + + [string] +Určuje minimální přijatelnou verzi modulu. + + + [string] +Určuje přesnou požadovanou verzi modulu. + + + [string] +Určuje maximální přijatelnou verzi modulu. + + + Stručný popis funkce nebo skriptu. +Toto klíčové slovo lze použít v každém tématu jen jednou. + + + Podrobný popis funkce nebo skriptu. +Toto klíčové slovo lze použít v každém tématu jen jednou. + + + .PARAMETER <Název-parametru> +Popis parametru +Pro každý parametr v syntaxi funkce nebo skriptu přidejte klíčové slovo .PARAMETER. + + + Ukázkový příkaz používající funkci nebo skript, volitelně následovaný ukázkovým výstupem a popisem. +Toto klíčové slovo opakujte pro každý příklad. + + + Typy .NET objektů, které lze předat do funkce nebo skriptu. +Můžete také zahrnout popis vstupních objektů. + + + Typ objektů .NET, které rutina vrací. +Můžete také zahrnout popis vrácených objektů. + + + Další informace o funkci nebo skriptu + + + Název souvisejícího tématu +Opakujte klíčové slovo .LINK pro každé související téma. +Obsah klíčového slova .Link může obsahovat také identifikátor URI odkazující na online verzi stejného tématu nápovědy. + + + Název technologie nebo funkce, kterou funkce nebo skript používá nebo se kterou souvisí. + + + Název role uživatele pro téma nápovědy + + + Klíčová slova, která popisují zamýšlené použití funkce + + + .FORWARDHELPTARGETNAME <Název-Příkazu> +Přesměruje na téma nápovědy pro zadaný příkaz. + + + .FORWARDHELPCATEGORY <Kategorie> +Určuje kategorii nápovědy položky v .ForwardHelpTargetName. + + + .REMOTEHELPRUNSPACE <proměnná-PSSession> +Určuje relaci obsahující téma nápovědy. +Zadejte proměnnou obsahující objekt PSSession. + + + .EXTERNALHELP <Soubor nápovědy XML> +Klíčové slovo .ExternalHelp je vyžadováno, pokud je funkce nebo skript zdokumentován v souborech XML. + + + Určuje cestu k sestavení .NET, které se má načíst. + +pomocí sestavení <cesta-k-sestavení.NET> + + + Určuje modul PowerShellu, ze kterého se načítají třídy. + +pomocí modulu <NázevModulu nebo Cesta> + +pomocí modulu <ModuleSpecification hashtable> + + + Určuje obor názvů .NET pro překládání typů z oboru názvů nebo aliasu oboru názvů. + +pomocí oboru názvů <obor-názvů-.NET> + +pomocí oboru názvů <NázevAliasu> = <obor-názvů-.NET> + + + Určuje alias pro typ .NET. + +pomocí typu <NázevAliasu> = <typ-.NET> + + + Normální řetězec. + + + Řetězec obsahující nerozbalené odkazy na proměnné prostředí, které se rozbalí při načtení hodnoty. + + + Binární data v libovolné podobě + + + 32bitové binární číslo. + + + Pole řetězců. + + + 64bitové binární číslo. + + + Nepodporovaný datový typ registru + + + ',' – čárka + + + ', ' - čárka a mezera + + + ';' – středník + + + '; ' – středník mezera + + + {0} – nový řádek + + + '-' – pomlčka + + + ' ' – mezera + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/TransactionStrings.cs.resx b/src/System.Management.Automation/resources/cs/TransactionStrings.cs.resx new file mode 100644 index 00000000000..3233c0d87fc --- /dev/null +++ b/src/System.Management.Automation/resources/cs/TransactionStrings.cs.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Transakci nelze použít. Žádná transakce není aktivní. + + + Transakci nelze potvrdit. Žádná transakce není aktivní. + + + Transakci nelze vrátit zpět, protože není aktivní žádná transakce. + + + Transakci nelze vrátit zpět. Transakce již byla potvrzena. + + + Transakci nelze potvrdit. Transakce již byla potvrzena. + + + Transakci nelze potvrdit. Transakce byla vrácena zpět nebo vypršel časový limit. + + + Transakci nelze vrátit zpět. Transakce již byla vrácena zpět nebo vypršel časový limit. + + + Nelze nastavit aktivní transakci. Nebyla vytvořena žádná transakce. + + + Nelze nastavit aktivní transakci. Aktivní transakce byla vrácena zpět nebo vypršel časový limit. + + + Tato rutina vyžaduje aktivní transakci. Aktuální transakce již byla potvrzena nebo vrácena zpět. + + + Tato rutina vyžaduje transakci. Spusťte příkaz znovu s parametrem -UseTransaction. + + + Transakci nelze použít. Nebyla spuštěna žádná transakce. + + + Transakci nelze použít. Transakce byla potvrzena. + + + Transakci nelze použít. Transakce byla vrácena zpět nebo vypršel časový limit. + + + Transakci nelze použít. Vypršel časový limit transakce. + + + Základní transakce nebyla nastavena. + + + Základní transakce není aktivní. + + + Základní transakci nelze nastavit po vytvoření jiných transakcí. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/TypesXmlStrings.cs.resx b/src/System.Management.Automation/resources/cs/TypesXmlStrings.cs.resx new file mode 100644 index 00000000000..707d47ec416 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/TypesXmlStrings.cs.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : Chyba: {3} + + + {0}, {1}({2}) : Chyba v typu {3}: {4} + + + Uzel {0} se pod uzlem {1} smí vyskytovat jen jednou. Nadřazený uzel {1} bude ignorován. + + + Uzel {0} není povolený. Povolené jsou následující uzly: {1}. + + + Uzel {0} by neměl obsahovat vnitřní text. + + + Uzel {0} by měl obsahovat vnitřní text. + + + Uzel {0} se nenašel. Pod uzlem {1} se smí vyskytovat jen jednou. Nadřazený uzel {1} bude ignorován. + + + Uzel Type musí obsahovat Members, TypeConverters nebo TypeAdapters. + + + Instanci převaděče typů pro typ {0} nejde vytvořit kvůli výjimce: {1}. + + + PowerShell nemůže vytvořit instanci adaptéru typů pro typ {0} kvůli následující výjimce: {1}. + + + Adaptovaný typ {0} není platný. + + + TypeConverter byl ignorován, protože už se vyskytuje. + + + TypeAdapter byl ignorován, protože už se vyskytuje. + + + Typ {0} musí být TypeConverter nebo PSTypeConverter. + + + Typ {0} by měl být PSPropertyAdapter. + + + Člen {0} už existuje. + + + Následující název členu je rezervovaný: {0} + + + Výjimka: {0} + + + ScriptProperty musí obsahovat getter nebo setter. + + + CodeProperty musí obsahovat getter nebo setter. + + + {0}, {1} : {2} + + + Místo hodnoty {0} použijte TRUE nebo FALSE. + + + Uzel {0} by neměl obsahovat atribut {1}. + + + {0}, {1}: Soubor se nenašel. + + + {0}, {1}: Soubor byl přeskočen, protože už byl načtený pomocí {2}. + + + Klíč registru se nenašel: {0}{1}. Konfigurační soubory se načítají pomocí {2}. + + + Cesta {0} zadaná v klíči registru {1}{2} se nenašla. Konfigurační soubory se načítají pomocí {3}. + + + {0}, {1}: Soubor byl přeskočen, protože nemá příponu názvu souboru ps1xml. + + + {0}, {1}: Soubor byl přeskočen kvůli následující výjimce při ověřování: {2}. + + + Člen {0} musí být poznámka. + + + Poznámku {0}:{1} nejde převést. + + + Člen {0} tady nepoužívejte. + + + Člen {0} musí být typu {1}. + + + Prvek {0} musí existovat, když {1} má hodnotu {2} a {3} má hodnotu {4}. + + + Kvůli předchozí chybě byla ignorována všechna nastavení serializace. + + + {0} není standardní člen a bude ignorován. + + + Cesta {0} není plně kvalifikovaná. Zadejte plně kvalifikovanou cestu k souboru typu. + + + Objekt TypeTable nejde aktualizovat, protože mohl být vytvořený mimo prostředí runspace. + + + Při načítání objektu TypeTable došlo k chybám. Podrobné chybové zprávy najdete ve vlastnosti Errors. + + + Chyba v TypeData {0}: {1} + + + Prvek {0} by měl mít ve vlastnosti {1} hodnotu. + + + Prvek {0} nesmí mít ve vlastnosti {1} hodnotu null ani prázdný řetězec. + + + Typ {0} se nenašel. Hodnota názvu typu musí být úplný název typu. Ověřte název typu a spusťte příkaz znovu. + + + TypeData musí obsahovat Members, TypeConverters, TypeAdapters nebo StandardMembers. + + + Sdílenou tabulku typů nejde aktualizovat více než jednou položkou. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/VerbDescriptionStrings.cs.resx b/src/System.Management.Automation/resources/cs/VerbDescriptionStrings.cs.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/VerbDescriptionStrings.cs.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/cs/WildcardPatternStrings.cs.resx b/src/System.Management.Automation/resources/cs/WildcardPatternStrings.cs.resx new file mode 100644 index 00000000000..1969709c591 --- /dev/null +++ b/src/System.Management.Automation/resources/cs/WildcardPatternStrings.cs.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 + + + Zadaný vzor se zástupnými znaky není platný: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/Authenticode.de.resx b/src/System.Management.Automation/resources/de/Authenticode.de.resx new file mode 100644 index 00000000000..ae798265932 --- /dev/null +++ b/src/System.Management.Automation/resources/de/Authenticode.de.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 + + + Die Datei {0} kann nicht geladen werden, weil Sie sich entschieden haben, diese Software jetzt nicht auszuführen. + + + Die Datei {0} kann nicht geladen werden, weil Sie sich entschieden haben, keine Software von diesem Herausgeber auszuführen. + + + Die Datei {0} wird von {1} veröffentlicht. Dieser Herausgeber ist auf Ihrem System explizit nicht vertrauenswürdig. Das Skript wird nicht auf dem System ausgeführt. Führen Sie den Befehl „get-help about_signing“ aus, um weitere Informationen zu erhalten. + + + Die Datei {0} kann nicht geladen werden, weil das Ausführen von Skripten auf diesem System deaktiviert ist. Weitere Informationen finden Sie unter about_Execution_Policies unter https://go.microsoft.com/fwlink/?LinkID=135170. + + + Die Datei {0} kann nicht geladen werden. {1}. + + + Die Datei {0} kann nicht geladen werden, da ihr Vorgang durch Richtlinien für Softwareeinschränkungen blockiert wird, z. B. durch Richtlinien, die mithilfe der Gruppenrichtlinie erstellt wurden. + + + Die Datei {0} kann nicht geladen werden, da ihr Inhalt nicht gelesen werden konnte. + + + Code kann nicht signiert werden. Das angegebene Zertifikat ist nicht zum Codesignieren geeignet. + + + Code kann nicht signiert werden. Die TimeStamp-Server-URL muss im Format http://<server url> oder https://<server url> vollqualifiziert sein. + + + Code kann nicht signiert werden. Der Hashalgorithmus wird nicht unterstützt. + + + Möchten Sie Software von diesem nicht vertrauenswürdigen Herausgeber ausführen? + + + Die Datei {0} wird von {1} veröffentlicht und ist in Ihrem System nicht vertrauenswürdig. Führen Sie nur Skripte von vertrauenswürdigen Herausgebern aus. + + + Software {0} wird von einem unbekannten Herausgeber veröffentlicht. Es wird empfohlen, diese Software nicht auszuführen. + + + Sicherheitswarnung + + + Nur Skripte ausführen, denen Sie vertrauen. Skripte aus dem Internet können zwar nützlich sein, aber dieses Skript kann ihren Computer möglicherweise beschädigen. Wenn Sie diesem Skript vertrauen, verwenden Sie das Cmdlet „Unblock-File“, um die Ausführung des Skripts ohne diese Warnmeldung zuzulassen. Möchten Sie {0} ausführen? + + + Ni&e ausführen + + + Skript jetzt nicht von diesem Herausgeber ausführen und mich in Zukunft nicht auffordern, dieses Skript auszuführen. Zukünftige Versuche, dieses Skript auszuführen, führen zu einem stillen Fehler. + + + Nicht &ausführen + + + Skript jetzt nicht von diesem Herausgeber ausführen und mich in Zukunft weiterhin auffordern, dieses Skript auszuführen. + + + Einmal &ausführen + + + Skript jetzt von diesem Herausgeber ausführen und mich in Zukunft weiterhin auffordern, dieses Skript auszuführen. + + + &Immer ausführen + + + Skript jetzt von diesem Herausgeber ausführen und mich in Zukunft nicht auffordern, dieses Skript auszuführen. + + + &Anhalten + + + Halten Sie die aktuelle Pipeline an, und kehren Sie zur Eingabeaufforderung zurück. Geben Sie „Beenden“ ein, um den Vorgang fortzusetzen, wenn Sie fertig sind. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/AuthorizationManagerBase.de.resx b/src/System.Management.Automation/resources/de/AuthorizationManagerBase.de.resx new file mode 100644 index 00000000000..f7623cd74bc --- /dev/null +++ b/src/System.Management.Automation/resources/de/AuthorizationManagerBase.de.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 + + + Fehler bei der AuthorizationManager-Überprüfung. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/AutomationExceptions.de.resx b/src/System.Management.Automation/resources/de/AutomationExceptions.de.resx new file mode 100644 index 00000000000..f044f634e0e --- /dev/null +++ b/src/System.Management.Automation/resources/de/AutomationExceptions.de.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Das Argument kann nicht verarbeitet werden, da der Wert des Arguments „{0}“ ungültig ist. Ändern Sie den Wert des Arguments „{0}“ und führen Sie den Vorgang erneut aus. + + + Das Argument kann nicht verarbeitet werden, da der Wert des Parameters „{0}“ ungültig ist. Gültige Werte sind Global, Local oder Script oder eine Zahl relativ zum aktuellen Bereich (0 bis zur Anzahl der Bereiche, wobei 0 der aktuelle Bereich und 1 der übergeordnete Bereich ist). Ändern Sie den Wert des Parameters „{0}“, und führen Sie den Vorgang erneut aus. + + + Das Argument kann nicht verarbeitet werden, da der Wert des Arguments „{0}“ NULL ist. Ändern Sie den Wert des Arguments „{0}“ in einen Wert ungleich NULL. + + + Das Argument kann nicht verarbeitet werden, da der Wert des Arguments „{0}“ außerhalb des Bereichs ist. Ändern Sie das Argument „{0}“ in einen Wert, der innerhalb des zulässigen Bereichs liegt. + + + Der Vorgang kann nicht ausgeführt werden, da der Vorgang „{0}“ ungültig ist. Entfernen Sie den Vorgang „{0}“, oder untersuchen Sie, warum er ungültig ist. + + + Der Vorgang kann nicht ausgeführt werden, da der Vorgang „{0}“ nicht implementiert ist. + + + Der Vorgang kann nicht ausgeführt werden, da der Vorgang „{0}“ nicht unterstützt wird. + + + Der Vorgang kann nicht ausgeführt werden, da das Objekt „{0}“ bereits verworfen wurde. + + + Der Skriptblock kann nicht aufgerufen werden, da er mehr als eine Klausel enthält. Die Invoke()-Methode kann nur für Skriptblöcke verwendet werden, die eine einzelne Klausel enthalten. + + + Der Skriptblock kann nicht konvertiert werden, da er mehr als eine Klausel enthält. Ausdrücke oder Kontrollstrukturen sind nicht zulässig. Stellen Sie sicher, dass der Skriptblock genau eine Pipeline oder genau einen Befehl enthält. + + + Ein leerer Skriptblock kann nicht konvertiert werden. Stellen Sie sicher, dass der Skriptblock genau eine Pipeline oder genau einen Befehl enthält. + + + Nur ein Skriptblock, der genau eine Pipeline oder genau einen Befehl enthält, kann konvertiert werden. Ausdrücke oder Kontrollstrukturen sind nicht zulässig. Stellen Sie sicher, dass der Skriptblock genau eine Pipeline oder genau einen Befehl enthält. + + + Ein Skriptblock, der eine trap-Anweisung auf oberster Ebene enthält, kann nicht konvertiert werden. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, wenn Variablen dereferenziert werden, die im param(...)-Block nicht deklariert sind. Name der nicht deklarierten Variablen: {0}. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, wenn nicht konstante Ausdrücke ausgewertet werden. Nicht konstanter Ausdruck: {0}. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, wenn dynamische Ausdrücke ausgewertet werden. Dynamischer Ausdruck: {0}. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, wenn andere Skriptblöcke innerhalb von Argumentwerten übergeben werden sollen. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, wenn Pipelines, Befehle oder Funktionen aufgerufen werden, um Argumente der Hauptpipeline auszuwerten. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, der Dot-Sourcing verwendet. + + + Für einen ScriptBlock, der andere Skriptblöcke aufruft, kann kein PowerShell-Objekt generiert werden. + + + Der Skriptblock kann nicht in ein PowerShell-Objekt konvertiert werden, da er unzulässige Umleitungsoperatoren enthält. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, da kein zugeordneter Vorgangskontext vorhanden ist. + + + Der Befehl wurde vom Benutzer abgebrochen. + + + Das Objekt „{0}“ hat den falschen Typ, um vom dynamicparam-Block zurückgegeben zu werden. Der dynamicparam-Block muss entweder $null oder ein Objekt vom Typ [System.Management.Automation.RuntimeDefinedParameterDictionary] zurückgeben. + + + Der Skriptblock kann nicht in einen offenen generischen Typ konvertiert werden. Definieren Sie einen geeigneten geschlossenen generischen Typ, und wiederholen Sie den Vorgang. + + + Für einen ScriptBlock kann kein PowerShell-Objekt generiert werden, wenn eine Pipeline mit einem Ausdruck gestartet wird. + + + Der Wert der Using-Variablen „$using:{0}“ kann nicht abgerufen werden, da er in der lokalen Sitzung nicht festgelegt wurde. + + + Der Wert des Using-Ausdrucks „{0}“ im angegebenen Variablenwörterbuch kann nicht abgerufen werden. Beim Erstellen einer PowerShell-Instanz aus einem Skriptblock darf der Using-Ausdruck keinen Indizierungsvorgang oder Memberzugriff enthalten. + + + Punktquellen des kompilierten Skriptblocks + + + Der Aufruf des Skriptblocks „{0}“ im aktuellen Bereich ist im eingeschränkten Sprachmodus nicht zulässig. Skriptsprachmodus: {1}, Kontextsprachmodus: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CatalogStrings.de.resx b/src/System.Management.Automation/resources/de/CatalogStrings.de.resx new file mode 100644 index 00000000000..5d631a47f34 --- /dev/null +++ b/src/System.Management.Automation/resources/de/CatalogStrings.de.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die Katalogdefinitionsdatei kann nicht generiert werden. + + + Die Datei „{0}“ wird dem Katalog hinzugefügt. Der relative Pfad der Datei im Katalog ist „{1}“. + + + Die Überprüfung der Datei {0} aus dem Katalog wird übersprungen. + + + Im Katalog wurde eine Datei {0} mit dem Hash von {1}gefunden. + + + Pfade für Katalog enthält mehrere Dateien mit demselben relativen Pfad {0}. + + + Die Datei {0} wurde auf dem Datenträger mit dem Hash von {1} gefunden. + + + Die Überprüfung der Datei {0} aus dem Pfad wird übersprungen. + + + Für einen angegebenen Hashalgorithmus {0} kann kein Handle für einen Katalogadministratorkontext abgerufen werden. + + + Der Hash für die Datei {0} kann nicht erstellt werden. + + + Die Katalogdatei {0} kann nicht geöffnet werden. + + + Die Katalogversion ist ungültig. Wir unterstützen nur die Katalogversion {0} und Version {1}. + + + Die Katalogdefinitionsdatei kann nicht geöffnet werden. + + + Es wurden mehrere Einträge des Dateimitglieds {0} im Katalog gefunden. + + + Der Dateiname oder Pfad für das Katalogmitglied {0} wurde nicht gefunden. + + + Die zu hashende Datei {0} wurde nicht gefunden. + + + Die Datei {0} kann nicht gelesen werden, um ihren Hash zu berechnen. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CimInstanceTypeAdapterResources.de.resx b/src/System.Management.Automation/resources/de/CimInstanceTypeAdapterResources.de.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/de/CimInstanceTypeAdapterResources.de.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CmdletizationCoreResources.de.resx b/src/System.Management.Automation/resources/de/CmdletizationCoreResources.de.resx new file mode 100644 index 00000000000..d01b0249919 --- /dev/null +++ b/src/System.Management.Automation/resources/de/CmdletizationCoreResources.de.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlets über „{0}“-Klasse + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Die Cmdlet Definition XML für die folgende Datei kann nicht verarbeitet werden: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Das ObjectModelWrapper-Attribut kann nicht verarbeitet werden. Der {0} Typ definiert mehrere Parametersätze. Überprüfen Sie, ob die Cmdlet Definition XML einen gültigen Typ im ObjectModelWrapper-Attribut angibt, und wiederholen Sie den Vorgang. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Das ObjectModelWrapper-Attribut kann nicht verarbeitet werden. Der {0} Typ ist ein offener generischer Typ. Überprüfen Sie, ob die Cmdlet Definition XML einen gültigen Typ im ObjectModelWrapper-Attribut angibt, und wiederholen Sie den Vorgang. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Das ObjectModelWrapper-Attribut kann nicht verarbeitet werden. Der {0} Typ wird nicht von der folgenden Klasse abgeleitet: {1}. Überprüfen Sie, ob die Cmdlet Definition XML einen gültigen Typ im ObjectModelWrapper-Attribut angibt, und wiederholen Sie den Vorgang. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Das ObjectModelWrapper-Attribut kann nicht verarbeitet werden. Der {0} Typ definiert den {1} cmdlet-Parameter mit einem {2} Attributparameter, der ignoriert wird. Überprüfen Sie, ob die Cmdlet Definition XML einen gültigen Typ im ObjectModelWrapper-Attribut angibt, und wiederholen Sie den Vorgang. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Der {0} Parameter für das {1} cmdlet kann nicht definiert werden. Der Parametername ist bereits von der {2} Klasse definiert. Ändern Sie den Namen des Parameters in Cmdlet Definition XML, und wiederholen Sie den Vorgang. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Der {0} Parameter für das {1} cmdlet kann nicht definiert werden. Der Parametername ist bereits im {2} XML-Element definiert. Ändern Sie den Namen des Parameters in der Cmdlet Definition XML, und versuchen Sie es dann erneut. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + Der Wert des EnumName-Attributs wird nicht in einen gültigen C#-Bezeichner übersetzt: {0}. Überprüfen Sie das EnumName-Attribut in der Cmdlet Definition XML, und versuchen Sie es dann erneut. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Die <Enum EnumName="{0}" ...> Element kann nicht verarbeitet werden. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + Der Remotecomputer hat eine ungültige CDXML-Datei zurückgegeben. Der folgende cmdlet-Adapter wird für den Import eines CDXML-Moduls von einem Remotecomputer nicht unterstützt: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CommandBaseStrings.de.resx b/src/System.Management.Automation/resources/de/CommandBaseStrings.de.resx new file mode 100644 index 00000000000..f48e5775089 --- /dev/null +++ b/src/System.Management.Automation/resources/de/CommandBaseStrings.de.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Mit diesem Vorgang fortfahren? + + + &Ja + + + Fahren Sie nur mit dem nächsten Schritt des Vorgangs fort. + + + Ja, &alle + + + Fahren Sie mit allen Schritten des Vorgangs fort. + + + &Nein + + + Überspringen Sie diesen Vorgang, und fahren Sie mit dem nächsten Vorgang fort. + + + Nein, &keine + + + Überspringen Sie diesen Vorgang und alle nachfolgenden Vorgänge. + + + Beenden Sie diesen Befehl. + + + Befehl &anhalten + + + &Anhalten + + + Halten Sie die aktuelle Pipeline an, und kehren Sie zur Eingabeaufforderung zurück. Geben Sie „{0}“ ein, um die Pipeline fortzusetzen. + + + + Das Programm „{0}“ wurde mit einem Exitcode ungleich 0 beendet: {1} ({2}). + + + Der Vorgang „{0}“ wird für das Ziel „{1}“ ausgeführt. + + + What If: {0} + + + Möchten Sie diese Aktion wirklich ausführen? +{0} + + + Bestätigen + + + Der ausgeführte Befehl wurde beendet, weil die Einstellungsvariable „{0}“ oder der allgemeine Parameter auf „Stopp“ festgelegt ist: {1} + + + Der ausgeführte Befehl wurde beendet, da die Einstellungsvariable „{0}“ oder der allgemeine Parameter auf „Stopp“ festgelegt ist. + + + Der ausgeführte Befehl wurde beendet, da die Einstellungsvariable „{0}“ oder der allgemeine Parameter auf den folgenden ungültigen Wert festgelegt ist: „{1}“. + + + Der ausgeführte Befehl wurde beendet, da der Benutzer die Option „Stopp“ ausgewählt hat. + + + Der ausgeführte Befehl wurde beendet, da der Benutzer den Befehl unterbrochen hat. + + + Von PSCmdlet abgeleitete Cmdlets können nicht direkt aufgerufen werden. + + + Das Cmdlet „{0}“ unterstützt den Parameter „{1}“ in einer Remotesitzung nicht. + + + Gesamtanzahl: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Geschätzte Gesamtanzahl: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Unbekannte Gesamtanzahl + Reviewed by TArcher on 2010-07-20 + + + Befehl „{0}“ + + + Der {0} ist veraltet. {1} + + + Fehler beim Ausführen des Aufrufs mit errorno {0} für die Befehlszeile: {1} + + + Der Befehl „{0}“ wurde nicht gefunden. Der angegebene Befehl muss eine ausführbare Datei sein. + + + Skriptblockverarbeitung Punkt-Quelle-Überprüfung + + + Die Dot-Source-Verarbeitung für den Skriptblock „{0}“ schlägt im Modus „Eingeschränkte Sprache“ fehl, da der Sprachmodus „{1}“ nicht mit dem aktuellen Sprachmodus „{2}“ übereinstimmt. + + + Befehlssuche + + + Der Befehl „{0}“ im Modul „{1}“ ist nicht vertrauenswürdig und im ConstrainedLanguage-Modus nicht zugänglich. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ConsoleInfoErrorStrings.de.resx b/src/System.Management.Automation/resources/de/ConsoleInfoErrorStrings.de.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/de/ConsoleInfoErrorStrings.de.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CoreClrStubResources.de.resx b/src/System.Management.Automation/resources/de/CoreClrStubResources.de.resx new file mode 100644 index 00000000000..2bce9eb9687 --- /dev/null +++ b/src/System.Management.Automation/resources/de/CoreClrStubResources.de.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Der Name der Umgebungsvariable darf kein Gleichheitszeichen enthalten. + + + Der Name oder Wert der Umgebungsvariable ist zu lang. + + + Das erste Zeichen in der Zeichenfolge ist das Null-Zeichen. + + + Die Länge der Zeichenfolge darf nicht Null sein. + + + Der Computername konnte nicht abgerufen werden. + + + Der Domänenname des aktuellen Benutzers konnte nicht abgerufen werden. + + + Unbekannter Fehler „{0}“. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CredUI.de.resx b/src/System.Management.Automation/resources/de/CredUI.de.resx new file mode 100644 index 00000000000..e08de97b6e6 --- /dev/null +++ b/src/System.Management.Automation/resources/de/CredUI.de.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell-Anmeldeinformationsanforderung + + + Geben Sie Ihre Anmeldeinformationen ein. + + + Geben Sie Ihre Anmeldeinformationen ein. + + + Die maximale Länge der Beschriftung beträgt {0} Zeichen. + + + Die maximale Länge der Nachricht beträgt {0} Zeichen. + + + Die maximale Länge des UserName-Werts beträgt {0} Zeichen. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/Credential.de.resx b/src/System.Management.Automation/resources/de/Credential.de.resx new file mode 100644 index 00000000000..eac830bb75b --- /dev/null +++ b/src/System.Management.Automation/resources/de/Credential.de.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 + + + Die Anmeldeinformationen können nicht serialisiert werden. Wenn dieser Befehl einen Workflow startet, können die Anmeldeinformationen nicht beibehalten werden, da der Prozess, in dem der Workflow gestartet wird, nicht über die Berechtigung zum Serialisieren von Anmeldeinformationen verfügt. + +– Wenn der Workflow in einer PSSession auf dem lokalen Computer gestartet wurde, fügen Sie dem Befehl, der die Sitzung erstellt hat, den EnableNetworkAccess-Parameter hinzu. +– Wenn der Workflow in einer PSSession auf einem Remotecomputer gestartet wurde, fügen Sie dem Befehl, der die Sitzung erstellt hat, den Authentication-Parameter mit dem Wert CredSSP hinzu. Oder stellen Sie eine Verbindung mit einer Sitzungskonfiguration her, die über einen RunAsUser-Eigenschaftswert verfügt. + + + Der Wert für „UserName“ weist nicht das richtige Format auf. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/CredentialAttributeStrings.de.resx b/src/System.Management.Automation/resources/de/CredentialAttributeStrings.de.resx new file mode 100644 index 00000000000..f21e9cb19aa --- /dev/null +++ b/src/System.Management.Automation/resources/de/CredentialAttributeStrings.de.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 + + + PowerShell-Anmeldeinformationsanforderung + + + Geben Sie Ihre Anmeldeinformationen ein. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/DebuggerStrings.de.resx b/src/System.Management.Automation/resources/de/DebuggerStrings.de.resx new file mode 100644 index 00000000000..8bc8ccaebbc --- /dev/null +++ b/src/System.Management.Automation/resources/de/DebuggerStrings.de.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Variablenhaltepunkt bei „${0}“ (Zugriff auf {1}) + + + Variablenhaltepunkt bei „{0}:${1}“ (Zugriff auf {2}) + + + Zeilenhaltepunkt auf „{0}:{1}“ + + + Zeilenhaltepunkt auf „{0}:{1}, {2}“ + + + Befehlshaltepunkt auf „{0}“ + + + Befehlshaltepunkt auf „{0}:{1}“ + + + Haltepunkt „{0}“ wird nicht erreicht + + + {0}, {1,-16} Einzelschritt (in Funktionen, Skripts usw. hinein) + + + {0}, {1,-16} Zur nächsten Anweisung springen (Funktionen, Skripts usw. überspringen) + + + {0}, {1,-16} Aus der aktuellen Funktion, dem Skript usw. herausspringen + + + {0}, {1,-16} Vorgang fortsetzen + + + {0}, {1,-16} Vorgang beenden und den Debugger schließen + + + {0}, Aufrufliste „Get-PSCallStack“ anzeigen + + + {0}, {1,-16} Quellcode für das aktuelle Skript auflisten. + + + Verwenden Sie „list“, um ab der aktuellen Zeile zu beginnen, „<m> auflisten“ + + + , um ab Zeile <m> zu beginnen, und „<m> <n> auflisten“, um <n> aufzulisten + + + Zeilen ab Zeile <m> + + + <enter> Letzten Befehl wiederholen, wenn er {0}, {1} oder {2} war + + + {0}, {1,-16} zeigt diese Hilfemeldung an. + + + Anweisungen zum Anpassen der Debuggeraufforderung erhalten Sie mit „help about_prompt“. + + + +Die aktuelle Sitzung unterstützt kein Debugging, der Vorgang wird fortgesetzt. + + + + + {0}: Zeile {1} + + + Der Quellcode ist nicht verfügbar. + + + Die Startzeile muss eine positive ganze Zahl sein, die nicht größer als {0} ist. + + + Die Zeilenanzahl muss eine positive ganze Zahl sein. + + + <No file> + + + bei {0}, {1}: Zeile {2} + + + Der Debugger kann nur Befehle verarbeiten, wenn er sich im Zustand Stopped befindet. + + + SetDebugAction ist für den lokalen Skriptdebugger nicht implementiert. + + + Der Debugger kann keine Fortsetzungsaktion festlegen, da sich der Debugger in der Remotesitzung nicht im Zustand Stopped befindet. + + + Der Job kann nicht debuggt werden, da der Debugger derzeit ausgelastet ist. + + + Der angegebene Auftrag und alle untergeordneten Aufträge wurden geprüft, aber es wurden keine Aufträge gefunden, die debuggt werden konnten. Um einen Auftrag oder untergeordneten Auftrag zu debuggen, muss der Auftrag Debuggen unterstützen und sich im Ausführungszustand befinden. + + + Der Debugger kann für den Schrittmodus nicht aktiviert werden, da der Debugmodus auf None festgelegt ist und der Debugger deaktiviert ist. + + + Der Runspace kann nicht debuggt werden, da der Hostdebugger derzeit ausgelastet ist. + + + Runspace kann nicht debuggt werden. Der Runspace-Debugger ist derzeit deaktiviert (DebugMode ist „None“). + + + Runspace kann nicht debuggt werden, wenn es sich nicht im Zustand Opened befindet. Dieser Runspace-Zustand ist „{0}“. + + + Runspace kann nicht debuggt werden. Dem Runspace „{0}“ ist kein Debugger zugeordnet. + + + Der Debugger wurde bereits außer Kraft gesetzt. + + + Ein Debuggerobjekt kann nicht auf sich selbst gepusht werden. + + + Der {0}-Befehl wird in der PowerShell-Version, die im Remoterunspace ausgeführt wird, für die Remoteverwendung nicht unterstützt. + + + Prozess + + + {0}, {1,-16} Vorgang fortsetzen und Debugger trennen. + + + Der Debuggerbefehl zum Trennen ist nicht anwendbar. Der Trennbefehl gilt nur beim Debuggen von Aufträgen und Runspaces mit den Cmdlets „Debug-Job“ oder „Debug-Runspace“. + + + Ungültige Runspace-ID: {0} + + + Runspace kann nicht abgerufen werden. + + + Ein Haltepunkt oder eine Haltepunktliste muss angegeben werden. + + + Die BreakpointList enthielt ein Element, das kein Haltepunkt war. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/DescriptionsStrings.de.resx b/src/System.Management.Automation/resources/de/DescriptionsStrings.de.resx new file mode 100644 index 00000000000..e76a5a450a7 --- /dev/null +++ b/src/System.Management.Automation/resources/de/DescriptionsStrings.de.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 + + + {0} darf nicht NULL oder leer sein. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/DiscoveryExceptions.de.resx b/src/System.Management.Automation/resources/de/DiscoveryExceptions.de.resx new file mode 100644 index 00000000000..8f2975a153d --- /dev/null +++ b/src/System.Management.Automation/resources/de/DiscoveryExceptions.de.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 + + + Der Cmdlet-Name „{0}“ kann nicht überprüft werden, da er nicht das richtige Format aufweist. Cmdlet-Namen müssen ein Verb und ein Substantiv enthalten, die durch einen „-“ getrennt sind, z. B. „Get-Process“. + + + Der Parameter „{0}“ wird im Parametersatz „{1}“ mehrmals deklariert. + + + Der Alias „{0}“ ist mehrfach deklariert. + + + Der Parameter konnte nicht deklariert werden. Parameter können nur in Feldern und Eigenschaften deklariert werden. + + + Das Cmdlet kann nicht verarbeitet werden. Ein Cmdlet-Name muss aus einem durch „-” getrennten Verb- und Substantivpaar bestehen. + + + Der Begriff „{0}“ wird nicht als Name eines Cmdlets, einer Funktion, einer Skriptdatei oder eines ausführbaren Programms erkannt. +Prüfen Sie die Schreibweise des Namens bzw. stellen Sie sicher, dass der Pfad korrekt angegeben wurde, und versuchen Sie es erneut. + + + Das Argument „{0}“ wird nicht als Cmdlet erkannt: {1} + + + Das Argument „{0}“ wird nicht als Cmdlet erkannt, da es möglicherweise nicht von der Cmdlet- oder PSCmdlet-Klasse abgeleitet ist: {1} + + + Der Alias „{0}“ kann nicht aufgelöst werden, da er auf den Begriff „{1}“ verweist, der nicht als Cmdlet, Funktion, ausführbares Programm oder Skriptdatei erkannt wird. Überprüfen Sie den Begriff, und versuchen Sie es erneut. + + + Der Parameter „{0}“ mit dem Wert „{1}“ kann nicht verarbeitet werden, da er kein Cmdlet ist und nicht vom CommandProcessor verarbeitet werden kann. + + + Ein Cmdlet mit dem Namen „{0}“ ist bereits vorhanden. Cmdlets müssen eindeutige Namen haben. + + + Ein Cmdlet-Anbieter mit dem Namen „{0}“ ist bereits vorhanden. Cmdlet-Anbieter müssen eindeutige Namen haben. + + + Eine Assembly mit dem Namen „{0}“ ist bereits vorhanden. Assemblys müssen eindeutige Namen aufweisen. + + + Ein Skript mit dem Namen „{0}“ ist bereits vorhanden. Skripts müssen eindeutige Namen haben. + + + Die #requires-Anweisung kann nicht verarbeitet werden, da sie nicht das richtige Format aufweist. +Die #requires-Anweisung muss in einem der folgenden Formate vorliegen: + „#requires -shellid <shellID>“ + „#requires -version <major.minor>“ + „#requires -psedition <edition>“ + „#requires -pssnapin <psSnapInName> [-version <major.minor>]“ + „#requires -modules <ModuleSpecification>“ + „#requires -runasadministrator“ + + + Das Skript „{0}“ kann nicht ausgeführt werden, da es eine #requires-Anweisung mit der Shell-ID „{1}“ enthält, die mit der aktuellen Shell nicht kompatibel ist. Um dieses Skript auszuführen, müssen Sie die Shell unter „{2}“ verwenden. + + + Das Skript „{0}“ kann nicht ausgeführt werden, da es eine #requires-Anweisung mit der Shell-ID „{1}“ enthält, die mit der aktuellen Shell nicht kompatibel ist. + + + Das Skript „{0}“ kann nicht ausgeführt werden, da es eine #requires-Anweisung für PowerShell „{1}“ enthält. Die vom Skript erforderliche PowerShell-Version stimmt nicht mit der aktuell ausgeführten PowerShell-Version „{2}“ überein. + + + Das Skript „{0}“ kann nicht ausgeführt werden, da es eine #requires-Anweisung für PowerShell-Editionen „{1}“ enthält. Die vom Skript erforderliche PowerShell-Edition stimmt nicht mit der aktuell ausgeführten PowerShell {2}-Edition überein. + + + Das Skript „{0}“ kann nicht ausgeführt werden, da die folgenden Snap-Ins, die in den #requires-Anweisungen des Skripts angegeben sind, fehlen: {1}. + + + In einer #requires-Anweisung wurde nur eine shellID angegeben. #Requires-Anweisungen müssen ein erforderliches PowerShell-Snap-In angeben, wenn sie in PowerShell ausgeführt werden. + + + Das Skript „{0}“ kann nicht ausgeführt werden, da es eine "#requires"-Anweisung für die Ausführung als Admin enthält. Die aktuelle PowerShell-Sitzung wird nicht als Admin ausgeführt. Starten Sie PowerShell über die Option „Als Admin ausführen“, und versuchen Sie dann erneut, das Skript auszuführen. + + + {0} (Version {1}) + + + Der Befehl konnte nicht abgerufen werden, da der Parameter ArgumentList nur beim Abrufen eines einzelnen Cmdlets oder Skripts angegeben werden kann. + + + Der Parametername „{0}“ ist für die zukünftige Verwendung reserviert. + + + Das Skript „{0}“ kann nicht ausgeführt werden, da die folgenden Module, die in den #requires-Anweisungen des Skripts angegeben sind, fehlen: {1}. + + + Der Befehl „{0}“ wurde im Modul „{1}“ gefunden, aber das Modul konnte nicht geladen werden. Weitere Informationen finden Sie mit „Import-Module {1}“. + + + Der Befehl „{0}“ wurde im Modul „{1}“ gefunden, aber das Modul konnte aufgrund des folgenden Fehlers nicht geladen werden: [{2}] +Weitere Informationen finden Sie mit „Import-Module {1}“. + + + Das Modul „{0}“ konnte nicht geladen werden. Weitere Informationen finden Sie mit „Import-Module {0}“. + + + Keine übereinstimmenden Befehle enthalten einen Parameter mit dem Namen „{0}“. Überprüfen Sie die Schreibweise des Parameternamens, und versuchen Sie es dann erneut. + + + Dieser Befehl kann nicht per Dot-Sourcing aufgerufen werden, da er in einem anderen Sprachmodus definiert wurde. Lassen Sie den Operator „.“ weg, um diesen Befehl aufzurufen, ohne seinen Inhalt zu importieren. + + + Die Parameter „ShowCommandInfo“ und „Syntax“ können nicht zusammen angegeben werden. + + + Dieser Skriptbefehl ist deaktiviert, wenn die experimentelle Funktion „{0}“ aktiviert ist. + + + Dieser Skriptbefehl ist deaktiviert, wenn die experimentelle Funktion „{0}“ deaktiviert ist. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/EnumExpressionEvaluatorStrings.de.resx b/src/System.Management.Automation/resources/de/EnumExpressionEvaluatorStrings.de.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/de/EnumExpressionEvaluatorStrings.de.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ErrorCategoryStrings.de.resx b/src/System.Management.Automation/resources/de/ErrorCategoryStrings.de.resx new file mode 100644 index 00000000000..f34a72f74e8 --- /dev/null +++ b/src/System.Management.Automation/resources/de/ErrorCategoryStrings.de.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Deadlock gefunden: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Unbekannte Fehlerkategorie {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ErrorPackage.de.resx b/src/System.Management.Automation/resources/de/ErrorPackage.de.resx new file mode 100644 index 00000000000..4553d0e8076 --- /dev/null +++ b/src/System.Management.Automation/resources/de/ErrorPackage.de.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 + + + {0}…{1} + + + Der Fehlertext ist für Fehler „{0}“ leer: „{1}“ + + + Das Objekt „{0}“ wird als Fehler gemeldet. + + + Der Wert {0} wird für eine ActionPreference-Variable nicht unterstützt. Der angegebene Wert darf nur als Wert für einen Einstellungsparameter verwendet werden und wurde durch den Standardwert ersetzt. Weitere Informationen finden Sie im Hilfethema „about_preference_variables“. + + + Der {0} ActionPreference-Wert ist für die zukünftige Verwendung reserviert und wird derzeit nicht unterstützt. Weitere Informationen zu Einstellungsvariablen finden Sie im Hilfethema „about_Preference_Variables“. + + + Der {0} ActionPreference-Wert ist für die zukünftige Verwendung reserviert und wird derzeit nicht unterstützt. Er wurde in Ihrer {1} Variablen durch den Standardwert von {2} ersetzt. Weitere Informationen zu Einstellungsvariablen finden Sie im Hilfethema „about_Preference_Variables“. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/EtwLoggingStrings.de.resx b/src/System.Management.Automation/resources/de/EtwLoggingStrings.de.resx new file mode 100644 index 00000000000..d9084cc95ca --- /dev/null +++ b/src/System.Management.Automation/resources/de/EtwLoggingStrings.de.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Befehl {0} ist {1}. + + + Der Engine-Zustand wurde von {0} in {1} geändert. + + + Vollqualifizierte Fehler-ID = {0} + + + Fehlermeldung = {0} + + + Empfohlene Aktion = {0} + + + Ausführungsrichtlinie + + + Auftragsbefehl = {0} + + + Auftrags-ID = {0} + + + Auftragsinstanz-ID = {0} + + + Auftragsspeicherort = {0} + + + Auftragsname = {0} + + + Auftragszustand = {0} + + + Befehlsname = + + + Befehlspfad = + + + Befehlstyp = + + + Engine-Version = + + + Host-ID = + + + Hostname = + + + Hostanwendung = + + + Hostversion = + + + Pipeline-ID = + + + Runspace-ID = + + + Skriptname = + + + Sequenznummer = + + + Schweregrad = + + + Shell-ID = + + + Zeit = + + + Benutzer = + + + Verbundener Benutzer = + + + NULL-Auftrag + + + Anbietername + + + Der Status des Anbieters {0} wurde in {1} geändert. + + + Skriptausführung ist {0}. + + + Die Variable {0} wurde von {1} in {2} geändert. + + + Die Variable {0} wurde in {1} geändert. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/EventResource.de.resx b/src/System.Management.Automation/resources/de/EventResource.de.resx new file mode 100644 index 00000000000..8d4234e353d --- /dev/null +++ b/src/System.Management.Automation/resources/de/EventResource.de.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Für die Ereignis-ID „PowerShell.Core.Instrumentation.man“ wurde keine Meldung gefunden. + + + Geplanter Auftrag {0} um {1} gestartet + + + + Geplanter Auftrag {0} um {1} mit dem Status {2} abgeschlossen + + + + Ausnahme für geplanten Auftrag {0}: + Nachricht: {1} + StackTrace: {2} + InnerException: {3} + + + + Experimentelle Funktionsinitialisierung: Die experimentelle Funktion „{0}“ aus der Konfigurationsdatei wird ignoriert. {1} + + + Experimentelle Featureinitialisierung: Fehler beim Lesen der Konfigurationsdatei. + Ausnahme: {0} + Nachricht: {1} + StackTrace: {2} + + + + Workflow-Plug-In geladen. + EndpointName: {0} + Benutzer: {1} + HostingMode: {2} + Protokoll: {3} + Konfiguration: + {4} + + + Die Workflowausführung wurde gestartet. + WorkflowId: {0} + ManagedNodes: {1} + + + Der Workflowzustand wurde geändert. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + Für das Workflow-Plug-In wurde das Herunterfahren angefordert. + EndpointName: {0} + + + Das Workflow-Plug-In wurde neu gestartet. + EndpointName: {0} + + + Workflow wird fortgesetzt. + WorkflowId: {0} + + + Eine für den Endpunkt festgelegte Kontingentgrenze wurde überschritten. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + Der Workflow wurde fortgesetzt. + WorkflowId: {0} + + + Der Workflowrunspacepool wurde erstellt. + WorkflowId: {0} + ManagedNode: {1} + + + Die Aktivität wurde zur Ausführung in die Warteschlange eingereiht. + WorkflowId: {0} + ActivityName: {1} + + + Aktivitätsausführung gestartet. + ActivityName: {0} + ActivityTypeName: {1} + + + Der Workflow wird aus einer XAML-Datei importiert. + WorkflowId: {0} + XamlFile: {1} + + + Der Workflow wurde aus einer XAML-Datei importiert. + WorkflowId: {0} + XamlFile: {1} + + + Der Workflow konnte aufgrund eines Fehlers nicht aus einer XAML-Datei importiert werden. + WorkflowId: {0} + ErrorDescription: {1} + + + Die Workflowüberprüfung wurde gestartet. + WorkflowId: {0} + + + Workflowüberprüfung erfolgreich. + WorkflowId: {0} + + + Fehler bei der Workflowüberprüfung. + WorkflowId: {0} + + + Die Workflowaktivität wurde validiert. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Die Workflowaktivität konnte nicht validiert werden. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Aktivitätsausführung fehlgeschlagen. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Die Runspaceverfügbarkeit wurde geändert. + RunspaceId: {0} + Verfügbarkeit: {1} + + + Der Runspacezustand wurde geändert. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Workflow zur Ausführung geladen. + WorkflowId: {0} + + + Workflow entladen. + WorkflowId: {0} + + + Die Workflowausführung wurde abgebrochen. + WorkflowId: {0} + + + Die Workflowausführung wurde abgebrochen. + WorkflowId: {0} + + + Die Workflowbereinigung wurde ausgeführt. + WorkflowId: {0} + + + Der persistierte Workflow wurde von der Festplatte geladen. + WorkflowId: {0} + Pfad: {1} + + + Die Workflowdaten wurden von der Festplatte gelöscht. + WorkflowId: {0} + Pfad: {1} + + + Der Lösungsauftrag wird gestartet. + JobId: {0} + + + Auftragsstatus wurde geändert. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Auftragsfehler. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Auftrag für Workflow erstellt (untergeordneter Auftrag). + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Übergeordneter Auftrag für den Workflow erstellt. + JobId: {0} + + + Alle erforderlichen Aufträge wurden für die Workflowausführung erstellt. + JobId: {0} + WorkflowId: {1} + + + Untergeordneter Auftrag für den Workflow wurde entfernt. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + Fehler beim Entfernen des Auftrags. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Error: {3} + + + Workflow wird zur Ausführung geladen. + WorkflowId: {0} + + + Die Workflowausführung wurde beendet. + WorkflowId: {0} + + + Workflowausführung wird abgebrochen. + WorkflowId: {0} + + + Workflowausführung wird abgebrochen. + WorkflowId: {0} + Grund: {1} + + + Workflow wird entladen. + WorkflowId: {0} + + + Erzwungene Beendigung des Workflows gestartet. + WorkflowId: {0} + + + Erzwungene Beendigung des Workflows beendet. + WorkflowId: {0} + + + Beim erzwungenen Beenden eines Workflows ist ein Fehler aufgetreten. + WorkflowId: {0} + ErrorDescription: {1} + + + Workflow wird auf dem Datenträger gespeichert. + WorkflowId: {0} + PersistPath: {1} + + + Workflow auf dem Datenträger gespeichert. + WorkflowId: {0} + + + Aktivitätsausführung beendet. + ActivityName: {0} + + + Workflowausführungsfehler. + WorkflowId: {0} + ErrorDescription: {1} + + + Ein neuer PowerShell-Endpunkt wurde registriert. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Die Endpunktkonfiguration wurde geändert. + EndpointName: {0} + ModifiedBy: {1} + + + Die Registrierung der Endpunktkonfiguration wurde aufgehoben. + EndpointName: {0} + UnregisteredBy: {1} + + + Die Endpunktkonfiguration wurde deaktiviert. + EndpointName: {0} + DisabledBy: {1} + + + Endpunktkonfiguration aktiviert. + EndpointName: {0} + EnabledBy: {1} + + + Out-of-Process-Runspace gestartet. + Befehl: {0} + + + Während der Workflowausführung wurden Parameter splatted. + Parameter: {0} + Computer: {1} + + + Die Workflow-Engine wurde gestartet. + EndpointName: {0} + + + Workflow-Manager instanziiert mit + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + Pfad: {3} + + + Computername $null oder . wird in Localhost aufgelöst + + + In Standardschema HTTP auflösen + + + Der Remoteshellname wurde in das standardmäßige PowerShellCore aufgelöst. + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + Skriptblocktext ({0}von {1}) wird erstellt: +{2} + +ScriptBlock-ID: {3} +Pfad: {4} + + + Der Aufruf der ScriptBlock-ID wurde gestartet: {0} +Runspace ID: {1} + + + Der Aufruf der ScriptBlock-ID wurde abgeschlossen: {0} +Runspace ID: {1} + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + {2} + +Kontext: +{0} + +Benutzerdaten: +{1} + + + + Aktivitäts-IDs werden korreliert. + CurrentActivityId: {0} + ParentActivityId: {1} + + + Klassenname = {0} +Methodenname = {1} +Workflow-GUID = {2} +Nachricht = {3} +{4} +Aktivitätsname = {5} +Aktivitäts-GUID = {6} +Parameter = {7} + + + Runspace-Objekt wird erstellt + Instanz-ID: {0} + + + RunspacePool-Objekt wird erstellt + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + RunspacePool wird geöffnet + + + Aktivitäts-ID wird geändert und zugeordnet + + + Runspacezustand in „{0}“ geändert + + + Es wird versucht, die Sitzungserstellung für Fehlercode {0} auf Sitzungs-ID {1} zu wiederholen {2} + + + PowerShell hat einen IPC-Listeningthread für Prozess: {0} in AppDomain: {1} gestartet. + + + PowerShell hat einen IPC-Listeningthread für Prozess: {0} in AppDomain: {1} beendet. + + + Im PowerShell IPC-Listenerthread im Prozess: {0} in AppDomain: {1} ist ein Fehler aufgetreten. Fehlermeldung: {2}. + + + PowerShell-IPC-Verbindung für Prozess: {0} in AppDomain: {1} für Benutzer: {2}. + + + PowerShell-IPC-Verbindung getrennt für Prozess: {0} in AppDomain: {1} für Benutzer: {2}. + + + Port aufgelöst in {0} + + + AppName aufgelöst in {0} + + + ComputerName aufgelöst in {0} + + + Schema ist {0} + + + Testanalysemeldung + + + Verbindungsparameter sind + Verbindungs-URI: {0} + Ressourcen-URI: {1} + Benutzer: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Fingerabdruck: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Aktivitäts-ID wird geändert und zugeordnet + + + Objekt empfangen mit Runspace-ID: {0} Befehls-ID: {1} Ziel: {2} DataType: {3} TargetInterface: {4} + + + Ausnahmefehler in der AppDomain. +Ausnahmetyp: {0} +Ausnahmenachricht: {1} +Ausnahme-StackTrace: {2} + + + Runspace-ID: {0} Pipeline-ID: {1}. WSMan hat einen Fehler mit dem Fehlercode: {2} gemeldet. + Fehlermeldung: {3} + StackTrace: {4} + + + Ausnahmefehler in der AppDomain. +Ausnahmetyp: {0} +Ausnahmenachricht: {1} +Ausnahme-StackTrace: {2} + + + Runspace-ID: {0} Pipeline-ID: {1}. WSMan hat einen Fehler mit dem Fehlercode: {2} gemeldet. + Fehlermeldung: {3} + StackTrace: {4} + + + Runspace-ID: {0}. Verbindung wird mit WSMan Create Shell hergestellt + + + Runspace-ID: {0}. Rückruf für WSMan Create Shell empfangen. + + + Runspace-ID: {0} Shell wird mit WSManCloseShell geschlossen. + + + Runspace-ID: {0} Rückruf für WSManCloseShell empfangen + + + Runspace-ID: {0} Pipeline-ID: {1}. Daten der Größe {2} werden gesendet + + + Runspace-ID: {0} Pipeline-ID: {1}. Rückruf für WSManSendShellInputEx empfangen. + + + Runspace-ID: {0} Pipeline-ID: {1}. Empfangsanforderung wird mit WSManReceiveShellOutputEx platziert. + + + Runspace-ID: {0} Pipeline-ID: {1}. Daten der Größe {2} empfangen. + + + Runspace-ID: {0} Pipeline-ID: {1}. Eine Befehlsverbindung wird mit WSManRunShellCommandEx hergestellt. + + + Runspace-ID: {0} Pipeline-ID: {1}. Rückruf für die Befehlsverbindung empfangen + + + Runspace-ID: {0} Pipeline-ID: {1}. Transport für den Befehl wird geschlossen. + + + Runspace-ID: {0} Pipeline-ID: {1}. Rückruf für das Schließen des Befehls + + + Runspace-ID: {0} Pipeline-ID: {1}. Das Signal mit Code {2} wird mit WSManSignalShellEx gesendet. + + + Runspace-ID: {0} Pipeline-ID: {1}. Rückruf für WSManSignalShellEx empfangen. + + + Runspace-ID: {0} Die Verbindung wird zu URI umgeleitet: {1} + + + Runspace-ID: {0} Pipeline-ID: {1}. Der Server sendet Daten der Größe {2} an den Client. DataType: {3} TargetInterface: {4} + + + Anforderung {0}. Eine Remotesitzung auf dem Server wird erstellt. Benutzername: {1} Benutzerdefinierte Shell-ID: {2} + + + Kontext für Anforderung wird gemeldet: {0} Gemeldeter Kontext: {0} + + + Vorgang für die Anforderung abgeschlossen gemeldet: {0} + Fehlercode: {1} + Fehlermeldung: {2} + StackTrace: {3} + + + Shellkontext {0}. Anforderungs-ID {1}. Es wird eine allgemeine Sitzung zum Ausführen eines Befehls erstellt. + + + Shellkontext {0} Befehlskontext {1} Anforderungs-ID {2}. Befehl wird beendet. + + + Shellkontext {0} Befehlskontext {1} Anforderungs-ID {2}. Daten vom Client empfangen. + + + Shellkontext {0} Befehlskontext {1} Anforderungs-ID {2}. Der Client hat eine Empfangsanforderung gesendet, damit der Server Daten senden kann. + + + Shellkontext {0} Befehlskontext {1} IsReceiveOperation {2}. Anforderung zum Schließen des Vorgangs erhalten. + + + Die Assembly „{0}“ für die benutzerdefinierte Shell mit der Shell-ID {1} wird geladen. + + + Der Typ {0} für die benutzerdefinierte Shell mit der Shell-ID {1} wird geladen. + + + Remotingfragment empfangen. + Objekt-ID: {0} + Fragment-ID: {1} + Startflag: {2} + Endflag: {3} + Nutzdatenlänge: {4} + Nutzlastdaten: {5} + + + Remotingfragment gesendet. + Objekt-ID: {0} + Fragment-ID: {1} + Startflag: {2} + Endflag: {3} + Nutzdatenlänge: {4} + Nutzlastdaten: {5} + + + Der WinRM-Dienst wird heruntergefahren. + + + Ein Objekt wurde erfolgreich neu aufgebaut. + Deserialisierter Typname: {0} + Durch Umwandlung in folgenden Typ aktiviert: {1} + Das neu aufgebaute Objekt ist vom Typ: {2} + + + Fehler beim Aktivieren eines Objekts. + Deserialisierter Typname: {0} + Durch Umwandlung in folgenden Typ aktiviert: {1} + Ausnahme bei Typumwandlung: {2} + Innere Ausnahme bei Typumwandlung: {3} + + + Die Serialisierungstiefe wurde überschrieben. + Serialisierter Typname: {0} + Ursprüngliche Tiefe: {1} + Überschriebene Tiefe: {2} + Aktuelle Tiefe unterhalb der obersten Ebene: {3} + + + Der Serialisierungsmodus wurde überschrieben. + Serialisierter Typname: {0} + Überschriebener Modus: {1} + + + Die Serialisierung einer Skripteigenschaft wurde übersprungen, da kein Runspace für die Auswertung der Eigenschaft verwendet werden kann. + Eigenschaftsname: {0} + Typname des Besitzers der Eigenschaft: {1} + Getterskript: {2} + + + Die Serialisierung einer Eigenschaft wurde übersprungen, da der Getter der Eigenschaft fehlgeschlagen ist. + Eigenschaftsname: {0} + Typname des Besitzers der Eigenschaft: {1} + Ausnahme aus dem Getter der Eigenschaft: {2} + Innere Ausnahme aus dem Getter der Eigenschaft: {3} + + + Die Serialisierung eines aufzählbaren Objekts wurde möglicherweise nicht abgeschlossen, da das aufzählbare Objekt eine Ausnahme ausgelöst hat. + Typ des aufzählbaren Objekts: {0} + Ausnahme: {1} + + + Bei der Serialisierung wurde die ToString-Methode des Objekts aufgerufen. Dabei ist ein Fehler aufgetreten. + Objekttyp: {0} + Ausnahme: {1} + + + Die maximale Tiefe unterhalb der obersten Ebene wurde erreicht. Das Objekt wird daher als Zeichenfolgen serialisiert. + Objekttyp bei maximaler Tiefe: {0} + Eigenschaftenname bei maximaler Tiefe: {1} + Tiefe: {2} + + + Vom Deserialisierer wurde eine XmlException ausgelöst (weist vermutlich auf ein falsches CLIXML-Format hin). + Zeilennummer: {0} Zeilenposition: {1} + Ausnahme: {2} + + + Fehler bei der Serialisierung der angegebenen Eigenschaften, da eine der angegebenen Eigenschaften fehlt. + Objekttyp: {0} + Eigenschaftenname: {1} + + + Die PowerShell-Konsole wird gestartet. + + + Die PowerShell-Konsole ist für Benutzereingaben bereit. + + + {0} + + + Ablaufverfolgungs-ErrorRecord: + Nachricht: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + Ausnahmedetails: + Nachricht: {5} + Stapelüberwachung: {6} + InnerException {7} + + + + Ausnahme: + Nachricht: {0} + StackTrace: {1} + InnerException: {2} + + + + PSObject wird nachverfolgt. + + + Ablaufverfolgungsauftrag: + ID: {0} + InstanceId: {1} + Name: {2} + Speicherort: {3} + Status: {4} + Befehl: {5} + + + + Ablaufverfolgungsinformationen: + {0} + + + Ablaufverfolgungsinformationen: + {0} {1} + + + ANFANG: ImportWorkflowCommand::StartWorkflowApplication. Der Aufruf der Workflowfunktion wird gestartet. Nachverfolgungs-GUID {0} + + + ENDE: ImportWorkflowCommand::StartWorkflowApplication. Der Aufruf der Workflowfunktion wird beendet. Nachverfolgungs-GUID {0} + + + ANFANG: Erstellen eines neuen Auftrags in „ImportWorkflowCommand::StartWorkflowApplication“. Nachverfolgungs-GUID {0} + + + ENDE: Erstellen eines neuen Auftrags in „ImportWorkflowCommand::StartWorkflowApplication“. Nachverfolgungs-GUID {0} + + + ENDE: Erstellen eines neuen Auftrags in „ImportWorkflowCommand::StartWorkflowApplication“. Tracking-GUID {0}: ContainerParentJob-GUID {1} + + + ANFANG: JobLogic ContainerParentJob GUID {0} + + + ENDE: JobLogic ContainerParentJob GUID {0} + + + ANFANG: WorkflowExecution ContainerParentJob GUID {0} + + + ENDE: WorkflowExecution ContainerParentJob GUID {0} + + + WorkflowJob mit GUID {0} zu ContainerParentJob mit GUID {1} hinzugefügt + + + ProxyJob mit GUID {0} ist dem remote ContainerParentJob mit GUID {1} zugeordnet + + + ANFANG: Ausführen von ContainerParentJob mit GUID {0} + + + ENDE: Ausführen von ContainerParentJob mit GUID {0} + + + ANFANG: Ausführen des Proxyauftrags mit GUID {0} + + + ENDE: Ausführen des Proxyauftrags mit GUID {0} + + + ANFANG: StateChanged-Ereignishandler für Proxyauftrag mit GUID {0} + + + ENDE: StateChanged-Ereignishandler für Proxyauftrag mit GUID {0} + + + ANFANG: StateChanged-Ereignishandler für untergeordneten Proxyauftrag mit GUID {0} + + + ENDE: StateChanged-Ereignishandler für untergeordneten Proxyauftrag mit GUID {0} + + + ANFANG: Ausführen der GC + + + ENDE: Ausführen der GC + + + Der Persistenzspeicher hat die maximal angegebene Größe erreicht. + + + Windows PowerShell ISE hat mit der Ausführung der Skriptdatei {0} begonnen. + + + Windows PowerShell ISE hat mit der Ausführung eines vom Benutzer ausgewählten Skripts aus der Datei {0} begonnen. + + + Windows PowerShell ISE beendet den aktuellen Befehl. + + + Windows PowerShell ISE setzt den Debugger fort. + + + Windows PowerShell ISE beendet den Debugger. + + + Windows PowerShell ISE führt das Debuggen schrittweise aus. + + + Windows PowerShell ISE führt das Debuggen schrittweise aus. + + + Windows PowerShell ISE beendet den Debugvorgang. + + + Windows PowerShell ISE aktiviert alle Haltepunkte. + + + Windows PowerShell ISE deaktiviert alle Haltepunkte. + + + Windows PowerShell ISE deaktiviert alle Haltepunkte. + + + Windows PowerShell ISE legt den Haltepunkt in Zeile #: {0} der Datei {1} fest. + + + Windows PowerShell ISE entfernt den Haltepunkt in Zeile #: {0} der Datei {1}. + + + Windows PowerShell ISE aktiviert den Haltepunkt in Zeile #: {0} der Datei {1}. + + + Windows PowerShell ISE deaktiviert den Haltepunkt in Zeile #: {0} der Datei {1}. + + + Windows PowerShell ISE hat einen Haltepunkt in Zeile #: {0} der Datei {1} erreicht. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/EventingResources.de.resx b/src/System.Management.Automation/resources/de/EventingResources.de.resx new file mode 100644 index 00000000000..3e9ed1334bc --- /dev/null +++ b/src/System.Management.Automation/resources/de/EventingResources.de.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die Registrierung für das angegebene Ereignis ist nicht möglich. Ereignisse, die einen Rückgabewert erfordern, werden nicht unterstützt. + + + Die Registrierung für das angegebene Ereignis ist nicht möglich. Ein Ereignis mit dem Namen „{0}“ ist nicht vorhanden. + + + PowerShell kann keine Windows RT-Ereignisse abonnieren. + + + Die Registrierung für das angegebene Ereignis ist nicht möglich. Der Ereignisquellenbezeichner „{0}“ ist für die PowerShell-Engine reserviert. + + + Dieser Vorgang wird auf Remoteinstanzen nicht unterstützt. + + + Die Aktion wird beim Weiterleiten von Ereignissen nicht unterstützt. + + + Das angegebene Ereignis kann nicht abonniert werden. Ein Abonnement mit dem Quellbezeichner „{0}“ ist bereits vorhanden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ExperimentalFeatureStrings.de.resx b/src/System.Management.Automation/resources/de/ExperimentalFeatureStrings.de.resx new file mode 100644 index 00000000000..bf02cf0f9ca --- /dev/null +++ b/src/System.Management.Automation/resources/de/ExperimentalFeatureStrings.de.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Es wurde keine experimentelle Funktion gefunden, die dem Namen „{0}“ entspricht. + + + Das Aktivieren und Deaktivieren experimenteller Funktionen wird erst beim nächsten Start von PowerShell wirksam. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ExtendedTypeSystem.de.resx b/src/System.Management.Automation/resources/de/ExtendedTypeSystem.de.resx new file mode 100644 index 00000000000..590cb3f736f --- /dev/null +++ b/src/System.Management.Automation/resources/de/ExtendedTypeSystem.de.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Der Member „{0}“ ist bereits vorhanden. + + + Der Member „{0}“ ist bereits in der Datei mit den erweiterten Typdaten vorhanden. + + + Der Member „{0}“ ist nicht vorhanden. + + + Ausnahme beim Festlegen von „{0}“: „{1}“ + + + Ausnahme beim Abrufen von „{0}“: „{1}“ + + + Die folgende Ausnahme ist beim Versuch aufgetreten, die Sammlung „{0}“ aufzulisten. + + + Auf den Member „{0}“ kann außerhalb eines PSObject nicht zugegriffen werden. + + + Das aus der Typkonfiguration „{0}“ erstellte Element kann nicht geändert werden. + + + Der Membername „{0}“ ist reserviert. + + + „{0}“ kann nicht geändert werden. + + + Ausnahme beim Aufrufen von „{0}“ mit „{1}“ Argument(en): „{2}“ + + + Beim Versuch, „{0}“ aufzurufen, um den Inhalt eines Objekts vom Typ „{1}“ zu extrahieren, ist eine Ausnahme aufgetreten: „{2}“ + + + Für „{0}“ konnte keine Überladung mit der Argumentanzahl „{1}“ gefunden werden. + + + Es wurde keine geeignete generische Methodenüberladung für „{0}“ mit „{1}“ Typparametern und der Argumentanzahl „{2}“ gefunden. + + + Es wurden mehrere mehrdeutige Überladungen für „{0}“ und die Argumentanzahl „{1}“ gefunden. + + + Das Argument „{0}“ mit dem Wert „{1}“ für „{2}“ kann nicht in den Typ „{3}“ konvertiert werden: „{4}“ + + + Der Get-Accessor für die Eigenschaft „{0}“ ist nicht verfügbar. + + + Der Set-Accessor für die Eigenschaft „{0}“ ist nicht verfügbar. + + + Die Setter-Methode muss „public“, „void“ und „static“ sein und zwei Parameter haben. Der erste Parameter sollte den PSObject-Typ aufweisen. Ein zweiter Parameter ist erforderlich, wenn auch eine Getter-Methode verfügbar ist, und sollte denselben Typ wie der Rückgabetyp der Getter-Methode haben. + + + Die Getter-Methode muss „public“, „not void“, „static“ und mit einem Parameter vom Typ „PSObject“ versehen sein. + + + CodeProperty sollte eine Getter- oder Setter-Methode verwenden. + + + Aufgrund des Methodenformats kann keine Codemethode erstellt werden. Die Methode muss öffentlich und statisch sein und einen Parameter vom Typ PSObject haben. + + + Der Alias mit dem Namen „{0}“ enthält einen Zyklus. + + + Der Wert „{0}“ vom Typ „{1}“ kann nicht in den Typ „{2}“ konvertiert werden. + + + Der Wert vom Typ „{0}“ kann nicht in den Typ „{1}“ konvertiert werden. + + + Der Wert „{0}“ kann nicht in den Typ „{1}“ konvertiert werden. Fehler: „{2}“ + + + Der Wert „{0}“ kann nicht in den Typ „{1}“ konvertiert werden, da für diese Aufzählung keine Kommas zulässig sind. + + + Der Wert „{0}“ kann wegen ungültiger Enumerationswerte nicht in den Typ „{1}“ konvertiert werden. Geben Sie einen der folgenden Enumerationswerte an, und versuchen Sie es erneut. Die möglichen Enumerationswerte sind „{2}“. + + + NULL kann wegen ungültiger Enumerationswerte nicht in den Typ „{0}“ konvertiert werden. Geben Sie einen der folgenden Enumerationswerte an, und versuchen Sie es erneut. Die möglichen Enumerationswerte sind „{1}“. + + + NULL kann nicht in den Typ „{0}“ konvertiert werden. + + + Der Wert kann nicht in den Typ „{0}“ konvertiert werden. Fehler: „{1}“ + + + Der Wert kann nicht in den Typ „System.String“ konvertiert werden. + + + Ein Verweistyp wird als Argument erwartet. + + + „{0}“ kann nicht verglichen werden, da es nicht IComparable implementiert. + + + „{0}“ konnte nicht mit „{1}“ verglichen werden. Fehler: „{2}“ + + + „{0}“ kann nicht mit „{1}“ verglichen werden, da die Objekte nicht denselben Typ haben oder das Objekt „{0}“ „{2}“ nicht implementiert. + + + Der Wert „{0}“ kann nicht in den Typ „{1}“ konvertiert werden, da mindestens zwei Übereinstimmungen gefunden wurden ({2}, {3}) und für diese Enumeration nur eine Übereinstimmung zulässig ist. + + + Der Wert „{0}“ kann nicht in den Typ „{1}“ konvertiert werden. Boolesche Parameter akzeptieren nur boolesche Werte und Zahlen wie $True, $False, 1 oder 0. + + + Der Eigenschaftswert kann nicht abgerufen werden, da „{0}“ eine schreibgeschützte Eigenschaft ist. + + + „{0}“ ist eine schreibgeschützte Eigenschaft. + + + „{0}“ kann nicht festgelegt werden, da für das Festlegen von XmlNode-Eigenschaften nur Zeichenfolgen als Werte verwendet werden können. + + + „{0}“ kann nicht festgelegt werden, da nur eindeutige Attribute oder eindeutige, nicht attributierte Blattknoten festgelegt werden können. + + + Ein PSProperty- oder PSMethod-Objekt kann dieser Sammlung nicht hinzugefügt werden. + + + Beim Laden der Datei mit den erweiterten Typdaten ist der folgende Fehler aufgetreten: {0} + + + Die folgende Ausnahme ist beim Abrufen der Zeichenfolge „{0}“ aufgetreten. + + + Das Feld oder die Eigenschaft „{0}“ für den Typ „{1}“ unterscheidet sich von dem Feld oder der Eigenschaft „{2}“ nur durch die Groß- und Kleinschreibung. Der Typ muss der Common Language Specification (CLS) entsprechen. + + + Die folgende Ausnahme ist beim Abrufen der Typnamenhierarchie „{0}“ aufgetreten. + + + Beim Abrufen des Members „{1}“ ist die folgende Ausnahme aufgetreten: „{0}“ + + + Beim Abrufen von Membern ist die folgende Ausnahme aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen des Lesestatus für die Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen des Schreibstatus für die Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen des Typs für die Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen der Zeichenfolgendarstellung für die Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen der Attribute für die Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen der Definitionen für die Methode „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen der Zeichenfolgendarstellung für die Methode „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen des Typs für die parametrisierte Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen des Lesestatus für die parametrisierte Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen des Schreibstatus für die parametrisierte Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen der Definitionen für die parametrisierte Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die folgende Ausnahme ist beim Abrufen der Zeichenfolgendarstellung für die parametrisierte Eigenschaft „{1}“ aufgetreten: „{0}“ + + + Die Value-Eigenschaft für das PSMemberInfo-Objekt vom Typ „{0}“ kann nicht festgelegt werden. + + + Argument: „{0}“ sollte ein „{1}“ sein. Verwenden Sie „{2}“. + + + Argument: „{0}“ darf kein {1} sein. {2} darf nicht verwendet werden. + + + Die {0}-Eigenschaft wurde nicht gefunden. + + + Der Eigenschaftswert kann nicht abgerufen oder festgelegt werden. Der Typ des Arguments „{0}“ sollte „{1}“ oder „{2}“ sein. + + + Der Wert für die Eigenschaft „{0}“ kann nicht festgelegt werden, da das Objekt den Typ „{1}“ statt „{2}“ aufweist. + + + Ausnahme beim Aufruf von „{0}“: „{1}“ + + + „{0}“ ist kein gültiger Klassenpfad. + + + {0} ist kein gültiger Pfad. + + + Der Adapter kann nicht feststellen, ob die Eigenschaft „{0}“ geändert werden kann. + + + Der Adapter kann nicht feststellen, ob die Eigenschaft „{0}“ abrufbar ist. + + + Der Adapter kann den Wert der Eigenschaft „{0}“ nicht abrufen. + + + Der Adapter kann den Wert der Eigenschaft „{0}“ nicht festlegen. + + + Der Adapter kann den Typ der Eigenschaft „{0}“ nicht abrufen. + + + Der Adapter kann den Typ der Hierarchie von „{0}“ nicht abrufen. + + + Der Adapter kann die Eigenschaften von „{0}“ nicht abrufen. + + + Der Adapter kann die Eigenschaft „{0}“ für „{1}“ nicht abrufen. + + + Von „{0}“ wurde ein Null-Wert zurückgegeben. + + + Die Eigenschaft „{0}“ wurde für das Objekt „{1}“ nicht gefunden. Die festlegbaren Eigenschaften sind: {2}. + + + Die Eigenschaft „{0}“ wurde für das Objekt „{1}“ nicht gefunden. Es ist keine festlegbare Eigenschaft verfügbar. + + + Das Objekt vom Typ „{0}“ kann nicht erstellt werden. {1} + + + Für den offenen generischen Typ „{0}“ können keine statischen Methoden aufgerufen und keine statischen Eigenschaften abgerufen werden. Geben Sie die Typparameter an, und versuchen Sie es erneut. Verwenden Sie zum Beispiel statt [System.Collections.Generic.HashSet``1]::CreateSetComparer() [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + Die folgende Ausnahme ist beim Erstellen des Attributs „{1}“ aufgetreten: „{0}“ + + + Der Wert „{0}“ kann nicht in ein Zeichenfolgenarray konvertiert werden. + + + Der Wert kann nicht in den Typ „{0}“ konvertiert werden. In diesem Sprachmodus werden nur Kerntypen unterstützt. + + + Eine Konvertierung in den ByRef-ähnlichen Typ „{0}“ ist nicht möglich. ByRef-ähnliche Typen werden in PowerShell nicht unterstützt. + + + Die Eigenschaft oder das Feld „{0}“ des ByRef-ähnlichen Typs „{1}“ kann nicht abgerufen oder festgelegt werden. ByRef-ähnliche Typen werden in PowerShell nicht unterstützt. + + + Die Methode „{0}“ des ByRef-ähnlichen Rückgabetyps „{1}“ kann nicht aufgerufen werden. ByRef-ähnliche Typen werden in PowerShell nicht unterstützt. + + + Es kann keine Instanz des ByRef-ähnlichen Typs „{0}“ erstellt werden. ByRef-ähnliche Typen werden in PowerShell nicht unterstützt. + + + Erweiterte Typsystem-Hashtabellenkonvertierung + + + Die Typkonvertierung von „HashTable“ in „{0}“ ist im ConstrainedLanguage-Modus nicht zulässig. + + + Erweiterte Typsystem-Hashtabellenkonvertierung + + + Die Typkonvertierung von „{0}“ in „{1}“ ist im ConstrainedLanguage-Modus nicht zulässig. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/FileSystemProviderStrings.de.resx b/src/System.Management.Automation/resources/de/FileSystemProviderStrings.de.resx new file mode 100644 index 00000000000..490abb2f0cc --- /dev/null +++ b/src/System.Management.Automation/resources/de/FileSystemProviderStrings.de.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Invoke Item + + + Item: {0} + + + Remove File + + + Remove Directory + + + Copy File + + + Item: {0} Destination: {1} + + + Copy Directory + + + Rename File + + + Rename Directory + + + Item: {0} Destination: {1} + + + Move File + + + Move Directory + + + Item: {0} Destination: {1} + + + Set Property File + + + Set Property Directory + + + Item: {0} Property: {1} Value: {2} + + + Clear Property File + + + Clear Property Directory + + + Item: {0} Property: {1} + + + Create File + + + Create Directory + + + Destination: {0} + + + Clear Content + + + Item: {0} + + + Could not find item {0}. + + + Cannot remove item {0}: {1} + + + Cannot restore attributes on item {0}: {1} + + + An object at the specified path {0} does not exist. + + + Directory {0} cannot be removed because it is not empty. + + + The type is not a known type for the file system. Only "file","directory" or "symboliclink" can be specified. + + + Cannot process the path because the specified path refers to an item that is outside the basePath. + + + The specified drive root "{0}" either does not exist, or it is not a folder. + + + An item with the specified name {0} already exists. + + + A delimiter cannot be specified when reading the stream one byte at a time. + + + Cannot overwrite the item {0} with itself. + + + Cannot rename the specified target, because it represents a path or device name. + + + The property {0} does not exist or was not found. + + + You do not have sufficient access rights to perform this operation or the item is hidden, system, or read only. + + + The attribute cannot be set because attributes are not supported. Only the following attributes can be set: Archive, Hidden, Normal, ReadOnly, or System. + + + The property cannot be cleared because the property is not supported. Only the Attributes property can be cleared. + + + Cannot process path '{0}' because the target represents a reserved device name. + + + Encoding not used when '-AsByteStream' specified. + + + Cannot proceed with byte encoding. When using byte encoding the content must be of type byte. + + + Cannot process the file because the file {0} was not found. + + + Directory: + + + Cannot detect the encoding of the file. The specified encoding {0} is not supported when the content is read in reverse. + + + Could not open the alternate data stream '{0}' of the file '{1}'. + + + Stream '{0}' of file '{1}'. + + + The Raw and Wait parameters cannot be specified in the same command. + + + To use the Persist switch parameter, the drive name must be supported by the operating system (for example, drive letters A-Z). + + + When you use the Persist parameter, the root must be a file system location on a remote computer. + + + The '{0}' and '{1}' parameters cannot be specified in the same command. + + + A directory is required for the operation. The item '{0}' is not a directory. + + + Create Junction + + + Create Symbolic Link + + + Administrator privilege required for this operation. + + + Create Hard Link + + + A file is required for the operation. The item '{0}' is not a file. + + + Hard links are not supported for the specified path. + + + Symbolic links are not supported for the specified path. + + + '{0}' wird in '{1}' kopiert. + + + Destination path {0} is a file that already exists on the target destination. + + + Failed to copy file {0} to remote target destination. + + + Von {0} bis {1} + + + Cannot copy a directory '{0}' to file '{0}' + + + Failed to get directory {0} child items. + + + Failed to read remote file '{0}'. + + + Cannot validate if remote destination {0} is a file. + + + Failed to create directory '{0}' on remote destination. + + + Maximum size for drive has been exceeded: {0}. + + + Cannot create link because the path already exists: {0}. + + + Skip already-visited directory {0}. + + + Destination path cannot be a subdirectory of the source or the source itself: {0}. + + + The target and path cannot be the same. + + + Copied {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Removed {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Creating a junction requires an absolute path for the target. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/FormatAndOutXmlLoadingStrings.de.resx b/src/System.Management.Automation/resources/de/FormatAndOutXmlLoadingStrings.de.resx new file mode 100644 index 00000000000..b0be1be50f7 --- /dev/null +++ b/src/System.Management.Automation/resources/de/FormatAndOutXmlLoadingStrings.de.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Fehler bei XPath „{0}“ in Datei {1}: Das XML-Element {2} lässt keine Attribute zu. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Knoten „{2}“ darf keine untergeordneten Objekte haben. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} ist ungültig. + + + Fehler bei XPath „{0}“ in Datei {1}: Es muss mindestens ein Standard {2} vorhanden sein. + + + Fehler bei XPath „{0}“ in Datei {1}: Es darf nicht mehr als ein Standard {2} vorhanden sein. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Steuerelementname darf nicht NULL oder leer sein. + + + Fehler bei XPath „{0}“ in Datei {1}: Out-of-Band-Ansichten können nur CustomControl oder ListControl enthalten. + + + Fehler bei XPath „{0}“ in Datei {1}: Eine Out-of-Band-Ansicht darf kein GroupBy enthalten. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Ansicht kann nicht geladen werden. + + + Fehler bei XPath „{0}“ in Datei {1}: „{2}“ ist kein gültiger Ausrichtungswert. + + + Fehler bei XPath „{0}“ in Datei {1}: Es wird eine positive ganze Zahl erwartet. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Definition der Spaltenüberschriften ist ungültig; alle Überschriften werden verworfen. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Anzahl der Zeilenelemente = {2} im alternativen Satz #{3} stimmt nicht mit der Standardanzahl der Zeilenelemente = {4} überein. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Anzahl der Headerelemente = {2} stimmt nicht mit der Standardanzahl der Zeilenelemente = {3} überein. + + + Fehler bei XPath „{0}“ in Datei {1}: Mindestens ein Element in der Listenansicht muss angegeben werden. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Eigenschaftseintrag ist ungültig. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Definitionsliste fehlt. + + + Fehler bei XPath „{0}“ in Datei {1}: Es wird ein boolescher Wert erwartet. + + + Fehler bei XPath „{0}“ in Datei {1}: Es wird eine nicht negative ganze Zahl erwartet. + + + Fehler bei XPath „{0}“ in Datei {1}: Es wird eine ganze Zahl erwartet. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Wert des inneren Texts fehlt. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Tokenliste des benutzerdefinierten Steuerelements darf nicht leer sein. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} konnte nicht geladen werden. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} kann nicht ohne Ausdruck angegeben werden. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} kann nicht mit Ausdruck angegeben werden. + + + Fehler bei XPath „{0}“ in Datei {1}: Eine Formatzeichenfolge fehlt. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Skriptblocktext fehlt. + + + Fehler bei XPath „{0}“ in Datei {1}: Eine Eigenschaft fehlt. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Skriptblock „{2}“ ist ungültig. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Zeichenfolge {2} aus der Ressource „{3}“ in der Assembly {4} wurde nicht gefunden. + + + Fehler beim XPath „{0}“ in der Datei {1}: Die Ressource „{2}“ in der Assembly „{3}“ wurde nicht gefunden. + + + Fehler bei XPath „{0}“ in Datei {1}: Die Assembly {2} wurde nicht gefunden. + + + Fehler bei XPath „{0}“ in Datei {1}: Der Knoten muss ein XmlElement sein. + + + Fehler bei XPath „{0}“ in Datei {1}: Ein Ausdruck wird erwartet. + + + Fehler bei XPath „{0}“ in Datei {1}: Steuerelement oder Label kann nicht ohne Ausdruck verwendet werden. + + + Fehler bei XPath „{0}“ in Datei {1}: Steuerelement und Bezeichnung können nicht gleichzeitig vorhanden sein. + + + Fehler bei XPath „{0}“ in Datei {1}: SelectionSetName und TypeName können nicht gleichzeitig angegeben werden. + + + Fehler bei XPath „{0}“ in Datei {1}: Für das Anwenden der Ansicht ist kein Typ und keine Bedingung angegeben. + + + Fehler bei XPath „{0}“ in Datei {1}: Der {2}-Wert ist ungültig. + + + Fehler bei XPath „{0}“ in Datei {1}: Ein doppelter Knoten ist vorhanden. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} und {3} schließen sich gegenseitig aus. + + + Fehler bei XPath „{0}“ in Datei {1}: {2}, {3} und {4} schließen sich gegenseitig aus. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} ist ein unbekannter Knoten. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} ist ein unbekanntes Attribut. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} ist ein fehlendes Attribut. + + + Fehler bei XPath „{0}“ in Datei {1}: Knoten {2} fehlt. + + + Fehler beim XPath „{0}“ in der Datei {1}: In „{2}“ fehlt ein Knoten. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} ist ein leerer Knoten. + + + Fehler bei XPath „{0}“ in Datei {1}: {2} ist ein leeres Attribut. + + + Fehler in Datei {0}: {1} + + + Zu viele Fehler in Datei „{0}“. + + + Beim Laden der Formatdatendatei sind Fehler aufgetreten: {0} + + + (Globaler Assemblycachee) {0} + + + {0}, {1} + + + Der {0}-Pfad ist nicht vollqualifiziert. Geben Sie einen vollqualifizierten Formatdateipfad an. + + + Die FormatTable kann nicht aktualisiert werden, da die FormatTable möglicherweise außerhalb des Runspaces erstellt wurde. + + + Beim Laden der FormatTable sind Fehler aufgetreten. Zeigen Sie den Inhalt der Errors-Eigenschaft an, um detaillierte Fehlermeldungen abzurufen. + + + Fehler beim Formatieren der Daten „{0}“: {1} + + + Fehler in den Ansichtsdaten mit dem Typnamen {0} am Index {1}: Die Anzahl der Kopfzeilenelemente = {2} stimmt nicht mit der Standardanzahl der Zeilenelemente = {3} überein. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: Die Formatierung der Daten „{2}“ ist ungültig. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: Der Skriptblock „{2}“ ist ungültig. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: {2} konnte nicht geladen werden. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: Ein TableControl darf nur {2} enthalten. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: Es muss mindestens ein Standard {2}vorhanden sein. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: Es muss mindestens ein Element in der Listenansicht angegeben werden. + + + Fehler in Ansichtsdaten mit dem Typnamen „{0}“ bei Index {1}: Es darf nicht mehr als ein Standard {2}vorhanden sein. + + + Zu viele Fehler in den Formatierungsdaten für Typ „{0}“. + + + Eine freigegebene Formattabelle kann nicht mit mehr als einem Eintrag aktualisiert werden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/FormatAndOut_MshParameter.de.resx b/src/System.Management.Automation/resources/de/FormatAndOut_MshParameter.de.resx new file mode 100644 index 00000000000..efd867e41dc --- /dev/null +++ b/src/System.Management.Automation/resources/de/FormatAndOut_MshParameter.de.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 + + + {0} kann nicht in einen der folgenden Typen {1} konver werden. + + + Der Wert eines Parameters war Null. einer der folgenden Typen wurde erwartet: {0}. + + + Der duplizierte Schlüssel „{0}“ verursacht einen Konflikt mit „{1}“. + + + Der Schlüssel „{0}“ weist einen ungültigen Typ {1} auf; erwartete Typen sind {2}. + + + Der Schlüssel „{0}“ weist einen ungültigen Typ „{1}“ auf; erwarteter Typ: {2}. + + + Der Schlüssel {0} ist mehrdeutig und {1} und {2} stehen in Konflikt. + + + Der Wert eines Schlüssels darf nicht Null sein. + + + Der Schlüsseltyp „{0}“ ist ungültig. Der Schlüssel muss eine Zeichenfolge sein. + + + Der Schlüssel „{0}“ hat keinen Wert. + + + Ein obligatorischer Eintrag für {0} fehlt. + + + Der Schlüssel „{0}“ ist ungültig. + + + Der Wert „{0}“ für den Schlüssel „{1}“ ist ungültig. Gültige Werte sind {2}. + + + Der Wert „{0}“ für den Schlüssel „{1}“ muss größer als 0 sein. + + + Für den Schlüssel „{0}“ darf keine leere Formatierungszeichenfolge vorhanden sein. + + + Der Schlüssel „{0}“ darf keinen leeren Zeichenfolgenwert aufweisen. + + + Ein leerer Zeichenfolgenwert ist nicht zulässig. + + + Der Schlüssel „{0}“ darf keine Platzhalterzeichen im Wert „{1}“ enthalten. + + + Die Platzhalterzeichen sind in „{0}“ nicht zulässig. + + + Der EnumerableExpansion-Wert ist ungültig. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/FormatAndOut_format_xxx.de.resx b/src/System.Management.Automation/resources/de/FormatAndOut_format_xxx.de.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/de/FormatAndOut_format_xxx.de.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/FormatAndOut_out_xxx.de.resx b/src/System.Management.Automation/resources/de/FormatAndOut_out_xxx.de.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/de/FormatAndOut_out_xxx.de.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/GetErrorText.de.resx b/src/System.Management.Automation/resources/de/GetErrorText.de.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/de/GetErrorText.de.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/HelpDisplayStrings.de.resx b/src/System.Management.Automation/resources/de/HelpDisplayStrings.de.resx new file mode 100644 index 00000000000..570244f98ea --- /dev/null +++ b/src/System.Management.Automation/resources/de/HelpDisplayStrings.de.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NAME + + + SYNOPSIS + + + DESCRIPTION + + + SYNTAX + + + PARAMETERS + + + INPUTS + + + OUTPUTS + + + TERMINATING ERRORS + + + NON-TERMINATING ERRORS + + + NOTES + + + EXAMPLES + + + Beispiel + + + EXAMPLE + + + OUTPUT + + + RELATED LINKS + + + SHORT DESCRIPTION + + + Title: + + + Question: + + + Antwort + + + Term: + + + Definition: + + + Content: + + + PROVIDER NAME + + + This cmdlet supports the common parameters: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. For more information, see + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Required? + + + Position? + + + Type: + + + Target Object Type: + + + Default value + + + Accept pipeline input? + + + Accept wildcard characters? + + + (Category: + + + Suggested Action: + + + For more information, type: + + + For technical information, type: + + + To see the examples, type: + + + For online help, type: + + + <CommonParameters> + + + REMARKS + + + true + + + Named + + + DRIVES + + + CAPABILITIES + + + TASKS + + + TASK: + + + FILTERS + + + DYNAMIC PARAMETERS + + + Cmdlets Supported: + + + ALIASES + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + -- To view the Help topic for this cmdlet online, type: "Get-Help {0} -Online" or + go to {1}. + + + Keine + + + Aliases + + + Dynamic? + + + Parameter set name + + + Unable to retrieve the HelpInfo XML file for UI culture {0}. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + + + The ModuleBase directory cannot be found. Verify the directory and try again. + + + The path {0} is not a valid directory. Make sure the directory exists and retry. + + + A Help URI cannot contain more than 10 redirections. Specify a valid Help URI. + + + Updating Help + + + Connecting to Help Content... + + + Downloading Help Content... + + + Installing Help content... + + + Locating Help Content... + + + (All) + + + No PowerShell modules were found that match the following pattern: {0}. Verify the pattern and then try the command again. + + + No PowerShell modules were found that match the specified FullyQualifiedModule {0}. Verify the FullyQualifiedModule value and then try the command again. + + + Help content cannot be found. Make sure the server is available and the help content location is properly defined in the HelpInfo XML. + + + The Update-Help command failed because the specified module does not support updatable help. Use Get-Help -Online or look online for help for the commands in this module. + + + The following parameter must not be null or empty: Module. + + + The following parameter must not be null or empty: Path. + + + Update-Help has completed successfully. + + + Error extracting Help content. + + + Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. + + + The Help content at the specified location is not valid. Specify a location that contains valid Help Content. + + + The HelpInfo XML is not valid. Specify valid HelpInfo XML. + + + Help content was successfully saved to the following location: {0} + + + The Help content XSD file cannot be found in {0}. Verify that the XSD file exists at the specified location, and then retry the command. + + + Failed to update Help for the module(s) : +'{0}' +{1} + + + Saving Help + + + Help content contains files that are not valid. Only .txt and .xml files are supported. + + + Failed to save Help for the module(s) '{0}' : {1} + + + Failed to save Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be saved using: Save-Help -UICulture en-US. + + + Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + + + false + + + The -Recurse parameter is only available if a source path is specified. + + + The path {0} does not contain a FileSystem provider. Verify that the specified path contains the FileSystem provider, and then retry the command. + + + Searching Help for {0} ... + + + No UI culture was found that matches the following pattern: {0}. Verify the pattern and then try the command again. + + + Help was not saved for the module {0}, because the Save-Help command was run on this computer within the last 24 hours. +To save help again, add the Force parameter to your command. + + + Help was not updated for the module {0}, because the Update-Help command was run on this computer within the last 24 hours. +To update help again, add the Force parameter to your command. + + + The most current Help files are already installed. + + + {0}: {1}. Culture {2} Version {3} + + + Updated {0} + + + The value of the HelpInfoUri key in the module manifest must resolve to a container or root URL on a website where the help files are stored. The HelpInfoUri '{0}' does not resolve to a container. + + + Help content must be in the namespace {0}. + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + + + The most current Help files are already downloaded. + + + Saved {0} + + + The HelpInfoURI {0} does not start with HTTP. + + + The root level element of the help content must be "helpItems". + + + Saving Help for module {0} + + + Updating Help for module {0} + + + Resolving URI: "{0}" + + + Help URI: {0} + + + {0}, Current Version: {1}, Available Version: {2}, UICulture: {3} + + + PROPERTIES + + + METHODS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/HelpErrors.de.resx b/src/System.Management.Automation/resources/de/HelpErrors.de.resx new file mode 100644 index 00000000000..2e0b6273476 --- /dev/null +++ b/src/System.Management.Automation/resources/de/HelpErrors.de.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + „Get-Help“ konnte in dieser Sitzung keine „{0}“ in einer Hilfedatei finden. Geben Sie zum Herunterladen aktualisierter Hilfethemen Folgendes ein: „Update-Help“. Um online Hilfe zu erhalten, suchen Sie in der TechNet-Bibliothek unter https://go.microsoft.com/fwlink/?LinkID=107116 nach dem Hilfethema. + + + Die Hilfekategorie kann nicht verarbeitet werden, da „{0}“ keine gültige Hilfekategorie ist. + + + Die Hilfedatei „{0}“ kann nicht geladen werden. Details: {1}. + + + Auf die Hilfedatei „{0}“ kann nicht zugegriffen werden, da der aktuelle Benutzer keine Zugriffsrechte für die Datei besitzt. Details: {1}. + + + Die Hilfedatei „{0}“ ist kein gültiges XML-Dokument. Details: {1}. + + + Beim Laden des Hilfeinhalts für „{0}“ aus der Datei „{1}“ ist ein Fehler aufgetreten. Details: {2}. Um aktualisierte Hilfethemen herunterzuladen, führen Sie das Cmdlet „Update-Help“ aus. Um online Hilfe zu erhalten, suchen Sie in der TechNet-Bibliothek unter https://go.microsoft.com/fwlink/?LinkID=107116 nach dem Hilfethema. + + + Der Anbieter „{0}“ kann nicht geladen werden. Details: {1}. + + + Die Hilfedatei kann nicht geladen werden. Die folgenden {1}-Fehler sind beim Laden der Hilfedatei „{0}“ aufgetreten. + + + Der Knoten „{0}“ darf „{1}“ nicht als untergeordneten Knoten haben. Knotenpfad: {2}. + + + Der Knoten „{0}“ darf maximal {2} untergeordnete Knoten vom Typ „{1}“ haben. Knotenpfad: {3}. + + + Der Registrierungsschlüssel „{0}{1}“ wurde nicht gefunden; verwenden Sie „{2}“ zum Laden der Hilfedateien. + + + Kein Parameter entspricht den {0}-Kriterien. + + + „{0}“ wird von der angeforderten Hilfekategorie nicht unterstützt. + + + Die Onlineversion dieses Hilfethemas kann nicht angezeigt werden, da die Internetadresse (URI) des Hilfethemas im Befehlscode oder in der Hilfedatei für den Befehl nicht angegeben ist. + + + Der angegebene URI „{0}“ ist ungültig. + + + Beim Starten eines Browsers zum Anzeigen der Onlinehilfe ist ein Fehler aufgetreten. Zum Öffnen der URI „{0}“ ist kein Programm oder Browser zugeordnet. + + + Das im URI „{0}“ angegebene Protokoll wird nicht unterstützt. Es werden nur die Protokolle „{1}“ und „{2}“ unterstützt. + + + Es wurden mehrere Hilfethemen gefunden. Verwenden Sie nur ein Hilfethema mit der Option „-{0} “. + + + Von einem Remoterunspace kann keine Hilfe abgerufen werden, da der Runspace nicht geöffnet wurde. Öffnen Sie den Runspace, indem Sie einen impliziten Remotingbefehl ausführen, und versuchen Sie dann erneut, den Befehl zum Abrufen der Hilfe auszuführen. + + + Der Zugriff wird verweigert. Der Befehl konnte die Hilfethemen für die PowerShell-Kernmodule oder für Module im Verzeichnis „$pshome\Modules“ nicht aktualisieren. +Um diese Hilfethemen zu aktualisieren, starten Sie PowerShell mit dem Befehl „Als Admin ausführen“, und führen Sie „Update-Help“ erneut aus. + + + Um die „{0}“ zu verwenden, stellen Sie sicher, dass Ihre Anwendung „Microsoft.NET.Sdk.WindowsDesktop“ als Projekt-SDK verwendet und die entsprechende Assembly „Microsoft.PowerShell.GraphicalHost“ verfügbar ist. ({1}) + + + „{0}“ funktioniert in einer Remotesitzung nicht. + + + „ForwardHelpTargetName“ kann nicht auf die Funktion selbst verweisen. + + + In einer eingeschränkten Sitzung kann keine Hilfe von einem Netzwerkstandort abgerufen werden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/HistoryStrings.de.resx b/src/System.Management.Automation/resources/de/HistoryStrings.de.resx new file mode 100644 index 00000000000..2d30f757515 --- /dev/null +++ b/src/System.Management.Automation/resources/de/HistoryStrings.de.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Der Bezeichner „{0}“ ist kein gültiger Wert für einen Verlaufsbezeichner. Geben Sie eine positive Zahl an, und wiederholen Sie den Vorgang. + + + Der Verlauf für die ID „{0}“ kann nicht gefunden werden. + + + Die Anzahl kann nicht mit mehreren IDs kombiniert werden. + + + Der Verlauf für die Befehlszeile „{0}“ kann nicht gefunden werden. + + + Der neueste Verlauf kann nicht gefunden werden. + + + Das Cmdlet „Invoke-History“ wird wiederholt in einer Schleife aufgerufen. + + + Es können nicht mehrere Verlaufsbefehle verarbeitet werden. Mit „Invoke-History“ kann nur ein einzelner Befehl ausgeführt werden. + + + Der Verlauf kann nicht hinzugefügt werden, da das Eingabeobjekt ein ungültiges Format aufweist. + + + Der Bezeichner „{0}“ ist ungültig. Geben Sie eine positive Zahl an, und wiederholen Sie den Vorgang. + + + Mit diesem Befehl werden alle Einträge aus dem Sitzungsverlauf gelöscht. + + + Die Anzahl kann nicht mit mehreren CommandLine-Parametern kombiniert werden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/HostInterfaceExceptionsStrings.de.resx b/src/System.Management.Automation/resources/de/HostInterfaceExceptionsStrings.de.resx new file mode 100644 index 00000000000..a8264688cfc --- /dev/null +++ b/src/System.Management.Automation/resources/de/HostInterfaceExceptionsStrings.de.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 + + + Ein Fehler vom Typ „{0}“ ist aufgetreten. + + + Ein Befehl, der einen Prompt an die Benutzerseite stellte, ist fehlgeschlagen, da das Hostprogramm oder der Befehlstyp keine Benutzerinteraktion unterstützt. Verwenden Sie ein Hostprogramm, das Benutzerinteraktion unterstützt, z. B. die PowerShell-Konsole, und entfernen Sie Befehle mit Eingabeaufforderungen aus Befehlstypen, die keine Benutzerinteraktion unterstützen. + + + Ein Befehl, der einen Prompt an die Benutzerseite stellte, ist fehlgeschlagen, da das Hostprogramm oder der Befehlstyp keine Benutzerinteraktion unterstützt. Der Host hat versucht, mit der folgenden Meldung eine Bestätigung anzufordern: {0} + + + Die Methode kann nicht aufgerufen werden, da der Pool geschlossen wurde oder ein Fehler aufgetreten ist. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/InternalCommandStrings.de.resx b/src/System.Management.Automation/resources/de/InternalCommandStrings.de.resx new file mode 100644 index 00000000000..377a1f19d70 --- /dev/null +++ b/src/System.Management.Automation/resources/de/InternalCommandStrings.de.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched methods. Possible matches include:{1}. + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched members. Possible matches include:{1}. + + + Retrieve the value for key '{0}' + + + Invoke method '{0}' with arguments: {1} + + + Invoke method '{0}' + + + Retrieve the value for property '{0}' + + + InputObject: {0} + + + Cannot operate on a 'null' input object. + + + Input name "{0}" cannot be resolved to a method. + + + Cannot invoke a method in the restricted language mode. + + + The -WhatIf and -Confirm parameters are not supported for script blocks. + + + The '{0}' operation is not allowed in the RestrictedLanguage mode. + + + An operator is required to compare the two specified values. Include a valid operator in the command, and then try the command again. For example, Get-Process | Where-Object -Property Name -eq Idle + + + The input name "{0}" cannot be resolved to a property. + + + The input name "{0}" cannot be resolved to a member. + + + The specified operator requires both the -Property and -Value parameters. Provide values for both parameters, and then try the command again. + + + This method cannot be run on the current thread. It can only be called on the cmdlet thread. + + + A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + A ForEach-Object -Parallel piped input object cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + The 'TimeoutSeconds' parameter cannot be used with the 'AsJob' parameter. + + + The following common parameters are not currently supported in the Parallel parameter set: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/InternalHostStrings.de.resx b/src/System.Management.Automation/resources/de/InternalHostStrings.de.resx new file mode 100644 index 00000000000..7614dbf869e --- /dev/null +++ b/src/System.Management.Automation/resources/de/InternalHostStrings.de.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 + + + EnterNestedPrompt wurde nicht so oft aufgerufen wie ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/InternalHostUserInterfaceStrings.de.resx b/src/System.Management.Automation/resources/de/InternalHostUserInterfaceStrings.de.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/de/InternalHostUserInterfaceStrings.de.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/Logging.de.resx b/src/System.Management.Automation/resources/de/Logging.de.resx new file mode 100644 index 00000000000..8cdfb530ad3 --- /dev/null +++ b/src/System.Management.Automation/resources/de/Logging.de.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + UNBEKANNT + + + Das experimentelle Engine-Feature „{0}“, das in der Konfigurationsdatei deklariert ist, ist in der aktuellen PowerShell nicht registriert. + + + Das in der Konfigurationsdatei deklarierte experimentelle Feature „{0}“ ist ungültig. +Der Name eines experimentellen Features sollte der folgenden Konvention entsprechen: + Name des Modulfeatures: „PS[FeatureName]“ + Name des Modulfeatures: „[Modulname]. [Featurename]“ + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/Metadata.de.resx b/src/System.Management.Automation/resources/de/Metadata.de.resx new file mode 100644 index 00000000000..e3f4b09e6ea --- /dev/null +++ b/src/System.Management.Automation/resources/de/Metadata.de.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Attribute für „{0}“ können nicht initialisiert werden: „{1}“ + + + Das Argument kann nicht überprüft werden, da sein Typ „{0}“ nicht mit dem Typ ({1}) der maximalen und minimalen Grenzen des Parameters übereinstimmt. Stellen Sie sicher, dass das Argument vom Typ „{1}“ ist, und führen Sie den Befehl dann erneut aus. + + + Das Argument „{0}“ kann nicht überprüft werden, da sein Wert nicht größer als NULL ist. + + + Das Argument „{0}“ kann nicht überprüft werden, da sein Wert nicht größer oder gleich NULL ist. + + + Das Argument „{0}“ kann nicht überprüft werden, da sein Wert nicht kleiner als NULL ist. + + + Das Argument „{0}“ kann nicht überprüft werden, da sein Wert nicht kleiner oder gleich NULL ist. + + + Der angegebene minimale Bereich ({0}) kann nicht akzeptiert werden, da er nicht denselben Typ wie der angegebene maximale Bereich ({1}) hat. Aktualisieren Sie das Attribut „ValidateRange“ für den Parameter. + + + Die Parametertypen „MaxRange“ und „MinRange“ können nicht akzeptiert werden. Beide Parameter müssen Objekte sein, die eine IComparable-Schnittstelle implementieren. + + + Der angegebene maximale Bereich kann nicht akzeptiert werden, da er kleiner als der angegebene Mindestbereich ist. Aktualisieren Sie das Attribut „ValidateRange“ für den Parameter. + + + Das {0}-Argument ist größer als der maximal zulässige Bereich von {1}. Geben Sie ein Argument an, das kleiner oder gleich {1} ist, und führen Sie den Befehl dann erneut aus. + + + Das {0}-Argument ist kleiner als der minimal zulässige Bereich von {1}. Geben Sie ein Argument an, das größer oder gleich {1} ist, und führen Sie den Befehl dann erneut aus. + + + Das Argument „{0}“ stimmt nicht mit dem Muster „{1}“ überein. Geben Sie ein Argument an, das „{1}“ entspricht, und führen Sie den Befehl dann erneut aus. + + + Das ValidateCount-Attribut kann nicht auf einen Parameter angewendet werden, der kein Array ist. Entfernen Sie das Attribut aus dem Parameter, oder machen Sie den Parameter zu einem Arrayparameter. + + + Der Parameter erfordert genau {0} Wert(e) – {1} Wert(e) wurden bereitgestellt. + + + Der Parameter erfordert mindestens {0} Wert(e) und nicht mehr als {1} Wert(e) – {2} Wert(e) wurden bereitgestellt. + + + Die angegebene maximale Anzahl von Argumenten für einen Parameter ist kleiner als die angegebene minimale Anzahl von Argumenten. Aktualisieren Sie das ValidateCount-Attribut für den Parameter. + + + Die angegebene maximale Zeichenlänge des Arguments ist kürzer als die angegebene minimale Zeichenlänge des Arguments. Aktualisieren Sie das ValidateLength-Attribut für den Parameter. + + + Das ValidateLength-Attribut kann nicht auf einen Parameter angewendet werden, der kein String- oder String[]-Parameter ist. Ändern Sie den Parameter in einen String- oder String[]-Parameter. + + + Die Zeichenlänge ({1}) des Arguments ist zu kurz. Geben Sie ein Argument an, dessen Länge größer oder gleich „{0}“ ist, und führen Sie den Befehl dann erneut aus. + + + Die Zeichenlänge ({1}) des Arguments ist zu lang. Geben Sie ein Argument an, dessen Länge kürzer oder gleich „{0}“ ist, und führen Sie den Befehl dann erneut aus. + + + Das Argument „{0}“ gehört nicht zu dem vom ValidateSet-Attribut angegebenen Satz „{1}“. Geben Sie ein Argument an, das sich im Satz befindet, und wiederholen Sie dann den Befehl. + + + Der Generator für gültige Werte gibt einen NULL-Wert zurück. + + + „{0}“ ist bei der Eigenschaft „{1}“ {2} fehlgeschlagen + + + Der Befehl kann nicht abgerufen oder ausgeführt werden. Die maximale Anzahl von Parametersätzen für diesen Befehl wurde überschritten. + + + Das Argument kann nicht verarbeitet werden, da der Argumentwert keine Zeichenfolge ist. Die Werte von Parameterargumenten, für die das TransformationAttribute-Argument angegeben ist, müssen Zeichenfolgen sein. + + + Die Variable kann nicht überprüft werden, da der Wert „{1}“ kein gültiger Wert für die Variable „{0}“ ist. + + + Das Attribut kann nicht hinzugefügt werden, da die Variable „{0}“ mit dem Wert „{1}“ sonst nicht mehr gültig wäre. + + + Das Argument ist NULL. Geben Sie einen gültigen Wert für das Argument an, und versuchen Sie dann, den Befehl erneut auszuführen. + + + Das Argument hat einen NULL-Wert, oder ein Element der Argumentsammlung enthält einen NULL-Wert. Geben Sie eine Sammlung an, die keine NULL-Werte enthält, und führen Sie den Befehl dann erneut aus. + + + Das Argument ist NULL oder leer. Geben Sie ein Argument an, das nicht NULL oder leer ist, und führen Sie den Befehl erneut aus. + + + Das Argument ist NULL, leer, oder ein Element der Argumentsammlung enthält einen NULL-Wert. Geben Sie eine Sammlung an, die keine NULL-Werte enthält, und führen Sie den Befehl dann erneut aus. + + + Das Argument ist NULL, leer oder besteht nur aus Leerzeichen. Geben Sie ein Argument an, das nicht nur Leerzeichen enthält, und führen Sie den Befehl dann erneut aus. + + + Ein Element der Argumentsammlung ist NULL, leer oder besteht nur aus Leerzeichen. Geben Sie eine Sammlung an, die keine dieser Werte enthält, und führen Sie den Befehl dann erneut aus. + + + Ein Parameter mit dem Namen „{0}“ wurde für den Befehl mehrfach definiert. + + + Der Parameteralias kann nicht angegeben werden, da für den Befehl bereits ein Alias mit dem Namen „{0}“ mehrfach definiert wurde. + + + Der Parameter „{0}“ kann nicht angegeben werden, da er mit dem gleichnamigen Parameteralias für den Parameter „{1}“ in Konflikt steht. + + + Das Validierungsskript „{1}“ für das Argument mit dem Wert „{0}“ hat nicht den Wert TRUE zurückgegeben. Ermitteln Sie, warum das Validierungsskript fehlgeschlagen ist, und führen Sie den Befehl dann erneut aus. + + + Das Argument „{0}“ enthält keine gültige PowerShell-Version. Geben Sie eine gültige Versionsnummer an, und führen Sie den Befehl dann erneut aus. + + + Das Argument „{0}“ kann nicht überprüft werden, da es kein gültiger Variablenname ist. + + + Der Conversion-Typ des Auftrags muss von „IAstToScriptBlockConverter“ abgeleitet werden. + + + Das Argument ist ungültig. Geben Sie ein Pfadargument vom Typ Zeichenfolge an. + + + Das Laufwerk {0} des Pfadarguments gehört nicht zu den zulässigen Laufwerken: {1}. Geben Sie ein Pfadargument mit einem zulässigen Laufwerk an. + + + Das Pfadargument enthält ungültige Zeichen. + + + Das Pfadargument hat kein Stammauslaufwerk. Geben Sie ein vollständiges Pfadargument mit einem Stammauslaufwerk an. + + + Der Argumentwert für den Parameter „{0}“ darf nicht NULL oder eine leere Zeichenfolge sein. + + + Das Enumerationselement „{0}“ ist kein gültiger Wert für den Parameter „{1}“. Geben Sie eines der folgenden Elementen an, und versuchen Sie es erneut: {2}. + + + Die Eingabe kann nicht verarbeitet werden. Das Argument „{0}“ ist nicht vertrauenswürdig. + + + Fehler bei der Prüfung des ValidateTrustedData-Attributs. + + + Das Parameterargument „{0}“ ist nicht vertrauenswürdig und führt im Modus für eingeschränkte Sprache zur Überprüfung des Parameterattributs „ValidateTrustedData“. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/MiniShellErrors.de.resx b/src/System.Management.Automation/resources/de/MiniShellErrors.de.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/de/MiniShellErrors.de.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/Modules.de.resx b/src/System.Management.Automation/resources/de/Modules.de.resx new file mode 100644 index 00000000000..2e46017ae62 --- /dev/null +++ b/src/System.Management.Automation/resources/de/Modules.de.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Das angegebene Modul „{0}“ wurde nicht geladen, da in keinem Modulverzeichnis eine gültige Moduldatei gefunden wurde. + + + Das angegebene Modul „{0}“ mit MaximumVersion „{1}“ wurde nicht geladen, da in keinem Modulverzeichnis eine gültige Moduldatei gefunden wurde. + + + Der angegebene Wert für MaximumVersion „{0}“ war falsch. Wenn Sie „*“ verwenden, unterstützt MaximumVersion nur ein „*“ und es muss immer am Ende von MaximumVersion stehen. + + + Das angegebene Modul „{0}“ mit MaximumVersion „{1}“ wurde nicht geladen, da in keinem Modulverzeichnis eine gültige Moduldatei gefunden wurde. + + + Das angegebene Modul „{0}“ mit MinimumVersion „{1}“ und MaximumVersion „{2}“ wurde nicht geladen, da in keinem Modulverzeichnis eine gültige Moduldatei gefunden wurde. + + + Die MinimumVersion „{0}“ darf nicht größer als MaximumVersion „{1}“ sein. + + + Die Assembly „{0}“ wurde nicht geladen, da keine Assembly mit diesem Namen gefunden wurde. Überprüfen Sie den Assemblynamen, und versuchen Sie es dann erneut. + + + Das zu verarbeitende Modul „{0}“, das im Feld „{1}“ des Modulmanifests „{2}“ aufgeführt ist, wurde nicht verarbeitet, da in keinem Modulverzeichnis ein gültiges Modul gefunden wurde. + + + Für das Modul „{0}“ wurde kein benutzerdefiniertes Objekt zurückgegeben, da der Parameter „-AsCustomObject“ nur mit Skriptmodulen verwendet werden kann. + + + Das Modulmanifest „{0}“ konnte nicht verarbeitet werden, da es keine gültige PowerShell-Modulmanifestdatei ist. Entfernen Sie die nicht zulässigen Elemente: {1} + + + Die Verarbeitung der Modulmanifestdatei „{0}“ hat kein gültiges Manifestobjekt ergeben. Aktualisieren Sie die Datei so, dass sie ein gültiges PowerShell-Modulmanifest enthält. Ein gültiges Manifest kann mit dem New-ModuleManifest-Cmdlet erstellt werden. + + + Das „{0}“-Modul kann nicht importiert werden, da das zugehörige Manifest ein oder mehrere ungültige Elemente enthält. Die gültigen Manifestelemente sind ({1}). Entfernen Sie die ungültigen Elemente ({2}), und versuchen Sie dann erneut, das Modul zu importieren. + + + Die Hashtabelle, die ein Modul beschreibt, enthält ein oder mehrere ungültige Elemente. Die gültigen Elemente sind ({0}). Entfernen Sie die ungültigen Elemente ({1}), und versuchen Sie es dann erneut. + + + Das Modul „{0}“ kann nicht geladen werden, da der Grenzwert für die Moduldarstellung überschritten wurde. Module können nur bis zu {1} Ebenen geschachtelt werden. Überprüfen Sie die Reihenfolge, in der Sie Module laden, und ändern Sie sie, um eine Überschreitung des Grenzwerts für die Schachtelung zu verhindern, und führen Sie dann Ihr Skript erneut aus. + + + Das Element „ModuleVersion“ ist im Modulmanifest nicht vorhanden. Dieses Element muss vorhanden sein und einer Versionsnummer im Format „n.n.n.n“ zugewiesen werden. Fügen Sie das fehlende Element der Datei „{0}“ hinzu. + + + Das Element „{0}“ ist in der Modulmanifestdatei „{2}“ nicht gültig: {1} + + + Die Version „{0}“ des Moduls „{1}“ erfüllt die erforderliche Mindestversion „{2}“ nicht. Überprüfen Sie, ob die Versionsnummer unterstützt wird, und laden Sie das Modul dann erneut. + + + Die PowerShell-Version auf diesem Computer ist „{0}“. Für die Ausführung des Moduls „{1}“ ist mindestens PowerShell-Version „{2}“ erforderlich. Vergewissern Sie sich, dass die erforderliche Mindestversion von PowerShell installiert ist, und versuchen Sie es dann erneut. + + + Das Modulmanifestelement „NestedModules“ kann nicht verwendet werden, wenn das Element „ModuleToProcess“ ein Binärmodul ist. Bearbeiten Sie die Modulmanifestdatei unter „{0}“, und versuchen Sie es dann erneut. + + + Das Element „{0}“ im Modulmanifest ist ungültig: {1}. Überprüfen Sie, ob in der Datei „{2}“ für dieses Feld ein gültiger Wert angegeben ist. + + + Der Pfad des Modulmanifests „{0}“ ist ungültig. Der Wert des Path-Arguments muss zu einer einzelnen Datei mit der Erweiterung „.psd1“ aufgelöst werden. Ändern Sie den Wert des Path-Arguments so, dass er auf eine gültige psd1-Datei verweist, und versuchen Sie es dann erneut. + + + Der Schlüssel ModuleVersion im Modulmanifest „{0}“ gibt die Modulversion „{1}“ an, die nicht mit dem Namen des Versionsordners unter „{2}“ übereinstimmt. Ändern Sie den Wert des Schlüssels „ModuleVersion“ so, dass er mit dem Namen des Versionsordners übereinstimmt. + + + Der angegebene NestedModule-Eintrag „{0}“ im Modulmanifest „{1}“ ist ungültig. Versuchen Sie es erneut, nachdem Sie diesen Eintrag mit gültigen Werten aktualisiert haben. + + + Der angegebene RequiredAssemblies-Eintrag „{0}“ im Modulmanifest „{1}“ ist ungültig. Versuchen Sie es erneut, nachdem Sie diesen Eintrag mit gültigen Werten aktualisiert haben. + + + Der angegebene NestedModule-Eintrag „{0}“ im Modulmanifest „{1}“ ist ungültig. Versuchen Sie es erneut, nachdem Sie diesen Eintrag mit gültigen Werten aktualisiert haben. + + + Der angegebene RequiredModules-Eintrag „{0}“ im Modulmanifest „{1}“ ist ungültig. Versuchen Sie es erneut, nachdem Sie diesen Eintrag mit gültigen Werten aktualisiert haben. + + + Der angegebene ModuleList-Eintrag „{0}“ im Modulmanifest „{1}“ ist ungültig. Versuchen Sie es erneut, nachdem Sie diesen Eintrag mit gültigen Werten aktualisiert haben. + + + Das Modulmanifest „{0}“ verwendet den Schlüssel CompatiblePSEditions, der nur in PowerShell Version 5.1 oder höher unterstützt wird. Aktualisieren Sie den Wert des Schlüssels PowerShellVersion auf „5.1“ oder höher, und versuchen Sie es dann erneut. + + + Der angegebene Wert „{0}“ für CompatiblePSEditions enthält doppelte PowerShell-Editionsnamen. Versuchen Sie es erneut, nachdem Sie die doppelten PowerShell-Editionsnamen entfernt haben. + + + Die in der Schlüsselzeile „ModuleVersion“ angegebene Version entspricht dem Namen des Versionsordners. + + + Der Versionsordner „{0}“ unter Modul „{1}“ wird übersprungen, da er keine gültige Modulmanifestdatei enthält. + + + Das Element „ModuleName“ ist in der Hashtabelle, die dieses Modul beschreibt, nicht vorhanden. + + + Die Elemente „ModuleVersion“, „MaximumVersion“ und „RequiredVersion“ sind in der Hashtabelle, die dieses Modul beschreibt, nicht vorhanden. Mindestens eines dieser drei Elemente muss vorhanden sein und einer Versionsnummer im Format „n.n.n.n“ zugewiesen werden. + + + Das erforderliche Modul „{1}“ wurde nicht geladen. Laden Sie das Modul, oder entfernen Sie es aus „RequiredModules“ in der Datei „{0}“. + + + Das erforderliche Modul „{1}“ mit der GUID „{2}“ ist nicht geladen. Laden Sie das Modul, oder entfernen Sie es aus „RequiredModules“ in der Datei „{0}“. + + + Das erforderliche Modul „{1}“ mit der Version „{2}“ ist nicht geladen. Laden Sie das Modul, oder entfernen Sie es aus „RequiredModules“ in der Datei „{0}“. + + + Das erforderliche Modul „{1}“ mit MaximumVersion „{2}“ ist nicht geladen. Laden Sie das Modul, oder entfernen Sie es aus „RequiredModules“ in der Datei „{0}“. + + + Das erforderliche Modul „{1}“ mit MinimumVersion „{2}“ und MaximumVersion „{3}“ wurde nicht geladen. Laden Sie das Modul, oder entfernen Sie es aus „RequiredModules“ in der Datei „{0}“. + + + Das Modul „{0}“ kann mit ModuleVersion „{1}“ nicht gefunden werden. + + + Das Modul „{0}“ kann mit RequiredVersion „{1}“ nicht gefunden werden. + + + Das Modul „{0}“ kann mit MaximumVersion „{1}“ nicht gefunden werden. + + + Das Modul „{0}“ mit ModuleVersion „{1}“ und MaximumVersion „{2}“ wurde nicht gefunden. + + + Das Modul „{0}“ kann nicht gefunden werden. + + + Es wurden keine Module entfernt. Stellen Sie sicher, dass die angegebenen zu entfernenden Module korrekt sind und dass diese Module im Runspace vorhanden sind. + + + Das Element „{0}“, das aus dem Modul „{1}“ importiert wurde, kann aus folgendem Grund nicht entfernt werden: {2} + + + Das Modul „{0}“ kann nicht entfernt werden, da es schreibgeschützt ist. Fügen Sie Ihrem Befehl den Parameter „Erzwingen“ hinzu, um schreibgeschützte Module zu entfernen. + + + Das Modul „{0}“ kann nicht entfernt werden, da es als „Konstante“ gekennzeichnet ist. Ein Modul kann nicht entfernt werden, wenn es als „Konstante“ gekennzeichnet ist. + + + Das Modul „{0}“ kann nicht entfernt werden, da es von „{1}“ benötigt wird. Fügen Sie dem Befehl den Parameter „Erzwingen“ hinzu, um das Modul zu entfernen. + + + Das Export-ModuleMember-Cmdlet kann nur innerhalb eines Moduls aufgerufen werden. + + + Die Erweiterung „{0}“ ist keine gültige Modulerweiterung. Die unterstützten Modulerweiterungen sind „.dll“, „.ps1“, „.psm1“, „.psd1“ und „.cdxml“. Korrigieren Sie die Erweiterung, und versuchen Sie dann erneut, die Datei „{1}“ hinzuzufügen. + + + Dieser Vorgang kann nicht für ein Binärmodul ausgeführt werden. Er kann nur für ein Skriptmodul ausgeführt werden. + + + Die Datei „{0}“ ist nicht zulässig, da sie nicht die Erweiterung „.ps1“ hat. + + + Unbekannt + + + (c) {0}. Alle Rechte vorbehalten. + + + Die importierte Funktion „{0}“ wird entfernt. + + + Das importierte Alias „{0}“ wird entfernt. + + + Die importierte Variable „{0}“ wird entfernt. + + + Das Modul wird aus dem Pfad „{0}“ geladen. + + + „{0}“ wird aus dem Pfad „{1}“ geladen. + + + Die Skriptdatei „{0}“ wird per Dot-Sourcing geladen. + + + Die Funktion „{0}“ wird importiert. + + + Das Cmdlet „{0}“ wird importiert. + + + Das Alias „{0}“ wird importiert. + + + Die Variable „{0}“ wird importiert. + + + Das Cmdlet „{0}“ wird exportiert. + + + Die Funktion „{0}“ wird exportiert. + + + Das Alias „{0}“ wird exportiert. + + + Die Variable „{0}“ wird exportiert. + + + Die Namen einiger importierter Befehle aus dem Modul „{0}“ enthalten nicht genehmigte Verben, wodurch sie möglicherweise schwerer auffindbar sind. Um die Befehle mit nicht genehmigten Verben zu finden, führen Sie den Befehl „Import-Module“ erneut mit dem Parameter „Ausführlich“ aus. Geben Sie Get-Verb ein, um eine Liste der genehmigten Verben anzuzeigen. + + + Der Befehl „{0}“ im Modul „{1}“ wurde importiert, aber da sein Name kein genehmigtes Verb enthält, ist er möglicherweise schwer zu finden. Geben Sie Get-Verb ein, um eine Liste der genehmigten Verben anzuzeigen. + + + Der Befehl „{0}“ im Modul „ {2}“ wurde importiert, aber da sein Name kein genehmigtes Verb enthält, ist er möglicherweise schwer zu finden. Die vorgeschlagenen Alternativverben sind „{1}“. + + + Einige importierte Befehlsnamen enthalten mindestens eines der folgenden eingeschränkten Zeichen: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Der Befehlsname „{0}“ aus dem Modul „{1}“ enthält mindestens eines der folgenden eingeschränkten Zeichen: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Die Modulmanifestdatei „{0}“ wird erstellt. + + + {0} (Pfad: „{1}“) + + + Die aktuelle Prozessorarchitektur ist: {0}. Das Modul „{1}“ erfordert die folgende Architektur: {2}. + + + Der Name des aktuellen PowerShell-Hosts ist: „{0}“. Das Modul „{1}“ erfordert den folgenden PowerShell-Host: „{2}“. + + + Der aktuelle PowerShell-Host ist: „{0}“ (Version {1}). Das Modul „{2}“ erfordert zum Ausführen mindestens die PowerShell-Hostversion „{3}“. + + + Modulmanifest für das Modul „{0}“ + + + Generiert von: {0} + + + Generiert am: {0} + + + Skriptmodul- oder Binärmoduldatei, die diesem Manifest zugeordnet ist. + + + Module, die als geschachtelte Module des in RootModule/ModuleToProcess angegebenen Moduls importiert werden sollen + + + ID zum eindeutigen Identifizieren dieses Moduls + + + Autor dieses Moduls + + + Unternehmen oder Hersteller dieses Moduls + + + Urheberrechtserklärung für dieses Modul + + + Versionsnummer dieses Moduls + + + Beschreibung der von diesem Modul bereitgestellten Funktionalität + + + Von diesem Modul erforderliche Mindestversion der PowerShell-Engine + + + Die für dieses Modul mindestens erforderliche Version der Common Language Runtime (CLR). {0} + + + Module, die vor dem Importieren dieses Moduls in die globale Umgebung importiert werden müssen + + + Skriptdateien (.ps1), die vor dem Importieren dieses Moduls in der Umgebung des Aufrufenden ausgeführt werden. + + + Typdateien (.ps1xml), die beim Importieren dieses Moduls geladen werden sollen + + + Formatdateien (.ps1xml), die beim Importieren dieses Moduls geladen werden sollen + + + Assemblys, die vor dem Importieren dieses Moduls geladen werden müssen + + + Liste aller mit diesem Modul paketierten Dateien + + + Private Daten, die an das in RootModule/ModuleToProcess angegebene Modul übergeben werden. Diese können auch eine PSData-Hashtabelle mit zusätzlichen Modulmetadaten enthalten, die von PowerShell verwendet werden. + + + Tags, die auf dieses Modul angewendet werden Diese helfen bei der Modulermittlung in Onlinekatalogen. + + + Eine URL zur Hauptwebsite für dieses Projekt. + + + Eine URL zur Lizenz für dieses Modul. + + + Eine URL zu einem Symbol, das dieses Modul darstellt. + + + ReleaseNotes dieses Moduls + + + Vorabversionszeichenfolge dieses Moduls + + + Kennzeichen, das angibt, ob das Modul für die Installation/Aktualisierung/Speicherung eine explizite Zustimmung erfordert. + + + Externe abhängige Module dieses Moduls + + + Ende der {0}-Hashtabelle + + + Der Parameterwert „PrivateData“ muss eine Hashtabelle sein, um das Modulmanifest mit den folgenden Parameterwerten zu erstellen: Tags, ProjectUri, LicenseUri, IconUri oder ReleaseNotes. Entfernen Sie entweder die Parameterwerte Tags, ProjectUri, LicenseUri, IconUri oder ReleaseNotes, oder schließen Sie den Inhalt von PrivateData in eine Hashtabelle ein. + + + PrivateData sollte als Hashtabelle definiert werden, aber dieses Modulmanifest definiert es als Objekt. Erwägen Sie, den Inhalt von PrivateData in eine Hashtabelle einzuschließen. So können Sie dem Modulmanifest die Eigenschaften Tags, ProjectUri, LicenseUri, IconUri und ReleaseNotes später hinzufügen. + + + Der angegebene Wert „{0}“ ist ungültig. Wiederholen Sie den Vorgang mit einem gültigen Wert. + + + Zu exportierende Funktionen aus diesem Modul. Für optimale Leistung verwenden Sie keine Platzhalter, und löschen Sie den Eintrag nicht. Verwenden Sie ein leeres Array, wenn keine Funktionen exportiert werden sollen. + + + Zu exportierende Aliase aus diesem Modul. Verwenden Sie für eine optimale Leistung keine Platzhalter, und löschen Sie den Eintrag nicht. Verwenden Sie ein leeres Array, wenn keine Aliase exportiert werden sollen. + + + Zu exportierende Cmdlets aus diesem Modul. Für optimale Leistung verwenden Sie keine Platzhalter, und löschen Sie den Eintrag nicht. Verwenden Sie ein leeres Array, wenn keine Cmdlets exportiert werden sollen. + + + Aus diesem Modul zu exportierende Variablen + + + Aus diesem Modul zu exportierende DSC-Ressourcen + + + Unterstützte PSEditions + + + Von diesem Modul benötigte Prozessorarchitektur (None, X86, Amd64) + + + Liste aller in diesem Modul enthaltenen Module + + + Mindestversion von Microsoft .NET Framework, die von diesem Modul benötigt wird. {0} + + + Name des PowerShell-Hosts, der von diesem Modul benötigt wird + + + Von diesem Modul erforderliche Mindestversion des PowerShell-Hosts + + + HelpInfo-URI dieses Moduls + + + Da das {0}-Modul das PSDrive in der aktuellen PowerShell-Sitzung bereitstellt, wurden keine Module entfernt. Ändern Sie den aktuellen PSDrive-Anbieter, und versuchen Sie dann erneut, Module zu entfernen. + + + Das Cmdlet „{0}“ wurde nicht importiert, da im aktuellen Bereich ein Element mit demselben Namen vorhanden ist. + + + Der Alias „{0}“ wurde nicht importiert, da im aktuellen Bereich ein Element mit demselben Namen vorhanden ist. + + + Die Funktion „{0}“ wurde nicht importiert, da im aktuellen Bereich ein Element mit demselben Namen vorhanden ist. + + + Die Variable „{0}“ wurde nicht importiert, da im aktuellen Bereich ein Element mit demselben Namen vorhanden ist. + + + Platzhalterzeichen sind in den Elementen „ModuleToProcess“, „RootModule“ oder „NestedModules“ im Modulmanifest „{0}“ nicht zulässig. + + + Das Modul „{0}“ ist ein Kernmodul für PowerShell. Fügen Sie Ihrem Befehl den Parameter „Erzwingen“ hinzu, um Kernmodule zu entfernen. + + + Das Modulmanifest darf nicht gleichzeitig die Elemente „ModuleToProcess“ und „RootModule“ enthalten. Entfernen Sie eines dieser Elemente in der Modulmanifestdatei unter „{0}“, und versuchen Sie es dann erneut. + + + Das Modulmanifestelement „ModuleToProcess“ ist veraltet. Verwenden Sie stattdessen das Element „RootModule“. + + + Standardpräfix für aus diesem Modul exportierte Befehle. Überschreiben Sie das Standardpräfix mit dem Import-Module-Prefix. + + + Die Parameter „Global“ und „Bereich“ können nicht zusammen angegeben werden. Entfernen Sie einen dieser Parameter, und führen Sie den Befehl dann erneut aus. + + + Das erforderliche Modul „{0}“ ist nicht geladen. Das Modul „{0}“ enthält im Modulmanifest „{1}“ ein requiredModule „{2}“, das auf eine zyklische Abhängigkeit verweist. + + + Das erforderliche Modul „{0}“ wurde nicht geladen, da in keinem Modulverzeichnis eine gültige Moduldatei gefunden wurde. + + + Einige Befehle aus dem Modul „{0}“ können nicht über eine CimSession importiert werden. Um alle Befehle zu erhalten, überprüfen Sie, ob die Remoteverwaltung von PowerShell auf dem Remoteserver aktiviert ist, und fügen Sie dann den Parameter „PSSession“ dem Import-Module-Cmdlet hinzu. + + + Das Modul „{0}“ wird in Windows PowerShell mit einer {1}-Remotesitzung geladen. Beachten Sie, dass alle Eingaben und Ausgaben von Befehlen aus diesem Modul deserialisierte Objekte sind. Wenn Sie dieses Modul in PowerShell laden möchten, verwenden Sie die Syntax „Import-Module -SkipEditionCheck“. + + + Windows PowerShell-Version {0} erkannt. Zum Laden von Modulen mit der Windows PowerShell-Kompatibilitätsfunktion ist Windows PowerShell 5.1 erforderlich. Installieren Sie Windows Management Framework (WMF) 5.1 von https://aka.ms/WMF5Download, um diese Funktion zu aktivieren. + + + Das Modul „{0}“ ist vom Laden über die Windows PowerShell-Kompatibilitätsfunktion blockiert. Ursache ist die Einstellung „WindowsPowerShellCompatibilityModuleDenyList“ in der PowerShell-Konfigurationsdatei. + + + Das Modul {0} kann nicht über eine CimSession importiert werden. Verwenden Sie den Parameter „PSSession“ des Import-Module-Cmdlets. + + + Der Wert von {0} für die Prozessorarchitektur wird nicht unterstützt. Führen Sie den New-ModuleManifest-Befehl erneut aus, und geben Sie einen der folgenden unterstützten Enumerationswerte für die Prozessorarchitektur an: None, MSIL, X86, Amd64, Arm + + + Beim Ausführen des Get-Module-Cmdlets auf einem Remotecomputer können nur verfügbare Module aufgelistet werden. Fügen Sie dem Befehl den Parameter „ListAvailable“ hinzu, und versuchen Sie es dann erneut. + + + Das Modul „{0}“ wurde nicht importiert, da das Snap-In „{0}“ bereits importiert wurde. + + + Platzhalterzeichen sind im Element „RequiredAssemblies“ im Modulmanifest „{0}“ nicht zulässig. + + + Der Wert des Schlüssels {0} in {1} ist {2}, und das Modul enthält geschachtelte Module. Wenn eine CDXML-Datei das Stammmodul ist, schlägt der Import-Module-Befehl fehl, da die Befehle in geschachtelten Modulen nicht exportiert werden können. Verschieben Sie die CDXML-Datei in den Schlüssel „NestedModules“, und versuchen Sie den Befehl erneut. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Fehler vom Remotebefehl: {0}: {{0}} + + + Fehler beim Generieren von Proxys für das Remotemodul „{0}“. {{0}} + + + Fehler beim Verarbeiten des Remotemoduls {0}. {1} + + + Fehler beim Empfangen von Moduldaten aus der Remote-CimSession. {0} + + + Das erforderliche Modul „{0}“ mit der GUID „{1}“ und der Version „{2}“ wurde nicht geladen, da in keinem Modulverzeichnis eine gültige Moduldatei gefunden wurde. + + + Auf dem CIM-Server wurde kein CIM-Anbieter für die Modulermittlung gefunden. {0} + {0} is a placeholder for a more detailed error message + + + Die Microsoft .NET Framework-Version {0} kann nicht überprüft werden, da sie nicht in der Liste der zulässigen Versionen enthalten ist. + + + {0} wird analysiert. + {0} should not be localized, is used to contain a file path. + + + Die Module werden für die erste Verwendung vorbereitet. + + + Es wird nach verfügbaren Modulen gesucht. + + + Die UNC-Freigabe „{0}“ wird durchsucht. + {0} should not be localized, is used to contain a file path. + + + Das Ausführen des Get-Module-Cmdlets für einen Remotecomputer ist nur für Modulnamen möglich, die keinen Pfad enthalten. Der Name-Parameter enthält dieses Element „{0}“, das in einen Pfad aufgelöst wird. Aktualisieren Sie den Name-Parameter so, dass keine Pfadelemente enthalten sind, und versuchen Sie es dann erneut. + + + Das Ausführen des Get-Module-Cmdlets ohne den ListAvailable-Parameter wird für Modulnamen, die einen Pfad enthalten, nicht unterstützt. Der Name-Parameter enthält dieses Element „{0}“, das in einen Pfad aufgelöst wird. Aktualisieren Sie den Name-Parameter so, dass keine Pfadelemente enthalten sind, und versuchen Sie es dann erneut. + + + Das angegebene Modul „{0}“ wurde nicht gefunden. Aktualisieren Sie den Name-Parameter, sodass er auf einen gültigen Pfad verweist, und versuchen Sie es dann erneut. + + + Die Eigenschaft „RepositorySourceLocation“ für das Modul „{0}“ wird aufgefüllt. + + + Das zu verarbeitende Modul „{0}“, das im Feld „{1}“ des Modulmanifests „{2}“ aufgeführt ist, wurde nicht verarbeitet. {3} + + + Diese Voraussetzung gilt nur für die PowerShell Desktop-Edition. + + + Das Modul „{0}“ unterstützt die aktuelle PowerShell-Edition „{1}“ nicht. Die unterstützten Editionen sind „{2}“. Verwenden Sie „Import-Module -SkipEditionCheck“, um die Kompatibilität dieses Moduls zu ignorieren. + + + Das Modul „{0}“ unterstützt die PowerShell-Edition „{1}“ und kann nicht implizit mit der Windows Compatibility-Funktion geladen werden, da es in der Einstellungsdatei deaktiviert ist. Verwenden Sie „Import-Module -UseWindowsPowerShell“, um dieses Modul mit Windows PowerShell zu laden, oder „Import-Module -SkipEditionCheck“, um zu versuchen, das Modul mit der aktuellen PowerShell zu laden. + + + Für eine experimentelle Funktion, die im Modulmanifest deklariert ist, sollte ein nicht leerer Zeichenfolgenwert angegeben werden. + + + Es wurden ein oder mehrere ungültige Namen für experimentelle Funktionen gefunden: {0}. Ein Name für eine experimentelle Funktion eines Moduls sollte dieser Konvention folgen: „ModuleName.FeatureName“. + + + Der Switch-Parameter „-SkipEditionCheck“ kann nicht ohne den Switch-Parameter „-ListAvailable“ verwendet werden. + + + Das Importieren von *.ps1-Dateien als Module ist im ConstrainedLanguage-Modus nicht zulässig. + + + Beim Laden des Skriptmoduls „{0}“ ist ein Fehler aufgetreten, da es einen anderen Sprachmodus als das Modulmanifest hat. Der Sprachmodus des Manifests ist „{1}“, und der Sprachmodus des Moduls ist „{2}“. Stellen Sie sicher, dass alle Moduldateien signiert sind oder anderweitig Teil der Konfiguration der Zulassungsliste der App sind. + + + Dieses Modul verwendet den dot-source-Operator beim Exportieren von Funktionen mit Platzhalterzeichen, und dies ist nicht zulässig, wenn für das System die Anwendungsüberprüfung erzwungen wird. + + + Elemente eines Moduls können nicht exportiert werden, wenn das Modul einen anderen Sprachmodus als die ausführende Sitzung aufweist. + + + Es kann kein neues Modul erstellt werden, während sich die Sitzung im ConstrainedLanguage-Modus befindet. + + + Das integrierte Modul „{0}“, das mit der „Core“-Edition kompatibel ist, wurde nicht gefunden. Stellen Sie sicher, dass die integrierten PowerShell-Module verfügbar sind. Sie werden in der Regel mit dem PowerShell-Paket unter dem Modulpfad $PSHOME bereitgestellt und sind erforderlich, damit PowerShell ordnungsgemäß funktioniert. + + + Export-ModuleMember-Cmdlet + + + Das Exportieren von Modulelementen schlägt im Eingeschränkten Sprachmodus fehl, da das Modul „{0}“ einen Sprachmodus „{1}“ aufweist, der sich von der aktuellen Sitzung „{2}“ unterscheidet. + + + Export impliziter Modulfunktionen + + + Der implizite Funktionsexport für das Modul „{0}“ wird verweigert, da es vertrauenswürdig ist (wird im Uneingeschränkten Sprachmodus ausgeführt), die Sitzung jedoch nicht vertrauenswürdig ist (wird im Eingeschränkten Sprachmodus ausgeführt). Es hat sich bewährt, Modulfunktionen immer einzeln unter dem vollständigen Namen zu exportieren. + + + Die Skriptdatei wird als Modul importiert. + + + Das Importieren der Skriptdatei „{0}“ als Modul ist im ConstrainedLanguage-Modus nicht zulässig. + + + Modul enthält dot-source-Operator + + + Der Import des Moduls „{0}“ schlägt im Eingeschränkten Sprachmodus fehl, da Funktionen mit Platzhalterzeichen exportiert werden und gleichzeitig der dot-source-Operator verwendet wird. + + + "Modulexportfunktionen + + + Modul „{0}“ exportiert Funktionen mit Namensplatzhaltern. Alle Funktionsnamen aus geschachtelten Modulen werden im Eingeschränkten Sprachmodus entfernt. + + + "New-Module-Cmdlet + + + Ein neues Modul aus einer nicht vertrauenswürdigen Eingeschränkten Sprachsitzung wird daran gehindert, den FullLanguage-Skriptblock bereitzustellen. + + + "Nicht übereinstimmende Modulsprachmodi + + + Ein abhängiges Modul wird geladen, das einen anderen Sprachmodus als das übergeordnete Modul verwendet. Dies ist im Eingeschränkten Sprachmodus nicht zulässig. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/MshHostRawUserInterfaceStrings.de.resx b/src/System.Management.Automation/resources/de/MshHostRawUserInterfaceStrings.de.resx new file mode 100644 index 00000000000..ec870c37e77 --- /dev/null +++ b/src/System.Management.Automation/resources/de/MshHostRawUserInterfaceStrings.de.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}“ darf nicht größer oder gleich „{1}“ sein. + + + „{0}“ muss eine positive Zahl sein. + + + Alle Zeichenfolgen sind NULL oder leer. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/MshSignature.de.resx b/src/System.Management.Automation/resources/de/MshSignature.de.resx new file mode 100644 index 00000000000..d692b2667e2 --- /dev/null +++ b/src/System.Management.Automation/resources/de/MshSignature.de.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 + + + Signatur überprüft. + + + Die Datei „{0}“ ist nicht digital signiert. Dieses Skript kann nicht auf dem aktuellen System ausgeführt werden. Weitere Informationen zum Ausführen von Skripts und zum Festlegen der Ausführungsrichtlinie finden Sie in „about_Execution_Policies“ unter https://go.microsoft.com/fwlink/?LinkID=135170 + + + Der Inhalt der Datei „{0}“ könnte von einer nicht autorisierten Person oder einem nicht autorisierten Prozess geändert worden sein, da der Hash der Datei nicht mit dem in der digitalen Signatur gespeicherten Hash übereinstimmt. Das Skript kann auf dem angegebenen System nicht ausgeführt werden. Führen Sie „Get-Help about_Signing“ aus, um weitere Informationen zu erhalten. + + + Die Datei „{0}“ ist signiert, aber die signierende Person gilt auf diesem System nicht als vertrauenswürdig. + + + Die Datei kann nicht signiert werden, da das System keine Signiervorgänge für {0}-Dateien unterstützt. + + + Die Datei kann nicht signiert werden, da das System keine Signiervorgänge für Dateien ohne Dateinamenerweiterung unterstützt. + + + Die Signatur kann nicht überprüft werden, da sie mit dem aktuellen System nicht kompatibel ist. + + + Die Signatur kann nicht überprüft werden, da sie mit dem aktuellen System nicht kompatibel ist. Der Hashalgorithmus ist ungültig. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/MshSnapInCmdletResources.de.resx b/src/System.Management.Automation/resources/de/MshSnapInCmdletResources.de.resx new file mode 100644 index 00000000000..132c8fe3245 --- /dev/null +++ b/src/System.Management.Automation/resources/de/MshSnapInCmdletResources.de.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 + + + Der Vorgang kann nicht durchgeführt werden. Das angegebene cmdlet wird in einer benutzerdefinierten Shell nicht unterstützt. + + + Es wurden keine PowerShell-Snap-Ins gefunden, die mit dem Muster „{0}“ übereinstimmen. Überprüfen Sie das Muster, und wiederholen Sie dann den Befehl. + + + Das Format des angegebenen Snap-In-Namens war ungültig. PowerShell-Snap-In-Namen dürfen nur alphanumerische Zeichen, Bindestriche, Unterstriche und Punkte enthalten. Korrigieren Sie den Namen, und wiederholen Sie anschließend den Vorgang. + + + Das PowerShell-Snap-In {0} kann nicht hinzugefügt werden, da es sich um ein PowerShell-Systemmodul handelt. Verwenden Sie Import-Module, um das Modul zu laden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/MshSnapinInfo.de.resx b/src/System.Management.Automation/resources/de/MshSnapinInfo.de.resx new file mode 100644 index 00000000000..f9e4487edd6 --- /dev/null +++ b/src/System.Management.Automation/resources/de/MshSnapinInfo.de.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 + + + Auf die PowerShell-Registrierungsinformationen kann nicht zugegriffen werden. + + + Auf die Registrierungsinformationen der PowerShell-Engine kann nicht zugegriffen werden. + + + Zugriff auf PublicKeyToken-Informationen nicht möglich. + + + Die PowerShell-Version {0} ist auf diesem Computer nicht verfügbar. + + + Das PowerShell-Snap-In „{0}“ ist auf diesem Computer nicht installiert. + + + Der obligatorische Wert {0} ist für den Registrierungsschlüssel {1} nicht angegeben. + + + Der obligatorische Wert {0} weist nicht das richtige Format für den Registrierungsschlüssel {1} auf. Das erwartete Format ist „string“. + + + Der obligatorische Wert {0} weist nicht das richtige Format für den Registrierungsschlüssel {1} auf. Das erwartete Format ist „multistring“. + + + Erforderliche Informationen können in der Registrierung oder fehlenden Schlüsseldateien nicht gefunden werden. Einige cmdlets können nicht geladen werden. + + + Für die PowerShell-Version {0} wurden keine Snap-Ins registriert. + + + Die Zeichenfolgenressource kann nicht abgerufen werden, da der Reader verworfen wurde. + + + Der Versionswert {0} wurde nicht angegeben oder ist für den Registrierungsschlüssel {1} falsch. + + + Für den PowerShell-Typ {0} wurde kein [PSVersion]-Attribut gefunden. Fügen Sie dem Typ mithilfe von [PSVersion(PowerShell SnapinBase.PSEngineVersion)] ein PSVersion-Attribut hinzu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/NativeCP.de.resx b/src/System.Management.Automation/resources/de/NativeCP.de.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/de/NativeCP.de.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PSCommandStrings.de.resx b/src/System.Management.Automation/resources/de/PSCommandStrings.de.resx new file mode 100644 index 00000000000..826a5aa405e --- /dev/null +++ b/src/System.Management.Automation/resources/de/PSCommandStrings.de.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 + + + Zum Hinzufügen eines Parameters ist ein Befehl erforderlich. Vor dem Hinzufügen eines Parameters muss „{0}“ ein Befehl hinzugefügt werden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PSConfigurationStrings.de.resx b/src/System.Management.Automation/resources/de/PSConfigurationStrings.de.resx new file mode 100644 index 00000000000..73dd8f23625 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PSConfigurationStrings.de.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 + + + PowerShell funktioniert aufgrund eines Sicherheitsproblems nicht mehr: Die Konfigurationsdatei kann nicht gelesen werden: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PSDataBufferStrings.de.resx b/src/System.Management.Automation/resources/de/PSDataBufferStrings.de.resx new file mode 100644 index 00000000000..095f9db6b28 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PSDataBufferStrings.de.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 + + + Der angegebene Index ist kleiner als null oder größer als die Anzahl der Elemente im Puffer. Der Index muss im Bereich {0}–{1} liegen. + + + Ein NULL-Verweis kann nicht in einen Werttyp konvertiert werden. + + + Der Wert kann nicht vom Typ {0} in den Typ {1} konvertiert werden. + + + Objekte können nicht zu einem geschlossenen Puffer hinzugefügt werden. Stellen Sie sicher, dass der Puffer geöffnet ist, damit die Vorgänge „Hinzufügen“ und „Einfügen“ erfolgreich ausgeführt werden können. + + + Die SerializeInput-Eigenschaft kann nur für den PSObject-Typ von PSDataCollection festgelegt werden. Legen Sie die SerializeInput-Eigenschaft auf FALSE fest, oder ändern Sie den Auflistungstyp in ein PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PSListModifierStrings.de.resx b/src/System.Management.Automation/resources/de/PSListModifierStrings.de.resx new file mode 100644 index 00000000000..48386e259b2 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PSListModifierStrings.de.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 + + + Der folgende unbekannte Listenmodifizierer wurde erkannt: „{0}“. Gültige Listenmodifizierer sind „Hinzufügen“, „Entfernen“ und „Ersetzen“. + + + Das Update kann nicht angewendet werden, da das Objekt kein unterstützter Auflistungstyp ist. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PSStyleStrings.de.resx b/src/System.Management.Automation/resources/de/PSStyleStrings.de.resx new file mode 100644 index 00000000000..80719f4a954 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PSStyleStrings.de.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die angegebene Zeichenfolge enthält druckbaren Inhalt, obwohl sie nur ANSI-Escape-Sequenzen enthalten sollte: {0} + + + „MaxWidth“ für das Fortschrittsrendering muss mindestens 18 betragen, damit es korrekt gerendert wird. + + + Beim Hinzufügen oder Entfernen von Erweiterungen muss die Erweiterung mit einem Punkt beginnen. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ParameterBinderStrings.de.resx b/src/System.Management.Automation/resources/de/ParameterBinderStrings.de.resx new file mode 100644 index 00000000000..95a3a323953 --- /dev/null +++ b/src/System.Management.Automation/resources/de/ParameterBinderStrings.de.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Es wurde kein Parameter gefunden, der dem Parameternamen „{1}“ entspricht. + + + Es wurde kein Positionsparameter gefunden, der das Argument „{1}“ akzeptiert. + + + Für den Parameter „{1}“ fehlt ein Argument. Geben Sie einen Parameter vom Typ „{2}“ an, und versuchen Sie es erneut. + + + Der Parameter kann nicht verarbeitet werden, da der Parametername „{1}“ mehrdeutig ist. Mögliche Übereinstimmungen sind:{6}. + + + „{6}“ kann nicht in den Typ „{2}“ konvertiert werden, der für den Parameter „{1}“ erforderlich ist. {7} + + + Der Parameter „{1}“ kann nicht gebunden werden. {6} + + + Positionsparameter „{1}“ können nicht gebunden werden. + + + Positionsparameter können nicht gebunden werden, da keine Namen angegeben wurden. + + + Der Parametersatz kann mit den angegebenen benannten Parametern nicht aufgelöst werden. Ein oder mehrere angegebene Parameter können nicht zusammen verwendet werden, oder es wurde eine zu geringe Anzahl von Parametern angegeben. + + + Der Befehl kann nicht verarbeitet werden, da ein oder mehrere erforderliche Parameter fehlen:{1}. + + + Der Parameter „{1}“ kann nicht im Parametersatz „{6}“ angegeben werden. + + + Der Parameter kann nicht gebunden werden, da der Parameter „{1}“ mehrmals angegeben wurde. Verwenden Sie die Arraysyntax, um Parametern, die mehrere Werte akzeptieren, mehrere Werte zu übergeben. Beispiel: „-parameter value1,value2,value3“. + + + Der Parameter „{1}“ kann nicht ausgewertet werden, da sein Argument als Skriptblock angegeben wurde und keine Eingabe vorhanden ist. Ein Skriptblock kann nicht ohne Eingabe ausgewertet werden. + + + Die Eingabe für den Skriptblock des Parameters „{1}“ ist fehlgeschlagen. {6} + + + Der Parameter „{1}“ kann nicht ausgewertet werden, da für seine Argumenteingabe keine Ausgabe erzeugt wurde. + + + Das Eingabeobjekt kann keinem Parameter für den Befehl zugeordnet werden, weil der Befehl keine Pipelineeingabe akzeptiert oder die Eingabe und ihre Eigenschaften mit keinem der Parameter übereinstimmen, die Pipelineeingabe akzeptieren. + + + Das Eingabeobjekt kann nicht gebunden werden, da die zum Binden aller erforderlichen Parameter nötigen Informationen fehlen: {6} + + + Die Pipeline kann nicht verarbeitet werden, da der Standardwert des Parameters „{1}“ nicht abgerufen werden kann. {6} + + + Die dynamischen Parameter für das Cmdlet können nicht abgerufen werden. {6} + + + Geben Sie Werte für die folgenden Parameter an: + + + Cmdlet „{0}“ an der Position in der Befehlspipeline „{1}“ + + + Die Argumenttransformation für den Parameter „{1}“ kann nicht verarbeitet werden. {6} + + + {6} + + + Das Argument für den Parameter „{1}“ kann nicht überprüft werden. {6} + + + Der Parameter „{1}“ kann nicht an das Ziel gebunden werden. {6} + + + Das Argument kann nicht an den Parameter „{1}“ gebunden werden, da es NULL ist. + + + Das Argument kann nicht an den Parameter „{1}“ gebunden werden, da es eine leere Zeichenfolge ist. + + + Das Argument kann nicht an den Parameter „{1}“ gebunden werden, da es eine leere Sammlung ist. + + + Das Argument kann nicht an den Parameter „{1}“ gebunden werden, da es ein leeres Array ist. + + + Der Befehl kann nicht verarbeitet werden. Der Parameter „{0}“ ist mehrfach definiert. + + + Das Cmdlet „{0}“ kann nicht gebunden werden, da der Parameter „{1}“ vom Typ „{2}“ ist und die Add()-Methode nicht ermittelt werden kann oder mehrere Add()-Methoden vorhanden sind. {6} + + + Das Cmdlet „{0}“ kann nicht gebunden werden, da der zur Laufzeit definierte Parameter „{1}“ dem RuntimeDefinedParameterDictionary mit dem Schlüssel „{6}“ hinzugefügt wurde. Der Schlüssel muss mit RuntimeDefinedParameter.Name übereinstimmen. + + + Das Argument kann nicht an den Parameter „{1}“ gebunden werden, da die PSTypeNames des Arguments nicht mit dem für den Parameter erforderlichen PSTypeName übereinstimmen: {6}. + + + In $PSDefaultParameterValues sind mehrere unterschiedliche Standardwerte für den Parameter definiert, der dem folgenden Namen oder Alias entspricht: {0}. Diese Standardwerte wurden ignoriert. + + + Der folgende Name oder Alias, der in $PSDefaultParameterValues für dieses Cmdlet definiert ist, wird auf mehrere Parameter aufgelöst: {0}. Der Standardwert wurde ignoriert. + + + {6} Dieser Fehler kann durch die Anwendung der Standardparameterbindung verursacht worden sein. Sie können die Standardparameterbindung in $PSDefaultParameterValues deaktivieren, indem Sie $PSDefaultParameterValues["Disabled"] auf $true setzen, und es dann erneut versuchen. Die folgenden Standardparameter wurden zum Zeitpunkt des Fehlers erfolgreich für dieses Cmdlet gebunden:{7} + + + {6} Dieser Fehler kann durch die Anwendung der Standardparameterbindung verursacht worden sein. Sie können die Standardparameterbindung in $PSDefaultParameterValues deaktivieren, indem Sie $PSDefaultParameterValues["Disabled"] auf $true setzen, und es dann erneut versuchen. Der folgende Standardparameter wurde zum Zeitpunkt des Fehlers erfolgreich für dieses Cmdlet gebunden:{7} + + + Die Bindung des Standardwerts „{0}“ an den Parameter „{1}“ ist fehlgeschlagen: {2} + + + Der Schlüssel „{0}“ hat kein gültiges Format. Informationen zum richtigen Format finden Sie unter about_Parameters_Default_Values unter https://go.microsoft.com/fwlink/?LinkId=228266. + + + Die Schlüssel „{0}“ haben kein gültiges Format. Informationen zum richtigen Format finden Sie unter about_Parameters_Default_Values unter https://go.microsoft.com/fwlink/?LinkId=228266. + + + Der Parameter „{0}“ ist veraltet. {1} + + + Der Schlüssel „{0}“ vom Typ „{1}“ ist kein Zeichenfolgenwert. DefaultParameterDictionary akzeptiert nur Schlüssel mit Zeichenfolgenwert. + + + Der Schlüssel „{0}“ wurde dem Wörterbuch bereits hinzugefügt. + + + Methoden- oder Eigenschaftsaufruf nicht zulässig + + + Der Aufruf der Methode oder Eigenschaft „{0}“ für Typ „{1}“ ist im Constrained Language-Modus für nicht vertrauenswürdige Skripts nicht zulässig. + + + Typerstellung nicht zulässig + + + Die Erstellung des Typs „{0}“ ist während der Parameterbindung im eingeschränkten Sprachmodus für nicht vertrauenswürdige Skripts nicht zulässig. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ParserStrings.de.resx b/src/System.Management.Automation/resources/de/ParserStrings.de.resx new file mode 100644 index 00000000000..4d1ed32618c --- /dev/null +++ b/src/System.Management.Automation/resources/de/ParserStrings.de.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Assembly "{0}" kann nicht geladen werden. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PathUtilsStrings.de.resx b/src/System.Management.Automation/resources/de/PathUtilsStrings.de.resx new file mode 100644 index 00000000000..a6266a5d203 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PathUtilsStrings.de.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die Codierung „UTF-7“ ist veraltet. Verwenden Sie UTF-8. + + + Die Datei {0} ist bereits vorhanden und {1} wurde angegeben. + + + Die Datei kann nicht geöffnet werden, da der aktuelle Anbieter ({0}) keine Datei öffnen kann. + + + Der Vorgang kann nicht ausgeführt werden, da der Pfad in mehrere Dateien aufgelöst wurde. Dieser Befehl kann nicht für mehrere Dateien verwendet werden. + + + Der Vorgang kann nicht ausgeführt werden, da der Wildcardpfad „{0}“ nicht in eine Datei aufgelöst wurde. + + + Unbekannte Codierung {0}; gültige Werte sind {1}. + + + Das Verzeichnis „{0}“ ist bereits vorhanden. Verwenden Sie den -Force-Parameter, wenn Sie das Verzeichnis und die Dateien innerhalb des Verzeichnisses überschreiben möchten. + + + Der Benutzermodulpfad ist nicht vorhanden, weshalb kein Modulordner für den angegebenen Modulnamen „{0}“ erstellt werden kann. + + + Das Modul {0} kann aufgrund der folgenden Ursachen nicht erstellt werden: {1}. Verwenden Sie ein anderes Argument für den Parameter „-OutputModule“ und wiederholen Sie den Vorgang. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Das Modul kann nicht geladen werden, da es mit einer inkompatiblen Version des {0} cmdlets generiert wurde. Generieren Sie das Modul mit dem {0} cmdlet aus der aktuellen Sitzung, und versuchen Sie erneut, das Modul zu laden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PipelineStrings.de.resx b/src/System.Management.Automation/resources/de/PipelineStrings.de.resx new file mode 100644 index 00000000000..916b0300f29 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PipelineStrings.de.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die cmdlet-Instanz kann nicht verarbeitet werden, da die cmdlet-Instanz von einer anderen Pipeline verwendet wird. Wenden Sie sich an den Microsoft-Kundendienst. + + + Der Vorgang kann nicht ausgeführt werden, da die Pipeline gestartet wurde. Beenden Sie die Pipeline, und wiederholen Sie den Vorgang. + + + Die Ausführung des cmdlets kann nicht fortgesetzt werden, da die Ausführung von cmdlets durch die Stopp-Richtlinie verhindert wurde. + + + Die Pipeline kann nicht ausgeführt werden, da das erste cmdlet in der Pipeline versucht, Eingaben aus den Ergebnissen eines vorherigen cmdlets zu lesen. Ändern Sie entweder das erste cmdlet, entfernen Sie das erste cmdlet, oder fügen Sie der Pipeline das cmdlet hinzu, dessen Ausgabe für das erste cmdlet erforderlich ist, und versuchen Sie dann erneut, die Pipeline auszuführen. + + + Die cmdlet-Nummer kann nicht verarbeitet werden. Die ReadFromCommand-Funktion muss die ID eines cmdlets angeben, das der Pipeline bereits hinzugefügt wurde. Wenden Sie sich an den Microsoft-Kundendienst. + + + Die Ausgabe der Funktionen ReadFromCommand und ReadErrorQueue kann nicht gelesen werden, da diese Ausgabe bereits von einem anderen cmdlet gelesen wird. Wenden Sie sich an den Microsoft-Kundendienst. + + + Die Pipeline kann nicht ausgeführt werden, da keine Befehle vorhanden sind. Fügen Sie der Pipeline mindestens einen Befehl hinzu, und führen Sie ihn dann erneut aus. + + + Der Pipelinevorgang kann nicht abgeschlossen werden, da er noch nicht gestartet wurde. Sie müssen die Begin()-Methode aufrufen, bevor Sie End() für eine schrittweise Pipeline aufrufen. + + + Die WriteObject- und WriteError-Methoden können nicht von außerhalb der Außerkraftsetzungen der BeginProcessing-, ProcessRecord- und EndProcessing-Methoden aufgerufen werden, und sie können nur innerhalb desselben Threads aufgerufen werden. Überprüfen Sie, ob das cmdlet diese Anrufe ordnungsgemäß durchführt, oder wenden Sie sich an den Microsoft-Kundendienst. + + + Ein cmdlet hat nach dem Aufrufen von ThrowTerminatingError eine Ausnahme ausgelöst. +Die erste Ausnahme war „{0}“ mit Stapelüberwachung „{1}“. +Die zweite Ausnahme war „{2}“ mit Stapelüberwachung „{3}“. + + + Die WriteObject- und WriteError-Methoden können nicht aufgerufen werden, nachdem die Pipeline geschlossen wurde. Wenden Sie sich an den Microsoft-Kundendienst. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Fehler beim Erstellen der Pipeline. + + + Diese Pipeline unterstützt keine Semantik zum Trennen von Verbindungen. + + + Diese Pipeline kann nicht verbunden werden, da sie sich nicht im getrennten Zustand befindet. + + + Dem Runspaceobjekt ist ein NULL-Remotebefehl zugeordnet. Ein getrenntes RemotePipeline-Objekt kann nicht erstellt werden, da kein Remotebefehl angegeben ist. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/PowerShellStrings.de.resx b/src/System.Management.Automation/resources/de/PowerShellStrings.de.resx new file mode 100644 index 00000000000..3cf93d82ec6 --- /dev/null +++ b/src/System.Management.Automation/resources/de/PowerShellStrings.de.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 + + + Der Zustand der aktuellen PowerShell-Instanz ist für diesen Vorgang ungültig. + + + Der Vorgang kann nicht ausgeführt werden, da bereits ein Befehl gestartet wurde. Warten Sie, bis der Befehl abgeschlossen ist, oder beenden Sie ihn, und wiederholen Sie dann den Vorgang. + + + Es wurden keine Befehle angegeben. + + + Die PowerShell-Instanz befindet sich nicht im richtigen Zustand zum Erstellen einer geschachtelten PowerShell-Instanz. Geschachtelte PowerShell-Instanzen dürfen nur in einer ausgeführten PowerShell-Instanz erstellt werden. + + + Der Vorgang kann nicht ausgeführt werden, da sich der Runspace nicht im Zustand „{0}“ befindet. Der aktuelle Zustand des Runspaces ist „{1}“. + + + Geschachtelte PowerShell-Instanzen können nicht asynchron aufgerufen werden. Verwenden Sie die Invoke-Methode. + + + Das {0}-Objekt wurde nicht durch Aufrufen von „{1}“ für diese PowerShell-Instanz erstellt. + + + Wenn der Runspace für die Wiederverwendung eines Threads festgelegt ist, muss der Apartmentzustand in den Aufrufeinstellungen mit dem Runspace übereinstimmen. + + + Wenn der Runspace für die Verwendung des aktuellen Threads festgelegt ist, muss der Apartmentzustand in den Aufrufeinstellungen mit dem aktuellen Thread übereinstimmen. + + + Zum Hinzufügen eines Parameters ist ein Befehl erforderlich. Vor dem Hinzufügen eines Parameters muss der PowerShell-Instanz ein Befehl hinzugefügt werden. + + + Die Schlüssel im Wörterbuch müssen Zeichenfolgen sein. + + + Es ist kein Runspace zum Ausführen von Befehlen in diesem Thread verfügbar. Sie können einen in der DefaultRunspace-Eigenschaft des Typs „System.Management.Automation.Runspaces.Runspace“ angeben. Der Befehl, den Sie aufrufen wollten, war: {0} + + + Für dieses PowerShell-Objekt kann keine Verbindung hergestellt werden, da es keinem Remoterunspace oder Runspacepool zugeordnet ist. + + + Der ausgeführte Befehl wurde getrennt, wird aber weiterhin auf dem Remoteserver ausgeführt. Stellen Sie die Verbindung wieder her, um den Status des Befehlsvorgangs und die Ausgabedaten abzurufen. + + + Der Vorgang kann nicht ausgeführt werden, da sich die aktuelle PowerShell-Sitzung im Zustand „Getrennt“ befindet. Stellen Sie die Verbindung mit dieser PowerShell-Sitzung her, und warten Sie dann, bis der Befehl abgeschlossen ist, oder beenden Sie den Befehl. + + + Der Vorgang kann nicht ausgeführt werden, da sich die aktuelle PowerShell-Sitzung im Zustand „Getrennt“ befindet. Stellen Sie die Verbindung mit dieser PowerShell-Sitzung her, und wiederholen Sie dann den Vorgang. + + + Fehler beim Herstellen einer Verbindung mit dem Remotebefehl. + + + Der Vorgang kann nicht ausgeführt werden, da zurzeit ein Befehl angehalten wird. Warten Sie, bis das Anhalten des Befehls abgeschlossen ist, und wiederholen Sie dann den Vorgang. + + + Es ist kein Runspace zum Ausführen von Befehlen in diesem Thread verfügbar. Sie können einen in der DefaultRunspace-Eigenschaft des Typs „System.Management.Automation.Runspaces.Runspace“ angeben. Die aktuelle PowerShell-Instanz enthält keinen aufzurufenden Befehl. + + + Es kann kein PowerShell-Objekt erstellt werden, das den aktuellen Runspace verwendet, da kein aktueller Runspace verfügbar ist. Der aktuelle Runspace wird möglicherweise gestartet, z. B. wenn er mit einem Initial Session State erstellt wird. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ProgressRecordStrings.de.resx b/src/System.Management.Automation/resources/de/ProgressRecordStrings.de.resx new file mode 100644 index 00000000000..1a645fdb6d0 --- /dev/null +++ b/src/System.Management.Automation/resources/de/ProgressRecordStrings.de.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Das Argument kann nicht verarbeitet werden, da „{0}“ nicht negativ sein darf. + + + Das Argument kann nicht verarbeitet werden, da der Wert von „{0}“ nicht NULL oder leer sein darf. + + + Der Prozentwert kann nicht festgelegt werden, da „{0}“ nicht größer als 100 sein darf. + + + „ParentActivityId“ darf nicht mit der „ActivityId“ identisch sein. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ProviderBaseSecurity.de.resx b/src/System.Management.Automation/resources/de/ProviderBaseSecurity.de.resx new file mode 100644 index 00000000000..f0f94a8dd23 --- /dev/null +++ b/src/System.Management.Automation/resources/de/ProviderBaseSecurity.de.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 + + + Die Schnittstelle kann nicht verwendet werden, da die ISecurityDescriptorCmdletProvider-Schnittstelle von diesem Anbieter nicht unterstützt wird. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/ProxyCommandStrings.de.resx b/src/System.Management.Automation/resources/de/ProxyCommandStrings.de.resx new file mode 100644 index 00000000000..c021e6ee5a7 --- /dev/null +++ b/src/System.Management.Automation/resources/de/ProxyCommandStrings.de.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 + + + Der Parameter „help“ wird nicht als gültiges HelpInfo-Objekt erkannt, das vom Befehl „get-help“ erstellt wurde. + + + Der Proxybefehl kann nicht generiert werden, da CommandMetadata keinen Namen enthält. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/RegistryProviderStrings.de.resx b/src/System.Management.Automation/resources/de/RegistryProviderStrings.de.resx new file mode 100644 index 00000000000..4e64b90a8ad --- /dev/null +++ b/src/System.Management.Automation/resources/de/RegistryProviderStrings.de.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Element festlegen + + + Element: {0} Wert: {1} + + + Element löschen + + + Element: {0} + + + Neues Element + + + Element: {0} + + + Schlüssel entfernen + + + Element: {0} + + + Schlüssel kopieren + + + Element: {0} Ziel: {1} + + + Element umbenennen + + + Element: {0} NewName: {1} + + + Element verschieben + + + Element: {0} Ziel: {1} + + + Eigenschaft festlegen + + + Element: {0} Eigenschaft: {1} + + + Eigenschaft löschen + + + Element: {0} Eigenschaft: {1} + + + Neue Eigenschaft + + + Element: {0} Eigenschaft: {1} + + + Eigenschaft entfernen + + + Element: {0} Eigenschaft: {1} + + + Eigenschaft umbenennen. + + + Element: {0} SourceProperty: {1} DestinationProperty: {2} + + + Eigenschaft kopieren + + + Element: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Eigenschaft verschieben + + + Element: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Der Vorgang wurde nicht verarbeitet. Der angegebene Speicherort lässt diesen Vorgang nicht zu. + + + Der Vorgang ist am Quellspeicherort nicht zulässig. + + + Der Vorgang ist am Zielspeicherort nicht zulässig. + + + Die Konfigurationseinstellungen für den lokalen Computer + + + Die Softwareeinstellungen für den aktuellen Benutzer + + + Ein Schlüssel in diesem Pfad ist bereits vorhanden. + + + Der Vorgang kann nicht ausgeführt werden, da der Zielpfad dem Quellpfad untergeordnet ist. + + + Die Eigenschaft ist bereits vorhanden. + + + Die Eigenschaft {0} existiert nicht im Pfad {1}. + + + Der Registrierungsschlüssel am angegebenen Pfad ist nicht vorhanden. + + + Der Parameter „Typ“ konnte nicht gebunden werden. „{0}“ konnte nicht in „{1}“ konvertiert werden. Die möglichen Enumerationswerte sind „String, ExpandString, Binary, DWord, MultiString, QWord, Unbekannt“. + + + Der Schlüssel {0} wurde erstellt, aber ein Standardwert konnte nicht festgelegt werden. + + + Es kann kein Laufwerk mit dem angegebenen Stamm erstellt werden. Der Stammpfad ist nicht vorhanden. + + + Das Element kann nicht umbenannt werden, da ein Element mit diesem Namen bereits im selben Container vorhanden ist. + + + Der Name des Registrierungsschlüssels muss mit einem gültigen Basisschlüsselnamen beginnen. + + + Das Unterschlüsselargument ist ungültig. + + + Eine Unterschlüsselstruktur kann nicht gelöscht werden, da der Unterschlüssel nicht vorhanden ist. + + + Es ist kein Wert mit diesem Namen vorhanden. + + + Der Enumerationswert {0} ist ungültig. + + + Ein Wertargument muss angegeben werden. + + + Ein Namensargument muss angegeben werden. + + + Der angegebene RegistryValueKind ist ein ungültiger Wert. + + + „RegistryKey.SetValue“ lässt keine Zeichenfolge[] zu, die einen NULL-Zeichenfolgenverweis enthält. + + + Registrierungsunterschlüssel dürfen nicht mehr als 255 Zeichen umfassen. + + + Ein nicht leerer Unterschlüsselname muss angegeben werden. + + + Der Typ des Wertobjekts stimmte nicht mit dem angegebenen RegistryValueKind überein, oder das Objekt konnte nicht ordnungsgemäß konvertiert werden. + + + RegistryKey.SetValue unterstützt keine Arrays vom Typ „{0}“. Nur Byte[] und String[] werden unterstützt. + + + Der angegebene Registrierungsschlüssel ist nicht vorhanden. + + + Die Länge des angegebenen Wertnamens überschreitet die maximale Länge von 16383 Zeichen. + + + Die Größe der angegebenen Wertdaten überschreitet das Maximum von 1 MB. + + + Der angegebene Registrierungsunterschlüssel ist nicht vorhanden. + + + Der angegebene RegistryKeyPermissionCheck-Wert ist ungültig. + + + Der Registrierungsschlüssel verfügt über Unterschlüssel. Rekursive Entfernungen werden von dieser Methode nicht unterstützt. + + + Ein KTM-Handle kann nicht ohne Transaction.Current oder eine angegebene Transaktion erstellt werden. + + + Die angegebene Transaktion oder Transaction.Current muss mit der Transaktion übereinstimmen, die zum Erstellen oder Öffnen dieses TransactedRegistryKey verwendet wird. + + + Das TransactedRegistryKey-Objekt ist keiner Transaktion zugeordnet, da es sich um einen vordefinierten Schlüssel handelt. + + + Angeforderter Registrierungszugriff ist nicht zulässig. + + + Der Zugriff auf den Registrierungsschlüssel „{0}“ wird verweigert. + + + In den Registrierungsschlüssel kann nicht geschrieben werden. + + + Auf einen geschlossenen Registrierungsschlüssel kann nicht zugegriffen werden. + + + Unbekannter Fehler: {0}. + + + Registrierungstransaktionen werden auf dieser Plattform nicht unterstützt. + + + Das angegebene Handle ist ungültig. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/RemotingErrorIdStrings.de.resx b/src/System.Management.Automation/resources/de/RemotingErrorIdStrings.de.resx new file mode 100644 index 00000000000..25147fe6be5 --- /dev/null +++ b/src/System.Management.Automation/resources/de/RemotingErrorIdStrings.de.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + Platzhalterzeichen werden für den FilePath-Parameter nicht unterstützt. Geben Sie einen Pfad ohne Platzhalterzeichen an. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + Ein {0}-Wert muss für die Sitzungsoption „{1}“ angegeben werden. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + Die maximale Anzahl von WS-Man-URI-Umleitungen, die beim Herstellen einer Verbindung mit einem Remotecomputer zulässig sind + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + Der WriteEvents-Parameter kann nicht ohne den Wait-Parameter verwendet werden. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + PowerShell-Remoting wird in der Windows Preinstallation Environment (WinPE) nicht unterstützt. + + + Von „{0}“ vorgenommene Änderungen werden erst wirksam, nachdem der WinRM-Dienst neu gestartet wurde. + + + {0} muss möglicherweise den WinRM-Dienst neu starten, wenn eine Konfiguration mit diesem Namen kürzlich nicht registriert war. Bestimmte Systemdatenstrukturen sind dann möglicherweise noch zwischengespeichert. In diesem Fall kann ein Neustart von WinRM erforderlich sein. +Alle WinRM-Sitzungen, die mit PowerShell-Sitzungskonfigurationen verbunden sind, z. B. Microsoft.PowerShell und Sitzungskonfigurationen, die mit dem Cmdlet „Register-PSSessionConfiguration“ erstellt wurden, werden getrennt. + + + Sie befinden sich in einer Remotesitzung und haben die Force-Option ausgewählt. Dadurch kann der WinRM-Dienst neu gestartet werden. Wenn der WinRM-Dienst neu gestartet wird, wird diese Remotesitzung beendet, und für die Fortsetzung ist eine neue Sitzung erforderlich. + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + Der Parameter „-WriteJobInResults“ kann nicht ohne den Parameter „-Wait“ verwendet werden. + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + Der angegebene Eingabestream ist ungültig. Nur „{0}“ wird als Eingabestream unterstützt. + + + Der angegebene Ausgabestreamsatz ist ungültig. Nur „{0}“ wird als Ausgabestream unterstützt. + + + Der angegebene WSMAN_SENDER_DETAILS ist ungültig. Ein NULL-Wert für WSMAN_SENDER_DETAILS kann nicht verarbeitet werden. + + + Der angegebene Shellkontext ist ungültig. + + + {0} + + + Ein NULL-Wert ist für „{0}“ mit der Plug-In-Methode „{1}“ nicht zulässig. + + + Ein NULL-Wert ist für Eingabe- und Ausgabestreamgruppen nicht zulässig. „{0}“ und „{1}“ sind die unterstützten Eingabe- und Ausgabestreams. + + + Ein NULL-Wert ist für „{0}“ mit der Plug-In-Methode „{1}“ nicht zulässig. + + + Ein NULL-Wert ist für „{0}“ mit der Plug-In-Methode „{1}“ nicht zulässig. + + + Der PowerShell-Plug-In-Vorgang wird beendet. Dies kann passieren, wenn der Hostdienst oder die Hostanwendung beendet wird. + + + Das PowerShell-Plug-In versteht die {0}-Option nicht. Stellen Sie sicher, dass der Client mit dem Build {1} und der Protokollversion {2} von PowerShell kompatibel ist. + + + Vom Client wird eine Option mit dem Namen „{0}“ erwartet. Stellen Sie sicher, dass der Client mit dem Build {1} und der Protokollversion {2} von PowerShell kompatibel ist. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Das PowerShell-Plug-In unterstützt die vom Client angeforderte Protokollversion {2} nicht.</PSProtocolVersionError> + + + Im PowerShell-Plug-In ist beim Melden des Kontexts an den WSMan-Dienst ein schwerwiegender Fehler aufgetreten. + + + Die verwaltete Serversitzung kann nicht erstellt werden. + + + Im PowerShell-Plug-In ist beim Registrieren eines Wait-Handles für die Herunterfahrbenachrichtigung ein schwerwiegender Fehler aufgetreten. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + Die ausführbare Datei „{0}“ wurde nicht gefunden. Überprüfen Sie, ob das WOW64-Feature installiert ist. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + Der Windows PowerShell-Prozess kann nicht erstellt werden, da Windows PowerShell auf diesem Computer nicht gefunden wurde. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/RunspaceInit.de.resx b/src/System.Management.Automation/resources/de/RunspaceInit.de.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/de/RunspaceInit.de.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/RunspacePoolStrings.de.resx b/src/System.Management.Automation/resources/de/RunspacePoolStrings.de.resx new file mode 100644 index 00000000000..87751d11ee5 --- /dev/null +++ b/src/System.Management.Automation/resources/de/RunspacePoolStrings.de.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die maximale Poolgröße darf nicht kleiner als 1 sein. + + + Die mindeste Poolgröße darf nicht kleiner als 1 sein. + + + Die minimale Poolgröße darf nicht größer als die maximale Poolgröße sein. + + + Der Zustand des Runspacepools ist für diesen Vorgang ungültig. + + + Der Vorgang kann nicht ausgeführt werden, da sich der Runspacepool nicht im Zustand „{0}“ befindet. Der aktuelle Status ist „{1}“. + + + Der Runspacepool kann nicht geöffnet werden, da er sich nicht im Zustand „BeforeOpen“ befindet. Der aktuelle Status ist „{0}“. + + + Das {0} Objekt wurde nicht durch Aufrufen von {1} der aktuellen RunspacePool-Instanz erstellt. + + + Der Runspace kann nicht für den aktuellen Pool freigegeben werden, da der Runspace nicht zum aktuellen Pool gehört. + + + Diese Eigenschaft kann nicht mehr geändert werden, nachdem der Runspacepool geöffnet wurde. + + + Dieser Runspace unterstützt keine Trennungs- und Verbindungsvorgänge. + + + Der Vorgang kann nicht ausgeführt werden, da sich der Runspacepool im Zustand „Getrennt“ befindet. + + + Der Trennvorgang wird auf dem Server nicht unterstützt. Auf dem Server muss PowerShell 3.0 oder höher ausgeführt werden, damit die Trennung von Remoterunspacepools unterstützt wird. + + + Dieser Runspacepool {0} ist nicht für die Bereitstellung getrennter PowerShell-Objekte für Befehle konfiguriert, die auf dem Remoteserver ausgeführt werden. Verwenden Sie die statische GetRunspacePools()-Methode der RunspacePool-Klasse, um den Server abzufragen und Runspacepoolobjekte zurückzugeben, die dafür konfiguriert sind. + + + Dieser Runspacepool kann nicht verbunden werden, da der entsprechende serverseitige Runspacepool mit einem anderen Client verbunden ist. + + + ResetRunspaceState wird auf dem Server nicht unterstützt. Auf dem Server muss PowerShell 5.0 oder höher ausgeführt werden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/RunspaceStrings.de.resx b/src/System.Management.Automation/resources/de/RunspaceStrings.de.resx new file mode 100644 index 00000000000..7461d495385 --- /dev/null +++ b/src/System.Management.Automation/resources/de/RunspaceStrings.de.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Der Runspacezustand ist für diesen Vorgang ungültig. + + + Der Runspace kann nicht geöffnet werden, da der Runspace sich nicht im Zustand „BeforeOpen“ befindet. Der aktuelle Zustand des Runspaces ist „{0}“. + + + Der Vorgang kann nicht ausgeführt werden, da sich der Runspac nicht im Zustand „Geöffnet“ befindet. Der aktuelle Zustand des Runspaces ist „{0}“. + + + Die Pipeline kann nicht aufgerufen werden, da sich der Runspace nicht im Zustand „Opened“ (geöffnet) befindet. Der aktuelle Zustand des Runspaces ist „{0}“. + + + Der Pipelinezustand ist für diesen Vorgang ungültig. + + + Die Pipeline kann nicht aufgerufen werden, da sie bereits aufgerufen wurde. + + + Der gültige Wert für den Parameter ist PipelineResultTypes.Output. + + + Die Pipeline enthält keinen Befehl. + + + Die Pipeline wurde nicht ausgeführt, da bereits eine Pipeline ausgeführt wird. Pipelines können nicht gleichzeitig ausgeführt werden. + + + Eine geschachtelte Pipeline kann nicht asynchron aufgerufen werden. Verwenden Sie die Invoke-Methode. + + + Sie sollten eine geschachtelte Pipeline nur innerhalb einer ausgeführten Pipeline ausführen. + + + Runspace kann nicht geschlossen werden, während ein SessionStateProxy-Methodenaufruf ausgeführt wird. + + + Die Pipeline kann nicht aufgerufen werden, während ein SessionStateProxy-Methodenaufruf ausgeführt wird. + + + Ein SessionStateProxy-Methodenaufruf wird ausgeführt. Gleichzeitige SessionStateProxy-Methodenaufrufe sind nicht zulässig. + + + Eine Pipeline wird bereits ausgeführt. Gleichzeitige SessionStateProxy-Methodenaufrufe sind nicht zulässig. + + + Diese Eigenschaft kann nicht mehr geändert werden, nachdem der Runspace geöffnet wurde. + + + Beim Verarbeiten des Moduls „{0}“, das im InitialSessionState-Objekt zum Erstellen dieses Runspaces angegeben wurde, ist mindestens ein Fehler aufgetreten. Eine vollständige Liste der Fehler finden Sie in der Eigenschaft „ErrorRecords“. Der erste Fehler war: {1} + + + Die Threadoptionen können nur geändert werden, wenn der Apartmentzustand Multithreaded Apartment (MTA) ist, die aktuellen Optionen UseNewThread oder UseCurrentThread sind und der neue Wert ReuseThread ist. + + + „{0}“ darf nicht FALSE sein, wenn der Sprachmodus „{1}“ oder „{2}“ ist. + + + Sie können einen nur lokalen Runspace nicht trennen. + + + Der Verbindungsvorgang wird für lokale Runspaces nicht unterstützt. + + + Die Sitzung ist ausgelastet. Sie werden mit der Sitzung verbunden, sobald sie verfügbar ist. Um den Enter-PSSession-Befehl abzubrechen, drücken Sie STRG + C. + + + Der Befehl kann nicht abgeschlossen werden. Skriptaufrufe werden in dieser Sitzungskonfiguration nicht unterstützt. Dies kann vorkommen, wenn sich die Sitzungskonfiguration im Nur-Sprachmodus befindet. + + + Für lokale Runspaces können keine Vorgänge zum Trennen und Verbinden verwendet werden. + + + Die Pipeline kann nicht verbunden werden, da sich der Runspace nicht im Zustand „Opened“ befindet. Der aktuelle Zustand des Runspaces ist „{0}“. + + + RemoteRunspace kann nicht erstellt werden. Das angegebene RunspacePool-Objekt ist ungültig. + + + Diesem Runspace ist kein Befehl mit getrennter Verbindung zugeordnet. + + + Der Trennungsvorgang wird auf dem Remotecomputer nicht unterstützt. Damit das Trennen unterstützt wird, muss auf dem Remotecomputer Windows PowerShell 3.0 oder eine höhere Version von Windows PowerShell ausgeführt werden und der WSMan-Transport verwendet werden. + + + Die PSSession kann nicht verbunden werden, da sich die Sitzung nicht im Zustand „Disconnected“ (getrennt) befindet oder keine Verbindung möglich ist. + + + Der Wert für den Parameter darf nicht PipelineResultTypes.None oder PipelineResultTypes.Output sein. + + + Gültige Werte für den Parameter sind PipelineResultTypes.Output oder PipelineResultTypes.Null. + + + Die Umleitung des Debugdatenstroms wird auf dem Zielremotecomputer nicht unterstützt. + + + Die ausführliche Umleitung des Datenstroms wird auf dem Zielremotecomputer nicht unterstützt. + + + Die Umleitung des Warnungsdatenstroms wird auf dem Zielremotecomputer nicht unterstützt. + + + Die Umleitung des Informationsstreams wird auf dem Zielremotecomputer nicht unterstützt. + + + Sie haben eine Sitzung geöffnet, in der gerade ein Befehl oder Skript ausgeführt wird. Da die Ausgabe an den Auftrag „{0}“ weitergeleitet wird, wird in der Konsole keine Ausgabe angezeigt. Sie können warten, bis der ausgeführte Befehl beendet ist, oder den Befehl abbrechen und mit STRG+C eine Eingabeaufforderung erhalten. + + + + Sie haben eine Sitzung geöffnet, in der gerade ein Befehl oder Skript ausgeführt wird. Die Ausgabe wird in der Konsole angezeigt. Sie können warten, bis der ausgeführte Befehl beendet ist, oder ihn abbrechen und mit STRG+C eine Eingabeaufforderung erhalten. + + + + Sie haben eine Sitzung geöffnet, die derzeit an einem Debughaltepunkt in einem ausgeführten Befehl oder Skript angehalten ist. Verwenden Sie den PowerShell-Befehlszeilendebugger, um mit dem Debuggen fortzufahren. + + + + Der DefaultRunspace muss ein LocalRunspace sein. + + + Die statische PrimaryRunspace-Eigenschaft kann nur einmal festgelegt werden und wurde bereits festgelegt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/SecuritySupportStrings.de.resx b/src/System.Management.Automation/resources/de/SecuritySupportStrings.de.resx new file mode 100644 index 00000000000..fc233244245 --- /dev/null +++ b/src/System.Management.Automation/resources/de/SecuritySupportStrings.de.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Das Zertifikat kann nicht geladen werden. „{0}“ muss in einen Dateisystempfad aufgelöst werden. + + + Das Zertifikat „{0}“ kann nicht für die Verschlüsselung verwendet werden. Verschlüsselungszertifikate müssen die Verwendung des Datenverschlüsselungs- oder Schlüsselverschlüsselungsschlüssels enthalten und die erweiterte Schlüsselverwendung der Dokumentverschlüsselung ({1}) enthalten. + + + Das Zertifikat kann nicht geladen werden. Der Bezeichner „{0}“ stimmt mit mehreren Zertifikaten überein. Wenn Sie die Verschlüsselung für mehrere Empfänger ausführen möchten, geben Sie dem Parameter „{1}“ mehrere spezifische Werte anstelle eines Platzhalters an, der mit mehreren Zertifikaten übereinstimmt. + + + Verschlüsselungszertifikat kann nicht geladen werden. Die Zertifikateinstellung „{0}“ stellt weder ein gültiges Base64-codiertes Zertifikat noch ein gültiges Zertifikat nach Datei, Verzeichnis, Fingerabdruck oder Antragstellername dar. + + + WARNUNG: Das Zertifikat „{0}“ enthält einen privaten Schlüssel. Zertifikate für die Protokollierung geschützter Ereignisse, die für die Verschlüsselung verwendet werden, dürfen nur den öffentlichen Schlüssel enthalten. + + + FEHLER: Die Ereignisprotokollmeldung „{0}“ konnte nicht geschützt werden: {1} + + + FEHLER: Zertifikat konnte nicht gefunden oder verwendet werden: {0} + + + Der Sitzungsschlüssel zum Verschlüsseln der sicheren Zeichenfolge ist nicht verfügbar. + + + Ungültiger Pufferoffset. + + + Ungültige öffentliche Schlüssel-Daten. + + + Der öffentliche Schlüssel kann nicht importiert werden. + + + Ungültige Sitzungsschlüssel-Daten. + + + Die Ausführung der Skriptdatei „{0}“ wird durch die Systemrichtlinie blockiert. + + + Ein unbekannter Wert für die Erzwingung der Skriptdateirichtlinie wurde zurückgegeben: {0}. + + + Skriptdatei lesen + + + Die Skriptdatei „{0}“ ist von der Richtlinie nicht vertrauenswürdig und wird im ConstrainedLanguage-Modus ausgeführt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/Serialization.de.resx b/src/System.Management.Automation/resources/de/Serialization.de.resx new file mode 100644 index 00000000000..b85273dce62 --- /dev/null +++ b/src/System.Management.Automation/resources/de/Serialization.de.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} Attribut wurde erwartet. + + + {0} XML-Tag wird nicht erkannt. + + + Für referenceId {0} wurde kein Objekt gefunden. + + + Das Namensattribut für den Wörterbuchschlüssel wurde falsch angegeben. + + + Das Namensattribut für den Wörterbuchwert wurde falsch angegeben. + + + Die Version von „PSObject“ ist ungültig. + + + Die Version des eingehenden PSObject ist {0}. Erwartet wird der Wert 1. + + + Namen können nicht verarbeitet werden, da für referenceId {0} keine TypeNames gefunden wurden. + + + Der Wert des depth-Parameters muss größer oder gleich 1 sein. + + + Der aktuelle Knotentyp ist „{0}“. Erwarteter Typ: {1}. + + + Der Schlüssel für den Wörterbucheintrag wurde nicht angegeben. + + + Der Wert für den Wörterbucheintrag wurde nicht angegeben. + + + Es sind keine weiteren Objekte zum Deserialisieren vorhanden. + + + NULL ist als Wörterbuchschlüssel angegeben. + + + Der Inhalt des primitiven Typs „{0}“ ist ungültig. + + + Serialisiertes XML ist zu tief geschachtelt. + + + Die Serialisierungskomponente wurde geschlossen. + + + Die Daten im Befehl haben die maximal zulässige Größe für die Sitzungskonfiguration überschritten. Das zulässige Maximum beträgt {0} MB. Ändern Sie die Eingabe, verwenden Sie eine andere Sitzungskonfiguration, oder ändern Sie die Eigenschaften „{1}" und „{2}" der Sitzungskonfiguration auf dem entfernten Computer. + + + Die Deserialisierung der verschlüsselten sicheren Zeichenfolge ist fehlgeschlagen. + + + Der Schlüsseltyp „{0}“ ist ungültig. Die PSPrimitiveDictionary-Klasse akzeptiert nur Schlüssel vom Typ System.String. + + + Der Typ des Werts „{0}“ ist ungültig. Die PSPrimitiveDictionary-Klasse akzeptiert nur Werte von Typen, die über PowerShell-Remoting vollständig serialisierbar sind. Im Hilfethema about_Remoting finden Sie eine Liste der vollständig serialisierbaren Typen. + + + Die Daten konnten nicht entschlüsselt werden. Die Daten wurden nicht mit diesem Schlüssel verschlüsselt. + + + Der Parameterwert „{0}“ ist keine gültige verschlüsselte Zeichenfolge. + + + Die angegebene „{0}“ ist ungültig. Gültige {0} Längeneinstellungen sind entweder 128 Bit, 192 Bit oder 256 Bit. + + + Die Deserialisierung von SecureString wird derzeit nur unter Windows unterstützt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/SessionStateProviderBaseStrings.de.resx b/src/System.Management.Automation/resources/de/SessionStateProviderBaseStrings.de.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/de/SessionStateProviderBaseStrings.de.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/SessionStateStrings.de.resx b/src/System.Management.Automation/resources/de/SessionStateStrings.de.resx new file mode 100644 index 00000000000..d74fd4151e9 --- /dev/null +++ b/src/System.Management.Automation/resources/de/SessionStateStrings.de.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die zurückgegebenen Informationen können nicht verarbeitet werden, da die von der Start-Methode des Anbieters zurückgegebenen Informationen für einen anderen Anbieter als den übergebenen bestimmt waren. + + + Die zurückgegebenen Informationen können nicht verarbeitet werden, da die von der Start-Methode des Anbieters zurückgegebenen Informationen NULL waren. + + + Der Versuch, den GetItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den GetItem-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den SetItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den SetItem-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den ClearItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den InvokeDefaultAction-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den InvokeDefaultAction-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den ItemExists-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den ItemExists-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den IsValidPath-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den IsItemContainer-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den RemoveItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den GetChildItems-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den GetChildItems-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den GetChildNames-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den GetChildNames-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den RenameItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den RenameItem-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den NewItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den NewItem-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den HasChildItems-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den CopyItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den CopyItem-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den GetParentPath-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den NormalizeRelativePath-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den MakePath-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den GetChildName-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den MoveItem-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den MoveItem-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den GetProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den GetProperty-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den SetProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den SetProperty-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den ClearProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den ClearProperty-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den NewProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den NewProperty-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den RemoveProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den RemoveProperty-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den CopyProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den CopyProperty-Vorgang können für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den MoveProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Die dynamischen Parameter für den MoveProperty-Vorgang können für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den RenameProperty-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Dynamische Parameter für RenameProperty können für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Inhaltsleser kann für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Die dynamischen Parameter für den GetContentReader-Vorgang können für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Inhaltswriter kann für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Die dynamischen Parameter für den GetContentWriter-Vorgang können für den Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Inhalt kann nicht abgerufen werden, da es sich um ein Verzeichnis handelt: „{0}“. Verwenden Sie stattdessen „Get-ChildItem“. + + + Der Inhalt kann nicht geschrieben werden, da es sich um ein Verzeichnis handelt: „{0}“. + + + Es ist kein Standortverlauf mehr vorhanden, um rückwärts zu navigieren. + + + Es ist kein Standortverlauf mehr vorhanden, um vorwärts zu navigieren. + + + Der BoundedStack ist leer. + + + Der Versuch, den ClearContent-Vorgang für den Anbieter „{0}“ auszuführen, ist für den Pfad „{1}“ fehlgeschlagen. {2} + + + Der Inhalt von „{0}“ kann nicht gelöscht werden, da es sich um ein Verzeichnis handelt. Clear-Content wird nur für Dateien unterstützt. + + + Die dynamischen Parameter für den ClearContent-Vorgang können vom Anbieter „{0}“ für den Pfad „{1}“ nicht abgerufen werden. {2} + + + Der Versuch, den GetSecurityDescriptor-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den SetSecurityDescriptor-Vorgang beim Anbieter „{0}“ für den Pfad „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Der Versuch, den Start-Vorgang beim Anbieter „{0}“ auszuführen, ist fehlgeschlagen. {1} + + + Der Versuch, den InitializeDefaultDrives-Vorgang für den Anbieter „{0}“ auszuführen, ist fehlgeschlagen. + + + Der Versuch, den NewDrive-Vorgang beim Anbieter „{0}“ für das Laufwerk mit dem Stamm „{1}“ auszuführen, ist fehlgeschlagen. {2} + + + Dynamische Parameter für „NewDrive“ können für den Anbieter „{0}“ nicht abgerufen werden. {1} + + + Das Aufrufen von „RemoveDrive“ für den Anbieter „{0}“ ist fehlgeschlagen. {1} + + + Das Laufwerk „{0}“ kann nicht entfernt werden, da der Anbieter „{1}“ dies verhindert hat. + + + Der Pfad „{0}“ verweist auf ein Element, das sich außerhalb der Basis „{1}“ befindet. + + + Der Aufruf von „Seek“ für den Inhaltswriter des Anbieters „{0}“ ist für den Pfad „{1}“ fehlgeschlagen. {2} + + + Der Aufruf von „Close“ für den Inhaltsleser oder -writer des Anbieters „{0}“ ist für den Pfad „{1}“ fehlgeschlagen. {2} + + + Der Aufruf von „Read“ für den Inhaltsleser des Anbieters „{0}“ ist für den Pfad „{1}“ fehlgeschlagen. {2} + + + Der Aufruf von „Write“ für den Inhaltswriter des Anbieters „{0}“ ist für den Pfad „{1}“ fehlgeschlagen. {2} + + + Der Anbieter „{0}“ kann nicht verwendet werden, um mithilfe der Variablensyntax Daten abzurufen oder festzulegen. {2} + + + Die Variablensyntax kann nicht verwendet werden, um Daten im Anbieter abzurufen oder festzulegen. {2} + + + Der Alias kann nicht geschrieben werden, da der Alias „{0}“ schreibgeschützt oder konstant ist und daher nicht geschrieben werden kann. + + + In Funktion „{0}“ kann nicht geschrieben werden, da sie schreibgeschützt oder konstant ist. + + + Die Variable „{0}“ kann nicht überschrieben werden, da sie schreibgeschützt oder konstant ist. + + + Auf die Variable „${0}“ kann nicht zugegriffen werden, da es sich um eine private Variable handelt. + + + Auf den Befehl „{0}“ kann nicht zugegriffen werden, da es sich um einen privaten Befehl handelt. + + + Auf den Befehl kann nicht zugegriffen werden, da es sich um einen privaten Befehl handelt. + + + Auf die Ressource des Sitzungszustands kann nicht zugegriffen werden, da es sich um eine private Ressource handelt. + + + Der Alias wurde nicht entfernt, da Alias „{0}“ konstant oder schreibgeschützt ist. + + + Die Funktion „{0}“ kann nicht entfernt werden, da sie konstant ist. + + + Die Variable „{0}“ kann nicht entfernt werden, da sie konstant oder schreibgeschützt ist. Wenn die Variable schreibgeschützt ist, wiederholen Sie den Vorgang mit der Option Force. + + + Der Alias „{0}“ kann nicht geändert werden, da er konstant ist. + + + Der Alias „{0}“ kann nicht geändert werden, da er schreibgeschützt ist. + + + Die Funktion „{0}“ kann nicht geändert werden, da sie konstant ist. + + + Die Funktion „{0}“ kann nicht geändert werden, da sie schreibgeschützt ist. + + + Der Alias „{0}“ kann nach der Erstellung nicht als Konstante festgelegt werden. Aliase können nur bei der Erstellung als Konstante festgelegt werden. + + + Eine vorhandene Funktion „{0}“ kann nicht als konstant festgelegt werden. Funktionen können nur bei der Erstellung als konstant festgelegt werden. + + + Eine vorhandene Variable „{0}“ kann nicht konstant gemacht werden. Variablen können nur bei der Erstellung als konstant festgelegt werden. + + + Die Option AllScope-Option kann nicht aus dem Alias „{0}“ entfernt werden. + + + Die Option AllScope-Option kann nicht aus der Funktion „{0}“ entfernt werden. + + + Die Option AllScope-Option kann nicht aus der Variable „{0}“ entfernt werden. + + + Die Funktionsdefinition „{0}“ enthielt einen Bereichsqualifizierer, aber keinen Funktionsnamen. + + + Der Anbieter „{0}“ kann nicht entfernt werden. Alle Laufwerke, die dem Anbieter „{0}“ zugeordnet sind, müssen entfernt werden, bevor der Anbieter „{0}“ entfernt werden kann. + + + Der Laufwerkname kann nicht verarbeitet werden, da er mindestens eines der folgenden ungültigen Zeichen enthält: ; ~ / \ . : + + + Das Erstellen des neuen Laufwerks ist fehlgeschlagen, da der Anbieter das Erstellen des neuen Laufwerks nicht zulässt. + + + Der angegebene Wert „{0}“ wurde in mehr als einen Speicherstapel aufgelöst. + + + Der Speicherortstapel „{0}“ wurde nicht gefunden. Er ist nicht vorhanden oder kein Container. + + + Der Pfad "{0}" wurde nicht gefunden, da er nicht vorhanden ist. + + + Der Alias kann nicht gefunden werden, da der Alias „{0}“ nicht vorhanden ist. + + + Der Speicherort kann nicht festgelegt werden, da der Pfad „{0}“ zu mehreren Containern aufgelöst wurde. Der Speicherort kann jeweils nur für einen einzelnen Container festgelegt werden. + + + Die Variable kann nicht verarbeitet werden, da der Variablenpfad „{0}“ zu mehreren Elementen aufgelöst wurde. Sie können den Variablenwert jeweils nur für ein Element abrufen oder festlegen. + + + Laufwerk wurde nicht gefunden. Ein Laufwerk mit dem Namen „{0}“ ist nicht vorhanden. + + + Es wurde kein Anbieter mit dem Namen „{0}“ gefunden. + + + Es wurde kein Anbieter mit dem Namen „{0}“ gefunden. Der Name hat nicht das richtige Format. Ein Anbietername darf nur alphanumerische Zeichen oder einen PowerShell-Snap-In-Namen enthalten, auf den ein einzelner '\' und alphanumerische Zeichen folgen. + + + „{0}“ wurde in mehr als einen Anbieternamen aufgelöst. Mögliche Übereinstimmungen sind:{1}. + + + Beim Erstellen einer Instanz des Anbieters ist ein Fehler aufgetreten. Der Anbietertypname „{0}“ wurde in der Assembly nicht gefunden. + + + Der angegebene Anbietername „{0}“ kann nicht verwendet werden, da er mindestens eines der folgenden ungültigen Zeichen enthält: \ [ ] ? * : + + + Beim Erstellen einer Instanz des Anbieters „{0}“ ist ein Fehler aufgetreten. {1} + + + Es wurde keine Variable mit dem Namen „{0}“ gefunden. + + + Es wurde keine Ablaufverfolgungsquelle mit dem Namen „{0}“ gefunden. + + + Ein Laufwerk mit dem Namen „{0}“ ist bereits vorhanden. + + + Eine Variable mit dem Namen „{0}“ ist bereits vorhanden. + + + Der Alias ist nicht zulässig, da bereits ein Alias mit dem Namen „{0}“ vorhanden ist. + + + Der Cmdlet-Anbieter kann nicht registriert werden, da bereits ein Cmdlet-Anbieter mit dem Namen „{0}“ vorhanden ist. + + + Der Pfad verweist nicht auf einen Dateisystempfad. + + + Der globale Bereich lässt sich nicht entfernen. + + + Die Bereichsnummer „{0}“ überschreitet die Anzahl der aktiven Bereiche. + + + PSDriveInfo kann nicht verglichen werden. Eine PSDriveInfo-Instanz kann nur mit einer anderen PSDriveInfo-Instanz verglichen werden. + + + Der Cmdlet-Anbieter kann die Ergebnisse nicht streamen, da kein Cmdlet angegeben wurde, über das die Ausgabe gestreamt werden kann. + + + Der Cmdlet-Anbieter kann die Ergebnisse nicht streamen, da kein Cmdlet angegeben wurde, über das der Fehler gestreamt werden kann. + + + Der Startort für diesen Anbieter ist nicht festgelegt. Um den Startort festzulegen, rufen Sie „(get-psprovider '{0}').Home = 'path'“ auf. + + + Der Pfad weist nicht das richtige Format auf. Anbieterpfade müssen eine Anbieter-ID enthalten, gefolgt von "::" und einem anbieterspezifischen Pfad. + + + Das Element kann nicht verschoben werden, da sich der Zielpfad nur in einen einzelnen Pfad auflösen lässt. + + + Das Element kann nicht verschoben werden, da Quell- und Zielpfad nicht im selben Anbieter aufgelöst wurden. + + + Das Element kann nicht verschoben werden, da der Quellpfad auf ein oder mehrere Elemente verweist und der Zielpfad kein Container ist. Überprüfen Sie, ob der Zielpfad ein Container ist, und versuchen Sie es erneut. + + + Das Element kann nicht verschoben werden, da das Ziel in mehrere Pfade aufgelöst wurde. Geben Sie einen Zielpfad an, der in genau ein Ziel aufgelöst wird, und wiederholen Sie den Vorgang. + + + Ein Container kann nicht auf ein vorhandenes Blattelement kopiert werden. + + + Ein Container kann nicht in einen anderen Container kopiert werden. Der Parameter „-Recurse“ oder „-Container“ wurde nicht angegeben. + + + Quell- und Zielpfad wurden nicht demselben Anbieter zugeordnet. + + + Das Element kann nicht umbenannt werden, da der Pfad in mehrere Elemente aufgelöst wurde. Es kann jeweils nur ein Element umbenannt werden. + + + Der Anbieter „{0}“ kann aufgrund eines Fehlers beim Anbieter nicht zum Auflösen des Pfads „{1}“ verwendet werden. + + + Schnittstelle kann nicht verwendet werden. Die IContentCmdletProvider-Schnittstelle wird von diesem Anbieter nicht implementiert. + + + Schnittstelle kann nicht verwendet werden. Die IPropertyCmdletProvider-Schnittstelle wird von diesem Anbieter nicht unterstützt. + + + Schnittstelle kann nicht verwendet werden. Die IDynamicPropertyCmdletProvider-Schnittstelle wird von diesem Anbieter nicht implementiert. + + + Die NavigationCmdletProvider-Methoden werden von diesem Anbieter nicht unterstützt. + + + Anbietermethoden wurden nicht verarbeitet. Die ContainerCmdletProvider-Methoden werden von diesem Anbieter nicht unterstützt. + + + Die Methoden können nicht aufgerufen werden. Die ItemCmdletProvider-Methoden werden von diesem Anbieter nicht unterstützt. + + + Die DriveCmdletProvider-Methoden werden von diesem Anbieter nicht unterstützt. + + + Der Anbietervorgang wurde beendet, da der Anbieter diesen Vorgang nicht unterstützt. + + + Der Anbietervorgang wurde beendet, da der Anbieter den Parameter „Depth“ nicht unterstützt. + + + Die Methode kann nicht aufgerufen werden. Die Methode „Content Seek“ wird von diesem Anbieter nicht unterstützt. + + + Der ClearContent-Vorgang kann nicht ausgeführt werden. Dieser Anbieter unterstützt den Vorgang ClearContent nicht. + + + Der Anbieter unterstützt die Verwendung von Anmeldeinformationen nicht. Führen Sie den Vorgang erneut aus, ohne Anmeldeinformationen anzugeben. + + + Der Dateisystemanbieter unterstützt Anmeldeinformationen nur mit dem Cmdlet „New-PSDrive“. Führen Sie den Vorgang erneut aus, ohne Anmeldeinformationen anzugeben. + + + Die Transaktionen werden vom Anbieter nicht unterstützt. Führen Sie den Vorgang erneut ohne den Parameter „-UseTransaction“ aus. + + + Die Methode kann nicht aufgerufen werden. Der Anbieter unterstützt die Verwendung von Filtern nicht. + + + Das Laufwerk kann nicht erstellt werden. Der Anbieter unterstützt die Verwendung von Anmeldeinformationen nicht. + + + Das Element im Pfad „{0}“ existiert bereits. + + + Das Element kann nicht kopiert werden. Das Element im Pfad „{0}“ ist nicht vorhanden. + + + Das Element im Pfad „{0}“ ist nicht vorhanden. + + + Laufwerk mit einer Ansicht der in einem Sitzungszustand gespeicherten Aliase + + + Laufwerk mit einer Ansicht der Umgebungsvariablen für den Prozess + + + Laufwerk mit einer Ansicht der in einem Sitzungszustand gespeicherten Funktionen + + + Laufwerk mit einer Ansicht der in einem Sitzungszustand gespeicherten Variablen + + + Laufwerk, das dem Pfad des temporären Verzeichnisses für die aktuelle Benutzerperson zugeordnet ist + + + Die Verknüpfung „{0}“ kann nicht erstellt werden, da der Zielwert nicht angegeben wurde. + + + Verweise auf die NULL-Variable geben immer den NULL-Wert zurück. Zuweisungen haben keine Auswirkungen. + + + Maximale Anzahl von Verlaufsobjekten, die in einer Sitzung beibehalten werden + + + Die Funktion kann nicht umbenannt werden, da Funktion „{0}“ schreibgeschützt oder konstant ist. + + + Der Alias kann nicht umbenannt werden, da Alias „{0}“ schreibgeschützt oder konstant ist. + + + Die Variable kann nicht umbenannt werden, da die Variable „{0}“ schreibgeschützt oder konstant ist. + + + Für die lokale Variable „{0}“ können keine Optionen festgelegt werden. Verwenden Sie „New-Variable“, um eine Variable zu erstellen, bei der Optionen festgelegt werden können. + + + Das Cmdlet „{0}“ kann nicht geändert werden, da er schreibgeschützt ist. + + + Die Variable „{0}“ kann nicht entfernt werden, da sie optimiert wurde und nicht entfernt werden kann. Verwenden Sie das Cmdlet „Remove-Variable“ (ohne Aliase), oder dot-sourcen Sie den Befehl, den Sie zum Entfernen der Variablen verwenden. + + + Die Variable „{0}“ kann nicht überschrieben werden, da sie optimiert wurde. Verwenden Sie das Cmdlet „New-Variable“ oder „Set-Variable“ (ohne Aliase), oder dot-sourcen Sie den Befehl, den Sie zum Festlegen der Variablen verwenden. + + + Die Parameter „{0}“ und „{1}“ können nicht zusammen verwendet werden. Geben Sie nur einen Parameter an. + + + Der Tail-Parameter wird derzeit nur für den Dateisystemanbieter unterstützt. + + + Der Alias ist nicht zulässig, da bereits ein Befehl mit dem Namen „{0}“ und dem Befehlstyp „{1}“ vorhanden ist. + + + Software kann nicht ausgeführt werden. Der Zugriff wurde verweigert. + + + „-{0}“ und „-{1}“ schließen sich gegenseitig aus und können nicht gleichzeitig angegeben werden. + + + Der Pfad „{0}“ ist ungültig. Bei Remotekopiervorgängen werden nur absolute Pfade unterstützt. + + + Der Remotepfad „{0}“ kann nicht überprüft werden. + + + Der Vorgang kann nicht ausgeführt werden, da die Sitzung „{0}“ auf „{1}“ festgelegt ist. + + + Der Parameter „{0}“ darf nicht NULL oder leer sein. + + + Sitzungszustandsvariablen + + + Das Ändern oder Erstellen des Bereichs der Variablen „{0}“ in AllScope wird im ConstrainedLanguage-Modus verhindert. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/StringDecoratedStrings.de.resx b/src/System.Management.Automation/resources/de/StringDecoratedStrings.de.resx new file mode 100644 index 00000000000..8fbc8290a0e --- /dev/null +++ b/src/System.Management.Automation/resources/de/StringDecoratedStrings.de.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Für diese Methode wird nur „ANSI“ oder „PlainText“ unterstützt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/SubsystemStrings.de.resx b/src/System.Management.Automation/resources/de/SubsystemStrings.de.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/de/SubsystemStrings.de.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/SuggestionStrings.de.resx b/src/System.Management.Automation/resources/de/SuggestionStrings.de.resx new file mode 100644 index 00000000000..a70330a1b83 --- /dev/null +++ b/src/System.Management.Automation/resources/de/SuggestionStrings.de.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 + + + Der Befehl „{0}“ wurde nicht gefunden, ist aber am aktuellen Speicherort vorhanden. +PowerShell lädt standardmäßig keine Befehle vom aktuellen Speicherort (siehe „Get-Help about_Command_Precedence“). + +Wenn Sie diesem Befehl vertrauen, führen Sie stattdessen den folgenden Befehl aus: + + + Die ähnlichsten Befehle sind: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/TabCompletionStrings.de.resx b/src/System.Management.Automation/resources/de/TabCompletionStrings.de.resx new file mode 100644 index 00000000000..399531801ea --- /dev/null +++ b/src/System.Management.Automation/resources/de/TabCompletionStrings.de.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Das Ergebnis der TAB-Vervollständigung kann nicht ordnungsgemäß deserialisiert werden, da der Remotesitzungsbereich keine TypeTable-Instanz enthält. + + + Auf Eigenschaften einer NULL-Instanz vom Typ CompletionResult kann nicht zugegriffen werden. + + + Bitweises NOT + + + Logisches "Nicht" Negiert die darauf folgende Anweisung. + + + Gleich – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die gleich dem rechten Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand gleich dem rechten Operand ist. + + + Gleich – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die gleich dem rechten Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand gleich dem rechten Operand ist. + + + Gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die gleich dem rechten Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand gleich dem rechten Operand ist. + + + Ungleich – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Ungleich – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Ungleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Größer als oder gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die größer oder gleich dem rechten Operanden sind. Andernfalls gibt er TRUE zurück, wenn der linke Operand größer oder gleich dem rechten Operanden ist. + + + Größer als oder gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die größer oder gleich dem rechten Operanden sind. Andernfalls gibt er TRUE zurück, wenn der linke Operand größer oder gleich dem rechten Operanden ist. + + + Größer als oder gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die größer oder gleich dem rechten Operanden sind. Andernfalls gibt er TRUE zurück, wenn der linke Operand größer oder gleich dem rechten Operanden ist. + + + Größer als – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die größer als der rechte Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand größer als der rechte Operand ist. + + + Größer als – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die größer als der rechte Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand größer als der rechte Operand ist. + + + Größer als – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die größer als der rechte Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand größer als der rechte Operand ist. + + + Kleiner als – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die kleiner als der rechte Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand kleiner als der rechte Operand ist. + + + Kleiner als – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die kleiner als der rechte Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand kleiner als der rechte Operand ist. + + + Kleiner als – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, werden Werte aus der Auflistung zurückgegeben, die kleiner als der rechte Operand sind. Andernfalls wird TRUE zurückgegeben, wenn der linke Operand kleiner als der rechte Operand ist. + + + Kleiner als oder gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die kleiner oder gleich dem rechten Operanden sind. Andernfalls gibt er TRUE zurück, wenn der linke Operand kleiner oder gleich dem rechten Operanden ist. + + + Kleiner als oder gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die kleiner oder gleich dem rechten Operanden sind. Andernfalls gibt er TRUE zurück, wenn der linke Operand kleiner oder gleich dem rechten Operanden ist. + + + Kleiner als oder gleich – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die kleiner oder gleich dem rechten Operanden sind. Andernfalls gibt er TRUE zurück, wenn der linke Operand kleiner oder gleich dem rechten Operanden ist. + + + Platzhalterabgleichsoperator – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand mit dem rechten Operanden übereinstimmt. + + + Platzhalterabgleichsoperator – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand mit dem rechten Operanden übereinstimmt. + + + Platzhalterabgleichsoperator – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand mit dem rechten Operanden übereinstimmt. + + + Platzhalterabgleichsoperator – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Platzhalterabgleichsoperator – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Platzhalterabgleichsoperator – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Operator für den Abgleich regulärer Ausdrücke – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand mit dem rechten Operanden übereinstimmt. + + + Operator für den Abgleich regulärer Ausdrücke – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand mit dem rechten Operanden übereinstimmt. + + + Operator für den Abgleich regulärer Ausdrücke – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand mit dem rechten Operanden übereinstimmt. + + + Operator für den Abgleich regulärer Ausdrücke – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Operator für den Abgleich regulärer Ausdrücke – Groß-/Kleinschreibung nicht beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Operator für den Abgleich regulärer Ausdrücke – Groß-/Kleinschreibung beachten. Wenn der linke Operand eine Auflistung ist, gibt dieser Operator Werte aus der Auflistung zurück, die dem rechten Operanden nicht entsprechen. Andernfalls gibt er TRUE zurück, wenn der linke Operand nicht mit dem rechten Operanden übereinstimmt. + + + Ersetzungsoperator – Groß-/Kleinschreibung nicht beachten. Ändert den linken Operanden. Beispiel: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Ersetzungsoperator – Groß-/Kleinschreibung nicht beachten. Ändert den linken Operanden. Beispiel: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Ersetzungsoperator – Groß-/Kleinschreibung beachten. Ändert den linken Operanden. Beispiel: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (rechter Operand) genau mit mindestens einem der Werte im linken Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (rechter Operand) genau mit mindestens einem der Werte im linken Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung beachten. Gibt nur TRUE zurück, wenn der Testwert (rechter Operand) genau mit mindestens einem der Werte im linken Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (rechter Operand) genau mit keinem der Werte im linken Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (rechter Operand) genau mit keinem der Werte im linken Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung beachten. Gibt TRUE zurück, wenn der Testwert (rechter Operand) genau mit keinem der Werte im linken Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (linker Operand) genau mit mindestens einem der Werte im rechten Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (linker Operand) genau mit mindestens einem der Werte im rechten Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung beachten. Gibt TRUE zurück, wenn der Testwert (linker Operand) genau mit mindestens einem der Werte im rechten Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung beachten. Gibt TRUE zurück, wenn der Testwert (linker Operand) genau mit keinem der Werte im rechten Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung nicht beachten. Gibt TRUE zurück, wenn der Testwert (linker Operand) genau mit keinem der Werte im rechten Operanden übereinstimmt. + + + Enthaltenheitsoperator – Groß-/Kleinschreibung beachten. Gibt TRUE zurück, wenn der Testwert (linker Operand) genau mit keinem der Werte im rechten Operanden übereinstimmt. + + + Teilen – Groß-/Kleinschreibung nicht beachten. Teilt eine oder mehrere Zeichenfolgen in Teilzeichenfolgen auf. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Teilen – Groß-/Kleinschreibung nicht beachten. Teilt eine oder mehrere Zeichenfolgen in Teilzeichenfolgen auf. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split – Groß-/Kleinschreibung beachten. Teilt eine oder mehrere Zeichenfolgen in Teilzeichenfolgen auf. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Gibt TRUE zurück, wenn der linke Operand keine Instanz des angegebenen .NET Framework-Typs (rechter Operand) ist. + + + Gibt TRUE zurück, wenn der linke Operand eine Instanz des angegebenen .NET Framework-Typs (rechter Operand) ist. + + + Konvertiert den linken Operanden in den angegebenen .NET Framework-Typ (rechter Operand). + + + Formatiert Zeichenfolgen mithilfe der Formatmethode von Zeichenfolgenobjekten. + + + Logisches "Und" Gibt TRUE zurück, wenn beide Anweisungen TRUE sind. + + + Bitweises AND + + + Logisches "Oder" TRUE, wenn eine oder beide Anweisungen TRUE sind. + + + Bitweises OR (inklusiv) + + + Logisches XODER. Gibt TRUE zurück, wenn eine der Anweisungen TRUE und die andere FALSE ist. + + + Bitweises OR (exklusiv) + + + Verknüpfen – mehrere Zeichenfolgen zu einer einzelnen Zeichenfolge kombinieren. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Bitoperator „Nach links verschieben“. Fügt an der ganz rechten Bitposition eine Null ein. + + + Bitoperator „Nach rechts verschieben“. Fügt an der ganz linken Bitposition eine Null ein. Bei vorzeichenbehafteten Werten bleibt das Vorzeichenbit erhalten. + + + [string] +Gibt den Namen der Eigenschaft an. + + + [string] +Gibt den Namen der Eigenschaft an. + + + [scriptblock] +Ein Skriptblock zum Berechnen des Werts der neuen Eigenschaft. + + + [string] +Gibt an, wie die Werte in einer Spalte angezeigt werden. +Gültige Werte sind „left“, „center“ oder „right“. + + + [string] +Gibt eine Formatzeichenfolge an, die definiert, wie der Wert für die Ausgabe formatiert wird. + + + [int] +Gibt die maximale Spaltenbreite in einer Tabelle an, wenn der Wert angezeigt wird. +Der Wert muss größer als 0 sein. + + + [int] +Der Tiefenschlüssel gibt die Tiefe der Erweiterung pro Eigenschaft an. + + + [bool] +Gibt die Sortierreihenfolge für eine oder mehrere Eigenschaften an. + + + [bool] +Gibt die Sortierreihenfolge für eine oder mehrere Eigenschaften an. + + + [String[]] +Gibt die Protokollnamen an, aus denen Ereignisse abgerufen werden sollen. +Unterstützt Platzhalter. + + + [String[]] +Gibt die Ereignisprotokollanbieter an, von denen Ereignisse abgerufen werden sollen. +Unterstützt Platzhalter. + + + [String[]] +Gibt Dateipfade zu Protokolldateien an, aus denen Ereignisse abgerufen werden sollen. +Gültige Dateiformate sind .etl, .evt und .evtx + + + [Long[]] +Wählt Ereignisse mit der angegebenen Schlüsselwortbitmaske aus. +Im Folgenden sind die Standardschlüsselwörter aufgeführt: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Wählt Ereignisse mit den angegebenen Ereignis-IDs aus. + + + [int[]] +Wählt Ereignisse mit den angegebenen Protokollebenen aus. +Die folgenden Protokollebenen sind gültig: +1: Kritisch +2: Fehler +3: Warnung +4: Informational +5: Ausführlich + + + [datetime] +Wählt Ereignisse aus, die nach dem angegebenen Datum und der angegebenen Uhrzeit erstellt wurden. + + + [datetime] +Wählt Ereignisse aus, die vor dem angegebenen Datum und der angegebenen Uhrzeit erstellt wurden. + + + [string] +Wählt Ereignisse aus, die vom angegebenen Benutzer generiert wurden. +Dies kann entweder eine Zeichenfolgendarstellung einer SID oder eine Domäne und ein Benutzername im Format DOMÄNE\BENUTZERNAME oder USERNAME@DOMAIN sein. + + + [string[]] +Wählt Ereignisse mit einem der angegebenen Werte im Abschnitt „EventData“ aus. + + + [hashtable] +Schließt Ereignisse aus, die mit den in der Hashtabelle angegebenen Werten übereinstimmen. + + + [string] oder [hashtable] +Gibt ein Array von PowerShell-Modulen an, die das Skript erfordert. +Jedes Element kann entweder eine Zeichenfolge mit dem Modulnamen als Wert oder eine Hashtabelle mit den folgenden Schlüsseln sein: +Name: Der Name des Moduls +GUID: GUID des Moduls +Eine der folgenden Optionen: +ModuleVersion: Gibt eine minimal zulässige Version des Moduls an. +RequiredVersion: Gibt eine exakte, erforderliche Version des Moduls an. +MaximumVersion: Gibt die maximal zulässige Version des Moduls an. + + + [string] +Gibt eine PowerShell-Edition an, die das Skript erfordert. +Gültige Werte sind „Core“ und „Desktop“. + + + [switch] +Gibt an, dass PowerShell unter Windows als Admin ausgeführt werden muss. +Dies muss der letzte Parameter in der Zeile mit der #requires-Anweisung sein. + + + [version] +Gibt die mindestens erforderliche PowerShell-Version für das Skript an. + + + Gibt an, dass für die Ausführung des Skripts PowerShell 7+ erforderlich ist. + + + Gibt an, dass für die Ausführung des Skripts Windows PowerShell 5.1 erforderlich ist. + + + [string] +Obligatorisch Gibt den Namen des Moduls an. + + + [string] +Optional Gibt den GUID des Moduls an. + + + [string] +Gibt eine minimal zulässige Version des Moduls an. + + + [string] +Gibt eine exakte, erforderliche Version des Moduls an. + + + [string] +Gibt die maximal zulässige Version des Moduls an. + + + Eine kurze Beschreibung der Funktion oder des Skripts. +Dieses Schlüsselwort kann nur einmal für jeden Inhalt verwendet werden. + + + Eine detaillierte Beschreibung der Funktion oder des Skripts. +Dieses Schlüsselwort kann nur einmal für jeden Inhalt verwendet werden. + + + .PARAMETER <Parameter-Name> +Die Beschreibung eines Parameters. +Fügen Sie für jeden Parameter in der Funktions- oder Skriptsyntax ein .PARAMETER-Schlüsselwort hinzu. + + + Ein Beispielbefehl, der die Funktion oder das Skript verwendet, optional gefolgt von einer Beispielausgabe und einer Beschreibung. +Wiederholen Sie dieses Schlüsselwort für jedes Beispiel. + + + Die .NET-Typen von Objekten, die an die Funktion oder das Skript weitergeleitet werden können. +Sie können auch eine Beschreibung der Eingabeobjekte einschließen. + + + Der .NET-Typ der Objekte, die vom Cmdlet zurückgegeben werden. +Sie können auch eine Beschreibung der zurückgegebenen Objekte einschließen. + + + Zusätzliche Informationen zur Funktion oder zum Skript. + + + Der Name eines verwandten Themas. +Wiederholen Sie das Schlüsselwort .LINK für jedes verwandte Thema. +Der Inhalt des .LINK-Schlüsselworts kann auch einen URI zu einer Onlineversion des Hilfethemas enthalten. + + + Der Name der Technologie oder des Features, die bzw. das von der Funktion oder dem Skript verwendet wird oder mit dem bzw. der es verknüpft ist. + + + Der Name der Benutzerrolle für das Hilfethema. + + + Die Schlüsselwörter, die die beabsichtigte Verwendung der Funktion beschreiben. + + + .FORWARDHELPTARGETNAME <Command-Name> +Leitet zum Hilfethema für den angegebenen Befehl um. + + + .FORWARDHELPCATEGORY <Category> +Dieser Befehl gibt die Hilfekategorie des Elements in ForwardHelpTargetName an. + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Gibt eine Sitzung an, die das Hilfethema enthält. +Geben Sie eine Variable ein, die ein PSSession-Objekt enthält. + + + .EXTERNALHELP <XML Help File> +Das Schlüsselwort .ExternalHelp ist erforderlich, wenn eine Funktion oder ein Skript in XML-Dateien dokumentiert ist. + + + Gibt den Pfad zu einer .NET-Assembly an, die geladen werden soll. + +using assembly <.NET-assembly-path> + + + Gibt ein PowerShell-Modul an, aus dem Klassen geladen werden. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Gibt einen .NET-Namespace an, aus dem Typen aufgelöst werden sollen, oder einen Namespacealias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Gibt einen Alias für einen .NET-Typ an. + +using type <AliasName> = <.NET-type> + + + Eine normale Zeichenfolge. + + + Eine Zeichenfolge, die nicht erweiterte Verweise auf Umgebungsvariablen enthält, die beim Abrufen des Werts erweitert werden. + + + Binärdaten in beliebiger Form. + + + Eine 32-Bit-Binärzahl. + + + Ein Array der Zeichenfolgen. + + + Eine 64-Bit-Binärzahl. + + + Ein nicht unterstützter Registrierungsdatentyp. + + + ',' – Komma + + + ', ' – Komma-Leerzeichen + + + ';' – Semikolon + + + '; ' – Semikolon-Leerzeichen + + + {0} – Zeilenumbruch + + + '-' – Gedankenstrich + + + ' ' – Leerzeichen + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/TransactionStrings.de.resx b/src/System.Management.Automation/resources/de/TransactionStrings.de.resx new file mode 100644 index 00000000000..d1b74555de0 --- /dev/null +++ b/src/System.Management.Automation/resources/de/TransactionStrings.de.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Die Transaktion kann nicht verwendet werden. Es ist keine Transaktion aktiv. + + + Die Transaktion kann nicht committet werden. Es ist keine Transaktion aktiv. + + + Die Transaktion kann nicht zurückgesetzt werden, da keine aktive Transaktion vorhanden ist. + + + Die Transaktion kann nicht zurückgesetzt werden. Für die Transaktion wurde bereits ein Commit ausgeführt. + + + Die Transaktion kann nicht committet werden. Für die Transaktion wurde bereits ein Commit ausgeführt. + + + Die Transaktion kann nicht committet werden. Die Transaktion wurde zurückgesetzt, oder das Zeitlimit wurde überschritten. + + + Die Transaktion kann nicht zurückgesetzt werden. Die Transaktion wurde bereits zurückgesetzt, oder das Zeitlimit wurde überschritten. + + + Die aktive Transaktion kann nicht festgelegt werden. Es wurde keine Transaktion erstellt. + + + Die aktive Transaktion kann nicht festgelegt werden. Die aktive Transaktion wurde zurückgesetzt, oder das Zeitlimit wurde überschritten. + + + Für dieses Cmdlet ist eine aktive Transaktion erforderlich. Die aktuelle Transaktion wurde bereits übernommen oder zurückgesetzt. + + + Für dieses Cmdlet ist eine Transaktion erforderlich. Führen Sie den Befehl erneut mit dem -UseTransaction-Parameter aus. + + + Die Transaktion kann nicht verwendet werden. Es wurde keine Transaktion gestartet. + + + Die Transaktion kann nicht verwendet werden. Für die Transaktion wurde ein Commit ausgeführt. + + + Die Transaktion kann nicht verwendet werden. Die Transaktion wurde zurückgesetzt, oder das Zeitlimit wurde überschritten. + + + Die Transaktion kann nicht verwendet werden. Das Zeitlimit für die Transaktion wurde überschritten. + + + Die Basistransaktion wurde nicht festgelegt. + + + Die Basistransaktion ist nicht aktiv. + + + Die Basistransaktion kann nicht festgelegt werden, nachdem andere Transaktionen erstellt wurden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/TypesXmlStrings.de.resx b/src/System.Management.Automation/resources/de/TypesXmlStrings.de.resx new file mode 100644 index 00000000000..2a91071d618 --- /dev/null +++ b/src/System.Management.Automation/resources/de/TypesXmlStrings.de.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}): Fehler: {3} + + + {0}, {1}({2}) : Fehler im Typ „{3}“: {4} + + + Der Knoten „{0}“ darf nur einmal unter „{1}“ auftreten. Der übergeordnete Knoten „{1}“ wird ignoriert. + + + Der Knoten {0} ist nicht zulässig. Die folgenden Knoten sind zulässig: {1}. + + + Der Knoten „{0}“ darf keinen inneren Text enthalten. + + + Der Knoten „{0}“ sollte einen inneren Text aufweisen. + + + Der Knoten „{0}“ wurde nicht gefunden. Er sollte nur einmal unter „{1}“ auftreten. Der übergeordnete Knoten „{1}“ wird ignoriert. + + + Der Knoten „Typ“ muss „Mitglieder“, „TypeConverters“ oder „TypeAdapters“ aufweisen. + + + Aufgrund einer Ausnahme kann keine Instanz des Typkonverters für den Typ {0} erstellt werden: {1}. + + + PowerShell kann aufgrund der folgenden Ausnahme keine Instanz des Typadapters für den Typ {0} erstellen: {1}. + + + Der angepasste Typ „{0}“ ist ungültig. + + + Der TypeConverter wurde ignoriert, da er bereits auftritt. + + + Der TypeAdapter wurde ignoriert, da er bereits auftritt. + + + Der Typ „{0}“ muss entweder TypeConverter oder PSTypeConverter sein. + + + Der Typ „{0}“ muss ein PSPropertyAdapter sein. + + + Das Mitglied {0} ist bereits vorhanden. + + + Der folgende Mitgliedsname ist reserviert: {0} + + + Ausnahme: {0} + + + ScriptProperty sollte einen Getter oder Setter aufweisen. + + + Die CodeProperty sollte einen Getter oder Setter aufweisen. + + + {0}, {1}: {2} + + + Der Wert sollte entweder TRUE oder FALSE anstelle von {0}sein. + + + Der Knoten „{0}“ darf nicht das Attribut „{1}“ aufweisen. + + + {0}, {1}: Die Datei wurde nicht gefunden. + + + {0}, {1}: Die Datei wurde übersprungen, da sie bereits von {2} geladen wurde. + + + Der Registrierungsschlüssel konnte nicht gefunden werden: {0}{1}. {2} wird zum Laden der Konfigurationsdateien verwendet. + + + Der im Registrierungsschlüssel angegebene Pfad {0} wurde nicht gefunden: {1}{2}. {3} wird zum Laden der Konfigurationsdateien verwendet. + + + {0}, {1}: Die Datei wurde übersprungen, da sie nicht die Dateinamenerweiterung ps1xml aufweist. + + + {0}, {1}: Die Datei wurde aufgrund der folgenden Validierungsausnahme übersprungen: {2}. + + + Das Mitglied „{0}“ muss eine Notiz sein. + + + Hinweis „{0}“ kann nicht konvertiert werden:„{1}“ + + + Verwenden Sie hier nicht das Mitglied „{0}“. + + + Das Mitglied „{0}" muss den Typ „{1}“ aufweisen. + + + „{0}“ muss vorhanden sein, wenn „{1}“ „{2}“ und „{3}“ „{4}“ ist. + + + Ein vorheriger Fehler hat dazu geführt, dass alle Serialisierungseinstellungen ignoriert wurden. + + + „{0}“ ist kein Standardmitglied und wird ignoriert. + + + Der {0} Pfad ist nicht vollqualifiziert. Geben Sie einen vollqualifizierten Dateipfad an. + + + Die TypeTable kann nicht aktualisiert werden, da die TypeTable möglicherweise außerhalb des Runspaces erstellt wurde. + + + Fehler beim Laden der TypeTable. Suchen Sie in der Eigenschaft Fehler nach detaillierten Fehlermeldungen. + + + Fehler in TypeData „{0}“: {1} + + + „{0}“ muss einen Wert für die Eigenschaft „{1}“ aufweisen. + + + „{0}“ darf nicht NULL oder eine leere Zeichenfolge in der Eigenschaft „{1}“ enthalten. + + + Der Typ „{0}“ wurde nicht gefunden. Der Wert des Typnamens muss der vollständige Name des Typs sein. Überprüfen Sie den Typnamen, und führen Sie den Befehl erneut aus. + + + TypeData muss über „Mitglieder“, „TypeConverters“, „TypeAdapters“ oder „StandardMembers“ verfügen. + + + Eine freigegebene Typtabelle kann nicht mit mehr als einem Eintrag aktualisiert werden. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/VerbDescriptionStrings.de.resx b/src/System.Management.Automation/resources/de/VerbDescriptionStrings.de.resx new file mode 100644 index 00000000000..f731085cabe --- /dev/null +++ b/src/System.Management.Automation/resources/de/VerbDescriptionStrings.de.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Fügt einem Container eine Ressource hinzu oder fügt ein Element an ein anderes Element an + + + Hiermit wird der Zustand einer Ressource oder eines Prozesses bestätigt oder akzeptiert + + + Hiermit wird der Zustand einer Ressource bestätigt + + + Hiermit werden Daten durch Replikation gespeichert + + + Schränkt den Zugriff auf eine Ressource ein + + + Hiermit wird ein Artefakt (in der Regel eine Binärdatei oder ein Dokument) aus einer Gruppe von Eingabedateien erstellt (in der Regel Quellcode oder deklarative Dokumente) + + + Erstellt eine Momentaufnahme des aktuellen Zustands der Daten oder ihrer Konfiguration + + + Hiermit werden alle Ressourcen in einem Container entfernt, der Container selbst wird jedoch nicht gelöscht + + + Ändert den Zustand einer Ressource, damit sie nicht zugänglich, verfügbar oder verwendbar ist + + + Vergleicht und bewertet die Daten einer Ressource mit den Daten einer anderen Ressource + + + Schließt einen Vorgang ab + + + Komprimiert die Daten einer Ressource + + + Hiermit wird der Zustand einer Ressource oder eines Prozesses anerkannt, verifiziert oder validiert + + + Stelle eine Verbindung zwischen einer Quelle und einem Ziel her + + + Ändert die Daten von einer Darstellung in eine andere, wenn das Cmdlet die bidirektionale Konvertierung unterstützt oder wenn das Cmdlet die Konvertierung zwischen mehreren Datentypen unterstützt + + + Hiermit wird ein primärer Eingabetyp (das Substantiv des Cmdlets gibt die Eingabe an) in einen oder mehrere unterstützte Ausgabetypen konvertiert + + + Wandelt einen oder mehrere Eingabetypen in einen primären Ausgabetyp (das Cmdlet-Nomen gibt den Ausgabetyp an) + + + Kopiert eine Ressource in einen anderen Namen oder in einen anderen Container + + + Untersucht eine Ressource, um Probleme im Betrieb zu diagnostizieren + + + Hiermit wird der Zustand einer Ressource oder eines Prozesses nicht zugelassen, abgelehnt, blockiert oder verweigert + + + Hiermit wird eine Anwendung, Website oder Lösung an ein oder mehrere Remoteziele gesendet, sodass ein Endbenutzer dieser Lösung nach Abschluss der Bereitstellung darauf zugreifen kann + + + Versetzt eine Ressource in einen nicht verfügbaren oder inaktiven Zustand + + + Trennt die Verbindung zwischen einer Quelle und einem Ziel + + + Hiermit wird eine angegebene Entität von einem Speicherort getrennt + + + Ändert vorhandene Daten durch Hinzufügen oder Entfernen von Inhalten + + + Konfiguriert eine Ressource in einem verfügbaren oder aktiven Zustand + + + Hiermit wird eine Aktion angegeben, die dem Benutzer das Wechseln zu einer Ressource ermöglicht + + + Legt die aktuelle Umgebung oder den aktuellen Kontext auf den zuletzt verwendeten Kontext fest + + + Hiermit wird der ursprüngliche Zustand der Daten einer komprimierten Ressource wiederhergestellt + + + Kapselt die primäre Eingabe in einen persistenten Datenspeicher, z. B. eine Datei, oder in ein Austauschformat + + + Hiermit wird in einem unbekannten, impliziten, optionalen oder angegebenen Container nach einem Objekt gesucht + + + Ordnet Objekte in einem angegebenen Formular oder Layout an + + + Gibt eine Aktion an, die eine Ressource abruft + + + Ermöglicht den Zugriff auf eine Ressource + + + Hiermit werden eine oder mehrere Ressourcen an- oder zugeordnet + + + Bewirkt, dass eine Ressource nicht mehr auffindbar ist + + + Erstellt eine Ressource aus Daten, die in einem persistenten Datenspeicher (z. B. einer Datei) oder in einem Austauschformat gespeichert sind + + + Bereitet eine Ressource für die Verwendung vor und legt sie auf einen Standardzustand fest + + + Platziert eine Ressource an einem Speicherort und initialisiert sie optional + + + Führt eine Aktion aus, z. B. Ausführen eines Befehls oder einer Methode + + + Kombiniert Ressourcen in einer Ressource + + + Wendet Einschränkungen auf eine Ressource an + + + Schützt eine Ressource + + + Hiermit werden Ressourcen ermittelt, die von einem angegebenen Vorgang genutzt werden, oder Statistiken über eine Ressource abgerufen + + + Erstellt eine einzelne Ressource aus mehreren Ressourcen + + + Fügt eine benannte Entität an einen Speicherort an + + + Verschiebt eine Ressource von einem Speicherort an einen anderen + + + Erstellt eine Ressource + + + Ändert den Zustand einer Ressource, um sie zugänglich, verfügbar oder verwendbar zu machen + + + Erhöht die Effektivität einer Ressource + + + Sendet Daten aus der Umgebung + + + Testverb verwenden + + + Entfernt ein Element vom oberen Ende des Stapels + + + Schützt eine Ressource vor Angriffen oder Verlust + + + Hiermit wird eine Ressource für andere zugänglich gemacht + + + Fügt ein Element dem oberen Ende des Stapels hinzu + + + Ruft Informationen aus einer Quelle ab + + + Akzeptiert Informationen, die von einer Quelle gesendet werden + + + Setzt eine Ressource auf den Zustand zurück, der rückgängig gemacht wurde + + + Hiermit wird ein Eintrag für eine Ressource in einem Repository erstellt, z. B. in einer Datenbank + + + Hiermit wird eine Ressource aus einem Container gelöscht + + + Ändert den Namen einer Ressource + + + Hiermit wird ein verwendbarer Zustand einer Ressource wiederhergestellt + + + Fragt nach einer Ressource oder nach Berechtigungen + + + Legt eine Ressource wieder auf ihren ursprünglichen Zustand fest + + + Hiermit wird die Größe einer Ressource geändert + + + Ordnet eine Kurzdarstellung einer Ressource einer ausführlicheren Darstellung zu + + + Hiermit wird ein Vorgang beendet und anschließend wieder gestartet + + + Legt eine Ressource auf einen vordefinierten Zustand fest, z. B. einen Zustand, der von Prüfpunkt festgelegt wird + + + Hiermit wird ein angehaltener Vorgang gestartet + + + Gibt eine Aktion an, die keinen Zugriff auf eine Ressource zulässt + + + Behält Daten bei, um Verlust zu vermeiden + + + Hiermit wird ein Verweis auf eine Ressource in einem Container erstellt + + + Hiermit wird eine Ressource in einem Container gesucht + + + Hiermit werden Informationen an ein Ziel gesendet + + + Ersetzt Daten in einer vorhandenen Ressource oder erstellt eine Ressource, die einige Daten enthält + + + Macht eine Ressource für den Benutzer sichtbar + + + Stellt sicher, dass sich mindestens zwei Ressourcen im selben Zustand befinden + + + Umgeht eine oder mehrere Ressourcen oder Punkte in einer Sequenz + + + Hiermit werden Teile einer Ressource getrennt + + + Initiiert einen Vorgang + + + Hiermit wird in einer Sequenz zum nächsten Punkt oder zur nächsten Ressource gewechselt + + + Beendet eine Aktivität + + + Hiermit wird eine Ressource zur Genehmigung vorgelegt + + + Hiermit wird eine Aktivität angehalten + + + Gibt eine Aktion an, die zwischen zwei Ressourcen wechselt, z. B. um zwischen zwei Standorten, Zuständigkeiten oder Zuständen zu wechseln + + + Hiermit wird die Funktion oder Konsistenz einer Ressource überprüft + + + Verfolgt die Aktivitäten einer Ressource nach + + + Entfernt Einschränkungen für eine Ressource + + + Hiermit wird eine Ressource auf den vorherigen Zustand zurückgesetzt + + + Entfernt eine Ressource von einem angegebenen Speicherort + + + Gibt eine gesperrte Ressource frei + + + Entfernt Sicherheitsvorkehrungen aus einer Ressource, die hinzugefügt wurden, um einen Angriff oder Verlust zu verhindern + + + Hiermit wird eine Ressource für andere unzugänglich gemacht + + + Entfernt den Eintrag für eine Ressource aus einem Repository + + + Aktualisiert eine Ressource, um ihren Zustand, ihre Genauigkeit, Konformität oder Konformität auf dem neuesten Stand zu halten + + + Hiermit wird eine Ressource allein oder zusammen mit anderen Ressourcen für eine Aktion verwendet + + + Hält einen Vorgang an, bis ein angegebenes Ereignis auftritt + + + Überprüft oder überwacht eine Ressource kontinuierlich auf Änderungen + + + Fügt einem Ziel Informationen hinzu + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/de/WildcardPatternStrings.de.resx b/src/System.Management.Automation/resources/de/WildcardPatternStrings.de.resx new file mode 100644 index 00000000000..0e604875f26 --- /dev/null +++ b/src/System.Management.Automation/resources/de/WildcardPatternStrings.de.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 + + + Das angegebene Platzhalterzeichenmuster ist ungültig: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/Authenticode.es.resx b/src/System.Management.Automation/resources/es/Authenticode.es.resx new file mode 100644 index 00000000000..08dee512f59 --- /dev/null +++ b/src/System.Management.Automation/resources/es/Authenticode.es.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 + + + No se puede cargar el archivo {0} porque optó por no ejecutar este software ahora. + + + No se puede cargar el archivo {0} porque optó por no ejecutar nunca software desde este publicador. + + + El archivo {0} está publicado por {1}. Este editor no es de confianza explícita en el sistema. El script no se ejecutará en el sistema. Para obtener más información, ejecute el comando "get-help about_signing". + + + El archivo {0} no se puede cargar porque la ejecución de scripts está deshabilitada en este sistema. Para obtener más información, consulte about_Execution_Policies en https://go.microsoft.com/fwlink/?LinkID=135170. + + + El archivo {0} no se puede cargar {1}. + + + No se puede cargar el archivo {0} porque su operación está bloqueada por directivas de restricción de software, como las creadas mediante directiva de grupo. + + + No se puede cargar el archivo {0} porque no se pudo leer su contenido. + + + No se puede firmar el código. El certificado especificado no es adecuado para la firma de código. + + + No se puede firmar el código. La dirección URL del servidor de marca de tiempo debe ser completa y tener el formato http://<server url> o https://<server url>. + + + No se puede firmar el código. No se admite el algoritmo hash. + + + ¿Desea ejecutar software de este editor que no es de confianza? + + + El archivo {0} está publicado por {1} y no es de confianza en su sistema. Ejecute solo scripts de editores de confianza. + + + Un editor desconocido publica el software {0}. Se recomienda no ejecutar este software. + + + Advertencia de seguridad + + + Ejecute solo los scripts en los que confíe. Aunque los scripts de Internet pueden ser útiles, este script puede dañar el equipo. Si confía en este script, use el cmdlet Unblock-File para permitir que se ejecute sin mostrar este mensaje de advertencia. ¿Desea ejecutar {0}? + + + Nunc&a ejecutar + + + No ejecute el script de este publicador ahora y no me pida que lo ejecute en el futuro. Los intentos futuros de ejecutar este script producirán un error silencioso. + + + &No ejecutar + + + No ejecute ahora el script de este editor y siga preguntándome si deseo ejecutarlo en el futuro. + + + &Ejecutar una vez + + + Ejecute el script de este editor ahora y siga preguntándome si deseo ejecutar este script en el futuro. + + + &Ejecutar siempre + + + Ejecute ahora el script de este publicador y no me pida que lo ejecute en el futuro. + + + &Suspender + + + Ponga en pausa la canalización actual y vuelva al símbolo del sistema. Escriba salir para reanudar la operación cuando haya terminado. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/AuthorizationManagerBase.es.resx b/src/System.Management.Automation/resources/es/AuthorizationManagerBase.es.resx new file mode 100644 index 00000000000..1c75bcdbf33 --- /dev/null +++ b/src/System.Management.Automation/resources/es/AuthorizationManagerBase.es.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 + + + Error en la comprobación de AuthorizationManager. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/AutomationExceptions.es.resx b/src/System.Management.Automation/resources/es/AutomationExceptions.es.resx new file mode 100644 index 00000000000..18d6f475628 --- /dev/null +++ b/src/System.Management.Automation/resources/es/AutomationExceptions.es.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 argument because the value of argument "{0}" is not valid. Change the value of the "{0}" argument and run the operation again. + + + Cannot process argument because the value of parameter "{0}" is not valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). Change the value of the "{0}" parameter and run the operation again. + + + Cannot process argument because the value of argument "{0}" is null. Change the value of argument "{0}" to a non-null value. + + + Cannot process argument because the value of argument "{0}" is out of range. Change argument "{0}" to a value that is within range. + + + Cannot perform operation because operation "{0}" is not valid. Remove operation "{0}", or investigate why it is not valid. + + + Cannot perform operation because operation "{0}" is not implemented. + + + Cannot perform operation because operation "{0}" is not supported. + + + Cannot perform operation because object "{0}" has already been disposed. + + + The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause. + + + The script block cannot be converted because it contains more than one clause. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + An empty script block cannot be converted. Verify that the script block contains exactly one pipeline or command. + + + Only a script block that contains exactly one pipeline or command can be converted. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + A script block that contains a top-level trap statement cannot be converted. + + + Cannot generate a PowerShell object for a ScriptBlock dereferencing variables undeclared in the param(...) block. Name of undeclared variable: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating non-constant expressions. Non-constant expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions. Dynamic expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock that tries to pass other script blocks inside argument values. + + + Cannot generate a PowerShell object for a ScriptBlock which invokes pipelines, commands or functions to evaluate arguments of the main pipeline. + + + Cannot generate a PowerShell object for a ScriptBlock that uses dot sourcing. + + + Cannot generate a PowerShell object for a ScriptBlock that invokes other script blocks. + + + The script block cannot be converted to a PowerShell object because it contains forbidden redirection operators. + + + Cannot generate a PowerShell object for a ScriptBlock that does not have an associated operation context. + + + The command was stopped by the user. + + + Object "{0}" is the wrong type to return from the dynamicparam block. The dynamicparam block must return either $null, or an object with type [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + The script block cannot be converted to an open generic type. Define an appropriate closed generic type, and then retry. + + + Cannot generate a PowerShell object for a ScriptBlock that starts a pipeline with an expression. + + + The value of the using variable '$using:{0}' cannot be retrieved because it has not been set in the local session. + + + Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CatalogStrings.es.resx b/src/System.Management.Automation/resources/es/CatalogStrings.es.resx new file mode 100644 index 00000000000..5c5021fb2b9 --- /dev/null +++ b/src/System.Management.Automation/resources/es/CatalogStrings.es.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede generar el archivo de definición del catálogo. + + + Agregando el archivo "{0}" al catálogo. La ruta de acceso relativa del archivo en el catálogo es "{1}". + + + Omitiendo la validación del archivo {0} del catálogo. + + + Se encontró el archivo {0} en el catálogo con un hash de {1}. + + + Las rutas del catálogo contienen varios archivos con la misma ruta relativa {0}. + + + Se encontró el archivo {0} en el disco con un hash de {1}. + + + Omitiendo la validación del archivo {0} de la ruta. + + + No se puede obtener un controlador para un contexto de administrador de catálogo para un algoritmo hash determinado {0}. + + + No se puede crear el hash para el archivo {0}. + + + No se puede abrir el archivo de catálogo {0}. + + + La versión del catálogo no es válida. Solo se admite la versión del catálogo {0} y la versión {1}. + + + No se puede abrir el archivo de definición del catálogo. + + + Se encontraron varias entradas del miembro de archivo {0} en el catálogo. + + + No se puede encontrar el nombre de archivo o la ruta de acceso del miembro del catálogo {0}. + + + No se encuentra el archivo {0} para el hash. + + + No se puede leer el archivo {0} para calcular su hash. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CimInstanceTypeAdapterResources.es.resx b/src/System.Management.Automation/resources/es/CimInstanceTypeAdapterResources.es.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/es/CimInstanceTypeAdapterResources.es.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CmdletizationCoreResources.es.resx b/src/System.Management.Automation/resources/es/CmdletizationCoreResources.es.resx new file mode 100644 index 00000000000..798bf54d88c --- /dev/null +++ b/src/System.Management.Automation/resources/es/CmdletizationCoreResources.es.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlets de la clase "{0}" + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + No se puede procesar el XML de definición de cmdlet para el siguiente archivo: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + No se puede procesar el atributo ObjectModelWrapper. El tipo {0} define varios conjuntos de parámetros. Compruebe que el XML de definición de cmdlet especifica un tipo válido en el atributo ObjectModelWrapper e inténtelo de nuevo. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + No se puede procesar el atributo ObjectModelWrapper. El tipo {0} es un tipo genérico abierto. Compruebe que el XML de definición de cmdlet especifica un tipo válido en el atributo ObjectModelWrapper e inténtelo de nuevo. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + No se puede procesar el atributo ObjectModelWrapper. El tipo {0} no hereda de la siguiente clase: {1}. Compruebe que el XML de definición de cmdlet especifica un tipo válido en el atributo ObjectModelWrapper e inténtelo de nuevo. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + No se puede procesar el atributo ObjectModelWrapper. El tipo {0} define el parámetro de cmdlet {1} con un parámetro de atributo {2} que se omite. Compruebe que el XML de definición de cmdlet especifica un tipo válido en el atributo ObjectModelWrapper e inténtelo de nuevo. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + No se puede definir el parámetro {0} para el cmdlet {1}. El nombre del parámetro ya está definido por la clase {2}. Cambie el nombre del parámetro en el XML de definición de cmdlet e inténtelo de nuevo. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + No se puede definir el parámetro {0} para el cmdlet {1}. El nombre del parámetro ya está definido dentro del elemento XML {2}. Cambie el nombre del parámetro en el XML de definición de cmdlet e inténtelo de nuevo. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + El valor del atributo EnumName no se traduce a un identificador de C# válido: {0}. Compruebe el atributo EnumName en el XML de definición de cmdlet y, a continuación, inténtelo de nuevo. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + No se puede procesar el elemento <Enum EnumName="{0}" ...>. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + El equipo remoto devolvió un archivo CDXML no válido. El siguiente adaptador de cmdlet no es compatible con la importación de un módulo CDXML desde un equipo remoto: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CommandBaseStrings.es.resx b/src/System.Management.Automation/resources/es/CommandBaseStrings.es.resx new file mode 100644 index 00000000000..2748fc3e9e0 --- /dev/null +++ b/src/System.Management.Automation/resources/es/CommandBaseStrings.es.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ¿Desea continuar con esta operación? + + + &Sí + + + Continúe solo con el siguiente paso de la operación. + + + Sí a &todo + + + Continúe con todos los pasos de la operación. + + + &No + + + Omitir esta operación y continuar con la siguiente. + + + No a &todo + + + Omita esta operación y todas las operaciones posteriores. + + + Detener este comando. + + + &Detener comando + + + &Suspender + + + Ponga en pausa la canalización actual y vuelva al símbolo del sistema. Escriba "{0}" para reanudar la canalización. + + + + El programa "{0}" finalizó con un código de salida distinto de cero: {1} ({2}). + + + Realizando la operación "{0}" en el objetivo "{1}". + + + What If: {0} + + + ¿Seguro que quiere realizar esta acción? +{0} + + + Confirmar + + + El comando en ejecución se detuvo porque la variable de preferencia "{0}" o el parámetro común está establecido en Detener: {1} + + + El comando en ejecución se detuvo porque la variable de preferencia "{0}" o el parámetro común está establecido en Detener. + + + El comando en ejecución se detuvo porque la variable de preferencia "{0}" o el parámetro común está establecido en el siguiente valor que no es válido: "{1}". + + + El comando en ejecución se detuvo porque el usuario seleccionó la opción Detener. + + + El comando en ejecución se detuvo porque el usuario lo interrumpió. + + + Los cmdlets derivados de PSCmdlet no se pueden invocar directamente. + + + El cmdlet "{0}" no admite el parámetro "{1}" en una sesión remota. + + + Número total: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Recuento estimado total: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Recuento total desconocido + Reviewed by TArcher on 2010-07-20 + + + comando "{0}" + + + El {0} está obsoleto. {1} + + + La llamada a Exec falló con errorno {0} para la línea de comandos: {1} + + + No se encontró el comando "{0}". El comando especificado debe ser un ejecutable. + + + Comprobación de operador punto del procesamiento de bloques de script + + + El procesamiento de operador punto para el bloque de script "{0}" fallará en modo de lenguaje restringido porque su modo de lenguaje "{1}" no coincide con el modo de lenguaje actual "{2}". + + + Buscador de comandos + + + El comando "{0}" del módulo "{1}" no es de confianza y no estará disponible en el modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ConsoleInfoErrorStrings.es.resx b/src/System.Management.Automation/resources/es/ConsoleInfoErrorStrings.es.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/es/ConsoleInfoErrorStrings.es.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CoreClrStubResources.es.resx b/src/System.Management.Automation/resources/es/CoreClrStubResources.es.resx new file mode 100644 index 00000000000..8430eb4b19c --- /dev/null +++ b/src/System.Management.Automation/resources/es/CoreClrStubResources.es.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El nombre de la variable de entorno no puede contener el mismo carácter. + + + El nombre o valor de la variable de entorno es demasiado largo. + + + El primer carácter de la cadena es el carácter nulo. + + + La cadena no puede tener una longitud cero. + + + No se pudo obtener el nombre del equipo. + + + No se pudo obtener el nombre de dominio del usuario actual. + + + Error desconocido "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CredUI.es.resx b/src/System.Management.Automation/resources/es/CredUI.es.resx new file mode 100644 index 00000000000..e5a46f22536 --- /dev/null +++ b/src/System.Management.Automation/resources/es/CredUI.es.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Solicitud de credenciales de PowerShell + + + Escriba sus credenciales. + + + Escriba sus credenciales. + + + La longitud máxima del título son {0} caracteres. + + + La longitud máxima del mensaje es de {0}caracteres. + + + La longitud máxima del valor UserName es de {0} caracteres. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/Credential.es.resx b/src/System.Management.Automation/resources/es/Credential.es.resx new file mode 100644 index 00000000000..ad0d3d52c49 --- /dev/null +++ b/src/System.Management.Automation/resources/es/Credential.es.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 + + + No se puede serializar la credencial. Si este comando inicia un flujo de trabajo, las credenciales no se pueden persistir porque el proceso en el que se inicia el flujo de trabajo no tiene permiso para serializar credenciales. + +-- Si el flujo de trabajo se inició en una PSSession del equipo local, agregue el parámetro EnableNetworkAccess al comando que creó la sesión. +-- Si el flujo de trabajo se inició en una PSSession de un equipo remoto, agregue el parámetro Authentication con un valor de CredSSP al comando que creó la sesión. O bien, conéctese a una configuración de sesión que tenga un valor de propiedad RunAsUser. + + + El valor de UserName no tiene el formato correcto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/CredentialAttributeStrings.es.resx b/src/System.Management.Automation/resources/es/CredentialAttributeStrings.es.resx new file mode 100644 index 00000000000..892056374c5 --- /dev/null +++ b/src/System.Management.Automation/resources/es/CredentialAttributeStrings.es.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 + + + Solicitud de credenciales de PowerShell + + + Especifique sus credenciales. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/DebuggerStrings.es.resx b/src/System.Management.Automation/resources/es/DebuggerStrings.es.resx new file mode 100644 index 00000000000..7690e230b87 --- /dev/null +++ b/src/System.Management.Automation/resources/es/DebuggerStrings.es.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Punto de interrupción variable en "${0}" (acceso de {1}) + + + Punto de interrupción variable en "{0}:${1}" (acceso de {2}) + + + Punto de interrupción de línea en "{0}:{1}" + + + Punto de interrupción de línea en "{0}:{1}, {2}" + + + Punto de interrupción de comando en "{0}" + + + Punto de interrupción de comando en "{0}:{1}" + + + No se alcanzará el punto de interrupción {0} + + + {0}, {1,-16} Un solo paso (ir a funciones, scripts, etc.) + + + {0}, {1,-16} Ir a la siguiente instrucción (paso a paso por funciones, scripts, etc.) + + + {0}, {1,-16} Salga de la función, script, etc. actual. + + + {0}, {1,-16} Continuar la operación + + + {0}, {1,-16} Detener la operación y salir del depurador + + + {0}, Mostrar la pila de llamadas Get-PSCallStack + + + {0}, {1,-16} Muestre el código fuente del script actual. + + + Use "list" para empezar desde la línea actual, "list <m>" + + + para empezar desde la línea <m> y "list <m> <n>" para enumerar <n> + + + líneas a partir de la línea <m> + + + <enter> Repita el último comando si fue {0}, {1} o {2} + + + {0}, {1,-16} muestra este mensaje de ayuda. + + + Para obtener instrucciones sobre cómo personalizar la indicación del depurador, escriba "help about_prompt". + + + +La sesión actual no admite la depuración; la operación continuará. + + + + + {0}: línea {1} + + + No hay código fuente disponible. + + + La línea inicial debe ser un entero positivo no mayor que {0} + + + El recuento de líneas debe ser un entero positivo. + + + <No hay ningún archivo> + + + en {0}, {1}: línea {2} + + + El depurador no puede procesar comandos a menos que esté en estado Detenido. + + + SetDebugAction no está implementado para el depurador de scripts local. + + + El depurador no puede establecer una acción de reanudación porque el depurador de la sesión remota no está en estado Detenido. + + + No se puede depurar el trabajo porque el depurador está ocupado actualmente. + + + Se examinó el trabajo proporcionado y todos los trabajos secundarios, pero no se encontró ningún trabajo que pudiera depurarse. Para depurar un trabajo o un trabajo secundario, el trabajo debe admitir la depuración y estar en estado en ejecución. + + + No se puede habilitar el depurador para el modo de paso porque el depurador está desactivado con el modo de depuración establecido en Ninguno. + + + No se puede depurar el espacio de ejecución porque el depurador del host está ocupado actualmente. + + + No se puede depurar el espacio de ejecución. El depurador del espacio de ejecución está desactivado actualmente (DebugMode es "None"). + + + No se puede depurar un espacio de ejecución que no esté en el estado Abierto. Este espacio de ejecución está en el estado {0}. + + + No se puede depurar el espacio de ejecución. El espacio de ejecución {0} no tiene ningún depurador asociado. + + + El depurador ya está invalidado. + + + No se puede insertar un objeto depurador sobre sí mismo. + + + El comando {0} no se admite para uso remoto en la versión de PowerShell que se ejecuta en el espacio de ejecución remoto. + + + Proceso + + + {0}, {1,-16} Continúe la operación y desasocie el depurador. + + + El comando de desasociar el depurador no está disponible. El comando de desasociar solo se aplica al depurar trabajos y espacios de ejecución con los cmdlets Debug-Job o Debug-Runspace. + + + Id. de espacio de ejecución no válido: {0} + + + No se puede obtener el espacio de ejecución. + + + Se debe especificar Breakpoint o BreakpointList. + + + BreakpointList contenía un elemento que no era un punto de interrupción. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/DescriptionsStrings.es.resx b/src/System.Management.Automation/resources/es/DescriptionsStrings.es.resx new file mode 100644 index 00000000000..3aa45dfb2ee --- /dev/null +++ b/src/System.Management.Automation/resources/es/DescriptionsStrings.es.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 + + + {0} no puede ser nulo ni estar vacío. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/DiscoveryExceptions.es.resx b/src/System.Management.Automation/resources/es/DiscoveryExceptions.es.resx new file mode 100644 index 00000000000..b0f1c5a3730 --- /dev/null +++ b/src/System.Management.Automation/resources/es/DiscoveryExceptions.es.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 + + + El nombre del cmdlet "{0}" no se puede validar porque no tiene el formato correcto. Los nombres de cmdlet deben incluir un verbo y un sustantivo separados por un "-", como "Get-Process". + + + El parámetro "{0}" se declara en el conjunto de parámetros "{1}" varias veces. + + + El alias "{0}" se declara varias veces. + + + No se pudo declarar el parámetro. Los parámetros solo se pueden declarar en campos y propiedades. + + + No se puede procesar el cmdlet. Un nombre de cmdlet debe constar de un par de verbos y sustantivos separados por '-'. + + + El término "{0}" no se reconoce como nombre de un cmdlet, función, archivo de script o programa ejecutable. +Compruebe la ortografía del nombre o, si se incluyó una ruta de acceso, compruebe que la ruta de acceso es correcta e inténtelo de nuevo. + + + El argumento "{0}" no se reconoce como cmdlet: {1} + + + El argumento "{0}" no se reconoce como cmdlet, posiblemente porque no deriva de las clases Cmdlet o PSCmdlet: {1} + + + No se puede resolver el alias "{0}" porque hace referencia al término "{1}", que no se reconoce como cmdlet, función, programa ejecutable o archivo de script. Compruebe el término e inténtelo de nuevo. + + + El parámetro "{0}" con el valor "{1}" no se puede procesar porque no es un cmdlet y el CommandProcessor no puede procesarlo. + + + Ya existe un cmdlet denominado "{0}". Los cmdlets deben tener nombres únicos. + + + Ya existe un proveedor de cmdlet con el nombre "{0}". Los proveedores de cmdlets deben tener nombres únicos. + + + Ya existe un ensamblado con el nombre "{0}". Los ensamblados deben tener nombres únicos. + + + Ya existe un script con el nombre "{0}". Los scripts deben tener nombres únicos. + + + No se puede procesar la instrucción #requires porque no tiene el formato correcto. +La instrucción #requires debe tener uno de los siguientes formatos: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + No se puede ejecutar el script "{0}" porque contenía una instrucción "#requires" con un identificador de shell de {1} que no es compatible con el shell actual. Para ejecutar este script, debe usar el shell ubicado en "{2}". + + + No se puede ejecutar el script "{0}" porque contenía una instrucción "#requires" con un identificador de shell de {1} que no es compatible con el shell actual. + + + No se puede ejecutar el script "{0}" porque contenía una instrucción "#requires" para PowerShell {1}. La versión de PowerShell que requiere el script no coincide con la versión que se está ejecutando actualmente de PowerShell {2}. + + + No se puede ejecutar el script "{0}" porque contenía una instrucción "#requires" para las ediciones de PowerShell "{1}". La edición de PowerShell que requiere el script no coincide con la edición {2} de PowerShell que se está ejecutando actualmente. + + + No se puede ejecutar el script "{0}" porque faltan los siguientes complementos especificados por las instrucciones "#requires" del script: {1}. + + + Una instrucción #requires solo ha especificado un shellID. Las instrucciones #Requires deben especificar un complemento de PowerShell necesario cuando se ejecutan en PowerShell. + + + No se puede ejecutar el script "{0}" porque contiene una instrucción "#requires" para ejecutarse como administrador. La sesión actual de PowerShell no se está ejecutando como administrador. Inicie PowerShell con la opción Ejecutar como administrador e intente ejecutar el script de nuevo. + + + {0} (Versión {1}) + + + No se pudo recuperar el comando porque el parámetro ArgumentList solo se puede especificar al recuperar un único cmdlet o script. + + + El nombre del parámetro "{0}" está reservado para su uso futuro. + + + No se puede ejecutar el script "{0}" porque faltan los siguientes módulos especificados por las instrucciones "#requires" del script: {1}. + + + Se encontró el comando "{0}" en el módulo "{1}", pero no se pudo cargar el módulo. Para obtener más información, ejecute "Import-Module {1}". + + + Se encontró el comando "{0}" en el módulo "{1}", pero no se pudo cargar el módulo debido al siguiente error: [{2}] +Para obtener más información, ejecute "Import-Module {1}". + + + No se pudo cargar el módulo "{0}". Para obtener más información, ejecute "Import-Module {0}". + + + Ningún comando coincidente incluye un parámetro denominado "{0}". Compruebe la ortografía del nombre del parámetro e inténtelo de nuevo. + + + No se puede usar este comando con importación mediante punto porque se definió en un modo de lenguaje diferente. Para invocar este comando sin importar su contenido, omita el operador '.'. + + + Los parámetros ShowCommandInfo y Syntax no se pueden especificar juntos. + + + Este comando de script se deshabilita cuando la característica experimental "{0}" está activada. + + + Este comando de script se deshabilita cuando la característica experimental "{0}" está desactivada. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/EnumExpressionEvaluatorStrings.es.resx b/src/System.Management.Automation/resources/es/EnumExpressionEvaluatorStrings.es.resx new file mode 100644 index 00000000000..a07fedc675e --- /dev/null +++ b/src/System.Management.Automation/resources/es/EnumExpressionEvaluatorStrings.es.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La expresión de entrada no debe estar vacía. Especifique al menos un nombre de identificador en cada expresión de entrada. + + + No se puede hacer coincidir un nombre de identificador vacío con un nombre de enumerador válido. Especifique uno de los siguientes nombres de enumerador y vuelva a intentarlo: {0}. + + + El tipo genérico especificado para la expresión debe representar una enumeración. Especifique un tipo de enumeración válido. + + + No se puede procesar el nombre {0} del identificador porque es demasiado similar o idéntico a los siguientes nombres de enumerador: {1}. Use un nombre de identificador más específico. + + + No se puede hacer coincidir el nombre del identificador {0} con un nombre de enumerador válido. Especifique uno de los siguientes nombres de enumerador e inténtelo de nuevo: +{1} + + + El uso de paréntesis no es válido en la expresión porque no se permite la agrupación de identificadores. Intente quitar los paréntesis o, si una subexpresión está delimitada, intente expandir la expresión. + + + No se puede analizar la expresión debido a un token inesperado. Solo se espera un operador OR (,) o AND (+) después de un nombre de identificador. + + + No se puede analizar la expresión debido a un token inesperado después de un operador NOT (!). Se espera un nombre de identificador después de un operador NOT (!). + + + No se puede analizar la expresión debido a un token inesperado. Se espera un nombre de identificador o un operador NOT (!) al principio de la expresión, o después de un operador OR (,) o un operador AND (+). Además, una expresión no debe terminar con un operador OR (,), AND (+) o NOT (!). + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ErrorCategoryStrings.es.resx b/src/System.Management.Automation/resources/es/ErrorCategoryStrings.es.resx new file mode 100644 index 00000000000..cc50810a440 --- /dev/null +++ b/src/System.Management.Automation/resources/es/ErrorCategoryStrings.es.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 + + + Error al cerrar: ({1}:{2}) [{0}], {3} + + + Interbloqueo detectado: ({1}:{2}) [{0}], {3} + + + Error del dispositivo: ({1}:{2}) [{0}], {3} + + + Argumento no válido: ({1}:{2}) [{0}], {3} + + + Datos no válidos: ({1}:{2}) [{0}], {3} + + + Operación no válida: ({1}:{2}) [{0}], {3} + + + Resultado no válido: ({1}:{2}) [{0}], {3} + + + Tipo no válido: ({1}:{2}) [{0}], {3} + + + Error de metadatos: ({1}:{2}) [{0}], {3} + + + No implementado: ({1}:{2}) [{0}], {3} + + + No instalado: ({1}:{2}) [{0}], {3} + + + Objeto no encontrado: ({1}:{2}) [{0}], {3} + + + Error al abrir: ({1}:{2}) [{0}], {3} + + + Operación detenida: ({1}:{2}) [{0}], {3} + + + Tiempo de espera de la operación agotado: ({1}:{2}) [{0}], {3} + + + Error del analizador: ({1}:{2}) [{0}], {3} + + + Permiso denegado: ({1}:{2}) [{0}], {3} + + + Error de lectura: ({1}:{2}) [{0}], {3} + + + Recurso ocupado: ({1}:{2}) [{0}], {3} + + + El recurso ya existe: ({1}:{2}) [{0}], {3} + + + Recurso no disponible: ({1}:{2}) [{0}], {3} + + + Error de sintaxis: ({1}:{2}) [{0}], {3} + + + Error de escritura: ({1}:{2}) [{0}], {3} + + + Desde StdErr: ({1}:{2}) [{0}], {3} + + + Error de seguridad: ({1}:{2}) [{0}], {3} + + + Error de protocolo: ({1}:{2}) [{0}], {3} + + + Error de conexión: ({1}:{2}) [{0}], {3} + + + Error de autenticación: ({1}:{2}) [{0}], {3} + + + Se superaron los límites: ({1}:{2}) [{0}], {3} + + + Se superó la cuota: ({1}:{2}) [{0}], {3} + + + No habilitado: ({1}:{2}) [{0}], {3} + + + No especificado: ({1}:{2}) [{0}], {3} + + + Categoría de error no reconocida {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ErrorPackage.es.resx b/src/System.Management.Automation/resources/es/ErrorPackage.es.resx new file mode 100644 index 00000000000..01f7557b615 --- /dev/null +++ b/src/System.Management.Automation/resources/es/ErrorPackage.es.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 + + + {0}…{1} + + + El texto del error está vacío para el error "{0}" : "{1}" + + + Object "{0}" is reported as an error. + + + The value {0} is not supported for an ActionPreference variable. The provided value should be used only as a value for a preference parameter, and has been replaced by the default value. For more information, see the Help topic, "about_Preference_Variables." + + + El valor {0} de ActionPreference está reservado para uso futuro y no se admite en este momento. Para obtener más información acerca de las variables de preferencia, vea el tema de ayuda "about_Preference_Variables". + + + El valor {0} de ActionPreference está reservado para uso futuro y no se admite en este momento. Se ha reemplazado en la variable {1} por el valor predeterminado de {2}. Para obtener más información acerca de las variables de preferencia, vea el tema de ayuda "about_Preference_Variables". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/EtwLoggingStrings.es.resx b/src/System.Management.Automation/resources/es/EtwLoggingStrings.es.resx new file mode 100644 index 00000000000..ec878ee8a53 --- /dev/null +++ b/src/System.Management.Automation/resources/es/EtwLoggingStrings.es.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El comando {0} está {1}. + + + El estado del motor cambió de {0} a {1}. + + + Id. de error completo = {0} + + + Mensaje de error = {0} + + + Acción recomendada = {0} + + + Directiva de ejecución + + + Comando de trabajo = {0} + + + Id. de trabajo = {0} + + + Id. de instancia de trabajo = {0} + + + Ubicación del trabajo = {0} + + + Nombre del trabajo = {0} + + + Estado del trabajo = {0} + + + Nombre de comando = + + + Ruta de acceso del comando = + + + Tipo de comando = + + + Versión del motor = + + + Id. de host = + + + Nombre de host = + + + Aplicación host = + + + Versión del host = + + + Id. de canalización = + + + Id. de espacio de ejecución = + + + Nombre de script = + + + Número de secuencia = + + + Gravedad = + + + Id. de shell = + + + Hora = + + + Usuario = + + + Usuario conectado = + + + Trabajo NULL + + + Nombre del proveedor + + + El proveedor {0} cambió el estado a {1}. + + + La ejecución del script es {0}. + + + La variable {0} cambió de {1} a {2}. + + + La variable {0} cambió a {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/EventResource.es.resx b/src/System.Management.Automation/resources/es/EventResource.es.resx new file mode 100644 index 00000000000..c497d164fff --- /dev/null +++ b/src/System.Management.Automation/resources/es/EventResource.es.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se encontró un mensaje para el id. de evento PowerShell.Core.Instrumentation.man. + + + El trabajo {0} programado se inició a las {1} + + + + Trabajo programado {0} completado a las {1} con el estado {2} + + + + Excepción {0} de trabajo programado : + Mensaje: {1} + StackTrace: {2} + InnerException: {3} + + + + Inicialización de características experimentales: omita la característica experimental '{0}' del archivo de configuración. {1} + + + Inicialización experimental de características: no se pudo leer el archivo de configuración. + Excepción: {0} + Mensaje: {1} + StackTrace: {2} + + + + Complemento de flujo de trabajo cargado. + EndpointName: {0} + Usuario: {1} + HostingMode: {2} + Protocolo: {3} + Configuración: + {4} + + + Se inició la ejecución del flujo de trabajo. + WorkflowId: {0} + ManagedNodes: {1} + + + El estado del flujo de trabajo cambió. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + Se ha solicitado un apagado del complemento de flujo de trabajo. + EndpointName: {0} + + + Se reinició el complemento de flujo de trabajo. + EndpointName: {0} + + + El flujo de trabajo se está reanudando. + WorkflowId: {0} + + + Se superó un límite de cuota establecido para el punto de conexión. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + El flujo de trabajo se ha reanudado. + WorkflowId: {0} + + + Se creó un grupo de espacio de ejecución de flujo de trabajo. + WorkflowId: {0} + ManagedNode: {1} + + + La actividad se puso en cola para su ejecución. + WorkflowId: {0} + ActivityName: {1} + + + Se inició la ejecución de la actividad. + ActivityName: {0} + ActivityTypeName: {1} + + + El flujo de trabajo se está importando desde un archivo XAML. + WorkflowId: {0} + XamlFile: {1} + + + El flujo de trabajo se ha importado desde un archivo XAML. + WorkflowId: {0} + XamlFile: {1} + + + No se pudo importar el flujo de trabajo desde un archivo XAML debido a un error. + WorkflowId: {0} + ErrorDescription: {1} + + + Se inició la validación del flujo de trabajo. + WorkflowId: {0} + + + La validación del flujo de trabajo se realizó correctamente. + WorkflowId: {0} + + + Error en la validación del flujo de trabajo. + WorkflowId: {0} + + + Actividad de flujo de trabajo validada. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + No se pudo validar la actividad de flujo de trabajo. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Error en la ejecución de la actividad. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + La disponibilidad del espacio de ejecución ha cambiado. + RunspaceId: {0} + Disponibilidad: {1} + + + El estado del espacio de ejecución cambió. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Flujo de trabajo cargado para su ejecución. + WorkflowId: {0} + + + Flujo de trabajo descargado. + WorkflowId: {0} + + + Ejecución del flujo de trabajo cancelada. + WorkflowId: {0} + + + Se anuló la ejecución del flujo de trabajo. + WorkflowId: {0} + + + Operación de limpieza de flujo de trabajo ejecutada. + WorkflowId: {0} + + + Flujo de trabajo persistente cargado desde el disco. + WorkflowId: {0} + Ruta: {1} + + + Los datos de flujo de trabajo se eliminaron del disco. + WorkflowId: {0} + Ruta: {1} + + + Iniciando el trabajo de eliminación. + JobId: {0} + + + El estado del trabajo ha cambiado. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Error de trabajo. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Trabajo creado para el flujo de trabajo (trabajo secundario). + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Trabajo primario creado para el flujo de trabajo. + JobId: {0} + + + Se crearon todos los trabajos necesarios para la ejecución del flujo de trabajo. + JobId: {0} + WorkflowId: {1} + + + Trabajo secundario quitado para el flujo de trabajo. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + Error al quitar el trabajo. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Error: {3} + + + Cargando flujo de trabajo para su ejecución. + WorkflowId: {0} + + + Finalizó la ejecución del flujo de trabajo. + WorkflowId: {0} + + + Cancelando la ejecución del flujo de trabajo. + WorkflowId: {0} + + + Anulando la ejecución del flujo de trabajo. + WorkflowId: {0} + Motivo: {1} + + + Descargando flujo de trabajo. + WorkflowId: {0} + + + Se inició el apagado forzado del flujo de trabajo. + WorkflowId: {0} + + + Finalizó el cierre forzado del flujo de trabajo. + WorkflowId: {0} + + + Error al cerrar forzosamente un flujo de trabajo. + WorkflowId: {0} + ErrorDescription: {1} + + + Conservando el flujo de trabajo en el disco. + WorkflowId: {0} + PersistPath: {1} + + + El flujo de trabajo se conserva en el disco. + WorkflowId: {0} + + + Finalizó la ejecución de la actividad. + ActivityName: {0} + + + Error de ejecución del flujo de trabajo. + WorkflowId: {0} + ErrorDescription: {1} + + + Se registró un nuevo punto de conexión de PowerShell. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Se modificó la configuración del punto de conexión. + EndpointName: {0} + ModifiedBy: {1} + + + Se anule el registro de la configuración del punto de conexión. + EndpointName: {0} + UnregisteredBy: {1} + + + Configuración del punto de conexión deshabilitada. + EndpointName: {0} + DisabledBy: {1} + + + Configuración de punto de conexión habilitada. + EndpointName: {0} + EnabledBy: {1} + + + Se inició el espacio de ejecución fuera del proceso. + Comando: {0} + + + La expansión de parámetros se realizó durante la ejecución del flujo de trabajo. + Parámetros: {0} + Equipos: {1} + + + Se inició el motor de flujo de trabajo. + EndpointName: {0} + + + Se creó una instancia del administrador de flujo de trabajo con + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + Ruta: {3} + + + Nombre de equipo $null o . resolver en LocalHost + + + Resolviendo en http de esquema predeterminado + + + Nombre de shell remoto resuelto en PowerShellCore predeterminado + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + Creando texto de bloque de script ({0} de {1}): +{2} + +Id. de bloque de script: {3} +Ruta: {4} + + + Se inició la invocación del id. de ScriptBlock: {0} +Id. de espacio de ejecución: {1} + + + Invocación completada del id. de ScriptBlock: {0} +Id. de espacio de ejecución: {1} + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + {2} + +Contexto: +{0} + +Datos de usuario: +{1} + + + + Correlación de identificadores de actividad. + CurrentActivityId: {0} + ParentActivityId: {1} + + + Nombre de clase = {0} +Nombre del método = {1} +GUID de flujo de trabajo = {2} +Mensaje = {3} +{4} +Nombre de actividad = {5} +GUID de actividad = {6} +Parámetros = {7} + + + Creando objeto Runspace + Id. de instancia: {0} + + + Creando objeto RunspacePool + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Abriendo RunspacePool + + + Modificación del identificador de actividad y correlación + + + El estado del espacio de ejecución cambió a {0} + + + Intentando reintentar {0} la creación de la sesión para el código de error {1} en el identificador de sesión {2} + + + PowerShell ha iniciado un subproceso de escucha de IPC en el proceso: {0} en AppDomain: {1}. + + + PowerShell ha finalizado un subproceso de escucha de IPC en el proceso: {0} en AppDomain: {1}. + + + Error en el subproceso de escucha de IPC de PowerShell en el proceso: {0} en AppDomain: {1}. Mensaje error: {2}. + + + Conexión IPC de PowerShell en el proceso: {0} en AppDomain: {1} para el usuario: {2}. + + + Desconexión de IPC de PowerShell en el proceso: {0} en AppDomain: {1} para el usuario: {2}. + + + Puerto resuelto en {0} + + + AppName resuelto en {0} + + + ComputerName resuelto en {0} + + + El esquema es {0} + + + Mensaje analítico de prueba + + + Los parámetros de conexión son + URI de conexión: {0} + URI de recurso: {1} + Usuario: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Huella digital: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Modificación del identificador de actividad y correlación + + + Objeto recibido con id. de espacio de ejecución: {0} Id. de comando: {1} Destino: {2} DataType: {3} TargetInterface: {4} + + + Se produjo una excepción no controlada en el appdomain. +Tipo de excepción: {0} +Mensaje de excepción: {1} +Excepción StackTrace: {2} + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. WSMan notificó un error con el código de error: {2}. + Mensaje de error: {3} + StackTrace: {4} + + + Se produjo una excepción no controlada en el appdomain. +Tipo de excepción: {0} +Mensaje de excepción: {1} +Excepción StackTrace: {2} + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. WSMan notificó un error con el código de error: {2}. + Mensaje de error: {3} + StackTrace: {4} + + + Id. de espacio de ejecución {0}. Establecimiento de una conexión mediante WSMan Create Shell + + + Id. de espacio de ejecución {0}. Devolución de llamada recibida para WSMan Create Shell + + + Id. de espacio de ejecución: {0}. Cierre del shell mediante WSManCloseShell + + + Id. de espacio de ejecución: {0}. Devolución de llamada recibida para WSManCloseShell + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. Envío de datos de tamaño {2} + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. Devolución de llamada recibida para WSManSendShellInputEx + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. Colocación de la solicitud receive mediante WSManReceiveShellOutputEx + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. Datos recibidos de tamaño {2}. + + + Id. de espacio de ejecución {0} Id. de canalización {1}. Establecimiento de una conexión de comandos mediante WSManRunShellCommandEx + + + Id. de espacio de ejecución {0} Id. de canalización {1}. Devolución de llamada recibida para la conexión de comandos + + + Id. de espacio de ejecución: {0} Id. de canalización {1}. Cerrando transporte para el comando + + + Id. de espacio de ejecución: {0} Id. de canalización {1}. Devolución de llamada recibida para cerrar el comando + + + Id. de espacio de ejecución: {0} Id. de canalización {1}. Envío de señal con código {2} mediante WSManSignalShellEx + + + Id. de espacio de ejecución: {0} Id. de canalización {1}. Devolución de llamada recibida para WSManSignalShellEx + + + Id. de espacio de ejecución: {0}. La conexión se redirige al URI: {1} + + + Id. de espacio de ejecución: {0} Id. de canalización: {1}. El servidor está enviando datos de tamaño {2} al cliente. DataType: {3} TargetInterface: {4} + + + Solicitud {0}. Creando una sesión remota de servidor. UserName: {1} Id. de shell personalizado: {2} + + + Contexto de informe para la solicitud: {0} contexto notificado: {0} + + + Operación de informes completada para la solicitud: {0} + Código de error: {1} + Mensaje de error: {2} + StackTrace: {3} + + + Contexto de shell {0}. Id. de solicitud {1}. Crear una sesión de Commonad para ejecutar un comando. + + + Contexto de shell {0} Contexto de comando {1} Id. de solicitud {2}. Deteniendo comando. + + + Contexto de shell {0} Contexto de comando {1} Id. de solicitud {2}. Datos recibidos del cliente. + + + Contexto de shell {0} Contexto de comando {1} Id. de solicitud {2}. El cliente envió una solicitud de recepción para que el servidor pueda enviar datos. + + + Contexto {1} de comando de contexto {0} de shell IsReceiveOperation {2}. Se obtuvo una solicitud de operación de cierre. + + + Cargando ensamblado {0} para shell personalizado con id. de shell {1} + + + Cargando el tipo {0} para el shell personalizado con el identificador de shell {1} + + + Fragmento de comunicación remota recibido. + Id. de objeto: {0} + Id. de fragmento: {1} + Marca de inicio: {2} + Marca de finalización: {3} + Longitud de carga: {4} + Datos de carga: {5} + + + Fragmento de comunicación remota enviado. + Id. de objeto: {0} + Id. de fragmento: {1} + Marca de inicio: {2} + Marca de finalización: {3} + Longitud de carga: {4} + Datos de carga: {5} + + + Cerrando el servicio winrm. + + + Un objeto se rehidrató correctamente. + Nombre del tipo deserializado: {0} + Rehidratación mediante conversión al tipo: {1} + El objeto rehidratado es de tipo: {2} + + + No se pudo rehidratar un objeto. + Nombre del tipo deserializado: {0} + Rehidratación mediante conversión al tipo: {1} + Excepción de conversión de tipos: {2} + Excepción interna de conversión de tipos: {3} + + + Se ha invalidado la profundidad de serialización. + Nombre de tipo serializado: {0} + Profundidad original: {1} + Profundidad invalidada: {2} + Profundidad actual por debajo del nivel superior: {3} + + + Se ha invalidado el modo de serialización. + Nombre de tipo serializado: {0} + Modo invalidado: {1} + + + Se ha omitido la serialización de una propiedad de script porque no hay ningún espacio de ejecución que usar para la evaluación de la propiedad. + Nombre de la propiedad: {0} + Nombre de tipo del propietario de la propiedad: {1} + Script de captador: {2} + + + Se omitió la serialización de una propiedad porque se produjo un error en el captador de propiedad. + Nombre de la propiedad: {0} + Nombre de tipo del propietario de la propiedad: {1} + Excepción del captador de propiedades: {2} + Excepción interna del captador de propiedades: {3} + + + Es posible que la serialización de un objeto enumerable no esté completa, porque el objeto que se está enumerando produjo una excepción. + Tipo de objeto que se enumera: {0} + Excepción: {1} + + + La serialización llamó al método ToString del objeto y se produjo un error. + Tipo de objeto: {0} + Excepción: {1} + + + Se ha alcanzado la profundidad máxima por debajo del nivel superior, lo que obliga a serializar el objeto como cadenas. + Tipo de objeto en profundidad máxima: {0} + Nombre de propiedad en profundidad máxima: {1} + Profundidad: {2} + + + El deserializador ha iniciado XmlException (lo más probable es que indique un formato clixml incorrecto). + Número de línea: {0} posición de línea: {1} + Excepción: {2} + + + Error en la serialización de las propiedades especificadas porque faltaba una de las propiedades especificadas. + Tipo de objeto: {0} + Nombre de la propiedad: {1} + + + Se está iniciando la consola de PowerShell + + + La consola de PowerShell está lista para la entrada del usuario + + + {0} + + + Registro de errores de seguimiento: + Mensaje: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + Detalles de la excepción: + Mensaje : {5} + Seguimiento de la pila: {6} + InnerException {7} + + + + Excepción: + Mensaje: {0} + StackTrace: {1} + InnerException : {2} + + + + Seguimiento de PSObject + + + Trabajo de seguimiento: + Id: {0} + InstanceId: {1} + Nombre: {2} + Ubicación: {3} + Estado: {4} + Comando: {5} + + + + Información de seguimiento: + {0} + + + Información de seguimiento: + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication. Iniciando la invocación de la función de flujo de trabajo. GUID de seguimiento {0} + + + END ImportWorkflowCommand::StartWorkflowApplication. Finalización de la invocación de la función de flujo de trabajo. GUID de seguimiento {0} + + + EMPEZAR a crear un nuevo trabajo en ImportWorkflowCommand::StartWorkflowApplication. GUID de seguimiento {0} + + + FIN Crear un nuevo trabajo en ImportWorkflowCommand::StartWorkflowApplication. GUID de seguimiento {0} + + + FIN Crear un nuevo trabajo en ImportWorkflowCommand::StartWorkflowApplication. GUID {0} de seguimiento : Guid de ContainerParentJob {1} + + + BEGIN JobLogic ContainerParentJob Guid {0} + + + END JobLogic ContainerParentJob Guid {0} + + + BEGIN WorkflowExecution ContainerParentJob Guid {0} + + + END WorkflowExecution ContainerParentJob Guid {0} + + + WorkflowJob con GUID {0} agregado a ContainerParentJob con GUID {1} + + + ProxyJob con GUID {0} asociado a ContainerParentJob remoto con GUID {1} + + + BEGIN Ejecución de ContainerParentJob con GUID {0} + + + END Ejecución de ContainerParentJob con GUID {0} + + + INICIAR ejecución del trabajo de proxy con GUID {0} + + + END Ejecución del trabajo de proxy con GUID {0} + + + Controlador de eventos BEGIN StateChanged para el trabajo de proxy con GUID {0} + + + Controlador de eventos END StateChanged para el trabajo de proxy con GUID {0} + + + Controlador de eventos BEGIN StateChanged para el trabajo secundario de proxy con GUID {0} + + + Controlador de eventos END StateChanged para el trabajo secundario de proxy con GUID {0} + + + EMPEZAR a ejecutar la recolección de elementos no utilizados + + + FINALIZAR la ejecución de la recolección de elementos no utilizados + + + El almacén de persistencia ha alcanzado su tamaño máximo especificado + + + Windows PowerShell ISE ha empezado a ejecutar el archivo {0}de script. + + + Windows PowerShell ISE ha empezado a ejecutar un script seleccionado por el usuario desde el archivo {0}. + + + Windows PowerShell ISE está deteniendo el comando actual. + + + Windows PowerShell ISE está reanudando el depurador. + + + Windows PowerShell ISE está deteniendo el depurador. + + + Windows PowerShell ISE está depurando paso a paso. + + + Windows PowerShell ISE está recorriendo paso a paso la depuración. + + + Windows PowerShell ISE está saliendo de la depuración. + + + Windows PowerShell ISE está habilitando todos los puntos de interrupción. + + + Windows PowerShell ISE está deshabilitando todos los puntos de interrupción. + + + Windows PowerShell ISE quita todos los puntos de interrupción. + + + Windows PowerShell ISE está estableciendo el punto de interrupción en la línea #: {0} del archivo {1}. + + + Windows PowerShell ISE está quitando el punto de interrupción de la línea #: {0} del archivo {1}. + + + Windows PowerShell ISE está habilitando el punto de interrupción en la línea #: {0} del archivo {1}. + + + Windows PowerShell ISE está deshabilitando el punto de interrupción en la línea #: {0} del archivo {1}. + + + Windows PowerShell ISE ha alcanzado un punto de interrupción en la línea #: {0} del archivo {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/EventingResources.es.resx b/src/System.Management.Automation/resources/es/EventingResources.es.resx new file mode 100644 index 00000000000..56869aaaf89 --- /dev/null +++ b/src/System.Management.Automation/resources/es/EventingResources.es.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede registrar el evento especificado. No se admiten los eventos que requieren un valor devuelto. + + + No se puede registrar el evento especificado. No existe un evento con el nombre "{0}". + + + PowerShell no puede suscribirse a eventos de Windows RT. + + + No se puede registrar el evento especificado. El identificador de origen de eventos "{0}" está reservado para el motor de PowerShell. + + + Esta operación no se admite en instancias remotas. + + + La acción no se admite cuando se reenvían eventos. + + + No se puede suscribir al evento especificado. Ya existe un suscriptor con el identificador de origen "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ExperimentalFeatureStrings.es.resx b/src/System.Management.Automation/resources/es/ExperimentalFeatureStrings.es.resx new file mode 100644 index 00000000000..86fef3fda9a --- /dev/null +++ b/src/System.Management.Automation/resources/es/ExperimentalFeatureStrings.es.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se encontró ninguna característica experimental que coincida con el nombre "{0}". + + + La habilitación y deshabilitación de características experimentales no surtirán efecto hasta el próximo inicio de PowerShell. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ExtendedTypeSystem.es.resx b/src/System.Management.Automation/resources/es/ExtendedTypeSystem.es.resx new file mode 100644 index 00000000000..04211f16d6f --- /dev/null +++ b/src/System.Management.Automation/resources/es/ExtendedTypeSystem.es.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El miembro "{0}" ya está presente. + + + El miembro "{0}" ya está presente en el archivo de datos de tipo extendido. + + + El miembro "{0}" no está presente. + + + Configuración de excepción "{0}": "{1}" + + + Excepción al obtener "{0}": "{1}" + + + Se produjo la siguiente excepción al intentar enumerar la colección: "{0}". + + + No se puede tener acceso al miembro "{0}" fuera de un PSObject. + + + No se puede cambiar el miembro creado a partir de la configuración de tipo: "{0}". + + + El nombre del miembro "{0}" está reservado. + + + "{0}" no se puede cambiar. + + + Excepción al llamar a "{0}" con "{1}" argumentos: "{2}" + + + Se produjo una excepción al intentar llamar a "{0}" para extraer el contenido de un objeto de tipo "{1}": "{2}" + + + No se encuentra una sobrecarga para "{0}" y el recuento de argumentos: "{1}". + + + No se encontró una sobrecarga de método genérico adecuada para "{0}" con "{1}" parámetros de tipo y el recuento de argumentos: "{2}". + + + Se encontraron varias sobrecargas ambiguas para "{0}" y el recuento de argumentos: "{1}". + + + No se puede convertir el argumento "{0}", con el valor "{1}", para "{2}" al tipo "{3}": "{4}" + + + Obtener descriptor de acceso para la propiedad "{0}" no está disponible. + + + Establecer descriptor de acceso para la propiedad "{0}" no está disponible. + + + El método establecedor debe ser público, void, static y tener dos parámetros. El primer parámetro debe ser del tipo PSObject. Se requiere un segundo parámetro si un método captador también está disponible y debe tener el mismo tipo que el tipo de valor devuelto para el método captador. + + + El método captador debe ser público, no void, static y tener un parámetro del tipo PSObject. + + + CodeProperty debe usar un método captador o establecedor. + + + No se puede crear un método de código debido al formato del método. El método debe ser público, estático y tener un parámetro de tipo PSObject. + + + El alias con el nombre "{0}" contiene un ciclo. + + + No se puede convertir el valor "{0}" de tipo "{1}" al tipo "{2}". + + + No se puede convertir el valor de tipo "{0}" al tipo "{1}". + + + No se puede convertir el valor "{0}" al tipo "{1}". Error: "{2}" + + + No se puede convertir el valor "{0}" al tipo "{1}" porque no se permiten comas en esta enumeración. + + + No se puede convertir el valor "{0}" al tipo "{1}" debido a valores de enumeración que no son válidos. Especifique uno de los siguientes valores de enumeración e inténtelo de nuevo. Los valores de enumeración posibles son "{2}". + + + No se puede convertir null al tipo "{0}" debido a que hay valores de enumeración no válidos. Especifique uno de los siguientes valores de enumeración e inténtelo de nuevo. Los valores de enumeración posibles son "{1}". + + + No se puede convertir null al tipo "{0}". + + + No se puede convertir el valor al tipo "{0}". Error: "{1}" + + + No se puede convertir el valor al tipo System.String. + + + Se espera un tipo de referencia en el argumento. + + + No se puede comparar "{0}" porque no es IComparable. + + + No se pudo comparar "{0}" con "{1}". Error: "{2}" + + + No se puede comparar "{0}" con "{1}" porque los objetos no son del mismo tipo o el objeto "{0}" no implementa "{2}". + + + No se puede convertir el valor "{0}" al tipo "{1}" porque se encontraron al menos dos coincidencias ({2}, {3}) y solo se permite una coincidencia para esta enumeración. + + + No se puede convertir el valor "{0}" al tipo "{1}". Los parámetros booleanos solo aceptan valores y números booleanos, como $True, $False, 1 o 0. + + + No se puede obtener el valor de la propiedad porque "{0}" es una propiedad de solo escritura. + + + "{0}" es una propiedad ReadOnly. + + + No se puede establecer "{0}" porque solo se pueden usar cadenas como valores para establecer propiedades XmlNode. + + + No se puede establecer "{0}" porque solo se pueden establecer atributos únicos o nodos hoja únicos sin atributos. + + + No se puede agregar un objeto PSProperty o PSMethod a esta colección. + + + Se produjo el siguiente error al cargar el archivo de datos de tipo extendido: {0} + + + Se produjo la siguiente excepción al recuperar la cadena: "{0}" + + + El campo o propiedad: "{0}" para el tipo : "{1}" solo difiere en mayúsculas y minúsculas del campo o propiedad: "{2}". El tipo debe ser compatible con Common Language Specification (CLS). + + + Se produjo la siguiente excepción al recuperar la jerarquía de nombres de tipo: "{0}". + + + Se produjo la siguiente excepción al recuperar el miembro "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar los miembros: "{0}" + + + Se produjo la siguiente excepción al recuperar el estado de lectura de la propiedad "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar el estado de escritura de la propiedad "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar el tipo para la propiedad "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar la representación de cadena de la propiedad "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar los atributos de la propiedad "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar las definiciones del método "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar la representación de cadena del método "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar el tipo de la propiedad parametrizada "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar el estado de lectura de la propiedad parametrizada "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar el estado de escritura de la propiedad parametrizada "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar las definiciones de la propiedad parametrizada "{1}": "{0}" + + + Se produjo la siguiente excepción al recuperar la representación de cadena de la propiedad parametrizada "{1}": "{0}" + + + No se puede establecer la propiedad Value para el objeto PSMemberInfo de tipo "{0}". + + + Argumento: "{0}" debe ser un {1}. Use {2}. + + + Argumento: "{0}" no debe ser un {1}. No use {2}. + + + No se encontró la propiedad '{0}'. + + + No se puede obtener o establecer el valor de propiedad. El argumento "{0}" debe ser de tipo "{1}" o "{2}". + + + No se puede establecer el valor de la propiedad "{0}" porque el objeto tiene el tipo "{1}" en lugar de "{2}". + + + Excepción que llama a "{0}" : "{1}" + + + {0} no es una ruta de acceso de clase válida. + + + {0} no es una ruta de acceso válida. + + + El adaptador no puede determinar si se puede cambiar la propiedad "{0}". + + + El adaptador no puede determinar si la propiedad "{0}" se puede leer. + + + El adaptador no puede obtener el valor de la propiedad "{0}". + + + El adaptador no puede establecer el valor de la propiedad "{0}". + + + El adaptador no puede obtener el tipo de propiedad "{0}". + + + El adaptador no puede obtener la jerarquía de tipos de "{0}". + + + El adaptador no puede obtener las propiedades de "{0}". + + + El adaptador no puede obtener la propiedad "{0}" para "{1}". + + + "{0}" devolvió un valor null. + + + No se encontró la propiedad "{0}" para el objeto "{1}". Las propiedades configurables son: {2}. + + + No se encontró la propiedad "{0}" para el objeto "{1}". No hay ninguna propiedad configurable disponible. + + + No se puede crear un objeto de tipo "{0}". {1} + + + No se pueden invocar métodos estáticos ni obtener acceso a propiedades estáticas en el tipo genérico abierto {0}. Especifique los parámetros de tipo y vuelva a intentarlo. Por ejemplo, en lugar de [System.Collections.Generic.HashSet``1]::CreateSetComparer(), use [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + Se produjo la siguiente excepción al construir el atributo "{1}": "{0}" + + + El valor "{0}" no se puede convertir en una matriz de cadenas. + + + No se puede convertir el valor al tipo "{0}". En este modo de lenguaje solo se admiten los tipos principales. + + + No se puede convertir al tipo tipo ByRef "{0}". Los tipos de tipo ByRef no se admiten en PowerShell. + + + No se puede obtener ni establecer la propiedad o el campo "{0}" del tipo similar a ByRef "{1}". Los tipos de tipo ByRef no se admiten en PowerShell. + + + No se puede invocar el método "{0}" del tipo de retorno similar a ByRef "{1}". Los tipos de tipo ByRef no se admiten en PowerShell. + + + No se puede crear una instancia del tipo byRef "{0}". Los tipos de tipo ByRef no se admiten en PowerShell. + + + Conversión de tabla hash del sistema de tipos extendidos + + + La conversión de tipos de HashTable a "{0}" no se permitirá en el modo ConstrainedLanguage. + + + Conversión de tabla hash del sistema de tipos extendidos + + + La conversión de tipos de "{0}" a "{1}" no se permitirá en el modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/FileSystemProviderStrings.es.resx b/src/System.Management.Automation/resources/es/FileSystemProviderStrings.es.resx new file mode 100644 index 00000000000..c7cfa089776 --- /dev/null +++ b/src/System.Management.Automation/resources/es/FileSystemProviderStrings.es.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Invoke Item + + + Item: {0} + + + Remove File + + + Remove Directory + + + Copy File + + + Item: {0} Destination: {1} + + + Copy Directory + + + Rename File + + + Rename Directory + + + Item: {0} Destination: {1} + + + Move File + + + Move Directory + + + Item: {0} Destination: {1} + + + Set Property File + + + Set Property Directory + + + Item: {0} Property: {1} Value: {2} + + + Clear Property File + + + Clear Property Directory + + + Item: {0} Property: {1} + + + Create File + + + Create Directory + + + Destination: {0} + + + Clear Content + + + Item: {0} + + + Could not find item {0}. + + + Cannot remove item {0}: {1} + + + Cannot restore attributes on item {0}: {1} + + + An object at the specified path {0} does not exist. + + + Directory {0} cannot be removed because it is not empty. + + + The type is not a known type for the file system. Only "file","directory" or "symboliclink" can be specified. + + + Cannot process the path because the specified path refers to an item that is outside the basePath. + + + The specified drive root "{0}" either does not exist, or it is not a folder. + + + An item with the specified name {0} already exists. + + + A delimiter cannot be specified when reading the stream one byte at a time. + + + Cannot overwrite the item {0} with itself. + + + Cannot rename the specified target, because it represents a path or device name. + + + The property {0} does not exist or was not found. + + + You do not have sufficient access rights to perform this operation or the item is hidden, system, or read only. + + + The attribute cannot be set because attributes are not supported. Only the following attributes can be set: Archive, Hidden, Normal, ReadOnly, or System. + + + The property cannot be cleared because the property is not supported. Only the Attributes property can be cleared. + + + Cannot process path '{0}' because the target represents a reserved device name. + + + Encoding not used when '-AsByteStream' specified. + + + Cannot proceed with byte encoding. When using byte encoding the content must be of type byte. + + + Cannot process the file because the file {0} was not found. + + + Directory: + + + Cannot detect the encoding of the file. The specified encoding {0} is not supported when the content is read in reverse. + + + Could not open the alternate data stream '{0}' of the file '{1}'. + + + Stream '{0}' of file '{1}'. + + + The Raw and Wait parameters cannot be specified in the same command. + + + To use the Persist switch parameter, the drive name must be supported by the operating system (for example, drive letters A-Z). + + + When you use the Persist parameter, the root must be a file system location on a remote computer. + + + The '{0}' and '{1}' parameters cannot be specified in the same command. + + + A directory is required for the operation. The item '{0}' is not a directory. + + + Create Junction + + + Create Symbolic Link + + + Administrator privilege required for this operation. + + + Create Hard Link + + + A file is required for the operation. The item '{0}' is not a file. + + + Hard links are not supported for the specified path. + + + Symbolic links are not supported for the specified path. + + + Copiando {0} en {1} + + + Destination path {0} is a file that already exists on the target destination. + + + Failed to copy file {0} to remote target destination. + + + De {0} a {1} + + + Cannot copy a directory '{0}' to file '{0}' + + + Failed to get directory {0} child items. + + + Failed to read remote file '{0}'. + + + Cannot validate if remote destination {0} is a file. + + + Failed to create directory '{0}' on remote destination. + + + Maximum size for drive has been exceeded: {0}. + + + Cannot create link because the path already exists: {0}. + + + Skip already-visited directory {0}. + + + Destination path cannot be a subdirectory of the source or the source itself: {0}. + + + The target and path cannot be the same. + + + Copied {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Removed {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Creating a junction requires an absolute path for the target. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/FormatAndOutXmlLoadingStrings.es.resx b/src/System.Management.Automation/resources/es/FormatAndOutXmlLoadingStrings.es.resx new file mode 100644 index 00000000000..9dba497bfd9 --- /dev/null +++ b/src/System.Management.Automation/resources/es/FormatAndOutXmlLoadingStrings.es.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Error en XPath {0} del archivo {1}: el elemento XML {2} no permite atributos. + + + Error en XPath {0} del archivo {1}: el nodo {2} no puede tener objetos secundarios. + + + Error en XPath {0} en el archivo {1}: {2} no es válido. + + + Error en XPath {0} del archivo {1}: debe haber al menos un valor predeterminado {2}. + + + Error en XPath {0} del archivo {1}: no puede haber más de un valor predeterminado {2}. + + + Error en XPath {0} del archivo {1}: el nombre del control no puede ser nulo ni estar vacío. + + + Error en XPath {0} del archivo {1}: las vistas fuera de banda solo pueden tener CustomControl o ListControl. + + + Error en XPath {0} del archivo {1}: una vista fuera de banda no puede tener GroupBy. + + + Error en XPath {0} del archivo {1}: no se puede cargar la vista. + + + Error en XPath {0} del archivo {1}: "{2}" no es un valor de alineación válido. + + + Error en XPath {0} del archivo {1}: se espera un entero positivo. + + + Error en XPath {0} del archivo {1}: la definición del encabezado de columna no es válida; se descartan todos los encabezados. + + + Error en XPath {0} del archivo {1}: el recuento de elementos de fila = {2} del conjunto alternativo #{3} no coincide con el recuento predeterminado de elementos de fila = {4}. + + + Error en XPath {0} del archivo {1}: el recuento de elementos del encabezado = {2} no coincide con el recuento predeterminado de elementos de fila = {3}. + + + Error en XPath {0} del archivo {1}: se debe especificar al menos un elemento de vista de lista. + + + Error en XPath {0} del archivo {1}: la entrada de propiedad no es válida. + + + Error en XPath {0} del archivo {1}: falta la lista de definiciones. + + + Error en XPath {0} del archivo {1}: se espera un valor booleano. + + + Error en XPath {0} del archivo {1}: se espera un entero no negativo. + + + Error en XPath {0} del archivo {1}: se espera un entero. + + + Error en XPath {0} del archivo {1}: falta el valor de texto interno. + + + Error en XPath {0} en el archivo {1}: la lista de tokens de control personalizado no puede estar vacía. + + + Error en XPath {0} del archivo {1}: error al cargar {2}. + + + Error en XPath {0} del archivo {1}: no se puede especificar {2} sin una expresión. + + + Error en XPath {0} del archivo {1}: no se puede especificar {2} con una expresión. + + + Error en XPath {0} del archivo {1}: falta una cadena de formato. + + + Error en XPath {0} del archivo {1}: falta el texto del bloque de script. + + + Error en XPath {0} del archivo {1}: falta una propiedad. + + + Error en XPath {0} del archivo {1}: el bloque de script "{2}" no es válido. + + + Error en XPath {0} del archivo {1}: no se encuentra la cadena {2} del recurso {3} en el ensamblado {4}. + + + Error en XPath {0} del archivo {1}: no se encuentra el recurso {2} en el ensamblado {3}. + + + Error en XPath {0} del archivo {1}: no se encuentra el ensamblado {2}. + + + Error en XPath {0} del archivo {1}: el nodo debe ser un XmlElement. + + + Error en XPath {0} del archivo {1}: se espera una expresión. + + + Error en XPath {0} del archivo {1}: no se puede tener el control o la etiqueta sin una expresión. + + + Error en XPath {0} del archivo {1}: no se pueden tener el control y la etiqueta al mismo tiempo. + + + Error en XPath {0} del archivo {1}: no se pueden tener SelectionSetName y TypeName al mismo tiempo. + + + Error en XPath {0} del archivo {1}: no se ha especificado ningún tipo ni condición para aplicar la vista. + + + Error en XPath {0} del archivo {1}: el valor {2} no es válido. + + + Error en XPath {0} del archivo {1}: existe un nodo duplicado. + + + Error en XPath {0} del archivo {1}: {2} y {3} se excluyen mutuamente. + + + Error en XPath {0} del archivo {1}: {2}, {3} y {4} se excluyen mutuamente. + + + Error en XPath {0} en el archivo {1}: {2} es un nodo desconocido. + + + Error en XPath {0} del archivo {1}: {2} es un atributo desconocido. + + + Error en XPath {0} del archivo {1}: {2} es un atributo que falta. + + + Error en XPath {0} en el archivo {1}: falta el nodo {2}. + + + Error en XPath {0} del archivo {1}: falta un nodo de {2}. + + + Error en XPath {0} del archivo {1}: {2} es un nodo vacío. + + + Error en XPath {0} del archivo {1}: {2} es un atributo vacío. + + + Error en el archivo {0}: {1} + + + Hay demasiados errores en el archivo {0}. + + + Se han producido errores al cargar el archivo de datos de formato: {0} + + + (Caché global de ensamblados) {0} + + + {0}, {1} + + + La ruta {0} no está completa. Especifique una ruta de acceso de archivo de formato completa. + + + No se puede actualizar FormatTable porque es posible que se haya creado fuera del espacio de ejecución. + + + Se han producido errores al cargar FormatTable. Consulte el contenido de la propiedad Errors para obtener mensajes de error detallados. + + + Error al dar formato a los datos "{0}": {1} + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: el recuento de elementos del encabezado = {2} no coincide con el recuento de elementos predeterminado de la fila = {3}. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: los datos de formato "{2}" no son válidos. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: el bloque de script "{2}" no es válido. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: {2} no se pudo cargar. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: TableControl solo debe contener una {2}. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: debe haber al menos un valor predeterminado {2}. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: se debe especificar al menos un elemento de vista de lista. + + + Error en los datos de vista con el nombre de tipo {0} en el índice {1}: no puede haber más de un valor predeterminado {2}. + + + Hay demasiados errores en los datos de formato para el tipo "{0}". + + + Una tabla de formato compartida no se puede actualizar con más de una entrada. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/FormatAndOut_MshParameter.es.resx b/src/System.Management.Automation/resources/es/FormatAndOut_MshParameter.es.resx new file mode 100644 index 00000000000..917b0a743a0 --- /dev/null +++ b/src/System.Management.Automation/resources/es/FormatAndOut_MshParameter.es.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 + + + No se puede convertir {0} a uno de los siguientes tipos {1}. + + + El valor de un parámetro era nulo; se esperaba uno de los siguientes tipos: {0}. + + + La clave duplicada "{0}" entra en conflicto con "{1}". + + + La clave "{0}" tiene un tipo, {1}, que no es válido; los tipos esperados son {2}. + + + La clave "{0}" tiene un tipo, {1}, que no es válido; el tipo esperado es {2}. + + + La clave {0} es ambigua; {1} y {2} entran en conflicto. + + + El valor de una clave no puede ser nulo. + + + El tipo de clave {0} no es válido. La clave debe ser una cadena. + + + La clave {0} no tiene ningún valor. + + + Falta una entrada obligatoria para {0}. + + + La clave de {0} no es válida. + + + El valor "{0}" para la clave "{1}" no es válido; los valores válidos son {2}. + + + El valor "{0}" para la clave "{1}" debe ser mayor que 0. + + + No puede haber una cadena de formato vacía para la clave "{0}". + + + La clave "{0}" no puede tener un valor de cadena vacío. + + + No se permite un valor de cadena vacío. + + + La clave "{0}" no puede tener caracteres comodín en el valor "{1}". + + + No se permiten caracteres comodín en "{0}". + + + El valor de EnumerableExpansion no es válido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/FormatAndOut_format_xxx.es.resx b/src/System.Management.Automation/resources/es/FormatAndOut_format_xxx.es.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/es/FormatAndOut_format_xxx.es.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/FormatAndOut_out_xxx.es.resx b/src/System.Management.Automation/resources/es/FormatAndOut_out_xxx.es.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/es/FormatAndOut_out_xxx.es.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/GetErrorText.es.resx b/src/System.Management.Automation/resources/es/GetErrorText.es.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/es/GetErrorText.es.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/HelpDisplayStrings.es.resx b/src/System.Management.Automation/resources/es/HelpDisplayStrings.es.resx new file mode 100644 index 00000000000..7efb6c17e21 --- /dev/null +++ b/src/System.Management.Automation/resources/es/HelpDisplayStrings.es.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NOMBRE + + + SINOPSIS + + + DESCRIPCIÓN + + + SINTAXIS + + + PARÁMETROS + + + ENTRADAS + + + SALIDAS + + + ERRORES DE TERMINACIÓN + + + ERRORES DE NO TERMINACIÓN + + + NOTAS + + + EJEMPLOS + + + Ejemplo + + + EJEMPLO + + + RESULTADO + + + VÍNCULOS RELACIONADOS + + + DESCRIPCIÓN BREVE + + + Título: + + + Pregunta: + + + Respuesta + + + Término: + + + Definición: + + + Contenido: + + + NOMBRE DEL PROVEEDOR + + + Este cmdlet admite los parámetros comunes: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, y OutVariable. Para más información, consulte + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + ¿Obligatorio? + + + ¿Posición? + + + Tipo: + + + Tipo de objeto de destino: + + + Valor predeterminado + + + ¿Aceptar la entrada de la canalización? + + + ¿Aceptar caracteres comodín? + + + (Categoría: + + + Acción sugerida: + + + Para obtener más información, escriba: + + + Para obtener información técnica, escriba: + + + Para ver los ejemplos, escriba: + + + Para obtener ayuda en línea, escriba: + + + <CommonParameters> + + + COMENTARIOS + + + true + + + Con nombre + + + UNIDADES + + + FUNCIONALIDADES + + + TAREAS + + + TAREA: + + + FILTROS + + + PARÁMETROS DINÁMICOS + + + Cmdlets admitidos: + + + ALIAS + + + Get-Help no puede encontrar los archivos de Ayuda para este cmdlet en este equipo. Solo muestra ayuda parcial. + -- Para descargar e instalar los archivos de Ayuda del módulo que incluye este cmdlet, use Update-Help. + -- Para ver el tema de Ayuda de este cmdlet en línea, escriba: "Get-Help {0} -Online" o + vaya a {1}. + + + Ninguno + + + Alias + + + ¿Dinámico? + + + Nombre del conjunto de parámetros + + + No se puede recuperar el archivo XML de HelpInfo para el idioma de interfaz de usuario {0}. Asegúrese de que la propiedad HelpInfoUri del manifiesto del módulo es válida o compruebe la conexión de red e intente ejecutar el comando de nuevo. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + No se admite la referencia cultural especificada: {0}. Especifique una referencia cultural de la lista siguiente: {{{1}}}. + + + Si se pospone el error y se prueban las referencias culturales de reserva, se mostrará como error si no se admite ninguna de las referencias de reserva: +{0} + + + No se encuentra el directorio ModuleBase. Compruebe el directorio e inténtelo de nuevo. + + + La ruta de acceso {0} no es un directorio válido. Asegúrese de que el directorio existe y vuelva a intentarlo. + + + Un URI de Ayuda no puede contener más de 10 redirecciones. Especifique un URI de Ayuda válido. + + + Actualización de Ayuda + + + Conectando con el contenido de Ayuda... + + + Descargando contenido de Ayuda... + + + Instalando contenido de Ayuda... + + + Buscando contenido de Ayuda... + + + (Todos) + + + No se encontraron módulos de PowerShell que coincidan con el siguiente patrón: {0}. Compruebe el patrón e intente de nuevo el comando. + + + No se encontraron módulos de PowerShell que coincidan con el FullyQualifiedModule {0} especificado. Compruebe el valor de FullyQualifiedModule e intente ejecutar el comando de nuevo. + + + No se encuentra el contenido de Ayuda. Asegúrese de que el servidor está disponible y de que la ubicación del contenido de Ayuda está definida correctamente en el XML de HelpInfo. + + + Se ha producido un error en el comando Update-Help porque el módulo especificado no admite ayuda que se pueda actualizar. Use Get-Help -Online o busque ayuda en línea para los comandos de este módulo. + + + El siguiente parámetro no debe ser null ni estar vacío: Module. + + + El siguiente parámetro no debe ser null ni estar vacío: Path. + + + Update-Help se ha completado correctamente. + + + Error al extraer el contenido de Ayuda. + + + No se puede conectar al contenido de la Ayuda. Es posible que el servidor en el que se almacena el contenido de la Ayuda no esté disponible. Compruebe que el servidor está disponible o espere a que vuelva a estar en línea e intente ejecutar el comando de nuevo. + + + El contenido de Ayuda en la ubicación especificada no es válido. Especifique una ubicación que contenga contenido de Ayuda válido. + + + El XML de HelpInfo no es válido. Especifique XML de HelpInfo válido. + + + El contenido de Ayuda se guardó correctamente en la siguiente ubicación: {0} + + + No se encuentra el archivo XSD de contenido de Ayuda en {0}. Compruebe que el archivo XSD existe en la ubicación especificada y, a continuación, vuelva a intentar el comando. + + + No se pudo guardar la Ayuda para los módulos: +"{0}" +{1} + + + Guardando Ayuda + + + El contenido de Ayuda contiene archivos que no son válidos. Solo se admiten archivos .txt y .xml. + + + No se pudo guardar la Ayuda para los módulos "{0}": {1} + + + No se pudo guardar la Ayuda para los módulos "{0}" con los idiomas de interfaz de usuario {{{1}}} : {2}. +El contenido de Ayuda de English-US está disponible y se puede guardar mediante: Save-Help -UICulture en-US. + + + No se pudo actualizar la Ayuda para los módulos "{0}" con los idiomas de interfaz de usuario {{{1}}} : {2}. +El contenido de Ayuda de English-US está disponible y se puede instalar mediante: Update-Help -UICulture en-US. + + + La cultura actual es ({0}), que no está asociada a ningún idioma. Considere la posibilidad de cambiar la referencia cultural del sistema o instalar el contenido de ayuda de inglés de EE. UU. mediante: Update-Help -UICulture en-US. + + + falso + + + El parámetro -Recurse solo está disponible si se especifica una ruta de acceso de origen. + + + La ruta de acceso {0} no contiene un proveedor FileSystem. Compruebe que la ruta de acceso especificada contiene el proveedor FileSystem y, a continuación, vuelva a intentar el comando. + + + Buscando Ayuda para {0} ... + + + No se encontró ningún idioma de interfaz de usuario que coincida con el siguiente patrón: {0}. Compruebe el patrón e intente de nuevo el comando. + + + No se guardó la Ayuda del módulo {0} porque el comando Save-Help se ejecutó en este equipo en las últimas 24 horas. +Para guardar la Ayuda de nuevo, agregue el parámetro Force al comando. + + + No se actualizó la Ayuda del módulo {0} porque el comando Update-Help se ejecutó en este equipo en las últimas 24 horas. +Para actualizar la Ayuda de nuevo, agregue el parámetro Force al comando. + + + Ya se han instalado los archivos de Ayuda más recientes. + + + {0}: {1}. Cultura {2} versión {3} + + + Actualizado {0} + + + El valor de la clave HelpInfoUri en el manifiesto del módulo debe resolverse en una URL raíz o contenedor en un sitio web donde se almacenan los archivos de ayuda. El HelpInfoUri "{0}" no se resuelve en un contenedor. + + + El contenido de Ayuda debe estar en el espacio de nombres {0}. + + + Get-Help no puede encontrar los archivos de Ayuda para este cmdlet en este equipo. Solo muestra ayuda parcial. + -- Para descargar e instalar los archivos de Ayuda del módulo que incluye este cmdlet, use Update-Help. + + + Ya se han descargado los archivos de Ayuda más recientes. + + + Se guardó {0} + + + El HelpInfoURI {0} no comienza con HTTP. + + + El elemento a nivel raíz del contenido de la Ayuda debe ser "helpItems". + + + Guardando Ayuda para el módulo {0} + + + Actualizando Ayuda para el módulo {0} + + + Resolviendo URI: "{0}" + + + URI de Ayuda: {0} + + + {0}, Versión actual: {1}, Versión disponible: {2}, UICulture: {3} + + + PROPIEDADES + + + MÉTODOS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/HelpErrors.es.resx b/src/System.Management.Automation/resources/es/HelpErrors.es.resx new file mode 100644 index 00000000000..bd2a7f276e8 --- /dev/null +++ b/src/System.Management.Automation/resources/es/HelpErrors.es.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help no pudo encontrar {0} en un archivo de ayuda de esta sesión. Para descargar temas de Ayuda actualizados, escriba: "Update-Help". Para obtener ayuda en pantalla, busque el tema de ayuda en la biblioteca de TechNet en https://go.microsoft.com/fwlink/?LinkID=107116. + + + No se puede procesar la categoría de Ayuda porque "{0}" no es una categoría de Ayuda válida. + + + No se puede cargar el archivo de Ayuda "{0}". Detalles: {1}. + + + No se puede acceder al archivo de Ayuda "{0}" porque el usuario actual no tiene permisos de acceso al archivo. Detalles: {1}. + + + El archivo de Ayuda "{0}" no es un documento XML válido. Detalles: {1}. + + + Se produjo un error al cargar el contenido de Ayuda para {0} desde el archivo {1}. Detalles: {2}. Para descargar los temas de Ayuda actualizados, ejecute el cmdlet Update-Help. Para obtener ayuda en pantalla, busque el tema de Ayuda en la biblioteca de TechNet en https://go.microsoft.com/fwlink/?LinkID=107116. + + + No se puede cargar el proveedor "{0}". Detalles: {1}. + + + No se puede cargar el archivo de Ayuda. Se produjeron los siguientes {1} errores al cargar el archivo de Ayuda "{0}". + + + El nodo "{0}" no puede tener "{1}" como nodo secundario. Ruta del nodo: {2}. + + + El nodo "{0}" puede tener un máximo de {2} nodos secundarios de tipo "{1}". Ruta del nodo: {3}. + + + No se encuentra la clave del Registro: "{0}{1}"; se está usando "{2}" para cargar los archivos de Ayuda. + + + No hay ningún parámetro que coincida con los criterios {0}. + + + {0} no es compatible con la categoría de Ayuda solicitada. + + + No se puede mostrar la versión en línea de este tema de Ayuda porque la dirección de Internet (URI) del tema de Ayuda no está especificada en el código del comando ni en el archivo de Ayuda del comando. + + + El URI {0} especificado no es válido. + + + Error al iniciar un explorador para mostrar la Ayuda en pantalla. No hay ningún programa ni explorador asociado para abrir el URI {0}. + + + No se admite el protocolo especificado en el URI "{0}". Solo se admiten los protocolos "{1}" y "{2}". + + + Se encontraron varios temas de Ayuda. Use solo un tema de Ayuda con la opción -{0}. + + + No se puede obtener Ayuda de un espacio de ejecución remoto porque no se ha abierto. Abra el espacio de ejecución ejecutando un comando remoto implícito y, después, vuelva a intentar ejecutar el comando para obtener Ayuda. + + + Acceso denegado. El comando no pudo actualizar los temas de Ayuda de los módulos principales de PowerShell ni de ningún módulo del directorio $pshome\Modules. +Para actualizar estos temas de Ayuda, inicie PowerShell con el comando "Ejecutar como administrador" e intente ejecutar Update-Help de nuevo. + + + Para usar el {0}, asegúrese de que la aplicación usa "Microsoft.NET.Sdk.WindowsDesktop" como SDK del proyecto y de que el ensamblado correspondiente "Microsoft.PowerShell.GraphicalHost" está disponible. ({1}) + + + {0} no funciona en una sesión remota. + + + ForwardHelpTargetName no puede hacer referencia a la propia función. + + + No se puede obtener Ayuda de una ubicación de red cuando se está en una sesión restringida. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/HistoryStrings.es.resx b/src/System.Management.Automation/resources/es/HistoryStrings.es.resx new file mode 100644 index 00000000000..7dffccf7a49 --- /dev/null +++ b/src/System.Management.Automation/resources/es/HistoryStrings.es.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 identifier {0} is not a valid value for a History identifier. Specify a positive number, and then try again. + + + Cannot locate the history for Id {0}. + + + The count cannot be combined with multiple Ids. + + + Cannot locate the history for command line {0}. + + + Cannot locate most recent history. + + + The Invoke-History cmdlet is called repeatedly, in a loop. + + + Cannot process multiple history commands. You can only run a single command by using Invoke-History. + + + Cannot add history because the input object has a format that is not valid. + + + The identifier {0} is not valid. Specify a positive number, and then try again. + + + This command will clear all the entries from the session history. + + + The count cannot be combined with multiple CommandLine parameters. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/HostInterfaceExceptionsStrings.es.resx b/src/System.Management.Automation/resources/es/HostInterfaceExceptionsStrings.es.resx new file mode 100644 index 00000000000..b6333d4e8f0 --- /dev/null +++ b/src/System.Management.Automation/resources/es/HostInterfaceExceptionsStrings.es.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 + + + Se ha producido un error de tipo "{0}". + + + Un comando que solicita información al usuario falló porque el programa host o el tipo de comando no admite la interacción con el usuario. Pruebe con un programa host que sí admita la interacción con el usuario, como la consola de PowerShell, y quite los comandos relacionados con solicitudes de los tipos de comando que no admiten la interacción con el usuario. + + + Un comando que solicita información al usuario falló porque el programa host o el tipo de comando no admite la interacción con el usuario. El host intentaba solicitar confirmación con el siguiente mensaje: {0} + + + No se puede invocar el método porque el pool se ha cerrado o ha fallado. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/InternalCommandStrings.es.resx b/src/System.Management.Automation/resources/es/InternalCommandStrings.es.resx new file mode 100644 index 00000000000..377a1f19d70 --- /dev/null +++ b/src/System.Management.Automation/resources/es/InternalCommandStrings.es.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched methods. Possible matches include:{1}. + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched members. Possible matches include:{1}. + + + Retrieve the value for key '{0}' + + + Invoke method '{0}' with arguments: {1} + + + Invoke method '{0}' + + + Retrieve the value for property '{0}' + + + InputObject: {0} + + + Cannot operate on a 'null' input object. + + + Input name "{0}" cannot be resolved to a method. + + + Cannot invoke a method in the restricted language mode. + + + The -WhatIf and -Confirm parameters are not supported for script blocks. + + + The '{0}' operation is not allowed in the RestrictedLanguage mode. + + + An operator is required to compare the two specified values. Include a valid operator in the command, and then try the command again. For example, Get-Process | Where-Object -Property Name -eq Idle + + + The input name "{0}" cannot be resolved to a property. + + + The input name "{0}" cannot be resolved to a member. + + + The specified operator requires both the -Property and -Value parameters. Provide values for both parameters, and then try the command again. + + + This method cannot be run on the current thread. It can only be called on the cmdlet thread. + + + A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + A ForEach-Object -Parallel piped input object cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + The 'TimeoutSeconds' parameter cannot be used with the 'AsJob' parameter. + + + The following common parameters are not currently supported in the Parallel parameter set: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/InternalHostStrings.es.resx b/src/System.Management.Automation/resources/es/InternalHostStrings.es.resx new file mode 100644 index 00000000000..860c67ed30c --- /dev/null +++ b/src/System.Management.Automation/resources/es/InternalHostStrings.es.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 + + + No se ha llamado a EnterNestedPrompt tantas veces como a ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/InternalHostUserInterfaceStrings.es.resx b/src/System.Management.Automation/resources/es/InternalHostUserInterfaceStrings.es.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/es/InternalHostUserInterfaceStrings.es.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/Logging.es.resx b/src/System.Management.Automation/resources/es/Logging.es.resx new file mode 100644 index 00000000000..64728e00c48 --- /dev/null +++ b/src/System.Management.Automation/resources/es/Logging.es.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + DESCONOCIDO + + + La característica experimental del motor "{0}" declarada en el archivo de configuración no está registrada en la versión actual de PowerShell. + + + La característica experimental "{0}" declarada en el archivo de configuración no es válida. +El nombre de una característica experimental debe seguir la convención siguiente: + Nombre de la característica del motor: "PS[FeatureName]" + Nombre de la característica del módulo: "[ModuleName].[FeatureName]" + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/Metadata.es.resx b/src/System.Management.Automation/resources/es/Metadata.es.resx new file mode 100644 index 00000000000..ee55d1bb9a7 --- /dev/null +++ b/src/System.Management.Automation/resources/es/Metadata.es.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se pueden inicializar atributos para "{0}": "{1}" + + + No se puede validar el argumento porque su tipo "{0}" no es del mismo tipo ({1}) que los límites máximo y mínimo del parámetro. Asegúrese de que el argumento es de tipo {1} e intente el comando de nuevo. + + + No se puede validar el argumento "{0}" porque su valor no es mayor que cero. + + + No se puede validar el argumento "{0}" porque su valor no es mayor o igual que cero. + + + No se puede validar el argumento "{0}" porque su valor no es menor que cero. + + + No se puede validar el argumento "{0}" porque su valor no es menor o igual que cero. + + + No se puede aceptar el intervalo mínimo especificado ({0}) porque no es del mismo tipo que el intervalo máximo especificado ({1}). Actualice el atributo ValidateRange para el parámetro. + + + No se pueden aceptar los tipos de parámetro MaxRange y MinRange. Ambos parámetros deben ser objetos que implementen una interfaz IComparable. + + + No se puede aceptar el intervalo máximo especificado porque es menor que el intervalo mínimo especificado. Actualice el atributo ValidateRange para el parámetro. + + + El argumento {0} es mayor que el intervalo máximo permitido de {1}. Proporcione un argumento menor o igual que {1} e intente el comando de nuevo. + + + El argumento {0} es menor que el intervalo mínimo permitido de {1}. Proporcione un argumento mayor o igual {1} que e intente el comando de nuevo. + + + El argumento "{0}" no coincide con el patrón "{1}". Proporcione un argumento que coincida con "{1}" e intente el comando de nuevo. + + + El atributo ValidateCount no se puede aplicar a un parámetro que no es de matriz. Quite el atributo del parámetro o convierta el parámetro en un parámetro de matriz. + + + El parámetro requiere exactamente {0} valores: {1} se proporcionaron valores. + + + El parámetro requiere al menos {0} valores y no más de {1} valores: {2} se proporcionaron valores. + + + El número máximo de argumentos especificado para un parámetro es menor que el número mínimo de argumentos especificado. Actualice el atributo ValidateCount para el parámetro. + + + La longitud de caracteres máxima especificada del argumento es menor que la longitud mínima de caracteres del argumento especificada. Actualice el atributo ValidateLength para el parámetro. + + + El atributo ValidateLength no se puede aplicar a un parámetro que no es un parámetro string o string[]. Convierta el parámetro en un parámetro string o string[]. + + + La longitud del carácter ({1}) del argumento es demasiado corta. Especifique un argumento con una longitud mayor o igual que "{0}" e intente el comando de nuevo. + + + La longitud de caracteres ({1}) del argumento es demasiado larga. Especifique un argumento con una longitud menor o igual que "{0}" e intente el comando de nuevo. + + + El argumento "{0}" no pertenece al conjunto "{1}" especificado por el atributo ValidateSet. Proporcione un argumento que esté en el conjunto e intente el comando de nuevo. + + + El generador de valores válidos devuelve un valor null. + + + "{0}" error en la propiedad "{1}" {2} + + + No se puede obtener o ejecutar el comando. Se ha superado el número máximo de conjuntos de parámetros para este comando. + + + No se puede procesar el argumento porque el valor del argumento no es una cadena. Los valores de los argumentos de parámetro que tienen especificado ArgumentTransformationAttribute deben ser cadenas. + + + No se puede validar la variable porque el valor {1} no es un valor válido para la {0} variable. + + + No se puede agregar el atributo porque la variable {0} con valor {1} ya no sería válida. + + + El argumento es null. Proporcione un valor válido para el argumento e intente ejecutar el comando de nuevo. + + + El argumento tiene un valor null, o un elemento de la colección de argumentos contiene un valor nulo. Proporcione una colección que no contenga valores null e intente de nuevo el comando. + + + El argumento es nulo o está vacío. Especifique un argumento que no sea NULL o esté vacío y, después, vuelva a intentar el comando. + + + El argumento es null, está vacío o un elemento de la colección de argumentos contiene un valor null. Proporcione una colección que no contenga valores null e intente el comando de nuevo. + + + El argumento es null, está vacío o solo consta de caracteres de espacio en blanco. Proporcione un argumento que contenga caracteres que no contengan espacios en blanco e intente el comando de nuevo. + + + Un elemento de la colección de argumentos es null, está vacío o solo consta de caracteres de espacio en blanco. Proporcione una colección que no contenga esos valores e intente el comando de nuevo. + + + Un parámetro con el nombre "{0}" se definió varias veces para el comando. + + + No se puede especificar el alias de parámetro porque ya se definió varias veces un alias con el nombre "{0}" para el comando. + + + No se puede especificar el parámetro "{0}" porque entra en conflicto con el alias de parámetro del mismo nombre para el parámetro "{1}". + + + El script de validación "{1}" para el argumento con el valor "{0}" no devolvió un resultado de True. Determine por qué se produjo un error en el script de validación e intente el comando de nuevo. + + + El argumento "{0}" no contiene una versión válida de PowerShell. Proporcione un número de versión válido e intente el comando de nuevo. + + + No se puede validar el argumento "{0}" porque no es un nombre de variable válido. + + + El tipo de conversión de trabajo debe derivarse de IAstToScriptBlockConverter. + + + El argumento de ruta de acceso no es válido. Proporcione un argumento de ruta de acceso que sea un tipo de cadena. + + + La unidad de argumento de {0} ruta de acceso no pertenece al conjunto de unidades aprobadas: {1}. Proporcione un argumento de ruta de acceso con una unidad aprobada. + + + El argumento de ruta de acceso contiene caracteres no válidos. + + + El argumento de ruta de acceso no tiene ninguna unidad raíz. Proporcione un argumento de ruta de acceso completa con una unidad raíz. + + + El valor del argumento del parámetro "{0}" no puede ser nulo ni una cadena vacía. + + + El miembro de enumeración "{0}" no es un valor válido para el parámetro "{1}". Especifique uno de los siguientes miembros e inténtelo de nuevo: {2}. + + + No se puede procesar la entrada. El argumento "{0}" no es de confianza. + + + Error en la comprobación del atributo ValidateTrustedData + + + El argumento de parámetro "{0}" no es de confianza y se producirá un error en la comprobación del atributo de parámetro ValidateTrustedData en el modo de lenguaje restringido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/MiniShellErrors.es.resx b/src/System.Management.Automation/resources/es/MiniShellErrors.es.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/es/MiniShellErrors.es.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/Modules.es.resx b/src/System.Management.Automation/resources/es/Modules.es.resx new file mode 100644 index 00000000000..1970254de11 --- /dev/null +++ b/src/System.Management.Automation/resources/es/Modules.es.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se cargó el módulo especificado "{0}" porque no se encontró ningún archivo de módulo válido en ningún directorio de módulos. + + + El módulo especificado "{0}" con la versión "{1}" no se cargó porque no se encontró ningún archivo de módulo válido en ningún directorio de módulo. + + + El valor de MaximumVersion "{0}" especificado no era correcto. Si usa "*", MaximumVersion solo admite un "*" y siempre debe colocarse al final de MaximumVersion. + + + El módulo especificado "{0}" con MaximumVersion "{1}" no se cargó porque no se encontró ningún archivo de módulo válido en ningún directorio de módulos. + + + No se cargó el módulo especificado "{0}" con MinimumVersion "{1}" y MaximumVersion "{2}" porque no se encontró ningún archivo de módulo válido en ningún directorio de módulos. + + + MinimumVersion "{0}" no debe ser mayor que MaximumVersion "{1}". + + + No se cargó el ensamblado "{0}" porque no se encontró ningún ensamblado con ese nombre. Compruebe el nombre del ensamblado e inténtelo de nuevo. + + + El módulo que se va a procesar "{0}", incluido en el campo "{1}" del manifiesto del módulo "{2}", no se procesó porque no se encontró ningún módulo válido en ningún directorio de módulos. + + + No se devolvió ningún objeto personalizado para el módulo "{0}" porque el parámetro -AsCustomObject solo se puede usar con módulos de script. + + + No se pudo procesar el manifiesto del módulo "{0}" porque no es un archivo de manifiesto de módulo de PowerShell válido. Quite los elementos que no están permitidos: {1} + + + El procesamiento del archivo de manifiesto de módulo "{0}" no dio como resultado un objeto de manifiesto válido. Actualice el archivo para que contenga un manifiesto de módulo de PowerShell válido. Puede crear un manifiesto válido con el cmdlet New-ModuleManifest. + + + No se puede importar el módulo "{0}" porque su manifiesto contiene uno o varios miembros que no son válidos. Los miembros de manifiesto válidos son ({1}). Quite los miembros que no son válidos ({2}) e intente importar el módulo de nuevo. + + + La tabla hash que describe un módulo contiene uno o varios miembros que no son válidos. Los miembros válidos son ({0}). Quite los miembros que no son válidos ({1}) e inténtelo de nuevo. + + + No se puede cargar el módulo "{0}" porque se ha superado el límite de anidamiento del módulo. Los módulos solo se pueden anidar a {1} niveles. Evalúe y cambie el orden en que se cargan los módulos para evitar superar el límite de anidamiento e intente ejecutar el script de nuevo. + + + El miembro "ModuleVersion" no está presente en el manifiesto del módulo. Este miembro debe existir y tener asignado un número de versión con el formato "n.n.n.n". Agregue el miembro que falta al archivo ''{0}". + + + El miembro "{0}" no es válido en el archivo de manifiesto de módulo ''{2}": {1} + + + La versión "{0}" del módulo "{1}" no cumple la versión mínima requerida ''{2}. Compruebe que se admite el número de versión e intente cargar el módulo de nuevo. + + + La versión de PowerShell en este equipo es ''{0}". El módulo "{1}" requiere una versión mínima de PowerShell de "{2}" para ejecutarse. Compruebe que tiene instalada la versión mínima necesaria de PowerShell e inténtelo de nuevo. + + + No se puede usar el miembro de manifiesto de módulo "NestedModules" si el miembro 'ModuleToProcess' es un módulo binario. Edite el archivo de manifiesto del módulo en "{0}" e inténtelo de nuevo. + + + El miembro "{0}" del manifiesto del módulo no es válido: {1}. Compruebe que se ha especificado un valor válido para este campo en el archivo ''{2}". + + + La ruta de acceso del manifiesto del módulo "{0}" no es válida. El valor del argumento Path debe resolverse en un único archivo que tenga una extensión ".psd1". Cambie el valor del argumento Path para que apunte a un archivo psd1 válido e inténtelo de nuevo. + + + La clave ModuleVersion del manifiesto del módulo "{0}" especifica la versión del módulo "{1}", que no coincide con el nombre de la carpeta de versión en "{2}". Cambie el valor de la clave ModuleVersion para que coincida con el nombre de la carpeta de versión. + + + La entrada NestedModule especificada "{0}" en el manifiesto del módulo "{1}" no es válida. Vuelva a intentarlo después de actualizar esta entrada con valores válidos. + + + La entrada RequiredAssemblies especificada "{0}" en el manifiesto del módulo "{1}" no es válida. Vuelva a intentarlo después de actualizar esta entrada con valores válidos. + + + La entrada FileList especificada "{0}" en el manifiesto de módulo "{1}" no es válida. Vuelva a intentarlo después de actualizar esta entrada con valores válidos. + + + La entrada RequiredModules especificada "{0}" en el manifiesto del módulo "{1}" no es válida. Vuelva a intentarlo después de actualizar esta entrada con valores válidos. + + + La entrada ModuleList especificada "{0}" en el manifiesto de módulo "{1}" no es válida. Vuelva a intentarlo después de actualizar esta entrada con valores válidos. + + + El manifiesto del módulo "{0}" se especifica con la clave CompatiblePSEditions, que solo se admite en la versión "5.1" o posterior de PowerShell. Actualice el valor de la clave PowerShellVersion a "5.1" o superior e inténtelo de nuevo. + + + El valor especificado "{0}" para CompatiblePSEditions contiene nombres duplicados de la edición de PowerShell. Vuelva a intentarlo después de quitar los nombres duplicados de la edición de PowerShell. + + + La versión especificada en la clave ModuleVersion es igual al nombre de la carpeta de versión. + + + Omitiendo la carpeta {0} Versión en Módulo {1} porque no tiene un archivo de manifiesto de módulo válido. + + + El miembro 'ModuleName' no existe en la tabla hash que describe este módulo. + + + Los miembros "ModuleVersion", "MaximumVersion" y "RequiredVersion" no existen en la tabla hash que describe este módulo. Debe existir uno de estos tres miembros y se le debe asignar un número de versión con el formato "n.n.n.n". + + + El módulo necesario "{1}" no está cargado. Cargue el módulo o quítelo de "RequiredModules" en el archivo "{0}". + + + El módulo necesario "{1}" con GUID "{2}" no está cargado. Cargue el módulo o quítelo de "RequiredModules" en el archivo "{0}". + + + El módulo necesario "{1}" con la versión "{2}" no está cargado. Cargue el módulo o quítelo de "RequiredModules" en el archivo "{0}". + + + El módulo necesario "{1}" con MaximumVersion "{2}" no está cargado. Cargue el módulo o quítelo de "RequiredModules" en el archivo "{0}". + + + El módulo necesario "{1}" con MinimumVersion "{2}" y MaximumVersion "{3}" no está cargado. Cargue el módulo o quítelo de "RequiredModules" en el archivo "{0}". + + + No se encuentra el módulo "{0}" con ModuleVersion "{1}". + + + No se encuentra el módulo "{0}" con RequiredVersion "{1}". + + + No se encuentra el módulo "{0}" con MaximumVersion "{1}". + + + No se encuentra el módulo "{0}" con ModuleVersion "{1}" y MaximumVersion ''{2}". + + + No se encuentra el módulo "{0}". + + + No se quitó ningún módulo. Compruebe que la especificación de los módulos que se van a quitar es correcta y que esos módulos existen en el espacio de ejecución. + + + El miembro "{0}", que se importó desde el módulo ''{1}", no se puede quitar por el siguiente motivo: {2} + + + No se puede quitar el módulo "{0}" porque es de solo lectura. Agregue el parámetro Force al comando para quitar módulos de solo lectura. + + + No se puede quitar el módulo "{0}" porque está marcado como "constant". No se puede quitar un módulo si está marcado como "constant". + + + No se puede quitar el módulo "{0}" porque lo requiere "{1}". Agregue el parámetro Force al comando para quitar el módulo. + + + Solo se puede llamar al cmdlet Export-ModuleMember desde dentro de un módulo. + + + La extensión "{0}" no es una extensión de módulo válida. Las extensiones de módulo admitidas son ".dll", ".ps1", ".psm1", ".psd1" y ".cdxml". Corrija la extensión y vuelva a intentar agregar el archivo "{1}". + + + Esta operación no se puede realizar en un módulo binario. Solo se puede realizar en un módulo de script. + + + No se permite el archivo "{0}" porque no tiene la extensión ".ps1". + + + Desconocido + + + (c) {0}. Todos los derechos reservados. + + + Quitando la función "{0}" importada. + + + Quitando el alias "{0}" importado. + + + Quitando la variable "{0}" importada. + + + Cargando módulo desde la ruta de acceso "{0}". + + + Cargando "{0}" desde la ruta de acceso "{1}". + + + Dot-sourcing del archivo de script ''{0}". + + + Importando función "{0}". + + + Importando cmdlet "{0}". + + + Importando alias "{0}". + + + Importando variable ''{0}". + + + Exportando cmdlet "{0}". + + + Exportando función "{0}". + + + Exportando alias "{0}". + + + Exportando variable "{0}". + + + Los nombres de algunos comandos importados del módulo "{0}" incluyen verbos no aprobados que podrían hacer que sean menos reconocibles. Para buscar los comandos con verbos no aprobados, vuelva a ejecutar el comando Import-Module con el parámetro Verbose. Para obtener una lista de verbos aprobados, escriba Get-Verb. + + + Se importó el comando "{0}" del módulo "{1}", pero como su nombre no incluye un verbo aprobado, puede ser difícil de encontrar. Para obtener una lista de verbos aprobados, escriba Get-Verb. + + + Se importó el comando "{0}" del módulo "{2}", pero como su nombre no incluye un verbo aprobado, puede ser difícil de encontrar. Los verbos alternativos sugeridos son "{1}". + + + Algunos nombres de comando importados contienen uno o varios de los siguientes caracteres restringidos: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + El nombre de comando "{0}" del módulo "{1}" contiene uno o varios de los siguientes caracteres restringidos: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Creando el archivo de manifiesto del módulo "{0}". + + + {0} (ruta de acceso: "{1}") + + + La arquitectura actual del procesador es: {0}. El módulo "{1}" requiere la arquitectura siguiente: {2}. + + + El nombre del host de PowerShell actual es: "{0}". El módulo "{1}" requiere el siguiente host de PowerShell: "{2}". + + + El host de PowerShell actual es: "{0}" (versión {1}). El módulo "{2}" requiere una versión mínima del host de PowerShell de "{3}" para ejecutarse. + + + Manifiesto de módulo para el módulo "{0}" + + + Generado por: {0} + + + Generado el: {0} + + + Módulo de script o archivo de módulo binario asociado a este manifiesto. + + + Módulos que se van a importar como módulos anidados del módulo especificado en RootModule/ModuleToProcess + + + Id. usado para identificar de forma única este módulo + + + Autor de este módulo + + + Empresa o proveedor de este módulo + + + Declaración de copyright para este módulo + + + Número de versión de este módulo. + + + Descripción de la funcionalidad proporcionada por este módulo + + + Versión mínima del motor de PowerShell requerida por este módulo + + + Versión mínima de Common Language Runtime (CLR) requerida por este módulo. {0} + + + Módulos que se deben importar en el entorno global antes de importar este módulo + + + Archivos de script (.ps1) que se ejecutan en el entorno del autor de la llamada antes de importar este módulo. + + + Archivos de tipo (.ps1xml) que se cargarán al importar este módulo + + + Archivos de formato (.ps1xml) que se cargarán al importar este módulo + + + Ensamblados que deben cargarse antes de importar este módulo + + + Lista de todos los archivos empaquetados con este módulo + + + Datos privados que se van a pasar al módulo especificado en RootModule/ModuleToProcess. También puede contener una tabla hash PSData con metadatos de módulo adicionales usados por PowerShell. + + + Etiquetas aplicadas a este módulo. Esto ayuda con la detección de módulos en galerías en línea. + + + Una dirección URL al sitio web principal de este proyecto. + + + Una dirección URL a la licencia de este módulo. + + + Dirección URL a un icono que representa este módulo. + + + Notas de la versión de este módulo + + + Cadena de versión preliminar de este módulo + + + Marca para indicar si el módulo requiere la aceptación explícita del usuario para instalar, actualizar o guardar + + + Módulos dependientes externos de este módulo + + + Final de {0} tabla hash + + + El valor del parámetro PrivateData debe ser una tabla hash para crear el manifiesto del módulo con los siguientes valores de parámetro Tags, ProjectUri, LicenseUri, IconUri o ReleaseNotes. Quite los valores de los parámetros Tags, ProjectUri, LicenseUri, IconUri o ReleaseNotes o encapsule el contenido de PrivateData en una tabla hash. + + + PrivateData debe definirse como una tabla hash, pero este manifiesto de módulo lo define como un objeto. Considere la posibilidad de encapsular el contenido de PrivateData en una tabla hash. Esto le permitirá agregar las propiedades Tags, ProjectUri, LicenseUri, IconUri y ReleaseNotes al manifiesto del módulo más adelante. + + + El valor especificado "{0}" no es válido; inténtelo de nuevo con un valor válido. + + + Las funciones para exportar desde este módulo, para obtener el mejor rendimiento, no usan caracteres comodín y no eliminan la entrada, use una matriz vacía si no hay ninguna función para exportar. + + + Los alias para exportar desde este módulo, para obtener el mejor rendimiento, no usan caracteres comodín y no eliminan la entrada, usan una matriz vacía si no hay ningún alias para exportar. + + + Los cmdlets para exportar desde este módulo, para obtener el mejor rendimiento, no usan caracteres comodín y no eliminan la entrada, usan una matriz vacía si no hay cmdlets para exportar. + + + Variables para exportar desde este módulo + + + Recursos de DSC para exportar desde este módulo + + + PSEditions admitidas + + + Arquitectura de procesador (None, X86, Amd64) requerida por este módulo + + + Lista de todos los módulos empaquetados con este módulo + + + Versión mínima de Microsoft .NET Framework requerida por este módulo. {0} + + + Nombre del host de PowerShell requerido por este módulo + + + Versión mínima del host de PowerShell requerida por este módulo + + + URI de HelpInfo de este módulo + + + Dado que el {0} módulo proporciona el PSDrive en la sesión actual de PowerShell, no se quitó ningún módulo. Cambie el proveedor de PSDrive actual e intente quitar módulos de nuevo. + + + No se importó el cmdlet "{0}" porque hay un miembro con el mismo nombre en el ámbito actual. + + + No se importó el alias "{0}" porque hay un miembro con el mismo nombre en el ámbito actual. + + + No se importó la función "{0}" porque hay un miembro con el mismo nombre en el ámbito actual. + + + No se importó la variable "{0}" porque hay un miembro con el mismo nombre en el ámbito actual. + + + No se permiten caracteres comodín en los miembros "ModuleToProcess", "RootModule" o "NestedModules" en el manifiesto de módulo "{0}". + + + El módulo "{0}" es un módulo principal de PowerShell. Agregue el parámetro Force al comando para quitar los módulos principales. + + + El manifiesto del módulo no puede contener los miembros "ModuleToProcess" y "RootModule". Cambie el archivo de manifiesto del módulo para quitar uno de estos miembros en ''{0}" e inténtelo de nuevo. + + + El miembro del manifiesto de módulo "ModuleToProcess" está en desuso. En su lugar, use el miembro "RootModule". + + + Prefijo predeterminado para los comandos exportados desde este módulo. Invalide el prefijo predeterminado mediante Import-Module -Prefix. + + + Los parámetros "Global" y "Scope" no se pueden especificar juntos. Quite uno de estos parámetros e intente ejecutar el comando de nuevo. + + + El módulo necesario "{0}" no está cargado. El módulo "{0}" tiene un requiredModule "{1}" en su manifiesto de módulo "{2}" que apunta a una dependencia cíclica. + + + No se cargó el módulo necesario "{0}" porque no se encontró ningún archivo de módulo válido en ningún directorio de módulos. + + + Algunos comandos del módulo {0} no se pueden importar a través de una CimSession. Para obtener todos los comandos, compruebe que el servidor remoto tiene habilitada la administración remota de PowerShell e intente agregar el parámetro PSSession a un cmdlet Import-Module. + + + El módulo {0} se carga en Windows PowerShell mediante {1} la sesión remota; tenga en cuenta que toda la entrada y salida de los comandos de este módulo serán objetos deserializados. Si desea cargar este módulo en PowerShell, use la sintaxis "Import-Module -SkipEditionCheck". + + + Se detectó Windows PowerShell versión {0}. Se requiere Windows PowerShell 5.1 para cargar módulos mediante la característica de compatibilidad con Windows PowerShell. Instale Windows Management Framework (WMF) 5.1 desde https://aka.ms/WMF5Download para habilitar esta característica. + + + La configuración "WindowsPowerShellCompatibilityModuleDenyList" del archivo de configuración de PowerShell bloquea la carga del módulo "{0}" mediante la característica de compatibilidad de Windows PowerShell. + + + No se puede importar el módulo {0} a través de una CimSession. Pruebe a usar el parámetro PSSession del cmdlet Import-Module. + + + No se admite el valor de arquitectura de procesador de {0}. Vuelva a ejecutar el comando New-ModuleManifest y especifique uno de los siguientes valores de enumeración admitidos para la arquitectura del procesador: None, MSIL, X86, Amd64, Arm + + + La ejecución del cmdlet Get-Module en un equipo remoto solo puede enumerar los módulos disponibles. Agregue el parámetro ListAvailable al comando e inténtelo de nuevo. + + + No se importó el módulo "{0}" porque ya se importó el complemento ''{0}". + + + No se permiten caracteres comodín en el miembro "RequiredAssemblies" del manifiesto de módulo "{0}". + + + El valor de la {0} clave en {1} es {2} y el módulo tiene módulos anidados. Cuando un archivo CDXML es el módulo raíz, se produce un error en el comando Import-Module porque los comandos de los módulos anidados no se pueden exportar. Mueva el archivo CDXML a la clave NestedModules e intente el comando de nuevo. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Error del comando remoto: {0}{{0}} + + + No se pudieron generar servidores proxy para el módulo remoto "{0}". {{0}} + + + No se pudo procesar el módulo remoto {0}. {1} + + + No se pudieron recibir los datos del módulo de la CimSession remota. {0} + + + El módulo necesario "{0}" con el GUID "{1}" y la versión "{2}" no se cargó porque no se encontró ningún archivo de módulo válido en ningún directorio de módulos. + + + No se encontró un proveedor CIM para la detección de módulos en el servidor CIM. {0} + {0} is a placeholder for a more detailed error message + + + No se puede comprobar la versión {0} de Microsoft .NET Framework porque no está incluida en la lista de versiones permitidas. + + + Analizando {0}. + {0} should not be localized, is used to contain a file path. + + + Preparando los módulos para su primer uso. + + + Buscando módulos disponibles + + + Buscando el recurso compartido UNC {0}. + {0} should not be localized, is used to contain a file path. + + + La ejecución del cmdlet Get-Module en un equipo remoto solo se puede realizar para nombres de módulo que no incluyan una ruta de acceso. El parámetro Name tiene este elemento "{0}" que se resuelve en una ruta de acceso. Actualice el parámetro Name para que no tenga elementos de ruta de acceso e inténtelo de nuevo. + + + No se admite la ejecución del cmdlet Get-Module sin el parámetro ListAvailable para los nombres de módulo que incluyen una ruta de acceso. El parámetro Name tiene este elemento "{0}" que se resuelve en una ruta de acceso. Actualice el parámetro Name para que no tenga elementos de ruta de acceso e inténtelo de nuevo. + + + No se encontró el módulo especificado "{0}". Actualice el parámetro Name para que apunte a una ruta de acceso válida e inténtelo de nuevo. + + + Rellenando la propiedad RepositorySourceLocation para el módulo {0}. + + + El módulo que se va a procesar "{0}", incluido en el campo "{1}" del manifiesto del módulo "{2}", no se procesó. {3} + + + Este requisito previo solo es válido para la edición de PowerShell Desktop. + + + El módulo "{0}" no admite la edición actual de PowerShell "{1}". Sus ediciones admitidas son ''{2}". Use "Import-Module -SkipEditionCheck" para omitir la compatibilidad de este módulo. + + + El módulo "{0}" admite la edición de PowerShell "{1}" y no se puede cargar implícitamente mediante la característica compatibilidad de Windows porque está deshabilitado en el archivo de configuración. Use "Import-Module -UseWindowsPowerShell" para cargar este módulo con Windows PowerShell o "Import-Module -SkipEditionCheck" para intentar cargar el módulo con el PowerShell actual. + + + Se debe especificar un valor de cadena no vacío para una característica experimental declarada en el manifiesto del módulo. + + + Se encontraron uno o varios nombres de características experimentales no válidos: {0}. El nombre de una característica experimental de módulo debe seguir esta convención: "ModuleName.FeatureName". + + + El parámetro de modificador -SkipEditionCheck no se puede usar sin el parámetro de modificador -ListAvailable. + + + No se permite importar archivos *.ps1 como módulos en el modo ConstrainedLanguage. + + + Error al cargar el módulo {0} de script porque tiene un modo de lenguaje diferente al manifiesto del módulo. El modo de lenguaje del manifiesto es {1} y el modo de lenguaje del módulo es {2}. Asegúrese de que todos los archivos de módulo están firmados o forman parte de la configuración de la lista de permitidos de la aplicación. + + + Este módulo usa el operador dot-source al exportar funciones con caracteres comodín, y esto no se permite cuando el sistema está bajo aplicación estricta de la verificación de aplicaciones. + + + No se pueden exportar los miembros del módulo de un módulo que tiene un modo de lenguaje diferente al de la sesión en ejecución. + + + No se puede crear un nuevo módulo mientras la sesión está en modo ConstrainedLanguage. + + + No se encuentra el módulo integrado "{0}" compatible con la edición "Core". Asegúrese de que los módulos integrados de PowerShell están disponibles. Normalmente vienen con el paquete de PowerShell en la ruta de acceso del módulo $PSHOME y son necesarios para que PowerShell funcione correctamente. + + + Cmdlet Export-ModuleMember + + + Se producirá un error en la exportación de los miembros del módulo en el modo de lenguaje restringido porque el módulo "{0}" tiene un modo de lenguaje "{1}" que es diferente de la sesión actual "{2}". + + + Exportación de funciones implícitas del módulo + + + Se denegará la exportación implícita de funciones para el módulo "{0}" porque es de confianza (se ejecuta en modo de lenguaje completo), pero la sesión no es de confianza (se ejecuta en modo de lenguaje restringido). Se recomienda exportar siempre las funciones del módulo individualmente por nombre completo. + + + Importando archivo de script como módulo + + + La importación del archivo de script "{0}" como módulo no se permitirá en el modo ConstrainedLanguage. + + + El módulo contiene el operador dot-source + + + La importación del módulo "{0}" producirá un error en el modo de lenguaje restringido porque exporta funciones con caracteres comodín mientras también usa el operador dot-source. + + + "Funciones de exportación de módulos + + + El módulo "{0}" exporta funciones con caracteres comodín de nombre. Los nombres de función de módulo anidados se quitarán cuando se ejecuten en modo de lenguaje restringido. + + + "Cmdlet New-Module + + + Se bloqueará un nuevo módulo de una sesión de lenguaje restringido que no sea de confianza para que no proporcione el bloque de script FullLanguage. + + + "Modos de idioma no coincidentes del módulo + + + Se está cargando un módulo dependiente que tiene un modo de lenguaje diferente al primario. Esto no se permitirá cuando esté en modo de lenguaje restringido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/MshHostRawUserInterfaceStrings.es.resx b/src/System.Management.Automation/resources/es/MshHostRawUserInterfaceStrings.es.resx new file mode 100644 index 00000000000..0377a8f0e70 --- /dev/null +++ b/src/System.Management.Automation/resources/es/MshHostRawUserInterfaceStrings.es.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}" no puede ser mayor o igual que "{1}". + + + "{0}" debe ser un número positivo. + + + Todas las cadenas son nulas o están vacías. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/MshSignature.es.resx b/src/System.Management.Automation/resources/es/MshSignature.es.resx new file mode 100644 index 00000000000..288493acfef --- /dev/null +++ b/src/System.Management.Automation/resources/es/MshSignature.es.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 + + + Firma verificada. + + + El archivo {0} no está firmado digitalmente. No se puede ejecutar este script en el sistema actual. Para obtener más información sobre la ejecución de scripts y la configuración de la directiva de ejecución, consulte about_Execution_Policies en https://go.microsoft.com/fwlink/?LinkID=135170 + + + Es posible que un usuario o proceso no autorizado haya cambiado el contenido del archivo {0}, porque el hash del archivo no coincide con el hash almacenado en la firma digital. El script no se puede ejecutar en el sistema especificado. Para obtener más información, ejecute Get-Help about_Signing. + + + El archivo {0} está firmado, pero el signante no es de confianza en este sistema. + + + No se puede firmar el archivo porque el sistema no admite operaciones de firma en {0} archivos. + + + No se puede firmar el archivo porque el sistema no admite operaciones de firma en archivos que no tienen una extensión de nombre de archivo. + + + No se puede verificar la firma porque no es compatible con el sistema actual. + + + No se puede verificar la firma porque no es compatible con el sistema actual. El algoritmo hash no es válido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/MshSnapInCmdletResources.es.resx b/src/System.Management.Automation/resources/es/MshSnapInCmdletResources.es.resx new file mode 100644 index 00000000000..c2909d86ecb --- /dev/null +++ b/src/System.Management.Automation/resources/es/MshSnapInCmdletResources.es.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 + + + No se puede realizar la operación. El cmdlet especificado no se admite en un shell personalizado. + + + No se encontraron complementos de PowerShell que coincidan con el patrón "{0}". Compruebe el patrón e intente de nuevo el comando. + + + El formato del nombre de complemento especificado no es válido. Los nombres de complemento de PowerShell solo pueden contener caracteres alfanuméricos, guiones, guiones bajos y puntos. Corrija el nombre y vuelva a realizar la operación. + + + No se puede agregar el complemento de PowerShell {0} porque es un módulo de PowerShell del sistema. Use Import-Module para cargar el módulo. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/MshSnapinInfo.es.resx b/src/System.Management.Automation/resources/es/MshSnapinInfo.es.resx new file mode 100644 index 00000000000..074465ee171 --- /dev/null +++ b/src/System.Management.Automation/resources/es/MshSnapinInfo.es.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 + + + No se puede acceder a la información del registro de PowerShell. + + + No se puede acceder a la información del registro del motor de PowerShell. + + + No se puede acceder a la información de PublicKeyToken. + + + La versión {0} de PowerShell no está disponible en este equipo. + + + El complemento de PowerShell "{0}" no está instalado en este equipo. + + + No se especificó el valor obligatorio {0} para la clave del registro {1}. + + + El valor obligatorio {0} no tiene el formato correcto para la clave del registro {1}. El formato esperado es "string". + + + El valor obligatorio {0} no tiene el formato correcto para la clave del registro {1}. El formato esperado es "multistring". + + + No se encuentra la información necesaria en el registro o faltan archivos de clave. No se pueden cargar algunos cmdlets. + + + No se ha registrado ningún complemento para la versión {0} de PowerShell. + + + No se puede recuperar el recurso de cadena porque se ha desechado el lector. + + + No se ha especificado el valor de versión {0} o es incorrecto para la clave del registro {1}. + + + No se encontró ningún atributo [PSVersion] para el tipo de PowerShell {0}. Agregue un atributo PSVersion al tipo mediante [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/NativeCP.es.resx b/src/System.Management.Automation/resources/es/NativeCP.es.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/es/NativeCP.es.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PSCommandStrings.es.resx b/src/System.Management.Automation/resources/es/PSCommandStrings.es.resx new file mode 100644 index 00000000000..e08f549e70c --- /dev/null +++ b/src/System.Management.Automation/resources/es/PSCommandStrings.es.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 + + + Se requiere un comando para agregar un parámetro. Debe agregarse un comando a {0} antes de agregar un parámetro. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PSConfigurationStrings.es.resx b/src/System.Management.Automation/resources/es/PSConfigurationStrings.es.resx new file mode 100644 index 00000000000..7c833695182 --- /dev/null +++ b/src/System.Management.Automation/resources/es/PSConfigurationStrings.es.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 + + + PowerShell ha dejado de funcionar debido a un problema de seguridad: no se puede leer el archivo de configuración: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PSDataBufferStrings.es.resx b/src/System.Management.Automation/resources/es/PSDataBufferStrings.es.resx new file mode 100644 index 00000000000..e14c0ac4abb --- /dev/null +++ b/src/System.Management.Automation/resources/es/PSDataBufferStrings.es.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 + + + El índice especificado es menor que cero o mayor que el número de elementos del búfer. El índice debe estar en el intervalo {0}-{1}. + + + No se puede convertir una referencia nula en un tipo de valor. + + + No se puede convertir el valor del tipo {0} al tipo {1}. + + + No se pueden agregar objetos a un búfer cerrado. Asegúrese de que el búfer esté abierto para que las operaciones Add e Insert se realicen correctamente. + + + La propiedad SerializeInput solo se puede establecer para el tipo PSObject de PSDataCollection. Establezca la propiedad SerializeInput en false o cambie el tipo de colección a un PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PSListModifierStrings.es.resx b/src/System.Management.Automation/resources/es/PSListModifierStrings.es.resx new file mode 100644 index 00000000000..d43b067ab07 --- /dev/null +++ b/src/System.Management.Automation/resources/es/PSListModifierStrings.es.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 + + + Se detectó el siguiente modificador de lista desconocido: "{0}". Los modificadores de lista válidos son Agregar, Quitar y Reemplazar. + + + No se puede aplicar la actualización porque el objeto no es un tipo de colección compatible. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PSStyleStrings.es.resx b/src/System.Management.Automation/resources/es/PSStyleStrings.es.resx new file mode 100644 index 00000000000..3519d54c6d7 --- /dev/null +++ b/src/System.Management.Automation/resources/es/PSStyleStrings.es.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La cadena especificada contiene contenido imprimible cuando solo debería contener secuencias de escape ANSI: {0} + + + El valor de MaxWidth para el renderizado de Progress debe ser al menos 18 para que se muestre correctamente. + + + Al agregar o quitar extensiones, la extensión debe comenzar por un punto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ParameterBinderStrings.es.resx b/src/System.Management.Automation/resources/es/ParameterBinderStrings.es.resx new file mode 100644 index 00000000000..fd86fb11c7b --- /dev/null +++ b/src/System.Management.Automation/resources/es/ParameterBinderStrings.es.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se encuentra un parámetro que coincida con el nombre de parámetro "{1}". + + + No se encuentra ningún parámetro posicional que acepte el argumento "{1}". + + + Falta un argumento para el parámetro "{1}". Especifique un parámetro de tipo "{2}" e inténtelo de nuevo. + + + No se puede procesar el parámetro porque el nombre del parámetro "{1}" es ambiguo. Las posibles coincidencias incluyen:{6}. + + + No se puede convertir "{6}" al tipo "{2}" que requiere el parámetro "{1}". {7} + + + No se puede enlazar el parámetro "{1}". {6} + + + No se pueden enlazar los parámetros posicionales "{1}". + + + No se pueden enlazar parámetros posicionales porque no se han proporcionado nombres. + + + El conjunto de parámetros no se puede resolver con los parámetros con nombre especificados. Uno o varios parámetros enviados no se pueden usar juntos o se proporcionó un número insuficiente de parámetros. + + + No se puede procesar el comando porque faltan uno o varios parámetros obligatorios:{1}. + + + El parámetro "{1}" no se puede especificar en el conjunto de parámetros "{6}". + + + No se puede enlazar el parámetro porque el parámetro "{1}" se ha especificado más de una vez. Para proporcionar varios valores a parámetros que aceptan varios valores, use la sintaxis de matriz. Por ejemplo, "-parameter value1,value2,value3". + + + No se puede evaluar el parámetro "{1}" porque su argumento está especificado como un bloque de script y no hay entrada. Un bloque de script no se puede evaluar sin entrada. + + + Error en la entrada del bloque de script para el parámetro "{1}". {6} + + + No se puede evaluar el parámetro "{1}" porque la entrada de su argumento no produjo ninguna salida. + + + El objeto de entrada no se puede enlazar a ningún parámetro del comando, bien porque el comando no acepta entrada de canalización o porque la entrada y sus propiedades no coinciden con ninguno de los parámetros que aceptan entrada de canalización. + + + No se puede enlazar el objeto de entrada porque no contiene la información necesaria para enlazar todos los parámetros obligatorios: {6} + + + No se puede procesar la entrada de la canalización porque no se puede recuperar el valor predeterminado del parámetro "{1}". {6} + + + No se puede recuperar los parámetros dinámicos para el cmdlet. {6} + + + Proporcione valores para estos parámetros: + + + cmdlet {0} en la posición {1} de la canalización de comandos + + + No se puede procesar la transformación del argumento del parámetro "{1}". {6} + + + {6} + + + No se puede validar el argumento en el parámetro "{1}". {6} + + + No se puede enlazar el parámetro "{1}" al destino. {6} + + + No se puede enlazar el argumento al parámetro "{1}" porque es null. + + + No se puede enlazar el argumento al parámetro "{1}" porque es una cadena vacía. + + + No se puede enlazar el argumento al parámetro "{1}" porque es una colección vacía. + + + No se puede enlazar el argumento al parámetro "{1}" porque es un matriz vacía. + + + No se puede procesar el comando. El parámetro "{0}" se define varias veces. + + + No se puede enlazar el cmdlet {0} porque el parámetro "{1}" es de tipo "{2}" y no se puede identificar el método Add() o existen varios métodos Add(). {6} + + + No se puede enlazar el cmdlet {0} porque el parámetro definido por el runtime "{1}" se agregó al RuntimeDefinedParameterDictionary con la clave "{6}". La clave debe ser la misma que RuntimeDefinedParameter.Name. + + + No se puede enlazar el argumento al parámetro "{1}" porque los PSTypeNames del argumento no coinciden con el PSTypeName que requiere el parámetro: {6}. + + + En $PSDefaultParameterValues se definen varios valores predeterminados diferentes para el parámetro que coincide con el siguiente nombre o alias: {0}. Estos valores predeterminados se han ignorado. + + + El siguiente nombre o alias definido en $PSDefaultParameterValues para este cmdlet se resuelve en varios parámetros: {0}. Se ha ignorado el valor predeterminado. + + + {6} Es posible que este error se deba a la aplicación del enlace de parámetros predeterminado. Puede deshabilitar el enlace de parámetros predeterminado en $PSDefaultParameterValues estableciendo $PSDefaultParameterValues["Disabled"] en $true y, a continuación, vuelva a intentarlo. Los siguientes parámetros predeterminados se enlazaron correctamente a este cmdlet cuando se produjo el error:{7} + + + {6} Es posible que este error se deba a la aplicación del enlace de parámetros predeterminado. Puede deshabilitar el enlace de parámetros predeterminado en $PSDefaultParameterValues estableciendo $PSDefaultParameterValues["Disabled"] en $true y volver a intentarlo. El siguiente parámetro predeterminado se enlazó correctamente a este cmdlet cuando se produjo el error:{7} + + + Error al enlazar el valor predeterminado "{0}" al parámetro "{1}": {2} + + + La clave "{0}" no tiene un formato válido. Para obtener información sobre el formato correcto, consulte about_Parameters_Default_Values en https://go.microsoft.com/fwlink/?LinkId=228266. + + + Las claves "{0}" no tienen un formato válido. Para obtener información sobre el formato correcto, consulte about_Parameters_Default_Values en https://go.microsoft.com/fwlink/?LinkId=228266. + + + El parámetro "{0}" está obsoleto. {1} + + + La clave "{0}" de tipo "{1}" no es un valor de cadena. DefaultParameterDictionary solo acepta claves con valores de cadena. + + + La clave "{0}" ya se ha agregado al diccionario. + + + No se permite invocar una propiedad o un método + + + No se permitirá invocar el Método o la Propiedad "{0}" en el tipo "{1}" en el modo de lenguaje restringido para scripts que no son de confianza. + + + No se permite crear tipos + + + No se permitirá la creación del tipo "{0}" durante el enlace de parámetros en el modo de lenguaje restringido para scripts que no son de confianza. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ParserStrings.es.resx b/src/System.Management.Automation/resources/es/ParserStrings.es.resx new file mode 100644 index 00000000000..6d4f3d460f3 --- /dev/null +++ b/src/System.Management.Automation/resources/es/ParserStrings.es.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se encuentra el tipo [{0}]. + + + No se encuentra el tipo [{0}]. Detalles: {1} + + + Token de cadena incompleto. + + + La secuencia de escape Unicode no es válida. Una secuencia válida es `u{ seguida de entre uno y seis dígitos hexadecimales y un "}" de cierre. + + + El valor de secuencia de escape Unicode está fuera del intervalo. El valor máximo es 0x10FFFF. + + + A la secuencia de escape Unicode le falta el cierre "}". + + + La secuencia de escape Unicode contiene más del máximo de seis dígitos hexadecimales entre llaves. + + + No se puede usar [ref] con otros tipos en una restricción de tipo. + + + [ref] solo puede ser el tipo final en la secuencia de conversión de tipos. + + + No puede haber dos repeticiones de [ref] en una secuencia de tipos. + + + La constante numérica {0} no es válida. + + + El patrón de expresión regular {0} no es válido. + + + Se encontró una referencia de variable ${} vacía. Se requiere un nombre dentro de las llaves. + + + La referencia de variable no es válida. "$" no estaba seguido de un carácter de nombre de variable válido. Considere la posibilidad de usar ${} para delimitar el nombre. + + + No se puede llamar a un método en una expresión con valores null. + + + Error en la invocación del método porque [{0}] no contiene un método denominado ''{1}". + + + La asignación ha fallado porque [{0}] no contiene una propiedad "{1}()" que se pueda establecer. + + + Token inesperado "{0}" en la expresión o instrucción. + + + El operador de expansión "@" no se puede usar para hacer referencia a variables en una expresión. "@{0}" solo se puede usar como argumento de un comando. Para hacer referencia a variables en una expresión, use "${0}". + + + El parámetro "{0}" no es válido + + + Falta la expresión después de "{0}" en el elemento de canalización. + + + La expresión después de "{0}" en un elemento de canalización produjo un objeto no válido. Debe dar como resultado un nombre de comando, un bloque de script o un objeto CommandInfo. + + + El parámetro {0} requiere un argumento. + + + El parámetro {0} no puede tener un argumento. + + + Parámetro duplicado ${0} en la lista de parámetros. + + + Falta el argumento en la lista de parámetros. + + + Las variables expandidas, como "@{0}", no pueden formar parte de una lista de argumentos separados por comas. + + + Falta la especificación de archivo después del operador de redirección. + + + El operador "{0}" está reservado para uso futuro. + + + Error al redirigir a ''{0}": {1} + + + Las expresiones solo se permiten como primer elemento de una canalización. + + + No se permite un elemento de canalización vacío. + + + La expresión de asignación no es válida. La entrada de un operador de asignación debe ser un objeto que pueda aceptar asignaciones, como una variable o una propiedad. + + + Una tabla hash solo se puede agregar a otra tabla hash. + + + El operando derecho de "-is" debe ser un tipo. + + + El operando derecho de "-as" debe ser un tipo. + + + Error al dar formato a una cadena: {0}. + + + El argumento del operador "{0}" no es válido: {1}. + + + El operador "{0}" falló: {1}. + + + El operador {0} solo permite que le sigan dos elementos, no {1}. + + + Debe proporcionar una expresión de valor después del operador ''{0}". + + + El operador "{0}" solo funciona en variables o propiedades. + + + El atributo {0} solo se puede especificar en un nodo literal hash. + + + Falta la expresión de índice de matriz o no es válida. + + + Falta el nombre de propiedad después del operador de referencia. + + + No se encuentra la propiedad "{0}" en este objeto. Compruebe que la propiedad existe y se puede establecer. + + + No se encuentra la propiedad "{0}" en este objeto. Compruebe que la propiedad existe. + + + Error en la operación de índice; el índice de matriz se evaluó como null. + + + No se puede indizar una matriz nula. + + + No se puede indizar en un objeto de tipo "{0}". + + + No se puede indizar en un objeto de tipo "{0}" con el tipo de retorno similar a ByRef "{1}". Los tipos de tipo ByRef no se admiten en PowerShell. + + + La matriz tiene demasiadas dimensiones: {0}. El número de dimensiones de una matriz debe ser menor o igual que 32. + + + Error al asignar una matriz a [{0}] porque no se admite la asignación a segmentos. + + + No se puede indexar en una {0} matriz dimensional con el índice [{1}]. + + + Error en la asignación de matriz porque el índice "{0}" estaba fuera del intervalo. + + + Falta la expresión después de ''{0}". + + + Falta el cierre "}}" en el inicio de la referencia ${{variable}}. + + + $(subexpression) no tiene el paréntesis de cierre ")". + + + Error interno: operador unario inesperado {0}. + + + [ref] no se puede aplicar a una variable que no existe. + + + No se puede recuperar la variable "${0}" porque no se ha establecido. + + + No se permiten claves duplicadas "{0}" en literales hash. + + + No se permiten argumentos con nombre duplicados "{0}". + + + El operador "{0}" solo funciona en números. El operando es ''{1}". + + + Se esperaba una expresión después de "(". + + + Falta el operador "=" después de la clave en el literal de hash. + + + Falta la instrucción después de "=" en el literal de hash. + + + Falta la instrucción después de "=" en el argumento con nombre. + + + Falta ";" o el final de línea en la definición de la propiedad. + + + Falta la expresión después del operador unario "{0}". + + + Falta la condición en la instrucción if después de "{0}". + + + Falta el bloque de instrucciones después de {0} ( condición ). + + + Falta el bloque de instrucciones después de la palabra clave "else". + + + No se pudo leer el archivo: {0}. + + + El proveedor actual ({0}) no puede abrir un archivo. + + + No se encontraron archivos que coincidan con ''{0}". + + + No se puede procesar la ruta de acceso porque se resolvió en más de un archivo; solo se puede procesar un archivo a la vez. + + + El parámetro {0} "-{1}" está reservado para uso futuro. + + + No se puede procesar la instrucción "switch" porque falta un argumento de nombre de archivo para la opción -file. + + + El argumento de nombre de archivo para -file en la instrucción switch no es válido. + + + El parámetro {0} no es válido para la instrucción switch. + + + El parámetro {0} no es válido para la instrucción foreach. + + + Una instrucción switch debe tener uno de los siguientes elementos: "-file file_name" o "( expression )". + + + Falta la condición en la cláusula de instrucción switch. + + + Una instrucción switch solo puede tener una cláusula predeterminada. + + + Falta el bloque de instrucciones en la cláusula de instrucción switch. + + + Falta la expresión en el bucle foreach. +La forma correcta es: foreach ($a en $b) {...} + + + Falta el cuerpo de la instrucción en el bucle foreach. +La forma correcta es: foreach ($a en $b) {...} + + + No se puede usar la instrucción param si se especificaron argumentos en la declaración de función. + + + La operación "[{0}] {1} [{2}]" no está definida. + + + Error al enumerar a través de una colección: {0}. + + + Excepción de interoperabilidad COM no controlada: {0} + + + Se ha accedido a un objeto COM después de que ya se haya liberado: {0} + + + Se detuvo el procesamiento porque el script es demasiado complejo. + + + Este espacio de ejecución no admite la sintaxis. Esto puede ocurrir si el espacio de ejecución está en modo sin lenguaje. + + + La combinación de opciones con el operador -split no es válida. + + + No se permiten opciones en el operador -split con un predicado. + + + El token "{0}" no es un separador de instrucciones válido en esta versión. + + + La palabra clave "{0}" no se admite en esta versión del lenguaje. + + + Falta la expresión después de "{0}" en el bucle. + + + Falta el cuerpo de la instrucción en {0} bucle. + + + La instrucción "trap" está incompleta. Una instrucción trap requiere un cuerpo. + + + Instrucción "try" incompleta. Una instrucción try requiere un cuerpo. + + + Las declaraciones de parámetros son una lista separada por comas de nombres de variable con expresiones de inicialización opcionales. + + + Falta el cuerpo de la función en la declaración de función. + + + La cláusula de comando de script "{0}" ya se ha definido. + + + token inesperado "{0}", se esperaba "begin", "process", "end", "clean" o "dynamicparam". + + + Falta el cierre "}" en el bloque de instrucciones o la definición de tipo. + + + Falta ")" en la llamada al método. + + + Falta "]" después de la expresión de índice de matriz. + + + Falta el cierre ")" en la expresión. + + + Falta el paréntesis de cierre ")" en la subexpresión. + + + Falta "(" después de "{0}" en la instrucción if. + + + Falta ")" después de la expresión en la instrucción switch. + + + Falta "{" en la instrucción switch. + + + Falta el nombre de variable después de foreach. +La forma correcta es: foreach ($a en $b) {...} + + + Falta "in" después de la variable en el bucle foreach. +La forma correcta es: foreach ($a en $b) {...} + + + Falta el paréntesis de cierre ")" después de la parte de la expresión del bucle foreach. +La forma correcta es: foreach ($a en $b) {...} + + + Falta la apertura "(" después de la palabra clave "{0}". + + + Falta la palabra clave while o until en el bucle do. + + + Falta el cierre ")" después de la expresión en la instrucción ''{0}". + + + Falta el nombre después de la palabra clave {0}. + + + Falta ")" en la lista de parámetros de la función. + + + Error "{0}" al procesar este script. No se pudo cargar el texto que describe este error. + + + Error "{0}" al procesar este script. No se pudo cargar el texto que describe este error debido al error "{1}". + + + No hay ningún espacio de ejecución disponible para ejecutar scripts en este subproceso. Puede proporcionar uno en la propiedad DefaultRunspace del tipo System.Management.Automation.Runspaces.Runspace. El bloque de script que intentó invocar era: {0} + + + Token no reconocido en el texto de origen. + + + Acción que se realizará para esta excepción: + + + &Continuar + + + Notifique el error y continúe con la siguiente instrucción de script. + + + Continuar con s&ilentitud + + + No informe de este error, simplemente continúe con la siguiente instrucción de script. + + + &Interrumpir + + + No continúe con el procesamiento, inicie la excepción en su lugar. + + + &Suspender + + + Ponga en pausa la canalización actual y vuelva al símbolo del sistema. Escriba salir para reanudar la operación cuando haya terminado. + + + No se puede ejecutar un documento en medio de una canalización: {0}. + + + No se pudo ejecutar el programa "{0}": {1}{2}. + + + No se puede usar "&" para invocar en el contexto del módulo binario "{0}". Especifique un módulo no binario después de "&" e inténtelo de nuevo. + + + No se puede usar "&" para invocar en el contexto del módulo "{0}" porque no se ha importado. Importe el módulo "{0}" e intente la operación de nuevo. + + + Se encontró código de script ejecutable en el bloque de firma. + + + línea + + + En {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = "{1}". + + + ! Función CALL "{0}" + + + ! Función CALL "{0}" (definida en el archivo "{1}") + + + ! MÉTODO CALL "{0}" + + + Falta el terminador en la cadena: {0}. + + + No se permiten espacios en blanco antes del terminador de cadena. + + + Falta ] al final del token de tipo. + + + Use `{ en lugar de { en los nombres de variable. + + + Falta el bloque de instrucciones en la Sección de datos. + + + El parámetro "{0}" de la Sección de datos no es válido. El parámetro válido de la Sección de datos es SupportedCommand. + + + No se permiten referencias de matriz en el modo de lenguaje restringido o en una Sección de datos. + + + No se permiten instrucciones de asignación en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permite el redireccionamiento en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permiten las instrucciones Do y While en el modo de lenguaje restringido o en una Sección de datos. + + + No se permiten cadenas expansibles en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permite el operador "{0}" en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permite la instrucción Trap en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permite la instrucción Try en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permiten instrucciones de control de flujo como Break, Continue, Return, Exit y Throw en el modo de lenguaje restringido o en una Sección de datos. + + + Las instrucciones Foreach no se permiten en el modo de lenguaje restringido ni en una Sección de datos. + + + Las instrucciones For y While no se permiten en el modo de lenguaje restringido ni en una Sección de datos. + + + Las declaraciones de función no se permiten en el modo de lenguaje restringido ni en una sección Data. + + + Las llamadas a métodos no se permiten en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permiten declaraciones de parámetros en modo de lenguaje restringido ni en una Sección de datos. + + + No se permiten referencias de propiedad en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permiten literales de bloque de script en modo de lenguaje restringido ni en una Sección de datos. + + + La instrucción switch no se permite en el modo de lenguaje restringido ni en una Sección de datos. + + + Se está haciendo referencia a una variable a la que no se puede hacer referencia en el modo de lenguaje restringido ni en una Sección de datos. Entre las variables a las que se puede hacer referencia se incluyen las siguientes: {0}. + + + No se permite el comando "{0}" en el modo de lenguaje restringido ni en una Sección de datos. + + + La instrucción de datos no se permite en el modo de lenguaje restringido u otra Sección de datos. + + + Falta un valor en el parámetro SupportedCommand de la Sección de datos. Proporcione un cmdlet o un nombre de función al parámetro. + + + No se permite un bloque de instrucciones Begin, un bloque de instrucciones Process ni una instrucción de parámetro en una Sección de datos. + + + Los resultados de multiplicación de cadenas con más de "{0}" caracteres no se permiten en el modo de lenguaje restringido ni en una sección Data. + + + No se permite la multiplicación de matrices que da como resultado más de {0} elementos en el modo de lenguaje restringido o en una Sección de datos. + + + No se permite el aprovisionamiento de puntos en el modo de lenguaje restringido ni en una Sección de datos. + + + El argumento de atributo debe ser una constante o un bloque de script. + + + No se encuentra el tipo para el atributo personalizado "{0}". Asegúrese de que el ensamblado que contiene este tipo está cargado. + + + No se encuentra la propiedad "{0}" para el tipo "{1}". + + + Atributo inesperado "{0}". + + + Falta ] al final del atributo o literal de tipo. + + + Se llamó a la función o al comando como si fuera un método. Los parámetros deben estar separados por espacios. Para obtener información sobre los parámetros, consulte el tema de Ayuda about_Parameters. + + + Falta su bloque de instrucciones en la instrucción Try. + + + Falta el bloque Catch o Finally de la instrucción Try. + + + Al bloque Catch le falta su bloque de instrucciones. + + + Falta su bloque de instrucciones en el bloque Finally. + + + El tipo de excepción {0} ya está controlado por un controlador anterior. + + + El bloque Catch debe ser el último bloque catch. + + + Falta el literal de tipo. + + + Falta el terminador "#>" en el comentario de varias líneas. + + + No se permiten caracteres después de un encabezado here-string, pero antes del final de la línea. + + + Se detectaron errores del analizador. + + + Falta un bloque de instrucciones después de "{0}". + + + Se encontró un tipo [{0}] inesperado en la instrucción de parámetro. + + + Se encontró un tipo inesperado [{0}] antes de la instrucción. + + + No se permite una clave NULL en un literal hash. + + + No se permiten atributos en el modo de lenguaje restringido ni en una Sección de datos. + + + No se permite el tipo {0} en el modo de lenguaje restringido ni en una Sección de datos. + + + "{0}" es una propiedad ReadOnly. + + + Falta la especificación del nombre del ensamblado en el nombre de tipo. + + + El flujo de control no puede salir de un bloque Finally. + + + Error irrecuperable en PowerShell. + + + No se puede usar un AST como elemento secundario de más de un AST. Para usar este AST en otro AST, llame al método Copy() y use su resultado. + + + No se permite la expresión en una expresión Using. + + + No se puede recuperar una variable Using. Una variable Using solo se puede usar con Invoke-Command, Start-Job o InlineScript en el flujo de trabajo del script. Cuando se usa con Invoke-Command, la variable Using solo es válida si el bloque de script se invoca en un equipo remoto. + + + La referencia de variable no es válida. Falta el nombre de la variable. + + + La referencia de variable no es válida. ":" no va seguido de un carácter de nombre de variable válido. Considere la posibilidad de usar ${} para delimitar el nombre. + + + No se notificaron todos los errores de análisis. Corrija los errores notificados e inténtelo de nuevo. + + + Falta el nombre de tipo después de "[". + + + * secuencia + + + secuencia de depuración + + + secuencia de errores + + + flujo de salida + + + El {0} para este comando ya se ha redirigido. + + + flujo detallado + + + secuencia de advertencia + + + Falta el cuerpo de la instrucción después de la palabra clave "{0}". + + + Los bloques paralelos y de secuencia no se permiten en el modo de lenguaje restringido ni en una Sección de datos. + + + Palabra clave inesperada "{0}". + + + [void] no se puede usar como tipo de parámetro ni en el lado izquierdo de una asignación. + + + No se puede invocar al método. + + + No se puede convertir la tabla hash en un objeto del tipo siguiente: {0}. No se admite la conversión de tabla hash a objeto en el modo de lenguaje restringido o en una Sección de datos. + + + El argumento debe ser constante. + + + El argumento del {0} parámetro no es válido. Especifique un argumento de cadena válido. + + + El argumento del parámetro Module no es válido. {0} + + + El argumento del parámetro Version no es válido. Especifique una versión válida de PowerShell con el formato major.minor. + + + El argumento del {0} parámetro no es válido. Especifique una edición válida de PowerShell. + + + El argumento del parámetro {0} contiene valores duplicados. No especifique valores duplicados de la edición de PowerShell. + + + No se admiten caracteres comodín para los nombres de módulo. + + + No se puede invocar el método. La invocación de métodos solo se admite en los tipos principales de este modo de lenguaje. + + + No se puede establecer la propiedad. La configuración de propiedad solo se admite en los tipos principales de este modo de lenguaje. + + + Se encontró un nombre de atributo para el recurso "{0}" que no es válido. Un nombre de atributo debe ser una cadena simple y no puede contener variables ni expresiones. Reemplace "{1}" por una cadena simple. + + + El miembro "{0}" no es válido. Los miembros válidos son +"{1}". + + + Falta "{" en la definición de objeto. + + + Faltaba un nombre o una expresión necesarios. + + + No se encontró el archivo de esquema {0}. Compruebe que los módulos especificados en una instrucción de configuración contienen un archivo schema.mof e intente ejecutar el script de nuevo. + + + No se puede definir la sección de datos. No se admite la definición de comandos admitidos adicionales en este modo de lenguaje. + + + Falta "{" en la instrucción de configuración. + + + Excepción al analizar el archivo MOF "{0}":{1}. + + + Falta el nombre de la configuración. Proporcione el nombre que falta como un nombre simple, una cadena o una expresión que devuelva una cadena. + + + No se pudo encontrar el módulo "{0}". + + + Se encontraron varias versiones del módulo ''{0}". Puede ejecutar "Get-Module -ListAvailable -FullyQualifiedName {0}" para ver las versiones disponibles en el sistema y, a continuación, usar el nombre completo "@{{ModuleName="{0}"; RequiredVersion="Version"}}". + + + Falta un valor en el parámetro ThrottleLimit de la instrucción foreach. Proporcione un límite para el parámetro. + 'ThrottleLimit' must not be localized. + + + El parámetro ThrottleLimit solo se admite en instrucciones foreach que usan el parámetro Parallel. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + Los resultados del bloque de configuración eran nulos o estaban vacíos. Compruebe que las configuraciones se definieron en el bloque. + + + El recurso "{0}" solo se puede usar una vez por configuración y, por tanto, no puede tener un nombre. Quite "{1}" y vuelva a ejecutar el script. + + + Hay un bloque de asignación de propiedades incompleto en la definición de instancia. + + + Falta el operador "=" después de la clave en la asignación de propiedad. + + + No se permiten asignaciones de propiedades duplicadas en una definición de instancia. + + + Se encontró una segunda definición de clase CIM para "{0}" al procesar el archivo de esquema "{1}". Esta clase ya se definió en los archivos "{2}". Quite la definición redundante e inténtelo de nuevo. + + + El nombre de recurso "{0}" ya lo está usando otro recurso o configuración. + + + El nombre de clase "{0}" no coincide con "{1}", el nombre del archivo en el que está definida. Cambie el nombre del archivo para que coincida con el nombre de clase o viceversa + + + Se encontró un identificador de recurso duplicado "{0}" al procesar la especificación para el nodo "{1}". Cambie el nombre de este recurso para que sea único dentro de la especificación del nodo. + + + No hay ningún espacio en blanco entre el nombre y el bloque de script en la instrucción body de la palabra clave dinámica ''{0}". + + + La propiedad de clave de una entrada del diccionario de funciones que se va a definir no puede estar vacía porque la propiedad de clave se usa como nombre de función. Especifique una cadena que no esté vacía como valor de la propiedad de clave e intente la operación de nuevo. + + + El formato de la referencia de recurso "{0}" en la lista Requires para el recurso "{1}" no es válido. Un nombre de recurso necesario debe tener el formato "[<typename>]<name>", con caracteres alfanuméricos, espacios, "_", "-", "." y "\". + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + El formato de la referencia de recurso "{0}" en la lista exclusiva del recurso "{1}" no es válido. Un nombre de recurso exclusivo debe tener el formato "<typename>\<name>", sin espacios. + + + PartialConfiguration "{0}" está establecido en el modo de extracción, que requiere una propiedad ConfigurationSource. + + + Se encontró una entrada nula en la lista de entradas de variables que se van a crear en el ámbito del bloque de script. Quite la entrada en el índice {0}, o reemplácela por una entrada que no sea null e inténtelo de nuevo. + + + El bloque de script que define la función "{0}" no puede ser nulo ni estar vacío. Proporcione un bloque de script no vacío en el diccionario de definición de función e intente la operación de nuevo. + + + La sintaxis de la palabra clave dinámica Import-DscResource es: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Nombre : Nombres de uno o varios recursos que se van a importar. +ModuleName : Nombres de módulo u objetos ModuleSpecification de uno o varios módulos que se van a importar. +ModuleVersion: versión del módulo que se va a importar. Si se usa, ModuleName debe representar un solo módulo por el nombre. + + + La palabra clave dinámica Import-DscResource solo admite un módulo cuando se especifica el parámetro Name. + + + No se admiten parámetros posicionales para la palabra clave dinámica Import-DscResource. La sintaxis de la palabra clave dinámica Import-DscResource es: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + No se puede cargar el recurso "{0}": recurso no encontrado. + + + La palabra clave Configuration no se permite en el modo constrainedLanguage. + + + El nombre de configuración "{0}" no es válido. Los nombres Standard solo pueden contener letras (a-z, A-Z), números (0-9), puntos (.), guiones (-) y guiones bajos (_). El nombre no puede ser nulo ni estar vacío y debe comenzar con una letra. + + + La configuración solo admite el bloque End en su cuerpo. No se permiten los bloques Begin, Process y DynamicParam en una configuración. + + + El deserializador CIM generó un error al deserializar el archivo {0}. + + + "{0}" no es un valor válido para la propiedad "{1}" en la clase "{2}". Cambie el valor a una de las siguientes cadenas: {3}. + + + Al menos uno de los valores "{0}" no se admite o no es válido para la propiedad "{1}" de la clase "{2}". Especifique solo los valores admitidos: +{3}. + + + El recurso "{0}" requiere que se proporcione un valor de tipo "{1}" para la propiedad "{2}". + + + La propiedad "{0}" del recurso "{1}" tiene un valor "{2}" que no está entre el intervalo válido "{3}" y "{4}". + + + No se pudo cargar el archivo de datos de PowerShell "{0}" debido al siguiente error: +{1} + + + No se puede resolver la ruta de acceso "{0}" en un único archivo .psd1. + + + El archivo de datos de PowerShell "{0}" no es válido porque no se puede evaluar como un objeto Hashtable. + + + No se admite la configuración en WinPE. + + + Si la expresión pasada al operador Where() es null, debe especificar un valor distinto de Predeterminado para el argumento de modo de selección. Cambie el valor del argumento de modo por un valor distinto de Predeterminado e intente ejecutar el script de nuevo. + + + El tipo de colección genérico [{0}] pasado a ForEach() tiene demasiados argumentos de tipo. Cambie el tipo especificado para que sea una colección genérica con un solo argumento de tipo e intente ejecutar el script de nuevo. + + + No se puede convertir la entrada al tipo de destino [{0}] pasado al operador ForEach(). Compruebe el tipo especificado e intente ejecutar el script de nuevo. + + + El método "ForEach" no admite bloques de script con un bloque "clean". + + + El valor "numberToReturn" proporcionado al tercer argumento del operador Where() debe ser mayor que cero. Corrija el valor del argumento e intente ejecutar el script de nuevo. + + + El redireccionamiento solo permite combinar otro flujo con el flujo de salida. Corrija la operación de redirección para combinar en el flujo de salida e intente ejecutar el script de nuevo. + + + El operador ForEach() no pudo encontrar el miembro "{0}" en el objeto de destino. Compruebe que el miembro con nombre existe e intente ejecutar el script de nuevo. + + + La palabra clave "{0}" no se admite en esta versión del lenguaje. + + + La propiedad "{0}" no se admite en esta versión del lenguaje. + + + Calificador duplicado "{0}" + + + El modificador "{0}" no se puede combinar con "{1}" + + + Falta la directiva using + + + Falta el alias de espacio de nombres + + + Falta el operador "=" + + + Falta el nombre using + + + La variable no está asignada en el método. + + + Falta un nombre de propiedad o una definición de método. + + + El miembro "{0}" ya está definido. + + + Solo se puede especificar un tipo en los miembros de clase. + + + Error durante la creación del tipo "{0}". Mensaje de error: +{1} + + + No se puede convertir el valor al tipo "{0}". + + + No se encuentra la propiedad "{0}" para el atributo "{1}". Especifique una de las siguientes propiedades: {2}. + + + El atributo "{0}" no es válido en esta declaración. Solo es válido en declaraciones ''{1}". + + + El argumento de atributo debe ser una constante. + + + Recurso de DSC no definido "{0}". Use Import-DSCResource para importar el recurso. + + + Excepción al analizar previamente la palabra clave dinámica "{0}" con los detalles ''{1}". + + + Excepción al analizar posteriormente la palabra clave dinámica "{0}" con los detalles "{1}". + + + El flujo de trabajo no es compatible con PowerShell 6+. + + + El recurso de metaconfiguración {0} no se permite en la configuración normal. Use los recursos de metaconfiguración en una configuración con el atributo [DscLocalConfigurationManager()]. + + + No se permite el recurso DSC normal {0} en la metaconfiguración. + + + No hay ningún espacio de ejecución disponible para obtener y ejecutar SteppablePipeline en este subproceso. Puede proporcionar uno en la propiedad DefaultRunspace del tipo System.Management.Automation.Runspaces.Runspace. El bloque de script del que intentó obtener SteppablePipeline era: {0} + + + Hay conversiones válidas de {0} a {1}. + + + No se puede realizar la llamada. + + + No se puede recuperar la información de tipo. + + + No se pudo obtener el identificador de envío para {0} (error: {1}). + + + No se encuentra una sobrecarga para "{0}" y el recuento de argumentos: "{1}" + + + Error al invocar {0}. No se pudo encontrar el miembro. + + + Error al invocar {0}. No se admiten argumentos con nombre. + + + Error al invocar {0}. Desbordamiento detectado. + + + Error al invocar {0}. Se omitió un parámetro requerido. + + + Configuración de excepción "{0}": no se puede convertir el valor "{1}" de tipo "{2}" al tipo "{3}". + + + IDispatch::GetIDsOfNames se comportó de forma inesperada para {0}. + + + Error en Marshal.SetComObjectData. + + + VarEnum inesperado {0}. + + + Se intentó pasar un controlador de eventos de un tipo no admitido. + + + La palabra clave Configuration no se admite en PowerShell 6+. + + + No todas las rutas de acceso de código devuelven un valor dentro del método. + + + Instrucción return no válida dentro del método void. + + + Instrucción return no válida en un método que no devuelve void. + + + Falta el cuerpo "{0}" en la declaración ''{0}". + + + No se puede definir la enumeración debido a un ciclo en las expresiones de inicialización. + + + El valor del enumerador es demasiado grande o demasiado pequeño para {0}. + + + El valor del enumerador debe ser un valor constante. + + + Se produjo una excepción al realizar la comprobación semántica de la palabra clave dinámica "{0}" con detalles "{1}". + + + No se admite la propiedad "{0}" con el tipo "{1}" de la clase de recurso DSC "{2}". + + + Falta "(" en la lista de parámetros del método de clase. + + + No se permite un bloque con nombre en un método de clase. + + + No se permite un bloque param en un método de clase. + + + No se puede heredar de la clase sellada "{0}". + + + Se esperaba un nombre de tipo. + + + "{0}" no es un tipo subyacente válido para enumeraciones. Se esperaba un tipo entero integrado (uno de bytes, sbyte, short, ushort, int, uint, long o ulong) + + + "{0}": se esperaba un nombre de interfaz. + + + La clase base "{0}" no contiene un constructor sin parámetros. + + + Tipo base no válido "{0}". El tipo base no puede ser una matriz. + + + Tipo base no válido "{0}". El tipo base no puede ser genérico con parámetros no especificados. + + + Falta "base" después de ":" en una llamada al constructor de la clase base. + + + Un constructor no puede especificar un tipo de valor devuelto. + + + El recurso DSC "{0}" no tiene ningún constructor predeterminado. + + + Al recurso DSC "{0}" le falta un método Get que devuelva [{0}] y no acepte parámetros. + + + El recurso de DSC "{0}" debe tener al menos una propiedad de clave (con la sintaxis [DscProperty(Key)].) + + + Falta un método Set en el recurso de DSC "{0}" que devuelve [void] y no acepta ningún parámetro. + + + Falta un método Test en el recurso de DSC "{0}" que devuelva [bool] y no acepte parámetros. + + + Un constructor estático no puede tener parámetros. + + + No se permite el tipo "{0}" en una propiedad. + + + No se permite el tipo "{0}" en un parámetro. + + + No se puede obtener acceso al miembro no estático "{0}" en un método estático o en el inicializador de una propiedad estática. + + + No se pudo analizar el archivo de script del módulo "{0}" con el error +"{1}". + + + No se puede ejecutar un documento en PowerShell: {0}. + + + No se permiten varias restricciones de tipo en un parámetro de método. + + + Este script contiene contenido malintencionado y el software antivirus lo ha bloqueado. + + + "{0}" no se puede especificar en el recurso LocalConfigurationManager. Cambie a Configuración en su lugar o use solo los siguientes valores: {1}. + + + "{0}" se define en un tipo genérico. + + + El nombre de tipo "{0}" es ambiguo; podría ser "{1}" o "{2}". + + + Una instrucción "using" debe aparecer antes que cualquier otra instrucción de un script. + + + No se admite esta sintaxis de la instrucción "using". + + + El espacio de nombres especificado en la instrucción "using" contiene caracteres no válidos. + + + flujo de información + + + Propiedad de clave no válida. La propiedad de clave debe ser de [cadena], entero con signo o sin signo o tipos de enumeración. + + + Método Get no válido. El método Get debe devolver [{0}] y no acepta ningún parámetro. + + + No se puede cargar el ensamblado '{0}'. + + + No se puede usar el ensamblado con una ruta de acceso UNC: "{0}". + + + No se puede usar el ensamblado con el esquema URI "{0}". + + + Falta una nueva línea o punto y coma. + + + No se puede asignar la propiedad; use ''{0}{1}". + + + "{0}" no es un valor válido para usar el nombre. + + + No se puede asignar la propiedad; use ''{0}{1}". + + + DebugMode solo debe tener un valor. + + + No se encontró la etiqueta "{0}" dentro del método. + + + No se pudo convertir el valor de CimProperty {0} en el valor de propiedad de la clase {1}. + + + La propiedad {0} de la clase de PowerShell {1} no está declarada como tipo de matriz, sino que se define en su instancia de configuración como tipo de matriz de instancia. + + + No se pudo crear un objeto de la clase PowerShell {0}. + + + La tabla hash proporcionada al recurso Desired State Configuration {0} no es válida. La clave o el valor no pueden ser nulos ni estar vacíos. + + + El nombre de usuario proporcionado al recurso {0} de Desired State Configuration no es válido. El nombre de usuario no puede ser nulo ni estar vacío. + + + El nombre de usuario proporcionado al recurso {0} de Desired State Configuration no es válido. El nombre de usuario no puede ser nulo ni estar vacío. + + + La propiedad {0} no se declara en la clase de PowerShell {1}, sino que se define en su instancia de configuración. + + + PartialConfiguration "{0}" tiene un modo de actualización establecido en Deshabilitado, que no es un modo válido para las configuraciones parciales. Use el modo de actualización de extracción o inserción. + + + No se puede crear el tipo. En este modo de lenguaje solo se admiten los tipos principales. + + + Import-DscResource no se puede especificar dentro del contexto de Node + + + $PSCulture, $PSUICulture, $true, $false $null + + + No se puede asignar una variable automática "{0}" con el tipo "{1}" + + + Hay un conflicto al usar PsDscRunAsCredential para el recurso {0} porque ya especifica un valor de PsDscRunAsCredential. Solo se puede usar un PsDscRunAsCredential para el recurso compuesto. + + + No se encuentra el almacén de esquemas de DSC en "{0}". Asegúrese de que el módulo PSDesiredStateConfiguration v3 está instalado. + + + {0} + + + Este script contiene contenido que se ha marcado como sospechoso a través de una configuración de directiva y se ha bloqueado con el código de error {0}. Póngase en contacto con el administrador para obtener más información. + + + No se pueden usar los operadores '&' ni '.' para invocar un comando de ámbito de módulo entre límites de idioma. + + + La palabra clave Class no se permite en el modo ConstrainedLanguage. + + + Falta ":" en la expresión ternaria. + + + Un operador de cadena de canalización debe ir seguido de una canalización. + + + Los operadores en segundo plano solo se pueden usar al final de una cadena de canalización. + + + No se admite la invocación directa del bloque "clean" de un bloque de script. + + + Palabra clave de configuración del analizador + + + La palabra clave Configuration no se permitirá en el modo de lenguaje restringido para scripts que no sean de confianza. + + + Palabra clave de clase Parser + + + La palabra clave Class no se permitirá en el modo de lenguaje restringido para scripts que no sean de confianza. + + + Sección de datos del analizador SupportedCommand + + + La Sección de datos que incluye el parámetro SupportedCommand no se permite en el modo de lenguaje restringido para scripts que no son de confianza. + + + Operador de llamada de ámbito de módulo + + + El operador de llamada de ámbito de módulo se denegará en el modo de lenguaje restringido. + + + Invocación del método de palabra clave ForEach + + + La palabra clave ForEach producirá un error al invocar el método del elemento de iteración "{0}" cuando se ejecute en el modo de lenguaje restringido. + + + Puede producirse un error en la evaluación de expresiones + + + La creación de una canalización paso a paso a partir de un bloque de script puede requerir la evaluación de algunas expresiones dentro del bloque de script. La evaluación de expresiones producirá un error en modo silencioso y devolverá "null" en el modo de lenguaje restringido, a menos que la expresión represente un valor constante. + + + La palabra clave de configuración no se admite en procesadores ARM64. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PathUtilsStrings.es.resx b/src/System.Management.Automation/resources/es/PathUtilsStrings.es.resx new file mode 100644 index 00000000000..8af7195e89d --- /dev/null +++ b/src/System.Management.Automation/resources/es/PathUtilsStrings.es.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La codificación "UTF-7" está obsoleta; use UTF-8. + + + El archivo {0} ya existe y {1} se especificó. + + + No se puede abrir el archivo porque el proveedor actual ({0}) no puede abrir un archivo. + + + No se puede realizar la operación porque la ruta de acceso se resolvió en más de un archivo. Este comando no puede funcionar en varios archivos. + + + No se puede realizar la operación porque la ruta de acceso comodín {0} no se resolvió en un archivo. + + + Codificación desconocida {0}; los valores válidos son {1}. + + + El directorio "{0}" ya existe. Use el parámetro -Force si desea sobrescribir el directorio y los archivos dentro del directorio. + + + La ruta de acceso del módulo de usuario no existe y, por lo tanto, no se puede crear una carpeta de módulo para el nombre de módulo proporcionado "{0}". + + + No se puede crear el módulo {0} debido a lo siguiente: {1}. Use un argumento diferente para el parámetro -OutputModule y vuelva a intentarlo. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + No se puede cargar el módulo porque se generó con una versión incompatible del cmdlet {0}. Genere el módulo con el cmdlet {0} de la sesión actual e intente cargar el módulo de nuevo. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PipelineStrings.es.resx b/src/System.Management.Automation/resources/es/PipelineStrings.es.resx new file mode 100644 index 00000000000..0970b799588 --- /dev/null +++ b/src/System.Management.Automation/resources/es/PipelineStrings.es.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede procesar la instancia de cmdlet porque otra canalización está usando la instancia del cmdlet. Póngase en contacto con los servicios de atención al cliente de Microsoft. + + + No se puede realizar la operación porque se ha iniciado la canalización. Detenga la canalización e intente la operación de nuevo. + + + No se puede seguir ejecutando el cmdlet porque la directiva Stop ha impedido la ejecución de cmdlets. + + + No se puede ejecutar la canalización porque el primer cmdlet de la canalización intenta leer la entrada a partir de los resultados de un cmdlet anterior. Modifique el primer cmdlet, elimínelo o agregue a la canalización el cmdlet cuya salida necesita el primer cmdlet y, después, vuelva a intentar ejecutar la canalización. + + + No se puede procesar el número de cmdlet. La función ReadFromCommand debe especificar el id. de un cmdlet que ya se haya agregado a la canalización. Póngase en contacto con los servicios de atención al cliente de Microsoft. + + + No se puede leer la salida de las funciones ReadFromCommand y ReadErrorQueue porque otro cmdlet ya está leyendo esa salida. Póngase en contacto con los servicios de atención al cliente de Microsoft. + + + No se puede ejecutar la canalización porque no hay comandos. Agregue al menos un comando a la canalización y vuelva a ejecutarlo. + + + No se puede completar la operación de canalización porque aún no se ha iniciado. Debe llamar al método Begin() antes de llamar a End() en una canalización paso a paso. + + + Los métodos WriteObject y WriteError no se pueden llamar desde fuera de las invalidaciones de los métodos BeginProcessing, ProcessRecord y EndProcessing, y solo se pueden llamar desde el mismo subproceso. Compruebe que el cmdlet realiza estas llamadas correctamente o póngase en contacto con el servicio de soporte técnico de Microsoft. + + + Un cmdlet produjo una excepción después de llamar a ThrowTerminatingError. +La primera excepción fue "{0}" con el seguimiento de pila "{1}". +La segunda excepción fue "{2}" con el seguimiento de pila "{3}". + + + No se pueden llamar a los métodos WriteObject y WriteError después de cerrar la canalización. Póngase en contacto con los servicios de atención al cliente de Microsoft. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Error al crear la canalización. + + + Esta canalización no admite la semántica de desconexión y conexión. + + + No se puede conectar esta canalización porque no está en estado desconectado. + + + El objeto de espacio de ejecución tiene asociado un comando remoto nulo. No se puede crear un objeto RemotePipeline desconectado porque no se ha especificado ningún comando remoto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/PowerShellStrings.es.resx b/src/System.Management.Automation/resources/es/PowerShellStrings.es.resx new file mode 100644 index 00000000000..52f3e64adea --- /dev/null +++ b/src/System.Management.Automation/resources/es/PowerShellStrings.es.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 + + + El estado de la instancia actual de PowerShell no es válido para esta operación. + + + No se puede realizar la operación porque ya se inició un comando. Espere a que se complete el comando o deténgalo y, a continuación, vuelva a intentar la operación. + + + No se ha especificado ningún comando. + + + La instancia de PowerShell no está en el estado correcto para crear una instancia anidada de PowerShell. Las instancias anidadas de PowerShell solo se deben crear en una instancia de PowerShell en ejecución. + + + No se puede realizar la operación porque el espacio de ejecución no se encuentra en el estado "{0}". El estado actual del espacio de ejecución es "{1}". + + + Las instancias anidadas de PowerShell no se pueden invocar de forma asincrónica. Use el método de Invocar. + + + El objeto {0} no se creó mediante la llamada a {1} en esta instancia de PowerShell. + + + Cuando el espacio de ejecución está configurado para reutilizar un subproceso, el estado del apartamento en la configuración de invocación debe coincidir con el del espacio de ejecución. + + + Cuando el espacio de ejecución está configurado para usar el subproceso actual, el estado del apartamento en la configuración de invocación debe coincidir con el del subproceso actual. + + + Se requiere un comando para agregar un parámetro. Debe agregarse un comando a la instancia de PowerShell antes de agregar un parámetro. + + + Las claves del diccionario deben ser cadenas. + + + No hay ningún espacio de ejecución disponible para ejecutar comandos en este subproceso. Puede proporcionar uno en la propiedad DefaultRunspace del tipo System.Management.Automation.Runspaces.Runspace. El comando que intentó invocar era: {0} + + + Este objeto de PowerShell no se puede conectar porque no está asociado a un espacio de ejecución remoto ni a un grupo de espacios de ejecución. + + + El comando en ejecución se ha desconectado, pero sigue ejecutándose en el servidor remoto. Vuelva a conectarse para obtener el estado de la operación del comando y los datos de salida. + + + No se puede realizar la operación porque la sesión actual de PowerShell está en estado Desconectado. Conecte esta sesión de PowerShell y, a continuación, espere a que el comando termine o deténgalo. + + + No se puede realizar la operación porque la sesión actual de PowerShell está en estado Desconectado. Conecte esta sesión de PowerShell e inténtelo de nuevo. + + + Error al intentar conectar con el comando remoto. + + + No se puede realizar la operación porque un comando se está deteniendo actualmente. Espere a que termine de detenerse el comando y, a continuación, vuelva a intentar la operación. + + + No hay ningún espacio de ejecución disponible para ejecutar comandos en este subproceso. Puede proporcionar uno en la propiedad DefaultRunspace del tipo System.Management.Automation.Runspaces.Runspace. La instancia actual de PowerShell no contiene ningún comando que invocar. + + + No se puede crear un objeto de PowerShell que use el espacio de ejecución actual porque no hay ningún espacio de ejecución actual disponible. Es posible que el espacio de ejecución actual se esté iniciando, como cuando se crea con un estado de sesión inicial. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ProgressRecordStrings.es.resx b/src/System.Management.Automation/resources/es/ProgressRecordStrings.es.resx new file mode 100644 index 00000000000..3d2b60a8d3d --- /dev/null +++ b/src/System.Management.Automation/resources/es/ProgressRecordStrings.es.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede procesar el argumento porque {0} no puede ser un valor negativo. + + + No se puede procesar el argumento porque el valor de {0} no puede ser nulo ni estar vacío. + + + No se puede establecer el porcentaje porque {0} no puede ser mayor que 100. + + + ParentActivityId no puede ser igual a ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ProviderBaseSecurity.es.resx b/src/System.Management.Automation/resources/es/ProviderBaseSecurity.es.resx new file mode 100644 index 00000000000..3bbf622644e --- /dev/null +++ b/src/System.Management.Automation/resources/es/ProviderBaseSecurity.es.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 + + + No se puede usar la interfaz porque este proveedor no admite la interfaz ISecurityDescriptorCmdletProvider. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/ProxyCommandStrings.es.resx b/src/System.Management.Automation/resources/es/ProxyCommandStrings.es.resx new file mode 100644 index 00000000000..59b1f0e16a9 --- /dev/null +++ b/src/System.Management.Automation/resources/es/ProxyCommandStrings.es.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 + + + El parámetro "help" no se reconoce como un objeto HelpInfo válido creado por el comando "get-help". + + + No se puede generar el comando proxy porque CommandMetadata no tiene nombre. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/RegistryProviderStrings.es.resx b/src/System.Management.Automation/resources/es/RegistryProviderStrings.es.resx new file mode 100644 index 00000000000..918fa0442da --- /dev/null +++ b/src/System.Management.Automation/resources/es/RegistryProviderStrings.es.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Establecer elemento + + + Elemento: {0} Valor: {1} + + + Borrar elemento + + + Elemento: {0} + + + Nuevo elemento + + + Elemento: {0} + + + Quitar clave + + + Elemento: {0} + + + Copiar clave + + + Elemento: {0} Destino: {1} + + + Cambiar nombre de elemento + + + Elemento: {0} NewName: {1} + + + Mover elemento + + + Elemento: {0} Destino: {1} + + + Establecer propiedad + + + Elemento: {0} Propiedad: {1} + + + Borrar propiedad + + + Elemento: {0} Propiedad: {1} + + + Nueva propiedad + + + Elemento: {0} Propiedad: {1} + + + Quitar propiedad + + + Elemento: {0} Propiedad: {1} + + + Cambiar el nombre de la propiedad. + + + Elemento: {0} SourceProperty: {1} DestinationProperty: {2} + + + Copiar propiedad + + + Elemento: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Mover propiedad + + + Elemento: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + No se procesó la operación. La ubicación proporcionada no permite esta operación. + + + No se permite la operación en la ubicación de origen. + + + No se permite la operación en la ubicación de destino. + + + Las opciones de configuración del equipo local + + + La configuración de software del usuario actual + + + Ya existe una clave con esta ruta de acceso. + + + No se puede realizar la operación porque la ruta de destino está subordinada a la ruta de origen. + + + La propiedad ya existe. + + + La propiedad {0} no existe en la ruta de acceso {1}. + + + La clave del Registro de la ruta especificada no existe. + + + No se pudo enlazar el parámetro "Type". No se pudo convertir "{0}" en "{1}". Los valores de enumeración posibles son "String, ExpandString, Binary, DWord, MultiString, QWord, Unknown". + + + Se ha creado la clave {0}, pero no se pudo establecer un valor predeterminado. + + + No se puede crear una unidad con la raíz especificada. La ruta de acceso raíz no existe. + + + No se puede cambiar el nombre del elemento porque ya existe un elemento con ese nombre en el mismo contenedor. + + + El nombre de la clave del Registro debe empezar por un nombre de clave raíz válido. + + + El argumento de subclave no es válido. + + + No se puede eliminar el árbol de la subclave porque la subclave no existe. + + + No existe ningún valor con ese nombre. + + + El valor de enumeración {0} no es válido. + + + Se debe especificar un argumento de valor. + + + Se debe especificar un argumento de nombre. + + + El valor de RegistryValueKind especificado no es válido. + + + RegistryKey.SetValue no permite un String[] que contenga una referencia Cadena nula. + + + Las subclaves del Registro no debe superar los 255 caracteres. + + + Debe especificarse un nombre de subclave que no esté vacío. + + + El tipo del objeto de valor no coincide con el RegistryValueKind especificado o el objeto no se pudo convertir correctamente. + + + RegistryKey.SetValue no admite matrices de tipo "{0}". Solo se admiten Byte[] y String[]. + + + La clave del Registro especificada no existe. + + + La longitud del nombre del valor especificado supera el máximo de 16383 caracteres. + + + El tamaño de los datos del valor especificado supera el máximo de 1 MB. + + + La subclave del Registro especificada no existe. + + + El valor especificado para RegistryKeyPermissionCheck no es válido. + + + La clave del Registro tiene subclaves; este método no admite eliminaciones recursivas. + + + No se puede crear un controlador de KTM sin Transaction.Current o una transacción especificada. + + + La transacción especificada o Transaction.Current debe coincidir con la transacción usada para crear o abrir este TransactedRegistryKey. + + + El objeto TransactedRegistryKey no está asociado a una transacción porque corresponde a una clave predefinida. + + + No se permite el acceso al Registro solicitado. + + + Se denegó el acceso a la clave del Registro "{0}". + + + No se puede escribir en la clave del Registro. + + + No se puede acceder a una clave del Registro cerrada. + + + Error desconocido: {0}. + + + Las transacciones del Registro no se admiten en esta plataforma. + + + El identificador especificado no es válido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/RemotingErrorIdStrings.es.resx b/src/System.Management.Automation/resources/es/RemotingErrorIdStrings.es.resx new file mode 100644 index 00000000000..01969264705 --- /dev/null +++ b/src/System.Management.Automation/resources/es/RemotingErrorIdStrings.es.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + No se admiten caracteres comodín para el parámetro FilePath. Especifique una ruta de acceso sin caracteres comodín. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + Se debe especificar un {0} valor para la opción de sesión {1}. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + El número máximo de redireccionamientos de URI de WS-Man que se permiten al conectarse a un equipo remoto + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + El parámetro WriteEvents no se puede usar sin el parámetro Wait. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + La comunicación remota de PowerShell no se admite en el Entorno de preinstalación de Windows (WinPE). + + + Los cambios realizados por {0} no pueden surtir efecto hasta que se reinicie el servicio WinRM. + + + {0} es posible que tenga que reiniciar el servicio WinRM si recientemente se ha anulado el registro de una configuración que usa este nombre, es posible que algunas estructuras de datos del sistema aún se almacenen en caché. En ese caso, puede ser necesario reiniciar WinRM. +Todas las sesiones de WinRM conectadas a configuraciones de sesión de PowerShell, como Microsoft.PowerShell, y a configuraciones de sesión creadas con el cmdlet Register-PSSessionConfiguration, se desconectan. + + + Está ejecutando una sesión remota y ha seleccionado la opción Force, lo que significa que el servicio WinRM puede reiniciarse. Si el servicio WinRM se reinicia, esta sesión remota finalizará y tendrá que crear una nueva sesión para continuar + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + El parámetro -WriteJobInResults no se puede usar sin el parámetro -Wait + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + El flujo de entrada proporcionado no es válido. Solo {0} se admite como flujo de entrada. + + + El conjunto de flujos de salida proporcionado no es válido. Solo {0} se admite como flujo de salida. + + + El WSMAN_SENDER_DETAILS proporcionado no es válido. No se puede procesar la WSMAN_SENDER_DETAILS null. + + + El contexto de shell proporcionado no es válido. + + + {0} + + + No se permite {0} el valor NULL con el método {1}de complemento. + + + No se permite un valor NULL para los conjuntos de flujo de entrada y de flujo de salida. {0} y {1} son los flujos de entrada y salida admitidos. + + + No se permite {0} el valor NULL con el método {1}de complemento. + + + No se permite {0} el valor NULL con el método {1}de complemento. + + + La operación del complemento de PowerShell se está cerrando. Esto puede ocurrir si el servicio de hospedaje o la aplicación se está cerrando. + + + El complemento de PowerShell no entiende la opción {0}. Asegúrese de que el cliente es compatible con la compilación {1} y la versión {2} de protocolo de PowerShell. + + + Se espera una opción con el nombre {0} del cliente. Asegúrese de que el cliente es compatible con la compilación {1} y la versión {2} de protocolo de PowerShell. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">El complemento de PowerShell no admite la versión del protocolo {2} solicitada por el cliente.</PSProtocolVersionError> + + + El complemento de PowerShell encontró un error irrecuperable al notificar el contexto al servicio WSMan. + + + No se puede crear la sesión del servidor administrado. + + + El complemento de PowerShell encontró un error irrecuperable al registrar un identificador de espera para la notificación de apagado. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + No se encontró el archivo ejecutable "{0}". Compruebe que la característica WOW64 está instalada. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + No se puede crear Windows PowerShell proceso porque no se encontró Windows PowerShell en este equipo. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/RunspaceInit.es.resx b/src/System.Management.Automation/resources/es/RunspaceInit.es.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/es/RunspaceInit.es.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/RunspacePoolStrings.es.resx b/src/System.Management.Automation/resources/es/RunspacePoolStrings.es.resx new file mode 100644 index 00000000000..0bb3a8c54ab --- /dev/null +++ b/src/System.Management.Automation/resources/es/RunspacePoolStrings.es.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El tamaño máximo del grupo no puede ser inferior a 1. + + + El tamaño mínimo del grupo no puede ser inferior a 1. + + + El tamaño mínimo del grupo no puede ser mayor que el tamaño máximo del grupo. + + + El estado del grupo de espacios de ejecución no es válido para esta operación. + + + No se puede realizar la operación porque el grupo de espacio de ejecución no se encuentra en el estado "{0}". El estado actual es "{1}". + + + No se puede abrir el grupo de espacios de ejecución porque no está en el estado "BeforeOpen". El estado actual es "{0}". + + + El objeto {0} no se creó al llamar a {1} en la instancia actual de RunspacePool. + + + No se puede lanzar el espacio de ejecución en el grupo actual porque el espacio de ejecución no pertenece a ese grupo. + + + Esta propiedad no se puede cambiar después de abrir el grupo de espacios de ejecución. + + + Este espacio de ejecución no admite operaciones de desconexión y conexión. + + + No se puede realizar la operación porque el grupo de espacio de ejecución está en estado Desconectado. + + + La operación Desconectar no se admite en el servidor. El servidor debe ejecutar PowerShell 3.0 o una versión posterior para admitir la desconexión del grupo de espacios de ejecución remoto. + + + Este grupo de espacios de ejecución {0} no está configurado para proporcionar objetos de PowerShell desconectados para los comandos que se ejecutan en el servidor remoto. Use el método estático GetRunspacePools() de la clase RunspacePool para consultar el servidor y devolver los objetos de grupo de espacios de ejecución que están configurados para hacerlo. + + + No se puede conectar este grupo de espacios de ejecución porque el grupo de espacios de ejecución correspondiente del lado del servidor está conectado a otro cliente. + + + ResetRunspaceState no se admite en el servidor. El servidor debe ejecutar PowerShell 5.0 o una versión posterior. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/RunspaceStrings.es.resx b/src/System.Management.Automation/resources/es/RunspaceStrings.es.resx new file mode 100644 index 00000000000..d2ca017ecec --- /dev/null +++ b/src/System.Management.Automation/resources/es/RunspaceStrings.es.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El estado del espacio de ejecución no es válido para esta operación. + + + No se puede abrir el espacio de ejecución porque el espacio de ejecución no está en el estado BeforeOpen. El estado actual del espacio de ejecución es "{0}". + + + No se puede realizar la operación porque el espacio de ejecución no tiene el estado Opened. El estado actual del espacio de ejecución es "{0}". + + + No se puede invocar la canalización porque el espacio de ejecución no tiene el estado Opened. El estado actual del espacio de ejecución es "{0}". + + + El estado de canalización no es válido para esta operación. + + + No se puede invocar la canalización porque ya se ha invocado. + + + El valor válido para el parámetro es PipelineResultTypes.Output. + + + La canalización no contiene un comando. + + + No se ejecutó la canalización porque ya se está ejecutando una canalización. Las canalizaciones no se pueden ejecutar simultáneamente. + + + Una canalización anidada no se puede invocar de forma asincrónica. Use el método de Invocar. + + + Solo debe ejecutar una canalización anidada desde dentro de una canalización en ejecución. + + + No se puede cerrar el espacio de ejecución mientras haya una llamada al método SessionStateProxy en curso. + + + No se puede invocar la canalización mientras hay una llamada al método SessionStateProxy en curso. + + + Hay una llamada al método SessionStateProxy en curso. No se permiten llamadas simultáneas al método SessionStateProxy. + + + Ya se está ejecutando una canalización. No se permiten llamadas simultáneas al método SessionStateProxy. + + + Esta propiedad no se puede cambiar una vez abierto el espacio de ejecución. + + + Se produjeron uno o varios errores al procesar el módulo "{0}" especificado en el objeto InitialSessionState usado para crear este espacio de ejecución. Consulte la propiedad ErrorRecords para obtener una lista completa de errores. El primer error fue: {1} + + + Las opciones de subproceso solo se pueden cambiar si el estado del contenedor es contenedor multiproceso (MTA), las opciones actuales son UseNewThread o UseCurrentThread y el nuevo valor es ReuseThread. + + + {0} no puede ser false cuando el modo de idioma es {1} o {2}. + + + No se puede desconectar un espacio de ejecución solo local. + + + La operación Connect no se admite en espacios de ejecución locales. + + + La sesión está ocupada. Se conectará a la sesión en cuanto esté disponible. Para cancelar el comando Enter-PSSession, presione Ctrl-C. + + + El comando no se ha podido completar. No se admite la invocación de scripts en esta configuración de sesión. Esto puede ocurrir si la configuración de sesión está en modo sin idioma. + + + No puede usar las operaciones Disconnect y Connect en espacios de ejecución locales. + + + No se puede conectar la canalización porque el espacio de ejecución no está en el estado Abierto. El estado actual del espacio de ejecución es "{0}". + + + No se puede construir un RemoteRunspace. El objeto RunspacePool proporcionado no es válido. + + + No hay ningún comando desconectado asociado a este espacio de ejecución. + + + La operación de desconexión no se admite en el equipo remoto. Para admitir la desconexión, el equipo remoto debe ejecutar Windows PowerShell 3.0 o una versión posterior de Windows PowerShell y usar el transporte WSMan. + + + No se puede conectar la PSSession porque la sesión no está en estado Desconectado o no está disponible para la conexión. + + + El valor del parámetro no puede ser PipelineResultTypes.None ni PipelineResultTypes.Output. + + + Los valores válidos para el parámetro son PipelineResultTypes.Output o PipelineResultTypes.Null. + + + No se admite la redirección de secuencias de depuración en el equipo remoto de destino. + + + No se admite el redireccionamiento detallado de secuencias en el equipo remoto de destino. + + + El redireccionamiento de secuencias de advertencia no se admite en el equipo remoto de destino. + + + El redireccionamiento de flujo de información no se admite en el equipo remoto de destino. + + + Ha entrado en una sesión que está ocupada ejecutando un comando o script. Dado que la salida se enruta al trabajo "{0}", no verá la salida en la consola. Puede esperar a que finalice el comando en ejecución o cancelar el comando y obtener un símbolo del sistema de entrada presionando Ctrl-C. + + + + Ha entrado en una sesión que está ocupada ejecutando un comando o script y la salida se mostrará en la consola. Puede esperar a que finalice el comando en ejecución o cancelarlo y obtener un mensaje de entrada presionando Ctrl-C. + + + + Ha entrado en una sesión que está detenida actualmente en un punto de interrupción de depuración dentro de un comando o script en ejecución. Use el depurador de línea de comandos de PowerShell para continuar con la depuración. + + + + DefaultRunspace debe ser LocalRunspace + + + La propiedad PrimaryRunspace estática solo se puede establecer una vez y ya se ha establecido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/SecuritySupportStrings.es.resx b/src/System.Management.Automation/resources/es/SecuritySupportStrings.es.resx new file mode 100644 index 00000000000..06bf01991d5 --- /dev/null +++ b/src/System.Management.Automation/resources/es/SecuritySupportStrings.es.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede cargar el certificado. "{0}" debe resolverse en una ruta de acceso del sistema de archivos. + + + El certificado "{0}" no se puede usar para el cifrado. Los certificados de cifrado deben contener el uso de claves de cifrado de datos o cifrado de claves, e incluir el uso mejorado de claves de cifrado de documentos ({1}). + + + No se puede cargar el certificado. El identificador "{0}" coincide con varios certificados. Para cifrar para varios destinatarios, proporcione varios valores específicos para el parámetro "{1}", en lugar de un comodín que coincida con varios certificados. + + + No se puede cargar certificado de cifrado. La configuración de certificado "{0}" no representa un certificado codificado en Base64 válido ni representa un certificado válido mediante archivo, directorio, huella digital o nombre de sujeto. + + + ADVERTENCIA: el certificado "{0}" contiene una clave privada. Los certificados de registro de eventos protegido usados para el cifrado solo deben contener la clave pública. + + + ERROR: no se pudo proteger el mensaje de registro de eventos "{0}": {1} + + + ERROR: no se pudo encontrar o usar el certificado: {0} + + + La clave de sesión no está disponible para cifrar la cadena segura. + + + Desplazamiento de búfer no válido. + + + Datos de clave pública no válidos. + + + No se puede importar la clave pública. + + + Datos de clave de sesión no válidos. + + + El archivo de script "{0}" no puede ejecutarse porque lo ha bloqueado la directiva del sistema. + + + Se devolvió un valor desconocido de aplicación de directiva de archivo de script: {0}. + + + Archivo de script leído + + + La directiva no confía en el archivo de script "{0}" y se ejecutará en modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/Serialization.es.resx b/src/System.Management.Automation/resources/es/Serialization.es.resx new file mode 100644 index 00000000000..726ab2ec3be --- /dev/null +++ b/src/System.Management.Automation/resources/es/Serialization.es.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} se esperaba el atributo. + + + {0} No se reconoce la etiqueta XML. + + + No se encontró ningún objeto para referenceId {0} + + + El atributo de nombre para la clave del diccionario no se especificó correctamente. + + + El atributo Name del valor del diccionario se ha especificado incorrectamente. + + + La versión de PSObject no es válida. + + + La versión del PSObject entrante es {0}. El valor esperado es 1. + + + No se pueden procesar los nombres porque no se encontró ningún TypeName para referenceId {0}. + + + El valor del parámetro de profundidad debe ser mayor o igual que 1. + + + El tipo de nodo actual es {0}. El tipo esperado es {1}. + + + No se especificó la clave para la entrada del diccionario. + + + No se ha especificado el valor de la entrada del diccionario. + + + No hay más objetos para deserializar. + + + Null se especifica como clave del diccionario. + + + El contenido del {0} tipo primitivo no es válido. + + + El XML serializado está demasiado anidado. + + + Se cerró el serializador. + + + Los datos del comando superaron el tamaño máximo permitido por la configuración de sesión. El máximo permitido es {0} MB. Cambie la entrada, use una configuración de sesión diferente o cambie las propiedades "{1}" y "{2}" de la configuración de sesión en el equipo remoto. + + + Error en la deserialización de la cadena segura cifrada + + + El tipo de clave {0} no es válido. La clase PSPrimitiveDictionary solo acepta claves del tipo System.String. + + + El tipo del valor {0} no es válido. La clase PSPrimitiveDictionary solo acepta valores de tipos que son totalmente serializables a través de la comunicación remota de PowerShell. Consulte el tema de ayuda about_Remoting para obtener una lista de tipos totalmente serializables. + + + No se pudieron descifrar los datos. Los datos no se cifraron con esta clave. + + + El valor de parámetro "{0}" no es una cadena cifrada válida. + + + El especificado {0} no es válido. Los valores de longitud válidos de {0} son 128 bits, 192 bits o 256 bits. + + + Actualmente, la deserialización de SecureString solo se admite en Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/SessionStateProviderBaseStrings.es.resx b/src/System.Management.Automation/resources/es/SessionStateProviderBaseStrings.es.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/es/SessionStateProviderBaseStrings.es.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/SessionStateStrings.es.resx b/src/System.Management.Automation/resources/es/SessionStateStrings.es.resx new file mode 100644 index 00000000000..5461b89efaf --- /dev/null +++ b/src/System.Management.Automation/resources/es/SessionStateStrings.es.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede procesar la información devuelta porque la información devuelta desde el método Start del proveedor era para un proveedor diferente del que se pasó. + + + No se puede procesar la información devuelta porque la información devuelta desde el método Start del proveedor era null. + + + Error al intentar realizar la operación GetItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación GetItem no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación SetItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación SetItem no se pueden recuperar del proveedor "{0}" para la ruta de acceso ''{1}". {2} + + + Error al intentar realizar la operación ClearItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación InvokeDefaultAction en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación InvokeDefaultAction no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación ItemExists en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación ItemExists no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación IsValidPath en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación IsItemContainer en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación RemoveItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación GetChildItems en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación GetChildItems no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación GetChildNames en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación GetChildNames no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación RenameItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación RenameItem no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación NewItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación NewItem no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación HasChildItems en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación CopyItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación CopyItem no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación GetParentPath en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación NormalizeRelativePath en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación MakePath en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación GetChildName en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación MoveItem en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación MoveItem no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación GetProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación GetProperty no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación SetProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación SetProperty no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación ClearProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación ClearProperty no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación NewProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación NewProperty no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación RemoveProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Los parámetros dinámicos para la operación RemoveProperty no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación CopyProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + No se pueden recuperar los parámetros dinámicos de la operación CopyProperty para el proveedor "{0}" de la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación MoveProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + No se pueden recuperar los parámetros dinámicos de la operación MoveProperty para el proveedor "{0}" de la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación RenameProperty en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + No se pueden recuperar parámetros dinámicos para RenameProperty para el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + No se puede recuperar el lector de contenido para el proveedor "{0}" para la ruta de acceso ''{1}". {2} + + + No se pueden recuperar los parámetros dinámicos de la operación GetContentReader para el proveedor "{0}" de la ruta de acceso "{1}". {2} + + + No se puede recuperar el escritor de contenido para el proveedor "{0}" para la ruta de acceso ''{1}". {2} + + + No se pueden recuperar los parámetros dinámicos de la operación GetContentWriter para el proveedor "{0}" de la ruta de acceso "{1}". {2} + + + No se puede obtener contenido porque es un directorio: "{0}". Use "Get-ChildItem" en su lugar. + + + No se puede escribir contenido porque es un directorio: "{0}". + + + No queda ningún historial de ubicaciones para navegar hacia atrás. + + + No queda ningún historial de ubicaciones para avanzar. + + + BoundedStack está vacío. + + + Error al intentar realizar la operación ClearContent en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + No se puede borrar el contenido de "{0}" porque es un directorio. Clear-Content solo se admite en archivos. + + + Los parámetros dinámicos para la operación ClearContent no se pueden recuperar del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación GetSecurityDescriptor en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación SetSecurityDescriptor en el proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error al intentar realizar la operación De inicio en el proveedor ''{0}". {1} + + + Error al intentar realizar la operación InitializeDefaultDrives en el proveedor ''{0}". + + + Error al intentar realizar la operación NewDrive en el proveedor "{0}" para la unidad con la raíz "{1}". {2} + + + No se pueden recuperar parámetros dinámicos para NewDrive para el proveedor ''{0}". {1} + + + Error en la invocación de RemoveDrive en el proveedor ''{0}". {1} + + + No se puede quitar la unidad "{0}" porque el proveedor "{1}" lo impidió. + + + La ruta de acceso "{0}" hacía referencia a un elemento que estaba fuera de la base ''{1}". + + + Error en la invocación de Seek en el escritor de contenido del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error en la invocación de Close en el lector de contenido o escritor del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error en la invocación de Read en el lector de contenido del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + Error en la invocación de Write en el escritor de contenido del proveedor "{0}" para la ruta de acceso "{1}". {2} + + + El proveedor "{0}" no se puede usar para obtener o establecer datos mediante la sintaxis de variable. {2} + + + La sintaxis de variable no se puede usar para obtener o establecer datos en el proveedor. {2} + + + No se puede escribir en el alias porque el alias {0} es de solo lectura o constante y no se puede modificar. + + + No se puede escribir en la función {0} porque es de solo lectura o constante. + + + No se puede sobrescribir la variable {0} porque es de solo lectura o constante. + + + No se puede tener acceso a la variable "${0}" porque es una variable privada. + + + No se puede tener acceso al comando "{0}" porque es un comando privado. + + + No se puede tener acceso al comando porque es un comando privado. + + + No se puede acceder al recurso de estado de sesión porque es un recurso privado. + + + No se quitó el alias {0} porque es constante o de solo lectura. + + + No se puede quitar la función {0} porque es constante. + + + No se puede quitar la variable {0} porque es constante o de solo lectura. Si la variable es de solo lectura, intente la operación de nuevo especificando la opción Force. + + + El alias {0} no se puede modificar porque es constante. + + + No se puede modificar el alias {0} porque es de solo lectura. + + + No se puede modificar la función {0} porque es constante. + + + No se puede modificar la función {0} porque es de solo lectura. + + + El alias {0} no se puede convertir en constante después de crearse. Los alias solo se pueden hacer constantes en el momento de la creación. + + + La función existente {0} no se puede convertir en constante. Las funciones solo se pueden hacer constantes en el momento de la creación. + + + La variable {0} existente no se puede hacer constante. Las variables solo se pueden convertir en constantes en el momento de la creación. + + + La opción AllScope no se puede quitar del alias ''{0}. + + + La opción AllScope no se puede quitar de la función "{0}". + + + La opción AllScope no se puede quitar de la variable "{0}". + + + La definición de función "{0}" contenía un calificador de ámbito, pero ningún nombre de función. + + + No se puede quitar el proveedor {0}. Todas las unidades asociadas con el proveedor {0} deben quitarse antes de que se pueda quitar el proveedor {0}. + + + No se puede procesar el nombre de la unidad porque contiene uno o varios de los caracteres siguientes que no son válidos: ; ~ / \ . : + + + Error al crear la nueva unidad porque el proveedor no permite la creación de la nueva unidad. + + + El valor proporcionado "{0}" se resolvió en más de una pila de ubicación. + + + No se encuentra la pila de ubicación "{0}". No existe o no es un contenedor. + + + No se encuentra la ruta de acceso '{0}' porque no existe. + + + No se encuentra el alias porque el alias "{0}" no existe. + + + No se puede establecer la ubicación porque la ruta de acceso "{0}" se resolvió en varios contenedores. Solo puede establecer la ubicación en un único contenedor a la vez. + + + No se puede procesar la variable porque la ruta de acceso de la variable "{0}" se resolvió en varios elementos. Solo puede obtener o establecer el valor de variable de un elemento a la vez. + + + No se encuentra la unidad. No existe una unidad con el nombre "{0}". + + + No se encuentra un proveedor con el nombre ''{0}". + + + No se encuentra un proveedor con el nombre ''{0}". El nombre no tiene el formato adecuado. Un nombre de proveedor solo puede ser caracteres alfanuméricos o un nombre de complemento de PowerShell seguido de un solo '\', seguido de caracteres alfanuméricos. + + + "{0}" se resolvió en más de un nombre de proveedor. Las posibles coincidencias incluyen:{1}. + + + Error al intentar crear una instancia del proveedor. No se encontró el nombre de tipo de proveedor "{0}" en el ensamblado. + + + No se puede usar el nombre de proveedor especificado "{0}" porque contiene uno o varios de los siguientes caracteres que no son válidos: \ [ ] ? * : + + + Error al intentar crear una instancia del proveedor ''{0}". {1} + + + No se encuentra una variable con el nombre ''{0}". + + + No se encuentra un origen de seguimiento con el nombre "{0}". + + + Ya existe una unidad con el nombre "{0}". + + + Ya existe una variable con el nombre "{0}". + + + No se permite el alias porque ya existe un alias con el nombre ''{0}". + + + No se puede registrar el proveedor de cmdlets porque ya existe un proveedor de cmdlets con el nombre ''{0}". + + + La ruta de acceso no hace referencia a una ruta de acceso del sistema de archivos. + + + No se puede quitar el ámbito global. + + + El número de ámbito "{0}" supera el número de ámbitos activos. + + + No se puede comparar PSDriveInfo. Una instancia de PSDriveInfo solo se puede comparar con otra instancia de PSDriveInfo. + + + El proveedor de cmdlets no puede transmitir los resultados porque no se especificó ningún cmdlet a través del cual transmitir la salida. + + + El proveedor de cmdlet no puede transmitir los resultados porque no se especificó ningún cmdlet a través del cual transmitir el error. + + + La ubicación principal de este proveedor no está establecida. Para establecer la ubicación principal, llame a "(get-psprovider ''{0}). Inicio = 'path'". + + + La ruta de acceso no tiene el formato correcto. Las rutas de acceso del proveedor deben contener un identificador de proveedor, seguido de "::", seguido de una ruta de acceso específica del proveedor. + + + No se puede mover el elemento porque la ruta de acceso de destino solo se puede resolver en una única ruta de acceso. + + + No se puede mover el elemento porque las rutas de acceso de origen y destino no se resolvieron en el mismo proveedor. + + + No se puede mover el elemento porque la ruta de acceso de origen apunta a uno o varios elementos y la ruta de acceso de destino no es un contenedor. Valide que la ruta de acceso de destino sea un contenedor e inténtelo de nuevo. + + + No se puede mover el elemento porque el destino se resolvió en varias rutas de acceso. Especifique una ruta de acceso de destino que se resuelva en un único destino e inténtelo de nuevo. + + + No se puede copiar el contenedor en el elemento hoja existente. + + + El contenedor no se puede copiar en otro contenedor. No se especificó el parámetro -Recurse ni el parámetro -Container. + + + La ruta de acceso de origen y destino no se resolvió en el mismo proveedor. + + + No se puede cambiar el nombre del elemento porque la ruta de acceso se resolvió en varios elementos. Solo se puede cambiar el nombre de un elemento a la vez. + + + No se puede usar el proveedor "{0}" para resolver la ruta de acceso "{1}" debido a un error en el proveedor. + + + No se puede usar la interfaz. Este proveedor no implementa la interfaz IContentCmdletProvider. + + + No se puede usar la interfaz. Este proveedor no admite la interfaz IPropertyCmdletProvider. + + + No se puede usar la interfaz. Este proveedor no implementa la interfaz IDynamicPropertyCmdletProvider. + + + Este proveedor no admite los métodos NavigationCmdletProvider. + + + Métodos de proveedor no procesados. Este proveedor no admite los métodos ContainerCmdletProvider. + + + No se pueden llamar a métodos. Este proveedor no admite los métodos ItemCmdletProvider. + + + Este proveedor no admite los métodos DriveCmdletProvider. + + + Operación de proveedor detenida porque el proveedor no admite esta operación. + + + La operación del proveedor se detuvo porque el proveedor no admite el parámetro "Depth". + + + No se puede llamar al método. Este proveedor no admite el método Seek para contenido. + + + No se puede realizar la operación ClearContent. Este proveedor no admite la operación ClearContent. + + + El proveedor no admite el uso de credenciales. Vuelva a realizar la operación sin especificar las credenciales. + + + El proveedor FileSystem solo admite credenciales en el cmdlet New-PSDrive. Vuelva a realizar la operación sin especificar las credenciales. + + + El proveedor no admite transacciones. Vuelva a realizar la operación sin el parámetro -UseTransaction. + + + No se puede llamar al método. El proveedor no admite el uso de filtros. + + + No se puede crear la unidad. El proveedor no admite el uso de credenciales. + + + El elemento de la ruta de acceso "{0}'"ya existe. + + + No se puede copiar el elemento. El elemento de la ruta de acceso "{0}" no existe. + + + El elemento de la ruta de acceso "{0}" no existe. + + + Unidad que contiene una vista de los alias almacenados en un estado de sesión + + + Unidad que contiene una vista de las variables de entorno del proceso + + + Unidad que contiene una vista de las funciones almacenadas en un estado de sesión + + + Unidad que contiene una vista de las variables almacenadas en un estado de sesión + + + Unidad que se asigna a la ruta de acceso del directorio temporal para el usuario actual + + + No se puede crear el vínculo "{0}" porque no se especificó el valor de destino. + + + Las referencias a la variable null siempre devuelven el valor null. Las asignaciones no tienen ningún efecto. + + + Número máximo de objetos de historial que se conservarán en una sesión + + + No se puede cambiar el nombre de la función porque la función {0} es de solo lectura o constante. + + + No se puede cambiar el nombre del alias porque el alias {0} es de solo lectura o constante. + + + No se puede cambiar el nombre de la variable {0} porque es de solo lectura o constante. + + + No se pueden establecer opciones en la variable local {0}. Use New-Variable para crear una variable que permita establecer opciones. + + + No se puede modificar el cmdlet {0} porque es de solo lectura. + + + No se puede quitar la variable {0} porque se ha optimizado y no se puede quitar. Pruebe a usar el cmdlet Remove-Variable (sin ningún alias) o use dot-sourcing para usar el comando que usa para quitar la variable. + + + No se puede sobrescribir la variable {0} porque se ha optimizado. Pruebe a usar el cmdlet New-Variable o Set-Variable (sin ningún alias), o use dot-source para establecer la variable. + + + Los parámetros {0} y {1} no se pueden usar juntos. Especifique solo un parámetro. + + + Actualmente, el parámetro Tail solo se admite para el proveedor FileSystem. + + + No se permite el alias porque ya existe un comando con el nombre "{0}" y el tipo de comando ''{1}". + + + No se puede ejecutar el software. Permiso denegado. + + + "-{0}" y "-{1}" son mutuamente excluyentes y no se pueden especificar al mismo tiempo. + + + La ruta de acceso "{0}" no es válida. Solo se admiten rutas de acceso absolutas en las operaciones de copia remota. + + + No se puede validar la ruta de acceso remota "{0}". + + + No se puede realizar la operación porque la sesión {0} está establecida en {1}. + + + El parámetro "{0}" no puede ser nulo ni estar vacío. + + + Variables de estado de sesión + + + El cambio o creación del ámbito de la variable "{0}" a AllScope se impedirá en el modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/StringDecoratedStrings.es.resx b/src/System.Management.Automation/resources/es/StringDecoratedStrings.es.resx new file mode 100644 index 00000000000..2e3d956515f --- /dev/null +++ b/src/System.Management.Automation/resources/es/StringDecoratedStrings.es.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Solo se admite ''ANSI'' o ''PlainText'' para este método. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/SubsystemStrings.es.resx b/src/System.Management.Automation/resources/es/SubsystemStrings.es.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/es/SubsystemStrings.es.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/SuggestionStrings.es.resx b/src/System.Management.Automation/resources/es/SuggestionStrings.es.resx new file mode 100644 index 00000000000..1c19b64fae9 --- /dev/null +++ b/src/System.Management.Automation/resources/es/SuggestionStrings.es.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 + + + No se encontró el comando "{0}", pero sí existe en la ubicación actual. +PowerShell no carga comandos desde la ubicación actual de manera predeterminada (consulte "Get-Help about_Command_Precedence"). + +Si confía en este comando, ejecute en su lugar el siguiente comando: + + + Los comandos más similares son: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/TabCompletionStrings.es.resx b/src/System.Management.Automation/resources/es/TabCompletionStrings.es.resx new file mode 100644 index 00000000000..455f25d4f48 --- /dev/null +++ b/src/System.Management.Automation/resources/es/TabCompletionStrings.es.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + El resultado de la finalización con tabulación no se puede deserializar correctamente porque el espacio de ejecución remoto no contiene una instancia de TypeTable. + + + No se puede acceder a las propiedades de una instancia null del tipo CompletionResult. + + + No bit a bit + + + Operador lógico no. Niega la instrucción que le sigue. + + + Igual a: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es igual que el operando derecho. + + + Igual a: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es igual que el operando derecho. + + + Igual a: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es igual que el operando derecho. + + + No es igual a: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no es igual que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no es igual que el operando derecho. + + + No es igual a: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no es igual que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no es igual que el operando derecho. + + + No es igual a: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no es igual que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no es igual que el operando derecho. + + + Mayor que o igual a: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son mayores o iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es mayor o igual que el operando derecho. + + + Mayor que o igual a: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son mayores o iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es mayor o igual que el operando derecho. + + + Mayor o igual que: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son mayores o iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es mayor o igual que el operando derecho. + + + Mayor que: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son mayores que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es mayor que el operando derecho. + + + Mayor que: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son mayores que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es mayor que el operando derecho. + + + Mayor que: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son mayores que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es mayor que el operando derecho. + + + Menor que: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son menores que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es menor que el operando derecho. + + + Menor que: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son menores que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es menor que el operando derecho. + + + Menor que: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son menores que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es menor que el operando derecho. + + + Menor o igual que: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son menores o iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es menor o igual que el operando derecho. + + + Menor o igual que: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son menores o iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es menor o igual que el operando derecho. + + + Menor o igual que: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que son menores o iguales que el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo es menor o igual que el operando derecho. + + + Carácter comodín que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo coincide con el operando derecho. + + + Carácter comodín que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo coincide con el operando derecho. + + + Carácter comodín que coincide con el operador: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo coincide con el operando derecho. + + + Carácter comodín que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no coincide con el operando derecho. + + + Carácter comodín que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no coincide con el operando derecho. + + + Carácter comodín que coincide con el operador: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no coincide con el operando derecho. + + + Expresión regular que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo coincide con el operando derecho. + + + Expresión regular que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo coincide con el operando derecho. + + + Expresión regular que coincide con el operador: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo coincide con el operando derecho. + + + Expresión regular que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no coincide con el operando derecho. + + + Expresión regular que coincide con el operador: no distingue entre mayúsculas y minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no coincide con el operando derecho. + + + Expresión regular que coincide con el operador: distingue mayúsculas de minúsculas. Cuando el operando izquierdo es una colección, devuelve los valores de la colección que no coinciden con el operando derecho; en caso contrario, devuelve TRUE si el operando izquierdo no coincide con el operando derecho. + + + Operador de reemplazo: no distingue entre mayúsculas y minúsculas. Cambia el operando izquierdo. Ejemplo: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operador de reemplazo: no distingue entre mayúsculas y minúsculas. Cambia el operando izquierdo. Ejemplo: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operador de reemplazo: distingue mayúsculas de minúsculas. Cambia el operando izquierdo. Ejemplo: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando derecho) coincide exactamente con al menos uno de los valores del operando izquierdo. + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando derecho) coincide exactamente con al menos uno de los valores del operando izquierdo. + + + Operador de independencia: distingue mayúsculas de minúsculas. Devuelve TRUE solo cuando el valor de prueba (operando derecho) coincide exactamente con al menos uno de los valores del operando izquierdo. + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando derecho) no coincide exactamente con ninguno de los valores del operando izquierdo. + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando derecho) no coincide exactamente con ninguno de los valores del operando izquierdo. + + + Operador de independencia: distingue mayúsculas de minúsculas. Devuelve TRUE cuando el valor de prueba (operando derecho) no coincide exactamente con ninguno de los valores del operando izquierdo. + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando izquierdo) coincide exactamente con al menos uno de los valores del operando derecho. + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando izquierdo) coincide exactamente con al menos uno de los valores del operando derecho. + + + Operador de independencia: distingue mayúsculas de minúsculas. Devuelve TRUE cuando el valor de prueba (operando izquierdo) coincide exactamente con al menos uno de los valores del operando derecho. + + + Operador de independencia: distingue mayúsculas de minúsculas. Devuelve TRUE cuando el valor de prueba (operando izquierdo) no coincide exactamente con ninguno de los valores del operando derecho. + + + Operador de independencia: no distingue entre mayúsculas y minúsculas. Devuelve TRUE cuando el valor de prueba (operando izquierdo) no coincide exactamente con ninguno de los valores del operando derecho. + + + Operador de independencia: distingue mayúsculas de minúsculas. Devuelve TRUE cuando el valor de prueba (operando izquierdo) no coincide exactamente con ninguno de los valores del operando derecho. + + + Dividir: no distingue entre mayúsculas y minúsculas. Divide una o varias cadenas en substrings. +-Dividir <String> + +<String> -Dividir <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Dividir {<ScriptBlock>} [,<Max-substrings>] + + + Dividir: no distingue entre mayúsculas y minúsculas. Divide una o varias cadenas en substrings. +-Dividir <String> + +<String> -Dividir <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Dividir {<ScriptBlock>} [,<Max-substrings>] + + + Dividir: distingue mayúsculas de minúsculas. Divide una o varias cadenas en substrings. +-Dividir <String> + +<String> -Dividir <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Dividir {<ScriptBlock>} [,<Max-substrings>] + + + Devuelve TRUE cuando el operando izquierdo no es una instancia del tipo de .NET Framework especificado (operando derecho). + + + Devuelve TRUE cuando el operando izquierdo es una instancia del tipo de .NET Framework especificado (operando derecho). + + + Convierte el operando izquierdo al tipo .NET Framework especificado (operando derecho). + + + Da formato a las cadenas mediante el método de formato de los objetos de cadena. + + + Operador lógico and. Devuelve TRUE cuando ambas instrucciones son TRUE. + + + Bit a bit Y + + + Operador lógico or. TRUE cuando una o ambas instrucciones son TRUE. + + + Bit a bit O (inclusivo) + + + Operador lógico or exclusivo. Devuelve TRUE cuando una de las instrucciones es TRUE y la otra es FALSE. + + + Bit a bit O (exclusivo) + + + Unir: combina varias cadenas en una sola. +-Unir <String[]> +<String[]> -Unir <Delimiter> + + + Operador de bits de desplazamiento a la izquierda. Inserta un cero en la posición del bit más a la derecha. + + + Operador de bits de desplazamiento a la derecha. Inserta un cero en la posición del bit más a la izquierda. En los valores con signo, se conserva el bit de signo. + + + [string] +Especifica el nombre de la propiedad que se va a crear. + + + [string] +Especifica el nombre de la propiedad que se va a crear. + + + [scriptblock] +Bloque de script que se usa para calcular el valor de la nueva propiedad. + + + [string] +Define cómo se muestran los valores en una columna. +Los valores válidos son "left", "center" o "right". + + + [string] +Especifica una cadena de formato que define cómo se da formato al valor para la salida. + + + [int] +Especifica el ancho máximo de columna en una tabla cuando se muestra el valor. +El valor debe ser mayor que 0. + + + [int] +La clave de profundidad especifica la profundidad de expansión por propiedad. + + + [bool] +Especifica el orden de ordenación de una o más propiedades. + + + [bool] +Especifica el orden de ordenación de una o más propiedades. + + + [String[]] +Especifica los nombres de registro de los que se obtendrán eventos. +Admite caracteres comodín. + + + [String[]] +Especifica los proveedores del registro de eventos de los que se obtendrán eventos. +Admite caracteres comodín. + + + [String[]] +Especifica las rutas de acceso a los archivos de registro de los que se van a obtener eventos. +Los formatos de archivo válidos son: .etl, .evt y .evtx + + + [Long[]] +Selecciona eventos con las máscaras de bits de palabra clave especificadas. +Las siguientes son palabras clave estándar: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Selecciona eventos con los identificadores de evento especificados. + + + [int[]] +Selecciona eventos con los niveles de registro especificados. +Los siguientes niveles de registro son válidos: +1: Crítico +2: Error +3: Advertencia +4: Información +5: Detallado + + + [datetime] +Selecciona eventos creados después de la fecha y hora especificadas. + + + [datetime] +Selecciona eventos creados antes de la fecha y hora especificadas. + + + [string] +Selecciona eventos generados por el usuario especificado. +Puede ser una representación de cadena de un SID o un dominio y nombre de usuario con el formato DOMAIN\USERNAME o USERNAME@DOMAIN + + + [string[]] +Selecciona eventos con cualquiera de los valores especificados en la sección EventData. + + + [hashtable] +Excluye los eventos que coinciden con los valores especificados en la tabla hash. + + + [string] o [hashtable] +Especifica una matriz de módulos de PowerShell que requiere el script. +Cada elemento puede ser una cadena con el nombre del módulo como valor o una tabla hash con las siguientes claves: +Nombre: nombre del módulo +GUID: GUID del módulo +Uno de los siguientes: +ModuleVersion: especifica la versión mínima aceptable del módulo. +RequiredVersion: especifica una versión exacta y obligatoria del módulo. +MaximumVersion: especifica la versión máxima aceptable del módulo. + + + [string] +Especifica una edición de PowerShell que requiere el script. +Los valores válidos son "Core" y "Desktop" + + + [switch] +Especifica que PowerShell debe ejecutarse como administrador en Windows. +Debe ser el último parámetro de la línea de la instrucción #requires. + + + [version] +Especifica la versión mínima de PowerShell que requiere el script. + + + Especifica que el script requiere PowerShell 7+* para ejecutarse. + + + Especifica que el script requiere Windows PowerShell 5.1 para ejecutarse. + + + [string] +Obligatorio. Especifica el nombre del módulo. + + + [string] +Opcional. Especifica el GUID del módulo. + + + [string] +Especifica la versión mínima aceptable del módulo. + + + [string] +Especifica una versión exacta y obligatoria del módulo. + + + [string] +Especifica la versión máxima aceptable del módulo. + + + Una descripción breve de la función o script. +Esta palabra clave solo se puede usar una vez en cada tema. + + + Una descripción detallada de la función o script. +Esta palabra clave solo se puede usar una vez en cada tema. + + + .PARAMETER <Parameter-Name> +La descripción de un parámetro. +Agregue la palabra clave .PARAMETER para cada parámetro en la sintaxis de la función o del script. + + + Comando de ejemplo que usa la función o el script, seguido opcionalmente de una salida de ejemplo y una descripción. +Repita esta palabra clave para cada ejemplo. + + + Los tipos .NET de los objetos que se pueden canalizar a la función o script. +También puede incluir una descripción de los objetos de entrada. + + + Tipo de .NET de los objetos que devuelve el cmdlet. +También puede incluir una descripción de los objetos devueltos. + + + Información adicional sobre la función o script. + + + Nombre de un tema relacionado. +Repita la palabra clave .LINK para cada tema relacionado. +El contenido de la palabra clave .Link también puede incluir un URI en una versión en línea del mismo tema de ayuda. + + + Nombre de la tecnología o característica que usa la función o el script, o con la que está relacionada. + + + El nombre del rol de usuario para el tema de ayuda. + + + Las palabras clave que describen el uso previsto de la función. + + + .FORWARDHELPTARGETNAME <Command-Name> +Redirige al tema de ayuda del comando especificado. + + + .FORWARDHELPCATEGORY <Category> +Especifica la categoría de ayuda del elemento en .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Especifica una sesión que contiene el tema de ayuda. +Escriba una variable que contenga un objeto PSSession. + + + .EXTERNALHELP <XML Help File> +La palabra clave .ExternalHelp es necesaria cuando una función o un script se documenta en archivos XML. + + + Especifica la ruta de acceso a un ensamblado .NET que se va a cargar. + +usando el ensamblado <.NET-assembly-path> + + + Especifica un módulo de PowerShell desde el que cargar clases. + +usando módulo <ModuleName o Path> + +usando módulo <tabla hash ModuleSpecification> + + + Especifica un espacio de nombres .NET desde el que resolver tipos o un alias de espacio de nombres. + +usando el espacio de nombres <.NET-namespace> + +usando el espacio de nombres <AliasName> = <.NET-namespace> + + + Especifica un alias para un tipo de .NET. + +usando el tipo <AliasName> = <.NET-type> + + + Una cadena normal. + + + Una cadena que contiene referencias no expandidas a variables de entorno que se expanden cuando se recupera el valor. + + + Datos binarios en cualquier formulario. + + + Un número binario de 32 bits. + + + Una matriz de cadenas. + + + Un número binario de 64 bits. + + + Un tipo de datos del Registro no admitido. + + + ",": coma + + + ", ": coma y espacio + + + ";": punto y coma + + + "; ": punto y coma y espacio + + + {0} - Newline + + + "-": guion + + + " ": espacio + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/TransactionStrings.es.resx b/src/System.Management.Automation/resources/es/TransactionStrings.es.resx new file mode 100644 index 00000000000..ce910313c2b --- /dev/null +++ b/src/System.Management.Automation/resources/es/TransactionStrings.es.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No se puede usar la transacción. No hay ninguna transacción activa. + + + No se puede confirmar la transacción. No hay ninguna transacción activa. + + + No se puede revertir la transacción porque no hay ninguna transacción activa. + + + No se puede revertir la transacción. La transacción ya se ha confirmado. + + + No se puede confirmar la transacción. La transacción ya se ha confirmado. + + + No se puede confirmar la transacción. La transacción se ha revertido o se ha agotado el tiempo de espera. + + + No se puede revertir la transacción. La transacción ya se ha revertido o se ha agotado el tiempo de espera. + + + No se puede establecer la transacción activa. No se ha creado ninguna transacción. + + + No se puede establecer la transacción activa. La transacción activa se ha revertido o se ha agotado el tiempo de espera. + + + Este cmdlet requiere una transacción activa. La transacción actual ya se ha confirmado o revertido. + + + Este cmdlet requiere una transacción. Vuelva a ejecutar el comando con el parámetro -UseTransaction. + + + No se puede usar la transacción. No se ha iniciado ninguna transacción. + + + No se puede usar la transacción. La transacción se ha confirmado. + + + No se puede usar la transacción. La transacción se ha revertido o se ha agotado el tiempo de espera. + + + No se puede usar la transacción. Se agotó el tiempo de espera de la transacción. + + + No se ha establecido la transacción base. + + + La transacción base no está activa. + + + No se puede establecer la transacción base después de crear otras transacciones. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/TypesXmlStrings.es.resx b/src/System.Management.Automation/resources/es/TypesXmlStrings.es.resx new file mode 100644 index 00000000000..e65b590474f --- /dev/null +++ b/src/System.Management.Automation/resources/es/TypesXmlStrings.es.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : Error: {3} + + + {0}, {1}({2}): error en el tipo "{3}": {4} + + + El nodo "{0}" debe aparecer solo una vez en "{1}". Se ignorará el nodo primario "{1}". + + + No se permite el nodo {0}. Están permitidos los siguientes nodos: {1}. + + + El nodo "{0}" no debe tener texto interno. + + + El nodo "{0}" debe tener texto interno. + + + No se encontró el nodo "{0}". Debe producirse solo una vez en "{1}". Se ignorará el nodo primario "{1}". + + + El nodo "Type" debe tener "Members", "TypeConverters" o "TypeAdapters". + + + No se puede crear una instancia del convertidor de tipos para el tipo {0} debido a la excepción: {1}. + + + PowerShell no puede crear una instancia del adaptador de tipos para el tipo {0} debido a la siguiente excepción: {1}. + + + El tipo adaptado "{0}" no es válido. + + + Se ignoró TypeConverter porque ya se produce. + + + Se ignoró TypeAdapter porque ya se produce. + + + El tipo "{0}" debe ser TypeConverter o PSTypeConverter. + + + El tipo "{0}" debe ser un PSPropertyAdapter. + + + El miembro {0} ya está presente. + + + El siguiente nombre de miembro está reservado: {0} + + + Excepción: {0} + + + ScriptProperty debe tener un captador o un establecedor. + + + CodeProperty debe tener un captador o un establecedor. + + + {0}, {1} : {2} + + + El valor debe ser TRUE o FALSE en lugar de {0}. + + + El nodo "{0}" no debe tener el atributo "{1}". + + + {0}, {1}: no se encontró el archivo. + + + {0}, {1}: se omitió el archivo porque {2} ya lo había cargado. + + + No se encuentra la clave del Registro: {0}{1}. Usando {2} para cargar los archivos de configuración. + + + No se encuentra la ruta de acceso {0} especificada en la clave del Registro: {1}{2}. Usando {3} para cargar los archivos de configuración. + + + {0}, {1}: se omitió el archivo porque no tiene la extensión de nombre de archivo ps1xml. + + + {0}, {1}: se omitió el archivo debido a la siguiente excepción de validación: {2}. + + + El miembro "{0}" debe ser una nota. + + + No se puede convertir la nota "{0}": "{1}". + + + No use el miembro "{0}" aquí. + + + El miembro "{0}" debe tener el tipo "{1}". + + + "{0}" debe estar presente cuando "{1}" sea "{2}" y "{3}" sea "{4}". + + + Un error anterior provocó que se ignoraran todos los valores de configuración de serialización. + + + "{0}" no es un miembro estándar y se ignorará. + + + La ruta {0} no está completa. Especifique una ruta de acceso de archivo de tipo completo. + + + No se puede actualizar TypeTable porque es posible que se haya creado fuera del espacio de ejecución. + + + Se produjeron errores al cargar TypeTable. Consulte la propiedad Errores para obtener mensajes de error detallados. + + + Error en TypeData "{0}": {1} + + + "{0}" debe tener un valor para su propiedad "{1}". + + + "{0}" no debe tener un valor null ni una cadena vacía en la propiedad "{1}". + + + No se encontró el tipo "{0}". El valor del nombre de tipo debe ser el nombre completo del tipo. Compruebe el nombre de tipo y vuelva a ejecutar el comando. + + + TypeData debe tener "Members", "TypeConverters", "TypeAdapters" o "StandardMembers". + + + Una tabla de tipos compartida no se puede actualizar con más de una entrada. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/VerbDescriptionStrings.es.resx b/src/System.Management.Automation/resources/es/VerbDescriptionStrings.es.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/es/VerbDescriptionStrings.es.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/es/WildcardPatternStrings.es.resx b/src/System.Management.Automation/resources/es/WildcardPatternStrings.es.resx new file mode 100644 index 00000000000..179e5428fc4 --- /dev/null +++ b/src/System.Management.Automation/resources/es/WildcardPatternStrings.es.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 + + + El patrón de caracteres comodín especificado no es válido: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/Authenticode.fr.resx b/src/System.Management.Automation/resources/fr/Authenticode.fr.resx new file mode 100644 index 00000000000..09d18c1d324 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/Authenticode.fr.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 + + + Nous ne pouvons pas charger le fichier {0}, car vous avez choisi de ne pas exécuter ce logiciel maintenant. + + + Le fichier {0} ne peut pas être chargé, car vous avez choisi de ne jamais exécuter de logiciel de cet éditeur. + + + Le fichier {0} est publié par {1}. Cet éditeur n’est pas explicitement approuvé sur votre système. Le script ne s’exécutera pas sur le système. Pour découvrir plus d’informations, exécutez la commande « get-help about_signing ». + + + Nous ne pouvons pas charger le fichier {0}, car l’exécution de scripts est désactivée sur ce système. Pour découvrir plus d’informations, consultez about_Execution_Policies à l’adresse https://go.microsoft.com/fwlink/?LinkID=135170. + + + Nous ne pouvons pas charger le fichier {0}. {1}. + + + Nous ne pouvons pas charger le fichier {0} car son exécution est bloquée par des stratégies de restriction logicielle, telles que celles créées en tirant parti de la stratégie de groupe. + + + Nous ne pouvons pas charger le fichier {0} car son contenu n’a pas pu être lu. + + + Nous ne pouvons pas signer le code. Le certificat spécifié ne convient pas pour la signature de code. + + + Nous ne pouvons pas signer le code. L’URL du serveur TimeStamp doit être entièrement qualifiée et au format http://<server url> ou https://<server url>. + + + Nous ne pouvons pas signer le code. L'algorithme de hachage n'est pas pris en charge. + + + Voulez-vous exécuter le logiciel provenant de cet éditeur non approuvé ? + + + Le fichier {0} est publié par {1} et n’est pas approuvé sur votre système. N’exécutez que des scripts provenant d’éditeurs approuvés. + + + Le logiciel {0} est publié par un éditeur inconnu. Nous vous recommandons de ne pas exécuter ce logiciel. + + + Avertissement de sécurité + + + Référencez uniquement les scripts auxquels vous faites confiance. Les scripts provenant d’Internet peuvent être utiles, mais ce script peut éventuellement endommager votre ordinateur. Si vous faites confiance à ce script, utilisez la cmdlet Unblock-File pour autoriser son exécution sans ce message d’avertissement. Voulez-vous exécuter {0} ? + + + Ja&mais exécuté + + + Ne pas exécuter le script de cet éditeur dès maintenant et ne pas m’inviter à l’exécuter à l’avenir. Les futures tentatives d’exécution de ce script entraîneront un échec silencieux. + + + &Ne pas exécuter + + + Ne pas exécuter pas le script de cet éditeur dès maintenant et continuer à m’inviter à l’exécuter à l’avenir. + + + &Exécuter une fois + + + Exécuter le script de cet éditeur dès maintenant et continuer à m’inviter à l’exécuter à l’avenir. + + + &Toujours exécuter + + + Exécutez le script de cet éditeur maintenant et continuer à m’inviter à l’exécuter à l’avenir. + + + &Suspendre + + + Suspendez le pipeline actuel et revenez à l’invite de commandes. Tapez exit pour reprendre l’opération lorsque vous avez terminé. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/AuthorizationManagerBase.fr.resx b/src/System.Management.Automation/resources/fr/AuthorizationManagerBase.fr.resx new file mode 100644 index 00000000000..c32d25c6a32 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/AuthorizationManagerBase.fr.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 + + + Échec de la vérification d’AuthorizationManager. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/AutomationExceptions.fr.resx b/src/System.Management.Automation/resources/fr/AutomationExceptions.fr.resx new file mode 100644 index 00000000000..18d6f475628 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/AutomationExceptions.fr.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 argument because the value of argument "{0}" is not valid. Change the value of the "{0}" argument and run the operation again. + + + Cannot process argument because the value of parameter "{0}" is not valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). Change the value of the "{0}" parameter and run the operation again. + + + Cannot process argument because the value of argument "{0}" is null. Change the value of argument "{0}" to a non-null value. + + + Cannot process argument because the value of argument "{0}" is out of range. Change argument "{0}" to a value that is within range. + + + Cannot perform operation because operation "{0}" is not valid. Remove operation "{0}", or investigate why it is not valid. + + + Cannot perform operation because operation "{0}" is not implemented. + + + Cannot perform operation because operation "{0}" is not supported. + + + Cannot perform operation because object "{0}" has already been disposed. + + + The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause. + + + The script block cannot be converted because it contains more than one clause. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + An empty script block cannot be converted. Verify that the script block contains exactly one pipeline or command. + + + Only a script block that contains exactly one pipeline or command can be converted. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + A script block that contains a top-level trap statement cannot be converted. + + + Cannot generate a PowerShell object for a ScriptBlock dereferencing variables undeclared in the param(...) block. Name of undeclared variable: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating non-constant expressions. Non-constant expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions. Dynamic expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock that tries to pass other script blocks inside argument values. + + + Cannot generate a PowerShell object for a ScriptBlock which invokes pipelines, commands or functions to evaluate arguments of the main pipeline. + + + Cannot generate a PowerShell object for a ScriptBlock that uses dot sourcing. + + + Cannot generate a PowerShell object for a ScriptBlock that invokes other script blocks. + + + The script block cannot be converted to a PowerShell object because it contains forbidden redirection operators. + + + Cannot generate a PowerShell object for a ScriptBlock that does not have an associated operation context. + + + The command was stopped by the user. + + + Object "{0}" is the wrong type to return from the dynamicparam block. The dynamicparam block must return either $null, or an object with type [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + The script block cannot be converted to an open generic type. Define an appropriate closed generic type, and then retry. + + + Cannot generate a PowerShell object for a ScriptBlock that starts a pipeline with an expression. + + + The value of the using variable '$using:{0}' cannot be retrieved because it has not been set in the local session. + + + Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CatalogStrings.fr.resx b/src/System.Management.Automation/resources/fr/CatalogStrings.fr.resx new file mode 100644 index 00000000000..c357630e20b --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CatalogStrings.fr.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nous ne pouvons pas générer le fichier de définition de catalogue. + + + Ajout du fichier {0} au catalogue. Le chemin relatif du fichier dans le catalogue est {1}. + + + La validation du fichier {0} depuis le catalogue est ignorée. + + + Fichier {0} trouvé dans le catalogue avec le hachage de {1}. + + + Les chemins du catalogue contiennent plusieurs fichiers avec le même chemin relatif {0}. + + + Fichier {0} trouvé sur le disque avec le hachage de {1}. + + + La validation du fichier {0} depuis le chemin est ignorée. + + + Nous ne pouvons pas acquérir un handle vers un contexte d’administration du catalogue pour un algorithme de hachage donné {0}. + + + Nous ne pouvons pas créer le hachage du fichier {0}. + + + Nous ne pouvons pas ouvrir le fichier de catalogue {0}. + + + La version de catalogue n’est pas valide. Nous prenons uniquement en charge la version {0} et la version {1} du catalogue. + + + Nous ne pouvons pas ouvrir le fichier de définition de catalogue. + + + Plusieurs entrées du membre de fichier {0} ont été trouvées dans le catalogue. + + + Nous ne pouvons pas trouver le nom ou le chemin du fichier pour le membre du catalogue {0}. + + + Nous ne pouvons pas trouver le hash de {0}. + + + Nous ne pouvons pas lire le fichier {0} pour calculer son hachage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CimInstanceTypeAdapterResources.fr.resx b/src/System.Management.Automation/resources/fr/CimInstanceTypeAdapterResources.fr.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CimInstanceTypeAdapterResources.fr.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CmdletizationCoreResources.fr.resx b/src/System.Management.Automation/resources/fr/CmdletizationCoreResources.fr.resx new file mode 100644 index 00000000000..04d51f592df --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CmdletizationCoreResources.fr.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlets de la classe « {0} » + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Nous ne pouvons pas traiter le fichier XML de définition de l’applet de commande suivant : {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Nous ne pouvons pas traiter l’attribut ObjectModelWrapper. Le type {0} définit plusieurs jeux de paramètres. Vérifiez que le fichier XML de définition de l’applet de commande spécifie un type valide dans l’attribut ObjectModelWrapper, puis réessayez. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Nous ne pouvons pas traiter l’attribut ObjectModelWrapper. Le type {0} est un type générique ouvert. Vérifiez que le fichier XML de définition de l’applet de commande spécifie un type valide dans l’attribut ObjectModelWrapper, puis réessayez. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Nous ne pouvons pas traiter l’attribut ObjectModelWrapper. Le type {0} n’est pas dérivé de la classe suivante : {1}. Vérifiez que le fichier XML de définition de l’applet de commande spécifie un type valide dans l’attribut ObjectModelWrapper, puis réessayez. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Nous ne pouvons pas traiter l’attribut ObjectModelWrapper. Le type {0} définit le paramètre d’applet de commande {1} avec un paramètre d’attribut {2} ignoré. Vérifiez que le fichier XML de définition de l’applet de commande spécifie un type valide dans l’attribut ObjectModelWrapper, puis réessayez. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Nous ne pouvons pas définir le paramètre {0} pour l’applet de commande {1}. Le nom du paramètre est déjà défini par la classe {2}. Modifiez le nom du paramètre dans le fichier XML de définition de l’applet de commande, puis réessayez. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Nous ne pouvons pas définir le paramètre {0} pour l’applet de commande {1}. Le nom du paramètre est déjà défini dans l’élément XML {2}. Modifiez le nom du paramètre dans le fichier XML de définition de l’applet de commande, puis réessayez. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + La valeur de l’attribut EnumName ne se convertit pas en identificateur C# valide : {0}. Vérifiez l’attribut EnumName dans le fichier XML de définition de l’applet de commande, puis réessayez. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Nous ne pouvons pas traiter l’élément <Enum EnumName="{0}" ...>. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + L’ordinateur distant a renvoyé un fichier CDXML non valide. L’adaptateur d’applet de commande suivant n’est pas pris en charge pour l’importation d’un module CDXML depuis un ordinateur distant : {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CommandBaseStrings.fr.resx b/src/System.Management.Automation/resources/fr/CommandBaseStrings.fr.resx new file mode 100644 index 00000000000..cd7b81a21dd --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CommandBaseStrings.fr.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Voulez-vous continuer cette opération ? + + + &Oui + + + Continuez en n’exécutant que l’étape suivante de l’opération. + + + Oui pour &tout + + + Continuez avec toutes les étapes de l’opération. + + + &Non + + + Ignorez cette opération et passez à l’opération suivante. + + + Non pou&r tout + + + Ignorez cette opération et toutes les opérations suivantes. + + + Arrêter cette commande. + + + &Interrompre la commande + + + &Suspendre + + + Suspendez le pipeline actuel et revenez à l’invite de commandes. Tapez « {0} » pour reprendre le pipeline. + + + + Le programme « {0} » s’est terminé avec un code de sortie différent de zéro : {1} ({2}). + + + Exécution de l’opération « {0} » sur la cible « {1} ». + + + What If : {0} + + + Voulez-vous vraiment effectuer cette action ? +{0} + + + Confirmer + + + La commande en cours d’exécution s’est arrêtée, car la variable de préférence « {0} » ou le paramètre commun est défini sur Stop : {1} + + + La commande en cours d’exécution s’est arrêtée, car la variable de préférence « {0} » ou le paramètre commun est défini sur Stop. + + + La commande en cours d’exécution s’est arrêtée, car la variable de préférence « {0} » ou le paramètre commun est défini sur la valeur suivante qui est non valide : « {1} ». + + + La commande en cours d’exécution s’est arrêtée, car l’utilisateur(-trice) a sélectionné l’option Stop. + + + La commande en cours d’exécution s’est arrêtée, car l’utilisateur(-trice) l’a interrompue. + + + Les applets de commande dérivées de PSCmdlet ne peuvent pas être appelées directement. + + + L’applet de commande « {0} » ne prend pas en charge le paramètre « {1} » dans une session à distance. + + + Nombre total : {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Coût total estimé : {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Nombre total inconnu + Reviewed by TArcher on 2010-07-20 + + + commande « {0} » + + + Le {0} est obsolète. {1} + + + Échec de l’appel Exec avec le code d’erreur {0} pour la ligne de commande : {1} + + + La commande « {0} » était introuvable. La commande spécifiée doit être un exécutable. + + + Vérification du dot-sourcing des blocs de script + + + Le traitement Dot-Source du bloc de script « {0} » échouera en mode de langage contraint, car son mode de langage « {1} » ne correspond pas au mode de langage actuel « {2} ». + + + Outil de recherche de commandes + + + La commande « {0} » du module « {1} » n’est pas approuvée et ne sera pas accessible en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ConsoleInfoErrorStrings.fr.resx b/src/System.Management.Automation/resources/fr/ConsoleInfoErrorStrings.fr.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ConsoleInfoErrorStrings.fr.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CoreClrStubResources.fr.resx b/src/System.Management.Automation/resources/fr/CoreClrStubResources.fr.resx new file mode 100644 index 00000000000..6ff6ba06271 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CoreClrStubResources.fr.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Le nom de la variable d'environnement ne doit pas contenir de caractères égaux. + + + Le nom ou la valeur de la variable d’environnement est trop long. + + + Le premier caractère de la chaîne est le caractère nul. + + + La chaîne ne peut pas être de longueur nulle. + + + Nous n’avons pas pu obtenir le nom de l’ordinateur. + + + Nous n’avons pas pu obtenir le nom de domaine de l’utilisateur(-trice) actuel(le). + + + Erreur inconnue : « {0} ». + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CredUI.fr.resx b/src/System.Management.Automation/resources/fr/CredUI.fr.resx new file mode 100644 index 00000000000..8e2325d7512 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CredUI.fr.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Requête d’informations d’identification PowerShell + + + Entrez vos informations d’identification. + + + Entrez vos informations d’identification. + + + La longueur maximale de légende est de {0} caractères. + + + La longueur maximale du message est de {0} caractères. + + + La longueur maximale de la valeur UserName est de {0} caractères. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/Credential.fr.resx b/src/System.Management.Automation/resources/fr/Credential.fr.resx new file mode 100644 index 00000000000..c07850c1673 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/Credential.fr.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 + + + Nous ne pouvons pas sérialiser les informations d’identification. Si cette commande démarre un flux de travail, les informations d’identification ne peuvent pas être conservées, car le processus dans lequel le flux de travail est démarré n’a pas l’autorisation de sérialiser les informations d’identification. + +-- Si le flux de travail a été démarré dans une PSSession sur l’ordinateur local, ajoutez le paramètre EnableNetworkAccess à la commande qui a créé la session. +-- Si le flux de travail a été démarré dans une PSSession vers un ordinateur distant, ajoutez le paramètre Authentication avec la valeur CredSSP à la commande qui a créé la session. Ou connectez-vous à une configuration de session dont la valeur de la propriété RunAsUser est définie. + + + La valeur du nom d’utilisateur n’est pas au bon format. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/CredentialAttributeStrings.fr.resx b/src/System.Management.Automation/resources/fr/CredentialAttributeStrings.fr.resx new file mode 100644 index 00000000000..f05393d9118 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/CredentialAttributeStrings.fr.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 + + + Requête d’informations d’identification PowerShell + + + Entrez vos informations d’identification. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/DebuggerStrings.fr.resx b/src/System.Management.Automation/resources/fr/DebuggerStrings.fr.resx new file mode 100644 index 00000000000..aefe86fb0cf --- /dev/null +++ b/src/System.Management.Automation/resources/fr/DebuggerStrings.fr.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Point d’arrêt de variable sur « ${0} » ({1} accès) + + + Point d’arrêt de variable sur « {0} :${1} » (accès {2}) + + + Point d’arrêt de ligne sur « {0} :{1} » + + + Point d’arrêt de ligne sur « {0} :{1}, {2} » + + + Point d’arrêt de commande sur « {0} » + + + Point d’arrêt de commande sur « {0} :{1} » + + + Le point d’arrêt {0} ne sera pas atteint + + + {0}, {1,-16} Étape unique (pas à pas dans les fonctions, scripts, etc.) + + + {0}, {1,-16} Passer à l’instruction suivante (pas à pas principal dans les fonctions, les scripts, etc.) + + + {0}, {1,-16} Quittez la fonction, le script, etc. + + + {0}, {1,-16} Continuer l’opération + + + {0}, {1,-16} Arrêter l’opération et quitter le débogueur + + + {0}, Get-PSCallStack Afficher la pile des appels + + + {0}, {1,-16} Répertoriez le code source du script actif. + + + Utiliser « list » pour commencer à partir de la ligne active, « list <m> » + + + pour commencer à partir de la ligne <m>, et « list <m> <n> » pour répertorier <n> + + + lignes à partir de la ligne <m> + + + <enter> Répéter la dernière commande si elle était {0}, {1} ou {2} + + + {0}, {1,-16} affiche ce message d’aide. + + + Pour obtenir des instructions sur la personnalisation de l’invite de votre débogueur, tapez « help about_prompt ». + + + +La session active ne prend pas en charge le débogage, l’opération se poursuivra. + + + + + {0} : ligne {1} + + + Aucun code source n’est disponible. + + + La ligne de départ doit être un entier positif inférieur ou égal à {0} + + + Le nombre de lignes doit être un entier positif. + + + <No file> + + + sur {0}, {1} : ligne {2} + + + Le débogueur ne peut pas traiter les commandes tant qu’il n’est pas à l’état Arrêté. + + + SetDebugAction n’est pas implémenté pour le débogueur de script local. + + + Le débogueur ne peut pas définir d’action de reprise, car le débogueur de la session distante n’est pas à l’état Arrêté. + + + Nous ne pouvons pas déboguer le travail, car le débogueur est actuellement occupé. + + + Le travail fourni et tous les travaux enfants ont été passés en revue, mais aucun travail pouvant être débogué n’a été trouvé. Pour déboguer un travail ou un travail enfant, celui-ci doit prendre en charge le débogage et être à l’état en cours d’exécution. + + + Le débogueur ne peut pas être activé pour le mode pas à pas, car il est désactivé avec le mode de débogage défini sur Aucun. + + + Nous ne pouvons pas déboguer l’instance d’exécution, car le débogueur hôte est actuellement occupé. + + + Nous ne pouvons pas déboguer l’instance d’exécution. Le débogueur d’instance d’exécution est actuellement désactivé (DebugMode a la valeur « Aucun »). + + + Nous ne pouvons pas déboguer une instance d’exécution qui n’est pas à l’état Ouvert. L’état de cette instance d’exécution est {0}. + + + Nous ne pouvons pas déboguer l’instance d’exécution. L’instance d’exécution {0} n’a aucun débogueur associé. + + + Le débogueur est déjà remplacé. + + + Nous ne pouvons pas envoyer un objet de débogueur sur lui-même. + + + La commande {0} n’est pas prise en charge pour une utilisation à distance dans la version de PowerShell qui s’exécute dans l’instance d’exécution distante. + + + Processus + + + {0}, {1,-16} Poursuivez l’opération et détachez le débogueur. + + + La commande de détachement du débogueur n’est pas applicable. La commande de détachement s’applique uniquement lors du débogage de travaux et d’instances d’exécution avec les cmdlets Debug-Job ou Debug-Runspace. + + + ID d’instance d’exécution non valide : {0} + + + Nous ne pouvons pas obtenir l’instance d’exécution. + + + Un point d’arrêt ou une BreakpointList doit être spécifiée. + + + La BreakpointList contenait un élément qui n’était pas un point d’arrêt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/DescriptionsStrings.fr.resx b/src/System.Management.Automation/resources/fr/DescriptionsStrings.fr.resx new file mode 100644 index 00000000000..ebb90920ac6 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/DescriptionsStrings.fr.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 + + + {0} ne peut pas être nul ou vide. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/DiscoveryExceptions.fr.resx b/src/System.Management.Automation/resources/fr/DiscoveryExceptions.fr.resx new file mode 100644 index 00000000000..0dafcb78fe9 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/DiscoveryExceptions.fr.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 + + + Le nom de l’applet de commande « {0} » ne peut pas être validé, car son format est incorrect. Les noms d’applets de commande doivent inclure un verbe et un nom séparés par un « – », par exemple « Get-Process ». + + + Le paramètre « {0} » est déclaré plusieurs fois dans le jeu de paramètres « {1} ». + + + Les alias « {0} » sont déclarés plusieurs fois. + + + Nous n’avons pas pu déclarer le paramètre. Les paramètres ne peuvent être déclarés que sur des champs et des propriétés. + + + Nous ne pouvons pas traiter le cmdlet. Un nom de cmdlet doit être constitué d’un verbe et d’un nom séparés par « – ». + + + Le terme « {0} » n’est pas reconnu comme nom d’applet de commande, d’une fonction, d’un fichier de script ou d’un programme exécutable. +Vérifiez l’orthographe du nom ou, si un chemin d’accès a été inclus, vérifiez que le chemin d’accès est correct et réessayez. + + + L’argument « {0} » n’est pas reconnu comme une applet de commande : {1} + + + L’argument « {0} » n’est pas reconnu comme une applet de commande, peut-être parce qu’il ne dérive pas des classes Cmdlet ou PSCmdlet : {1} + + + Impossible de résoudre l’alias « {0} », car il fait référence au terme « {1} », qui n’est pas reconnu comme une applet de commande, une fonction, un programme exécutable ou un fichier de script. Vérifiez le terme, puis réessayez. + + + Le paramètre « {0} » avec la valeur « {1} » ne peut pas être traité, car il ne s’agit pas d’une applet de commande et ne peut pas être traité par le CommandProcessor. + + + Une applet de commande nommée « {0} » existe déjà. Les Cmdlets ne doivent pas porter le même nom. + + + Un fournisseur d’applets de commande nommé « {0} » existe déjà. Les fournisseurs d’applets de commande doivent avoir des noms uniques. + + + Un assembly nommé « {0} » existe déjà. Les assemblys doivent avoir des noms uniques. + + + Un script nommé « {0} » existe déjà. Les scripts ne doivent pas porter le même nom. + + + Nous ne pouvons pas traiter l’instruction #requires car son format est incorrect. +L’instruction #requires doit être dans l’un des formats suivants : + « #requires -shellid <shellID> » + « #requires -version <major.minor> » + « #requires -psedition <edition> » + « #requires -pssnapin <psSnapInName> [-version <major.minor>] » + « #requires -modules <ModuleSpecification> » + « #requires -runasadministrator » + + + Le script « {0} » ne peut pas être exécuté car il contient une instruction « #requires » avec un ID d’interpréteur de commandes de {1} incompatible avec l’interpréteur de commandes actuel. Pour exécuter ce script, vous devez utiliser l’interpréteur de commandes situé dans « {2} ». + + + Le script « {0} » ne peut pas être exécuté car il contient une instruction « #requires » avec un ID d’interpréteur de commandes de {1} incompatible avec l’interpréteur de commandes actuel. + + + Le script « {0} » ne peut pas être exécuté, car il contient une instruction « #requires » pour PowerShell {1}. La version de PowerShell requise par le script ne correspond pas à la version en cours d’exécution de PowerShell {2}. + + + Le script « {0} » ne peut pas être exécuté, car il contient une instruction « #requires » pour les éditions PowerShell « {1} ». L’édition de PowerShell requise par le script ne correspond pas à l’édition de PowerShell {2} en cours d’exécution. + + + Nous ne pouvons pas exécuter le script « {0} », car les composants logiciels enfichables suivants spécifiés par les instructions « #requires » du script sont manquants : {1}. + + + Une instruction #requires a spécifié uniquement un shellID. Les instructions #Requires doivent spécifier un composant logiciel enfichable PowerShell requis lors de l’exécution dans PowerShell. + + + Le script « {0} » ne peut pas être exécuté car il contient une instruction « #requires » pour une exécution en tant qu’administrateur(-trice). La session PowerShell actuelle n’est pas exécutée en tant qu’administrateur(-trice). Démarrez PowerShell en utilisant l’option Exécuter en tant qu’administrateur(-trice), puis essayez de relancer le script. + + + {0} (Version {1}) + + + Nous n’avons pas pu récupérer la commande, car le paramètre ArgumentList ne peut être spécifié que lors de la récupération d’une seule applet de commande ou d’un seul script. + + + Le nom du paramètre « {0} » est réservé à un usage futur. + + + Nous ne pouvons pas exécuter le script « {0} », car les modules suivants spécifiés par les instructions « #requires » du script sont manquants : {1}. + + + La commande « {0} » a été trouvée dans le module « {1} », mais le module n’a pas pu être chargé. Pour plus d’informations, exécutez « Import-Module {1} ». + + + La commande « {0} » a été trouvée dans le module « {1} », mais le module n’a pas pu être chargé à cause de l’erreur suivante : [{2}] +Pour plus d’informations, exécutez « Import-Module {1} ». + + + Nous ne pouvons pas charger le module « {0} ». Pour plus d’informations, exécutez « Import-Module {0} ». + + + Aucune commande correspondante n’inclut un paramètre nommé « {0} ». Vérifiez l’orthographe du nom du paramètre, puis réessayez. + + + Nous ne pouvons pas effectuer un dot-source sur cette commande, car elle a été définie dans un autre mode de langage. Pour appeler cette commande sans importer son contenu, omettez l’opérateur '.'. + + + Les paramètres ShowCommandInfo et Syntax ne peuvent pas être spécifiés ensemble. + + + Cette commande de script est désactivée lorsque la fonctionnalité expérimentale « {0} » est activée. + + + Cette commande de script est désactivée lorsque la fonctionnalité expérimentale « {0} » est désactivée. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/EnumExpressionEvaluatorStrings.fr.resx b/src/System.Management.Automation/resources/fr/EnumExpressionEvaluatorStrings.fr.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/fr/EnumExpressionEvaluatorStrings.fr.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ErrorCategoryStrings.fr.resx b/src/System.Management.Automation/resources/fr/ErrorCategoryStrings.fr.resx new file mode 100644 index 00000000000..fc385f57635 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ErrorCategoryStrings.fr.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 + + + CloseError : ({1} :{2}) [{0}], {3} + + + Blocage détecté : ({1} :{2}) [{0}], {3} + + + DeviceError : ({1} :{2}) [{0}], {3} + + + InvalidArgument : ({1} :{2}) [{0}], {3} + + + InvalidData : ({1} :{2}) [{0}], {3} + + + InvalidOperation : ({1} :{2}) [{0}], {3} + + + InvalidResult : ({1} :{2}) [{0}], {3} + + + InvalidType : ({1} :{2}) [{0}], {3} + + + MetadataError : ({1} :{2}) [{0}], {3} + + + NotImplemented : ({1} :{2}) [{0}], {3} + + + NotInstalled : ({1} :{2}) [{0}], {3} + + + ObjectNotFound : ({1} :{2}) [{0}], {3} + + + OpenError : ({1} :{2}) [{0}], {3} + + + OperationStopped : ({1} :{2}) [{0}], {3} + + + OperationTimeout : ({1} :{2}) [{0}], {3} + + + ParserError : ({1} :{2}) [{0}], {3} + + + PermissionDenied : ({1} :{2}) [{0}], {3} + + + ReadError : ({1} :{2}) [{0}], {3} + + + ResourceBusy : ({1} :{2}) [{0}], {3} + + + ResourceExists : ({1} :{2}) [{0}], {3} + + + ResourceUnavailable : ({1} :{2}) [{0}], {3} + + + SyntaxError : ({1} :{2}) [{0}], {3} + + + WriteError : ({1} :{2}) [{0}], {3} + + + FromStdErr : ({1} :{2}) [{0}], {3} + + + SecurityError : ({1} :{2}) [{0}], {3} + + + ProtocolError : ({1} :{2}) [{0}], {3} + + + ConnectionError : ({1} :{2}) [{0}], {3} + + + AuthenticationError : ({1} :{2}) [{0}], {3} + + + LimitsExceeded : ({1} :{2}) [{0}], {3} + + + QuotaExceeded : ({1} :{2}) [{0}], {3} + + + NotEnabled : ({1} :{2}) [{0}], {3} + + + NotSpecified : ({1} :{2}) [{0}], {3} + + + Code d’erreur non reconnu : {4} : ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ErrorPackage.fr.resx b/src/System.Management.Automation/resources/fr/ErrorPackage.fr.resx new file mode 100644 index 00000000000..b68a8cc12bd --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ErrorPackage.fr.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 + + + {0}…{1} + + + Le texte d’erreur est vide pour l’erreur « {0} » : « {1} » + + + L’objet « {0} » est signalé comme une erreur. + + + La valeur {0} n’est pas prise en charge pour une variable ActionPreference. La valeur fournie doit être utilisée uniquement comme valeur pour un paramètre de préférence et a été remplacée par la valeur par défaut. Pour plus d’informations, consultez la rubrique d’aide « about_Preference_Variables ». + + + La valeur {0} ActionPreference est réservée à un usage futur et n’est pas prise en charge pour le moment. Pour plus d’informations sur les variables de préférence, consultez la rubrique d’Aide « about_Preference_Variables. » + + + La valeur {0} ActionPreference est réservée à un usage futur et n’est pas prise en charge pour le moment. Elle a été remplacée dans votre {1} variable par la valeur par défaut de {2}. Pour plus d’informations sur les variables de préférence, consultez la rubrique d’Aide « about_Preference_Variables. » + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/EtwLoggingStrings.fr.resx b/src/System.Management.Automation/resources/fr/EtwLoggingStrings.fr.resx new file mode 100644 index 00000000000..a9246b02358 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/EtwLoggingStrings.fr.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La commande {0} est {1}. + + + L’état du moteur est passé de {0} à {1}. + + + ID d’erreur complet = {0} + + + Message d’erreur = {0} + + + Action recommandée = {0} + + + Stratégie d’exécution + + + Commande de travail = {0} + + + ID de travail = {0} + + + ID d’instance de travail = {0} + + + Emplacement du travail = {0} + + + Nom de travail = {0} + + + État du travail = {0} + + + Nom de la commande = + + + Chemin d’accès de la commande = + + + Type de commande = + + + Version de moteur = + + + ID d’hôte = + + + Nom d’hôte = + + + Application hôte = + + + Version de l’hôte = + + + ID de pipeline = + + + ID d’instance d’exécution = + + + Nom du script = + + + Numéro de séquence = + + + Gravité = + + + ID d’interpréteur de commandes = + + + Heure = + + + Utilisateur = + + + Utilisateur connecté = + + + Travail NULL + + + Nom du fournisseur + + + Le fournisseur {0} a changé d’état pour {1}. + + + L’exécution du script est {0}. + + + La variable {0} est passé de {1} à {2}. + + + La variable {0} est passé à {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/EventResource.fr.resx b/src/System.Management.Automation/resources/fr/EventResource.fr.resx new file mode 100644 index 00000000000..b55ea939fab --- /dev/null +++ b/src/System.Management.Automation/resources/fr/EventResource.fr.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Aucun message n’a été trouvé pour l’ID d’événement PowerShell.Core.Instrumentation.man. + + + La tâche planifiée {0} a démarré à {1} + + + + La tâche planifiée {0} s’est terminée à {1} avec l’état {2} + + + + Exception de tâche planifiée {0} : + Message : {1} + StackTrace : {2} + InnerException : {3} + + + + Initialisation de la fonctionnalité expérimentale : ignorez la fonctionnalité expérimentale « {0} » du fichier de configuration. {1} + + + Initialisation de la fonctionnalité expérimentale : échec de la lecture du fichier de configuration. + Exception :{0} + Message : {1} + StackTrace : {2} + + + + Plug-in de workflow chargé. + EndpointName : {0} + Utilisateur(-trice) : {1} + HostingMode : {2} + Protocole : {3} + Configuration : + {4} + + + Démarrage de l’exécution du workflow. + WorkflowId : {0} + ManagedNodes : {1} + + + État du workflow modifié. + WorkflowId : {0} + NewState : {1} + OldState : {2} + + + La fermeture du plug-in de workflow a été demandée. + EndpointName : {0} + + + Le plug-in de workflow a redémarré. + EndpointName : {0} + + + Le flux de travail reprend. + WorkflowId : {0} + + + Une limite de quota définie pour le point de terminaison a été dépassée. + EndpointName : {0} + ConfigName : {1} + Get allowedValue : {2} + ValueInQuestion : {3} + + + Le workflow a repris. + WorkflowId : {0} + + + Le pool d’instances d’exécution de workflow a été créé. + WorkflowId : {0} + ManagedNode : {1} + + + L’activité a été mise en file d’attente pour son exécution. + WorkflowId : {0} + ActivityName : {1} + + + Détails de l’exécution de l’activité. + ActivityName : {0} + Nom du type d’activité : {1} + + + Le workflow est importé à partir d’un fichier XAML. + WorkflowId : {0} + XamlFile : {1} + + + Le workflow a été importé à partir d’un fichier XAML. + WorkflowId : {0} + XamlFile : {1} + + + Le workflow n’a pas pu être importé à partir d’un fichier XAML en raison d’une erreur. + WorkflowId : {0} + ErrorDescription : {1} + + + La validation du flux de travail a démarré. + WorkflowId : {0} + + + La validation du flux de travail a réussi. + WorkflowId : {0} + + + Échec de la validation du flux de travail avec une erreur. + WorkflowId : {0} + + + Activité de workflow validée. + WorkflowId : {0} + ActivityDisplayName : {1} + Nom du type d’activité : {2} + + + Nous n’avons pas pu valider l’activité de workflow. + WorkflowId : {0} + ActivityDisplayName : {1} + Nom du type d’activité : {2} + + + L’exécution de l’activité a échoué. + WorkflowId : {0} + ActivityName : {1} + FailureDescription : {2} + + + La disponibilité du runspace a changé. + RunspaceId : {0} + Disponibilité : {1} + + + L’état de l’instance d’exécution a changé. + RunspaceId : {0} + NewState : {1} + OldState : {2} + + + Flux de travail chargé pour l’exécution. + WorkflowId : {0} + + + Flux de travail déchargé. + WorkflowId : {0} + + + L’exécution du workflow a été annulée. + WorkflowId : {0} + + + Abandon de l’exécution du workflow. + WorkflowId : {0} + + + Opération de nettoyage du workflow exécutée. + WorkflowId : {0} + + + Le workflow conservé a été chargé depuis le disque. + WorkflowId : {0} + Chemin : {1} + + + Les données du workflow ont été supprimées du disque. + WorkflowId : {0} + Chemin : {1} + + + Démarrage de la tâche de suppression. + JobId : {0} + + + État du travail modifié. + JobId : {0} + WorkflowId : {1} + NewState : {2} + OldState : {3} + + + Erreur de travail. + JobId : {0} + WorkflowId : {1} + ErrorDescription : {2} + + + Tâche créée pour le workflow (tâche enfant). + ParentJobId : {0} + ChildJobId : {1} + ChildWorkflowId : {2} + + + Tâche parente créée pour le workflow. + JobId : {0} + + + Toutes les tâches requises ont été créées pour l’exécution du workflow. + JobId : {0} + WorkflowId : {1} + + + Tâche enfant supprimée pour le workflow. + ParentJobId : {0} + ChildJobId : {1} + WorkflowId : {2} + + + Une erreur s’est produite lors de la suppression de la tâche. + ParentJobId : {0} + ChildJobId : {1} + WorkflowId : {2} + Erreur : {3} + + + Chargement du flux de travail pour l’exécution. + WorkflowId : {0} + + + L’exécution du workflow est terminée. + WorkflowId : {0} + + + Annulation de l’exécution du workflow. + WorkflowId : {0} + + + Abandon de l’exécution du workflow. + WorkflowId : {0} + Raison : {1} + + + Déchargement du workflow. + WorkflowId : {0} + + + L’arrêt forcé du flux de travail a démarré. + WorkflowId : {0} + + + Arrêt forcé du workflow terminé. + WorkflowId : {0} + + + Une erreur s’est produite lors de l’arrêt forcé d’un workflow. + WorkflowId : {0} + ErrorDescription : {1} + + + Persistance du workflow sur le disque. + WorkflowId : {0} + Chemin de persistance : {1} + + + Flux de travail enregistré sur le disque. + WorkflowId : {0} + + + L’exécution de l’activité est terminée. + ActivityName : {0} + + + Erreur d’exécution de flux de travail. + WorkflowId : {0} + ErrorDescription : {1} + + + Un nouveau point de terminaison PowerShell a été inscrit. + EndpointName : {0} + EndpointType : {1} + RegisteredBy : {2} + + + Endpoint Configuration modifié. + EndpointName : {0} + ModifiedBy : {1} + + + Configuration du point de terminaison désinscrite. + EndpointName : {0} + UnregisteredBy : {1} + + + Endpoint Configuration désactivé. + EndpointName : {0} + DisabledBy : {1} + + + Configuration du point de terminaison activée. + EndpointName : {0} + Activé par : {1} + + + L’instance d’exécution hors processus a démarré. + Commande : {0} + + + La diffusion d’arguments a été effectuée lors de l’exécution du workflow. + Paramètres : {0} + Ordinateurs : {1} + + + Le moteur de workflow a démarré. + EndpointName : {0} + + + Gestionnaire de workflow instancié avec + CheckpointPath : {0} + ConfigProviderId : {1} + Nom d’utilisateur : {2} + Chemin : {3} + + + Nom de l’ordinateur $null ou . résolu en hôte local + + + Résolution vers le schéma par défaut http + + + Le nom de l’interpréteur de commandes distant a été résolu sur PowerShellCore par défaut + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + Création du texte Scriptblock ({0} sur {1}) : +{2} + +ID Scriptblock : {3} +Chemin : {4} + + + Appel démarré de l’ID ScriptBlock : {0} +ID d’instance d’exécution : {1} + + + Appel terminé de l’ID ScriptBlock : {0} +ID d’instance d’exécution : {1} + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + {2} + +Contexte : +{0} + +Données utilisateur : +{1} + + + + Corrélation des ID d’activité. + CurrentActivityId : {0} + ParentActivityId : {1} + + + Nom de classe = {0} +Nom de la méthode = {1} +GUID de workflow = {2} +Message = {3} +{4} +Nom de l’activité = {5} +GUID de l’activité = {6} +Paramètres = {7} + + + Création d’un objet Runspace + ID d’instance : {0} + + + Création de l’objet RunspacePool + InstanceId : {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Ouverture de RunspacePool + + + Modification de l’ID d’activité et corrélation + + + L’état de l’instance d’exécution a changé en {0} + + + Nouvelle tentative de création de session {0} pour le code d’erreur {1} sur l’ID de session {2} + + + PowerShell a démarré un thread d’écoute IPC sur le processus : {0} dans AppDomain : {1}. + + + PowerShell a fini un thread d’écoute IPC sur le processus : {0} dans AppDomain : {1}. + + + Une erreur s’est produite dans le thread d’écoute IPC PowerShell du processus : {0} dans AppDomain : {1}. Message d’erreur : {2}. + + + Connexion IPC PowerShell sur le processus : {0} dans AppDomain : {1} pour l’utilisateur(-trice) : {2}. + + + Déconnexion IPC PowerShell sur le processus : {0} dans AppDomain : {1} pour l’utilisateur(-trice) : {2}. + + + Port résolu en {0} + + + AppName résolu en {0} + + + Nom de l’ordinateur résolu en {0} + + + Le schéma est {0} + + + Tester le message analytique + + + Les paramètres de connexion sont + URI de connexion : {0} + URI de ressource : {1} + Utilisateur(-trice) : {2} + Délai d’expiration d’ouverture : {3} + Délai d’expiration d’inactivité : {4} + Délai d’expiration d’annulation : {5} + AuthenticationMechanism L {6} + Empreinte numérique : {7} + Nombre maximal de redirections d’URI : {8} + Taille maximale des données reçues par commande : {0}0 + Taille maximale de l’objet reçu : {0}1 + + + Modification de l’ID d’activité et corrélation + + + Objet reçu avec ID de l’instance d’exécution : {0} ID de commande : {1} Destination : {2} Type de données : {3} Interface cible : {4} + + + Une exception non gérée s'est produite dans le domaine d’application. +Type d’exception : {0} +Message d’exception : {1} +$PSItem.Exception.StackTrace : {2} + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. WSMan a signalé une erreur avec le code d’erreur : {2}. + Message d’erreur : {3} + StackTrace : {4} + + + Une exception non gérée s'est produite dans le domaine d’application. +Type d’exception : {0} +Message d’exception : {1} +$PSItem.Exception.StackTrace : {2} + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. WSMan a signalé une erreur avec le code d’erreur : {2}. + Message d’erreur : {3} + StackTrace : {4} + + + ID d’instance d’exécution {0}. Établissement d’une connexion à l’aide de WSMan Create Shell + + + ID d’instance d’exécution {0}. Rappel reçu pour WSMan Create Shell + + + ID d’instance d’exécution : {0}. Fermeture du shell à l’aide de WSManCloseShell + + + ID d’instance d’exécution : {0}. Rappel reçu pour WSManCloseShell + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. Envoi de données d’une taille de {2} + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. Rappel reçu pour WSManSendShellInputEx + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. Envoi d’une requête Receive à l’aide de WSManReceiveShellOutputEx + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. Données reçues d’une taille de {2}. + + + ID de l’instance d’exécution {0} ID de pipeline {1}. Établissement d’une connexion de commande à l’aide de WSManRunShellCommandEx + + + ID de l’instance d’exécution {0} ID de pipeline {1}. Rappel reçu pour la connexion de commande + + + ID de l’instance d’exécution :{0} ID de pipeline {1}. Fermeture du transport pour la commande + + + ID de l’instance d’exécution :{0} ID de pipeline {1}. Rappel reçu pour la fermeture de commande + + + ID de l’instance d’exécution :{0} ID de pipeline {1}. Envoi d’un signal avec le code {2} à l’aide de WSManSignalShellEx + + + ID de l’instance d’exécution :{0} ID de pipeline {1}. Rappel reçu pour WSManSignalShellEx + + + ID d’instance d’exécution : {0}. La connexion est redirigée vers l’URI : {1} + + + ID de l’instance d’exécution : {0} ID du Pipeline : {1}. Le serveur envoie des données d’une taille de {2} au client. Type de données : {3} Interface cible : {4} + + + Requête {0}. Création d’une session distante côté serveur. Nom d’utilisateur : {1} ID de shell personnalisé : {2} + + + Signalement du contexte pour la requête : {0} Contexte signalé : {0} + + + Rapport de fin d’opération pour la requête : {0} + Code d’erreur : {1} + Message d’erreur : {2} + StackTrace : {3} + + + Contexte de l’interpréteur de commandes {0}. ID de requête : {1}. Création d’une session commune pour exécuter une commande. + + + Contexte d’interpréteur de commandes {0} Contexte de commande {1} ID de requête {2}. Arrêt de la commande. + + + Contexte d’interpréteur de commandes {0} Contexte de commande {1} ID de requête {2}. Données reçues du client. + + + Contexte d’interpréteur de commandes {0} Contexte de commande {1} ID de requête {2}. Le client a envoyé une requête de réception pour que le serveur puisse envoyer des données. + + + Contexte du shell {0} Contexte de commande {1} IsReceiveOperation {2}. Requête d’opération de fermeture reçue. + + + Chargement de l’assembly {0} pour l’interpréteur de commandes personnalisé avec l’ID d’environnement {1} + + + Chargement du type {0} pour l’interpréteur de commandes personnalisé avec l’ID d’environnement {1} + + + Fragment de communication à distance reçu. + ID d’objet : {0} + ID de fragment : {1} + Indicateur de début : {2} + Indicateur de fin : {3} + Longueur de la charge utile : {4} + Données de charge utile : {5} + + + Fragment de communication à distance envoyé. + ID d’objet : {0} + ID de fragment : {1} + Indicateur de début : {2} + Indicateur de fin : {3} + Longueur de la charge utile : {4} + Données de charge utile : {5} + + + Arrêt du service winrm. + + + Un objet a été restauré avec succès. + Nom du type désérialisé : {0} + Type restauré par conversion vers : {1} + L’objet restauré est de type : {2} + + + Échec de la restauration d’un objet. + Nom du type désérialisé : {0} + Type restauré par conversion vers : {1} + Exception de conversion de type : {2} + Exception interne de type : {3} + + + La profondeur de sérialisation a été remplacée. + Nom du type sérialisé : {0} + Profondeur d’origine : {1} + Profondeur remplacée : {2} + Profondeur actuelle sous le niveau supérieur : {3} + + + Le mode de sérialisation a été remplacé. + Nom du type sérialisé : {0} + Mode remplacé : {1} + + + La sérialisation d’une propriété de script a été ignorée, car il n’y a aucune instance d’exécution à utiliser pour évaluer la propriété. + Nom de la propriété : {0} + Nom du type du propriétaire de la propriété : {1} + Script du getter : {2} + + + La sérialisation d’une propriété a été ignorée, car le getter de la propriété a échoué. + Nom de la propriété : {0} + Nom du type du propriétaire de la propriété : {1} + Exception renvoyée par le getter de la propriété : {2} + Exception interne renvoyée par le getter de la propriété : {3} + + + La sérialisation d’un objet énumérable peut ne pas être complète, car l’objet en cours d’énumération a levé une exception. + Type d’objet en cours d’énumération : {0} + Exception : {1} + + + La sérialisation a appelé la méthode ToString de l’objet, qui a échoué. + Type d'objet : {0} + Exception : {1} + + + La profondeur maximale sous le niveau supérieur a été atteinte, ce qui force les objets à être sérialisés sous forme de chaînes. + Type d’objet à la profondeur maximale : {0} + Nom de la propriété à la profondeur maximale : {1} + Profondeur : {2} + + + Une exception XmlException a été levée par le désérialiseur (ce qui indique probablement un format clixml incorrect). + Numéro de ligne : {0} et position de ligne : {1} + Exception : {2} + + + La sérialisation des propriétés spécifiées a échoué, car l’une des propriétés spécifiées était manquante. + Type d'objet : {0} + Nom de la propriété : {1} + + + La console PowerShell est en cours de démarrage + + + La console PowerShell est prête à recevoir une entrée utilisateur + + + {0} + + + Suivi de ErrorRecord : + Message : {0} + CategoryInfo.Category : {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId : {4} + Détails de l’exception : + Message : {5} + Trace des appels de procédure : {6} + InnerException {7} + + + + Exception : + Message : {0} + StackTrace : {1} + InnerException : {2} + + + + Suivi de PSObject + + + Tâche de suivi : + ID : {0} + InstanceId : {1} + Nom : {2} + Emplacement : {3} + État : {4} + Commande : {5} + + + + Informations de trace : + {0} + + + Informations de trace : + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication. Début de l’appel de la fonction de workflow. Guid de suivi {0} + + + END ImportWorkflowCommand::StartWorkflowApplication. Fin de l’appel de la fonction de workflow. Guid de suivi {0} + + + BEGIN Création d’une nouvelle tâche dans ImportWorkflowCommand::StartWorkflowApplication. Guid de suivi {0} + + + END Création d’une nouvelle tâche dans ImportWorkflowCommand::StartWorkflowApplication. Guid de suivi {0} + + + END Création d’une nouvelle tâche dans ImportWorkflowCommand::StartWorkflowApplication. Guid de suivi {0} : Guid de ContainerParentJob {1} + + + DÉBUT Logique de tâche ContainerParentJob {0}Guid + + + END Logique de tâche ContainerParentJob Guid {0} + + + BEGIN Exécution du flux de travail ContainerParentJob {0}Guid + + + FIN Exécution du flux de travail ContainerParentJob Guid {0} + + + WorkflowJob avec Guid {0} ajouté à ContainerParentJob avec Guid {1} + + + ProxyJob avec le Guid {0} associé au ContainerParentJob distant avec le Guid {1} + + + BEGIN Exécution de ContainerParentJob avec Guid {0} + + + FIN Exécution de ContainerParentJob avec Guid {0} + + + BEGIN Exécution de la tâche proxy avec le GUID {0} + + + FIN Exécution de la tâche proxy avec le GUID {0} + + + BEGIN Gestionnaire d’événements de changement d’état pour la tâche proxy avec Guid {0} + + + END Gestionnaire d’événements de changement d’état pour la tâche proxy avec Guid {0} + + + BEGIN Gestionnaire d’événements de changement d’état pour la tâche proxy enfant avec Guid {0} + + + END Gestionnaire d’événements de changement d’état pour la tâche proxy enfant avec Guid {0} + + + BEGIN du garbage collection + + + Démarrage du garbage collection + + + Le magasin de persistance a atteint sa taille maximale spécifiée + + + Windows PowerShell ISE a commencé à exécuter le fichier de script {0}. + + + Windows PowerShell ISE a commencé à exécuter un script sélectionné par l’utilisateur à partir du fichier {0}. + + + Windows PowerShell ISE arrête la commande en cours. + + + Windows PowerShell ISE a poursuivi le débogueur. + + + Windows PowerShell ISE arrête le débogueur. + + + Windows PowerShell ISE effectue un débogage pas à pas entrant. + + + Windows PowerShell ISE effectue un pas à pas détaillé sur le débogage. + + + Windows PowerShell ISE se retire du débogage pas à pas. + + + Windows PowerShell ISE active tous les points d’arrêt. + + + Windows PowerShell ISE désactive tous les points d’arrêt. + + + Windows PowerShell ISE supprime tous les points d’arrêt. + + + Windows PowerShell ISE définit le point d’arrêt à la ligne # : {0} du fichier {1}. + + + Windows PowerShell ISE supprime le point d’arrêt à la ligne n° {0} du fichier {1}. + + + Windows PowerShell ISE active le point d’arrêt à la ligne n° {0} du fichier {1}. + + + Windows PowerShell ISE désactive le point d’arrêt à la ligne n° {0} du fichier {1}. + + + Windows PowerShell ISE a atteint un point d’arrêt à la ligne n° {0} du fichier {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/EventingResources.fr.resx b/src/System.Management.Automation/resources/fr/EventingResources.fr.resx new file mode 100644 index 00000000000..bd30bfd60c3 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/EventingResources.fr.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nous ne pouvons pas effectuer l’inscription à l’événement spécifié. Les événements qui nécessitent une valeur de retour ne sont pas pris en charge. + + + Nous ne pouvons pas effectuer l’inscription à l’événement spécifié. Un événement nommé « {0} » n’existe pas. + + + PowerShell ne peut pas s’abonner aux événements Windows RT. + + + Nous ne pouvons pas effectuer l’inscription à l’événement spécifié. L’identificateur de source d’événement « {0} » est réservé au moteur PowerShell. + + + Cette opération n’est pas prise en charge sur les instances distantes. + + + Cette action n’est pas prise en charge lorsque vous transférez des événements. + + + Nous ne pouvons pas effectuer l’abonnement à l’événement spécifié. Un abonné avec l’identificateur de source « {0} » existe déjà. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ExperimentalFeatureStrings.fr.resx b/src/System.Management.Automation/resources/fr/ExperimentalFeatureStrings.fr.resx new file mode 100644 index 00000000000..39edbb96b57 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ExperimentalFeatureStrings.fr.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Aucune fonctionnalité expérimentale correspondant au nom '{0}' n’a été trouvée. + + + L’activation et la désactivation des fonctionnalités expérimentales ne prennent pas effet avant le prochain démarrage de PowerShell. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ExtendedTypeSystem.fr.resx b/src/System.Management.Automation/resources/fr/ExtendedTypeSystem.fr.resx new file mode 100644 index 00000000000..2cd620ef1b9 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ExtendedTypeSystem.fr.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Le membre « {0} » est déjà présent. + + + Le membre « {0} » est déjà présent dans le fichier de données de type étendu. + + + Le membre « {0} » n’est pas présent. + + + Exception lors de la définition de « {0} » : « {1} » + + + Exception lors de l’obtention de « {0} » : « {1} » + + + L’exception suivante s’est produite lors de la tentative d’énumération de la collection : « {0} ». + + + Impossible d’accéder au membre « {0} » en dehors d’un PSObject. + + + Impossible de modifier le membre créé à partir de la configuration de type : « {0} ». + + + Le nom de membre « {0} » est réservé. + + + « {0} » n’est pas modifiable. + + + Exception lors de l’appel de « {0} » avec « {1} » argument(s) : « {2} » + + + Une exception a été levée lors de la tentative d’appel de « {0} » pour extraire le contenu d’un objet de type « {1} » : « {2} » + + + Impossible de trouver une surcharge pour « {0} » avec le nombre d’arguments « {1} ». + + + Impossible de trouver une surcharge de méthode générique appropriée pour « {0} » avec « {1} » paramètre(s) de type et avec le nombre d’arguments « {2} ». + + + Plusieurs surcharges ambiguës ont été trouvées pour « {0} » avec le nombre d’arguments « {1} ». + + + Impossible de convertir l’argument « {0} », avec la valeur « {1} », pour « {2} » en type « {3} » : « {4} » + + + L’accesseur Get de la propriété « {0} » n’est pas disponible. + + + L’accesseur Set de la propriété « {0} » n’est pas disponible. + + + La méthode setter doit être publique, nulle et non avenue, statique et comporter deux paramètres. Le premier paramètre doit être de type PSObject. Un second paramètre est requis si une méthode getter est également disponible, et il doit avoir le même type que le type de retour de la méthode getter. + + + La méthode getter doit être publique, non void, statique et avoir un paramètre de type PSObject. + + + Le CodeProperty doit utiliser une méthode getter ou setter. + + + Impossible de créer une méthode de code en raison du format de la méthode. La méthode doit être publique, statique et avoir un paramètre de type PSObject. + + + L’alias nommé « {0} » contient une boucle. + + + Impossible de convertir la valeur « {0} » de type « {1} » en type « {2} ». + + + Impossible de convertir la valeur de type « {0} » en type « {1} ». + + + Impossible de convertir la valeur « {0} » en type « {1} ». Erreur : « {2} » + + + Impossible de convertir la valeur « {0} » en type « {1} » car aucune virgule n’est autorisée pour cette énumération. + + + Impossible de convertir la valeur « {0} » en type « {1} » en raison de valeurs d’énumération non valides. Spécifiez l’une des valeurs d’énumération suivantes, puis réessayez. Les valeurs d’énumération possibles sont « {2} ». + + + Impossible de convertir null en type « {0} » en raison de valeurs d’énumération non valides. Spécifiez l’une des valeurs d’énumération suivantes, puis réessayez. Les valeurs d’énumération possibles sont « {1} ». + + + Impossible de convertir null en type « {0} ». + + + Impossible de convertir la valeur en type « {0} ». Erreur : « {1} » + + + Impossible de convertir la valeur en type System.String. + + + Un type de référence est attendu dans l’argument. + + + Impossible de comparer « {0} » car il n’est pas IComparable. + + + Impossible de comparer « {0} » à « {1} ». Erreur : « {2} » + + + Impossible de comparer « {0} » et « {1} », car les objets ne sont pas du même type ou l’objet « {0} » n’implémente pas « {2} ». + + + Impossible de convertir la valeur « {0} » en type « {1} », car au moins deux correspondances ont été trouvées ({2}, {3}) et une seule correspondance est autorisée pour cette énumération. + + + Impossible de convertir la valeur « {0} » en type « {1} ». Les paramètres booléens acceptent uniquement les valeurs booléennes et les nombres, tels que $True, $False, 1 ou 0. + + + Impossible d’obtenir la valeur de la propriété, car « {0} » est une propriété en écriture seule. + + + « {0} » est une propriété ReadOnly. + + + Impossible de définir « {0} » car seules des chaînes peuvent être utilisées comme valeurs pour définir les propriétés XmlNode. + + + Impossible de définir « {0} » car seuls des attributs uniques ou des nœuds terminaux uniques non attribués peuvent être définis. + + + Impossible d’ajouter un objet PSProperty ou PSMethod à cette collection. + + + L’erreur suivante s’est produite lors du chargement du fichier de données de type étendu : {0} + + + L’exception suivante s’est produite lors de la récupération de la chaîne : « {0} » + + + Le champ ou la propriété « {0} » du type «{1} » ne diffère du champ ou de la propriété « {2} » autrement que par la casse. Le type doit être conforme à CLS (Common Language Specification). + + + L’exception suivante s’est produite lors de la récupération de la hiérarchie des noms de type : « {0} ». + + + L’exception suivante s’est produite lors de la récupération des membres « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération des membres : « {0} » + + + L’exception suivante s’est produite lors de la récupération de l’état de lecture de la propriété « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération de l’état d’écrire de la propriété « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération du type pour la propriété « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération de la représentation sous forme de chaîne de la propriété « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération des attributs de la propriété « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération des définitions de la méthode « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération de la représentation sous forme de chaîne de la méthode « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération du type pour la propriété paramétrable « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération de l’état de lecture de la propriété paramétrée « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération de l’état d’écriture de la propriété paramétrée « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération des définitions de la propriété paramétrée « {1} » : « {0} » + + + L’exception suivante s’est produite lors de la récupération de la représentation sous forme de chaîne pour la propriété paramétrable « {1} » : « {0} » + + + Impossible de définir la propriété Value pour l’objet PSMemberInfo de type « {0} ». + + + L’argument « {0} » doit être un {1}. Utilisez {2}. + + + Argument : « {0} » ne doit pas être un {1}. N’utilisez pas {2}. + + + La propriété « {0} » est introuvable. + + + Impossible d'obtenir ou de définir la valeur de la propriété. L’argument « {0} » doit être de type « {1} » ou « {2} ». + + + Impossible de définir la valeur de la propriété « {0} » car l’objet est de type « {1} » au lieu de « {2} ». + + + Exception lors de l’appel de « {0} » : « {1} » + + + {0} n’est pas un chemin d’accès de classe valide. + + + {0} est un chemin non valide. + + + L’adaptateur ne peut pas déterminer si la propriété « {0} » peut être modifiée. + + + L’adaptateur ne peut pas déterminer si la propriété « {0} » est accessible en lecture. + + + L’adaptateur ne peut pas obtenir la valeur de la propriété « {0} ». + + + L’adaptateur ne peut pas définir la valeur de la propriété « {0} ». + + + L’adaptateur ne peut pas obtenir le type de propriété « {0} ». + + + L’adaptateur ne peut pas obtenir la hiérarchie de types de « {0} ». + + + L’adaptateur ne peut pas obtenir les propriétés de « {0} ». + + + L’adaptateur ne peut pas obtenir la propriété « {0} » pour « {1} ». + + + « {0} » a renvoyé une valeur null. + + + La propriété « {0} » est introuvable pour l’objet « {1} ». Les propriétés définissables sont : {2}. + + + La propriété « {0} » est introuvable pour l’objet « {1} ». Aucune propriété définissable n’est disponible. + + + Impossible de créer un objet de type « {0} ». {1} + + + Impossible d’appeler des méthodes statiques ou d’accéder aux propriétés statiques sur le type générique ouvert {0}. Spécifiez les paramètres de type, puis réessayez. Par exemple, au lieu de [System.Collections.Generic.HashSet``1]::CreateSetComparer(), utilisez [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + L’exception suivante s’est produite lors de la construction de l’attribut « {1} » : « {0} » + + + La valeur « {0} » ne peut pas être convertie en tableau de chaînes. + + + Impossible de convertir la valeur en type « {0} ». Seuls les types principaux sont pris en charge dans ce mode de langage. + + + Impossible de convertir en type ByRef-like « {0} ». Les types similaires à ByRef ne sont pas pris en charge dans PowerShell. + + + Impossible d’obtenir ou de définir la propriété ou le champ « {0} » du type similaire à ByRef « {1} ». Les types similaires à ByRef ne sont pas pris en charge dans PowerShell. + + + Impossible d’appeler la méthode « {0} » du type de retour similaire à ByRef « {1} ». Les types similaires à ByRef ne sont pas pris en charge dans PowerShell. + + + Nous ne pouvons pas créer une instance du type similaire à ByRef « {0} ». Les types similaires à ByRef ne sont pas pris en charge dans PowerShell. + + + Conversion de table de hachage du système de types étendus + + + La conversion de type de HashTable vers « {0} » ne sera pas autorisée en mode ConstrainedLanguage. + + + Conversion de table de hachage du système de types étendus + + + La conversion de type de « {0} » vers « {1} » ne sera pas autorisée en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/FileSystemProviderStrings.fr.resx b/src/System.Management.Automation/resources/fr/FileSystemProviderStrings.fr.resx new file mode 100644 index 00000000000..331170171e1 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/FileSystemProviderStrings.fr.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Appeler un élément + + + Élément : {0} + + + Supprimer le fichier + + + Supprimer le répertoire + + + Copier le fichier + + + Élément : {0} Destination : {1} + + + Copier le répertoire + + + Renommer le fichier + + + Renommer le répertoire + + + Élément : {0} Destination : {1} + + + Déplacer le fichier + + + Déplacer le répertoire + + + Élément : {0} Destination : {1} + + + Définir le fichier de propriétés + + + Définir le répertoire des propriétés + + + Élément : {0} Propriété : {1} Valeur : {2} + + + Effacer le fichier de propriétés + + + Effacer le répertoire des propriétés + + + Élément : {0} Propriété : {1} + + + Créer un fichier + + + Créer un répertoire + + + Destination : {0} + + + Effacer le contenu + + + Élément : {0} + + + Nous n’avons pas pu trouver l’élément {0}. + + + Impossible de supprimer l’élément {0} : {1} + + + Impossible de restaurer les attributs de l’élément {0} : {1} + + + Aucun objet au chemin d’accès spécifié {0} n’existe. + + + Le répertoire {0} ne peut pas être supprimé parce qu'il n'est pas vide. + + + Le type n’est pas un type connu pour le système de fichiers. Seuls « file » (fichier), « directory » (répertoire) ou « symboliclink » peuvent être spécifiés. + + + Impossible de traiter le chemin d’accès, car le chemin d’accès spécifié fait référence à un élément situé en dehors du chemin de base basePath. + + + La racine du lecteur spécifié « {0} » n’existe pas ou n’est pas un dossier. + + + Un mappage avec le nom spécifié {0} existe déjà. + + + Impossible de spécifier un délimiteur lors de la lecture du flux un octet à la fois. + + + Impossible de remplacer l’élément {0} par lui-même. + + + Impossible de renommer la cible spécifiée, car elle représente un chemin d’accès ou un nom d’appareil. + + + La propriété {0} n’existe pas ou n’a pas été trouvée. + + + Vous ne disposez pas de droits d’accès suffisants pour effectuer cette opération ou l’élément est masqué, système ou en lecture seule. + + + Impossible de définir l’attribut, car les attributs ne sont pas pris en charge. Seuls les attributs suivants peuvent être définis : Archive, Hidden (Masqué), Normal, ReadOnly (Lecture seule) ou System (Système). + + + Impossible d’effacer la propriété, car elle n’est pas prise en charge. Seule la propriété Attributs peut être effacée. + + + Impossible de traiter le chemin d’accès « {0} », car la cible représente un nom d’appareil réservé. + + + L’encodage n’est pas utilisé quand « -AsByteStream » est spécifié. + + + Impossible de poursuivre l’encodage d’octets. Lors de l’utilisation de l’encodage d’octets, le contenu doit être de type octet. + + + Impossible de traiter le fichier, car le fichier {0} est introuvable. + + + Répertoire : + + + Impossible de détecter l’encodage du fichier. L’encodage spécifié {0} n’est pas pris en charge lorsque le contenu est lu en sens inverse. + + + Nous n’avons pas pu ouvrir le flux de données alternatif « {0} » du fichier « {1} ». + + + Flux « {0} » du fichier « {1} ». + + + Les paramètres Raw (Brut) et Wait (Attendre) ne peuvent pas être spécifiés dans la même commande. + + + Pour utiliser le paramètre de commutateur Conserver, le nom du lecteur doit être pris en charge par le système d’exploitation (par exemple, les lettres de lecteur A-Z). + + + Lorsque vous utilisez le paramètre Persist (Conserver), la racine doit être un emplacement de système de fichiers sur un ordinateur distant. + + + Les paramètres « {0} » et « {1} » ne peuvent pas être spécifiés dans la même commande. + + + Un répertoire est requis pour l’opération. L’élément « {0} » n’est pas un répertoire. + + + Créer un raccordement + + + Créer un lien symbolique + + + Des privilèges d’administrateur sont requis pour cette opération. + + + Créer un lien physique + + + Un fichier est requis pour l’opération. L’élément « {0} » n’est pas un fichier. + + + Les liens physiques ne sont pas pris en charge pour le chemin d’accès spécifié. + + + Les liens symboliques ne sont pas pris en charge pour le chemin d’accès spécifié. + + + Copie de {0} dans {1} + + + Le chemin de destination {0} est un fichier qui existe déjà sur la destination cible. + + + Nous n’avons pas pu copier le fichier {0} vers la destination cible distante. + + + De {0} à {1} + + + Impossible de copier un répertoire « {0} » dans le fichier « {0} » + + + Nous n’avons pas pu obtenir les éléments enfants du répertoire {0} . + + + Nous n’avons pas pu lire le fichier distant « {0} ». + + + Impossible de valider si la destination distante {0} est un fichier. + + + Nous n’avons pas pu créer le répertoire « {0} » sur la destination distante. + + + La taille maximale du lecteur a été dépassée : {0}. + + + Impossible de créer le lien, car le chemin d’accès existe déjà : {0}. + + + Ignorez le répertoire déjà consulté {0}. + + + Le chemin de destination ne peut pas être un sous-répertoire de la source ni la source elle-même : {0}. + + + La cible et le chemin d’accès ne peuvent pas être identiques. + + + {0} fichiers copiés sur {1} + + + {0} sur {1} ({2:0.0} Mo/s) + + + {0} fichiers supprimés sur {1} + + + {0} sur {1} ({2:0.0} Mo/s) + + + La création d’un raccordement nécessite un chemin d’accès absolu pour la cible. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/FormatAndOutXmlLoadingStrings.fr.resx b/src/System.Management.Automation/resources/fr/FormatAndOutXmlLoadingStrings.fr.resx new file mode 100644 index 00000000000..809207d0fee --- /dev/null +++ b/src/System.Management.Automation/resources/fr/FormatAndOutXmlLoadingStrings.fr.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Erreur à XPath {0} dans le fichier {1} : l’élément XML {2} n’autorise pas les attributs. + + + Erreur à XPath {0} dans le fichier {1} : le nœud {2} ne peut pas avoir d’objets enfants. + + + Erreur XPath {0} dans le fichier {1} : {2} n'est pas valide. + + + Erreur XPath {0} dans le fichier {1} : Il doit y avoir au moins une valeur par défaut {2}. + + + Erreur à XPath {0} dans le fichier {1} : il ne peut pas y avoir plus d’un élément par défaut {2}. + + + Erreur à XPath {0} dans le fichier {1} : le nom du contrôle ne peut pas être nul ou vide. + + + Erreur XPath {0} dans le fichier {1} : les vues hors bande ne peuvent contenir que des CustomControl ou des ListControl. + + + Erreur à XPath {0} dans le fichier {1} : une vue hors bande ne peut pas avoir GroupBy. + + + Erreur à XPath {0} dans le fichier {1} : impossible de charger la vue. + + + Erreur à XPath {0} dans le fichier {1} : "{2}" n'est pas une valeur d'alignement valide. + + + Erreur à XPath {0} dans le fichier {1} : un entier positif est attendu. + + + Erreur à XPath {0} dans le fichier {1} : la définition de l’en-tête de colonne n’est pas valide ; tous les en-têtes sont ignorés. + + + Erreur à XPath {0} dans le fichier {1} : le nombre d’éléments de ligne = {2} dans l’ensemble alternatif #{3} ne correspond pas au nombre d’éléments de ligne par défaut = {4}. + + + Erreur à XPath {0} dans le fichier {1} : le nombre d’éléments d’en-tête = {2} ne correspond pas au nombre d’éléments de ligne par défaut = {3}. + + + Erreur au niveau de XPath {0} dans le fichier {1} : au moins un élément de vue de liste doit être spécifié. + + + Erreur à XPath {0} dans le fichier {1} : l’entrée de propriété n’est pas valide. + + + Erreur à XPath {0} dans le fichier {1} : la liste de définitions est manquante. + + + Erreur à XPath {0} dans le fichier {1} : une valeur booléenne est attendue. + + + Erreur à XPath {0} dans le fichier {1} : un entier non négatif est attendu. + + + Erreur à XPath {0} dans le fichier {1} : un entier est attendu. + + + Erreur au niveau de XPath {0} dans le fichier {1} : la valeur de texte interne est manquante. + + + Erreur au niveau de XPath {0} dans le fichier {1} : la liste de jetons de contrôle personnalisé ne peut pas être vide. + + + Erreur au niveau de XPath {0} dans le fichier {1} : {2} n’a pas pu être chargé. + + + Erreur XPath {0} dans le fichier {1} : {2} ne peut pas être spécifié sans expression. + + + Erreur XPath {0} dans le fichier {1} : {2} ne peut pas être spécifié avec une expression. + + + Erreur au niveau de XPath {0} dans le fichier {1} : une chaîne de format est manquante. + + + Erreur à XPath {0} dans le fichier {1} : le texte du bloc de script est manquant. + + + Erreur au niveau de XPath {0} dans le fichier {1} : une propriété est manquante. + + + Erreur XPath {0} dans le fichier {1} : le bloc de script « {2} » n’est pas valide. + + + Erreur XPath {0} dans le fichier {1} : La chaîne de caractères {2} de la ressource {3} dans l'assembly {4} est introuvable. + + + Erreur XPath {0} dans le fichier {1} : La chaîne de caractères {2} de la ressource {3} dans l'assembly est introuvable. + + + Erreur XPath {0} dans le fichier {1} : l'assembly {2} est introuvable. + + + Erreur à XPath {0} dans le fichier {1} : le nœud doit être un XmlElement. + + + Erreur XPath {0} dans le fichier {1} : une expression est attendue. + + + Erreur à XPath {0} dans le fichier {1} : impossible d’avoir un contrôle ou un Label sans expression. + + + Erreur à XPath {0} dans le fichier {1} : impossible d’avoir le contrôle et Label en même temps. + + + Erreur à XPath {0} dans le fichier {1} : impossible d’avoir SelectionSetName et TypeName en même temps. + + + Erreur à XPath {0} dans le fichier {1} : aucun type ni aucune condition n’est spécifié pour appliquer la vue. + + + Erreur XPath {0} dans le fichier {1} : la valeur {2} n'est pas valide. + + + Erreur à XPath {0} dans le fichier {1} : un nœud en double existe. + + + Erreur à XPath {0} dans le fichier {1} : {2} et {3} s’excluent mutuellement. + + + Erreur à XPath {0} dans le fichier {1} : {2}, {3} et {4} s’excluent mutuellement. + + + Erreur au niveau de XPath {0} dans le fichier {1} : {2} est un nœud inconnu. + + + Erreur au niveau de XPath {0} dans le fichier {1} : {2} est un attribut inconnu. + + + Erreur au niveau de XPath {0} dans le fichier {1} : {2} est un attribut manquant. + + + Erreur XPath {0} dans le fichier {1} : Nœud {2} manquant. + + + Erreur XPath {0} dans le fichier {1} : un nœud est manquant dans {2}. + + + Erreur au niveau de XPath {0} dans le fichier {1} : {2} est un nœud vide. + + + Erreur au niveau de XPath {0} dans le fichier {1} : {2} est un attribut vide. + + + Erreur dans le fichier {0} : {1} + + + Trop d’erreurs dans le fichier {0}. + + + Des erreurs se sont produites lors du chargement du fichier de données de format : {0} + + + (Global Assembly Cache) {0} + + + {0}, {1} + + + Le chemin d’accès {0} n’est pas complet. Spécifiez un chemin d’accès complet vers le fichier de type. + + + Impossible de mettre à jour FormatTable, car le FormatTable a peut-être été créé en dehors de l’espace d’exécution. + + + Des erreurs se sont produites lors du chargement de FormatTable. Consultez la propriété Erreurs pour obtenir des messages d’erreur détaillés. + + + Erreur lors de la mise en forme des données «{0}» : {1} + + + Erreur dans les données d’affichage avec le nom de type {0} à l’index {1} : le nombre d’éléments d’en-tête = {2} ne correspond pas au nombre d’éléments de ligne par défaut = {3}. + + + Erreur dans les données d’affichage avec le nom de type {0} à l’index {1} : le bloc de script «{2}» n’est pas valide. + + + Erreur dans les données d’affichage avec le nom de type {0} à l’index {1}: le bloc de script «{2}» n’est pas valide. + + + Erreur dans les données d’affichage avec le nom de type {0} à l’index {1}: échec du chargement de {2} . + + + Erreur lors de l'affichage des données avec le nom {0} de type à l'index {1} : Un TableControl ne doit contenir qu'un seul {2}. + + + Erreur lors de l'affichage des données avec le nom {0} de type à l'index {1} : Il doit y avoir au moins une valeur par défaut {2}. + + + Erreur lors de l'affichage des données avec le type nommé {0} à l'index {1} : Au moins un élément de liste doit être spécifié. + + + Erreur dans les données d’affichage avec le nom de type {0} à l’index {1} : il ne peut pas y avoir plus d’un élément par défaut {2}. + + + Trop d’erreurs dans les données de mise en forme pour le type «{0}». + + + Une table de format partagé ne peut pas être mise à jour avec plusieurs entrées. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/FormatAndOut_MshParameter.fr.resx b/src/System.Management.Automation/resources/fr/FormatAndOut_MshParameter.fr.resx new file mode 100644 index 00000000000..f2e8771fc3e --- /dev/null +++ b/src/System.Management.Automation/resources/fr/FormatAndOut_MshParameter.fr.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 + + + Impossible de convertir {0} en l’un des types suivants {1}. + + + La valeur d’un paramètre était null; l’un des types suivants était attendu : {0}. + + + La clé dupliquée « {0} » est en conflit avec « {1} ». + + + La clé « {0} » a un type, {1}, qui n’est pas valide; les types attendus sont {2}. + + + La clé « {0} » a un type, {1}, qui n’est pas valide; le type attendu est {2}. + + + La clé {0} est ambiguë; {1} et {2} entrent en conflit. + + + La valeur d’une clé ne peut pas être null. + + + Le type de clé « {0} » n’est pas valide. La clé doit être une chaîne. + + + La clé {0} n’a pas de valeur. + + + Une entrée obligatoire pour {0} est manquante. + + + La clé API {0} n’est pas valide. + + + La valeur « {0} » pour la clé « {1} » n’est pas valide; les valeurs valides sont {2}. + + + La valeur « {0} » pour la clé « {1} » doit être supérieure à 0. + + + Nous ne pouvons pas avoir une chaîne de mise en forme vide pour la clé « {0} ». + + + La clé « {0} » ne peut pas avoir une valeur de chaîne vide. + + + La valeur de la chaîne ne peut pas être vide. + + + La clé « {0} » ne peut pas contenir de caractères génériques dans la valeur « {1} ». + + + Les caractères génériques ne sont pas autorisés dans « {0} ». + + + La valeur EnumerableExpansion n’est pas valide. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/FormatAndOut_format_xxx.fr.resx b/src/System.Management.Automation/resources/fr/FormatAndOut_format_xxx.fr.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/FormatAndOut_format_xxx.fr.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/FormatAndOut_out_xxx.fr.resx b/src/System.Management.Automation/resources/fr/FormatAndOut_out_xxx.fr.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/FormatAndOut_out_xxx.fr.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/GetErrorText.fr.resx b/src/System.Management.Automation/resources/fr/GetErrorText.fr.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/GetErrorText.fr.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/HelpDisplayStrings.fr.resx b/src/System.Management.Automation/resources/fr/HelpDisplayStrings.fr.resx new file mode 100644 index 00000000000..47ea5adf5c3 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/HelpDisplayStrings.fr.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NOM + + + SYNOPSIS + + + DESCRIPTION + + + SYNTAX + + + PARAMETERS + + + INPUTS + + + OUTPUTS + + + TERMINATING ERRORS + + + NON-TERMINATING ERRORS + + + NOTES + + + EXAMPLES + + + Exemple + + + EXAMPLE + + + OUTPUT + + + RELATED LINKS + + + SHORT DESCRIPTION + + + Title: + + + Question: + + + Répondre + + + Term: + + + Definition: + + + Content: + + + PROVIDER NAME + + + This cmdlet supports the common parameters: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. For more information, see + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Required? + + + Position? + + + Type: + + + Target Object Type: + + + Default value + + + Accept pipeline input? + + + Accept wildcard characters? + + + (Category: + + + Suggested Action: + + + For more information, type: + + + For technical information, type: + + + To see the examples, type: + + + For online help, type: + + + <CommonParameters> + + + REMARKS + + + true + + + Named + + + DRIVES + + + CAPABILITIES + + + TASKS + + + TASK: + + + FILTERS + + + DYNAMIC PARAMETERS + + + Cmdlets Supported: + + + ALIASES + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + -- To view the Help topic for this cmdlet online, type: "Get-Help {0} -Online" or + go to {1}. + + + Aucun + + + Aliases + + + Dynamic? + + + Parameter set name + + + Unable to retrieve the HelpInfo XML file for UI culture {0}. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + + + The ModuleBase directory cannot be found. Verify the directory and try again. + + + The path {0} is not a valid directory. Make sure the directory exists and retry. + + + A Help URI cannot contain more than 10 redirections. Specify a valid Help URI. + + + Updating Help + + + Connecting to Help Content... + + + Downloading Help Content... + + + Installing Help content... + + + Locating Help Content... + + + (All) + + + No PowerShell modules were found that match the following pattern: {0}. Verify the pattern and then try the command again. + + + No PowerShell modules were found that match the specified FullyQualifiedModule {0}. Verify the FullyQualifiedModule value and then try the command again. + + + Help content cannot be found. Make sure the server is available and the help content location is properly defined in the HelpInfo XML. + + + The Update-Help command failed because the specified module does not support updatable help. Use Get-Help -Online or look online for help for the commands in this module. + + + The following parameter must not be null or empty: Module. + + + The following parameter must not be null or empty: Path. + + + Update-Help has completed successfully. + + + Error extracting Help content. + + + Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. + + + The Help content at the specified location is not valid. Specify a location that contains valid Help Content. + + + The HelpInfo XML is not valid. Specify valid HelpInfo XML. + + + Help content was successfully saved to the following location: {0} + + + The Help content XSD file cannot be found in {0}. Verify that the XSD file exists at the specified location, and then retry the command. + + + Failed to update Help for the module(s) : +'{0}' +{1} + + + Saving Help + + + Help content contains files that are not valid. Only .txt and .xml files are supported. + + + Failed to save Help for the module(s) '{0}' : {1} + + + Failed to save Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be saved using: Save-Help -UICulture en-US. + + + Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + + + false + + + The -Recurse parameter is only available if a source path is specified. + + + The path {0} does not contain a FileSystem provider. Verify that the specified path contains the FileSystem provider, and then retry the command. + + + Searching Help for {0} ... + + + No UI culture was found that matches the following pattern: {0}. Verify the pattern and then try the command again. + + + Help was not saved for the module {0}, because the Save-Help command was run on this computer within the last 24 hours. +To save help again, add the Force parameter to your command. + + + Help was not updated for the module {0}, because the Update-Help command was run on this computer within the last 24 hours. +To update help again, add the Force parameter to your command. + + + The most current Help files are already installed. + + + {0}: {1}. Culture {2} Version {3} + + + Updated {0} + + + The value of the HelpInfoUri key in the module manifest must resolve to a container or root URL on a website where the help files are stored. The HelpInfoUri '{0}' does not resolve to a container. + + + Help content must be in the namespace {0}. + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + + + The most current Help files are already downloaded. + + + Saved {0} + + + The HelpInfoURI {0} does not start with HTTP. + + + The root level element of the help content must be "helpItems". + + + Saving Help for module {0} + + + Updating Help for module {0} + + + Resolving URI: "{0}" + + + Help URI: {0} + + + {0}, Current Version: {1}, Available Version: {2}, UICulture: {3} + + + PROPERTIES + + + METHODS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/HelpErrors.fr.resx b/src/System.Management.Automation/resources/fr/HelpErrors.fr.resx new file mode 100644 index 00000000000..c18e57407f4 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/HelpErrors.fr.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help n’a pas pu trouver {0} dans un fichier d’Aide de cette session. Pour télécharger les rubriques d’Aide mises à jour, tapez : « Update-Help ». Pour obtenir de l’Aide en ligne, recherchez la rubrique d’Aide dans la bibliothèque TechNet à l’adresse https://go.microsoft.com/fwlink/?LinkID=107116. + + + Nous ne pouvons pas traiter la catégorie d’Aide, car « {0} » n’est pas une catégorie d’Aide valide. + + + Nous ne pouvons pas charger le fichier d’Aide « {0} ». Détails: {1}. + + + Nous ne pouvons pas accéder au fichier d’Aide « {0} », car l’utilisateur(-trice) actuel(le) ne dispose pas des droits d’accès au fichier. Détails: {1}. + + + Le fichier d’Aide « {0} » n’est pas un document XML valide. Détails: {1}. + + + Une erreur s’est produite lors du chargement du contenu d’Aide pour {0} à partir du fichier {1}. Détails : {2}. Pour télécharger les rubriques d’Aide mises à jour, exécutez l’applet de commande Update-Help. Pour obtenir de l’Aide en ligne, recherchez la rubrique d’Aide dans la bibliothèque TechNet à l’adresse https://go.microsoft.com/fwlink/?LinkID=107116. + + + Le fournisseur « {0} » ne peut pas être chargé. Détails: {1}. + + + Nous ne pouvons pas charger le fichier d’Aide. Les erreurs de {1} suivantes se sont produites lors du chargement du fichier d’aide « {0} ». + + + Le nœud « {0} » ne peut pas avoir « {1} » comme nœud enfant. Chemin du nœud : {2}. + + + Le nœud « {0} » peut avoir un maximum de {2} nœuds enfants de type « {1} ». Chemin du nœud : {3}. + + + Nous ne pouvons pas trouver la clé de Registre : « {0}{1} »; utilisation de « {2} » pour charger les fichiers d’Aide. + + + Aucun paramètre ne correspond aux critères {0}. + + + {0} n’est pas pris en charge par la catégorie d’Aide demandée. + + + Nous ne pouvons pas afficher la version en ligne de cette rubrique d’Aide, car l’adresse Internet (URI) de la rubrique d’Aide n’est pas spécifiée dans le code de la commande ou dans le fichier d’Aide de la commande. + + + L'URI {0} spécifié est non valide. + + + Échec du démarrage d’un navigateur pour afficher l’Aide en ligne. Aucun programme ni navigateur n’est associé pour ouvrir l’URI {0}. + + + Le protocole spécifié dans l’URI « {0} » n’est pas pris en charge. Seuls les protocoles « {1} » et « {2} » sont pris en charge. + + + Plusieurs rubriques d’Aide ont été trouvées. Utilisez une seule rubrique d’Aide avec l’option -{0}. + + + Nous ne pouvons pas obtenir de l’Aide à partir d’un espace d’exécution distant, car l’espace d’exécution n’a pas été ouvert. Ouvrez l’espace d’exécution en exécutant une commande de communication à distance implicite, puis essayez de nouveau d’exécuter la commande pour obtenir de l’Aide. + + + L'accès est refusé. La commande n’a pas pu mettre à jour les rubriques d’Aide pour les modules principaux de PowerShell ou pour l’un des modules du répertoire $pshome\Modules. +Pour mettre à jour ces rubriques d’Aide, démarrez PowerShell à l’aide de la commande « Exécuter en tant qu’administrateur(-trice) », puis essayez d’exécuter Update-Help à nouveau. + + + Pour utiliser le {0}, vérifiez que votre application utilise « Microsoft.NET.Sdk.WindowsDesktop » comme SDK du projet et que l’assembly correspondant « Microsoft.PowerShell.GraphicalHost » est disponible. ({1}) + + + {0} ne fonctionne pas dans une session à distance. + + + ForwardHelpTargetName ne peut pas faire référence à la fonction elle-même. + + + Nous ne pouvons pas obtenir de l’Aide à partir d’un emplacement réseau dans une session restreinte. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/HistoryStrings.fr.resx b/src/System.Management.Automation/resources/fr/HistoryStrings.fr.resx new file mode 100644 index 00000000000..7dffccf7a49 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/HistoryStrings.fr.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 identifier {0} is not a valid value for a History identifier. Specify a positive number, and then try again. + + + Cannot locate the history for Id {0}. + + + The count cannot be combined with multiple Ids. + + + Cannot locate the history for command line {0}. + + + Cannot locate most recent history. + + + The Invoke-History cmdlet is called repeatedly, in a loop. + + + Cannot process multiple history commands. You can only run a single command by using Invoke-History. + + + Cannot add history because the input object has a format that is not valid. + + + The identifier {0} is not valid. Specify a positive number, and then try again. + + + This command will clear all the entries from the session history. + + + The count cannot be combined with multiple CommandLine parameters. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/HostInterfaceExceptionsStrings.fr.resx b/src/System.Management.Automation/resources/fr/HostInterfaceExceptionsStrings.fr.resx new file mode 100644 index 00000000000..8bc9ddb4a20 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/HostInterfaceExceptionsStrings.fr.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 + + + An error of type "{0}" has occurred. + + + A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the PowerShell Console, and remove prompt-related commands from command types that do not support user interaction. + + + A command that prompts the user failed because the host program or the command type does not support user interaction. The host was attempting to request confirmation with the following message: {0} + + + The method cannot be invoked because the pool has been closed or has failed. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/InternalCommandStrings.fr.resx b/src/System.Management.Automation/resources/fr/InternalCommandStrings.fr.resx new file mode 100644 index 00000000000..e32d59813bb --- /dev/null +++ b/src/System.Management.Automation/resources/fr/InternalCommandStrings.fr.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Le nom d’entrée « {0} » est ambigu. Il peut correspondre à plusieurs méthodes. Correspondances possibles :{1}. + + + Le nom d’entrée « {0} » est ambigu. Il peut correspondre à plusieurs membres. Correspondances possibles :{1}. + + + Récupérer la valeur de la clé « {0} » + + + Appeler la méthode « {0} » avec les arguments : {1} + + + Appeler la méthode « {0} » + + + Récupérer la valeur de la propriété « {0} » + + + InputObject : {0} + + + Nous ne pouvons pas effectuer cette opération sur un objet d’entrée null. + + + Le nom d’entrée « {0} » ne peut pas être résolu en méthode. + + + Nous ne pouvons pas appeler une méthode en mode de langage restreint. + + + Les paramètres -WhatIf et -Confirm ne sont pas pris en charge pour les blocs de script. + + + L’opération « {0} » n’est pas autorisée en mode RestrictedLanguage. + + + Un opérateur est requis pour comparer les deux valeurs spécifiées. Incluez un opérateur valide dans la commande, puis réessayez. Par exemple, Get-Process | Where-Object -Property Name -eq Idle + + + Le nom d’entrée « {0} » ne peut pas être résolu en propriété. + + + Le nom d’entrée « {0} » ne peut pas être résolu en membre. + + + L’opérateur spécifié requiert les paramètres -Property et -Value. Fournissez des valeurs pour ces deux paramètres, puis réessayez la commande. + + + Cette méthode ne peut pas être exécutée sur le thread actuel. Elle ne peut être appelée que sur le thread de l’applet de commande. + + + Une variable utilisée avec ForEach-Object -Parallel ne peut pas être un bloc de script. Les variables de bloc de script passées ne sont pas prises en charge avec ForEach-Object -Parallel et peuvent entraîner un comportement indéfini. + + + Un objet d’entrée transmis à ForEach-Object -Parallel ne peut pas être un bloc de script. Les variables de bloc de script passées ne sont pas prises en charge avec ForEach-Object -Parallel et peuvent entraîner un comportement indéfini. + + + Le paramètre « TimeoutSeconds » ne peut pas être utilisé avec le paramètre « AsJob ». + + + Les paramètres communs suivants ne sont actuellement pas pris en charge dans le jeu de paramètres Parallel : +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + Une erreur inattendue s’est produite lors du traitement de l’entrée ForEach-Object -Parallel. Cela peut signifier qu’une partie des entrées transmises par le pipeline n’a pas été traitée. Erreur {0}. + + + Cmdlet ForEach-Object + + + L’appel de méthode sur le type « {0} » ne sera pas autorisé lors de l’exécution en mode de langage contraint. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/InternalHostStrings.fr.resx b/src/System.Management.Automation/resources/fr/InternalHostStrings.fr.resx new file mode 100644 index 00000000000..556a1fae61b --- /dev/null +++ b/src/System.Management.Automation/resources/fr/InternalHostStrings.fr.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 + + + EnterNestedPrompt n’a pas été appelé autant de fois que ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/InternalHostUserInterfaceStrings.fr.resx b/src/System.Management.Automation/resources/fr/InternalHostUserInterfaceStrings.fr.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/fr/InternalHostUserInterfaceStrings.fr.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/Logging.fr.resx b/src/System.Management.Automation/resources/fr/Logging.fr.resx new file mode 100644 index 00000000000..5d792b76318 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/Logging.fr.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Gravité =[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo : + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Gravité =[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Gravité =[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + INCONNU + + + La fonctionnalité expérimentale du moteur « {0} » déclarée dans le fichier de configuration n’est pas enregistrée dans la version actuelle de PowerShell. + + + La fonctionnalité expérimentale « {0} » déclarée dans le fichier de configuration n’est pas valide. +Le nom d’une fonctionnalité expérimentale doit suivre la convention ci-dessous : + Nom de la fonctionnalité du moteur : « PS[FeatureName] » + Nom de la fonctionnalité du module : « [ModuleName].[FeatureName] » + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/Metadata.fr.resx b/src/System.Management.Automation/resources/fr/Metadata.fr.resx new file mode 100644 index 00000000000..f7e2c7fc1c1 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/Metadata.fr.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impossible d’initialiser les attributs pour «{0}» : «{1}» + + + Impossible de valider l’argument, car son type «{0}» n’est pas du même type ({1}) que les limites maximale et minimale du paramètre. Vérifiez que l’argument est de type {1}, puis réessayez la commande. + + + Impossible de valider l’argument «{0}», car sa valeur n’est pas supérieure à zéro. + + + Impossible de valider l’argument «{0}», car sa valeur n’est pas supérieure ou égale à zéro. + + + Impossible de valider l’argument «{0}», car sa valeur n’est pas inférieure à zéro. + + + Impossible de valider l’argument «{0}», car sa valeur n’est pas inférieure ou égale à zéro. + + + La plage minimale spécifiée ({0}) ne peut pas être acceptée, car elle n’est pas du même type que la plage maximale spécifiée ({1}). Mettez à jour l’attribut ValidateRange pour le paramètre. + + + Impossible d’accepter les types de paramètres MaxRange et MinRange. Les deux paramètres doivent être des objets qui implémentent une interface IComparable. + + + Impossible d’accepter la plage maximale spécifiée, car elle est inférieure à la plage minimale spécifiée. Mettez à jour l’attribut ValidateRange pour le paramètre. + + + L’argument {0} est supérieur à la plage maximale autorisée de {1}. Fournissez un argument inférieur ou égal à {1}, puis recommencez la commande. + + + L’argument {0} est inférieur à la plage minimale autorisée de {1}. Fournissez un argument supérieur ou égal à {1}, puis recommencez la commande. + + + L’argument «{0}» ne correspond pas au modèle «{1}». Fournissez un argument qui correspond à «{1}», puis réessayez la commande. + + + L’attribut ValidateCount ne peut pas être appliqué à un paramètre autre qu’un paramètre de tableau. Supprimez l’attribut du paramètre ou faites du paramètre un paramètre de tableau. + + + Le paramètre requiert exactement {0} valeur(s) - {1} valeur(s) ont été fournies. + + + Le paramètre nécessite au moins {0} valeur(s) et pas plus de {1} valeur(s) - {2} valeur(s) ont été fournies. + + + Le nombre maximal d’arguments spécifié pour un paramètre est inférieur au nombre minimal d’arguments spécifié. Mettez à jour l’attribut ValidateCount pour le paramètre. + + + La longueur de caractère maximale spécifiée de l’argument est inférieure à la longueur minimale de caractère d’argument spécifiée. Mettez à jour l’attribut ValidateLength pour le paramètre. + + + L’attribut ValidateLength ne peut pas être appliqué à un paramètre qui n’est pas un paramètre string ou string[]. Définissez le paramètre comme un paramètre string ou string[]. + + + La longueur du caractère ({1}) de l’argument est trop courte. Spécifiez un argument dont la longueur est supérieure ou égale à «{0}», puis réessayez. + + + La longueur du caractère ({1}) de l’argument est trop longue. Spécifiez un argument dont la longueur est inférieure ou égale à «{0}», puis réessayez. + + + L’argument «{0}» n’appartient pas à l’ensemble «{1}» spécifié par l’attribut ValidateSet. Fournissez un argument qui se trouve dans le jeu, puis réessayez la commande. + + + Le générateur de valeurs valides renvoie une valeur nulle. + + + «{0}» a échoué sur la propriété «{1}» {2} + + + Impossible d’obtenir ou d’exécuter la commande. Le nombre maximal de jeux de paramètres pour cette commande a été dépassé. + + + Impossible de traiter l’argument, car la valeur de l’argument n’est pas une chaîne. Les valeurs des arguments de paramètre dont ArgumentTransformationAttribute est spécifié doivent être des chaînes. + + + Impossible de valider la variable, car la valeur {1} n’est pas une valeur valide pour la variable {0}. + + + Impossible d’ajouter l’attribut, car la variable {0} avec une valeur {1} n’est plus valide. + + + L’argument est nul. Fournissez une valeur valide pour l’argument, puis réessayez d’exécuter la commande. + + + L'argument a une valeur nulle, ou un élément de la collection d'arguments contient une valeur nul. Fournissez une collection ne contenant aucune valeur nul, puis réessayez la commande. + + + L'argument est nul ou vide. Fournissez un argument qui n'est ni nul ni vide, puis réessayez la commande. + + + L’argument est nul, vide ou un élément de la collection d’arguments contient une valeur nul. Fournissez une collection qui ne contient aucune valeur nul, puis réessayez la commande. + + + L’argument est nul, vide ou se compose uniquement de caractères d’espace blanc. Fournissez un argument qui contient des caractères autres que des espaces blancs, puis recommencez la commande. + + + Un élément de la collection d’arguments est nul, vide ou se compose uniquement de caractères d’espace blanc. Fournissez une collection qui ne contient aucune de ces valeurs, puis réessayez la commande. + + + Un paramètre portant le nom «{0}» a été défini plusieurs fois pour la commande. + + + Impossible de spécifier l’alias de paramètre, car un alias portant le nom «{0}» a déjà été défini plusieurs fois pour la commande. + + + Impossible de spécifier le paramètre «{0}», car il est en conflit avec l’alias de paramètre du même nom pour le paramètre «{1}». + + + Le script de validation «{1}» pour l’argument avec la valeur «{0}» n’a pas retourné le résultat True. Déterminez pourquoi le script de validation a échoué, puis réessayez la commande. + + + L’argument «{0}» ne contient pas de version PowerShell valide. Fournissez un numéro de version valide, puis recommencez la commande. + + + Impossible de valider l’argument «{0}», car il ne s’agit pas d’un nom de variable valide. + + + Le type de conversion de travail doit dériver de IAstToScriptBlockConverter. + + + L’argument de chemin d’accès n’est pas valide. Fournissez un argument de chemin d’accès qui est un type de chaîne. + + + Le lecteur d’argument de chemin d’accès {0} n’appartient pas à l’ensemble de lecteurs approuvés : {1}. Fournissez un argument de chemin d’accès avec un lecteur approuvé. + + + L’argument de chemin d’accès contient des caractères non valides. + + + L’argument de chemin d’accès n’a pas de lecteur racine. Fournissez un argument de chemin d’accès complet avec un lecteur racine. + + + La valeur d’argument du paramètre '{0}' ne peut pas être nul ou une chaîne vide. + + + Le membre Enum '{0}' n’est pas une valeur valide pour le paramètre '{1}'. Spécifiez l’un des membres suivants et réessayez : {2}. + + + Impossible de traiter l’entrée. L’argument «{0}» n’est pas approuvé. + + + Échec de la vérification d’attribut ValidateTrustedData + + + L’argument de paramètre «{0}» n’est pas approuvé et échoue à la vérification de l’attribut de paramètre ValidateTrustedData en mode langue contrainte. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/MiniShellErrors.fr.resx b/src/System.Management.Automation/resources/fr/MiniShellErrors.fr.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/MiniShellErrors.fr.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/Modules.fr.resx b/src/System.Management.Automation/resources/fr/Modules.fr.resx new file mode 100644 index 00000000000..ed6b95bdb54 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/Modules.fr.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Le module spécifié « {0} » n’a pas été chargé, car aucun fichier de module valide n’a été trouvé dans aucun répertoire de module. + + + Le module spécifié « {0} » avec la version « {1} » n’a pas été chargé, car aucun fichier de module valide n’a été trouvé dans aucun répertoire de module. + + + La valeur spécifiée pour MaximumVersion « {0} » est incorrecte. Si vous utilisez « * », MaximumVersion ne prend en charge qu’un seul « * » et doit toujours être placé à la fin de MaximumVersion. + + + Le module spécifié « {0} » avec MaximumVersion « {1} » n’a pas été chargé, car aucun fichier de module valide n’a été trouvé dans aucun répertoire de module. + + + Le module spécifié « {0} » avec MinimumVersion « {1} » et MaximumVersion « {2} » n’a pas été chargé, car aucun fichier de module valide n’a été trouvé dans aucun répertoire de module. + + + La valeur MinimumVersion « {0} » ne doit pas être supérieure à MaximumVersion « {1} ». + + + L’assembly « {0} » n’a pas été chargé, car aucun assembly portant ce nom n’a été trouvé. Vérifiez le nom de l’assembly, puis réessayez. + + + Le module à traiter « {0} », répertorié dans le champ « {1} » du manifeste du module « {2} », n’a pas été traité, car aucun module valide n’a été trouvé dans aucun répertoire de module. + + + Aucun objet personnalisé n’a été retourné pour le module « {0} » car le paramètre -AsCustomObject ne peut être utilisé qu’avec des modules de script. + + + Impossible de traiter le manifeste du module « {0} », car il ne s’agit pas d’un fichier manifeste de module PowerShell valide. Supprimez les éléments non autorisés : {1} + + + Le traitement du fichier manifeste du module « {0} » n’a pas abouti à un objet manifeste valide. Mettez à jour le fichier pour qu’il contienne un manifeste de module PowerShell valide. Vous pouvez créer un manifeste valide à l’aide de l’applet de commande New-ModuleManifest. + + + Impossible d’importer le module « {0} » car son manifeste contient un ou plusieurs membres non valides. Les membres de manifeste valides sont ({1}). Supprimez les membres non valides ({2}), puis réessayez d’importer le module. + + + La table de hachage décrivant un module contient un ou plusieurs membres non valides. Les membres valides sont ({0}). Supprimez les membres non valides ({1}), puis réessayez. + + + Impossible de charger le module « {0} », car la limite d’imbrication des modules a été dépassée. Les modules ne peuvent être imbriqués que jusqu’à {1} niveaux. Évaluez et modifiez l’ordre dans lequel vous chargez les modules pour éviter de dépasser la limite d’imbrication, puis réessayez d’exécuter votre script. + + + Le membre « ModuleVersion » n’est pas présent dans le manifeste du module. Ce membre doit exister et recevoir un numéro de version au format « n.n.n.n ». Ajoutez le membre manquant au fichier « {0} ». + + + Le membre « {0} » n’est pas valide dans le fichier manifeste du module « {2} » : {1} + + + La version « {0} » du module « {1} » ne répond pas à la version minimale requise « {2} ». Vérifiez que ce numéro de version est pris en charge, puis essayez de charger à nouveau le module. + + + La version de PowerShell installée sur cet ordinateur est « {0} ». Le module « {1} » nécessite une version minimale de PowerShell « {2} » pour s’exécuter. Vérifiez que la version minimale requise de PowerShell est installée, puis réessayez. + + + Le membre de manifeste du module « NestedModules » ne peut pas être utilisé si le membre « ModuleToProcess » est un module binaire. Modifiez le fichier manifeste du module dans « {0} », puis réessayez. + + + Le membre « {0} » dans le manifeste du module n’est pas valide : {1}. Vérifiez qu’une valeur valide est spécifiée pour ce champ dans le fichier « {2} ». + + + Le chemin d’accès au manifeste du module « {0} » n’est pas valide. La valeur de l’argument Path doit résoudre un seul fichier avec l’extension « .psd1 ». Modifiez la valeur de l’argument Path pour qu’il pointe vers un fichier psd1 valide, puis réessayez. + + + La clé ModuleVersion dans le manifeste du module « {0} » spécifie la version du module « {1} », qui ne correspond pas au nom de son dossier de version à l’emplacement « {2} ». Modifiez la valeur de la clé ModuleVersion pour qu’elle corresponde au nom du dossier de version. + + + L’entrée NestedModule spécifiée « {0} » dans le manifeste du module « {1} » n’est pas valide. Réessayez après avoir mis à jour cette entrée avec des valeurs valides. + + + L’entrée RequiredAssemblies spécifiée « {0} » dans le manifeste du module « {1} » n’est pas valide. Réessayez après avoir mis à jour cette entrée avec des valeurs valides. + + + L’entrée FileList spécifiée « {0} » dans le manifeste du module « {1} » n’est pas valide. Réessayez après avoir mis à jour cette entrée avec des valeurs valides. + + + L’entrée RequiredModules spécifiée « {0} » dans le manifeste du module « {1} » n’est pas valide. Réessayez après avoir mis à jour cette entrée avec des valeurs valides. + + + L’entrée ModuleList spécifiée « {0} » dans le manifeste du module « {1} » n’est pas valide. Réessayez après avoir mis à jour cette entrée avec des valeurs valides. + + + Le manifeste du module « {0} » est spécifié avec la clé CompatiblePSEditions, prise en charge uniquement sous PowerShell version « 5.1 » ou ultérieure. Mettez à jour la valeur de la clé PowerShellVersion à « 5.1 » ou une version ultérieure, puis réessayez. + + + La valeur spécifiée « {0} » pour CompatiblePSEditions contient des noms d’édition PowerShell en double. Réessayez après avoir supprimé les noms d’édition PowerShell en double. + + + La version spécifiée dans la clé ModuleVersion est identique au nom du dossier de version. + + + Le dossier Version {0} sous le module {1} est ignoré, car il ne contient pas de fichier manifeste de module valide. + + + Le membre « ModuleName » n’existe pas dans la table de hachage qui décrit ce module. + + + Les membres « ModuleVersion », « MaximumVersion » et « RequiredVersion » n’existent pas dans la table de hachage qui décrit ce module. L’un de ces trois membres doit exister et recevoir un numéro de version au format « n.n.n.n ». + + + Le module requis « {1} » n’est pas chargé. Chargez le module ou supprimez-le de « RequiredModules » dans le fichier « {0} ». + + + Le module requis « {1} » avec le GUID « {2} » n’est pas chargé. Chargez le module ou supprimez-le de « RequiredModules » dans le fichier « {0} ». + + + Le module requis « {1} » avec la version « {2} » n’est pas chargé. Chargez le module ou supprimez-le de « RequiredModules » dans le fichier « {0} ». + + + Le module requis « {1} » avec MaximumVersion « {2} » n’est pas chargé. Chargez le module ou supprimez-le de « RequiredModules » dans le fichier « {0} ». + + + Le module requis « {1} » avec MinimumVersion « {2} » et MaximumVersion « {3} » n’est pas chargé. Chargez le module ou supprimez-le de « RequiredModules » dans le fichier « {0} ». + + + Le module « {0} » est introuvable avec ModuleVersion « {1} ». + + + Le module « {0} » est introuvable avec RequiredVersion « {1} ». + + + Le module « {0} » est introuvable avec MaximumVersion « {1} ». + + + Le module « {0} » est introuvable avec ModuleVersion « {1} » et MaximumVersion « {2} ». + + + Le module « {0} » est introuvable. + + + Aucun module n’a été supprimé. Vérifiez que la spécification des modules à supprimer est correcte et que ces modules existent dans l’instance d’exécution. + + + Impossible de supprimer le membre « {0} » importé à partir du module « {1} » pour la raison suivante : {2} + + + Impossible de supprimer le module « {0} » car il est en lecture seule. Ajoutez le paramètre Force à votre commande pour supprimer les modules en lecture seule. + + + Impossible de supprimer le module « {0} » car il est marqué comme « constant ». Un module ne peut pas être supprimé s’il est marqué comme « constant ». + + + Impossible de supprimer le module « {0} », car il est requis par « {1} ». Ajoutez le paramètre Force à votre commande pour supprimer le module. + + + La cmdlet Export-ModuleMember ne peut être appelée qu’à partir d’un module. + + + L’extension « {0} » n’est pas une extension de module valide. Les extensions de module prises en charge sont « .dll », « .ps1 », « .psm1 », « .psd1 » et « .cdxml ». Corrigez l’extension, puis essayez d’ajouter de nouveau le fichier « {1} ». + + + Cette opération ne peut pas être effectuée sur un module binaire. Elle ne peut être effectuée que sur un module de script. + + + Le fichier « {0} » n’est pas autorisé, car il n’a pas l’extension « .ps1 ». + + + Inconnu + + + (c) {0}. Tous droits réservés. + + + Suppression de la fonction « {0} » importée. + + + Suppression de l’alias « {0} » importé. + + + Suppression de la variable importée « {0} ». + + + Chargement du module depuis le chemin d’accès « {0} ». + + + Chargement de « {0} » à partir du chemin d’accès « {1} ». + + + Dot-sourcing du fichier de script « {0} ». + + + Importation de la fonction « {0} ». + + + Importation de la cmdlet « {0} ». + + + Importation de l’alias « {0} ». + + + Importation de la variable « {0} ». + + + Exportation de l’applet de commande « {0} ». + + + Exportation de la fonction « {0} ». + + + Exportation de l’alias « {0} ». + + + Exportation de la variable « {0} ». + + + Les noms de certaines commandes importées depuis le module « {0} » incluent des verbes non approuvés, ce qui peut les rendre moins faciles à découvrir. Pour trouver les commandes qui utilisent des verbes non approuvés, exécutez de nouveau la commande Import-Module avec le paramètre Verbose. Pour obtenir la liste des verbes approuvés, tapez Get-Verb. + + + La commande « {0} » dans le module « {1} » a été importée, mais comme son nom n’inclut pas de verbe approuvé, elle peut être difficile à trouver. Pour obtenir la liste des verbes approuvés, tapez Get-Verb. + + + La commande « {0} » dans le module « {2} » a été importée, mais comme son nom n’inclut pas de verbe approuvé, elle peut être difficile à trouver. Les verbes alternatifs suggérés sont « {1} ». + + + Certains noms de commandes importés contiennent un ou plusieurs des caractères restreints suivants : # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Le nom de commande « {0} » du module « {1} » contient un ou plusieurs des caractères restreints suivants : # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Création du fichier manifeste du module « {0} ». + + + {0} (chemin d’accès : « {1} ») + + + L’architecture actuelle du processeur est : {0}. Le module « {1} » nécessite l’architecture suivante : {2}. + + + Le nom de l’hôte PowerShell actuel est : « {0} ». Le module « {1} » nécessite l’hôte PowerShell suivant : « {2} ». + + + L’hôte PowerShell actuel est : « {0} » (version {1}). Le module « {2} » nécessite une version minimale de l’hôte PowerShell « {3} » pour s’exécuter. + + + Manifeste du module « {0} » + + + Généré par : {0} + + + Généré le : {0} + + + Module de script ou fichier de module binaire associé à ce manifeste. + + + Modules à importer en tant que modules imbriqués du module spécifié dans RootModule/ModuleToProcess + + + ID utilisé pour identifier ce module de manière unique + + + Auteur de ce module + + + Société ou fournisseur de ce module + + + Déclaration de copyright pour ce module + + + Numéro de version de ce module. + + + Description de la fonctionnalité fournie par ce module + + + Version minimale du moteur PowerShell requise par ce module + + + Version minimale du CLR (Common Language Runtime) requise par ce module. {0} + + + Modules qui doivent être importés dans l’environnement global avant l’importation de ce module + + + Fichiers de script (.ps1) exécutés dans l’environnement de l’appelant avant l’importation de ce module. + + + Fichiers de type (.ps1xml) à charger lors de l’importation de ce module + + + Fichiers de format (.ps1xml) à charger lors de l’importation de ce module + + + Assemblys qui doivent être chargés avant l’importation de ce module + + + Liste de tous les fichiers empaquetés avec ce module + + + Données privées à transmettre au module spécifié dans RootModule/ModuleToProcess. Cela peut également contenir une table de hachage PSData avec des métadonnées de module supplémentaires utilisées par PowerShell. + + + Balises appliquées à ce module. Elles aident à la découverte de modules dans les galeries en ligne. + + + URL du site web principal de ce projet. + + + URL de la licence de ce module. + + + URL d’une icône représentant ce module. + + + Notes de publication de ce module + + + Chaîne de préversion de ce module + + + Indique si le module nécessite une acceptation explicite de l’utilisateur pour l’installation, la mise à jour ou l’enregistrement + + + Modules dépendants externes de ce module + + + Fin de la table de hachage {0} + + + La valeur du paramètre PrivateData doit être une table de hachage pour créer le manifeste du module avec les valeurs de paramètre suivantes : Tags, ProjectUri, LicenseUri, IconUri ou ReleaseNotes. Supprimez les valeurs des paramètres Tags, ProjectUri, LicenseUri, IconUri ou ReleaseNotes, ou enveloppez le contenu de PrivateData dans une table de hachage. + + + PrivateData doit être défini comme une table de hachage, mais ce manifeste de module le définit comme un objet. Envisagez d’envelopper le contenu de PrivateData dans une table de hachage. Cela vous permettra d’ajouter ultérieurement les propriétés Tags, ProjectUri, LicenseUri, IconUri et ReleaseNotes au manifeste du module. + + + La valeur spécifiée « {0} » n’est pas valide. Réessayez avec une valeur valide. + + + Fonctions à exporter à partir de ce module. Pour de meilleures performances, n’utilisez pas de caractères génériques et ne supprimez pas l’entrée. Utilisez un tableau vide s’il n’y a aucune fonction à exporter. + + + Les alias à exporter à partir de ce module. Pour de meilleures performances, n’utilisez pas de caractères génériques et ne supprimez pas l’entrée. Utilisez un tableau vide s’il n’y a aucun alias à exporter. + + + Cmdlets à exporter à partir de ce module. Pour de meilleures performances, n’utilisez pas de caractères génériques et ne supprimez pas l’entrée. Utilisez un tableau vide s’il n’y a aucune cmdlet à exporter. + + + Variables à exporter depuis ce module + + + Ressources DSC à exporter depuis ce module + + + Éditions PowerShell prises en charge + + + Architecture du processeur (None, X86, Amd64) requise par ce module + + + Liste de tous les modules empaquetés avec ce module + + + Version minimale de Microsoft .NET Framework requise par ce module. {0} + + + Nom de l’hôte PowerShell requis par ce module + + + Version minimale de l’hôte PowerShell requis par ce module + + + URI HelpInfo de ce module + + + Étant donné que le module {0} fournit le PSDrive dans la session PowerShell actuelle, aucun module n’a été supprimé. Modifiez le fournisseur PSDrive actuel, puis réessayez de supprimer des modules. + + + La cmdlet « {0} » n’a pas été importée, car un membre portant le même nom existe dans l’étendue actuelle. + + + L’alias « {0} » n’a pas été importé, car un membre portant le même nom existe dans l’étendue actuelle. + + + La fonction « {0} » n’a pas été importée, car un membre portant le même nom existe dans l’étendue actuelle. + + + La variable « {0} » n’a pas été importée, car un membre portant le même nom existe dans l’étendue actuelle. + + + Les caractères génériques ne sont pas autorisés dans les membres « ModuleToProcess », « RootModule » ou « NestedModules » du manifeste du module « {0} ». + + + Le module « {0} » est un module de base pour PowerShell. Ajoutez le paramètre Force à votre commande pour supprimer les modules de base. + + + Le manifeste du module ne peut pas contenir à la fois les membres « ModuleToProcess » et « RootModule ». Modifiez le fichier manifeste du module pour supprimer l’un de ces membres dans « {0} », puis réessayez. + + + Le membre du manifeste de module « ModuleToProcess » est déconseillé. Utilisez le membre « RootModule » à la place. + + + Préfixe par défaut des commandes exportées à partir de ce module. Remplacez le préfixe par défaut à l’aide de Import-Module -Prefix. + + + Les paramètres « Global » et « Scope » ne peuvent pas être spécifiés ensemble. Supprimez l’un de ces paramètres, puis réessayez d’exécuter la commande. + + + Le module requis « {0} » n’est pas chargé. Le module « {0} » a un requiredModule « {1} » dans son manifeste de module « {2} » qui pointe vers une dépendance cyclique. + + + Le module requis « {0} » n’a pas été chargé, car aucun fichier de module valide n’a été trouvé dans aucun répertoire de module. + + + Certaines commandes du module {0} ne peuvent pas être importées via une CimSession. Pour obtenir toutes les commandes, vérifiez que la gestion distante PowerShell est activée sur le serveur distant, puis essayez d’ajouter le paramètre PSSession à la cmdlet Import-Module. + + + Le module {0} est chargé dans Windows PowerShell à l’aide d’une session de remoting {1} ; notez que toutes les entrées et sorties des commandes de ce module seront des objets désérialisés. Si vous souhaitez charger ce module dans PowerShell, utilisez la syntaxe « Import-Module -SkipEditionCheck ». + + + Windows PowerShell, version {0}. Windows PowerShell 5.1 est requis pour charger des modules à l’aide de la fonctionnalité de compatibilité Windows PowerShell. Installez Windows Management Framework (WMF) 5.1 à partir de https://aka.ms/WMF5Download pour activer cette fonctionnalité. + + + Le chargement du module « {0} » à l’aide de la fonctionnalité de compatibilité Windows PowerShell est bloqué par un paramètre « WindowsPowerShellCompatibilityModuleDenyList » dans le fichier de configuration PowerShell. + + + Impossible d’importer le module {0} sur une session CimSession. Essayez d’utiliser le paramètre PSSession de la cmdlet Import-Module. + + + La valeur d’architecture de processeur de {0} n’est pas prise en charge. Réexécutez la commande New-ModuleManifest en spécifiant l’une des valeurs d’énumération prises en charge suivantes pour l’architecture de processeur : None, MSIL, X86, Amd64, Arm + + + L’exécution de la cmdlet Get-Module sur un ordinateur distant peut uniquement répertorier les modules disponibles. Ajoutez le paramètre ListAvailable à votre commande, puis réessayez. + + + Le module « {0} » n’a pas été importé, car le composant logiciel enfichable « {0} » avait déjà été importé. + + + Les caractères génériques ne sont pas autorisés dans le membre « RequiredAssemblies » du manifeste du module « {0} ». + + + La valeur de la clé {0} dans {1} est {2} et le module contient des modules imbriqués. Lorsqu’un fichier CDXML est le module racine, la commande Import-Module échoue, car les commandes des modules imbriqués ne peuvent pas être exportées. Déplacez le fichier CDXML vers la clé NestedModules, puis réessayez la commande. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Échec de la commande distante : {0} : {{0}} + + + Échec de la génération des proxys pour le module distant « {0} ». {{0}} + + + Échec du traitement du module distant {0}. {1} + + + Échec de la réception des données du module à partir de la CimSession distante. {0} + + + Le module requis « {0} » avec le GUID « {1} » et la version « {2} » n’a pas été chargé, car aucun fichier de module valide n’a été trouvé dans aucun répertoire de module. + + + Un fournisseur CIM pour la découverte de modules est introuvable sur le serveur CIM. {0} + {0} is a placeholder for a more detailed error message + + + Impossible de vérifier la version de Microsoft .NET Framework {0}, car elle ne figure pas dans la liste des versions autorisées. + + + Analyse de {0}. + {0} should not be localized, is used to contain a file path. + + + Préparation des modules pour la première utilisation. + + + Recherche des modules disponibles + + + Recherche du partage UNC {0}. + {0} should not be localized, is used to contain a file path. + + + L’utilisation de la cmdlet Get-Module sur un ordinateur distant n’est possible que pour les noms de module qui n’incluent pas de chemin d’accès. Le paramètre Name contient l’élément « {0} », qui se résout en chemin d’accès. Mettez à jour le paramètre Name pour qu’il ne contienne pas d’éléments de chemin d’accès, puis réessayez. + + + L’utilisation de l’applet de commande Get-Module sans le paramètre ListAvailable n’est pas prise en charge pour les noms de module qui incluent un chemin d’accès. Le paramètre Name contient l’élément « {0} », qui se résout en chemin d’accès. Mettez à jour le paramètre Name pour qu’il ne contienne pas d’éléments de chemin d’accès, puis réessayez. + + + Le module spécifié « {0} » est introuvable. Mettez à jour le paramètre Name pour qu’il pointe vers un chemin valide, puis réessayez. + + + Remplissage de la propriété RepositorySourceLocation pour le module {0}. + + + Le module à traiter « {0} », répertorié dans le champ « {1} » du manifeste du module « {2} », n’a pas été traité. {3} + + + Cette condition préalable est valide uniquement pour l’édition PowerShell Desktop. + + + Le module « {0} » ne prend pas en charge l’édition actuelle de PowerShell « {1} ». Les éditions prises en charge sont « {2} ». Utilisez « Import-Module -SkipEditionCheck » pour ignorer la compatibilité de ce module. + + + Le module « {0} » prend en charge l’édition PowerShell « {1} » et ne peut pas être chargé implicitement à l’aide de la fonctionnalité de compatibilité Windows, car celle-ci est désactivée dans le fichier de paramètres. Utilisez « Import-Module -UseWindowsPowerShell » pour charger ce module avec Windows PowerShell ou « Import-Module -SkipEditionCheck » pour essayer de le charger avec la version actuelle de PowerShell. + + + Une valeur de chaîne non vide doit être spécifiée pour une fonctionnalité expérimentale déclarée dans le manifeste du module. + + + Un ou plusieurs noms de fonctionnalité expérimentale non valides ont été trouvés : {0}. Un nom de fonctionnalité expérimentale de module doit suivre cette convention : « ModuleName.FeatureName ». + + + Le paramètre de commutateur -SkipEditionCheck ne peut pas être utilisé sans le paramètre de commutateur -ListAvailable. + + + L’importation de fichiers *.ps1 en tant que modules n’est pas autorisée en mode ConstrainedLanguage. + + + Une erreur s’est produite lors du chargement du module de script {0}, car son mode de langage est différent de celui du manifeste du module. Le mode de langage du manifeste est {1} et le mode de langage du module est {2}. Vérifiez que tous les fichiers du module sont signés ou qu’ils font partie de la configuration de la liste d’autorisation de votre application. + + + Ce module utilise l’opérateur dot-source lors de l’exportation de fonctions à l’aide de caractères génériques, ce qui n’est pas autorisé lorsque le système est soumis à obligation de vérification des applications. + + + Impossible d’exporter des membres de module à partir d’un module dont le mode de langage est différent de celui de la session en cours. + + + Impossible de créer un nouveau module tant que la session est en mode ConstrainedLanguage. + + + Impossible de trouver le module intégré « {0} » compatible avec l’édition « Core ». Vérifiez que les modules intégrés PowerShell sont disponibles. Ils sont généralement fournis avec le package PowerShell sous le chemin de module $PSHOME, et sont nécessaires au bon fonctionnement de PowerShell. + + + Cmdlet Export-ModuleMember + + + L’exportation des membres du module échouera en mode de langage contraint, car le module « {0} » a un mode de langage « {1} » différent du mode de la session actuelle « {2} ». + + + Exportation implicite des fonctions du module + + + L’exportation implicite de fonctions pour le module « {0} » sera refusée, car il est approuvé (il s’exécute en mode de langage complet), mais la session ne l’est pas (elle s’exécute en mode de langage contraint). Il est recommandé d’exporter systématiquement les fonctions du module individuellement, avec leur nom complet. + + + Importation du fichier de script en tant que module + + + L’importation du fichier de script « {0} » en tant que module ne sera pas autorisée en mode ConstrainedLanguage. + + + Le module contient un opérateur Dot-Source + + + L’importation du module « {0} » échouera en mode de langage contraint, car il exporte des fonctions à l’aide de caractères génériques tout en utilisant l’opérateur dot-source. + + + « Fonctions d’exportation de module + + + Le module « {0} » exporte des fonctions à l’aide de caractères génériques dans le nom. Tous les noms de fonctions des modules imbriqués seront supprimés lors de l’exécution en mode de langage contraint. + + + «Cmdlet New-Module + + + Un nouveau module provenant d’une session de langage contraint non approuvée sera empêché de fournir le bloc de script FullLanguage. + + + « Modes de langage incompatibles avec les modules + + + Un module dépendant est en cours de chargement avec un mode de langue différent de celui du module parent. Cela ne sera pas autorisé en mode de langage contraint. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/MshHostRawUserInterfaceStrings.fr.resx b/src/System.Management.Automation/resources/fr/MshHostRawUserInterfaceStrings.fr.resx new file mode 100644 index 00000000000..e6a4fec55de --- /dev/null +++ b/src/System.Management.Automation/resources/fr/MshHostRawUserInterfaceStrings.fr.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} » ne peut pas être supérieur ou égal à « {1} ». + + + « {0} » doit être un nombre positif. + + + Toutes les chaînes sont nulles ou vides. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/MshSignature.fr.resx b/src/System.Management.Automation/resources/fr/MshSignature.fr.resx new file mode 100644 index 00000000000..a835c019157 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/MshSignature.fr.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 + + + Signature vérifiée. + + + Le fichier {0} n’est pas signé numériquement. Vous ne pouvez pas exécuter ce script sur le système actuel. Pour plus d’informations sur l’exécution des scripts et la définition de la stratégie d’exécution, consultez about_Execution_Policies à l’adresse https://go.microsoft.com/fwlink/?LinkID=135170 + + + Le contenu du fichier {0} a peut-être été modifié par un utilisateur ou un processus non autorisé, car le hachage du fichier ne correspond pas au hachage stocké dans la signature numérique. Le script ne peut pas s’exécuter sur le système spécifié. Pour plus d’informations, exécutez Get-Help about_Signing. + + + Le fichier {0} est signé, mais le signataire n’est pas approuvé sur ce système. + + + Nous ne pouvons pas signer le fichier, car le système ne prend pas en charge les opérations de signature sur {0} fichiers. + + + Nous ne pouvons pas signer le fichier, car le système ne prend pas en charge les opérations de signature sur les fichiers qui n’ont pas d’extension de nom de fichier. + + + La signature ne peut pas être vérifiée, car elle est incompatible avec le système actuel. + + + La signature ne peut pas être vérifiée, car elle est incompatible avec le système actuel. L’algorithme de hachage n’est pas valide. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/MshSnapInCmdletResources.fr.resx b/src/System.Management.Automation/resources/fr/MshSnapInCmdletResources.fr.resx new file mode 100644 index 00000000000..db1dce9a7c9 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/MshSnapInCmdletResources.fr.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 + + + L’opération ne peut pas être effectuée. L’applet de commande spécifiée n’est pas prise en charge dans un interpréteur de commandes personnalisé. + + + Aucun composant logiciel enfichable PowerShell correspondant au modèle « {0} » n’a été trouvé. Vérifiez le modèle, puis réessayez la commande. + + + Le format du nom du composant logiciel enfichable spécifié n’était pas valide. Les noms des composants logiciels enfichables PowerShell ne peuvent contenir que des caractères alphanumériques, des tirets, des traits de soulignement et des points. Corrigez le nom, puis retentez l'opération. + + + Nous ne pouvons pas ajouter le composant logiciel enfichable PowerShell {0}, car il s’agit d’un module PowerShell système. Utilisez Import-Module pour charger le module. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/MshSnapinInfo.fr.resx b/src/System.Management.Automation/resources/fr/MshSnapinInfo.fr.resx new file mode 100644 index 00000000000..9adf5d87b7c --- /dev/null +++ b/src/System.Management.Automation/resources/fr/MshSnapinInfo.fr.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 + + + Nous ne pouvons pas accéder aux informations du Registre de PowerShell. + + + Nous ne pouvons pas accéder aux informations du Registre du moteur PowerShell. + + + Nous ne pouvons pas accéder aux informations de PublicKeyToken. + + + La version {0} de PowerShell n’est pas disponible sur cet ordinateur. + + + Le composant logiciel enfichable PowerShell « {0} » n’est pas installé sur cet ordinateur. + + + La valeur obligatoire {0} n’est pas spécifiée pour la clé de Registre {1}. + + + La valeur obligatoire {0} n’est pas au format correct pour la clé de Registre {1}. Le format attendu est « chaîne ». + + + La valeur obligatoire {0} n’est pas au format correct pour la clé de Registre {1}. Le format attendu est « multistring ». + + + Nous ne pouvons pas trouver les informations requises dans le Registre ou certains fichiers de clé sont manquants. Nous ne pouvons pas charger certaines applets de commande. + + + Aucun composant logiciel enfichable n’a été inscrit pour la version {0}de PowerShell. + + + Nous ne pouvons pas extraire la ressource de chaîne car le lecteur a été supprimé. + + + La valeur de version {0} n’est pas spécifiée ou est incorrecte pour la clé de Registre {1}. + + + Aucun attribut [PSVersion] n’a été trouvé pour le type PowerShell {0}. Ajoutez un attribut PSVersion au type à l’aide de [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/NativeCP.fr.resx b/src/System.Management.Automation/resources/fr/NativeCP.fr.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/NativeCP.fr.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PSCommandStrings.fr.resx b/src/System.Management.Automation/resources/fr/PSCommandStrings.fr.resx new file mode 100644 index 00000000000..66bcd169b3f --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PSCommandStrings.fr.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 + + + Une commande est requise pour ajouter un paramètre. Vous devez ajouter une commande à {0} avant d’ajouter un paramètre. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PSConfigurationStrings.fr.resx b/src/System.Management.Automation/resources/fr/PSConfigurationStrings.fr.resx new file mode 100644 index 00000000000..30ee6c66a25 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PSConfigurationStrings.fr.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 + + + PowerShell a cessé de fonctionner en raison d’un problème de sécurité : impossible de lire le fichier de configuration : {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PSDataBufferStrings.fr.resx b/src/System.Management.Automation/resources/fr/PSDataBufferStrings.fr.resx new file mode 100644 index 00000000000..281199e7aff --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PSDataBufferStrings.fr.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 + + + L’index spécifié est inférieur à zéro ou supérieur au nombre d’éléments dans le tampon. L’index doit se trouver dans la plage {0}-{1}. + + + Nous ne pouvons pas convertir une référence nulle en type valeur. + + + Nous ne pouvons pas convertir la valeur du type {0} en type {1}. + + + Nous ne pouvons pas ajouter de nouveaux objets à un magasin fermé. Vérifiez que le tampon est ouvert pour que les opérations d’ajout et d’insertion réussissent. + + + La propriété SerializeInput ne peut être définie que pour le type PSObject de PSDataCollection. Définissez la propriété SerializeInput sur false, ou remplacez le type de collection par PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PSListModifierStrings.fr.resx b/src/System.Management.Automation/resources/fr/PSListModifierStrings.fr.resx new file mode 100644 index 00000000000..614c76a6386 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PSListModifierStrings.fr.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 + + + Le modificateur de liste inconnu suivant a été détecté : « {0} ». Les modificateurs de liste valides sont Add, Remove et Replace. + + + Nous ne pouvons pas appliquer la mise à jour, car l’objet n’est pas un type de collection pris en charge. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PSStyleStrings.fr.resx b/src/System.Management.Automation/resources/fr/PSStyleStrings.fr.resx new file mode 100644 index 00000000000..de8f9ab0c54 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PSStyleStrings.fr.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La chaîne spécifiée contient du contenu imprimable alors qu’elle ne devrait contenir que des séquences d’échappement ANSI : {0} + + + La valeur MaxWidth pour le rendu de progression doit être d’au moins 18 pour s’afficher correctement. + + + Lors de l’ajout ou de la suppression d’extensions, l’extension doit commencer par un point. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ParameterBinderStrings.fr.resx b/src/System.Management.Automation/resources/fr/ParameterBinderStrings.fr.resx new file mode 100644 index 00000000000..8426323ccfa --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ParameterBinderStrings.fr.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nous ne pouvons pas trouver un paramètre qui correspond au nom de paramètre « {1} ». + + + Nous ne pouvons pas trouver un paramètre positionnel qui accepte l’argument « {1} ». + + + Argument manquant pour le paramètre « {1} ». Indiquez un paramètre de type « {2} », puis réessayez. + + + Nous ne pouvons pas traiter le paramètre, car le nom du paramètre « {1} » est ambigu. Correspondances possibles :{6}. + + + Nous ne pouvons pas convertir « {6} » en type « {2} », requis par le paramètre « {1} ». {7} + + + Nous ne pouvons pas lier le paramètre « {1} ». {6} + + + Nous ne pouvons pas lier les paramètres positionnels « {1} ». + + + Nous ne pouvons pas lier les paramètres positionnels, car aucun nom n’a été fourni. + + + Impossible de résoudre le jeu de paramètres à l'aide des paramètres nommés indiqués. Un ou plusieurs paramètres fournis ne peuvent pas être utilisés ensemble ou un nombre insuffisant de paramètres a été fourni. + + + Nous ne pouvons pas traiter la commande, car un ou plusieurs paramètres obligatoires sont manquants :{1}. + + + Le paramètre « {1} » ne peut pas être spécifié dans le jeu de paramètres « {6} ». + + + Nous ne pouvons pas lier le paramètre, car le paramètre « {1} » est spécifié plusieurs fois. Pour fournir plusieurs valeurs aux paramètres qui acceptent plusieurs valeurs, utilisez la syntaxe de tableau. Par exemple, « -parameter value1,value2,value3 ». + + + Nous ne pouvons pas évaluer le paramètre « {1} », car son argument est spécifié sous forme de bloc de script et qu’il n’y a pas d’entrée. Un bloc de script ne peut pas être évalué sans entrée. + + + La saisie dans le bloc de script pour le paramètre « {1} » a échoué. {6} + + + Nous ne pouvons pas évaluer le paramètre « {1} », car l’entrée de son argument n’a produit aucune sortie. + + + L’objet d’entrée ne peut être lié à aucun paramètre de la commande, soit parce que la commande n’accepte pas d’entrée de pipeline, soit parce que l’entrée et ses propriétés ne correspondent à aucun des paramètres qui acceptent l’entrée de Pipeline. + + + L’objet d’entrée ne peut pas être lié, car il ne contenait pas les informations nécessaires pour lier tous les paramètres obligatoires : {6} + + + Nous ne pouvons pas traiter l’entrée de Pipeline, car la valeur par défaut du paramètre « {1} » ne peut pas être récupérée. {6} + + + Nous ne pouvons pas récupérer les paramètres dynamiques pour l’applet de commande. {6} + + + Fournissez des valeurs pour les paramètres suivants : + + + L’applet de commande {0} à la position du pipeline de commande {1} + + + Nous ne pouvons pas traiter la transformation d’argument sur le paramètre « {1} ». {6} + + + {6} + + + Impossible de valider l’argument sur le paramètre « {1} ». {6} + + + Nous ne pouvons pas lier le paramètre « {1} » à la cible. {6} + + + Nous ne pouvons pas lier l’argument au paramètre « {1} », car il s’agit d’une valeur nulle. + + + Nous ne pouvons pas lier l’argument au paramètre « {1} », car il s’agit d’une chaîne vide. + + + Nous ne pouvons pas lier l’argument au paramètre « {1} », car il s’agit d’une collection vide. + + + Nous ne pouvons pas lier l’argument au paramètre « {1} », car il s’agit d’un tableau vide. + + + Nous ne pouvons pas traiter la commande. Le paramètre « {0} » est défini plusieurs fois. + + + Impossible de lier l’applet de commande {0}, car le paramètre « {1} » est de type « {2} » et la méthode Add() ne peut pas être identifiée, ou plusieurs méthodes Add() existent. {6} + + + Nous ne pouvons pas lier l’applet de commande {0}, car le paramètre défini à l’exécution « {1} » a été ajouté au RuntimeDefinedParameterDictionary avec la clé « {6} ». La clé doit être identique à RuntimeDefinedParameter.Name. + + + Nous ne pouvons pas lier l’argument au paramètre « {1} », car les PSTypeNames de l’argument ne correspondent pas au PSTypeName requis par le paramètre : {6}. + + + Plusieurs valeurs par défaut différentes sont définies dans $PSDefaultParameterValues pour le paramètre correspondant au nom ou alias suivant : {0}. Ces valeurs par défaut ont été ignorées. + + + Le nom ou alias suivant défini dans $PSDefaultParameterValues pour cette applet de commande correspond à plusieurs paramètres : {0}. La valeur par défaut a été ignorée. + + + {6} Cette erreur peut être due à l’application de la liaison de paramètres par défaut. Vous pouvez désactiver cette liaison dans $PSDefaultParameterValues en définissant $PSDefaultParameterValues["Disabled"] sur $true, puis réessayer. Les paramètres par défaut suivants ont été liés avec succès pour cette applet de commande lorsque l’erreur s’est produite :{7} + + + {6} Cet échec peut être dû à l’application de la liaison de paramètres par défaut. Vous pouvez désactiver cette liaison dans $PSDefaultParameterValues en définissant $PSDefaultParameterValues["Disabled"] sur $true, puis réessayer. Le paramètre par défaut suivant a été lié avec succès pour cette applet de commande lorsque l’erreur s’est produite :{7} + + + La liaison de la valeur par défaut « {0} » au paramètre « {1} » a échoué : {2} + + + Le format de la clé « {0} » n’est pas valide. Pour plus d’informations sur le format correct, consultez about_Parameters_Default_Values à l’adresse https://go.microsoft.com/fwlink/?LinkId=228266. + + + Les clés « {0} » n’ont pas de format valide. Pour plus d’informations sur le format correct, consultez about_Parameters_Default_Values à l’adresse https://go.microsoft.com/fwlink/?LinkId=228266. + + + Le paramètre « {0} » est obsolète. {1} + + + La clé « {0} » de type « {1} » n’est pas une valeur de chaîne. DefaultParameterDictionary n’accepte que des clés de type chaîne. + + + La clé « {0} » a déjà été ajoutée au dictionnaire. + + + Appel de méthode ou de propriété non autorisé + + + L’appel d’une méthode ou d’une propriété « {0} » sur le type « {1} » n’est pas autorisé en mode de langage contraint pour les scripts non approuvés. + + + Création de type non autorisée + + + La création du type « {0} » n’est pas autorisée lors de la liaison de paramètres en mode de langage contraint pour les scripts non approuvés. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ParserStrings.fr.resx b/src/System.Management.Automation/resources/fr/ParserStrings.fr.resx new file mode 100644 index 00000000000..f4e242eca9a --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ParserStrings.fr.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Impossible de charger l'assembly '{0}'. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PathUtilsStrings.fr.resx b/src/System.Management.Automation/resources/fr/PathUtilsStrings.fr.resx new file mode 100644 index 00000000000..c835bc05bd5 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PathUtilsStrings.fr.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + L’encodage « UTF-7 » est obsolète. Veuillez utiliser UTF-8. + + + Le fichier {0} existe déjà et {1} a été spécifié. + + + Nous ne pouvons ouvrir aucun fichier, car le fournisseur actuel ({0}) ne peut pas les ouvrir. + + + Nous ne pouvons pas effectuer l’opération, car le chemin d’accès a été résolu en plusieurs fichiers. Cette commande ne peut pas s’exécuter sur plusieurs fichiers. + + + Nous ne pouvons pas effectuer l’opération, car le chemin d’accès contenant des caractères génériques {0} n’a pas été résolu en un fichier. + + + Encodage inconnu {0}, les valeurs valides sont {1}. + + + Le répertoire « {0} » existe déjà. Utilisez le paramètre -Force si vous voulez remplacer le répertoire et les fichiers qu’il contient. + + + Le chemin d’accès du module utilisateur n’existe pas. Nous ne pouvons par conséquent pas créer un dossier de module pour le nom de module fourni « {0} ». + + + Nous ne pouvons pas créer le module {0} pour la raison suivante : {1}. Utilisez un autre argument pour le paramètre -OutputModule, puis réessayez. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Nous ne pouvons pas charger le module, car il a été généré avec une version incompatible de la cmdlet {0}. Générez le module avec la cmdlet {0} à partir de la session actuelle, puis essayez de recharger le module. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PipelineStrings.fr.resx b/src/System.Management.Automation/resources/fr/PipelineStrings.fr.resx new file mode 100644 index 00000000000..2e191b5583c --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PipelineStrings.fr.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impossible de traiter l’instance d’applet de commande, car l’instance d’applet de commande est utilisée par un autre pipeline. Contactez les services de support technique Microsoft. + + + Impossible d’effectuer l’opération, car le pipeline est démarré. Arrêtez le pipeline et recommencez l’opération. + + + Impossible de continuer à exécuter l’applet de commande, car l’exécution des applets de commande a été empêchée par la stratégie d’arrêt. + + + Impossible d’exécuter le pipeline, car la première applet de commande du pipeline tente de lire l’entrée à partir des résultats d’une applet de commande précédente. Modifiez la première applet de commande, supprimez la première applet de commande ou ajoutez au pipeline l’applet de commande dont la sortie est requise par la première applet de commande, puis réessayez d’exécuter le pipeline. + + + Impossible de traiter le numéro d’applet de commande. La fonction ReadFromCommand doit spécifier l'identifiant d'une cmdlet qui a déjà été ajoutée au pipeline. Contactez les services de support technique Microsoft. + + + Impossible de lire la sortie des fonctions ReadFromCommand et ReadErrorQueue, car une autre applet de commande lit déjà cette sortie. Contactez les services de support technique Microsoft. + + + Impossible d’exécuter le pipeline, car il n’existe aucune commande. Ajoutez au moins une commande au pipeline, puis exécutez-la à nouveau. + + + Impossible de terminer l’opération de pipeline, car elle n’a pas encore été démarrée. Vous devez appeler la méthode Begin() avant d'appeler End() sur un pipeline pas à pas. + + + Les méthodes WriteObject et WriteError ne peuvent pas être appelées à partir de l’extérieur des remplacements des méthodes BeginProcessing, ProcessRecord et EndProcessing, et elles ne peuvent être appelées qu’à partir du même thread. Vérifiez que l’applet de commande effectue correctement ces appels ou contactez les services de support technique Microsoft. + + + Une applet de commande a levé une exception après avoir appelé ThrowTerminatingError. +La première exception était «{0}» avec la trace de pile «{1}». +La deuxième exception était «{2}» avec la trace de pile «{3}». + + + Les méthodes WriteObject et WriteError ne peuvent pas être appelées après la fermeture du pipeline. Contactez les services de support technique Microsoft. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Une erreur s’est produite lors de la création du pipeline. + + + Ce pipeline ne prend pas en charge la sémantique de déconnexion-connexion. + + + Impossible de connecter ce pipeline, car il n’est pas à l’état déconnecté. + + + L'objet d'espace d'exécution est associé à une commande distante nulle. Impossible de créer un objet RemotePipeline déconnecté, car aucune commande distante n’est spécifiée. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/PowerShellStrings.fr.resx b/src/System.Management.Automation/resources/fr/PowerShellStrings.fr.resx new file mode 100644 index 00000000000..7474d75f0a8 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/PowerShellStrings.fr.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 + + + L’état de l’instance PowerShell actuelle n’est pas valide pour cette opération. + + + Nous ne pouvons pas effectuer l’opération, car une commande a déjà été lancée. Attendez que la commande ait fini de s’arrêter, ou arrêtez-la, puis réessayez. + + + Aucune commande n’est pas spécifiée. + + + L’état de l’instance PowerShell n’est pas correct pour créer une instance PowerShell imbriquée. Les instances PowerShell imbriquées ne doivent être créées que dans une instance PowerShell en cours d’exécution. + + + Nous ne pouvons pas effectuer l’opération, car les instances d’exécution ne sont pas dans l’état « {0} ». L’état actuel de l’instance d’exécution est « {1} ». + + + Les instances PowerShell imbriquées ne peuvent pas être appelées de manière asynchrone. Utilisez la méthode Invoke. + + + L’objet {0} n’a pas été créé en appelant {1} sur cette instance PowerShell. + + + Lorsque l’instance d’exécution est configurée pour réutiliser un thread, l’état de cloisonnement dans les paramètres d’invocation doit correspondre à celui de l’instance d’exécution. + + + Lorsque l’instance d’exécution est configurée pour utiliser le thread actuel, l’état de cloisonnement dans les paramètres d’appel doit correspondre à celui du thread actuel. + + + Une commande est requise pour ajouter un paramètre. Vous devez ajouter une commande à l’instance PowerShell avant d’ajouter un paramètre. + + + Les clés du dictionnaire doivent être des chaînes. + + + Aucune instance d’exécution n’est disponible pour exécuter des commandes dans ce thread. Vous pouvez en fournir une dans la propriété DefaultRunspace du type System.Management.Automation.Runspaces.Runspace. La commande que vous avez tenté d’appeler était : {0} + + + Nous ne pouvons pas connecter cet objet PowerShell, car il n’est pas associé à une instance d’exécution distante ou à un pool d’instances d’exécution. + + + La commande en cours d’exécution a été déconnectée, mais elle s’exécute toujours sur le serveur distant. Reconnectez-vous pour obtenir l’état de l’opération de la commande et les données de sortie. + + + Nous ne pouvons pas effectuer l’opération, car la session PowerShell actuelle est à l’état Déconnecté. Connectez cette session PowerShell, puis attendez que la commande se termine ou arrêtez-la. + + + Nous ne pouvons pas effectuer l’opération, car la session PowerShell actuelle est à l’état Déconnecté. Connectez cette session PowerShell, puis réessayez. + + + La tentative de connexion à la commande distante a échoué. + + + L’opération ne peut pas être effectuée, car une commande est en cours d’arrêt. Attendez que la commande ait fini de s’arrêter, puis réessayez. + + + Aucune instance d’exécution n’est disponible pour exécuter des commandes dans ce thread. Vous pouvez en fournir une dans la propriété DefaultRunspace du type System.Management.Automation.Runspaces.Runspace. L’instance PowerShell actuelle ne contient aucune commande à appeler. + + + Nous ne pouvons pas créer un objet PowerShell qui utilise l’instance d’exécution actuelle, car aucune instance d’exécution n’est disponible. L’instance d’exécution actuelle est peut-être en cours de démarrage, par exemple lorsqu’elle est créée avec un état de session initial. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ProgressRecordStrings.fr.resx b/src/System.Management.Automation/resources/fr/ProgressRecordStrings.fr.resx new file mode 100644 index 00000000000..2408a12bd3c --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ProgressRecordStrings.fr.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nous ne pouvons pas traiter l’argument, car {0} ne peut pas être négatif. + + + Nous ne pouvons pas traiter l’argument, car la valeur de {0} ne peut pas être null ou vide. + + + Nous ne pouvons pas définir le pourcentage, car {0} ne peut pas être supérieur à 100. + + + ParentActivityId ne peut pas être identique à ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ProviderBaseSecurity.fr.resx b/src/System.Management.Automation/resources/fr/ProviderBaseSecurity.fr.resx new file mode 100644 index 00000000000..00a243de06c --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ProviderBaseSecurity.fr.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 + + + Nous ne pouvons pas utiliser l’interface, car ce fournisseur ne prend pas en charge l’interface ISecurityDescriptorCmdletProvider. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/ProxyCommandStrings.fr.resx b/src/System.Management.Automation/resources/fr/ProxyCommandStrings.fr.resx new file mode 100644 index 00000000000..397c3cc9f6a --- /dev/null +++ b/src/System.Management.Automation/resources/fr/ProxyCommandStrings.fr.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 + + + Le paramètre « help » n’est pas reconnu comme un objet HelpInfo valide créé par la commande « get-help ». + + + Nous ne pouvons pas générer la commande proxy, car CommandMetadata est sans nom. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/RegistryProviderStrings.fr.resx b/src/System.Management.Automation/resources/fr/RegistryProviderStrings.fr.resx new file mode 100644 index 00000000000..13a2d5cd069 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/RegistryProviderStrings.fr.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Définir l’élément + + + Élément : {0} Valeur : {1} + + + Effacer l’élément + + + Élément : {0} + + + Nouvel élément + + + Élément : {0} + + + Supprimer la clé + + + Élément : {0} + + + Copier la clé + + + Élément : {0} Destination : {1} + + + Renommer un élément + + + Élément : {0} NewName : {1} + + + Déplacer l'élément + + + Élément : {0} Destination : {1} + + + Définir la propriété + + + Élément : {0} Propriété : {1} + + + Effacer la propriété + + + Élément : {0} Propriété : {1} + + + Nouvelle propriété + + + Élément : {0} Propriété : {1} + + + Supprimer la propriété + + + Élément : {0} Propriété : {1} + + + Renommer la propriété. + + + Article : {0} Propriété source : {1} Propriété de destination : {2} + + + Copier la propriété + + + Élément : {0} SourceProperty : {1} DestinationItem : {2} DestinationProperty : {3} + + + Déplacer la propriété + + + Élément : {0} SourceProperty : {1} DestinationItem : {2} DestinationProperty : {3} + + + L’opération n’a pas été traitée. L’emplacement fourni n’autorise pas cette opération. + + + L’opération n’est pas autorisée à l’emplacement source. + + + L’opération n’est pas autorisée à l’emplacement de destination. + + + Les paramètres de configuration de l’ordinateur local + + + Paramètres logiciels de l’utilisateur(-trice) actuel(le) + + + Une clé existe déjà dans ce chemin d’accès. + + + L’opération ne peut pas être effectuée, car le chemin de destination dépend du chemin source. + + + La propriété existe déjà. + + + La propriété « {0} » n’existe pas pour le type « {1} ». + + + La clé de Registre à l’emplacement spécifié n’existe pas. + + + Nous n’avons pas pu lier le paramètre « Type ». Nous n’avons pas pu convertir « {0} » en « {1} ». Les valeurs d’énumération possibles sont « String, ExpandString, Binary, DWord, MultiString, QWord, Unknown ». + + + La clé {0} a été créée, mais une valeur par défaut n’a pas pu être définie. + + + Nous ne pouvons pas créer un lecteur avec la racine spécifiée. Le chemin racine n’existe pas. + + + Nous ne pouvons pas renommer l’élément, car un élément portant ce nom existe déjà dans le même conteneur. + + + Le nom de la clé de Registre doit commencer par un nom de clé racine valide. + + + L’argument de sous-clé n’est pas valide. + + + Nous ne pouvons pas supprimer l’arborescence de sous-clés, car la sous-clé n’existe pas. + + + Aucune valeur n’existe avec ce nom. + + + La valeur d’énumération {0} n’est pas valide. + + + Une valeur d’argument de nom doit être spécifiée. + + + Un argument de nom doit être spécifié. + + + La valeur RegistryValueKind spécifiée n’est pas valide. + + + RegistryKey.SetValue n’autorise pas un String[] qui contient une référence String null. + + + La longueur de l'URL ne doit pas dépasser 255 caractères. + + + Un nom de sous-clé non vide doit être spécifié. + + + Le type de l’objet valeur ne correspondait pas au RegistryValueKind spécifié ou l’objet n’a pas pu être correctement converti. + + + RegistryKey.SetValue ne prend pas en charge les tableaux de type « {0} ». Seuls Byte[] et String[] sont pris en charge. + + + La clé de Registre spécifiée n’existe pas. + + + La longueur du nom de valeur spécifié dépasse le maximum de 1 6383 caractères. + + + La taille des données de valeur spécifiées dépasse le maximum de 1 Mo. + + + La sous-clé de Registre spécifiée n’existe pas. + + + La valeur RegistryKeyPermissionCheck spécifiée n’est pas valide. + + + La clé de Registre comporte des sous-clés; cette méthode ne prend pas en charge les suppressions récursives. + + + Nous ne pouvons pas créer un handle KTM sans Transaction.Current ou transaction spécifiée. + + + La transaction spécifiée ou Transaction.Current doit correspondre à la transaction utilisée pour créer ou ouvrir ce TransactedRegistryKey. + + + L’objet TransactedRegistryKey n’est pas associé à une transaction, car il s’agit d’une clé prédéfinie. + + + L’accès au Registre demandé n’est pas autorisé. + + + L’accès à la clé de Registre « {0} » est refusé. + + + Nous ne pouvons pas écrire dans la clé de Registre. + + + Nous ne pouvons pas accéder à une clé de Registre fermée. + + + Erreur inconnue : {0}. + + + Les transactions de Registre ne sont pas prises en charge sur cette plateforme. + + + Le handle spécifié n'est pas valide. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/RemotingErrorIdStrings.fr.resx b/src/System.Management.Automation/resources/fr/RemotingErrorIdStrings.fr.resx new file mode 100644 index 00000000000..aa83b97d417 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/RemotingErrorIdStrings.fr.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + Les caractères génériques ne sont pas pris en charge pour le paramètre FilePath. Indiquez un chemin d’accès sans caractères génériques. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + Une valeur {0} doit être spécifiée pour l’option de session {1}. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + Nombre maximal de redirections d’URI WS-Man autorisées lors de la connexion à un ordinateur distant + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + Le paramètre WriteEvents ne peut pas être utilisé sans le paramètre Wait. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + La communication à distance PowerShell n’est pas prise en charge dans l’environnement de préinstallation Windows (WinPE). + + + Les modifications effectuées par {0} ne peuvent pas prendre effet tant que le service WinRM n’est pas redémarré. + + + {0} Vous devrez peut-être redémarrer le service WinRM si une configuration utilisant ce nom a été récemment désinscrite, car des structures de données système peuvent encore être mises en cache. Dans ce cas, un redémarrage de WinRM peut être requis. +Toutes les sessions WinRM connectées à des configurations de session PowerShell, telles que Microsoft.PowerShell et les configurations de session, créées avec la cmdlet Register-PSSessionConfiguration, sont déconnectées. + + + Vous exécutez une session à distance et avez sélectionné l’option Forcer, ce qui signifie que le service WinRM peut redémarrer. Si le service WinRM redémarre, cette session à distance est terminée et vous devez créer une session pour continuer + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + Le paramètre -WriteJobInResults ne peut pas être utilisé sans le paramètre -Wait + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + Le flux d’entrée fourni n’est pas valide. Seul {0} est pris en charge comme flux d’entrée. + + + Le jeu de flux de sortie fourni n’est pas valide. Seul {0} est pris en charge comme flux de sortie. + + + L’élément WSMAN_SENDER_DETAILS fourni n’est pas valide. Nous ne pouvons pas traiter un élément WSMAN_SENDER_DETAILS nul. + + + Le contexte d’interpréteur de commandes fourni n’est pas valide. + + + {0} + + + La valeur NULL n’est pas autorisée pour {0} avec la méthode de plug-in {1}. + + + La valeur NULL n’est pas autorisée pour les jeux de flux d’entrée et de sortie. {0} et {1} sont des flux d’entrée et de sortie pris en charge. + + + La valeur NULL n’est pas autorisée pour {0} avec la méthode de plug-in {1}. + + + La valeur NULL n’est pas autorisée pour {0} avec la méthode de plug-in {1}. + + + L’opération du plug-in de PowerShell est en cours d’arrêt. Ce problème peut se produire si le service ou l’application d’hébergement est en cours d’arrêt. + + + Le plug-in PowerShell ne comprend pas l’option {0}. Vérifiez que le client est compatible avec la version de build {1} et de protocole {2} de PowerShell. + + + Une option nommée {0} est attendue du client. Vérifiez que le client est compatible avec la version de build {1} et de protocole {2} de PowerShell. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Le plug-in PowerShell ne prend pas en charge la version de protocole {2} demandée par le client.</PSProtocolVersionError> + + + Le plug-in PowerShell a rencontré une erreur irrécupérable lors de la transmission du contexte au service WSMan. + + + Nous ne pouvons pas créer une session de serveur géré. + + + Le plug-in PowerShell a rencontré une erreur irrécupérable lors d’inscriptions d’un handle d’attente pour la notification d’arrêt. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + Le fichier exécutable « {0} » est introuvable. Confirmez que la fonctionnalité WOW64 est installée. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + Nous ne pouvons pas créer le processus Windows PowerShell, car Windows PowerShell est introuvable sur cet ordinateur. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/RunspaceInit.fr.resx b/src/System.Management.Automation/resources/fr/RunspaceInit.fr.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/RunspaceInit.fr.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/RunspacePoolStrings.fr.resx b/src/System.Management.Automation/resources/fr/RunspacePoolStrings.fr.resx new file mode 100644 index 00000000000..54b00712c8b --- /dev/null +++ b/src/System.Management.Automation/resources/fr/RunspacePoolStrings.fr.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La taille maximale du pool ne peut pas être inférieure à 1. + + + La taille minimale du pool ne peut pas être inférieure à 1. + + + La taille minimale du pool ne peut pas être supérieure à la taille maximale du pool. + + + L’état du pool d’instances d’exécution n’est pas valide pour cette opération. + + + Nous ne pouvons pas effectuer l’opération, car le pool d’instances d’exécution n’est pas dans l’état « {0} ». L'état actuel est « {1} ». + + + Nous ne pouvons pas ouvrir le pool d’instances d’exécution, car il n’est pas dans l’état « BeforeOpen ». L'état actuel est « {0} ». + + + L’objet {0} n’a pas été créé en appelant {1} sur l’instance RunspacePool actuelle. + + + Nous ne pouvons pas libérer l’instance d’exécution vers le pool actuel, car l’instance d’exécution n’appartient pas au pool actuel. + + + Cette propriété ne peut pas être modifiée après l’ouverture du pool d’instances d’exécution. + + + Cette instance d’exécution ne prend pas en charge les opérations de déconnexion et de connexion. + + + Nous ne pouvons pas effectuer l’opération, car le pool d’instances d’exécution est dans l’état Déconnecté. + + + L’opération de déconnexion n’est pas prise en charge sur le serveur. Le serveur doit exécuter PowerShell 3.0 ou une version ultérieure pour prendre en charge la déconnexion du pool d’instances d’exécution distantes. + + + Ce pool d’espaces d’exécution {0} n’est pas configuré pour fournir des objets PowerShell déconnectés pour les commandes exécutées sur le serveur distant. Utilisez la méthode statique GetRunspacePools() de la classe RunspacePool pour interroger le serveur et renvoyer les objets de pool d’espaces d’exécution configurés à cet effet. + + + Nous ne pouvons pas vous connecter ce pool d’instances d’exécution, car le pool d’instances d’exécution correspondant côté serveur est connecté à un autre client. + + + ResetRunspaceState n’est pas pris en charge sur le serveur. Le serveur doit exécuter PowerShell 5.0 ou une version ultérieure. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/RunspaceStrings.fr.resx b/src/System.Management.Automation/resources/fr/RunspaceStrings.fr.resx new file mode 100644 index 00000000000..05d20237e44 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/RunspaceStrings.fr.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + L’état de l’instance d’exécution n’est pas valide pour cette opération. + + + Nous ne pouvons pas ouvrir l’instance d’exécution, car elle n’est pas dans l’état BeforeOpen. L’état actuel de l’instance d’exécution est « {0} ». + + + Nous ne pouvons pas effectuer l’opération, car l’instance d’exécution n’est pas dans l’état Ouvert. L’état actuel de l’instance d’exécution est « {0} ». + + + Nous ne pouvons pas appeler le pipeline, car l’instance d’exécution n’est pas à l’état Ouvert. L’état actuel de l’instance d’exécution est « {0} ». + + + L’état du pipeline n’est pas valide pour cette opération. + + + Nous ne pouvons pas appeler le pipeline, car il a déjà été appelé. + + + La valeur valide pour le paramètre est PipelineResultTypes.Output. + + + Le pipeline ne contient pas de commande. + + + Le pipeline n’a pas été exécuté, car un pipeline est déjà en cours d’exécution. Vous ne pouvez pas exécuter les pipelines simultanément. + + + Un pipeline imbriqué ne peut pas être appelé de manière asynchrone. Utilisez la méthode Invoke. + + + Vous devez exécuter un pipeline imbriqué uniquement à partir d’un pipeline en cours d’exécution. + + + Nous ne pouvons pas fermer l’instance d’exécution pendant qu’un appel de méthode SessionStateProxy est en cours. + + + Nous ne pouvons pas appeler le pipeline pendant qu’un appel de méthode SessionStateProxy est en cours. + + + Un appel de méthode SessionStateProxy est en cours. Les appels simultanés de méthode SessionStateProxy ne sont pas autorisés. + + + Un pipeline est déjà en cours d’exécution. Les appels simultanés de méthode SessionStateProxy ne sont pas autorisés. + + + Cette propriété ne peut pas être modifiée après l’ouverture de l’instance d’exécution. + + + Une ou plusieurs erreurs se sont produites lors du traitement du module « {0} » spécifié dans l’objet InitialSessionState utilisé pour créer cette instance d’exécution. Consultez la propriété ErrorRecords pour obtenir la liste complète des erreurs. La première erreur était : {1} + + + Les options de thread ne peuvent être modifiées que si l’état de cloisonnement est MTA (Multithreaded Apartment), si les options actuelles sont UseNewThread ou UseCurrentThread, et si la nouvelle valeur est ReuseThread. + + + {0} ne peut pas avoir la valeur false lorsque le mode de langage est {1} ou {2}. + + + Vous ne pouvez pas déconnecter un espace d’exécution local uniquement. + + + L’opération Connect n’est pas prise en charge sur les instances d’exécution locales. + + + La session est occupée. Dès que la session sera disponible, vous serez connecté. Pour annuler la commande Enter-PSSession, appuyez sur Ctrl+C. + + + Nous ne pouvons pas effectuer la commande. L’appel de script n’est pas pris en charge dans la configuration de cette session. Cela peut se produire si la configuration de session est en mode sans langage. + + + Vous ne pouvez pas utiliser les opérations Disconnect et Connect sur les instances d’exécution locales. + + + Nous ne pouvons pas effectuer la connexion au pipeline, car l’instance d’exécution n’est pas à l’état Ouvert. L’état actuel de l’instance d’exécution est « {0} ». + + + Nous ne pouvons pas créer un RemoteRunspace. L’objet RunspacePool fourni n’est pas valide. + + + Il n’existe aucune commande déconnectée associée à cette instance d’exécution. + + + L’opération de déconnexion n’est pas prise en charge sur l’ordinateur distant. Pour prendre en charge la déconnexion, l’ordinateur distant doit exécuter Windows PowerShell 3.0 ou une version ultérieure de Windows PowerShell et utiliser le transport WSMan. + + + Nous ne pouvons pas effectuer la connexion à PSSession, car la session n’est pas à l’état Déconnecté ou n’est pas disponible pour la connexion. + + + La valeur du paramètre ne peut pas être PipelineResultTypes.None ou PipelineResultTypes.Output. + + + Les valeurs valides pour le paramètre sont PipelineResultTypes.Output ou PipelineResultTypes.Null. + + + La redirection du flux de débogage n’est pas prise en charge sur l’ordinateur distant ciblé. + + + La redirection du flux détaillé n’est pas prise en charge sur l’ordinateur distant ciblé. + + + La redirection du flux d’avertissement n’est pas prise en charge sur l’ordinateur distant ciblé. + + + La redirection du flux d’informations n’est pas prise en charge sur l’ordinateur distant ciblé. + + + Vous avez ouvert une session qui est occupée à exécuter une commande ou un script. Comme la sortie est redirigée vers le travail « {0} », vous ne verrez pas la sortie dans la console. Vous pouvez attendre la fin de la commande en cours ou l’annuler pour obtenir une requête d’entrée en appuyant sur Ctrl-C. + + + + Vous avez entré une session qui est occupée à exécuter une commande ou un script dont le résultat s’affichera dans la console. Vous pouvez attendre la fin de la commande en cours ou l’annuler pour obtenir une requête d’entrée en appuyant sur Ctrl-C. + + + + Vous avez entré une session actuellement arrêtée à un point d’arrêt de débogage au sein d’une commande ou d’un script en cours d’exécution. Utilisez le débogueur de ligne de commande PowerShell pour poursuivre le débogage. + + + + DefaultRunspace doit être un LocalRunspace + + + La propriété statique PrimaryRunspace ne peut être définie qu’une seule fois et a déjà été définie. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/SecuritySupportStrings.fr.resx b/src/System.Management.Automation/resources/fr/SecuritySupportStrings.fr.resx new file mode 100644 index 00000000000..80a0e992ba7 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/SecuritySupportStrings.fr.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impossible de charger le certificat. '{0}' doit être résolu en chemin d’accès au système de fichiers. + + + Le certificat '{0}' ne peut pas être utilisé pour le chiffrement. Les certificats de chiffrement doivent contenir l’utilisation de la clé Chiffrement des données ou Chiffrement de clé, et inclure l’utilisation améliorée de la clé de chiffrement de document ({1}). + + + Impossible de charger le certificat. L’identificateur «{0}» correspond à plusieurs certificats. Pour chiffrer sur plusieurs destinataires, fournissez plusieurs valeurs spécifiques au paramètre «{1}», plutôt qu’un caractère générique qui correspond à plusieurs certificats. + + + Impossible de charger le certificat de chiffrement. Le paramètre de certificat «{0}» ne représente pas un certificat encodé en base 64 valide, ni un certificat valide par fichier, répertoire, empreinte numérique ou nom de sujet. + + + AVERTISSEMENT : le certificat «{0}» contient une clé privée. Les certificats de journalisation des événements protégés utilisés pour le chiffrement doivent contenir uniquement la clé publique. + + + Erreur : impossible de protéger le message du journal des événements «{0}» : {1} + + + Erreur : impossible de trouver ou d’utiliser le certificat : {0} + + + Clé de session non disponible pour chiffrer la chaîne sécurisée. + + + Décalage de mémoire tampon non valide. + + + Données de clé publique non valides. + + + Impossible d’importer la clé publique. + + + Données de clé de session non valides. + + + Le fichier de script, '{0}', est bloqué par la stratégie système. + + + Une valeur d’application de stratégie de fichier de script inconnue a été retournée : {0}. + + + Fichier de script lu + + + Le fichier de script «{0}» n’est pas approuvé par la stratégie et s’exécutera en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/Serialization.fr.resx b/src/System.Management.Automation/resources/fr/Serialization.fr.resx new file mode 100644 index 00000000000..d4cf8b67a40 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/Serialization.fr.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} attribut était attendu. + + + Le jeton {0} n’est pas reconnu. + + + Aucun objet trouvé pour referenceId {0} + + + L’attribut Name de la clé du dictionnaire est mal spécifié. + + + L’attribut Name de la valeur du dictionnaire est mal spécifié. + + + La version de PSObject n’est pas valide. + + + La version du PSObject entrant est {0}. La valeur attendue est 1. + + + Nous ne pouvons pas traiter les noms, car aucun TypeNames n’a été trouvé pour referenceId {0}. + + + La valeur du paramètre de profondeur doit être supérieure ou égale à 1. + + + Le type de nœud actuel est {0}. Type attendu est {1}. + + + La clé de l’entrée du dictionnaire n’est pas spécifiée. + + + La valeur de l’entrée du dictionnaire n’est pas spécifiée. + + + Il n’y a plus d’objets à désérialiser. + + + Null est spécifié comme clé de dictionnaire. + + + Le contenu du type primitif {0} n’est pas valide. + + + Le XML sérialisé est imbriqué trop profondément. + + + Le sérialiseur a été fermé. + + + Les données de la commande ont dépassé la taille maximale autorisée par la configuration de session. Le maximum autorisé est {0} Mo. Modifiez l’entrée, utilisez une autre configuration de session ou modifiez les propriétés « {1} » et « {2} » de la configuration de session sur l’ordinateur distant. + + + Échec de la désérialisation de la chaîne sécurisée chiffrée + + + Le type de clé « {0} » n’est pas valide. La classe PSPrimitiveDictionary accepte uniquement les clés de type System.String. + + + Le type de la valeur {0} n’est pas valide. La classe PSPrimitiveDictionary accepte uniquement les valeurs de types entièrement sérialisables via PowerShell remoting. Consultez la rubrique d’Aide about_Remoting pour obtenir la liste des types entièrement sérialisables. + + + Nous n’avons pas pu déchiffrer les données. Elles n’ont pas été chiffrées avec cette clé. + + + La valeur du paramètre « {0} » n’est pas une chaîne chiffrée valide. + + + Le {0} spécifié n'est pas valide. Les valeurs de longueur {0} valide sont 128 bits, 192 bits ou 256 bits. + + + La désérialisation de SecureString n’est actuellement prise en charge que sur Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/SessionStateProviderBaseStrings.fr.resx b/src/System.Management.Automation/resources/fr/SessionStateProviderBaseStrings.fr.resx new file mode 100644 index 00000000000..e11cfa82ae6 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/SessionStateProviderBaseStrings.fr.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Définir l’élément + + + Élément : {0} Valeur : {1} + + + Effacer l’élément + + + Élément : {0} + + + Supprimer l'élément + + + Élément : {0} + + + Nouvel élément + + + Élément : {0} Type : {1} Valeur : {2} + + + Copier l’élément + + + Élément : {0} Destination : {1} + + + Renommer un élément + + + Élément : {0} NewName : {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/SessionStateStrings.fr.resx b/src/System.Management.Automation/resources/fr/SessionStateStrings.fr.resx new file mode 100644 index 00000000000..062c6d22d2f --- /dev/null +++ b/src/System.Management.Automation/resources/fr/SessionStateStrings.fr.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impossible de traiter les informations retournées, car celles retournées par la méthode Start du fournisseur étaient pour un différent fournisseur de celui qui a été transmis. + + + Impossible de traiter les informations retournées, car celles retournées par la méthode Start du fournisseur étaient null. + + + La tentative d’exécution de l’opération GetItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération GetItem pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération SetItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération SetItem pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération ClearItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération InvokeDefaultAction sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération InvokeDefaultAction pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération ItemExists sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération ItemExists pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération IsValidPath sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération IsItemContainer sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération RemoveItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération GetChildItems sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération GetChildItems pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération GetChildNames sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération GetChildNames pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération RenameItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération RenameItem pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération NewItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération NewItem pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération HasChildItems sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération CopyItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération CopyItem pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération GetParentPath sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération NormalizeRelativePath sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération MakePath sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération GetChildName sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération MoveItem sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération MoveItem pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération GetProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération GetProperty pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération SetProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération SetProperty pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération ClearProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération ClearProperty pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération NewProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération NewProperty pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération RemoveProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération RemoveProperty pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération CopyProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération CopyProperty pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération MoveProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération MoveProperty pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération RenameProperty sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de RenameProperty pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer le lecteur de contenu pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération GetContentReader pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer l’enregistreur de contenu pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de l’opération GetContentWriter pour le fournisseur « {0} » pour le chemin d’accès « {1} ». {2} + + + Impossible d’obtenir le contenu, car il s’agit d’un répertoire : « {0} ». Utilisez plutôt « Get-ChildItem ». + + + Impossible d’écrire le contenu, car il s’agit d’un répertoire : « {0} ». + + + Il n’y a plus d’historique d’emplacement pour naviguer vers l’arrière. + + + Il n’y a plus d’historique d’emplacement pour naviguer vers l’avant. + + + BoundedStack est vide. + + + La tentative d’exécution de l’opération ClearContent sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Impossible d’effacer le contenu de « {0} », car il s’agit d’un répertoire. Clear-Content n’est pris en charge que sur les fichiers. + + + Impossible de récupérer les paramètres dynamiques de l’opération ClearContent pour le fournisseur « {0} » depuis le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération GetSecurityDescriptor sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération SetSecurityDescriptor sur le fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + La tentative d’exécution de l’opération Start sur le fournisseur « {0} » a échoué. {1} + + + La tentative d’exécution de l’opération InitializeDefaultDrives sur le fournisseur « {0} » a échoué. + + + La tentative d’exécution de l’opération NewDrive sur le fournisseur « {0} » a échoué pour le lecteur avec la racine « {1} ». {2} + + + Impossible de récupérer les paramètres dynamiques de NewDrive pour le fournisseur « {0} ». {1} + + + L’appel de RemoveDrive sur le fournisseur « {0} » a échoué. {1} + + + Le lecteur « {0} » ne peut pas être supprimé, car le fournisseur « {1} » l’a empêché. + + + Le chemin d’accès « {0} » faisait référence à un élément situé en dehors de la base « {1} ». + + + L’appel de Seek sur le rédacteur de contenu du fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + L’appel de Close sur le lecteur ou l’enregistreur de contenu du fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + L’appel de Read sur le lecteur de contenu du fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + L’appel de Write sur le rédacteur de contenu du fournisseur « {0} » a échoué pour le chemin d’accès « {1} ». {2} + + + Le fournisseur « {0} » ne peut pas être utilisé pour obtenir ou définir des données à l’aide de la syntaxe de variable. {2} + + + Impossible d’utiliser la syntaxe de variable pour obtenir ou définir des données dans le fournisseur. {2} + + + Alias n’est pas accessible en écriture, car l’alias {0} étant une constante ou en lecture seule, il n’est pas possible d’y écrire. + + + Impossible d’écrire dans la fonction {0}, car elle est en lecture seule ou constante. + + + Impossible de remplacer la variable {0} car elle est en lecture seule ou constante. + + + Impossible d’accéder à la variable « ${0} », car il s’agit d’une variable privée. + + + Impossible d’accéder à la commande « {0} », car il s’agit d’une commande privée. + + + Impossible d’accéder à la commande, car il s’agit d’une commande privée. + + + Impossible d’accéder à la ressource d’état de session, car il s’agit d’une ressource privée. + + + L’alias n’a pas été supprimé, car l’alias {0} est constant ou en lecture seule. + + + Impossible de supprimer la fonction {0}, car elle est constante. + + + Impossible de supprimer la variable {0} car elle est constante ou en lecture seule. Si la variable est en lecture seule, recommencez l’opération en spécifiant l’option Force. + + + Impossible de modifier l’alias {0} car il est constant. + + + Impossible de modifier l’alias {0} car il est en lecture seule. + + + Impossible de modifier la fonction {0}, car elle est constante. + + + Impossible de modifier la fonction {0}, car elle est « lecture seule ». + + + L’alias {0} ne peut pas être défini comme constant une fois créé. Les alias ne peuvent être définis comme constants qu’au moment de leur création. + + + La fonction existante {0} ne peut pas être définie comme constante. Les fonctions ne peuvent être définies comme constantes qu’au moment de leur création. + + + La variable existante {0} ne peut pas être définie comme constante. Les variables ne peuvent être définies comme constantes qu’au moment de leur création. + + + L’option AllScope ne peut pas être supprimée de l’alias « {0} ». + + + L’option AllScope ne peut pas être supprimée de la fonction « {0} ». + + + L’option AllScope ne peut pas être supprimée de la variable « {0} ». + + + La définition de fonction « {0} » contenait un qualificateur d’étendue, mais aucun nom de fonction. + + + Impossible de supprimer le fournisseur {0}. Tous les lecteurs associés au fournisseur {0} doivent être supprimés avant de pouvoir supprimer le fournisseur {0}. + + + Impossible de traiter le nom du lecteur, car il contient un ou plusieurs des caractères non valides suivants : ; ~ / \ . : + + + La création du nouveau lecteur a échoué, car le fournisseur n’autorise pas la création d’un nouveau lecteur. + + + La valeur fournie « {0} » correspond à plusieurs piles d’emplacements. + + + Impossible de trouver la pile d’emplacements « {0} ». Elle n’existe pas ou ce n’est pas un conteneur. + + + Impossible de trouver le chemin d'accès « {0} », car il n'existe pas. + + + Alias introuvable, car l’alias « {0} » n’existe pas. + + + Impossible de définir l’emplacement, car le chemin « {0} » a été résolu en plusieurs conteneurs. Vous ne pouvez définir l’emplacement que sur un seul conteneur à la fois. + + + Impossible de traiter la variable, car le chemin d’accès de variable « {0} » a été résolu en plusieurs éléments. Vous ne pouvez obtenir ou définir la valeur de la variable d’un seul élément à la fois. + + + Nous ne pouvons pas trouver le lecteur. Aucun lecteur nommé « {0} » n’existe. + + + Impossible de trouver un fournisseur portant le nom « {0} ». + + + Impossible de trouver un fournisseur portant le nom « {0} ». Le format du nom n’est pas correct. Un nom de fournisseur ne peut contenir que des caractères alphanumériques, ou un nom de composant logiciel enfichable PowerShell suivi d’un seul « \ », puis de caractères alphanumériques. + + + « {0} » a donné plusieurs noms de fournisseur. Les correspondances possibles sont les suivantes : {1}. + + + Une erreur s’est produite lors de la tentative de création d’une instance du fournisseur. Le nom du type de fournisseur « {0} » est introuvable dans l’assembly. + + + Le nom de fournisseur spécifié « {0} » ne peut pas être utilisé, car il contient un ou plusieurs des caractères non valides suivants : \ [ ] ? * : + + + Une erreur s’est produite lors de la tentative de création d’une instance du fournisseur « {0} ». {1} + + + Impossible de trouver une variable nommée « {0} ». + + + Impossible de trouver une source de trace nommée « {0} ». + + + Un lecteur portant le nom « {0} » existe déjà. + + + Une variable portant le nom « {0} » existe déjà. + + + L’alias n’est pas autorisé, car un alias portant le nom « {0} » existe déjà. + + + Impossible d’inscrire le fournisseur d’applets de commande, car un fournisseur d’applets de commande portant le nom « {0} » existe déjà. + + + Le chemin d’accès ne fait pas référence à un chemin d’accès de système de fichiers. + + + L’étendue globale ne peut pas être supprimée. + + + Le nombre d’étendues actives est inférieur à « {0} ». + + + Impossible de comparer PSDriveInfo. Une instance de PSDriveInfo ne peut être comparée qu’à une autre instance de PSDriveInfo. + + + Le fournisseur d’applets de commande ne peut pas diffuser les résultats, car aucun cmdlet n’a été spécifié n’a été spécifiée pour diffuser la sortie. + + + Le fournisseur d’applets de commande ne peut pas diffuser les résultats, car aucun cmdlet n’a été spécifié pour diffuser l’erreur. + + + L’emplacement d’accueil de ce fournisseur n’est pas défini. Pour définir l’emplacement d’accueil, appelez « (get-psprovider '{0}').Home = 'path' ». + + + Le format du chemin est incorrect. Les chemins d’accès du fournisseur doivent contenir un ID de fournisseur, suivi de « :: », puis d’un chemin d’accès propre au fournisseur. + + + Impossible de déplacer l’élément, car le chemin d’accès de destination ne peut être résolu qu’en un seul chemin d’accès. + + + Impossible de déplacer l’élément, car les chemins d’accès source et destination n’ont pas été résolus vers le même fournisseur. + + + Impossible de déplacer l’élément, car le chemin source pointe vers un ou plusieurs éléments et le chemin de destination n’est pas un conteneur. Vérifiez que le chemin de destination est un conteneur et réessayez. + + + Impossible de déplacer l’élément, car la destination a été résolue en plusieurs chemins d’accès. Spécifiez un chemin de destination qui mène à une seule destination, puis réessayez. + + + Impossible de copier un conteneur sur un élément feuille existant. + + + Impossible de copier un conteneur dans un autre conteneur. Le paramètre -Recurse ou -Container n’est pas spécifié. + + + Les chemins source et de destination n’ont pas été résolus vers le même fournisseur. + + + Impossible de renommer l’élément, car le chemin d’accès a été résolu en plusieurs éléments. Un seul élément peut être renommé à la fois. + + + Le fournisseur « {0} » ne peut pas être utilisé pour résoudre le chemin d’accès « {1} » en raison d’une erreur dans le fournisseur. + + + Impossible d’utiliser l’interface. L’interface IContentCmdletProvider n’est pas implémentée par ce fournisseur. + + + Impossible d’utiliser l’interface. L’interface IPropertyCmdletProvider n’est pas prise en charge par ce fournisseur. + + + Impossible d’utiliser l’interface. L’interface IDynamicPropertyCmdletProvider n’est pas implémentée par ce fournisseur. + + + Les méthodes NavigationCmdletProvider ne sont pas prises en charge par ce fournisseur. + + + Méthodes de fournisseur non traitées. Les méthodes ContainerCmdletProvider ne sont pas prises en charge par ce fournisseur. + + + Impossible d'appeler des méthodes. Les méthodes ItemCmdletProvider ne sont pas prises en charge par ce fournisseur. + + + Les méthodes DriveCmdletProvider ne sont pas prises en charge par ce fournisseur. + + + L’opération du fournisseur s’est arrêtée, car ce fournisseur ne prend pas en charge cette opération. + + + L’opération du fournisseur s’est arrêtée, car ce fournisseur ne prend pas en charge le paramètre « Depth ». + + + Impossible d'appeler la méthode. La méthode Seek du contenu n’est pas prise en charge par ce fournisseur. + + + Impossible d’effectuer l’opération ClearContent. Cette opération n’est pas prise en charge par ce fournisseur. + + + Le fournisseur ne prend pas en charge l’utilisation des informations d’identification. Recommencez l’opération sans spécifier d’informations d’identification. + + + Le fournisseur FileSystem ne prend en charge les informations d’identification que dans le cmdlet New-PSDrive. Recommencez l’opération sans spécifier d’informations d’identification. + + + Le fournisseur ne prend pas en charge les transactions. Recommencez l’opération sans le paramètre -UseTransaction. + + + Impossible d'appeler la méthode. Le fournisseur ne prend pas en charge l’utilisation des filtres. + + + Désolé, nous ne pouvons pas créer le lecteur. Le fournisseur ne prend pas en charge l’utilisation des informations d’identification. + + + L'élément « {0} » du chemin d’accès existe déjà. + + + Impossible de copier l’élément. L’élément « {0} » du chemin d’accès n’existe pas. + + + L’élément « {0} » du chemin d’accès n’existe pas. + + + Lecteur qui contient une vue des alias stockés dans un état de session + + + Lecteur qui contient une vue des variables d’environnement pour le processus + + + Lecteur qui contient une vue des fonctions stockées dans un état de session + + + Lecteur qui contient une vue de ces variables dans un état de session + + + Lecteur mappé au chemin d’accès du répertoire temporaire pour l’utilisateur actuel + + + Le lien « {0} » ne peut pas être créé, car la valeur de destination n’a pas été spécifiée. + + + Les références à la variable null retournent toujours la valeur null. Les affectations n’ont aucun effet. + + + Nombre maximal d’objets d’historique à conserver dans une session + + + Impossible de renommer la fonction, car la fonction {0} est en lecture seule ou constante. + + + Impossible de renommer l’alias, car l’alias {0} est en lecture seule ou constant. + + + Impossible de renommer la variable, car la variable {0} est en lecture seule ou constante. + + + Impossible de définir des options sur la variable locale {0}. Utilisez New-Variable pour créer une variable qui autorise la définition d’options. + + + Impossible de modifier le cmdlet {0} car il est en lecture seule. + + + Impossible de supprimer la variable {0} car elle a été optimisée et ne peut pas être supprimée. Essayez d’utiliser le cmdlet Remove-Variable (sans alias) ou d’effectuer un dot-sourcing de la commande que vous utilisez pour supprimer la variable. + + + Impossible de remplacer la variable {0} car elle a été optimisée. Essayez d’utiliser le cmdlet New-Variable ou Set-Variable (sans alias) ou d’effectuer un dot-sourcing de la commande que vous utilisez pour définir la variable. + + + Les paramètres {0} et {1} ne peuvent pas être utilisés ensemble. Spécifiez un seul paramètre. + + + Le paramètre Tail n’est actuellement pris en charge que pour le fournisseur FileSystem. + + + L’alias n’est pas autorisé, car une commande portant le nom « {0} » et le type de commande « {1} » existe déjà. + + + Impossible d’exécuter le logiciel. Autorisation refusée. + + + « -{0} » et « -{1} » s’excluent mutuellement et ne peuvent pas être spécifiés en même temps. + + + Le chemin d'accès « {0} » n'est pas valide. Seuls les chemins d’accès absolus sont pris en charge pour les opérations de copie à distance. + + + Impossible de valider le chemin d’accès distant « {0} ». + + + Impossible d’effectuer l’opération, car la session {0} est définie sur {1}. + + + Le paramètre « {0} » ne peut pas être vide ou avoir une valeur null. + + + Variables d’état de session + + + La modification de portée de la variable « {0} » en AllScope, ou la création d’une telle variable, sera empêchée en mode ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/StringDecoratedStrings.fr.resx b/src/System.Management.Automation/resources/fr/StringDecoratedStrings.fr.resx new file mode 100644 index 00000000000..6aaa4a078f0 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/StringDecoratedStrings.fr.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Seuls « ANSI » et « PlainText » sont pris en charge pour cette méthode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/SubsystemStrings.fr.resx b/src/System.Management.Automation/resources/fr/SubsystemStrings.fr.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/fr/SubsystemStrings.fr.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/SuggestionStrings.fr.resx b/src/System.Management.Automation/resources/fr/SuggestionStrings.fr.resx new file mode 100644 index 00000000000..5ec77ad5b42 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/SuggestionStrings.fr.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 + + + La commande « {0} » est introuvable, mais elle existe dans l’emplacement actuel. +Par défaut, PowerShell ne charge pas les commandes depuis l’emplacement actuel (voir « Get-Help about_Command_Precedence »). + +Si vous faites confiance à cette commande, exécutez plutôt la commande suivante : + + + Les commandes les plus similaires sont : + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/TabCompletionStrings.fr.resx b/src/System.Management.Automation/resources/fr/TabCompletionStrings.fr.resx new file mode 100644 index 00000000000..30debf0f2bf --- /dev/null +++ b/src/System.Management.Automation/resources/fr/TabCompletionStrings.fr.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 tab completion result cannot be properly deserialized because the remote runspace does not contain a TypeTable instance. + + + Cannot access properties on a null instance of the type CompletionResult. + + + Bitwise NOT + + + Logical not. Negates the statement that follows it. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case sensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case sensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case sensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case sensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case sensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE only when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case sensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Returns TRUE when the left operand is not an instance of the specified .NET Framework type (right operand). + + + Returns TRUE when the left operand is an instance of the specified .NET Framework type (right operand). + + + Converts the left operand to the specified .NET Framework type (right operand). + + + Formats strings by using the format method of string objects. + + + Logical and. Returns TRUE when both statements are TRUE. + + + Bitwise AND + + + Logical or. TRUE when either or both statements are TRUE. + + + Bitwise OR (inclusive) + + + Logical exclusive or. Returns TRUE when one of the statements is TRUE and the other is FALSE. + + + Bitwise OR (exclusive) + + + Join - combine multiple strings into a single string. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Shift Left bit operator. Inserts zero in right-most bit position. + + + Shift Right bit operator. Inserts zero in the left-most bit position. For signed values, sign bit is preserved. + + + [string] +Specifies the name of the property being created. + + + [string] +Specifies the name of the property being created. + + + [scriptblock] +A script block used to calculate the value of the new property. + + + [string] +Define how the values are displayed in a column. +Valid values are 'left', 'center', or 'right'. + + + [string] +Specifies a format string that defines how the value is formatted for output. + + + [int] +Specifies the maximum column width in a table when the value is displayed. +The value must be greater than 0. + + + [int] +The depth key specifies the depth of expansion per property. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [String[]] +Specifies the log names to get events from. +Supports wildcards. + + + [String[]] +Specifies the event log providers to get events from. +Supports wildcards. + + + [String[]] +Specifies file paths to log files to get events from. +Valid file formats are: .etl, .evt, and .evtx + + + [Long[]] +Selects events with the specified keyword bitmasks. +The following are standard keywords: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Selects events with the specified event IDs. + + + [int[]] +Selects events with the specified log levels. +The following log levels are valid: +1: Critical +2: Error +3: Warning +4: Informational +5: Verbose + + + [datetime] +Selects events created after the specified date and time. + + + [datetime] +Selects events created before the specified date and time. + + + [string] +Selects events generated by the specified user. +This can either be a string representation of a SID or a domain and username in the format DOMAIN\USERNAME or USERNAME@DOMAIN + + + [string[]] +Selects events with any of the specified values in the EventData section. + + + [hashtable] +Excludes events that match the values specified in the hashtable. + + + [string] or [hashtable] +Specifies an array of PowerShell modules that the script requires. +Each element can either be a string with the module name as value or a hashtable with the following keys: +Name: Name of the module +GUID: GUID of the module +One of the following: +ModuleVersion: Specifies a minimum acceptable version of the module. +RequiredVersion: Specifies an exact, required version of the module. +MaximumVersion: Specifies the maximum acceptable version of the module. + + + [string] +Specifies a PowerShell edition that the script requires. +Valid values are "Core" and "Desktop" + + + [switch] +Specifies that PowerShell must be running as administrator on Windows. +This must be the last parameter on the #requires statement line. + + + [version] +Specifies the minimum version of PowerShell that the script requires. + + + Specifies that the script requires PowerShell 7+ to run. + + + Specifies that the script requires Windows PowerShell 5.1 to run. + + + [string] +Required. Specifies the module name. + + + [string] +Optional. Specifies the GUID of the module. + + + [string] +Specifies a minimum acceptable version of the module. + + + [string] +Specifies an exact, required version of the module. + + + [string] +Specifies the maximum acceptable version of the module. + + + A brief description of the function or script. +This keyword can be used only once in each topic. + + + A detailed description of the function or script. +This keyword can be used only once in each topic. + + + .PARAMETER <Parameter-Name> +The description of a parameter. +Add a .PARAMETER keyword for each parameter in the function or script syntax. + + + A sample command that uses the function or script, optionally followed by sample output and a description. +Repeat this keyword for each example. + + + The .NET types of objects that can be piped to the function or script. +You can also include a description of the input objects. + + + The .NET type of the objects that the cmdlet returns. +You can also include a description of the returned objects. + + + Additional information about the function or script. + + + The name of a related topic. +Repeat the .LINK keyword for each related topic. +The .Link keyword content can also include a URI to an online version of the same help topic. + + + The name of the technology or feature that the function or script uses, or to which it is related. + + + The name of the user role for the help topic. + + + The keywords that describe the intended use of the function. + + + .FORWARDHELPTARGETNAME <Command-Name> +Redirects to the help topic for the specified command. + + + .FORWARDHELPCATEGORY <Category> +Specifies the help category of the item in .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Specifies a session that contains the help topic. +Enter a variable that contains a PSSession object. + + + .EXTERNALHELP <XML Help File> +The .ExternalHelp keyword is required when a function or script is documented in XML files. + + + Specifies the path to a .NET assembly to load. + +using assembly <.NET-assembly-path> + + + Specifies a PowerShell module to load classes from. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifies a .NET namespace to resolve types from or a namespace alias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifies an alias for a .NET Type. + +using type <AliasName> = <.NET-type> + + + A normal string. + + + A string that contains unexpanded references to environment variables that are expanded when the value is retrieved. + + + Binary data in any form. + + + A 32-bit binary number. + + + An array of strings. + + + A 64-bit binary number. + + + An unsupported registry data type. + + + ',' - Comma + + + ', ' - Comma-Space + + + ';' - Semi-Colon + + + '; ' - Semi-Colon-Space + + + {0} - Newline + + + '-' - Dash + + + ' ' - Space + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/TransactionStrings.fr.resx b/src/System.Management.Automation/resources/fr/TransactionStrings.fr.resx new file mode 100644 index 00000000000..0228c9341d4 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/TransactionStrings.fr.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nous ne pouvons pas utiliser la transaction. Aucune transaction n’est active. + + + Nous ne pouvons pas valider une transaction. Aucune transaction n’est active. + + + Nous ne pouvons pas restaurer la transaction, car aucune transaction n’est active. + + + Nous ne pouvons pas restaurer la transaction. La transaction a déjà été validée. + + + Nous ne pouvons pas valider une transaction. La transaction a déjà été validée. + + + Nous ne pouvons pas valider une transaction. La transaction a été restaurée ou a expiré. + + + Nous ne pouvons pas restaurer la transaction. La transaction a déjà été restaurée ou a expiré. + + + Nous ne pouvons pas définir de transaction active. Aucune transaction n’a été créée. + + + Nous ne pouvons pas définir de transaction active. La transaction active a été restaurée ou a expiré. + + + La cmdlet nécessite une transaction active. La transaction actuelle a déjà été validée ou restaurée. + + + Cette cmdlet requiert une transaction. Réexécutez la commande avec le paramètre -UseTransaction. + + + Nous ne pouvons pas utiliser la transaction. Aucune transaction n’a été lancée. + + + Nous ne pouvons pas utiliser la transaction. La transaction a été validée. + + + Nous ne pouvons pas utiliser la transaction. La transaction a été restaurée ou a expiré. + + + Nous ne pouvons pas utiliser la transaction. La transaction a expiré. + + + La transaction de base n’a pas été définie. + + + La transaction de base n’est pas active. + + + La transaction de base ne peut pas être définie après la création d’autres transactions. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/TypesXmlStrings.fr.resx b/src/System.Management.Automation/resources/fr/TypesXmlStrings.fr.resx new file mode 100644 index 00000000000..b26e799db6f --- /dev/null +++ b/src/System.Management.Automation/resources/fr/TypesXmlStrings.fr.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : Erreur : {3} + + + {0}, {1}({2}) : erreur dans le type « {3} » : {4} + + + Le nœud « {0} » ne doit apparaître qu’une seule fois sous « {1} ». Le nœud parent « {1} » sera ignoré. + + + Le nœud {0} n'est pas autorisé. Les nœuds suivants sont autorisés : {1}. + + + Le nœud « {0} » ne doit pas contenir un texte interne. + + + Le nœud « {0} » doit contenir un texte interne. + + + Le nœud « {0} » est introuvable. Il ne doit apparaître qu’une seule fois sous « {1} ». Le nœud parent « {1} » sera ignoré. + + + Le nœud « Type » doit contenir « Members », « TypeConverters » ou « TypeAdapters ». + + + Nous ne pouvons pas créer une instance du convertisseur de type pour le type {0} en raison de l’exception suivante : {1}. + + + PowerShell ne peut pas créer une instance de l’adaptateur de type pour le type {0} en raison de l’exception suivante : {1}. + + + Le type adapté « {0} » n’est pas valide. + + + Le TypeConverter a été ignoré, car il existe déjà. + + + Le TypeAdapter a été ignoré, car il existe déjà. + + + Le type « {0} » doit être TypeConverter ou PSTypeConverter. + + + Le type « {0} » doit être un PSPropertyAdapter. + + + Le membre {0} est déjà présent. + + + Le nom de membre suivant est réservé : {0} + + + Exception : {0} + + + Le ScriptProperty doit avoir un accesseur get ou set. + + + Le CodeProperty doit avoir un accesseur get ou set. + + + {0}, {1} : {2} + + + La valeur doit être TRUE ou FALSE au lieu de {0}. + + + Le nœud « {0} » ne doit pas avoir l’attribut « {1} ». + + + {0}, {1} : Le fichier était introuvable. + + + {0}, {1} : le fichier a été ignoré, car il avait déjà été chargé par {2}. + + + Nous ne pouvons pas trouver la clé de Registre : {0}{1}. Utiliser {2} pour charger le fichier de configuration. + + + Le chemin d’accès {0} spécifié dans la clé de Registre : {1}{2}est introuvable. Utiliser {3} pour charger le fichier de configuration. + + + {0}, {1} : le fichier a été ignoré, car il n’a pas l’extension de nom de fichier ps1xml. + + + {0}, {1} : le fichier a été ignoré en raison de l’exception de validation suivante : {2}. + + + Le membre « {0} » doit être une note. + + + Nous ne pouvons pas convertir « {0} » : « {1} ». + + + N’utilisez pas le membre « {0} » ici. + + + Le membre « {0} » doit avoir le type « {1} ». + + + « {0} » doit être présent lorsque « {1} » est « {2} » et que « {3} » est « {4} ». + + + Une erreur précédente a entraîné l’ignorance de tous les paramètres de sérialisation. + + + « {0} » n’est pas un membre standard et sera ignoré. + + + Le chemin d’accès {0} n’est pas complet. Spécifiez un chemin d’accès complet vers le fichier de type. + + + Nous ne pouvons pas mettre à jour le TypeTable, car il a peut-être été créé en dehors de l’espace d’exécution. + + + Des erreurs se sont produites lors du chargement de TypeTable. Consultez la propriété Erreurs pour obtenir des messages d’erreur détaillés. + + + Erreur dans TypeData « {0} » : {1} + + + « {0} » doit avoir une valeur pour sa propriété « {1} ». + + + « {0} » ne doit pas avoir de valeur null ni de chaîne vide dans sa propriété « {1} ». + + + Le type « {0} » est introuvable. La valeur du nom de type doit correspondre au nom complet du type. Vérifiez le nom du type, puis exécutez de nouveau la commande. + + + Le TypeData doit contenir « Members », « TypeConverters », « TypeAdapters » ou « StandardMembers ». + + + Une table de types partagée ne peut pas être mise à jour avec plus d’une entrée. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/VerbDescriptionStrings.fr.resx b/src/System.Management.Automation/resources/fr/VerbDescriptionStrings.fr.resx new file mode 100644 index 00000000000..57cbb3cba28 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/VerbDescriptionStrings.fr.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ajoute une ressource à un conteneur ou attache un élément à un autre élément + + + Confirme ou accepte l’état d’une ressource ou d’un processus + + + Affirme l’état d’une ressource + + + Stocke des données en les répliquant + + + Restreint l’accès à une ressource + + + Crée un artefact (généralement un fichier binaire ou un document) à partir d’un ensemble de fichiers d’entrée (généralement du code source ou des documents déclaratifs) + + + Crée une capture instantanée de l’état actuel des données ou de leur configuration + + + Supprime toutes les ressources d’un conteneur, mais ne supprime pas le conteneur + + + Change l’état d’une ressource afin de la rendre inaccessible, indisponible ou inutilisable + + + Évalue les données d’une ressource par rapport aux données d’une autre ressource + + + Conclut une opération + + + Compacte les données d’une ressource + + + Accuse réception, vérifie ou valide l’état d’une ressource ou d’un processus + + + Crée un lien entre une source et une destination + + + Change les données d’une représentation en une autre lorsque la cmdlet prend en charge la conversion bidirectionnelle ou la conversion entre plusieurs types de données + + + Convertit un type principal d’entrée (le nom de la cmdlet indique l’entrée) en un ou plusieurs types de sortie pris en charge + + + Convertit à partir d’un ou plusieurs types d’entrée en un type de sortie principal (le substantif de l’applet de commande indique le type de sortie) + + + Copie une ressource vers un autre nom ou un autre conteneur + + + Examine une ressource pour diagnostiquer les problèmes opérationnels + + + Refuse, objecte, bloque ou s’oppose à l’état d’une ressource ou d’un processus + + + Envoie une application, un site web ou une solution à une ou plusieurs cibles distantes de manière à ce qu’un consommateur de cette solution puisse y accéder une fois le déploiement terminé + + + Configure une ressource à un état indisponible ou inactif + + + Rompt le lien entre une source et une destination + + + Détache une entité nommée d’un emplacement + + + Modifie des données existantes en ajoutant ou en supprimant du contenu + + + Configure une ressource à un état disponible ou actif + + + Spécifie une action qui permet à l’utilisateur de se placer dans une ressource + + + Définit l’environnement ou le contexte utilisé comme contexte le plus utilisé + + + Restaure l’état d’origine des données d’une ressource qui a été compressée + + + Encapsule l’entrée principale dans un magasin de données persistant, tel qu’un fichier, ou dans un format d’échange + + + Recherche un objet dans un conteneur inconnu, implicite, facultatif ou spécifié + + + Organise des objets sous une forme ou dans une disposition spécifiée + + + Spécifie une action qui récupère une ressource + + + Autorise l’accès à une ressource + + + Organise ou associe une ou plusieurs ressources + + + Rend une ressource indétectable + + + Crée une ressource à partir de données stockées dans un magasin de données persistant (tel qu’un fichier) ou dans un format d’échange + + + Prépare une ressource en vue de l’utiliser et lui affecte un état par défaut + + + Place une ressource dans un emplacement et l’initialise éventuellement + + + Effectue une action, telle que l’exécution d’une commande ou d’une méthode + + + Combine des ressources en une seule ressource + + + Applique des contraintes à une ressource + + + Sécurise une ressource + + + Identifie les ressources qui sont consommées par une opération spécifiée ou récupère des statistiques sur une ressource + + + Crée une ressource unique à partir de plusieurs ressources + + + Attache une entité nommée à un emplacement + + + Déplace une ressource d’un emplacement à un autre + + + Crée une ressource + + + Change l’état d’une ressource afin de la rendre accessible, disponible ou utilisable + + + Augmente l’efficacité d’une ressource + + + Envoie des données à partir de l’environnement + + + Utiliser le verbe Tester + + + Supprime un élément du haut d’une pile + + + Protège une ressource contre les attaques ou pertes + + + Met une ressource à la disposition d’autres utilisateurs + + + Ajoute un élément en haut d’une pile + + + Acquiert des informations à partir d’une source + + + Accepte les informations envoyées à partir d’une source + + + Réinitialise une ressource à l’état qui a été annulé + + + Crée une entrée pour une ressource dans un référentiel tel qu’une base de données + + + Supprime une ressource d’un conteneur + + + Change le nom d’une ressource + + + Restaure une ressource dans une condition utilisable + + + Demande une ressource ou des autorisations + + + Restaure une ressource à son état d’origine + + + Change la taille d’une ressource + + + Mappe une représentation abrégée d’une ressource à une représentation plus complète + + + Arrête une opération, puis la redémarre + + + Affecte à une ressource un état prédéfini, tel qu’un état défini par un point de contrôle + + + Démarre une opération qui a été suspendue + + + Spécifie une action qui n’autorise pas l’accès à une ressource + + + Préserve des données afin d’éviter toute perte + + + Crée une référence à une ressource dans un conteneur + + + Localise une ressource dans un conteneur + + + Envoie des informations à une destination + + + Remplace des données sur une ressource existante ou crée une ressource qui contient des données + + + Rend une ressource visible par l’utilisateur + + + Garantit que deux ressources ou plus sont dans le même état + + + Ignore une ou plusieurs ressources ou un ou plusieurs points dans une séquence + + + Sépare les parties d’une ressource + + + Lance une opération + + + Passe au point suivant ou à la ressource suivante dans une séquence + + + Interrompt une activité + + + Présente une ressource pour approbation + + + Suspend une activité + + + Spécifie une action qui alterne entre deux ressources, telles que le changement entre deux emplacements, responsabilités ou états + + + Vérifie l’opération ou la cohérence d’une ressource + + + Effectue le suivi des activités d’une ressource + + + Supprime les restrictions applicables à une ressource + + + Définit une ressource à son état précédent + + + Supprime une ressource d’un emplacement indiqué + + + Libère une ressource qui a été verrouillée + + + Supprime les mesures de sécurité d’une ressource qui ont été ajoutées pour la protéger contre les attaques ou pertes + + + Rend une ressource inaccessible à d’autres personnes + + + Supprime l’entrée d’une ressource d’un référentiel + + + Met à jour une ressource afin de maintenir son état, son exactitude ou sa conformité + + + Utilise ou inclut une ressource pour effectuer une opération + + + Suspend une opération jusqu’à ce qu’un événement spécifié se produise + + + Inspecte ou supervise en permanence une ressource afin de détecter les modifications + + + Ajoute des informations à une cible + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/fr/WildcardPatternStrings.fr.resx b/src/System.Management.Automation/resources/fr/WildcardPatternStrings.fr.resx new file mode 100644 index 00000000000..e1da0c72571 --- /dev/null +++ b/src/System.Management.Automation/resources/fr/WildcardPatternStrings.fr.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 + + + Le modèle de caractère générique spécifié n’est pas valide : {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/Authenticode.it.resx b/src/System.Management.Automation/resources/it/Authenticode.it.resx new file mode 100644 index 00000000000..9f3e087356e --- /dev/null +++ b/src/System.Management.Automation/resources/it/Authenticode.it.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 + + + Non è possibile caricare il file {0} perché hai scelto di non eseguire subito il software. + + + Non è possibile caricare il file {0} perché hai scelto di non eseguire mai software di questo editore. + + + Il file {0} è pubblicato da {1}. L'editore è esplicitamente considerato non attendibile nel sistema. Lo script non verrà eseguito nel sistema. Per ulteriori informazioni, eseguire il comando Get-Help about_Signing. + + + Non è possibile caricare il file {0} perché l'esecuzione di script è disabilitata nel sistema. Per altre informazioni, vedi about_Execution_Policies all'indirizzo https://go.microsoft.com/fwlink/?LinkID=135170. + + + Non è possibile caricare il file {0}. {1}. + + + Non è possibile caricare il file {0} perché il relativo funzionamento è bloccato da criteri di restrizione al software, ad esempio da quelli creati tramite Criteri di gruppo. + + + Non è possibile caricare il file {0} perché non è possibile leggerne il contenuto. + + + Non è possibile firmare il codice. Il certificato specificato non è adatto per la firma del codice. + + + Non è possibile firmare il codice. L'URL del server TimeStamp deve essere completo e nel formato http://<url server> o https://<url server>. + + + Non è possibile firmare il codice. L'algoritmo hash non è supportato. + + + Vuoi eseguire il software di questo editore non attendibile? + + + Il file {0} è pubblicato da {1} e non è considerato attendibile nel sistema. Esegui solo script di editori attendibili. + + + Il software {0} è pubblicato da un editore sconosciuto. È consigliabile non eseguire questo software. + + + Avviso di sicurezza + + + Esegui solo gli script attendibili. Sebbene gli script provenienti da Internet possano essere utili, questo script può potenzialmente danneggiare il computer. Se consideri attendibile lo script, usa il cmdlet Unblock-File per consentirne l'esecuzione senza questo messaggio di avviso. Vuoi eseguire {0}? + + + Non eseguire &mai + + + Non eseguire subito lo script dell'editore e non continuare a chiedermi di eseguirlo in futuro. I tentativi futuri di eseguire lo script restituiranno un errore silenzioso. + + + &Non eseguire + + + Non eseguire subito lo script dell'editore e continua a chiedermi di eseguirlo in futuro. + + + &Esegui una volta + + + Esegui subito lo script dell'editore e continua a chiedermi di eseguirlo in futuro. + + + Esegui &sempre + + + Esegui subito lo script dell'editore e non continuare a chiedermi di eseguirlo in futuro. + + + &Sospendi + + + Sospendi la pipeline corrente e torna al prompt dei comandi. Al termine, digita exit per riprendere l'operazione. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/AuthorizationManagerBase.it.resx b/src/System.Management.Automation/resources/it/AuthorizationManagerBase.it.resx new file mode 100644 index 00000000000..7ccaa31d5f3 --- /dev/null +++ b/src/System.Management.Automation/resources/it/AuthorizationManagerBase.it.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 + + + Verifica di AuthorizationManager non riuscita. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/AutomationExceptions.it.resx b/src/System.Management.Automation/resources/it/AutomationExceptions.it.resx new file mode 100644 index 00000000000..01228164374 --- /dev/null +++ b/src/System.Management.Automation/resources/it/AutomationExceptions.it.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile elaborare l'argomento perché il valore dell'argomento "{0}" non è valido. Modificare il valore dell'argomento "{0}" ed eseguire di nuovo l'operazione. + + + Non è possibile elaborare l'argomento perché il valore del parametro "{0}" non è valido. I valori validi sono "Global", "Local" o "Script" oppure un numero relativo all'ambito corrente (tra 0 e il numero di ambiti, dove 0 è l'ambito corrente e 1 è il relativo ambito padre). Modificare il valore del parametro "{0}" ed eseguire di nuovo l'operazione. + + + Non è possibile elaborare l'argomento perché il valore dell'argomento "{0}" è null. Modificare il valore dell'argomento "{0}" in un valore non null. + + + Non è possibile elaborare l'argomento perché il valore dell'argomento "{0}" non rientra nell'intervallo. Modificare il valore dell'argomento "{0}" in un valore compreso nell'intervallo. + + + Non è possibile eseguire l'operazione perché l'operazione "{0}" non è valida. Rimuovere l'operazione "{0}" oppure individuare il motivo per cui non è valida. + + + Non è possibile eseguire l'operazione perché l'operazione "{0}" non è implementata. + + + Non è possibile eseguire l'operazione perché l'operazione "{0}" non è supportata. + + + Non è possibile eseguire l'operazione perché l'oggetto "{0}" è già stato eliminato. + + + Non è possibile richiamare il blocco di script perché contiene più di una clausola. Il metodo Invoke() può essere usato solo su blocchi di script che contengono una singola clausola. + + + Non è possibile convertire il blocco di script perché contiene più di una clausola. Le espressioni o le strutture di controllo non sono consentite. Verificare che il blocco di script contenga esattamente una pipeline o un comando. + + + Non è possibile convertire un blocco di script vuoto. Verificare che il blocco di script contenga esattamente una pipeline o un comando. + + + È possibile convertire solo un blocco di script che contenga esattamente una pipeline o un comando. Le espressioni o le strutture di controllo non sono consentite. Verificare che il blocco di script contenga esattamente una pipeline o un comando. + + + Non è possibile convertire un blocco di script contenente un'istruzione trap di primo livello. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che dereferenzia variabili non dichiarate nel blocco param(...). Nome della variabile non dichiarata: {0}. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che restituisce espressioni non costanti. Espressione non costante: {0}. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che restituisce espressioni dinamiche. Espressione dinamica: {0}. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che tenta di passare altri blocchi di script all'interno dei valori degli argomenti. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che richiama pipeline, comandi o funzioni per restituire gli argomenti della pipeline principale. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che usa il dot sourcing. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che richiama altri blocchi di script. + + + Non è possibile convertire il blocco di script in un oggetto PowerShell perché contiene operatori di reindirizzamento non consentiti. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock a cui non è associato un contesto dell'operazione. + + + Il comando è stato interrotto dall'utente. + + + L'oggetto "{0}" è di tipo errato per essere restituito dal blocco dynamicparam. Il blocco dynamicparam deve restituire $null o un oggetto di tipo [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + Non è possibile convertire il blocco di script in un tipo generico aperto. Definire un tipo generico chiuso appropriato e riprovare. + + + Non è possibile generare un oggetto PowerShell per uno ScriptBlock che avvia una pipeline con un'espressione. + + + Non è possibile recuperare il valore della variabile using "$using:{0}" perché non è stata impostata nella sessione locale. + + + Non è possibile ottenere il valore dell'espressione Using "{0}" nel dizionario delle variabili specificato. Quando si crea un'istanza di PowerShell da un blocco di script, l'espressione Using non può contenere un'operazione di indicizzazione o di accesso ai membri. + + + Dot sourcing del blocco di script compilato + + + La chiamata del blocco di script "{0}" nell'ambito corrente non sarà consentita in modalità Linguaggio con restrizioni. Modalità linguaggio script: {1}, modalità linguaggio contesto: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CatalogStrings.it.resx b/src/System.Management.Automation/resources/it/CatalogStrings.it.resx new file mode 100644 index 00000000000..9f7a48c23a8 --- /dev/null +++ b/src/System.Management.Automation/resources/it/CatalogStrings.it.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Impossibile generare il file di definizione del catalogo. + + + Aggiunta del file "{0}" al catalogo. Il percorso relativo del file nel catalogo è "{1}". + + + La convalida del file {0} del catalogo verrà ignorata. + + + Trovato file {0} nel catalogo con hash di {1}. + + + I percorsi per il catalogo contengono più file con lo stesso percorso relativo {0}. + + + Trovato file {0} su disco con hash di {1}. + + + La convalida del file {0} del percorso verrà ignorata. + + + Impossibile acquisire un handle per un contesto amministratore del catalogo per un determinato algoritmo hash {0}. + + + Impossibile creare l'hash per il file {0}. + + + Impossibile aprire il file di catalogo {0}. + + + La versione del catalogo non è valida. Sono supportate solo le versioni {0} e {1} del catalogo. + + + Impossibile aprire il file di definizione del catalogo. + + + Sono state trovate più voci del membro del file {0} nel catalogo. + + + Impossibile trovare il nome file o il percorso per il membro del catalogo {0}. + + + Impossibile trovare il file {0} per cui eseguire l'hashing. + + + Impossibile leggere il file {0} per calcolarne l'hash. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CimInstanceTypeAdapterResources.it.resx b/src/System.Management.Automation/resources/it/CimInstanceTypeAdapterResources.it.resx new file mode 100644 index 00000000000..744074bcfbd --- /dev/null +++ b/src/System.Management.Automation/resources/it/CimInstanceTypeAdapterResources.it.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile convertire "{0}" in un oggetto di tipo "{1}". + + + "{0}" è una proprietà di sola lettura. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CmdletizationCoreResources.it.resx b/src/System.Management.Automation/resources/it/CmdletizationCoreResources.it.resx new file mode 100644 index 00000000000..a1cf0e812df --- /dev/null +++ b/src/System.Management.Automation/resources/it/CmdletizationCoreResources.it.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet nella classe '{0}' + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Non è possibile elaborare Cmdlet Definition XML per il file seguente: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Non è possibile elaborare l'attributo ObjectModelWrapper. Il tipo {0} definisce più set di parametri. Verificare che in Cmdlet Definition XML sia specificato un tipo valido nell'attributo ObjectModelWrapper e riprovare. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Non è possibile elaborare l'attributo ObjectModelWrapper. Il tipo {0} è un tipo generico aperto. Verificare che in Cmdlet Definition XML sia specificato un tipo valido nell'attributo ObjectModelWrapper e riprovare. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Non è possibile elaborare l'attributo ObjectModelWrapper. Il tipo di {0} non è derivato dalla classe seguente: {1}. Verificare che in Cmdlet Definition XML sia specificato un tipo valido nell'attributo ObjectModelWrapper e riprovare. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Non è possibile elaborare l'attributo ObjectModelWrapper. Il tipo {0} definisce il parametro del cmdlet {1} con un parametro di attributo {2} ignorato. Verificare che in Cmdlet Definition XML sia specificato un tipo valido nell'attributo ObjectModelWrapper e riprovare. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Non è possibile definire il parametro {0} per il cmdlet {1}. Il nome del parametro è già definito dalla classe {2}. Modificare il nome del parametro in mdlet Definition XML e riprovare. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Non è possibile definire il parametro {0} per il cmdlet {1}. Il nome del parametro è già definito nell'elemento XML {2}. Modificare il nome del parametro in Cmdlet Definition XML e riprovare. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + Il valore dell'attributo EnumName non viene convertito in un identificatore C# valido: {0}. Verificare l'attributo EnumName in Cmdlet Definition XML e riprovare. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Non è possibile elaborare l'elemento <Enum EnumName="{0}" ...>. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + Il computer remoto ha restituito un file CDXML non valido. L'adattatore per cmdlet seguente non è supportato per l'importazione di un modulo CDXML da un computer remoto: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CommandBaseStrings.it.resx b/src/System.Management.Automation/resources/it/CommandBaseStrings.it.resx new file mode 100644 index 00000000000..cafc980a21e --- /dev/null +++ b/src/System.Management.Automation/resources/it/CommandBaseStrings.it.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Continuare con questa operazione? + + + &Sì + + + Continuare solo con il passaggio successivo dell'operazione. + + + Sì per t&utti + + + Continuare con tutti i passaggi dell'operazione. + + + &No + + + Ignorare questa operazione e procedere con l'operazione successiva. + + + N&o per tutti + + + Ignorare questa operazione e tutte le operazioni successive. + + + Arrestare questo comando. + + + Comando I&nterrompi + + + &Sospendi + + + Sospendere la pipeline corrente e tornare al prompt dei comandi. Digitare "{0}" per riprendere la pipeline. + + + + Il programma "{0}" è terminato con un codice di uscita diverso da zero: {1} ({2}). + + + Esecuzione dell'operazione "{0}" sulla destinazione "{1}". + + + What if: {0} + + + Eseguire questa azione? +{0} + + + Confermare + + + Il comando in esecuzione è stato arrestato perché la variabile di preferenza "{0}" o il parametro comune è impostato su Arresta: {1} + + + Il comando in esecuzione è stato arrestato perché la variabile di preferenza "{0}" o il parametro comune è impostato su Arresta. + + + Il comando in esecuzione è stato arrestato perché la variabile di preferenza "{0}" o il parametro comune è impostato sul valore seguente, che non è valido: "{1}". + + + Il comando in esecuzione è stato arrestato perché l'utente ha selezionato l'opzione Arresta. + + + Il comando in esecuzione è stato arrestato perché l'utente lo ha interrotto. + + + Impossibile richiamare direttamente i cmdlet derivati da PSCmdlet. + + + Il cmdlet '{0}' non supporta il parametro '{1}' in una sessione remota. + + + Numero totale: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Numero totale stimato: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Conteggio totale sconosciuto + Reviewed by TArcher on 2010-07-20 + + + comando '{0}' + + + L'oggetto {0} è obsoleto. {1} + + + Chiamata EXEC non riuscita con errore {0} per la riga di comando: {1} + + + Non è possibile trovare il comando "{0}". Il comando specificato deve essere un file eseguibile. + + + Controllo Dot-Source per elaborazione blocco script + + + L'elaborazione Dot-Source per il blocco di script '{0}' non riuscirà in modalità linguaggio con restrizioni perché la relativa modalità linguaggio '{1}' non corrisponde alla modalità linguaggio corrente '{2}'. + + + Strumento di ricerca comandi + + + Il comando '{0}' nel modulo '{1}' non è attendibile e non sarà accessibile in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ConsoleInfoErrorStrings.it.resx b/src/System.Management.Automation/resources/it/ConsoleInfoErrorStrings.it.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/it/ConsoleInfoErrorStrings.it.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CoreClrStubResources.it.resx b/src/System.Management.Automation/resources/it/CoreClrStubResources.it.resx new file mode 100644 index 00000000000..0e35bd74ccd --- /dev/null +++ b/src/System.Management.Automation/resources/it/CoreClrStubResources.it.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Il nome della variabile di ambiente non può contenere il segno di uguale. + + + Il nome o il valore della variabile di ambiente è troppo lungo. + + + Il primo carattere nella stringa è il carattere nullo. + + + La lunghezza della stringa non può essere zero. + + + Non è possibile ottenere il nome del computer. + + + Non è possibile ottenere il nome di dominio dell'utente corrente. + + + Errore sconosciuto: "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CredUI.it.resx b/src/System.Management.Automation/resources/it/CredUI.it.resx new file mode 100644 index 00000000000..ebb8e55c103 --- /dev/null +++ b/src/System.Management.Automation/resources/it/CredUI.it.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Richiesta di credenziali di PowerShell + + + Immettere le credenziali. + + + Immettere le credenziali. + + + La lunghezza massima della didascalia è {0} caratteri. + + + La lunghezza massima del messaggio è {0} caratteri. + + + La lunghezza massima del valore UserName è {0} caratteri. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/Credential.it.resx b/src/System.Management.Automation/resources/it/Credential.it.resx new file mode 100644 index 00000000000..b59b0b122a0 --- /dev/null +++ b/src/System.Management.Automation/resources/it/Credential.it.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 + + + Non è possibile serializzare le credenziali. Se questo comando avvia un flusso di lavoro, le credenziali non possono essere persistite, perché il processo in cui il flusso di lavoro viene avviato non dispone dell'autorizzazione per serializzare le credenziali. + +-- Se il flusso di lavoro è stato avviato in una PSSession sul computer locale, aggiungere il parametro EnableNetworkAccess al comando che ha creato la sessione. +-- Se il flusso di lavoro è stato avviato in una PSSession verso un computer remoto, aggiungi il parametro Autenticazione con valore CredSSP al comando che ha creato la sessione. In alternativa, connettersi a una configurazione di sessione che ha un valore della proprietà RunAsUser. + + + Il valore di UserName non è nel formato corretto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/CredentialAttributeStrings.it.resx b/src/System.Management.Automation/resources/it/CredentialAttributeStrings.it.resx new file mode 100644 index 00000000000..8de0b5b727c --- /dev/null +++ b/src/System.Management.Automation/resources/it/CredentialAttributeStrings.it.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 + + + Richiesta di credenziali di PowerShell + + + Immettere le credenziali. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/DebuggerStrings.it.resx b/src/System.Management.Automation/resources/it/DebuggerStrings.it.resx new file mode 100644 index 00000000000..6712c4f18e6 --- /dev/null +++ b/src/System.Management.Automation/resources/it/DebuggerStrings.it.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Punto di interruzione variabile in '${0}' ({1} accesso) + + + Punto di interruzione variabile in '{0}${1}' ({2} accesso) + + + Punto di interruzione riga in '{0}:{1}' + + + Punto di interruzione riga in '{0}:{1}, {2}' + + + Punto di interruzione comando in '{0}' + + + Punto di interruzione comando in '{0}:{1}' + + + Il punto di interruzione {0} non verrà raggiunto + + + {0}, {1,-16} Passaggio singolo (entra nelle funzioni, negli script e così via) + + + {0}, {1,-16} Passa all'istruzione successiva (salta le funzioni, gli script e così via) + + + {0}, {1,-16} Esci dalla funzione, dallo script correnti e così via. + + + {0}, {1,-16} Continua l'operazione + + + {0}, {1,-16} Interrompe l'operazione ed esce dal debugger + + + {0}, Get-PSCallStack Visualizza lo stack di chiamate + + + {0}, {1,-16} Elenca il codice sorgente per lo script corrente. + + + Usa "list" per iniziare dalla riga corrente, "list <m>" + + + per iniziare dalla riga <m> e "list <m> <n>" per elencare <n> + + + righe a partire dalla riga <m> + + + <enter> Ripeti l'ultimo comando se è stato {0}, {1} o {2} + + + {0}, {1,-16} visualizza questo messaggio della guida. + + + Per istruzioni su come personalizzare il prompt del debugger, digita "help about_prompt". + + + +La sessione corrente non supporta il debug; l'operazione proseguirà. + + + + + {0}: riga {1} + + + Non sono disponibili codici sorgente. + + + La riga di inizio deve essere un numero intero positivo non maggiore di {0} + + + Il numero di righe deve essere un numero intero positivo. + + + <No file> + + + in {0}, {1}: riga {2} + + + Il debugger non può elaborare i comandi se lo stato è Arrestato. + + + SetDebugAction non è implementato per il debugger degli script locali. + + + Il debugger non può impostare un'azione di ripristino perché lo stato del debugger nella sessione remota non è Arrestato. + + + Non è possibile eseguire il debug del processo perché il debugger è attualmente occupato. + + + Il processo specificato e tutti i processi figlio sono stati esaminati, ma non sono stati trovati processi di cui eseguire il debug. Per eseguire il debug di un processo o di un processo figlio, il è necessario che il processo supporti il debug e sia anche in esecuzione. + + + Non è possibile abilitare il debugger per la modalità passo a passo perché il debugger è disattivato e la modalità debug è impostata su Nessuna. + + + Non è possibile eseguire il debug dello spazio di esecuzione perché il debugger host è attualmente occupato. + + + Non è possibile eseguire il debug dello spazio di esecuzione. Il debugger dello spazio di esecuzione è attualmente disattivato (DebugMode è impostato su 'Nessuna'). + + + Non è possibile eseguire il debug di uno spazio di esecuzione il cui stato non è Aperto. Lo stato dello spazio di esecuzione è {0}. + + + Non è possibile eseguire il debug dello spazio di esecuzione. Lo spazio di esecuzione {0} non è associato al debugger. + + + Il debugger è già stato sostituito. + + + Non è possibile eseguire il push di un oggetto debugger su se stesso. + + + Il comando {0} non è supportato per l'uso remoto nella versione di PowerShell in esecuzione nello spazio di esecuzione remoto. + + + Processo + + + {0}, {1,-16} Continua l'operazione e scollega il debugger. + + + Il comando di scollegamento del debugger non è applicabile. Il comando di scollegamento si applica solo quando si esegue il debug di processi e spazi di esecuzione con i cmdlet Debug-Job o Debug-Runspace. + + + ID dello spazio di esecuzione non valido: {0} + + + Non è possibile recuperare lo spazio di esecuzione. + + + È necessario specificare un punto di interruzione o BreakpointList. + + + BreakpointList conteneva un elemento che non era un punto di interruzione. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/DescriptionsStrings.it.resx b/src/System.Management.Automation/resources/it/DescriptionsStrings.it.resx new file mode 100644 index 00000000000..6ebd2bddd52 --- /dev/null +++ b/src/System.Management.Automation/resources/it/DescriptionsStrings.it.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 + + + {0} non può essere Null né vuoto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/DiscoveryExceptions.it.resx b/src/System.Management.Automation/resources/it/DiscoveryExceptions.it.resx new file mode 100644 index 00000000000..d49de865de2 --- /dev/null +++ b/src/System.Management.Automation/resources/it/DiscoveryExceptions.it.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 + + + Non è possibile convalidare il nome del cmdlet "{0}" perché il formato non è corretto. I nomi dei cmdlet devono includere un verbo e un sostantivo separati da "-", ad esempio "Get-Process". + + + Il parametro "{0}" è dichiarato più volte nel set di parametri "{1}". + + + L'alias "{0}" viene dichiarato più volte. + + + Non è possibile dichiarare il parametro. I parametri possono essere dichiarati solo su campi e proprietà. + + + Non è possibile elaborare il cmdlet. Il nome di un cmdlet deve essere costituito da una coppia verbo-sostantivo separata da '-'. + + + Il termine '{0}' non è riconosciuto come nome di un cmdlet, di una funzione, di un file di script o di un programma eseguibile. +Verificare l'ortografia del nome, che il percorso sia incluso e corretto, quindi riprovare. + + + L'argomento '{0}' non è riconosciuto come cmdlet: {1} + + + L'argomento '{0}' non è riconosciuto come cmdlet, probabilmente perché non deriva dalle classi Cmdlet o PSCmdlet: {1} + + + Non è possibile risolvere l'alias '{0}' perché fa riferimento al termine '{1}', che non è riconosciuto come cmdlet, funzione, programma eseguibile o file di script. Verificare il termine e riprovare. + + + Non è possibile elaborare il parametro '{0}' con valore '{1}' perché non è un cmdlet e non può essere elaborato da CommandProcessor. + + + Esiste già un cmdlet denominato '{0}'. I nomi dei cmdlet devono essere univoci. + + + Esiste già un provider di cmdlet denominato '{0}'. I provider di cmdlet devono avere nomi univoci. + + + Esiste già un assembly denominato '{0}'. I nomi degli assembly devono essere univoci. + + + Esiste già uno script denominato "{0}". I nomi degli script devono essere univoci. + + + Non è possibile elaborare l'istruzione #requires perché il formato non è corretto. +L'istruzione #requires deve essere in uno dei formati seguenti: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + Non è possibile eseguire lo script '{0}' perché contiene un'istruzione "#requires" con ID shell {1} incompatibile con la shell corrente. Per eseguire questo script è necessario usare la shell in '{2}'. + + + Non è possibile eseguire lo script '{0}' perché contiene un'istruzione "#requires" con ID shell {1} incompatibile con la shell corrente. + + + Non è possibile eseguire lo script '{0}' perché contiene un'istruzione "#requires" per PowerShell {1}. La versione di PowerShell richiesta dallo script non corrisponde alla versione attualmente in esecuzione di PowerShell {2}. + + + Non è possibile eseguire lo script '{0}' perché contiene un'istruzione "#requires" per le edizioni di PowerShell '{1}'. L'edizione di PowerShell richiesta dallo script non corrisponde all'edizione di PowerShell {2} attualmente in esecuzione. + + + Non è possibile eseguire lo script '{0}' perché mancano gli snap-in seguenti, specificati dalle istruzioni '#requires' dello script: {1}. + + + In un'istruzione #requires è stato specificato solo un ID shell. Le istruzioni #Requires devono specificare uno snap-in di PowerShell obbligatorio durante l'esecuzione in PowerShell. + + + Non è possibile eseguire lo script '{0}' perché contiene un'istruzione "#requires" per l'esecuzione come amministratore. La sessione di PowerShell corrente non è in esecuzione come amministratore. Avvia PowerShell usando l'opzione Esegui come amministratore, quindi prova a eseguire di nuovo lo script. + + + {0} (Versione {1}) + + + Non è possibile recuperare il comando perché il parametro ArgumentList può essere specificato solo quando si recupera un singolo cmdlet o script. + + + Il nome del parametro "{0}" è riservato per usi futuri. + + + Non è possibile eseguire lo script '{0}' perché mancano i moduli seguenti, specificati dalle istruzioni '#requires' dello script: {1}. + + + Il comando '{0}' è stato trovato nel modulo '{1}', ma non è stato possibile caricare il modulo. Per altre informazioni, eseguire 'Import-Module {1}'. + + + Il comando '{0}' è stato trovato nel modulo '{1}', ma non è stato possibile caricare il modulo a causa del seguente errore: [{2}] +Per altre informazioni, eseguire 'Import-Module {1}'. + + + Non è possibile caricare il modulo '{0}'. Per altre informazioni, eseguire 'Import-Module {0}'. + + + Nessun comando corrispondente include un parametro denominato '{0}'. Controllare l'ortografia del nome del parametro, quindi riprovare. + + + Non è possibile eseguire il comando con dot-sourcing perché è stato definito in una modalità linguaggio diversa. Per richiamare questo comando senza importarne il contenuto, omettere l'operatore '.'. + + + I parametri ShowCommandInfo e Syntax non possono essere specificati insieme. + + + Questo comando per script è disabilitato quando la funzionalità sperimentale '{0}' è attivata. + + + Questo comando per script è disabilitato quando la funzionalità sperimentale '{0}' è disattivata. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/EnumExpressionEvaluatorStrings.it.resx b/src/System.Management.Automation/resources/it/EnumExpressionEvaluatorStrings.it.resx new file mode 100644 index 00000000000..9e67231e4ab --- /dev/null +++ b/src/System.Management.Automation/resources/it/EnumExpressionEvaluatorStrings.it.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + L'espressione di input non deve essere vuota. Specificare almeno un nome di identificatore in ogni espressione di input. + + + Non è possibile trovare una corrispondenza tra un nome di identificatore vuoto e un nome di enumeratore valido. Specificare uno dei seguenti nomi di enumeratore e riprovare: {0}. + + + Il tipo generico specificato per l'espressione deve rappresentare un'enumerazione. Specificare un tipo di enumerazione valido. + + + Il nome dell'identificatore {0} non può essere elaborato perché è troppo simile o identico ai seguenti nomi di enumeratore: {1}. Usare un nome di identificatore più specifico. + + + Non è possibile trovare una corrispondenza tra il nome dell'identificatore {0} e un nome di enumeratore valido. Specificare uno dei seguenti nomi di enumeratore e riprovare: +{1} + + + L'uso delle parentesi non è valido nell'espressione perché il raggruppamento degli identificatori non è consentito. Provare a rimuovere le parentesi, oppure, se è racchiusa una sottoespressione, provare a espandere l'espressione. + + + Non è possibile analizzare l'espressione a causa di un token imprevisto. Dopo un nome di identificatore è previsto solo un operatore OR (,) o AND (+). + + + Non è possibile analizzare l'espressione a causa di un token imprevisto dopo un operatore NOT (!). Dopo un operatore NOT (!) è previsto un nome di identificatore. + + + Non è possibile analizzare l'espressione a causa di un token imprevisto. All'inizio dell'espressione, oppure dopo un operatore OR (,) o AND (+), è previsto un nome di identificatore, oppure un operatore NOT (!). Inoltre, un'espressione non deve terminare con un operatore OR (,), AND (+) o NOT (!). + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ErrorCategoryStrings.it.resx b/src/System.Management.Automation/resources/it/ErrorCategoryStrings.it.resx new file mode 100644 index 00000000000..6e71dd7c6ff --- /dev/null +++ b/src/System.Management.Automation/resources/it/ErrorCategoryStrings.it.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Rilevato deadlock: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + Non abilitato: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Categoria errore non riconosciuta {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ErrorPackage.it.resx b/src/System.Management.Automation/resources/it/ErrorPackage.it.resx new file mode 100644 index 00000000000..a26d15cf2b7 --- /dev/null +++ b/src/System.Management.Automation/resources/it/ErrorPackage.it.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 + + + {0}…{1} + + + Il testo dell'errore è vuoto per l'errore "{0}": "{1}" + + + L'oggetto "{0}" viene segnalato come errore. + + + Il valore {0} non è supportato per una variabile ActionPreference. Il valore specificato deve essere usato solo come valore per un parametro di preferenza ed è stato sostituito dal valore predefinito. Per altre informazioni, vedere l'argomento "about_Preference_Variables" della Guida. + + + Il valore {0} ActionPreference è riservato a un uso futuro e non è al momento supportato. Per ulteriori informazioni sulle variabili di preferenza, vedere l'argomento "about_Preference_Variables" della Guida. + + + Il valore {0} ActionPreference è riservato a un uso futuro e non è al momento supportato. È stato sostituito nella variabile {1} con il valore predefinito di {2}. Per ulteriori informazioni sulle variabili di preferenza, vedere l'argomento "about_Preference_Variables" della Guida. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/EtwLoggingStrings.it.resx b/src/System.Management.Automation/resources/it/EtwLoggingStrings.it.resx new file mode 100644 index 00000000000..e1ad2a36f52 --- /dev/null +++ b/src/System.Management.Automation/resources/it/EtwLoggingStrings.it.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Il comando {0} è {1}. + + + Stato del motore modificato da {0} a {1}. + + + ID errore completo = {0} + + + Messaggio di errore = {0} + + + Azione consigliata = {0} + + + Criteri di esecuzione + + + Comando processo = {0} + + + ID processo = {0} + + + ID istanza processo = {0} + + + Posizione processo = {0} + + + Nome processo = {0} + + + Stato del processo = {0} + + + Nome comando = + + + Percorso comando = + + + Tipo di comando = + + + Versione motore = + + + ID host = + + + Nome host = + + + Applicazione host = + + + Versione host = + + + ID pipeline = + + + ID spazio di esecuzione = + + + Nome script = + + + Numero sequenza = + + + Gravità = + + + ID shell = + + + Ora = + + + Utente = + + + Utente connesso = + + + Processo NULL + + + Nome provider + + + Il provider {0} ha cambiato stato in {1}. + + + L'esecuzione di script è {0}. + + + Variabile {0} modificata da {1} a {2}. + + + La variabile {0} è stata modificata in {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/EventResource.it.resx b/src/System.Management.Automation/resources/it/EventResource.it.resx new file mode 100644 index 00000000000..e0e344dd806 --- /dev/null +++ b/src/System.Management.Automation/resources/it/EventResource.it.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Non è stato trovato alcun messaggio per l'ID evento PowerShell.Core.Instrumentation.man. + + + Il processo pianificato {0} è stato avviato alle {1} + + + + Il processo pianificato {0} è stato completato alle {1} con stato {2} + + + + Eccezione processo pianificato {0}: + Messaggio: {1} + StackTrace: {2} + InnerException: {3} + + + + Inizializzazione della funzionalità sperimentale: ignora la funzionalità sperimentale '{0}' dal file di configurazione. {1} + + + Inizializzazione della funzionalità sperimentale: non è stato possibile leggere il file di configurazione. + Eccezione: {0} + Messaggio: {1} + StackTrace: {2} + + + + Plug-in del flusso di lavoro caricato. + EndpointName: {0} + Utente: {1} + HostingMode: {2} + Protocollo: {3} + Configurazione: + {4} + + + Esecuzione del flusso di lavoro avviata. + WorkflowId: {0} + ManagedNodes: {1} + + + Stato del flusso di lavoro modificato. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + È stato richiesto l'arresto del plug-in del flusso di lavoro. + EndpointName: {0} + + + Plug-in del flusso di lavoro riavviato. + EndpointName: {0} + + + Il flusso di lavoro è in ripresa. + WorkflowId: {0} + + + È stato superato un limite di quota impostato per l'endpoint. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + Flusso di lavoro ripreso. + WorkflowId: {0} + + + Pool di spazi di esecuzione del flusso di lavoro creato. + WorkflowId: {0} + ManagedNode: {1} + + + L'attività è stata accodata per l'esecuzione. + WorkflowId: {0} + ActivityName: {1} + + + Esecuzione attività avviata. + ActivityName: {0} + ActivityTypeName: {1} + + + È in corso l'importazione del flusso di lavoro da un file XAML. + WorkflowId: {0} + XamlFile: {1} + + + Il flusso di lavoro è stato importato da un file XAML. + WorkflowId: {0} + XamlFile: {1} + + + Non è possibile importare il flusso di lavoro da un file XAML a causa di un errore. + WorkflowId: {0} + ErrorDescription: {1} + + + Convalida del flusso di lavoro avviata. + WorkflowId: {0} + + + Convalida dell'esportazione eseguita correttamente. + WorkflowId: {0} + + + Convalida del flusso di lavoro non riuscita con errore. + WorkflowId: {0} + + + Attività del flusso di lavoro convalidata. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Non è possibile convalidare l'attività del flusso di lavoro. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Esecuzione attività non riuscita. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + La disponibilità dello spazio di esecuzione ha subito variazioni. + RunspaceId: {0} + Disponibilità: {1} + + + Stato dello spazio di esecuzione modificato. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Flusso di lavoro caricato per l'esecuzione. + WorkflowId: {0} + + + Flusso di lavoro scaricato. + WorkflowId: {0} + + + Esecuzione del flusso di lavoro annullata. + WorkflowId: {0} + + + Esecuzione del flusso di lavoro interrotta. + WorkflowId: {0} + + + Operazione di pulizia del flusso di lavoro eseguita. + WorkflowId: {0} + + + Flusso di lavoro salvato permanentemente caricato dal disco. + WorkflowId: {0} + Percorso: {1} + + + I dati del flusso di lavoro sono stati eliminati dal disco. + WorkflowId: {0} + Percorso: {1} + + + Avvio del processo di rimozione. + JobId: {0} + + + Stato del processo modificato. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Errore del processo. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Processo creato per il flusso di lavoro (processo figlio). + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Processo padre creato per il flusso di lavoro. + JobId: {0} + + + Tutti i processi necessari sono stati creati per l'esecuzione del flusso di lavoro. + JobId: {0} + WorkflowId: {1} + + + Processo figlio rimosso per il flusso di lavoro. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + Si è verificato un errore durante la rimozione del processo. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Errore: {3} + + + Caricamento del flusso di lavoro per l'esecuzione. + WorkflowId: {0} + + + Esecuzione del flusso di lavoro completata. + WorkflowId: {0} + + + Annullamento dell'esecuzione del flusso di lavoro. + WorkflowId: {0} + + + Interruzione dell'esecuzione del flusso di lavoro. + WorkflowId: {0} + Motivo: {1} + + + Scaricamento del flusso. + WorkflowId: {0} + + + Arresto forzato del flusso di lavoro avviato. + WorkflowId: {0} + + + Arresto forzato del flusso di lavoro completato. + WorkflowId: {0} + + + Si è verificato un errore durante l'arresto forzato di un flusso di lavoro. + WorkflowId: {0} + ErrorDescription: {1} + + + Salvataggio permanente del flusso di lavoro su disco. + WorkflowId: {0} + PersistPath: {1} + + + Flusso di lavoro salvato permanentemente su disco. + WorkflowId: {0} + + + Esecuzione dell'attività completata. + ActivityName: {0} + + + Errore di esecuzione del flusso di lavoro. + WorkflowId: {0} + ErrorDescription: {1} + + + È stato registrato un nuovo endpoint di PowerShell. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Configurazione endpoint modificata. + EndpointName: {0} + ModifiedBy: {1} + + + Registrazione della configurazione endpoint annullata. + EndpointName: {0} + UnregisteredBy: {1} + + + Configurazione dell'endpoint disabilitata. + EndpointName: {0} + DisabledBy: {1} + + + Configurazione endpoint abilitata. + EndpointName: {0} + Abilitato da: {1} + + + Spazio di esecuzione out-of-process avviato. + Comando: {0} + + + Lo splatting dei parametri è stato eseguito durante l'esecuzione del flusso di lavoro. + Parametri: {0} + Computer: {1} + + + Motore del flusso di lavoro avviato. + EndpointName: {0} + + + Istanza di Workflow Manager creata con + CheckpointPath: {0} + ConfigProviderId: {1} + Nome utente: {2} + Percorso: {3} + + + Nome computer $null o . risolto in LocalHost + + + Risoluzione nello schema predefinito http + + + Il nome della shell remota è stato risolto in PowerShellCore predefinito + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + Creazione del testo di Scriptblock ({0} di {1}): +{2} + +ID ScriptBlock: {3} +Percorso: {4} + + + Chiamata ID ScriptBlock avviata: {0} +ID spazio di esecuzione: {1} + + + Chiamata ID ScriptBlock completata: {0} +ID spazio di esecuzione: {1} + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + {2} + +Contesto: +{0} + +Dati utente: +{1} + + + + Correlazione degli ID attività. + CurrentActivityId: {0} + ParentActivityId: {1} + + + Nome della classe = {0} +Nome metodo = {1} +GUID flusso di lavoro = {2} +Messaggio = {3} +{4} +Nome attività = {5} +GUID attività = {6} +Parametri = {7} + + + Creazione dell'oggetto Spazio di esecuzione + ID istanza: {0} + + + Creazione dell'oggetto RunspacePool + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Apertura di RunspacePool + + + Modifica dell'ID attività e correlazione + + + Lo stato dello spazio di esecuzione è stato modificato in {0} + + + Tentativo di ripetizione della creazione della sessione {0} per il codice di errore {1} nell'Id sessione {2} + + + PowerShell ha avviato un thread di ascolto IPC sul processo: {0} in AppDomain: {1}. + + + PowerShell ha terminato un thread di ascolto IPC sul processo: {0} in AppDomain: {1}. + + + Si è verificato un errore nel thread di ascolto IPC di PowerShell nel processo: {0} in AppDomain: {1}. Messaggio di errore: {2}. + + + Connessione IPC di PowerShell sul processo: {0} in AppDomain: {1} per l'utente: {2}. + + + Disconnessione IPC di PowerShell nel processo: {0} in AppDomain: {1} per l'utente: {2}. + + + Porta risolta in {0} + + + AppName risolto in {0} + + + ComputerName risolto in {0} + + + Lo schema è {0} + + + Messaggio di analisi di test + + + I parametri di connessione sono + URI connessione: {0} + URI risorsa: {1} + Utente: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Stampa identificazione personale: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Modifica dell'ID attività e correlazione + + + Oggetto ricevuto con ID spazio di esecuzione: {0} ID comando: {1} Destinazione: {2} DataType: {3} TargetInterface: {4} + + + Si è verificata un'eccezione non gestita nell'appdomain. +Tipo di eccezione: {0} +Messaggio eccezione:{1} +StackTrace eccezione: {2} + + + ID spazio di esecuzione: {0} ID pipeline: {1}. WSMan ha segnalato un errore con codice errore: {2}. + Messaggio di errore: {3} + StackTrace: {4} + + + Si è verificata un'eccezione non gestita nell'appdomain. +Tipo di eccezione: {0} +Messaggio eccezione:{1} +StackTrace eccezione: {2} + + + ID spazio di esecuzione: {0} ID pipeline: {1}. WSMan ha segnalato un errore con codice errore: {2}. + Messaggio di errore: {3} + StackTrace: {4} + + + ID spazio di esecuzione {0}. Stabilire una connessione usando WSMan Create Shell + + + ID spazio di esecuzione {0}. Callback ricevuto per WSMan Create Shell + + + ID spazio di esecuzione: {0}. Chiusura della shell tramite WSManCloseShell + + + ID spazio di esecuzione: {0}. Callback ricevuto per WSManCloseShell + + + ID spazio di esecuzione: {0} ID pipeline: {1}. Invio di dati di dimensioni {2} + + + ID spazio di esecuzione: {0} ID pipeline: {1}. Callback ricevuto per WSManSendShellInputEx + + + ID spazio di esecuzione: {0} ID pipeline: {1}. Invio della richiesta di ricezione tramite WSManReceiveShellOutputEx + + + ID spazio di esecuzione: {0} ID pipeline: {1}. Ricezione di dati di dimensioni {2}. + + + ID spazio di esecuzione: {0} ID pipeline {1}. Stabilire una connessione del comando tramite WSManRunShellCommandEx + + + ID spazio di esecuzione: {0} ID pipeline {1}. Callback ricevuto per la connessione del comando + + + ID spazio di esecuzione: {0} ID pipeline {1}. Chiusura del trasporto per il comando + + + ID spazio di esecuzione: {0} ID pipeline {1}. Callback ricevuto per la chiusura del comando + + + ID spazio di esecuzione: {0} ID pipeline {1}. Invio del segnale con codice {2} tramite WSManSignalShellEx + + + ID spazio di esecuzione: {0} ID pipeline {1}. Callback ricevuto per WSManSignalShellEx + + + ID spazio di esecuzione: {0}. La connessione viene reindirizzata all'URI: {1} + + + ID spazio di esecuzione: {0} ID pipeline: {1}. Il server sta inviando dati di dimensioni {2} al client. DataType: {3} TargetInterface: {4} + + + Richiesta {0}. Creazione di una sessione remota del server. Nome utente: {1} ID shell personalizzata: {2} + + + Contesto di segnalazione per la richiesta: {0} Contesto segnalato: {0} + + + Operazione di report completata per la richiesta: {0} + Codice errore: {1} + Messaggio di errore: {2} + StackTrace: {3} + + + Contesto shell {0}. ID richiesta {1}. Creazione di una sessione comune per l'esecuzione di un comando. + + + Contesto shell {0} Contesto comando {1} ID richiesta {2}. Arresto del comando. + + + Contesto shell {0} Contesto comando {1} ID richiesta {2}. Dati ricevuti dal client. + + + Contesto shell {0} Contesto comando {1} ID richiesta {2}. Il client ha inviato una richiesta di ricezione in modo che il server possa inviare i dati. + + + Contesto shell {0}Contesto comando {1} IsReceiveOperation {2}. Ricevuta richiesta di chiusura dell'operazione. + + + Caricamento dell'assembly {0} per la shell personalizzata con ID shell {1} + + + Caricamento del tipo {0} per la shell personalizzata con ID shell {1} + + + Ricevuto frammento di comunicazione remota. + ID oggetto: {0} + ID frammento: {1} + Flag di inizio: {2} + Flag di fine: {3} + Lunghezza payload: {4} + Dati payload: {5} + + + Frammento di comunicazione remota inviato. + ID oggetto: {0} + ID frammento: {1} + Flag di inizio: {2} + Flag di fine: {3} + Lunghezza payload: {4} + Dati payload: {5} + + + Arresto del servizio Gestione remota Windows. + + + Oggetto riattivato correttamente. + Nome del tipo deserializzato: {0} + Riattivato eseguendo il cast al tipo: {1} + L'oggetto riattivato è di tipo: {2} + + + Non è possibile reidratare un oggetto. + Nome del tipo deserializzato: {0} + Riattivato eseguendo il cast al tipo: {1} + Eccezione di cast del tipo: {2} + Eccezione interna di cast del tipo: {3} + + + La profondità di serializzazione è stata sostituita. + Nome del tipo serializzato: {0} + Profondità originale: {1} + Profondità sostituita: {2} + Profondità corrente sotto il livello superiore: {3} + + + La modalità di serializzazione è stata sostituita. + Nome del tipo serializzato: {0} + Modalità sostituita: {1} + + + La serializzazione di una proprietà script è stata ignorata perché non è disponibile alcun spazio di esecuzione da usare per la valutazione della proprietà. + Nome proprietà:{0} + Nome del tipo proprietario della proprietà: {1} + Script del getter: {2} + + + La serializzazione di una proprietà è stata ignorata perché il getter della proprietà non è riuscito. + Nome proprietà:{0} + Nome del tipo proprietario della proprietà: {1} + Eccezione del getter della proprietà: {2} + Eccezione interna del getter della proprietà: {3} + + + La serializzazione di un oggetto enumerabile potrebbe non essere completa, perché l'oggetto in enumerazione ha generato un'eccezione. + Tipo di oggetto in enumerazione: {0} + Eccezione: {1} + + + La serializzazione ha chiamato il metodo ToString dell'oggetto, ma non è riuscito. + Tipo di oggetto: {0} + Eccezione: {1} + + + È stata raggiunta la profondità massima sotto il livello superiore, quindi l'oggetto verrà serializzato come stringa. + Tipo di oggetto alla profondità massima: {0} + Nome proprietà alla profondità massima: {1} + Profondità: {2} + + + XmlException generata dal deserializzatore (molto probabilmente indica un formato clixml non corretto). + Numero di riga: {0} Posizione riga: {1} + Eccezione: {2} + + + La serializzazione delle proprietà specificate non è riuscita perché una delle proprietà specificate non era presente. + Tipo di oggetto: {0} + Nome proprietà: {1} + + + È il corso l'avvio della console di PowerShell + + + La console di PowerShell è pronta per l'input dell'utente + + + {0} + + + Tracciamento ErrorRecord: + Messaggio: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + Dettagli eccezione: + Messaggio: {5} + Analisi dello stack: {6} + InnerException {7} + + + + Eccezione: + Messaggio: {0} + StackTrace: {1} + InnerException : {2} + + + + Traccia di PSObject + + + Processo di traccia: + ID: {0} + InstanceId: {1} + Nome: {2} + Posizione: {3} + Stato: {4} + Comando: {5} + + + + Informazioni di traccia: + {0} + + + Informazioni di traccia: + {0} {1} + + + INIZIO di ImportWorkflowCommand::StartWorkflowApplication. Avvio della chiamata alla funzione del flusso di lavoro. GUID di rilevamento {0} + + + FINE ImportWorkflowCommand::StartWorkflowApplication. Terminazione della chiamata della funzione del flusso di lavoro. GUID di rilevamento {0} + + + BEGIN Creazione di un nuovo processo in ImportWorkflowCommand::StartWorkflowApplication. GUID di rilevamento {0} + + + FINE della creazione di un nuovo processo in ImportWorkflowCommand::StartWorkflowApplication. GUID di rilevamento {0} + + + FINE della creazione di un nuovo processo in ImportWorkflowCommand::StartWorkflowApplication. GUID di rilevamento {0} : ContainerParentJob GUID {1} + + + INIZIO JobLogic ContainerParentJob GUID {0} + + + FINE JobLogic ContainerParentJob GUID {0} + + + INIZIO WorkflowExecution ContainerParentJob GUID {0} + + + FINE WorkflowExecution ContainerParentJob GUID {0} + + + WorkflowJob con GUID {0} aggiunto a ContainerParentJob con GUID {1} + + + ProxyJob con GUID {0} associato al ContainerParentJob remoto con GUID {1} + + + INIZIO esecuzione di ContainerParentJob con GUID {0} + + + FINE esecuzione di ContainerParentJob con GUID {0} + + + INIZIO esecuzione del processo proxy con GUID {0} + + + FINE esecuzione del processo proxy con GUID {0} + + + INIZIO gestore dell'evento StateChanged per il processo proxy con GUID {0} + + + FINE gestore dell'evento StateChanged per il processo proxy con GUID {0} + + + INIZIO gestore dell'evento StateChanged per il processo figlio proxy con GUID {0} + + + FINE gestore dell'evento StateChanged per il processo figlio proxy con GUID {0} + + + INIZIO esecuzione di GC + + + FINE esecuzione di GC + + + L'archivio salvataggi permanenti ha raggiunto le dimensioni massime specificate + + + Windows PowerShell ISE ha avviato l'esecuzione del file di script {0}. + + + Windows PowerShell ISE ha avviato l'esecuzione di uno script selezionato dall'utente dal file {0}. + + + Windows PowerShell ISE sta interrompendo il comando corrente. + + + Windows PowerShell ISE sta riprendendo il debugger. + + + Windows PowerShell ISE sta interrompendo il debugger. + + + Windows PowerShell ISE sta entrando il modalità di debug. + + + Windows PowerShell ISE sta eseguendo lo step-over di debug. + + + Windows PowerShell ISE sta uscendo dal debug. + + + Windows PowerShell ISE sta abilitando tutti i punti di interruzione. + + + Windows PowerShell ISE sta disabilitando tutti i punti di interruzione. + + + Windows PowerShell ISE sta rimuovendo tutti i punti di interruzione. + + + Windows PowerShell ISE sta impostando il punto di interruzione nella riga #: {0} del file {1}. + + + Windows PowerShell ISE sta rimuovendo il punto di interruzione nella riga #: {0} del file {1}. + + + Windows PowerShell ISE sta abilitando il punto di interruzione alla riga #: {0} del file {1}. + + + Windows PowerShell ISE sta disabilitando il punto di interruzione nella riga #: {0} del file {1}. + + + Windows PowerShell ISE ha raggiunto un punto di interruzione alla riga #: {0} del file {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/EventingResources.it.resx b/src/System.Management.Automation/resources/it/EventingResources.it.resx new file mode 100644 index 00000000000..00c791a3530 --- /dev/null +++ b/src/System.Management.Automation/resources/it/EventingResources.it.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Non è possibile registrarsi per l'evento specificato. Gli eventi che richiedono un valore restituito non sono supportati. + + + Non è possibile registrarsi per l'evento specificato. Un evento con il nome "{0}" non esiste. + + + PowerShell non può sottoscrivere eventi di Windows RT. + + + Non è possibile registrarsi per l'evento specificato. L'identificatore dell'origine eventi "{0}" è riservato al motore di PowerShell. + + + Questa operazione non è supportata nelle istanze remote. + + + L'azione non è supportata durante l'inoltro degli eventi. + + + Non è possibile sottoscrivere l'evento specificato. Esiste già un sottoscrittore con l'identificatore di origine "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ExperimentalFeatureStrings.it.resx b/src/System.Management.Automation/resources/it/ExperimentalFeatureStrings.it.resx new file mode 100644 index 00000000000..40f58d3e234 --- /dev/null +++ b/src/System.Management.Automation/resources/it/ExperimentalFeatureStrings.it.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Non è stata trovata alcuna funzionalità sperimentale corrispondente al nome "{0}". + + + L'attivazione e la disattivazione delle funzionalità sperimentali non hanno effetto fino al successivo avvio di PowerShell. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ExtendedTypeSystem.it.resx b/src/System.Management.Automation/resources/it/ExtendedTypeSystem.it.resx new file mode 100644 index 00000000000..2536a63b1cc --- /dev/null +++ b/src/System.Management.Automation/resources/it/ExtendedTypeSystem.it.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Il membro "{0}" è già presente. + + + Il membro "{0}" è già presente nel file di dati dei tipi estesi. + + + Il membro "{0}" non è presente. + + + Eccezione durante l'impostazione di "{0}": "{1}" + + + Eccezione durante l'impostazione di "{0}": "{1}" + + + Si è verificata l'eccezione seguente durante il tentativo di enumerare la raccolta: "{0}". + + + Non è possibile accedere al membro "{0}" al di fuori di un PSObject. + + + Non è possibile modificare il membro creato dalla configurazione del tipo: "{0}". + + + Il nome del membro "{0}" è riservato. + + + Non è possibile modificare "{0}". + + + Eccezione durante la chiamata di "{0}" con "{1}" argomento/i: "{2}" + + + È stata generata un'eccezione durante il tentativo di chiamare "{0}" per estrarre il contenuto di un oggetto di tipo "{1}": "{2}" + + + Non è possibile trovare un overload per "{0}" e il numero di argomenti: "{1}". + + + Non è possibile trovare un overload del metodo generico adatto per "{0}" con parametri di tipo "{1}" e numero di argomenti: "{2}". + + + Sono stati trovati più overload ambigui per "{0}" e il numero di argomenti: "{1}". + + + Non è possibile convertire l'argomento "{0}" con il valore "{1}" per "{2}" nel tipo "{3}": "{4}" + + + La funzione di accesso Get per la proprietà "{0}" non è disponibile. + + + La funzione di accesso Set per la proprietà "{0}" non è disponibile. + + + Il metodo setter deve essere public, void, static e includere due parametri. Il primo parametro deve essere di tipo PSObject. Un secondo parametro è necessario se è disponibile anche un metodo getter e deve restituire lo stesso tipo del metodo getter. + + + Il metodo getter deve essere pubblic, non void, static e contenere un parametro di tipo PSObject. + + + CodeProperty deve usare un metodo getter o setter. + + + Non è possibile creare un metodo code a causa del formato del metodo. Il metodo deve essere public, static e contenere un parametro di tipo PSObject. + + + L'alias denominato "{0}" contiene un ciclo. + + + Non è possibile convertire il tipo "{0}" del valore "{1}" nel tipo "{2}". + + + Non è possibile convertire il tipo "{0}" del valore nel tipo "{1}". + + + Non è possibile convertire il valore "{0}" nel tipo "{1}". Errore: "{2}" + + + Non è possibile convertire il valore "{0}" nel tipo "{1}" perché non sono consentite virgole per l'enumerazione. + + + Non è possibile convertire il valore "{0}" nel tipo "{1}" perché i valori di enumerazione non sono validi.. Specificare uno dei seguenti valori di enumerazione e riprovare. I valori di enumerazione possibili sono "{2}". + + + Non è possibile convertire null nel tipo "{0}" perché i valori di enumerazione non sono validi. Specificare uno dei seguenti valori di enumerazione e riprovare. I valori di enumerazione possibili sono "{1}". + + + Non è possibile convertire null nel tipo "{0}". + + + Non è possibile convertire il valore nel tipo "{0}". Errore: "{1}" + + + Non è possibile convertire il valore nel tipo System.String. + + + Nell'argomento è previsto il tipo di riferimento. + + + Non è possibile confrontare "{0}" perché non è I paragonabile. + + + Non è possibile confrontare "{0}" con "{1}". Errore: "{2}" + + + Non è possibile confrontare "{0}" con "{1}" perché gli oggetti non sono dello stesso tipo oppure l'oggetto "{0}" non implementa "{2}". + + + Non è possibile convertire il valore "{0}" nel tipo "{1}" perché sono state trovate almeno due corrispondenze ({2}, {3}) e per questa enumerazione ne è consentita una sola. + + + Non è possibile convertire il valore "{0}" nel tipo "{1}". I parametri booleani accettano solo valori booleani e numeri, ad esempio $True, $False, 1 o 0. + + + Non è possibile recuperare il valore della proprietà perché "{0}" è una proprietà in sola scrittura. + + + "{0}" è una proprietà di sola lettura. + + + Non è possibile impostare "{0}" perché è possibile usare come valori solo le stringhe per impostare le proprietà XmlNode. + + + Non è possibile impostare "{0}" perché è possibile impostare solo attributi univoci o nodi foglia univoci senza attributi. + + + Non è possibile aggiungere un oggetto PSProperty o PSMethod alla raccolta. + + + Si è verificato l'errore seguente durante il caricamento del file di dati dei tipi estesi: {0} + + + Si è verificata l'eccezione seguente durante il recupero della stringa: "{0}" + + + Il campo o la proprietà "{0}" per il tipo "{1}" differisce dal campo o dalla proprietà "{2}" solo per l'uso di maiuscole e minuscole. Il tipo deve essere conforme a CLS (Common Language Specification). + + + Si è verificata l'eccezione seguente durante il recupero della gerarchia dei nomi dei tipi "{0}". + + + Si è verificata l'eccezione seguente durante il recupero del membro "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero dei membri: "{0}" + + + Si è verificata l'eccezione seguente durante il recupero dello stato della lettura per la proprietà "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero dello stato della scrittura per la proprietà "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero del tipo per la proprietà "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero della rappresentazione di stringa per la proprietà "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero degli attributi per la proprietà "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero delle definizioni per il metodo "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero della rappresentazione di stringa per il metodo "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero del tipo per la proprietà parametrizzata "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero dello stato della lettura per la proprietà parametrizzata "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero dello stato della scrittura per la proprietà parametrizzata {1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero delle definizioni per la proprietà parametrizzata "{1}": "{0}" + + + Si è verificata l'eccezione seguente durante il recupero della rappresentazione di stringa per la proprietà parametrizzata "{1}": "{0}" + + + Non è possibile impostare la proprietà Value per l'oggetto PSMemberInfo di tipo "{0}". + + + L'argomento: '{0}' deve essere un/una {1}. Usare {2}. + + + Argomento: '{0}' non deve essere un/una {1}. Non usare {2}. + + + Impossibile trovare la proprietà "{0}". + + + Non è possibile recuperare né impostare il valore della proprietà. Il tipo dell'argomento "{0}" deve essere "{1}" o "{2}". + + + Non è possibile impostare il valore della proprietà "{0}" perché l'oggetto è di tipo "{1}" anziché "{2}". + + + Eccezione durante la chiamata di "{0}": "{1}" + + + {0} non è un percorso di classe non valido. + + + {0} non è un percorso valido. + + + L'adattatore non riesce a determinare se la proprietà "{0}" può essere modificata. + + + L'adattatore non riesce a determinare se la proprietà "{0}" può essere recuperata. + + + L'adattatore non riesce a recuperare il valore della proprietà "{0}". + + + L'adattatore non riesce a impostare il valore della proprietà "{0}". + + + L'adattatore non riesce a recuperare il tipo di proprietà "{0}". + + + L'adattatore non è riuscito a recuperare la gerarchia dei tipi di "{0}". + + + L'adattatore non riesce a ottenere le proprietà di "{0}". + + + L'adattatore non riesce a recuperare la proprietà "{0}" per "{1}". + + + "{0}" ha restituito il valore null. + + + La proprietà '{0}' non è stata trovata per l'oggetto '{1}'. Le proprietà impostabili sono: {2}. + + + La proprietà '{0}' non è stata trovata per l'oggetto '{1}'. Non sono disponibili proprietà impostabili. + + + Non è possibile creare un oggetto di tipo "{0}". {1} + + + Non è possibile richiamare metodi static o accedere a proprietà static nel tipo generico aperto {0}. Specificare i parametri del tipo e riprovare. Ad esempio, usare [System.Collections.Generic.HashSet[int]]::CreateSetComparer() anziché [System.Collections.Generic.HashSet``1]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + Si è verificata l'eccezione seguente durante la creazione dell'attributo "{1}": "{0}" + + + Non è possibile convertire il valore "{0}" in un array stringa. + + + Non è possibile convertire il valore nel tipo "{0}". In questa modalità linguaggio sono supportati solo i tipi di base. + + + Non è possibile eseguire la conversione nel tipo simile a ByRef "{0}". I tipi simili a ByRef non sono supportati in PowerShell. + + + Non è possibile recuperare né né impostare la proprietà o il campo "{0}" del tipo simile a ByRef "{1}". I tipi simili a ByRef non sono supportati in PowerShell. + + + Non è possibile richiamare il metodo "{0}" del tipo restituito simile a ByRef "{1}". I tipi simili a ByRef non sono supportati in PowerShell. + + + Non è possibile creare un'istanza del tipo simile a ByRef "{0}". I tipi simili a ByRef non sono supportati in PowerShell. + + + Conversione della tabella hash del sistema di tipi estesi + + + La conversione del tipo da HashTable in '{0}' non sarà consentita in modalità ConstrainedLanguage. + + + Conversione della tabella hash del sistema di tipi estesi + + + La conversione del tipo da '{0}' a '{1}' non sarà consentita in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/FileSystemProviderStrings.it.resx b/src/System.Management.Automation/resources/it/FileSystemProviderStrings.it.resx new file mode 100644 index 00000000000..00a2d9e1470 --- /dev/null +++ b/src/System.Management.Automation/resources/it/FileSystemProviderStrings.it.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Richiama elemento + + + Elemento: {0} + + + Rimuovi file + + + Rimuovere la directory + + + Copia file + + + Elemento: {0} Destinazione: {1} + + + Copia directory + + + Rinomina file + + + Rinomina directory + + + Elemento: {0} Destinazione: {1} + + + Sposta file + + + Sposta directory + + + Elemento: {0} Destinazione: {1} + + + Imposta file di proprietà + + + Imposta directory delle proprietà + + + Elemento: {0} Proprietà: {1} Valore: {2} + + + Cancella file delle proprietà + + + Cancella directory delle proprietà + + + Elemento: {0} Proprietà: {1} + + + Crea file + + + Crea directory + + + Destinazione: {0} + + + Cancella contenuto + + + Elemento: {0} + + + Non è possibile trovare l'elemento {0}. + + + Non è possibile rimuovere {0}elemento : {1} + + + Non è possibile ripristinare gli attributi dell'elemento {0}: {1} + + + Un oggetto nel percorso specificato {0} non esiste. + + + Non è possibile rimuovere la directory {0} perché non è vuota. + + + Il tipo non è un tipo noto per il file system. È possibile specificare solo "file","directory" o "symboliclink". + + + Non è possibile elaborare il percorso perché il percorso specificato fa riferimento a un elemento esterno a basePath. + + + La radice dell'unità specificata "{0}" non esiste oppure non è una cartella. + + + Esiste già un elemento con il nome specificato {0}. + + + Non è possibile specificare un delimitatore durante la lettura del flusso di un byte alla volta. + + + Non è possibile sovrascrivere l'elemento {0} con se stesso. + + + Non è possibile rinominare la destinazione specificata perché rappresenta un percorso o un nome di dispositivo. + + + La proprietà {0} non esiste o non è stata trovata. + + + Non si dispone di diritti di accesso sufficienti per eseguire questa operazione oppure l'elemento è nascosto, di sistema o di sola lettura. + + + Non è possibile impostare l'attributo perché gli attributi non sono supportati. È possibile impostare solo i seguenti attributi: Archive, Hidden, Normal, ReadOnly, o System. + + + Non è possibile cancellare la proprietà perché non è supportata. È possibile cancellare solo la proprietà Attributes. + + + Non è possibile elaborare il percorso ''{0}'' perché la destinazione rappresenta un nome di dispositivo riservato. + + + Codifica non utilizzata quando è specificato ''-AsByteStream''. + + + Non è possibile procedere con la codifica byte. Quando si utilizza la codifica byte, il contenuto deve essere di tipo byte. + + + Non è possibile elaborare il file perché il file {0} non è stato trovato. + + + Directory: + + + Non è possibile rilevare la codifica del file. La codifica specificata {0} non è supportata quando il contenuto viene letto in direzione inversa. + + + Non è possibile aprire il flusso di dati alternativo ''{0}'' del file ''{1}''. + + + Flusso ''{0}'' del file ''{1}''. + + + Non è possibile specificare i parametri Raw e Wait nello stesso comando. + + + Per utilizzare il parametro di commutazione Persist, il nome dell'unità deve essere supportato dal sistema operativo (ad esempio, lettere di unità A-Z). + + + Quando si utilizza il parametro Persist, la radice deve essere un percorso del file system in un computer remoto. + + + Non è possibile specificare i parametri ''{0}'' e ''{1}'' nello stesso comando. + + + Per l'operazione è necessaria una directory. L'elemento ''{0}'' non è una directory. + + + Crea giunzione + + + Crea collegamento simbolico + + + Per questa operazione sono necessari i privilegi di Amministratore. + + + Crea collegamento reale + + + Per l'operazione è necessario un file. L'elemento ''{0}'' non è un file. + + + I collegamenti reali non sono supportati per il percorso specificato. + + + I collegamenti simbolici non sono supportati per il percorso specificato. + + + Copia di {0} in {1} + + + Il percorso di destinazione {0} è un file già esistente nella destinazione. + + + Non è possibile copiare il file {0} nella destinazione remota. + + + Da {0} a {1} + + + Non è possibile copiare una directory ''{0}'' nel file ''{0}'' + + + Non è possibile ottenere gli elementi figlio della directory {0}. + + + Non è possibile leggere il file remoto ''{0}''. + + + Non è possibile verificare se la destinazione remota {0} è un file. + + + Non è possibile creare la directory ''{0}'' nella destinazione remota. + + + È stata superata la dimensione massima per l'unità: {0}. + + + Non è possibile creare il collegamento perché il percorso esiste già: {0}. + + + Ignora directory già visitata {0}. + + + Il percorso di destinazione non può essere una sottodirectory dell'origine o l'origine stessa: {0}. + + + La destinazione e il percorso non possono essere uguali. + + + Copiati {0} di {1} file + + + {0} di {1} ({2:0.0} MB/s) + + + Rimozione completata di {0} di {1} file + + + {0} di {1} ({2:0.0} MB/s) + + + La creazione di una giunzione richiede un percorso assoluto per la destinazione. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/FormatAndOutXmlLoadingStrings.it.resx b/src/System.Management.Automation/resources/it/FormatAndOutXmlLoadingStrings.it.resx new file mode 100644 index 00000000000..cf53cc07c1f --- /dev/null +++ b/src/System.Management.Automation/resources/it/FormatAndOutXmlLoadingStrings.it.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Errore in XPath {0} nel file {1}: l'elemento XML {2} non consente attributi. + + + Errore in XPath {0} nel file {1}: il nodo {2} non può avere oggetti figlio. + + + Errore in XPath {0} nel file {1}: {2} non è valido. + + + Errore in XPath {0} nel file {1}: è necessario specificare almeno un valore predefinito {2}. + + + Errore in XPath {0} nel file {1}: non può esserci più di un valore predefinito {2}. + + + Errore in XPath {0} nel file {1}: il nome del controllo non può essere null o vuoto. + + + Errore in XPath {0} nel file {1}: le visualizzazioni Out Of Band possono avere solo CustomControl o ListControl. + + + Errore in XPath {0} nel file {1}: una visualizzazione Out Of Band non può avere GroupBy. + + + Errore in XPath {0} nel file {1}: non è possibile caricare la visualizzazione. + + + Errore in XPath {0} nel file {1}: "{2}" non è un valore di allineamento valido. + + + Errore in XPath {0} nel file {1}: è previsto un numero intero positivo. + + + Errore in XPath {0} nel file {1}: la definizione dell'intestazione di colonna non è valida; tutte le intestazioni verranno ignorate. + + + Errore in XPath {0} nel file {1}: il numero di elementi della riga = {2} nel set alternativo #{3} non corrisponde al numero di elementi della riga predefinita = {4}. + + + Errore in XPath {0} nel file {1}: il numero di elementi dell'intestazione = {2} non corrisponde al numero di elementi della riga predefinita = {3}. + + + Errore in XPath {0} nel file {1}: è necessario specificare almeno un elemento della visualizzazione elenco. + + + Errore in XPath {0} nel file {1}: la voce di proprietà non è valida. + + + Errore in XPath {0} nel file {1}: manca l'elenco delle definizioni. + + + Errore in XPath {0} nel file {1}: è previsto un valore booleano. + + + Errore in XPath {0} nel file {1}: è previsto un numero intero non negativo. + + + Errore in XPath {0} nel file {1}: è previsto un numero intero. + + + Errore in XPath {0} nel file {1}: manca il valore del testo interno. + + + Errore in XPath {0} nel file {1}: l'elenco dei token del controllo personalizzato non può essere vuoto. + + + Errore in XPath {0} nel file {1}: {2} non è possibile caricare. + + + Errore in XPath {0} nel file {1}: {2} non può essere specificato senza un'espressione. + + + Errore in XPath {0} nel file {1}: {2} non può essere specificato con un'espressione. + + + Errore in XPath {0} nel file {1}: manca una stringa di formato. + + + Errore in XPath {0} nel file {1}: manca il testo del blocco di script. + + + Errore in XPath {0} nel file {1}: manca una proprietà. + + + Errore in XPath {0} nel file {1}: il blocco di script "{2}" non è valido. + + + Errore in XPath {0} nel file {1}: la stringa {2} della risorsa {3} nell'assembly {4} non è stata trovata. + + + Errore in XPath {0} nel file {1}: la risorsa {2} nell'assembly {3} non è stata trovata. + + + Errore in XPath {0} nel file {1}: non è possibile trovare l'assembly {2}. + + + Errore in XPath {0} nel file {1}: il nodo deve essere un XmlElement. + + + Errore in XPath {0} nel file {1}: è necessaria un'espressione. + + + Errore in XPath {0} nel file {1}: non è possibile avere un controllo o un'etichetta senza un'espressione. + + + Errore in XPath {0} nel file {1}: controllo ed etichetta non possono essere presenti contemporaneamente. + + + Errore in XPath {0} nel file {1}: SelectionSetName e TypeName non possono essere presenti contemporaneamente. + + + Errore in XPath {0} nel file {1}: non è specificato alcun tipo o condizione per l'applicazione della visualizzazione. + + + Errore in XPath {0} nel file {1}: il valore {2} non è valido. + + + Errore in XPath {0} nel file {1}: esiste un nodo duplicato. + + + Errore in XPath {0} nel file {1}: {2} e {3} si escludono a vicenda. + + + Errore in XPath {0} nel file {1}: {2}, {3} e {4} si escludono a vicenda. + + + Errore in XPath {0} nel file {1}: {2} è un nodo sconosciuto. + + + Errore in XPath {0} nel file {1}: {2} è un attributo sconosciuto. + + + Errore in XPath {0} nel file {1}: {2} è un attributo mancante. + + + Errore in XPath {0} nel file {1}: il nodo {2} è mancante. + + + Errore in XPath {0} nel file {1}: manca un nodo in {2}. + + + Errore in XPath {0} nel file {1}: {2} è un nodo vuoto. + + + Errore in XPath {0} nel file {1}: {2} è un attributo vuoto. + + + Errore nel file {0}: {1} + + + Troppi errori nel file {0}. + + + Si sono verificati errori durante il caricamento del file di dati di formato: {0} + + + (Global Assembly Cache) {0} + + + {0}, {1} + + + Il percorso {0} non è completo. Specificare un percorso di file con formato completo. + + + Non è possibile aggiornare FormatTable perché potrebbe essere stata creata all'esterno dello spazio di esecuzione. + + + Si sono verificati errori durante il caricamento di FormatTable. Visualizzare il contenuto della proprietà Errors per ottenere messaggi di errore dettagliati. + + + Errore durante la formattazione dei dati "{0}": {1} + + + Errore nei dati della visualizzazione con nome di tipo {0} all'indice {1}: il numero di elementi dell'intestazione = {2} non corrisponde al numero predefinito di elementi della riga = {3}. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: i dati di formattazione "{2}" non sono validi. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: il blocco di script "{2}" non è valido. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: caricamento di {2} non riuscito. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: un TableControl deve contenere solo un elemento {2}. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: è necessario specificare almeno un valore predefinito {2}. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: è necessario specificare almeno un elemento della visualizzazione elenco. + + + Errore nei dati di visualizzazione con nome di tipo {0} all'indice {1}: non può esserci più di un valore predefinito {2}. + + + Troppi errori nei dati di formattazione per il tipo "{0}". + + + Non è possibile aggiornare una tabella di formato condivisa con più di una voce. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/FormatAndOut_MshParameter.it.resx b/src/System.Management.Automation/resources/it/FormatAndOut_MshParameter.it.resx new file mode 100644 index 00000000000..d62a0b10f13 --- /dev/null +++ b/src/System.Management.Automation/resources/it/FormatAndOut_MshParameter.it.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 + + + Non è possibile convertire {0} in uno dei tipi seguenti {1}. + + + Il valore di un parametro è Null; è previsto uno dei tipi seguenti: {0}. + + + La chiave duplicata "{0}" è in conflitto con "{1}". + + + La chiave "{0}" contiene un tipo, {1}, non valido; i tipi previsti sono {2}. + + + La chiave "{0}" contiene un tipo, {1}, non valido; il tipo previsto è {2}. + + + La chiave {0} è ambigua; {1} e {2} sono in conflitto. + + + Il valore di una chiave non può essere Null. + + + Il tipo di chiave {0} non è valido. La chiave deve essere una stringa. + + + La chiave {0} non ha alcun valore. + + + Manca una voce obbligatoria per {0}. + + + La chiave {0} non è valida. + + + Il valore "{0}" per la chiave "{1}" non è valido; i valori validi sono {2}. + + + Il valore "{0}" per la chiave "{1}" deve essere maggiore di 0. + + + La chiave "{0}" non può contenere una stringa di formattazione vuota. + + + La chiave "{0}" non può contenere una stringa vuota come valore. + + + Non è consentito specificare una stringa vuota come valore. + + + La chiave "{0}" non può contenere caratteri jolly nel valore "{1}". + + + I caratteri jolly non sono consentiti in "{0}". + + + Il valore di EnumerableExpansion non è valido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/FormatAndOut_format_xxx.it.resx b/src/System.Management.Automation/resources/it/FormatAndOut_format_xxx.it.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/it/FormatAndOut_format_xxx.it.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/FormatAndOut_out_xxx.it.resx b/src/System.Management.Automation/resources/it/FormatAndOut_out_xxx.it.resx new file mode 100644 index 00000000000..f7637438e75 --- /dev/null +++ b/src/System.Management.Automation/resources/it/FormatAndOut_out_xxx.it.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> pagina successiva; <CR> riga successiva; Q esci + + + Il valore di LineOutput non deve essere Null. + + + Il tipo lineOutput {0} non era previsto; LineOutput prevede il tipo {1}. + + + L'oggetto di tipo "{0}" non è valido o non è nella sequenza corretta. È probabile che sia causato da un comando "{1}" specificato dall'utente, in conflitto con la formattazione predefinita. + + + Impossibile aprire il file "{0}". + + + Output su file + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/GetErrorText.it.resx b/src/System.Management.Automation/resources/it/GetErrorText.it.resx new file mode 100644 index 00000000000..b0abb19b95d --- /dev/null +++ b/src/System.Management.Automation/resources/it/GetErrorText.it.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile caricare una risorsa con nome di base "{0}". + + + Non è possibile caricare una stringa di risorsa con ID "{0}". + + + L'esecuzione dei comandi è impedita dalle impostazioni dei criteri di interruzione. + + + Non è possibile recuperare il messaggio "{0}" "{1}" "{2}" perché un assembly non è stato registrato. + + + Non è possibile recuperare il messaggio "{0}" "{1}" "{2}". Il formato della stringa modello non è valido nella stringa modello "{3}". + + + Non è possibile recuperare il messaggio "{0}" "{1}" "{2}". Esiste una stringa modello, ma il relativo valore è vuoto. + + + La pipeline è stata arrestata. + + + Lo script non è riuscito a causa dell'overflow della profondità di chiamata. + + + La pipeline non è riuscita a causa dell'overflow della profondità di chiamata. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/HelpDisplayStrings.it.resx b/src/System.Management.Automation/resources/it/HelpDisplayStrings.it.resx new file mode 100644 index 00000000000..3ea965943a0 --- /dev/null +++ b/src/System.Management.Automation/resources/it/HelpDisplayStrings.it.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NOME + + + RIEPILOGO + + + DESCRIPTION + + + SYNTAX + + + PARAMETRI + + + INPUT + + + OUTPUT + + + ERRORI IRREVERSIBILI + + + ERRORI NON FATALI + + + NOTE + + + ESEMPI + + + Esempio + + + ESEMPIO + + + OUTPUT + + + COLLEGAMENTI CORRELATI + + + DESCRIZIONE BREVE + + + Titolo: + + + Domanda: + + + Risposta + + + Termine: + + + Definizione: + + + Contenuto: + + + NOME DEL PROVIDER + + + Questo cmdlet supporta i parametri comuni: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable e OutVariable. Per altre informazioni, vedere + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Obbligatorio? + + + Posizione? + + + Tipo: + + + Tipo oggetto di destinazione: + + + Valore predefinito + + + Accettare input da pipeline? + + + Accettare caratteri jolly? + + + (Categoria: + + + Azione suggerita: + + + Per ulteriori informazioni, digitare: + + + Per informazioni tecniche, digitare: + + + Per visualizzare gli esempi, digitare: + + + Per visualizzare la Guida, digitare: + + + <CommonParameters> + + + REMARKS + + + true + + + Denominato + + + UNITÀ + + + FUNZIONALITÀ + + + ATTIVITÀ + + + ATTIVITÀ: + + + FILTRI + + + PARAMETRI DINAMICI + + + Cmdlet supportati: + + + ALIAS + + + Get-Help non riesce a trovare i file della Guida per questo cmdlet in questo computer. Viene visualizzata solo una parte della Guida. + -- Per scaricare e installare i file della Guida per il modulo che include questo cmdlet, usare Update-Help. + -- Per visualizzare l'argomento della Guida per questo cmdlet online, digitare "Get-Help {0} -Online" o + Passa a {1}. + + + Nessuno + + + Alias + + + Dinamica? + + + Nome del set di parametri + + + Non è possibile recuperare il file HelpInfo XML per le impostazioni cultura dell'interfaccia utente {0}. Verificare che la proprietà HelpInfoUri nel manifesto del modulo sia valida o controllare la connessione di rete, quindi riprovare. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + Le impostazioni di cultura specificate non sono supportate: {0}. Specificare un'impostazione di cultura dall'elenco seguente: {{{1}}}. + + + Il posticipo dell'errore e il tentativo di usare le impostazioni cultura di fallback verranno visualizzati come errore se nessuna delle impostazioni di fallback è supportata: +{0} + + + Non è possibile trovare la directory ModuleBase. Verificare la directory e riprovare. + + + Il percorso {0} non è una directory valida. Verificare che la directory esista e riprovare. + + + Un URI della Guida non può contenere più di 10 reindirizzamenti. Specificare un URI della Guida valido. + + + Aggiornamento della Guida + + + Connessione al contenuto della Guida in corso... + + + Download del contenuto della Guida in corso... + + + Installazione del contenuto della Guida in corso... + + + Individuazione del contenuto della Guida in corso... + + + (Tutti) + + + Non sono stati trovati moduli di PowerShell corrispondenti al modello seguente: {0}. Verificare il modello, quindi riprovare a eseguire il comando. + + + Non sono stati trovati moduli di PowerShell corrispondenti al valore FullyQualifiedModule specificato {0}. Verificare il valore di FullyQualifiedModule, quindi riprovare a eseguire il comando. + + + Non è possibile trovare il contenuto della Guida. Verificare che il server sia disponibile e che il percorso del contenuto della Guida sia definito correttamente nel codice XML HelpInfo. + + + Il comando Update-Help non è riuscito perché il modulo specificato non supporta la Guida aggiornabile. Usare Get-Help -Online oppure cercare online la Guida per i comandi di questo modulo. + + + Il parametro seguente non deve essere Null o vuoto: Module. + + + Il parametro seguente non deve essere Null o vuoto: Path. + + + Aggiornamento della Guida completato. + + + Errore durante l'estrazione del contenuto della Guida. + + + Non è possibile connettersi al contenuto della Guida. Il server in cui è archiviato il contenuto della Guida potrebbe non essere disponibile. Verificare che il server sia disponibile o attendere che il server sia nuovamente online, quindi riprovare. + + + Il contenuto della Guida nel percorso specificato non è valido. Specificare un percorso contenente contenuto valido della Guida. + + + HelpInfo XML non è valido. Specificare un HelpInfo XML valido. + + + Il contenuto della Guida è stato salvato nel percorso seguente: {0} + + + Non è possibile trovare il file XSD del contenuto della Guida in {0}. Verificare che il file XSD esista nel percorso specificato, quindi ripetere il comando. + + + Non è possibile aggiornare la Guida per i moduli: +'{0}' +{1} + + + Salvataggio della Guida + + + Il contenuto della Guida contiene file non validi. Sono supportati solo file .txt e .xml. + + + Non è possibile salvare la Guida per i moduli ''{0}'': {1} + + + Non è possibile salvare la Guida per i moduli ''{0}'' con impostazioni cultura dell'interfaccia utente {{{1}}}: {2}. +Il contenuto della Guida in inglese-US è disponibile e può essere salvato usando: Save-Help -UICulture en-US. + + + Non è stato possibile aggiornare la Guida per i moduli ''{0}'' con le impostazioni cultura dell'interfaccia utente {{{1}}}: {2}. +Il contenuto della Guida in inglese-US è disponibile e può essere installato usando: Update-Help -UICulture en-US. + + + Le impostazioni cultura correnti sono ({0}), che non sono associate ad alcuna lingua. Valutare di modificare le impostazioni cultura del sistema oppure installare il contenuto della Guida in inglese-US usando: Update-Help -UICulture en-US. + + + false + + + Il parametro -Recurse è disponibile solo se viene specificato un percorso di origine. + + + Il percorso {0} non contiene un provider FileSystem. Verificare che il percorso specificato contenga il provider FileSystem, quindi riprovare il comando. + + + Ricerca nella Guida di {0} ... + + + Non sono state trovate impostazioni cultura dell'interfaccia utente che corrispondono al modello seguente: {0}. Verificare il modello, quindi riprovare a eseguire il comando. + + + La Guida non è stata salvata per il modulo {0}, perché il comando Save-Help è stato eseguito nel computer nelle ultime 24 ore. +Per salvare di nuovo la Guida, aggiungere il parametro Force al comando. + + + La Guida non è stata aggiornata per il modulo {0}, perché il comando Update-Help è stato eseguito nel computer nelle ultime 24 ore. +Per aggiornare di nuovo la Guida, aggiungere il parametro Force al comando. + + + I file della Guida più recenti sono già installati. + + + {0}: {1}. Cultura {2} versione {3} + + + Aggiornamento di {0} completato + + + Il valore della chiave HelpInfoUri nel manifesto del modulo deve essere risolto in un contenitore o in un URL radice in un sito Web in cui sono archiviati i file della Guida. Il valore HelpInfoUri ''{0}'' non viene risolto in un contenitore. + + + Il contenuto della Guida deve essere nello spazio dei nomi {0}. + + + Get-Help non riesce a trovare i file della Guida per questo cmdlet in questo computer. Viene visualizzata solo una parte della Guida. + -- Per scaricare e installare i file della Guida per il modulo che include questo cmdlet, usare Update-Help. + + + I file più recenti della Guida sono già stati scaricati. + + + {0} salvato + + + HelpInfoURI {0} non inizia con HTTP. + + + L'elemento di livello radice del contenuto della Guida deve essere "helpItems". + + + Salvataggio della Guida per il modulo {0} + + + Aggiornamento della Guida per il modulo {0} + + + Risoluzione dell'URI in corso: "{0}" + + + URI della Guida: {0} + + + {0}, versione corrente: {1}, versione disponibile: {2}, UICulture: {3} + + + PROPRIETÀ + + + METODI + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/HelpErrors.it.resx b/src/System.Management.Automation/resources/it/HelpErrors.it.resx new file mode 100644 index 00000000000..ae5228ba676 --- /dev/null +++ b/src/System.Management.Automation/resources/it/HelpErrors.it.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help non è riuscito a trovare {0} in un file della Guida in questa sessione. Per scaricare gli argomenti della Guida aggiornati, digitare "Update-Help". Per ottenere assistenza online, cercare l'argomento della Guida nella libreria TechNet all'indirizzo https://go.microsoft.com/fwlink/?LinkID=107116. + + + Non è possibile elaborare la categoria della Guida perché "{0}" non è una categoria della Guida valida. + + + Non è possibile caricare il file della Guida "{0}". Dettagli: {1}. + + + Non è possibile accedere al file della Guida "{0}" perché l'utente corrente non dispone dei diritti di accesso al file. Dettagli: {1}. + + + Il file della Guida "{0}" non è un documento XML valido. Dettagli: {1}. + + + Si è verificato un errore durante il caricamento del contenuto della Guida per {0} dal file {1}. Dettagli: {2}. Per scaricare gli argomenti della Guida aggiornati, eseguire il cmdlet Update-Help. Per ottenere assistenza online, cercare l'argomento della Guida nella libreria TechNet all'indirizzo https://go.microsoft.com/fwlink/?LinkID=107116. + + + Non è possibile caricare il provider "{0}". Dettagli: {1}. + + + Non è possibile caricare il file della Guida. Si sono verificati i seguenti errori {1} durante il caricamento del file della Guida "{0}". + + + Il nodo "{0}" non può avere "{1}" come nodo figlio. Percorso nodo: {2}. + + + Il nodo "{0}" può avere al massimo {2} nodi figlio di tipo "{1}". Percorso nodo: {3}. + + + Non è possibile trovare la chiave del Registro di sistema: "{0}{1}"; verrà usato "{2}" per caricare i file della Guida. + + + Nessun parametro corrisponde ai criteri {0}. + + + {0} non è supportato dalla categoria della Guida richiesta. + + + La versione online di questo argomento della Guida non può essere visualizzata perché l'indirizzo Internet (URI) dell'argomento della Guida non è specificato nel codice del comando o nel file della Guida del comando. + + + L'URI {0} specificato non è valido. + + + Non è possibile avviare un browser per visualizzare la Guida online. Nessun programma o browser è associato per aprire l'URI {0}. + + + Il protocollo specificato nell'URI "{0}" non è supportato. Sono supportati solo i protocolli "{1}" e "{2}". + + + Sono stati trovati più argomenti della Guida. Usare un solo argomento della Guida con l'opzione -{0}. + + + Non è possibile ottenere la Guida da uno spazio di esecuzione remoto perché lo spazio di esecuzione non è stato aperto. Aprire lo spazio di esecuzione eseguendo un comando di comunicazione remota implicita, quindi provare di nuovo a eseguire il comando per ottenere la Guida. + + + Accesso negato. Il comando non è riuscito ad aggiornare gli argomenti della Guida per i moduli principali di PowerShell o per qualsiasi modulo nella directory $pshome\Modules. +Per aggiornare questi argomenti della Guida, avviare PowerShell usando il comando "Esegui come Amministratore" e provare a eseguire di nuovo Update-Help. + + + Per usare il {0}, assicurarsi che l'applicazione usi 'Microsoft.NET.Sdk.WindowsDesktop' come SDK del progetto e che sia disponibile il corrispondente assembly 'Microsoft.PowerShell.GraphicalHost'. ({1}) + + + {0} non funziona in una sessione remota. + + + ForwardHelpTargetName non può fare riferimento alla funzione stessa. + + + Non è possibile ottenere la Guida da una posizione di rete in una sessione con restrizioni. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/HistoryStrings.it.resx b/src/System.Management.Automation/resources/it/HistoryStrings.it.resx new file mode 100644 index 00000000000..f886068fa19 --- /dev/null +++ b/src/System.Management.Automation/resources/it/HistoryStrings.it.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + L'identificatore {0} non è un valore valido per un identificatore della cronologia. Specificare un numero positivo e riprovare. + + + Non è possibile individuare la cronologia per l'ID {0}. + + + Il conteggio non può essere combinato con più ID. + + + Non è possibile individuare la cronologia per la riga di comando {0}. + + + Non è possibile individuare la cronologia più recente. + + + Il cmdlet Invoke-History viene richiamato ripetutamente, in un ciclo. + + + Non è possibile elaborare più comandi della cronologia. È possibile eseguire un solo comando usando Invoke-History. + + + Non è possibile aggiungere la cronologia perché l'oggetto di input ha un formato non valido. + + + L'identificatore {0} non è valido. Specificare un numero positivo e riprovare. + + + Questo comando eliminerà tutte le voci dalla cronologia della sessione. + + + Il conteggio non può essere combinato con più parametri CommandLine. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/HostInterfaceExceptionsStrings.it.resx b/src/System.Management.Automation/resources/it/HostInterfaceExceptionsStrings.it.resx new file mode 100644 index 00000000000..5f0f90e3d4b --- /dev/null +++ b/src/System.Management.Automation/resources/it/HostInterfaceExceptionsStrings.it.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 + + + Si è verificato un errore di tipo "{0}". + + + Un comando che richiede l'intervento dell'utente ha riscontrato un errore perché il programma host o il tipo di comando non supporta l'interazione dell'utente. Provare con un programma host che supporta l'interazione dell'utente, come la console di PowerShell, e rimuovere i comandi correlati a prompt dai tipi di comandi che non supportano l'interazione dell'utente. + + + Un comando che richiede l'intervento dell'utente ha riscontrato un errore perché il programma host o il tipo di comando non supporta l'interazione dell'utente. L'host stava tentando di richiedere una conferma con il messaggio seguente: {0} + + + Il metodo non può essere richiamato perché il pool è stato chiuso o ha riscontrato un errore. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/InternalCommandStrings.it.resx b/src/System.Management.Automation/resources/it/InternalCommandStrings.it.resx new file mode 100644 index 00000000000..c80da393ec7 --- /dev/null +++ b/src/System.Management.Automation/resources/it/InternalCommandStrings.it.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Il nome di input "{0}" è ambiguo. Può essere risolto in più metodi corrispondenti. Le possibili corrispondenze includono:{1}. + + + Il nome di input "{0}" è ambiguo. Può essere risolto in più membri corrispondenti. Le possibili corrispondenze includono:{1}. + + + Recupera il valore per la chiave "{0}" + + + Richiama il metodo "{0}" con argomenti: {1} + + + Richiama il metodo "{0}" + + + Recupera il valore per la proprietà "{0}" + + + InputObject: {0} + + + Non è possibile operare su un oggetto di input "null". + + + Il nome di input "{0}" non può essere risolto in un metodo. + + + Non è possibile richiamare un metodo in modalità linguaggio con restrizioni. + + + I parametri -WhatIf e -Confirm non sono supportati per i blocchi di script. + + + L'operazione "{0}" non è consentita in modalità RestrictedLanguage. + + + Per confrontare i due valori specificati, è necessario un operatore. Immettere un operatore valido nel comando, quindi riprovare a eseguire il comando. Ad esempio, Get-Process | Where-Object -Property Name -eq Idle + + + Non è possibile risolvere il nome di input "{0}" in una proprietà. + + + Non è possibile risolvere il nome di input "{0}" in un membro. + + + L'operatore specificato richiede entrambi i parametri -Property e -Value. Specificare i valori per entrambi i parametri, quindi riprovare a eseguire il comando. + + + Non è possibile eseguire questo metodo sul thread corrente. Può essere chiamato solo sul thread del cmdlet. + + + Una variabile using di ForEach-Object -Parallel non può essere un blocco di script. Le variabili del blocco di script passate non sono supportate con ForEach-Object -Parallel e possono causare un comportamento indefinito. + + + Un oggetto di input inviato tramite pipe a ForEach-Object -Parallel non può essere un blocco di script. Le variabili del blocco di script passate non sono supportate con ForEach-Object -Parallel e possono causare un comportamento indefinito. + + + Non è possibile usare il parametro "TimeoutSeconds" con il parametro "AsJob". + + + I seguenti parametri comuni non sono attualmente supportati nel set di parametri Parallel: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + Si è verificato un errore imprevisto durante l'elaborazione dell'input di ForEach-Object -Parallel. Questo può significare che una parte dell'input inviato tramite pipe non è stata elaborata. Errore: {0}. + + + Cmdlet ForEach-Object + + + La chiamata al metodo sul tipo "{0}" non sarà consentita quando viene eseguita in modalità Linguaggio con restrizioni. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/InternalHostStrings.it.resx b/src/System.Management.Automation/resources/it/InternalHostStrings.it.resx new file mode 100644 index 00000000000..c28cbc50170 --- /dev/null +++ b/src/System.Management.Automation/resources/it/InternalHostStrings.it.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 + + + Il numero di chiamate a EnterNestedPrompt non corrisponde a quello di ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/InternalHostUserInterfaceStrings.it.resx b/src/System.Management.Automation/resources/it/InternalHostUserInterfaceStrings.it.resx new file mode 100644 index 00000000000..c80dd54e93e --- /dev/null +++ b/src/System.Management.Automation/resources/it/InternalHostUserInterfaceStrings.it.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug arrestato perché il valore della variabile DebugPreference è ''Stop''. + + + Il valore {0} non è un valore ActionPreference supportato. + + + Il parametro "{0}" deve contenere almeno un valore. + + + &Sì + + + Continuare. + + + Sì per t&utti + + + Continuare senza chiedere nuovamente se continuare in questa sessione. + + + &No + + + Terminare l'operazione con un errore. + + + N&o per tutti + + + Terminare l'operazione con un errore. Non richiedere di riprendere l'operazione per questa sessione. + + + &Sospendi + + + Sospendere l'operazione corrente e immettere un prompt dei comandi. Digitare "exit" per riprendere l'operazione sospesa. + + + Continuare con questa operazione? + + + (l'impostazione predefinita è ''{0}'') + + + (le opzioni predefinite sono {0}) + + + Opzione[{0}]: + + + "{0}" deve avere almeno un elemento. + + + "{0}" deve essere un indice valido in "{1}". "{2}" non è un indice valido. + + + Non è possibile elaborare il tasto di scelta rapida perché il punto interrogativo ("?") non può essere usato come tasto di scelta rapida. + + + DETTAGLIATO: {0} + + + AVVISO: {0} + + + DEBUG: {0} + + + L'host non è attualmente in fase di trascrizione. + + + Ora di inizio comando: {0} + + + ********************** +Avvio della trascrizione di PowerShell +Ora di inizio: {0:yyyyMMddHHmmss} +Nome utente: {1} +Utente RunAs: {2} +Nome configurazione: {3} +Computer: {4} ({5}) +Applicazione host: {6} +ID processo: {7} +{8} +********************** + + + ********************** +Avvio della trascrizione di PowerShell +Ora di inizio: {0:yyyyMMddHHmmss} +********************** + + + ********************** +Fine della trascrizione di PowerShell +Ora di fine: {0:yyyyMMddHHmmss} +********************** + + + Il percorso del file {0} viene risolto in una directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/Logging.it.resx b/src/System.Management.Automation/resources/it/Logging.it.resx new file mode 100644 index 00000000000..7760da41575 --- /dev/null +++ b/src/System.Management.Automation/resources/it/Logging.it.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Gravità=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Gravità=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Gravità=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + UNKNOWN + + + La funzionalità sperimentale del motore ''{0}'' dichiarata nel file di configurazione non è registrata nel PowerShell corrente. + + + La funzionalità sperimentale ''{0}'' dichiarata nel file di configurazione non è valida. +Il nome di una funzionalità sperimentale deve seguire la convenzione seguente: + Nome della funzionalità del motore: ''PS[FeatureName]'' + Nome della funzionalità del modulo: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/Metadata.it.resx b/src/System.Management.Automation/resources/it/Metadata.it.resx new file mode 100644 index 00000000000..18fa09dd6a6 --- /dev/null +++ b/src/System.Management.Automation/resources/it/Metadata.it.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile inizializzare gli attributi per "{0}": "{1}" + + + Non è possibile convalidare l'argomento perché il tipo "{0}" non è dello stesso tipo ({1}) dei limiti massimo e minimo del parametro. Verificare che l'argomento sia di tipo {1} quindi riprovare. + + + Non è possibile convalidare l'argomento "{0}" perché il relativo valore non è maggiore di zero. + + + Non è possibile convalidare l'argomento "{0}" perché il relativo valore non è maggiore di o uguale a zero. + + + Non è possibile convalidare l'argomento "{0}" perché il relativo valore non è minore di zero. + + + Non è possibile convalidare l'argomento "{0}" perché il relativo valore non è minore di o uguale a zero. + + + Non è possibile accettare l'intervallo minimo specificato ({0}) perché non è dello stesso tipo dell'intervallo massimo specificato ({1}). Aggiornare l'attributo ValidateRange per il parametro. + + + Non è possibile accettare i tipi di parametro MaxRange e MinRange. Entrambi i parametri devono essere oggetti che implementano un'interfaccia IComparable. + + + Non è possibile accettare l'intervallo massimo specificato perché è minore dell'intervallo minimo specificato. Aggiornare l'attributo ValidateRange per il parametro. + + + L'argomento {0} è maggiore dell'intervallo massimo consentito di {1}. Specificare un argomento minore o uguale a {1}, quindi riprovare. + + + L'argomento {0} è inferiore all'intervallo minimo consentito di {1}. Specificare un argomento maggiore o uguale a {1}, quindi riprovare. + + + L'argomento "{0}" non corrisponde al criterio "{1}". Specificare un argomento corrispondente a "{1}" e riprovare. + + + Non è possibile applicare l'attributo ValidateCount a un parametro non di matrice. Rimuovere l'attributo dal parametro o impostare il parametro come parametro di matrice. + + + Il parametro richiede esattamente {0} valori- sono stati specificati {1} valori. + + + Il parametro richiede almeno {0} valori e non più di {1} valori: sono stati forniti {2} valori. + + + Il numero massimo specificato di argomenti per un parametro è inferiore al numero minimo di argomenti specificato. Aggiornare l'attributo ValidateRange per il parametro. + + + La lunghezza massima specificata per l'argomento è inferiore alla lunghezza minima specificata per i caratteri dell'argomento. Aggiornare l'attributo ValidateLength per il parametro. + + + Non è possibile applicare l'attributo ValidateLength a un parametro che non è un parametro string o string[]. Impostare il parametro come stringa o parametro string[]. + + + La lunghezza in caratteri ({1}) dell'argomento è troppo breve. Specificare un argomento di lunghezza maggiore di o uguale a "{0}", quindi riprovare a eseguire il comando. + + + La lunghezza in caratteri ({1}) dell'argomento è troppo lungo. Specificare un argomento di lunghezza minore di o uguale a "{0}", quindi riprovare a eseguire il comando. + + + L'argomento "{0}" non appartiene al set "{1}" specificato dall'attributo ValidateSet. Specificare un argomento incluso nel set, quindi riprovare. + + + Il generatore di valori validi restituisce un valore Null. + + + Errore di "{0}" sulla proprietà "{1}" {2} + + + Non è possibile ottenere o eseguire il comando. È stato superato il numero massimo di set di parametri per questo comando. + + + Non è possibile elaborare l'argomento perché il valore dell'argomento non è una stringa. I valori degli argomenti di parametro con ArgumentTransformationAttribute specificato devono essere stringhe. + + + Non è possibile convalidare la variabile perché il valore {1} non è un valore valido per la variabile {0}. + + + Non è possibile aggiungere l'attributo perché la variabile {0} con valore {1} non sarebbe più valida. + + + L'argomento è Null. Specificare un valore valido per l'argomento, quindi riprovare a eseguire il comando. + + + L'argomento ha un valore Null o un elemento della raccolta di argomenti contiene un valore Null. Specificare una raccolta che non contenga valori Null, quindi riprovare. + + + Argomento Null o vuoto. Specificare un argomento non Null o vuoto, quindi riprovare. + + + L'argomento è Null, vuoto o un elemento della raccolta di argomenti contiene un valore Null. Specificare una raccolta che non contenga valori Null, quindi riprovare. + + + L'argomento è Null, vuoto o è costituito solo da spazi vuoti. Specificare un argomento contenente caratteri non spazi vuoti, quindi riprovare. + + + Un elemento della raccolta di argomenti è Null, vuoto o è costituito solo da spazi vuoti. Specificare una raccolta che non contenga tali valori, quindi riprovare. + + + Un parametro denominato ''{0}'' è stato definito più volte per il comando. + + + Non è possibile specificare l'alias del parametro perché un alias con il nome ''{0}'' è già stato definito più volte per il comando. + + + Impossibile specificare il parametro ''{0}'' perché è in conflitto con l'alias del parametro con lo stesso nome per il parametro ''{1}''. + + + Lo script di convalida "{1}" per l'argomento con valore "{0}" non ha restituito il risultato True. Determinare il motivo per cui lo script di convalida non è riuscito, quindi riprovare. + + + L'argomento "{0}" non contiene una versione di PowerShell valida. Specificare un numero di versione valido, quindi riprovare. + + + Non è possibile convalidare l'argomento ''{0}'' perché non è un nome di variabile valido. + + + Il tipo di conversione del processo deve derivare da IAstToScriptBlockConverter. + + + L'argomento del percorso non è valido. Specificare un argomento di percorso di tipo stringa. + + + L'unità argomento percorso {0} non appartiene al set di unità approvate: {1}. Specificare un argomento di percorso con un'unità approvata. + + + L'argomento del percorso contiene caratteri non validi. + + + L'argomento del percorso non ha un'unità radice. Specificare un argomento di percorso completo con un'unità radice. + + + Il valore dell'argomento per il parametro ''{0}'' non può essere Null o una stringa vuota. + + + Il membro Enum ''{0}'' non è un valore valido per il parametro ''{1}''. Specificare uno dei membri seguenti e riprovare: {2}. + + + Non è possibile elaborare l'input. L'argomento "{0}" non è attendibile. + + + Errore di controllo dell'attributo ValidateTrustedData + + + L'argomento del parametro ''{0}'' non è attendibile e non riuscirà il controllo dell'attributo del parametro ValidateTrustedData in modalità linguaggio vincolato. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/MiniShellErrors.it.resx b/src/System.Management.Automation/resources/it/MiniShellErrors.it.resx new file mode 100644 index 00000000000..ef36b6c6712 --- /dev/null +++ b/src/System.Management.Automation/resources/it/MiniShellErrors.it.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 + + + L'aggiornamento non è supportato per la categoria di configurazione dello spazio di esecuzione {0}. + + + Si sono verificati gli errori seguenti durante l'aggiornamento della lista assemblaggio per lo spazio di esecuzione: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/Modules.it.resx b/src/System.Management.Automation/resources/it/Modules.it.resx new file mode 100644 index 00000000000..29adda2ad13 --- /dev/null +++ b/src/System.Management.Automation/resources/it/Modules.it.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Il modulo specificato '{0}' non è stato caricato perché nelle directory dei moduli non è stato trovato alcun file di modulo valido. + + + Il modulo specificato '{0}' con versione '{1}' non è stato caricato perché nelle directory dei moduli non è stato trovato alcun file di modulo valido. + + + Il valore specificato per MaximumVersion '{0}' non è corretto. Se si usa '*', MaximumVersion supporta un solo '*' e deve essere sempre posizionato alla fine di MaximumVersion. + + + Il modulo specificato '{0}' con MaximumVersion '{1}' non è stato caricato perché nelle directory dei moduli non è stato trovato alcun file di modulo valido. + + + Il modulo specificato '{0}' con MinimumVersion '{1}' e MaximumVersion '{2}' non è stato caricato perché nelle directory dei moduli non è stato trovato alcun file di modulo valido. + + + Il valore MinimumVersion '{0}' non deve essere maggiore di MaximumVersion '{1}'. + + + L'assembly '{0}' non è stato caricato perché non è stato trovato un assembly con questo nome. Verificare il nome dell'assembly, quindi riprovare. + + + Il modulo da elaborare '{0}', elencato nel campo '{1}' del manifesto del modulo '{2}', non è stato elaborato perché nelle directory dei moduli non è stato trovato alcun modulo valido. + + + Non è stato restituito alcun oggetto personalizzato per il modulo '{0}' perché il parametro -AsCustomObject può essere usato solo con i moduli di script. + + + Il manifesto del modulo '{0}' non è stato elaborato perché non è un file manifesto del modulo PowerShell valido. Rimuovere gli elementi non consentiti: {1} + + + L'elaborazione del file manifesto del modulo '{0}' non ha prodotto un oggetto manifesto valido. Aggiornare il file in modo che contenga un manifesto del modulo PowerShell valido. È possibile creare un manifesto valido usando il cmdlet New-ModuleManifest. + + + Non è possibile importare il modulo '{0}' perché il relativo manifesto contiene uno o più membri non validi. I membri del manifesto validi sono ({1}). Rimuovere i membri non validi ({2}), quindi riprovare a importare il modulo. + + + La tabella hash che descrive un modulo contiene uno o più membri non validi. I membri validi sono ({0}). Rimuovere i membri non validi ({1}), quindi riprovare. + + + Non è possibile caricare il modulo '{0}' perché il limite di annidamento dei moduli è stato superato. I moduli possono essere annidati solo per {1} livelli. Valutare e modificare l'ordine di caricamento dei moduli per evitare di superare il limite di annidamento, quindi riprovare a eseguire lo script. + + + Il membro 'ModuleVersion' non è presente nel manifesto del modulo. Questo membro deve esistere e deve avere un numero di versione nel formato 'n.n.n.n'. Aggiungere il membro mancante al file '{0}'. + + + Il membro '{0}' non è valido nel file manifesto del modulo '{2}': {1} + + + La versione '{0}' del modulo '{1}' non soddisfa il requisito della versione minima '{2}'. Verificare che il numero di versione sia supportato, quindi provare di nuovo a caricare il modulo. + + + La versione di PowerShell installata in questo computer è '{0}'. Il modulo '{1}' richiede una versione minima di PowerShell di '{2}' per l'esecuzione. Verificare che sia installata la versione minima richiesta di PowerShell, quindi riprovare. + + + Non è possibile usare il membro del manifesto del modulo 'NestedModules' se il membro 'ModuleToProcess' è un modulo binario. Modificare il file manifesto del modulo in '{0}', quindi riprovare. + + + Il membro '{0}' nel manifesto del modulo non è valido: {1}. Verificare che sia specificato un valore valido per questo campo nel file '{2}'. + + + Il percorso del manifesto del modulo '{0}' non è valido. Il valore dell'argomento Path deve essere risolto in un unico file con estensione '.psd1'. Modificare il valore dell'argomento Path in modo che punti a un file psd1 valido, quindi riprovare. + + + La chiave ModuleVersion nel manifesto del modulo '{0}' specifica la versione del modulo '{1}', che non corrisponde al nome della cartella della versione in '{2}'. Modificare il valore della chiave ModuleVersion in modo che corrisponda al nome della cartella della versione. + + + La voce NestedModule specificata '{0}' nel manifesto del modulo '{1}' non è valida. Riprovare dopo aver aggiornato la voce con valori validi. + + + La voce RequiredAssemblies specificata '{0}' nel manifesto del modulo '{1}' non è valida. Riprovare dopo aver aggiornato la voce con valori validi. + + + La voce FileList specificata '{0}' nel manifesto del modulo '{1}' non è valida. Riprovare dopo aver aggiornato la voce con valori validi. + + + La voce RequiredModules specificata '{0}' nel manifesto del modulo '{1}' non è valida. Riprovare dopo aver aggiornato la voce con valori validi. + + + La voce ModuleList specificata '{0}' nel manifesto del modulo '{1}' non è valida. Riprovare dopo aver aggiornato la voce con valori validi. + + + Il manifesto del modulo '{0}' è specificato con la chiave CompatiblePSEditions, che è supportata solo in PowerShell versione '5.1' o successiva. Aggiornare il valore della chiave PowerShellVersion a '5.1' o versione successiva e riprovare. + + + Il valore specificato '{0}' per CompatiblePSEditions contiene nomi di edizione di PowerShell duplicati. Riprovare dopo aver rimosso i nomi delle edizioni di PowerShell duplicati. + + + La versione specificata nella chiave ModuleVersion è uguale al nome della cartella della versione. + + + La cartella della versione {0} nel modulo {1} verrà ignorata perché non dispone di un file manifesto del modulo valido. + + + Il membro 'ModuleName' non esiste nella tabella hash che descrive questo modulo. + + + I membri 'ModuleVersion', 'MaximumVersion' e 'RequiredVersion' non esistono nella tabella hash che descrive questo modulo. Uno di questi tre membri deve esistere e deve avere un numero di versione nel formato 'n.n.n.n'. + + + Il modulo richiesto '{1}' non è caricato. Caricare il modulo oppure rimuoverlo da 'RequiredModules' nel file '{0}'. + + + Il modulo obbligatorio '{1}' con GUID '{2}' non è caricato. Caricare il modulo oppure rimuoverlo da 'RequiredModules' nel file '{0}'. + + + Il modulo obbligatorio '{1}' con versione '{2}' non è caricato. Caricare il modulo oppure rimuoverlo da 'RequiredModules' nel file '{0}'. + + + Il modulo obbligatorio '{1}' con MaximumVersion '{2}' non è caricato. Caricare il modulo oppure rimuoverlo da 'RequiredModules' nel file '{0}'. + + + Il modulo richiesto '{1}' con MinimumVersion '{2}' e MaximumVersion '{3}' non è stato caricato. Caricare il modulo oppure rimuoverlo da 'RequiredModules' nel file '{0}'. + + + Non è possibile trovare il modulo '{0}' con ModuleVersion '{1}'. + + + Non è possibile trovare il modulo '{0}' con RequiredVersion '{1}'. + + + Non è possibile trovare il modulo '{0}' con MaximumVersion '{1}'. + + + Non è possibile trovare il modulo '{0}' con ModuleVersion '{1}' e MaximumVersion '{2}'. + + + Non è possibile trovare il modulo '{0}'. + + + Nessun modulo è stato rimosso. Verificare che la specifica dei moduli da rimuovere sia corretta e che tali moduli esistano nello spazio di esecuzione. + + + Non è possibile rimuovere il membro '{0}', importato dal modulo '{1}', per il motivo seguente: {2} + + + Non è possibile rimuovere il modulo '{0}' perché è di sola lettura. Aggiungere il parametro Force al comando per rimuovere i moduli di sola lettura. + + + Non è possibile rimuovere il modulo '{0}' perché è contrassegnato come 'constant'. Un modulo non può essere rimosso se è contrassegnato come 'constant'. + + + Non è possibile rimuovere il modulo '{0}' perché è richiesto da '{1}'. Aggiungere il parametro Force al comando per rimuovere il modulo. + + + Il cmdlet Export-ModuleMember può essere chiamato solo dall'interno di un modulo. + + + L'estensione '{0}' non è un'estensione del modulo valida. Le estensioni del modulo supportate sono '.dll', '.ps1', '.psm1', '.psd1' e '.cdxml'. Correggere l'estensione, quindi provare ad aggiungere di nuovo il file '{1}'. + + + Non è possibile eseguire questa operazione su un modulo binario. Può essere eseguita solo su un modulo di script. + + + Il file '{0}' non è consentito perché non ha l'estensione '.ps1'. + + + Sconosciuto + + + (c) {0}. Tutti i diritti sono riservati. + + + Rimozione della funzione "{0}" importata. + + + Rimozione dell'alias "{0}" importato. + + + Rimozione della variabile "{0}" importata. + + + Caricamento del modulo dal percorso '{0}'. + + + Caricamento di '{0}' dal percorso '{1}'. + + + Dot-sourcing del file di script '{0}'. + + + Importazione della funzione '{0}'. + + + Importazione del cmdlet '{0}'. + + + Importazione dell'alias '{0}'. + + + Importazione della variabile '{0}'. + + + Esportazione del cmdlet '{0}'. + + + Esportazione della funzione '{0}'. + + + Esportazione dell'alias '{0}'. + + + Esportazione della variabile '{0}'. + + + I nomi di alcuni comandi importati dal modulo '{0}' includono verbi non approvati che potrebbero renderli meno individuabili. Per trovare i comandi con verbi non approvati, eseguire di nuovo il comando Import-Module con il parametro Verbose. Per un elenco dei verbi approvati, digitare Get-Verb. + + + Il comando '{0}' nel modulo {1}' è stato importato, ma poiché il nome non include un verbo approvato, potrebbe risultare difficile da trovare. Per un elenco dei verbi approvati, digitare Get-Verb. + + + Il comando '{0}' nel modulo {2}' è stato importato, ma poiché il nome non include un verbo approvato, potrebbe risultare difficile da trovare. I verbi alternativi suggeriti sono "{1}". + + + Alcuni nomi di comandi importati contengono uno o più dei caratteri non consentiti seguenti: # , ( ) {{ }} [ ] & - / \ $ ^; : " ' < > | ? @ ` * % + = ~ + + + Il nome del comando '{0}' del modulo '{1}' contiene uno o più dei seguenti caratteri non consentiti: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Creazione del file manifesto del modulo "{0}". + + + {0} (Percorso: '{1}') + + + L'architettura del processore corrente è: {0}. Il modulo '{1}' richiede l'architettura seguente: {2}. + + + Il nome dell'host di PowerShell corrente è: '{0}'. Il modulo '{1}' richiede l'host di PowerShell seguente: '{2}'. + + + L'host di PowerShell corrente è: '{0}' (versione {1}). Il modulo '{2}' richiede una versione dell'host di PowerShell minima di '{3}' per l'esecuzione. + + + Manifesto del modulo per il modulo '{0}' + + + Generato da: {0} + + + Data di generazione: {0} + + + File del modulo di script o del modulo binario associato a questo manifesto. + + + Moduli da importare come moduli annidati del modulo specificato in RootModule/ModuleToProcess + + + ID usato per identificare in modo univoco il modulo + + + Autore di questo modulo + + + Società o fornitore di questo modulo + + + Informativa sul copyright per questo modulo + + + Numero di versione di questo modulo. + + + Descrizione delle funzionalità fornite da questo modulo + + + Versione minima del motore di PowerShell richiesta da questo modulo + + + Versione minima del Common Language Runtime (CLR) richiesta da questo modulo. {0} + + + Moduli che devono essere importati nell'ambiente globale prima di importare questo modulo + + + File di script (.ps1) eseguiti nell'ambiente del chiamante prima dell'importazione di questo modulo. + + + File di tipo (.ps1xml) da caricare durante l'importazione di questo modulo + + + File di formato (.ps1xml) da caricare durante l'importazione di questo modulo + + + Assembly da caricare prima di importare questo modulo + + + Elenco di tutti i file inclusi in questo modulo + + + Dati privati da passare al modulo specificato in RootModule/ModuleToProcess. Può anche contenere una tabella hash PSData con i metadati del modulo aggiuntivi usati da PowerShell. + + + Tag applicati a questo modulo. Sono utili per l'individuazione dei moduli nelle raccolte online. + + + URL del sito Web principale di questo progetto. + + + URL della licenza di questo modulo. + + + URL di un'icona che rappresenta questo modulo. + + + ReleaseNotes di questo modulo + + + Stringa della versione preliminare di questo modulo + + + Flag per indicare se il modulo richiede l'accettazione esplicita da parte dell'utente per l'installazione, l'aggiornamento o il salvataggio + + + Moduli dipendenti esterni di questo modulo + + + Fine della tabella hash {0} + + + Il valore del parametro PrivateData deve essere una tabella hash per creare il manifesto del modulo con i valori di parametro seguenti: Tags, ProjectUri, LicenseUri, IconUri o ReleaseNotes. Rimuovere i valori dei parametri Tags, ProjectUri, LicenseUri, IconUri o ReleaseNotes oppure eseguire il wrapping del contenuto di PrivateData in una tabella hash. + + + PrivateData deve essere definito come tabella hash, ma questo manifesto del modulo lo definisce come oggetto. Provare a eseguire il wrapping del contenuto di PrivateData in una tabella hash. In questo modo sarà possibile aggiungere le proprietà Tags, ProjectUri, LicenseUri, IconUri e ReleaseNotes al manifesto del modulo in un secondo momento. + + + Il valore specificato '{0}' non è valido. Riprovare con un valore valido. + + + Funzioni da esportare da questo modulo. Per ottenere prestazioni ottimali, non usare caratteri jolly e non eliminare la voce. Usare una matrice vuota se non sono presenti funzioni da esportare. + + + Alias da esportare da questo modulo. Per ottenere prestazioni ottimali, non usare caratteri jolly e non eliminare la voce. Usare una matrice vuota se non sono presenti alias da esportare. + + + Cmdlet da esportare da questo modulo. Per ottenere prestazioni ottimali, non usare caratteri jolly e non eliminare la voce. Usare una matrice vuota se non sono presenti cmdlet da esportare. + + + Variabili da esportare da questo modulo + + + Risorse DSC da esportare da questo modulo + + + PSEditions supportate + + + Architettura del processore (None, X86, Amd64) richiesta da questo modulo + + + Elenco di tutti i moduli inclusi in questo modulo + + + Versione minima di Microsoft .NET Framework richiesta da questo modulo. {0} + + + Nome dell'host di PowerShell richiesto da questo modulo + + + Versione minima dell'host di PowerShell richiesta da questo modulo + + + URI HelpInfo di questo modulo + + + Poiché il modulo {0} fornisce PSDrive nella sessione corrente di PowerShell, non è stato rimosso alcun modulo. Modificare il provider PSDrive corrente, quindi riprovare a rimuovere i moduli. + + + Il cmdlet '{0}' non è stato importato perché nell'ambito corrente è presente un membro con lo stesso nome. + + + L'alias '{0}' non è stato importato perché nell'ambito corrente è presente un membro con lo stesso nome. + + + La funzione '{0}' non è stata importata perché nell'ambito corrente è presente un membro con lo stesso nome. + + + La variabile '{0}' non è stata importata perché nell'ambito corrente è presente un membro con lo stesso nome. + + + I caratteri jolly non sono consentiti nei membri 'ModuleToProcess', 'RootModule' o 'NestedModules' nel manifesto del modulo '{0}'. + + + Il modulo '{0}' è un modulo principale per PowerShell. Aggiungere il parametro Force al comando per rimuovere i moduli principali. + + + Il manifesto del modulo non può contenere entrambi i membri 'ModuleToProcess' e 'RootModule'. Modificare il file manifesto del modulo per rimuoverne uno in '{0}', quindi riprovare. + + + Il membro del manifesto del modulo 'ModuleToProcess' è deprecato. Usare invece il membro 'RootModule'. + + + Prefisso predefinito per i comandi esportati da questo modulo. Eseguire l'override del prefisso predefinito con Import-Module -Prefix. + + + I parametri 'Global' e 'Scope' non possono essere specificati insieme. Rimuovere uno di questi parametri, quindi riprovare a eseguire il comando. + + + Il modulo richiesto '{0}' non è caricato. Il modulo '{0}' ha un elemento requiredModule '{1}' nel manifesto del modulo '{2}' che punta a una dipendenza ciclica. + + + Il modulo richiesto '{0}' non è stato caricato perché nelle directory dei moduli non è stato trovato alcun file di modulo valido. + + + Alcuni comandi del modulo {0} non possono essere importati tramite una CimSession. Per ottenere tutti i comandi, verificare che nel server remoto sia abilitata la gestione remota di PowerShell, quindi provare ad aggiungere il parametro PSSession a un cmdlet Import-Module. + + + Il modulo {0} viene caricato in Windows PowerShell usando una sessione di comunicazione remota {1}. Notare che tutti gli input e gli output dei comandi di questo modulo saranno oggetti deserializzati. Se si vuole caricare questo modulo in PowerShell, usare la sintassi 'Import-Module -SkipEditionCheck'. + + + È stata rilevata la versione di Windows PowerShell {0}. Per caricare moduli usando la funzionalità di compatibilità di Windows PowerShell è richiesto Windows PowerShell 5.1. Installare Windows Management Framework (WMF) 5.1 da https://aka.ms/WMF5Download per abilitare questa funzionalità. + + + Il caricamento del modulo '{0}' tramite la funzionalità di compatibilità di Windows PowerShell è bloccato da un'impostazione 'WindowsPowerShellCompatibilityModuleDenyList' nel file di configurazione di PowerShell. + + + Non è possibile importare il modulo {0} tramite CimSession. Provare a usare il parametro PSSession del cmdlet Import-Module. + + + Il valore dell'architettura del processore di {0} non è supportato. Eseguire di nuovo il comando New-ModuleManifest, specificando uno dei valori di enumerazione supportati seguenti per l'architettura del processore: None, MSIL, X86, Amd64, Arm + + + L'esecuzione del cmdlet Get-Module su un computer remoto consente di elencare solo i moduli disponibili. Aggiungere il parametro ListAvailable al comando, quindi riprovare. + + + Il modulo '{0}' non è stato importato perché lo snap-in '{0}' era già stato importato. + + + I caratteri jolly non sono consentiti nel membro 'RequiredAssemblies' del manifesto del modulo '{0}'. + + + Il valore della chiave {0} in {1} è {2} e il modulo contiene moduli annidati. Quando un file CDXML è il modulo radice, il comando Import-Module ha esito negativo perché i comandi nei moduli annidati non possono essere esportati. Spostare il file CDXML nella chiave NestedModules e riprovare a eseguire il comando. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Errore del comando remoto: {0}: {{0}} + + + Non è possibile generare proxy per il modulo remoto '{0}'. {{0}} + + + Non è possibile elaborare il modulo remoto {0}. {1} + + + Non è possibile ricevere i dati del modulo dalla CimSession remota. {0} + + + Il modulo richiesto '{0}' con GUID '{1}' e versione '{2}' non è stato caricato perché nelle directory dei moduli non è stato trovato alcun file di modulo valido. + + + Non è stato trovato alcun provider CIM per l'individuazione dei moduli nel server CIM. {0} + {0} is a placeholder for a more detailed error message + + + No è possibile verificare la versione di Microsoft .NET Framework {0} perché non è inclusa nell'elenco delle versioni consentite. + + + Analisi di {0}. + {0} should not be localized, is used to contain a file path. + + + Preparazione dei moduli per il primo utilizzo. + + + Ricerca dei moduli disponibili in corso + + + Ricerca nella condivisione UNC {0}. + {0} should not be localized, is used to contain a file path. + + + L'esecuzione del cmdlet Get-Module su un computer remoto può essere eseguita solo per i nomi di modulo che non includono un percorso. Il parametro Name contiene l'elemento '{0}', che viene risolto in un percorso. Aggiornare il parametro Name in modo che non contenga elementi di percorso, quindi riprovare. + + + L'esecuzione del cmdlet Get-Module senza il parametro ListAvailable non è supportata per i nomi di modulo che includono un percorso. Il parametro Name contiene l'elemento '{0}', che viene risolto in un percorso. Aggiornare il parametro Name in modo che non contenga elementi di percorso, quindi riprovare. + + + Il modulo specificato '{0}' non è stato trovato. Aggiornare il parametro Name in modo che punti a un percorso valido, quindi riprovare. + + + Popolamento della proprietà RepositorySourceLocation per il modulo {0}. + + + Il modulo da elaborare '{0}', elencato nel campo '{1}' del manifesto del modulo '{2}', non è stato elaborato. {3} + + + Questo prerequisito è valido solo per l'edizione Desktop di PowerShell. + + + Il modulo '{0}' non supporta l'edizione corrente di PowerShell '{1}'. Le edizioni supportate sono '{2}'. Usare 'Import-Module -SkipEditionCheck' per ignorare il controllo di compatibilità di questo modulo. + + + Il modulo '{0}' supporta l'edizione di PowerShell '{1}' e non può essere caricato in modo implicito usando la funzionalità di compatibilità con Windows perché è disabilitata nel file delle impostazioni. Usare 'Import-Module -UseWindowsPowerShell' per caricare questo modulo con Windows PowerShell oppure 'Import-Module -SkipEditionCheck' per provare a caricare il modulo con PowerShell corrente. + + + Per una funzionalità sperimentale dichiarata nel manifesto del modulo è necessario specificare un valore stringa non vuoto. + + + Sono stati trovati uno o più nomi di funzionalità sperimentali non validi: {0}. Il nome di una funzionalità sperimentale del modulo deve seguire questa convenzione: 'ModuleName.FeatureName'. + + + Il parametro opzionale -SkipEditionCheck non può essere usato senza il parametro opzionale -ListAvailable. + + + L'importazione di file *.ps1 come moduli non è consentita in modalità ConstrainedLanguage. + + + Si è verificato un errore durante il caricamento del modulo di script {0} perché ha una modalità di linguaggio diversa rispetto al manifesto del modulo. La modalità di linguaggio del manifesto è {1} e la modalità di linguaggio del modulo è {2}. Assicurarsi che tutti i file del modulo siano firmati o facciano comunque parte della configurazione dell'elenco di elementi consentiti dell'applicazione. + + + Questo modulo usa l'operatore dot-source per esportare funzioni utilizzando caratteri jolly e questo non è consentito quando nel sistema è applicata la verifica delle applicazioni. + + + Non è possibile esportare membri del modulo da un modulo con una modalità linguaggio diversa da quella della sessione in esecuzione. + + + Non è possibile creare un nuovo modulo mentre la sessione è in modalità ConstrainedLanguage. + + + Non è possibile trovare il modulo predefinito '{0}' compatibile con l'edizione 'Core'. Assicurarsi che i moduli predefiniti di PowerShell siano disponibili. In genere sono inclusi nel pacchetto PowerShell nel percorso del modulo $PSHOME e sono necessari per il corretto funzionamento di PowerShell. + + + Cmdlet Export-ModuleMember + + + L'esportazione dei membri del modulo avrà esito negativo in modalità linguaggio vincolato perché il modulo '{0}', ha una modalità di linguaggio '{1}' diversa rispetto a quella della sessione corrente '{2}'. + + + Esportazione implicita di funzioni del modulo + + + L'esportazione implicita delle funzioni per il modulo '{0}' verrà negata, perché è attendibile (viene eseguito in modalità linguaggio completo), ma la sessione non è attendibile (viene eseguita in modalità linguaggio vincolato). È consigliabile esportare sempre le funzioni del modulo singolarmente usando il nome completo. + + + Importazione del file di script come modulo + + + L'importazione del file di script '{0}' come modulo non sarà consentita in modalità ConstrainedLanguage. + + + Il modulo contiene l'operatore dot-source + + + L'importazione del modulo '{0}' avrà esito negativo in modalità linguaggio vincolato perché esporta le funzioni usando caratteri jolly e usando anche l'operatore dot-source. + + + "Funzioni di esportazione del modulo + + + Il modulo '{0}' esporta funzioni usando caratteri jolly nel nome. I nomi di funzione dei moduli annidati verranno rimossi quando si esegue il codice in modalità linguaggio vincolato. + + + "Cmdlet New-Module + + + A un nuovo modulo di una sessione di linguaggio vincolato non attendibile verrà impedito di fornire il blocco di script FullLanguage. + + + "Modalità di linguaggio del modulo non corrispondenti + + + È in corso il caricamento di un modulo dipendente con una modalità di linguaggio diversa da quella del modulo padre. Questa operazione non sarà consentita in modalità linguaggio vincolato. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/MshHostRawUserInterfaceStrings.it.resx b/src/System.Management.Automation/resources/it/MshHostRawUserInterfaceStrings.it.resx new file mode 100644 index 00000000000..8bf3adb7011 --- /dev/null +++ b/src/System.Management.Automation/resources/it/MshHostRawUserInterfaceStrings.it.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}" non può essere maggiore o uguale a "{1}". + + + "{0}" deve essere un intero positivo. + + + Tutte le stringhe sono null o vuote. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/MshSignature.it.resx b/src/System.Management.Automation/resources/it/MshSignature.it.resx new file mode 100644 index 00000000000..280e291e7ad --- /dev/null +++ b/src/System.Management.Automation/resources/it/MshSignature.it.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 + + + Firma verificata. + + + Il file {0} non è firmato digitalmente. Non è possibile eseguire questo script nel sistema corrente. Per altre informazioni sull'esecuzione di script e sull'impostazione dei criteri di esecuzione, vedere about_Execution_Policies all'indirizzo https://go.microsoft.com/fwlink/?LinkID=135170 + + + Il contenuto del file {0} potrebbe essere stato modificato da un processo o da un utente non autorizzato, poiché l'hash del file non corrisponde all'hash archiviato nella firma digitale. Non è possibile eseguire lo script nel sistema specificato. Per ulteriori informazioni, eseguire Get-Help about_Signing. + + + Il file {0} è firmato, ma il firmatario non è considerato attendibile in questo sistema. + + + Non è possibile firmare il file perché il sistema non supporta operazioni di firma su file {0}. + + + Non è possibile firmare il file perché il sistema non supporta operazioni di firma sui file che non hanno un'estensione. + + + Non è possibile verificare la firma perché non è compatibile con il sistema corrente. + + + Non è possibile verificare la firma perché non è compatibile con il sistema corrente. L'algoritmo hash non è valido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/MshSnapInCmdletResources.it.resx b/src/System.Management.Automation/resources/it/MshSnapInCmdletResources.it.resx new file mode 100644 index 00000000000..859b9b96624 --- /dev/null +++ b/src/System.Management.Automation/resources/it/MshSnapInCmdletResources.it.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 + + + Non è possibile eseguire l'operazione. Il cmdlet specificato non è supportato in una shell personalizzata. + + + Non è possibile trovare alcun snap-in di PowerShell corrispondente al criterio '{0}'. Controllare il modello, quindi riprovare il comando. + + + Il formato del nome dello snap-in specificato non è valido. I nomi degli snap-in di PowerShell possono contenere solo caratteri alfanumerici, trattini, caratteri di sottolineatura e punti. Correggere il nome e riprovare. + + + Non è possibile aggiungere lo snap-in PowerShell {0} perché si tratta di un modulo Powershell di sistema. Usare Import-Module per caricare il modulo. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/MshSnapinInfo.it.resx b/src/System.Management.Automation/resources/it/MshSnapinInfo.it.resx new file mode 100644 index 00000000000..50006ea63f7 --- /dev/null +++ b/src/System.Management.Automation/resources/it/MshSnapinInfo.it.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 + + + Non è possibile accedere alle informazioni del Registro di sistema di PowerShell. + + + Non è possibile accedere alle informazioni del Registro di sistema del motore di PowerShell. + + + Non è possibile accedere alle informazioni di PublicKeyToken. + + + La versione {0} di PowerShell non è disponibile in questo computer. + + + Lo snap-in di PowerShell '{0}' non è installato in questo computer. + + + Il valore obbligatorio {0} non è specificato per la chiave del Registro di sistema {1}. + + + Il valore obbligatorio {0} non è nel formato corretto per la chiave del Registro di sistema {1}. Il formato previsto è 'string.' + + + Il valore obbligatorio {0} non è nel formato corretto per la chiave del Registro di sistema {1}. Il formato previsto è 'multistring'. + + + Non è possibile trovare le informazioni necessarie nel Registro di sistema oppure mancano i file delle chiavi. Non è possibile caricare alcuni cmdlet. + + + Non sono stati registrati snap-in per la versione {0}di PowerShell. + + + Non è possibile recuperare la risorsa stringa perché è stato eliminato il lettore. + + + Il valore di versione {0} non è specificato o non è corretto per la chiave del Registro di sistema {1}. + + + Non è possibile trovare alcun attributo [PSVersion] per il tipo PowerShell {0}. Aggiungere un attributo PSVersion al tipo usando [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/NativeCP.it.resx b/src/System.Management.Automation/resources/it/NativeCP.it.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/it/NativeCP.it.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PSCommandStrings.it.resx b/src/System.Management.Automation/resources/it/PSCommandStrings.it.resx new file mode 100644 index 00000000000..d8d85aaf919 --- /dev/null +++ b/src/System.Management.Automation/resources/it/PSCommandStrings.it.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 + + + Per aggiungere un parametro è necessario un comando. Prima di aggiungere un parametro, è necessario aggiungere un comando a {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PSConfigurationStrings.it.resx b/src/System.Management.Automation/resources/it/PSConfigurationStrings.it.resx new file mode 100644 index 00000000000..dceea43e1d5 --- /dev/null +++ b/src/System.Management.Automation/resources/it/PSConfigurationStrings.it.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 + + + PowerShell ha smesso di funzionare a causa di un problema di sicurezza: non è possibile leggere il file di configurazione: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PSDataBufferStrings.it.resx b/src/System.Management.Automation/resources/it/PSDataBufferStrings.it.resx new file mode 100644 index 00000000000..1977f1cb926 --- /dev/null +++ b/src/System.Management.Automation/resources/it/PSDataBufferStrings.it.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 + + + L'indice specificato è minore di zero o maggiore del numero di elementi nel buffer. L'indice deve essere compreso nell'intervallo {0}-{1}. + + + Non è possibile convertire un riferimento null in un tipo di valore. + + + Non è possibile convertire il valore dal tipo {0} al tipo {1}. + + + Non è possibile aggiungere oggetti a un buffer chiuso. Assicurarsi che il buffer sia aperto per consentire l'esito positivo delle operazioni di aggiunta e inserimento. + + + La proprietà SerializeInput può essere impostata solo per il tipo PSObject di PSDataCollection. Impostare la proprietà SerializeInput su false oppure modificare il tipo di raccolta in PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PSListModifierStrings.it.resx b/src/System.Management.Automation/resources/it/PSListModifierStrings.it.resx new file mode 100644 index 00000000000..d9ec64e384a --- /dev/null +++ b/src/System.Management.Automation/resources/it/PSListModifierStrings.it.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 + + + È stato rilevato il modificatore di elenco sconosciuto seguente: '{0}'. I modificatori di elenco validi sono Add, Remove e Replace. + + + Non è possibile applicare l'aggiornamento perché l'oggetto non è un tipo di raccolta supportato. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PSStyleStrings.it.resx b/src/System.Management.Automation/resources/it/PSStyleStrings.it.resx new file mode 100644 index 00000000000..47c636b1967 --- /dev/null +++ b/src/System.Management.Automation/resources/it/PSStyleStrings.it.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La stringa specificata presenta contenuto stampabile quando dovrebbe contenere solo sequenze di escape ANSI: {0} + + + MaxWidth per il rendering dello Stato deve essere almeno 18 per essere visualizzato correttamente. + + + Quando si aggiungono o rimuovono estensioni, l'estensione deve iniziare con un punto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ParameterBinderStrings.it.resx b/src/System.Management.Automation/resources/it/ParameterBinderStrings.it.resx new file mode 100644 index 00000000000..57e81453dc9 --- /dev/null +++ b/src/System.Management.Automation/resources/it/ParameterBinderStrings.it.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile trovare un parametro corrispondente al nome parametro ''{1}''. + + + Non è possibile trovare un parametro posizionale che accetti l'argomento ''{1}''. + + + Argomento mancante per il parametro ''{1}''. Specificare un parametro di tipo ''{2}'' e riprovare. + + + Non è possibile elaborare il parametro perché il nome del parametro ''{1}'' è ambiguo. Le possibili corrispondenze includono:{6}. + + + Non è possibile convertire ''{6}'' nel tipo ''{2}'' richiesto dal parametro ''{1}''. {7} + + + Non è possibile associare il parametro ''{1}''. {6} + + + Non è possibile associare i parametri posizionali ''{1}''. + + + Non è possibile associare i parametri posizionali perché non è stato indicato alcun nome. + + + Impossibile impostare il parametro utilizzando i parametri denominati. Uno o più parametri emessi non possono essere usati insieme o è stato specificato un numero insufficiente di parametri. + + + Non è possibile elaborare il comando a causa di uno o più parametri obbligatori mancanti:{1}. + + + Non è possibile specificare il parametro ''{1}'' nel set di parametri ''{6}''. + + + Non è possibile associare il parametro perché il parametro ''{1}'' è specificato più di una volta. Per fornire più valori ai parametri che possono accettare più valori, usare la sintassi della matrice. Ad esempio, "-parameter value1,value2,value3". + + + Non è possibile valutare il parametro ''{1}'' perché il relativo argomento è specificato come blocco di script e non è presente alcun input. Un blocco di script non può essere valutato senza input. + + + L'input al blocco di script per il parametro ''{1}'' non è riuscito. {6} + + + Non è possibile valutare il parametro ''{1}'' perché l'input dell'argomento non ha prodotto alcun output. + + + Non è possibile associare l'oggetto di input ad alcun parametro per il comando, perché il comando non accetta input della pipeline oppure l'input e le relative proprietà non corrispondono ad alcun parametro che accetta l'input della pipeline. + + + Non è possibile associare l'oggetto di input perché non contiene le informazioni necessarie per associare tutti i parametri obbligatori: {6} + + + Non è possibile elaborare l'input della pipeline perché non è possibile recuperare il valore predefinito del parametro ''{1}''. {6} + + + Impossibile recuperare i parametri dinamici del cmdlet. {6} + + + Specificare i valori per i parametri seguenti: + + + cmdlet {0} nella posizione della pipeline di comando {1} + + + Non è possibile elaborare la trasformazione degli argomenti nel parametro "{1}".{6} + + + {6} + + + Non è possibile convalidare l'argomento per il parametro ''{1}''. {6} + + + Non è possibile associare il parametro ''{1}'' alla destinazione. {6} + + + Non è possibile associare l'argomento al parametro ''{1}'' perché è Null. + + + Non è possibile associare l'argomento al parametro ''{1}'' perché è una stringa vuota. + + + Non è possibile associare l'argomento al parametro ''{1}'' perché è una raccolta vuota. + + + Non è possibile associare l'argomento al parametro ''{1}'' perché è una matrice vuota. + + + Non è possibile elaborare il comando. Il parametro ''{0}'' è definito più volte. + + + Non è possibile associare il cmdlet {0} perché il parametro ''{1}'' è di tipo ''{2}'' e non è possibile identificare il metodo Add() oppure esistono più metodi Add(). {6} + + + Non è possibile associare il cmdlet {0} perché il parametro definito in fase di esecuzione ''{1}'' è stato aggiunto a RuntimeDefinedParameterDictionary con la chiave ''{6}''. La chiave deve essere uguale a RuntimeDefinedParameter.Name. + + + Non è possibile associare l'argomento al parametro ''{1}'' perché i PSTypeNames dell'argomento non corrispondono al PSTypeName richiesto dal parametro: {6}. + + + In $PSDefaultParameterValues sono definiti più valori predefiniti diversi per il parametro corrispondente al nome o all'alias seguente: {0}. Questi valori predefiniti sono stati ignorati. + + + Il nome o l'alias seguente definito in $PSDefaultParameterValues per questo cmdlet viene risolto in più parametri: {0}. Il valore predefinito è stato ignorato. + + + {6} Questo errore potrebbe essere stato causato dall'applicazione dell'associazione predefinita dei parametri. È possibile disabilitare l'associazione predefinita dei parametri in $PSDefaultParameterValues impostando $PSDefaultParameterValues["Disabled"] su $true, quindi riprovare. I seguenti parametri predefiniti sono stati associati correttamente per questo cmdlet quando si è verificato l'errore:{7} + + + {6} Questo errore potrebbe essere causato dall'applicazione dell'associazione predefinita dei parametri. È possibile disabilitare l'associazione predefinita dei parametri in $PSDefaultParameterValues impostando $PSDefaultParameterValues["Disabled"] su $true, quindi riprovare. Il seguente parametro predefinito è stato associato correttamente per questo cmdlet quando si è verificato l'errore:{7} + + + L'associazione del valore predefinito ''{0}'' al parametro ''{1}'' non è riuscita: {2} + + + La chiave ''{0}'' non ha un formato valido. Per informazioni sul formato corretto, vedi about_Parameters_Default_Values all'indirizzo https://go.microsoft.com/fwlink/?LinkId=228266. + + + I formati delle chiavi ''{0}'' non sono validi. Per informazioni sul formato corretto, vedi about_Parameters_Default_Values all'indirizzo https://go.microsoft.com/fwlink/?LinkId=228266. + + + Il parametro ''{0}'' è obsoleto. {1} + + + La chiave ''{0}'' di tipo ''{1}'' non è un valore stringa. DefaultParameterDictionary accetta solo chiavi con valore stringa. + + + La chiave ''{0}'' è già stata aggiunta al dizionario. + + + Chiamata di metodo o proprietà non consentita + + + La chiamata del metodo o della proprietà ''{0}'' per il tipo ''{1}'' non sarà consentita in modalità Linguaggio vincolato per gli script non attendibili. + + + Creazione del tipo non consentita + + + La creazione del tipo ''{0}'' non sarà consentita durante l'associazione dei parametri in modalità Linguaggio vincolato per gli script non attendibili. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ParserStrings.it.resx b/src/System.Management.Automation/resources/it/ParserStrings.it.resx new file mode 100644 index 00000000000..4d7b8badc79 --- /dev/null +++ b/src/System.Management.Automation/resources/it/ParserStrings.it.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Non è possibile caricare l'assembly '{0}'. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PathUtilsStrings.it.resx b/src/System.Management.Automation/resources/it/PathUtilsStrings.it.resx new file mode 100644 index 00000000000..28eccacc0c7 --- /dev/null +++ b/src/System.Management.Automation/resources/it/PathUtilsStrings.it.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La codifica 'UTF-7' è obsoleta; usare UTF-8. + + + Il file {0} esiste già e {1} è stato specificato. + + + Non è possibile aprire il file perché il provider corrente ({0}) non riesce ad aprire un file. + + + Non è possibile eseguire l'operazione perché il percorso è stato risolto in più file. Il comando non può eseguire operazioni su più file. + + + Non è possibile eseguire l'operazione perché il percorso con caratteri jolly {0} non si è risolto in un file. + + + Codifica sconosciuta {0}; i valori validi sono {1}. + + + La directory '{0}' esiste già. Utilizzare il parametro -Force se si vuole sovrascrivere la directory e i file al suo interno. + + + Il percorso dei moduli utente non esiste. Pertanto non è possibile creare una cartella di moduli per il nome del modulo '{0}'. + + + Non è possibile creare il modulo {0} a causa di quanto segue:{1}. Utilizzare un argomento diverso per il parametro -OutputModule e riprovare. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Non è possibile caricare il modulo perché è stato generato con una versione non compatibile del cmdlet {0}. Generare il modulo con il cmdlet {0} della sessione corrente e riprovare a caricare il modulo. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PipelineStrings.it.resx b/src/System.Management.Automation/resources/it/PipelineStrings.it.resx new file mode 100644 index 00000000000..c6a19ae74ee --- /dev/null +++ b/src/System.Management.Automation/resources/it/PipelineStrings.it.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è elaborare l'istanza del cmdlet perché è già in uso da un'altra pipeline. Contattare il servizio di supporto clienti Microsoft. + + + Non è possibile eseguire l'operazione perché la pipeline è stata avviata. Arrestare la pipeline e riprovare. + + + Non è possibile continuare l'esecuzione del cmdlet perché l'esecuzione dei cmdlet è stata impedita dai criteri Stop. + + + Non è possibile eseguire la pipeline perché il primo cmdlet della pipeline sta tentando di leggere l'input dai risultati di un cmdlet precedente. Modificare il primo cmdlet, rimuoverlo oppure aggiungere alla pipeline il cmdlet il cui output è richiesto dal primo cmdlet, quindi provare a eseguire di nuovo la pipeline. + + + Non è possibile elaborare il numero del cmdlet. La funzione ReadFromCommand deve specificare l'ID di un cmdlet già aggiunto alla pipeline. Contattare il servizio di supporto clienti Microsoft. + + + Non è possibile leggere l'output delle funzioni ReadFromCommand e ReadErrorQueue perché un altro cmdlet sta già leggendo tale output. Contattare il servizio di supporto clienti Microsoft. + + + Non è possibile eseguire la pipeline perché non sono presenti comandi. Aggiungere almeno un comando alla pipeline, quindi eseguirlo di nuovo. + + + Non è possibile completare l'operazione della pipeline perché non è ancora stata avviata. È necessario chiamare il metodo Begin() prima di chiamare End() su una pipeline di cui è possibile eseguire passaggi. + + + I metodi WriteObject e WriteError non possono essere chiamati dall'esterno degli override dei metodi BeginProcessing, ProcessRecord ed EndProcessing e possono essere chiamati solo dallo stesso thread. Verificare che il cmdlet effettui queste chiamate correttamente oppure contattare il servizio di supporto clienti Microsoft. + + + Un cmdlet ha generato un'eccezione dopo la chiamata a ThrowTerminatingError. +La prima eccezione è stata "{0}" con analisi dello stack "{1}". +La seconda eccezione è stata "{2}" con analisi dello stack "{3}". + + + I metodi WriteObject e WriteError non possono essere chiamati dopo che la pipeline è stata chiusa. Contattare il servizio di supporto clienti Microsoft. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Si è verificato un errore durante la creazione della pipeline. + + + Questa pipeline non supporta la semantica di disconnessione e riconnessione. + + + Non è possibile connettere questa pipeline perché non è nello stato disconnesso. + + + L'oggetto dello spazio di esecuzione ha un comando remoto Null associato. Non è possibile creare un oggetto RemotePipeline disconnesso perché non è stato specificato alcun comando remoto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/PowerShellStrings.it.resx b/src/System.Management.Automation/resources/it/PowerShellStrings.it.resx new file mode 100644 index 00000000000..9e116a6b102 --- /dev/null +++ b/src/System.Management.Automation/resources/it/PowerShellStrings.it.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 + + + Lo stato dell'istanza corrente di PowerShell non è valido per questa operazione. + + + Non è possibile eseguire l'operazione perché un comando è già stato avviato. Attendere il completamento del comando oppure arrestarlo e quindi ripetere l'operazione. + + + Nessun comando specificato. + + + L'istanza di PowerShell non si trova nello stato corretto per creare un'istanza di PowerShell annidata. Le istanze di PowerShell annidate devono essere create solo in un'istanza di PowerShell in esecuzione. + + + Non è possibile eseguire l'operazione perché lo stato dello spazio di esecuzione non è "{0}". Lo stato corrente dello spazio di esecuzione è "{1}". + + + Le istanze di PowerShell annidate non possono essere richiamate in modo asincrono. Usare il metodo Invoke. + + + L'oggetto {0} non è stato creato chiamando {1} in questa istanza di PowerShell. + + + Quando lo spazio di esecuzione è impostato per riutilizzare un thread, lo stato dell'apartment nelle impostazioni di chiamata deve corrispondere allo spazio di esecuzione. + + + Quando lo spazio di esecuzione è impostato per usare il thread corrente, lo stato dell'apartment nelle impostazioni di chiamata deve corrispondere a quello del thread corrente. + + + Per aggiungere un parametro è necessario un comando. Prima di aggiungere un parametro, è necessario aggiungere un comando all'istanza di PowerShell. + + + Le chiavi nel dizionario devono essere stringhe. + + + Nessuno spazio di esecuzione disponibile per eseguire comandi in questo thread. È possibile specificarne uno nella proprietà DefaultRunspace del tipo System.Management.Automation.Runspaces.Runspace. Il comando che si è tentato di richiamare è: {0} + + + Non è possibile connettere l'oggetto PowerShell perché non è associato a uno spazio di esecuzione remoto o a un pool di spazi di esecuzione. + + + Il comando in esecuzione è stato disconnesso, ma è ancora in esecuzione sul server remoto. Riconnettersi per ottenere lo stato dell'operazione del comando e i dati di output. + + + Non è possibile eseguire l'operazione perché la sessione corrente di PowerShell si trova nello stato Disconnesso. Connettere questa sessione di PowerShell e quindi attendere il completamento del comando oppure arrestarlo. + + + Non è possibile eseguire l'operazione perché la sessione corrente di PowerShell si trova nello stato Disconnesso. Connettere questa sessione di PowerShell e quindi riprovare. + + + Il tentativo di connessione al comando remoto non è riuscito. + + + Non è possibile eseguire l'operazione perché è in corso l'arresto di un comando. Attendere il completamento dell'arresto del comando e quindi ripetere l'operazione. + + + Nessuno spazio di esecuzione disponibile per eseguire comandi in questo thread. È possibile specificarne uno nella proprietà DefaultRunspace del tipo System.Management.Automation.Runspaces.Runspace. L'istanza corrente di PowerShell non contiene alcun comando da richiamare. + + + Non è possibile creare un oggetto PowerShell che usa lo spazio di esecuzione corrente perché non è disponibile alcuno spazio di esecuzione corrente. Lo spazio di esecuzione corrente potrebbe essere in fase di avvio, ad esempio quando viene creato con uno stato sessione iniziale. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ProgressRecordStrings.it.resx b/src/System.Management.Automation/resources/it/ProgressRecordStrings.it.resx new file mode 100644 index 00000000000..08ac31f54ee --- /dev/null +++ b/src/System.Management.Automation/resources/it/ProgressRecordStrings.it.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Non è possibile elaborare l'argomento perché {0} non può essere un valore negativo. + + + Non è possibile elaborare l'argomento perché il valore di {0} non può essere null o vuoto. + + + Non è possibile impostare la percentuale perché {0} non può essere maggiore di 100. + + + ParentActivityId non può essere uguale ad ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ProviderBaseSecurity.it.resx b/src/System.Management.Automation/resources/it/ProviderBaseSecurity.it.resx new file mode 100644 index 00000000000..8735a822062 --- /dev/null +++ b/src/System.Management.Automation/resources/it/ProviderBaseSecurity.it.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 + + + Non è possibile utilizzare l'interfaccia perché l'interfaccia ISecurityDescriptorCmdletProvider non è supportata da questo provider. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/ProxyCommandStrings.it.resx b/src/System.Management.Automation/resources/it/ProxyCommandStrings.it.resx new file mode 100644 index 00000000000..837517b4271 --- /dev/null +++ b/src/System.Management.Automation/resources/it/ProxyCommandStrings.it.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 + + + Il parametro 'help' non è riconosciuto come un oggetto HelpInfo valido creato dal comando 'get-help'. + + + Non è possibile generare il comando proxy perché CommandMetadata non ha un nome. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/RegistryProviderStrings.it.resx b/src/System.Management.Automation/resources/it/RegistryProviderStrings.it.resx new file mode 100644 index 00000000000..92bc0d6cac2 --- /dev/null +++ b/src/System.Management.Automation/resources/it/RegistryProviderStrings.it.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Imposta elemento + + + Elemento: {0} Valore: {1} + + + Cancella elemento + + + Elemento: {0} + + + Nuovo elemento + + + Elemento: {0} + + + Rimuovere la chiave + + + Elemento: {0} + + + Copia chiave + + + Elemento: {0} Destinazione: {1} + + + Rinomina elemento + + + Elemento: {0} NewName: {1} + + + Sposta elemento + + + Elemento: {0} Destinazione: {1} + + + Imposta proprietà + + + Elemento: {0} Proprietà: {1} + + + Cancella proprietà + + + Elemento: {0} Proprietà: {1} + + + Nuova proprietà + + + Elemento: {0} Proprietà: {1} + + + Rimuovi proprietà + + + Elemento: {0} Proprietà: {1} + + + Rinomina proprietà. + + + Elemento: {0} SourceProperty: {1} DestinationProperty: {2} + + + Copia proprietà + + + Elemento: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Sposta proprietà + + + Elemento: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + L'operazione non è stata elaborata. La posizione specificata non consente questa operazione. + + + L'operazione non è consentita nella posizione di origine. + + + L'operazione non è consentita nella posizione di destinazione. + + + Impostazioni di configurazione per il computer locale + + + Impostazioni software per l'utente corrente + + + Esiste già una chiave in questo percorso. + + + Non è possibile eseguire l'operazione perché il percorso di destinazione è subordinato al percorso di origine. + + + La proprietà esiste già. + + + La proprietà {0} non esiste nel percorso {1}. + + + La chiave del Registro di sistema non esiste nel percorso specificato. + + + Non è possibile associare il parametro 'Type'. Non è possibile convertire "{0}" in "{1}". I valori di enumerazione possibili sono "String, ExpandString, Binary, DWord, MultiString, QWord, Unknown". + + + La chiave {0} è stata creata, ma non è stato possibile impostare un valore predefinito. + + + Non è possibile creare un'unità con la radice specificata. Il percorso radice non esiste. + + + Non è possibile rinominare l'elemento perché esiste già un elemento con quel nome nello stesso contenitore. + + + Il nome della chiave del Registro di sistema deve iniziare con un nome chiave di base valido. + + + L'argomento della sottochiave non è valido. + + + Non è possibile eliminare un albero di sottochiavi perché la sottochiave non esiste. + + + Non esiste alcun valore con quel nome. + + + Il valore enum {0} non è valido. + + + È necessario specificare un argomento di tipo valore. + + + È necessario specificare un argomento name. + + + Il valore RegistryValueKind specificato non è valido. + + + RegistryKey.SetValue non consente un valore String[] che contiene un riferimento String null. + + + Le sottochiavi del Registro di sistema non devono contenere più di 255 caratteri. + + + È necessario specificare un nome di sottochiave non vuoto. + + + Il tipo dell'oggetto valore non corrisponde all'elemento RegistryValueKind specificato oppure non è possibile convertire correttamente l'oggetto. + + + RegistryKey.SetValue non supporta matrici di tipo '{0}'. Sono supportati solo Byte[] e String[]. + + + La chiave del Registro di sistema specificata non esiste. + + + La lunghezza del nome di valore specificato supera il numero massimo di 16383 caratteri. + + + Le dimensioni dei dati del valore specificato superano il valore massimo di 1 MB. + + + La sottochiave del Registro di sistema specificata non esiste. + + + Il valore RegistryKeyPermissionCheck specificato non è valido. + + + Nella chiave del Registro di sistema sono contenute sottochiavi e con questo metodo non sono supportate rimozioni. + + + Non è possibile creare un handle KTM senza Transaction.Current o una transazione specificata. + + + È necessario che la transazione specificata o Transaction.Current corrisponda alla transazione usata per creare o aprire questo elemento TransactedRegistryKey. + + + L'oggetto TransactedRegistryKey non è associato a una transazione perché si riferisce a una chiave predefinita. + + + L'accesso richiesto al Registro di sistema non è consentito. + + + Accesso negato alla chiave del Registro di sistema '{0}'. + + + Non è possibile scrivere nella chiave del Registro di sistema. + + + Non è possibile accedere a una chiave del Registro di sistema chiusa. + + + Errore sconosciuto: {0}. + + + Le transazioni del Registro di sistema non sono supportate in questa piattaforma. + + + L'handle di traccia specificato non è valido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/RemotingErrorIdStrings.it.resx b/src/System.Management.Automation/resources/it/RemotingErrorIdStrings.it.resx new file mode 100644 index 00000000000..d09262114f3 --- /dev/null +++ b/src/System.Management.Automation/resources/it/RemotingErrorIdStrings.it.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Si è verificato un errore di tipo "{0}". + + + Memoria del processo insufficiente. + + + L'enumerazione remota di PSSession con -ComputerName è supportata solo in Windows e non in "{0}". + + + L'ID pipeline "{0}" non corrisponde all'InstanceId della pipeline attualmente in esecuzione, "{1}". + + + L'ID pipeline "{0}" non è stato trovato nel server. + + + La pipeline remota è stata arrestata. + + + La sessione di esiste già. Non è consentito creare di nuovo la sessione con lo stesso InstanceId {0}. + + + L'InstanceId della sessione client specificato "{0}" non corrisponde all'InstanceId "{1}" della sessione esistente. + + + Apertura della sessione remota non riuscita. + + + Non è possibile trovare la sessione remota specificata con InstanceId client "{0}". + + + La risposta al prompt contiene un ID prompt "{0}" che non è stato trovato. + + + Chiamata dell'host remoto a "{0}" non riuscita. + + + Il metodo host remoto {0} non è implementato. + + + La codifica dei dati del metodo host remoto non è supportata per il tipo {0}. + + + La decodifica dei dati del metodo host remoto non è supportata per il tipo {0}. + + + La creazione di pipeline annidate non è supportata. + + + Gli URI relativi non sono supportati nella creazione di sessioni remote. + + + Si è verificato un errore durante la decodifica dei dati dall'host remoto. Sono presenti errori nei dati di rete. + + + Solo gli amministratori possono eseguire l'override delle opzioni thread in remoto. + + + Richiesta di credenziali di PowerShell: {0} + + + Avviso: uno script o un'applicazione nel computer remoto {0} sta richiedendo le credenziali dell'utente. Immettere le credenziali solo se si considerano attendibili il computer remoto e l'applicazione o lo script che le richiede. + +{1} + + + Uno script o un'applicazione nel computer remoto {0} richiede di leggere una riga in modo sicuro. Immettere informazioni riservate, ad esempio le credenziali, solo se si considerano attendibili il computer remoto e l'applicazione o lo script che le richiede. + + + Uno script o un'applicazione nel computer remoto {0} sta tentando di leggere il contenuto del buffer nell'host di PowerShell. Per motivi di sicurezza, questa operazione non è consentita; la chiamata è stata eliminata. + + + Uno script o un'applicazione nel computer remoto {0} sta inviando una richiesta di input. Quando richiesto immettere informazioni riservate, ad esempio le credenziali o le password, solo se si considerano attendibili il computer remoto e l'applicazione o lo script che richiede i dati. + + + Ricevuta chiamata a host remoto non supportata: {0}. + + + Sono stati ricevuti dati di comunicazione remota con azione non supportata: {0}. + + + Sono stati ricevuti dati remoti con azione non supportata: {0}. + + + I dati di comunicazione remota non includono la proprietà di destinazione. + + + La proprietà dell'interfaccia di destinazione manca nei dati di comunicazione remota. + + + Nei dati di comunicazione remota manca la proprietà Session InstanceId. + + + La proprietà RemotingDataType non è presente nei dati di comunicazione remota. + + + Manca la proprietà CallId nei dati di comunicazione remota. + + + I dati di comunicazione remota non includono la proprietà MethodName. + + + Il flag IsStartFragment per il primo frammento non è impostato. + + + Manca la proprietà {0} nei dati di comunicazione remota. + + + Ricevuto ObjectId imprevisto. È possibile che i frammenti non siano stati costruiti correttamente dal computer remoto oppure che i dati siano stati danneggiati o modificati. + + + ObjectId non può essere minore o uguale a 0. Questo può verificarsi se i frammenti non sono stati creati correttamente dal computer remoto oppure se i dati sono stati modificati da utenti non autorizzati. + + + Gli ID di frammento dello stesso oggetto devono essere in sequenza, con una variazione incrementale di 1. Questo problema può verificarsi se i frammenti non sono stati creati correttamente dal computer remoto. È anche possibile che i dati siano stati danneggiati o modificati. + + + I dati di comunicazione remota sono troppo grandi per essere riassemblati dai frammenti. Questo può accadere se la lunghezza dei dati in un frammento è maggiore di Int32.Max. Può anche verificarsi se i dati sono stati modificati da utenti non autorizzati. + + + Il flag IsEndFragment non è impostato per l'ultimo frammento. È possibile che i frammenti non siano stati costruiti correttamente dal computer remoto o se i dati sono danneggiati o modificati. + + + I dati di comunicazione remota deserializzati sono Null. + + + La lunghezza del BLOB del frammento non è compresa nell'intervallo: {0} + + + Errore durante la decodifica di ErrorRecord. + + + Errore durante la decodifica di PipelineStateInfo. + + + Errore durante la decodifica di RunspaceStateInfo. + + + Ricevuto tipo RemotingTargetInterface non supportato: {0} + + + Il metodo host remoto è stato richiamato su una classe di destinazione sconosciuta: {0} + + + Il metodo host remoto è stato richiamato senza specificare una classe di destinazione. + + + Errore durante la decodifica di RunspacePoolStateInfo. + + + Errore durante la decodifica del numero minimo di spazi di esecuzione. + + + Errore durante la decodifica del numero massimo di spazi di esecuzione. + + + Errore durante la decodifica di PowerShellStateInfo. + + + Tipo imprevisto della proprietà {0} (previsto {1}, ottenuto {2}). + + + Tipo imprevisto di dati di comunicazione remota (previsto PSObject, ottenuto {0}). + + + Tipo imprevisto di comando codificato (previsto PSObject, ottenuto {0}). + + + Tipo imprevisto di parametro di comando codificato (previsto PSObject, ottenuto {0}). + + + Si è verificato un errore durante la decodifica dei dati ricevuti dal computer remoto. Per decodificare un oggetto deserializzato ricevuto da un computer remoto sono necessari almeno {0} byte di dati. È possibile che i frammenti non siano stati costruiti correttamente dal computer remoto o se i dati sono danneggiati o modificati. + + + Ricevuto pacchetto non destinato all'utente connesso: utente = {0}, destinazione pacchetto = {1}. + + + Il timer di negoziazione del client è scaduto. L'intervallo di timeout della negoziazione è {0} millisecondi. + + + Il client PowerShell non supporta le {0} {1} negoziate dal server. Verificare che il server sia compatibile con la compilazione {2} e la versione del protocollo {3} di PowerShell. + + + {0}. La negoziazione con il server non è riuscita. Verificare che il server sia compatibile con la compilazione {1} e la versione del protocollo {2} di PowerShell. + + + Il server di destinazione ha inviato una richiesta di chiusura della sessione. + + + Il server che esegue PowerShell non supporta il {0} {1} negoziato dal computer client. Verificare che il computer client sia compatibile con la compilazione {2} e la versione del protocollo {3} di PowerShell. + + + Il server che esegue PowerShell non supporta operazioni di connessione su {0} {1} negoziato dal computer client. Verificare che il computer client sia compatibile con la compilazione {2} e la versione del protocollo {3} di PowerShell. + + + Il server che esegue PowerShell non è in grado di elaborare l'operazione di connessione perché le informazioni seguenti non sono state trovate o non sono valide: informazioni sulle funzionalità client e informazioni sul RunspacePool di connessione. + + + Il server che esegue PowerShell non è in grado di elaborare l'operazione di connessione perché il server non è stato avviato oppure è in fase di arresto. + + + Il server che esegue PowerShell non è in grado di elaborare l'operazione di connessione perché le proprietà del pool di spazi di esecuzione del server non corrispondono alle proprietà specificate del computer client. + + + {0}. La negoziazione con il client non è riuscita. Verificare che il client sia compatibile con la compilazione {1} e la versione del protocollo {2} di PowerShell. + + + Il timer di negoziazione del server è scaduto. L'intervallo di timeout della negoziazione è {0} millisecondi. + + + Il computer client ha inviato una richiesta per chiudere la sessione. + + + Si è verificato un errore che PowerShell non è in grado di gestire. Una sessione remota potrebbe essere terminata. + + + Il server non ha risposto con una chiave di sessione crittografata entro il periodo di timeout specificato. + + + Il client non ha risposto con una chiave pubblica entro il periodo di timeout specificato. + + + Tentativo di connessione non riuscito. + + + Tentativo di chiusura della sessione. + + + PowerShell non riesce a chiudere correttamente la sessione remota. La sessione si trova in uno stato indefinito perché non è stata aperta o connessa dopo essere stata disconnessa. PowerShell tenterà di forzare la chiusura della sessione nel computer locale, ma la sessione potrebbe non essere chiusa nel computer remoto. Per chiudere correttamente una sessione remota, aprirla prima o connettersi ad essa. + + + Non è possibile chiudere la sessione. + + + La sessione è chiusa. + + + Il tipo di handle Wait "{0}" non è supportato. + + + I dati ricevuti hanno un indice ID flusso di "{0}". È supportato solo un indice di ID flusso di output Standard pari a "0". + + + L'handle di standard input non è aperto. + + + Chiamata dell'API nativa a WriteFile non riuscita. Il codice errore è {0}. + + + Chiamata API nativa a ReadFile non riuscita. Il codice errore è {0}. + + + {0} non corrisponde a un valore dello schema valido. I valori validi sono ''http'' e ''https''. + + + La chiamata di ricezione lato client non è riuscita. + + + La chiamata di invio lato client non è riuscita. + + + L'handle di comando restituito dall'API WinRS WSManRunShellCommand è Null. + + + L'handle di standrad input non può essere impostato sullo stato ''no wait''. Il codice di errore di sistema è {0}. + + + Il numero di porta {0} non è compreso nell'intervallo di valori validi. L'intervallo di valori validi è compreso tra 1 e 65535. + + + Il processo del server è terminato. + + + La chiamata all'API di Windows GetStdHandle per ottenere l'handle di inout ha restituito un codice di errore: {0}. + + + La chiamata all'API di Windows GetStdHandle per ottenere l'handle di output ha restituito un codice di errore: {0}. + + + La chiamata all'API di Windows GetStdHandle per ottenere l'handle di errore ha restituito un codice di errore: {0}. + + + Connessione al server remoto {0} non riuscita. + + + La connessione al server remoto {0} non è riuscita con il messaggio di errore seguente: {1} + + + Chiusura dell'istanza della shell del server remoto non riuscita con il messaggio di errore seguente: {0} + + + Invio dei dati al server remoto {0} non riuscito. + + + L'invio dei dati al server remoto {0} non è riuscito con il messaggio di errore seguente: {1} + + + Ricezione dei dati dal server remoto {0} non riuscita. + + + L'elaborazione dei dati dal server remoto {0} non è riuscita con il messaggio di errore seguente: {1} + + + Avvio di un comando nel server remoto non riuscito. + + + Avvio di un comando nel server remoto non riuscito con il messaggio di errore seguente: {0} + + + Riconnessione a un comando nel server remoto non riuscito con il messaggio di errore seguente: {0} + + + Invio dei dati a un comando remoto non riuscito. + + + Invio dei dati a un comando remoto non riuscito con il seguente messaggio di errore: {0} + + + Ricezione dei dati per un comando remoto non riuscita. + + + Elaborazione dei dati per un comando remoto non riuscita con il seguente messaggio di errore: {0} + + + Si è verificato un errore con codice {0} durante la chiamata del metodo {1}. + + + {0} Per ulteriori informazioni, vedere l'argomento della Guida about_Remote_Troubleshooting. + + + Disconnessione dal server remoto {0} non riuscita. + + + La disconnessione al server remoto non è riuscita con il messaggio di errore seguente: {0} + + + Riconnessione al server remoto non riuscita. + + + La riconnessione al server remoto{0} non è riuscita con il messaggio di errore seguente: {1} + + + Il trasporto IPC (Inter-Process Communication) non supporta le operazioni di connessione. + + + EndpointConfiguration con ID {0} non esiste nel server remoto. Contattare l'amministratore di PowerShell oppure il proprietario o l'autore della configurazione dell'endpoint. + + + L'EndpointConfiguration con l'identificatore {0} non è in uno stato di sessione iniziale valido nel computer remoto. Contattare l'amministratore di PowerShell oppure il proprietario o l'autore della configurazione dell'endpoint. + + + Il valore obbligatorio {0} non è specificato per la chiave del Registro di sistema {1}. + + + Il valore obbligatorio {0} non è nel formato corretto per la chiave del Registro di sistema {1}. Il formato previsto è ''string''. + + + "{0}" deve specificare un file script PowerShell con estensione ".ps1". + + + Il parametro {0} è già specificato nella sezione {1}. Contattare l'amministratore per verificare che {0} sia specificato una sola volta. + + + Attributi "{0}" e "{1}" previsti nell'elemento "{2}". + + + "{0}", "{1}" devono essere specificati nella sezione "{2}" per caricare dinamicamente l'assembly. + + + Non è possibile caricare l'assembly "{0}" specificata nella sezione "{1}". + + + Non è possibile caricare il tipo "{0}" specificato nella sezione "{1}". + + + È necessario specificare sia "{0}" sia "{1}" nella sezione "{2}". + + + La destinazione "{0}" ha richiesto il reindirizzamento della connessione a "{1}". Tuttavia, "{1}" non è un URI formattato correttamente. + + + {0}Percorso di reindirizzamento segnalato: {1}. + + + La connessione è stata reindirizzata al seguente URI: "{0}" + + + {0} Per connettersi automaticamente all'URI reindirizzato, verificare la proprietà "{1}" della variabile di preferenza della sessione "{2}" e usare il parametro "{3}" nel cmdlet. + + + Le dimensioni correnti dell'oggetto deserializzato dei dati ricevuti dal server remoto hanno superato le dimensioni massime consentite per l'oggetto. Le dimensioni correnti dell'oggetto deserializzato sono {0}. La dimensione massima consentita per l'oggetto è {1}. + + + La quantità totale di dati ricevuti dal server remoto ha superato il valore massimo consentito. Il valore massimo consentito è {0}. + + + Le dimensioni correnti dell'oggetto deserializzato dei dati ricevuti dal computer client remoto hanno superato le dimensioni massime consentite per l'oggetto. Le dimensioni correnti dell'oggetto deserializzato sono {0}. La dimensione massima consentita per l'oggetto è {1}. + + + La quantità totale di dati ricevuti dal client remoto ha superato il valore massimo consentito. Il valore massimo consentito è {0}. + + + L'esecuzione dello script di avvio ha generato un errore: {0}. + + + Gli oggetti RemoteRunspaceInfo specificati sono duplicati. + + + Gli oggetti RemoteRunspaceInfo specificati hanno superato il limite massimo consentito. + + + Apertura della sessione remota non riuscita con uno stato imprevisto. Stato: {0}. + + + L'URI {0} specificato non è valido. + + + Sessione remota chiusa per l'URI {0}. + + + La sessione remota non è disponibile per ComputerName {0}. + + + La sessione remota non è disponibile per {0}. + + + Comando remoto: {0}, associato al processo con ID "{1}". + + + Un {0} non può essere specificato quando {1} è specificato. + + + I caratteri jolly non sono supportati per il parametro FilePath. Specificare un percorso senza caratteri jolly. + + + Il percorso specificato come valore del parametro FilePath non proviene dal provider FileSystem. + + + Il valore del parametro FilePath deve essere un file di script PowerShell. Immettere il percorso di un file con estensione .ps1 e riprovare a eseguire il comando. + + + Uno o più nomi di computer non sono validi. Se si sta tentando di passare un URI, usare il parametro -ConnectionUri oppure passare oggetti URI anziché stringhe. + + + Lo stato dell'istanza corrente del processo non è valido per questa operazione. + + + Il comando non riesce a trovare il processo perché il nome del processo {0} non è stato trovato. Verificare il valore del parametro Name, quindi riprovare a eseguire il comando. + + + Il comando non riesce a trovare un processo con l'identificatore di istanza {0}. Verificare il valore del parametro InstanceId, quindi riprovare a eseguire il comando. + + + Il comando non riesce a trovare un processo con ID processo {0}. Verificare il valore del parametro ID, quindi riprovare a eseguire il comando. + + + Non è possibile rimuovere il processon con l'ID processo {0} e il nome {1} perché non è stato completato. Per rimuovere il processo, arrestarlo prima oppure usare il parametro Force. + + + Non è possibile rimuovere il processon con l'ID processo {0} perché non è stato completato. Per rimuovere il processo, arrestarlo prima oppure usare il parametro Force. + + + Non è possibile rimuovere il processon con l'ID processo {0} e l'identificatore dell'istanza {1} perché non è stato completato. Per rimuovere il processo, arrestarlo prima oppure usare il parametro Force. + + + Comando remoto: {0}, associato al processo con ID "{1}". + + + Non è possibile recuperare i processi dei computer specificati. Il parametro ComputerName può essere usato solo con processi creati usando la comunicazione remota di PowerShell. + + + Il parametro Session può essere usato solo con oggetti PSRemotingJob. + + + La sessione remota con il nome {0} non è disponibile. + + + La sessione remota con l'ID sessione {0} non è disponibile. + + + {0} non contiene un elemento con ID {1}. + + + Il comando non può rimuovere il processo perché non esiste o perché è un processo figlio. I processi figlio possono essere rimossi solo rimuovendo il processo padre. + + + ''{0}'' non è un valore valido per il parametro ''{1}''. Il valore deve essere maggiore o uguale a zero. + + + {0} non può essere specificato come meccanismo di autenticazione proxy. Per l'autenticazione proxy sono supportati solo {1},{2} o {3}. + + + Non è possibile specificare le credenziali proxy quando si usa il seguente tipo di accesso proxy: {0}. Specificare un tipo di accesso diverso oppure non specificare le credenziali proxy. + + + È necessario specificare {0} un valore per l'opzione di sessione {1}. + + + La sessione deve essere aperta. + + + L'host non supporta Enter-PSSession ed Exit-PSSession. + + + Sono state trovate più corrispondenze perl'ID sessione {0}. + + + Sono state trovate più corrispondenze perl'ID sessione {0}. + + + Sono state trovate più corrispondenze per il nome {0}. + + + Enter-PSSession non è riuscito perché la sessione remota non fornisce i comandi necessari. + + + Non è possibile eseguire Enter-PSSession da un prompt nidificato. + + + Numero massimo di reindirizzamenti URI WS-Man consentiti durante la connessione a un computer remoto + + + Opzioni di sessione predefinite per le nuove sessioni remote + + + Nome della configurazione di sessione che verrà caricata nel computer remoto + + + AppName in cui verrà stabilita la connessione remota + + + Contiene informazioni sull'utente remoto che avvia la sessione remota. Questa variabile è disponibile solo da una sessione remota. + + + È necessario specificare sia "{0}" sia "{1}", oppure non specificarne nessuno. + + + La configurazione della sessione "{0}" non è stata trovata. + + + La configurazione della sessione "{0}" non è una shell basata su PowerShell. + + + La configurazione della sessione "{0}" è una shell basata su PowerShell. Usare PowerShell 6+ per modificarla. + + + La configurazione della sessione "{0}" è una shell basata su Windows PowerShell. Usare Windows PowerShell per modificarla. + + + Nessuna configurazione di sessione corrisponde ai criteri "{0}". + + + {0} + + + Nome: {0} + + + Nome: {0}. Consente agli amministratori di eseguire in remoto i comandi di PowerShell in questo computer. + + + Non è possibile eliminare il file temporaneo {0}. Motivo dell'errore: {1}. + + + La nuova shell è stata registrata correttamente, ma PowerShell non è in grado di eliminare il file temporaneo {0}. Motivo dell'errore: {1}. + + + Non è possibile scrivere i dati di configurazione della shell nel file temporaneo {0}. Motivo dell'errore: {1}. + + + Esecuzione del comando "{0}" per creare una nuova configurazione di sessione. + + + Nome: {0} SDDL: {1}. Consente agli utenti selezionati di eseguire in remoto i comandi di PowerShell in questo computer. + + + Esecuzione del comando "{0}" per rimuovere una configurazione di sessione. + + + Esecuzione del comando "{0}" per ottenere le configurazioni di sessione basate su PowerShell. + + + Esecuzione del comando "{0}" per aggiornare le proprietà di configurazione della sessione. + + + Nome: {0} SDDL: {1} + + + Esecuzione del comando "{0}" per abilitare la configurazione della sessione. + + + Configurazione rapida di Gestione remota Windows + + + Esecuzione del comando "{0}" per abilitare la gestione remota del computer tramite il servizio Windows Remote Management (WinRM). + Ciò include: + 1. Avviare o riavviare (se già avviato) il servizio WinRM + 2. Impostazione del tipo di avvio del servizio Gestione remota Windows su Automatico + 3. Creazione di un listener per accettare richieste su qualsiasi indirizzo IP + 4. Abilitare le eccezioni delle regole in entrata di Windows Firewall per il traffico WS-Management (solo per HTTP). + +Continuare? + + + Esecuzione dell'operazione: ''{0}''. + + + Nome: {0} SDDL: {1}. Consente agli utenti selezionati di eseguire in remoto i comandi di PowerShell in questo computer. + + + Esecuzione del comando "{0}" per disabilitare la configurazione della sessione. + + + Nome: {0} SDDL: {1}. Questo nega l'accesso remoto a questa configurazione di sessione per tutti gli utenti. + + + La disabilitazione delle configurazioni di sessione non annulla tutte le modifiche apportate dal cmdlet Enable-PSRemoting o Enable-PSSessionConfiguration. Potrebbe essere necessario annullare manualmente le modifiche seguendo questi passaggi: + 1. Arrestare e disabilitare il servizio WinRM. + 2. Eliminare il listener che accetta richieste in qualsiasi indirizzo IP. + 3. Disabilitare le eccezioni del firewall per le comunicazioni di WS-Management. + 4. Ripristinare il valore di LocalAccountTokenFilterPolicy su 0, che limita l'accesso remoto ai membri del gruppo Administrators nel computer. + + + Accesso negato. Per eseguire questo cmdlet, avviare PowerShell con l'opzione "Esegui come amministratore". + + + Riavvio del servizio Gestione remota Windows + + + ''Riavvia-servizio'' + + + Nome: {0} + + + È necessario riavviare il servizio Gestione remota Windows prima di visualizzare un'interfaccia utente per la selezione di SecurityDescriptor. Riavviare il servizio Gestione remota Windows, quindi eseguire il comando seguente: "{0}" + + + Registrazione della configurazione della sessione + + + La configurazione della sessione "{0}" non è stata trovata. Esecuzione del comando "{1}" per creare la configurazione della sessione "{0}". L'esecuzione di questo comando riavvia il servizio WinRM. + + + I parametri "{0}" e "{1}" non possono essere specificati insieme. Specificare il parametro "{0}" oppure quello "{1}". + + + Questa operazione potrebbe riavviare il servizio Gestione remota Windows. Continuare? + + + Non è possibile elaborare un elemento con tipo di nodo "{0}". Sono supportati solo i tipi di nodo {1} e {2}. + + + Non sono disponibili dati sufficienti per elaborare l'elemento {0}. + + + Sono previsti solo due attributi con i nomi "{0}" e "{1}" nell'elemento {2}. + + + Tipo di nodo "{0}" sconosciuto nell'elemento {1}. Nell'elemento {2} è previsto solo il tipo di nodo "{1}". + + + È previsto un solo attributo con il nome "{0}" nell'elemento {1}. + + + È stato ricevuto un elemento sconosciuto "{0}". Questo problema può verificarsi se il processo remoto è stato chiuso o terminato in modo anomalo. + + + Il meccanismo di autenticazione specificato "{0}" non è supportato. Per questa operazione è supportato solo "{1}". + + + Non è possibile trovare l'eseguibile pwsh in "{0}". +Si noti che ''Start-Job'' non è supportato per progettazione negli scenari in cui PowerShell è ospitato in altre applicazioni. In tali scenari, è invece consigliabile usare il modulo ''ThreadJob''. + + + Non è possibile avviare un processo ''pwsh'' a 32 bit dall'installazione ''pwsh'' a 64 bit. Installare ''pwsh'' a 32 bit se è necessario eseguire PowerShell in un processo a 32 bit. + + + Il processo in background ha segnalato un errore con il messaggio seguente: {0}. + + + Il processo in background è stato chiuso o terminato in modo anomalo: {0}. + + + Si è verificato un errore durante l'elaborazione dei dati dal processo in background. Errore segnalato: {0}. + + + Sono stati ricevuti dati per un comando inattivo con identificatore {0}. Dati ricevuti: {1}. + + + Un messaggio {0} destinato a una sessione non è supportato. Un messaggio {0} può essere inviato solo a un comando. + + + Il client non ha ricevuto una risposta per un'operazione di segnale nell'intervallo di tempo specificato. Ciò può verificarsi quando un comando non risponde a un messaggio di arresto in modo tempestivo. + + + Il client non ha ricevuto una risposta per un'operazione di chiusura nell'intervallo di tempo specificato. Ciò può verificarsi quando un comando non risponde a un messaggio di arresto in modo tempestivo. + + + Si è verificato un errore durante l'avvio del processo in background. Errore segnalato: {0}. + + + Il metodo ThrottlingJob.AddChildJob accetta solo processi figlio nello stato NotStarted. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + Il metodo ThrottlingJob.AddChildJob non può essere chiamato dopo una chiamata al metodo ThrottlingJob.EndOfChildJobs. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completato + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Per richiamare una pipeline annidata è necessario uno spazio di esecuzione valido. + + + Un adattatore di origine del processo {1} ha generato un'eccezione con il messaggio seguente: {0} + + + Il valore {0} non è valido per il parametro {1}. L'unico valore consentito è 5.1. + + + I parametri Wait e Keep non possono essere usati insieme nello stesso comando. + + + Il parametro WriteEvents non può essere usato senza il parametro Wait. + + + Il controllo delle versioni dell'endpoint di comunicazione remota di PowerShell non è supportato in PowerShell 7+. + + + Il tipo seguente non può essere creato come istanza perché il relativo costruttore non è pubblico: {0}. + + + Non è possibile eseguire l'operazione del processo (Create, Get o Remove) perché il tipo JobSourceAdapter specificato in JobDefinition non è registrato. Registrare il tipo JobSourceAdapter tramite una chiamata esplicita oppure chiamando il cmdlet Import-Module e specificando quindi un assembly. + + + Non è possibile creare il processo perché JobInvocationInfo non contiene una JobDefinition. Avviare JobInvocationInfo con una JobDefinition. + + + Lo stato dell'istanza del processo corrente è {0}. Questo stato non è valido per l'operazione tentata.{1} + + + Non è possibile connettere il processo ''{0}'' al server remoto. + + + Operazione Disconnect-PSSession non riuscita per l'ID spazio di esecuzione = {0}. + + + Operazione di connessione non riuscita per la sessione {0}. Lo stato dello spazio di esecuzione è {1} anziché Opened. + + + La query PSSession disconnessa non è riuscita per il computer "{0}". + + + Non è possibile connettere PSSession "{0}" perché non si trova nello stato Disconnesso o non è disponibile per la connessione. + + + La connessione di sessione non è supportata per PSSession "{0}" nella destinazione "{1}" perché il tipo di computer di destinazione è "{2}". + + + Non è possibile disconnettere PSSession "{0}" perché non si trova nello stato Aperto. + + + La disconnessione della sessione non è supportata per la PSSession "{0}" nel target "{1}" perché il tipo di computer di destinazione è "{2}". + + + Receive-PSSession non supporta PSSession "{0}" sulla destinazione "{1}" perché il tipo di computer di destinazione è "{2}". + + + Non è possibile completare il comando. La proprietà ChildJobs contiene un valore non valido. + + + Non è possibile sospendere il processo con ID {0}. La sospensione dei processi non è supportata per alcuni tipi di processo. Per ulteriori informazioni sul supporto per la sospensione dei processi, vedere l'argomento della Guida relativo al tipo di processo. + + + Non è possibile riprendere il processo con ID {0}. La ripresa dei processi non è supportata per alcuni tipi di processo. Per ulteriori informazioni sul supporto per la ripresa dei processi, vedere l'argomento della Guida relativo al tipo di processo. + + + Non è possibile utilizzare il cmdlet Invoke-Command con entrambi i parametri AsJob e Disconnected nello stesso comando. + + + Query della sessione remota non riuscita per {0} con il messaggio di errore seguente: {1} + + + Tentativo di creare un processo con ID {0}. Non è possibile creare un processo con questo ID in questo momento. Verificare che l'ID non sia già stato assegnato una volta in questo computer. + + + Non è possibile creare un processo con ID {0}; questo non è un ID valido. Specificare un numero intero maggiore di 0 per l'ID processo. + + + L'elemento JobIdentifier specificato non deve essere Null. Specificare un JobIdentifier valido. + + + Il cmdlet Wait-Job non può terminare l'esecuzione perché uno o più processi sono bloccati in attesa dell'interazione dell'utente. Elaborare l'output del processo interattivo usando il cmdlet Receive-Job, quindi riprovare. + + + Non è possibile connettere {0} alla sessione remota e rimuoverla dal server. L'oggetto della sessione remota client verrà rimosso dal server, ma lo stato della sessione remota nel server è sconosciuto. + + + Operazione Disconnect-PSSession non riuscita per l'ID spazio di esecuzione = {0} per il seguente motivo: {1} + + + Non è possibile connettere il processo "{0}" al server e quindi non è possibile arrestarlo. + + + Il comando non riesce a trovare una PSSession con un valore InstanceId di "{0}". + + + Il comando non riesce a trovare una PSSession con il nome "{0}". + + + La comunicazione remota di PowerShell non è supportata in Windows Preinstallation Environment (WinPE). + + + Le modifiche apportate da {0} avranno effetto solo dopo il riavvio del servizio WinRM. + + + {0} potrebbe essere necessario riavviare il servizio WinRM se di recente è stata annullata la registrazione di una configurazione con questo nome, perché alcune strutture di dati di sistema potrebbero essere ancora memorizzate nella cache. In tal caso, potrebbe essere necessario riavviare WinRM. +Tutte le sessioni di WinRM connesse alle configurazioni di sessione di PowerShell, ad esempio Microsoft.PowerShell, e alle configurazioni di sessione create con il cmdlet Register-PSSessionConfiguration, vengono disconnesse. + + + Si è in esecuzione in una sessione remota ed è stata selezionata l'opzione Force, il che significa che il servizio WinRM potrebbe riavviarsi. Se il servizio WinRM viene riavviato, questa sessione remota verrà terminata e sarà necessario crearne una nuova per continuare + + + Il processo era Null durante il tentativo di salvare gli identificatori. Specificare un processo per salvarne gli identificatori. + + + Non è stato trovato alcun comando in esecuzione per questa PSSession. + + + Microsoft .NET Framework 2.0, necessario per Windows PowerShell 2.0, non è installato. Installare .NET Framework 2.0 e riprovare. + + + La pipeline remota non è riuscita. + + + La pipeline remota non è riuscita per il motivo seguente: {0} + + + Uno o più processi non possono essere ripresi perché lo stato non è valido per l'operazione. + + + Non è stato specificato alcun computer client per lo spazio di esecuzione remoto che esegue un metodo lato client. + + + Nome: {0} SDDL: {1}. Questo nega l'accesso remoto a questa configurazione di sessione. + + + Abilitato: False. In questo modo il servizio WS-Management viene configurato per negare la richiesta di connessione. + + + Abilitato: True. In questo modo il servizio WS-Management viene configurato per accettare la richiesta di connessione. + + + Alias da definire quando vengono applicati a una sessione + + + Assembly da caricare quando vengono applicati a una sessione + + + Autore di questo documento + + + Versione di CLR da usare quando viene applicata a una sessione + + + Società associata a questo documento + + + Informativa sul copyright per questo documento + + + Descrizione della funzionalità fornita da queste impostazioni + + + Variabili ambiente da definire quando vengono applicate a una sessione + + + Criterio di esecuzione da applicare a una sessione + + + File di formato (.ps1xml) da caricare quando applicati a una sessione + + + Funzioni da definire quando vengono applicate a una sessione + + + ID utilizzato per identificare in modo univoco il documento + + + Per questa configurazione di sessione vengono applicati i valori predefiniti del tipo di sessione. Può essere ''RestrictedRemoteServer'' (scelta consigliata), ''Empty'' o ''Default'' + + + Directory in cui inserire le trascrizioni della sessione per questa configurazione di sessione + + + Indica se eseguire questa configurazione di sessione come account amministratore (virtuale) del computer + + + Modalità di linguaggio da applicare quando viene applicata a una sessione. Può essere ''NoLanguage'' (scelta consigliata), ''RestrictedLanguage'', ''ConstrainedLanguage'' o ''FullLanguage'' + + + Moduli da importare quando vengono applicati a una sessione + + + Versione del motore di PowerShell da usare quando applicata a una sessione + + + Architettura del processore da usare quando applicata a una sessione + + + Numero di versione dello schema usato per questo documento + + + Script da eseguire quando vengono applicati a una sessione + + + Tipi da aggiungere quando vengono applicati a una sessione + + + File di tipo (.ps1xml) da caricare quando applicati a una sessione + + + Variabili da definire quando vengono applicate a una sessione + + + Ruoli utente (gruppi di sicurezza) e funzionalità del ruolo che devono essere applicate quando applicate a una sessione + + + Alias da rendere visibili quando vengono applicati a una sessione + + + Cmdlet da rendere visibili quando vengono applicati a una sessione + + + Non è possibile analizzare la definizione del comando visibile per ''{0}''. La definizione del comando visibile deve essere una hashtable con le chiavi ''Name'' e ''Parameters''. Il valore della chiave ''Parameters'' deve essere una raccolta di hashtable con le chiavi ''Name'' e, facoltativamente, ''ValidateSet'' oppure ''ValidatePattern''. + + + Funzioni da rendere visibili quando vengono applicati a una sessione + + + Provider da rendere visibili quando vengono applicati a una sessione + + + Comandi esterni (script e applicazioni) da rendere visibili quando applicati a una sessione + + + Il percorso del file di configurazione PSSession ''{0}'' non è valido. L'argomento del percorso deve risolvere un singolo file nel file system con estensione ''.pssc''. Correggere la specifica del percorso e riprovare. + + + Il percorso del file Role Capability ''{0}'' non è valido. L'argomento del percorso deve risolvere un singolo file nel file system con estensione ''.psrc''. Correggere la specifica del percorso e riprovare. + + + La voce ''Roles'' deve essere una tabella hash, ma era una {0}. + + + Non é possibile convertire il valore della voce di ruolo ''{0}'' in una tabella hash. La voce ''Roles'' deve essere una tabella hash con i nomi dei gruppi come chiavi, dove il valore associato a ogni chiave è un'altra tabella hash delle proprietà di configurazione della sessione per tale ruolo. + + + Non è possibile trovare la funzionalità di ruolo ''{0}''. La funzionalità di ruolo deve essere un file denominato ''{1}'' all'interno di una cartella 'RoleCapabilities'' in un modulo nel percorso dei moduli corrente. + + + Non è possibile trovare il percorso del modulo da importare. Il valore del parametro ModulesToImport {0} non esiste o non è una directory di moduli. Correggere il valore e riprovare a eseguire il comando. + + + Il file di configurazione specificato ''{0}'' non è stato caricato perché non è stato trovato alcun file di configurazione valido. + + + Il computer {0} è stato disconnesso. + + + Tentativo di riconnessione a {0} non riuscito. Tentativo di disconnessione della sessione in corso... + + + Verrà effettuato un tentativo di riconnessione a {0}... + + + La connettività di rete a {0} è stata interrotta e il tentativo di riconnessione non è riuscito. Ripristinare la connessione di rete e riconnettersi usando Connect-PSSession o Receive-PSSession. + + + La connessione di rete a {0} è stata ripristinata. Tentativo di riconnessione per un massimo di {1} minuti... + + + La connessione di rete a {0} è stata ripristinata. + + + L'autenticazione {0} richiede un nome utente e una password espliciti. Specificare il nome utente e la password usando il parametro -Credential, quindi riprovare a eseguire il comando. + + + L'autenticazione di base non è supportata su HTTP in Unix. + + + Non è possibile trovare un processo pianificato con nome {0}. + {0} is the job definition name + + + Sono state trovate più definizioni di processo con nome {0}. Provare a includere il parametro -DefinitionType in Start-Job per limitare la ricerca della definizione del processo a un singolo adattatore di origine del processo. + + + Il membro ''SchemaVersion'' non è presente nel file di configurazione. Questo membro deve esistere ed essere assegnato a un numero di versione nel formato ''n.n.n.n''. Aggiungere il membro mancante al file {0}. + + + Il membro ''{0}'' deve essere una stringa. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + Il membro ''{0}'' deve essere una matrice di stringhe. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + Il membro ''{0}'' deve essere una tabella hash. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + Il membro ''{0}'' deve essere una matrice hash. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + Il membro ''{0}'' non è una chiave valida. Modificare il membro con una chiave valida nel file {1}. + + + Il membro ''{0}'' deve essere un tipo di enumerazione valido "{1}". I valori di enumerazione validi sono "{2}". Modificare il membro in modo che usi il tipo corretto nel file {3}. + + + Errore durante l'analisi del file di configurazione {0} con il seguente messaggio: {1} + + + Non è possibile utilizzare il parametro -WriteJobInResults senza il parametro -Wait + + + Il membro ''{0}'' non è un percorso assoluto {1}. Modificare il membro con un percorso assoluto nel file {2}. + + + La chiave ''{0}'' nel membro ''{1}'' non è valida. Modificare la chiave nel file {2}. + + + Il membro ''{0}'' deve contenere la chiave richiesta ''{1}''. Aggiungere la chiave richiesta al file {2}. + + + La chiave ''{0}'' contiene un'estensione {1} non valida. Specificare un'estensione dall'elenco seguente: {{{2}}}. + + + La chiave ''{0}'' nel membro ''{1}'' deve essere un blocco di script. Modificare la chiave in modo che usi il tipo corretto nel file {2}. + + + Il file di configurazione della sessione {0} non è valido. Specificare un file di configurazione della sessione valido e riprovare il comando. + + + Connessione di rete interrotta + + + Verrà effettuato un tentativo di riconnessione a {0}... + + + Il processo {0} è stato creato per la riconnessione. + + + La sessione {0} con ID istanza {1} nel computer {2} è stata disconnessa correttamente. + + + La sessione {0} con ID istanza {1} è stata creata per la riconnessione. + + + Il parametro SessionName può essere usato solo con il parametro di interruttore Disconnected. + + + Si è verificato un errore durante il tentativo di connessione della sessione PSSession. + + + Si è verificato un errore durante il tentativo di connessione alla macchina virtuale di destinazione. + + + Questo errore si è verificato durante il tentativo di connessione al contenitore di destinazione {0}. + + + PsSession si trova in uno stato disconnesso e non è disponibile per la connessione. + + + Il modulo Hyper-V per PowerShell non è disponibile in questo computer. + + + Non è possibile avviare il processo di PowerShell ({1}) all'interno del contenitore con ID {0} con errore: {2}. + + + La funzionalità Contenitori potrebbe non essere abilitata in questo computer. + + + Non è possibile terminare il processo di PowerShell con ID {0} all'interno del contenitore con ID {1}. + + + Il ContainerId di input {0} non esiste oppure il contenitore corrispondente non è in esecuzione. + + + Il parametro di input VMId non viene risolto in una singola macchina virtuale. + + + Il VMId di input {0} non viene risolto in una singola macchina virtuale. + + + Il parametro VMName di input non viene risolto in alcuna macchina virtuale. + + + Il parametro di input VMName corrisponde a più macchine virtuali. + + + Il VMName di input {0} non viene risolto in una singola macchina virtuale. + + + La macchina virtuale {0} non è in esecuzione. + + + La credenziale non è valida. + + + Il nome utente di input non può essere vuoto. + + + Non è possibile immettere la sessione {0} perché non si trova nello stato disconnesso o non è disponibile per la connessione. Recuperare la sessione remota usando Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Non è possibile immettere la sessione {0} perché non si trova nello stato disconnesso o non è disponibile per la connessione. Riconnettersi usando Connect-PSSession o Receive-PSSession. + + + La connettività di rete a {0} è stata interrotta e il tentativo di riconnessione non è riuscito. Ripristinare la connessione di rete e riconnettersi usando Connect-PSSession o Receive-PSSession. + + + Non è possibile creare un'istanza di RemoteSessionHyperVSocketClient a causa di un errore SetSocketOption. + + + Non è possibile creare un'istanza di RemoteSessionHyperVSocketServer. + + + Tentativo di riconnessione annullato. Ripristinare la connessione di rete e riconnettersi usando Connect-PSSession o Receive-PSSession. + + + Uno o più processi non possono essere sospesi perché lo stato non è valido per l'operazione. + + + Il parametro AutoRemoveJob non può essere usato senza il parametro Wait + + + Il servizio WS-Management non può elaborare la richiesta. Non é possibile trovare la configurazione della sessione {0} nell'unità WSMan: del computer {1}. Per ulteriori informazioni, vedere l'argomento della Guida about_Remote_Troubleshooting. + + + Non è possibile creare un processo dalla specifica {0} perché lo spazio di esecuzione specificato non è locale. Riprovare usando uno spazio di esecuzione locale oppure specificare un argomento RunspaceMode. + + + Non è possibile disconnettere la sessione {0} perché il valore di timeout di inattività specificato {1} (secondi) è maggiore del valore massimo consentito dal server {2} (secondi) oppure minore del valore minimo consentito {3} (secondi). Specificare un valore di timeout di inattività compreso nell'intervallo consentito e riprovare. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + L'opzione di sessione IdleTimeout specificata {0} (secondi) non è un intervallo valido. Specificare un valore di IdleTimeout maggiore o uguale al minimo consentito {1} (secondi). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + Il cmdlet "{0}" o l'alias "{1}" non possono essere presenti quando nel file di configurazione della sessione sono specificate le chiavi "{2}", "{3}", "{4}" o "{5}". + + + "L'opzione di trasporto non è valida. Il parametro "{0}" può essere diverso da zero solo se il parametro "{1}" è impostato su true". + + + Il membro ''{0}'' deve essere una matrice costituita da elementi stringa o tabella hash. + + + Il membro ''{0}'' deve essere una matrice costituita da elementi stringa o tabella hash. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + Non è possibile recuperare la definizione del processo ''{0}'' perché il percorso ''{1}'' fa riferimento a un percorso del provider ''{2}''. Modificare il parametro del percorso in un percorso del file system. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Non è possibile recuperare la definizione del processo ''{0}'' perché il percorso ''{1}'' si risolve in più percorsi di file. Modificare il parametro percorso in modo che corrisponda a un unico percorso. + {0} is job definition name +{1} is the user provided path + + + Non è possibile trovare un processo pianificato con tipo {0} e nome {1}. + {0} is the job definition type and {1} is the job definition name. + + + Non è possibile trovare il percorso WorkingDirectory {0}. + + + Non è possibile connettersi alla sessione {0}. La sessione non esiste più nel computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + Operazione di connessione non riuscita per la sessione {0} con il seguente messaggio di errore: {1} + + + Il parametro -Froce non può essere usato senza il parametro Wait. + + + Uno o più processi sono in stato sospeso o disconnesso e non possono continuare senza input utente aggiuntivo. Specificare il parametro -Force per passare a uno stato completato, non riuscito o arrestato. + + + Quando RunAs è abilitato in una configurazione di sessione di PowerShell, il modello di sicurezza di Windows non può applicare un limite di sicurezza tra sessioni utente diverse create tramite questo endpoint. Verificare che la configurazione dell'area di esecuzione di PowerShell sia limitata solo al set necessario di cmdlet e funzionalità. + + + Il processo è stato sospeso correttamente aggiungendo il parametro Force. + + + Il file di configurazione della sessione {0} non è valido. Specificare un file di configurazione della sessione valido e riprovare il comando. Errore durante l'analisi del file di configurazione: {1}. + + + Register-PSSessionConfiguration: la chiave ''{0}'' nel file di configurazione della sessione {1}. contiene un valore non valido. Correggere il file e riprovare a eseguire il comando. + + + Le sessioni disconnesse sono supportate solo quando il computer remoto esegue PowerShell 3.0 o una versione successiva di PowerShell. + + + L'utilizzo della memoria di un cmdlet ha superato il livello di avviso. Per evitare questa situazione, provare una delle soluzioni seguenti: 1) ridurre la velocità con cui le operazioni CIM producono dati (ad esempio, passando un valore basso al parametro ThrottleLimit), 2) aumentare la velocità con cui i dati vengono utilizzati dai cmdlet downstream oppure 3) usare il cmdlet Invoke-Command per eseguire l'intera pipeline nel server. Il cmdlet che ha superato un livello di avviso di utilizzo della memoria è stato avviato dalla seguente riga di comando: {0} + + + PSSession {0} è stata creata usando il parametro EnableNetworkAccess e può essere riconnessa solo dal computer locale. + + + Non è possibile avviare il processo. La modalità linguaggio per questa sessione non è compatibile con la modalità linguaggio a livello di sistema. + + + Non è possibile creare lo spazio di esecuzione. La modalità linguaggio per questa confiurazione non è compatibile con la modalità linguaggio a livello di sistema. + + + Non è possibile uscire da una pipeline annidata perché la pipeline non è nello stato annidato. + + + La sessione del server PowerShell non è in uno stato valido per l'esecuzione di comandi annidati. In questa sessione non è possibile eseguire comandi annidati. + + + Non è possibile richiamare un comando annidato nella sessione remota perché un comando annidato è già in esecuzione. + + + La sessione remota non è stata in grado di richiamare il comando {0} con l'errore: {1}. + + + Il comando della sessione remota è attualmente arrestato nel debugger. Usare il cmdlet Enter-PSSession per connettersi in modo interattivo alla sessione remota ed entrare automaticamente nel debugger della console. + + + La sessione remota a cui si è connessi non supporta il debug remoto. È necessario connettersi a un computer remoto che esegue PowerShell 4.0 o versioni successive. + + + Poiché lo stato della sessione {0}, {1}, {2} non è uguale a Open, non è possibile eseguire un comando nella sessione. Lo stato della sessione è {3}. + + + Non sono state specificate sessioni valide. Assicurarsi di fornire sessioni valide che siano nello stato Opened e disponibili per l'esecuzione di comandi. + + + La sessione {0}, {1}, {2} non è disponibile per l'esecuzione di comandi. La disponibilità della sessione è {3}. + + + Non è possibile eseguire il comando perché la proprietà ChildJobs è vuota. + + + Non è possibile eseguire il debug del processo perché non è disponibile alcun host debugger di PowerShell. Assicurarsi di eseguire questo comando in un host che supporta il debug. + + + Non è possibile trovare il processo coon ID {0}. + + + Non è possibile trovare il processo con ID istanza {0}. + + + Non è possibile trovare il processo denominato {0}. + + + Non è possibile eseguire il debug del processo perché non è disponibile alcuna interfaccia utente host. Assicurarsi di eseguire questo comando in un host PowerShell che implementa PSHostUserInterface. + + + Non è possibile eseguire il debug del processo perché la modalità host debugger è impostata su Nessuno o su Predefinito. La modalità host debugger deve essere LocalScript e/o RemoteScript. + + + Sono stati trovati più processi con ID {0}. Debug-Job può eseguire il debug di un solo processo alla volta. + + + Sono stati trovati più processi con il nome {0}. Debug-Job può eseguire il debug di un solo processo alla volta. + + + Il listener del server Named Pipe utilizzato per il collegamento di processi è già in esecuzione. + + + Enter-PSHostProcess non supporta l'accesso alla stessa sessione di PowerShell in cui è in esecuzione. + + + Sono stati trovati più processi con questo nome {0}. Usare l'ID del processo per specificare un solo processo a cui accedere. + + + Non è possibile entrare nel processo con ID ''{0}'' perché non ha caricato il motore di PowerShell oppure il listener named pipe è stato disabilitato. + + + Non è stato trovato alcun processo con ID: {0}. + + + Non è stato trovato alcun processo con nome: {0}. + + + Non è stata trovata alcuna named pipe con CustomPipeName: {0}. + + + Non è possibile elaborare il comando perché il pipeName specificato è troppo lungo. I nomi delle pipe in questa piattaforma possono contenere fino a {0} caratteri. Il nome della pipe ''{1}'' contiene {2} caratteri. + + + L'host corrente non supporta il cmdlet Enter-PSHostProcess. + + + "Il processo di destinazione della named pipe è terminato." + + + "Il processo di destinazione del socket Hyper-V è terminato." + + + {0}[Processo:{1}]: {2} + + + {0}[{1}]: {2} + + + Non è possibile connettersi al nome del dominio dell'applicazione {0} del processo {1}. Errore: {2}.. + + + Non è possibile connettersi alla pipe con nome {0}. Errore: {1}. + + + Il plug-in PowerShell non è in grado di elaborare l'operazione di connessione perché le informazioni di negoziazione richieste sono mancanti o incomplete. + + + Il plug-in PowerShell non è riuscito a elaborare l'operazione di connessione. + + + Il contesto del plug-in specificato non è valido. + + + Il plug-in PowerShell ha rilevato un errore irreversibile durante l'elaborazione degli argomenti {0}. + + + Il contesto di comando specificato non è valido. + + + I dati di input specificati non sono validi. Sono supportati solo dati di input di tipo {0}. + + + Il flusso di input specificato non è valido. Come flusso di input è supportato solo {0}. + + + Il set di flussi di output specificato non è valido. Come flusso di output è supportato solo {0}. + + + Il WSMAN_SENDER_DETAILS specificato non è valido. Non è possibile elaborare WSMAN_SENDER_DETAILS null. + + + Il contesto della shell fornito non è valido. + + + {0} + + + Il valore NULL non è consentito per {0} con il metodo del plug-in {1}. + + + Il valore NULL non è consentito per i set di flussi di input e output. {0} e {1} sono i flussi di input e output supportati. + + + Il valore NULL non è consentito per {0} con il metodo del plug-in {1}. + + + Il valore NULL non è consentito per {0} con il metodo del plug-in {1}. + + + L'operazione del plug-in PowerShell viene arrestata. Questo può accadere se il servizio o l'applicazione host viene arrestato. + + + Il plug-in PowerShell non riconosce l'opzione {0}. Verificare che il client sia compatibile con la compilazione {1} e la versione del protocollo {2} di PowerShell. + + + È prevista un'opzione con nome {0} dal client. Verificare che il client sia compatibile con la compilazione {1} e la versione del protocollo {2} di PowerShell. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Il plug-in PowerShell non supporta la versione del protocollo {2} richiesta dal client.</PSProtocolVersionError> + + + Il plug-in PowerShell ha rilevato un errore irreversibile durante la segnalazione del contesto al servizio WSMan. + + + Non è possibile creare una sessione del server gestito. + + + Il plug-in PowerShell ha rilevato un errore irreversibile durante la registrazione di un handle di attesa per la notifica di arresto. + + + Non è possibile entrare nello spazio di esecuzione perché in questa sessione è già stato eseguito il push di uno spazio di esecuzione. + + + Non è possibile entrare nello spazio di esecuzione perché non è disponibile alcun debugger remoto del server. + + + Non è possibile entrare nello spazio di esecuzione perché non è uno spazio di esecuzione remoto. + + + Errore di trasporto remoto: {0} + + + Non è possibile aprire la connessione pipe per PowerShell nel contenitore. Codice errore: {0}. + + + Non è possibile creare la named pipe IPC di PowerShell. Codice errore: {0}. + + + Timeout scaduto prima che fosse possibile stabilire la connessione alla named pipe. + + + Inizializzazione WSMan non riuscita. Codice di errore: {0}. + + + Non è possibile avviare il server named pipe in modalità server. + + + Non è possibile concedere l'accesso remoto a ''{0}'': ''{1}''. La configurazione della sessione è stata registrata, ma questo gruppo non ha accesso. Per risolvere l'errore, specificare un nome di gruppo valido e registrare di nuovo la configurazione della sessione. + + + Non è possibile ottenere le funzionalità della sessione per la configurazione di sessione''{0}'': questa configurazione non è stata registrata con un file di configurazione della sessione (.pssc), ad esempio uno creato dal cmdlet New-PSSessionConfigurationFile. + + + Non è possibile risolvere il nome utente ''{0}''. Verificare il nome utente e riprovare. + + + Gruppi associati all'account amministratore (virtuale) del computer + + + Non è possibile creare o aprire la sessione di configurazione {0}. + + + Applica la convalida dei parametri di input dello script. Questa opzione viene abilitata automaticamente quando si specifica MountUserDrive. + + + Crea un PSDrive ''User'' nella sessione da usare con Copy-Item quando il provider File System non è visibile. + + + Il membro ''{0}'' deve essere una tabella hash. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + Il membro "{0}" deve essere un numero intero. Modificare il membro in modo che usi il tipo corretto nel file {1}. + + + L'elaborazione dell'unità utente ha generato un errore {0}. + + + Dimensione massima facoltativa, in byte, dell'unità utente creata con il parametro MountUserDrive. La dimensione massima predefinita dell'unità utente è 50 MB. + + + Non è possibile trovare il provider del file system. + + + Nome dell'account del servizio gestito del gruppo in cui verrà eseguita la configurazione + + + Nome account del servizio gestito del grupponon valido. Il formato del nome account deve essere ''DomainName\UserName''. + + + Account di gruppo per i quali l'appartenenza è necessaria per usare la sessione. + + + Non è possibile analizzare la stringa sddl perché contiene parentesi non corrispondenti: {0}. + + + La tabella hash della proprietà RequiredGroups deve contenere una sola chiave. + + + La proprietà RequiredGroups non è in un formato di tabella hash con coppia nome-valore. Deve essere una tabella hash nel formato (usando la sintassi di PowerShell): RequiredGroups = @{ Or = 'Administrators' }. + + + Chiave sconosciuta nella configurazione dei Gruppi obbligatori. La tabella hash Gruppi obbligatori può contenere solo chiavi hash ''And'' e ''Or'' per i raggruppamenti di appartenenza logica. + + + Valore sconosciuto nella configurazione dei Gruppi obbligatori. La tabella hash Gruppi obbligatori può contenere solo valori che sono nomi di gruppo o un'altra tabella hash logica. + + + ACE in formato non valido {0}. Gli ACE regolari devono avere esattamente 6 sezioni. + + + Non è possibile creare un'unità utente di sessione perché il nome utente corrente contiene caratteri non validi nel percorso del file. + + + Chiave della funzionalità del ruolo non valida: {0}. Verificare che il nome della funzionalità di ruolo sia digitato correttamente e che sia una proprietà di configurazione di sessione valida. + + + Tipo di chiave della funzionalità del ruolo non valido: {0}. Le chiavi delle funzionalità di ruolo devono essere stringhe che identificano una proprietà di configurazione di sessione valida. + + + Tipo di chiave del ruolo non valido: {0}. Le chiavi ruolo devono essere stringhe che identificano un gruppo di sicurezza. + + + Altre cause possibili: + -Il nome del dominio o del computer non è stato incluso con le credenziali specificate, ad esempio: DOMINIO\NomeUtente o COMPUTER\NomeUtente. + + + Non è possibile avviare il processo client SSH necessario per la connessione remota con l'errore: {0}. + + + Non è possibile trovare il file di chiave specificato {0}. + + + La sessione client SSH è terminata con il messaggio di errore: {0} + + + Tentativo di connessione SSH non riuscito dopo il timeout: {0} secondi. + + + +Il processo client SSH è terminato prima che fosse possibile stabilire la connessione. + + + Nella tabella hash SSHConnection specificata manca il parametro obbligatorio ComputerName o HostName. + + + Il nome o l'elemento del parametro hashtable SSHConnection specificato è Null o vuoto. + + + Il parametro della tabella hash SSHConnection specificato {0} non è supportato. + + + La tabella hash SSHConnection specificata contiene sia un parametro ComputerName sia un parametro HostName. È possibile specificarne solo uno. + + + La tabella hash SSHConnection specificata contiene sia un parametro KeyFilePath sia un parametro IdentityFilePath. È possibile specificarne solo uno. + + + Non è possibile trovare il file delle funzionalità del ruolo specificato {0}. + + + Il file di funzionalità del ruolo specificato {0} non ha l'estensione .psrc richiesta. + + + Il processo di trasporto SSH è stato terminato improvvisamente, causando l'interruzione di questa sessione remota. + + + PowerShell 6+ non supporta WOW64. Il file binario deve corrispondere all'architettura del processore. + + + Il file eseguibile "{0}" non è stato trovato. Verificare che la funzionalità WOW64 sia installata. + + + Non è possibile installare il plug-in {0} nella directory {1}. + + + La DLL del plug-in WinRM {0} per PowerShell è mancante. Eseguire Enable-PSRemoting e riprovare il comando. + + + Questo set di parametri richiede WSMan e non è stata trovata alcuna libreria client WSMan supportata. WSMan non è installato o non è disponibile per questo sistema. + + + + Codice di uscita: {0} + Stdout: ''{1}'' + Stderr: ''{2}'' + + + + Non è possibile leggere le informazioni sul processo: ''{0}''. + + + Il sistema host non dispone della versione corretta dello schema Hyper-V. + + + HTTPS su Unix attualmente non supporta i controlli CA o CN. Usare PSSessionOption -SkipCACheck e -SkipCNCheck se si è certi di potersi fidare del server a cui ci si connette e della rete intermedia. + + + La comunicazione remota di PowerShell è stata disabilitata solo per le configurazioni di PowerShell 6+ e non influisce sulle configurazioni di comunicazione remota di Windows PowerShell. Eseguire questo cmdlet in Windows PowerShell per influire su tutte le configurazioni di comunicazione remota di PowerShell. + + + + La comunicazione remota di PowerShell è stata abilitata solo per le configurazioni di PowerShell 6+ e non influisce sulle configurazioni di comunicazione remota di Windows PowerShell. Eseguire questo cmdlet in Windows PowerShell per influire su tutte le configurazioni di comunicazione remota di PowerShell. + + + Il cmdlet Enter-PSHostProcess è disabilitato perché è in vigore un criterio di controllo delle applicazioni, ad esempio ''AppLocker'' o ''Windows Defender Application Control''. + + + Eccezione del debugger remoto: {0}, messaggio di errore: {1} + + + Non è possibile creare il processo di Windows PowerShell perché Windows PowerShell non è stato trovato in questo dispositivo. + + + L'argomento Runspace passato a Create deve essere un oggetto RemoteRunspace non Null. + + + La tabella hash di configurazione della sessione contiene un tipo di chiave non valido. Le chiavi devono essere di tipo stringa. + + + Il file di configurazione della sessione contiene un'opzione di configurazione non supportata: {0}. Si tratta di un'opzione di configurazione dell'endpoint di comunicazione remota che non si applica allo stato della sessione di PowerShell. + + + Il file di configurazione della sessione contiene un'opzione di configurazione sconosciuta: {0}. + + + La valutazione dell'espressione potrebbe non riuscire + + + La creazione di un oggetto PowerShell da un blocco di script può richiedere la valutazione di alcune espressioni all'interno del blocco di script. La valutazione dell'espressione avrà esito negativo in modo invisibile all'utente e restituirà ''null'' in modalità linguaggio vincolato, a meno che l'espressione non rappresenti un valore costante. + + + Non è possibile ottenere lo stato della VM Hyper-V. Il valore era di tipo {0} ma era previsto Microsoft.HyperV.PowerShell.VMState o System.String. + + + Hyper-V {0} ha inviato una risposta non valida {1} durante la negoziazione della connessione. + + + La negoziazione di una connessione sicura a Hyper-V non è riuscita. Assicurarsi che Host e Guest siano aggiornati con tutti gli Aggiornamenti Microsoft pertinenti. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/RunspaceInit.it.resx b/src/System.Management.Automation/resources/it/RunspaceInit.it.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/it/RunspaceInit.it.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/RunspacePoolStrings.it.resx b/src/System.Management.Automation/resources/it/RunspacePoolStrings.it.resx new file mode 100644 index 00000000000..30f7fe69fe4 --- /dev/null +++ b/src/System.Management.Automation/resources/it/RunspacePoolStrings.it.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + La dimensione massima del pool non può essere inferiore a 1. + + + La dimensione minima del pool non può essere inferiore a 1. + + + La dimensione minima del pool non può essere maggiore della sua dimensione massima. + + + Lo stato del pool di spazi di esecuzione non è valido per questa operazione. + + + Non è possibile eseguire l'operazione perché lo stato del pool di spazi di esecuzione non è "{0}". Lo stato attuale è "{1}". + + + Non è possibile aprire il pool di spazi di esecuzione perché lo stato non è "BeforeOpen". Lo stato attuale è "{0}". + + + L'oggetto {0} non è stato creato chiamando {1} nell'istanza RunspacePool attuale. + + + Non è possibile rilasciare lo spazio di esecuzione nel pool attuale perché non appartiene al pool attuale. + + + Non è possibile modificare la proprietà dopo l'apertura del pool di spazi di esecuzione. + + + Questo spazio di esecuzione non supporta le operazioni di collegamento e scollegamento. + + + Non è possibile eseguire l'operazione perché lo stato del pool di spazi di esecuzione è Scollegato. + + + Il server non supporta l'operazione di scollegamento. Il server deve eseguire PowerShell 3.0 o versioni successive per supportare lo scollegamento del pool di spazi di esecuzione remoti. + + + Questo pool di spazi di esecuzione {0} non è configurato per fornire oggetti PowerShell scollegati per i comandi in esecuzione nel server remoto. Usare il metodo statico GetRunspacePools() della classe RunspacePool per eseguire query sul server e restituire gli oggetti del pool di spazi di esecuzione configurati per questa operazione. + + + Questo pool di spazi di esecuzione non può essere collegato perché il pool di spazi di esecuzione lato server corrispondente è collegato a un altro client. + + + Il server non supporta ResetRunspaceState. Il server deve eseguire PowerShell 5.0 o versioni successive. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/RunspaceStrings.it.resx b/src/System.Management.Automation/resources/it/RunspaceStrings.it.resx new file mode 100644 index 00000000000..03233de5fc6 --- /dev/null +++ b/src/System.Management.Automation/resources/it/RunspaceStrings.it.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Lo stato dello spazio di esecuzione non è valido per questa operazione. + + + Non è possibile aprire lo spazio di esecuzione perché lo stato dello spazio di esecuzione non è BeforeOpen. Lo stato corrente dello spazio di esecuzione è ''{0}''. + + + Non è possibile eseguire l'operazione perché lo spazio di esecuzione non è nello stato Opened. Lo stato corrente dello spazio di esecuzione è ''{0}''. + + + Non è possibile richiamare la pipeline perché lo spazio di esecuzione non è nello stato Opened. Lo stato corrente dello spazio di esecuzione è ''{0}''. + + + Lo stato della pipeline non è valido per questa operazione. + + + Non è possibile richiamare la pipeline perché è già stata richiamata. + + + Il valore valido per il parametro è PipelineResultTypes.Output. + + + La pipeline non contiene un comando. + + + La pipeline non è stata eseguita perché una pipeline è già in esecuzione. Le pipeline non possono essere eseguite contemporaneamente. + + + Una pipeline annidata non può essere richiamata in modo asincrono. Usare il metodo Invoke. + + + È consigliabile eseguire solo una pipeline annidata all'interno di una pipeline in esecuzione. + + + Non è possibile chiudere lo spazio di esecuzione mentre è in corso una chiamata al metodo SessionStateProxy. + + + Non è possibile richiamare la pipeline mentre è in corso una chiamata al metodo SessionStateProxy. + + + È in corso una chiamata al metodo SessionStateProxy. Le chiamate simultanee al metodo SessionStateProxy non sono consentite. + + + Una pipeline è già in esecuzione. Le chiamate simultanee al metodo SessionStateProxy non sono consentite. + + + Impossibile modificare questa proprietà dopo l'apertura dello spazio di esecuzione. + + + Si sono verificati uno o più errori durante l'elaborazione del modulo ''{0}'' specificato nell'oggetto InitialSessionState usato per creare questo spazio di esecuzione. Per un elenco completo degli errori, vedere la proprietà ErrorRecords. Il primo errore è stato: {1} + + + Le opzioni del thread possono essere modificate solo se lo stato dell'apartment è multithreading apartment (MTA), le opzioni correnti sono UseNewThread o UseCurrentThread e il nuovo valore è ReuseThread. + + + {0} non può essere false quando la modalità lingua è {1} o {2}. + + + Non è possibile disconnettere uno spazio di esecuzione solo locale. + + + L'operazione di connessione non è supportata negli spazi di esecuzione locali. + + + La sessione è occupata. Si verrà connessi alla sessione non appena sarà disponibile. Per annullare il comando Enter-PSSession, premere CTRL+C. + + + Impossibile completare il comando. La chiamata di script non è supportata in questa configurazione di sessione. Questo problema può verificarsi se la configurazione della sessione è in modalità senza linguaggio. + + + Non puoi usare le operazioni Disconnect e Connect negli spazi di esecuzione locali. + + + Non è possibile connettere la pipeline perché lo spazio di esecuzione non è nello stato Opened. Lo stato corrente dello spazio di esecuzione è ''{0}''. + + + Non è possibile costruire un oggetto RemoteRunspace. L'oggetto RunspacePool specificato non è valido. + + + Nessun comando disconnesso associato a questo spazio di esecuzione. + + + L'operazione di disconnessione non è supportata nel computer remoto. Per supportare la disconnessione, il computer remoto deve eseguire Windows PowerShell 3.0 o una versione successiva di Windows PowerShell e usare il trasporto WSMan. + + + Non è possibile connettere psSession perché la sessione non si trova nello stato Disconnesso o non è disponibile per la connessione. + + + Il valore per il parametro non può essere PipelineResultTypes.None o PipelineResultTypes.Output. + + + I valori validi per il parametro sono PipelineResultTypes.Output o PipelineResultTypes.Null. + + + Il reindirizzamento del flusso di debug non è supportato nel computer remoto di destinazione. + + + Il dettagliato del flusso di debug non è supportato nel computer remoto di destinazione. + + + Il reindirizzamento del flusso di avviso non è supportato nel computer remoto di destinazione. + + + Il reindirizzamento del flusso di informazioni non è supportato nel computer remoto di destinazione. + + + È stata immessa una sessione occupata durante l'esecuzione di un comando o uno script. Poiché l'output viene instradato al processo "{0}", l'output non verrà visualizzato nella console. È possibile attendere il completamento del comando in esecuzione oppure annullare il comando e ottenere un prompt di input premendo CTRL+C. + + + + È stata immessa una sessione occupata durante l'esecuzione di un comando o di uno script e l'output verrà visualizzato nella console. È possibile attendere il completamento o l'annullamento del comando in esecuzione e ottenere un prompt di input premendo CTRL+C. + + + + È stata immessa una sessione attualmente arrestata in corrispondenza di un punto di interruzione di debug all'interno di un comando o uno script in esecuzione. Usare il debugger della riga di comando di PowerShell per continuare il debug. + + + + DefaultRunspace deve essere un LocalRunspace + + + La proprietà statica PrimaryRunspace può essere impostata una sola volta ed è già stata impostata. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/SecuritySupportStrings.it.resx b/src/System.Management.Automation/resources/it/SecuritySupportStrings.it.resx new file mode 100644 index 00000000000..b0b21af312c --- /dev/null +++ b/src/System.Management.Automation/resources/it/SecuritySupportStrings.it.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile caricare il certificato. '{0}' deve risolversi in un percorso del file system. + + + Non è possibile utilizzare il certificato '{0}' per la crittografia. I certificati di Crittografia devono contenere l'utilizzo della chiave Crittografia dati o Crittografia chiave e includere l'Utilizzo chiavi avanzato della crittografia del documento ({1}). + + + Non è possibile caricare il certificato. L'identificatore '{0}' corrisponde a più certificati. Per crittografare per più destinatari, specificare più valori distinti per il parametro '{1}', anziché un carattere jolly che corrisponde a più certificati. + + + Non è possibile caricare il certificato di crittografia. L'impostazione del certificato '{0}' non rappresenta un certificato valido con codifica Base64, né un certificato valido tramite file, directory, identificazione personale o nome soggetto. + + + AVVISO: il certificato '{0}' contiene una chiave privata. I certificati di registrazione eventi protetti usati per la crittografia devono contenere solo la chiave pubblica. + + + ERRORE: non è possibile proteggere il messaggio del registro eventi '{0}': {1} + + + ERRORE: non è possibile trovare o usare il certificato: {0} + + + La chiave di sessione non è disponibile per crittografare la stringa sicura. + + + Offset del buffer non valido. + + + Dati della chiave pubblica non validi. + + + Non è possibile importare la chiave pubblica. + + + Dati della chiave di sessione non validi. + + + Il file di script '{0}' è bloccato dall'esecuzione dai criteri di sistema. + + + È stato restituito un valore sconosciuto per l'applicazione dei criteri del file di script: {0}. + + + Lettura file di script + + + Il file di script '{0}' non è considerato attendibile dai criteri e verrà eseguito in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/Serialization.it.resx b/src/System.Management.Automation/resources/it/Serialization.it.resx new file mode 100644 index 00000000000..0956f48c8c1 --- /dev/null +++ b/src/System.Management.Automation/resources/it/Serialization.it.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} attributo previsto. + + + Il tag XML {0} non è stato riconosciuto. + + + Nessun oggetto trovato per referenceId {0} + + + L'attributo Name per la chiave del dizionario è specificato in modo errato. + + + L'attributo Name per il valore del dizionario è specificato in modo errato. + + + La versione di PSObject non è valida. + + + La versione di PSObject in ingresso è {0}. Il valore previsto è 1. + + + Non è possibile elaborare i nomi perché non sono stati trovati TypeName per referenceId {0}. + + + Il valore del parametro di profondità deve essere maggiore o uguale a 1. + + + Il tipo di nodo corrente è {0}. Il tipo previsto è {1}. + + + La chiave per la voce del dizionario non è specificata. + + + Il valore per la voce del dizionario non è specificato. + + + Non ci sono più oggetti da deserializzare. + + + Null è specificato come chiave del dizionario. + + + Il contenuto del tipo primitivo {0} non è valido. + + + L'XML serializzato è nidificato in modo eccessivo. + + + Il serializzatore è stato chiuso. + + + I dati nel comando superano le dimensioni massime consentite dalla configurazione della sessione. Il valore massimo consentito è {0} MB. Modificare l'input, usare una configurazione di sessione diversa, oppure modificare le proprietà "{1}" e "{2}" della configurazione di sessione nel computer remoto. + + + La deserializzazione della stringa sicura crittografata non è riuscita + + + Il tipo di chiave {0} non è valido. La classe PSPrimitiveDictionary accetta solo chiavi di tipo System.String. + + + Il tipo del valore {0} non è valido. La classe PSPrimitiveDictionary accetta solo valori di tipi completamente serializzabili tramite la comunicazione remota PowerShell. Per un elenco dei tipi completamente serializzabili, vedere l'argomento about_Remoting della Guida. + + + Non è stato possibile decrittografare i dati. I dati non sono stati crittografati con questa chiave. + + + Il valore del parametro "{0}" non è una stringa crittografata valida. + + + Il parametro {0} specificato non è valido. Le impostazioni valide per la lunghezza {0} sono 128 bit, 192 bit o 256 bit. + + + La deserializzazione di SecureString è attualmente supportata solo in Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/SessionStateProviderBaseStrings.it.resx b/src/System.Management.Automation/resources/it/SessionStateProviderBaseStrings.it.resx new file mode 100644 index 00000000000..b8359c25a1d --- /dev/null +++ b/src/System.Management.Automation/resources/it/SessionStateProviderBaseStrings.it.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Imposta elemento + + + Elemento: {0} Valore: {1} + + + Cancella elemento + + + Elemento: {0} + + + Rimuovi elemento + + + Elemento: {0} + + + Nuovo elemento + + + Elemento: {0} Tipo: {1} Valore: {2} + + + Copia elemento + + + Elemento: {0} Destinazione: {1} + + + Rinomina elemento + + + Elemento: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/SessionStateStrings.it.resx b/src/System.Management.Automation/resources/it/SessionStateStrings.it.resx new file mode 100644 index 00000000000..e5416edef56 --- /dev/null +++ b/src/System.Management.Automation/resources/it/SessionStateStrings.it.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile elaborare le informazioni restituite perché quelle restituite dal metodo Start del provider erano per un provider diverso da quello passato. + + + Non è possibile elaborare le informazioni restituite perché le informazioni restituite dal metodo Start del provider erano null. + + + Tentativo di eseguire l'operazione GetItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione GetItem dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione SetItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione SetItem dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione ClearItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione InvokeDefaultAction sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione InvokeDefaultAction dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione ItemExists sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione ItemExists dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione IsValidPath sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione IsItemContainer sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione RemoveItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione GetChildItems sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione GetChildItems dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione GetChildNames sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione GetChildNames dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione RenameItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione RenameItem dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione NewItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione NewItem dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione HasChildItems sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione CopyItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione CopyItem dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione GetParentPath sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione NormalizeRelativePath sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione MakePath sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione GetChildName sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione MoveItem sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione MoveItem dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione GetProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione GetProperty dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione SetProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione SetProperty dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione ClearProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione ClearProperty dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione NewProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione NewProperty dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione RemoveProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione RemoveProperty dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione CopyProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione CopyProperty per il provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione MoveProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione MoveProperty per il provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione RenameProperty sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per RenameProperty dal provider '{0}' per il percorso '{1}'. {2} + + + Non è possibile recuperare il lettore di contenuto per il provider '{0}' per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione GetContentReader per il provider '{0}' per il percorso '{1}'. {2} + + + Non è possibile recuperare il writer di contenuto per il provider '{0}' per il percorso '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per l'operazione GetContentWriter per il provider '{0}' per il percorso '{1}'. {2} + + + Non è possibile ottenere il contenuto perché si tratta di una directory: '{0}'. Usare invece 'Get-ChildItem'. + + + Non è possibile scrivere il contenuto perché si tratta di una directory: '{0}'. + + + Non è rimasta alcuna cronologia delle posizioni per spostarsi all'indietro. + + + Non è rimasta alcuna cronologia delle posizioni per spostarsi in avanti. + + + BoundedStack è vuoto. + + + Tentativo di eseguire l'operazione ClearContent sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Non è possibile cancellare il contenuto di '{0}' perché si tratta di una directory. Clear-Content è supportato solo sui file. + + + Non è possibile recuperare i parametri dinamici per l'operazione ClearContent dal provider '{0}' per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione GetSecurityDescriptor sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Tentativo di eseguire l'operazione SetSecurityDescriptor sul provider '{0}' non riuscito per il percorso '{1}'. {2} + + + Il tentativo di eseguire l'operazione Start sul provider '{0}' non è riuscito. {1} + + + Tentativo di eseguire l'operazione InitializeDefaultDrives sul provider '{0}' non riuscito. + + + Tentativo di eseguire l'operazione NewDrive sul provider '{0}' non riuscito per l'unità con radice '{1}'. {2} + + + Non è possibile recuperare i parametri dinamici per NewDrive dal provider '{0}'. {1} + + + La chiamata di RemoveDrive sul provider '{0}' non è riuscita. {1} + + + Non è possibile rimuovere l'unità '{0}' perché il provider '{1}' lo ha impedito. + + + Il percorso '{0}' faceva riferimento a un elemento esterno alla base '{1}'. + + + La chiamata di Seek sul writer di contenuto del provider '{0}' non è riuscita per il percorso '{1}'. {2} + + + La chiamata di Close sul lettore o writer di contenuto del provider '{0}' non è riuscita per il percorso '{1}'. {2} + + + La chiamata di Read sul lettore di contenuto del provider '{0}' non è riuscita per il percorso '{1}'. {2} + + + La chiamata di Write sul writer di contenuto del provider '{0}' non è riuscita per il percorso '{1}'. {2} + + + Il provider '{0}' non può essere usato per ottenere o impostare dati usando la sintassi della variabile. {2} + + + La sintassi della variabile non può essere usata per ottenere o impostare dati nel provider. {2} + + + Non è possibile scrivere sull'alias perché l'alias {0} è di sola lettura o costante e non è possibile eseguire operazioni di scrittura su di esso. + + + Non è possibile scrivere nella funzione {0} perché è di sola lettura o costante. + + + Non è possibile sovrascrivere la variabile {0} perché è di sola lettura o costante. + + + Non è possibile accedere alla variabile '${0}' perché è una variabile privata. + + + Non è possibile accedere al comando '{0}' perché è privato. + + + Non è possibile accedere al comando perché è privato. + + + Non è possibile accedere alla risorsa dello stato della sessione perché è una risorsa privata. + + + L'alias non è stato rimosso perché l'alias {0} è costante o di sola lettura. + + + Non è possibile rimuovere la funzione {0} perché è costante. + + + Non è possibile rimuovere la variabile {0} perché è costante o di sola lettura. Se la variabile è di sola lettura, riprovare specificando l'opzione Forza. + + + Non è possibile modificare l'alias {0} perché è costante. + + + Non è possibile modificare l'alias {0} perché è di sola lettura. + + + Non è possibile modificare la funzione {0} perché è costante. + + + Non è possibile modificare la funzione {0} perché è di sola lettura. + + + L'alias {0} non può essere reso costante dopo la creazione. Gli alias possono essere resi costanti solo al momento della creazione. + + + Non è possibile rendere costante la funzione esistente {0}. Le funzioni possono essere rese costanti solo al momento della creazione. + + + Non è possibile rendere costante la variabile {0} esistente. Le variabili possono essere rese costanti solo al momento della creazione. + + + L'opzione AllScope non può essere rimossa dall'alias '{0}'. + + + L'opzione AllScope non può essere rimossa dalla funzione '{0}'. + + + L'opzione AllScope non può essere rimossa dalla variabile '{0}'. + + + La definizione della funzione '{0}' conteneva un qualificatore di ambito, ma non un nome di funzione. + + + Non è possibile rimuovere il provider {0}. Prima di rimuovere il provider {0}, è necessario rimuovere tutte le unità associate al provider {0}. + + + Non è possibile elaborare il nome dell'unità perché contiene uno o più dei seguenti caratteri non validi: ; ~ / \ . : + + + La creazione della nuova unità è riuscita. Il provider non consente la creazione della nuova unità. + + + Il valore specificato '{0}' è stato risolto in più di uno stack di posizioni. + + + Non è possibile trovare lo stack di posizioni '{0}'. Non esiste, oppure non è un contenitore. + + + Non è possibile trovare il percorso '{0}' perché non esiste. + + + Non è possibile trovare l'alias perché l'alias '{0}' non esiste. + + + Non è possibile impostare la posizione perché il percorso '{0}' è stato risolto in più contenitori. È possibile impostare la posizione solo su un contenitore alla volta. + + + Non è possibile elaborare la variabile perché il percorso della variabile '{0}' è stato risolto in più elementi. È possibile ottenere o impostare il valore della variabile solo un elemento alla volta. + + + Non è possibile trovare l'unità. L'unità con il nome "{0}" non esiste. + + + Non è possibile trovare un provider con il nome '{0}'. + + + Non è possibile trovare un provider con il nome '{0}'. Il nome non è nel formato corretto. Un nome di provider può contenere solo caratteri alfanumerici, oppure un nome di snap-in di PowerShell seguito da un singolo '\', seguito da caratteri alfanumerici. + + + '{0}' è stato risolto in più di un nome di provider. Le possibili corrispondenze includono:{1}. + + + Si è verificato un errore durante il tentativo di creare un'istanza del provider. Non è possibile trovare il nome del tipo di provider '{0}' nell'assembly. + + + Il nome del provider specificato '{0}' non può essere usato perché contiene uno o più dei seguenti caratteri non validi: \ [ ] ? * : + + + Si è verificato un errore durante il tentativo di creare un'istanza del provider '{0}'. {1} + + + Non è possibile trovare una variabile con il nome '{0}'. + + + Non è possibile trovare un'origine di traccia con il nome '{0}'. + + + Esiste già un'unità denominata '{0}'. + + + Esiste già una variabile con il nome '{0}'. + + + L'alias non è consentito perché esiste già un alias con il nome '{0}'. + + + Non è possibile registrare il provider cmdlet perché esiste già un provider cmdlet con il nome '{0}'. + + + Il percorso non fa riferimento a un percorso del file system. + + + Non è possibile rimuovere l'ambito globale. + + + Il numero di ambito '{0}' supera il numero di ambiti attivi. + + + Non è possibile confrontare PSDriveInfo. Un'istanza di PSDriveInfo può essere confrontata solo con un'altra istanza di PSDriveInfo. + + + Il provider cmdlet non può trasmettere i risultati perché non è stato specificato alcun cmdlet tramite cui trasmettere l'output. + + + Il provider cmdlet non può trasmettere i risultati perché non è stato specificato alcun cmdlet tramite cui trasmettere l'errore. + + + La posizione Home per questo provider non è impostata. Per impostare la posizione Home, chiamare "(get-psprovider '{0}').Home = 'path'". + + + Il percorso non è nel formato corretto. I percorsi del provider devono contenere un ID provider, seguito da "::", seguito da un percorso specifico del provider. + + + Non è possibile spostare l'elemento perché il percorso di destinazione può essere risolto solo in un singolo percorso. + + + Non è possibile spostare l'elemento perché i percorsi di origine e di destinazione non sono stati risolti nello stesso provider. + + + Non è possibile spostare l'elemento perché il percorso di origine punta a uno o più elementi e il percorso di destinazione non è un contenitore. Verificare che il percorso di destinazione sia un contenitore e riprovare. + + + Non è possibile spostare l'elemento perché la destinazione è stata risolta in più percorsi. Specificare un percorso di destinazione che porti a una sola destinazione e riprovare. + + + Non è possibile copiare il contenitore sopra un elemento foglia esistente. + + + Non è possibile copiare il contenitore in un altro contenitore. Il parametro -Recurse o -Container non è specificato. + + + Il percorso di origine e quello di destinazione non sono stati risolti nello stesso provider. + + + Non è possibile rinominare l'elemento perché il percorso è stato risolto in più elementi. È possibile rinominare un solo elemento alla volta. + + + Il provider '{0}' non può essere usato per risolvere il percorso '{1}' a causa di un errore nel provider. + + + Non è possibile usare l'interfaccia. L'interfaccia IContentCmdletProvider non è implementata da questo provider. + + + Non è possibile usare l'interfaccia. L'interfaccia IPropertyCmdletProvider non è supportata da questo provider. + + + Non è possibile usare l'interfaccia. L'interfaccia IDynamicPropertyCmdletProvider non è implementata da questo provider. + + + I metodi NavigationCmdletProvider non sono supportati da questo provider. + + + Metodi del provider non elaborati. I metodi ContainerCmdletProvider non sono supportati da questo provider. + + + Non è possibile chiamare metodi. I metodi ItemCmdletProvider non sono supportati da questo provider. + + + I metodi DriveCmdletProvider non sono supportati da questo provider. + + + Operazione del provider interrotta perché il provider non supporta questa operazione. + + + Operazione del provider interrotta perché il provider non supporta il parametro 'Depth'. + + + Non è possibile chiamare il metodo. Il metodo Seek per il contenuto non è supportato da questo provider. + + + Non è possibile eseguire l'operazione ClearContent. Questa operazione non è supportata da questo provider. + + + Il provider non supporta l'uso di credenziali. Eseguire di nuovo l'operazione senza specificare le credenziali. + + + Il provider FileSystem supporta le credenziali solo nel cmdlet New-PSDrive. Eseguire di nuovo l'operazione senza specificare le credenziali. + + + Transazioni non supportate dal provider. Eseguire di nuovo l'operazione senza il parametro -UseTransaction. + + + Non è possibile chiamare il metodo. Il provider non supporta l'uso di filtri. + + + Non è possibile creare unità. Il provider non supporta l'uso di credenziali. + + + L'elemento nel percorso '{0}' esiste già. + + + Non è possibile copiare l'elemento. L'elemento presso il percorso '{0}' non esiste. + + + L'elemento nel percorso '{0}' non esiste. + + + Unità che contiene una visualizzazione degli alias archiviati nello stato della sessione + + + Unità che contiene una visualizzazione delle variabili di ambiente per il processo + + + Unità che contiene una visualizzazione delle funzioni archiviate nello stato della sessione + + + Unità che contiene una visualizzazione delle variabili archiviate nello stato della sessione + + + Unità che mappa al percorso della directory temporanea per l'utente corrente + + + Il collegamento '{0}' non può essere creato perché il valore di destinazione non è stato specificato. + + + I riferimenti alla variabile null restituiscono sempre il valore null. Le assegnazioni non hanno effetto. + + + Numero massimo di oggetti cronologia da mantenere in una sessione + + + Non è possibile rinominare la funzione perché la funzione {0} è di sola lettura o costante. + + + Non è possibile rinominare l'alias perché l'alias {0} è di sola lettura o costante. + + + Non è possibile rinominare la variabile perché la variabile {0} è di sola lettura o costante. + + + Non è possibile impostare opzioni sulla variabile locale {0}. Usare New-Variable per creare una variabile che consenta di impostare opzioni. + + + Non è possibile modificare il cmdlet {0} perché è di sola lettura. + + + Non è possibile rimuovere la variabile {0} perché è stata ottimizzata e non può essere rimossa. Provare a usare il cmdlet Remove-Variable (senza alias), oppure eseguire il dot-sourcing del comando usato per rimuovere la variabile. + + + Non è possibile sovrascrivere la variabile {0} perché è stata ottimizzata. Provare a usare il cmdlet New-Variable o Set-Variable (senza alias), oppure eseguire il dot-sourcing del comando usato per impostare la variabile. + + + I parametri {0} e {1} non possono essere usati insieme. Specificare un solo parametro. + + + Il parametro Tail è attualmente supportato solo per il provider FileSystem. + + + L'alias non è consentito perché esiste già un comando con il nome '{0}' e il tipo di comando '{1}'. + + + Non è possibile eseguire il software. Accesso negato. + + + '-{0}' e '-{1}' si escludono a vicenda e non possono essere specificati contemporaneamente. + + + Il percorso '{0}' non è valido. Nelle operazioni di copia remota sono supportati solo i percorsi assoluti. + + + Non è possibile convalidare il percorso remoto '{0}'. + + + Non è possibile eseguire l'operazione perché la sessione {0} è impostata su {1}. + + + Il parametro '{0}' non può essere null o vuoto. + + + Variabili di stato della sessione + + + La modifica o la creazione dell'ambito della variabile '{0}' in AllScope non sarà consentita in modalità ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/StringDecoratedStrings.it.resx b/src/System.Management.Automation/resources/it/StringDecoratedStrings.it.resx new file mode 100644 index 00000000000..91cde1e24df --- /dev/null +++ b/src/System.Management.Automation/resources/it/StringDecoratedStrings.it.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Questo metodo supporta solo "ANSI" o "PlainText". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/SubsystemStrings.it.resx b/src/System.Management.Automation/resources/it/SubsystemStrings.it.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/it/SubsystemStrings.it.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/SuggestionStrings.it.resx b/src/System.Management.Automation/resources/it/SuggestionStrings.it.resx new file mode 100644 index 00000000000..9f898815d77 --- /dev/null +++ b/src/System.Management.Automation/resources/it/SuggestionStrings.it.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 + + + Il comando "{0}" non è stato trovato, ma esiste nella posizione attuale. +Per impostazione predefinita, PowerShell non carica i comandi dalla posizione attuale (vedere "Get-Help about_Command_Precedence"). + +Se questo comando è considerato attendibile, eseguire il comando seguente: + + + I comandi più simili sono: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/TabCompletionStrings.it.resx b/src/System.Management.Automation/resources/it/TabCompletionStrings.it.resx new file mode 100644 index 00000000000..39094b569c3 --- /dev/null +++ b/src/System.Management.Automation/resources/it/TabCompletionStrings.it.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 è possibile deserializzare correttamente il risultato del completamento tramite TAB perché lo spazio di esecuzione remoto non contiene un'istanza di TypeTable. + + + Non è possibile accedere alle proprietà in un'istanza Null di tipo CompletionResult. + + + NOT bit per bit + + + NOT logico. Nega l'istruzione che lo segue. + + + Uguale a, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è uguale all'operando destro. + + + Uguale a, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è uguale all'operando destro. + + + Uguale a, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è uguale all'operando destro. + + + Diverso da, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non sono uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non è uguale all'operando destro. + + + Diverso da, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non sono uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non è uguale all'operando destro. + + + Diverso da, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non sono uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non è uguale all'operando destro. + + + Maggiore o uguale a, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta maggiori o uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è maggiore o uguale all'operando destro. + + + Maggiore o uguale a, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta maggiori o uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è maggiore o uguale all'operando destro. + + + Maggiore o uguale a, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta maggiori o uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è maggiore o uguale all'operando destro. + + + Maggiore di, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta maggiori dell'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è maggiore dell'operando destro. + + + Maggiore di, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta maggiori dell'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è maggiore dell'operando destro. + + + Maggiore di, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta maggiori dell'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è maggiore dell'operando destro. + + + Minore di, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta minori dell'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è minore dell'operando destro. + + + Minore di, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta minori dell'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è minore dell'operando destro. + + + Minore di, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta minori dell'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è minore dell'operando destro. + + + Minore o uguale a, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta minori o uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è minore o uguale all'operando destro. + + + Minore o uguale a, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta minori o uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è minore o uguale all'operando destro. + + + Minore o uguale a, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta minori o uguali all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro è minore o uguale all'operando destro. + + + Operatore di corrispondenza con caratteri jolly, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro corrisponde all'operando destro. + + + Operatore di corrispondenza con caratteri jolly, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro corrisponde all'operando destro. + + + Operatore di corrispondenza con caratteri jolly, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro corrisponde all'operando destro. + + + Operatore di corrispondenza con caratteri jolly, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non corrisponde all'operando destro. + + + Operatore di corrispondenza con caratteri jolly, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non corrisponde all'operando destro. + + + Operatore di corrispondenza con caratteri jolly, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non corrisponde all'operando destro. + + + Operatore di corrispondenza tramite espressioni regolari, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro corrisponde all'operando destro. + + + Operatore di corrispondenza tramite espressioni regolari, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro corrisponde all'operando destro. + + + Operatore di corrispondenza tramite espressioni regolari, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro corrisponde all'operando destro. + + + Operatore di corrispondenza tramite espressioni regolari, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non corrisponde all'operando destro. + + + Operatore di corrispondenza tramite espressioni regolari, senza distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non corrisponde all'operando destro. + + + Operatore di corrispondenza tramite espressioni regolari, con distinzione maiuscole/minuscole. Quando l'operando sinistro è una raccolta, restituisce i valori della raccolta che non corrispondono all'operando destro; in caso contrario, restituisce TRUE se l'operando sinistro non corrisponde all'operando destro. + + + Operatore di sostituzione, senza distinzione maiuscole/minuscole. Modifica l'operando sinistro. Esempio: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operatore di sostituzione, senza distinzione maiuscole/minuscole. Modifica l'operando sinistro. Esempio: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operatore di sostituzione, con distinzione maiuscole/minuscole. Modifica l'operando sinistro. Esempio: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando destro) corrisponde esattamente ad almeno uno dei valori nell'operando sinistro. + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando destro) corrisponde esattamente ad almeno uno dei valori nell'operando sinistro. + + + Operatore di contenimento, con distinzione maiuscole/minuscole. Restituisce TRUE solo quando il valore di test (operando destro) corrisponde esattamente ad almeno uno dei valori nell'operando sinistro. + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando destro) non corrisponde esattamente ad alcuno dei valori nell'operando sinistro. + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando destro) non corrisponde esattamente ad alcuno dei valori nell'operando sinistro. + + + Operatore di contenimento, con distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando destro) non corrisponde esattamente ad alcuno dei valori nell'operando sinistro. + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando sinistro) corrisponde esattamente ad almeno uno dei valori nell'operando destro. + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando sinistro) corrisponde esattamente ad almeno uno dei valori nell'operando destro. + + + Operatore di contenimento, con distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando sinistro) corrisponde esattamente ad almeno uno dei valori nell'operando destro. + + + Operatore di contenimento, con distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando sinistro) non corrisponde esattamente ad alcuno dei valori nell'operando destro. + + + Operatore di contenimento, senza distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando sinistro) non corrisponde esattamente ad alcuno dei valori nell'operando destro. + + + Operatore di contenimento, con distinzione maiuscole/minuscole. Restituisce TRUE quando il valore di test (operando sinistro) non corrisponde esattamente ad alcuno dei valori nell'operando destro. + + + Divisione, senza distinzione maiuscole/minuscole. Divide una o più stringhe in sottostringhe. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Divisione, senza distinzione maiuscole/minuscole. Divide una o più stringhe in sottostringhe. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Divisione, con distinzione maiuscole/minuscole. Divide una o più stringhe in sottostringhe. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Restituisce TRUE quando l'operando sinistro non è un'istanza del tipo .NET Framework specificato (operando destro). + + + Restituisce TRUE quando l'operando sinistro è un'istanza del tipo .NET Framework specificato (operando destro). + + + Converte l'operando sinistro nel tipo .NET Framework specificato (operando destro). + + + Formatta le stringhe usando il metodo di formato degli oggetti stringa. + + + AND logico. Restituisce TRUE quando entrambe le istruzioni sono TRUE. + + + AND bit per bit + + + OR logico. TRUE quando una o entrambe le istruzioni sono TRUE. + + + OR bit per bit (inclusivo) + + + XOR logico. Restituisce TRUE quando una delle istruzioni è TRUE e l'altra è FALSE. + + + OR bit per bit (esclusivo) + + + Join - combina più stringhe in un'unica stringa. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Operatore di spostamento bit a sinistra. Inserisce uno zero nella posizione del bit più a destra. + + + Operatore di spostamento bit a destra. Inserisce uno zero nella posizione del bit più a sinistra. Per i valori con segno, il bit di segno viene preservato. + + + [string] +Specifica il nome della proprietà da creare. + + + [string] +Specifica il nome della proprietà da creare. + + + [scriptblock] +Blocco di script usato per calcolare il valore della nuova proprietà. + + + [string] +Definisce la modalità di visualizzazione dei valori in una colonna. +I valori validi sono 'left', 'center' o 'right'. + + + [string] +Specifica una stringa di formato che definisce la formattazione del valore nell'output. + + + [int] +Specifica la larghezza massima delle colonne in una tabella quando viene visualizzato il valore. +Il valore deve essere maggiore di 0. + + + [int] +La chiave di profondità specifica la profondità di espansione per proprietà. + + + [bool] +Specifica l'ordine di ordinamento per una o più proprietà. + + + [bool] +Specifica l'ordine di ordinamento per una o più proprietà. + + + [String[]] +Specifica i nomi dei log da cui ottenere gli eventi. +Supporta caratteri jolly. + + + [String[]] +Specifica i provider del registro eventi da cui ottenere gli eventi. +Supporta caratteri jolly. + + + [String[]] +Specifica i percorsi dei file di log da cui ottenere gli eventi. +I formati di file validi sono: .etl, .evt ed .evtx + + + [Long[]] +Seleziona gli eventi con le maschere di bit delle parole chiave specificate. +Di seguito sono riportate le parole chiave standard: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Seleziona gli eventi con gli ID evento specificati. + + + [int[]] +Seleziona gli eventi con i livelli di log specificati. +I livelli di log seguenti sono validi: +1: Critico +2: Errore +3: Avviso +4: Informativo +5: Dettagliato + + + [datetime] +Seleziona gli eventi creati dopo la data e l'ora specificate. + + + [datetime] +Seleziona gli eventi creati prima della data e dell'ora specificate. + + + [string] +Seleziona gli eventi generati dall'utente specificato. +Può trattarsi di una rappresentazione in formato stringa di un SID o di un dominio e nome utente nel formato DOMINIO\NOMEUTENTE o NOMEUTENTE@DOMINIO + + + [string[]] +Seleziona gli eventi con uno dei valori specificati nella sezione EventData. + + + [hashtable] +Esclude gli eventi che corrispondono ai valori specificati nella tabella hash. + + + [string] o [hashtable] +Specifica una matrice di moduli di PowerShell richiesti dallo script. +Ogni elemento può essere una stringa con il nome del modulo come valore o una tabella hash con le chiavi seguenti: +Name: nome del modulo +GUID: GUID del modulo +Uno dei seguenti: +ModuleVersion: specifica una versione minima accettabile del modulo. +RequiredVersion: specifica una versione esatta e obbligatoria del modulo. +MaximumVersion: specifica la versione massima accettabile del modulo. + + + [string] +Specifica un'edizione di PowerShell richiesta dallo script. +I valori validi sono "Core" e "Desktop" + + + [switch] +Specifica che PowerShell deve essere in esecuzione come amministratore in Windows. +Deve essere l'ultimo parametro nella riga dell'istruzione #requires. + + + [version] +Specifica la versione minima di PowerShell richiesta dallo script. + + + Specifica che lo script richiede PowerShell 7 o versione successiva per l'esecuzione. + + + Specifica che lo script richiede Windows PowerShell 5.1 per l'esecuzione. + + + [string] +Obbligatorio. Specifica il nome del modulo. + + + [string] +Facoltativo. Specifica il GUID del modulo. + + + [string] +Specifica una versione minima accettabile del modulo. + + + [string] +Specifica una versione esatta e obbligatoria del modulo. + + + [string] +Specifica la versione massima accettabile del modulo. + + + Breve descrizione della funzione o dello script. +Questa parola chiave può essere usata una sola volta in ogni argomento. + + + Descrizione dettagliata della funzione o dello script. +Questa parola chiave può essere usata una sola volta in ogni argomento. + + + .PARAMETER <Parameter-Name> +Descrizione di un parametro. +Aggiungere una parola chiave .PARAMETER per ogni parametro nella sintassi della funzione o dello script. + + + Comando di esempio che usa la funzione o lo script, seguito facoltativamente da un output di esempio e da una descrizione. +Ripetere questa parola chiave per ogni esempio. + + + Tipi .NET di oggetti che possono essere inviati tramite pipe alla funzione o allo script. +È anche possibile includere una descrizione degli oggetti di input. + + + Tipo .NET degli oggetti restituiti dal cmdlet. +È anche possibile includere una descrizione degli oggetti restituiti. + + + Informazioni aggiuntive sulla funzione o sullo script. + + + Nome di un argomento correlato. +Ripetere la parola chiave .LINK per ogni argomento correlato. +Il contenuto della parola chiave .Link può includere anche un URI alla versione online dello stesso argomento della Guida. + + + Nome della tecnologia o della funzionalità usata dalla funzione o dallo script, oppure a cui la funzione o lo script sono correlati. + + + Nome del ruolo utente per l'argomento della Guida. + + + Parole chiave che descrivono l'uso previsto della funzione. + + + .FORWARDHELPTARGETNAME <Command-Name> +Reindirizza all'argomento della Guida per il comando specificato. + + + .FORWARDHELPCATEGORY <Category> +Specifica la categoria della Guida dell'elemento in .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Specifica una sessione che contiene l'argomento della Guida. +Immettere una variabile che contiene un oggetto PSSession. + + + .EXTERNALHELP <XML Help File> +La parola chiave .ExternalHelp è obbligatoria quando una funzione o uno script è documentato in file XML. + + + Specifica il percorso di un assembly .NET da caricare. + +using assembly <.NET-assembly-path> + + + Specifica un modulo di PowerShell da cui caricare le classi. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifica uno spazio dei nomi .NET da cui risolvere i tipi o un alias dello spazio dei nomi. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifica un alias per un tipo .NET. + +using type <AliasName> = <.NET-type> + + + Stringa normale. + + + Stringa contenente riferimenti non espansi a variabili di ambiente che vengono espanse quando viene recuperato il valore. + + + Dati binari in qualsiasi forma. + + + Numero binario a 32 bit. + + + Matrice di stringhe. + + + Numero binario a 64 bit. + + + Tipo di dati del Registro di sistema non supportato. + + + ',' - Virgola + + + ', ' - Virgola spazio + + + ';' - Punto e virgola + + + '; ' - Punto e virgola-spazio + + + {0} - Nuova riga + + + '-' - Trattino + + + ' ' - Spazio + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/TransactionStrings.it.resx b/src/System.Management.Automation/resources/it/TransactionStrings.it.resx new file mode 100644 index 00000000000..8c812d8aa9e --- /dev/null +++ b/src/System.Management.Automation/resources/it/TransactionStrings.it.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Non è possibile utilizzare la transazione. Nessuna transazione è attiva. + + + Non è possibile eseguire il commit della transazione. Nessuna transazione è attiva. + + + Non è possibile ripristinare la transazione allo stato precedente perché non è attiva alcuna transazione. + + + Non è possibile ripristinare la transazione allo stato precedente. È già stato eseguito il commit della transazione. + + + Non è possibile eseguire il commit della transazione. È già stato eseguito il commit della transazione. + + + Non è possibile eseguire il commit della transazione. La transazione è stata ripristinata allo stato precedente o è scaduta. + + + Non è possibile ripristinare la transazione allo stato precedente. La transazione è già stata ripristinata allo stato precedente o è scaduta. + + + Non è possibile impostare la transazione attiva. Nessuna transazione è stata creata. + + + Non è possibile impostare la transazione attiva. La transazione attiva è stata ripristinata allo stato precedente o è scaduta. + + + Per questo cmdlet è necessaria una transazione attiva. La transazione corrente è già stata confermata o ripristinata allo stato precedente. + + + Questo cmdlet richiede una transazione. Eseguire di nuovo il comando con il parametro -UseTransaction. + + + Non è possibile utilizzare la transazione. Nessuna transazione è stata avviata. + + + Non è possibile utilizzare la transazione. È stato eseguito il commit della transazione. + + + Non è possibile utilizzare la transazione. La transazione è stata ripristinata allo stato precedente o è scaduta. + + + Non è possibile utilizzare la transazione. La transazione è scaduta. + + + La transazione di base non è stata impostata. + + + La transazione di base non è attiva. + + + Non è possibile impostare la transazione di base dopo la creazione di altre transazioni. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/TypesXmlStrings.it.resx b/src/System.Management.Automation/resources/it/TypesXmlStrings.it.resx new file mode 100644 index 00000000000..3f34bb972ae --- /dev/null +++ b/src/System.Management.Automation/resources/it/TypesXmlStrings.it.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : Errore: {3} + + + {0}, {1}({2}): errore nel tipo "{3}": {4} + + + Il nodo "{0}" deve comparire una sola volta sotto "{1}". Il nodo padre, "{1}", verrà ignorato. + + + Il nodo {0} non è consentito. I seguenti nodi sono consentiti: {1}. + + + Il nodo "{0}" non deve avere un testo interno. + + + Il nodo "{0}" deve avere un testo interno. + + + Il nodo "{0}" non è stato trovato. Deve comparire una sola volta sotto "{1}". Il nodo padre, "{1}", verrà ignorato. + + + Il nodo "Type" deve avere "Members", "TypeConverters" o "TypeAdapters". + + + Non è possibile creare un'istanza del convertitore di tipi per il tipo {0} a causa dell'eccezione: {1}. + + + PowerShell non può creare un'istanza dell'adattatore di tipi per il tipo {0} a causa della seguente eccezione: {1}. + + + Il tipo adattato "{0}" non è valido. + + + TypeConverter è stato ignorato perché è già presente. + + + TypeAdapter è stato ignorato perché è già presente. + + + Il tipo "{0}" deve essere TypeConverter o PSTypeConverter. + + + Il tipo "{0}" deve essere PSPropertyAdapter. + + + Il membro {0} è già presente. + + + Il seguente nome del membro è riservato: {0} + + + Eccezione: {0} + + + ScriptProperty deve avere un getter o un setter. + + + CodeProperty deve avere un getter o un setter. + + + {0}, {1}: {2} + + + Il valore deve essere TRUE o FALSE anziché {0}. + + + Il nodo "{0}" non deve avere l'attributo "{1}". + + + {0}, {1}: il file non è stato trovato. + + + {0}, {1}: il file è stato ignorato perché era già stato caricato da {2}. + + + Non è possibile trovare la chiave del Registro di sistema: {0}{1}. Verrà usato {2} per caricare i file di configurazione. + + + Non è possibile trovare il percorso {0} specificato nella chiave del Registro di sistema: {1}{2}. Verrà usato {3} per caricare i file di configurazione. + + + {0}, {1}: il file è stato ignorato perché non ha l'estensione ps1xml. + + + {0}, {1}: il file è stato ignorato a causa della seguente eccezione di convalida: {2}. + + + Il membro "{0}" deve essere una nota. + + + Non è possibile convertire la nota "{0}": "{1}". + + + Non usare il membro "{0}" qui. + + + Il membro "{0}" deve avere il tipo "{1}". + + + "{0}" deve essere presente quando "{1}" è "{2}" e "{3}" è "{4}". + + + A causa di un errore precedente, tutte le impostazioni di serializzazione sono state ignorate. + + + "{0}" non è un membro standard e verrà ignorato. + + + Il percorso {0} non è assoluto. Specificare un percorso assoluto del file del tipo. + + + TypeTable non può essere aggiornato perché potrebbe essere stato creato al di fuori dello spazio di esecuzione. + + + Si sono verificati errori durante il caricamento di TypeTable. Esaminare la proprietà Errors per ottenere messaggi di errore dettagliati. + + + Errore in TypeData "{0}": {1} + + + "{0}" deve avere un valore per la proprietà "{1}". + + + "{0}" non deve avere null o una stringa vuota nella proprietà "{1}". + + + Il tipo "{0}" non è stato trovato. Il valore del nome del tipo deve essere il nome completo del tipo. Verificare il nome del tipo ed eseguire di nuovo il comando. + + + TypeData deve avere "Members", "TypeConverters", "TypeAdapters" o "StandardMembers". + + + Una tabella dei tipi condivisa non può essere aggiornata con più di una voce. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/VerbDescriptionStrings.it.resx b/src/System.Management.Automation/resources/it/VerbDescriptionStrings.it.resx new file mode 100644 index 00000000000..8a206328383 --- /dev/null +++ b/src/System.Management.Automation/resources/it/VerbDescriptionStrings.it.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Aggiunge una risorsa a un contenitore o collega un elemento a un altro elemento + + + Conferma o accetta lo stato di una risorsa o di un processo + + + Afferma lo stato di una risorsa + + + Archivia i dati eseguendone la replica + + + Limita l'accesso a una risorsa + + + Crea un artefatto, in genere un file binario o un documento, da un set di file di input, in genere codice sorgente o documenti dichiarativi + + + Crea uno snapshot dello stato corrente dei dati o della relativa configurazione + + + Rimuove tutte le risorse da un contenitore, ma non elimina il contenitore + + + Modifica lo stato di una risorsa per renderla inaccessibile, non disponibile o inutilizzabile + + + Valuta i dati di una risorsa in base a quelli di un'altra risorsa + + + Conclude un'operazione + + + Compatta i dati di una risorsa + + + Conferma, verifica o convalida lo stato di una risorsa o di un processo + + + Crea un collegamento tra un'origine e una destinazione + + + Modifica i dati da una rappresentazione a un'altra quando il cmdlet supporta la conversione bidirezionale o quando il cmdlet supporta la conversione tra più tipi di dati + + + Converte un tipo di input primario (il nome del cmdlet indica l'input) in uno o più tipi di output supportati + + + Esegue la conversione da uno o più tipi di input a un tipo di output primario (il nome del cmdlet indica il tipo di output) + + + Copia una risorsa in un altro nome o in un altro contenitore + + + Esamina una risorsa per diagnosticare problemi operativi + + + Rifiuta, blocca, obietta o si oppone allo stato di una risorsa o di un processo + + + Invia un'applicazione, un sito Web o una soluzione a una o più destinazioni remote in modo che un utente di tale soluzione possa accedervi al termine della distribuzione + + + Configura una risorsa su uno stato non disponibile o inattivo + + + Interrompe il collegamento tra un'origine e una destinazione + + + Scollega un'entità denominata da un percorso + + + Modifica i dati esistenti aggiungendo o rimuovendo contenuto + + + Configura una risorsa su uno stato disponibile o attivo + + + Specifica un'azione che consente all'utente di spostarsi in una risorsa + + + Imposta l'ambiente o il contesto corrente sul contesto usato più di recente + + + Ripristina i dati di una risorsa che è stata compressa allo stato originale + + + Incapsula l'input primario in un archivio dati persistente, ad esempio un file, o in un formato di interscambio + + + Cerca un oggetto in un contenitore sconosciuto, implicito, facoltativo o specificato + + + Dispone gli oggetti in una forma o un layout specificato + + + Specifica un'azione che recupera una risorsa + + + Consente l'accesso a una risorsa + + + Dispone o associa una o più risorse + + + Rende una risorsa non rilevabile + + + Crea una risorsa da dati archiviati in un archivio dati permanente (ad esempio un file) o in un formato di interscambio + + + Prepara una risorsa per l'uso e la imposta su uno stato predefinito + + + Inserisce una risorsa in un percorso e, facoltativamente, la inizializza + + + Esegue un'azione, come l'esecuzione di un comando o di un metodo + + + Combina le risorse in un'unica risorsa + + + Applica vincoli a una risorsa + + + Protegge una risorsa + + + Identifica le risorse usate da un'operazione specificata o recupera le statistiche relative a una risorsa + + + Crea un'unica risorsa da più risorse + + + Collega un'entità denominata a un percorso + + + Sposta una risorsa da un percorso a un altro + + + Crea una risorsa + + + Modifica lo stato di una risorsa per renderla accessibile, disponibile o utilizzabile + + + Aumenta l'efficacia di una risorsa + + + Invia dati all'esterno dell'ambiente + + + Usa il verbo Test + + + Rimuove un elemento dall'inizio di uno stack + + + Protegge una risorsa da attacchi o perdite + + + Rende una risorsa disponibile ad altri utenti + + + Aggiunge un elemento all'inizio di uno stack + + + Acquisisce informazioni da un'origine + + + Accetta le informazioni inviate da un'origine + + + Reimposta una risorsa sullo stato che è stato annullato + + + Crea una voce per una risorsa in un repository, ad esempio un database + + + Elimina una risorsa da un contenitore + + + Modifica il nome di una risorsa + + + Riporta una risorsa a una condizione utilizzabile + + + Richiede una risorsa o chiede le autorizzazioni + + + Ripristina lo stato originale di una risorsa + + + Modifica la dimensione di una risorsa + + + Esegue il mapping di una rappresentazione abbreviata di una risorsa a una rappresentazione più completa + + + Arresta un'operazione, quindi la avvia nuovamente + + + Imposta una risorsa su uno stato predefinito, come uno stato impostato da Checkpoint + + + Avvia un'operazione precedentemente sospesa + + + Specifica un'azione che non consente l'accesso a una risorsa + + + Conserva i dati per evitare perdite + + + Crea un riferimento a una risorsa in un contenitore + + + Individua una risorsa in un contenitore + + + Recapita le informazioni a una destinazione + + + Sostituisce i dati in una risorsa esistente o crea una risorsa contenente alcuni dati + + + Rende visibile una risorsa all'utente + + + Assicura che due o più risorse si trovino nello stesso stato + + + Ignora una o più risorse o punti in una sequenza + + + Separa le parti di una risorsa + + + Avvia un'operazione + + + Passa al punto o alla risorsa successiva in una sequenza + + + Interrompe un'attività + + + Presenta una risorsa per l'approvazione + + + Sospende un'attività + + + Specifica un'azione che si alterna tra due risorse, ad esempio per passare da una posizione, responsabilità o stato all'altro + + + Verifica l'operazione o la coerenza di una risorsa + + + Tiene traccia delle attività di una risorsa + + + Rimuove le restrizioni per una risorsa + + + Imposta una risorsa sullo stato precedente + + + Rimuove una risorsa da una posizione indicata + + + Rilascia una risorsa bloccata + + + Rimuove le misure di sicurezza di una risorsa aggiunte per impedirne l'attacco o la perdita + + + Rende una risorsa non disponibile ad altri utenti + + + Rimuove la voce di una risorsa da un repository + + + Tiene aggiornata una risorsa per mantenerne lo stato, l'accuratezza e la conformità + + + Usa o include una risorsa per eseguire un'operazione + + + Sospende un'operazione fino a quando non si verifica un evento specificato + + + Controlla o monitora continuamente una risorsa per individuare eventuali modifiche + + + Aggiunge informazioni a una destinazione + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/it/WildcardPatternStrings.it.resx b/src/System.Management.Automation/resources/it/WildcardPatternStrings.it.resx new file mode 100644 index 00000000000..106bd4e5aad --- /dev/null +++ b/src/System.Management.Automation/resources/it/WildcardPatternStrings.it.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 + + + Il criterio di caratteri jolly specificato non è valido: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/Authenticode.ja.resx b/src/System.Management.Automation/resources/ja/Authenticode.ja.resx new file mode 100644 index 00000000000..8bb0dcb12c0 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/Authenticode.ja.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 + + + 今回はこのソフトウェアを実行しないことが選択されたため、ファイル {0} を読み込めません。 + + + この発行元のソフトウェアを決して実行しないことが選択されたため、ファイル {0} を読み込めません。 + + + ファイル {0} は {1}によって公開されています。このシステム上では、この発行元を信頼しないことが明示されています。このスクリプトは、このシステム上では実行されません。詳細については、コマンド "get-help about_signing" を実行してください。 + + + このシステムではスクリプトの実行が無効になっているため、ファイル {0} を読み込めません。詳細については、https://go.microsoft.com/fwlink/?LinkID=135170 の about_Execution_Policies を参照してください。 + + + ファイル {0} を読み込めません。{1}。 + + + ソフトウェア制限ポリシー (例: グループ ポリシーなどで作成されたもの) によって操作がブロックされているため、ファイル {0} を読み込めません。 + + + 内容を読み取れなかったため、ファイル {0} を読み込めません。 + + + コードに署名できません。指定された証明書はコード署名に適していません。 + + + コードに署名できません。TimeStamp サーバー URL は、http://<server url> または https://<server url> の形式で完全修飾されている必要があります。 + + + コードに署名できません。このハッシュ アルゴリズムはサポートされていません。 + + + この信頼されていない発行元からのソフトウェアを実行しますか? + + + ファイル {0} は {1} によって公開されており、このシステム上では信頼されません。信頼できる発行元からのスクリプトのみ実行してください。 + + + ソフトウェア {0} は不明な発行元によって公開されたものです。このソフトウェアは実行しないことをおすすめします。 + + + セキュリティ警告 + + + 信頼できるスクリプトのみ実行してください。インターネットから取得したスクリプトは役立つ場合がありますが、このスクリプトには、コンピューターに害を及ぼす可能性もあります。このスクリプトを信頼する場合は、Unblock-File コマンドレットを使用すると、この警告メッセージを表示せずにスクリプトを実行できるようになります。{0} を実行しますか? + + + 決して実行しない(&V) + + + 今回、この発行元からのスクリプトを実行しません。以後、このスクリプトの実行確認を求めません。今後このスクリプトの実行が試行された場合は通知なしで失敗します。 + + + 実行しない(&D) + + + 今回、この発行元からのスクリプトを実行しません。以後、このスクリプトを実行する際は引き続き確認を求めます。 + + + 今回は実行する(&R) + + + 今回、この発行元からのスクリプトを実行します。以後、このスクリプトを実行する際は引き続き確認を求めます。 + + + 常に実行(&A) + + + 今回、この発行元からのスクリプトを実行します。以後、このスクリプトの実行確認を求めません。 + + + 一時停止(&S) + + + 現在のパイプラインを一時停止し、コマンド プロンプトに戻ります。終了後、「exit」と入力して操作を再開してください。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/AuthorizationManagerBase.ja.resx b/src/System.Management.Automation/resources/ja/AuthorizationManagerBase.ja.resx new file mode 100644 index 00000000000..a40a0e310d4 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/AuthorizationManagerBase.ja.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 + + + AuthorizationManager チェックに失敗しました。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/AutomationExceptions.ja.resx b/src/System.Management.Automation/resources/ja/AutomationExceptions.ja.resx new file mode 100644 index 00000000000..cfa43602af4 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/AutomationExceptions.ja.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 引数 "{0}" の値が無効なため、引数を処理できません。"{0}" 引数の値を変更して、操作を再実行してください。 + + + パラメーター "{0}" の値が無効なため、引数を処理できません。指定可能な値は、"Global"、"Local"、"Script"、または現在のスコープの相対的な数値 (0 ~スコープの数。ここでは 0 は現在のスコープを表し、1 はその親を表す) です。"{0}" パラメーターの値を変更し、操作を再実行してください。 + + + 引数 "{0}" の値が null 値であるため、引数を処理できません。引数 "{0}" の値を null 値以外に変更してください。 + + + 引数 "{0}" の値が範囲外であるため、引数を処理できません。引数 "{0}" を範囲内の値に変更してください。 + + + 操作 "{0}" が無効なため、操作を実行できません。操作 "{0}" を削除するか、無効な理由を確認してください。 + + + 操作 "{0}" が実装されていないため、操作を実行できません。 + + + 操作 "{0}" はサポートされていないため、操作を実行できません。 + + + オブジェクト "{0}" は既に破棄されているため、操作を実行できません。 + + + スクリプト ブロックに複数の句が含まれているため、スクリプト ブロックを呼び出せません。Invoke() メソッドは、1 つの句を含むスクリプト ブロックでのみ使用できます。 + + + スクリプト ブロックには複数の句が含まれているため、変換できません。式または制御構造は許可されていません。スクリプト ブロックにパイプラインまたはコマンドが 1 つだけ含まれていることを確認してください。 + + + 空のスクリプト ブロックは変換できません。スクリプト ブロックにパイプラインまたはコマンドが 1 つだけ含まれていることを確認してください。 + + + 変換できるのは、パイプラインまたはコマンドを 1 つだけ含むスクリプト ブロックのみです。式または制御構造は許可されていません。スクリプト ブロックにパイプラインまたはコマンドが 1 つだけ含まれていることを確認してください。 + + + トップレベルのトラップ ステートメントを含むスクリプト ブロックは変換できません。 + + + param(...)ブロックで宣言されていない変数を逆参照する ScriptBlock に対して PowerShell オブジェクトを生成することはできません。 宣言されていない変数の名前: {0}。 + + + 非定数式を評価する ScriptBlock に対して PowerShell オブジェクトを生成することはできません。非定数式: {0}。 + + + 非定数式を評価する ScriptBlock に対して PowerShell オブジェクトを生成することはできません。動的な式: {0}。 + + + 引数値内で他のスクリプト ブロックを渡そうとする ScriptBlock に対して、PowerShell オブジェクトを生成することはできません。 + + + メイン パイプラインの引数を評価するためにパイプライン、コマンド、または関数を呼び出す ScriptBlock の PowerShell オブジェクトを生成することはできません。 + + + ドット ソースを使用する ScriptBlock に対しては PowerShell オブジェクトを生成できません。 + + + 他のスクリプト ブロックを呼び出す ScriptBlock に対しては PowerShell オブジェクトを生成できません。 + + + 禁止されているリダイレクト演算子が含まれているため、スクリプト ブロックを PowerShell オブジェクトに変換できません。 + + + 操作コンテキストが関連付けられていない ScriptBlock に対して PowerShell オブジェクトを生成することはできません。 + + + ユーザーがコマンドを停止しました。 + + + オブジェクト "{0}" は、dynamicparam ブロックから返す型として正しくありません。dynamicparam ブロックは、$null、または型 [System.Management.Automation.RuntimeDefinedParameterDictionary] のオブジェクトを返す必要があります。 + + + スクリプト ブロックはオープン ジェネリック型に変換できません。適切な閉じたジェネリック型を定義してから、再試行してください。 + + + 式を使用してパイプラインを開始する ScriptBlock に対して、 PowerShell オブジェクトを生成することはできません。 + + + Using 変数 '$using:{0}' の値は、ローカル セッションで設定されていないため取得できません。 + + + 指定された変数辞書の Using 式 '{0}' の値を取得できません。スクリプト ブロックから PowerShell インスタンスを作成する場合、Using 式にインデックス操作またはメンバー アクセス操作を含めることはできません。 + + + コンパイル済みスクリプト ブロックのドット ソース + + + 現在のスコープへのスクリプト ブロック '{0}' の呼び出しは、制限付き言語モードでは許可されません。スクリプト言語モード: {1}、コンテキスト言語モード: {2}。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CatalogStrings.ja.resx b/src/System.Management.Automation/resources/ja/CatalogStrings.ja.resx new file mode 100644 index 00000000000..09f1e9136da --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CatalogStrings.ja.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + カタログ定義ファイルを生成できません。 + + + ファイル '{0}' をカタログに追加しています。カタログ内のファイルの相対パスは '{1}' です。 + + + カタログからのファイル {0} の検証をスキップしています。 + + + {1} のハッシュを持つファイル {0} がカタログ内に見つかりました。 + + + カタログのパスには、同じ相対パス {0} を持つ複数のファイルが含まれています。 + + + {1} のハッシュを持つファイル {0} がディスクに見つかりました。 + + + パスからのファイル {0} の検証をスキップしています。 + + + 指定されたハッシュ アルゴリズム {0} のカタログ管理者コンテキストへのハンドルを取得できません。 + + + ファイル {0} のハッシュを作成できません。 + + + カタログ ファイル {0} を開けません。 + + + カタログ バージョンが無効です。カタログのバージョン {0} およびバージョン {1} のみがサポートされています。 + + + カタログ定義ファイルを開けません。 + + + カタログ内にファイル メンバー {0} の複数のエントリが見つかりました。 + + + カタログ メンバー {0} のファイル名またはパスが見つかりません。 + + + ハッシュするファイル {0} が見つかりません。 + + + ハッシュを計算するファイル {0} を読み取れません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CimInstanceTypeAdapterResources.ja.resx b/src/System.Management.Automation/resources/ja/CimInstanceTypeAdapterResources.ja.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CimInstanceTypeAdapterResources.ja.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CmdletizationCoreResources.ja.resx b/src/System.Management.Automation/resources/ja/CmdletizationCoreResources.ja.resx new file mode 100644 index 00000000000..4dbb017bce4 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CmdletizationCoreResources.ja.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{0}' クラスのコマンドレット + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + 次のファイルの Cmdlet Definition XML を処理できません: {0}。 {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + ObjectModelWrapper 属性を処理できません。{0} 型は、複数のパラメーター セットを定義します。Cmdlet Definition XML で ObjectModelWrapper 属性に有効な型が指定されていることを確認してから、再試行してください。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + ObjectModelWrapper 属性を処理できません。{0} 型はオープン ジェネリック型です。 Cmdlet Definition XML で ObjectModelWrapper 属性に有効な型が指定されていることを確認してから、再試行してください。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + ObjectModelWrapper 属性を処理できません。{0} 型は次のクラスから派生していません: {1}。 Cmdlet Definition XML で ObjectModelWrapper 属性に有効な型が指定されていることを確認してから、再試行してください。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + ObjectModelWrapper 属性を処理できません。{0} 型では、無視される {2} 属性パラメーターを使用して、{1} コマンドレット パラメーターを定義します。 Cmdlet Definition XML で ObjectModelWrapper 属性に有効な型が指定されていることを確認してから、再試行してください。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + {1} コマンドレットの {0} パラメーターを定義できません。 パラメーター名は、{2} クラスによって既に定義されています。 Cmdlet Definition XML でパラメーター名を変更してから、再試行してください。 + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + {1} コマンドレットの {0} パラメーターを定義できません。パラメーター名は、{2} XML 要素内で既に定義されています。Cmdlet Definition XML でパラメーター名を変更してから、再試行してください。 + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + EnumName 属性の値を有効な C# 識別子に変換できません: {0}。Cmdlet Definition XML で EnumName 属性を確認してから、再試行してください。 + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + その <Enum EnumName="{0}" ...> 要素を処理できません。 {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + リモート コンピューターから無効な CDXML ファイルが返されました。次のコマンドレット アダプターは、リモート コンピューターから CDXML モジュールをインポートする場合にはサポートされていません: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CommandBaseStrings.ja.resx b/src/System.Management.Automation/resources/ja/CommandBaseStrings.ja.resx new file mode 100644 index 00000000000..3b0a6bf9ca3 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CommandBaseStrings.ja.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + この操作を続行しますか? + + + はい(&Y) + + + 操作の次のステップのみを続行します。 + + + すべてはい(&A) + + + 操作のすべてのステップを続行します。 + + + いいえ(&N) + + + この操作をスキップし、次の操作に進みます。 + + + すべていいえ(&L) + + + この操作とそれ以降のすべての操作をスキップします。 + + + このコマンドを停止します。 + + + コマンドの停止(&H) + + + 一時停止(&S) + + + 現在のパイプラインを一時停止し、コマンド プロンプトに戻ります。パイプラインを再開するには、"{0}" と入力します。 + + + + プログラム "{0}" は 0 以外の終了コードで終了しました: {1} ({2})。 + + + ターゲット "{1}" に対して操作 "{0}" を実行しています。 + + + What If: {0} + + + この操作を実行しますか? +{0} + + + 確認 + + + 実行中のコマンドは、設定変数 "{0}" または共通パラメーターが Stop に設定されているため停止しました: {1} + + + 実行中のコマンドは、設定変数 "{0}" または共通パラメーターが Stop に設定されているため停止しました。 + + + 実行中のコマンドは、設定変数 "{0}" または共通パラメーターが無効な次の値に設定されているため停止しました: "{1}"。 + + + ユーザーが [停止] オプションを選択したため、実行中のコマンドが停止しました。 + + + ユーザーがコマンドを中断したため、実行中のコマンドが停止しました。 + + + PSCmdlet から派生したコマンドレットを直接呼び出すことはできません。 + + + コマンドレット '{0}' は、リモート セッションでパラメーター '{1}' をサポートしていません。 + + + 総数: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + 推定合計数: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + 不明な合計数 + Reviewed by TArcher on 2010-07-20 + + + コマンド '{0}' + + + {0} は廃止されています。 {1} + + + コマンド ラインに対する Exec 呼び出しがエラー番号 {0} で失敗しました: {1} + + + コマンド '{0}' が見つかりませんでした。指定されたコマンドは実行可能ファイルである必要があります。 + + + スクリプト ブロック処理のドット ソース チェック + + + スクリプト ブロック '{0}' のドット ソース処理は、ConstrainedLanguage モードでは失敗します。これは、その言語モード '{1}' が現在の言語モード '{2}' と一致しないためです。 + + + コマンド検索機能 + + + モジュール '{1}' のコマンド '{0}' は信頼されていないため、ConstrainedLanguage モードではアクセスできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ConsoleInfoErrorStrings.ja.resx b/src/System.Management.Automation/resources/ja/ConsoleInfoErrorStrings.ja.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ConsoleInfoErrorStrings.ja.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CoreClrStubResources.ja.resx b/src/System.Management.Automation/resources/ja/CoreClrStubResources.ja.resx new file mode 100644 index 00000000000..4f9a0f17557 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CoreClrStubResources.ja.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 環境変数名に等号を含めることはできません。 + + + 環境変数の名前または値が長すぎます。 + + + 文字列の最初の文字が null 値です。 + + + 文字列を 0 文字にすることはできません。 + + + コンピューター名を取得できませんでした。 + + + 現在のユーザーのドメイン名を取得できませんでした。 + + + 不明なエラー "{0}"。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CredUI.ja.resx b/src/System.Management.Automation/resources/ja/CredUI.ja.resx new file mode 100644 index 00000000000..e757fec80c7 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CredUI.ja.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell 資格情報の要求 + + + 資格情報を入力してください。 + + + 資格情報を入力してください。 + + + キャプションの最大長は {0} 文字です。 + + + メッセージの最大長は {0} 文字です。 + + + ユーザー名の最大長は {0} 文字です。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/Credential.ja.resx b/src/System.Management.Automation/resources/ja/Credential.ja.resx new file mode 100644 index 00000000000..98ddd690d2f --- /dev/null +++ b/src/System.Management.Automation/resources/ja/Credential.ja.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 + + + 資格情報をシリアル化できません。このコマンドがワークフローを開始している場合、ワークフローが開始されるプロセスには資格情報をシリアル化するアクセス許可がないため、資格情報を永続化できません。 + +-- PSSession でワークフローがローカル コンピューターに対して開始された場合は、セッションを作成したコマンドに EnableNetworkAccess パラメーターを追加します。 +-- PSSession でワークフローがリモート コンピューターに対して開始された場合は、セッションを作成したコマンドに、CredSSP の値を持つ Authentication パラメーターを追加します。または、RunAsUser プロパティ値を持つセッション構成に接続します。 + + + UserName の値が正しい形式ではありません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/CredentialAttributeStrings.ja.resx b/src/System.Management.Automation/resources/ja/CredentialAttributeStrings.ja.resx new file mode 100644 index 00000000000..1606c61bbf7 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/CredentialAttributeStrings.ja.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 + + + PowerShell 資格情報の要求 + + + 資格情報を入力してください。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/DebuggerStrings.ja.resx b/src/System.Management.Automation/resources/ja/DebuggerStrings.ja.resx new file mode 100644 index 00000000000..3a7067b0d85 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/DebuggerStrings.ja.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '${0}' の変数ブレークポイント ({1} アクセス) + + + '{0}:${1}' の変数ブレークポイント ({2} アクセス) + + + '{0}:{1}' の行ブレークポイント + + + '{0}:{1}, {2}' の行ブレークポイント + + + '{0}' 上のコマンド ブレークポイント + + + コマンドのブレークポイント '{0}:'{1}' + + + ブレークポイント {0} にヒットしません + + + {0}、{1,-16} 単一ステップ (関数、スクリプトなどにステップイン) + + + {0}、{1,-16} 次のステートメントへのステップ (関数、スクリプトなどをステップ オーバー) + + + {0}、{1,-16} 現在の関数、スクリプトなどをステップ アウトします。 + + + {0}、{1,-16} 操作の続行 + + + {0}、{1,-16} 操作を停止してデバッガーを終了する + + + {0}、Get-PSCallStack 表示呼び出し履歴 + + + {0}、{1,-16} 現在のスクリプトのソース コードを一覧表示します。 + + + "list" を使用して、現在の行 "list <m>" から開始します + + + 行 <m> から開始し、"list <m> <n>" を使用して <n> をリストします + + + 行 <m> から始まる行 + + + <enter> 最後のコマンドが {0}、{1}、または {2} + + + {0}、{1,-16} はヘルプ メッセージを表示します。 + + + デバッガー プロンプトをカスタマイズする方法については、「help about_prompt」と入力してください。 + + + +現在のセッションはデバッグをサポートしていません。操作は続行されます。 + + + + + {0}: 行 {1} + + + 使用できるソース コードはありません。 + + + 開始行は {0} 以下の正の整数である必要があります + + + 行数は正の整数でなければなりません。 + + + <No file> + + + {0}、{1}: 行 {2} で + + + デバッガーは、停止状態でない限り、コマンドを処理できません。 + + + SetDebugAction は、ローカル スクリプト デバッガーには実装されていません。 + + + リモート セッションのデバッガーが停止状態ではないため、デバッガーは再開アクションを設定できません。 + + + デバッガーが現在ビジー状態であるため、ジョブをデバッグできません。 + + + 指定されたジョブとすべての子ジョブが調べられましたが、デバッグ可能なジョブは見つかりませんでした。 ジョブまたは子ジョブをデバッグするには、ジョブがデバッグをサポートし、実行中の状態である必要があります。 + + + デバッグ モードが "なし" に設定された状態でデバッガーがオフになっているため、ステップ モードに対してデバッガーを有効にできません。 + + + ホスト デバッガーが現在ビジー状態であるため、実行空間をデバッグできません。 + + + 実行空間をデバッグできません。実行空間デバッガーは現在オフになっています (DebugMode は 'None' です)。 + + + Opened 状態ではない実行空間をデバッグできません。この実行空間の状態は {0}。 + + + 実行空間をデバッグできません。Runspace {0} には、デバッガーが関連付けされていません。 + + + デバッガーは既にオーバーライドされています。 + + + デバッガー オブジェクトをそれ自体にプッシュすることはできません。 + + + {0} コマンドは、リモート実行空間で実行されている PowerShell のバージョンでのリモート使用ではサポートされていません。 + + + プロセス + + + {0}、{1,-16} 操作を続行し、デバッガーをデタッチします。 + + + デバッガーのデタッチ コマンドは適用できません。 detach コマンドは、Debug-Job コマンドレットまたは Debug-Runspace コマンドレットを使用してジョブと実行空間をデバッグする場合にのみ適用されます。 + + + 実行空間 ID が無効です: {0} + + + 実行空間を取得できません。 + + + ブレークポイントまたは BreakpointList を指定する必要があります。 + + + BreakpointList にブレークポイントではない項目が含まれていました。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/DescriptionsStrings.ja.resx b/src/System.Management.Automation/resources/ja/DescriptionsStrings.ja.resx new file mode 100644 index 00000000000..8a4f4de7f6f --- /dev/null +++ b/src/System.Management.Automation/resources/ja/DescriptionsStrings.ja.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 + + + {0} を null 値または空にすることはできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/DiscoveryExceptions.ja.resx b/src/System.Management.Automation/resources/ja/DiscoveryExceptions.ja.resx new file mode 100644 index 00000000000..182edd2c702 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/DiscoveryExceptions.ja.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 + + + コマンドレット名 "{0}" は形式が正しくないため、検証できません。コマンドレット名には、"Get-Process" などの "-" で区切られた動詞と名詞を含める必要があります。 + + + パラメーター "{0}" が、パラメーターセット "{1}" で複数回宣言されています。 + + + エイリアス "{0}" が複数回宣言されています。 + + + パラメーターを宣言できませんでした。パラメーターは、フィールドとプロパティでのみ宣言できます。 + + + コマンドレットを処理できません。コマンドレット名は、動詞と名詞のペアを '-' で区切って構成する必要があります。 + + + 用語 '{0}' は、コマンドレット、関数、スクリプト ファイル、または実行可能プログラムの名前として認識されません。 +名前のスペルを確認するか、パスが含まれている場合はパスが正しいことを確認してから、もう一度お試しください。 + + + 引数 '{0}' はコマンドレットとして認識されません: {1} + + + 引数 '{0}' はコマンドレットとして認識されません。Cmdlet または PSCmdlet クラスから派生していない可能性があります: {1} + + + エイリアス '{0}' は、コマンドレット、関数、実行可能プログラム、またはスクリプト ファイルとして認識されない用語 '{1}' を参照しているため、解決できません。用語を確認して、もう一度お試しください。 + + + 値 '{1}' のパラメーター '{0}' はコマンドレットではなく、CommandProcessor で処理できないため、処理できません。 + + + '{0}' という名前のコマンドレットは既に存在します。コマンドレットには一意の名前が必要です。 + + + '{0}' という名前のコマンドレット プロバイダーは既に存在します。コマンドレット プロバイダーには一意の名前が必要です。 + + + '{0}' という名前のアセンブリは既に存在します。アセンブリには一意の名前が必要です。 + + + '{0}' という名前のスクリプトは既に存在します。スクリプトには一意の名前が必要です。 + + + #requires ステートメントは形式が正しくないため、処理できません。 +#requires ステートメントは、次のいずれかの形式である必要があります: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + スクリプト '{0}' は、現在のシェルと互換性のない {1} のシェル ID を持つ "#requires" ステートメントが含まれていたため、実行できません。このスクリプトを実行するには、'{2}' にあるシェルを使用する必要があります。 + + + スクリプト '{0}' は、現在のシェルと互換性のない {1} のシェル ID を持つ "#requires" ステートメントが含まれていたため、実行できません。 + + + スクリプト ' {0}' は、PowerShell {1} 用の "#requires" ステートメントが含まれていたため、実行できません。スクリプトに必要な PowerShell のバージョンが、現在実行中の PowerShell {2} のバージョンと一致しません。 + + + スクリプト '{0}' は、PowerShell エディション '{1}' 用の "#requires" ステートメントが含まれていたため、実行できません。スクリプトに必要な PowerShell のエディションが、現在実行中の PowerShell {2} のエディションと一致しません。 + + + スクリプト '{0}' は、スクリプトの "#requires" ステートメントで指定された次のスナップインがないため、実行できません: {1}。 + + + #requires ステートメントでは、shellID のみが指定されています。#Requires ステートメントでは、PowerShell で実行するときに必要な PowerShell スナップインを指定する必要があります。 + + + スクリプト '{0}' は、管理者として実行するための "#requires" ステートメントが含まれているため、実行できません。現在の PowerShell セッションは管理者として実行されていません。[管理者として実行] オプションを使用して PowerShell を起動し、もう一度スクリプトを実行してみてください。 + + + {0} (バージョン {1}) + + + コマンドを取得できませんでした。ArgumentList パラメーターは 1 つのコマンドレットまたはスクリプトを取得するときにのみ指定できます。 + + + パラメーター名 "{0}" は、将来使用するために予約されています。 + + + スクリプト '{0}' は、スクリプトの "#requires" ステートメントで指定された次のモジュールがないため、実行できません: {1}。 + + + '{0}' コマンドはモジュール '{1}' で見つかりましたが、モジュールを読み込めませんでした。詳細については、'Import-Module {1}' を実行してください。 + + + '{0}' コマンドはモジュール '{1}' で見つかりましたが、次のエラーによりモジュールを読み込めませんでした: [{2}] +詳細については、'Import-Module {1}' を実行してください。 + + + モジュール '{0}' を読み込めませんでした。詳細については、'Import-Module {0}' を実行してください。 + + + '{0}' という名前のパラメーターを含む一致するコマンドはありません。 パラメーター名のスペルを確認してから、もう一度お試しください。 + + + このコマンドは別の言語モードで定義されているため、ドットソース化できません。このコマンドを内容をインポートせずに呼び出すには、'.' 演算子を省略します。 + + + ShowCommandInfo パラメーターと Syntax パラメーターを同時に指定することはできません。 + + + このスクリプト コマンドは、試験的な機能 '{0}' が有効になっている場合は無効になります。 + + + このスクリプト コマンドは、試験的な機能 '{0}' が無効になっている場合は無効になります。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/EnumExpressionEvaluatorStrings.ja.resx b/src/System.Management.Automation/resources/ja/EnumExpressionEvaluatorStrings.ja.resx new file mode 100644 index 00000000000..0b765f7c170 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/EnumExpressionEvaluatorStrings.ja.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 入力式を空にすることはできません。各入力式に少なくとも 1 つの識別子名を指定します。 + + + 空の識別子名を有効な列挙子名と一致させることができません。次の列挙子名のいずれかを指定して、もう一度やり直してください: {0}。 + + + 式に指定するジェネリック型は、列挙型を表す必要があります。有効な列挙型を指定してください。 + + + 識別子名 {0} は、次の列挙子名と似ているか、同一であるため、処理できません: {1}。より具体的な識別子名を使用します。 + + + 識別子名 {0} を有効な列挙子名と一致させることができません。次の列挙子名のいずれかを指定して、もう一度やり直してください: +{1} + + + 識別子のグループ化は許可されていないため、式ではかっこの使用は無効です。かっこを削除するか、部分式を囲む場合は式を展開してみてください。 + + + 予期しないトークンが原因で式を解析できません。識別子名の後には、OR (,) 演算子または AND (+) 演算子のみが必要です。 + + + NOT (!) 演算子の後に予期しないトークンがあるため、式を解析できません。NOT (!) 演算子の後に識別子名が必要です。 + + + 予期しないトークンが原因で式を解析できません。識別子名または NOT (!) 演算子は、式の先頭、または OR (,) 演算子または AND (+) 演算子の後に必要です。また、式の末尾に OR (,)、AND (+) 演算子、NOT (!) 演算子を使用することはできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ErrorCategoryStrings.ja.resx b/src/System.Management.Automation/resources/ja/ErrorCategoryStrings.ja.resx new file mode 100644 index 00000000000..951bc6f5b5a --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ErrorCategoryStrings.ja.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + デッドロックが検出されました: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}]、{3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + 認識できないエラー カテゴリ {4}: ({1}:{2}) [{0}]、{3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ErrorPackage.ja.resx b/src/System.Management.Automation/resources/ja/ErrorPackage.ja.resx new file mode 100644 index 00000000000..752846fa8a3 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ErrorPackage.ja.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 + + + {0}: {1} + + + エラー "{0}" のエラー テキストが空です : "{1}" + + + オブジェクト "{0}" はエラーとして報告されます。 + + + {0} 値は、ActionPreference 変数ではサポートされていません。指定された値は、基本設定パラメーターの値としてのみ使用する必要があり、既定値に置き換えられています。詳細については、ヘルプ トピック「about_Preference_Variables」を参照してください。 + + + {0} ActionPreference 値は将来使用するために予約されており、現時点ではサポートされていません。基本設定変数の詳細については、ヘルプ トピック「about_Preference_Variables」を参照してください。 + + + {0} ActionPreference 値は将来使用するために予約されており、現時点ではサポートされていません。{1} 変数では、既定値の {2} に置き換えられました。基本設定変数の詳細については、ヘルプ トピック「about_Preference_Variables」を参照してください。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/EtwLoggingStrings.ja.resx b/src/System.Management.Automation/resources/ja/EtwLoggingStrings.ja.resx new file mode 100644 index 00000000000..319009ff74a --- /dev/null +++ b/src/System.Management.Automation/resources/ja/EtwLoggingStrings.ja.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + コマンド {0} は {1} です。 + + + エンジンの状態が {0} から {1} に変わりました。 + + + 完全修飾エラー ID = {0} + + + エラー メッセージ = {0} + + + 推奨されるアクション = {0} + + + 実行ポリシー + + + ジョブ コマンド = {0} + + + ジョブ ID = {0} + + + ジョブ インスタンス ID = {0} + + + ジョブの場所 = {0} + + + ジョブ名 = {0} + + + ジョブの状態 = {0} + + + コマンド名 = + + + コマンド パス = + + + コマンドの種類 = + + + エンジンのバージョン = + + + ホスト ID = + + + ホスト名 = + + + ホスト アプリケーション = + + + ホスト バージョン = + + + パイプライン ID = + + + 実行空間 ID = + + + スクリプト名 = + + + シーケンス番号 = + + + 重大度 = + + + シェル ID = + + + 時刻 = + + + ユーザー = + + + 接続されたユーザー = + + + NULL ジョブ + + + プロバイダー名 + + + プロバイダー {0} の状態が {1} に変更されました。 + + + スクリプトの実行は {0} です。 + + + 変数 {0} が {1} から {2} に変更されました。 + + + 変数 {0} は {1} に変更されました。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/EventResource.ja.resx b/src/System.Management.Automation/resources/ja/EventResource.ja.resx new file mode 100644 index 00000000000..251f2382af1 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/EventResource.ja.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + イベント ID PowerShell.Core.Instrumentation.man のメッセージが見つかりませんでした。 + + + スケジュール済みジョブ {0} が {1} に開始されました + + + + スケジュール済みジョブ {0} が {1} に状態 {2} で完了しました + + + + スケジュール済みジョブの例外 {0}: + メッセージ: {1} + StackTrace: {2} + InnerException: {3} + + + + 試験的な機能の初期化: 構成ファイルから試験的な機能 '{0}' を無視します。 {1} + + + 試験的な機能の初期化: 構成ファイルを読み取れませんでした。 + 例外: {0} + メッセージ: {1} + StackTrace: {2} + + + + ワークフロー プラグインが読み込まれました。 + EndpointName: {0} + ユーザー: {1} + HostingMode: {2} + プロトコル: {3} + 構成: + {4} + + + ワークフローの実行が開始されました。 + WorkflowId: {0} + ManagedNodes: {1} + + + ワークフローの状態が変更されました。 + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + ワークフロー プラグインのシャットダウンが要求されました。 + EndpointName: {0} + + + ワークフロー プラグインが再起動されました。 + EndpointName: {0} + + + ワークフローを再開しています。 + WorkflowId: {0} + + + エンドポイントに設定されたクォータ制限を超えました。 + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + ワークフローが再開されました。 + WorkflowId: {0} + + + ワークフロー実行空間プールが作成されました。 + WorkflowId: {0} + ManagedNode: {1} + + + アクティビティが実行のためにキューに登録されました。 + WorkflowId: {0} + ActivityName: {1} + + + アクティビティの実行が開始されました。 + ActivityName: {0} + ActivityTypeName: {1} + + + ワークフローを XAML ファイルからインポートしています。 + WorkflowId: {0} + XamlFile: {1} + + + ワークフローが XAML ファイルからインポートされました。 + WorkflowId: {0} + XamlFile: {1} + + + エラーのため、XAML ファイルからワークフローをインポートできませんでした。 + WorkflowId: {0} + ErrorDescription: {1} + + + ワークフローの検証が開始されました。 + WorkflowId: {0} + + + ワークフローの検証に成功しました。 + WorkflowId: {0} + + + エラーでワークフローの検証に失敗しました。 + WorkflowId: {0} + + + ワークフロー アクティビティが検証されました。 + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + ワークフロー アクティビティを検証できませんでした。 + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + アクティビティの実行に失敗しました。 + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + 実行空間の可用性が変更されました。 + RunspaceId: {0} + 可用性: {1} + + + 実行空間の状態が変更されました。 + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + ワークフローが実行のために読み込まれました。 + WorkflowId: {0} + + + ワークフローがアンロードされました。 + WorkflowId: {0} + + + ワークフローの実行はキャンセルされました。 + WorkflowId: {0} + + + ワークフローの実行が中止されました。 + WorkflowId: {0} + + + ワークフローのクリーンアップ操作が実行されました。 + WorkflowId: {0} + + + 永続化されたワークフローがディスクから読み込まれました。 + WorkflowId: {0} + パス: {1} + + + ワークフロー データがディスクから削除されました。 + WorkflowId: {0} + パス: {1} + + + 削除ジョブを開始しています。 + JobId: {0} + + + ジョブの状態が変更されました。 + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + ジョブ エラー。 + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + ワークフロー用の子ジョブが作成されました。 + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + ワークフローの親ジョブが作成されました。 + JobId: {0} + + + ワークフローの実行に必要なすべてのジョブが作成されました。 + JobId: {0} + WorkflowId: {1} + + + ワークフローの子ジョブが削除されました。 + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + ジョブの削除中にエラーが発生しました。 + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + エラー: {3} + + + 実行するワークフローを読み込んでいます。 + WorkflowId: {0} + + + ワークフローの実行が完了しました。 + WorkflowId: {0} + + + ワークフローの実行を取り消しています。 + WorkflowId: {0} + + + ワークフローの実行を中止しています。 + WorkflowId: {0} + 理由: {1} + + + ワークフローをアンロードしています。 + WorkflowId: {0} + + + ワークフローの強制シャットダウンが開始されました。 + WorkflowId: {0} + + + ワークフローの強制シャットダウンが完了しました。 + WorkflowId: {0} + + + ワークフローを強制的にシャットダウンしているときにエラーが発生しました。 + WorkflowId: {0} + ErrorDescription: {1} + + + ワークフローをディスクに永続化しています。 + WorkflowId: {0} + PersistPath: {1} + + + ワークフローがディスクに永続化されました。 + WorkflowId: {0} + + + アクティビティの実行が完了しました。 + ActivityName: {0} + + + ワークフローの実行エラー。 + WorkflowId: {0} + ErrorDescription: {1} + + + 新しい PowerShell エンドポイントが登録されました。 + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + エンドポイント構成が変更されました。 + EndpointName: {0} + ModifiedBy: {1} + + + エンドポイント構成の登録が解除されました。 + EndpointName: {0} + UnregisteredBy: {1} + + + エンドポイント構成が無効になっています。 + EndpointName: {0} + DisabledBy: {1} + + + エンドポイント構成が有効になっています。 + EndpointName: {0} + EnabledBy: {1} + + + プロセス外の実行空間が開始されました。 + コマンド: {0} + + + ワークフローの実行中にパラメーターのスプラッティングが実行されました。 + パラメーター: {0} + コンピューター: {1} + + + ワークフロー エンジンが開始されました。 + EndpointName: {0} + + + ワークフロー マネージャーを でインスタンス化しました + CheckpointPath: {0} + ConfigProviderId: {1} + ユーザー名: {2} + パス: {3} + + + コンピューター名 $null または . が LocalHost に解決されます + + + 既定のスキーム http に解決しています + + + リモート シェル名は既定の PowerShellCore に解決されました + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + Scriptblock テキストを作成しています ({0}/{1}): +{2} + +ScriptBlock ID: {3} +パス: {4} + + + ScriptBlock ID の呼び出しを開始しました: {0} +実行空間 ID: {1} + + + ScriptBlock ID の呼び出しが完了しました: {0} +実行空間 ID: {1} + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + {2} + +コンテキスト: +{0} + +ユーザー データ: +{1} + + + + アクティビティ ID を関連付けています。 + CurrentActivityId: {0} + ParentActivityId: {1} + + + クラス名 = {0} +メソッド名 = {1} +ワークフロー GUID = {2} +メッセージ = {3} +{4} +アクティビティ名 = {5} +アクティビティ GUID = {6} +パラメーター = {7} + + + Runspace オブジェクト を作成しています + インスタンス ID: {0} + + + RunspacePool オブジェクトを作成しています + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + RunspacePool を開いています + + + アクティビティ ID の変更と関連付け + + + 実行空間の状態が {0} に変更されました + + + セッション ID {2} のエラー コード {1} に対して、セッション作成の再試行 {0} を試みています + + + PowerShell は、AppDomain: {1} のプロセス: {0} で IPC リッスン スレッドを開始しました。 + + + PowerShell は、AppDomain: {1} のプロセス: {0} で IPC リッスン スレッドを終了しました。 + + + AppDomain: {1} のプロセス: {0} の PowerShell IPC リッスン スレッドでエラーが発生しました。 エラー メッセージ: {2}。 + + + PowerShell IPC が、ユーザー:{2} の AppDomain: {1} のプロセス: {0} で接続されました。 + + + PowerShell IPC が、ユーザー:{2} の AppDomain: {1} のプロセス: {0} で切断されました。 + + + ポートが {0} に解決されました + + + AppName が {0} に解決されました + + + ComputerName が {0} に解決されました + + + スキームは {0} です + + + テスト分析メッセージ + + + 接続パラメーターは です + 接続 URI: {0} + リソース URI: {1} + ユーザー: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + サム プリント: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + アクティビティ ID の変更と関連付け + + + 次のオブジェクトを受信しました。実行空間 ID: {0} コマンド ID: {1} 宛先: {2} DataType: {3} TargetInterface: {4} + + + appdomain でハンドルされない例外が発生しました。 +例外の種類: {0} +例外メッセージ: {1} +例外のスタック トレース: {2} + + + 実行空間 ID: {0} パイプライン ID: {1}。WSMan がエラー コード {2} のエラーを報告しました。 + エラー メッセージ: {3} + StackTrace: {4} + + + appdomain でハンドルされない例外が発生しました。 +例外の種類: {0} +例外メッセージ: {1} +例外のスタック トレース: {2} + + + 実行空間 ID: {0} パイプライン ID: {1}。WSMan がエラー コード {2} のエラーを報告しました。 + エラー メッセージ: {3} + StackTrace: {4} + + + 実行空間 ID: {0}。WSMan Create Shell を使用して接続を確立しています + + + 実行空間 ID: {0}。WSMan Create Shell のコールバックを受信しました + + + 実行空間 ID: {0}。WSManCloseShell を使用してシェルを閉じています + + + 実行空間 ID: {0}。WSManCloseShell のコールバックを受信しました + + + 実行空間 ID: {0} パイプライン ID: {1}。サイズ {2} のデータを送信しています + + + 実行空間 ID: {0} パイプライン ID: {1}。WSManSendShellInputEx のコールバックを受信しました + + + 実行空間 ID: {0} パイプライン ID: {1}。Placing Receive request using WSManReceiveShellOutputEx + + + 実行空間 ID: {0} パイプライン ID: {1}。サイズ {2}のデータを受信しました。 + + + 実行空間 ID: {0} パイプライン ID: {1}。WSManRunShellCommandEx を使用してコマンド接続を確立しています + + + 実行空間 ID: {0} パイプライン ID: {1}。コマンド接続のコールバックを受信しました + + + 実行空間 ID: {0} パイプライン ID: {1}。コマンドのトランスポートを閉じています + + + 実行空間 ID: {0} パイプライン ID: {1}。コマンド終了のコールバックを受信しました + + + 実行空間 ID: {0} パイプライン ID: {1}。WSManSignalShellEx を使用してコード {2} のシグナルを送信しています + + + 実行空間 ID: {0} パイプライン ID: {1}。WSManSignalShellEx のコールバックを受信しました + + + 実行空間 ID: {0}。接続が URI にリダイレクトされています: {1} + + + 実行空間 ID: {0} パイプライン ID: {1}。サーバーはサイズ {2} のデータをクライアントに送信しています。DataType: {3} TargetInterface: {4} + + + {0} を要求します。サーバー リモート セッションを作成しています。ユーザー名: {1} カスタム シェル ID: {2} + + + 要求のコンテキストを報告しています: {0} 報告されたコンテキスト: {0} + + + 要求のレポート操作が完了しました: {0} + エラー コード: {1} + エラー メッセージ: {2} + StackTrace: {3} + + + シェル コンテキスト {0}。要求 ID {1}。コマンドを実行するための共通セッションを作成しています。 + + + シェル コンテキスト {0} コマンド コンテキスト {1} 要求 ID {2}。コマンドを停止しています。 + + + シェル コンテキスト {0} コマンド コンテキスト {1} 要求 ID {2}。クライアントからデータを受信しました。 + + + シェル コンテキスト {0} コマンド コンテキスト {1} 要求 ID {2}。クライアントは、サーバーがデータを送信できるように受信要求を送信しました。 + + + シェル コンテキスト {0} コマンド コンテキスト {1} IsReceiveOperation {2}。終了操作要求を受信しました。 + + + シェル ID {1} のカスタム シェル用アセンブリ {0} を読み込んでいます + + + シェル ID {1} のカスタム シェルの種類 {0} を読み込んでいます + + + リモート処理フラグメントを受信しました。 + オブジェクト ID: {0} + フラグメント ID: {1} + 開始フラグ: {2} + 終了フラグ: {3} + ペイロードの長さ: {4} + ペイロード データ: {5} + + + リモート処理フラグメントを送信しました。 + オブジェクト ID: {0} + フラグメント ID: {1} + 開始フラグ: {2} + 終了フラグ: {3} + ペイロードの長さ: {4} + ペイロード データ: {5} + + + winrm サービスをシャットダウンしています。 + + + オブジェクトが正常にリハイドレートされました。 + 逆シリアル化された型名: {0} + 型にキャストしてリハイドレート: {1} + リハイドレートされたオブジェクトの種類: {2} + + + オブジェクトのリハイドレートに失敗しました。 + 逆シリアル化された型名: {0} + 型にキャストしてリハイドレート: {1} + 型キャストの例外: {2} + 型キャストの内部例外: {3} + + + シリアル化の深さがオーバーライドされました。 + シリアル化された型名: {0} + 元の深さ: {1} + オーバーライドされた深さ: {2} + トップ レベルより下の現在の深さ: {3} + + + シリアル化モードがオーバーライドされました。 + シリアル化された型名: {0} + オーバーライドされたモード: {1} + + + プロパティの評価に使用できる実行空間がないため、スクリプト プロパティのシリアル化はスキップされました。 + プロパティ名: {0} + プロパティ所有者の型名: {1} + ゲッター スクリプト: {2} + + + プロパティ ゲッターが失敗したため、プロパティのシリアル化はスキップされました。 + プロパティ名: {0} + プロパティ所有者の型名: {1} + プロパティ ゲッターの例外: {2} + プロパティ ゲッターの内部例外: {3} + + + 列挙されるオブジェクトが例外をスローしたため、列挙可能なオブジェクトのシリアル化が完了していない可能性があります。 + 列挙対象のオブジェクトの種類: {0} + 例外: {1} + + + シリアル化でオブジェクトの ToString メソッドが呼び出されましたが、失敗しました。 + オブジェクトの種類: {0} + 例外: {1} + + + トップ レベルより下の最大深度に達したため、オブジェクトは文字列としてシリアル化されます。 + 最大深度のオブジェクトの種類: {0} + 最大深度のプロパティ名: {1} + 深度: {2} + + + XmlException がデシリアライザーによってスローされました (clixml の形式が正しくない可能性があります)。 + 行番号: {0} 行の位置: {1} + 例外: {2} + + + 指定されたプロパティの 1 つが見つからなかったため、指定されたプロパティのシリアル化に失敗しました。 + オブジェクトの種類: {0} + プロパティ名: {1} + + + PowerShell コンソールを起動しています + + + PowerShell コンソールでユーザーによる入力が可能になりました + + + {0} + + + ErrorRecord のトレース: + メッセージ: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason: {2} + CategoryInfo.TargetName: {3} + FullyQualifiedErrorId: {4} + 例外の詳細: + メッセージ : {5} + スタック トレース: {6} + InnerException {7} + + + + 例外: + メッセージ: {0} + StackTrace: {1} + InnerException: {2} + + + + PSObject のトレース + + + トレース ジョブ: + ID: {0} + InstanceID: {1} + 名前: {2} + 場所: {3} + 状態: {4} + コマンド: {5} + + + + トレース情報: + {0} + + + トレース情報: + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication.ワークフロー関数の呼び出しを開始しています。追跡 GUID {0} + + + END ImportWorkflowCommand::StartWorkflowApplication.ワークフロー関数の呼び出しを終了しています。追跡 GUID {0} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication で新しいジョブを作成しています。追跡 GUID {0} + + + END ImportWorkflowCommand::StartWorkflowApplication で新しいジョブを作成しています。追跡 GUID {0} + + + END ImportWorkflowCommand::StartWorkflowApplication で新しいジョブを作成しています。追跡 GUID {0}: ContainerParentJob GUID {1} + + + BEGIN JobLogic ContainerParentJob Guid {0} + + + END JobLogic ContainerParentJob Guid {0} + + + BEGIN WorkflowExecution ContainerParentJob Guid {0} + + + END WorkflowExecution ContainerParentJob Guid {0} + + + Guid {0} の WorkflowJob が Guid {1} の ContainerParentJob に追加されました + + + Guid {0} の ProxyJob が、Guid {1} のリモート ContainerParentJob に関連付けられています + + + BEGIN Guid {0} の ContainerParentJob の実行 + + + END Guid {0} の ContainerParentJob の実行 + + + BEGIN Guid {0} のプロキシ ジョブの実行 + + + END Guid {0} のプロキシ ジョブの実行 + + + BEGIN Guid {0} のプロキシ ジョブの StateChanged イベント ハンドラー + + + END Guid {0} のプロキシ ジョブの StateChanged イベント ハンドラー + + + BEGIN Guid {0} のプロキシ子ジョブの StateChanged イベント ハンドラー + + + END Guid {0} のプロキシ子ジョブの StateChanged イベント ハンドラー + + + BEGIN GC の実行 + + + END GC の実行 + + + 永続化ストアが指定された最大サイズに達しました + + + Windows PowerShell ISE はスクリプト ファイル {0} の実行を開始しました。 + + + Windows PowerShell ISE は、ファイル {0}からユーザーが選択したスクリプトの実行を開始しました。 + + + Windows PowerShell ISE は現在のコマンドを停止しています。 + + + Windows PowerShell ISE はデバッガーを再開しています。 + + + Windows PowerShell ISE でデバッガーを停止しています。 + + + Windows PowerShell ISE はデバッグにステップ インしています。 + + + Windows PowerShell ISE はデバッグにステップ オーバーしています。 + + + Windows PowerShell ISE はデバッグからステップ アウトしています。 + + + Windows PowerShell ISE ですべてのブレークポイントを有効にしています。 + + + Windows PowerShell ISE ですべてのブレークポイントを無効にしています。 + + + Windows PowerShell ISE ですべてのブレークポイントを削除しています。 + + + Windows PowerShell ISE は、ファイル {1} の行 #: {0} のブレークポイントを設定しています。 + + + Windows PowerShell ISE は、ファイル {1} の行 #: {0} にあるブレークポイントを削除しています。 + + + Windows PowerShell ISE は、ファイル {1} の行 #: {0} のブレークポイントを有効にしています。 + + + Windows PowerShell ISE は、ファイル {1} の行 #: {0} のブレークポイントを無効にしています。 + + + Windows PowerShell ISE で、ファイル {1} の行 #: {0} のブレークポイントに到達しました。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/EventingResources.ja.resx b/src/System.Management.Automation/resources/ja/EventingResources.ja.resx new file mode 100644 index 00000000000..9090aa1b80c --- /dev/null +++ b/src/System.Management.Automation/resources/ja/EventingResources.ja.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}' という名前のイベントは存在しません。 + + + PowerShell は、Windows RT イベントをサブスクライブできません。 + + + 指定したイベントに登録できません。イベント ソース識別子 '{0}' は PowerShell エンジン用に予約されています。 + + + この操作はリモート インスタンスではサポートされていません。 + + + イベントを転送する場合、アクションはサポートされません。 + + + 指定したイベントをサブスクライブできません。ソース識別子 '{0}' のサブスクライバーは既に存在します。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ExperimentalFeatureStrings.ja.resx b/src/System.Management.Automation/resources/ja/ExperimentalFeatureStrings.ja.resx new file mode 100644 index 00000000000..3e049509eba --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ExperimentalFeatureStrings.ja.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}' という名前に一致する試験的な機能は見つかりませんでした。 + + + 試験的な機能の有効化と無効化は、PowerShell を次回起動するまで反映されません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ExtendedTypeSystem.ja.resx b/src/System.Management.Automation/resources/ja/ExtendedTypeSystem.ja.resx new file mode 100644 index 00000000000..be4fb465e32 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ExtendedTypeSystem.ja.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + メンバー "{0}" は既に存在します。 + + + メンバー "{0}" は、拡張型データ ファイルに既に存在します。 + + + メンバー "{0}" が存在しません。 + + + "{0}" の設定で例外が発生しました: "{1}" + + + "{0}" の取得中に例外が発生しました: "{1}" + + + コレクションの列挙中に次の例外が発生しました: "{0}"。 + + + PSObject の外部では、メンバー "{0}" にアクセスできません。 + + + 型の構成から作成されたメンバー "{0}" は変更できません。 + + + メンバー名 "{0}" は予約されています。 + + + "{0}" は変更できません。 + + + "{1}" 個の引数を指定して "{0}" を呼び出し中に例外が発生しました: "{2}" + + + 型 "{1}" のオブジェクトの内容を抽出するために "{0}" を呼び出そうとしたときに例外がスローされました: "{2}" + + + "{0}" に対するオーバーロードが見つかりません。引数の数は "{1}" です。 + + + "{1}" 型パラメーターを持つ "{0}" に対する適切なジェネリック メソッドのオーバーロードが見つかりませんでした。引数の数は "{2}" です。 + + + "{0}" と引数の数 "{1}" に対して、複数のあいまいなオーバーロードが見つかりました。 + + + "{2}" の引数 "{0}" (値: "{1}") を型 "{3}" に変換できません: "{4}" + + + プロパティ "{0}" の get アクセサーは使用できません。 + + + プロパティ "{0}" の set アクセサーは使用できません。 + + + セッター メソッドは public、void、static で、2 つのパラメーターを持つ必要があります。1 つめのパラメーターは PSObject 型である必要があります。ゲッター メソッドも使用できる場合は、2 つめのパラメーターが必要で、ゲッター メソッドの戻り値の型と同じ型にする必要があります。 + + + ゲッター メソッドは public で、void ではなく、static で、PSObject 型のパラメーターを 1 つ持つ必要があります。 + + + CodeProperty では、ゲッターまたはセッター メソッドを使用する必要があります。 + + + メソッドの形式が原因で、コード メソッドを作成できません。メソッドは public、static で、PSObject 型のパラメーターを 1 つ持つ必要があります。 + + + "{0}" という名前のエイリアスには、循環が含まれています。 + + + 型 "{1}" の値 "{0}" を型 "{2}" に変換できません。 + + + 型 "{0}" の値を型 "{1}" に変換できません。 + + + 値 "{0}" を型 "{1}" に変換できません。エラー:"{2}" + + + この列挙ではコンマが許可されていないため、値 "{0}" を型 "{1}" に変換できません。 + + + 列挙値が無効なため、値 "{0}" を型 "{1}" に変換できません。次のいずれかの列挙値を指定して、再試行してください。使用可能な列挙値は "{2}" です。 + + + 列挙値が無効なため、null 値を型 "{0}" に変換できません。次のいずれかの列挙値を指定して、再試行してください。使用可能な列挙値は "{1}" です。 + + + null 値を型 "{0}" に変換できません。 + + + 値を型 "{0}" に変換できません。 エラー:"{1}" + + + 値を System.String 型に変換できません。 + + + 引数には参照型が必要です。 + + + "{0}" は IComparable ではないため、比較できません。 + + + "{0}" と "{1}" を比較できませんでした。エラー:"{2}" + + + オブジェクトの型が同じでないか、オブジェクト "{0}" が "{2}" を実装していないため、"{0}" と "{1}" を比較できません。 + + + 値 "{0}" を型 "{1}" に変換できません。少なくとも 2 つの一致 ({2}、 {3}) が見つかりましたが、この列挙では 1 つの一致しか許可されていません。 + + + 値 "{0}" を型 "{1}" に変換できません。ブール値のパラメーターには、$True、$False、1、0 などのブール値と数値のみを使用できます。 + + + "{0}" は書き込み専用プロパティであるため、プロパティ値を取得できません。 + + + "{0}" は読み取り専用プロパティです。 + + + XmlNode プロパティを設定する値として使用できるのは文字列のみであるため、"{0}" を設定できません。 + + + 一意の属性、または一意の属性を持たないリーフ ノードのみを設定できるため、"{0}" を設定できません。 + + + PSProperty オブジェクトまたは PSMethod オブジェクトをこのコレクションに追加できません。 + + + 拡張型データ ファイルの読み込み中に次のエラーが発生しました: {0} + + + 文字列の取得中に次の例外が発生しました: "{0}" + + + 型 "{1}" のフィールドまたはプロパティ "{0}" は、フィールドまたはプロパティ "{2}" と大文字と小文字の区別のみが異なります。型は共通言語仕様 (CLS) に準拠している必要があります。 + + + 型名階層の取得中に次の例外が発生しました: "{0}"。 + + + メンバー "{1}" の取得中に次の例外が発生しました: {0} + + + メンバーの取得中に次の例外が発生しました: "{0}" + + + プロパティ "{1}": "{0}" の読み取り状態の取得中に次の例外が発生しました + + + プロパティ "{1}" の書き込み状態を取得中に次の例外が発生しました: "{0}" + + + プロパティ "{1}" の型の取得中に次の例外が発生しました: "{0}" + + + プロパティ "{1}" の文字列表現を取得中に次の例外が発生しました: "{0}" + + + プロパティ "{1}" の属性を取得中に次の例外が発生しました: "{0}" + + + メソッド "{1}" の定義を取得中に次の例外が発生しました: "{0}" + + + メソッド "{1}" の文字列表現を取得中に次の例外が発生しました: "{0}" + + + パラメーター化されたプロパティ "{1}" の型を取得中に次の例外が発生しました: "{0}" + + + パラメーター化されたプロパティ "{1}" の読み取り状態を取得中に次の例外が発生しました: "{0}" + + + パラメーター化されたプロパティ "{1}" の書き込み状態を取得中に次の例外が発生しました: "{0}" + + + パラメーター化されたプロパティ "{1}" の定義を取得中に次の例外が発生しました: "{0}" + + + パラメーター化されたプロパティ "{1}" の文字列表現を取得中に次の例外が発生しました: "{0}" + + + 型 "{0}" の PSMemberInfo オブジェクトの Value プロパティを設定できません。 + + + 引数: '{0}' は {1} である必要があります。{2} を使用してください。 + + + 引数: '{0}' を {1} にすることはできません。{2} を使用しないでください。 + + + プロパティ "{0}" は見つかりませんでした。 + + + プロパティ値を取得または設定できません。"{0}" 引数は型 "{1}" または "{2}" である必要があります。 + + + オブジェクトの型が "{2}" ではなく "{1}" であるため、プロパティ "{0}" の値を設定できません。 + + + "{0}" の呼び出しで例外が発生しました: "{1}" + + + {0} は有効なクラス パスではありません。 + + + {0} は有効なパスではありません。 + + + アダプターは、プロパティ "{0}" を変更できるかどうかを判断できません。 + + + アダプターはプロパティ "{0}" が取得可能かどうかを判断できません。 + + + アダプターはプロパティ "{0}" の値を取得できません。 + + + アダプターはプロパティ "{0}" の値を設定できません。 + + + アダプターはプロパティ "{0}" の型を取得できません。 + + + アダプターは "{0}" の型階層を取得できません。 + + + アダプターは "{0}" のプロパティを取得できません。 + + + アダプターは、"{1}" のプロパティ "{0}" を取得できません。 + + + "{0}" は null 値を返しました。 + + + ''{1} オブジェクトにプロパティ '{0}' が見つかりませんでした。設定可能なプロパティは次のとおりです: {2}。 + + + ''{1} オブジェクトにプロパティ '{0}' が見つかりませんでした。設定可能なプロパティはありません。 + + + 型 "{0}" のオブジェクトは作成できません。{1} + + + オープンなジェネリック型 {0}で静的メソッドを呼び出したり、静的プロパティにアクセスしたりすることはできません。 型パラメーターを指定して、再試行してください。 たとえば、[System.Collections.Generic.HashSet``1]::CreateSetComparer() の代わりに [System.Collections.Generic.HashSet[int]]::CreateSetComparer() を使用します。 + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + 属性 "{1}" の構築中に次の例外が発生しました: "{0}" + + + 値 "{0}" を文字列配列に変換できません。 + + + 値を型 "{0}" に変換できません。この言語モードでは、コア型のみがサポートされています。 + + + ByRef に似た型 "{0}" に変換できません。ByRef に似た型は、PowerShell ではサポートされていません。 + + + ByRef に似た型 "{1}" のプロパティまたはフィールド "{0}" を取得または設定できません。ByRef に似た型は、PowerShell ではサポートされていません。 + + + ByRef に似た戻り値の型 "{1}" のメソッド "{0}" を呼び出すことはできません。ByRef に似た型は、PowerShell ではサポートされていません。 + + + ByRef に似た型 "{0}" のインスタンスを作成できません。ByRef に似た型は、PowerShell ではサポートされていません。 + + + Extended Type System Hashtable Conversion + + + HashTable から '{0}' への型変換は、ConstrainedLanguage モードでは許可されません。 + + + Extended Type System Hashtable Conversion + + + ConstrainedLanguage モードでは、'{0}' から '{1}' への型変換は許可されません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/FileSystemProviderStrings.ja.resx b/src/System.Management.Automation/resources/ja/FileSystemProviderStrings.ja.resx new file mode 100644 index 00000000000..513db782e05 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/FileSystemProviderStrings.ja.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Invoke-Item + + + 項目: {0} + + + ファイルの削除 + + + ディレクトリの削除 + + + ファイルをコピーする + + + 項目: {0} 宛先: {1} + + + ディレクトリのコピー + + + ファイル名を変更する + + + ディレクトリ名の変更 + + + 項目: {0} 宛先: {1} + + + ファイルの移動 + + + ディレクトリの移動 + + + 項目: {0} 宛先: {1} + + + プロパティ ファイルの設定 + + + プロパティ ディレクトリの設定 + + + 項目: {0} プロパティ {1}: 値: {2} + + + プロパティ ファイルをクリア + + + プロパティ ディレクトリのクリア + + + 項目: {0} プロパティ: {1} + + + ファイルの作成 + + + ディレクトリの作成 + + + 宛先: {0} + + + コンテンツのクリア + + + 項目: {0} + + + 項目 {0} が見つかりませんでした。 + + + アイテム {0} を削除できません: {1} + + + 項目 {0}の属性を復元できません: {1} + + + 指定されたパス {0} のオブジェクトは存在しません。 + + + ディレクトリ {0} は空ではないので、削除できません。 + + + この型は、ファイル システムの既知の型ではありません。"file"、"directory" または "symboliclink" のみを指定できます。 + + + 指定されたパスが basePath の外部にある項目を参照しているため、パスを処理できません。 + + + 指定されたドライブ ルート "{0}" が存在しないか、フォルダーではありません。 + + + 指定された名前 {0} の項目は既に存在します。 + + + ストリームを一度に 1 バイトずつ読み取る場合、区切り記号を指定することはできません。 + + + 項目 {0} をそれ自体で上書きすることはできません。 + + + 指定したターゲットは、パスまたはデバイス名を表しているため、名前を変更できません。 + + + プロパティ {0} が存在しないか、見つかりませんでした。 + + + この操作を実行するための十分なアクセス権がないか、項目が非表示、システム、または読み取り専用です。 + + + 属性がサポートされていないため、属性を設定できません。設定できる属性は、Archive、Hidden、Normal、ReadOnly、または System のみです。 + + + プロパティがサポートされていないため、プロパティをクリアできません。Attributes プロパティのみをクリアできます。 + + + ターゲットが予約済みデバイス名を表しているため、パス '{0}' を処理できません。 + + + エンコードは、'-AsByteStream' が指定されている場合は使用されません。 + + + バイト エンコードを続行できません。バイト エンコードを使用する場合、コンテンツはバイト型である必要があります。 + + + ファイル {0} が見つからなかったため、ファイルを処理できません。 + + + ディレクトリ: + + + ファイルのエンコードを検出できません。指定されたエンコード {0} は、コンテンツを逆方向に読み取る場合にはサポートされていません。 + + + ファイル '{1}' の代替データ ストリーム '{0}' を開けませんでした。 + + + ファイル '{1}' のストリーム '{0}'。 + + + Raw パラメーターと Wait パラメーターを同じコマンドで指定することはできません。 + + + Persist スイッチ パラメーターを使用するには、オペレーティング システムでドライブ名がサポートされている必要があります (ドライブ文字 A ~ Z など)。 + + + Persist パラメーターを使用する場合、ルートはリモート コンピューター上のファイル システムの場所である必要があります。 + + + '{0}' パラメーターと '{1}' パラメーターを同じコマンドで指定することはできません。 + + + この操作にはディレクトリが必要です。項目 '{0}' はディレクトリではありません。 + + + ジャンクションの作成 + + + シンボリック リンクの作成 + + + この操作には管理者特権が必要です。 + + + ハード リンクの作成 + + + この操作にはファイルが必要です。項目 '{0}' はファイルではありません。 + + + ハード リンクは、指定されたパスではサポートされていません。 + + + シンボリック リンクは、指定されたパスではサポートされていません。 + + + {0} を {1} にコピーしています + + + 宛先パス {0} は、ターゲットの宛先に既に存在するファイルです。 + + + ファイル {0} をリモート ターゲットのコピー先にコピーできませんでした。 + + + {0} から {1} へ + + + ディレクトリ '{0}' をファイル '{0}' にコピーできません + + + ディレクトリ {0} の子項目を取得できませんでした。 + + + リモート ファイル '{0}' を読み取ることができませんでした。 + + + リモートの宛先 {0} がファイルかどうかを検証できません。 + + + リモート宛先にディレクトリ '{0}' を作成できませんでした。 + + + ドライブの最大サイズを超えました: {0}。 + + + パスが既に存在するため、リンクを作成できません: {0}。 + + + 既にアクセス済みのディレクトリ {0} をスキップします。 + + + 宛先パスをソースのサブディレクトリまたはソース自体にすることはできません: {0}。 + + + ターゲットとパスを同じにすることはできません。 + + + {1} 個のファイルのうち {0} 個がコピーされました + + + {0}/{1} ({2:0.0} MB/秒) + + + {1} 個中 {0} 個のファイルを削除しました + + + {0}/{1} ({2:0.0} MB/秒) + + + ジャンクションを作成するには、ターゲットの絶対パスが必要です。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/FormatAndOutXmlLoadingStrings.ja.resx b/src/System.Management.Automation/resources/ja/FormatAndOutXmlLoadingStrings.ja.resx new file mode 100644 index 00000000000..f0e06dc756a --- /dev/null +++ b/src/System.Management.Automation/resources/ja/FormatAndOutXmlLoadingStrings.ja.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ファイル {1} の XPath {0} でエラーが発生しました: XML 要素 {2} では属性が許可されていません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ノード {2} に子オブジェクトを含めることはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} が無効です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 既定の {2} が少なくとも 1 つ必要です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 既定の {2} が複数存在することはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: コントロール名を null 値または空にすることはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 帯域外ビューには CustomControl または ListControl のみを含めることができます。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 帯域外ビューに GroupBy を含めることはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ビューを読み込めません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: "{2}" は有効なアラインメント値ではありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 正の整数が必要です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 列ヘッダー定義が無効です。すべてのヘッダーが破棄されます。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 行項目数 = 代替セット # {3} の{2} が、既定の行項目数 = {4} と一致しません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ヘッダー項目数 = {2} が既定の行項目数 = {3} と一致しません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 少なくとも 1 つのリスト ビュー項目を指定する必要があります。 + + + ファイル {1} の XPath {0} でエラーが発生しました: プロパティ エントリが無効です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 定義リストがありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ブール値が必要です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 負でない整数が必要です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 整数が必要です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 内部テキスト値がありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: カスタム コントロール トークン リストを空にすることはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} が読み込めませんでした。 + + + ファイル {1} の XPath {0} でエラーが発生しました。式がないと {2} を指定できません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} を式で指定することはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 書式指定文字列がありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: スクリプト ブロックのテキストがありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: プロパティがありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: スクリプト ブロック "{2}" が無効です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: アセンブリ {4} のリソース {3} から文字列 {2} が見つかりません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: アセンブリ {3} のリソース {2} が見つかりません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: アセンブリ {2} が見つかりません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ノードは XmlElement である必要があります。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 式が必要です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 式がないと、コントロールまたはラベルを持つことができません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: コントロールとラベルを同時に持つことはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: SelectionSetName と TypeName を同時に指定することはできません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ビューを適用するための型または条件が指定されていません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} 値が無効です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: 重複するノードが存在します。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} と {3} は相互に排他的です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2}、{3}、{4} は相互に排他的です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} は不明なノードです。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} は不明な属性です。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} 属性がありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ノード {2} がありません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: ノードが {2} に見つかりません。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} は空のノードです。 + + + ファイル {1} の XPath {0} でエラーが発生しました: {2} は空の属性です。 + + + ファイル {0} でエラーが発生しました: {1} + + + ファイル {0} にエラーが多すぎます。 + + + フォーマット データ ファイルの読み込み中にエラーが発生しました: {0} + + + (グローバル アセンブリ キャッシュ) {0} + + + {0}、{1} + + + パス {0} は完全修飾パスではありません。完全修飾形式のファイル パスを指定します。 + + + FormatTable が実行空間の外部に作成されている可能性があるため、FormatTable を更新できません。 + + + FormatTable の読み込み中にエラーが発生しました。"Errors" プロパティの内容を表示して、詳細なエラー メッセージを取得します。 + + + データ "{0}" の書式設定中にエラーが発生しました: {1} + + + インデックス {1} で型名 {0} のビュー データでエラーが発生しました: ヘッダー項目数 = {2} が既定の行項目数 = {3} と一致しません。 + + + インデックス {1} で型名 {0} のビュー データでエラーが発生しました: データ "{2}" の書式設定が無効です。 + + + インデックス {1} で型名 {0} のビュー データでエラーが発生しました: スクリプト ブロック "{2}" が無効です。 + + + インデックス {1} で型名 {0} のビュー データでエラーが発生しました: {2} が読み込めませんでした。 + + + インデックス {1} で型名が {0} のビュー データでエラーが発生しました: TableControl に含める {2} は 1 つだけです。 + + + インデックス {1} で型名 {0} のビュー データでエラーが発生しました: 既定の {2} が少なくとも 1 つ必要です。 + + + インデックス {1} で型名 {0} のビュー データでエラーが発生しました: 少なくとも 1 つのリスト ビュー項目を指定する必要があります。 + + + インデックス {1} で型名が {0} のビュー データでエラーが発生しました: 既定の {2} が複数存在することはできません。 + + + 型 "{0}" の書式設定データにエラーが多すぎます。 + + + 共有フォーマット テーブルを複数のエントリで更新することはできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/FormatAndOut_MshParameter.ja.resx b/src/System.Management.Automation/resources/ja/FormatAndOut_MshParameter.ja.resx new file mode 100644 index 00000000000..f6b00af0cde --- /dev/null +++ b/src/System.Management.Automation/resources/ja/FormatAndOut_MshParameter.ja.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 + + + {0} を次のいずれかの型に変換できません: {1}。 + + + パラメーターの値が null でした。次のいずれかの型が必要です: {0}。 + + + 重複したキー "{0}" が "{1}" と競合しています。 + + + "{0}" キーの型 {1} は無効です。想定される型は {2} です。 + + + "{0}" キーの型 {1} は無効です。想定される型は {2} です。 + + + {0} キーがあいまいです。{1} と {2} が競合しています。 + + + キーの値を null にすることはできません。 + + + {0} キーの型が無効です。キーは文字列である必要があります。 + + + {0} キーに値がありません。 + + + {0} の必須エントリがありません。 + + + {0} キーが無効です。 + + + キー "{1}" の値 "{0}" が無効です。有効な値は {2} です。 + + + キー "{1}" の値 "{0}" は 0 より大きくする必要があります。 + + + キー "{0}" の書式設定文字列は空にできません。 + + + "{0}" キーに空の文字列値を指定することはできません。 + + + 空の文字列値は使用できません。 + + + "{0}" キーの値 "{1}" にワイルドカード文字を含めることはできません。 + + + ワイルドカード文字は "{0}" では使用できません。 + + + EnumerableExpansion 値は無効です。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/FormatAndOut_format_xxx.ja.resx b/src/System.Management.Automation/resources/ja/FormatAndOut_format_xxx.ja.resx new file mode 100644 index 00000000000..8cbdf8e2c6d --- /dev/null +++ b/src/System.Management.Automation/resources/ja/FormatAndOut_format_xxx.ja.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + コマンドレット パラメーター View と Property は相互に排他的です。 + + + コマンドレット パラメーター AutoSize と Column は相互に排他的です。 + + + ビュー名 {0} が見つかりません。 + + + ビュー名 {0} が {1} の書式設定に見つかりません。 + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + {1} オブジェクトの既存の {0} ビューはありません。 + + + ビュー名 {0} が見つかりません。次のいずれかの {1} ビューを指定して、もう一度お試しください: {2}。 + + + 次のいずれかの形式のコマンドレットを使用してみてください: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + 次のオブジェクトは IEnumerable をサポートしています: + + + IEnumerable にオブジェクトが含まれていない。 + + + IEnumerable には、次のオブジェクトが含まれています: + + + IEnumerable には、次の {0} オブジェクトが含まれています: + + + クラス ID {0}が不明です。 + + + プロパティ {1} の型 {0} が無効です。 + + + {0} データ メンバーの値を null 値にすることはできません。 + + + オブジェクトの種類が認識されません。 + + + クラス ID {0} のオブジェクトを作成できませんでした。 + + + {0} プロパティは再帰的です。 + + + 式 "{0}" を評価できませんでした。 + + + 書式指定文字列 "{0}" を解釈できませんでした。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/FormatAndOut_out_xxx.ja.resx b/src/System.Management.Automation/resources/ja/FormatAndOut_out_xxx.ja.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/FormatAndOut_out_xxx.ja.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/GetErrorText.ja.resx b/src/System.Management.Automation/resources/ja/GetErrorText.ja.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/GetErrorText.ja.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/HelpDisplayStrings.ja.resx b/src/System.Management.Automation/resources/ja/HelpDisplayStrings.ja.resx new file mode 100644 index 00000000000..3bd51be3ea8 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/HelpDisplayStrings.ja.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 名前 + + + 概要 + + + 説明 + + + 構文 + + + パラメーター + + + 入力 + + + 出力 + + + 強制終了になるエラー + + + 終了しないエラー + + + + + + + + + + + + + + + 出力 + + + 関連リンク + + + 概要 + + + タイトル: + + + 質問: + + + 回答 + + + 期間: + + + 定義: + + + 内容: + + + プロバイダー名 + + + このコマンドレットは、次の共通パラメーターをサポートしています: Verbose、Debug、 + ErrorAction、ErrorVariable、WarningAction、WarningVariable、 + OutBuffer、PipelineVariable、OutVariable。詳細については、次を参照してください + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216)。 + + + 必要ですか? + + + 位置は? + + + 型: + + + ターゲット オブジェクトの型 + + + 既定値 + + + パイプライン入力の受け入れますか? + + + ワイルドカード文字を受け入れますか? + + + (カテゴリ: + + + 提案されているアクション: + + + 詳細については、次のように入力してください: + + + 技術情報については、次のように入力してください: + + + 例を表示するには、次のように入力してください: + + + オンライン ヘルプについては、次のように入力してください: + + + <CommonParameters> + + + 注釈 + + + true + + + 名前付き + + + DRIVES + + + 機能 + + + タスク + + + タスク: + + + フィルター + + + 動的パラメーター + + + サポートされているコマンドレット: + + + 別名 + + + Get-Help は、このコンピューター上でこのコマンドレットのヘルプ ファイルを見つけることができません。部分的なヘルプのみを表示しています。 + -- このコマンドレットを含むモジュールのヘルプ ファイルをダウンロードしてインストールするには、Update-Help を使用してください。 + -- このコマンドレットのヘルプ トピックをオンラインで表示するには、"Get-Help {0} -Online" と入力するか、 + {1} へ移動してください。 + + + なし + + + Aliases + + + Dynamic? + + + パラメーター セット名 + + + UI カルチャ {0} の HelpInfo XML ファイルを取得できません。モジュール マニフェストの HelpInfoUri プロパティが有効であることを確認するか、ネットワーク接続を確認してからコマンドを再試行してください。 + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + 指定されたカルチャはサポートされていません: {0}。次の一覧からカルチャを指定してください: {{{1}}}。 + + + エラーを延期し、フォールバック カルチャを試行すると、すべてのフォールバックがサポートされていない場合はエラーとして表示されます: +{0} + + + ModuleBase ディレクトリが見つかりません。ディレクトリを確認して、もう一度やり直してください。 + + + パス {0} は有効なディレクトリではありません。ディレクトリが存在することを確認してから、再試行してください。 + + + ヘルプ URI には、10 個を超えるリダイレクトを含めることはできません。有効なヘルプ URI を指定してください。 + + + ヘルプの更新 + + + ヘルプ コンテンツに接続しています... + + + ヘルプ コンテンツをダウンロードしています... + + + ヘルプ コンテンツをインストールしています... + + + ヘルプ コンテンツを検索しています... + + + (すべて) + + + 次のパターンに一致する PowerShell モジュールが見つかりませんでした: {0}。パターンを確認してから、コマンドを再試行してください。 + + + 指定された FullyQualifiedModule {0}に一致する PowerShell モジュールが見つかりませんでした。FullyQualifiedModule 値を確認してから、コマンドを再試行してください。 + + + ヘルプ コンテンツが見つかりません。サーバーが使用可能であり、ヘルプ コンテンツの場所が HelpInfo XML で正しく定義されていることを確認してください。 + + + 指定されたモジュールが更新可能なヘルプをサポートしていないため、Update-Help コマンドが失敗しました。Get-Help -Online を使用するか、このモジュールのコマンドのヘルプをオンラインで検索してください。 + + + 次のパラメーターを null または空にすることはできません: Module。 + + + 次のパラメーターを null または空にすることはできません: Path。 + + + Update-Help が正常に完了しました。 + + + ヘルプ コンテンツの抽出中にエラーが発生しました。 + + + ヘルプ コンテンツに接続できません。ヘルプ コンテンツが保存されているサーバーが使用できない可能性があります。サーバーが使用可能であることを確認するか、サーバーがオンラインに戻るまで待ってから、コマンドを再試行してください。 + + + 指定した場所のヘルプ コンテンツが無効です。有効なヘルプ コンテンツを含む場所を指定してください。 + + + HelpInfo XML が無効です。有効な HelpInfo XML を指定してください。 + + + ヘルプ コンテンツが次の場所に正常に保存されました: {0} + + + ヘルプ コンテンツ XSD ファイルが {0} で見つかりませんでした。指定した場所に XSD ファイルが存在することを確認してから、コマンドを再試行してください。 + + + 次のモジュールのヘルプを更新できませんでした: +'{0}' +{1} + + + ヘルプの保存 + + + ヘルプ コンテンツに無効なファイルが含まれています。.txt ファイルと.xml ファイルのみがサポートされています。 + + + モジュール '{0}' のヘルプを保存できませんでした: {1} + + + UI カルチャ {{{1}}} でモジュール '{0}' のヘルプを保存できませんでした: {2}。 +英語 (米国) のヘルプ コンテンツが利用でき、Save-Help -UICulture en-US を使用して保存できます。 + + + UI カルチャ {{{1}}} でモジュール '{0}' のヘルプを更新できませんでした: {2}。 +英語 (米国) のヘルプ コンテンツが利用でき、Update-Help -UICulture en-US を使用してインストールできます。 + + + 現在のカルチャは ({0}) であり、どの言語にも関連付けられていないため、システム カルチャを変更するか、Update-Help -UICulture en-US を使用して英語 (米国) のヘルプ コンテンツをインストールすることを検討してください。 + + + false + + + -Recurse パラメーターは、ソース パスが指定されている場合にのみ使用できます。 + + + {0} パスに FileSystem プロバイダーが含まれていません。指定したパスに FileSystem プロバイダーが含まれていることを確認してから、コマンドを再試行してください。 + + + {0} のヘルプを検索しています... + + + 次のパターンに一致する UI カルチャが見つかりませんでした: {0}。パターンを確認してから、コマンドを再試行してください。 + + + このコンピューターで過去 24 時間以内に Save-Help コマンドが実行されたため、モジュール {0} のヘルプは保存されませんでした。 +ヘルプをもう一度保存するには、Force パラメーターをコマンドに追加してください。 + + + このコンピューターで Update-Help コマンドが過去 24 時間以内に実行されたため、モジュール {0} のヘルプは更新されませんでした。 +ヘルプをもう一度更新するには、Force パラメーターをコマンドに追加してください。 + + + 最新のヘルプ ファイルが既にインストールされています。 + + + {0}: {1}。カルチャ {2} バージョン {3} + + + {0} を更新しました + + + モジュール マニフェストの HelpInfoUri キーの値は、ヘルプ ファイルが格納されている Web サイトのコンテナーまたはルート URL に解決する必要があります。HelpInfoUri '{0}' はコンテナーに解決されません。 + + + ヘルプ コンテンツは名前空間 {0} に含まれている必要があります。 + + + Get-Help は、このコンピューター上でこのコマンドレットのヘルプ ファイルを見つけることができません。部分的なヘルプのみを表示しています。 + -- このコマンドレットを含むモジュールのヘルプ ファイルをダウンロードしてインストールするには、Update-Help を使用してください。 + + + 最新のヘルプ ファイルが既にダウンロードされています。 + + + {0} を保存しました + + + HelpInfoURI {0} は HTTP で始まっていません。 + + + ヘルプ コンテンツのルート レベル要素は "helpItems" である必要があります。 + + + モジュール {0} のヘルプを保存しています + + + モジュール {0} のヘルプを更新しています + + + URI: "{0}" を解決中です + + + ヘルプ URI: {0} + + + {0}、現在のバージョン: {1}、使用可能なバージョン: {2}、UICulture: {3} + + + プロパティ + + + メソッド + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/HelpErrors.ja.resx b/src/System.Management.Automation/resources/ja/HelpErrors.ja.resx new file mode 100644 index 00000000000..593bdd7c41e --- /dev/null +++ b/src/System.Management.Automation/resources/ja/HelpErrors.ja.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help は、このセッションのヘルプ ファイルで {0} を見つけることができませんでした。更新されたヘルプ トピックをダウンロードするには、「Update-Help」と入力してください。オンラインでヘルプを入手するには、TechNet ライブラリのヘルプ トピック (https://go.microsoft.com/fwlink/?LinkID=107116) を検索します。 + + + "{0}" は有効なヘルプ カテゴリではないため、ヘルプ カテゴリを処理できません。 + + + ヘルプ ファイル "{0}" を読み込めません。詳細: {1}。 + + + 現在のユーザーにはファイルへのアクセス権がないため、ヘルプ ファイル "{0}" にアクセスできません。詳細: {1}。 + + + ヘルプ ファイル "{0}" は有効な XML ドキュメントではありません。詳細: {1}。 + + + ファイル {1} から {0} のヘルプ コンテンツを読み込み中にエラーが発生しました。詳細: {2}。更新されたヘルプ トピックをダウンロードするには、Update-Help コマンドレットを実行します。オンラインでヘルプを入手するには、TechNet ライブラリのヘルプ トピック (https://go.microsoft.com/fwlink/?LinkID=107116) を検索します。 + + + プロバイダー "{0}" を読み込めません。詳細: {1}。 + + + ヘルプ ファイルを読み込めません。ヘルプ ファイル " {0} " の読み込み中に次の {1} エラーが発生しました。 + + + ノード "{0}" に子ノードとして "{1}" を指定することはできません。ノード パス: {2}。 + + + ノード "{0}" には、"{1}" 型の {2} 個の子ノードの最大数を指定できます。ノード パス: {3}。 + + + レジストリ キー "{0}{1}" が見つかりません。"{2}" を使用してヘルプ ファイルを読み込んでいます。 + + + 条件 {0} に一致するパラメーターはありません。 + + + {0} は、要求されたヘルプ カテゴリではサポートされていません。 + + + ヘルプ トピックのインターネット アドレス (URI) がコマンド コードまたはコマンドのヘルプ ファイルに指定されていないため、このヘルプ トピックのオンライン バージョンを表示できません。 + + + 指定された URI {0} は無効です。 + + + ブラウザーを起動してオンライン ヘルプを表示できませんでした。URI {0} を開くために関連付けられているプログラムまたはブラウザーはありません。 + + + URI "{0}" で指定されたプロトコルはサポートされていません。"{1}" プロトコルと "{2}" プロトコルのみがサポートされています。 + + + 複数のヘルプ トピックが見つかりました。"{0}" オプションで使用するヘルプ トピックは 1 つだけです。 + + + 実行空間が開かないため、リモート実行空間からヘルプを取得できません。 暗黙的なリモート処理コマンドを実行して実行空間を開き、コマンドを実行してヘルプをもう一度取得してください。 + + + アクセスは拒否されました。コマンドは、PowerShell コア モジュールのヘルプ トピック、または $pshome\Modules ディレクトリ内のモジュールのヘルプ トピックを更新できませんでした。 +これらのヘルプ トピックを更新するには、"Run as Administrator" コマンドを使用して PowerShell を起動し、Update-Help をもう一度実行してみてください。 + + + {0} を使用するには、アプリケーションがプロジェクト SDK として 'Microsoft .NET.Sdk.WindowsDesktop' を使用し、対応するアセンブリ 'Microsoft.PowerShell.GraphicalHost' が使用可能であることを確認します。({1}) + + + {0} はリモート セッションでは機能しません。 + + + ForwardHelpTargetName は当関数自体を参照できません。 + + + 制限されたセッションでは、ネットワークの場所からヘルプを取得できません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/HistoryStrings.ja.resx b/src/System.Management.Automation/resources/ja/HistoryStrings.ja.resx new file mode 100644 index 00000000000..d1ef7a35f05 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/HistoryStrings.ja.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} は、履歴の ID として有効な値ではありません。正の数を指定して、もう一度お試しください。 + + + ID {0} の履歴が見つかりません。 + + + カウントを複数の ID と組み合わせることはできません。 + + + コマンド ライン {0} の履歴が見つかりません。 + + + 最新の履歴が見つかりません。 + + + Invoke-History コマンドレットが、ループから繰り返し呼び出されています。 + + + 複数の履歴コマンドは処理できません。Invoke-History を使用して実行できるコマンドは 1 つのみです。 + + + 入力オブジェクトの形式が無効なため、履歴を追加できません。 + + + ID {0} は無効です。正の数を指定して、もう一度お試しください。 + + + このコマンドは、セッション履歴のすべてのエントリをクリアします。 + + + カウントを複数の CommandLine パラメーターと組み合わせることはできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/HostInterfaceExceptionsStrings.ja.resx b/src/System.Management.Automation/resources/ja/HostInterfaceExceptionsStrings.ja.resx new file mode 100644 index 00000000000..4efbaa312b9 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/HostInterfaceExceptionsStrings.ja.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 + + + "{0}" の種類のエラーが発生しました。 + + + ホスト プログラムまたはコマンドの種類がユーザーによる操作をサポートしていないため、ユーザーにプロンプトを表示するコマンドが失敗しました。ユーザーによる操作をサポートするホスト プログラム (PowerShell コンソールなど) を試し、ユーザーによる操作をサポートしていないコマンドの種類からプロンプト関連のコマンドを削除してください。 + + + ホスト プログラムまたはコマンドの種類がユーザーによる操作をサポートしていないため、ユーザーにプロンプトを表示するコマンドが失敗しました。ホストは、次のメッセージを使用して確認を要求しようとしました: {0} + + + プールが閉じられているか、失敗したため、メソッドを呼び出すことができません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/InternalCommandStrings.ja.resx b/src/System.Management.Automation/resources/ja/InternalCommandStrings.ja.resx new file mode 100644 index 00000000000..377a1f19d70 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/InternalCommandStrings.ja.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched methods. Possible matches include:{1}. + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched members. Possible matches include:{1}. + + + Retrieve the value for key '{0}' + + + Invoke method '{0}' with arguments: {1} + + + Invoke method '{0}' + + + Retrieve the value for property '{0}' + + + InputObject: {0} + + + Cannot operate on a 'null' input object. + + + Input name "{0}" cannot be resolved to a method. + + + Cannot invoke a method in the restricted language mode. + + + The -WhatIf and -Confirm parameters are not supported for script blocks. + + + The '{0}' operation is not allowed in the RestrictedLanguage mode. + + + An operator is required to compare the two specified values. Include a valid operator in the command, and then try the command again. For example, Get-Process | Where-Object -Property Name -eq Idle + + + The input name "{0}" cannot be resolved to a property. + + + The input name "{0}" cannot be resolved to a member. + + + The specified operator requires both the -Property and -Value parameters. Provide values for both parameters, and then try the command again. + + + This method cannot be run on the current thread. It can only be called on the cmdlet thread. + + + A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + A ForEach-Object -Parallel piped input object cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + The 'TimeoutSeconds' parameter cannot be used with the 'AsJob' parameter. + + + The following common parameters are not currently supported in the Parallel parameter set: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/InternalHostStrings.ja.resx b/src/System.Management.Automation/resources/ja/InternalHostStrings.ja.resx new file mode 100644 index 00000000000..a172f1a2b22 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/InternalHostStrings.ja.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 + + + EnterNestedPrompt は ExitNestedPrompt ほど頻繁に呼び出されていません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/InternalHostUserInterfaceStrings.ja.resx b/src/System.Management.Automation/resources/ja/InternalHostUserInterfaceStrings.ja.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/ja/InternalHostUserInterfaceStrings.ja.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/Logging.ja.resx b/src/System.Management.Automation/resources/ja/Logging.ja.resx new file mode 100644 index 00000000000..98e3330dfde --- /dev/null +++ b/src/System.Management.Automation/resources/ja/Logging.ja.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + 不明 + + + 構成ファイルで宣言されたエンジンの試験的機能 '{0}' は、現在の PowerShell に登録されていません。 + + + 構成ファイルで宣言された試験的機能 '{0}' が無効です。 +試験的な機能の名前は、次の規則に従う必要があります: + エンジン機能名: 'PS[FeatureName]' + モジュール機能名: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/Metadata.ja.resx b/src/System.Management.Automation/resources/ja/Metadata.ja.resx new file mode 100644 index 00000000000..dbe37b15bca --- /dev/null +++ b/src/System.Management.Automation/resources/ja/Metadata.ja.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + "{0}" の属性を初期化できません: "{1}" + + + 引数の型 "{0}" がパラメーターの最大および最小制限と同じ型 ({1}) ではないため、引数を検証できません。引数の型が {1} であることを確認してから、コマンドを再試行してください。 + + + 引数 "{0}" の値が 0 以下であるため、検証できません。 + + + 引数 "{0}" の値が 0 以上でないため、検証できません。 + + + 引数 "{0}" の値が 0 以下でないため、検証できません。 + + + 引数 "{0}" の値が 0 以下でないため、検証できません。 + + + 指定された最小範囲 ({0}) は、指定された最大範囲 ({1}) と同じ型ではないため、受け入れられません。パラメーターの ValidateRange 属性を更新してください。 + + + MaxRange および MinRange パラメーター型を受け入れることはできません。どちらのパラメーターも、IComparable インターフェイスを実装するオブジェクトである必要があります。 + + + 指定された最大範囲は、指定された最小範囲より小さいため受け入れられません。パラメーターの ValidateRange 属性を更新してください。 + + + {0} 引数が {1}の最大許容範囲を超えています。{1} 以下の引数を指定してから、コマンドを再試行してください。 + + + {0} 引数が {1}の最小許容範囲を下回っています。{1} 以上の引数を指定してから、コマンドを再試行してください。 + + + 引数 "{0}" が "{1}" パターンと一致しません。"{1}" と一致する引数を指定して、コマンドを再試行してください。 + + + ValidateCount 属性を配列以外のパラメーターに適用することはできません。パラメーターから属性を削除するか、パラメーターを配列パラメーターにしてください。 + + + パラメーターには正確に {0} 個の値が必要ですが、{1} 個の値が指定されました。 + + + パラメーターには少なくとも {0} 個の値が必要であり、{1} 個以下である必要があります。{2} 個の値が指定されました。 + + + パラメーターに指定された引数の最大数が、指定された引数の最小数より少なくなっています。パラメーターの ValidateCount 属性を更新してください。 + + + 引数の指定された最大文字数が、指定された最小引数文字の長さよりも短くなっています。パラメーターの ValidateLength 属性を更新してください。 + + + ValidateLength 属性は、文字列または string[] パラメーターではないパラメーターには適用できません。パラメーターを文字列または string[] パラメーターにしてください。 + + + 引数の文字の長さ ({1}) が短すぎます。長さが "{0}" 以上の引数を指定してから、コマンドを再試行してください。 + + + 引数の文字数 ({1}) が長すぎます。長さが "{0}" 以下の引数を指定してから、コマンドを再試行してください。 + + + 引数 "{0}" は ValidateSet 属性で指定されたセット "{1}" に属していません。セットでに属する引数を指定してから、コマンドを再試行してください。 + + + 有効な値ジェネレーターは null 値を返します。 + + + プロパティ "{1}" で "{0}" が失敗しました {2} + + + コマンドを取得または実行できません。このコマンドのパラメーター セットの最大数を超えました。 + + + 引数の値が文字列ではないため、引数を処理できません。ArgumentTransformationAttribute が指定されているパラメーター引数の値は文字列である必要があります。 + + + 値 {1} が {0} 変数の有効な値ではないため、変数を検証できません。 + + + 値が {1} の変数 {0} が無効になるため、属性を追加できません。 + + + 引数が null です。引数に有効な値を指定してから、コマンドを再実行してください。 + + + 引数に null 値が含まれているか、引数コレクションの要素に null 値が含まれています。null 値を含まないコレクションを指定してから、コマンドを再試行してください。 + + + 引数が null か空です。null または空でない引数を指定して、コマンドを再度実行してください。 + + + 引数が null または空であるか、引数コレクションの要素に null 値が含まれています。null 値を含まないコレクションを指定してから、コマンドを再試行してください。 + + + 引数が null、空、または空白文字のみで構成されています。空白文字以外の文字を含む引数を指定してから、コマンドを再試行してください。 + + + 引数コレクションの要素が null、空、または空白文字のみで構成されています。これらの値を含まないコレクションを指定してから、コマンドを再試行してください。 + + + '{0}' という名前のパラメーターがコマンドに対して複数回定義されました。 + + + '{0}' という名前のエイリアスがコマンドに対して既に複数回定義されているため、パラメーター エイリアスを指定できません。 + + + パラメーター '{0}' は、パラメーター '{1}' の同じ名前のパラメーター エイリアスと競合しているため、指定できません。 + + + 値が "{0}" の引数の "{1}" 検証スクリプトは True の結果を返しませんでした。検証スクリプトが失敗した理由を特定してから、コマンドを再試行してください。 + + + "{0}" 引数に有効な PowerShell バージョンが含まれていません。有効なバージョン番号を指定してから、コマンドを再試行してください。 + + + 引数 '{0}' は有効な変数名ではないため、検証できません。 + + + ジョブ変換の型は、IAstToScriptBlockConverter から派生する必要があります。 + + + path 引数が無効です。文字列型の path 引数を指定してください。 + + + パス引数ドライブ {0} は、承認済みドライブのセット: {1} に属していません。承認済みドライブにパス引数を指定してください。 + + + path 引数に無効な文字が含まれています。 + + + path 引数にルート ドライブがありません。 ルート ドライブを含む完全なパスを指定してください。 + + + パラメーター '{0}' の引数値を null または空の文字列にすることはできません。 + + + Enum メンバー '{0}' は、パラメーター '{1}' の有効な値ではありません。次のいずれかのメンバーを指定して、もう一度お試しください: {2}。 + + + 入力を処理できません。引数 "{0}" は信頼されていません。 + + + ValidateTrustedData 属性チェック エラー + + + パラメーター引数 '{0}' は信頼されていないため、制約言語モードでの ValidateTrustedData パラメーター属性のチェックに失敗します。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/MiniShellErrors.ja.resx b/src/System.Management.Automation/resources/ja/MiniShellErrors.ja.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/MiniShellErrors.ja.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/Modules.ja.resx b/src/System.Management.Automation/resources/ja/Modules.ja.resx new file mode 100644 index 00000000000..6409912cf99 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/Modules.ja.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 指定されたモジュール '{0}' は、モジュール ディレクトリに有効なモジュール ファイルが見つからなかったため読み込まれませんでした。 + + + バージョン '{1}' で指定されたモジュール '{0}' は、モジュール ディレクトリに有効なモジュール ファイルが見つからなかったため読み込まれませんでした。 + + + 指定された MaximumVersion '{0}' が正しくありません。'*' を使用している場合、MaximumVersion は 1 つの '*' のみをサポートし、常に MaximumVersion の末尾に配置する必要があります。 + + + MinimumVersion '{1}' で指定されたモジュール '{0}' は、モジュール ディレクトリに有効なモジュール ファイルが見つからなかったため読み込まれませんでした。 + + + MinimumVersion '{1}' および MaximumVersion '{2}' で指定されたモジュール '{0}' は、モジュール ディレクトリに有効なモジュール ファイルが見つからなかったため読み込まれませんでした。 + + + MinimumVersion '{0}' は MaximumVersion '{1}'より大きくすることはできません。 + + + アセンブリ '{0}' は読み込まれませんでした。その名前のアセンブリが見つかりませんでした。アセンブリ名を確認してから、もう一度やり直してください。 + + + モジュール マニフェスト '{2}' のフィールド '{1}' にリストされている '{0}' を処理するモジュールは、モジュール ディレクトリに有効なモジュールが見つからなかったため、処理されませんでした。 + + + -AsCustomObject パラメーターはスクリプト モジュールでのみ使用できるため、モジュール '{0}' に対してカスタム オブジェクトが返されませんでした。 + + + モジュール マニフェスト '{0}' は有効な PowerShell モジュール マニフェスト ファイルではないため、処理できませんでした。許可されていない要素を削除します: {1} + + + モジュール マニフェスト ファイル '{0}' を処理しても、有効なマニフェスト オブジェクトが生成されませんでした。有効な PowerShell モジュール マニフェストを含むようにファイルを更新してください。有効なマニフェストは、New-ModuleManifest コマンドレットを使用して作成できます。 + + + '{0}' モジュールは、マニフェストに無効なメンバーが 1 つ以上含まれているため、インポートできません。有効なマニフェスト メンバーは ({1}) です。無効なメンバー ({2}) を削除してから、モジュールのインポートを再試行してください。 + + + モジュールを記述するハッシュタグに 1 つ以上の無効なメンバーが含まれています。有効なメンバーは ({0}) です。無効なメンバー ({1}) を削除してから、もう一度やり直してください。 + + + モジュールの入れ子の制限を超えたため、モジュール '{0}' を読み込めません。モジュールは、{1} レベルにのみ入れ子にできます。モジュールを読み込む順序を評価して変更し、入れ子の制限を超えないようにしてから、スクリプトを再実行してください。 + + + メンバー 'ModuleVersion' はモジュール マニフェストに存在しません。このメンバーは存在する必要があり、'n.n.n.n' という形式のバージョン番号が割り当てられている必要があります。見つからないメンバーをファイル '{0}' に追加してください。 + + + モジュール マニフェスト ファイル '{2}' のメンバー '{0}' が無効です: {1} + + + モジュール '{1}' のバージョン '{0}' は、必要な最小バージョン '{2}' を満たしていません。バージョン番号がサポートされていることを確認してから、モジュールの読み込みを再試行してください。 + + + このコンピューターの PowerShell のバージョンは '{0}' です。モジュール '{1}' を実行するには、PowerShell の最小バージョン '{2}' が必要です。最低限必要なバージョンの PowerShell がインストールされていることを確認してから、もう一度やり直してください。 + + + モジュール マニフェスト メンバー 'NestedModules' は、'ModuleToProcess' メンバーがバイナリ モジュールの場合は使用できません。'{0}' でモジュール マニフェスト ファイルを編集してから、もう一度やり直してください。 + + + モジュール マニフェストのメンバー '{0}' が無効です: {1}。'{2}' ファイルのこのフィールドに有効な値が指定されていることを確認します。 + + + モジュール マニフェスト パス '{0}' が無効です。"Path" 引数の値は、拡張子が '.psd1' の 1 つのファイルに解決される必要があります。有効な psd1 ファイルを指すように "Path" 引数の値を変更してから、もう一度やり直してください。 + + + モジュール マニフェスト '{0}' の ModuleVersion キーは、'{2}' のバージョン フォルダー名と一致しないモジュール バージョン '{1}' を指定します。バージョン フォルダー名と一致するように ModuleVersion キーの値を変更します。 + + + モジュール マニフェスト '{1}' で指定された NestedModule エントリ '{0}' が無効です。有効な値でこのエントリを更新した後、もう一度お試しください。 + + + モジュール マニフェスト '{1}' で指定された RequiredAssemblies エントリ '{0}' が無効です。有効な値でこのエントリを更新した後、もう一度お試しください。 + + + モジュール マニフェスト '{1}' で指定された FileList エントリ '{0}' が無効です。有効な値でこのエントリを更新した後、もう一度お試しください。 + + + モジュール マニフェスト '{1}' で指定された RequiredModules エントリ '{0}' が無効です。有効な値でこのエントリを更新した後、もう一度お試しください。 + + + モジュール マニフェスト '{1}' で指定された ModuleList エントリ '{0}' が無効です。有効な値でこのエントリを更新した後、もう一度お試しください。 + + + モジュール マニフェスト '{0}' は、PowerShell バージョン '5.1' 以降でのみサポートされている CompatiblePSEditions キーで指定されています。PowerShellVersion キーの値を '5.1' 以上に更新してから、もう一度やり直してください。 + + + CompatiblePSEditions に指定された値 '{0}' に重複する PowerShell Edition 名が含まれています。重複する PowerShell Edition 名を削除した後、もう一度お試しください。 + + + ModuleVersion キーで指定されたバージョンは、バージョン フォルダー名と同じです。 + + + 有効なモジュール マニフェスト ファイルがないため、[モジュール {1}] の [バージョン] フォルダー {0} をスキップしています。 + + + 'ModuleName' メンバーは、このモジュールを記述するハッシュテーブルに存在しません。 + + + 'ModuleVersion' メンバー、'MaximumVersion' メンバー、'RequiredVersion' メンバーは、このモジュールを記述するハッシュテーブルに存在しません。これら 3 つのメンバーのいずれかが存在し、'n.n.n.n' という形式のバージョン番号が割り当てられている必要があります。 + + + 必要なモジュール '{1}' が読み込まれていません。モジュールを読み込むか、ファイル '{0}' の 'RequiredModules' からモジュールを削除します。 + + + GUID '{2}' の必要なモジュール '{1}' は読み込まれていません。モジュールを読み込むか、ファイル '{0}' の 'RequiredModules' からモジュールを削除します。 + + + バージョン '{2}' の必要なモジュール '{1}' は読み込まれていません。モジュールを読み込むか、ファイル '{0}' の 'RequiredModules' からモジュールを削除します。 + + + MaximumVersion '{2}' の必要なモジュール '{1}' は読み込まれていません。モジュールを読み込むか、ファイル '{0}' の 'RequiredModules' からモジュールを削除します。 + + + MinimumVersion '{2}' および MaximumVersion '{3}' の必須モジュール '{1}' は読み込まれていません。モジュールを読み込むか、ファイル '{0}' の 'RequiredModules' からモジュールを削除します。 + + + モジュール '{0}' が ModuleVersion '{1}' で見つかりません。 + + + RequiredVersion '{1}' のモジュール '{0}' が見つかりません。 + + + モジュール '{0}' が MaximumVersion '{1}' で見つかりません。 + + + ModuleVersion '{1}' および MaximumVersion '{2}' のモジュール '{0}' が見つかりません。 + + + モジュール '{0}' が見つかりません。 + + + モジュールは削除されませんでした。削除するモジュールの仕様が正しいことと、それらのモジュールが実行空間に存在することを確認してください。 + + + モジュール '{1}' からインポートされた '{0}' メンバーは、次の理由により削除できません: {2} + + + モジュール '{0}' は読み取り専用であるため、削除できません。Force パラメーターをコマンドに追加して、読み取り専用モジュールを削除します。 + + + モジュール '{0}' は 'constant' としてマークされているため、削除できません。モジュールが 'constant' とマークされている場合、モジュールを削除できません。 + + + モジュール '{0}' は '{1}' で必要なため削除できません。Force パラメーターをコマンドに追加して、このモジュールを削除します。 + + + Export-ModuleMember コマンドレットは、モジュール内からのみ呼び出すことができます。 + + + 拡張機能 '{0}' は有効なモジュール拡張機能ではありません。サポートされているモジュール拡張機能は、'.dll'、'.ps1'、'.psm1'、'.psd1'、.cdxml' です。拡張子を修正してから、ファイル '{1}' をもう一度追加してみてください。 + + + この操作はバイナリ モジュールでは実行できません。スクリプト モジュールでのみ実行できます。 + + + ファイル '{0}' には拡張子 '.ps1' がないため、使用できません。 + + + 不明 + + + (c) {0}.All rights reserved. + + + インポートされた "{0}" 関数を削除しています。 + + + インポートされた "{0}" エイリアスを削除しています。 + + + インポートされた "{0}" 変数を削除しています。 + + + パス '{0}' からモジュールを読み込んでいます。 + + + '{0}' をパス '{1}' から読み込んでいます。 + + + スクリプト ファイル '{0}' をドットソーシングしています。 + + + 関数 '{0}' をインポートしています。 + + + コマンドレット '{0}' をインポートしています。 + + + エイリアス '{0}' をインポートしています。 + + + 変数 '{0}' をインポートしています。 + + + コマンドレット '{0}' をエクスポートしています。 + + + 関数 '{0}' をエクスポートしています。 + + + エイリアス '{0}' をエクスポートしています。 + + + 変数 '{0}' をエクスポートしています。 + + + モジュール '{0}' からインポートされたコマンドの名前には、検出不能になる可能性のある未承認の動詞が含まれています。未承認の動詞を含むコマンドを見つけるには、Verbose パラメーターを指定して Import-Module コマンドをもう一度実行します。承認された動詞の一覧については、「Get-Verb」と入力します。 + + + '{1}' モジュールの '{0}' コマンドがインポートされましたが、その名前に承認済みの動詞が含まれていないため、見つけにくい場合があります。承認された動詞の一覧については、「Get-Verb」と入力します。 + + + '{2}' モジュールの '{0}' コマンドがインポートされましたが、その名前に承認済みの動詞が含まれていないため、見つけにくい場合があります。推奨される代替動詞は "{1}" です。 + + + 一部のインポートされたコマンド名には、次の制限文字が 1 つ以上含まれています: # , ( ) {{ }} [ ] & - / \ $ ^ ;: " ' < > | ?@ ` * % + = ~ + + + モジュール '{1}' のコマンド名 '{0}' には、次の制限文字が 1 つ以上含まれています: # , ( ) {{ }} [ ] & - / \ $ ^ ;: " ' < > | ?@ ` * % + = ~ + + + "{0}" モジュール マニフェスト ファイルを作成しています。 + + + {0} (パス: '{1}') + + + 現在のプロセッサ アーキテクチャは {0} です。モジュール '{1}' には、次のアーキテクチャが必要です: {2}。 + + + 現在の PowerShell ホストの名前は '{0}' です。モジュール '{1}' には、次の PowerShell ホストが必要です: '{2}'。 + + + 現在の PowerShell ホストは '{0}' (バージョン {1}) です。モジュール '{2}' を実行するには、PowerShell ホストの最小バージョン '{3}' が必要です。 + + + モジュール '{0}' のモジュール マニフェスト + + + 生成元: {0} + + + 生成日: {0} + + + このマニフェストに関連付けられているスクリプト モジュールまたはバイナリ モジュール ファイル。 + + + RootModule/ModuleToProcess で指定されたモジュールの入れ子になったモジュールとしてインポートするモジュール + + + このモジュールを一意に識別するために使用される ID + + + このモジュールの作成者 + + + このモジュールの会社またはベンダー + + + このモジュールの著作権に関する声明 + + + このモジュールのバージョン番号。 + + + このモジュールによって提供される機能の説明 + + + このモジュールで必要な PowerShell エンジンの最小バージョン + + + このモジュールに必要な共通言語ランタイム (CLR) の最小バージョン。{0} + + + このモジュールをインポートする前にグローバル環境にインポートする必要があるモジュール + + + このモジュールをインポートする前に呼び出し元の環境で実行されるスクリプト ファイル (.ps1)。 + + + このモジュールのインポート時に読み込まれる型ファイル (.ps1xml) + + + このモジュールのインポート時に読み込まれるフォーマット ファイル (.ps1xml) + + + このモジュールをインポートする前に読み込む必要があるアセンブリ + + + このモジュールでパッケージ化されたすべてのファイルの一覧 + + + RootModule/ModuleToProcess で指定されたモジュールに渡す非公開データ。これには、PowerShell で使用される追加のモジュール メタデータを含む PSData ハッシュテーブルも含まれる場合があります。 + + + このモジュールに適用されるタグ。これらは、オンライン ギャラリーでのモジュール検出に役立ちます。 + + + このプロジェクトのメイン Web サイトの URL。 + + + このモジュールのライセンスの URL。 + + + このモジュールを表すアイコンの URL。 + + + このモジュールの ReleaseNotes + + + このモジュールのプレリリース文字列 + + + モジュールがインストール/更新/保存に明示的なユーザーの同意を必要とするかどうかを示すフラグ + + + このモジュールの外部依存モジュール + + + {0} ハッシュテーブルの終わり + + + PrivateData パラメーター値は、次のパラメーター値 Tags、ProjectUri、LicenseUri、IconUri、または ReleaseNotes を含むモジュール マニフェストを作成するためのハッシュ テーブルである必要があります。Tags、ProjectUri、LicenseUri、IconUri、または ReleaseNotes パラメーター値を削除するか、PrivateData の内容をハッシュテーブルにラップします。 + + + PrivateData はハッシュテーブルとして定義する必要がありますが、このモジュール マニフェストではこれをオブジェクトとして定義します。PrivateData の内容をハッシュテーブルにラップすることを検討してください。これにより、後で Tags、ProjectUri、LicenseUri、IconUri、ReleaseNotes の各プロパティをモジュール マニフェストに追加できます。 + + + 指定された値 '{0}' は無効です。有効な値でもう一度お試しください。 + + + このモジュールからエクスポートする関数は、最適なパフォーマンスを得るためにワイルドカードを使用せず、エントリを削除しないでください。エクスポートする関数がない場合は空の配列を使用します。 + + + このモジュールからエクスポートするエイリアスは、最適なパフォーマンスを得るためにワイルドカードを使用せず、エントリを削除しないでください。エクスポートするエイリアスがない場合は空の配列を使用します。 + + + このモジュールからエクスポートするコマンドレットは、最適なパフォーマンスを得るためにワイルドカードを使用せず、エントリを削除しないでください。エクスポートするコマンドレットがない場合は空の配列を使用します。 + + + このモジュールからエクスポートする変数 + + + このモジュールからエクスポートする DSC リソース + + + サポートされている PSEditions + + + このモジュールで必要なプロセッサ アーキテクチャ (なし、X86、Amd64) + + + このモジュールでパッケージ化されたすべてのモジュールの一覧 + + + このモジュールで必要な Microsoft .NET Framework の最小バージョン。{0} + + + このモジュールで必要な PowerShell ホストの名前 + + + このモジュールで必要な PowerShell ホストの最小バージョン + + + このモジュールの HelpInfo の URI + + + {0} モジュールは現在の PowerShell セッションで PSDrive を提供しているため、モジュールは削除されませんでした。現在の PSDrive プロバイダーを変更してから、モジュールを削除し直してください。 + + + 現在のスコープに同じ名前のメンバーが存在するため、コマンドレット '{0}' はインポートされませんでした。 + + + 現在のスコープに同じ名前のメンバーが存在するため、エイリアス '{0}' はインポートされませんでした。 + + + 現在のスコープに同じ名前のメンバーが存在するため、関数 '{0}' はインポートされませんでした。 + + + 現在のスコープに同じ名前のメンバーが存在するため、変数 '{0}' はインポートされませんでした。 + + + ワイルドカード文字は、モジュール マニフェスト '{0}' のメンバー 'ModuleToProcess'、'RootModule'、または 'NestedModules' では使用できません。 + + + モジュール '{0}' は PowerShell のコア モジュールです。Force パラメーターをコマンドに追加して、コア モジュールを削除します。 + + + モジュール マニフェストに 'ModuleToProcess' メンバーと 'RootModule' メンバーの両方を含めることはできません。モジュール マニフェスト ファイルを変更して、'{0}' にあるこれらのメンバーのいずれかを削除してから、もう一度やり直してください。 + + + モジュール マニフェスト メンバー 'ModuleToProcess' は非推奨になりました。代わりに 'RootModule' メンバーを使用してください。 + + + このモジュールからエクスポートされたコマンドの既定のプレフィックス。Import-Module -Prefix を使用して既定のプレフィックスをオーバーライドします。 + + + 'Global' パラメーターと 'Scope' パラメーターを同時に指定することはできません。これらのパラメーターのいずれかを削除してから、コマンドを再実行してください。 + + + 必要なモジュール '{0}' が読み込まれていません。モジュール '{0}' のモジュール マニフェスト '{2}' に、循環依存関係を指す requiredModule '{1}' があります。 + + + 必要なモジュール '{0}' は、モジュール ディレクトリに有効なモジュール ファイルが見つからなかったため読み込まれませんでした。 + + + モジュール {0} の一部のコマンドを CimSession 経由でインポートすることはできません。すべてのコマンドを取得するには、リモート サーバーで PowerShell リモート管理が有効になっていることを確認してから、Import-Module コマンドレットに PSSession パラメーターを追加してみてください。 + + + モジュール {0} は、{1} リモート処理セッションを使用してWindows PowerShell に読み込まれます。このモジュールからのコマンドの入力と出力はすべて逆シリアル化されるオブジェクトであることに注意してください。このモジュールを PowerShell に読み込む場合は、'Import-Module -SkipEditionCheck' 構文を使用してください。 + + + Windows PowerShell のバージョン {0} を検出しました。Windows PowerShell 互換性機能を使用してモジュールを読み込むには、Windows PowerShell 5.1 が必要です。https://aka.ms/WMF5Download から Windows Management Framework (WMF) 5.1 をインストールして、この機能を有効にしてください。 + + + モジュール '{0}' は、PowerShell 構成ファイルの 'WindowsPowerShellCompatibilityModuleDenyList' 設定によって Windows PowerShell 互換性機能を使用して読み込むことがブロックされています。 + + + モジュール {0} を CimSession 経由でインポートすることはできません。Import-Module コマンドレットの PSSession パラメーターを使用してみてください。 + + + {0} のプロセッサ アーキテクチャ値はサポートされていません。New-ModuleManifest コマンドをもう一度実行し、プロセッサ アーキテクチャでサポートされている列挙値 (None、MSIL、X86、Amd64、Arm) のいずれかを指定します + + + リモート コンピューターに対して Get-Module コマンドレットを実行すると、使用可能なモジュールのみを一覧表示できます。ListAvailable パラメーターをコマンドに追加してから、もう一度やり直してください。 + + + '{0}' スナップインが既にインポートされているため、'{0}' モジュールはインポートされませんでした。 + + + ワイルドカード文字は、モジュール マニフェスト '{0}' のメンバー 'RequiredAssemblies' では使用できません。 + + + {1} の {0} キーの値が {2} であり、モジュールに入れ子になったモジュールがあります。CDXML ファイルがルート モジュールの場合、入れ子になったモジュール内のコマンドをエクスポートできないため、Import-Module コマンドは失敗します。CDXML ファイルを NestedModules キーに移動し、コマンドを再試行してください。 + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + リモート コマンドからのエラー: {0}: {{0}} + + + リモート モジュール '{0}' のプロキシを生成できませんでした。{{0}} + + + リモート モジュール {0} を処理できませんでした。{1} + + + リモート CimSession からモジュール データを受信できませんでした。{0} + + + 有効なモジュール ファイルがモジュール ディレクトリに見つからなかったため、GUID '{1}' およびバージョン '{2}' の必要なモジュール '{0}' は読み込まれませんでした。 + + + モジュール検出用の CIM プロバイダーが CIM サーバーで見つかりませんでした。{0} + {0} is a placeholder for a more detailed error message + + + Microsoft .NET Framework のバージョン {0} は、許可されているバージョンの一覧に含まれていないため確認できません。 + + + {0} を分析しています。 + {0} should not be localized, is used to contain a file path. + + + 初めて使用するモジュールを準備しています。 + + + 使用可能なモジュールを検索しています + + + UNC 共有 {0} を検索しています。 + {0} should not be localized, is used to contain a file path. + + + リモート コンピューターに対する Get-Module コマンドレットの実行は、パスを含まないモジュール名に対してのみ実行できます。Name パラメーターには、次の要素 '{0}' があります。これはパスに解決されます。Name パラメーターを更新してパス要素を持たないようにしてから、もう一度やり直してください。 + + + ListAvailable パラメーターを指定せずに Get-Module コマンドレットを実行することは、パスを含むモジュール名ではサポートされていません。Name パラメーターには、次の要素 '{0}' があります。これはパスに解決されます。Name パラメーターを更新してパス要素を持たないようにしてから、もう一度やり直してください。 + + + 指定されたモジュール '{0}' が見つかりませんでした。有効なパスを指すように Name パラメーターを更新してから、もう一度やり直してください。 + + + モジュール {0} の RepositorySourceLocation プロパティを設定しています。 + + + 処理するモジュール '{0}' は、モジュール マニフェスト '{2}' のフィールド '{1}' に一覧表示されましたが、処理されませんでした。{3} + + + この前提条件は、PowerShell Desktop エディションでのみ有効です。 + + + モジュール '{0}' は現在の PowerShell エディション '{1}' をサポートしていません。サポートされているエディションは '{2}' です。このモジュールの互換性を無視するには、'Import-Module -SkipEditionCheck' を使用します。 + + + モジュール '{0}' は PowerShell エディション '{1}' をサポートしており、Windows 互換性機能を使用して暗黙的に読み込むことはできません。これは、設定ファイルで無効になっています。'Import-Module -UseWindowsPowerShell' を使用してこのモジュールを Windows PowerShell または 'Import-Module -SkipEditionCheck' で読み込み、現在の PowerShell でモジュールを読み込もうとします。 + + + モジュール マニフェストで宣言された試験的機能には、空でない文字列値を指定する必要があります。 + + + 1 つ以上の無効な試験的特徴名が見つかりました: {0}。モジュールの試験的機能名は、次の規則に従う必要があります: 'ModuleName.FeatureName'。 + + + -SkipEditionCheck スイッチ パラメーターは、-ListAvailable スイッチ パラメーターなしでは使用できません。 + + + *.ps1 ファイルをモジュールとしてインポートすることは、ConstrainedLanguage モードでは許可されていません。 + + + スクリプト モジュール {0} の読み込み中にエラーが発生しました。モジュール マニフェストが言語モードが異なるためです。マニフェスト言語モードは {1} で、モジュール言語モードが {2} です。すべてのモジュール ファイルが署名されているか、アプリケーションの許可リスト構成の一部であることを確認してください。 + + + このモジュールでは、ワイルドカード文字を使用して関数をエクスポートするときにドットソース演算子を使用します。これは、システムがアプリケーション検証の適用下にある場合は許可されません。 + + + 実行中のセッションとは異なる言語モードのモジュールからモジュール メンバーをエクスポートすることはできません。 + + + セッションが ConstrainedLanguage モードの間は、新しいモジュールを作成できません。 + + + 'Core' エディションと互換性のある組み込みモジュール '{0}' が見つかりません。PowerShell 組み込みモジュールが使用可能であることを確認してください。これらは通常、$PSHOME モジュール パスの下に PowerShell パッケージが付属しており、PowerShell が正常に機能するために必要です。 + + + Export-ModuleMember コマンドレット + + + モジュール '{0}'、言語モード '{1}' が現在のセッション '{2}' とは異なるため、モジュール メンバーのエクスポートは制約付き言語モードで失敗します。 + + + モジュールの暗黙的な関数のエクスポート + + + モジュール '{0}' の暗黙的な関数エクスポートは、信頼されている (完全言語モードで実行される) が、セッションが信頼されていない (制約言語モードで実行される) ため、拒否されます。モジュール関数は常にフル ネームで個別にエクスポートすることをお勧めします。 + + + モジュールとしてスクリプト ファイルをインポートしています + + + スクリプト ファイル '{0}' をモジュールとしてインポートすることは、ConstrainedLanguage モードでは許可されません。 + + + モジュールにドットソース演算子が含まれています + + + モジュール '{0}' のインポートは、ドットソース演算子を使用しながらワイルドカード文字を使用して関数をエクスポートするため、制約付き言語モードで失敗します。 + + + "モジュールエクスポート関数 + + + モジュール '{0}' は、名前のワイルドカード文字を使用して関数をエクスポートします。入れ子になったモジュール関数名は、制約付き言語モードで実行すると削除されます。 + + + "New-Module コマンドレット + + + 信頼されていない制約言語セッションからの新しいモジュールは、FullLanguage スクリプト ブロックの提供をブロックされます。 + + + "モジュールの言語モードが一致しません + + + 親とは異なる言語モードの依存モジュールが読み込まれています。これは、制約付き言語モードでは許可されません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/MshHostRawUserInterfaceStrings.ja.resx b/src/System.Management.Automation/resources/ja/MshHostRawUserInterfaceStrings.ja.resx new file mode 100644 index 00000000000..bed9e2791b7 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/MshHostRawUserInterfaceStrings.ja.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}" 以上である必要があります。 + + + "{0}" は正の数値である必要があります。 + + + すべての文字列が null 値または空です。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/MshSignature.ja.resx b/src/System.Management.Automation/resources/ja/MshSignature.ja.resx new file mode 100644 index 00000000000..9942c2b0156 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/MshSignature.ja.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 + + + 署名が検証されました。 + + + ファイル {0} はデジタル署名されていません。現在のシステムでこのスクリプトを実行することはできません。スクリプトの実行と実行ポリシーの設定の詳細については、https://go.microsoft.com/fwlink/?LinkID=135170 で about_Execution_Policies を参照してください + + + ファイルのハッシュがデジタル署名に格納されているハッシュと一致しないため、ファイル {0} の内容が承認されていないユーザーまたはプロセスによって変更された可能性があります。指定されたシステムではスクリプトを実行できません。詳細については、Get-Help about_Signing を実行してください。 + + + ファイル {0} は署名されていますが、署名者はこのシステムで信頼されていません。 + + + システムが {0} ファイルに対する署名操作をサポートしていないため、ファイルに署名できません。 + + + ファイル名拡張子を持たないファイルに対する署名操作がシステムでサポートされていないため、ファイルに署名できません。 + + + 現在のシステムと互換性がないため、署名を検証できません。 + + + 現在のシステムと互換性がないため、署名を検証できません。ハッシュ アルゴリズムが無効です。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/MshSnapInCmdletResources.ja.resx b/src/System.Management.Automation/resources/ja/MshSnapInCmdletResources.ja.resx new file mode 100644 index 00000000000..4cb01e28b69 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/MshSnapInCmdletResources.ja.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 + + + 操作を実行できません。指定されたコマンドレットは、カスタム シェルではサポートされていません。 + + + パターン '{0}' に一致する PowerShell スナップインが見つかりませんでした。パターンを確認してから、コマンドを再試行してください。 + + + 指定されたスナップイン名の形式が無効でした。 PowerShell スナップイン名に使用できるのは、英数字、ダッシュ、アンダースコア、ピリオドのみです。名前を訂正してから、操作を再試行してください。 + + + システム PowerShell モジュールであるため、PowerShell スナップイン {0} を追加できません。Import-Module を使用してモジュールを読み込みます。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/MshSnapinInfo.ja.resx b/src/System.Management.Automation/resources/ja/MshSnapinInfo.ja.resx new file mode 100644 index 00000000000..12b8f3fea83 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/MshSnapinInfo.ja.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 + + + PowerShell のレジストリ情報にアクセスできません。 + + + PowerShell エンジンのレジストリ情報にアクセスできません。 + + + PublicKeyToken の情報にアクセスできません。 + + + PowerShell のバージョン {0} は、このコンピューターでは使用できません。 + + + PowerShell スナップイン '{0}' が、このコンピューターにインストールされていません。 + + + レジストリ キー {1} に必須の値 {0} が指定されていません。 + + + 必須の値 {0} は、レジストリ キー {1} に対して正しい形式ではありません。 必要な形式は 'string' です。 + + + 必須の値 {0} は、レジストリ キー {1} に対して正しい形式ではありません。 必要な形式は 'multistring' です。 + + + 必要な情報がレジストリに見つからないか、キー ファイルが見つかりません。 一部のコマンドレットを読み込めません。 + + + PowerShell バージョン {0} には、登録済みのスナップインがありません。 + + + リーダーが破棄されたため、文字列リソースを取得できません。 + + + レジストリ キー {1} のバージョン値 {0} が指定されていないか、正しくありません。 + + + PowerShell 型 {0} の [PSVersion] 属性が見つかりませんでした。[PSVersion(PowerShell SnapinBase.PSEngineVersion)] を使用して、型に PSVersion 属性を追加してください。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/NativeCP.ja.resx b/src/System.Management.Automation/resources/ja/NativeCP.ja.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/NativeCP.ja.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PSCommandStrings.ja.resx b/src/System.Management.Automation/resources/ja/PSCommandStrings.ja.resx new file mode 100644 index 00000000000..157b967521e --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PSCommandStrings.ja.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 + + + パラメーターを追加するには、コマンドが必要です。パラメーターを追加する前に、{0} にコマンドを追加する必要があります。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PSConfigurationStrings.ja.resx b/src/System.Management.Automation/resources/ja/PSConfigurationStrings.ja.resx new file mode 100644 index 00000000000..15fd480ced2 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PSConfigurationStrings.ja.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 + + + PowerShell はセキュリティ上の問題により動作を停止しました: 構成ファイル {0} を読み取れません + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PSDataBufferStrings.ja.resx b/src/System.Management.Automation/resources/ja/PSDataBufferStrings.ja.resx new file mode 100644 index 00000000000..deb282560d8 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PSDataBufferStrings.ja.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 + + + 指定されたインデックスが 0 未満か、バッファー内の項目数より大きくなっています。インデックスは {0} - {1} の範囲内である必要があります。 + + + null 参照を値の型に変換できません。 + + + 値を型 {0} から型 {1} に変換できません。 + + + 閉じられたバッファーにはオブジェクトを追加できません。Add および Insert 操作を正常に実行するには、バッファーが開いていることを確認してください。 + + + SerializeInput プロパティは、PSDataCollection の PSObject 型に対してのみ設定できます。SerializeInput プロパティを false に設定するか、コレクションの型を PSObject に変更してください。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PSListModifierStrings.ja.resx b/src/System.Management.Automation/resources/ja/PSListModifierStrings.ja.resx new file mode 100644 index 00000000000..8bb5b138263 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PSListModifierStrings.ja.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 + + + 次の不明なリスト修飾子が検出されました: '{0}'。有効なリスト修飾子は、Add、Remove、Replace です。 + + + オブジェクトがサポートされているコレクション型ではないため、更新プログラムを適用できません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PSStyleStrings.ja.resx b/src/System.Management.Automation/resources/ja/PSStyleStrings.ja.resx new file mode 100644 index 00000000000..df01cfe5b77 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PSStyleStrings.ja.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 指定された文字列に、ANSI エスケープ シーケンスのみを含める必要があるにもかかわらず、印刷可能なコンテンツが含まれています: {0} + + + 進行状況バーを正しく表示するには、最大幅を 18 以上にする必要があります。 + + + 拡張子を追加または削除するときは、拡張子の先頭にピリオドを付ける必要があります。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ParameterBinderStrings.ja.resx b/src/System.Management.Automation/resources/ja/ParameterBinderStrings.ja.resx new file mode 100644 index 00000000000..453ace6ec2b --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ParameterBinderStrings.ja.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + パラメーター名 '{1}' と一致するパラメーターが見つかりません。 + + + 引数 '{1}' を受け取る位置指定パラメーターが見つかりません。 + + + パラメーター '{1}' の引数がありません。型 '{2}' のパラメーターを指定して、もう一度やり直してください。 + + + パラメーター名 '{1}' があいまいであるため、パラメーターを処理できません。一致の可能性は次のとおりです:{6}。 + + + '{6}' をパラメーター '{1}' で必要な型 '{2}' に変換できません: {7} + + + パラメーター '{1}' をバインドできません。{6} + + + 位置指定パラメーター '{1}' がバインドされます。 + + + 名前が指定されていないため、位置指定パラメーターをバインドできません。 + + + 設定されたパラメーターは、指定された名前付きパラメーターを使って解決することができません。発行された 1 つ以上のパラメーターを同時に使用できないか、指定されたパラメーターの数が不足しています。 + + + 1 つ以上の必須パラメーターが不足しているため、コマンドを処理できません:{1}。 + + + パラメーター '{1}' をパラメーター セット '{6}' に指定することはできません。 + + + パラメーター '{1}' が複数回指定されているため、パラメーターをバインドできません。複数の値を受け取ることができるパラメーターに複数の値を指定するには、配列構文を使用します。たとえば、"-parameter value1,value2,value3" とします。 + + + パラメーター '{1}' を評価できません。引数がスクリプト ブロックとして指定されており、入力がないためです。スクリプト ブロックは、入力がないと評価できません。 + + + パラメーター '{1}' のスクリプト ブロックへの入力に失敗しました。{6} + + + パラメーター '{1}' を評価できません。引数の入力で出力が生成されませんでした。 + + + コマンドがパイプライン入力を受け取らないか、入力とそのプロパティがパイプライン入力を受け取るパラメーターと一致しないため、入力オブジェクトをコマンドのパラメーターにバインドできません。 + + + すべての必須パラメーターをバインドするために必要な情報が含まれていないため、入力オブジェクトをバインドできません: {6} + + + パラメーター '{1}' の既定値を取得できないため、パイプライン入力を処理できません。{6} + + + コマンドレットの動的パラメーターを取得できません。{6} + + + 次のパラメーターの値を入力します: + + + コマンド パイプラインの位置 {1} でのコマンドレット {0} + + + パラメーター '{1}' の引数変換を処理できません。{6} + + + {6} + + + パラメーター '{1}' の引数を検証できません。{6} + + + パラメーター '{1}' をターゲットにバインドできません。{6} + + + パラメーター '{1}' は null 値であるため、引数をバインドできません。 + + + パラメーター '{1}' は空の文字列であるため、引数をバインドできません。 + + + パラメーター '{1}' は空のコレクションであるため、引数をバインドできません。 + + + パラメーター '{1}' は空の配列であるため、引数をバインドできません。 + + + コマンドを処理できません。パラメーター '{0}' は複数回定義されています。 + + + パラメーター '{1}' の型が '{2}' で、Add() メソッドを識別できないか、複数の Add() メソッドが存在するため、コマンドレット {0} をバインドできません。{6} + + + ランタイム定義パラメーター '{1}' がキー '{6}' で RuntimeDefinedParameterDictionary に追加されたため、コマンドレット {0} をバインドできません。キーは RuntimeDefinedParameter.Name と同じである必要があります。 + + + 引数の PSTypeNames がパラメーター '{1}' で必要な PSTypeName と一致しないため、引数をパラメーター '{6}' にバインドできません。 + + + $PSDefaultParameterValues では、次の名前またはエイリアスに一致するパラメーターに対して複数の異なる既定値が定義されています: {0}。これらの既定値は無視されました。 + + + このコマンドレットの $PSDefaultParameterValues で定義されている次の名前またはエイリアスは、複数のパラメーターに解決されます: {0}。既定値は無視されました。 + + + {6} このエラーは、既定のパラメーター バインドの適用によって発生した可能性があります。$PSDefaultParameterValues で既定のパラメーター バインドを無効にするには、$PSDefaultParameterValues["Disabled"] を$trueに設定してから、もう一度やり直してください。次の既定のパラメーターは、エラーが発生したときにこのコマンドレットに対して正常にバインドされました: {7} + + + {6} このエラーは、既定のパラメーター バインドの適用によって発生する可能性があります。$PSDefaultParameterValues で既定のパラメーター バインドを無効にするには、$PSDefaultParameterValues["Disabled"] を $true に設定してから再試行してください。次の既定のパラメーターは、エラーが発生したときにこのコマンドレットに対して正常にバインドされました: {7} + + + パラメーター '{1}' への既定値 '{0}' のバインドに失敗しました: {2} + + + キー '{0}' に有効な形式がありません。正しい形式の詳細については、https://go.microsoft.com/fwlink/?LinkId=228266 でabout_Parameters_Default_Values を参照してください。 + + + キー '{0}' の形式が無効です。正しい形式の詳細については、https://go.microsoft.com/fwlink/?LinkId=228266 でabout_Parameters_Default_Values を参照してください。 + + + パラメーター '{0}' は廃止されました。{1} + + + 型 '{1}' のキー '{0}' は文字列値ではありません。DefaultParameterDictionary は文字列値キーのみを受け入れます。 + + + キー '{0}' は既にディクショナリに追加されています。 + + + メソッドまたはプロパティの呼び出しは許可されていません + + + 型 '{1}' でのメソッドまたはプロパティ '{0}' の呼び出しは、信頼されていないスクリプトの制約言語モードでは許可されません。 + + + 型の作成は許可されていません + + + 型 '{0}' の作成は、信頼されていないスクリプトの制約付き言語モードでのパラメーター バインド中に許可されません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ParserStrings.ja.resx b/src/System.Management.Automation/resources/ja/ParserStrings.ja.resx new file mode 100644 index 00000000000..b9fa75cdd31 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ParserStrings.ja.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + アセンブリ '{0}' を読み込むことができません。 + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PathUtilsStrings.ja.resx b/src/System.Management.Automation/resources/ja/PathUtilsStrings.ja.resx new file mode 100644 index 00000000000..a1146b66d7c --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PathUtilsStrings.ja.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + エンコード 'UTF-7' は非推奨です。UTF-8 を使用してください。 + + + ファイル {0} は既に存在し、{1} が指定されました。 + + + 現在のプロバイダー ({0}) がファイルを開くことができないため、ファイルを開けません。 + + + パスが複数のファイルに解決されたため、操作を実行できません。このコマンドは、複数のファイルに適用することはできません。 + + + ワイルドカード パス {0} がファイルに解決されなかったため、操作を実行できません。 + + + 不明なエンコード {0}。有効な値は {1} です。 + + + ディレクトリ '{0}' は既に存在します。 ディレクトリおよびその中のファイルを上書きする場合は、-Force パラメーターを使用してください。 + + + ユーザー モジュールのパスが存在しないため、指定されたモジュール名 '{0}' のモジュール フォルダーを作成できません。 + + + 次の理由により、モジュール {0} を作成できません: {1}。-OutputModule パラメーターに別の引数を指定して、再試行してください。 + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + このモジュールは、互換性のないバージョンの {0} コマンドレットで生成されているため、読み込めません。現在のセッションの {0} コマンドレットを使用してモジュールを生成し、もう一度読み込んでください。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PipelineStrings.ja.resx b/src/System.Management.Automation/resources/ja/PipelineStrings.ja.resx new file mode 100644 index 00000000000..42a9f6224ce --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PipelineStrings.ja.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + このコマンドレット インスタンスは、別のパイプラインによって使用されているため、処理できません。Microsoft カスタマー サポート サービスに連絡してください。 + + + パイプラインが開始されているため、この操作は実行できません。パイプラインを停止し、操作を再試行してください。 + + + Stop ポリシーによって実行中のコマンドレットが防止されているため、このコマンドレットの実行を続行できません。 + + + このパイプラインは、パイプライン内の最初のコマンドレットが前のコマンドレットの結果から入力を読み取ろうとしているため、実行できません。最初のコマンドレットを変更するか、最初のコマンドレットを削除するか、最初のコマンドレットで出力が必要なコマンドレットをパイプラインに追加してから、パイプラインを再実行してください。 + + + コマンドレット番号を処理できません。ReadFromCommand 関数には、パイプラインに既に追加されているコマンドレットの ID を指定する必要があります。Microsoft カスタマー サポート サービスに連絡してください。 + + + ReadFromCommand および ReadErrorQueue 関数の出力は、別のコマンドレットがその出力を既に読み取っているため、読み取れません。Microsoft カスタマー サポート サービスに連絡してください。 + + + コマンドがないため、このパイプラインを実行できません。このパイプラインに少なくとも 1 つのコマンドを追加してから、もう一度実行してください。 + + + パイプライン操作は、まだ開始されていないため、完了できません。ステップ可能なパイプラインで End() を呼び出す前に、Begin() メソッドを呼び出す必要があります。 + + + WriteObject および WriteError メソッドは、BeginProcessing、ProcessRecord、EndProcessing メソッドのオーバーライドの外部からは呼び出せません。これらは、同じスレッド内からのみ呼び出すことができます。コマンドレットがこれらの呼び出しを適切に行っていることを確認するか、Microsoft カスタマー サポート サービスにお問い合わせください。 + + + ThrowTerminatingError を呼び出した後、コマンドレットによって例外がスローされました。 +最初の例外は、スタック トレース "{1}" を持つ "{0}" でした。 +2 番目の例外は、スタック トレース "{3}" を持つ "{2}" でした。 + + + パイプラインが閉じられた後は、WriteObject および WriteError メソッドを呼び出すことはできません。Microsoft カスタマー サポート サービスに連絡してください。 + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + パイプラインの作成中にエラーが発生しました。 + + + このパイプラインでは、切断接続セマンティクスはサポートされていません。 + + + このパイプラインは、切断状態ではないため、接続できません。 + + + 実行空間オブジェクトには、null リモート コマンドが関連付けられています。 リモート コマンドが指定されていないため、切断された RemotePipeline オブジェクトを作成できません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/PowerShellStrings.ja.resx b/src/System.Management.Automation/resources/ja/PowerShellStrings.ja.resx new file mode 100644 index 00000000000..3d76aed8f42 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/PowerShellStrings.ja.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 + + + 現在の PowerShell インスタンスの状態は、この操作に対して無効です。 + + + コマンドは既に開始されているため、操作を実行できません。コマンドが完了するまで待つか、コマンドを停止してから、もう一度操作を実行してください。 + + + コマンドが指定されていません。 + + + PowerShell インスタンスが、入れ子になった PowerShell インスタンスを作成するための正しい状態ではありません。入れ子になった PowerShell インスタンスは、実行中の PowerShell インスタンスでのみ作成できます。 + + + 実行空間が '{0}' 状態ではないため、操作を実行できません。実行空間の現在の状態は '{1}' です。 + + + 入れ子になった PowerShell インスタンスを非同期に呼び出すことはできません。Invoke メソッドを使用してください。 + + + {0} は、この PowerShell インスタンスで {1} を呼び出して作成されたオブジェクトではありません。 + + + 実行空間がスレッドを再利用するように設定されている場合、呼び出し設定のアパートメント状態は実行空間と一致している必要があります。 + + + 実行空間が現在のスレッドを使用するように設定されている場合、呼び出し設定のアパートメント状態は現在のスレッドの状態と一致している必要があります。 + + + パラメーターを追加するには、コマンドが必要です。パラメーターを追加する前に、PowerShell インスタンスにコマンドを追加する必要があります。 + + + 辞書内のキーは文字列である必要があります。 + + + このスレッドには、コマンドを実行できる実行空間がありません。System.Management.Automation.Runspaces.Runspace 型の DefaultRunspace プロパティで指定できます。呼び出そうとしたコマンド: {0} + + + この PowerShell オブジェクトはリモート実行空間または実行空間プールに関連付けられていないため、接続できません。 + + + 実行中のコマンドは切断されていますが、リモート サーバーではまだ実行されています。 コマンドの操作状態と出力データを取得するには、再接続してください。 + + + 現在の PowerShell セッションが切断状態であるため、この操作を実行できません。 この PowerShell セッションに接続してから、コマンドの完了を待つか、コマンドを停止してください。 + + + 現在の PowerShell セッションが切断状態であるため、この操作を実行できません。 この PowerShell セッションに接続してから、もう一度お試しください。 + + + リモート コマンドへの接続に失敗しました。 + + + コマンドが現在停止しているため、この操作を実行できません。コマンドの停止が完了するまで待ってから、もう一度お試しください。 + + + このスレッドには、コマンドを実行できる実行空間がありません。System.Management.Automation.Runspaces.Runspace 型の DefaultRunspace プロパティで指定できます。現在の PowerShell インスタンスには、呼び出すコマンドが含まれていません。 + + + 現在の実行空間を使用する PowerShell オブジェクトは、現在の実行空間が使用できないため作成できません。 現在の実行空間は、Initial Session State を使用して作成された場合など、開始処理中である可能性があります。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ProgressRecordStrings.ja.resx b/src/System.Management.Automation/resources/ja/ProgressRecordStrings.ja.resx new file mode 100644 index 00000000000..966e0f54ac5 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ProgressRecordStrings.ja.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} に負の値を指定できないため、引数を処理できません。 + + + {0} の値を null 値または空にできないため、引数を処理できません。 + + + {0} を 100 より大きくできないため、パーセントを設定できません。 + + + ParentActivityId を ActivityId と同じにすることはできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ProviderBaseSecurity.ja.resx b/src/System.Management.Automation/resources/ja/ProviderBaseSecurity.ja.resx new file mode 100644 index 00000000000..02aa823929f --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ProviderBaseSecurity.ja.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 + + + ISecurityDescriptorCmdletProvider インターフェイスがこのプロバイダーでサポートされていないため、インターフェイスを使用できません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/ProxyCommandStrings.ja.resx b/src/System.Management.Automation/resources/ja/ProxyCommandStrings.ja.resx new file mode 100644 index 00000000000..31e8d961083 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/ProxyCommandStrings.ja.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 + + + 'help' パラメーターは、'get-help' コマンドによって作成された有効な HelpInfo オブジェクトとして認識されません。 + + + CommandMetadata に名前がないため、プロキシ コマンドを生成できません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/RegistryProviderStrings.ja.resx b/src/System.Management.Automation/resources/ja/RegistryProviderStrings.ja.resx new file mode 100644 index 00000000000..5cf5d8eba4f --- /dev/null +++ b/src/System.Management.Automation/resources/ja/RegistryProviderStrings.ja.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + 項目のクリア + + + 項目: {0} + + + 新しい項目 + + + 項目: {0} + + + キーの削除 + + + 項目: {0} + + + キーのコピー + + + 項目: {0} 宛先: {1} + + + 項目名の変更 + + + 項目: {0} NewName: {1} + + + 項目の移動 + + + 項目: {0} 宛先: {1} + + + プロパティの設定 + + + 項目: {0} プロパティ: {1} + + + プロパティをクリア + + + 項目: {0} プロパティ: {1} + + + 新しいプロパティ + + + 項目: {0} プロパティ: {1} + + + プロパティの削除 + + + 項目: {0} プロパティ: {1} + + + プロパティ名を変更します。 + + + 項目: {0} SourceProperty: {1} DestinationProperty: {2} + + + プロパティのコピー + + + 項目: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + プロパティの移動 + + + 項目: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 操作は処理されませんでした。指定された場所では、この操作は許可されていません。 + + + ソースの場所に対する操作は許可されていません。 + + + この操作は、宛先の場所では許可されていません。 + + + ローカル コンピューターの構成設定 + + + 現在のユーザーのソフトウェア設定 + + + このパスには既にキーが存在します。 + + + 宛先パスがソース パスの下位にあるため、操作を実行できません。 + + + プロパティは既に存在します。 + + + プロパティ {0} はパス {1} に存在しません。 + + + 指定されたパスのレジストリ キーが存在しません。 + + + パラメーター 'Type' をバインドできませんでした。"{0}" を "{1}" に変換できませんでした。使用可能な列挙値は、"String、ExpandString、Binary、DWord、MultiString、QWord、Unknown" です。 + + + キー {0} は作成されましたが、既定値を設定できませんでした。 + + + 指定されたルートを持つドライブを作成できません。ルート パスが存在しません。 + + + 同じコンテナーに同じ名前の項目が既に存在するため、項目の名前を変更できません。 + + + レジストリ キー名は、有効なベース キー名で始まる必要があります。 + + + サブキーの引数が無効です。 + + + サブキーが存在しないため、サブキー ツリーを削除できません。 + + + その名前の値は存在しません。 + + + 列挙値 {0} が無効です。 + + + 値引数を指定する必要があります。 + + + 名前引数を指定する必要があります。 + + + 指定された RegistryValueKind は無効な値です。 + + + RegistryKey.SetValue では、null 値の文字列参照を含む String[] は許可されていません。 + + + レジストリ サブキーは 255 文字以下にする必要があります。 + + + 空でないサブキー名を指定する必要があります。 + + + 値オブジェクトの型が指定された RegistryValueKind と一致しなかったか、オブジェクトを正しく変換できませんでした。 + + + RegistryKey.SetValue では型 '{0}' の配列はサポートされていません。サポートされているのは Byte[] と String[] のみです。 + + + 指定されたレジストリ キーが存在しません。 + + + 指定された値の名前の長さが最大 16383 文字を超えています。 + + + 指定された値データのサイズが最大の 1 MB を超えています。 + + + 指定されたレジストリ サブキーは存在しません。 + + + 指定された RegistryKeyPermissionCheck 値が無効です。 + + + レジストリ キーにはサブキーがあります。再帰的な削除は、このメソッドではサポートされていません。 + + + Transaction.Current または指定したトランザクションがないと、KTM ハンドルを作成できません。 + + + 指定されたトランザクションまたは Transaction.Current は、この TransactedRegistryKey の作成またはオープンに使用されたトランザクションと一致している必要があります。 + + + TransactedRegistryKey オブジェクトは、あらかじめ定義されたキー用であるため、トランザクションに関連付けられていません。 + + + 要求されたレジストリ アクセスは許可されていません。 + + + レジストリ キー '{0}' へのアクセスが拒否されました。 + + + レジストリ キーに書き込めません。 + + + 閉じているレジストリ キーにはアクセスできません。 + + + 不明なエラー: {0}。 + + + レジストリ トランザクションは、このプラットフォームではサポートされていません。 + + + 指定されたハンドルが無効です。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/RemotingErrorIdStrings.ja.resx b/src/System.Management.Automation/resources/ja/RemotingErrorIdStrings.ja.resx new file mode 100644 index 00000000000..b56e58f4540 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/RemotingErrorIdStrings.ja.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + FilePath パラメーターでは、ワイルドカード文字はサポートされていません。ワイルドカード文字を使用せずにパスを指定します。 + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + セッション オプション {1} には、{0} 値を指定する必要があります。 + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + リモート コンピューターへの接続中に許可する WS-Man URI リダイレクトの最大数 + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + WriteEvents パラメーターは、Wait パラメーターなしでは使用できません。 + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + PowerShell リモート処理は、Windows Preinstallation Environment (WinPE) ではサポートされていません。 + + + {0} によって行われた変更は、WinRM サービスが再起動されるまで有効にできません。 + + + {0} この名前を使用する構成が最近登録解除された場合は、WinRM サービスの再起動が必要になる場合があり、特定のシステム データ構造がまだキャッシュされている可能性があります。その場合は、WinRM の再起動が必要になる場合があります。 +Microsoft.PowerShell や Register-PSSessionConfiguration コマンドレットで作成されたセッション構成など、PowerShell セッション構成に接続されているすべての WinRM セッションは切断されます。 + + + リモート セッションで実行していて、"強制" オプションを選択しました。これは、WinRM サービスが再起動する可能性があることを意味します。WinRM サービスが再起動した場合、このリモート セッションは終了し、続行するには新しいセッションを作成する必要があります + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + WriteJobInResults パラメーターは、-Wait パラメーターなしでは使用できません + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + 指定された入力ストリームが無効です。{0} のみが入力ストリームとしてサポートされます。 + + + 指定された出力ストリーム セットが無効です。{0} のみが出力ストリームとしてサポートされます。 + + + 指定された WSMAN_SENDER_DETAILS は無効です。null 値の WSMAN_SENDER_DETAILS を処理できません。 + + + 指定されたシェル コンテキストが無効です。 + + + {0} + + + プラグイン メソッド {1} の {0}では null 値は許可されません。 + + + 入力ストリームと出力ストリーム セットに null 値は使用できません。{0} と {1} は、サポートされている入力ストリームと出力ストリームです。 + + + プラグイン メソッド {1} の {0}では null 値は許可されません。 + + + プラグイン メソッド {1} の {0}では null 値は許可されません。 + + + PowerShell プラグイン操作をシャットダウンしています。これは、ホスティング サービスまたはアプリケーションがシャットダウンしている場合に発生する可能性があります。 + + + PowerShell プラグインは、オプション {0} を理解していません。クライアントがビルド {1} および PowerShell のプロトコル バージョン {2} と互換性があることを確認します。 + + + {0} という名前のオプションがクライアントに必要です。クライアントがビルド {1} および PowerShell のプロトコル バージョン {2} と互換性があることを確認します。 + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Powershell プラグインは、クライアントによって要求されたプロトコル バージョン {2} をサポートしていません。</PSProtocolVersionError> + + + WSMan サービスへのコンテキストの報告中に、Powershell プラグインで致命的なエラーが発生しました。 + + + マネージド サーバー セッションを作成できません。 + + + PowerShell プラグインで、シャットダウン通知の待機ハンドルの登録中に致命的なエラーが発生しました。 + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + "{0}" 実行可能ファイルが見つかりませんでした。WOW64 機能がインストールされていることを確認します。 + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + このコンピューターでWindows PowerShellが見つからなかったため、Windows PowerShellプロセスを作成できません。 + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/RunspaceInit.ja.resx b/src/System.Management.Automation/resources/ja/RunspaceInit.ja.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/RunspaceInit.ja.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/RunspacePoolStrings.ja.resx b/src/System.Management.Automation/resources/ja/RunspacePoolStrings.ja.resx new file mode 100644 index 00000000000..bf154631f1b --- /dev/null +++ b/src/System.Management.Automation/resources/ja/RunspacePoolStrings.ja.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + プールの最大サイズを 1 未満にすることはできません。 + + + 最小プール サイズを 1 未満にすることはできません。 + + + 最小プール サイズを最大プール サイズより大きくすることはできません。 + + + この操作では、実行空間プールの状態が無効です。 + + + 実行空間プールが '{0}' 状態ではないため、操作を実行できません。現在の状態は '{1}' です。 + + + 実行空間プールは 'BeforeOpen' 状態ではないため、開けません。現在の状態は '{0}' です。 + + + {0} オブジェクトは、現在の RunspacePool インスタンスで {1} を呼び出すことによって作成されませんでした。 + + + 実行空間が現在のプールに属していないため、実行空間を現在のプールに解放できません。 + + + このプロパティは、実行空間プールを開いた後は変更できません。 + + + この実行空間では、切断操作と接続操作はサポートされていません。 + + + 実行空間プールが切断状態であるため、操作を実行できません。 + + + 切断操作はサーバーではサポートされていません。 リモート実行空間プールの切断をサポートするには、サーバーが PowerShell 3.0 以降を実行している必要があります。 + + + この実行空間プール {0} は、リモート サーバーで実行されているコマンドに対して切断された PowerShell オブジェクトを提供するように構成されていません。 RunspacePool クラス GetRunspacePools() 静的メソッドを使用して、サーバーにクエリを実行し、これを実行するように構成されている実行空間プール オブジェクトを返します。 + + + 対応するサーバー側の実行空間プールが別のクライアントに接続されているため、この実行空間プールを接続できません。 + + + ResetRunspaceState はサーバーではサポートされていません。 サーバーが PowerShell 5.0 以上を実行している必要があります。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/RunspaceStrings.ja.resx b/src/System.Management.Automation/resources/ja/RunspaceStrings.ja.resx new file mode 100644 index 00000000000..11b99fea10a --- /dev/null +++ b/src/System.Management.Automation/resources/ja/RunspaceStrings.ja.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + この操作では、実行空間の状態が無効です。 + + + 実行空間が BeforeOpen 状態ではないため、開くことができません。実行空間の現在の状態は '{0}' です。 + + + 実行空間プールがオープン状態ではないため、操作を実行できません。実行空間の現在の状態は '{0}' です。 + + + 実行空間がオープン状態ではないため、パイプラインを呼び出せません。実行空間の現在の状態は '{0}' です。 + + + この操作では、パイプラインの状態が無効です。 + + + パイプラインは既に呼び出されているため、呼び出せません。 + + + パラメーターの有効な値は PipelineResultTypes.Output です。 + + + パイプラインにコマンドが含まれていません。 + + + パイプラインは既に実行中のものがあるため実行されませんでした。Pipelines は同時に実行できません。 + + + 入れ子になったパイプラインを非同期的に呼び出すことはできません。呼び出しメソッドを使用してください。 + + + 入れ子になったパイプラインは、実行中のパイプライン内からのみ実行してください。 + + + SessionStateProxy メソッド呼び出しの進行中は、実行空間を閉じることはできません。 + + + SessionStateProxy メソッド呼び出しの進行中は、パイプラインを呼び出すことはできません。 + + + SessionStateProxy メソッド呼び出しが進行中です。SessionStateProxy メソッドの同時呼び出しは許可されていません。 + + + パイプラインは既に実行されています。SessionStateProxy メソッドの同時呼び出しは許可されていません。 + + + このプロパティは、実行空間を開いた後は変更できません。 + + + この実行空間の作成に使用された InitialSessionState オブジェクトで指定されたモジュール '{0}' の処理中に、1 つ以上のエラーが発生しました。全エラーの一覧については、ErrorRecords プロパティを参照してください。最初のエラーは次のとおりです: {1} + + + スレッド オプションを変更できるのは、アパートメント状態がマルチスレッド アパートメント (MTA) で、現在のオプションが UseNewThread または UseCurrentThread、かつ新しい値が ReuseThread の場合のみです。 + + + 言語モードが {1} または {2} の場合、{0}を false にすることはできません。 + + + ローカル専用の実行空間は切断できません。 + + + 接続操作は、ローカルの実行空間ではサポートされていません。 + + + セッションはビジー状態です。利用可能になり次第、セッションに接続されます。Enter-PSSession コマンドをキャンセルするには、Ctrl キーを押しながら C キーを押します。 + + + コマンドを完了できません。スクリプトの呼び出しは、このセッション構成ではサポートされていません。これは、セッション構成が no-language モードの場合に発生することがあります。 + + + ローカルの実行空間では、切断および接続の操作は使用できません。 + + + 実行空間がオープンの状態ではないため、パイプラインを接続できません。 実行空間の現在の状態は '{0}' です。 + + + RemoteRunspace を構築できません。指定された RunspacePool オブジェクトが無効です。 + + + この実行空間に関連付けられている切断されたコマンドはありません。 + + + リモート コンピューターでは切断操作はサポートされていません。切断をサポートするには、リモート コンピューターで Windows PowerShell 3.0 以降の Windows PowerShell を実行し、WSMan トランスポートを使用している必要があります。 + + + セッションが切断済みの状態ではないか、接続に使用できないため、PSSession に接続できません。 + + + パラメーターの値を PipelineResultTypes.None または PipelineResultTypes.Output にすることはできません。 + + + パラメーターの有効な値は PipelineResultTypes.Output または PipelineResultTypes.Null です。 + + + デバッグ ストリームのリダイレクトは、対象のリモート コンピューターではサポートされていません。 + + + 詳細ストリームのリダイレクトは、対象のリモート コンピューターではサポートされていません。 + + + 警告ストリームのリダイレクトは、対象のリモート コンピューターではサポートされていません。 + + + 情報ストリームのリダイレクトは、対象のリモート コンピューターではサポートされていません。 + + + コマンドまたはスクリプトの実行中でビジー状態のセッションに入りました。 出力はジョブ "{0}" にルーティングされるため、コンソールには表示されません。 実行中のコマンドの完了を待つか、Ctrl-C を押してキャンセルし、入力プロンプトを表示します。 + + + + コマンドまたはスクリプトの実行がビジー状態のセッションに入りました。出力はコンソールに表示されます。 実行中のコマンドの完了を待つか、Ctrl-C を押してキャンセルし、入力プロンプトを表示します。 + + + + 実行中のコマンドまたはスクリプト内のデバッグ ブレークポイントで現在停止しているセッションに入りました。 PowerShell コマンド ライン デバッガーを使用して、デバッグを続行してください。 + + + + DefaultRunspace は LocalRunspace である必要があります + + + 静的な PrimaryRunspace プロパティは 1 回しか設定できず、既に設定されています。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/SecuritySupportStrings.ja.resx b/src/System.Management.Automation/resources/ja/SecuritySupportStrings.ja.resx new file mode 100644 index 00000000000..1063fd89b70 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/SecuritySupportStrings.ja.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 証明書を読み込めません。'{0}' はファイル システム パスに解決する必要があります。 + + + 証明書 '{0}' は暗号化に使用できません。暗号化証明書には、データ暗号化キー使用法またはキー暗号化キー使用法を含め、ドキュメント暗号化拡張キー使用法 ({1}) を含める必要があります。 + + + 証明書を読み込むことができません。識別子 '{0}' は、複数の証明書と一致します。複数の受信者に暗号化するには、'{1}' パラメーターに、複数の証明書と一致するワイルドカードではなく、複数の特定の値を指定してください。 + + + 暗号化証明書を読み込めません。証明書設定 '{0}' は、有効な base-64 でエンコードされた証明書を表すものではなく、ファイル、ディレクトリ、拇印、またはサブジェクト名別の有効な証明書を表すものでもありません。 + + + 警告: 証明書 '{0}' に秘密キーが含まれています。暗号化に使用される保護されたイベント ログ証明書には、公開キーのみを含める必要があります。 + + + エラー: イベント ログ メッセージ '{0}' を保護できませんでした: {1} + + + エラー: 証明書が見つからないか、使用できませんでした: {0} + + + セッション キーは、安全な文字列を暗号化できません。 + + + バッファー オフセットが無効です。 + + + 公開キー データが無効です。 + + + 公開キーをインポートできません。 + + + セッション キー データが無効です。 + + + スクリプト ファイル '{0}' は、システム ポリシーによって実行がブロックされています。 + + + 不明なスクリプト ファイル ポリシーの適用値が返されました: {0}。 + + + スクリプト ファイルの読み取り + + + スクリプト ファイル '{0}' は、ポリシーによって信頼されていないため、ConstrainedLanguage モードで実行されます。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/Serialization.ja.resx b/src/System.Management.Automation/resources/ja/Serialization.ja.resx new file mode 100644 index 00000000000..7986456363d --- /dev/null +++ b/src/System.Management.Automation/resources/ja/Serialization.ja.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} 属性が必要です。 + + + {0} XML タグが認識されません。 + + + referenceId {0} のオブジェクトが見つかりません + + + ディクショナリ キーの "Name" 属性が正しく指定されていません。 + + + ディクショナリ値の "Name" 属性が正しく指定されていません。 + + + PSObject のバージョンが無効です。 + + + 受信 PSObject のバージョンは {0} です。必要な値は 1 です。 + + + referenceId {0}の TypeNames が見つからなかったため、名前を処理できません。 + + + 深度パラメーターの値は 1 以上である必要があります。 + + + 現在のノードの種類は {0} です。必要な型は {1} です。 + + + 辞書エントリのキーが指定されていません。 + + + ディクショナリ エントリの値が指定されていません。 + + + 逆シリアル化するオブジェクトはこれ以上ありません。 + + + null 値はディクショナリ キーとして指定されます。 + + + {0} プリミティブ型の内容が無効です。 + + + シリアル化された XML の入れ子が深すぎます。 + + + シリアライザーが閉じられました。 + + + コマンドのデータが、セッション構成で許可されている最大サイズを超えました。許可される最大値は {0} MB です。入力を変更するか、別のセッション構成を使用するか、リモート コンピューター上のセッション構成の "{1}" プロパティと "{2}" プロパティを変更します。 + + + 暗号化されたセキュリティで保護された文字列の逆シリアル化に失敗しました + + + {0} キーの型が無効です。PSPrimitiveDictionary クラスは、System.String 型のキーのみを受け入れます。 + + + {0} 値の型が無効です。PSPrimitiveDictionary クラスは、PowerShell リモート処理で完全にシリアル化できる型の値のみを受け入れます。完全にシリアル化可能な型の一覧については、ヘルプ トピック about_Remoting を参照してください。 + + + データの暗号化を解除できませんでした。データはこのキーで暗号化されていませんでした。 + + + パラメーター値 "{0}" は有効な暗号化された文字列ではありません。 + + + 指定された {0} が有効ではありません。有効な {0} の長さの設定は、128 ビット、192 ビット、または 256 ビットです。 + + + 現在、SecureString の逆シリアル化は Windows でのみサポートされています。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/SessionStateProviderBaseStrings.ja.resx b/src/System.Management.Automation/resources/ja/SessionStateProviderBaseStrings.ja.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/SessionStateProviderBaseStrings.ja.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/SessionStateStrings.ja.resx b/src/System.Management.Automation/resources/ja/SessionStateStrings.ja.resx new file mode 100644 index 00000000000..c7e0fa361c1 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/SessionStateStrings.ja.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + プロバイダーの Start メソッドから返された情報が、渡されたプロバイダーとは異なるプロバイダーに対して返されたため、返された情報を処理できません。 + + + プロバイダーの Start メソッドから返された情報が null 値のため、返された情報を処理できません。 + + + '{0}' プロバイダーで GetItems 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + GetItem 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで SetItems 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + SetItem 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで ClearItem 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで InvokeDefaultAction 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + InvokeDefaultAction 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで Exists 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + ItemExists 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで IsValidPath 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで IsItemContainer 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで RemoveItem 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで GetChildItems 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + GetChildItems 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで GetChildNames 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + GetChildNames 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで RenameItem 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + RenameItem 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで NewItem 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + NewItem 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで HasChildItems 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで CopyItem 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + CopyItem 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで GetParentPath 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで NormalizeRelativePath 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで MakePath 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで GetChildName 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで MoveItem 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + MoveItem 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで GetProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + GetProperty 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで SetProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + SetProperty 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで ClearProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + ClearProperty 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで NewProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + NewProperty 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで RemoveProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + RemoveProperty 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで CopyProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + パス '{1}' の '{0}' プロバイダーに対して CopyProperty 操作の動的パラメーターを取得できません。{2} + + + '{0}' プロバイダーで MoveProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + パス '{1}' の '{0}' プロバイダーに対して MoveProperty 操作の動的パラメーターを取得できません。{2} + + + '{0}' プロバイダーで RenameProperty 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + パス '{1}' の '{0}' プロバイダーの RenameProperty の動的パラメーターを取得できません。 {2} + + + パス '{1}' の '{0}' プロバイダーのコンテンツ リーダーを取得できません。{2} + + + パス '{1}' の '{0}' プロバイダーに対して GetContentReader 操作の動的パラメーターを取得できません。{2} + + + パス '{1}' の '{0}' プロバイダーのコンテンツ ライターを取得できません。{2} + + + パス '{1}' の '{0}' プロバイダーに対して GetContentWriter 操作の動的パラメーターを取得できません。{2} + + + ディレクトリであるため、コンテンツを取得できません: '{0}'。代わりに 'Get-ChildItem' を使用してください。 + + + ディレクトリであるため、コンテンツを書き込めません: '{0}'。 + + + 後ろに進む場所の履歴は残っていません。 + + + 前に進む場所の履歴は残っていません。 + + + BoundedStack が空です。 + + + '{0}' プロバイダーで ClearContent 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' はディレクトリであるため、その内容をクリアできません。Clear-Content はファイルでのみサポートされます。 + + + ClearContent 操作の動的パラメーターは、パス '{1}' の '{0}' プロバイダーから取得できません。{2} + + + '{0}' プロバイダーで GetSecurityDescriptor 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで SetSecurityDescriptor 操作を実行しようとしましたが、パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーで開始操作を実行できませんでした。{1} + + + '{0}' プロバイダーで InitializeDefaultDrives 操作を実行できませんでした。 + + + '{0}' プロバイダーで NewDrive 操作を実行しようとしましたが、ルート '{1}' のドライブに対して失敗しました。{2} + + + '{0}' プロバイダーの NewDrive の動的パラメーターを取得できません。{1} + + + '{0}' プロバイダーでの RemoveDrive の呼び出しに失敗しました。{1} + + + ドライブ '{0}' を削除できません。プロバイダー '{1}' によって防止されました。 + + + パス '{0}' は、ベース '{1}' の外側にある項目を参照しました。 + + + '{0}' プロバイダーのコンテンツ ライターで Seek の呼び出しがパス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーのコンテンツ リーダーまたはライターで Close を呼び出せませんでした。パス '{1}' に対して失敗しました。{2} + + + '{0}' プロバイダーのコンテンツ リーダーで Read の呼び出しがパス '{1}' に失敗しました。{2} + + + '{0}' プロバイダーのコンテンツ ライターで Write の呼び出しがパス '{1}' に対して失敗しました。{2} + + + プロバイダー '{0}' を使用して、変数構文を使用してデータを取得または設定することはできません。{2} + + + プロバイダーを使用して、変数構文を使用してデータを取得または設定することはできません。{2} + + + エイリアス {0} は読み取り専用または定数であり、書き込むことができないため、エイリアスは書き込み可能ではありません。 + + + 読み取り専用または定数であるため、関数 {0} に書き込めません。 + + + 変数 {0} は読み取り専用または定数であるため、上書きできません。 + + + 変数 '${0}' はプライベート変数であるため、アクセスできません。 + + + 非公開コマンドであるため、コマンド '{0}' にアクセスできません。 + + + プライベート コマンドであるため、コマンドにアクセスできません。 + + + セッション状態リソースは非公開リソースであるため、アクセスできません。 + + + エイリアス {0} が定数または読み取り専用であるため、エイリアスは削除されませんでした。 + + + 関数 {0} は定数であるため、削除できません。 + + + 変数 {0} は定数または読み取り専用であるため、削除できません。変数が読み取り専用の場合は、Force オプションを指定して操作を再試行してください。 + + + エイリアス {0} は定数のため変更できません。 + + + エイリアス {0} は読み取り専用のため変更できません。 + + + 関数 {0} は定数であるため、変更できません。 + + + 関数 {0} は読み取り専用のため、変更できません。 + + + エイリアス {0} は、作成後に定数にすることはできません。エイリアスは作成時にのみ定数にできます。 + + + 既存の関数 {0} を定数にすることはできません。関数は、作成時にのみ定数にすることができます。 + + + 既存の変数 {0} を定数にすることはできません。変数は、作成時にのみ定数にすることができます。 + + + AllScope オプションをエイリアス '{0}' から削除することはできません。 + + + AllScope オプションを関数 '{0}' から削除することはできません。 + + + AllScope オプションを変数 '{0}' から削除することはできません。 + + + 関数定義 '{0}' にスコープ修飾子が含まれていましたが、関数名が含まれていませんでした。 + + + プロバイダー {0} を削除できません。プロバイダー {0} を削除する前に、プロバイダー {0} に関連付けられているすべてのドライブを削除する必要があります。 + + + ドライブ名に無効な次の文字が 1 つ以上含まれているため、ドライブ名を処理できません: ;~ / \ .: + + + プロバイダーが新しいドライブの作成を許可していないため、新しいドライブの作成に失敗しました。 + + + 指定された値 '{0}' は複数の場所スタックに解決されました。 + + + 場所スタック '{0}' が見つかりません。存在しないか、コンテナーではありません。 + + + パス '{0}' は存在しないため、見つかりません。 + + + エイリアス '{0}' が存在しないため、エイリアスが見つかりません。 + + + パス '{0}' が複数のコンテナーに解決されたため、場所を設定できません。一度に設定できるコンテナーは 1 つだけです。 + + + 変数パス '{0}' が複数の項目に解決されたため、変数を処理できません。変数値は、一度に 1 つの項目のみを取得または設定できます。 + + + ドライブが見つかりません。'{0}' という名前のドライブは存在しません。 + + + '{0}' という名前のプロバイダーが見つかりません。 + + + '{0}' という名前のプロバイダーが見つかりません。名前の形式が正しくありません。プロバイダー名には、英数字、または 1 つの '\' の後に英数字が続く PowerShell スナップイン名のみを指定できます。 + + + '{0}' が複数のプロバイダー名に解決されました。一致の可能性は次のとおりです:{1}。 + + + プロバイダーのインスタンスの作成でエラーが発生しました。'{0}' のプロバイダー型名がアセンブリに見つかりませんでした。 + + + 無効な次の文字が 1 つ以上含まれているため、指定されたプロバイダー名 '{0}' を使用できません: \ [ ] ?* : + + + プロバイダー '{0}' のインスタンスの作成中にエラーが発生しました。{1} + + + '{0}' という名前の変数が見つかりません。 + + + '{0}' という名前のトレース ソースが見つかりません。 + + + '{0}' という名前のドライブは既に存在します。 + + + 名前 '{0}' の変数は既に存在します。 + + + '{0}' という名前のエイリアスが既に存在するため、エイリアスは使用できません。 + + + '{0}' という名前のコマンドレット プロバイダーが既に存在するため、コマンドレット プロバイダーを登録できません。 + + + パスはファイル システム パスを参照していません。 + + + グローバル スコープを削除できません。 + + + スコープ番号 '{0}' がアクティブなスコープの数を超えています。 + + + PSDriveInfo を比較できません。PSDriveInfo インスタンスは、別の PSDriveInfo インスタンスとのみ比較できます。 + + + コマンドレット プロバイダーは、出力のストリーミングに使用するコマンドレットが指定されていないため、結果をストリームできません。 + + + コマンドレット プロバイダーは、エラーのストリーミングに使用するコマンドレットが指定されていないため、結果をストリームできません。 + + + このプロバイダーのホームの場所が設定されていません。ホームの場所を設定するには、"(get-psprovider'{0}') を呼び出します。ホーム = 'path'"。 + + + パスが不適切な形式です。プロバイダー パスには、プロバイダー ID と "::" の後にプロバイダー固有のパスが含まれている必要があります。 + + + 移動先のパスは 1 つのパスにのみ解決できるため、項目を移動できません。 + + + ソース パスと宛先パスが同じプロバイダーに解決されなかったため、項目を移動できません。 + + + ソース パスが 1 つ以上の項目を指しており、宛先パスがコンテナーではないため、項目を移動できません。宛先パスがコンテナーであることを確認してから、もう一度やり直してください。 + + + 宛先が複数のパスに解決されたため、項目を移動できません。1 つの宛先に解決される宛先パスを指定してから、もう一度お試しください。 + + + コンテナーを既存のリーフ項目にコピーすることはできません。 + + + コンテナーを別のコンテナーにコピーすることはできません。-Recurse パラメーターまたは -Container パラメーターが指定されていません。 + + + ソース パスと宛先パスが同じプロバイダーに解決されませんでした。 + + + パスが複数の項目に解決されたため、項目の名前を変更できません。一度に名前を変更できる項目は 1 つだけです。 + + + プロバイダーでエラーが発生したため、プロバイダー '{0}' を使用してパス '{1}' を解決することはできません。 + + + インターフェイスを使用できません。IContentCmdletProvider インターフェイスは、このプロバイダーによって実装されていません。 + + + インターフェイスを使用できません。IPropertyCmdletProvider インターフェイスは、このプロバイダーではサポートされていません。 + + + インターフェイスを使用できません。IDynamicPropertyCmdletProvider インターフェイスは、このプロバイダーによって実装されていません。 + + + NavigationCmdletProvider メソッドは、このプロバイダーではサポートされていません。 + + + プロバイダー メソッドが処理されませんでした。ContainerCmdletProvider メソッドは、このプロバイダーではサポートされていません。 + + + メソッドを呼び出せません。ItemCmdletProvider メソッドは、このプロバイダーではサポートされていません。 + + + DriveCmdletProvider メソッドは、このプロバイダーではサポートされていません。 + + + プロバイダーがこの操作をサポートしていないため、プロバイダー操作が停止しました。 + + + プロバイダーが 'Depth' パラメーターをサポートしていないため、プロバイダー操作が停止しました。 + + + メソッドを呼び出すことはできません。コンテンツ シーク メソッドは、このプロバイダーではサポートされていません。 + + + ClearContent 操作を実行できません。ClearContent 操作は、このプロバイダーではサポートされていません。 + + + プロバイダーは資格情報の使用をサポートしていません。資格情報を指定せずに操作をもう一度実行してください。 + + + FileSystem プロバイダーは、New-PSDrive コマンドレットでのみ資格情報をサポートします。資格情報を指定せずに操作をもう一度実行してください。 + + + プロバイダーはトランザクションをサポートしていません。-UseTransaction パラメーターを指定せずに操作をもう一度実行します。 + + + メソッドを呼び出すことはできません。プロバイダーはフィルターの使用をサポートしていません。 + + + ドライブを作成できません。プロバイダーは資格情報の使用をサポートしていません。 + + + パス '{0}' の項目は既に存在します。 + + + 項目をコピーできません。パス '{0}' の項目が存在しません。 + + + パス '{0}' の項目が存在しません。 + + + セッション状態に格納されているエイリアスのビューを含むドライブ + + + プロセスの環境変数のビューを含むドライブ + + + セッション状態に格納されている関数のビューを含むドライブ + + + セッション状態に格納されているそれらの変数のビューを含むドライブ + + + 現在のユーザーの一時ディレクトリ パスにマップされるドライブ + + + ターゲット値が指定されていないため、リンク '{0}' を作成できません。 + + + null 変数への参照は、常に null 値を返します。割り当ては無効です。 + + + セッションで保持する履歴オブジェクトの最大数 + + + 関数 {0} が読み取り専用または定数であるため、関数の名前を変更できません。 + + + エイリアスの名前を変更できません。エイリアス {0} は読み取り専用または定数です。 + + + 変数 {0} が読み取り専用または定数であるため、変数の名前を変更できません。 + + + ローカル変数 {0} にオプションを設定できません。New-Variable を使用して、オプションを設定できる変数を作成してください。 + + + コマンドレット {0} は読み取り専用のため変更できません。 + + + 変数が最適化されており、削除できないため、変数 {0} を削除できません。Remove-Variable コマンドレット (エイリアスなし) を使用するか、変数を削除するために使用しているコマンドをドットソース化してみてください。 + + + 変数が最適化されているため、変数 {0} を上書きできません。New-Variable コマンドレットまたは Set-Variable コマンドレット (エイリアスなし) を使用するか、変数の設定に使用しているコマンドをドットソースで指定します。 + + + {0} パラメーターと {1} パラメーターを一緒に使用することはできません。パラメーターを 1 つだけ指定してください。 + + + Tail パラメーターは現在、FileSystem プロバイダーでのみサポートされています。 + + + '{0}' という名前のコマンドとコマンドの種類 '{1}' が既に存在するため、エイリアスは使用できません。 + + + ソフトウェアを実行できません。アクセス許可が拒否されました。 + + + '-{0}' と '-{1}' は相互に排他的であり、同時に指定することはできません。 + + + パス '{0}' が無効です。リモート コピー操作では、絶対パスのみがサポートされます。 + + + リモート パス '{0}' を検証できません。 + + + セッション {0} が {1} に設定されているため、操作を実行できません。 + + + '{0}' パラメーターを null 値や空にすることはできません。 + + + セッション状態変数 + + + 変数 '{0}' スコープを AllScope に変更または作成することは、ConstrainedLanguage モードでは禁止されます。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/StringDecoratedStrings.ja.resx b/src/System.Management.Automation/resources/ja/StringDecoratedStrings.ja.resx new file mode 100644 index 00000000000..eff2c52e695 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/StringDecoratedStrings.ja.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + このメソッドでは、'ANSI' または 'PlainText' のみがサポートされています。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/SubsystemStrings.ja.resx b/src/System.Management.Automation/resources/ja/SubsystemStrings.ja.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/ja/SubsystemStrings.ja.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/SuggestionStrings.ja.resx b/src/System.Management.Automation/resources/ja/SuggestionStrings.ja.resx new file mode 100644 index 00000000000..70309cdfb53 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/SuggestionStrings.ja.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 + + + コマンド "{0}" は見つかりませんでしたが、現在の場所に存在します。 +PowerShell は既定で、現在の場所からコマンドを読み込みません ('Get-Help about_Command_Precedence' を参照)。 + +このコマンドを信頼する場合は、代わりに次のコマンドを実行してください: + + + 最も類似しているコマンドは次のとおりです: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/TabCompletionStrings.ja.resx b/src/System.Management.Automation/resources/ja/TabCompletionStrings.ja.resx new file mode 100644 index 00000000000..3028018850e --- /dev/null +++ b/src/System.Management.Automation/resources/ja/TabCompletionStrings.ja.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + リモート実行空間に TypeTable インスタンスが含まれていないため、タブ補完の結果を正しく逆シリアル化できません。 + + + CompletionResult 型の null インスタンスのプロパティにアクセスできません。 + + + ビットごとの NOT + + + 論理 Not。その後のステートメントを否定します。 + + + 等しい - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランドと等しい値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと等しい場合は TRUE を返します。 + + + 等しい - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランドと等しい値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと等しい場合は TRUE を返します。 + + + 等しい - 大文字と小文字を区別します。左オペランドがコレクションの場合は、右オペランドと等しい値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと等しい場合は TRUE を返します。 + + + 等しくない - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランドと等しくない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと等しくない場合は TRUE を返します。 + + + 等しくない - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランドと等しくない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと等しくない場合は TRUE を返します。 + + + 等しくない - 大文字と小文字が区別されます。左オペランドがコレクションの場合は、右オペランドと等しくない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと等しくない場合は TRUE を返します。 + + + 以上 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランド以上の値をコレクションから返します。それ以外の場合、左オペランドが右オペランド以上の場合は TRUE を返します。 + + + 以上 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランド以上の値をコレクションから返します。それ以外の場合、左オペランドが右オペランド以上の場合は TRUE を返します。 + + + 以上 - 大文字と小文字が区別されます。左オペランドがコレクションの場合は、右オペランド以上の値をコレクションから返します。それ以外の場合、左オペランドが右オペランド以上の場合は TRUE を返します。 + + + より大きい - 大文字と小文字が区別されません。左オペランドがコレクションの場合は、右オペランドより大きい値をコレクションから返します。それ以外の場合、左オペランドが右オペランドより大きい場合は TRUE を返します。 + + + より大きい - 大文字と小文字が区別されません。左オペランドがコレクションの場合は、右オペランドより大きい値をコレクションから返します。それ以外の場合、左オペランドが右オペランドより大きい場合は TRUE を返します。 + + + より大きい - 大文字と小文字が区別されます。左オペランドがコレクションの場合は、右オペランドより大きい値をコレクションから返します。それ以外の場合、左オペランドが右オペランドより大きい場合は TRUE を返します。 + + + より小さい - 大文字と小文字が区別されません。左オペランドがコレクションの場合、右オペランドより小さい値をコレクションから返します。それ以外の場合、左オペランドが右オペランドより小さい場合は TRUE を返します。 + + + より小さい - 大文字と小文字が区別されません。左オペランドがコレクションの場合、右オペランドより小さい値をコレクションから返します。それ以外の場合、左オペランドが右オペランドより小さい場合は TRUE を返します。 + + + より小さい - 大文字と小文字が区別されます。左オペランドがコレクションの場合、右オペランドより小さい値をコレクションから返します。それ以外の場合、左オペランドが右オペランドより小さい場合は TRUE を返します。 + + + 以下 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランド以下の値をコレクションから返します。それ以外の場合は、左オペランドが右オペランド以下であれば TRUE を返します。 + + + 以下 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右オペランド以下の値をコレクションから返します。それ以外の場合は、左オペランドが右オペランド以下であれば TRUE を返します。 + + + 以下 - 大文字と小文字が区別されます。左オペランドがコレクションの場合は、右オペランド以下の値をコレクションから返します。それ以外の場合は、左オペランドが右オペランド以下であれば TRUE を返します。 + + + ワイルドカード一致演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドに一致する値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと一致する場合は TRUE を返します。 + + + ワイルドカード一致演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドに一致する値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと一致する場合は TRUE を返します。 + + + ワイルドカード照合演算子 - 大文字と小文字が区別されます。左オペランドがコレクションの場合は、右側のオペランドに一致する値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと一致する場合は TRUE を返します。 + + + ワイルドカード一致演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドと一致しない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと一致しない場合は TRUE を返します。 + + + ワイルドカード一致演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドと一致しない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと一致しない場合は TRUE を返します。 + + + ワイルドカード照合演算子 - 大文字と小文字が区別されます。左オペランドがコレクションの場合は、右側のオペランドと一致しない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと一致しない場合は TRUE を返します。 + + + 正規表現照合演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドに一致する値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと一致する場合は TRUE を返します。 + + + 正規表現照合演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドに一致する値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと一致する場合は TRUE を返します。 + + + 正規表現照合演算子 - 大文字と小文字を区別します。左オペランドがコレクションの場合は、右側のオペランドに一致する値をコレクションから返します。それ以外の場合は、左オペランドが右オペランドと一致する場合は TRUE を返します。 + + + 正規表現照合演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドと一致しない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと一致しない場合は TRUE を返します。 + + + 正規表現照合演算子 - 大文字と小文字を区別しません。左オペランドがコレクションの場合は、右側のオペランドと一致しない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと一致しない場合は TRUE を返します。 + + + 正規表現照合演算子 - 大文字と小文字を区別します。左オペランドがコレクションの場合は、右側のオペランドと一致しない値をコレクションから返します。それ以外の場合、左オペランドが右オペランドと一致しない場合は TRUE を返します。 + + + Replace 演算子 - 大文字と小文字を区別しません。左オペランドを変更します。例: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace 演算子 - 大文字と小文字を区別しません。左オペランドを変更します。例: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace 演算子 - 大文字と小文字を区別します。左オペランドを変更します。例: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (右オペランド) が左オペランドの少なくとも 1 つの値と完全に一致する場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (右オペランド) が左オペランドの少なくとも 1 つの値と完全に一致する場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別します。テスト値 (右オペランド) が左オペランドの少なくとも 1 つの値と完全に一致する場合にのみ TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (右オペランド) が左オペランドの値と完全に一致しない場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (右オペランド) が左オペランドの値と完全に一致しない場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別します。テスト値 (右オペランド) が左オペランドの値と完全に一致しない場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (左オペランド) が右オペランドの少なくとも 1 つの値と完全に一致する場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (左オペランド) が右オペランドの少なくとも 1 つの値と完全に一致する場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別します。テスト値 (左オペランド) が右オペランドの少なくとも 1 つの値と完全に一致する場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別します。テスト値 (左オペランド) が右オペランドの値と完全に一致しない場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別しません。テスト値 (左オペランド) が右オペランドの値と完全に一致しない場合に TRUE を返します。 + + + Containment 演算子 - 大文字と小文字を区別します。テスト値 (左オペランド) が右オペランドの値と完全に一致しない場合に TRUE を返します。 + + + 分割 -大文字と小文字の区別しません。1 つ以上の文字列を部分文字列に分割します。 +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + 分割 -大文字と小文字の区別しません。1 つ以上の文字列を部分文字列に分割します。 +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + 分割 - 大文字と小文字を区別します。1 つ以上の文字列を部分文字列に分割します。 +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + 左オペランドが指定した.NET Framework 型 (右オペランド) のインスタンスでない場合は TRUE を返します。 + + + 左オペランドが指定した .NET Framework 型 (右オペランド) のインスタンスである場合は TRUE を返します。 + + + 左オペランドを指定した.NET Framework 型 (右オペランド) に変換します。 + + + 文字列オブジェクトの format メソッドを使用して文字列を書式設定します。 + + + 論理 AND。両方のステートメントが TRUE の場合は TRUE を返します。 + + + ビットごとの AND + + + 論理 OR。いずれかのステートメントまたは両方のステートメントが TRUE の場合は TRUE です。 + + + ビットごとの OR (両端を含む) + + + 論理排他的 or。ステートメントの 1 つが TRUE で、もう一方が FALSE の場合は TRUE を返します。 + + + ビットごとの OR (排他的) + + + 結合 - 複数の文字列を 1 つの文字列に結合します。 +-Join <String[]> +<String[]> -Join <Delimiter> + + + 左ビット演算子をシフトします。右端のビット位置に 0 を挿入します。 + + + 右ビット演算子をシフトします。左端のビット位置に 0 を挿入します。符号付き値の場合、符号ビットは保持されます。 + + + [string] +作成するプロパティの名前を指定します。 + + + [string] +作成するプロパティの名前を指定します。 + + + [scriptblock] +新しいプロパティの値を計算するために使用されるスクリプト ブロックです。 + + + [string] +列に値を表示する方法を定義します。 +有効な値は、'left'、'center'、または 'right' です。 + + + [string] +値を出力用に書式設定する方法を定義する書式指定文字列を指定します。 + + + [int] +値を表示するときのテーブルの列の最大幅を指定します。 +値は 0 より大きくする必要があります。 + + + [int] +深度キーは、プロパティごとの展開の深さを指定します。 + + + [bool] +1 つ以上のプロパティの並べ替え順序を指定します。 + + + [bool] +1 つ以上のプロパティの並べ替え順序を指定します。 + + + [String[]] +イベントを取得するログ名を指定します。 +ワイルドカードがサポートされます。 + + + [String[]] +イベントを取得するイベント ログ プロバイダーを指定します。 +ワイルドカードがサポートされます。 + + + [String[]] +イベントを取得するログ ファイルのファイル パスを指定します。 +有効なファイル形式: .etl、.evt、および .evtx + + + [Long[]] +指定したキーワード ビットマスクを持つイベントを選択します。 +標準キーワードは次のとおりです: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +指定したイベント ID を持つイベントを選択します。 + + + [int[]] +指定したログ レベルのイベントを選択します。 +次のログ レベルが有効です: +1: クリティカル +2: エラー +3: 警告 +4: 情報 +5: 詳細 + + + [datetime] +指定した日時より後に作成されたイベントを選択します。 + + + [datetime] +指定した日時より前に作成されたイベントを選択します。 + + + [string] +指定したユーザーによって生成されたイベントを選択します。 +これは、SID または DOMAIN\USERNAME または USERNAME@DOMAIN の形式のドメイン名とユーザー名を表す文字列のいずれかです + + + [string[]] +EventData セクションで指定した値のいずれかを持つイベントを選択します。 + + + [hashtable] +ハッシュテーブルで指定された値と一致するイベントを除外します。 + + + [string] または [hashtable] +スクリプトに必要な PowerShell モジュールの配列を指定します。 +各要素には、モジュール名を値として含む文字列、または次のキーを持つハッシュテーブルを指定できます: +名前: モジュールの名前 +GUID: モジュールの GUID +次のいずれか: +ModuleVersion: モジュールの最小許容バージョンを指定します。 +RequiredVersion: モジュールの正確で必要なバージョンを指定します。 +MaximumVersion: モジュールの許容される最大バージョンを指定します。 + + + [string] +スクリプトに必要な PowerShell エディションを指定します。 +有効な値は "Core" と "Desktop" です + + + [switch] +PowerShell が Windows で管理者として実行されている必要があることを指定します。 +これは、#requires ステートメント行の最後のパラメーターである必要があります。 + + + [version] +スクリプトに必要な PowerShell の最小バージョンを指定します。 + + + スクリプトの実行に PowerShell 7 以降が必要であることを指定します。 + + + スクリプトの実行に Windows PowerShell 5.1 が必要であることを指定します。 + + + [string] +必須です。モジュール名を指定します。 + + + [string] +省略可能です。モジュールの GUID を指定します。 + + + [string] +モジュールの最小許容バージョンを指定します。 + + + [string] +モジュールの正確で必要なバージョンを指定します。 + + + [string] +モジュールの許容される最大バージョンを指定します。 + + + 関数またはスクリプトの簡単な説明です。 +このキーワードは、各トピックで 1 回だけ使用できます。 + + + 関数またはスクリプトの詳細な説明。 +このキーワードは、各トピックで 1 回だけ使用できます。 + + + .PARAMETER <Parameter-Name> +パラメーターの説明。 +関数またはスクリプトの構文の各パラメーターに .PARAMETER キーワードを追加してください。 + + + 関数またはスクリプトを使用するサンプル コマンドです。必要に応じて、サンプル出力と説明が続きます。 +各例に対してこのキーワードを繰り返してください。 + + + 関数またはスクリプトにパイプできる .NET 型のオブジェクトです。 +入力オブジェクトの説明を含めることもできます。 + + + コマンドレットが返すオブジェクトの .NET 型。 +返されるオブジェクトの説明を含めることもできます。 + + + 関数またはスクリプトに関する追加情報です。 + + + 関連トピックの名前。 +関連する各トピックの .LINK キーワードを繰り返します。 +.Link キーワード コンテンツには、同じヘルプ トピックのオンライン バージョンへの URI を含めることもできます。 + + + 関数またはスクリプトが使用するテクノロジーまたは機能の名前、または関連するテクノロジーまたは機能の名前です。 + + + ヘルプ トピックのユーザー ロールの名前です。 + + + 関数の使用目的を説明するキーワードです。 + + + .FORWARDHELPTARGETNAME <Command-Name> +指定したコマンドのヘルプ トピックにリダイレクトします。 + + + .FORWARDHELPCATEGORY <Category> +.ForwardHelpTargetName の項目のヘルプ カテゴリを指定します + + + .REMOTEHELPRUNSPACE <PSSession-variable> +ヘルプ トピックを含むセッションを指定します。 +PSSession オブジェクトを含む変数を入力してください。 + + + .EXTERNALHELP <XML Help File> +関数またはスクリプトが XML ファイルにドキュメント化されている場合は、.ExternalHelp キーワードが必要です。 + + + 読み込む .NET アセンブリへのパスを指定します。 + +アセンブリ <NET-assembly-path> を使用します + + + クラスを読み込む PowerShell モジュールを指定します。 + +モジュール <ModuleName or Path> を使用しています + +モジュール <ModuleSpecification hashtable> を使用しています + + + 型を解決する .NET 名前空間または名前空間エイリアスを指定します。 + +名前空間 <NET-namespace> を使用します + +名前空間 <AliasName> = <.NET-namespace> を使用します + + + .NET 型のエイリアスを指定します。 + +型 <AliasName> = <.NET-type> を使用しています + + + 通常の文字列。 + + + 値が読み出されるときに展開される環境変数の展開されない参照を含む文字列です。 + + + 任意の形式のバイナリ データ。 + + + 32 ビットの2 進数。 + + + 文字列の配列。 + + + 64 ビットの 2 進数。 + + + サポートされていないレジストリ データ型。 + + + ',' - コンマ + + + ', ' -コンマと空白 + + + ';' - セミコロン + + + '; ' - セミコロンと空白 + + + {0} - 改行 + + + '-' - ダッシュ + + + ' ' - 空白 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/TransactionStrings.ja.resx b/src/System.Management.Automation/resources/ja/TransactionStrings.ja.resx new file mode 100644 index 00000000000..25e6d93847a --- /dev/null +++ b/src/System.Management.Automation/resources/ja/TransactionStrings.ja.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + トランザクションを使用できません。アクティブなトランザクションはありません。 + + + トランザクションをコミットできません。アクティブなトランザクションはありません。 + + + アクティブなトランザクションがないため、トランザクションをロールバックできません。 + + + トランザクションをロールバックできません。トランザクションは既にコミットされています。 + + + トランザクションをコミットできません。トランザクションは既にコミットされています。 + + + トランザクションをコミットできません。トランザクションはロールバックされたか、タイムアウトしました。 + + + トランザクションをロールバックできません。トランザクションは既にロールバックされたか、タイムアウトしています。 + + + アクティブなトランザクションを設定できません。トランザクションが作成されていません。 + + + アクティブなトランザクションを設定できません。アクティブなトランザクションがロールバックされたか、タイムアウトしました。 + + + このコマンドレットにはアクティブなトランザクションが必要です。現在のトランザクションは既にコミットまたはロールバックされています。 + + + このコマンドレットにはトランザクションが必要です。-UseTransaction パラメーターを指定して、コマンドをもう一度実行してください。 + + + トランザクションを使用できません。トランザクションが開始されていません。 + + + トランザクションを使用できません。トランザクションがコミットされました。 + + + トランザクションを使用できません。トランザクションはロールバックされたか、タイムアウトしました。 + + + トランザクションを使用できません。トランザクションがタイムアウトしました。 + + + ベース トランザクションが設定されていません。 + + + ベース トランザクションがアクティブではありません。 + + + 他のトランザクションが作成された後は、ベース トランザクションを設定できません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/TypesXmlStrings.ja.resx b/src/System.Management.Automation/resources/ja/TypesXmlStrings.ja.resx new file mode 100644 index 00000000000..a0f8fec1bf8 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/TypesXmlStrings.ja.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}、{1}({2}) : エラー: {3} + + + {0}、{1}({2}): 型"{3}" でのエラー: {4} + + + ノード "{0}" は、"{1}" の下に 1 回だけ出現する必要があります。親ノード "{1}" は無視されます。 + + + ノード {0} は許可されていません。次のノードが許可されています: {1}。 + + + ノード "{0}" に内部テキストを含めることはできません。 + + + ノード "{0}" には内部テキストが必要です。 + + + ノード '{0}' が見つかりませんでした。これは、"{1}" の下で 1 回だけ発生する必要があります。親ノード "{1}" は無視されます。 + + + "Type" ノードには、"Members"、"TypeConverters"、または "TypeAdapters" が必要です。 + + + 例外が原因で、型 {0} の型コンバーターのインスタンスを作成できません: {1}。 + + + 次の例外が発生したため、PowerShell は型 {0} の型アダプターのインスタンスを作成できません: {1}。 + + + 適応された型 "{0}" は無効です。 + + + TypeConverter は、既に発生しているため、無視されました。 + + + TypeAdapter は、既に発生しているため、無視されました。 + + + 型 "{0}" は TypeConverter または PSTypeConverter のいずれかである必要があります。 + + + 型 "{0}" は PSPropertyAdapter である必要があります。 + + + メンバー {0} は既に存在します。 + + + 次のメンバー名が予約されています: {0} + + + 例外: {0} + + + ScriptProperty には getter または setter が必要です。 + + + CodeProperty には、getter または setter が必要です。 + + + {0}、{1}: {2} + + + 値は、{0} ではなく、TRUE または FALSE である必要があります。 + + + ノード "{0}" に "{1}" 属性を指定することはできません。 + + + {0}、{1}: ファイルが見つかりませんでした。 + + + {0}、{1}: このファイルは、{2} によって既に読み込まれているため、スキップされました。 + + + レジストリ キーが見つかりません: {0}{1}。{2} を使用して構成ファイルを読み込んでいます。 + + + レジストリ キー内に指定されたパス {0} が見つかりません: {1}{2}。{3} を使用して構成ファイルを読み込んでいます。 + + + {0}、{1}: このファイルは、ps1xml ファイル名拡張子がないため、スキップされました。 + + + {0}、{1}: 次の検証例外が発生したため、ファイルはスキップされました: {2}。 + + + メンバー "{0}" はメモである必要があります。 + + + メモ "{0}" を変換できません: "{1}"。 + + + ここではメンバー "{0}" を使用しないでください。 + + + メンバー "{0}" の型は "{1}" である必要があります。 + + + "{1}" が "{2}" で、"{3}" が "{4}" である場合、"{0}" が存在する必要があります。 + + + 以前のエラーが原因で、すべてのシリアル化設定が無視されました。 + + + "{0}" は標準メンバーではないため、無視されます。 + + + {0} パスは完全修飾パスではありません。完全修飾型のファイル パスを指定してください。 + + + TypeTable が実行空間の外部に作成されている可能性があるため、TypeTable を更新できません。 + + + TypeTable の読み込み中にエラーが発生しました。Errors プロパティ内を検索して、詳細なエラー メッセージを取得してください。 + + + TypeData "{0}" でのエラー: {1} + + + "{0}" には、そのプロパティ "{1}" の値が必要です。 + + + "{0}" のプロパティ "{1}" に null または空の文字列を含めることはできません。 + + + 型 "{0}" が見つかりませんでした。型名の値は、型の完全な名前である必要があります。型名を確認して、コマンドをもう一度実行してください。 + + + TypeData には、"Members"、"TypeConverters"、"TypeAdapters"、または "StandardMembers" が必要です。 + + + 共有型テーブルを複数のエントリを使用して更新することはできません。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/VerbDescriptionStrings.ja.resx b/src/System.Management.Automation/resources/ja/VerbDescriptionStrings.ja.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/ja/VerbDescriptionStrings.ja.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ja/WildcardPatternStrings.ja.resx b/src/System.Management.Automation/resources/ja/WildcardPatternStrings.ja.resx new file mode 100644 index 00000000000..0aa26a1f1cc --- /dev/null +++ b/src/System.Management.Automation/resources/ja/WildcardPatternStrings.ja.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 + + + 指定されたワイルドカード文字パターンが無効です: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/Authenticode.ko.resx b/src/System.Management.Automation/resources/ko/Authenticode.ko.resx new file mode 100644 index 00000000000..84ff9977cf5 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/Authenticode.ko.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 + + + 지금 이 소프트웨어를 실행하지 않도록 선택했기 때문에 File {0}을(를) 로드할 수 없습니다. + + + 이 게시자의 소프트웨어를 다시는 실행하지 않기로 선택했기 때문에 File {0}을(를) 로드할 수 없습니다. + + + File {0}은(는) {1}에서 게시되었습니다. 이 게시자는 시스템에서 명시적으로 신뢰되지 않습니다. 이 시스템에서는 스크립트가 실행되지 않습니다. 자세한 내용은 "get-help about_signing" 명령을 실행하세요. + + + 이 시스템에서 스크립트 실행이 사용하지 않도록 설정되어 있으므로 File {0}을(를) 로드할 수 없습니다. 자세한 내용은 https://go.microsoft.com/fwlink/?LinkID=135170.의 about_Execution_Policies를 참조하세요. + + + 파일 {0}은(는) 로드할 수 없습니다. {1}. + + + 그룹 정책에서 만든 것과 같은 소프트웨어 제한 정책 때문에 작업이 차단되어 File {0}을(를) 로드할 수 없습니다. + + + 콘텐츠를 읽을 수 없으므로 File {0}을(를) 로드할 수 없습니다. + + + 코드에 서명할 수 없습니다. 지정한 인증서는 코드 서명에 적합하지 않습니다. + + + 코드에 서명할 수 없습니다. TimeStamp 서버 URL은 정규화된 형식이어야 하며, http://<server url> 또는 https://<server url> 형식이어야 합니다. + + + 코드에 서명할 수 없습니다. 해시 알고리즘은 지원되지 않습니다. + + + 이 신뢰할 수 없는 게시자의 소프트웨어를 실행하시겠습니까? + + + File {0}은(는) {1}에서 게시되었으며 시스템에서 신뢰할 수 없습니다. 신뢰할 수 있는 게시자의 스크립트만 실행하세요. + + + 알 수 없는 게시자가 Software {0}을(를) 게시했습니다. 이 소프트웨어는 실행하지 않는 것이 좋습니다. + + + 보안 경고 + + + 신뢰하는 스크립트만 실행합니다. 인터넷에서 받은 스크립트는 유용할 수 있지만, 이 스크립트는 컴퓨터에 해를 끼칠 수 있습니다. 이 스크립트를 신뢰하면 Unblock-File cmdlet을 사용해 이 경고 메시지 없이 스크립트가 실행되도록 허용하세요. {0}을(를) 실행하시겠습니까? + + + Ne&ver 실행 안 함 + + + 지금은 이 게시자의 스크립트를 실행하지 말고, 앞으로도 이 스크립트를 실행할지 묻지 마세요. 나중에 이 스크립트를 실행하려고 하면 오류 메시지 없이 실패합니다. + + + 실행 안 함(&D) + + + 지금은 이 게시자의 스크립트를 실행하지 말고, 앞으로도 이 스크립트를 실행할지 계속 묻도록 하세요. + + + 한 번 실행(&R) + + + 이 게시자의 스크립트를 지금 실행하고, 앞으로도 이 스크립트를 실행할지 계속 묻도록 하세요. + + + 항상 실행(&A) + + + 이 게시자의 스크립트를 지금 실행하고, 앞으로는 이 스크립트를 실행할지 묻지 마세요. + + + 일시 중단(&S) + + + 현재 파이프라인을 일시 중지하고 명령 프롬프트로 돌아갑니다. 작업을 마치면 exit를 입력해 다시 시작하세요. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/AuthorizationManagerBase.ko.resx b/src/System.Management.Automation/resources/ko/AuthorizationManagerBase.ko.resx new file mode 100644 index 00000000000..e8c8064c436 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/AuthorizationManagerBase.ko.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 + + + AuthorizationManager 확인에 실패했습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/AutomationExceptions.ko.resx b/src/System.Management.Automation/resources/ko/AutomationExceptions.ko.resx new file mode 100644 index 00000000000..1eddf016c1b --- /dev/null +++ b/src/System.Management.Automation/resources/ko/AutomationExceptions.ko.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 인수 "{0}"의 값이 유효하지 않아 인수를 처리할 수 없습니다. "{0}" 인수의 값을 변경한 다음 작업을 다시 실행하세요. + + + 매개 변수 "{0}"의 값이 유효하지 않아 인수를 처리할 수 없습니다. 유효한 값은 "Global", "Local", "Script" 또는 현재 범위와 관련된 수(0부터 범위 수까지, 여기서 0은 현재 범위이고 1은 그 상위 범위)입니다. "{0}" 매개 변수의 값을 변경한 다음 작업을 다시 실행하세요. + + + 인수 "{0}"의 값이 null이므로 인수를 처리할 수 없습니다. 인수 "{0}"의 값을 null이 아닌 값으로 변경하세요. + + + 인수 "{0}"의 값이 범위를 벗어났으므로 인수를 처리할 수 없습니다. 인수 "{0}"을(를) 범위 내의 값으로 변경하세요. + + + 작업 "{0}"이(가) 유효하지 않아 작업을 수행할 수 없습니다. 작업 "{0}"을(를) 제거하거나 유효하지 않은 이유를 확인하세요. + + + 작업 "{0}"이(가) 구현되지 않았으므로 작업을 수행할 수 없습니다. + + + "{0}" 작업은 지원되지 않으므로 작업을 수행할 수 없습니다. + + + 개체 "{0}"이(가) 이미 삭제되었으므로 작업을 수행할 수 없습니다. + + + 스크립트 블록에 절이 두 개 이상 포함되어 있으므로 호출할 수 없습니다. Invoke() 메서드는 단일 절을 포함한 스크립트 블록에서만 사용할 수 있습니다. + + + 스크립트 블록에 절이 두 개 이상 포함되어 있으므로 변환할 수 없습니다. 식이나 제어 구조는 허용되지 않습니다. 스크립트 블록에 정확히 하나의 파이프라인이나 명령이 포함되어 있는지 확인하세요. + + + 빈 스크립트 블록은 변환할 수 없습니다. 스크립트 블록에 정확히 하나의 파이프라인이나 명령이 포함되어 있는지 확인하세요. + + + 정확히 하나의 파이프라인이나 명령을 포함한 스크립트 블록만 변환할 수 있습니다. 식이나 제어 구조는 허용되지 않습니다. 스크립트 블록에 정확히 하나의 파이프라인이나 명령이 포함되어 있는지 확인하세요. + + + 최상위 trap 문이 포함된 스크립트 블록은 변환할 수 없습니다. + + + param(...) 블록에서 선언되지 않은 변수를 역참조하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. 선언되지 않은 변수의 이름: {0}. + + + 비상수 식을 평가하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. 비상수 식: {0}. + + + 동적 식을 평가하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. 동적 식: {0}. + + + 인수 값 안에 다른 스크립트 블록을 전달하려는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. + + + 주 파이프라인의 인수를 평가하기 위해 파이프라인, 명령 또는 함수를 호출하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. + + + 도트 소싱을 사용하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. + + + 다른 스크립트 블록을 호출하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. + + + 금지된 리디렉션 연산자가 포함되어 있으므로 스크립트 블록을 PowerShell 개체로 변환할 수 없습니다. + + + 연결된 작업 컨텍스트가 없는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. + + + 사용자가 명령을 중단했습니다. + + + "{0}" 개체는 dynamicparam 블록에서 반환할 수 있는 올바른 형식이 아닙니다. dynamicparam 블록은 $null 또는 [System.Management.Automation.RuntimeDefinedParameterDictionary] 형식의 개체를 반환해야 합니다. + + + 스크립트 블록을 개방형 제네릭 형식으로 변환할 수 없습니다. 적절한 닫힌 제네릭 형식을 정의한 다음 다시 시도하세요. + + + 식으로 파이프라인을 시작하는 ScriptBlock에 대한 PowerShell 개체를 생성할 수 없습니다. + + + using 변수 '$using:{0}'은(는) 로컬 세션에 설정되어 있지 않으므로 값을 가져올 수 없습니다. + + + 지정한 변수 사전에서 Using 식 '{0}'의 값을 가져올 수 없습니다. 스크립트 블록에서 PowerShell instance를 만들 때 Using 식에는 인덱싱 작업이나 멤버 액세스 작업을 포함할 수 없습니다. + + + 컴파일된 스크립트 블록 점 소스 + + + 제한된 언어 모드에서는 스크립트 블록 '{0}'을(를) 현재 범위에 호출할 수 없습니다. 스크립트 언어 모드: {1}, 컨텍스트 언어 모드: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CatalogStrings.ko.resx b/src/System.Management.Automation/resources/ko/CatalogStrings.ko.resx new file mode 100644 index 00000000000..bfe057ebd51 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CatalogStrings.ko.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 카탈로그 정의 파일을 생성할 수 없습니다. + + + 파일 '{0}'을(를) 카탈로그에 추가하는 중입니다. 카탈로그에 있는 파일의 상대 경로는 '{1}'입니다. + + + 카탈로그에서 파일 {0}의 유효성 검사를 건너뜁니다. + + + 해시가 {1}인 파일 {0}을(를) 카탈로그에서 찾았습니다. + + + 카탈로그 경로에 상대 경로가 {0}(으)로 동일한 파일이 여러 개 있습니다. + + + 해시가 {1}인 파일 {0}을(를) 디스크에서 찾았습니다. + + + 경로에서 파일 {0}의 유효성 검사를 건너뜁니다. + + + 지정된 해시 알고리즘 {0}에 대한 카탈로그 관리자 컨텍스트의 핸들을 가져올 수 없습니다. + + + 파일 {0}의 해시를 만들 수 없습니다. + + + 카탈로그 파일 {0}을(를) 열 수 없습니다. + + + 카탈로그 버전이 유효하지 않습니다. 버전 {0} 및 버전 {1} 카탈로그만 지원됩니다. + + + 카탈로그 정의 파일을 열 수 없습니다. + + + 카탈로그에서 파일 구성원 {0}의 항목을 여러 개 찾았습니다. + + + 카탈로그 구성원 {0}의 파일 이름 또는 경로를 찾을 수 없습니다. + + + 해시할 파일 {0}을(를) 찾을 수 없습니다. + + + 해시를 계산할 파일 {0}을(를) 읽을 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CimInstanceTypeAdapterResources.ko.resx b/src/System.Management.Automation/resources/ko/CimInstanceTypeAdapterResources.ko.resx new file mode 100644 index 00000000000..9e37b24d4d3 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CimInstanceTypeAdapterResources.ko.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + "{0}"을(를) "{1}" 형식의 개체로 변환할 수 없습니다. + + + {0}은(는) 읽기 전용 속성입니다. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CmdletizationCoreResources.ko.resx b/src/System.Management.Automation/resources/ko/CmdletizationCoreResources.ko.resx new file mode 100644 index 00000000000..73777d73c68 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CmdletizationCoreResources.ko.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{0}' 클래스의 cmdlet + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + 다음 파일에 대한 Cmdlet 정의 XML을 처리할 수 없습니다: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + ObjectModelWrapper 특성을 처리할 수 없습니다. {0} 형식은 여러 매개 변수 집합을 정의합니다. Cmdlet 정의 XML에서 ObjectModelWrapper 특성에 유효한 형식을 지정했는지 확인한 다음 다시 시도하세요. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + ObjectModelWrapper 특성을 처리할 수 없습니다. {0} 형식은 열린 제네릭 형식입니다. Cmdlet 정의 XML에서 ObjectModelWrapper 특성에 유효한 형식을 지정했는지 확인한 다음 다시 시도하세요. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + ObjectModelWrapper 특성을 처리할 수 없습니다. {0} 형식은 다음 클래스에서 파생되지 않았습니다: {1}. Cmdlet 정의 XML에서 ObjectModelWrapper 특성에 유효한 형식을 지정했는지 확인한 다음 다시 시도하세요. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + ObjectModelWrapper 특성을 처리할 수 없습니다. {0} 형식은 무시되는 {1} 특성 매개 변수가 있는 {2} cmdlet 매개 변수를 정의합니다. Cmdlet 정의 XML에서 ObjectModelWrapper 특성에 유효한 형식을 지정했는지 확인한 다음 다시 시도하세요. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + {0} 매개 변수를 {1} cmdlet에 정의할 수 없습니다. 매개 변수 이름은 이미 {2} 클래스에서 정의되었습니다. Cmdlet 정의 XML에서 매개 변수 이름을 변경한 다음 다시 시도하세요. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + {0} 매개 변수를 {1} cmdlet에 정의할 수 없습니다. 매개 변수 이름은 이미 {2} XML 요소 내에 정의되어 있습니다. Cmdlet 정의 XML에서 매개 변수 이름을 변경한 다음 다시 시도하세요. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + EnumName 특성 값이 유효한 C# 식별자로 변환되지 않습니다: {0}. Cmdlet 정의 XML에서 EnumName 특성을 확인한 다음 다시 시도하세요. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + <Enum EnumName="{0}" ...> 요소를 처리할 수 없습니다. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + 원격 컴퓨터에서 잘못된 CDXML 파일을 반환했습니다. 다음 cmdlet 어댑터는 원격 컴퓨터에서 CDXML 모듈을 가져올 때 지원되지 않습니다: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CommandBaseStrings.ko.resx b/src/System.Management.Automation/resources/ko/CommandBaseStrings.ko.resx new file mode 100644 index 00000000000..6eec2039358 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CommandBaseStrings.ko.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 이 작업을 계속하시겠습니까? + + + 예(&Y) + + + 작업의 다음 단계만 계속하세요. + + + 모두 예(&A) + + + 작업의 모든 단계를 계속하세요. + + + 아니요(&N) + + + 이 작업을 건너뛰고 다음 작업을 진행합니다. + + + 모두 아니요(&L) + + + 이 작업과 이후의 모든 작업을 건너뛰세요. + + + 이 명령을 중지합니다. + + + 명령 중지(&H) + + + 일시 중단(&S) + + + 현재 파이프라인을 일시 중지하고 명령 프롬프트로 돌아갑니다. 파이프라인을 다시 시작하려면 "{0}"을(를) 입력하세요. + + + + 프로그램 "{0}"이(가) 0이 아닌 종료 코드로 종료되었습니다. {1}({2}). + + + 대상 "{0}"에 "{1}" 작업을 수행하는 중입니다. + + + What if: {0} + + + 이 작업을 수행하시겠습니까? +{0} + + + 확인 + + + 기본 설정 변수 "{0}" 또는 일반 매개 변수가 Stop: {1}(으)로 설정되어 실행 중인 명령이 중지되었습니다. + + + 기본 설정 변수 "{0}" 또는 공통 매개 변수가 Stop으로 설정되어 있으므로 실행 중인 명령이 중지되었습니다. + + + 기본 설정 변수 "{0}" 또는 공통 매개 변수가 잘못된 값인 "{1}"(으)로 설정되어 있으므로 실행 중인 명령이 중지되었습니다. + + + 사용자가 [중지] 옵션을 선택했기 때문에 실행 중인 명령이 중지되었습니다. + + + 사용자가 명령을 중단했기 때문에 실행 중인 명령이 중지되었습니다. + + + PSCmdlet에서 파생된 cmdlet은 직접 호출할 수 없습니다. + + + cmdlet '{0}'은(는) 원격 세션에서 '{1}' 매개 변수를 지원하지 않습니다. + + + 총 개수: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + 예상 총 수: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + 알 수 없는 총 개수 + Reviewed by TArcher on 2010-07-20 + + + 명령 '{0}' + + + '{0}'은(는) 더 이상 사용되지 않습니다. {1} + + + 명령줄에 대한 errorno {0}(으)로 Exec 호출이 실패했습니다. {1} + + + 명령 ‘{0}’을(를) 찾을 수 없습니다. 지정한 명령은 실행 파일이어야 합니다. + + + 스크립트 블록 처리 Dot-Source 검사 + + + 스크립트 블록 '{0}'의 Dot-Source 처리는 제한된 언어 모드에서 실패합니다. 언어 모드 '{1}'이(가) 현재 언어 모드 '{2}'과(와) 일치하지 않기 때문입니다. + + + 명령 검색기 + + + '{1}' 모듈의 '{0}' 명령은 신뢰할 수 없으며 ConstrainedLanguage 모드에서 액세스할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ConsoleInfoErrorStrings.ko.resx b/src/System.Management.Automation/resources/ko/ConsoleInfoErrorStrings.ko.resx new file mode 100644 index 00000000000..91ba469039e --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ConsoleInfoErrorStrings.ko.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell 버전 {0}이(가) 잘못되었습니다. 이 컴퓨터에서는 PowerShell 버전 {1}이(가) 지원됩니다. + + + 콘솔 {0}을(를) 로드하는 동안 다음 오류가 발생했습니다. {1} + + + 다음 오류 때문에 PowerShell 스냅인 {0}을(를) 로드할 수 없습니다. {1} + + + PowerShell 스냅인 "{0}"이(가) 로드되었지만 다음 경고가 발생했습니다. {1} + + + PowerShell 스냅인 모듈 {0}에 필요한 PowerShell 스냅인 강력한 이름 {1}이(가) 없습니다. + + + cmdlet '{0}'은(는) PowerShell 스냅인 '{1}'에 두 번 이상 있으면 안 됩니다. + + + PowerShell 공급자 '{0}'은(는) PowerShell 스냅인 '{1}'에 두 번 이상 있으면 안 됩니다. + + + PowerShell {0}은(는) 현재 콘솔에서 지원되지 않습니다. PowerShell {1}은(는) 현재 콘솔에서 지원됩니다. + + + 파일 {0}이(가) 이미 존재하며 {1}이(가) 지정되었습니다. + + + 제공된 구성 파일 '{0}'이(가) 없습니다. + + + 제공된 구성 파일 '{0}'에는 .pssc 파일 확장명이 있어야 합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CoreClrStubResources.ko.resx b/src/System.Management.Automation/resources/ko/CoreClrStubResources.ko.resx new file mode 100644 index 00000000000..4e5c305d920 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CoreClrStubResources.ko.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 환경 변수 이름에는 등호 문자를 사용할 수 없습니다. + + + 환경 변수 이름 또는 값이 너무 깁니다. + + + 문자열의 첫 번째 문자는 null 문자입니다. + + + 문자열은 길이가 0일 수 없습니다. + + + 컴퓨터 이름을 가져올 수 없습니다. + + + 현재 사용자의 도메인 이름을 가져올 수 없습니다. + + + 알 수 없는 오류 {0}이(가) 발생했습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CredUI.ko.resx b/src/System.Management.Automation/resources/ko/CredUI.ko.resx new file mode 100644 index 00000000000..454700a8b7c --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CredUI.ko.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell 자격 증명 요청 + + + 자격 증명을 입력합니다. + + + 자격 증명을 입력합니다. + + + 캡션의 최대 길이는 {0}자입니다. + + + 메시지의 최대 길이는 {0}자입니다. + + + UserName 값의 최대 길이는 {0}자입니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/Credential.ko.resx b/src/System.Management.Automation/resources/ko/Credential.ko.resx new file mode 100644 index 00000000000..62173425172 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/Credential.ko.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 + + + 자격 증명을 직렬화할 수 없습니다. 이 명령으로 워크플로를 시작하는 경우, 워크플로를 시작한 프로세스에 자격 증명을 직렬화할 권한이 없으므로 자격 증명을 유지할 수 없습니다. + +-- 워크플로가 로컬 컴퓨터의 PSSession에서 시작된 경우, 세션을 만든 명령에 EnableNetworkAccess 매개 변수를 추가하세요. +-- 워크플로가 원격 컴퓨터의 PSSession에서 시작된 경우, 세션을 만든 명령에 값이 CredSSP인 Authentication 매개 변수를 추가하세요. 또는 RunAsUser 속성 값이 있는 세션 구성에 연결하세요. + + + UserName 값의 형식이 올바르지 않습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/CredentialAttributeStrings.ko.resx b/src/System.Management.Automation/resources/ko/CredentialAttributeStrings.ko.resx new file mode 100644 index 00000000000..7acfb0f229f --- /dev/null +++ b/src/System.Management.Automation/resources/ko/CredentialAttributeStrings.ko.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 + + + PowerShell 자격 증명 요청 + + + 자격 증명을 입력합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/DebuggerStrings.ko.resx b/src/System.Management.Automation/resources/ko/DebuggerStrings.ko.resx new file mode 100644 index 00000000000..5f8c3baf793 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/DebuggerStrings.ko.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '${0}'의 변수 중단점({1} 액세스) + + + '{0}:${1}'의 변수 중단점({2} 액세스) + + + '{0}:{1}'의 줄 중단점 + + + '{0}:{1}, {2}'의 줄 중단점 + + + '{0}'의 명령 중단점 + + + '{0}:{1}'의 명령 중단점 + + + 중단점 {0}이(가) 적중되지 않습니다. + + + {0}, {1,-16} 단일 단계(함수, 스크립트 등으로 들어가기) + + + {0}, {1,-16} 다음 문까지 한 단계씩 실행(함수, 스크립트 등 건너뛰기) + + + {0}, {1,-16} 현재 함수, 스크립트 등에서 빠져나옵니다. + + + {0}, {1,-16} 작업을 계속합니다 + + + {0}, {1,-16} 작업을 중지하고 디버거를 종료합니다 + + + {0}, Get-PSCallStack 호출 스택 표시 + + + {0}, {1,-16} 현재 스크립트의 소스 코드를 표시합니다. + + + 현재 줄에서 시작하려면 "list"를 사용하고, "list <m>"은 + + + 줄 <m>부터 시작하고, "list <m> <n>"를 사용하여 <n> 나열합니다 + + + 줄 <m>부터 시작하는 줄 + + + <enter> 마지막 명령이 {0}, {1} 또는 {2}인 경우 반복합니다. + + + {0}, {1,-16}이(가) 이 도움말 메시지를 표시합니다. + + + 디버거 프롬프트를 사용자 지정하는 방법은 "help about_prompt"를 입력하여 확인하세요. + + + +현재 세션은 디버깅을 지원하지 않습니다. 작업을 계속합니다. + + + + + {0}: 줄 {1} + + + 사용 가능한 소스 코드가 없습니다. + + + 시작 줄은 {0}보다 크지 않은 양의 정수여야 합니다. + + + 줄 수는 양의 정수여야 합니다. + + + <No file> + + + {0}에서 {1}: 줄 {2} + + + 디버거는 중지 상태일 때만 명령을 처리할 수 있습니다. + + + 로컬 스크립트 디버거에는 SetDebugAction이 구현되어 있지 않습니다. + + + 원격 세션의 디버거가 중지 상태가 아니므로 다시 시작 작업을 설정할 수 없습니다. + + + 디버거가 현재 사용 중이므로 작업을 디버그할 수 없습니다. + + + 제공된 작업과 모든 자식 작업을 검사했지만 디버그할 수 있는 작업을 찾지 못했습니다. 작업이나 자식 작업을 디버그하려면 해당 작업이 디버깅을 지원하고 실행 중이어야 합니다. + + + 디버그 모드가 [없음]으로 설정되어 디버거가 꺼져 있으므로 단계 모드에서는 디버거를 사용할 수 없습니다. + + + 호스트 디버거가 현재 사용 중이므로 Runspace를 디버그할 수 없습니다. + + + Runspace를 디버그할 수 없습니다. Runspace 디버거가 현재 꺼져 있습니다(DebugMode가 'None'임). + + + 열림 상태가 아닌 Runspace는 디버그할 수 없습니다. 이 Runspace의 상태는 {0}입니다. + + + Runspace를 디버그할 수 없습니다. Runspace {0}에 연결된 디버거가 없습니다. + + + 디버거가 이미 재정의되어 있습니다. + + + 디버거 개체를 자신에게 밀어 넣을 수 없습니다. + + + 원격 Runspace에서 실행 중인 PowerShell 버전에서는 {0} 명령을 원격으로 사용할 수 없습니다. + + + 처리 + + + {0}, {1,-16} 작업을 계속하고 디버거를 분리합니다. + + + 디버거 분리 명령은 사용할 수 없습니다. 이 명령은 Debug-Job 또는 Debug-Runspace cmdlet으로 작업과 Runspace를 디버그할 때만 적용됩니다. + + + 잘못된 runspace ID: {0} + + + Runspace를 가져올 수 없습니다. + + + Breakpoint 또는 BreakpointList를 지정해야 합니다. + + + BreakpointList에 중단점이 아닌 항목이 포함되어 있습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/DescriptionsStrings.ko.resx b/src/System.Management.Automation/resources/ko/DescriptionsStrings.ko.resx new file mode 100644 index 00000000000..79e3e3f3b1c --- /dev/null +++ b/src/System.Management.Automation/resources/ko/DescriptionsStrings.ko.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 + + + {0}은(는) null이거나 비어 있을 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/DiscoveryExceptions.ko.resx b/src/System.Management.Automation/resources/ko/DiscoveryExceptions.ko.resx new file mode 100644 index 00000000000..1c1146daf5e --- /dev/null +++ b/src/System.Management.Automation/resources/ko/DiscoveryExceptions.ko.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 + + + cmdlet 이름 "{0}"이(가) 올바른 형식이 아니므로 유효성을 검사할 수 없습니다. Cmdlet 이름에는 "Get-Process"와 같이 "-"로 구분된 동사와 명사가 포함되어야 합니다. + + + "{0}" 매개 변수는 매개 변수 집합 "{1}"에서 여러 번 선언되었습니다. + + + "{0}" 별칭은 여러 번 선언됩니다. + + + 매개 변수를 선언할 수 없습니다. 매개 변수는 필드 및 속성에서만 선언할 수 있습니다. + + + cmdlet을 처리할 수 없습니다. cmdlet 이름은 '-'로 구분된 동사와 명사 쌍으로 구성되어야 합니다. + + + '{0}' 용어는 cmdlet, 함수, 스크립트 파일 또는 실행 프로그램의 이름으로 인식되지 않습니다. +이름의 철자를 확인하거나 경로가 포함되어 있으면 경로가 올바른지 확인하고 다시 시도합니다. + + + '{0}' 인수는 cmdlet으로 인식되지 않습니다. {1} + + + '{0}' 인수는 cmdlet 또는 PSCmdlet 클래스에서 파생되지 않았기 때문에 cmdlet으로 인식되지 않습니다. {1} + + + 별칭 '{0}'은(는) cmdlet, 함수, 실행 프로그램 또는 스크립트 파일로 인식되지 않는 '{1}' 용어를 참조하므로 확인할 수 없습니다. 용어를 확인하고 다시 시도하세요. + + + 값이 '{0}'인 매개 변수 '{1}'은(는) cmdlet이 아니므로 CommandProcessor에서 처리할 수 없습니다. + + + 이름이 '{0}'인 cmdlet이 이미 있습니다. Cmdlet에는 고유한 이름이 있어야 합니다. + + + 이름이 '{0}'인 cmdlet 공급자가 이미 있습니다. Cmdlet 공급자는 고유한 이름이 있어야 합니다. + + + 이름이 '{0}'인 어셈블리가 이미 있습니다. 어셈블리에는 고유한 이름이 있어야 합니다. + + + 이름이 '{0}'인 스크립트가 이미 있습니다. 스크립트에는 고유한 이름이 있어야 합니다. + + + #requires 문이 올바른 형식이 아니므로 처리할 수 없습니다. +#requires 문은 다음 형식 중 하나여야 합니다. + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + 스크립트 '{0}'에 현재 셸과 호환되지 않는 셸 ID가 {1}인 "#requires" 문이 포함되어 있으므로 스크립트를 실행할 수 없습니다. 이 스크립트를 실행하려면 '{2}'에 있는 셸을 사용해야 합니다. + + + 스크립트 '{0}'에 현재 셸과 호환되지 않는 셸 ID가 {1}인 "#requires" 문이 포함되어 있으므로 스크립트를 실행할 수 없습니다. + + + 스크립트 '{0}'에 PowerShell {1}에 대한 "#requires" 문이 포함되어 있으므로 스크립트를 실행할 수 없습니다. 스크립트에 필요한 PowerShell 버전이 현재 실행 중인 PowerShell {2} 버전과 일치하지 않습니다. + + + 스크립트 '{0}'에 PowerShell 에디션 '{1}'에 대한 "#requires" 문이 포함되어 있으므로 스크립트를 실행할 수 없습니다. 스크립트에 필요한 PowerShell 에디션이 현재 실행 중인 PowerShell {2} 에디션과 일치하지 않습니다. + + + 스크립트의 "#requires" 문에 지정된 다음 snap-in이 없으므로 스크립트 '{0}'을(를) 실행할 수 없습니다: {1}. + + + #requires 문에서 shellID만 지정했습니다. #Requires 문은 PowerShell에서 실행할 때 필요한 PowerShell 스냅인을 지정해야 합니다. + + + 스크립트 '{0}'에는 관리자 권한으로 실행하기 위한 "#requires" 문이 포함되어 있어 실행할 수 없습니다. 현재 PowerShell 세션은 관리자 권한으로 실행되고 있지 않습니다. [관리자 권한으로 실행] 옵션을 사용해 PowerShell을 시작한 다음 스크립트를 다시 실행해 보세요. + + + {0}(버전 {1}) + + + ArgumentList 매개 변수는 단일 cmdlet 또는 스크립트를 검색할 때만 지정할 수 있으므로 명령을 검색할 수 없습니다. + + + 매개 변수 이름 "{0}"은(는) 나중에 사용하도록 예약되어 있습니다. + + + 스크립트의 "#requires" 문에 지정된 다음 모듈이 없으므로 '{0}' 스크립트를 실행할 수 없습니다. {1}. + + + 모듈 '{0}'에서 '{1}' 명령을 찾았지만 모듈을 로드할 수 없습니다. 자세한 내용은 'Import-Module {1}'을(를) 실행하세요. + + + '{0}' 명령이 '{1}' 모듈에서 발견되었지만 다음 오류로 인해 모듈을 로드할 수 없습니다. [{2}] +자세한 내용은 'Import-Module {1}'을(를) 실행하세요. + + + '{0}' 모듈을 로드할 수 없습니다. 자세한 내용은 'Import-Module {0}'을(를) 실행하세요. + + + 일치하는 명령에 이름이 '{0}'인 매개 변수가 포함되어 있지 않습니다. 매개 변수 이름의 철자를 확인한 다음 다시 시도하세요. + + + 이 명령은 다른 언어 모드에서 정의되었으므로 도트 소스로 불러올 수 없습니다. 이 명령의 내용을 가져오지 않고 호출하려면 '.' 연산자를 생략하세요. + + + ShowCommandInfo 및 구문 매개 변수는 함께 지정할 수 없습니다. + + + 실험적 기능 '{0}'이(가) 켜져 있으면 이 스크립트 명령을 사용할 수 없습니다. + + + 실험적 기능 '{0}'이(가) 꺼져 있으면 이 스크립트 명령을 사용할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/EnumExpressionEvaluatorStrings.ko.resx b/src/System.Management.Automation/resources/ko/EnumExpressionEvaluatorStrings.ko.resx new file mode 100644 index 00000000000..9de148bbb24 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/EnumExpressionEvaluatorStrings.ko.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 입력 식은 비워 둘 수 없습니다. 각 입력 식에 하나 이상의 식별자 이름을 지정합니다. + + + 빈 식별자 이름을 유효한 열거자 이름과 일치시킬 수 없습니다. 다음 열거자 이름 중 하나를 지정하고 다시 시도하세요. {0}. + + + 식에 지정된 제네릭 형식은 열거형을 나타내야 합니다. 유효한 열거형 형식을 지정하세요. + + + 식별자 이름 {0}이(가) 다음 열거자 이름과 너무 유사하거나 동일하기 때문에 처리할 수 없습니다. {1}. 보다 구체적인 식별자 이름을 사용하세요. + + + 식별자 이름 {0}을(를) 올바른 열거자 이름과 일치시킬 수 없습니다. 다음 열거자 이름 중 하나를 지정하고 다시 시도하세요. +{1} + + + 식별자 그룹화가 허용되지 않으므로 식에서 괄호를 사용할 수 없습니다. 괄호를 제거하거나 하위 식이 괄호로 묶인 경우 식을 확장해 보세요. + + + 예기치 않은 토큰으로 인해 식을 구문 분석할 수 없습니다. 식별자 이름 뒤에는 OR(,) 연산자 또는 AND(+) 연산자만 필요합니다. + + + NOT(!) 연산자 뒤에 예기치 않은 토큰이 있어서 식을 구문 분석할 수 없습니다. NOT(!) 연산자 뒤에 식별자 이름이 필요합니다. + + + 예기치 않은 토큰으로 인해 식을 구문 분석할 수 없습니다. 식 시작 시 또는 OR(,) 연산자 또는 AND(+) 연산자 뒤에 식별자 이름 또는 NOT(!) 연산자가 필요합니다. 또한 식은 OR(,), AND(+) 또는 NOT(!) 연산자로 끝나서는 안 됩니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ErrorCategoryStrings.ko.resx b/src/System.Management.Automation/resources/ko/ErrorCategoryStrings.ko.resx new file mode 100644 index 00000000000..9a40ed65189 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ErrorCategoryStrings.ko.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + 교착 상태 검색: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + 인식할 수 없는 오류 범주 {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ErrorPackage.ko.resx b/src/System.Management.Automation/resources/ko/ErrorPackage.ko.resx new file mode 100644 index 00000000000..e227f384457 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ErrorPackage.ko.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 + + + {0}…{1} + + + 오류 "{0}"의 오류 텍스트가 비어 있음 : "{1}" + + + 개체 "{0}"이(가) 오류로 보고됩니다. + + + ActionPreference 변수에는 값 {0}이(가) 지원되지 않습니다. 제공된 값은 기본 설정 매개 변수의 값으로만 사용해야 하며 기본값으로 대체되었습니다. 자세한 내용은 도움말 항목 "about_Preference_Variables"를 참조하세요. + + + {0} ActionPreference 값은 나중에 사용하도록 예약되어 있으며 현재는 지원되지 않습니다. 기본 설정 변수에 대한 자세한 내용은 도움말 항목 "about_Preference_Variables"를 참조하세요. + + + {0} ActionPreference 값은 나중에 사용하도록 예약되어 있으며 현재는 지원되지 않습니다. {1} 변수에서 기본값인 {2}(으)로 대체되었습니다. 기본 설정 변수에 대한 자세한 내용은 도움말 항목 "about_Preference_Variables"를 참조하세요. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/EtwLoggingStrings.ko.resx b/src/System.Management.Automation/resources/ko/EtwLoggingStrings.ko.resx new file mode 100644 index 00000000000..53749defe61 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/EtwLoggingStrings.ko.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 명령 {0}은(는) {1}입니다. + + + 엔진 상태가 {0}에서 {1}(으)로 변경되었습니다. + + + 정규화된 전체 오류 ID = {0} + + + 오류 메시지 = {0} + + + 권장 조치 = {0} + + + 실행 정책 + + + 작업 명령 = {0} + + + 작업 ID = {0} + + + 작업 인스턴스 ID = {0} + + + 작업 위치 = {0} + + + 작업 이름 = {0} + + + 작업 상태= {0} + + + 명령 이름 = + + + 명령 경로 = + + + 명령 유형 = + + + 엔진 버전 = + + + 호스트 ID = + + + 호스트 이름 = + + + 호스트 애플리케이션 = + + + 호스트 버전 = + + + 파이프라인 ID = + + + Runspace ID = + + + 스크립트 이름 = + + + 시퀀스 번호 = + + + 심각도 = + + + 셸 ID = + + + 시간 = + + + 사용자 = + + + 연결된 사용자 = + + + NULL 작업 + + + 공급자 이름 + + + 공급자 {0}이(가) 상태를 {1}(으)로 변경했습니다. + + + 스크립트 실행이 {0}. + + + 변수 {0}이(가) {1}에서 {2}(으)로 변경되었습니다. + + + 변수 {0}이(가) {1}(으)로 변경되었습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/EventResource.ko.resx b/src/System.Management.Automation/resources/ko/EventResource.ko.resx new file mode 100644 index 00000000000..7c90a8b3536 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/EventResource.ko.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 이벤트 ID PowerShell.Core.Instrumentation.man에 대한 메시지를 찾을 수 없습니다. + + + 예약된 작업 {0} 시작 날짜: {1} + + + + 예약된 작업이 {0} 상태와 함께 완료됨 {1} {2} + + + + 예약된 작업 예외 {0}: + 메시지: {1} + StackTrace: {2} + InnerException: {3} + + + + 실험적 기능 초기화: 구성 파일에서 실험적 기능 '{0}'을(를) 무시합니다. {1} + + + 실험적 기능 초기화: 구성 파일을 읽지 못했습니다. + 예외: {0} + 메시지: {1} + StackTrace: {2} + + + + 워크플로 플러그 인이 로드되었습니다. + EndpointName: {0} + 사용자: {1} + HostingMode: {2} + 프로토콜: {3} + 구성: + {4} + + + 워크플로 실행이 시작되었습니다. + WorkflowId: {0} + ManagedNodes: {1} + + + 워크플로 상태가 변경되었습니다. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + 워크플로 플러그 인이 종료를 요청했습니다. + EndpointName: {0} + + + 워크플로 플러그 인이 다시 시작되었습니다. + EndpointName: {0} + + + 워크플로를 다시 시작하는 중입니다. + WorkflowId: {0} + + + 엔드포인트에 대해 설정된 할당량 한도를 초과했습니다. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + 워크플로가 다시 시작되었습니다. + WorkflowId: {0} + + + 워크플로 Runspace 풀을 만들었습니다. + WorkflowId: {0} + ManagedNode: {1} + + + 활동이 실행 대기열에 추가되었습니다. + WorkflowId: {0} + ActivityName: {1} + + + 활동 실행이 시작되었습니다. + ActivityName: {0} + ActivityTypeName: {1} + + + XAML 파일에서 워크플로를 가져오는 중입니다. + WorkflowId: {0} + XamlFile: {1} + + + XAML 파일에서 워크플로를 가져왔습니다. + WorkflowId: {0} + XamlFile: {1} + + + 오류로 인해 XAML 파일에서 워크플로를 가져올 수 없습니다. + WorkflowId: {0} + ErrorDescription: {1} + + + 워크플로 유효성 검사가 시작되었습니다. + WorkflowId: {0} + + + 워크플로 유효성 검사에 성공했습니다. + WorkflowId: {0} + + + 오류가 발생하여 워크플로 유효성 검사에 실패했습니다. + WorkflowId: {0} + + + 워크플로 활동의 유효성을 검사했습니다. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + 워크플로 활동의 유효성을 검사할 수 없습니다. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + 활동을 실행하지 못했습니다. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Runspace 가용성이 변경되었습니다. + RunspaceId: {0} + 사용 가능 여부: {1} + + + Runspace 상태가 변경되었습니다. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + 실행할 워크플로를 로드했습니다. + WorkflowId: {0} + + + 워크플로가 언로드되었습니다. + WorkflowId: {0} + + + 워크플로 실행이 취소되었습니다. + WorkflowId: {0} + + + 워크플로 실행이 중단되었습니다. + WorkflowId: {0} + + + 워크플로 정리 작업이 실행되었습니다. + WorkflowId: {0} + + + 지속성 워크플로가 디스크에서 로드되었습니다. + WorkflowId: {0} + 경로: {1} + + + 워크플로 데이터가 디스크에서 삭제되었습니다. + WorkflowId: {0} + 경로: {1} + + + 작업 제거를 시작하는 중입니다. + JobId: {0} + + + 작업 상태가 변경되었습니다. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + 작업 오류입니다. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + 워크플로(자식 작업)에 대해 만들어진 작업입니다. + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + 워크플로에 대해 만든 부모 작업입니다. + JobId: {0} + + + 워크플로 실행을 위해 필요한 모든 작업이 생성되었습니다. + JobId: {0} + WorkflowId: {1} + + + 워크플로에 대한 자식 작업이 제거되었습니다. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + 역할을 제거하는 중 오류가 발생했습니다. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + 오류: {3} + + + 실행할 워크플로를 로드하는 중입니다. + WorkflowId: {0} + + + 워크플로 실행이 완료되었습니다. + WorkflowId: {0} + + + 워크플로 실행을 취소하는 중입니다. + WorkflowId: {0} + + + 워크플로 실행을 중단하는 중입니다. + WorkflowId: {0} + 이유: {1} + + + 워크플로를 언로드하는 중입니다. + WorkflowId: {0} + + + 강제 워크플로 종료가 시작되었습니다. + WorkflowId: {0} + + + 강제 워크플로 종료가 완료되었습니다. + WorkflowId: {0} + + + 워크플로를 강제로 종료하는 동안 오류가 발생했습니다. + WorkflowId: {0} + ErrorDescription: {1} + + + 디스크에 워크플로를 유지합니다. + WorkflowId: {0} + PersistPath: {1} + + + 워크플로가 디스크에 유지되었습니다. + WorkflowId: {0} + + + 활동 실행이 완료되었습니다. + ActivityName: {0} + + + 워크플로 실행 중 오류가 발생했습니다. + WorkflowId: {0} + ErrorDescription: {1} + + + 새 PowerShell 엔드포인트가 등록되었습니다. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + 엔드포인트 구성이 수정되었습니다. + EndpointName: {0} + ModifiedBy: {1} + + + 엔드포인트 구성 등록이 취소되었습니다. + EndpointName: {0} + UnregisteredBy: {1} + + + 엔드포인트 구성을 사용할 수 없습니다. + EndpointName: {0} + DisabledBy: {1} + + + 엔드포인트 구성을 사용하도록 설정했습니다. + EndpointName: {0} + EnabledBy: {1} + + + 프로세스 외 runspace가 시작되었습니다. + 명령: {0} + + + 워크플로 실행 중에 매개 변수 스플래팅이 수행되었습니다. + 매개 변수: {0} + 컴퓨터: {1} + + + 워크플로 엔진이 시작되었습니다. + EndpointName: {0} + + + 사용하여 인스턴스화된 워크플로 관리자 + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + 경로: {3} + + + 컴퓨터 이름 $null 또는 .을 LocalHost로 확인 + + + 기본 체계 http로 확인 중 + + + 원격 셸 이름이 기본 PowerShellCore로 확인됨 + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + Scriptblock 텍스트를 만드는 중({0}/{1}): +{2} + +ScriptBlock ID: {3} +경로: {4} + + + ScriptBlock ID 호출을 시작했습니다: {0} +Runspace ID: {1} + + + ScriptBlock ID 호출을 완료했습니다: {0} +Runspace ID: {1} + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + {2} + +컨텍스트: +{0} + +사용자 데이터: +{1} + + + + 활동 ID를 서로 연결하는 중입니다. + CurrentActivityId: {0} + ParentActivityId: {1} + + + 클래스 이름 = {0} +메서드 이름 = {1} +워크플로 GUID = {2} +메시지 = {3} +{4} +활동 이름 = {5} +활동 GUID = {6} +매개 변수 = {7} + + + Runspace 개체를 만드는 중 + 인스턴스 ID: {0} + + + RunspacePool 개체 만들기 + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + RunspacePool을 여는 중 + + + 활동 ID 수정 및 상관 관계 지정 + + + Runspace 상태가 {0}(으)로 변경됨 + + + 세션 ID {2}에서 오류 코드 {1}에 대한 세션 만들기를 {0}회 다시 시도하는 중입니다. + + + PowerShell이 프로세스 {0}의 애플리케이션 도메인 {1}에서 IPC 수신 스레드를 시작했습니다. + + + PowerShell이 프로세스 {0}의 애플리케이션 도메인 {1}에서 IPC 수신 스레드를 종료했습니다. + + + 프로세스 {0}의 애플리케이션 도메인 {1}에서 실행 중인 PowerShell IPC 수신 스레드에서 오류가 발생했습니다. 오류 메시지: {2}. + + + 프로세스 {0}의 애플리케이션 도메인 {1}에서 사용자 {2}에 대한 PowerShell IPC 연결을 처리하는 중입니다. + + + 프로세스 {0}의 애플리케이션 도메인 {1}에서 사용자 {2}에 대한 PowerShell IPC 연결이 끊어졌습니다. + + + 포트가 {0}(으)로 확인됨 + + + AppName이 {0}(으)로 확인됨 + + + ComputerName이 {0}(으)로 확인됨 + + + 스키마는 {0}입니다. + + + 분석 메시지 테스트 + + + 연결 매개 변수는 입니다 + 연결 URI: {0} + 리소스 URI: {1} + 사용자: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + 지문 인쇄: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + 활동 ID 수정 및 상관 관계 지정 + + + Runspace ID: {0}, 명령 ID: {1}, 대상: {2}, 데이터 형식: {3}, 대상 인터페이스: {4}인 개체를 받았습니다. + + + 애플리케이션 도메인에서 처리되지 않은 예외가 발생했습니다. +예외 형식: {0} +예외 메시지: {1} +예외 StackTrace: {2} + + + Runspace ID: {0} 파이프라인 ID: {1}. WSMan에서 오류를 보고했습니다. 오류 코드: {2}. + 오류 메시지: {3} + StackTrace: {4} + + + 애플리케이션 도메인에서 처리되지 않은 예외가 발생했습니다. +예외 형식: {0} +예외 메시지: {1} +예외 StackTrace: {2} + + + Runspace ID: {0} 파이프라인 ID: {1}. WSMan에서 오류를 보고했습니다. 오류 코드: {2}. + 오류 메시지: {3} + StackTrace: {4} + + + Runspace ID {0}. WSMan Create Shell을 사용하여 연결 설정 + + + Runspace ID {0}. WSMan Create Shell에 대한 콜백 수신됨 + + + Runspace ID: {0}. WSManCloseShell을 사용하여 셸 닫기 + + + Runspace ID: {0}. WSManCloseShell에 대한 콜백 수신됨 + + + Runspace ID: {0} 파이프라인 ID: {1}. 크기 {2}의 데이터를 보내는 중 + + + Runspace ID: {0} 파이프라인 ID: {1}. WSManSendShellInputEx에 대한 콜백 수신됨 + + + Runspace ID: {0} 파이프라인 ID: {1}. WSManReceiveShellOutputEx를 사용하여 수신 요청 배치 + + + Runspace ID: {0} 파이프라인 ID: {1}. 크기 {2}의 데이터를 받았습니다. + + + Runspace ID {0} 파이프라인 ID {1}. WSManRunShellCommandEx를 사용하여 명령 연결 설정 + + + Runspace ID {0} 파이프라인 ID {1}. 명령 연결에 대한 콜백을 받았습니다. + + + Runspace ID: {0} 파이프라인 ID {1}. 명령에 대한 전송을 닫는 중 + + + Runspace ID: {0} 파이프라인 ID {1}. 명령 닫기에 대한 콜백 수신됨 + + + Runspace ID: {0} 파이프라인 ID {1}. WSManSignalShellEx를 사용하여 코드 {2}(으)로 신호 보내기 + + + Runspace ID: {0} 파이프라인 ID {1}. WSManSignalShellEx에 대한 콜백 수신됨 + + + Runspace ID: {0}. 연결이 URI {1}(으)로 리디렉션됩니다. + + + Runspace ID: {0} 파이프라인 ID: {1}. 서버가 크기 {2}의 데이터를 클라이언트로 보내고 있습니다. DataType: {3} TargetInterface: {4} + + + 요청 {0}. 서버 원격 세션을 만드는 중입니다. 사용자 이름: {1} 사용자 지정 셸 ID: {2} + + + {0} 요청에 대한 컨텍스트를 보고합니다. 보고된 컨텍스트: {0} + + + 요청에 대한 보고 작업이 완료되었습니다: {0} + 오류 코드: {1} + 오류 메시지: {2} + StackTrace: {3} + + + 셸 컨텍스트 {0}. 요청 ID {1}. 명령을 실행하기 위한 commonad 세션을 만드는 중입니다. + + + 셸 컨텍스트 {0} 명령 컨텍스트 {1} 요청 ID {2}. 명령을 중지하는 중입니다. + + + 셸 컨텍스트 {0} 명령 컨텍스트 {1} 요청 ID {2}. 클라이언트에서 데이터를 받았습니다. + + + 셸 컨텍스트 {0} 명령 컨텍스트 {1} 요청 ID {2}. 서버가 데이터를 보낼 수 있도록 클라이언트가 받기 요청을 보냈습니다. + + + 셸 컨텍스트 {0} 명령 컨텍스트 {1} IsReceiveOperation {2}. 닫기 작업 요청을 받았습니다. + + + 셸 ID가 {1}인 사용자 지정 셸에 대한 어셈블리 {0}을(를) 로드하는 중입니다 + + + 셸 ID {1}이(가) 있는 사용자 지정 셸에 대한 형식 {0} 로드 중 + + + 원격 조각을 받았습니다. + 개체 ID: {0} + 조각 ID: {1} + 시작 플래그: {2} + 종료 플래그: {3} + 페이로드 길이: {4} + 페이로드 데이터: {5} + + + 원격 조각을 보냈습니다. + 개체 ID: {0} + 조각 ID: {1} + 시작 플래그: {2} + 종료 플래그: {3} + 페이로드 길이: {4} + 페이로드 데이터: {5} + + + winrm 서비스를 종료하는 중입니다. + + + 개체를 성공적으로 다시 하이드레이션했습니다. + 역직렬화된 형식 이름: {0} + 다음 형식으로 캐스팅하여 다시 하이드레이션됨: {1} + 다시 하이드레이션된 개체의 형식: {2} + + + 개체를 다시 하이드레이션하지 못했습니다. + 역직렬화된 형식 이름: {0} + 다음 형식으로 캐스팅하여 다시 하이드레이션됨: {1} + 형식 캐스트 예외: {2} + 형식 캐스트 내부 예외: {3} + + + serialization 깊이가 재정의되었습니다. + serialize된 형식 이름: {0} + 원래 깊이: {1} + 재정의된 깊이: {2} + 최상위 수준 아래의 현재 깊이: {3} + + + serialization 모드가 재정의되었습니다. + serialize된 형식 이름: {0} + 재정의된 모드: {1} + + + 속성 평가에 사용할 runspace가 없으므로 스크립트 속성의 serialization을 건너뛰었습니다. + 속성 이름: {0} + 속성 소유자의 형식 이름: {1} + Getter 스크립트: {2} + + + 속성 getter가 실패했기 때문에 속성 serialization을 건너뛰었습니다. + 속성 이름: {0} + 속성 소유자의 형식 이름: {1} + 속성 getter의 예외: {2} + 속성 getter의 내부 예외: {3} + + + 열거 중인 개체에서 예외가 발생했기 때문에 열거 가능한 개체의 serialization이 완료되지 않을 수 있습니다. + 열거되는 개체의 형식: {0} + 예외: {1} + + + serialization이 실패한 개체의 ToString 메서드를 호출했습니다. + 개체 유형: {0} + 예외: {1} + + + 최상위 수준 아래의 최대 깊이에 도달하여 개체를 문자열로 직렬화합니다. + 최대 깊이의 개체 유형: {0} + 최대 깊이의 속성 이름: {1} + 깊이: {2} + + + 역직렬 변환기에서 XmlException이 발생했습니다. 잘못된 clixml 형식을 나타내는 경우가 많습니다. + 줄 번호: {0} 줄 위치: {1} + 예외: {2} + + + 지정된 속성 중 하나가 없으므로 지정된 속성의 serialization이 실패했습니다. + 개체 유형: {0} + 속성 이름: {1} + + + PowerShell 콘솔을 시작하는 중 + + + PowerShell 콘솔에서 사용자 입력이 준비되었습니다. + + + {0} + + + 추적 ErrorRecord: + 메시지: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + 예외 정보: + 메시지 : {5} + 스택 추적: {6} + InnerException {7} + + + + 예외: + 메시지: {0} + StackTrace: {1} + InnerException : {2} + + + + PSObject 추적 + + + 추적 작업: + ID: {0} + InstanceId: {1} + 이름: {2} + 위치: {3} + 상태: {4} + 명령: {5} + + + + 추적 정보: + {0} + + + 추적 정보: + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication. 워크플로 함수 호출을 시작하는 중입니다. 추적 GUID {0} + + + END ImportWorkflowCommand::StartWorkflowApplication. 워크플로 함수 호출을 종료하는 중입니다. 추적 GUID {0} + + + ImportWorkflowCommand::StartWorkflowApplication에서 새 작업 만들기를 시작합니다. 추적 GUID {0} + + + ImportWorkflowCommand::StartWorkflowApplication에서 새 작업 만들기를 종료합니다. 추적 GUID {0} + + + ImportWorkflowCommand::StartWorkflowApplication에서 새 작업 만들기를 종료합니다. 추적 GUID {0} : ContainerParentJob GUID {1} + + + JobLogic ContainerParentJob GUID {0} 시작 + + + JobLogic ContainerParentJob GUID {0} 종료 + + + BEGIN WorkflowExecution ContainerParentJob GUID {0} + + + WorkflowExecution ContainerParentJob GUID {0} 종료 + + + GUID {0}의 WorkflowJob이 GUID {1}의 ContainerParentJob에 추가됨 + + + GUID {0}의 ProxyJob은 GUID {1}의 원격 ContainerParentJob과 연결되어 있습니다. + + + GUID {0}의 ContainerParentJob 실행 시작 + + + GUID {0}의 ContainerParentJob 실행 종료 + + + GUID {0}의 프록시 작업 실행 시작 + + + GUID {0}의 프록시 작업 실행 종료 + + + GUID {0}의 프록시 작업에 대한 StateChanged 이벤트 처리기 시작 + + + GUID {0}의 프록시 작업에 대한 StateChanged 이벤트 처리기 종료 + + + GUID {0}의 프록시 자식 작업에 대한 StateChanged 이벤트 처리기 시작 + + + GUID {0}의 프록시 자식 작업에 대한 StateChanged 이벤트 처리기 종료 + + + 가비지 수집 실행 시작 + + + 가비지 수집 실행 종료 + + + 지속성 저장소가 지정된 최대 크기에 도달했습니다. + + + Windows PowerShell ISE가 스크립트 파일 {0} 실행을 시작했습니다. + + + Windows PowerShell ISE가 파일 {0}에서 사용자가 선택한 스크립트 실행을 시작했습니다. + + + Windows PowerShell ISE가 현재 명령을 중지하는 중입니다. + + + Windows PowerShell ISE가 디버거를 다시 시작하는 중입니다. + + + Windows PowerShell ISE가 디버거를 중지합니다. + + + Windows PowerShell ISE가 한 단계씩 코드 실행 디버깅을 시작합니다. + + + Windows PowerShell ISE가 프로시저 단위 실행 디버깅을 시작합니다. + + + Windows PowerShell ISE가 디버깅을 단계적으로 중단합니다. + + + Windows PowerShell ISE가 모든 중단점을 사용하도록 설정하고 있습니다. + + + Windows PowerShell ISE가 모든 중단점을 사용하지 않도록 설정합니다. + + + Windows PowerShell ISE가 모든 중단점을 제거합니다. + + + Windows PowerShell ISE가 파일 {1}의 {0}번째 줄에서 중단점을 설정하는 중입니다. + + + Windows PowerShell ISE가 파일 {1}의 {0}번째 줄에서 중단점을 제거하는 중입니다. + + + Windows PowerShell ISE가 파일 {1}의 {0}번째 줄에서 중단점을 사용하도록 설정하는 중입니다. + + + Windows PowerShell ISE가 파일 {1}의 {0}번째 줄에서 중단점을 사용하지 않도록 설정하는 중입니다. + + + Windows PowerShell ISE가 파일 {1}의 {0}번째 줄에서 중단점에 도달했습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/EventingResources.ko.resx b/src/System.Management.Automation/resources/ko/EventingResources.ko.resx new file mode 100644 index 00000000000..2b7cb2490c8 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/EventingResources.ko.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}'인 이벤트가 없습니다. + + + PowerShell에서는 Windows RT 이벤트를 구독할 수 없습니다. + + + 지정한 이벤트를 등록할 수 없습니다. 이벤트 원본 식별자 '{0}'은(는) PowerShell 엔진용으로 예약되어 있습니다. + + + 원격 인스턴스에서는 이 작업이 지원되지 않습니다. + + + 이벤트를 전달할 때는 이 작업이 지원되지 않습니다. + + + 지정한 이벤트를 구독할 수 없습니다. 원본 식별자가 '{0}'인 구독자가 이미 있습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ExperimentalFeatureStrings.ko.resx b/src/System.Management.Automation/resources/ko/ExperimentalFeatureStrings.ko.resx new file mode 100644 index 00000000000..99d1273f3cd --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ExperimentalFeatureStrings.ko.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}'인 일치하는 실험적 기능을 찾을 수 없습니다. + + + 실험적 기능을 사용하거나 사용하지 않도록 설정한 변경 내용은 다음에 PowerShell을 시작할 때 적용됩니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ExtendedTypeSystem.ko.resx b/src/System.Management.Automation/resources/ko/ExtendedTypeSystem.ko.resx new file mode 100644 index 00000000000..66082b75b2a --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ExtendedTypeSystem.ko.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 구성원 "{0}"이(가) 이미 있습니다. + + + 구성원 "{0}"은(는) 이미 확장된 형식 데이터 파일에 있습니다. + + + 구성원 "{0}"이(가) 없습니다. + + + "{0}"을(를) 설정하는 동안 예외가 발생함: "{1}" + + + "{0}"을(를) 가져오는 동안 예외가 발생함: "{1}" + + + 컬렉션을 열거하는 동안 다음 예외가 발생했습니다. "{0}". + + + PSObject 밖에서는 구성원 "{0}"에 액세스할 수 없습니다. + + + 형식 구성에서 만든 구성원을 변경할 수 없습니다. "{0}". + + + 구성원 이름 "{0}"은(는) 예약되어 있습니다. + + + "{0}"은(는) 변경할 수 없습니다. + + + "{0}"을(를) "{1}"개의 인수와 함께 호출하는 동안 예외가 발생함: "{2}" + + + "{1}" 형식의 개체 내용을 추출하기 위해 "{0}"을(를) 호출하려고 하는 동안 예외가 throw되었습니다. "{2}" + + + "{0}"에 대한 오버로드를 찾을 수 없으며, 인수 개수는 "{1}"입니다. + + + 형식 매개 변수가 "{1}"인 "{0}"에 대해 적절한 제네릭 메서드 오버로드를 찾을 수 없으며, 인수 개수는 "{2}"개입니다. + + + "{0}"에 대한 모호한 오버로드가 여러 개 발견되었으며, 인수 개수는 "{1}"개입니다. + + + "{2}"에 대한 인수 "{0}"(값: "{1}")을(를) 형식 "{3}"(으)로 변환할 수 없습니다. "{4}" + + + 속성 "{0}"의 Get 접근자를 사용할 수 없습니다. + + + 속성 "{0}"의 Set 접근자를 사용할 수 없습니다. + + + setter 메서드는 public, void, static이어야 하고 매개 변수는 두 개여야 합니다. 첫 번째 매개 변수는 PSObject 형식이어야 합니다. getter 메서드도 사용할 수 있는 경우 두 번째 매개 변수가 필요하며, 이는 getter 메서드의 반환 형식과 같아야 합니다. + + + getter 메서드는 void나 static이 아닌 public이어야 하며, PSObject 형식의 매개 변수가 하나 있어야 합니다. + + + CodeProperty는 getter 또는 setter 메서드를 사용해야 합니다. + + + 메서드 형식 때문에 코드 메서드를 만들 수 없습니다. 메서드는 public, static이어야 하며 PSObject 형식의 매개 변수가 하나 있어야 합니다. + + + 이름이 "{0}"인 별칭에 주기가 있습니다. + + + 형식 "{1}"의 "{0}" 값을 형식 "{2}"(으)로 변환할 수 없습니다. + + + 형식 "{0}"의 값을 형식 "{1}"(으)로 변환할 수 없습니다. + + + 값 "{0}"을(를) 형식 "{1}"(으)로 변환할 수 없습니다. 오류: "{2}" + + + 이 열거형에서는 쉼표를 허용하지 않으므로 값 "{0}"을(를) 형식 "{1}"(으)로 변환할 수 없습니다. + + + 잘못된 열거형 값이 있으므로 값 "{0}"을(를) 형식 "{1}"(으)로 변환할 수 없습니다. 다음 열거형 값 중 하나를 지정하고 다시 시도하세요. 가능한 열거형 값은 "{2}"입니다. + + + 잘못된 열거형 값이 있으므로 null을 형식 "{0}"(으)로 변환할 수 없습니다. 다음 열거형 값 중 하나를 지정하고 다시 시도하세요. 가능한 열거형 값은 "{1}"입니다. + + + null을 형식 "{0}"(으)로 변환할 수 없습니다. + + + 값을 형식 "{0}"(으)로 변환할 수 없습니다. 오류: "{1}" + + + 값을 형식 System.String으로 변환할 수 없습니다. + + + 인수에 참조 형식이 필요합니다. + + + "{0}"은(는) IComparable이 아니므로 비교할 수 없습니다. + + + "{0}"과(와) "{1}"을(를) 비교할 수 없습니다. 오류: "{2}" + + + 개체의 형식이 같지 않거나 개체 "{0}"이(가) "{2}"을(를) 구현하지 않으므로 "{0}"과(와) "{1}"을(를) 비교할 수 없습니다. + + + 일치 항목이 최소 두 개 이상 발견되었고({2}, {3}) 이 열거형에서는 일치 항목을 하나만 허용하므로 값 "{0}"을(를) 형식 "{1}"(으)로 변환할 수 없습니다. + + + 값 "{0}"을(를) 형식 "{1}"(으)로 변환할 수 없습니다. 부울 매개 변수에는 $True, $False, 1, 0 같은 부울 값과 숫자만 사용할 수 있습니다. + + + "{0}"은(는) 쓰기 전용 속성이므로 속성 값을 가져올 수 없습니다. + + + "{0}"은(는) 읽기 전용 속성입니다. + + + XmlNode 속성을 설정하는 값으로는 문자열만 사용할 수 있으므로 "{0}"을(를) 설정할 수 없습니다. + + + 고유 특성이나 고유 특성이 없는 리프 노드만 설정할 수 있으므로 "{0}"을(를) 설정할 수 없습니다. + + + PSProperty 또는 PSMethod 개체는 이 컬렉션에 추가할 수 없습니다. + + + 확장된 형식 데이터 파일을 로드하는 동안 다음 오류가 발생했습니다. {0} + + + 문자열을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 형식 "{1}"의 필드 또는 속성 "{0}"은(는) 필드 또는 속성 "{2}"과(와) 대/소문자만 다릅니다. 형식은 CLS(공용 언어 사양)를 준수해야 합니다. + + + 형식 이름 계층 구조를 검색하는 동안 다음 예외가 발생했습니다. "{0}". + + + 구성원 "{1}"을(를) 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 구성원을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 속성 "{1}"의 읽기 상태를 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 속성 "{1}"의 쓰기 상태를 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 속성 "{1}"에 대한 형식을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 속성 "{1}"의 문자열 표현을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 속성 "{1}"의 특성을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 메서드 "{1}"의 정의를 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 메서드 "{1}"의 문자열 표현을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 매개 변수가 있는 속성 "{1}"의 형식을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 매개 변수가 있는 속성 "{1}"의 읽기 상태를 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 매개 변수가 있는 속성 "{1}"의 쓰기 상태를 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 매개 변수가 있는 속성 "{1}"의 정의를 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 매개 변수가 있는 속성 "{1}"의 문자열 표현을 검색하는 동안 다음 예외가 발생했습니다. "{0}" + + + 형식 "{0}"의 PSMemberInfo 개체에 대해서는 Value 속성을 설정할 수 없습니다. + + + 인수 '{0}'은(는) {1}이어(여)야 합니다. {2}을(를) 사용합니다. + + + 인수 '{0}'은(는) {1}이면 안 됩니다. {2}은(는) 사용하지 마세요. + + + "{0}" 속성을 찾을 수 없습니다. + + + 속성 값을 가져오거나 설정할 수 없습니다. "{0}" 인수는 "{1}" 또는 "{2}" 형식이어야 합니다. + + + 개체의 형식이 "{2}" 대신 "{1}"이므로 속성 "{0}"의 값을 설정할 수 없습니다. + + + "{0}"을(를) 호출하는 중 예외가 발생함: "{1}" + + + {0}은(는) 올바른 클래스 경로가 아닙니다. + + + {0}은(는) 유효한 경로가 아닙니다. + + + 어댑터에서 속성 "{0}"을(를) 변경할 수 있는지 여부를 확인할 수 없습니다. + + + 어댑터에서 속성 "{0}"을(를) 가져올 수 있는지 여부를 확인할 수 없습니다. + + + 어댑터에서 속성 "{0}"의 값을 가져올 수 없습니다. + + + 어댑터에서 속성 "{0}"의 값을 설정할 수 없습니다. + + + 어댑터에서 속성 "{0}"의 형식을 가져올 수 없습니다. + + + 어댑터에서 "{0}"의 형식 계층 구조를 가져올 수 없습니다. + + + 어댑터에서 "{0}"의 속성을 가져올 수 없습니다. + + + 어댑터에서 "{1}"에 대한 속성 "{0}"을(를) 가져올 수 없습니다. + + + "{0}"에서 null 값이 반환되었습니다. + + + '{0}' 개체에 대한 속성 '{1}'을(를) 찾을 수 없습니다. 설정할 수 있는 속성은 다음과 같습니다. {2}. + + + '{0}' 개체에 대한 속성 '{1}'을(를) 찾을 수 없습니다. 설정할 수 있는 속성이 없습니다. + + + 형식 "{0}"의 개체를 만들 수 없습니다. {1} + + + 열려 있는 제네릭 형식 {0}에서는 정적 메서드를 호출하거나 정적 속성에 액세스할 수 없습니다. 형식 매개 변수를 지정하고 다시 시도하세요. 예를 들어 [System.Collections.Generic.HashSet``1]::CreateSetComparer() 대신 [System.Collections.Generic.HashSet[int]]::CreateSetComparer()를 사용하세요. + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + 특성 "{1}"을(를) 생성하는 동안 다음 예외가 발생했습니다. "{0}" + + + 값 "{0}"은(는) 문자열 배열로 변환할 수 없습니다. + + + 값을 형식 "{0}"(으)로 변환할 수 없습니다. 이 언어 모드에서는 핵심 형식만 지원됩니다. + + + ByRef와 유사한 형식 "{0}"(으)로 변환할 수 없습니다. PowerShell에서는 ByRef와 유사한 형식이 지원되지 않습니다. + + + ByRef와 유사한 형식 "{1}"의 속성 또는 필드 "{0}"을(를) 가져오거나 설정할 수 없습니다. PowerShell에서는 ByRef와 유사한 형식이 지원되지 않습니다. + + + ByRef와 유사한 반환 형식 "{1}"의 메서드 "{0}"을(를) 호출할 수 없습니다. PowerShell에서는 ByRef와 유사한 형식이 지원되지 않습니다. + + + ByRef와 유사한 형식 "{0}"의 인스턴스를 만들 수 없습니다. PowerShell에서는 ByRef와 유사한 형식이 지원되지 않습니다. + + + 확장 유형 시스템 해시 테이블 변환 + + + ConstrainedLanguage 모드에서는 HashTable에서 '{0}'(으)로 형식을 변환할 수 없습니다. + + + 확장 유형 시스템 해시 테이블 변환 + + + ConstrainedLanguage 모드에서는 '{0}'에서 '{1}'(으)로 형식을 변환할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/FileSystemProviderStrings.ko.resx b/src/System.Management.Automation/resources/ko/FileSystemProviderStrings.ko.resx new file mode 100644 index 00000000000..83ff373cc05 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/FileSystemProviderStrings.ko.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 항목 호출 + + + 항목: {0} + + + 파일 제거 + + + 디렉터리 제거 + + + 파일 복사 + + + 항목: {0} 대상: {1} + + + 디렉터리 복사 + + + 파일 이름 바꾸기 + + + 디렉터리 이름 바꾸기 + + + 항목: {0} 대상: {1} + + + 파일 이동 + + + 디렉터리 이동 + + + 항목: {0} 대상: {1} + + + 속성 파일 설정 + + + 속성 Directory 설정 + + + 항목: {0} 속성: {1} 값: {2} + + + 속성 파일 지우기 + + + 속성 디렉터리 지우기 + + + 항목: {0} 속성: {1} + + + 파일 생성 + + + 디렉토리 생성 + + + 대상: {0} + + + 콘텐츠 지우기 + + + 항목: {0} + + + {0} 항목을 찾을 수 없습니다. + + + {0} 항목을 제거할 수 없습니다. {1} + + + 항목 {0}의 속성을 복원할 수 없습니다. {1} + + + 지정한 경로 {0}에 개체가 없습니다. + + + 디렉터리 {0}은(는) 비어 있지 않으므로 제거할 수 없습니다. + + + 알 수 없는 파일 시스템 형식입니다. "file", "directory" 또는 "symboliclink"만 지정할 수 있습니다. + + + 지정한 경로가 basePath 밖의 항목을 가리키므로 경로를 처리할 수 없습니다. + + + 지정한 드라이브 루트 "{0}"이(가) 없거나 폴더가 아닙니다. + + + 지정된 이름의 {0} 파일이 이미 있습니다. + + + 스트림을 한 번에 1바이트씩 읽을 때는 구분 기호를 지정할 수 없습니다. + + + 항목 {0}을(를) 자체로 덮어쓸 수 없습니다. + + + 지정한 대상은 경로 또는 디바이스 이름을 나타내므로 이름을 바꿀 수 없습니다. + + + 속성 {0}이(가) 없거나 찾을 수 없습니다. + + + 이 작업을 수행할 수 있는 액세스 권한이 없거나, 항목이 숨김, 시스템 또는 읽기 전용입니다. + + + 특성을 지원하지 않으므로 특성을 설정할 수 없습니다. Archive, Hidden, Normal, ReadOnly 또는 System 특성만 설정할 수 있습니다. + + + 지원되지 않는 속성이므로 속성을 지울 수 없습니다. Attributes 속성만 지울 수 있습니다. + + + 대상이 예약된 디바이스 이름을 나타내므로 경로 '{0}'을(를) 처리할 수 없습니다. + + + '-AsByteStream'이 지정되면 인코딩은 사용되지 않습니다. + + + 바이트 인코딩을 계속할 수 없습니다. 바이트 인코딩을 사용할 때 콘텐츠는 바이트 형식이어야 합니다. + + + 파일 {0}을(를) 찾을 수 없어서 파일을 처리할 수 없습니다. + + + 디렉터리: + + + 파일 인코딩을 검색할 수 없습니다. 콘텐츠를 역방향으로 읽을 때는 지정한 인코딩 {0}을(를) 지원하지 않습니다. + + + 파일 '{0}'의 대체 데이터 스트림 '{1}'을(를) 열 수 없습니다. + + + 파일 '{1}'의 스트림 '{0}'입니다. + + + Raw 및 Wait 매개 변수는 같은 명령에서 함께 지정할 수 없습니다. + + + Persist 스위치 매개 변수를 사용하려면 드라이브 이름이 운영 체제에서 지원되어야 합니다. 예를 들어 A-Z 드라이브 문자를 사용할 수 있습니다. + + + Persist 매개 변수를 사용할 때 루트는 원격 컴퓨터의 파일 시스템 위치여야 합니다. + + + '{0}' 매개 변수와 '{1}' 매개 변수는 같은 명령에서 함께 지정할 수 없습니다. + + + 작업에 사용할 디렉터리가 필요합니다. '{0}' 항목은 디렉터리가 아닙니다. + + + 접합 만들기 + + + 바로 가기 링크 만들기 + + + 이 작업에는 관리자 권한이 필요합니다. + + + 하드 링크 만들기 + + + 작업에 사용할 파일이 필요합니다. '{0}' 항목은 파일이 아닙니다. + + + 지정한 경로에서는 하드 링크를 지원하지 않습니다. + + + 지정한 경로에서는 기호 링크를 지원하지 않습니다. + + + {1}에 {0} 복사 + + + 대상 경로 {0}은(는) 대상 위치에 이미 있는 파일입니다. + + + 파일 {0}을(를) 원격 대상 위치에 복사하지 못했습니다. + + + {0}에서 {1}(으)로 + + + 디렉터리 '{0}'을(를) 파일 '{0}'에 복사할 수 없습니다. + + + 디렉터리 {0}의 자식 항목을 가져오지 못했습니다. + + + 원격 파일 '{0}'을(를) 읽지 못했습니다. + + + 원격 대상 {0}이(가) 파일인지 확인할 수 없습니다. + + + 원격 대상에서 '{0}' 디렉터리를 만들지 못했습니다. + + + 드라이브의 최대 크기를 초과했습니다. {0}. + + + 경로가 이미 있으므로 링크를 만들 수 없습니다. {0}. + + + 이미 방문한 Directory {0}을(를) 건너뜁니다. + + + 대상 경로는 원본 또는 원본 자체의 하위 디렉터리일 수 없습니다. {0}. + + + 대상과 경로는 같을 수 없습니다. + + + 파일 {0}개 중 {1}개를 복사함 + + + {0}개 중 {1}개({2:0.0} MB/s) + + + 파일 {0}개 중 {1}개를 제거함 + + + {0}개 중 {1}개({2:0.0} MB/s) + + + 정션을 만들려면 대상에 절대 경로가 필요합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/FormatAndOutXmlLoadingStrings.ko.resx b/src/System.Management.Automation/resources/ko/FormatAndOutXmlLoadingStrings.ko.resx new file mode 100644 index 00000000000..d5a9db1b97f --- /dev/null +++ b/src/System.Management.Automation/resources/ko/FormatAndOutXmlLoadingStrings.ko.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 파일 {1}의 XPath {0} 오류: XML 요소 {2}에는 특성을 사용할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 노드 {2}에는 자식 개체가 있을 수 없습니다. + + + 파일 {1}의 XPath {0}에서 오류가 발생했습니다: {2}은(는) 유효하지 않습니다. + + + 파일 {1}의 XPath {0} 오류: 기본값 {2}이(가) 하나 이상 있어야 합니다. + + + 파일 {1}의 XPath {0} 오류: 기본값 {2}이(가) 두 개 이상 있을 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 컨트롤 이름은 null이거나 비워 둘 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: Out Of Band 보기는 CustomControl 또는 ListControl만 사용할 수 있습니다. + + + 파일 {1}의 XPath {0} 오류: Out Of Band 보기에는 GroupBy를 사용할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 뷰를 로드할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: "{2}"은(는) 올바른 맞춤 값이 아닙니다. + + + 파일 {1}의 XPath {0} 오류: 양의 정수가 필요합니다. + + + 파일 {1}의 XPath {0} 오류: 열 머리글 정의가 올바르지 않습니다. 모든 머리글이 무시됩니다. + + + 파일 {1}의 XPath {0} 오류: 대체 집합 #{3}의 행 항목 수 = {2}이(가) 기본 행 항목 수 = {4}과(와) 일치하지 않습니다. + + + 파일 {1}의 XPath {0} 오류: 헤더 항목 수 = {2}이(가) 기본 행 항목 수 = {3}과(와) 일치하지 않습니다. + + + 파일 {1}의 XPath {0} 오류: 목록 보기 항목은 하나 이상 지정해야 합니다. + + + 파일 {1}의 XPath {0} 오류: 속성 항목이 올바르지 않습니다. + + + 파일 {1}의 XPath {0} 오류: 정의 목록이 없습니다. + + + 파일 {1}의 XPath {0} 오류: 부울 값이 필요합니다. + + + 파일 {1}의 XPath {0} 오류: 음수가 아닌 정수가 필요합니다. + + + 파일 {1}의 XPath {0} 오류: 정수가 필요합니다. + + + 파일 {1}의 XPath {0} 오류: 내부 텍스트 값이 없습니다. + + + 파일 {1}의 XPath {0} 오류: 사용자 지정 컨트롤 토큰 목록은 비워 둘 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: {2}을(를) 로드하지 못했습니다. + + + 파일 {1}의 XPath {0} 오류: 식 없이 {2}을(를) 지정할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 식과 함께 {2}을(를) 지정할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 서식 문자열이 없습니다. + + + 파일 {1}의 XPath {0} 오류: 스크립트 블록 텍스트가 없습니다. + + + 파일 {1}의 XPath {0} 오류: 속성이 없습니다. + + + 파일 {1}의 XPath {0} 오류: 스크립트 블록 "{2}"이(가) 올바르지 않습니다. + + + 파일 {1}의 XPath {0} 오류: 어셈블리 {4}의 리소스 {3}에서 문자열 {2}을(를) 찾을 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 어셈블리 {3}의 리소스 {2}을(를) 찾을 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 어셈블리 {2}을(를) 찾을 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 노드는 XmlElement여야 합니다. + + + 파일 {1}의 XPath {0} 오류: 식이 필요합니다. + + + 파일 {1}의 XPath {0} 오류: 식 없이 컨트롤이나 Label을 사용할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 컨트롤과 Label을 동시에 사용할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: SelectionSetName과 TypeName을 동시에 사용할 수 없습니다. + + + 파일 {1}의 XPath {0} 오류: 뷰를 적용할 형식 또는 조건이 지정되지 않았습니다. + + + 파일 {1}의 XPath {0} 오류: {2}은(는) 유효하지 않습니다. + + + 파일 {1}의 XPath {0} 오류: 중복된 노드가 있습니다. + + + 파일 {1}의 XPath {0} 오류: {2} 과(와) {3}은(는) 서로 배타적입니다. + + + 파일 {1}의 XPath {0} 오류: {2}, {3} 및 {4}은(는) 서로 배타적입니다. + + + 파일 {1}의 XPath {0}에서 오류가 발생했습니다: {2}은(는) 알 수 없는 노드입니다. + + + 파일 {1}의 XPath {0} 오류: {2}은(는) 알 수 없는 특성입니다. + + + 파일 {1}의 XPath {0} 오류: {2}은(는) 누락된 특성입니다. + + + 파일 {1}의 XPath {0}에서 오류가 발생했습니다. 노드 {2}이(가) 없습니다. + + + 파일 {1}의 XPath {0} 오류: {2}에 노드가 없습니다. + + + 파일 {1}의 XPath {0} 오류: {2}은(는) 알 수 없는 노드입니다. + + + 파일 {1}의 XPath {0} 오류: {2}은(는) 빈 특성입니다. + + + 파일 {0}에서 오류가 발생했습니다: {1} + + + 파일 {0}에 오류가 너무 많습니다. + + + 형식 데이터 파일을 로드하는 동안 오류가 발생했습니다. {0} + + + (전역 어셈블리 캐시) {0} + + + {0}, {1} + + + 경로 {0}이(가) 완전히 정규화되지 않았습니다. 완전히 정규화된 형식 파일 경로를 지정하세요. + + + FormatTable이 runspace 외부에서 만들어졌을 수 있으므로 FormatTable을 업데이트할 수 없습니다. + + + FormatTable을 로드하는 동안 오류가 발생했습니다. 자세한 오류 메시지를 보려면 Errors 속성의 내용을 확인하세요. + + + 데이터 "{0}"의 서식을 지정하는 동안 오류가 발생했습니다: {1} + + + 인덱스 {1}의 형식 이름 {0}이(가) 있는 뷰 데이터에서 오류가 발생했습니다. 헤더 항목 수= {2}이(가) 기본 행 항목 수= {3}과(와) 일치하지 않습니다. + + + 형식 이름 {0}의 인덱스 {1}에 있는 뷰 데이터 오류: 서식 데이터 "{2}"이(가) 올바르지 않습니다. + + + 형식 이름 {0}의 인덱스 {1}에 있는 뷰 데이터 오류: 스크립트 블록 "{2}"이(가) 올바르지 않습니다. + + + 형식 이름 {0}의 인덱스 {1}에 있는 뷰 데이터 오류: {2}을(를) 로드하지 못했습니다. + + + 형식 이름 {0}의 인덱스 {1}에 있는 뷰 데이터 오류: TableControl에는 {2}이(가) 하나만 포함되어야 합니다. + + + 형식 이름 {0}의 인덱스 {1}에 있는 뷰 데이터 오류: 기본값이 하나 이상 있어야 합니다 {2}. + + + 형식 이름 {0}의 인덱스{1}에 있는 뷰 데이터 오류: 목록 보기 항목을 하나 이상 지정해야 합니다. + + + 형식 이름 {0}의 인덱스 {1}에 있는 뷰 데이터 오류: 기본값 {2}이(가) 두 개 이상 있을 수 없습니다. + + + "{0}" 형식의 서식 데이터에 오류가 너무 많습니다. + + + 공유 형식 테이블은 항목을 하나만 사용해 업데이트할 수 있습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/FormatAndOut_MshParameter.ko.resx b/src/System.Management.Automation/resources/ko/FormatAndOut_MshParameter.ko.resx new file mode 100644 index 00000000000..ce05cc3e57f --- /dev/null +++ b/src/System.Management.Automation/resources/ko/FormatAndOut_MshParameter.ko.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 + + + {0}을(를) 다음 {1} 형식 중 하나로 변환할 수 없습니다. + + + 매개 변수 값이 null입니다. 다음 형식 중 하나가 필요합니다: {0}. + + + 중복된 키 "{0}"이(가) "{1}"과(와) 충돌합니다. + + + "{0}" 키의 형식이 {1}(으)로 잘못되었습니다. 예상 형식은 {2}입니다. + + + "{0}" 키에 잘못된 형식이 {1}이(가) 있습니다. 필요한 형식은 {2}입니다. + + + {0} 키가 모호합니다. {1}과(와) {2}이(가) 충돌합니다. + + + 키 값은 null일 수 없습니다. + + + {0} 키 유형이 유효하지 않습니다. 키는 문자열이어야 합니다. + + + {0} 키에 값이 없습니다. + + + {0}에 필수 항목이 없습니다. + + + {0} 키가 잘못되었습니다. + + + 키 "{0}"의 값 "{1}"이(가) 잘못되었습니다. 유효한 값은 {2}입니다. + + + "{1}" 키의 "{0}" 값은 0보다 커야 합니다. + + + 키 "{0}"에 대해 빈 서식 문자열은 사용할 수 없습니다. + + + "{0}" 키에는 빈 문자열 값을 사용할 수 없습니다. + + + 빈 문자열 값은 허용되지 않습니다. + + + "{0}" 키의 값 "{1}"에는 와일드카드 문자를 사용할 수 없습니다. + + + "{0}"에서는 와일드카드 문자를 사용할 수 없습니다. + + + EnumerableExpansion 값이 올바르지 않습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/FormatAndOut_format_xxx.ko.resx b/src/System.Management.Automation/resources/ko/FormatAndOut_format_xxx.ko.resx new file mode 100644 index 00000000000..3fb4d0af7f9 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/FormatAndOut_format_xxx.ko.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet 매개 변수 View와 Property는 함께 사용할 수 없습니다. + + + Cmdlet 매개 변수 AutoSize와 Column은 함께 사용할 수 없습니다. + + + 뷰 이름 {0}을(를) 찾을 수 없습니다. + + + 뷰 이름 {0}을(를) {1} 서식에서 찾을 수 없습니다. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + 기존 {0} 뷰가 {1} 개체에 없습니다. + + + 뷰 이름 {0}을(를) 찾을 수 없습니다. 다음 {1} 뷰 중 하나를 지정하고 다시 시도하세요: {2}. + + + 사용할 수 있는 다른 뷰 이름 중 하나를 사용해 보세요. + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + 다음 개체는 IEnumerable을 지원합니다. + + + IEnumerable에 개체가 없습니다. + + + IEnumerable에는 다음 개체가 포함되어 있습니다. + + + IEnumerable에는 다음과 같은 {0} 개체가 포함되어 있습니다. + + + 알 수 없는 클래스 ID {0}. + + + {1} 속성의 {0} 형식이 올바르지 않습니다. + + + {0} 데이터 멤버의 값은 null일 수 없습니다. + + + 개체 유형을 인식할 수 없습니다. + + + 클래스 ID {0}인 개체를 만들지 못했습니다. + + + {0} 속성은 재귀적입니다. + + + 식 "{0}"을(를) 계산하지 못했습니다. + + + 서식 문자열 "{0}"을(를) 해석하지 못했습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/FormatAndOut_out_xxx.ko.resx b/src/System.Management.Automation/resources/ko/FormatAndOut_out_xxx.ko.resx new file mode 100644 index 00000000000..79da3a98c05 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/FormatAndOut_out_xxx.ko.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> 다음 페이지; <CR> 다음 줄; Q 종료 + + + LineOutput 값은 null이면 안 됩니다. + + + lineOutput 유형 {0}은(는) 예상되지 않았습니다. LineOutput에는 {1} 형식이 필요합니다. + + + "{0}" 형식의 개체가 올바르지 않거나 순서가 맞지 않습니다. 기본 서식과 충돌하는 사용자가 지정한 "{1}" 명령 때문일 수 있습니다. + + + 파일 "{0}"을(를) 열 수 없습니다. + + + 파일에 출력 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/GetErrorText.ko.resx b/src/System.Management.Automation/resources/ko/GetErrorText.ko.resx new file mode 100644 index 00000000000..988a0279680 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/GetErrorText.ko.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 기본 이름이 "{0}"인 리소스를 로드할 수 없습니다. + + + ID가 "{0}"인 리소스 문자열을 로드할 수 없습니다. + + + Stop 정책 설정으로 인해 명령 실행이 제한됩니다. + + + 어셈블리가 등록되지 않아 메시지 "{0}" "{1}" "{2}"을(를) 검색할 수 없습니다. + + + 메시지 "{0}" "{1}" "{2}"을(를) 검색할 수 없습니다. 템플릿 문자열 "{3}"의 형식이 올바르지 않습니다. + + + 메시지 "{0}" "{1}" "{2}"을(를) 검색할 수 없습니다. 템플릿 문자열은 있지만 값이 비어 있거나 공백입니다. + + + 파이프라인이 중지되었습니다. + + + 호출 깊이 초과로 인해 스크립트가 실패했습니다. + + + 호출 깊이 초과로 인해 파이프라인이 실패했습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/HelpDisplayStrings.ko.resx b/src/System.Management.Automation/resources/ko/HelpDisplayStrings.ko.resx new file mode 100644 index 00000000000..2bc09ef4820 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/HelpDisplayStrings.ko.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 이름 + + + 개요 + + + 설명 + + + SYNTAX + + + 매개 변수 + + + 입력 + + + 출력 + + + 종료 오류 + + + 종료되지 않는 오류 + + + 참고 + + + + + + 예제 + + + + + + 출력 + + + 관련 링크 + + + 간단한 설명 + + + 제목: + + + 질문: + + + 답변 + + + 용어: + + + 정의: + + + 콘텐츠: + + + 공급자 이름 + + + 이 cmdlet은 다음 공통 매개 변수를 지원합니다. Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable 및 OutVariable입니다. 자세한 내용은 다음을 참조하세요. + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + 필수인가요? + + + 위치 + + + 형식: + + + 대상 개체 유형: + + + 기본값 + + + 파이프라인 입력 허용 + + + 와일드카드 문자 허용 + + + (범주: + + + 추천 동작: + + + 더 자세한 내용을 보려면 다음을 입력하세요. + + + 기술 정보를 보려면 다음을 입력하세요. + + + 예제를 보려면 다음을 입력하세요. + + + 온라인 도움말을 보려면 다음을 입력하세요. + + + <CommonParameters> + + + REMARKS + + + true + + + 명명됨 + + + 드라이브 + + + 기능 + + + 작업 + + + 작업: + + + 필터 + + + 동적 매개 변수 + + + 지원되는 cmdlet: + + + 별칭 + + + Get-Help에서 이 cmdlet의 도움말 파일을 이 컴퓨터에서 찾을 수 없습니다. 부분적인 도움말만 표시됩니다. + -- 이 cmdlet을 포함하는 모듈의 도움말 파일을 다운로드하여 설치하려면 Update-Help를 사용하세요. + -- 이 cmdlet의 도움말 항목을 온라인으로 보려면 "Get-Help {0} -Online"을 입력하거나 + {1}(으)로 이동 + + + 없음 + + + 별칭 + + + 동적 여부 + + + 매개 변수 집합 이름 + + + UI 문화권 {0}에 대한 HelpInfo XML 파일을 검색할 수 없습니다. 모듈 매니페스트의 HelpInfoUri 속성이 올바른지 확인하거나 네트워크 연결을 확인한 다음 명령을 다시 시도하세요. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + 지정한 문화권은 지원되지 않습니다. {0}. 다음 목록에서 문화권을 지정하세요: {{{1}}}. + + + 오류 처리를 미루고 대체 문화권을 시도합니다. 대체 문화권이 모두 지원되지 않으면 다음과 같이 오류가 표시됩니다: +{0} + + + ModuleBase 디렉터리를 찾을 수 없습니다. 디렉터리를 확인한 다음 다시 시도하세요. + + + 경로 {0}은(는) 올바른 디렉터리가 아닙니다. 디렉터리가 있는지 확인한 다음 다시 시도하세요. + + + 도움말 URI에는 10개를 초과하는 리디렉션을 포함할 수 없습니다. 올바른 Help URI를 지정하세요. + + + 도움말 업데이트 + + + 도움말 콘텐츠에 연결하는 중... + + + 도움말 콘텐츠 다운로드 중... + + + 도움말 콘텐츠를 설치하는 중... + + + 도움말 콘텐츠를 찾는 중... + + + (모두) + + + 다음 패턴과 일치하는 PowerShell 모듈을 찾을 수 없습니다. {0}. 패턴을 확인한 다음 명령을 다시 시도하세요. + + + 지정된 FullyQualifiedModule {0}과(와) 일치하는 PowerShell 모듈을 찾을 수 없습니다. FullyQualifiedModule 값을 확인한 다음 명령을 다시 시도하세요. + + + 도움말 콘텐츠를 찾을 수 없습니다. 서버를 사용할 수 있는지, 그리고 도움말 콘텐츠 위치가 HelpInfo XML에 올바르게 정의되어 있는지 확인하세요. + + + 지정한 모듈이 업데이트 가능한 도움말을 지원하지 않으므로 Update-Help 명령이 실패했습니다. Get-Help -Online을 사용하거나 온라인에서 이 모듈의 명령에 대한 도움말을 찾아보세요. + + + 다음 매개 변수는 null이거나 비워 둘 수 없습니다. Module. + + + 다음 매개 변수는 null이거나 비워 둘 수 없습니다. Path. + + + Update-Help가 완료되었습니다. + + + 도움말 콘텐츠를 추출하는 중 오류가 발생했습니다. + + + 도움말 콘텐츠에 연결할 수 없습니다. 도움말 콘텐츠가 저장된 서버를 사용할 수 없을 수 있습니다. 서버를 사용할 수 있는지 확인하거나 서버가 다시 온라인 상태가 될 때까지 기다린 다음 명령을 다시 시도하세요. + + + 지정한 위치의 도움말 콘텐츠가 올바르지 않습니다. 유효한 도움말 콘텐츠가 포함된 위치를 지정하세요. + + + HelpInfo XML이 올바르지 않습니다. 유효한 HelpInfo XML을 지정하세요. + + + 도움말 내용이 다음 위치에 저장되었습니다. {0} + + + {0}에서 도움말 콘텐츠 XSD 파일을 찾을 수 없습니다. 지정된 위치에 XSD 파일이 있는지 확인한 다음 명령을 다시 시도하세요. + + + 모듈에 대한 도움말을 업데이트하지 못했습니다: +'{0}' +{1} + + + 도움말 저장 중 + + + 도움말 콘텐츠에 올바르지 않은 파일이 포함되어 있습니다. .txt 및 .xml 파일만 지원됩니다. + + + 모듈 '{0}'에 대한 도움말을 저장하지 못했습니다. {1} + + + UI 문화권이 {{{1}}}인 모듈 '{0}'에 대한 도움말을 저장하지 못했습니다: {2}. +영어-US 도움말 콘텐츠를 사용할 수 있으며 Save-Help -UICulture en-US를 사용하여 저장할 수 있습니다. + + + UI 문화권이 {{{1}}}인 모듈 '{0}'에 대한 도움말을 업데이트하지 못했습니다: {2}. +영어-US 도움말 콘텐츠를 사용할 수 있으며 Update-Help -UICulture en-US를 사용하여 설치할 수 있습니다. + + + 현재 문화권은 ({0})이며, 어떤 언어와도 연결되어 있지 않습니다. 시스템 문화권을 변경하거나 Update-Help -UICulture en-US를 사용하여 영어-US 도움말 콘텐츠를 설치하는 것이 좋습니다. + + + false + + + -Recurse 매개 변수는 원본 경로가 지정된 경우에만 사용할 수 있습니다. + + + 경로 {0}에 FileSystem 공급자가 없습니다. 지정한 경로에 FileSystem 공급자가 포함되어 있는지 확인한 다음 명령을 다시 시도하세요. + + + {0}에 대한 도움말을 검색하는 중... + + + 다음 패턴과 일치하는 UI 문화권을 찾을 수 없습니다. {0}. 패턴을 확인한 다음 명령을 다시 시도하세요. + + + 이 컴퓨터에서 지난 24시간 이내에 Save-Help 명령이 실행되었기 때문에 모듈 {0}에 대한 도움말이 저장되지 않았습니다. +도움말을 다시 저장하려면 명령에 Force 매개 변수를 추가하세요. + + + 이 컴퓨터에서 지난 24시간 이내에 Update-Help 명령이 실행되었기 때문에 모듈 {0}에 대한 도움말이 업데이트되지 않았습니다. +도움말을 다시 업데이트하려면 명령에 Force 매개 변수를 추가하세요. + + + 가장 최신의 도움말 파일이 이미 설치되어 있습니다. + + + {0}: {1}. 문화권 {2} 버전 {3} + + + {0}에 업데이트됨 + + + 모듈 매니페스트의 HelpInfoUri 키 값은 도움말 파일이 저장된 웹 사이트의 컨테이너 또는 루트 URL을 가리켜야 합니다. HelpInfoUri '{0}'은(는) 컨테이너를 가리키지 않습니다. + + + 도움말 콘텐츠는 네임스페이스 {0}에 있어야 합니다. + + + Get-Help에서 이 cmdlet의 도움말 파일을 이 컴퓨터에서 찾을 수 없습니다. 부분적인 도움말만 표시됩니다. + -- 이 cmdlet을 포함하는 모듈의 도움말 파일을 다운로드하여 설치하려면 Update-Help를 사용하세요. + + + 최신 도움말 파일이 이미 다운로드되어 있습니다. + + + {0} 저장됨 + + + HelpInfoURI {0}이(가) HTTP로 시작하지 않습니다. + + + 도움말 콘텐츠의 루트 수준 요소는 "helpItems"여야 합니다. + + + 모듈 {0}에 대한 도움말을 저장하는 중 + + + 모듈 {0}에 대한 도움말을 업데이트하는 중 + + + URI를 확인하는 중: "{0}” + + + 도움말 URI: {0} + + + {0}, 현재 버전: {1}, 사용 가능한 버전: {2}, UICulture: {3} + + + 속성 + + + 방법 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/HelpErrors.ko.resx b/src/System.Management.Automation/resources/ko/HelpErrors.ko.resx new file mode 100644 index 00000000000..3ce13056f98 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/HelpErrors.ko.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help가 이 세션의 도움말 파일에서 {0}을(를) 찾을 수 없습니다. 업데이트된 도움말 항목을 다운로드하려면 "Update-Help"를 입력하세요. 온라인으로 도움말을 보려면 TechNet 라이브러리(https://go.microsoft.com/fwlink/?LinkID=107116)에서 도움말 항목을 검색하세요. + + + "{0}"이(가) 올바른 도움말 범주가 아니므로 도움말 범주를 처리할 수 없습니다. + + + 도움말 파일 "{0}"을(를) 로드할 수 없습니다. 자세한 정보: {1}. + + + 현재 사용자에게 파일에 대한 액세스 권한이 없으므로 도움말 파일 "{0}"에 액세스할 수 없습니다. 자세한 정보: {1}. + + + 도움말 파일 "{0}"이(가) 유효한 XML 문서가 아닙니다. 자세한 정보: {1}. + + + {0}에 대한 도움말 콘텐츠를 파일 {1}에서 로드하는 동안 오류가 발생했습니다. 자세한 정보: {2}. 업데이트된 도움말 항목을 다운로드하려면 Update-Help cmdlet을 실행하세요. 온라인으로 도움말을 보려면 TechNet 라이브러리(https://go.microsoft.com/fwlink/?LinkID=107116)에서 도움말 항목을 검색하세요. + + + 공급자 "{0}"을(를) 로드할 수 없습니다. 자세한 정보: {1}. + + + 도움말 파일을 로드할 수 없습니다. 도움말 파일 "{0}"을(를) 로드하는 동안 다음 {1} 오류가 발생했습니다. + + + 노드 "{0}"은(는) "{1}"을(를) 자식 노드로 가질 수 없습니다. 노드 경로: {2}. + + + 노드 "{0}"은(는) 유형 "{1}"의 자식 노드를 최대 {2}개까지 가질 수 있습니다. 노드 경로: {3}. + + + 레지스트리 키 "{0}{1}"을(를) 찾을 수 없습니다. "{2}"을(를) 사용하여 도움말 파일을 로드하세요. + + + 조건 {0}과(와) 일치하는 매개 변수가 없습니다. + + + {0}은(는) 요청된 도움말 범주에서 지원되지 않습니다. + + + 명령 코드 또는 명령의 도움말 파일에 도움말 항목의 인터넷 주소(URI)가 지정되어 있지 않아 이 도움말 항목의 온라인 버전을 표시할 수 없습니다. + + + 지정한 URI {0}이(가) 잘못되었습니다. + + + 온라인 도움말을 표시하기 위해 브라우저를 시작하지 못했습니다. URI {0}을(를) 열 프로그램이나 브라우저가 연결되어 있지 않습니다. + + + URI "{0}"에 지정된 프로토콜은 지원되지 않습니다. "{1}" 및 "{2}" 프로토콜만 지원됩니다. + + + 여러 도움말 항목을 찾았습니다. -{0} 옵션에는 도움말 항목을 하나만 사용하세요. + + + 연결된 runspace의 도움말을 가져올 수 없습니다. runspace가 열려 있지 않기 때문입니다. 암시적 원격 명령을 실행하여 runspace를 연 다음, 도움말을 다시 가져오세요. + + + 액세스가 거부되었습니다. 이 명령은 PowerShell Core 모듈이나 $pshome\Modules 디렉터리에 있는 어떤 모듈에 대해서도 도움말 항목을 업데이트할 수 없습니다. +이 도움말 항목을 업데이트하려면 "관리자 권한으로 실행"을 사용해 PowerShell을 시작한 다음 Update-Help를 다시 실행해 보세요. + + + {0}을(를) 사용하려면 애플리케이션에서 'Microsoft.NET.Sdk.WindowsDesktop'을 프로젝트 SDK로 사용하고, 해당 어셈블리 'Microsoft.PowerShell.GraphicalHost'를 사용할 수 있는지 확인하세요. ({1}) + + + {0}은(는) 원격 세션에서 작동하지 않습니다. + + + ForwardHelpTargetName은 함수 자체를 참조할 수 없습니다. + + + 제한된 세션에 있을 때 네트워크 위치에서 도움을 받을 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/HistoryStrings.ko.resx b/src/System.Management.Automation/resources/ko/HistoryStrings.ko.resx new file mode 100644 index 00000000000..51e26bd974e --- /dev/null +++ b/src/System.Management.Automation/resources/ko/HistoryStrings.ko.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}은(는) 기록 식별자의 올바른 값이 아닙니다. 양수를 지정한 후 다시 시도하세요. + + + ID {0}의 기록을 찾을 수 없습니다. + + + 개수는 여러 ID와 함께 사용할 수 없습니다. + + + 명령줄 {0}에 대한 기록을 찾을 수 없습니다. + + + 가장 최근 기록을 찾을 수 없습니다. + + + Invoke-History cmdlet이 루프에서 반복적으로 호출됩니다. + + + 여러 기록 명령은 처리할 수 없습니다. Invoke-History를 사용하면 한 번에 하나의 명령만 실행할 수 있습니다. + + + 입력 개체의 형식이 올바르지 않아 기록을 추가할 수 없습니다. + + + 식별자 {0}은(는) 올바르지 않습니다. 양수를 지정한 후 다시 시도하세요. + + + 이 명령은 세션 기록의 모든 항목을 지웁니다. + + + 개수는 여러 CommandLine 매개 변수와 함께 사용할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/HostInterfaceExceptionsStrings.ko.resx b/src/System.Management.Automation/resources/ko/HostInterfaceExceptionsStrings.ko.resx new file mode 100644 index 00000000000..aa8826ec72c --- /dev/null +++ b/src/System.Management.Automation/resources/ko/HostInterfaceExceptionsStrings.ko.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 + + + "{0}" 형식의 오류가 발생했습니다. + + + 호스트 프로그램 또는 명령 유형이 사용자 상호 작용을 지원하지 않으므로 사용자에게 메시지를 표시하는 명령이 실패했습니다. PowerShell 콘솔과 같이 사용자 상호 작용을 지원하는 호스트 프로그램을 사용하고, 사용자 상호 작용을 지원하지 않는 명령 유형에서 메시지 표시 관련 명령을 제거하세요. + + + 호스트 프로그램 또는 명령 유형이 사용자 상호 작용을 지원하지 않으므로 사용자에게 메시지를 표시하는 명령이 실패했습니다. 호스트에서 다음 메시지로 확인을 요청하는 중이었음: {0} + + + 풀이 닫혔거나 실패했으므로 메서드를 호출할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/InternalCommandStrings.ko.resx b/src/System.Management.Automation/resources/ko/InternalCommandStrings.ko.resx new file mode 100644 index 00000000000..46432f65208 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/InternalCommandStrings.ko.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 입력 이름 "{0}"이(가) 모호합니다. 이 이름은 여러 일치 항목에 해당할 수 있습니다. 가능한 일치 항목은 다음과 같습니다. {1} + + + 입력 이름 "{0}"이(가) 모호합니다. 이 이름은 여러 일치 멤버에 해당할 수 있습니다. 가능한 일치 항목은 다음과 같습니다. {1} + + + 키 '{0}'의 값 검색 + + + 다음 인수를 사용하여 메서드 '{0}'을(를) 호출합니다. {1} + + + 메서드 '{0}' 호출 + + + 속성 '{0}'의 값 검색 + + + inputObject: {0} + + + 'null' 입력 개체에는 작업을 수행할 수 없습니다. + + + 입력 이름 "{0}"을(를) 메서드로 확인할 수 없습니다. + + + 제한된 언어 모드에서는 메서드를 호출할 수 없습니다. + + + -WhatIf 및 -Confirm 매개 변수는 스크립트 블록에서 지원되지 않습니다. + + + RestrictedLanguage 모드에서는 '{0}' 작업이 허용되지 않습니다. + + + 지정된 두 값을 비교하려면 연산자가 필요합니다. 명령에 올바른 연산자를 포함한 다음 명령을 다시 시도하세요. 예: Get-Process | Where-Object -Property Name -eq Idle + + + 입력 이름 "{0}"을(를) 속성으로 확인할 수 없습니다. + + + 입력 이름 "{0}"을(를) 멤버로 확인할 수 없습니다. + + + 지정된 연산자에는 -Property 및 -Value 매개 변수가 모두 필요합니다. 두 매개 변수에 값을 모두 입력한 다음 명령을 다시 시도하세요. + + + 이 메서드는 현재 스레드에서 실행할 수 없습니다. cmdlet 스레드에서만 호출할 수 있습니다. + + + 변수를 사용하는 ForEach-Object -Parallel의 입력 개체는 스크립트 블록일 수 없습니다. 전달된 스크립트 블록 변수는 ForEach-Object -Parallel에서 지원되지 않으며 정의되지 않은 동작을 일으킬 수 있습니다. + + + ForEach-Object -Parallel의 파이프된 입력 개체는 스크립트 블록일 수 없습니다. 전달된 스크립트 블록 변수는 ForEach-Object -Parallel에서 지원되지 않으며 정의되지 않은 동작을 일으킬 수 있습니다. + + + 'TimeoutSeconds' 매개 변수는 'AsJob' 매개 변수와 함께 사용할 수 없습니다. + + + 다음 일반 매개 변수는 현재 Parallel 매개 변수 집합에서 지원되지 않습니다. +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + ForEach-Object -Parallel 입력을 처리하는 동안 예기치 않은 오류가 발생했습니다. 파이프된 입력 중 일부가 처리되지 않았을 수 있습니다. 오류: {0}. + + + ForEach-Object Cmdlet + + + 제한된 언어 모드에서 '{0}' 형식에 대한 메서드 호출은 허용되지 않습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/InternalHostStrings.ko.resx b/src/System.Management.Automation/resources/ko/InternalHostStrings.ko.resx new file mode 100644 index 00000000000..a2edf6dc03b --- /dev/null +++ b/src/System.Management.Automation/resources/ko/InternalHostStrings.ko.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 + + + EnterNestedPrompt가 ExitNestedPrompt만큼 자주 호출되지 않았습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/InternalHostUserInterfaceStrings.ko.resx b/src/System.Management.Automation/resources/ko/InternalHostUserInterfaceStrings.ko.resx new file mode 100644 index 00000000000..61a8ea1fe31 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/InternalHostUserInterfaceStrings.ko.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + DebugPreference 변수의 값이 'Stop'이므로 WriteDebug를 중지했습니다. + + + 값 {0}은(는) 지원되는 ActionPreference 값이 아닙니다. + + + "{0}" 매개 변수에는 값이 하나 이상 있어야 합니다. + + + 예(&Y) + + + 계속. + + + 모두 예(&A) + + + 계속하고 이 세션에서 계속할지 다시 묻지 않습니다. + + + 아니요(&N) + + + 오류로 작업을 종료합니다. + + + 모두 아니요(&L) + + + 오류로 작업을 종료합니다. 이 세션에서는 작업을 다시 시작하도록 요청하지 않습니다. + + + 일시 중단(&S) + + + 현재 작업을 일시 중지하고 명령 프롬프트로 이동합니다. 일시 중지된 작업을 다시 시작하려면 "exit"를 입력하세요. + + + 이 작업을 계속하시겠습니까? + + + (기본값은 "{0}"입니다.) + + + (기본 선택 항목은 {0}입니다.) + + + 선택[{0}]: + + + "{0}"에는 요소가 하나 이상 있어야 합니다. + + + "{0}"은(는) "{1}"의 유효한 인덱스여야 합니다. "{2}"은(는) 유효한 인덱스가 아닙니다. + + + 물음표("?")는 바로 가기 키로 사용할 수 없으므로 바로 가기 키를 처리할 수 없습니다. + + + 자세한 정보: {0} + + + 경고: {0} + + + 디버그: {0} + + + 호스트가 현재 전사 중이 아닙니다. + + + 명령 시작 시간: {0} + + + ********************** +PowerShell 기록 시작 +시작 시간: {0:yyyyMMddHHmmss} +사용자 이름: {1} +실행 사용자: {2} +구성 이름: {3} +컴퓨터: {4} ({5}) +호스트 애플리케이션: {6} +프로세스 ID: {7} +{8} +********************** + + + ********************** +PowerShell 기록 시작 +시작 시간: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell 기록 끝 +종료 시간: {0:yyyyMMddHHmmss} +********************** + + + 파일 경로 {0}은(는) 디렉터리로 확인됩니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/Logging.ko.resx b/src/System.Management.Automation/resources/ko/Logging.ko.resx new file mode 100644 index 00000000000..21c18d72963 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/Logging.ko.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + 알 수 없음 + + + 구성 파일에 선언된 엔진 실험적 기능 '{0}'은(는) 현재 PowerShell에 등록되어 있지 않습니다. + + + 구성 파일에 선언된 실험적 기능 '{0}'은(는) 유효하지 않습니다. +실험적 기능 이름은 아래 규칙을 따라야 합니다. + 엔진 기능 이름: 'PS[FeatureName]' + 모듈 기능 이름: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/Metadata.ko.resx b/src/System.Management.Automation/resources/ko/Metadata.ko.resx new file mode 100644 index 00000000000..e808b0d6ae2 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/Metadata.ko.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + "{0}"에 대해 특성을 초기화할 수 없습니다. "{1}" + + + 인수의 형식 "{0}"이(가) 매개 변수의 최대 및 최소 제한과 같은 형식({1})이 아니므로 인수의 유효성을 검사할 수 없습니다. 인수가 {1} 형식인지 확인한 다음 명령을 다시 시도하세요. + + + 인수 "{0}"은(는) 값이 0보다 크지 않으므로 유효성을 검사할 수 없습니다. + + + 인수 "{0}"은(는) 값이 0보다 크거나 같지 않으므로 유효성을 검사할 수 없습니다. + + + 인수 "{0}"은(는) 값이 0보다 작지 않으므로 유효성을 검사할 수 없습니다. + + + 인수 "{0}"는 값이 0보다 작거나 같지 않으므로 유효성을 검사할 수 없습니다. + + + 지정된 최소 범위({0})는 지정된 최대 범위({1})와 형식이 같지 않으므로 사용할 수 없습니다. 매개 변수의 ValidateRange 특성을 업데이트하세요. + + + MaxRange 및 MinRange 매개 변수 형식을 사용할 수 없습니다. 두 매개 변수는 모두 IComparable 인터페이스를 구현하는 개체여야 합니다. + + + 지정된 최대 범위가 지정된 최소 범위보다 작으므로 사용할 수 없습니다. 매개 변수의 ValidateRange 특성을 업데이트하세요. + + + {0} 인수가 허용되는 최대 범위인 {1}보다 큽니다. {1}보다 작거나 같은 인수를 제공한 다음 명령을 다시 시도하세요. + + + {0} 인수가 허용되는 최소 범위인 {1}보다 작습니다. {1}보다 크거나 같은 인수를 제공한 다음 명령을 다시 시도하세요. + + + 인수 "{0}"이(가) "{1}" 패턴과 일치하지 않습니다. "{1}"과(와) 일치하는 인수를 제공한 다음 명령을 다시 시도하세요. + + + 배열이 아닌 매개 변수에는 ValidateCount 특성을 적용할 수 없습니다. 매개 변수에서 특성을 제거하거나 매개 변수를 배열 매개 변수로 만드세요. + + + 매개 변수에는 정확히 {0}개의 값이 필요합니다. {1}개의 값이 제공되었습니다. + + + 매개 변수에는 {0}개 이상의 값과 {1}개 이하의 값이 필요합니다. {2}개의 값이 제공되었습니다. + + + 매개 변수에 지정된 최대 인수 개수가 지정된 최소 인수 개수보다 적습니다. 매개 변수의 ValidateCount 특성을 업데이트하세요. + + + 인수에 지정된 최대 문자 길이가 지정된 최소 인수 문자 길이보다 짧습니다. 매개 변수의 ValidateLength 특성을 업데이트하세요. + + + ValidateLength 특성은 string 또는 string[] 매개 변수에만 적용할 수 있습니다. 매개 변수를 string 또는 string[] 매개 변수로 바꾸세요. + + + 인수의 문자 길이({1})가 너무 짧습니다. 길이가 "{0}"보다 크거나 같은 인수를 지정한 다음 명령을 다시 시도하세요. + + + 인수의 문자 길이({1})가 너무 깁니다. 길이가 "{0}"보다 짧거나 같은 인수를 지정한 다음 명령을 다시 시도하세요. + + + 인수 "{0}"은(는) ValidateSet 특성에 지정된 집합 "{1}"에 속하지 않습니다. 집합에 있는 인수를 제공한 다음 명령을 다시 시도하세요. + + + 유효한 값 생성기가 null 값을 반환합니다. + + + 속성 "{1}"에서 "{0}"이(가) 실패했습니다. {2} + + + 명령을 가져오거나 실행할 수 없습니다. 이 명령에 대해 허용되는 최대 매개 변수 집합 수를 초과했습니다. + + + 인수 값이 문자열이 아니므로 인수를 처리할 수 없습니다. ArgumentTransformationAttribute가 지정된 매개 변수 인수의 값은 문자열이어야 합니다. + + + 값 {1}이(가) {0} 변수에 대한 올바른 값이 아니므로 변수의 유효성을 검사할 수 없습니다. + + + 값이 {0}인 변수 {1}이(가) 더 이상 유효하지 않으므로 특성을 추가할 수 없습니다. + + + 인수가 null입니다. 인수에 유효한 값을 제공한 다음 명령을 다시 실행하세요. + + + 인수 값이 null이거나 인수 컬렉션의 요소에 null 값이 있습니다. null 값이 포함되지 않은 컬렉션을 제공한 다음 명령을 다시 시도하세요. + + + 인수가 Null이거나 비어 있습니다. null이 아니고 비어 있지 않은 인수를 제공한 다음 명령을 다시 시도하세요. + + + 인수가 null이거나, 비어 있거나, 인수 컬렉션의 요소에 null 값이 포함되어 있습니다. null 값이 포함되지 않은 컬렉션을 제공한 다음 명령을 다시 시도하세요. + + + 인수가 null이거나, 비어 있거나, 공백 문자로만 구성되어 있습니다. 공백이 아닌 문자가 포함된 인수를 제공한 다음 명령을 다시 시도하세요. + + + 인수 컬렉션의 요소가 null이거나, 비어 있거나, 공백 문자로만 구성되어 있습니다. 해당 값이 포함되지 않은 컬렉션을 제공한 후 명령을 다시 시도하세요. + + + 이름이 '{0}'인 매개 변수가 명령에 대해 여러 번 정의되었습니다. + + + 이름이 '{0}'인 별칭이 명령에 이미 여러 번 정의되어 있으므로 매개 변수 별칭을 지정할 수 없습니다. + + + '{0}' 매개 변수는 '{1}' 매개 변수의 같은 이름 별칭과 충돌하므로 지정할 수 없습니다. + + + 값이 "{1}"인 인수에 대한 "{0}" 유효성 검사 스크립트가 True를 반환하지 않았습니다. 유효성 검사 스크립트가 실패한 이유를 확인한 후 명령을 다시 시도하세요. + + + "{0}" 인수에 유효한 PowerShell 버전이 포함되어 있지 않습니다. 올바른 버전 번호를 제공한 다음 명령을 다시 시도하세요. + + + 인수 '{0}'의 유효성을 검사할 수 없습니다. 유효한 변수 이름이 아닙니다. + + + 작업 변환 형식은 IAstToScriptBlockConverter에서 파생되어야 합니다. + + + 인수가 잘못되었습니다. 문자열 형식의 경로 인수를 제공하세요. + + + 경로 인수 드라이브 {0}이(가) 승인된 드라이브 집합 {1}에 속하지 않습니다. 승인된 드라이브가 포함된 경로 인수를 제공하세요. + + + 경로에 유효하지 않은 문자가 포함되어 있습니다. + + + 경로 인수에 루트 드라이브가 없습니다. 루트 드라이브가 포함된 전체 경로 인수를 제공하세요. + + + '{0}' 매개 변수의 인수 값은 null이거나 빈 문자열일 수 없습니다. + + + '{0}'은(는) '{1}' 매개 변수의 올바른 값이 아닙니다. 다음 멤버 중 하나를 지정한 다음 다시 시도하세요: {2}. + + + 입력을 처리할 수 없습니다. "{0}" 인수는 신뢰할 수 없습니다. + + + ValidateTrustedData 특성 검사 실패 + + + '{0}' 매개 변수 인수는 신뢰할 수 없으며, 제한 언어 모드에서 ValidateTrustedData 매개 변수 특성 검사에 실패합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/MiniShellErrors.ko.resx b/src/System.Management.Automation/resources/ko/MiniShellErrors.ko.resx new file mode 100644 index 00000000000..bb95c7070a9 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/MiniShellErrors.ko.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 + + + 런스페이스 구성 범주 {0}에서는 업데이트를 지원하지 않습니다. + + + 런스페이스의 어셈블리 목록을 업데이트하는 동안 다음 오류가 발생했습니다. {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/Modules.ko.resx b/src/System.Management.Automation/resources/ko/Modules.ko.resx new file mode 100644 index 00000000000..4c043247124 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/Modules.ko.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 지정한 모듈 '{0}'은(는) 어떤 모듈 디렉터리에서도 유효한 모듈 파일을 찾을 수 없어 로드되지 않았습니다. + + + 버전이 '{0}'인 지정된 모듈 '{1}'은(는) 어떤 모듈 디렉터리에서도 유효한 모듈 파일을 찾을 수 없어 로드되지 않았습니다. + + + 지정한 MaximumVersion '{0}'이(가) 잘못되었습니다. '*'를 사용하는 경우 MaximumVersion에 '*'를 하나만 사용할 수 있으며, 항상 MaximumVersion의 끝에 위치해야 합니다. + + + MaximumVersion이 '{1}'인 지정된 모듈 '{0}'은(는) 어떤 모듈 디렉터리에서도 유효한 모듈 파일을 찾지 못해 로드되지 않았습니다. + + + MinimumVersion이 '{1}'이고 MaximumVersion이 '{2}'인 지정된 모듈 '{0}'은(는) 어떤 모듈 디렉터리에서도 유효한 모듈 파일을 찾지 못해 로드되지 않았습니다. + + + MinimumVersion '{0}'은(는) MaximumVersion '{1}'보다 클 수 없습니다. + + + 해당 이름의 어셈블리를 찾을 수 없어 어셈블리 '{0}'를 로드하지 못했습니다. 어셈블리 이름을 확인한 후 다시 시도하세요. + + + 모듈 매니페스트 '{2}'의 필드 '{1}'에 나열된, '{0}'을(를) 처리할 모듈은 어떤 모듈 디렉터리에서도 유효한 모듈을 찾지 못해 처리되지 않았습니다. + + + -AsCustomObject 매개 변수는 스크립트 모듈에만 사용할 수 있으므로 모듈 '{0}'에 대해 사용자 지정 개체가 반환되지 않았습니다. + + + 모듈 매니페스트 '{0}'은(는) 유효한 PowerShell 모듈 매니페스트 파일이 아니므로 처리할 수 없습니다. 허용되지 않는 요소를 제거하세요: {1} + + + 모듈 매니페스트 파일 '{0}'을(를) 처리하는 과정에서 유효한 매니페스트 개체를 생성하지 못했습니다. 파일을 수정하여 유효한 PowerShell 모듈 매니페스트가 포함되도록 하세요. 유효한 매니페스트는 New-ModuleManifest cmdlet으로 만들 수 있습니다. + + + '{0}' 모듈의 매니페스트에 잘못된 멤버가 하나 이상 포함되어 있어 모듈을 가져올 수 없습니다. 유효한 매니페스트 멤버는 ({1})입니다. 잘못된 멤버({2})를 제거한 후 모듈을 다시 가져오세요. + + + 모듈을 설명하는 해시 테이블에 잘못된 멤버가 하나 이상 있습니다. 유효한 멤버는 ({0})입니다. 잘못된 멤버({1})를 제거한 후 다시 시도하세요. + + + 모듈 중첩 제한을 초과했으므로 모듈 '{0}'을(를) 로드할 수 없습니다. 모듈은 {1} 단계까지만 중첩할 수 있습니다. 모듈을 로드하는 순서를 검토하여 중첩 제한을 넘지 않도록 변경한 후 스크립트를 다시 실행하세요. + + + 'ModuleVersion' 멤버가 모듈 매니페스트에 없습니다. 이 멤버는 반드시 있어야 하고 'n.n.n.n' 형식의 버전 번호가 할당되어야 합니다. 누락된 멤버를 파일 '{0}'에 추가하세요. + + + 모듈 매니페스트 파일 '{2}'의 '{0}' 멤버가 잘못되었습니다: {1} + + + 모듈 '{1}'의 버전 '{0}'이(가) 필요한 최소 버전 '{2}'을(를) 충족하지 않습니다. 지원되는 버전 번호인지 확인한 후 모듈을 다시 로드해 보세요. + + + 이 컴퓨터의 PowerShell 버전은 '{0}'입니다. 모듈 '{1}'을(를) 실행하려면 '{2}' 이상의 PowerShell 버전이 필요합니다. 최소 요구 버전 이상의 PowerShell이 설치되어 있는지 확인한 후 다시 시도하세요. + + + 'ModuleToProcess' 멤버가 이진 모듈이면 모듈 매니페스트 멤버 'NestedModules'를 사용할 수 없습니다. '{0}'에서 모듈 매니페스트 파일을 편집한 후 다시 시도하세요. + + + 모듈 매니페스트의 멤버 '{0}'이(가) 잘못되었습니다: {1}. '{2}' 파일의 이 필드에 유효한 값이 지정되어 있는지 확인하세요. + + + 모듈 매니페스트 경로 '{0}'이(가) 잘못되었습니다. Path 인수의 값은 확장자가 '.psd1'인 단일 파일로 확인되어야 합니다. Path 인수의 값을 유효한 psd1 파일 경로로 변경한 후 다시 시도하세요. + + + 모듈 매니페스트 '{0}'의 ModuleVersion 키에 지정된 모듈 버전 '{1}'이(가) '{2}'의 버전 폴더 이름과 일치하지 않습니다. ModuleVersion 키의 값을 버전 폴더 이름과 일치하도록 변경하세요. + + + 모듈 매니페스트 '{1}'의 지정된 NestedModule 항목 '{0}'이(가) 잘못되었습니다. 이 항목을 유효한 값으로 업데이트한 후 다시 시도하세요. + + + 모듈 매니페스트 '{1}'의 지정된 RequiredAssemblies 항목 '{0}'이(가) 잘못되었습니다. 이 항목을 유효한 값으로 업데이트한 후 다시 시도하세요. + + + 모듈 매니페스트 '{1}'의 지정된 FileList 항목 '{0}'이(가) 잘못되었습니다. 이 항목을 유효한 값으로 업데이트한 후 다시 시도하세요. + + + 모듈 매니페스트 '{1}'의 지정된 RequiredModules 항목 '{0}'이(가) 잘못되었습니다. 이 항목을 유효한 값으로 업데이트한 후 다시 시도하세요. + + + 모듈 매니페스트 '{1}'의 지정된 ModuleList 항목 '{0}'이(가) 잘못되었습니다. 이 항목을 유효한 값으로 업데이트한 후 다시 시도하세요. + + + 모듈 매니페스트 '{0}'은(는) PowerShell 버전 '5.1' 이상에서만 지원되는 CompatiblePSEditions 키로 지정되어 있습니다. PowerShellVersion 키의 값을 '5.1' 이상으로 업데이트한 후 다시 시도하세요. + + + CompatiblePSEditions에 지정한 값 '{0}'에 중복된 PowerShell 에디션 이름이 있습니다. 중복된 PowerShell 에디션 이름을 제거한 후 다시 시도하세요. + + + ModuleVersion 키에 지정된 버전이 버전 폴더 이름과 같습니다. + + + 모듈 {1} 아래의 버전 폴더 {0}에 유효한 모듈 매니페스트 파일이 없으므로 해당 폴더를 건너뜁니다. + + + 이 모듈을 설명하는 해시 테이블에 'ModuleName' 멤버가 없습니다. + + + 이 모듈을 설명하는 해시 테이블에 'ModuleVersion', 'MaximumVersion' 및 'RequiredVersion' 멤버가 없습니다. 이 세 멤버 중 하나는 있어야 하며 'n.n.n.n' 형식의 버전 번호가 할당되어야 합니다. + + + 필수 모듈 '{1}'이(가) 로드되지 않았습니다. 모듈을 로드하거나 파일 '{0}'의 'RequiredModules'에서 해당 모듈을 제거하세요. + + + GUID가 '{2}'인 필수 모듈 '{1}'이(가) 로드되지 않았습니다. 모듈을 로드하거나 파일 '{0}'의 'RequiredModules'에서 해당 모듈을 제거하세요. + + + 버전이 '{2}'인 필수 모듈 '{1}'이(가) 로드되지 않았습니다. 모듈을 로드하거나 파일 '{0}'의 'RequiredModules'에서 해당 모듈을 제거하세요. + + + MaximumVersion이 '{2}'인 필수 모듈 '{1}'이(가) 로드되지 않았습니다. 모듈을 로드하거나 파일 '{0}'의 'RequiredModules'에서 해당 모듈을 제거하세요. + + + MinimumVersion이 '{2}'이고 MaximumVersion이 '{3}'인 필수 모듈 '{1}'이(가) 로드되지 않았습니다. 모듈을 로드하거나 파일 '{0}'의 'RequiredModules'에서 해당 모듈을 제거하세요. + + + ModuleVersion이 '{1}'인 모듈 '{0}'을(를) 찾을 수 없습니다. + + + RequiredVersion이 '{1}'인 모듈 '{0}'을(를) 찾을 수 없습니다. + + + 최대 버전이 '{1}'인 모듈 '{0}'을(를) 찾을 수 없습니다. + + + ModuleVersion이 '{1}'이고 MaximumVersion이 '{2}'인 모듈 '{0}'을(를) 찾을 수 없습니다. + + + 모듈 '{0}'을(를) 찾을 수 없습니다. + + + 제거된 모듈이 없습니다. 제거할 모듈을 올바르게 지정했는지, 해당 모듈이 runspace에 있는지 확인하세요. + + + 모듈 '{1}'에서 가져온 '{0}' 멤버는 다음 이유로 제거할 수 없습니다. {2} + + + 모듈 '{0}'은(는) 읽기 전용이어서 제거할 수 없습니다. 읽기 전용 모듈을 제거하려면 명령에 Force 매개 변수를 추가하세요. + + + 모듈 '{0}'이(가) 'constant'로 표시되어 있으므로 제거할 수 없습니다. 'constant'로 표시된 모듈은 제거할 수 없습니다. + + + 모듈 '{0}'은(는) '{1}'에 필요하므로 제거할 수 없습니다. 모듈을 제거하려면 명령에 Force 매개 변수를 추가하세요. + + + Export-ModuleMember cmdlet은 모듈 내부에서만 호출할 수 있습니다. + + + 확장명 '{0}'은(는) 유효한 모듈 확장명이 아닙니다. 지원되는 모듈 확장명은 '.dll', '.ps1', '.psm1', '.psd1' 및 '.cdxml'입니다. 확장명을 수정한 후 파일 '{1}'을(를) 다시 추가해 보세요. + + + 이 작업은 이진 모듈에서는 수행할 수 없습니다. 스크립트 모듈에서만 수행할 수 있습니다. + + + 파일 '{0}'은(는) 파일 확장명이 '.ps1'가 아니므로 허용되지 않습니다. + + + 알 수 없음 + + + (c) {0}. All rights reserved. + + + 가져온 "{0}" 함수를 제거하는 중입니다. + + + 가져온 "{0}" 별칭을 제거하는 중입니다. + + + 가져온 "{0}" 변수를 제거하는 중입니다. + + + '{0}' 경로에서 모듈을 로드하는 중입니다. + + + '{0}'을(를) '{1}' 경로에서 로드하는 중입니다. + + + 스크립트 파일 '{0}'을(를) 도트 소싱하는 중입니다. + + + 함수 '{0}을(를) 가져오는 중입니다. + + + cmdlet '{0}'을(를) 가져오는 중입니다. + + + 별칭 '{0}'을(를) 가져오는 중입니다. + + + 변수 '{0}'을(를) 가져오는 중입니다. + + + cmdlet '{0}'을(를) 내보내는 중입니다. + + + 함수 '{0}'을(를) 내보내는 중입니다. + + + 별칭 '{0}'을(를) 내보내는 중입니다. + + + 변수 '{0}'을(를) 내보내는 중입니다. + + + 모듈 '{0}'에서 가져온 일부 명령 이름에 승인되지 않은 동사가 포함되어 있어 검색이 잘 안될 수 있습니다. 승인되지 않은 동사가 있는 명령을 찾으려면 Verbose 매개 변수와 함께 Import-Module 명령을 다시 실행하세요. 승인된 동사 목록을 보려면 Get-Verb를 입력하세요. + + + {1} 모듈의 '{0}' 명령을 가져왔지만, 이름에 승인된 동사가 포함되어 있지 않아 찾기 어려울 수 있습니다. 승인된 동사 목록을 보려면 Get-Verb를 입력하세요. + + + {2} 모듈의 '{0}' 명령을 가져왔지만, 이름에 승인된 동사가 포함되어 있지 않아 찾기 어려울 수 있습니다. 제안된 대체 동사는 "{1}"입니다. + + + 가져온 일부 명령 이름에 다음 제한 문자 중 하나 이상이 포함되어 있습니다: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + 모듈 '{1}'의 명령 이름 '{0}'에 다음 제한 문자 중 하나 이상이 포함되어 있습니다: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + "{0}" 모듈 매니페스트 파일을 만드는 중입니다. + + + {0} (경로: '{1}') + + + 현재 프로세서 아키텍처는 {0}입니다. 모듈 '{1}'에는 {2} 아키텍처가 필요합니다. + + + 현재 PowerShell 호스트 이름은 '{0}'입니다. 모듈 '{1}'을(를) 사용하려면 PowerShell 호스트 '{2}'이(가) 필요합니다. + + + 현재 PowerShell 호스트는 '{0}'(버전 {1})입니다. 모듈 '{2}'을(를) 실행하려면 '{3}' 이상의 PowerShell 호스트 버전이 필요합니다. + + + 모듈 '{0}'의 모듈 매니페스트 + + + 생성자: {0} + + + 생성 날짜: {0} + + + 이 매니페스트와 연결된 스크립트 모듈 또는 이진 모듈 파일입니다. + + + RootModule/ModuleToProcess에 지정된 모듈의 중첩 모듈로 가져올 모듈 + + + 이 모듈을 고유하게 식별하는 데 사용하는 ID + + + 이 모듈의 작성자 + + + 이 모듈의 회사 또는 공급업체 + + + 이 모듈의 저작권 문구 + + + 이 모듈의 버전 번호입니다. + + + 이 모듈에서 제공하는 기능에 대한 설명 + + + 이 모듈에 필요한 PowerShell 엔진의 최소 버전 + + + 이 모듈에 필요한 CLR(공용 언어 런타임)의 최소 버전입니다. {0} + + + 이 모듈을 가져오기 전에 전역 환경으로 가져와야 하는 모듈 + + + 이 모듈을 가져오기 전에 호출자의 환경에서 실행되는 스크립트 파일(.ps1)입니다. + + + 이 모듈을 가져올 때 로드할 형식 파일(.ps1xml) + + + 이 모듈을 가져올 때 로드할 서식 파일(.ps1xml) + + + 이 모듈을 가져오기 전에 로드해야 하는 어셈블리 + + + 이 모듈과 함께 패키지된 모든 파일 목록 + + + RootModule/ModuleToProcess에 지정된 모듈에 전달할 프라이빗 데이터입니다. 여기에는 PowerShell에서 사용하는 추가 모듈 메타데이터가 있는 PSData 해시 테이블도 포함될 수 있습니다. + + + 이 모듈에 적용된 태그입니다. 온라인 갤러리에서 모듈을 검색하는 데 도움이 됩니다. + + + 이 프로젝트의 기본 웹 사이트 URL입니다. + + + 이 모듈의 라이선스 URL입니다. + + + 이 모듈을 나타내는 아이콘의 URL입니다. + + + 이 모듈의 ReleaseNotes + + + 이 모듈의 시험판 문자열 + + + 설치/업데이트/저장 시 모듈에 명시적 사용자 승인이 필요한지 여부를 나타내는 플래그 + + + 이 모듈의 외부 종속 모듈 + + + 해시 테이블 {0}의 끝 + + + Tags, ProjectUri, LicenseUri, IconUri 또는 ReleaseNotes 매개 변수 값을 사용하여 모듈 매니페스트를 만들려면 PrivateData 매개 변수 값이 해시 테이블이어야 합니다. Tags, ProjectUri, LicenseUri, IconUri 또는 ReleaseNotes 매개 변수 값을 제거하거나, PrivateData 내용을 해시 테이블로 감싸세요. + + + PrivateData가 해시 테이블로 정의되어야 하는데, 이 모듈 매니페스트에서는 개체로 정의되어 있습니다. PrivateData 내용을 해시 테이블로 감싸는 것이 좋습니다. 이렇게 하면 나중에 모듈 매니페스트에 Tags, ProjectUri, LicenseUri, IconUri 및 ReleaseNotes 속성을 추가할 수 있습니다. + + + 지정한 값 '{0}'이(가) 잘못되었습니다. 유효한 값으로 다시 시도하세요. + + + 이 모듈에서 내보낼 함수입니다. 최상의 성능을 위해 와일드카드를 사용하지 말고, 항목을 삭제하지 마세요. 내보낼 함수가 없으면 빈 배열을 사용하세요. + + + 이 모듈에서 내보낼 별칭입니다. 최상의 성능을 위해 와일드카드를 사용하지 말고, 항목을 삭제하지 마세요. 내보낼 별칭이 없으면 빈 배열을 사용하세요. + + + 이 모듈에서 내보낼 cmdlet입니다. 최상의 성능을 위해 와일드카드를 사용하지 말고, 항목을 삭제하지 마세요. 내보낼 cmdlet이 없으면 빈 배열을 사용하세요. + + + 이 모듈에서 내보낼 변수 + + + 이 모듈에서 내보낼 DSC 리소스 + + + 지원되는 PSEditions + + + 이 모듈에 필요한 프로세서 아키텍처(None, X86, Amd64) + + + 이 모듈과 함께 패키지된 모든 모듈 목록 + + + 이 모듈에 필요한 Microsoft .NET Framework의 최소 버전입니다. {0} + + + 이 모듈에 필요한 PowerShell 호스트의 이름 + + + 이 모듈에 필요한 PowerShell 호스트의 최소 버전 + + + 이 모듈의 HelpInfo URI + + + 현재 PowerShell 세션에서 {0} 모듈이 PSDrive를 제공하고 있으므로 어떤 모듈도 제거되지 않았습니다. 현재 PSDrive 공급자를 변경한 후 모듈을 다시 제거해 보세요. + + + 현재 범위에 동일한 이름의 멤버가 있어 cmdlet '{0}'을(를) 가져오지 않았습니다. + + + 현재 범위에 동일한 이름의 멤버가 있어 별칭 '{0}'을(를) 가져오지 않았습니다. + + + 현재 범위에 동일한 이름의 멤버가 있어 함수 '{0}'을(를) 가져오지 않았습니다. + + + 현재 범위에 동일한 이름의 멤버가 있어 변수 '{0}'을(를) 가져오지 않았습니다. + + + 모듈 매니페스트 '{0}'의 'ModuleToProcess', 'RootModule' 또는 'NestedModules' 멤버에는 와일드카드 문자를 사용할 수 없습니다. + + + 모듈 '{0}'은(는) PowerShell의 핵심 모듈입니다. 핵심 모듈을 제거하려면 명령에 Force 매개 변수를 추가하세요. + + + 모듈 매니페스트에는 'ModuleToProcess' 멤버와 'RootModule' 멤버가 동시에 포함될 수 없습니다. '{0}'에서 둘 중 하나를 모듈 매니페스트 파일에서 제거한 후 다시 시도하세요. + + + 모듈 매니페스트 멤버 'ModuleToProcess'는 더 이상 사용되지 않습니다. 대신 'RootModule' 멤버를 사용하세요. + + + 이 모듈에서 내보낸 명령의 기본 접두사입니다. Import-Module -Prefix를 사용하여 기본 접두사를 재정의하세요. + + + 'Global' 및 'Scope' 매개 변수는 함께 지정할 수 없습니다. 이 매개 변수 중 하나를 제거한 후 명령을 다시 실행해 보세요. + + + 필수 모듈 '{0}'이(가) 로드되지 않았습니다. 모듈 '{0}'의 모듈 매니페스트 '{1}'에 순환 종속성을 가리키는 requiredModule '{2}'이 있습니다. + + + 필수 모듈 '{0}'은(는) 어떤 모듈 디렉터리에서도 유효한 모듈 파일을 찾지 못해 로드되지 않았습니다. + + + 모듈 {0}의 일부 명령은 CimSession을 통해 가져올 수 없습니다. 모든 명령을 가져오려면 원격 서버에 PowerShell 원격 관리가 사용하도록 설정되어 있는지 확인한 후 Import-Module cmdlet에 PSSession 매개 변수를 추가해 보세요. + + + 모듈 {0}은(는) Windows PowerShell에서 {1} 원격 세션을 사용해 로드됩니다. 이 모듈의 모든 명령 입력과 출력은 역직렬화된 개체가 됩니다. 이 모듈을 PowerShell에 로드하려면 'Import-Module -SkipEditionCheck' 구문을 사용하세요. + + + Windows PowerShell 버전 {0}이(가) 감지되었습니다. Windows PowerShell 호환성 기능을 사용하여 모듈을 로드하려면 Windows PowerShell 5.1이 있어야 합니다. 이 기능을 사용하려면 https://aka.ms/WMF5Download에서 Windows Management Framework(WMF) 5.1을 설치하세요. + + + PowerShell 구성 파일의 'WindowsPowerShellCompatibilityModuleDenyList' 설정에 의해 모듈 '{0}'이(가) Windows PowerShell 호환성 기능을 사용해 로드되는 것이 차단되었습니다. + + + 모듈 {0}은(는) CimSession을 통해 가져올 수 없습니다. Import-Module cmdlet의 PSSession 매개 변수를 사용해 보세요. + + + {0}의 프로세서 아키텍처 값은 지원되지 않습니다. 프로세서 아키텍처에 대해 지원되는 열거형 값(None, MSIL, X86, Amd64, Arm) 중 하나를 지정하여 New-ModuleManifest 명령을 다시 실행하세요. + + + 원격 컴퓨터에 대해 Get-Module cmdlet을 실행하면 사용할 수 있는 모듈만 나열됩니다. 명령에 ListAvailable 매개 변수를 추가한 후 다시 시도하세요. + + + '{0}' 스냅인을 이미 가져왔으므로 '{0}' 모듈을 가져오지 못했습니다. + + + 모듈 매니페스트 '{0}'의 'RequiredAssemblies' 멤버에는 와일드카드 문자를 사용할 수 없습니다. + + + {1}의 {0} 키 값이 {2}이며, 모듈에 중첩 모듈이 있습니다. CDXML 파일이 루트 모듈일 때 중첩 모듈의 명령은 내보낼 수 없으므로 Import-Module 명령이 실패합니다. CDXML 파일을 NestedModules 키로 이동한 후 명령을 다시 시도하세요. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + 원격 명령 실패: {0}: {{0}} + + + 원격 모듈 '{0}'에 대한 프록시를 생성하지 못했습니다. {{0}} + + + 원격 모듈 {0}을(를) 처리하지 못했습니다. {1} + + + 원격 CimSession에서 모듈 데이터를 받지 못했습니다. {0} + + + GUID가 '{1}'이고 버전이 '{2}'인 필수 모듈 '{0}'은(는) 어떤 모듈 디렉터리에서 유효한 모듈 파일을 찾을 수 없어 로드되지 않았습니다. + + + CIM 서버에서 모듈 검색을 위한 CIM 공급자를 찾을 수 없습니다. {0} + {0} is a placeholder for a more detailed error message + + + Microsoft .NET Framework 버전 {0}은(는) 허용된 버전 목록에 포함되어 있지 않아 확인할 수 없습니다. + + + {0}을(를) 분석하는 중입니다. + {0} should not be localized, is used to contain a file path. + + + 처음 사용할 모듈을 준비하는 중입니다. + + + 사용 가능한 모듈을 검색하는 중 + + + UNC 공유 {0}을(를) 검색하는 중입니다. + {0} should not be localized, is used to contain a file path. + + + 원격 컴퓨터에 대해 Get-Module cmdlet을 실행할 때는 경로를 포함하지 않는 모듈 이름만 사용할 수 있습니다. Name 매개 변수에 경로로 확인되는 요소 '{0}'이(가) 있습니다. Name 매개 변수에 경로가 포함되지 않도록 수정한 후 다시 시도하세요. + + + 모듈 이름에 경로가 포함되어 있으면 ListAvailable 매개 변수 없이 Get-Module cmdlet을 실행할 수 없습니다. Name 매개 변수에 경로로 확인되는 요소 '{0}'이(가) 있습니다. Name 매개 변수에 경로가 포함되지 않도록 수정한 후 다시 시도하세요. + + + 지정한 모듈 '{0}'을(를) 찾을 수 없습니다. Name 매개 변수를 올바른 경로로 업데이트한 후 다시 시도하세요. + + + 모듈 {0}의 RepositorySourceLocation 속성을 채우는 중입니다. + + + 모듈 매니페스트 '{2}'의 필드 '{1}'에 나열된, '{0}'을(를) 처리할 모듈이 처리되지 않았습니다. {3} + + + 이 필수 구성 요소는 PowerShell 데스크톱 버전에만 유효합니다. + + + 모듈 '{0}'은(는) 현재 PowerShell 에디션 '{1}'을(를) 지원하지 않습니다. 지원되는 에디션은 '{2}'입니다. 이 모듈의 호환성 검사를 무시하려면 'Import-Module -SkipEditionCheck'를 사용하세요. + + + 모듈 '{0}'은(는) PowerShell 버전 '{1}'을(를) 지원하며, 설정 파일에 Windows 호환성 기능이 비활성화되어 있으므로 이를 사용해 암시적으로 로드할 수 없습니다. Windows PowerShell로 이 모듈을 로드하려면 'Import-Module -UseWindowsPowerShell'을 사용하고, 현재 PowerShell에서 로드를 시도하려면 'Import-Module -SkipEditionCheck'를 사용하세요. + + + 모듈 매니페스트에 선언된 실험적 기능에는 비어 있지 않은 문자열 값을 지정해야 합니다. + + + 잘못된 실험적 기능 이름이 하나 이상 발견되었습니다: {0}. 모듈 실험적 기능 이름은 'ModuleName.FeatureName' 형식을 따라야 합니다. + + + -SkipEditionCheck 스위치 매개 변수는 -ListAvailable 스위치 매개 변수 없이 사용할 수 없습니다. + + + ConstrainedLanguage 모드에서는 *.ps1 파일을 모듈로 가져올 수 없습니다. + + + 스크립트 모듈 {0}은(는) 모듈 매니페스트와 언어 모드가 다르기 때문에 로드하는 동안 오류가 발생했습니다. 매니페스트 언어 모드는 {1}이고 모듈 언어 모드는 {2}입니다. 모든 모듈 파일이 서명되어 있는지, 또는 애플리케이션 허용 목록 구성에 포함되어 있는지 확인하세요. + + + 이 모듈은 와일드카드 문자를 사용해 함수를 내보내는 동안 도트 소싱 연산자를 사용합니다. 이는 시스템이 애플리케이션 검증 적용 상태일 때는 허용되지 않습니다. + + + 실행 중인 세션과 언어 모드가 다른 모듈에서는 모듈 멤버를 내보낼 수 없습니다. + + + 세션이 ConstrainedLanguage 모드인 동안에는 새 모듈을 만들 수 없습니다. + + + 'Core' 버전과 호환되는 기본 제공 모듈 '{0}'을(를) 찾을 수 없습니다. PowerShell 기본 제공 모듈이 사용 가능한지 확인하세요. 이 모듈은 일반적으로 $PSHOME 모듈 경로 아래의 PowerShell 패키지와 함께 제공되며, PowerShell이 제대로 작동하는 데 필요합니다. + + + Export-ModuleMember Cmdlet + + + 모듈 '{0}'은(는) 현재 세션 '{1}'과 다른 언어 모드 '{2}'이(가) 있어 제한된 언어 모드에서 모듈 멤버를 내보낼 수 없습니다. + + + 모듈 암시적 함수 내보내기 + + + 모듈 '{0}'에 대한 암시적 함수 내보내기가 거부됩니다. 이 모듈은 신뢰할 수 있지만(전체 언어 모드에서 실행), 세션은 신뢰할 수 없기 때문입니다(제한된 언어 모드에서 실행). 모듈 함수는 항상 전체 이름으로 개별적으로 내보내는 것이 좋습니다. + + + 스크립트 파일을 모듈로 가져오기 + + + ConstrainedLanguage 모드에서는 스크립트 파일 '{0}'을(를) 모듈로 가져올 수 없습니다. + + + 모듈에 도트 소싱 연산자가 포함되어 있음 + + + 모듈 '{0}'은(는) 와일드카드 문자를 사용해 함수를 내보내면서 동시에 도트 소싱 연산자를 사용하므로 제한된 언어 모드에서 가져오기에 실패합니다. + + + "함수를 내보내는 모듈 + + + 모듈 '{0}'은(는) 이름 와일드카드 문자를 사용하여 함수를 내보냅니다. 제한된 언어 모드에서 실행하면 중첩된 모듈 함수 이름이 제거됩니다. + + + "New-Module cmdlet + + + 신뢰할 수 없는 제한된 언어 세션의 새 모듈은 FullLanguage 스크립트 블록을 제공하지 못하도록 차단됩니다. + + + "모듈 언어 모드가 일치하지 않음 + + + 부모 모듈과 다른 언어 모드를 사용하는 종속 모듈이 로드되고 있습니다. 제한된 언어 모드에서는 이 작업이 허용되지 않습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/MshHostRawUserInterfaceStrings.ko.resx b/src/System.Management.Automation/resources/ko/MshHostRawUserInterfaceStrings.ko.resx new file mode 100644 index 00000000000..15734f3a45a --- /dev/null +++ b/src/System.Management.Automation/resources/ko/MshHostRawUserInterfaceStrings.ko.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}"보다 크거나 같을 수 없습니다. + + + "{0}"은(는) 양수여야 합니다. + + + 모든 문자열은 null이거나 비어 있습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/MshSignature.ko.resx b/src/System.Management.Automation/resources/ko/MshSignature.ko.resx new file mode 100644 index 00000000000..495d32a0701 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/MshSignature.ko.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 + + + 서명이 확인되었습니다. + + + 파일 {0}에는 디지털 서명이 없습니다. 현재 시스템에서 이 스크립트를 실행할 수 없습니다. 스크립트 실행 및 실행 정책 설정에 대한 자세한 내용은 https://go.microsoft.com/fwlink/?LinkID=135170 about_Execution_Policies를 참조하세요. + + + 파일 {0}의 내용은 파일의 해시가 디지털 서명에 저장된 해시와 일치하지 않기 때문에 무단 사용자나 프로세스에 의해 변경되었을 수 있습니다. 지정한 시스템에서 스크립트를 실행할 수 없습니다. 자세한 내용은 Get-Help about_Signing을 실행해 보세요. + + + 파일 {0}은(는) 서명되었지만 이 시스템에서 서명자를 신뢰할 수 없습니다. + + + 시스템에서 {0} 파일에 대한 서명 작업을 지원하지 않으므로 파일에 서명할 수 없습니다. + + + 파일 이름 확장명이 없는 파일에서는 서명 작업을 지원하지 않으므로 파일에 서명할 수 없습니다. + + + 서명이 현재 시스템과 호환되지 않아 확인할 수 없습니다. + + + 서명이 현재 시스템과 호환되지 않아 확인할 수 없습니다. 해시 알고리즘이 올바르지 않습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/MshSnapInCmdletResources.ko.resx b/src/System.Management.Automation/resources/ko/MshSnapInCmdletResources.ko.resx new file mode 100644 index 00000000000..67e00a49d60 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/MshSnapInCmdletResources.ko.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 + + + 작업을 수행할 수 없습니다. 지정한 cmdlet은 사용자 지정 셸에서 지원되지 않습니다. + + + '{0}' 패턴과 일치하는 PowerShell 스냅인을 찾을 수 없습니다. 패턴을 확인한 다음 명령을 다시 시도하세요. + + + 지정한 스냅인 이름의 형식이 올바르지 않습니다. PowerShell 스냅인 이름에는 영숫자, 대시, 밑줄, 마침표만 사용할 수 있습니다. 이름을 수정한 다음 작업을 다시 시도하십시오. + + + PowerShell 스냅인 {0}은(는) 시스템 PowerShell 모듈이므로 추가할 수 없습니다. 모듈을 로드하려면 Import-Module을 사용하세요. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/MshSnapinInfo.ko.resx b/src/System.Management.Automation/resources/ko/MshSnapinInfo.ko.resx new file mode 100644 index 00000000000..e10459d4044 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/MshSnapinInfo.ko.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 + + + PowerShell 레지스트리 정보에 액세스할 수 없습니다. + + + PowerShell 엔진 레지스트리 정보에 액세스할 수 없습니다. + + + PublicKeyToken 정보에 액세스할 수 없습니다. + + + 이 컴퓨터에서는 PowerShell 버전 {0}을(를) 사용할 수 없습니다. + + + 이 컴퓨터에는 PowerShell 스냅인 '{0}'이(가) 설치되어 있지 않습니다. + + + 레지스트리 키 {0}에 대해 필수 값 {1}이(가) 지정되지 않았습니다. + + + 필수 값 {0}이(가) 레지스트리 키 {1}의 올바른 형식이 아닙니다. 예상 형식은 'string'입니다. + + + 필수 값 {0}이(가) 레지스트리 키 {1}의 올바른 형식이 아닙니다. 예상 형식은 'multistring'입니다. + + + 레지스트리에서 필요한 정보를 찾을 수 없거나 키 파일이 없습니다. 일부 cmdlet을 로드할 수 없습니다. + + + PowerShell 버전 {0}에 등록된 스냅인이 없습니다. + + + 판독기가 삭제되었으므로 문자열 리소스를 검색할 수 없습니다. + + + 버전 값 {0}이(가) 지정되지 않았거나 레지스트리 키 {1}에 대해 올바르지 않습니다. + + + PowerShell 유형 {0}에 대한 [PSVersion] 특성을 찾을 수 없습니다. [PSVersion(PowerShell SnapinBase.PSEngineVersion)]을 사용하여 해당 형식에 PSVersion 특성을 추가하세요. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/NativeCP.ko.resx b/src/System.Management.Automation/resources/ko/NativeCP.ko.resx new file mode 100644 index 00000000000..b69cdc7e476 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/NativeCP.ko.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 + + + ScriptBlock은 Command 매개 변수의 값으로만 지정할 수 있습니다. + + + Command 매개 변수의 값을 지정하지 않았습니다. + + + {7} 매개 변수에 잘못된 값({6})이 지정되었습니다. 유효한 값은 Text 및 Xml입니다. + + + InputFormat 매개 변수에 대한 값이 지정되지 않았습니다. 유효한 값은 Text 및 Xml입니다. + + + OutputFormat 매개 변수에 대한 값이 지정되지 않았습니다. 유효한 값은 text 및 XML입니다. + + + {6} 매개 변수에는 문자열 값이 필요합니다. + + + Args 매개 변수의 값을 지정하지 않았습니다. + + + {6} 매개 변수는 이미 지정되었습니다. + + + '{1}'의 '{0}' 스트림에서 XML을 처리할 수 없습니다. {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PSCommandStrings.ko.resx b/src/System.Management.Automation/resources/ko/PSCommandStrings.ko.resx new file mode 100644 index 00000000000..ae7dab49535 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PSCommandStrings.ko.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 + + + 매개 변수를 추가하려면 명령이 필요합니다. 매개 변수를 추가하기 전에 {0}에 명령을 추가해야 합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PSConfigurationStrings.ko.resx b/src/System.Management.Automation/resources/ko/PSConfigurationStrings.ko.resx new file mode 100644 index 00000000000..5cc6ae88f91 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PSConfigurationStrings.ko.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 + + + 보안 문제로 인해 PowerShell이 작동을 중지했습니다. 구성 파일을 읽을 수 없습니다. {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PSDataBufferStrings.ko.resx b/src/System.Management.Automation/resources/ko/PSDataBufferStrings.ko.resx new file mode 100644 index 00000000000..115be4bd93e --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PSDataBufferStrings.ko.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 + + + 지정한 인덱스가 0보다 작거나 버퍼의 항목 수보다 큽니다. 인덱스가 범위 {0}-{1}에 있어야 합니다. + + + null 참조를 값 형식으로 변환할 수 없습니다. + + + 값을 형식 {0}에서 형식 {1}(으)로 변환할 수 없습니다. + + + 닫힌 버퍼에는 개체를 추가할 수 없습니다. Add 및 Insert 작업이 성공하려면 버퍼를 열어 두세요. + + + SerializeInput 속성은 PSDataCollection의 PSObject 형식에만 설정할 수 있습니다. SerializeInput 속성을 false로 설정하거나 컬렉션 형식을 PSObject로 변경하세요. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PSListModifierStrings.ko.resx b/src/System.Management.Automation/resources/ko/PSListModifierStrings.ko.resx new file mode 100644 index 00000000000..6d220304681 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PSListModifierStrings.ko.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 + + + 알 수 없는 목록 한정자가 검색되었습니다. '{0}'. 올바른 목록 한정자는 Add, Remove, Replace입니다. + + + 개체가 지원되는 컬렉션 형식이 아니므로 업데이트를 적용할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PSStyleStrings.ko.resx b/src/System.Management.Automation/resources/ko/PSStyleStrings.ko.resx new file mode 100644 index 00000000000..608632fa194 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PSStyleStrings.ko.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 지정한 문자열에는 인쇄 가능한 콘텐츠가 포함되어 있습니다. ANSI 이스케이프 시퀀스만 포함해야 합니다. {0} + + + 진행률 렌더링이 올바르게 표시되려면 MaxWidth는 최소 18이어야 합니다. + + + 확장명을 추가하거나 제거할 때는 확장명의 시작에 마침표가 있어야 합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ParameterBinderStrings.ko.resx b/src/System.Management.Automation/resources/ko/ParameterBinderStrings.ko.resx new file mode 100644 index 00000000000..82e8a51d726 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ParameterBinderStrings.ko.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 매개 변수 이름 '{1}'과(와) 일치하는 매개 변수를 찾을 수 없습니다. + + + 인수 '{1}'을(를) 받을 수 있는 위치 매개 변수를 찾을 수 없습니다. + + + 매개 변수 '{1}'에 대한 인수가 없습니다. '{2}' 형식의 매개 변수를 지정한 다음 다시 시도하세요. + + + 매개 변수 이름 '{1}'이(가) 모호해서 매개 변수를 처리할 수 없습니다. 가능한 일치 항목은 다음과 같습니다.{6} + + + '{6}'을(를) '{1}' 매개 변수에 필요한 형식 '{2}'(으)로 변환할 수 없습니다. {7} + + + 매개 변수 '{1}'을(를) 바인딩할 수 없습니다. {6} + + + 위치 매개 변수 '{1}'을(를) 바인딩할 수 없습니다. + + + 이름이 지정되지 않았으므로 위치 매개 변수를 바인딩할 수 없습니다. + + + 매개 변수 집합은 명명된 지정 매개 변수를 사용하여 확인할 수 없습니다. 함께 사용할 수 없는 매개 변수가 있거나 제공된 매개 변수 수가 부족합니다. + + + 하나 이상의 필수 매개 변수({1})가 없어서 명령을 처리할 수 없습니다. + + + 매개 변수 집합 '{6}'에는 매개 변수 '{1}'을(를) 지정할 수 없습니다. + + + 매개 변수 '{1}'이(가) 두 번 이상 지정되었으므로 매개 변수를 바인딩할 수 없습니다. 여러 값을 받을 수 있는 매개 변수에 여러 값을 제공하려면 배열 구문을 사용하세요. 예를 들어 "-parameter value1,value2,value3"입니다. + + + 인수가 스크립트 블록으로 지정되어 있고 입력이 없어서 매개 변수 '{1}'을(를) 평가할 수 없습니다. 입력 없이는 스크립트 블록을 평가할 수 없습니다. + + + 매개 변수 '{1}'의 스크립트 블록에 대한 입력이 실패했습니다. {6} + + + 인수 입력에서 출력이 생성되지 않아 매개 변수 '{1}'을(를) 평가할 수 없습니다. + + + 명령이 파이프라인 입력을 받지 않거나 입력과 해당 속성이 파이프라인 입력을 받는 어떤 매개 변수와도 일치하지 않으므로 입력 개체를 명령의 어떤 매개 변수에도 바인딩할 수 없습니다. + + + 입력 개체에 모든 필수 매개 변수를 바인딩하는 데 필요한 정보가 없어서 바인딩할 수 없습니다. {6} + + + 매개 변수 '{1}'의 기본값을 검색할 수 없어서 파이프라인 입력을 처리할 수 없습니다. {6} + + + cmdlet에 대한 동적 매개 변수를 검색할 수 없습니다. {6} + + + 다음 매개 변수에 대한 값을 제공하세요. + + + 명령 파이프라인 위치 {1}에서 cmdlet {0} + + + '{1}' 매개 변수에서 인수 변환을 처리할 수 없습니다. {6} + + + {6} + + + 매개 변수 '{1}'에 대한 인수의 유효성을 검사할 수 없습니다. {6} + + + 매개 변수 '{1}'을(를) 대상에 바인딩할 수 없습니다. {6} + + + 매개 변수 '{1}'이(가) null이어서 인수를 바인딩할 수 없습니다. + + + 매개 변수 '{1}'에 대한 인수가 빈 문자열이어서 바인딩할 수 없습니다. + + + 매개 변수 '{1}'에 대한 인수가 빈 컬렉션이어서 바인딩할 수 없습니다. + + + 매개 변수 '{1}'에 대한 인수가 빈 배열이어서 바인딩할 수 없습니다. + + + 명령을 처리할 수 없습니다. 매개 변수 '{0}'이(가) 여러 번 정의되었습니다. + + + 매개 변수 '{1}'이(가) '{2}' 형식이고 Add() 메서드를 식별할 수 없거나 Add() 메서드가 여러 개 있어서 cmdlet {0}을(를) 바인딩할 수 없습니다. {6} + + + 런타임 정의 매개 변수 '{1}'이(가) 키 '{6}'(으)로 RuntimeDefinedParameterDictionary에 추가되었으므로 cmdlet {0}을(를) 바인딩할 수 없습니다. 키는 RuntimeDefinedParameter.Name과 같아야 합니다. + + + 인수의 PSTypeNames가 매개 변수 '{6}'에 필요한 PSTypeName과 일치하지 않아서 인수를 매개 변수 '{1}'에 바인딩할 수 없습니다. + + + {0} 이름 또는 별칭과 일치하는 매개 변수에 대해 $PSDefaultParameterValues에 여러 기본값이 정의되어 있습니다. 이 기본값은 무시되었습니다. + + + 이 cmdlet의 $PSDefaultParameterValues에 정의된 다음 이름 또는 별칭이 여러 매개 변수에 해당합니다. {0} 기본값이 무시되었습니다. + + + {6} 이 오류는 기본 매개 변수 바인딩을 적용해서 발생했을 수 있습니다. $PSDefaultParameterValues에서 $PSDefaultParameterValues["Disabled"]를 $true로 설정한 다음 다시 시도해 기본 매개 변수 바인딩을 사용하지 않도록 설정할 수 있습니다. 오류가 발생했을 때 이 cmdlet에 성공적으로 바인딩된 기본 매개 변수는 다음과 같습니다.{7} + + + {6} 이 오류는 기본 매개 변수 바인딩을 적용해서 발생했을 수 있습니다. $PSDefaultParameterValues에서 $PSDefaultParameterValues["Disabled"]를 $true로 설정해 기본 매개 변수 바인딩을 사용하지 않도록 설정한 다음 다시 시도하세요. 오류가 발생했을 때 이 cmdlet에 성공적으로 바인딩된 기본 매개 변수는 다음과 같습니다.{7} + + + 매개 변수 '{1}'에 기본값 '{0}'을(를) 바인딩하지 못했습니다. {2} + + + 키 '{0}'의 형식이 올바르지 않습니다. 올바른 형식에 대한 자세한 내용은 about_Parameters_Default_Values at https://go.microsoft.com/fwlink/?LinkId=228266을 참조하세요. + + + 키 '{0}'의 형식이 올바르지 않습니다. 올바른 형식에 대한 자세한 내용은 about_Parameters_Default_Values at https://go.microsoft.com/fwlink/?LinkId=228266을 참조하세요. + + + 매개 변수 '{0}'은(는) 더 이상 사용되지 않습니다. {1} + + + '{1}' 형식의 키 '{0}'은(는) 문자열 값이 아닙니다. DefaultParameterDictionary는 문자열 값 키만 허용합니다. + + + 키 '{0}'은(는) 이미 사전에 추가되어 있습니다. + + + 메서드 또는 속성 호출은 허용되지 않습니다. + + + 신뢰할 수 없는 스크립트에 대한 제한된 언어 모드에서는 '{1}' 형식의 메서드 또는 속성 '{0}' 호출을 허용하지 않습니다. + + + 형식 만들기가 허용되지 않음 + + + 신뢰할 수 없는 스크립트에 대한 제한된 언어 모드에서는 매개 변수 바인딩 중에 '{0}' 형식을 만들 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ParserStrings.ko.resx b/src/System.Management.Automation/resources/ko/ParserStrings.ko.resx new file mode 100644 index 00000000000..5cc21561340 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ParserStrings.ko.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + '{0}' 어셈블리를 로드할 수 없습니다. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PathUtilsStrings.ko.resx b/src/System.Management.Automation/resources/ko/PathUtilsStrings.ko.resx new file mode 100644 index 00000000000..999fb3c52d0 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PathUtilsStrings.ko.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 'UTF-7' 인코딩은 더 이상 사용되지 않습니다. UTF-8을 사용하세요. + + + 파일 {0}이(가) 이미 존재하며 {1}이(가) 지정되었습니다. + + + 현재 공급자({0})는 파일을 열 수 없으므로 파일을 열 수 없습니다. + + + 경로가 두 개 이상의 파일로 확인되어 작업을 수행할 수 없습니다. 이 명령은 여러 파일에 사용할 수 없습니다. + + + 와일드카드 경로 {0}이(가) 파일로 확인되지 않아 작업을 수행할 수 없습니다. + + + 알 수 없는 인코딩 {0}입니다. 유효한 값은 {1}입니다. + + + '{0}' 디렉터리가 이미 있습니다. 디렉터리와 디렉터리 안의 파일을 덮어쓰려면 -Force 매개 변수를 사용하세요. + + + 사용자 모듈 경로가 없으므로 제공된 모듈 이름 '{0}'에 대한 모듈 폴더를 만들 수 없습니다. + + + 다음과 같은 이유로 모듈 {0}을(를) 만들 수 없습니다. {1}. -OutputModule 매개 변수에 다른 인수를 사용한 다음 다시 시도하세요. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + 호환되지 않는 버전의 {0} cmdlet을 사용해 모듈을 생성했으므로 모듈을 로드할 수 없습니다. 현재 세션에서 {0} cmdlet을 사용해 모듈을 생성한 다음 모듈을 다시 로드하세요. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PipelineStrings.ko.resx b/src/System.Management.Automation/resources/ko/PipelineStrings.ko.resx new file mode 100644 index 00000000000..ac367d67132 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PipelineStrings.ko.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 다른 파이프라인에서 이미 이 cmdlet instance를 사용하고 있으므로 처리할 수 없습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 파이프라인이 시작된 상태이므로 작업을 수행할 수 없습니다. 파이프라인을 중지한 다음 작업을 다시 시도하세요. + + + Stop 정책에 의해 cmdlet 실행이 차단되었으므로 cmdlet을 더 이상 실행할 수 없습니다. + + + 파이프라인의 첫 번째 cmdlet이 앞선 cmdlet의 결과에서 입력을 읽으려고 해서 파이프라인을 실행할 수 없습니다. 첫 번째 cmdlet을 수정하거나, 제거하거나, 첫 번째 cmdlet에 필요한 출력을 제공하는 cmdlet을 파이프라인에 추가한 다음 다시 실행해 보세요. + + + cmdlet 번호를 처리할 수 없습니다. ReadFromCommand 함수에는 이미 파이프라인에 추가된 cmdlet의 ID를 지정해야 합니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 다른 cmdlet이 이미 해당 출력을 읽고 있으므로 ReadFromCommand 및 ReadErrorQueue 함수의 출력을 읽을 수 없습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + 명령이 없어서 파이프라인을 실행할 수 없습니다. 파이프라인에 명령을 하나 이상 추가한 다음 다시 실행하세요. + + + 파이프라인 작업이 아직 시작되지 않았으므로 완료할 수 없습니다. 스테퍼블 파이프라인에서 End()를 호출하기 전에 Begin() 메서드를 호출해야 합니다. + + + WriteObject 및 WriteError 메서드는 BeginProcessing, ProcessRecord 및 EndProcessing 메서드의 재정의 외부에서 호출할 수 없으며 동일한 스레드 내에서만 호출할 수 있습니다. cmdlet이 이러한 호출을 올바르게 수행하는지 확인하거나 Microsoft 고객 지원 서비스에 문의하세요. + + + cmdlet이 ThrowTerminatingError를 호출한 후 예외를 throw했습니다. +첫 번째 예외는 "{0}"이며 스택 추적은 "{1}"입니다. +두 번째 예외는 "{2}"이며 스택 추적은 "{3}"입니다. + + + 파이프라인을 닫은 후에는 WriteObject 및 WriteError 메서드를 호출할 수 없습니다. Microsoft 고객 지원 서비스에 문의하세요. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + 파이프라인을 만드는 동안 오류가 발생했습니다. + + + 이 파이프라인은 연결 끊기 연결 의미 체계를 지원하지 않습니다. + + + 이 파이프라인은 연결 끊김 상태가 아니므로 연결할 수 없습니다. + + + runspace 개체에 연결된 원격 명령이 null입니다. 지정된 원격 명령이 없으므로 연결이 끊긴 RemotePipeline 개체를 만들 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/PowerShellStrings.ko.resx b/src/System.Management.Automation/resources/ko/PowerShellStrings.ko.resx new file mode 100644 index 00000000000..3be15a3bac7 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/PowerShellStrings.ko.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 + + + 현재 PowerShell 인스턴스의 상태는 이 작업에 유효하지 않습니다. + + + 명령이 이미 시작되었으므로 작업을 수행할 수 없습니다. 명령이 완료될 때까지 기다리거나 중지한 다음 다시 시도하세요. + + + 명령이 지정되지 않았습니다. + + + PowerShell 인스턴스가 중첩된 PowerShell 인스턴스를 만들 수 있는 올바른 상태가 아닙니다. 중첩된 PowerShell 인스턴스는 실행 중인 PowerShell 인스턴스에서만 만들 수 있습니다. + + + runspace가 '{0}' 상태가 아니므로 작업을 수행할 수 없습니다. runspace의 현재 상태는 '{1}'입니다. + + + 중첩된 PowerShell 인스턴스는 비동기적으로 호출할 수 없습니다. Invoke 메서드를 사용하세요. + + + {0} 개체는 이 PowerShell 인스턴스에서 {1}을(를) 호출하여 만들어지지 않았습니다. + + + runspace가 스레드를 다시 사용하도록 설정된 경우 호출 설정의 아파트 상태는 runspace와 일치해야 합니다. + + + runspace가 현재 스레드를 사용하도록 설정된 경우 호출 설정의 아파트 상태는 현재 스레드의 아파트 상태와 일치해야 합니다. + + + 매개 변수를 추가하려면 명령이 필요합니다. 매개 변수를 추가하기 전에 PowerShell 인스턴스에 명령을 추가하세요. + + + 사전의 키는 문자열이어야 합니다. + + + 이 스레드에서 명령을 실행할 수 있는 Runspace가 없습니다. System.Management.Automation.Runspaces.Runspace 형식의 DefaultRunspace 속성에서 Runspace를 제공할 수 있습니다. 호출하려는 명령은 다음과 같습니다. {0} + + + 이 PowerShell 개체는 원격 runspace 또는 runspace 풀과 연결되어 있지 않으므로 연결할 수 없습니다. + + + 실행 중인 명령의 연결이 끊겼지만 원격 서버에서는 아직 실행 중입니다. 명령 작업 상태와 출력 데이터를 가져오려면 다시 연결하세요. + + + 현재 PowerShell 세션이 연결 끊김 상태이므로 작업을 수행할 수 없습니다. 이 PowerShell 세션에 연결한 다음 명령이 완료될 때까지 기다리거나 명령을 중지하세요. + + + 현재 PowerShell 세션이 연결 끊김 상태이므로 작업을 수행할 수 없습니다. 이 PowerShell 세션에 연결한 후 다시 시도하세요. + + + 원격 명령에 대한 연결을 시도했지만 실패했습니다. + + + 명령이 현재 중지 중이므로 작업을 수행할 수 없습니다. 명령이 중지될 때까지 기다린 다음 다시 시도하세요. + + + 이 스레드에서 명령을 실행할 수 있는 Runspace가 없습니다. System.Management.Automation.Runspaces.Runspace 형식의 DefaultRunspace 속성에서 Runspace를 제공할 수 있습니다. 현재 PowerShell 인스턴스에 호출할 명령이 없습니다. + + + 현재 사용할 수 있는 runspace가 없으므로 현재 runspace를 사용하는 PowerShell 개체를 만들 수 없습니다. 초기 세션 상태로 만들어진 경우처럼 현재 runspace가 시작 중일 수 있습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ProgressRecordStrings.ko.resx b/src/System.Management.Automation/resources/ko/ProgressRecordStrings.ko.resx new file mode 100644 index 00000000000..c5af96fd97a --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ProgressRecordStrings.ko.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + {0} 값은 null이거나 비어 있을 수 없으므로 인수를 처리할 수 없습니다. + + + {0}은(는) 100보다 클 수 없으므로 백분율을 설정할 수 없습니다. + + + ParentActivityId는 ActivityId와 같을 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ProviderBaseSecurity.ko.resx b/src/System.Management.Automation/resources/ko/ProviderBaseSecurity.ko.resx new file mode 100644 index 00000000000..96ad653bccf --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ProviderBaseSecurity.ko.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 + + + ISecurityDescriptorCmdletProvider 인터페이스가 이 공급자에서 지원되지 않으므로 인터페이스를 사용할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/ProxyCommandStrings.ko.resx b/src/System.Management.Automation/resources/ko/ProxyCommandStrings.ko.resx new file mode 100644 index 00000000000..c5b40b475f0 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/ProxyCommandStrings.ko.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 + + + 'help' 매개 변수를 'get-help' 명령으로 만든 올바른 HelpInfo 개체로 인식할 수 없습니다. + + + CommandMetadata에 이름이 없으므로 프록시 명령을 생성할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/RegistryProviderStrings.ko.resx b/src/System.Management.Automation/resources/ko/RegistryProviderStrings.ko.resx new file mode 100644 index 00000000000..37920ec66a8 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/RegistryProviderStrings.ko.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + 항목 지우기 + + + 항목: {0} + + + 새 항목 + + + 항목: {0} + + + 키 제거 + + + 항목: {0} + + + 키 복사 + + + 항목: {0} 대상: {1} + + + 항목 이름 바꾸기 + + + 항목: {0} NewName: {1} + + + 항목 이동 + + + 항목: {0} 대상: {1} + + + 속성 설정 + + + 항목: {0} 속성: {1} + + + 속성 지우기 + + + 항목: {0} 속성: {1} + + + 새 속성 + + + 항목: {0} 속성: {1} + + + 속성 제거 + + + 항목: {0} 속성: {1} + + + 속성 이름을 바꿉니다. + + + 항목: {0} SourceProperty: {1} DestinationProperty: {2} + + + 속성 복사 + + + 항목: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 속성 이동 + + + 항목: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 작업이 완료되지 않았습니다. 제공된 위치에서는 이 작업을 허용하지 않습니다. + + + 원본 위치에서는 이 작업을 허용하지 않습니다. + + + 대상 위치에서는 이 작업을 허용하지 않습니다. + + + 로컬 컴퓨터에 대한 구성 설정 + + + 현재 사용자에 대한 소프트웨어 설정 + + + 이 경로에 이미 키가 있습니다. + + + 대상 경로가 원본 경로의 하위 경로이므로 작업을 수행할 수 없습니다. + + + 속성이 이미 있습니다. + + + {1} 경로에 속성 {0}이(가) 없습니다. + + + 지정한 경로에 있는 레지스트리 키가 없습니다. + + + 'Type' 매개 변수를 바인딩할 수 없습니다. "{0}"을(를) "{1}"(으)로 변환할 수 없습니다. 가능한 열거형 값은 "String, ExpandString, Binary, DWord, MultiString, QWord, Unknown"입니다. + + + 키 {0}이(가) 만들어졌지만 기본값을 설정할 수 없습니다. + + + 지정한 루트로 드라이브를 만들 수 없습니다. 루트 경로가 없습니다. + + + 같은 컨테이너에 같은 이름의 항목이 이미 있으므로 이름을 바꿀 수 없습니다. + + + 레지스트리 키 이름은 유효한 기본 키 이름으로 시작해야 합니다. + + + 하위 키 인수가 잘못되었습니다. + + + 하위 키가 존재하지 않으므로 하위 키 트리를 삭제할 수 없습니다. + + + 해당 이름의 값이 없습니다. + + + 열거형 값 {0}이(가) 올바르지 않습니다. + + + 값 인수를 지정해야 합니다. + + + 이름 인수를 지정해야 합니다. + + + 지정한 RegistryValueKind는 유효하지 않은 값입니다. + + + RegistryKey.SetValue는 null 문자열 참조를 포함하는 String[]을 허용하지 않습니다. + + + 레지스트리 하위 키는 255자 이하여야 합니다. + + + 비어 있지 않은 하위 키 이름을 지정해야 합니다. + + + 값 개체의 형식이 지정한 RegistryValueKind와 일치하지 않거나 개체를 올바르게 변환할 수 없습니다. + + + RegistryKey.SetValue는 '{0}' 형식의 배열을 지원하지 않습니다. Byte[]와 String[]만 지원됩니다. + + + 지정한 레지스트리 키가 없습니다. + + + 지정된 값 이름의 길이가 최대 16383자를 초과합니다. + + + 지정한 값 데이터의 크기가 최대 1MB를 초과합니다. + + + 지정한 레지스트리 하위 키가 없습니다. + + + 지정한 RegistryKeyPermissionCheck 값이 올바르지 않습니다. + + + 레지스트리 키에 하위 키가 있습니다. 이 메서드에서는 재귀적 제거를 지원하지 않습니다. + + + Transaction.Current 또는 지정한 트랜잭션이 없으면 KTM 핸들을 만들 수 없습니다. + + + 지정한 트랜잭션 또는 Transaction.Current는 이 TransactedRegistryKey를 만들거나 연 데 사용한 트랜잭션과 일치해야 합니다. + + + 이 TransactedRegistryKey 개체는 미리 정의된 키이므로 트랜잭션과 연결되어 있지 않습니다. + + + 요청한 레지스트리 액세스가 허용되지 않습니다. + + + 레지스트리 키 '{0}'에 대한 액세스가 거부되었습니다. + + + 레지스트리 키에 쓸 수 없습니다. + + + 닫힌 레지스트리 키에 액세스할 수 없습니다. + + + 알 수 없는 오류 {0}이(가) 발생했습니다. + + + 이 플랫폼에서는 레지스트리 트랜잭션을 지원하지 않습니다. + + + 지정한 핸들이 잘못되었습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/RemotingErrorIdStrings.ko.resx b/src/System.Management.Automation/resources/ko/RemotingErrorIdStrings.ko.resx new file mode 100644 index 00000000000..e7f04755314 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/RemotingErrorIdStrings.ko.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + FilePath 매개 변수에는 와일드카드 문자를 사용할 수 없습니다. 와일드카드 문자가 없는 경로를 지정하세요. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + 세션 옵션 {0}에는 {1} 값을 지정해야 합니다. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + 원격 컴퓨터에 연결할 때 허용할 최대 WS-Man URI 리디렉션 수 + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + WriteEvents 매개 변수는 Wait 매개 변수와 함께만 사용할 수 있습니다. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + WinPE(Windows 사전 설치 환경)에서는 PowerShell 원격 처리가 지원되지 않습니다. + + + WinRM 서비스를 다시 시작하기 전에는 {0}이(가) 적용한 변경 내용이 적용되지 않습니다. + + + {0}이(가) 이름을 사용하는 구성이 최근에 등록 취소된 경우 WinRM 서비스를 다시 시작해야 할 수 있습니다. 일부 시스템 데이터 구조가 아직 캐시되어 있을 수 있기 때문입니다. 이 경우 WinRM을 다시 시작해야 할 수 있습니다. +Microsoft.PowerShell과 Register-PSSessionConfiguration cmdlet으로 만든 세션 구성 같은 PowerShell 세션 구성에 연결된 모든 WinRM 세션의 연결이 끊어집니다. + + + 원격 세션에서 실행 중이며 강제 옵션을 선택했습니다. 그러면 WinRM 서비스가 다시 시작될 수 있습니다. WinRM 서비스가 다시 시작되면 이 원격 세션은 종료됩니다. 계속하려면 새 세션을 만들어야 합니다 + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + -WriteJobInResults 매개 변수는 -Wait 매개 변수와 함께만 사용할 수 있습니다. + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + 제공된 입력 스트림이 올바르지 않습니다. 입력 스트림으로는 {0}만 지원됩니다. + + + 제공된 출력 스트림 집합이 올바르지 않습니다. 출력 스트림으로는 {0}만 지원됩니다. + + + 제공된 WSMAN_SENDER_DETAILS가 올바르지 않습니다. null WSMAN_SENDER_DETAILS는 처리할 수 없습니다. + + + 제공한 셸 컨텍스트가 올바르지 않습니다. + + + {0} + + + 플러그 인 메서드 {0}에 대한 {1}에는 NULL 값이 허용되지 않습니다. + + + 입력 스트림 및 출력 스트림 집합에는 NULL 값이 허용되지 않습니다. {0}과(와) {1}은(는) 지원되는 입력 및 출력 스트림입니다. + + + 플러그 인 메서드 {0}에 대한 {1}에는 NULL 값이 허용되지 않습니다. + + + 플러그 인 메서드 {0}에 대한 {1}에는 NULL 값이 허용되지 않습니다. + + + PowerShell 플러그 인 작업을 종료하는 중입니다. 호스팅 서비스 또는 응용 프로그램이 종료되는 경우 이 문제가 발생할 수 있습니다. + + + PowerShell 플러그 인이 {0} 옵션을 인식하지 못합니다. 클라이언트가 PowerShell의 빌드 {1}과(와) 프로토콜 버전 {2}과(와) 호환되는지 확인하세요. + + + 이름이 {0}인 옵션이 클라이언트에 있어야 합니다. 클라이언트가 PowerShell의 빌드 {1}과(와) 프로토콜 버전 {2}과(와) 호환되는지 확인하세요. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">PowerShell 플러그 인이 클라이언트에서 요청한 프로토콜 버전 {2}을(를) 지원하지 않습니다.</PSProtocolVersionError> + + + PowerShell 플러그 인에서 WSMan 서비스에 컨텍스트를 보고하는 동안 치명적인 오류가 발생했습니다. + + + 관리형 서버 세션을 만들 수 없습니다. + + + PowerShell 플러그 인에서 종료 알림용 대기 핸들을 등록하는 동안 치명적인 오류가 발생했습니다. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + "{0}" 실행 파일을 찾을 수 없습니다. WOW64 기능이 설치되어 있는지 확인하세요. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + 이 컴퓨터에서 Windows PowerShell을 찾을 수 없으므로 Windows PowerShell 프로세스를 만들 수 없습니다. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/RunspaceInit.ko.resx b/src/System.Management.Automation/resources/ko/RunspaceInit.ko.resx new file mode 100644 index 00000000000..c2e8db69782 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/RunspaceInit.ko.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 + + + 활성화된 실험적 기능 이름을 저장할 변수 + + + 현재 runspace의 호스트 애플리케이션의 상위 폴더 + + + 현재 사용자 프로필이 들어 있는 폴더 + + + 현재 runspace 호스트에 대한 참조 + + + cmdlet에서 사용할 수 있는 실행 개체 + + + 현재 PowerShell 세션의 버전 정보 + + + 현재 프로세스 ID + + + 마지막 명령 상태 + + + 부모 프로세스 ID + + + ShellID는 현재 셸을 식별합니다. #Requires에서 사용됩니다. + + + 현재 콘솔 파일 이름 + + + 텍스트를 네이티브 실행 파일로 파이프할 때 사용하는 텍스트 인코딩 + + + 네이티브 실행 파일에서 출력 텍스트를 읽을 때 사용하는 텍스트 인코딩 + + + 텍스트 렌더링 방식을 제어하는 구성 + + + 전자 메일 서버의 이름을 저장하는 변수입니다. Send-MailMessage cmdlet에서 HostName 매개 변수 대신 사용할 수 있습니다. + + + 확인을 요청해야 하는 시기를 지정합니다. 작업의 ConfirmImpact가 $ConfirmPreference보다 크거나 같으면 확인을 요청합니다. $ConfirmPreference가 None이면 Confirm을 지정한 경우에만 작업을 확인합니다. + + + 디버그 메시지가 전달될 때 수행할 작업 지정 + + + 오류 메시지가 전달될 때 수행할 작업 지정 + + + 진행률 레코드가 전달될 때 수행할 작업 지정 + + + Verbose 정보 메시지가 전달될 때 수행할 작업 지정 + + + 경고 메시지가 전달될 때 수행할 작업을 지정합니다. + + + 명령이 정보 스트림에 항목을 생성할 때 수행할 작업 지정 + + + 오류를 표시할 때 사용할 보기 모드를 지정합니다. + + + 현재 중첩 수준에 표시할 프롬프트 유형 지정 + + + true면 $ErrorActionPreference가 네이티브 실행 파일에도 적용됩니다. 따라서 0이 아닌 종료 코드는 오류 동작 설정에 따라 cmdlet 스타일 오류를 생성합니다. + + + true이면 WhatIf가 모든 명령에 대해 사용하도록 설정된 것으로 간주됩니다. + + + 네이티브 실행 파일에 인수를 전달하는 방식을 지정합니다. + + + IEnumerable 개체의 서식을 지정할 때 열거 제한 지정 + + + 스택 추적을 포함하여 오류 표시 + + + 내부 예외를 포함하여 오류 표시 + + + 출처를 포함하여 오류 표시 + + + 오류 클래스에 대한 설명과 함께 오류를 표시합니다. + + + 현재 PowerShell 세션의 문화권 + + + 현재 PowerShell 세션의 UI 문화권 + + + 모든 기본 <cmdlet:parameter, value> 쌍을 저장할 변수 + + + 계속하려면 Enter 키를 누르세요... + + + 현재 PowerShell 세션의 에디션 정보 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/RunspacePoolStrings.ko.resx b/src/System.Management.Automation/resources/ko/RunspacePoolStrings.ko.resx new file mode 100644 index 00000000000..f03c38dfba4 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/RunspacePoolStrings.ko.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 최대 풀 크기는 1보다 작을 수 없습니다. + + + 최소 풀 크기는 1보다 작을 수 없습니다. + + + 최소 풀 크기는 최대 풀 크기보다 클 수 없습니다. + + + 실행 공간 풀의 상태가 이 작업에 유효하지 않습니다. + + + 실행 공간 풀이 '{0}' 상태가 아니므로 작업을 수행할 수 없습니다. 현재 상태는 '{1}'입니다. + + + 실행 공간 풀이 'BeforeOpen' 상태가 아니므로 열 수 없습니다. 현재 상태는 '{0}'입니다. + + + {0} 개체가 현재 RunspacePool 인스턴스에서 {1}을(를) 호출하여 만들어지지 않았습니다. + + + 실행 공간이 현재 풀에 속해 있지 않으므로 현재 풀에 실행 공간을 해제할 수 없습니다. + + + 실행 공간 풀이 열린 후에는 이 속성을 변경할 수 없습니다. + + + 이 실행 공간은 연결 끊기 및 연결 작업을 지원하지 않습니다. + + + 실행 공간 풀이 연결 끊김 상태이므로 작업을 수행할 수 없습니다. + + + 서버에서 연결 끊기 작업이 지원되지 않습니다. 원격 실행 공간 풀 연결 끊기를 지원하려면 서버에서 PowerShell 3.0 이상을 실행해야 합니다. + + + 이 실행 공간 풀 {0}은(는) 원격 서버에서 실행 중인 명령에 대해 연결이 끊어진 PowerShell 개체를 제공하도록 구성되어 있지 않습니다. RunspacePool 클래스의 GetRunspacePools() 정적 메서드를 사용하여 서버를 쿼리하고 이렇게 하도록 구성된 실행 공간 풀 개체를 반환하세요. + + + 해당 서버 쪽 실행 공간 풀이 다른 클라이언트에 연결되어 있으므로 이 실행 공간 풀을 연결할 수 없습니다. + + + 서버에서 ResetRunspaceState가 지원되지 않습니다. 서버에서 PowerShell 5.0 이상을 실행해야 합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/RunspaceStrings.ko.resx b/src/System.Management.Automation/resources/ko/RunspaceStrings.ko.resx new file mode 100644 index 00000000000..8eadcedbcb0 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/RunspaceStrings.ko.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 이 작업에는 runspace 상태가 유효하지 않습니다. + + + runspace가 BeforeOpen 상태가 아니므로 runspace를 열 수 없습니다. runspace의 현재 상태는 '{0}'입니다. + + + runspace가 Opened 상태가 아니므로 작업을 수행할 수 없습니다. runspace의 현재 상태는 '{0}'입니다. + + + Runspace가 열림 상태가 아니므로 파이프라인을 호출할 수 없습니다. runspace의 현재 상태는 '{0}'입니다. + + + 이 작업에는 파이프라인 상태가 유효하지 않습니다. + + + 파이프라인이 이미 호출되었으므로 호출할 수 없습니다. + + + 매개 변수의 유효한 값은 PipelineResultTypes.Output입니다. + + + 파이프라인에 명령이 포함되어 있지 않습니다. + + + 파이프라인이 이미 실행 중이므로 실행할 수 없습니다. 파이프라인은 동시에 실행할 수 없습니다. + + + 중첩된 파이프라인은 비동기적으로 호출할 수 없습니다. Invoke 메서드를 사용하세요. + + + 중첩된 파이프라인은 실행 중인 파이프라인 안에서만 실행해야 합니다. + + + SessionStateProxy 메서드 호출이 진행 중인 동안에는 runspace를 닫을 수 없습니다. + + + SessionStateProxy 메서드 호출이 진행 중인 동안에는 파이프라인을 호출할 수 없습니다. + + + SessionStateProxy 메서드 호출이 진행 중입니다. 동시에 여러 SessionStateProxy 메서드를 호출할 수 없습니다. + + + 파이프라인이 이미 실행 중입니다. 동시에 여러 SessionStateProxy 메서드를 호출할 수 없습니다. + + + 이 속성은 runspace를 연 후에는 변경할 수 없습니다. + + + 이 runspace를 만드는 데 사용된 InitialSessionState 개체에 지정된 모듈 '{0}'을(를) 처리하는 동안 하나 이상의 오류가 발생했습니다. 전체 오류 목록은 ErrorRecords 속성을 참조하세요. 첫 번째 오류는 다음과 같습니다: {1} + + + 아파트 상태가 MTA(다중 스레드 아파트)이고, 현재 옵션이 UseNewThread 또는 UseCurrentThread이며, 새 값이 ReuseThread인 경우에만 스레드 옵션을 변경할 수 있습니다. + + + {0}은(는) 언어 모드가 {1} 또는 {2}일 때는 false일 수 없습니다. + + + 로컬 전용 runspace는 연결을 끊을 수 없습니다. + + + 로컬 runspace에서는 연결 작업이 지원되지 않습니다. + + + 세션이 사용 중입니다. 사용할 수 있게 되면 바로 세션에 연결됩니다. Enter-PSSession 명령을 취소하려면 Ctrl-C를 누르세요. + + + 명령을 완료할 수 없습니다. 이 세션 구성에서는 스크립트 호출이 지원되지 않습니다. 세션 구성이 no-language 모드일 때 이 문제가 발생할 수 있습니다. + + + 로컬 runspace에서는 연결 끊기 및 연결 작업을 사용할 수 없습니다. + + + runspace가 Opened 상태가 아니므로 파이프라인을 연결할 수 없습니다. runspace의 현재 상태는 '{0}'입니다. + + + RemoteRunspace를 만들 수 없습니다. 제공된 RunspacePool 개체가 올바르지 않습니다. + + + 이 runspace와 연결된 연결 끊긴 명령이 없습니다. + + + 원격 컴퓨터에서는 연결 끊기 작업이 지원되지 않습니다. 연결 끊기를 지원하려면 원격 컴퓨터에서 Windows PowerShell 3.0 이상을 실행하고 WSMan 전송을 사용해야 합니다. + + + 세션이 연결 끊김 상태가 아니거나 연결할 수 없으므로 PSSession에 연결할 수 없습니다. + + + 매개 변수 값은 PipelineResultTypes.None 또는 PipelineResultTypes.Output일 수 없습니다. + + + 매개 변수의 유효한 값은 PipelineResultTypes.Output 또는 PipelineResultTypes.Null입니다. + + + 디버그 스트림 리디렉션은 대상 원격 컴퓨터에서 지원되지 않습니다. + + + 자세한 정보 스트림 리디렉션은 대상 원격 컴퓨터에서 지원되지 않습니다. + + + 경고 스트림 리디렉션은 대상 원격 컴퓨터에서 지원되지 않습니다. + + + 정보 스트림 리디렉션은 대상 원격 컴퓨터에서 지원되지 않습니다. + + + 명령이나 스크립트를 실행 중인 세션에 들어왔습니다. 출력은 작업 "{0}"(으)로 라우팅되므로 콘솔에 출력이 표시되지 않습니다. 실행 중인 명령이 끝날 때까지 기다리거나, 명령을 취소하고 Ctrl-C를 눌러 입력 프롬프트를 가져올 수 있습니다. + + + + 명령 또는 스크립트를 실행 중인 세션에 들어왔으며 출력은 콘솔에 표시됩니다. 실행 중인 명령이 끝날 때까지 기다리거나 Ctrl-C를 눌러 취소한 다음 입력 프롬프트를 받을 수 있습니다. + + + + 실행 중인 명령 또는 스크립트 내부의 디버그 중단점에서 현재 중지된 세션에 들어왔습니다. PowerShell 명령줄 디버거를 사용하여 디버깅을 계속하세요. + + + + DefaultRunspace는 LocalRunspace여야 합니다. + + + 정적 PrimaryRunspace 속성은 한 번만 설정할 수 있으며, 이미 설정되어 있습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/SecuritySupportStrings.ko.resx b/src/System.Management.Automation/resources/ko/SecuritySupportStrings.ko.resx new file mode 100644 index 00000000000..2061817dd6f --- /dev/null +++ b/src/System.Management.Automation/resources/ko/SecuritySupportStrings.ko.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 인증서를 로드할 수 없습니다. '{0}'은(는) 파일 시스템 경로로 확인되어야 합니다. + + + 인증서 '{0}'은(는) 암호화에 사용할 수 없습니다. 암호화 인증서에는 데이터 암호화 또는 키 암호화 키 사용이 포함되어야 하며, 문서 암호화 확장된 키 사용({1})도 포함되어야 합니다. + + + 인증서를 로드할 수 없습니다. 식별자 '{0}'이(가) 여러 인증서와 일치합니다. 여러 수신자에게 암호화하려면 여러 인증서와 일치하는 와일드카드 대신 '{1}' 매개 변수에 여러 개의 특정 값을 제공하세요. + + + 암호화 인증서를 로드할 수 없습니다. 인증서 설정 '{0}'은(는) 유효한 base-64 인코딩 인증서를 나타내지 않으며, 파일, 디렉터리, 지문 또는 주체 이름으로 된 유효한 인증서도 나타내지 않습니다. + + + 경고: 인증서 '{0}'에 개인 키가 포함되어 있습니다. 암호화에 사용되는 보호된 이벤트 로깅 인증서에는 공개 키만 포함되어야 합니다. + + + 오류: 이벤트 로그 메시지 '{0}'을(를) 보호할 수 없음: {1} + + + 오류: 인증서를 찾거나 사용할 수 없음: {0} + + + 보안 문자열을 암호화할 세션 키를 사용할 수 없습니다. + + + 버퍼 오프셋이 잘못되었습니다. + + + 공개 키 데이터가 잘못되었습니다. + + + 공개 키를 가져올 수 없습니다. + + + 세션 키 데이터가 잘못되었습니다. + + + 스크립트 파일 '{0}'은(는) 시스템 정책에 의해 실행이 차단되었습니다. + + + 알 수 없는 스크립트 파일 정책 적용 값이 반환됨: {0}. + + + 스크립트 파일 읽기 + + + 스크립트 파일 '{0}'은(는) 정책에서 신뢰되지 않으므로 ConstrainedLanguage 모드에서 실행됩니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/Serialization.ko.resx b/src/System.Management.Automation/resources/ko/Serialization.ko.resx new file mode 100644 index 00000000000..8f51b7052e9 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/Serialization.ko.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} 특성이 필요합니다. + + + {0} XML 태그를 인식할 수 없습니다. + + + referenceId {0}에 대한 개체를 찾을 수 없습니다. + + + 사전 키에 대한 Name 특성이 잘못 지정되었습니다. + + + 사전 값에 대한 Name 특성이 잘못 지정되었습니다. + + + PSObject 버전이 올바르지 않습니다. + + + 들어오는 PSObject의 버전은 {0}입니다. 예상 값은 1입니다. + + + referenceId {0}에 대한 TypeNames를 찾을 수 없어 이름을 처리할 수 없습니다. + + + depth 매개 변수 값은 1보다 크거나 같아야 합니다. + + + 현재 노드 형식은 {0}입니다. {1} 형식이 필요합니다. + + + 사전 항목의 키가 지정되지 않았습니다. + + + 사전 항목의 값이 지정되지 않았습니다. + + + 더 이상 역직렬화할 개체가 없습니다. + + + Null이 사전 키로 지정되었습니다. + + + {0} 기본 형식의 내용이 올바르지 않습니다. + + + 직렬화된 XML의 중첩이 너무 깊습니다. + + + 직렬 변환기가 닫혔습니다. + + + 명령에 포함된 데이터가 세션 구성에서 허용하는 최대 크기를 초과했습니다. 허용되는 최대 크기는 {0}MB입니다. 입력을 변경하거나, 다른 세션 구성을 사용하거나, 원격 컴퓨터에서 세션 구성의 "{1}" 및 "{2}" 속성을 변경하세요. + + + 암호화된 보안 문자열의 역직렬화에 실패했습니다. + + + {0} 키 유형이 유효하지 않습니다. PSPrimitiveDictionary 클래스는 System.String 형식의 키만 허용합니다. + + + 값 형식 {0}이(가) 올바르지 않습니다. PSPrimitiveDictionary 클래스는 PowerShell 원격을 통해 완전히 직렬화할 수 있는 형식의 값만 허용합니다. 완전히 직렬화할 수 있는 형식 목록은 about_Remoting 도움말 항목을 참조하세요. + + + 데이터를 해독할 수 없습니다. 이 키로 암호화된 데이터가 아닙니다. + + + 매개 변수 값 "{0}"은(는) 올바른 암호화된 문자열이 아닙니다. + + + 지정한 {0}이(가) 잘못되었습니다. 유효한 {0} 길이 설정은 128비트, 192비트 또는 256비트입니다. + + + SecureString 역직렬화는 현재 Windows에서만 지원됩니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/SessionStateProviderBaseStrings.ko.resx b/src/System.Management.Automation/resources/ko/SessionStateProviderBaseStrings.ko.resx new file mode 100644 index 00000000000..447e1e34cb4 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/SessionStateProviderBaseStrings.ko.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + 항목 지우기 + + + 항목: {0} + + + 항목 제거 + + + 항목: {0} + + + 새 항목 + + + 항목: {0} 형식: {1} 값: {2} + + + 항목 복사 + + + 항목: {0} 대상: {1} + + + 항목 이름 바꾸기 + + + 항목: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/SessionStateStrings.ko.resx b/src/System.Management.Automation/resources/ko/SessionStateStrings.ko.resx new file mode 100644 index 00000000000..153cdfc5f05 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/SessionStateStrings.ko.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 공급자의 Start 메서드에서 반환된 정보가 전달된 것과 다른 공급자에 대한 정보이므로 반환된 정보를 처리할 수 없습니다. + + + 공급자의 Start 메서드에서 반환된 정보가 null이므로 반환된 정보를 처리할 수 없습니다. + + + 경로 '{1}'의 '{0}' 공급자에서 GetItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetItem 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 SetItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 SetItem 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 ClearItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 InvokeDefaultAction 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 InvokeDefaultAction 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 ItemExists 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 ItemExists 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 IsValidPath 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 IsItemContainer 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 RemoveItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetChildItems 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetChildItems 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetChildNames 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetChildNames 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 RenameItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 RenameItem 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 NewItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 NewItem 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 HasChildItems 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 CopyItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 CopyItem 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetParentPath 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 NormalizeRelativePath 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 MakePath 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetChildName 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 MoveItem 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 MoveItem 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 SetProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 SetProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 ClearProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 ClearProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 NewProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 NewProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 RemoveProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 RemoveProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 CopyProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 CopyProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 MoveProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 MoveProperty 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 RenameProperty 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 RenameProperty에 대한 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 콘텐츠 판독기를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 GetContentReader 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 콘텐츠 작성기를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에 대해 GetContentWriter 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + '{0}'은(는) 디렉터리이므로 콘텐츠를 가져올 수 없습니다. 대신 'Get-ChildItem'을 사용하세요. + + + '{0}'은(는) 디렉터리이므로 콘텐츠를 쓸 수 없습니다. + + + 뒤로 이동할 위치 기록이 남아 있지 않습니다. + + + 앞으로 이동할 위치 기록이 남아 있지 않습니다. + + + BoundedStack이 비어 있습니다. + + + 경로 '{1}'의 '{0}' 공급자에서 ClearContent 작업을 수행하지 못했습니다. {2} + + + '{0}'은(는) 디렉터리이므로 해당 콘텐츠를 지울 수 없습니다. Clear-Content는 파일에서만 지원됩니다. + + + 경로 '{1}'의 '{0}' 공급자에서 ClearContent 작업의 동적 매개 변수를 검색할 수 없습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 GetSecurityDescriptor 작업을 수행하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자에서 SetSecurityDescriptor 작업을 수행하지 못했습니다. {2} + + + '{0}' 공급자에서 Start 작업을 수행하지 못했습니다. {1} + + + '{0}' 공급자에서 InitializeDefaultDrives 작업을 수행하지 못했습니다. + + + 루트 '{1}'이(가) 있는 드라이브의 '{0}' 공급자에서 NewDrive 작업을 수행하지 못했습니다. {2} + + + '{0}' 공급자에 대한 NewDrive의 동적 매개 변수를 검색할 수 없습니다. {1} + + + '{0}' 공급자에서 RemoveDrive를 호출하지 못했습니다. {1} + + + 공급자 '{1}'에서 허용하지 않으므로 드라이브 '{0}'을(를) 제거할 수 없습니다. + + + 경로 '{0}'이(가) 기준 '{1}' 밖에 있는 항목을 참조했습니다. + + + 경로 '{1}'의 '{0}' 공급자 콘텐츠 작성기에서 Seek를 호출하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자 콘텐츠 판독기 또는 작성기에서 Close를 호출하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자 콘텐츠 판독기에서 Read를 호출하지 못했습니다. {2} + + + 경로 '{1}'의 '{0}' 공급자 콘텐츠 작성기에서 Write를 호출하지 못했습니다. {2} + + + 변수 구문을 사용하여 데이터를 가져오거나 설정할 때는 공급자 '{0}'을(를) 사용할 수 없습니다. {2} + + + 변수 구문을 사용하여 공급자에서 데이터를 가져오거나 설정할 수 없습니다. {2} + + + 별칭 {0}이(가) 읽기 전용이거나 상수이고 쓰기가 불가능하므로 별칭을 쓸 수 없습니다. + + + 함수 {0}은(는) 읽기 전용이거나 상수이므로 쓸 수 없습니다. + + + 변수가 읽기 전용이거나 상수이므로 변수 {0}을(를) 덮어쓸 수 없습니다. + + + 변수 '${0}'은(는) 비공개 변수이므로 액세스할 수 없습니다. + + + 명령 '{0}'은(는) 비공개 명령이므로 명령에 액세스할 수 없습니다. + + + 비공개 명령이므로 명령에 액세스할 수 없습니다. + + + 비공개 리소스이므로 세션 상태 리소스에 액세스할 수 없습니다. + + + 별칭 {0}은(는) 상수이거나 읽기 전용이므로 제거하지 못했습니다. + + + 함수 {0}은(는) 상수이므로 제거할 수 없습니다. + + + 변수 {0}은(는) 상수이거나 읽기 전용이므로 제거할 수 없습니다. 변수가 읽기 전용인 경우 Force 옵션을 지정하여 작업을 다시 시도하세요. + + + 별칭 {0}은(는) 상수이므로 수정할 수 없습니다. + + + 별칭 {0}은(는) 읽기 전용이므로 수정할 수 없습니다. + + + 함수 {0}은(는) 상수이므로 수정할 수 없습니다. + + + 함수 {0}은(는) 읽기 전용이므로 수정할 수 없습니다. + + + 별칭 {0}은(는) 만든 후 상수로 설정할 수 없습니다. 별칭은 만들 때만 상수로 설정할 수 있습니다. + + + 기존 함수 {0}은(는) 상수로 만들 수 없습니다. 함수는 만들 때만 상수로 설정할 수 있습니다. + + + 기존 변수 {0}을(를) 상수로 만들 수 없습니다. 변수는 만들 때만 상수로 설정할 수 있습니다. + + + 별칭 '{0}'에서 AllScope 옵션을 제거할 수 없습니다. + + + 함수 '{0}'에서 AllScope 옵션을 제거할 수 없습니다. + + + 변수 '{0}'에서 AllScope 옵션을 제거할 수 없습니다. + + + 함수 정의 '{0}'에는 범위 한정자는 있지만 함수 이름이 없습니다. + + + 공급자 {0}을(를) 제거할 수 없습니다. 공급자 {0}을(를) 제거하려면 먼저 공급자 {0}과(와) 연결된 모든 드라이브를 제거해야 합니다. + + + 드라이브 이름에 다음과 같은 잘못된 문자가 하나 이상 포함되어 있으므로 드라이브 이름을 처리할 수 없습니다. ; ~ / \ . : + + + 공급자가 새 드라이브 만들기를 허용하지 않으므로 새 드라이브를 만들지 못했습니다. + + + 제공된 값 '{0}'이(가) 둘 이상의 위치 스택으로 확인되었습니다. + + + 위치 스택 '{0}'을(를) 찾을 수 없습니다. 존재하지 않거나 컨테이너가 아닙니다. + + + 경로 '{0}'이(가) 없으므로 찾을 수 없습니다. + + + 별칭 '{0}'이(가) 없으므로 별칭을 찾을 수 없습니다. + + + 경로 '{0}'이(가) 여러 컨테이너로 확인되어 위치를 설정할 수 없습니다. 위치는 한 번에 하나의 컨테이너로만 설정할 수 있습니다. + + + 변수 경로 '{0}'이(가) 여러 항목으로 확인되었으므로 변수를 처리할 수 없습니다. 변수 값은 한 번에 한 항목씩만 가져오거나 설정할 수 있습니다. + + + 드라이브를 찾을 수 없습니다. 이름이 '{0}'인 드라이브가 없습니다. + + + 이름이 '{0}'인 공급자를 찾을 수 없습니다. + + + 이름이 '{0}'인 공급자를 찾을 수 없습니다. 이름 형식이 올바르지 않습니다. 공급자 이름은 영숫자 문자로만 구성되거나, PowerShell 스냅인 이름 뒤에 단일 '\'와 영숫자 문자가 와야 합니다. + + + '{0}'이(가) 둘 이상의 공급자 이름으로 확인되었습니다. 가능한 일치 항목은 다음과 같습니다.{1}. + + + 공급자의 인스턴스를 만드는 동안 오류가 발생했습니다. 어셈블리에서 '{0}'의 공급자 형식 이름을 찾을 수 없습니다. + + + 지정한 공급자 이름 '{0}'에 다음과 같은 잘못된 문자가 하나 이상 포함되어 있으므로 공급자 이름을 사용할 수 없습니다. \ [ ] ? * : + + + 공급자 '{0}'의 인스턴스를 만드는 동안 오류가 발생했습니다. {1} + + + 이름이 '{0}'인 변수를 찾을 수 없습니다. + + + 이름이 '{0}'인 추적 원본을 찾을 수 없습니다. + + + 이름이 '{0}'인 지정된 드라이브가 이미 있습니다. + + + 이름이 '{0}'인 변수가 이미 있습니다. + + + 이름이 '{0}'인 별칭이 이미 있으므로 별칭을 사용할 수 없습니다. + + + 이름이 '{0}'인 cmdlet 공급자가 이미 있으므로 cmdlet 공급자를 등록할 수 없습니다. + + + 경로가 파일 시스템 경로를 참조하지 않습니다. + + + 전역 범위를 제거할 수 없습니다. + + + 범위 번호 '{0}'이(가) 활성 범위 수를 초과합니다. + + + PSDriveInfo를 비교할 수 없습니다. PSDriveInfo 인스턴스는 다른 PSDriveInfo 인스턴스와만 비교할 수 있습니다. + + + 출력을 스트리밍할 cmdlet이 지정되지 않아 cmdlet 공급자가 결과를 스트리밍할 수 없습니다. + + + 오류를 스트리밍할 cmdlet이 지정되지 않아 cmdlet 공급자가 결과를 스트리밍할 수 없습니다. + + + 이 공급자의 홈 위치가 설정되지 않았습니다. 홈 위치를 설정하려면 "(get-psprovider '{0}').Home = 'path'"를 호출하세요. + + + 경로 형식이 잘못되었습니다. 공급자 경로에는 공급자 ID 뒤에 "::" 및 공급자별 경로가 차례로 포함되어야 합니다. + + + 대상 경로를 단일 경로로만 확인할 수 있으므로 항목을 이동할 수 없습니다. + + + 원본 경로와 대상 경로가 동일한 공급자로 확인되지 않았으므로 항목을 이동할 수 없습니다. + + + 원본 경로가 하나 이상의 항목을 가리키고 대상 경로가 컨테이너가 아니므로 항목을 이동할 수 없습니다. 대상 경로가 컨테이너인지 확인하고 다시 시도하세요. + + + 대상이 여러 경로로 확인되었으므로 항목을 이동할 수 없습니다. 하나의 대상으로만 확인되는 대상 경로를 지정하고 다시 시도하세요. + + + 컨테이너를 기존 리프 항목에 복사할 수 없습니다. + + + 컨테이너를 다른 컨테이너에 복사할 수 없습니다. -Recurse 또는 -Container 매개 변수가 지정되지 않았습니다. + + + 원본 경로와 대상 경로가 같은 공급자로 확인되지 않았습니다. + + + 경로가 여러 항목으로 확인되었으므로 항목 이름을 바꿀 수 없습니다. 한 번에 하나의 항목만 이름을 바꿀 수 있습니다. + + + 공급자의 오류로 인해 공급자 '{0}'을(를) 사용하여 경로 '{1}'을(를) 확인할 수 없습니다. + + + 인터페이스를 사용할 수 없습니다. 이 공급자는 IContentCmdletProvider 인터페이스를 구현하지 않습니다. + + + 인터페이스를 사용할 수 없습니다. 이 공급자는 IPropertyCmdletProvider 인터페이스를 지원하지 않습니다. + + + 인터페이스를 사용할 수 없습니다. 이 공급자는 IDynamicPropertyCmdletProvider 인터페이스를 구현하지 않습니다. + + + 이 공급자는 NavigationCmdletProvider 메서드를 지원하지 않습니다. + + + 공급자 메서드를 처리할 수 없습니다. 이 공급자는 ContainerCmdletProvider 메서드를 지원하지 않습니다. + + + 메서드를 호출할 수 없습니다. 이 공급자는 ItemCmdletProvider 메서드를 지원하지 않습니다. + + + 이 공급자는 DriveCmdletProvider 메서드를 지원하지 않습니다. + + + 공급자가 이 작업을 지원하지 않으므로 공급자 작업이 중지되었습니다. + + + 공급자가 'Depth' 매개 변수를 지원하지 않으므로 공급자 작업이 중지되었습니다. + + + 메서드를 호출할 수 없습니다. 이 공급자는 콘텐츠 Seek 메서드를 지원하지 않습니다. + + + ClearContent 작업을 수행할 수 없습니다. 이 공급자는 ClearContent 작업을 지원하지 않습니다. + + + 공급자가 자격 증명의 사용을 지원하지 않습니다. 자격 증명을 지정하지 않고 작업을 다시 수행하세요. + + + FileSystem 공급자는 New-PSDrive cmdlet에서만 자격 증명을 지원합니다. 자격 증명을 지정하지 않고 작업을 다시 수행하세요. + + + 공급자가 트랜잭션을 지원하지 않습니다. -UseTransaction 매개 변수 없이 작업을 다시 수행하세요. + + + 메서드를 호출할 수 없습니다. 공급자가 필터의 사용을 지원하지 않습니다. + + + 드라이브를 만들 수 없습니다. 공급자가 자격 증명의 사용을 지원하지 않습니다. + + + 경로 '{0}'에 항목이 이미 있습니다. + + + 항목을 복사할 수 없습니다. 경로 '{0}'에 항목이 없습니다. + + + 경로 '{0}'에 항목이 없습니다. + + + 세션 상태에 저장된 별칭의 보기가 포함된 드라이브 + + + 프로세스에 대한 환경 변수의 보기가 포함된 드라이브 + + + 세션 상태에 저장된 함수의 보기가 포함된 드라이브 + + + 세션 상태에 저장된 해당 별칭의 보기가 포함된 드라이브 + + + 현재 사용자의 임시 디렉터리 경로에 매핑되는 드라이브 + + + 대상 값을 지정하지 않았으므로 링크 '{0}'을(를) 만들 수 없습니다. + + + null 변수에 대한 참조는 항상 null 값을 반환합니다. 할당해도 아무 효과가 없습니다. + + + 세션에서 유지할 최대 기록 개체 수 + + + 함수 {0}은(는) 읽기 전용이거나 상수이므로 이름을 바꿀 수 없습니다. + + + 별칭 {0}은(는) 읽기 전용이거나 상수이므로 이름을 바꿀 수 없습니다. + + + 변수 {0}은(는) 읽기 전용이거나 상수이므로 이름을 바꿀 수 없습니다. + + + 로컬 변수 {0}에는 옵션을 설정할 수 없습니다. 옵션을 설정할 수 있는 변수를 만들려면 New-Variable을 사용하세요. + + + Cmdlet {0}은(는) 읽기 전용이므로 수정할 수 없습니다. + + + 변수가 최적화되어 제거할 수 없으므로 변수 {0}을(를) 제거할 수 없습니다. 별칭 없이 Remove-Variable cmdlet을 사용하거나, 변수를 제거하는 데 사용하는 명령을 도트 소싱해 보세요. + + + 변수 {0}이(가) 최적화되어 있으므로 변수를 덮어쓸 수 없습니다. 별칭 없이 New-Variable 또는 Set-Variable cmdlet을 사용하거나, 변수를 설정하는 데 사용하는 명령을 도트 소싱해 보세요. + + + 매개 변수 {0}과(와) {1}은(는) 함께 사용할 수 없습니다. 매개 변수를 하나만 지정하세요. + + + 현재 Tail 매개 변수는 FileSystem 공급자에 대해서만 지원됩니다. + + + 이름이 '{0}'이고 명령 유형이 '{1}'인 명령이 이미 있으므로 별칭을 사용할 수 없습니다. + + + 소프트웨어를 실행할 수 없습니다. 사용 권한이 거부되었습니다. + + + '-{0}' 및 '-{1}'은(는) 상호 배타적이며 동시에 지정할 수 없습니다. + + + 경로 '{0}'은(는) 유효하지 않습니다. 원격 복사 작업에서는 절대 경로만 지원됩니다. + + + 원격 경로 '{0}'의 유효성을 검사할 수 없습니다. + + + 세션 {0}이(가) {1}(으)로 설정되어 있으므로 작업을 수행할 수 없습니다. + + + '{0}' 매개 변수는 null이거나 비워 둘 수 없습니다. + + + 세션 상태 변수 + + + ConstrainedLanguage 모드에서는 변수 '{0}'의 범위를 AllScope로 변경하거나 만들 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/StringDecoratedStrings.ko.resx b/src/System.Management.Automation/resources/ko/StringDecoratedStrings.ko.resx new file mode 100644 index 00000000000..dfc6501f21a --- /dev/null +++ b/src/System.Management.Automation/resources/ko/StringDecoratedStrings.ko.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 이 메서드에는 'ANSI' 또는 'PlainText'만 지원됩니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/SubsystemStrings.ko.resx b/src/System.Management.Automation/resources/ko/SubsystemStrings.ko.resx new file mode 100644 index 00000000000..495e0f4f432 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/SubsystemStrings.ko.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 + + + 하위 시스템 '{0}'에서는 둘 이상의 구현 등록을 허용하지 않습니다. + + + ID가 '{0}'인 구현은 하위 시스템 '{1}'에 이미 등록되어 있습니다. + + + 하위 시스템 '{0}'에서는 구현 등록 취소를 허용하지 않습니다. + + + 하위 시스템 '{0}'에 대해 등록된 구현이 없습니다. + + + ID가 '{0}'인 등록된 구현을 찾을 수 없습니다. + + + 지정한 하위 시스템 유형 '{0}'은(는) 알 수 없습니다. + + + 기본 인터페이스 'ISubsystem' 대신 구체적인 하위 시스템 형식을 지정해야 합니다. + + + 지정한 하위 시스템 종류 '{0}'은(는) 알 수 없습니다. + + + 대상 하위 시스템 종류 '{0}'의 경우, 지정된 하위 시스템 instance는 해당하는 구체적인 인터페이스나 추상 클래스 '{1}'을(를) 구현해야 합니다. + + + 하위 시스템 종류 '{0}'에 대해 선언된 메타데이터가 올바르지 않습니다. cmdlet이나 함수를 정의해야 하는 하위 시스템은 여러 번 등록할 수 없습니다. 한 구현이 다른 구현에서 정의한 명령을 덮어쓰게 되기 때문입니다. + + + 하위 시스템 '{0}'에 대한 구현의 'Id' 속성은 빈 GUID일 수 없습니다. + + + 하위 시스템 '{0}'에 대한 구현의 'Name' 속성은 null이거나 빈 문자열일 수 없습니다. + + + 하위 시스템 '{0}'에 대한 구현의 'Description' 속성은 null이거나 빈 문자열일 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/SuggestionStrings.ko.resx b/src/System.Management.Automation/resources/ko/SuggestionStrings.ko.resx new file mode 100644 index 00000000000..801524473b3 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/SuggestionStrings.ko.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 + + + 명령 "{0}"을(를) 찾을 수 없지만 현재 위치에 있습니다. +PowerShell은 기본적으로 현재 위치에서 명령을 로드하지 않습니다('Get-Help about_Command_Precedence' 참조). + +이 명령을 신뢰하는 경우 대신 다음 명령을 실행하세요: + + + 가장 유사한 명령은 다음과 같습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/TabCompletionStrings.ko.resx b/src/System.Management.Automation/resources/ko/TabCompletionStrings.ko.resx new file mode 100644 index 00000000000..4cfa12f1b95 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/TabCompletionStrings.ko.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 원격 runspace에 TypeTable instance가 없으므로 탭 완성 결과를 제대로 역직렬화할 수 없습니다. + + + CompletionResult 형식의 null instance에 있는 속성에 액세스할 수 없습니다. + + + 비트 관련 아님 + + + 논리적이지 않습니다. 뒤에 오는 문을 부정합니다. + + + 같음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 같을 때 TRUE를 반환합니다. + + + 같음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 같을 때 TRUE를 반환합니다. + + + 같음 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 같을 때 TRUE를 반환합니다. + + + 같지 않음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 같지 않은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 같지 않을 때 TRUE를 반환합니다. + + + 같지 않음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 같지 않은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 같지 않을 때 TRUE를 반환합니다. + + + 같지 않음 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 같지 않은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 같지 않을 때 TRUE를 반환합니다. + + + 크거나 같음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 크거나 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같을 때 TRUE를 반환합니다. + + + 크거나 같음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 크거나 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같을 때 TRUE를 반환합니다. + + + 크거나 같음 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 크거나 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 크거나 같을 때 TRUE를 반환합니다. + + + 보다 큼 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 큰 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 클 때 TRUE를 반환합니다. + + + 보다 큼 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 큰 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 클 때 TRUE를 반환합니다. + + + 보다 큼 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 큰 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 클 때 TRUE를 반환합니다. + + + 보다 작음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션인 경우 오른쪽 피연산자보다 작은 컬렉션의 값을 반환하고, 왼쪽 피연산자가 오른쪽 피연산자보다 작으면 TRUE를 반환합니다. + + + 보다 작음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션인 경우 오른쪽 피연산자보다 작은 컬렉션의 값을 반환하고, 왼쪽 피연산자가 오른쪽 피연산자보다 작으면 TRUE를 반환합니다. + + + 보다 작음 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션인 경우 오른쪽 피연산자보다 작은 컬렉션의 값을 반환하고, 왼쪽 피연산자가 오른쪽 피연산자보다 작으면 TRUE를 반환합니다. + + + 작거나 같음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 작거나 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같을 때 TRUE를 반환합니다. + + + 작거나 같음 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 작거나 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같을 때 TRUE를 반환합니다. + + + 작거나 같음 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자보다 작거나 같은 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자보다 작거나 같을 때 TRUE를 반환합니다. + + + 와일드카드 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치할 때 TRUE를 반환합니다. + + + 와일드카드 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치할 때 TRUE를 반환합니다. + + + 와일드카드 일치 연산자 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치할 때 TRUE를 반환합니다. + + + 와일드카드 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하지 않는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치하지 않을 때 TRUE를 반환합니다. + + + 와일드카드 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하지 않는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치하지 않을 때 TRUE를 반환합니다. + + + 와일드카드 일치 연산자 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하지 않는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치하지 않을 때 TRUE를 반환합니다. + + + 정규식 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치할 때 TRUE를 반환합니다. + + + 정규식 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치할 때 TRUE를 반환합니다. + + + 정규식 일치 연산자 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치할 때 TRUE를 반환합니다. + + + 정규식 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하지 않는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치하지 않을 때 TRUE를 반환합니다. + + + 정규식 일치 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하지 않는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치하지 않을 때 TRUE를 반환합니다. + + + 정규식 일치 연산자 - 대/소문자를 구분합니다. 왼쪽 피연산자가 컬렉션이면 오른쪽 피연산자와 일치하지 않는 컬렉션의 값을 반환하고, 그렇지 않으면 왼쪽 피연산자가 오른쪽 피연산자와 일치하지 않을 때 TRUE를 반환합니다. + + + 바꾸기 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자를 변경합니다. 예: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + 바꾸기 연산자 - 대/소문자를 구분하지 않습니다. 왼쪽 피연산자를 변경합니다. 예: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + 연산자 바꾸기 - 대/소문자를 구분합니다. 왼쪽 피연산자를 변경합니다. 예: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(오른쪽 피연산자)이 왼쪽 피연산자의 값 중 하나 이상과 정확히 일치하면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(오른쪽 피연산자)이 왼쪽 피연산자의 값 중 하나 이상과 정확히 일치하면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분합니다. 테스트 값(오른쪽 피연산자)이 왼쪽 피연산자의 값 중 하나 이상과 정확히 일치할 때만 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(오른쪽 피연산자)이 왼쪽 피연산자의 값과 하나도 정확히 일치하지 않으면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(오른쪽 피연산자)이 왼쪽 피연산자의 값과 하나도 정확히 일치하지 않으면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분합니다. 테스트 값(오른쪽 피연산자)이 왼쪽 피연산자의 값과 하나도 정확히 일치하지 않으면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(왼쪽 피연산자)이 오른쪽 피연산자의 값 중 하나 이상과 정확히 일치하면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(왼쪽 피연산자)이 오른쪽 피연산자의 값 중 하나 이상과 정확히 일치하면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분합니다. 테스트 값(왼쪽 피연산자)이 오른쪽 피연산자의 값 중 하나 이상과 정확히 일치하면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분합니다. 테스트 값(왼쪽 피연산자)이 오른쪽 피연산자의 값과 하나도 정확히 일치하지 않으면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분하지 않습니다. 테스트 값(왼쪽 피연산자)이 오른쪽 피연산자의 값과 하나도 정확히 일치하지 않으면 TRUE를 반환합니다. + + + 포함 연산자 - 대/소문자를 구분합니다. 테스트 값(왼쪽 피연산자)이 오른쪽 피연산자의 값과 하나도 정확히 일치하지 않으면 TRUE를 반환합니다. + + + Split - 대/소문자를 구분하지 않습니다. 하나 이상의 문자열을 하위 문자열로 분할합니다. +-split <String> + +<String> -split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -split {<ScriptBlock>} [,<Max-substrings>] + + + Split - 대/소문자를 구분하지 않습니다. 하나 이상의 문자열을 하위 문자열로 분할합니다. +-split <String> + +<String> -split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -split {<ScriptBlock>} [,<Max-substrings>] + + + Split - 대/소문자를 구분합니다. 하나 이상의 문자열을 하위 문자열로 분할합니다. +-split <String> + +<String> -split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -split {<ScriptBlock>} [,<Max-substrings>] + + + 왼쪽 피연산자가 지정된 .NET Framework 형식(오른쪽 피연산자)의 인스턴스가 아니면 TRUE를 반환합니다. + + + 왼쪽 피연산자가 지정된 .NET Framework 형식(오른쪽 피연산자)의 인스턴스이면 TRUE를 반환합니다. + + + 왼쪽 피연산자를 지정한 .NET Framework 형식(오른쪽 피연산자)으로 변환합니다. + + + 문자열 개체의 형식 메서드를 사용하여 문자열의 서식을 지정합니다. + + + 논리적 AND. 두 문이 모두 TRUE이면 TRUE를 반환합니다. + + + 비트 AND + + + 논리적 OR. 문 중 하나 또는 둘 다 TRUE이면 TRUE입니다. + + + 비트 OR(포함)입니다. + + + 논리적 배타적 OR입니다. 문 중 하나는 TRUE이고 다른 하나는 FALSE이면 TRUE를 반환합니다. + + + 비트 OR(배타적) + + + Join - 여러 문자열을 하나의 문자열로 결합합니다. +-Join <String[]> +<String[]> -Join <Delimiter> + + + 왼쪽으로 이동 비트 연산자입니다. 가장 오른쪽 비트 위치에 0을 삽입합니다. + + + 오른쪽으로 이동 비트 연산자입니다. 가장 왼쪽 비트 위치에 0을 삽입합니다. 부호 있는 값의 경우 부호 비트는 유지됩니다. + + + [string] +만들려는 속성의 이름을 지정합니다. + + + [string] +만들려는 속성의 이름을 지정합니다. + + + [scriptblock] +새 속성의 값을 계산하는 데 사용하는 스크립트 블록입니다. + + + [string] +값을 열에 표시하는 방법을 정의합니다. +유효한 값은 'left', 'center' 또는 'right'입니다. + + + [string] +출력을 위해 값의 형식을 지정하는 형식 문자열을 지정합니다. + + + [int] +값이 표시될 때 테이블의 최대 열 너비를 지정합니다. +값은 0보다 커야 합니다. + + + [int] +깊이 키는 속성별 확장 깊이를 지정합니다. + + + [bool] +하나 이상의 속성에 대한 정렬 순서를 지정합니다. + + + [bool] +하나 이상의 속성에 대한 정렬 순서를 지정합니다. + + + [String[]] +이벤트를 가져올 로그 이름을 지정합니다. +와일드카드를 지원합니다. + + + [String[]] +이벤트를 가져올 이벤트 로그 공급자를 지정합니다. +와일드카드를 지원합니다. + + + [String[]] +이벤트를 가져올 로그 파일의 파일 경로를 지정합니다. +유효한 파일 형식은 .etl, .evt, .evtx입니다. + + + [Long[]] +지정된 키워드 비트 마스크가 있는 이벤트를 선택합니다. +다음은 표준 키워드입니다. +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +지정된 이벤트 ID의 이벤트를 선택합니다. + + + [int[]] +지정된 로그 수준의 이벤트를 선택합니다. +유효한 로그 수준은 다음과 같습니다. +1 - 위험 +2: 오류 +3: 경고 +4: 정보 제공 +5: 자세한 정보 + + + [datetime] +지정된 날짜 및 시간 이후에 만들어진 이벤트를 선택합니다. + + + [datetime] +지정된 날짜 및 시간 이전에 만들어진 이벤트를 선택합니다. + + + [string] +지정된 사용자가 생성한 이벤트를 선택합니다. +이 값은 SID의 문자열 표현이거나 DOMAIN\USERNAME 또는 USERNAME@DOMAIN 형식의 도메인과 사용자 이름일 수 있습니다. + + + [string[]] +EventData 섹션에 지정된 값이 있는 이벤트를 선택합니다. + + + [hashtable] +해시 테이블에 지정된 값과 일치하는 이벤트를 제외합니다. + + + [string] 또는 [hashtable] +스크립트에 필요한 PowerShell 모듈 배열을 지정합니다. +각 요소는 모듈 이름을 값으로 하는 문자열이거나 다음 키를 포함하는 해시 테이블일 수 있습니다. +이름: 모듈의 이름 +GUID: 모듈의 GUID +다음 중 하나: +ModuleVersion: 모듈의 최소 허용 버전을 지정합니다. +RequiredVersion: 모듈의 정확한 필수 버전을 지정합니다. +MaximumVersion: 모듈의 최대 허용 버전을 지정합니다. + + + [string] +스크립트에 필요한 PowerShell 에디션을 지정합니다. +유효한 값은 "Core" 및 "Desktop"입니다. + + + [switch] +PowerShell이 Windows에서 관리자 권한으로 실행되어야 함을 지정합니다. +이 매개 변수는 #requires 문 줄의 마지막에 와야 합니다. + + + [version] +스크립트에 필요한 PowerShell의 최소 버전을 지정합니다. + + + 스크립트를 실행하려면 PowerShell 7+가 필요하도록 지정합니다. + + + 스크립트를 실행하려면 Windows PowerShell 5.1이 필요함을 지정합니다. + + + [string] +필수 사항입니다. 모듈 이름을 지정합니다. + + + [string] +옵션입니다. 모듈의 GUID를 지정합니다. + + + [string] +모듈의 최소 허용 버전을 지정합니다. + + + [string] +모듈의 정확한 필수 버전을 지정합니다. + + + [string] +모듈의 최대 허용 버전을 지정합니다. + + + 함수 또는 스크립트에 대한 간단한 설명입니다. +이 키워드는 각 항목에서 한 번만 사용할 수 있습니다. + + + 함수 또는 스크립트에 대한 자세한 설명입니다. +이 키워드는 각 항목에서 한 번만 사용할 수 있습니다. + + + .PARAMETER <Parameter-Name> +매개 변수에 대한 설명입니다. +함수 또는 스크립트 구문의 각 매개 변수마다 .PARAMETER 키워드를 추가합니다. + + + 함수 또는 스크립트를 사용하는 샘플 명령이며, 필요에 따라 샘플 출력과 설명이 뒤따릅니다. +각 예제마다 이 키워드를 반복합니다. + + + 함수 또는 스크립트에 파이프할 수 있는 개체의 .NET 형식입니다. +입력 개체에 대한 설명도 포함할 수 있습니다. + + + cmdlet이 반환하는 개체의 .NET 형식입니다. +반환된 개체에 대한 설명을 포함할 수도 있습니다. + + + 함수 또는 스크립트에 대한 추가 정보입니다. + + + 관련 항목의 이름입니다. +각 관련 항목마다 .LINK 키워드를 반복하세요. +.Link 키워드 콘텐츠에는 같은 도움말 항목의 온라인 버전 URI도 포함할 수 있습니다. + + + 함수 또는 스크립트에서 사용하거나 관련된 기술 또는 기능의 이름입니다. + + + 도움말 항목의 사용자 역할 이름입니다. + + + 함수의 용도를 설명하는 키워드입니다. + + + .FORWARDHELPTARGETNAME <Command-Name> +지정한 명령의 도움말 항목으로 리디렉션됩니다. + + + .FORWARDHELPCATEGORY <Category> +.ForwardHelpTargetName의 항목에 대한 도움말 범주를 지정합니다. + + + .REMOTEHELPRUNSPACE <PSSession-variable> +도움말 항목이 포함된 세션을 지정합니다. +PSSession 개체가 포함된 변수를 입력하세요. + + + .EXTERNALHELP <XML Help File> +함수 또는 스크립트가 XML 파일에 문서화된 경우 .ExternalHelp 키워드가 필요합니다. + + + 로드할 .NET 어셈블리의 경로를 지정합니다. + +using assembly <.NET-assembly-path> + + + 클래스를 로드할 PowerShell 모듈을 지정합니다. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + 형식을 resolve할 .NET 네임스페이스 또는 네임스페이스 별칭을 지정합니다. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + .NET 형식의 별칭을 지정합니다. + +using type <AliasName> = <.NET-type> + + + 일반 문자열입니다. + + + 값을 검색할 때 확장되는 환경 변수에 대한 확장되지 않은 참조를 포함하는 문자열입니다. + + + 모든 형식의 이진 데이터입니다. + + + 32비트 이진수입니다. + + + 문자열 배열입니다. + + + 64비트 이진수입니다. + + + 지원되지 않는 레지스트리 데이터 형식입니다. + + + ',' - 쉼표 + + + ', ' - 쉼표와 공백 + + + ';' - 세미콜론 + + + '; ' - Semi-Colon-Space + + + {0} - 줄 바꿈 + + + '-' - 대시 + + + ' ' - 공간 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/TransactionStrings.ko.resx b/src/System.Management.Automation/resources/ko/TransactionStrings.ko.resx new file mode 100644 index 00000000000..5ea91426480 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/TransactionStrings.ko.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 트랜잭션을 사용할 수 없습니다. 활성 트랜잭션이 없습니다. + + + 트랜잭션을 커밋할 수 없습니다. 활성 트랜잭션이 없습니다. + + + 활성 트랜잭션이 없으므로 트랜잭션을 롤백할 수 없습니다. + + + 트랜잭션을 롤백할 수 없습니다. 트랜잭션이 이미 커밋되었습니다. + + + 트랜잭션을 커밋할 수 없습니다. 트랜잭션이 이미 커밋되었습니다. + + + 트랜잭션을 커밋할 수 없습니다. 트랜잭션이 롤백되었거나 시간이 초과되었습니다. + + + 트랜잭션을 롤백할 수 없습니다. 트랜잭션이 이미 롤백되었거나 시간이 초과되었습니다. + + + 활성 트랜잭션을 설정할 수 없습니다. 트랜잭션이 생성되지 않았습니다. + + + 활성 트랜잭션을 설정할 수 없습니다. 활성 트랜잭션이 롤백되었거나 시간이 초과되었습니다. + + + 이 cmdlet에는 활성 트랜잭션이 필요합니다. 현재 트랜잭션은 이미 커밋되었거나 롤백되었습니다. + + + 이 cmdlet에는 트랜잭션이 필요합니다. -UseTransaction 매개 변수와 함께 명령을 다시 실행하세요. + + + 트랜잭션을 사용할 수 없습니다. 트랜잭션이 시작되지 않았습니다. + + + 트랜잭션을 사용할 수 없습니다. 트랜잭션이 커밋되었습니다. + + + 트랜잭션을 사용할 수 없습니다. 트랜잭션이 롤백되었거나 시간이 초과되었습니다. + + + 트랜잭션을 사용할 수 없습니다. 트랜잭션 시간이 초과되었습니다. + + + 기본 트랜잭션이 설정되지 않았습니다. + + + 기본 트랜잭션이 활성 상태가 아닙니다. + + + 다른 트랜잭션이 생성된 후에는 기본 트랜잭션을 설정할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/TypesXmlStrings.ko.resx b/src/System.Management.Automation/resources/ko/TypesXmlStrings.ko.resx new file mode 100644 index 00000000000..8b353b0f873 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/TypesXmlStrings.ko.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : 오류: {3} + + + {0}, {1}({2}) : 형식 "{3}" 오류: {4} + + + 노드 "{0}"은(는) "{1}"에서 한 번만 발생해야 합니다. 부모 노드 "{1}"은(는) 무시됩니다. + + + 노드 {0}은(는) 허용되지 않습니다. 다음 노드가 허용됩니다. {1}. + + + 노드 "{0}"에는 내부 텍스트가 없어야 합니다. + + + 노드 "{0}"에는 내부 텍스트가 있어야 합니다. + + + 노드 "{0}"을(를) 찾을 수 없습니다. "{1}" 아래에는 하나만 있어야 합니다. 부모 노드 "{1}"은(는) 무시됩니다. + + + "Type" 노드에는 "Members", "TypeConverters" 또는 "TypeAdapters"가 있어야 합니다. + + + 예외로 인해 {0} 형식에 대한 형식 변환기의 인스턴스를 만들 수 없습니다. {1}. + + + PowerShell은 다음 예외 때문에 형식 {0}에 대한 형식 어댑터의 인스턴스를 만들 수 없습니다: {1}. + + + 조정된 형식 "{0}"이(가) 잘못되었습니다. + + + TypeConverter가 이미 있으므로 무시되었습니다. + + + TypeAdapter가 이미 있으므로 무시되었습니다. + + + "{0}" 형식은 TypeConverter 또는 PSTypeConverter여야 합니다. + + + "{0}" 형식은 PSPropertyAdapter여야 합니다. + + + 멤버 {0}이(가) 이미 있습니다. + + + 다음 멤버 이름이 예약되어 있습니다. {0} + + + 예외: {0} + + + ScriptProperty에는 getter 또는 setter가 있어야 합니다. + + + CodeProperty에는 getter 또는 setter가 있어야 합니다. + + + {0}, {1} : {2} + + + 값은 {0} 대신 TRUE 또는 FALSE여야 합니다. + + + 노드 "{0}"에는 "{1}" 특성이 없어야 합니다. + + + {0}, {1}: 파일을 찾을 수 없습니다. + + + {0}, {1}: 파일은 이미 {2}에서 로드되었으므로 건너뛰었습니다. + + + 레지스트리 키 {0}{1}을(를) 찾을 수 없습니다. {2} 사용하여 구성 파일을 로드합니다. + + + 레지스트리 키에 지정된 경로 {0}을(를) 찾을 수 없습니다: {1}{2}. 구성 파일을 로드하기 위해 {3}을(를) 사용합니다. + + + {0}, {1}: ps1xml 파일 이름 확장명이 없으므로 파일을 건너뛰었습니다. + + + {0}, {1}: 유효성 검사 예외 {2} 때문에 파일을 건너뛰어 졌습니다. + + + 멤버 "{0}"은(는) 메모여야 합니다. + + + 메모 "{0}":"{1}"을(를) 변환할 수 없습니다. + + + 여기서는 "{0}" 멤버를 사용하지 마세요. + + + 멤버 "{0}"에는 "{1}" 형식이 있어야 합니다. + + + "{0}"은(는) "{1}"이(가) "{2}"이고 "{3}"이(가) "{4}"일 때 있어야 합니다. + + + 이전 오류로 인해 모든 직렬화 설정이 무시되었습니다. + + + "{0}"은(는) 표준 멤버가 아니며 무시됩니다. + + + {0} 경로는 정규화되지 않았습니다. 정규화된 형식의 파일 경로를 지정하세요. + + + TypeTable은 runspace 외부에서 만들어졌을 수 있으므로 업데이트할 수 없습니다. + + + TypeTable을 로드하는 동안 오류가 발생했습니다. 자세한 오류 메시지는 Errors 속성을 확인하세요. + + + TypeData "{0}" 오류: {1} + + + "{0}"에는 "{1}" 속성에 대한 값이 있어야 합니다. + + + "{0}"의 속성 "{1}"에는 null이나 빈 문자열이 있으면 안 됩니다. + + + "{0}" 형식을 찾을 수 없습니다. 형식 이름 값은 형식의 전체 이름이어야 합니다. 형식 이름을 확인한 다음 명령을 다시 실행하세요. + + + TypeData에는 "Members", "TypeConverters", "TypeAdapters" 또는 "StandardMembers"가 있어야 합니다. + + + 공유 형식 테이블은 여러 항목으로 업데이트할 수 없습니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/VerbDescriptionStrings.ko.resx b/src/System.Management.Automation/resources/ko/VerbDescriptionStrings.ko.resx new file mode 100644 index 00000000000..fd9c7a45398 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/VerbDescriptionStrings.ko.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 컨테이너에 리소스를 추가하거나 항목을 다른 항목에 연결합니다. + + + 리소스 또는 프로세스의 상태를 확인하거나 이에 동의합니다. + + + 리소스의 상태를 확인합니다. + + + 데이터를 복제하여 저장합니다. + + + 리소스에 대한 액세스를 제한합니다. + + + 몇몇 입력 파일 집합(일반적으로 소스 코드 또는 선언적 문서)에서 하나의 아티팩트(일반적으로 이진 또는 문서)를 만듭니다. + + + 데이터의 현재 상태 또는 해당 구성의 스냅샷을 만듭니다. + + + 컨테이너에서 모든 리소스를 제거하지만 컨테이너는 삭제하지 않습니다. + + + 리소스의 상태를 변경하여 액세스할 수 없거나, 사용할 수 없게 만듭니다. + + + 한 리소스의 데이터를 다른 리소스의 데이터에 대해 평가합니다. + + + 작업을 종료합니다. + + + 리소스의 데이터를 압축합니다. + + + 리소스 또는 프로세스의 상태를 승인 또는 확인하거나 유효성을 검사합니다. + + + 원본과 대상 간에 링크를 만듭니다. + + + cmdlet이 양방향 변환을 지원하거나 cmdlet이 여러 데이터 형식 간의 변환을 지원하는 경우 한 표현에서 다른 표현 방식으로 데이터를 변경합니다. + + + 입력의 한 가지 기본 형식(cmdlet 명사는 입력을 나타냄)을 하나 이상의 지원되는 출력 형식으로 변환합니다. + + + 하나 이상의 입력 형식에서 기본 출력 형식(cmdlet 명사는 출력 형식을 나타냄)으로 변환합니다. + + + 리소스를 다른 이름 또는 다른 컨테이너에 복사합니다. + + + 리소스를 검사하여 운영 문제를 진단합니다. + + + 리소스 또는 프로세스의 상태를 거부, 이의 제지, 차단 또는 반대합니다. + + + 배포가 완료된 후 해당 솔루션의 소비자가 액세스할 수 있는 방식으로 애플리케이션, 웹 사이트 또는 솔루션을 원격 대상에 보냅니다. + + + 리소스를 사용할 수 없는 상태 또는 비활성 상태로 구성합니다. + + + 원본과 대상 간의 연결을 끊습니다. + + + 위치에서 명명된 엔터티를 분리합니다. + + + 콘텐츠를 추가하거나 제거하여 기존 데이터를 수정합니다. + + + 리소스를 사용 가능한 상태 또는 활성 상태로 구성합니다. + + + 사용자가 리소스로 이동하도록 허용하는 작업을 지정합니다. + + + 현재 환경 또는 컨텍스트를 가장 최근에 사용한 컨텍스트로 설정합니다. + + + 원래 상태로 압축된 리소스의 데이터를 복원합니다. + + + 기본 입력을 파일과 같은 영구적 데이터 저장소나 교환 형식으로 캡슐화합니다. + + + 알 수 없거나, 암시적이거나, 선택적이거나, 지정된 컨테이너에서 개체를 찾습니다. + + + 지정된 양식 또는 레이아웃의 개체를 정렬합니다. + + + 리소스를 검색하는 작업을 지정합니다. + + + 리소스에 대한 액세스를 허용합니다. + + + 하나 이상의 리소스를 정렬하거나 연결합니다. + + + 리소스를 감지할 수 없게 만듭니다. + + + 영구 데이터 저장소(예: 파일)에 저장되거나 교환 형식으로 저장된 데이터에서 리소스를 만듭니다. + + + 사용할 리소스를 준비하고 기본 상태로 설정합니다. + + + 리소스를 위치에 배치하고, 필요한 경우 초기화합니다. + + + 명령 또는 메서드 실행과 같은 작업을 수행합니다. + + + 리소스를 하나의 리소스로 결합합니다. + + + 리소스에 제약 조건을 적용합니다. + + + 리소스를 보호합니다. + + + 지정된 작업에서 사용되는 리소스를 식별하거나 리소스에 대한 통계를 검색합니다. + + + 여러 리소스에서 단일 리소스를 만듭니다. + + + 명명된 엔터티를 위치에 연결합니다. + + + 리소스를 한 위치에서 다른 위치로 이동합니다. + + + 리소스를 만듭니다. + + + 리소스의 상태를 변경하여 액세스 가능 또는 사용 가능하도록 만듭니다. + + + 리소스의 효율성을 높입니다. + + + 환경 외부로 데이터를 보냅니다. + + + 테스트 동사를 사용합니다. + + + 스택의 맨 위에서 항목을 제거합니다. + + + 공격 또는 손실로부터 리소스를 보호합니다. + + + 다른 사용자가 리소스를 사용할 수 있도록 합니다. + + + 스택의 맨 위에 항목을 추가합니다. + + + 원본에서 정보를 가져옵니다. + + + 원본에서 보낸 정보를 수락합니다. + + + 리소스를 실행 취소된 상태로 다시 설정합니다. + + + 데이터베이스와 같은 리포지토리에 리소스에 대한 항목을 만듭니다. + + + 컨테이너에서 리소스를 삭제합니다. + + + 리소스의 이름을 변경합니다. + + + 리소스를 사용 가능한 상태로 복원합니다. + + + 리소스를 요청하거나 사용 권한을 요청합니다. + + + 리소스를 원래 상태로 다시 설정합니다. + + + 리소스의 크기를 변경합니다. + + + 리소스의 약식 표현을 보다 완전한 표현으로 매핑합니다. + + + 작업을 중지한 다음 다시 시작합니다. + + + 리소스를 검사점에서 설정한 상태와 같이 미리 정의된 상태로 설정합니다. + + + 일시 중단된 작업을 시작합니다. + + + 리소스에 대한 액세스를 허용하지 않는 작업을 지정합니다. + + + 손실을 방지하기 위해 데이터를 보존합니다. + + + 컨테이너의 리소스에 대한 참조를 만듭니다. + + + 컨테이너에서 리소스를 찾습니다. + + + 대상에 정보를 전달합니다. + + + 기존 리소스의 데이터를 대체하거나 일부 데이터가 포함된 리소스를 만듭니다. + + + 리소스를 사용자에게 표시합니다. + + + 둘 이상의 리소스가 동일한 상태에 있도록 보장합니다. + + + 시퀀스에서 하나 이상의 리소스나 지점을 건너뜁니다. + + + 리소스의 여러 부분를 분리합니다. + + + 작업을 시작합니다. + + + 시퀀스의 다음 지점 또는 리소스로 이동합니다. + + + 활동을 중단합니다. + + + 승인을 위한 리소스를 제시합니다. + + + 활동을 일시 중지합니다. + + + 두 위치, 책임 또는 상태 간에 전환하는 등 두 리소스 사이를 번갈아 수행하는 작업을 지정합니다. + + + 리소스의 작업 또는 일관성을 확인합니다. + + + 리소스의 활동을 추적합니다. + + + 리소스에 대한 제한을 제거합니다. + + + 리소스를 이전 상태로 설정합니다. + + + 지정된 위치에서 리소스를 제거합니다. + + + 잠긴 리소스를 해제합니다. + + + 공격 또는 손실을 방지하기 위해 추가된 리소스에서 세이프가드를 제거합니다. + + + 리소스를 다른 사용자가 사용할 수 없게 만듭니다. + + + 리포지토리에서 리소스에 대한 항목을 제거합니다. + + + 리소스의 상태, 정확성, 적합성 또는 규정 준수를 유지하기 위해 최신 상태로 유지합니다. + + + 작업을 수행하기 위해 리소스를 사용하거나 포함합니다. + + + 지정된 이벤트가 발생할 때까지 작업을 일시 중지합니다. + + + 리소스의 변경 내용을 지속적으로 검사하거나 모니터링합니다. + + + 대상에 정보를 추가합니다. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ko/WildcardPatternStrings.ko.resx b/src/System.Management.Automation/resources/ko/WildcardPatternStrings.ko.resx new file mode 100644 index 00000000000..9b8afeb30a1 --- /dev/null +++ b/src/System.Management.Automation/resources/ko/WildcardPatternStrings.ko.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 + + + 지정한 와일드카드 문자 패턴이 유효하지 않음: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/Authenticode.pl.resx b/src/System.Management.Automation/resources/pl/Authenticode.pl.resx new file mode 100644 index 00000000000..195d5bdbd83 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/Authenticode.pl.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 + + + Nie można załadować pliku {0}, ponieważ nie chcesz teraz uruchamiać tego oprogramowania. + + + Nie można załadować pliku {0}, ponieważ wybrano opcję nigdy nie uruchamiania oprogramowania od tego wydawcy. + + + Plik {0} został opublikowany przez {1}. Ten wydawca został jawnie oznaczony jako niezaufany w Twoim systemie. Skrypt nie zostanie uruchomiony w systemie. Aby uzyskać więcej informacji, uruchom polecenie „get-help about_signing”. + + + Nie można załadować pliku {0}, ponieważ uruchomione skrypty są wyłączone w tym systemie. Aby uzyskać więcej informacji, zobacz about_Execution_Policies pod adresem https://go.microsoft.com/fwlink/?LinkID=135170. + + + Nie można załadować pliku {0}. {1}. + + + Nie można załadować pliku {0}, ponieważ jego działanie jest blokowane przez zasady ograniczeń oprogramowania, takie jak zasady utworzone przy użyciu zasad grupy. + + + Nie można załadować pliku {0}, ponieważ nie można odczytać jego zawartości. + + + Nie można podpisać kodu. Określony certyfikat nie jest odpowiedni do podpisywania kodu. + + + Nie można podpisać kodu. Adres URL serwera TimeStamp musi być w pełni kwalifikowany i w formacie http://<serwer url> lub adres URL serwera https://<>. + + + Nie można podpisać kodu. Algorytm skrótu nie jest obsługiwany. + + + Czy chcesz uruchomić oprogramowanie od tego niezaufanego wydawcy? + + + Plik {0} został opublikowany przez {1} i nie jest zaufany w Twoim systemie. Uruchamiaj tylko skrypty od zaufanych wydawców. + + + Oprogramowanie {0} zostało opublikowane przez nieznanego wydawcę. Zaleca się, aby nie uruchamiać tego oprogramowania. + + + Ostrzeżenie o zabezpieczeniach + + + Uruchamiaj tylko skrypty, którym ufasz. Skrypty z Internetu mogą być przydatne, ale ten skrypt może potencjalnie uszkodzić Twój komputer. Jeśli ufasz temu skryptowi, użyj polecenia cmdlet Unblock-File, aby zezwolić na jego uruchomienie bez tego komunikatu ostrzegawczego. Czy chcesz uruchomić {0}? + + + Ni&gdy nie uruchamiaj + + + Nie uruchamiaj teraz skryptu od tego wydawcy i nie monituj mnie o uruchomienie tego skryptu w przyszłości. Przyszłe próby uruchomienia tego skryptu zakończą się cichym niepowodzeniem. + + + &Nie uruchamiaj + + + Nie uruchamiaj teraz skryptu od tego wydawcy i w przyszłości nadal wyświetlaj monit o uruchomienie tego skryptu. + + + &Uruchom raz + + + Uruchom teraz skrypt od tego wydawcy i w przyszłości nadal wyświetlaj monit o uruchomienie tego skryptu. + + + &Zawsze uruchamiaj + + + Uruchom teraz skrypt od tego wydawcy i nie monituj mnie o uruchomienie tego skryptu w przyszłości. + + + &Wstrzymaj + + + Wstrzymaj bieżący potok i wróć do wiersza polecenia. Gdy skończysz, wpisz wyjście, aby wznowić działanie. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/AuthorizationManagerBase.pl.resx b/src/System.Management.Automation/resources/pl/AuthorizationManagerBase.pl.resx new file mode 100644 index 00000000000..28ac3f33141 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/AuthorizationManagerBase.pl.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 + + + Sprawdzenie elementu AuthorizationManager nie powiodło się. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/AutomationExceptions.pl.resx b/src/System.Management.Automation/resources/pl/AutomationExceptions.pl.resx new file mode 100644 index 00000000000..449cc0566b0 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/AutomationExceptions.pl.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można przetworzyć argumentu, ponieważ wartość argumentu „{0}” jest nieprawidłowa. Zmień wartość argumentu „{0}” i uruchom operację ponownie. + + + Nie można przetworzyć argumentu, ponieważ wartość parametru „{0}” jest nieprawidłowa. Prawidłowe wartości to „Global”, „Local” lub „Script”, albo liczba względna względem bieżącego zakresu (od 0 do liczby zakresów, gdzie 0 oznacza bieżący zakres, a 1 jego element nadrzędny). Zmień wartość parametru „{0}” i uruchom operację ponownie. + + + Nie można przetworzyć argumentu, ponieważ wartość argumentu „{0}” ma wartość null. Zmień wartość argumentu „{0}” na wartość inną niż null. + + + Nie można przetworzyć argumentu, ponieważ wartość argumentu „{0}” jest spoza zakresu. Zmień argument „{0}” na wartość znajdującą się w zakresie. + + + Nie można wykonać operacji, ponieważ operacja „{0}” jest nieprawidłowa. Usuń operację „{0}” albo sprawdź, dlaczego jest nieprawidłowa. + + + Nie można wykonać operacji, ponieważ operacja „{0}” nie jest zaimplementowana. + + + Nie można wykonać operacji, ponieważ operacja „{0}” nie jest obsługiwana. + + + Nie można wykonać operacji, ponieważ obiekt „{0}” został już zwolniony. + + + Nie można wywołać bloku skryptu, ponieważ zawiera on więcej niż jedną klauzulę. Metody Invoke() można używać tylko w blokach skryptu zawierających jedną klauzulę. + + + Nie można przekonwertować bloku skryptu, ponieważ zawiera więcej niż jedną klauzulę. Wyrażenia i struktury sterujące są niedozwolone. Sprawdź, czy blok skryptu zawiera dokładnie jeden potok lub jedno polecenie. + + + Nie można przekonwertować pustego bloku skryptu. Sprawdź, czy blok skryptu zawiera dokładnie jeden potok lub jedno polecenie. + + + Można przekonwertować tylko blok skryptu zawierający dokładnie jeden potok lub jedno polecenie. Wyrażenia i struktury sterujące są niedozwolone. Sprawdź, czy blok skryptu zawiera dokładnie jeden potok lub jedno polecenie. + + + Nie można przekonwertować bloku skryptu zawierającego instrukcję trap najwyższego poziomu. + + + Nie można wygenerować obiektu programu PowerShell dla zmiennych wyłuskania ScriptBlock niezadeklarowanych w bloku param(...). Nazwa niezadeklarowanej zmiennej: {0}. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock oceniającego wyrażenia niestałe. Wyrażenie inne niż stałe: {0}. + + + Nie można wygenerować obiektu programu PowerShell dla obiektu ScriptBlock oceniającego wyrażenia dynamiczne. Wyrażenie dynamiczne: {0}. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock, który próbuje przekazać inne bloki skryptów jako wartości argumentów. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock, który wywołuje potoki, polecenia lub funkcje w celu obliczenia argumentów głównego potoku. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock, który używa dot sourcing. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock, który wywołuje inne bloki skryptu. + + + Nie można przekonwertować bloku skryptu na obiekt programu PowerShell, ponieważ zawiera on zabronione operatory przekierowywania. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock, który nie ma skojarzonego kontekstu operacji. + + + Polecenie zostało zatrzymane przez użytkownika. + + + Obiekt „{0}” ma nieprawidłowy typ do zwrócenia z bloku dynamicparam. Blok dynamicparam musi zwracać wartość $null albo obiekt typu [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + Nie można przekonwertować bloku skryptu na otwarty typ ogólny. Zdefiniuj odpowiedni zamknięty typ ogólny, a następnie spróbuj ponownie. + + + Nie można wygenerować obiektu programu PowerShell dla ScriptBlock, który rozpoczyna potok wyrażeniem. + + + Nie można pobrać wartości zmiennej użycia „$using:{0}”, ponieważ nie została ustawiona w sesji lokalnej. + + + Nie można pobrać wartości wyrażenia Using „{0}” w określonym słowniku zmiennych. Podczas tworzenia wystąpienia programu PowerShell na podstawie bloku skryptu wyrażenie Using nie może zawierać operacji indeksowania ani operacji dostępu do elementu członkowskiego. + + + Kropkowe źródło skompilowanego bloku skryptu + + + Wywołanie bloku skryptu „{0}” w bieżącym zakresie będzie niedozwolone w trybie Constrained Language. Tryb języka skryptu: {1}, tryb języka kontekstu: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CatalogStrings.pl.resx b/src/System.Management.Automation/resources/pl/CatalogStrings.pl.resx new file mode 100644 index 00000000000..3cbd3e5a4e5 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CatalogStrings.pl.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można wygenerować pliku definicji wykazu. + + + Dodawanie pliku „{0}” do wykazu. Ścieżka względna pliku w wykazie to „{1}”. + + + Pomijanie weryfikacji pliku {0} z wykazu. + + + Znaleziono plik {0} w wykazie o wartości skrótu {1}. + + + Ścieżki wykazu zawierają wiele plików o tej samej ścieżce względnej {0}. + + + Znaleziono plik {0} na dysku o wartości skrótu {1}. + + + Pomijanie weryfikacji pliku {0} ze ścieżki. + + + Nie można uzyskać dojścia do kontekstu administratora katalogu dla danego algorytmu wyznaczania wartości skrótu {0}. + + + Nie można utworzyć skrótu dla pliku {0}. + + + Nie można otworzyć pliku wykazu {0}. + + + Wersja wykazu jest nieprawidłowa. Obsługujemy tylko wersję {0} i wersję {1} wykazu. + + + Nie można otworzyć pliku definicji wykazu. + + + Znaleziono wiele wpisów elementu członkowskiego pliku {0} w wykazie. + + + Nie można odnaleźć nazwy pliku lub ścieżki dla elementu członkowskiego wykazu {0}. + + + Nie można odnaleźć pliku {0} dla skrótu. + + + Nie można odczytać pliku {0} w celu obliczenia jego wartości skrótu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CimInstanceTypeAdapterResources.pl.resx b/src/System.Management.Automation/resources/pl/CimInstanceTypeAdapterResources.pl.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CimInstanceTypeAdapterResources.pl.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CmdletizationCoreResources.pl.resx b/src/System.Management.Automation/resources/pl/CmdletizationCoreResources.pl.resx new file mode 100644 index 00000000000..765cae933dd --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CmdletizationCoreResources.pl.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Polecenia cmdlet w ramach klasy „{0}” + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Nie można przetworzyć pliku XML definicji polecenia cmdlet dla następującego pliku: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Nie można przetworzyć atrybutu ObjectModelWrapper. Typ {0} definiuje wiele zestawów parametrów. Sprawdź, czy plik XML definicji polecenia cmdlet określa prawidłowy typ w atrybucie ObjectModelWrapper, i spróbuj ponownie. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Nie można przetworzyć atrybutu ObjectModelWrapper. Typ {0} jest otwartym typem ogólnym. Sprawdź, czy plik XML definicji polecenia cmdlet określa prawidłowy typ w atrybucie ObjectModelWrapper, i spróbuj ponownie. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Nie można przetworzyć atrybutu ObjectModelWrapper. Typ {0} nie pochodzi od następującej klasy: {1}. Sprawdź, czy plik XML definicji polecenia cmdlet określa prawidłowy typ w atrybucie ObjectModelWrapper, i spróbuj ponownie. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Nie można przetworzyć atrybutu ObjectModelWrapper. Typ {0} definiuje parametr polecenia cmdlet {1} z parametrem atrybutu {2}, który jest ignorowany. Sprawdź, czy plik XML definicji polecenia cmdlet określa prawidłowy typ w atrybucie ObjectModelWrapper, i spróbuj ponownie. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Nie można zdefiniować parametru {0} dla polecenia cmdlet {1}. Nazwa parametru jest już zdefiniowana przez klasę {2}. Zmień nazwę parametru w pliku XML definicji polecenia cmdlet i ponów próbę. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Nie można zdefiniować parametru {0} dla polecenia cmdlet {1}. Nazwa parametru jest już zdefiniowana w elemencie XML {2}. Zmień nazwę parametru w pliku XML definicji polecenia cmdlet, a następnie spróbuj ponownie. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + Wartość atrybutu EnumName nie przekłada się na prawidłowy identyfikator języka C#: {0}. Sprawdź atrybut EnumName w pliku XML definicji polecenia cmdlet, a następnie spróbuj ponownie. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Nie można przetworzyć elementu <Enum EnumName="{0}" ... >. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + Komputer zdalny zwrócił nieprawidłowy plik CDXML. Następująca karta polecenia cmdlet nie jest obsługiwana w przypadku importowania modułu CDXML z komputera zdalnego: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CommandBaseStrings.pl.resx b/src/System.Management.Automation/resources/pl/CommandBaseStrings.pl.resx new file mode 100644 index 00000000000..2c4c6fdb256 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CommandBaseStrings.pl.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Kontynuować tę operację? + + + &Tak + + + Kontynuuj, wykonując tylko kolejny krok operacji. + + + Tak w przypadku &Wszystko + + + Kontynuuj, wykonując wszystkie kroki operacji. + + + &Nie + + + Pomiń tę operację i kontynuuj, wykonując następną operację. + + + Nie w przypadku W&szystko + + + Pomiń tę operację i wszystkie kolejne operacje. + + + Zatrzymaj to polecenie. + + + &Zatrzymaj polecenie + + + &Wstrzymaj + + + Wstrzymaj bieżący potok i wróć do wiersza polecenia. Wpisz polecenie „{0}”, aby wznowić potok. + + + + Program „{0}” zakończył działanie z kodem zakończenia innym niż zero: {1} ({2}). + + + Wykonywanie operacji „{0}” w lokalizacji docelowej „{1}”. + + + What If: {0} + + + Czy na pewno chcesz wykonać tę akcję? +{0} + + + Potwierdź + + + Uruchomione polecenie zostało zatrzymane, ponieważ zmienna preferencji „{0}” lub wspólny parametr jest ustawiony na wartość Zatrzymaj: {1} + + + Uruchomione polecenie zostało zatrzymane, ponieważ zmienna preferencji „{0}” lub wspólny parametr jest ustawiony na wartość Zatrzymaj. + + + Uruchomione polecenie zostało zatrzymane, ponieważ zmienna preferencji „{0}” lub wspólny parametr jest ustawiony na następującą wartość, która nie jest prawidłowa: „{1}”. + + + Uruchomione polecenie zostało zatrzymane, ponieważ użytkownik wybrał opcję Zatrzymaj. + + + Uruchomione polecenie zostało zatrzymane, ponieważ użytkownik przerwał je. + + + Nie można bezpośrednio wywoływać poleceń cmdlet pochodzących z polecenia PSCmdlet. + + + Polecenie cmdlet „{0}” nie obsługuje parametru „{1}” w sesji zdalnej. + + + Łączna liczba: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Szacowany łączny koszt: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Nieznana łączna liczba + Reviewed by TArcher on 2010-07-20 + + + polecenie „{0}” + + + Element {0} jest przestarzały. {1} + + + Wywołanie exec nie powiodło się z powodu błędu {0} w przypadku wiersza polecenia: {1} + + + Nie znaleziono polecenia „{0}”. Określone polecenie musi być plikiem wykonywalnym. + + + Sprawdzanie dot-source podczas przetwarzania bloku skryptu + + + Przetwarzanie dot-source dla bloku skryptu „{0}” zakończy się niepowodzeniem w trybie ograniczonego języka, ponieważ jego tryb języka „{1}” nie jest zgodny z bieżącym trybem języka „{2}”. + + + Wyszukiwanie poleceń + + + Polecenie „{0}” w module „{1}” jest niezaufane i nie będzie dostępne w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ConsoleInfoErrorStrings.pl.resx b/src/System.Management.Automation/resources/pl/ConsoleInfoErrorStrings.pl.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ConsoleInfoErrorStrings.pl.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CoreClrStubResources.pl.resx b/src/System.Management.Automation/resources/pl/CoreClrStubResources.pl.resx new file mode 100644 index 00000000000..96cd795fde3 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CoreClrStubResources.pl.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nazwa zmiennej środowiskowej nie może zawierać znaku równości. + + + Nazwa lub wartość zmiennej środowiskowej jest za długa. + + + Pierwszy znak w ciągu to znak zerowy. + + + Ciąg nie może mieć długości zerowej. + + + Nie można uzyskać nazwy komputera. + + + Nie można uzyskać nazwy domeny bieżącego użytkownika. + + + Nieznany błąd „{0}”. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CredUI.pl.resx b/src/System.Management.Automation/resources/pl/CredUI.pl.resx new file mode 100644 index 00000000000..2bd54a40f41 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CredUI.pl.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Żądanie poświadczeń programu PowerShell + + + Wprowadź poświadczenia. + + + Wprowadź poświadczenia. + + + Maksymalna długość podpisu to {0} znaków. + + + Maksymalna długość wiadomości to {0} znaków. + + + Maksymalna długość wartości UserName wynosi {0} znaków. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/Credential.pl.resx b/src/System.Management.Automation/resources/pl/Credential.pl.resx new file mode 100644 index 00000000000..fad78f9e971 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/Credential.pl.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 + + + Nie można serializować poświadczeń. Jeśli to polecenie uruchamia przepływ pracy, nie można utrwalić poświadczeń, ponieważ proces, w którym przepływ pracy jest uruchamiany, nie ma uprawnień do serializacji poświadczeń. + +-- Jeśli przepływ pracy został uruchomiony w sesji PSSession na komputerze lokalnym, dodaj parametr EnableNetworkAccess do polecenia, które utworzyło sesję. +-- Jeśli przepływ pracy został uruchomiony w sesji PSSession na komputerze zdalnym, dodaj parametr Authentication z wartością CredSSP do polecenia, które utworzyło sesję. Możesz też nawiązać połączenie z konfiguracją sesji, która ma wartość właściwości RunAsUser. + + + Wartość parametru UserName ma niepoprawny format. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/CredentialAttributeStrings.pl.resx b/src/System.Management.Automation/resources/pl/CredentialAttributeStrings.pl.resx new file mode 100644 index 00000000000..1ce85381a85 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/CredentialAttributeStrings.pl.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 + + + Żądanie poświadczeń programu PowerShell + + + Wprowadź poświadczenia. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/DebuggerStrings.pl.resx b/src/System.Management.Automation/resources/pl/DebuggerStrings.pl.resx new file mode 100644 index 00000000000..07e2240c69c --- /dev/null +++ b/src/System.Management.Automation/resources/pl/DebuggerStrings.pl.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Zmienny punkt przerwania na „${0}” ({1} dostęp) + + + Zmienny punkt przerwania w „{0}:${1}” ({2} dostęp) + + + Punkt przerwania wiersza w „{0}:{1}” + + + Punkt przerwania wiersza w „{0}:{1}, {2}” + + + Punkt przerwania polecenia na „{0}” + + + Punkt przerwania polecenia na „{0}:{1}” + + + Punkt przerwania {0} nie zostanie osiągnięty + + + {0}, {1,-16} Pojedynczy krok (wkrocz do funkcji, skryptów itp.) + + + {0}, {1,-16} Krok do następnej instrukcji (przekrocz funkcje, skrypty itp.) + + + {0}, {1,-16} Wyjdź z bieżącej funkcji, skryptu itp. + + + {0}, {1,-16} Kontynuuj operację + + + {0}, {1,-16} Zatrzymaj operację i zamknij debuger + + + {0}, Stos wywołań wyświetlania Get-PSCallStack + + + {0}, {1,-16} Wyświetl kod źródłowy bieżącego skryptu. + + + Użyj polecenia „list”, aby rozpocząć od aktualnego wiersza, „list <m>” + + + aby rozpocząć od wiersza <m>, a polecenie „list <m> <n>” służy do wyświetlenia <n> + + + wiersze rozpoczynające się od wiersza <m> + + + <enter> Powtórz ostatnie polecenie, jeśli było to {0}, {1} lub {2} + + + {0}, {1,-16} wyświetla ten komunikat pomocy. + + + Aby uzyskać instrukcje dotyczące dostosowywania wiersza poleceń debuggera, wpisz „help about_prompt”. + + + +Bieżąca sesja nie obsługuje debugowania; operacja będzie kontynuowana. + + + + + {0}: wiersz {1} + + + Brak dostępnego kodu źródłowego. + + + Wartość początkowa musi być dodatnią liczbą całkowitą nie większą niż {0} + + + Liczba wierszy musi być dodatnią liczbą całkowitą. + + + <No file> + + + w {0}, {1}: wiersz {2} + + + Debugger nie może przetwarzać poleceń, dopóki nie znajduje się w stanie „Zatrzymany”. + + + Element SetDebugAction nie jest zaimplementowany dla debugera skryptu lokalnego. + + + Debuger nie może ustawić akcji wznowienia, ponieważ debuger w sesji zdalnej nie znajduje się w stanie zatrzymania. + + + Nie można debugować zadania, ponieważ debuger jest obecnie zajęty. + + + Przeanalizowano podane zadanie oraz wszystkie zadania podrzędne, ale nie znaleziono żadnych zadań, które można by poddać debugowaniu. Aby przeprowadzić debugowanie zadania lub zadania podrzędnego, zadanie to musi obsługiwać funkcję debugowania i znajdować się w stanie uruchomienia. + + + Nie można włączyć debugera w trybie krokowym, ponieważ debuger jest wyłączony, a tryb debugowania ustawiono na „Brak”. + + + Nie można debugować obszaru działania, ponieważ debuger hosta jest obecnie zajęty. + + + Nie można debugować obszaru działania. Debugger obszaru działania jest obecnie wyłączony (wartość DebugMode to „None”). + + + Nie można debugować obszaru działania, który nie jest w stanie Otwórz. Stan obszaru działania to {0}. + + + Nie można debugować obszaru działania. Obszar działania{0} nie ma skojarzonego debugera. + + + Debuger został już zastąpiony. + + + Nie można wypchnąć obiektu debugera do samego siebie. + + + Polecenie {0} nie jest obsługiwane w przypadku użycia zdalnego w wersji programu PowerShell uruchomionej w zdalnym obszarze działania. + + + Proces + + + {0}, {1,-16} Kontynuuj działanie i odłącz debuger. + + + Polecenie odłączenia debugera nie ma zastosowania. Polecenie „detach” ma zastosowanie wyłącznie podczas debugowania zadań i przestrzeni uruchomieniowych za pomocą poleceń cmdlet „Debug-Job” lub „Debug-Runspace”. + + + Nieprawidłowy identyfikator obszaru uruchamiania: {0} + + + Nie udało się uzyskać dostępu do obszaru działania. + + + Należy określić punkt przerwania lub listę punktów przerwania. + + + Lista punktów przerwania zawierała element, który nie był punktem przerwania. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/DescriptionsStrings.pl.resx b/src/System.Management.Automation/resources/pl/DescriptionsStrings.pl.resx new file mode 100644 index 00000000000..26437954488 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/DescriptionsStrings.pl.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 + + + Element {0} nie może mieć wartości null ani być pusty. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/DiscoveryExceptions.pl.resx b/src/System.Management.Automation/resources/pl/DiscoveryExceptions.pl.resx new file mode 100644 index 00000000000..bcba509b120 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/DiscoveryExceptions.pl.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 + + + Nie można sprawdzić poprawności nazwy polecenia cmdlet „{0}”, ponieważ ma ona niepoprawny format. Nazwy poleceń cmdlet muszą zawierać czasownik i rzeczownik oddzielony znakiem „-”, na przykład „Get-Process”. + + + Parametr „{0}” jest wielokrotnie zadeklarowany w zestawie parametrów „{1}”. + + + Alias „{0}” jest deklarowany wiele razy. + + + Nie można zadeklarować parametru. Parametry mogą być deklarowane tylko w polach i właściwościach. + + + Nie można przetworzyć polecenia cmdlet. Nazwa polecenia cmdlet musi składać się z pary czasowników i rzeczowników rozdzielonych znakiem „-”. + + + Termin „{0}” nie jest rozpoznawany jako nazwa polecenia cmdlet, funkcji, pliku skryptu lub programu wykonywalnego. +Sprawdź pisownię nazwy lub sprawdź, czy ścieżka została dołączona, sprawdź, czy ścieżka jest poprawna, i spróbuj ponownie. + + + Argument „{0}” nie jest rozpoznawany jako polecenie cmdlet: {1} + + + Argument „{0}” nie jest rozpoznawany jako polecenie cmdlet, prawdopodobnie dlatego, że nie pochodzi od klas cmdlet lub PSCmdlet: {1} + + + Nie można rozpoznać aliasu „{0}”, ponieważ odwołuje się on do terminu „{1}”, który nie jest rozpoznawany jako polecenie cmdlet, funkcja, program wykonywalny lub plik skryptu. Sprawdź termin i spróbuj ponownie. + + + Nie można przetworzyć parametru „{0}” o wartości „{1}”, ponieważ nie jest on poleceniem cmdlet i nie może zostać przetworzony przez element CommandProcessor. + + + Polecenie cmdlet o nazwie „{0}” już istnieje. Polecenia cmdlet muszą mieć unikatowe nazwy. + + + Dostawca poleceń cmdlet o nazwie „{0}” już istnieje. Dostawcy poleceń cmdlet muszą mieć unikatowe nazwy. + + + Zestaw o nazwie „{0}” już istnieje. Zestawy muszą mieć unikatowe nazwy. + + + Skrypt o nazwie „{0}” już istnieje. Skrypty muszą mieć unikatowe nazwy. + + + Nie można przetworzyć instrukcji #requires, ponieważ ma ona niepoprawny format. +Instrukcja #requires musi mieć jeden z następujących formatów: + „#requires -shellid <shellID>” + „#requires -version <major.minor>” + „#requires -psedition <edition>” + „#requires -pssnapin <psSnapInName> [-version <major.minor>]” + „#requires -modules <ModuleSpecification>” + „#requires -runasadministrator” + + + Nie można uruchomić skryptu „{0}”, ponieważ zawierał instrukcję „#requires” o identyfikatorze powłoki {1}, która jest niezgodna z bieżącą powłoką. Aby uruchomić ten skrypt, musisz użyć powłoki znajdującej się w lokalizacji „{2}”. + + + Nie można uruchomić skryptu „{0}”, ponieważ zawierał instrukcję „#requires” o identyfikatorze powłoki {1}, która jest niezgodna z bieżącą powłoką. + + + Nie można uruchomić skryptu „{0}”, ponieważ zawiera on instrukcję „#requires” dla programu PowerShell {1}. Wersja programu PowerShell wymagana przez skrypt jest niezgodna z aktualnie uruchomioną wersją programu PowerShell {2}. + + + Nie można uruchomić skryptu „{0}”, ponieważ zawierał instrukcję „#requires” dla wersji programu PowerShell „{1}”. Wersja programu PowerShell wymagana przez skrypt jest niezgodna z aktualnie uruchomioną wersją programu PowerShell {2}. + + + Nie można uruchomić skryptu „{0}”, ponieważ brakuje następujących przystawek określonych przez instrukcje „#requires” skryptu: {1}. + + + Instrukcja #requires określiła tylko identyfikator shellID. Instrukcje #Requires muszą określać wymaganą przystawkę programu PowerShell podczas uruchamiania w programie PowerShell. + + + Nie można uruchomić skryptu „{0}”, ponieważ zawiera on instrukcję „#requires” służącą do uruchamiania jako administrator. Bieżąca sesja programu PowerShell nie jest uruchomiona jako administrator. Uruchom program PowerShell przy użyciu opcji Uruchom jako administrator, a następnie spróbuj ponownie uruchomić skrypt. + + + {0} (Wersja {1}) + + + Nie można pobrać polecenia, ponieważ parametr ArgumentList można określić tylko podczas pobierania pojedynczego polecenia cmdlet lub skryptu. + + + Nazwa parametru „{0}” jest zarezerwowana do użycia w przyszłości. + + + Nie można uruchomić skryptu „{0}”, ponieważ brakuje następujących modułów określonych przez instrukcje „#requires” skryptu: {1}. + + + Znaleziono polecenie „{0}” w module „{1}”, ale nie można załadować modułu. Aby uzyskać więcej informacji, uruchom polecenie „Import-Module {1}”. + + + W module „{1}” znaleziono polecenie „{0}”, ale nie można załadować modułu z powodu następującego błędu: [{2}] +Aby uzyskać więcej informacji, uruchom polecenie „Import-Module {1}”. + + + Nie można załadować modułu „{0}”. Aby uzyskać więcej informacji, uruchom polecenie „Import-Module {0}”. + + + Żadne pasujące polecenia nie zawierają parametru o nazwie „{0}”. Sprawdź pisownię nazwy parametru, a następnie spróbuj ponownie. + + + Nie można wykonać polecenia dot-source, ponieważ zostało ono zdefiniowane w innym trybie języka. Aby wywołać to polecenie bez importowania jego zawartości, pomiń operator „.”. + + + Nie można jednocześnie określić parametrów ShowCommandInfo i Syntax. + + + To polecenie skryptu jest wyłączone, gdy funkcja eksperymentalna „{0}” została włączona. + + + To polecenie skryptu jest wyłączone, gdy funkcja eksperymentalna „{0}” została wyłączona. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/EnumExpressionEvaluatorStrings.pl.resx b/src/System.Management.Automation/resources/pl/EnumExpressionEvaluatorStrings.pl.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/pl/EnumExpressionEvaluatorStrings.pl.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ErrorCategoryStrings.pl.resx b/src/System.Management.Automation/resources/pl/ErrorCategoryStrings.pl.resx new file mode 100644 index 00000000000..0099346bb57 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ErrorCategoryStrings.pl.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Wykryto zakleszczenie: ({1}:{2}) [{0}], {3} + + + Błąd urządzenia: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + Błąd analizatora: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + Błąd składni: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Nierozpoznana kategoria błędu {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ErrorPackage.pl.resx b/src/System.Management.Automation/resources/pl/ErrorPackage.pl.resx new file mode 100644 index 00000000000..016a6eb83e1 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ErrorPackage.pl.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 + + + {0}…{1} + + + Tekst błędu jest pusty dla błędu „{0}”: „{1}” + + + Obiekt „{0}” jest zgłaszany jako błąd. + + + Wartość {0} nie jest obsługiwana dla zmiennej ActionPreference. Podanej wartości należy używać tylko jako wartości parametru preferencji i została ona zastąpiona wartością domyślną. Aby uzyskać więcej informacji, zobacz temat Pomocy „about_Preference_Variables”. + + + Wartość {0} ActionPreference jest zarezerwowana do użycia w przyszłości i nie jest obecnie obsługiwana. Aby uzyskać więcej informacji na temat zmiennych preferencji, zobacz temat Pomocy „about_Preference_Variables”. + + + Wartość {0} ActionPreference jest zarezerwowana do użycia w przyszłości i nie jest obecnie obsługiwana. Została zastąpiona w zmiennej {1} domyślną wartością {2}. Aby uzyskać więcej informacji na temat zmiennych preferencji, zobacz temat Pomocy „about_Preference_Variables”. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/EtwLoggingStrings.pl.resx b/src/System.Management.Automation/resources/pl/EtwLoggingStrings.pl.resx new file mode 100644 index 00000000000..6384f5de2d2 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/EtwLoggingStrings.pl.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Polecenie {0} jest {1}. + + + Zmieniono stan aparatu z {0} na {1}. + + + W pełni kwalifikowany identyfikator błędu = {0} + + + Komunikat o błędzie = {0} + + + Zalecana akcja = {0} + + + Zasady wykonywania + + + Polecenie zadania = {0} + + + Identyfikator zadania = {0} + + + Identyfikator wystąpienia zadania = {0} + + + Lokalizacja zadania = {0} + + + Nazwa zadania = {0} + + + Stan zadania = {0} + + + Nazwa polecenia = + + + Ścieżka polecenia = + + + Typ polecenia = + + + Wersja aparatu = + + + Identyfikator hosta = + + + Nazwa hosta = + + + Aplikacja hosta = + + + Wersja hosta = + + + Identyfikator potoku = + + + Identyfikator obszaru uruchamiania = + + + Nazwa skryptu = + + + Numer sekwencji = + + + Ważność = + + + Identyfikator powłoki = + + + Czas = + + + Użytkownik = + + + Połączony użytkownik = + + + Zadanie o wartości NULL + + + Nazwa dostawcy + + + Dostawca {0} zmienił stan na {1}. + + + Wykonywanie skryptu jest {0}. + + + Zmienna {0} została zmieniona z {1} na {2}. + + + Zmienna {0} zmieniona na {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/EventResource.pl.resx b/src/System.Management.Automation/resources/pl/EventResource.pl.resx new file mode 100644 index 00000000000..4cdedecc764 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/EventResource.pl.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie znaleziono komunikatu dla identyfikatora zdarzenia PowerShell.Core.Instrumentation.man. + + + Zaplanowane zadanie {0} rozpoczęte o {1} + + + + Zaplanowane zadanie {0} zakończone o {1} ze stanem {2} + + + + Wyjątek zaplanowanego zadania {0}: + Wiadomość: {1} + Ślad stosu: {2} + InnerException: {3} + + + + Inicjowanie funkcji eksperymentalnej: zignoruj funkcję eksperymentalną „{0}” z pliku konfiguracji. {1} + + + Inicjowanie funkcji eksperymentalnej: nie można odczytać pliku konfiguracji. + Wyjątek: {0} + Wiadomość: {1} + Ślad stosu: {2} + + + + Załadowano wtyczkę przepływu pracy. + EndpointName: {0} + Użytkownik: {1} + HostingMode: {2} + Protokół: {3} + Konfiguracja: + {4} + + + Rozpoczęto wykonywanie przepływu pracy. + WorkflowId: {0} + ManagedNodes: {1} + + + Zmieniono stan przepływu pracy. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + Zażądano zamknięcia wtyczki przepływu pracy. + EndpointName: {0} + + + Wtyczka przepływu pracy została uruchomiona ponownie. + EndpointName: {0} + + + Przepływ pracy jest wznawiany. + WorkflowId: {0} + + + Przekroczono limit przydziału ustawiony dla punktu końcowego. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + Przepływ pracy został wznowiony. + WorkflowId: {0} + + + Utworzono pulę obszarów działania przepływów pracy. + WorkflowId: {0} + ManagedNode: {1} + + + Działanie zostało umieszczone w kolejce do wykonania. + WorkflowId: {0} + ActivityName: {1} + + + Rozpoczęto wykonywanie aktywności. + ActivityName: {0} + ActivityTypeName: {1} + + + Przepływ pracy jest importowany z pliku XAML. + WorkflowId: {0} + XamlFile: {1} + + + Przepływ pracy został zaimportowany z pliku XAML. + WorkflowId: {0} + XamlFile: {1} + + + Nie można zaimportować przepływu pracy z pliku XAML z powodu błędu. + WorkflowId: {0} + ErrorDescription: {1} + + + Rozpoczęto weryfikację przepływu pracy. + WorkflowId: {0} + + + Weryfikacja przepływu pracy zakończyła się powodzeniem. + WorkflowId: {0} + + + Weryfikacja przepływu pracy zakończyła się niepowodzeniem z powodu błędu. + WorkflowId: {0} + + + Działanie przepływu pracy zostało zweryfikowane. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Nie można zweryfikować działania przepływu pracy. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Wykonanie aktywności zakończyło się niepowodzeniem. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Zmieniono dostępność obszaru działania. + RunspaceId: {0} + Dostępność: {1} + + + Stan obszaru działania zmieniono. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Przepływ pracy został załadowany do wykonania. + WorkflowId: {0} + + + Przepływ pracy został zwolniony. + WorkflowId: {0} + + + Wykonywanie przepływu pracy zostało anulowane. + WorkflowId: {0} + + + Przerwano wykonywanie przepływu pracy. + WorkflowId: {0} + + + Wykonano czyszczenie przepływu pracy. + WorkflowId: {0} + + + Załadowano utrwalony przepływ pracy z dysku. + WorkflowId: {0} + Ścieżka: {1} + + + Dane przepływu pracy zostały usunięte z dysku. + WorkflowId: {0} + Ścieżka: {1} + + + Rozpoczynanie usuwania zadania. + JobId: {0} + + + Zmieniono stan zadania. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Błąd zadania. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Utworzono zadanie dla przepływu pracy (zadanie podrzędne). + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Utworzono zadanie nadrzędne dla przepływu pracy. + JobId: {0} + + + Utworzono wszystkie wymagane zadania na potrzeby wykonywania przepływu pracy. + JobId: {0} + WorkflowId: {1} + + + Usunięto zadanie podrzędne dla przepływu pracy. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + Wystąpił błąd podczas usuwania zadania. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Błąd: {3} + + + Ładowanie przepływu pracy do wykonania. + WorkflowId: {0} + + + Wykonywanie przepływu pracy zostało zakończone. + WorkflowId: {0} + + + Anulowanie wykonywania przepływu pracy. + WorkflowId: {0} + + + Przerywanie wykonywania przepływu pracy. + WorkflowId: {0} + Przyczyna: {1} + + + Zwalnianie przepływu pracy. + WorkflowId: {0} + + + Rozpoczęto wymuszone zamykanie przepływu pracy. + WorkflowId: {0} + + + Zakończono wymuszone zamykanie przepływu pracy. + WorkflowId: {0} + + + Wystąpił błąd podczas wymuszonego zamykania przepływu pracy. + WorkflowId: {0} + ErrorDescription: {1} + + + Trwały przepływ pracy na dysku. + WorkflowId: {0} + PersistPath: {1} + + + Przepływ pracy został zapisany na dysku. + WorkflowId: {0} + + + Zakończono wykonywanie działania. + ActivityName: {0} + + + Błąd wykonywania przepływu pracy. + WorkflowId: {0} + ErrorDescription: {1} + + + Zarejestrowano nowy punkt końcowy programu PowerShell. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Zmodyfikowano konfigurację punktu końcowego. + EndpointName: {0} + ModifiedBy: {1} + + + Wyrejestrowano konfigurację punktu końcowego. + EndpointName: {0} + UnregisteredBy: {1} + + + Wyłączono konfigurację punktu końcowego. + EndpointName: {0} + DisabledBy: {1} + + + Konfiguracja punktu końcowego włączona. + EndpointName: {0} + EnabledBy: {1} + + + Uruchomiono obszar działania poza procesem. + Polecenie: {0} + + + Podczas wykonywania przepływu pracy zastosowano metodę splatting dla parametrów. + Parametry: {0} + Komputery: {1} + + + Silnik przepływu pracy został uruchomiony. + EndpointName: {0} + + + Wystąpienie menedżera przepływów pracy utworzone przy użyciu + CheckpointPath: {0} + ConfigProviderId: {1} + Nazwy użytkownika: {2} + Ścieżki: {3} + + + Nazwa komputera $null lub . jest rozpoznawana jako host lokalny + + + Rozpoznawanie domyślnego schematu HTTP + + + Nazwa zdalnej powłoki została rozpoznana jako domyślny element PowerShellCore + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + Tworzenie tekstu Scriptblock ({0} z {1}): +{2} + +Identyfikator ScriptBlock: {3} +Ścieżka: {4} + + + Rozpoczęto wywołanie obiektu ScriptBlock o identyfikatorze: {0} +Identyfikator obszaru działania: {1} + + + Zakończono wywołanie obiektu ScriptBlock o identyfikatorze: {0} +Identyfikator obszaru działania: {1} + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + {2} + +Kontekst: +{0} + +Dane użytkownika: +{1} + + + + Korelowanie identyfikatorów aktywności. + CurrentActivityId: {0} + ParentActivityId: {1} + + + Nazwa klasy = {0} +Nazwa metody = {1} +Identyfikator GUID przepływu pracy = {2} +Wiadomość = {3} +{4} +Nazwa działania = {5} +Identyfikator GUID działania = {6} +Parametry = {7} + + + Tworzenie obiektu obszaru działania + Identyfikator wystąpienia: {0} + + + Tworzenie obiektu RunspacePool + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Otwieranie elementu RunspacePool + + + Modyfikowanie identyfikatora aktywności i korelowanie + + + Stan obszaru działania zmieniono na {0} + + + Trwa próba ponowienia utworzenia sesji {0} o kodzie błędu {1} dla identyfikatora sesji {2} + + + Program PowerShell uruchomił wątek nasłuchiwania IPC dla procesu: {0} w domenie aplikacji: {1}. + + + Program PowerShell zakończył wątek nasłuchiwania IPC dla procesu: {0} w domenie aplikacji: {1}. + + + W wątku nasłuchiwania IPC programu PowerShell w procesie: {0} w domenie aplikacji: {1} wystąpił błąd. Komunikat o błędzie: {2}. + + + Łączenie protokołu IPC programu PowerShell dla procesu: {0} w domenie aplikacji: {1} dla użytkownika: {2}. + + + Rozłączenie protokołu IPC programu PowerShell dla procesu: {0} w domenie aplikacji: {1} dla użytkownika: {2}. + + + Port rozpoznany jako {0} + + + Nazwa aplikacji rozpoznana jako {0} + + + Element ComputerName rozpoznany jako {0} + + + Schemat to {0} + + + Testuj wiadomość analityczną + + + Parametry połączenia to + Identyfikator URI połączenia: {0} + Identyfikator URI zasobu: {1} + Użytkownik: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Odcisk palca: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Modyfikowanie identyfikatora aktywności i korelowanie + + + Odebrano obiekt o identyfikatorze obszaru roboczego: {0} Identyfikator polecenia: {1} Element docelowy: {2} Typ danych: {3} Interfejs docelowy: {4} + + + Wystąpił nieobsługiwany wyjątek w domenie aplikacji. +Typ wyjątku: {0} +Komunikat o wyjątku: {1} +Ślad stosu wyjątku: {2} + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Usługa WSMan zgłosiła błąd o kodzie: {2}. + Komunikat o błędzie: {3} + Ślad stosu: {4} + + + Wystąpił nieobsługiwany wyjątek w domenie aplikacji. +Typ wyjątku: {0} +Komunikat o wyjątku: {1} +Ślad stosu wyjątku: {2} + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Usługa WSMan zgłosiła błąd o kodzie: {2}. + Komunikat o błędzie: {3} + Ślad stosu: {4} + + + Identyfikator obszaru działania {0}. Nawiązywanie połączenia przy użyciu polecenia WSMan Create Shell + + + Identyfikator obszaru działania {0}. Odebrano wywołanie zwrotne dla polecenia WSMan Create Shell + + + Identyfikator obszaru działania: {0}. Zamykanie powłoki przy użyciu WSManCloseShell + + + Identyfikator obszaru działania: {0}. Odebrano wywołanie zwrotne dla WSManCloseShell + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Wysyłanie danych o rozmiarze {2} + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Odebrano wywołanie zwrotne dla polecenia WSManSendShellInputEx + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Wysyłanie żądania odbioru przy użyciu polecenia WSManReceiveShellOutputEx + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Odebrano dane o rozmiarze {2}. + + + Identyfikator obszaru działania {0} identyfikator potoku {1}. Nawiązywanie połączenia polecenia przy użyciu polecenia WSManRunShellCommandEx + + + Identyfikator obszaru działania {0} identyfikator potoku {1}. Odebrano wywołanie zwrotne dla połączenia polecenia + + + Identyfikator obszaru działania: {0} identyfikator potoku {1}. Zamykanie transportu dla polecenia + + + Identyfikator obszaru działania: {0} identyfikator potoku {1}. Odebrano wywołanie zwrotne dla polecenia zamknięcia + + + Identyfikator obszaru działania: {0} identyfikator potoku {1}. Wysyłanie sygnału z kodem {2} przy użyciu WSManSignalShellEx + + + Identyfikator obszaru działania: {0} identyfikator potoku {1}. Odebrano wywołanie zwrotne dla polecenia WSManSignalShellEx + + + Identyfikator obszaru działania: {0}. Połączenie jest przekierowywane do identyfikatora URI: {1} + + + Identyfikator obszaru działania: {0} identyfikator potoku: {1}. Serwer wysyła do klienta dane o rozmiarze {2}. Typ danych: {3} TargetInterface: {4} + + + Żądanie {0}. Tworzenie zdalnej sesji serwera. Nazwa użytkownika: {1} Niestandardowy identyfikator powłoki: {2} + + + Raportowanie kontekstu dla żądania: {0} Zgłoszony kontekst: {0} + + + Operacja raportowania zakończona dla żądania: {0} + Kod błędu: {1} + Komunikat o błędzie: {2} + Ślad stosu: {3} + + + Kontekst powłoki {0}. Identyfikator żądania {1}. Tworzenie wspólnej sesji do uruchamiania polecenia. + + + Kontekst powłoki {0} Kontekst polecenia {1} Identyfikator żądania {2}. Zatrzymywanie polecenia. + + + Kontekst powłoki {0} Kontekst polecenia {1} Identyfikator żądania {2}. Odebrano dane od klienta. + + + Kontekst powłoki {0} Kontekst polecenia {1} Identyfikator żądania {2}. Klient wysłał żądanie odbioru, aby serwer mógł wysłać dane. + + + Kontekst powłoki {0} Kontekst polecenia {1} IsReceiveOperation {2}. Odebrano żądanie zamknięcia. + + + Ładowanie zestawu {0} dla niestandardowej powłoki z identyfikatorem powłoki {1} + + + Ładowanie typu {0} dla niestandardowej powłoki z identyfikatorem powłoki {1} + + + Odebrano fragment komunikacji zdalnej. + Identyfikator obiektu: {0} + Identyfikator fragmentu: {1} + Flaga początkowa: {2} + Flaga końcowa: {3} + Długość ładunku: {4} + Dane ładunku: {5} + + + Wysłano fragment komunikacji zdalnej. + Identyfikator obiektu: {0} + Identyfikator fragmentu: {1} + Flaga początkowa: {2} + Flaga końcowa: {3} + Długość ładunku: {4} + Dane ładunku: {5} + + + Zamykanie usługi WinRM. + + + Pomyślnie przywrócono obiekt. + Nazwa typu po deserializacji: {0} + Przywrócono przez rzutowanie na typ: {1} + Przywrócony obiekt ma typ: {2} + + + Nie można przywrócić obiektu. + Nazwa typu po deserializacji: {0} + Przywrócono przez rzutowanie na typ: {1} + Wyjątek rzutowania typu: {2} + Wewnętrzny wyjątek rzutowania typu: {3} + + + Głębokość serializacji została zastąpiona. + Nazwa typu po serializacji: {0} + Oryginalna głębokość: {1} + Zastąpiona głębokość: {2} + Bieżąca głębokość poniżej najwyższego poziomu: {3} + + + Tryb serializacji został zastąpiony. + Nazwa typu po serializacji: {0} + Zastąpiony tryb: {1} + + + Serializacja właściwości skryptu została pominięta, ponieważ nie ma obszaru roboczego, którego można użyć do oceny właściwości. + Nazwa właściwości: {0} + Nazwa typu właściciela właściwości: {1} + Skrypt metody pobierającej: {2} + + + Serializacja właściwości została pominięta, ponieważ pobranie właściwości zakończyło się niepowodzeniem. + Nazwa właściwości: {0} + Nazwa typu właściciela właściwości: {1} + Wyjątek z metody pobierającej właściwość: {2} + Wyjątek wewnętrzny z metody pobierającej właściwość: {3} + + + Serializacja obiektu wyliczanego może nie być kompletna, ponieważ obiekt wyliczany zgłosił wyjątek. + Typ obiektu wyliczanego: {0} + Wyjątek:{1} + + + Serializacja wywołała metodę ToString obiektu, która zakończyła się niepowodzeniem. + Typ obiektu: {0} + Wyjątek:{1} + + + Osiągnięto maksymalną głębokość poniżej najwyższego poziomu, więc obiekt zostanie zapisany w postaci ciągów. + Typ obiektu przy maksymalnej głębokości: {0} + Nazwa właściwości przy maksymalnej głębokości: {1} + Głębokość: {2} + + + Deserializator zgłosił wyjątek XmlException (najprawdopodobniej wskazuje to na niepoprawny format clixml). + Numer wiersza: {0} Pozycja wiersza: {1} + Wyjątek:{2} + + + Serializacja określonych właściwości zakończyła się niepowodzeniem, ponieważ brakuje jednej ze wskazanych właściwości. + Typ obiektu: {0} + Nazwa właściwości: {1} + + + Trwa uruchamianie konsoli programu PowerShell + + + Konsola programu PowerShell jest gotowa na dane wejściowe użytkownika + + + {0} + + + Rekord błędu śledzenia: + Wiadomość: {0} + CategoryInfo.Kategoria: {1} + CategoryInfo.Przyczyna : {2} + CategoryInfo.Nazwa docelowa : {3} + FullyQualifiedErrorId: {4} + Szczegóły wyjątku: + Wiadomość : {5} + Ślad stosu: {6} + InnerException {7} + + + + Wyjątek: + Wiadomość: {0} + StackTrace: {1} + InnerException : {2} + + + + Śledzenie obiektu PSObject + + + Zadanie śledzenia: + Identyfikator: {0} + InstanceId: {1} + Nazwa: {2} + Lokalizacja: {3} + Stan: {4} + Polecenie: {5} + + + + Informacje śledzenia: + {0} + + + Informacje śledzenia: + {0} {1} + + + POCZĄTEK ImportWorkflowCommand::StartWorkflowApplication. Rozpoczynanie wywołania funkcji przepływu pracy. Identyfikator GUID śledzenia {0} + + + KONIEC ImportWorkflowCommand::StartWorkflowApplication. Kończenie wywołania funkcji przepływu pracy. Identyfikator GUID śledzenia {0} + + + POCZĄTEK Tworzenie nowego zadania w poleceniu ImportWorkflowCommand::StartWorkflowApplication. Identyfikator GUID śledzenia {0} + + + KONIEC Tworzenie nowego zadania w poleceniu ImportWorkflowCommand::StartWorkflowApplication. Identyfikator GUID śledzenia {0} + + + KONIEC Tworzenie nowego zadania w poleceniu ImportWorkflowCommand::StartWorkflowApplication. Identyfikator GUID śledzenia {0} : identyfikator GUID zadania nadrzędnego ContainerParentJob {1} + + + POCZĄTEK Identyfikator GUID zadania JobLogic ContainerParentJob {0} + + + KONIEC Identyfikator GUID zadania JobLogic ContainerParentJob {0} + + + POCZĄTEK identyfikatora GUID WorkflowExecution ContainerParentJob {0} + + + KONIEC identyfikatora GUID WorkflowExecution ContainerParentJob {0} + + + Zadanie WorkflowJob z identyfikatorem GUID {0} dodane do zadania ContainerParentJob z identyfikatorem GUID {1} + + + Zadanie ProxyJob o identyfikatorze GUID {0} skojarzone ze zdalnym zadaniem nadrzędnym ContainerParentJob o identyfikatorze GUID {1} + + + POCZĄTEK wykonywania zadania ContainerParentJob o identyfikatorze GUID{0} + + + KONIEC wykonywania zadania ContainerParentJob o identyfikatorze GUID{0} + + + POCZĄTEK wykonywania zadania serwera proxy o identyfikatorze GUID {0} + + + KONIEC wykonywania zadania serwera proxy o identyfikatorze GUID {0} + + + POCZĄTEK Obsługa zdarzenia StateChanged dla zadania serwera proxy z identyfikatorem GUID {0} + + + KONIEC Obsługa zdarzenia StateChanged dla zadania serwera proxy z identyfikatorem GUID {0} + + + POCZĄTEK Obsługa zdarzenia StateChanged dla podrzędnego zadania serwera proxy z identyfikatorem GUID {0} + + + KONIEC Obsługa zdarzenia StateChanged dla podrzędnego zadania serwera proxy z identyfikatorem GUID {0} + + + POCZĄTEK Uruchamianie zbierania nieużywanych zasobów + + + KONIEC Uruchamianie zbierania nieużywanych zasobów + + + Magazyn stanów trwałych osiągnął maksymalny określony rozmiar + + + Program Windows PowerShell ISE rozpoczął uruchamianie pliku skryptu {0}. + + + Program Windows PowerShell ISE rozpoczął uruchamianie skryptu wybranego przez użytkownika z pliku {0}. + + + Program Windows PowerShell ISE zatrzymuje bieżące polecenie. + + + Program Windows PowerShell ISE wznawia debuger. + + + Program Windows PowerShell ISE zatrzymuje debuger. + + + Program Windows PowerShell ISE wchodzi w debugowanie. + + + Program Windows PowerShell ISE wychodzi z debugowania. + + + Program Windows PowerShell ISE wychodzi z debugowania. + + + Program Windows PowerShell ISE włącza wszystkie punkty przerwania. + + + Program Windows PowerShell ISE wyłącza wszystkie punkty przerwania. + + + Program Windows PowerShell ISE usuwa wszystkie punkty przerwania. + + + Program Windows PowerShell ISE ustawia punkt przerwania w wierszu #: {0} pliku {1}. + + + Program Windows PowerShell ISE przenosi punkt przerwania w wierszu #: {0} pliku {1}. + + + Program Windows PowerShell ISE włącza punkt przerwania w wierszu #: {0} pliku {1}. + + + Program Windows PowerShell ISE wyłącza punkt przerwania w wierszu #: {0} pliku {1}. + + + Program Windows PowerShell ISE napotkał punkt przerwania w wierszu #: {0} pliku {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/EventingResources.pl.resx b/src/System.Management.Automation/resources/pl/EventingResources.pl.resx new file mode 100644 index 00000000000..919594ac34b --- /dev/null +++ b/src/System.Management.Automation/resources/pl/EventingResources.pl.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można zarejestrować się dla określonego zdarzenia. Zdarzenia wymagające wartości zwracanej nie są obsługiwane. + + + Nie można zarejestrować się dla określonego zdarzenia. Zdarzenie o nazwie „{0}” nie istnieje. + + + Program PowerShell nie może subskrybować zdarzeń w systemie Windows RT. + + + Nie można zarejestrować się dla określonego zdarzenia. Identyfikator źródła zdarzenia „{0}” jest zarezerwowany dla aparatu programu PowerShell. + + + Ta operacja nie jest obsługiwana w wystąpieniach zdalnych. + + + Ta akcja nie jest obsługiwana podczas przekazywania zdarzeń dalej. + + + Nie można zasubskrybować określonego zdarzenia. Subskrybent o identyfikatorze źródła „{0}” już istnieje. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ExperimentalFeatureStrings.pl.resx b/src/System.Management.Automation/resources/pl/ExperimentalFeatureStrings.pl.resx new file mode 100644 index 00000000000..c8b6edc440f --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ExperimentalFeatureStrings.pl.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie znaleziono funkcji eksperymentalnej o nazwie „{0}”. + + + Włączenie i wyłączenie funkcji eksperymentalnych zaczną obowiązywać dopiero po następnym uruchomieniu programu PowerShell. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ExtendedTypeSystem.pl.resx b/src/System.Management.Automation/resources/pl/ExtendedTypeSystem.pl.resx new file mode 100644 index 00000000000..aa950b54594 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ExtendedTypeSystem.pl.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Element członkowski „{0}” już istnieje. + + + Element członkowski „{0}” jest już obecny w pliku danych typów rozszerzonych. + + + Element członkowski „{0}” nie istnieje. + + + Wyjątek podczas ustawiania „{0}”: „{1}” + + + Wyjątek podczas pobierania „{0}”: „{1}” + + + Podczas próby wyliczenia kolekcji wystąpił następujący wyjątek: „{0}”. + + + Nie można uzyskać dostępu do elementu członkowskiego „{0}” poza obiektem PSObject. + + + Nie można zmienić elementu członkowskiego utworzonego na podstawie konfiguracji typu: „{0}”. + + + Nazwa elementu członkowskiego „{0}” jest zastrzeżona. + + + „{0}” nie można zmienić. + + + Wyjątek podczas wywoływania „{0}” z argumentami „{1}”: „{2}” + + + Zgłoszono wyjątek podczas próby wywołania „{0}” w celu wyodrębnienia zawartości obiektu typu „{1}”: „{2}” + + + Nie można znaleźć przeciążenia dla „{0}” i liczby argumentów: „{1}”. + + + Nie można znaleźć odpowiedniego przeciążenia metody ogólnej dla „{0}” z liczbą parametrów typu „{1}” i liczbą argumentów: „{2}”. + + + Znaleziono wiele niejednoznacznych przeciążeń dla „{0}” i liczbę argumentów: „{1}”. + + + Nie można przekonwertować argumentu „{0}” o wartości „{1}” dla „{2}” na typ „{3}”: „{4}” + + + Metoda pobierająca właściwość „{0}” jest niedostępna. + + + Ustawianie metody dostępu dla właściwości „{0}” jest niedostępne. + + + Metoda ustawiająca powinna być publiczna, zwracać void, być statyczna i mieć dwa parametry. Pierwszy parametr powinien mieć typ PSObject. Drugi parametr jest wymagany, jeśli dostępna jest też metoda pobierająca, i powinien mieć ten sam typ co typ zwracany przez metodę pobierającą. + + + Metoda pobierająca powinna być publiczna, nie zwracać wartości void, być statyczna i przyjmować jeden parametr typu PSObject. + + + Właściwość CodeProperty powinna używać metody pobierającej lub ustawiającej. + + + Nie można utworzyć metody kodu z powodu formatu metody. Metoda powinna być publiczna, statyczna i mieć jeden parametr typu PSObject. + + + Alias o nazwie „{0}” zawiera cykl. + + + Nie można przekonwertować wartości „{0}” typu „{1}” na typ „{2}”. + + + Nie można przekonwertować wartości typu „{0}” na typ „{1}”. + + + Nie można przekonwertować wartości „{0}” na typ „{1}”. Błąd: „{2}” + + + Nie można przekonwertować wartości „{0}” na typ „{1}”, ponieważ w tym wyliczeniu nie są dozwolone przecinki. + + + Nie można przekonwertować wartości „{0}” na typ „{1}” z powodu nieprawidłowych wartości wyliczenia. Określ jedną z następujących wartości wyliczenia i spróbuj ponownie. Możliwe wartości wyliczenia to „{2}”. + + + Nie można przekonwertować wartości null na typ „{0}”, ponieważ wartości wyliczenia są nieprawidłowe. Określ jedną z następujących wartości wyliczenia i spróbuj ponownie. Możliwe wartości wyliczenia to „{1}”. + + + Nie można przekonwertować wartości null na typ „{0}”. + + + Nie można przekonwertować wartości na typ „{0}”. Błąd: „{1}” + + + Nie można przekonwertować wartości na typ System.String. + + + Oczekiwano typu referencyjnego w argumencie. + + + Nie można porównać „{0}”, ponieważ nie implementuje interfejsu IComparable. + + + Nie można porównać „{0}” z „{1}”. Błąd: „{2}” + + + Nie można porównać „{0}” z „{1}”, ponieważ obiekty nie są tego samego typu lub obiekt „{0}” nie implementuje „{2}”. + + + Nie można przekonwertować wartości „{0}” na typ „{1}”, ponieważ znaleziono co najmniej dwa dopasowania ({2}, {3}), a dla tego wyliczenia dozwolone jest tylko jedno dopasowanie. + + + Nie można przekonwertować wartości „{0}” na typ „{1}”. Parametry logiczne akceptują tylko wartości logiczne i liczby, takie jak $True, $False, 1 lub 0. + + + Nie można pobrać wartości właściwości, ponieważ „{0}” jest właściwością tylko do zapisu. + + + „{0}” jest właściwością ReadOnly. + + + Nie można ustawić „{0}”, ponieważ jako wartości właściwości XmlNode można używać tylko ciągów. + + + Nie można ustawić „{0}”, ponieważ można ustawić tylko unikatowe atrybuty lub unikatowe nieatrybutowe węzły liściowe. + + + Nie można dodać obiektu PSProperty ani PSMethod do tej kolekcji. + + + Podczas ładowania pliku danych typu rozszerzonego wystąpił następujący błąd: {0} + + + Wystąpił następujący wyjątek podczas pobierania ciągu: „{0}” + + + Pole lub właściwość: „{0}” dla typu: „{1}” różni się od pola lub właściwości: „{2}” tylko wielkością liter. Typ musi być zgodny ze specyfikacją Common Language Specification (CLS). + + + Wystąpił następujący wyjątek podczas pobierania hierarchii nazw typów: „{0}”. + + + Wystąpił następujący wyjątek podczas pobierania elementu członkowskiego „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania elementów członkowskich: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania stanu odczytu dla właściwości „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania stanu zapisu dla właściwości „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania typu właściwości „{1}”: „{0}” + + + Podczas pobierania reprezentacji ciągu dla właściwości „{1}” wystąpił następujący wyjątek: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania atrybutów właściwości „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania definicji dla metody „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania reprezentacji ciągu dla metody „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania typu właściwości sparametryzowanej „{1}”: „{0}” + + + Podczas pobierania stanu odczytu dla właściwości sparametryzowanej „{1}” wystąpił następujący wyjątek: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania stanu zapisu dla właściwości sparametryzowanej „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania definicji właściwości sparametryzowanej „{1}”: „{0}” + + + Wystąpił następujący wyjątek podczas pobierania reprezentacji ciągu dla właściwości sparametryzowanej „{1}”: „{0}” + + + Nie można ustawić właściwości Value dla obiektu PSMemberInfo typu „{0}”. + + + Argument: „{0}” powinien być {1}. Użyj {2}. + + + Argument : „{0}” nie powinien być {1}. Nie używaj {2}. + + + Właściwość "{0}" nie została znaleziona. + + + Nie można pobrać lub ustawić wartości właściwości. Argument „{0}” powinien być typu „{1}” lub „{2}”. + + + Nie można ustawić wartości właściwości „{0}”, ponieważ obiekt ma typ „{1}” zamiast „{2}”. + + + Wyjątek podczas wywoływania „{0}” : „{1}” + + + {0} nie jest prawidłową ścieżką klasy. + + + {0} nie jest prawidłową ścieżką. + + + Adapter nie może określić, czy można zmienić właściwość „{0}”. + + + Adapter nie może określić, czy właściwość „{0}” umożliwia pobranie wartości. + + + Adapter nie może pobrać wartości właściwości „{0}”. + + + Adapter nie może ustawić wartości właściwości „{0}”. + + + Adapter nie może pobrać typu właściwości „{0}”. + + + Adapter nie może pobrać hierarchii typów dla „{0}”. + + + Adapter nie może pobrać właściwości „{0}”. + + + Adapter nie może pobrać właściwości „{0}” dla „{1}”. + + + „{0}” zwróciła wartość null. + + + Nie znaleziono właściwości „{0}” dla obiektu „{1}”. Właściwości, które można ustawić, to: {2}. + + + Nie znaleziono właściwości „{0}” dla obiektu „{1}”. Brak dostępnej właściwości settable. + + + Nie można utworzyć obiektu typu „{0}”. {1} + + + Nie można wywoływać metod statycznych ani uzyskiwać dostępu do właściwości statycznych w otwartym typie generycznym {0}. Określ parametry typu i spróbuj ponownie. Na przykład zamiast [System.Collections.Generic.HashSet``1]::CreateSetComparer() użyj [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + Wystąpił następujący wyjątek podczas konstruowania atrybutu „{1}”: „{0}” + + + Nie można przekonwertować wartości „{0}” na tablicę ciągów. + + + Nie można przekonwertować wartości na typ „{0}”. W tym trybie języka są obsługiwane tylko typy podstawowe. + + + Nie można przekonwertować na typ „{0}” typu ByRef. Typy podobne do ByRef nie są obsługiwane w programie PowerShell. + + + Nie można pobrać ani ustawić właściwości lub pola „{0}” typu podobnego do ByRef „{1}”. Typy podobne do ByRef nie są obsługiwane w programie PowerShell. + + + Nie można wywołać metody „{0}” zwracającej typ podobny do ByRef „{1}”. Typy podobne do ByRef nie są obsługiwane w programie PowerShell. + + + Nie można utworzyć wystąpienia typu podobnego do ByRef „{0}”. Typy podobne do ByRef nie są obsługiwane w programie PowerShell. + + + Konwersja tabeli skrótów systemu typów rozszerzonych + + + Konwersja typu z wartości HashTable na „{0}” nie będzie dozwolona w trybie ConstrainedLanguage. + + + Konwersja tabeli skrótów systemu typów rozszerzonych + + + Konwersja typu z „{0}” na „{1}” nie będzie dozwolona w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/FileSystemProviderStrings.pl.resx b/src/System.Management.Automation/resources/pl/FileSystemProviderStrings.pl.resx new file mode 100644 index 00000000000..12e8712a0ea --- /dev/null +++ b/src/System.Management.Automation/resources/pl/FileSystemProviderStrings.pl.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Invoke Item + + + Item: {0} + + + Remove File + + + Remove Directory + + + Copy File + + + Item: {0} Destination: {1} + + + Copy Directory + + + Rename File + + + Rename Directory + + + Item: {0} Destination: {1} + + + Move File + + + Move Directory + + + Item: {0} Destination: {1} + + + Set Property File + + + Set Property Directory + + + Item: {0} Property: {1} Value: {2} + + + Clear Property File + + + Clear Property Directory + + + Item: {0} Property: {1} + + + Create File + + + Create Directory + + + Destination: {0} + + + Clear Content + + + Item: {0} + + + Could not find item {0}. + + + Cannot remove item {0}: {1} + + + Cannot restore attributes on item {0}: {1} + + + An object at the specified path {0} does not exist. + + + Directory {0} cannot be removed because it is not empty. + + + The type is not a known type for the file system. Only "file","directory" or "symboliclink" can be specified. + + + Cannot process the path because the specified path refers to an item that is outside the basePath. + + + The specified drive root "{0}" either does not exist, or it is not a folder. + + + An item with the specified name {0} already exists. + + + A delimiter cannot be specified when reading the stream one byte at a time. + + + Cannot overwrite the item {0} with itself. + + + Cannot rename the specified target, because it represents a path or device name. + + + The property {0} does not exist or was not found. + + + You do not have sufficient access rights to perform this operation or the item is hidden, system, or read only. + + + The attribute cannot be set because attributes are not supported. Only the following attributes can be set: Archive, Hidden, Normal, ReadOnly, or System. + + + The property cannot be cleared because the property is not supported. Only the Attributes property can be cleared. + + + Cannot process path '{0}' because the target represents a reserved device name. + + + Encoding not used when '-AsByteStream' specified. + + + Cannot proceed with byte encoding. When using byte encoding the content must be of type byte. + + + Cannot process the file because the file {0} was not found. + + + Directory: + + + Cannot detect the encoding of the file. The specified encoding {0} is not supported when the content is read in reverse. + + + Could not open the alternate data stream '{0}' of the file '{1}'. + + + Stream '{0}' of file '{1}'. + + + The Raw and Wait parameters cannot be specified in the same command. + + + To use the Persist switch parameter, the drive name must be supported by the operating system (for example, drive letters A-Z). + + + When you use the Persist parameter, the root must be a file system location on a remote computer. + + + The '{0}' and '{1}' parameters cannot be specified in the same command. + + + A directory is required for the operation. The item '{0}' is not a directory. + + + Create Junction + + + Create Symbolic Link + + + Administrator privilege required for this operation. + + + Create Hard Link + + + A file is required for the operation. The item '{0}' is not a file. + + + Hard links are not supported for the specified path. + + + Symbolic links are not supported for the specified path. + + + Kopiowanie {0} do {1} + + + Destination path {0} is a file that already exists on the target destination. + + + Failed to copy file {0} to remote target destination. + + + Z {0} do {1} + + + Cannot copy a directory '{0}' to file '{0}' + + + Failed to get directory {0} child items. + + + Failed to read remote file '{0}'. + + + Cannot validate if remote destination {0} is a file. + + + Failed to create directory '{0}' on remote destination. + + + Maximum size for drive has been exceeded: {0}. + + + Cannot create link because the path already exists: {0}. + + + Skip already-visited directory {0}. + + + Destination path cannot be a subdirectory of the source or the source itself: {0}. + + + The target and path cannot be the same. + + + Copied {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Removed {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Creating a junction requires an absolute path for the target. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/FormatAndOutXmlLoadingStrings.pl.resx b/src/System.Management.Automation/resources/pl/FormatAndOutXmlLoadingStrings.pl.resx new file mode 100644 index 00000000000..d1637700665 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/FormatAndOutXmlLoadingStrings.pl.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Błąd w XPath {0} w pliku {1}: element XML {2} nie zezwala na atrybuty. + + + Błąd w XPath {0} w pliku {1}: węzeł {2}nie może mieć obiektów podrzędnych. + + + Błąd w ścieżce XPath {0} w pliku {1}: {2} jest nieprawidłowy. + + + Błąd w ścieżce XPath {0} w pliku {1}: musi istnieć co najmniej jedna wartość domyślna {2}. + + + Błąd w ścieżce XPath {0} w pliku {1}: nie może istnieć więcej niż jedna wartość domyślna {2}. + + + Błąd w XPath {0} w pliku {1}: nazwa formantu nie może mieć wartości null ani być pusta. + + + Błąd w XPath {0} w pliku {1}: widoki poza pasmem mogą mieć tylko kontrolki CustomControl lub ListControl. + + + Błąd w XPath {0} w pliku {1}: widok poza pasmem nie może mieć elementu GroupBy. + + + Błąd w XPath {0} w pliku {1}: nie można załadować widoku. + + + Błąd w ścieżce XPath {0} w pliku {1}: „{2}” nie jest prawidłową wartością wyrównania. + + + Błąd w XPath {0} w pliku {1}: oczekiwano dodatniej liczby całkowitej. + + + Błąd w XPath {0} w pliku {1}: definicja nagłówka kolumny jest nieprawidłowa; wszystkie nagłówki są odrzucane. + + + Błąd w XPath {0} w pliku {1}: liczba elementów wiersza = {2} w zestawie alternatywnym #{3} nie jest zgodna z domyślną liczbą elementów wiersza = {4}. + + + Błąd w XPath {0} w pliku {1}: liczba elementów nagłówka = {2} nie jest zgodna z domyślną liczbą elementów wiersza = {3}. + + + Błąd w XPath {0} w pliku {1}: należy określić co najmniej jeden element widoku listy. + + + Błąd w XPath {0} w pliku {1}: wpis właściwości jest nieprawidłowy. + + + Błąd w XPath {0} w pliku {1}: brak listy definicji. + + + Błąd w XPath {0} w pliku {1}: oczekiwano wartości logicznej. + + + Błąd w XPath {0} w pliku {1}: oczekiwano nieujemnej liczby całkowitej. + + + Błąd w XPath {0} w pliku {1}: oczekiwano liczby całkowitej. + + + Błąd w XPath {0} w pliku {1}: brak wewnętrznej wartości tekstowej. + + + Błąd w XPath {0} w pliku {1}: lista niestandardowych tokenów kontrolek nie może być pusta. + + + Błąd w XPath {0} w pliku {1}: nie można załadować {2}. + + + Błąd w ścieżce XPath {0} w pliku {1}: {2} nie można określić bez wyrażenia. + + + Błąd w ścieżce XPath {0} w pliku {1}: {2} nie można określić za pomocą wyrażenia. + + + Błąd w XPath {0} w pliku {1}: brak ciągu formatu. + + + Błąd w XPath {0} w pliku {1}: brak tekstu bloku skryptu. + + + Błąd w XPath {0} w pliku {1}: brak właściwości. + + + Błąd w XPath {0} w pliku {1}: blok skryptu „{2}” jest nieprawidłowy. + + + Błąd w XPath {0} w pliku {1}: nie znaleziono ciągu {2} z zasobu {3} w zestawie {4}. + + + Błąd w XPath {0} w pliku {1}: nie znaleziono zasobu {2} w zestawie {3}. + + + Błąd w XPath {0} w pliku {1}: nie znaleziono zestawu {2}. + + + Błąd w XPath {0} w pliku {1}: węzeł musi być elementem XmlElement. + + + Błąd w ścieżce XPath {0} w pliku {1}: oczekiwano wyrażenia. + + + Błąd w XPath {0} w pliku {1}: nie można mieć formantu lub etykiety bez wyrażenia. + + + Błąd w XPath {0} w pliku {1}: nie można jednocześnie mieć kontrolki i etykiety. + + + Błąd w XPath {0} w pliku {1}: Nie można jednocześnie mieć elementów SelectionSetName i TypeName. + + + Błąd w XPath {0} w pliku {1}: nie określono typu ani warunku na potrzeby stosowania widoku. + + + Błąd w XPath {0} w pliku {1}: wartość {2} jest nieprawidłowa. + + + Błąd w XPath {0} w pliku {1}: istnieje zduplikowany węzeł. + + + Błąd w XPath {0} w pliku {1}: {2} i {3} wykluczają się wzajemnie. + + + Błąd w XPath {0} w pliku {1}. {2}, {3} i{4} wzajemnie się wykluczają. + + + Błąd w XPath {0} w pliku {1}: {2} jest nieznanym węzłem. + + + Błąd w XPath {0} w pliku {1}: {2} jest nieznanym atrybutem. + + + Błąd w XPath {0} w pliku {1}: {2} jest brakującym atrybutem. + + + Błąd w ścieżce XPath {0} w pliku {1}: brak węzła {2}. + + + Błąd w XPath {0} w pliku {1}: brak węzła w {2}. + + + Błąd w XPath {0} w pliku {1}: {2} jest pustym węzłem. + + + Błąd w XPath {0} w pliku {1}: {2} jest pustym atrybutem. + + + Błąd w pliku {0}: {1} + + + Zbyt wiele błędów w pliku {0}. + + + Wystąpiły błędy podczas ładowania pliku danych formatu: {0} + + + (Globalna pamięć podręczna zestawów) {0} + + + {0}, {1} + + + Ścieżka {0} nie jest w pełni kwalifikowana. Określ w pełni kwalifikowaną ścieżkę pliku formatu. + + + Nie można zaktualizować obiektu FormatTable, ponieważ obiekt FormatTable mógł zostać utworzony poza obszarem runspace. + + + Wystąpiły błędy podczas ładowania obiektu FormatTable. Wyświetl zawartość właściwości Errors, aby uzyskać szczegółowe komunikaty o błędach. + + + Błąd podczas formatowania danych „{0}”: {1} + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: liczba elementów nagłówka = {2} nie jest zgodna z domyślną liczbą elementów wiersza = {3}. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: formatowanie danych „{2}„ jest nieprawidłowe. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: blok skryptu „{2}” jest nieprawidłowy. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: nie można załadować {2}. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: Element TableControl powinien zawierać tylko jeden element {2}. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: musi istnieć co najmniej jedna wartość domyślna {2}. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: należy określić co najmniej jeden element widoku listy. + + + Błąd podczas wyświetlania danych o nazwie typu {0} w indeksie {1}: nie może istnieć więcej niż jedna wartość domyślna {2}. + + + Zbyt wiele błędów w danych formatowania dla typu „{0}”. + + + Tabeli formatu udostępnionego nie można zaktualizować za pomocą więcej niż jednego wpisu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/FormatAndOut_MshParameter.pl.resx b/src/System.Management.Automation/resources/pl/FormatAndOut_MshParameter.pl.resx new file mode 100644 index 00000000000..b6609d9b5d5 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/FormatAndOut_MshParameter.pl.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 + + + Nie można przekonwertować {0} na jeden z następujących typów {1}. + + + Wartość parametru miała wartość null; oczekiwano jednego z następujących typów: {0}. + + + Zduplikowany klucz „{0}” powoduje konflikt z „{1}”. + + + Klucz „{0}” ma typ {1}, który jest nieprawidłowy; oczekiwanymi typami są {2}. + + + Klucz „{0}” ma typ {1}, który jest nieprawidłowy; oczekiwanym typem jest {2}. + + + Klucz {0} jest niejednoznaczny, {1}, i powoduje konflikt z {2}. + + + Wartość klucza nie może mieć wartości null. + + + Typ klucza {0} jest nieprawidłowy. Klucz musi być ciągiem. + + + Klucz {0} nie ma żadnej wartości. + + + Brak obowiązkowego wpisu dla {0}. + + + Klucz {0} jest nieprawidłowy. + + + Wartość „{0}” dla klucza „{1}” jest nieprawidłowa; prawidłowymi wartościami są {2}. + + + Wartość „{0}” dla klucza „{1}” powinna być większa niż 0. + + + Nie można mieć pustego ciągu formatowania w przypadku klucza „{0}”. + + + Klucz „{0}” nie może mieć pustej wartości ciągu. + + + Pusta wartość ciągu jest niedozwolona. + + + Klucz „{0}” nie może zawierać symboli wieloznacznych w wartości „{1}”. + + + Symbole wieloznaczne są niedozwolone w ciągu „{0}”. + + + Wartość EnumerableExpansion jest nieprawidłowa. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/FormatAndOut_format_xxx.pl.resx b/src/System.Management.Automation/resources/pl/FormatAndOut_format_xxx.pl.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/FormatAndOut_format_xxx.pl.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/FormatAndOut_out_xxx.pl.resx b/src/System.Management.Automation/resources/pl/FormatAndOut_out_xxx.pl.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/FormatAndOut_out_xxx.pl.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/GetErrorText.pl.resx b/src/System.Management.Automation/resources/pl/GetErrorText.pl.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/GetErrorText.pl.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/HelpDisplayStrings.pl.resx b/src/System.Management.Automation/resources/pl/HelpDisplayStrings.pl.resx new file mode 100644 index 00000000000..23ec9aa733b --- /dev/null +++ b/src/System.Management.Automation/resources/pl/HelpDisplayStrings.pl.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NAZWA + + + SYNOPSIS + + + OPIS + + + SKŁADNIA + + + PARAMETRY + + + DANE WEJŚCIOWE + + + DANE WYJŚCIOWE + + + BŁĘDY POWODUJĄCE PRZERWANIE DZIAŁANIA + + + BŁĘDY NIEPOWODUJĄCE PRZERWANIA DZIAŁANIA + + + UWAGI + + + PRZYKŁADY + + + Przykład + + + PRZYKŁAD + + + DANE WYJŚCIOWE + + + POWIĄZANE LINKI + + + KRÓTKI OPIS + + + Tytuł: + + + Pytanie: + + + Odpowiedź + + + Okres: + + + Definicja: + + + Zawartość: + + + NAZWA DOSTAWCY + + + To polecenie cmdlet obsługuje typowe parametry: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. Aby uzyskać więcej informacji, zobacz + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Wymagany? + + + Lokalizacja? + + + Typ: + + + Typ obiektu docelowego: + + + Wartość domyślna + + + Zaakceptować dane wejściowe potoku? + + + Akceptować symbole wieloznaczne? + + + (Kategoria: + + + Sugerowana akcja: + + + Aby uzyskać więcej informacji, wpisz: + + + Aby uzyskać informacje techniczne, wpisz: + + + Aby wyświetlić przykłady, wpisz: + + + Aby uzyskać pomoc online, wpisz: + + + <CommonParameters> + + + UWAGI + + + true + + + Nazwane + + + DYSKI + + + MOŻLIWOŚCI + + + ZADANIA + + + ZADANIE: + + + FILTRY + + + PARAMETRY DYNAMICZNE + + + Obsługiwane polecenia cmdlet: + + + ALIASY + + + Funkcja Get-Help nie może znaleźć plików pomocy dotyczących tego polecenia cmdlet na tym komputerze. Wyświetla tylko częściową pomoc. + -- Aby pobrać i zainstalować pliki Pomocy dla modułu zawierającego to polecenie cmdlet, użyj polecenia Update-Help. + -- Aby wyświetlić temat Pomocy dla tego polecenia cmdlet w trybie online, wpisz: „Get-Help {0} -Online” lub + przejdź do {1}. + + + Brak + + + Aliasy + + + Dynamiczny? + + + Nazwa zestawu parametrów + + + Nie można pobrać pliku XML HelpInfo dla kultury interfejsu użytkownika {0}. Upewnij się, że właściwość HelpInfoUri w manifeście modułu jest prawidłowa lub sprawdź połączenie sieciowe, a następnie spróbuj ponownie wykonać polecenie. + + + ByPropertyName + + + Wartość ByValue + + + FromRemainingArguments + + + Określona kultura jest nieobsługiwana: {0}. Określ kulturę z następującej listy: {{{1}}}. + + + Odłożenie błędu i wypróbowanie kultur rezerwowych spowoduje wyświetlenie błędu, jeśli żadna z kultur rezerwowych nie jest obsługiwana: +{0} + + + Nie można odnaleźć katalogu ModuleBase. Sprawdź katalog i spróbuj ponownie. + + + Ścieżka {0} nie jest prawidłowym katalogiem. Upewnij się, że katalog istnieje, i spróbuj ponownie. + + + Identyfikator URI Pomocy nie może zawierać więcej niż 10 przekierowań. Określ prawidłowy identyfikator URI Pomocy. + + + Aktualizowanie Pomocy + + + Trwa łączenie z zawartością Pomocy... + + + Trwa pobieranie zawartości Pomocy... + + + Trwa instalowanie zawartości Pomocy... + + + Trwa lokalizowanie zawartości Pomocy... + + + (Wszystko) + + + Nie znaleziono modułów programu PowerShell zgodnych z następującym wzorcem: {0}. Sprawdź wzorzec, a następnie spróbuj ponownie wykonać polecenie. + + + Nie znaleziono modułów programu PowerShell zgodnych z określonym modułem FullyQualifiedModule {0}. Sprawdź wartość FullyQualifiedModule, a następnie spróbuj ponownie wykonać polecenie. + + + Nie można odnaleźć zawartości pomocy. Upewnij się, że serwer jest dostępny, a lokalizacja treści pomocy jest prawidłowo zdefiniowana w pliku XML HelpInfo. + + + Polecenie „Update-Help” zakończyło się niepowodzeniem, ponieważ wskazany moduł nie obsługuje pomocy z możliwością aktualizacji. Aby uzyskać pomoc dotyczącą poleceń zawartych w tym module, użyj polecenia Get-Help -Online lub poszukaj informacji w Internecie. + + + Następujący parametr nie może mieć wartości null ani być pusty: Moduł. + + + Następujący parametr nie może mieć wartości null ani być pusty: Path. + + + Operacja Update-Help została ukończona pomyślnie. + + + Błąd podczas wyodrębniania zawartości Pomocy. + + + Nie można nawiązać połączenia z zawartością Pomocy. Serwer, na którym jest przechowywana zawartość Pomocy, może być niedostępny. Sprawdź, czy serwer jest dostępny, lub zaczekaj, aż serwer wróci do trybu online, a następnie spróbuj ponownie wykonać polecenie. + + + Treść Pomocy w podanej lokalizacji jest nieprawidłowa. Określ lokalizację zawierającą prawidłową zawartość Pomocy. + + + Kod XML HelpInfo jest nieprawidłowy. Określ prawidłowy kod XML HelpInfo. + + + Zawartość pomocy została pomyślnie zapisana w następującej lokalizacji: {0} + + + Nie można odnaleźć pliku XSD zawartości Pomocy w {0}. Sprawdź, czy plik XSD istnieje w określonej lokalizacji, a następnie ponów próbę wykonania polecenia. + + + Nie udało się zaktualizować Pomocy dla następujących modułów: +„{0}” +{1} + + + Zapisywanie Pomocy + + + Zawartość Pomocy zawiera nieprawidłowe pliki. Obsługiwane są wyłącznie pliki z rozszerzeniami .txt i .xml. + + + Nie można zapisać Pomocy dla modułów „{0}” : {1} + + + Nie udało się zapisać pomocy dla modułu(-ów) „{0}” z ustawieniami kulturowymi interfejsu użytkownika {{{1}}} : {2}. +Dostępna jest treść pomocy w języku angielskim (wersja amerykańska), którą można zapisać za pomocą polecenia: Save-Help -UICulture en-US. + + + Nie można zaktualizować Pomocy dla modułów „{0}”z kulturami interfejsu użytkownika {{{1}}}: {2}. +Dostępna jest dokumentacja pomocy w języku angielskim (wersja amerykańska), którą można zainstalować za pomocą polecenia: Update-Help -UICulture en-US. + + + Obecna kultura systemu to ({0}), która nie jest powiązana z żadnym językiem. Rozważ zmianę kultury systemu lub zainstaluj treści pomocy w języku angielskim (USA), korzystając z polecenia: Update-Help -UICulture en-US. + + + false + + + Parametr -Recurse jest dostępny tylko wtedy, gdy określono ścieżkę źródłową. + + + Ścieżka {0} nie zawiera dostawcy FileSystem. Sprawdź, czy określona ścieżka zawiera dostawcę FileSystem, a następnie spróbuj ponownie wykonać polecenie. + + + Wyszukiwanie Pomocy dla {0} ... + + + Nie znaleziono żadnej kultury interfejsu użytkownika, która odpowiadałaby poniższemu wzorcowi: {0}. Sprawdź wzorzec, a następnie spróbuj ponownie wykonać polecenie. + + + Pomoc nie została zapisana dla modułu {0}, ponieważ polecenie Save-Help zostało uruchomione na tym komputerze w ciągu ostatnich 24 godzin. +Aby ponownie zapisać pomoc, dodaj parametr Force do polecenia. + + + Pomoc dla modułu {0} nie została zaktualizowana, ponieważ polecenie Update-Help zostało uruchomione na tym komputerze w ciągu ostatnich 24 godzin. +Aby ponownie zaktualizować pomoc, dodaj parametr Force do polecenia. + + + Najnowsze pliki Pomocy są już zainstalowane. + + + {0}: {1}. Kultura {2} Wersja {3} + + + Zaktualizowano {0} + + + Wartość klucza „HelpInfoUri” w manifeście modułu musi odnosić się do adresu URL kontenera lub adresu głównego witryny internetowej, na której przechowywane są pliki pomocy. Adres HelpInfoUri „{0}” nie prowadzi do żadnego kontenera. + + + Zawartość Pomocy musi znajdować się w przestrzeni nazw {0}. + + + Funkcja Get-Help nie może znaleźć plików pomocy dotyczących tego polecenia cmdlet na tym komputerze. Wyświetla tylko częściową pomoc. + -- Aby pobrać i zainstalować pliki pomocy dla modułu zawierającego ten cmdlet, należy użyć polecenia Update-Help. + + + Najnowsze pliki Pomocy są już pobrane. + + + Zapisano kategorię {0} + + + Identyfikator HelpInfoURI {0} nie rozpoczyna się od protokołu HTTP. + + + Elementem najwyższego poziomu treści pomocy musi mieć wartość „helpItems”. + + + Zapisywanie Pomocy dla modułu {0} + + + Aktualizowanie Pomocy dla modułu {0} + + + Rozpoznawanie identyfikatora URI: „{0}” + + + Identyfikator URI Pomocy: {0} + + + {0}, bieżąca wersja: {1}, dostępna wersja: {2}, UICulture: {3} + + + WŁAŚCIWOŚCI + + + METODY + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/HelpErrors.pl.resx b/src/System.Management.Automation/resources/pl/HelpErrors.pl.resx new file mode 100644 index 00000000000..764db714552 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/HelpErrors.pl.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help nie może odnaleźć {0} w pliku Pomocy w tej sesji. Aby pobrać zaktualizowane tematy pomocy, wpisz: „Update-Help”. Aby uzyskać pomoc online, wyszukaj temat pomocy w bibliotece TechNet pod adresem https://go.microsoft.com/fwlink/?LinkID=107116. + + + Nie można przetworzyć kategorii Pomoc, ponieważ „{0}” nie jest prawidłową kategorią Pomocy. + + + Nie można załadować pliku Pomocy „{0}”. Szczegóły: {1}. + + + Nie można uzyskać dostępu do pliku Pomocy „{0}”, ponieważ bieżący użytkownik nie ma praw dostępu do pliku. Szczegóły: {1}. + + + Plik Pomoc „{0}” nie jest prawidłowym dokumentem XML. Szczegóły: {1}. + + + Wystąpił błąd podczas ładowania zawartości Pomocy dla {0} z pliku {1}. Szczegóły: {2}. Aby pobrać zaktualizowane tematy Pomocy, uruchom polecenie cmdlet Update-Help. Aby uzyskać pomoc online, wyszukaj temat Pomocy w bibliotece TechNet pod adresem https://go.microsoft.com/fwlink/?LinkID=107116. + + + Nie można załadować dostawcy „{0}”. Szczegóły: {1}. + + + Nie można załadować pliku Pomocy. Wystąpiły błędy ({1}) podczas ładowania pliku pomocy „{0}”. + + + Węzeł „{0}” nie może mieć węzła „{1}” jako węzła podrzędnego. Ścieżka węzła: {2}. + + + Węzeł „{0}” może mieć maksymalną liczbę {2} węzłów podrzędnych typu „{1}”. Ścieżka węzła: {3}. + + + Nie można odnaleźć klucza rejestru: „{0}{1}”; do załadowania plików Pomocy jest używany „{2}”. + + + Brak parametru spełniającego kryteria {0}. + + + {0} nie jest obsługiwana przez żądaną kategorię Pomoc. + + + Nie można wyświetlić wersji online tego tematu Pomocy, ponieważ adres internetowy (URI) tematu Pomocy nie jest określony w kodzie polecenia ani w pliku pomocy polecenia. + + + Określony identyfikator URI {0} jest nieprawidłowy. + + + Uruchomienie przeglądarki w celu wyświetlenia Pomocy online nie powiodło się. Żaden program ani przeglądarka nie są skojarzone z otwieraniem identyfikatora URI {0}. + + + Protokół określony w identyfikatorze URI „{0}” nie jest obsługiwany. Obsługiwane są tylko protokoły „{1}” i „{2}”. + + + Znaleziono wiele tematów Pomocy. Użyj tylko jednego tematu Pomocy z opcją -{0} . + + + Nie można uzyskać Pomocy ze zdalnego obszaru uruchomieniowego, ponieważ obszar uruchomieniowy nie został otwarty. Otwórz obszar uruchomieniowy, uruchamiając niejawne polecenie komunikacji zdalnej, a następnie spróbuj ponownie uruchomić polecenie, aby uzyskać Pomoc. + + + Odmowa dostępu. Polecenie nie może zaktualizować tematów Pomocy dla podstawowych modułów programu PowerShell ani żadnych modułów w katalogu $pshome\Modules. +Aby zaktualizować te tematy Pomocy, uruchom program PowerShell za pomocą polecenia „Uruchom jako administrator”, a następnie spróbuj ponownie uruchomić polecenie Update-Help. + + + Aby użyć {0}, upewnij się, że aplikacja używa „Microsoft.NET.Sdk.WindowsDesktop” jako zestawu SDK projektu i odpowiedniego zestawu „Microsoft.PowerShell.GraphicalHost”. ({1}) + + + {0} nie działa w sesji zdalnej. + + + Element ForwardHelpTargetName nie może odwoływać się do samej funkcji. + + + Nie można uzyskać pomocy z lokalizacji sieciowej w sesji z ograniczeniami. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/HistoryStrings.pl.resx b/src/System.Management.Automation/resources/pl/HistoryStrings.pl.resx new file mode 100644 index 00000000000..a0e3163f0a2 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/HistoryStrings.pl.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Identyfikator {0} nie jest prawidłową wartością identyfikatora historii. Określ liczbę dodatnią, a następnie spróbuj ponownie. + + + Nie można zlokalizować historii dla wiersza polecenia {0}. + + + Nie można połączyć liczby z wieloma identyfikatorami. + + + Nie można zlokalizować historii dla wiersza polecenia {0}. + + + Nie można zlokalizować najnowszej historii. + + + Polecenie cmdlet Invoke-History jest wywoływane wielokrotnie w pętli. + + + Nie można przetworzyć wielu poleceń historii. Za pomocą polecenia Invoke-History można uruchomić tylko jedno polecenie. + + + Nie można dodać historii, ponieważ format obiektu wejściowego jest nieprawidłowy. + + + Identyfikator {0} jest nieprawidłowy. Określ liczbę dodatnią, a następnie spróbuj ponownie. + + + To polecenie wyczyści wszystkie wpisy z historii sesji. + + + Tej liczby nie można łączyć z wieloma parametrami wiersza polecenia. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/HostInterfaceExceptionsStrings.pl.resx b/src/System.Management.Automation/resources/pl/HostInterfaceExceptionsStrings.pl.resx new file mode 100644 index 00000000000..144907fafc5 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/HostInterfaceExceptionsStrings.pl.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 + + + Wystąpił błąd typu „{0}”. + + + Polecenie, które monituje użytkownika, nie powiodło się, ponieważ program hosta lub typ polecenia nie obsługuje interakcji z użytkownikiem. Wypróbuj program hosta, który obsługuje interakcje z użytkownikiem, takie jak konsola programu PowerShell, i usuń polecenia związane z wierszem polecenia z typów poleceń, które nie obsługują interakcji z użytkownikiem. + + + Polecenie, które monituje użytkownika, nie powiodło się, ponieważ program hosta lub typ polecenia nie obsługuje interakcji z użytkownikiem. Host próbował zażądać potwierdzenia z następującym komunikatem: {0} + + + Nie można wywołać metody, ponieważ pula została zamknięta lub nie powiodła się. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/InternalCommandStrings.pl.resx b/src/System.Management.Automation/resources/pl/InternalCommandStrings.pl.resx new file mode 100644 index 00000000000..5ade3837ed8 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/InternalCommandStrings.pl.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nazwa wejściowa „{0}” jest niejednoznaczna. Można go rozpoznać jako wiele dopasowanych metod. Możliwe dopasowania to: {1}. + + + Nazwa wejściowa „{0}” jest niejednoznaczna. Można go rozpoznać jako wiele pasujących elementów członkowskich. Możliwe dopasowania to: {1}. + + + Pobierz wartość klucza „{0}” + + + Wywołaj metodę „{0}” z argumentami: {1} + + + Wywołaj metodę „{0}” + + + Pobieranie wartości właściwości „{0}” + + + Obiekt wejściowy: {0} + + + Nie można wykonać operacji na obiekcie wejściowym „null”. + + + Nie można rozpoznać nazwy wejściowej „{0}” jako metody. + + + Nie można wywołać metody w trybie języka z ograniczeniami. + + + Parametry -WhatIf i -Confirm nie są obsługiwane w blokach skryptów. + + + Operacja „{0}” jest niedozwolona w trybie RestrictedLanguage. + + + Operator jest wymagany do porównania dwóch określonych wartości. Dodaj prawidłowy operator do polecenia, a następnie spróbuj ponownie. Na przykład: Get-Process | Where-Object -Property Name -eq Idle + + + Nie można rozpoznać nazwy wejściowej „{0}” jako właściwości. + + + Nie można rozpoznać nazwy wejściowej „{0}” jako elementu członkowskiego. + + + Określony operator wymaga parametrów -Property i -Value. Podaj wartości dla obu parametrów, a następnie spróbuj ponownie wykonać polecenie. + + + Tej metody nie można uruchomić w bieżącym wątku. Można ją wywołać tylko w wątku poleceń cmdlet. + + + Zmienna używana przez ForEach-Object -Parallel nie może być blokiem skryptu. Przekazywane zmienne bloku skryptu nie są obsługiwane w przypadku ForEach-Object -Parallel i mogą powodować niezdefiniowane zachowanie. + + + Obiekt danych wejściowych potoku ForEach-Object -Parallel nie może być blokiem skryptu. Przekazywane zmienne bloku skryptu nie są obsługiwane w przypadku ForEach-Object -Parallel i mogą powodować niezdefiniowane zachowanie. + + + Parametru „TimeoutSeconds” nie można użyć z parametrem „AsJob”. + + + Następujące wspólne parametry nie są obecnie obsługiwane w zestawie parametrów Parallel: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + Wystąpił nieoczekiwany błąd podczas przetwarzania danych wejściowych ForEach-Object -Parallel. Może to oznaczać, że niektóre dane wejściowe przesyłane potokami nie zostały przetworzone. Błąd: {0}. + + + ForEach-Object Cmdlet + + + Wywoływanie metod dla typu „{0}” nie będzie dozwolone po uruchomieniu w trybie języka z ograniczeniami. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/InternalHostStrings.pl.resx b/src/System.Management.Automation/resources/pl/InternalHostStrings.pl.resx new file mode 100644 index 00000000000..0ded9ca598f --- /dev/null +++ b/src/System.Management.Automation/resources/pl/InternalHostStrings.pl.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 + + + Funkcja EnterNestedPrompt nie została wywołana tyle razy co funkcja ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/InternalHostUserInterfaceStrings.pl.resx b/src/System.Management.Automation/resources/pl/InternalHostUserInterfaceStrings.pl.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/pl/InternalHostUserInterfaceStrings.pl.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/Logging.pl.resx b/src/System.Management.Automation/resources/pl/Logging.pl.resx new file mode 100644 index 00000000000..bdd9b6bf1fc --- /dev/null +++ b/src/System.Management.Automation/resources/pl/Logging.pl.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[Nazwa_hosta] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[Wersja hosta] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[Nazwa_hosta] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + NIEZNANY + + + Funkcja eksperymentalna aparatu „{0}” zadeklarowana w pliku konfiguracji nie jest zarejestrowana w bieżącym programie PowerShell. + + + Funkcja eksperymentalna „{0}” zadeklarowana w pliku konfiguracji jest nieprawidłowa. +Nazwa funkcji eksperymentalnej powinna być zgodna z poniższą konwencją: + Nazwa funkcji aparatu: „PS[FeatureName]” + Nazwa funkcji modułu: „[ModuleName]. [FeatureName]” + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/Metadata.pl.resx b/src/System.Management.Automation/resources/pl/Metadata.pl.resx new file mode 100644 index 00000000000..6fdfbb21856 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/Metadata.pl.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można zainicjować atrybutów dla „{0}”: „{1}” + + + Nie można sprawdzić poprawności argumentu, ponieważ jego typ „{0}” nie jest taki sam ({1}) jak maksymalne i minimalne granice parametru. Upewnij się, że argument ma typ {1}, a następnie spróbuj ponownie wykonać polecenie. + + + Nie można sprawdzić poprawności argumentu „{0}”, ponieważ jego wartość nie jest większa od zera. + + + Nie można sprawdzić poprawności argumentu „{0}”, ponieważ jego wartość nie jest większa lub równa zero. + + + Nie można sprawdzić poprawności argumentu „{0}”, ponieważ jego wartość nie jest mniejsza od zera. + + + Nie można zweryfikować argumentu „{0}”, ponieważ jego wartość nie jest mniejsza lub równa zero. + + + Nie można zaakceptować określonego zakresu minimalnego ({0}), ponieważ nie jest tego samego typu co określony zakres maksymalny ({1}). Zaktualizuj atrybut ValidateRange dla parametru. + + + Nie można zaakceptować typów parametrów MaxRange i MinRange. Oba parametry muszą być obiektami implementującymi interfejs IComparable. + + + Nie można zaakceptować określonego zakresu maksymalnego, ponieważ jest on mniejszy niż określony zakres minimalny. Zaktualizuj atrybut ValidateRange dla parametru. + + + Argument {0} jest większy niż maksymalny dozwolony zakres {1}. Podaj argument mniejszy lub równy {1}, a następnie spróbuj ponownie wykonać polecenie. + + + Argument {0} jest mniejszy niż minimalny dozwolony zakres {1}. Podaj argument, który jest większy lub równy {1}, a następnie spróbuj ponownie wykonać polecenie. + + + Argument „{0}” nie pasuje do wzorca „{1}”. Podaj argument zgodny ze wzorcem „{1}” i spróbuj ponownie wykonać polecenie. + + + Atrybutu ValidateCount nie można zastosować do parametru, który nie jest tablicą. Usuń atrybut z parametru albo zmień parametr na parametr tablicowy. + + + Parametr wymaga dokładnie {0} wartości — podano {1} wartości. + + + Parametr wymaga co najmniej {0} wartości i nie więcej niż {1} wartości — podano {2} wartości. + + + Określona maksymalna liczba argumentów dla parametru jest mniejsza niż określona minimalna liczba argumentów. Zaktualizuj atrybut ValidateCount parametru. + + + Określona maksymalna długość argumentu w znakach jest krótsza niż określona minimalna długość argumentu w znakach. Zaktualizuj atrybut ValidateLength dla parametru. + + + Atrybutu ValidateLength nie można zastosować do parametru, który nie jest parametrem typu string ani string[]. Zmień parametr na string lub string[]. + + + Długość argumentu w znakach ({1}) jest zbyt mała. Określ argument o długości większej lub równej „{0}”, a następnie spróbuj ponownie wykonać polecenie. + + + Długość znaku ({1}) argumentu jest za długa. Określ argument o długości mniejszej lub równej „{0}”, a następnie spróbuj ponownie wykonać polecenie. + + + Argument „{0}” nie należy do zestawu „{1}” określonego przez atrybut ValidateSet. Podaj argument znajdujący się w zestawie, a następnie spróbuj ponownie wykonać polecenie. + + + Generator poprawnych wartości zwrócił wartość null. + + + „{0}” nie powiodło się we właściwości „{1}” {2} + + + Nie można pobrać ani uruchomić polecenia. Przekroczono maksymalną liczbę zestawów parametrów dla tego polecenia. + + + Nie można przetworzyć argumentu, ponieważ jego wartość nie jest ciągiem. Wartości argumentów parametrów, dla których określono atrybut ArgumentTransformationAttribute, powinny być ciągami. + + + Nie można sprawdzić poprawności zmiennej, ponieważ wartość {1} nie jest prawidłową wartością dla zmiennej {0}. + + + Nie można dodać atrybutu, ponieważ zmienna {0} o wartości {1} nie byłaby już prawidłowa. + + + Argument ma wartość null. Podaj prawidłową wartość argumentu, a następnie spróbuj ponownie uruchomić polecenie. + + + Argument ma wartość null lub element kolekcji argumentów zawiera wartość null. Podaj kolekcję, która nie zawiera żadnych wartości null, a następnie spróbuj ponownie wykonać polecenie. + + + Argument ma wartość null lub jest pusty. Podaj argument, który nie ma wartości null ani nie jest pusty, a następnie spróbuj ponownie wykonać polecenie. + + + Argument ma wartość null, jest pusty lub element kolekcji argumentów zawiera wartość null. Podaj kolekcję, która nie zawiera żadnych wartości null, a następnie spróbuj ponownie wykonać polecenie. + + + Argument ma wartość null, jest pusty lub zawiera tylko znaki białe. Podaj argument, który zawiera znaki inne niż białe, a następnie spróbuj ponownie wykonać polecenie. + + + Element kolekcji argumentów ma wartość null, jest pusty lub składa się tylko ze znaków białych. Podaj kolekcję, która nie zawiera żadnych tych wartości, a następnie spróbuj ponownie wykonać polecenie. + + + Parametr o nazwie „{0}” został zdefiniowany wielokrotnie dla polecenia. + + + Nie można określić aliasu parametru, ponieważ alias o nazwie „{0}” został już zdefiniowany wielokrotnie dla polecenia. + + + Nie można określić parametru „{0}”, ponieważ powoduje konflikt z aliasem parametru o tej samej nazwie dla parametru „{1}”. + + + Skrypt walidacji „{1}” dla argumentu o wartości „{0}” nie zwrócił wyniku True. Ustal, dlaczego skrypt walidacji się nie powiódł, a następnie spróbuj ponownie wykonać polecenie. + + + Argument „{0}” nie zawiera prawidłowej wersji programu PowerShell. Podaj prawidłowy numer wersji, a następnie spróbuj ponownie wykonać polecenie. + + + Nie można sprawdzić poprawności argumentu „{0}”, ponieważ nie jest to prawidłowa nazwa zmiennej. + + + Typ konwersji zadania musi pochodzić z IAstToScriptBlockConverter. + + + Argument ścieżki jest nieprawidłowy. Podaj argument ścieżki, który jest typem ciągu. + + + Argument ścieżki na dysku {0} nie należy do zestawu zatwierdzonych dysków: {1}. Podaj argument ścieżki z zatwierdzonym dyskiem. + + + Argument ścieżki zawiera nieprawidłowe znaki. + + + Argument ścieżki nie ma katalogu głównego. Podaj pełną ścieżkę z katalogiem głównym. + + + Wartość argumentu dla parametru „{0}” nie może być równa null ani być pustym ciągiem. + + + Element członkowski Enum „{0}” nie jest prawidłową wartością parametru „{1}”. Określ jeden z następujących elementów członkowskich i spróbuj ponownie: {2}. + + + Nie można przetworzyć danych wejściowych. Argument „{0}” nie jest zaufany. + + + Sprawdzanie atrybutu ValidateTrustedData nie powiodło się + + + Argument parametru „{0}” nie jest zaufany i nie przejdzie sprawdzania atrybutu ValidateTrustedData w trybie Constrained Language. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/MiniShellErrors.pl.resx b/src/System.Management.Automation/resources/pl/MiniShellErrors.pl.resx new file mode 100644 index 00000000000..bf5aef4a620 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/MiniShellErrors.pl.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 + + + Aktualizacja nie jest obsługiwana dla kategorii konfiguracji obszaru działania {0}. + + + Podczas aktualizowania listy zestawów dla obszaru działania wystąpiły następujące błędy: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/Modules.pl.resx b/src/System.Management.Automation/resources/pl/Modules.pl.resx new file mode 100644 index 00000000000..d9174c404f8 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/Modules.pl.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Określony moduł „{0}” nie został załadowany, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego pliku modułu. + + + Określony moduł „{0}” z numerem wersji „{1}” nie został załadowany, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego pliku modułu. + + + Określony element MaximumVersion „{0}” jest niepoprawny. Jeśli używasz znaku „*”, element MaximumVersion obsługuje tylko jeden taki znak i musi on znajdować się na końcu wartości MaximumVersion. + + + Określony moduł „{0}” z parametrem MaximumVersion „{1}” nie został załadowany, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego pliku modułu. + + + Określony moduł „{0}” z parametrami MinimumVersion „{1}” i MaximumVersion „{2}” nie został załadowany, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego pliku modułu. + + + Wartość MinimumVersion „{0}” nie może być większa niż wartość MaximumVersion „{1}”. + + + Nie załadowano zestawu „{0}”, ponieważ nie znaleziono zestawu o tej nazwie. Sprawdź nazwę zestawu, a następnie spróbuj ponownie. + + + Moduł do przetwarzania „{0}”, wymieniony w polu „{1}” manifestu modułu „{2}”, nie został przetworzony, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego modułu. + + + Nie zwrócono niestandardowego obiektu dla modułu „{0}”, ponieważ parametru -AsCustomObject można używać tylko z modułami skryptowymi. + + + Nie można przetworzyć manifestu modułu „{0}”, ponieważ nie jest to prawidłowy plik manifestu modułu programu PowerShell. Usuń niedozwolone elementy: {1} + + + Przetwarzanie pliku manifestu modułu „{0}” nie spowodowało utworzenia prawidłowego obiektu manifestu. Zaktualizuj plik tak, aby zawierał prawidłowy manifest modułu programu PowerShell. Prawidłowy manifest można utworzyć za pomocą polecenia cmdlet New-ModuleManifest. + + + Nie można zaimportować modułu „{0}”, ponieważ jego manifest zawiera jeden lub więcej nieprawidłowych elementów. Prawidłowe elementy manifestu to ({1}). Usuń nieprawidłowe elementy ({2}), a następnie spróbuj ponownie zaimportować moduł. + + + Tablica skrótów opisująca moduł zawiera jeden lub więcej elementów, które są nieprawidłowe. Prawidłowe elementy to ({0}). Usuń nieprawidłowe elementy ({1}), a następnie spróbuj ponownie. + + + Nie można załadować modułu „{0}”, ponieważ przekroczono limit zagnieżdżania modułów. Moduły można zagnieżdżać tylko do poziomu {1}. Sprawdź kolejność ładowania modułów i zmień ją, aby nie przekraczać limitu zagnieżdżania, a potem spróbuj ponownie uruchomić skrypt. + + + Elementu „ModuleVersion” nie ma w manifeście modułu. Ten element musi istnieć i mieć przypisany numer wersji w formacie „n.n.n.n”. Dodaj brakujący element do pliku „{0}”. + + + Element „{0}” nie jest prawidłowy w pliku manifestu modułu „{2}”: {1} + + + Wersja „{0}” modułu „{1}” nie spełnia wymaganego minimum „{2}”. Sprawdź, czy numer wersji jest obsługiwany, a następnie spróbuj ponownie załadować moduł. + + + Wersja programu PowerShell na tym komputerze to „{0}”. Do uruchomienia modułu „{1}” wymagana jest co najmniej wersja programu PowerShell „{2}”. Sprawdź, czy masz zainstalowaną minimalną wymaganą wersję programu PowerShell, a następnie spróbuj ponownie. + + + Nie można użyć elementu manifestu modułu „NestedModules”, jeśli element „ModuleToProcess” jest modułem binarnym. Edytuj plik manifestu modułu w „{0}”, a następnie spróbuj ponownie. + + + Element „{0}” w manifeście modułu jest nieprawidłowy: {1}. Sprawdź, czy dla tego pola w pliku „{2}” określono prawidłową wartość. + + + Ścieżka manifestu modułu „{0}” jest nieprawidłowa. Wartość argumentu ścieżki musi wskazywać pojedynczy plik z rozszerzeniem „.psd1”. Zmień wartość argumentu ścieżki tak, aby wskazywała prawidłowy plik psd1, a następnie spróbuj ponownie. + + + Klucz ModuleVersion w manifeście modułu „{0}” określa wersję modułu „{1}”, która nie zgadza się z nazwą folderu wersji w lokalizacji „{2}”. Zmień wartość klucza ModuleVersion, aby pasowała do nazwy folderu wersji. + + + Określony wpis NestedModule „{0}” w manifeście modułu „{1}” jest nieprawidłowy. Spróbuj ponownie po zaktualizowaniu tego wpisu prawidłowymi wartościami. + + + Określony wpis RequiredAssemblies „{0}” w manifeście modułu „{1}” jest nieprawidłowy. Spróbuj ponownie po zaktualizowaniu tego wpisu prawidłowymi wartościami. + + + Określony wpis FileList „{0}” w manifeście modułu „{1}” jest nieprawidłowy. Spróbuj ponownie po zaktualizowaniu tego wpisu prawidłowymi wartościami. + + + Określony wpis RequiredModules „{0}” w manifeście modułu „{1}” jest nieprawidłowy. Spróbuj ponownie po zaktualizowaniu tego wpisu prawidłowymi wartościami. + + + Określony wpis ModuleList „{0}” w manifeście modułu „{1}” jest nieprawidłowy. Spróbuj ponownie po zaktualizowaniu tego wpisu prawidłowymi wartościami. + + + Manifest modułu „{0}” zawiera klucz CompatiblePSEditions, który jest obsługiwany tylko w programie PowerShell w wersji „5.1” lub nowszej. Zaktualizuj wartość klucza PowerShellVersion do „5.1” lub nowszej, a następnie spróbuj ponownie. + + + Określona wartość „{0}” dla elementu CompatiblePSEditions zawiera zduplikowane nazwy edycji programu PowerShell. Spróbuj ponownie po usunięciu zduplikowanych nazw edycji programu PowerShell. + + + Wersja określona w kluczu ModuleVersion jest taka sama jak nazwa folderu wersji. + + + Pomijanie folderu wersji {0} w module {1}, ponieważ nie zawiera prawidłowego pliku manifestu modułu. + + + Element „ModuleName” nie istnieje w tabeli skrótów opisującej ten moduł. + + + Elementy „ModuleVersion”, „MaximumVersion” i „RequiredVersion” nie istnieją w tabeli skrótów opisującej ten moduł. Jeden z tych trzech elementów musi istnieć i mieć przypisany numer wersji w formacie „n.n.n.n”. + + + Wymagany moduł „{1}” nie został załadowany. Załaduj moduł albo usuń go z elementu „RequiredModules” w pliku „{0}”. + + + Wymagany moduł „{1}” o identyfikatorze GUID „{2}” nie jest załadowany. Załaduj moduł albo usuń go z elementu „RequiredModules” w pliku „{0}”. + + + Wymagany moduł „{1}” o numerze wersji „{2}” nie jest załadowany. Załaduj moduł albo usuń go z elementu „RequiredModules” w pliku „{0}”. + + + Wymagany moduł „{1}” o parametrze MaximumVersion „{2}” nie jest załadowany. Załaduj moduł albo usuń go z elementu „RequiredModules” w pliku „{0}”. + + + Wymagany moduł „{1}” z wartościami MinimumVersion „{2}” i MaximumVersion „{3}” nie jest załadowany. Załaduj moduł albo usuń go z elementu „RequiredModules” w pliku „{0}”. + + + Nie można znaleźć modułu „{0}” z wersją ModuleVersion „{1}”. + + + Nie można znaleźć modułu „{0}” z wymaganą wersją RequiredVersion „{1}”. + + + Nie można znaleźć modułu „{0}” z wersją MaximumVersion „{1}”. + + + Nie można odnaleźć modułu „{0}” z wartością ModuleVersion „{1}” i MaximumVersion „{2}”. + + + Nie można znaleźć modułu {0}. + + + Nie usunięto żadnych modułów. Sprawdź, czy specyfikacja modułów do usunięcia jest poprawna i czy te moduły istnieją w obszarze działania. + + + Nie można usunąć elementu „{0}”, który został zaimportowany z modułu „{1}”. Przyczyna: {2} + + + Nie można usunąć modułu „{0}”, ponieważ jest tylko do odczytu. Dodaj parametr „Force” do polecenia, aby usunąć moduły tylko do odczytu. + + + Nie można usunąć modułu „{0}”, ponieważ jest oznaczony wartością „constant”. Modułu nie można usunąć, jeśli jest oznaczony wartością „constant”. + + + Nie można usunąć modułu „{0}”, ponieważ jest on wymagany przez „{1}”. Dodaj parametr „Force” do polecenia, aby usunąć moduł. + + + Polecenie cmdlet Export-ModuleMember można wywołać tylko z poziomu modułu. + + + Rozszerzenie „{0}” nie jest prawidłowym rozszerzeniem modułu. Obsługiwane rozszerzenia modułów to „.dll”, „.ps1”, „.psm1”, „.psd1” i „.cdxml”. Popraw rozszerzenie, a następnie spróbuj ponownie dodać plik „{1}”. + + + Tej operacji nie można wykonać na module binarnym. Można ją wykonać tylko na module skryptowym. + + + Plik „{0}” jest niedozwolony, ponieważ nie ma rozszerzenia „.ps1”. + + + Nieznane + + + (c) {0}. Wszelkie prawa zastrzeżone. + + + Usuwanie zaimportowanej funkcji „{0}”. + + + Usuwanie zaimportowanego aliasa „{0}”. + + + Usuwanie zaimportowanej zmiennej „{0}”. + + + Ładowanie modułu ze ścieżki „{0}”. + + + Ładowanie elementu „{0}” ze ścieżki „{1}”. + + + Importowanie metodą dot-sourcing pliku skryptu '{0}'. + + + Importowanie funkcji „{0}”. + + + Importowanie polecenia cmdlet „{0}”. + + + Importowanie aliasu „{0}”. + + + Importowanie zmiennej „{0}”. + + + Eksportowanie polecenia cmdlet „{0}”. + + + Eksportowanie funkcji „{0}”. + + + Eksportowanie aliasu „{0}”. + + + Eksportowanie zmiennej „{0}”. + + + Nazwy niektórych zaimportowanych poleceń z modułu „{0}” zawierają niezatwierdzone czasowniki, przez co mogą być trudniejsze do odnalezienia. Aby znaleźć polecenia z niezatwierdzonymi czasownikami, uruchom ponownie polecenie Import-Module z parametrem Verbose. Aby wyświetlić listę zatwierdzonych czasowników, wpisz polecenie Get-Verb. + + + Polecenie „{0}” w module „{1}” zostało zaimportowane, ale ponieważ jego nazwa nie zawiera zatwierdzonego czasownika, może być trudne do znalezienia. Aby wyświetlić listę zatwierdzonych czasowników, wpisz polecenie Get-Verb. + + + Polecenie „{0}” w module „{2}” zostało zaimportowane, ale ponieważ jego nazwa nie zawiera zatwierdzonego czasownika, może być trudne do znalezienia. Sugerowane alternatywne czasowniki to „{1}”. + + + Niektóre zaimportowane nazwy poleceń zawierają co najmniej jeden z następujących znaków ograniczonych: # , ( ) {{ }} [ ] & - / \ $ ^ ; : „” < > | ? @ ` * % + = ~ + + + Nazwa polecenia „{0}” z modułu „{1}” zawiera co najmniej jeden z następujących znaków ograniczonych: # , ( ) {{ }} [ ] & - / \ $ ^ ; : „” < > | ? @ ` * % + = ~ + + + Tworzenie pliku manifestu modułu „{0}”. + + + {0} (ścieżka: „{1}”) + + + Bieżąca architektura procesora to: {0}. Moduł „{1}” wymaga następującej architektury: {2}. + + + Nazwa bieżącego hosta programu PowerShell to: „{0}”. Moduł „{1}” wymaga następującego hosta programu PowerShell: „{2}”. + + + Bieżący host programu PowerShell to: „{0}” (wersja {1}). Do uruchomienia modułu „{2}” wymagana jest minimalna wersja hosta programu PowerShell „{3}”. + + + Manifest modułu dla modułu „{0}” + + + Wygenerowane przez: {0} + + + Wygenerowano: {0} + + + Plik modułu skryptowego lub binarnego skojarzony z tym manifestem. + + + Moduły do zaimportowania jako moduły zagnieżdżone modułu określonego w lokalizacji RootModule/ModuleToProcess + + + Identyfikator używany do jednoznacznego identyfikowania tego modułu + + + Autor tego modułu + + + Firma lub dostawca tego modułu + + + Oświadczenie o prawach autorskich do tego modułu + + + Numer wersji tego modułu. + + + Opis funkcjonalności udostępnianej przez ten moduł + + + Minimalna wersja aparatu programu PowerShell wymagana przez ten moduł + + + Minimalna wersja środowiska uruchomieniowego języka wspólnego (CLR) wymagana przez ten moduł. {0} + + + Moduły, które muszą zostać zaimportowane do środowiska globalnego przed zaimportowaniem tego modułu + + + Pliki skryptów (.ps1) uruchamiane w środowisku wywołującego przed zaimportowaniem tego modułu. + + + Wpisz pliki (.ps1xml), które mają zostać załadowane podczas importowania tego modułu + + + Pliki formatowania (.ps1xml) do załadowania podczas importowania tego modułu + + + Zestawy, które muszą zostać załadowane przed zaimportowaniem tego modułu + + + Lista wszystkich plików dołączonych do tego modułu + + + Dane prywatne do przekazania do modułu określonego w elemencie RootModule/ModuleToProcess. Może też zawierać tabelę skrótów PSData z dodatkowymi metadanymi modułu używanymi przez program PowerShell. + + + Tagi zastosowane do tego modułu. Pomagają one w odnajdywaniu modułów w galeriach online. + + + Adres URL głównej witryny internetowej tego projektu. + + + Adres URL licencji dla tego modułu. + + + Adres URL ikony reprezentującej ten moduł. + + + Informacje o wersji tego modułu + + + Ciąg wersji wstępnej tego modułu + + + Flaga wskazująca, czy moduł wymaga jawnej akceptacji użytkownika podczas instalowania, aktualizowania lub zapisywania + + + Zewnętrzne moduły zależne tego modułu + + + Koniec tablicy skrótów {0} + + + Wartość parametru PrivateData musi być tabelą skrótów, aby można było utworzyć manifest modułu z następującymi wartościami parametrów: tagi, ProjectUri, LicenseUri, IconUri lub ReleaseNotes. Usuń wartości parametrów tagów, ProjectUri, LicenseUri, IconUri lub ReleaseNotes albo umieść zawartość parametru PrivateData w tabeli skrótów. + + + Parametr PrivateData powinien być zdefiniowany jako tabela skrótów, ale w tym manifeście modułu jest zdefiniowany jako obiekt. Rozważ umieszczenie zawartości parametru PrivateData w tabeli skrótów. Dzięki temu będzie można później dodać do manifestu modułu właściwości tagów, ProjectUri, LicenseUri, IconUri i ReleaseNotes. + + + Określona wartość „{0}” jest nieprawidłowa. Spróbuj ponownie, podając prawidłową wartość. + + + Funkcje do wyeksportowania z tego modułu: aby uzyskać najlepszą wydajność, nie używaj symboli wieloznacznych i nie usuwaj wpisu, a jeśli nie ma funkcji do wyeksportowania, użyj pustej tablicy. + + + Aliasy do wyeksportowania z tego modułu: aby uzyskać najlepszą wydajność, nie używaj symboli wieloznacznych i nie usuwaj wpisu, a jeśli nie ma aliasów do wyeksportowania, użyj pustej tablicy. + + + Polecenia cmdlet do wyeksportowania z tego modułu: aby uzyskać najlepszą wydajność, nie używaj symboli wieloznacznych i nie usuwaj wpisu, a jeśli nie ma poleceń cmdlet do wyeksportowania, użyj pustej tablicy. + + + Zmienne do wyeksportowania z tego modułu + + + Zasoby konfiguracji DSC do wyeksportowania z tego modułu + + + Obsługiwane elementy PSEditions + + + Architektura procesora (brak, X86, Amd64) wymagana przez ten moduł + + + Lista wszystkich modułów dołączonych do tego modułu + + + Minimalna wersja platformy Microsoft .NET Framework wymagana przez ten moduł. {0} + + + Nazwa hosta programu PowerShell wymagana przez ten moduł + + + Minimalna wersja hosta programu PowerShell wymagana przez ten moduł + + + Identyfikator URI HelpInfo tego modułu + + + Ponieważ moduł {0} udostępnia element PSDrive w bieżącej sesji programu PowerShell, nie usunięto żadnych modułów. Zmień bieżącego dostawcę elementu PSDrive, a następnie spróbuj ponownie usunąć moduły. + + + Polecenie cmdlet „{0}” nie zostało zaimportowane, ponieważ w bieżącym zakresie istnieje element o tej samej nazwie. + + + Alias „{0}” nie został zaimportowany, ponieważ w bieżącym zakresie istnieje element o tej samej nazwie. + + + Funkcja „{0}” nie została zaimportowana, ponieważ w bieżącym zakresie istnieje element o tej samej nazwie. + + + Zmienna „{0}” nie została zaimportowana, ponieważ w bieżącym zakresie istnieje element o tej samej nazwie. + + + Symbole wieloznaczne są niedozwolone w elementach „ModuleToProcess”, „RootModule” ani „NestedModules” w manifeście modułu „{0}”. + + + Moduł „{0}” jest modułem podstawowym programu PowerShell. Dodaj parametr „Force” do polecenia, aby usunąć moduły podstawowe. + + + Manifest modułu nie może zawierać jednocześnie elementów „ModuleToProcess” i „RootModule”. Zmień plik manifestu modułu w „{0}”, aby usunąć jeden z tych elementów, a następnie spróbuj ponownie. + + + Element manifestu modułu „ModuleToProcess” jest przestarzały. Zamiast tego użyj elementu „RootModule”. + + + Domyślny prefiks poleceń eksportowanych z tego modułu. Zmień domyślny prefiks przy użyciu polecenia Import-Module -Prefix. + + + Nie można jednocześnie określić parametrów „Global” i „Scope”. Usuń jeden z tych parametrów, a następnie spróbuj ponownie uruchomić polecenie. + + + Wymagany moduł „{0}” nie został załadowany. Moduł „{0}” ma element requiredModule „{1}” w manifeście modułu „{2}”, który wskazuje zależność cykliczną. + + + Wymagany moduł „{0}” nie został załadowany, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego pliku modułu. + + + Niektórych poleceń z modułu {0} nie można zaimportować za pośrednictwem polecenia CimSession. Aby uzyskać wszystkie polecenia, sprawdź, czy na serwerze zdalnym włączono zdalne zarządzanie programem PowerShell, a następnie spróbuj dodać parametr PSSession do polecenia cmdlet Import-Module. + + + Moduł {0} jest ładowany w programie Windows PowerShell przy użyciu sesji zdalnej {1}; pamiętaj, że wszystkie dane wejściowe i wyjściowe poleceń z tego modułu będą obiektami po deserializacji. Jeśli chcesz załadować ten moduł do programu PowerShell, użyj składni „Import-Module -SkipEditionCheck”. + + + Wykryto program Windows PowerShell w wersji {0}. Do ładowania modułów przy użyciu funkcji zgodności z programem Windows PowerShell wymagana jest wersja programu Windows PowerShell 5.1. Aby włączyć tę funkcję, zainstaluj funkcję Windows Management Framework (WMF) 5.1 z https://aka.ms/WMF5Download. + + + Ładowanie modułu „{0}” przy użyciu funkcji zgodności z programem Windows PowerShell jest blokowane przez ustawienie „WindowsPowerShellCompatibilityModuleDenyList” w pliku konfiguracji programu PowerShell. + + + Modułu {0} nie można zaimportować za pośrednictwem polecenia CimSession. Spróbuj użyć parametru PSSession polecenia cmdlet Import-Module. + + + Wartość architektury procesora {0} nie jest obsługiwana. Uruchom ponownie polecenie New-ModuleManifest, określając jedną z następujących obsługiwanych wartości wyliczenia dla architektury procesora: brak, MSIL, X86, Amd64, Arm + + + Uruchamianie polecenia cmdlet Get-Module na komputerze zdalnym może wyświetlać tylko dostępne moduły. Dodaj parametr ListAvailable do polecenia, a następnie spróbuj ponownie. + + + Moduł „{0}” nie został zaimportowany, ponieważ przystawka „{0}” została już zaimportowana. + + + Symbole wieloznaczne są niedozwolone w elemencie „RequiredAssemblies” w manifeście modułu „{0}”. + + + Wartość klucza {0} w elemencie {1} ma wartość {2}, a moduł ma zagnieżdżone moduły. Gdy plik CDXML jest modułem głównym, polecenie Import-Module kończy się niepowodzeniem, ponieważ polecenia w modułach zagnieżdżonych nie mogą zostać wyeksportowane. Przenieś plik CDXML do klucza NestedModules i spróbuj ponownie uruchomić polecenie. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Niepowodzenie polecenia zdalnego: {0}: {{0}} + + + Nie można wygenerować serwerów proxy dla modułu zdalnego „{0}”. {{0}} + + + Nie można przetworzyć modułu zdalnego {0}. {1} + + + Nie można odebrać danych modułu ze zdalnej sesji CimSession. {0} + + + Wymagany moduł „{0}” o identyfikatorze GUID „{1}” i wersji „{2}” nie został załadowany, ponieważ w żadnym katalogu modułów nie znaleziono prawidłowego pliku modułu. + + + Na serwerze CIM nie znaleziono dostawcy CIM na potrzeby odnajdywania modułów. {0} + {0} is a placeholder for a more detailed error message + + + Nie można zweryfikować wersji platformy Microsoft .NET Framework {0}, ponieważ nie ma jej na liście dozwolonych wersji. + + + Analizowanie elementu {0}. + {0} should not be localized, is used to contain a file path. + + + Przygotowywanie modułów do pierwszego użycia. + + + Trwa wyszukiwanie dostępnych modułów... + + + Wyszukiwanie udziału UNC {0}. + {0} should not be localized, is used to contain a file path. + + + Uruchamianie polecenia cmdlet Get-Module na komputerze zdalnym jest możliwe tylko w przypadku nazw modułów, które nie zawierają ścieżki. Parametr „Name” ma element „{0}”, który jest rozpoznawany jako ścieżka. Zaktualizuj parametr „Name” tak, aby nie zawierał elementów ścieżki, a następnie spróbuj ponownie. + + + Uruchamianie polecenia cmdlet Get-Module bez parametru ListAvailable nie jest obsługiwane w przypadku nazw modułów zawierających ścieżkę. Parametr „Name” ma element „{0}”, który jest rozpoznawany jako ścieżka. Zaktualizuj parametr „Name” tak, aby nie zawierał elementów ścieżki, a następnie spróbuj ponownie. + + + Określony moduł „{0}” nie został znaleziony. Zaktualizuj parametr „Name”, aby wskazywał prawidłową ścieżkę, i spróbuj ponownie. + + + Wypełnianie właściwości RepositorySourceLocation dla modułu {0}. + + + Moduł do przetwarzania „{0}”, wymieniony w polu „{1}” manifestu modułu „{2}”, nie został przetworzony. {3} + + + To wymaganie wstępne dotyczy tylko edycji programu PowerShell na komputery stacjonarne. + + + Moduł „{0}” nie obsługuje bieżącej edycji programu PowerShell „{1}”. Obsługiwane edycje to „{2}”. Użyj polecenia „Import-Module -SkipEditionCheck”, aby pominąć sprawdzanie zgodności tego modułu. + + + Moduł „{0}” obsługuje edycję programu PowerShell „{1}” i nie może zostać załadowany niejawnie przy użyciu funkcji zgodności z systemem Windows, ponieważ jest ona wyłączona w pliku ustawień. Użyj polecenia „Import-Module -UseWindowsPowerShell”, aby załadować ten moduł w programie Windows PowerShell, lub polecenia „Import-Module -SkipEditionCheck”, aby spróbować załadować go w bieżącym programie PowerShell. + + + Dla funkcji eksperymentalnej zadeklarowanej w manifeście modułu należy określić wartość ciągu, która nie jest pusta. + + + Znaleziono co najmniej jedną nieprawidłową nazwę funkcji eksperymentalnej: {0}. Nazwa funkcji eksperymentalnej modułu powinna mieć postać „ModuleName.FeatureName”. + + + Nie można użyć parametru przełącznika -SkipEditionCheck bez parametru przełącznika -ListAvailable. + + + Importowanie plików *.ps1 jako modułów jest niedozwolone w trybie ConstrainedLanguage. + + + Wystąpił błąd podczas ładowania modułu skryptu {0}, ponieważ ma on inny tryb językowy niż manifest modułu. Tryb językowy manifestu to {1}, a tryb językowy modułu to {2}. Upewnij się, że wszystkie pliki modułu są podpisane lub w inny sposób znajdują się na liście dozwolonych aplikacji. + + + Ten moduł używa operatora dot-source podczas eksportowania funkcji przy użyciu symboli wieloznacznych, a jest to niedozwolone, gdy system wymusza weryfikację aplikacji. + + + Nie można wyeksportować elementów modułu z modułu, który ma inny tryb języka niż uruchomiona sesja. + + + Nie można utworzyć nowego modułu, gdy sesja jest w trybie ConstrainedLanguage. + + + Nie można znaleźć wbudowanego modułu „{0}”, który jest zgodny z edycją „Core”. Upewnij się, że wbudowane moduły programu PowerShell są dostępne. Zazwyczaj są dostarczane z pakietem programu PowerShell w ścieżce modułu $PSHOME i są wymagane do prawidłowego działania programu PowerShell. + + + Polecenie cmdlet Export-ModuleMember + + + Eksportowanie elementów modułu w trybie języka z ograniczeniami zakończy się niepowodzeniem, ponieważ moduł „{0}” ma tryb języka „{1}”, który różni się od bieżącej sesji „{2}”. + + + Niejawny eksport funkcji modułu + + + Niejawny eksport funkcji dla modułu „{0}” zostanie odrzucony, ponieważ moduł jest zaufany (działa w trybie Full Language), ale sesja nie jest zaufana (działa w trybie Constrained Language). Najlepszym rozwiązaniem jest zawsze eksportowanie funkcji modułu osobno, używając pełnej nazwy. + + + Importowanie pliku skryptu jako modułu + + + Importowanie pliku skryptu „{0}” jako modułu będzie niedozwolone w trybie ConstrainedLanguage. + + + Moduł zawiera operator dot-source + + + Importowanie modułu „{0}” zakończy się niepowodzeniem w trybie języka z ograniczeniami, ponieważ eksportuje funkcje przy użyciu symboli wieloznacznych, a jednocześnie używa operatora dot-source. + + + „Funkcje eksportowane przez moduł + + + Moduł „{0}” eksportuje funkcje przy użyciu symboli wieloznacznych w nazwie. Wszystkie nazwy funkcji zagnieżdżonych modułów zostaną usunięte podczas działania w trybie języka z ograniczeniami. + + + „Polecenie cmdlet New-Module + + + Nowy moduł z niezaufanej sesji języka z ograniczeniami będzie blokowany przed udostępnianiem bloku skryptu FullLanguage. + + + „Niezgodne tryby języka modułu + + + Trwa ładowanie modułu zależnego, który ma inny tryb języka niż moduł nadrzędny. W trybie Constrained Language nie będzie to dozwolone. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/MshHostRawUserInterfaceStrings.pl.resx b/src/System.Management.Automation/resources/pl/MshHostRawUserInterfaceStrings.pl.resx new file mode 100644 index 00000000000..32cbee74d30 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/MshHostRawUserInterfaceStrings.pl.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 + + + Wartość „{0}” musi być większa lub równa „{1}”. + + + Wartość „{0}” musi być liczbą dodatnią. + + + Wszystkie ciągi mają wartość null lub są puste. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/MshSignature.pl.resx b/src/System.Management.Automation/resources/pl/MshSignature.pl.resx new file mode 100644 index 00000000000..ebe4f2a27da --- /dev/null +++ b/src/System.Management.Automation/resources/pl/MshSignature.pl.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 + + + Zweryfikowano podpis. + + + Plik {0} nie jest podpisany cyfrowo. Nie można uruchomić tego skryptu w bieżącym systemie. Aby uzyskać więcej informacji na temat uruchamiania skryptów i ustawiania zasad wykonywania, zobacz about_Execution_Policies na https://go.microsoft.com/fwlink/?LinkID=135170 + + + Zawartość pliku {0} mogła zostać zmieniona przez nieautoryzowanego użytkownika lub proces, ponieważ skrót pliku jest niezgodny ze skrótem przechowywanym w podpisie cyfrowym. Nie można uruchomić skryptu w określonym systemie. Aby uzyskać więcej informacji, uruchom polecenie Get-Help about_Signing. + + + Plik {0} jest podpisany, ale podpisywanie nie jest zaufane w tym systemie. + + + Nie można podpisać pliku, ponieważ system nie obsługuje operacji podpisywania plików ({0}) . + + + Nie można podpisać pliku, ponieważ system nie obsługuje operacji podpisywania plików, które nie mają rozszerzenia nazwy pliku. + + + Nie można zweryfikować podpisu, ponieważ jest on niezgodny z bieżącym systemem. + + + Nie można zweryfikować podpisu, ponieważ jest on niezgodny z bieżącym systemem. Algorytm wyznaczania wartości skrótu jest nieprawidłowy. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/MshSnapInCmdletResources.pl.resx b/src/System.Management.Automation/resources/pl/MshSnapInCmdletResources.pl.resx new file mode 100644 index 00000000000..a37f64c472d --- /dev/null +++ b/src/System.Management.Automation/resources/pl/MshSnapInCmdletResources.pl.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 + + + Nie można wykonać operacji. Określone polecenie cmdlet nie jest obsługiwane w powłoce niestandardowej. + + + Nie znaleziono żadnych przystawek programu PowerShell pasujących do wzorca „{0}”. Sprawdź wzorzec, a następnie spróbuj ponownie wykonać polecenie. + + + Format określonej nazwy przystawki był nieprawidłowy. Nazwy przystawek programu PowerShell mogą zawierać tylko znaki alfanumeryczne, łączniki, podkreślenia i kropki. Sprawdź nazwę, a następnie spróbuj ponownie wykonać operację. + + + Nie można dodać przystawki {0} programu PowerShell, ponieważ jest to moduł systemowy programu PowerShell. Załaduj moduł za pomocą polecenia Import-Module. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/MshSnapinInfo.pl.resx b/src/System.Management.Automation/resources/pl/MshSnapinInfo.pl.resx new file mode 100644 index 00000000000..f041fb73380 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/MshSnapinInfo.pl.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 + + + Nie można uzyskać dostępu do informacji dotyczących rejestru programu PowerShell. + + + Nie można uzyskać dostępu do informacji dotyczących rejestru aparatu programu PowerShell. + + + Nie można uzyskać dostępu do informacji PublicKeyToken. + + + Wersja {0} programu PowerShell nie jest dostępna na tym komputerze. + + + Przystawka programu PowerShell „{0}” nie jest zainstalowana na tym komputerze. + + + Nie określono wartości obowiązkowej {0} dla klucza rejestru {1}. + + + Wartość obowiązkowa {0} ma niepoprawny format dla klucza rejestru {1}. Oczekiwany format to „string”. + + + Wartość obowiązkowa {0} ma niepoprawny format dla klucza rejestru {1}. Oczekiwany format to „multistring”. + + + Nie można odnaleźć wymaganych informacji w rejestrze lub brakujących plików kluczy. Nie można załadować niektórych poleceń cmdlet. + + + Nie zarejestrowano żadnych przystawek dla programu PowerShell w wersji {0}. + + + Nie można pobrać zasobu ciągu, ponieważ czytnik został usunięty. + + + Wartość wersji {0} nie została określona lub jest niepoprawna dla klucza rejestru {1}. + + + Nie znaleziono atrybutu [PSVersion] dla typu programu PowerShell {0}. Dodaj atrybut PSVersion do typu przy użyciu [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/NativeCP.pl.resx b/src/System.Management.Automation/resources/pl/NativeCP.pl.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/NativeCP.pl.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PSCommandStrings.pl.resx b/src/System.Management.Automation/resources/pl/PSCommandStrings.pl.resx new file mode 100644 index 00000000000..4ad99703ca6 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PSCommandStrings.pl.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 + + + Do dodania parametru jest wymagane polecenie. Przed dodaniem parametru należy dodać polecenie do {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PSConfigurationStrings.pl.resx b/src/System.Management.Automation/resources/pl/PSConfigurationStrings.pl.resx new file mode 100644 index 00000000000..e7b5611cdb7 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PSConfigurationStrings.pl.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 + + + Program PowerShell przestał działać z powodu problemu z zabezpieczeniami: nie można odczytać pliku konfiguracji: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PSDataBufferStrings.pl.resx b/src/System.Management.Automation/resources/pl/PSDataBufferStrings.pl.resx new file mode 100644 index 00000000000..5bf7bcb0ec9 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PSDataBufferStrings.pl.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 + + + Określony indeks jest mniejszy od zera lub większy od liczby elementów w buforze. Indeks powinien znajdować się w zakresie {0}-{1}. + + + Nie można przekonwertować odwołania null na typ wartości. + + + Nie można przekonwertować wartości z typu {0} na typ {1}. + + + Nie można dodać obiektów do zamkniętego buforu. Upewnij się, że bufor jest otwarty, aby operacje dodawania i wstawiania mogły się powieść. + + + Właściwość SerializeInput można ustawić tylko dla typu PSObject w obiekcie PSDataCollection. Ustaw właściwość SerializeInput na false albo zmień typ kolekcji na PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PSListModifierStrings.pl.resx b/src/System.Management.Automation/resources/pl/PSListModifierStrings.pl.resx new file mode 100644 index 00000000000..f4b5f9180e7 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PSListModifierStrings.pl.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 + + + Wykryto następujący modyfikator nieznanej listy: „{0}”. Prawidłowe modyfikatory listy to Add, Remove i Replace. + + + Nie można zastosować aktualizacji, ponieważ obiekt nie jest obsługiwanym typem kolekcji. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PSStyleStrings.pl.resx b/src/System.Management.Automation/resources/pl/PSStyleStrings.pl.resx new file mode 100644 index 00000000000..4a8d09350fd --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PSStyleStrings.pl.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Określony ciąg zawiera zawartość do wydrukowania, gdy powinien zawierać tylko sekwencje ucieczki ANSI: {0} + + + Maksymalna długość renderowania postępu musi wynosić co najmniej 18, aby renderowanie został wykonane poprawnie. + + + Podczas dodawania lub usuwania rozszerzeń rozszerzenie musi rozpoczynać się od kropki. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ParameterBinderStrings.pl.resx b/src/System.Management.Automation/resources/pl/ParameterBinderStrings.pl.resx new file mode 100644 index 00000000000..60bd82659ab --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ParameterBinderStrings.pl.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można znaleźć parametru pasującego do nazwy parametru „{1}”. + + + Nie można odnaleźć parametru pozycyjnego akceptującego argument „{1}”. + + + Brak argumentu dla parametru „{1}”. Określ parametr typu „{2}” i spróbuj ponownie. + + + Nie można przetworzyć parametru, ponieważ nazwa parametru „{1}” jest niejednoznaczna. Możliwe dopasowania to:{6}. + + + Nie można przekonwertować elementu „{6}” na typ „{2}” wymagany przez parametr „{1}”. {7} + + + Nie można powiązać parametru „{1}”. {6} + + + Nie można powiązać parametrów pozycyjnych „{1}”. + + + Nie można powiązać parametrów pozycyjnych, ponieważ nie podano żadnych nazw. + + + Nie można rozpoznać ustawionego parametru za pomocą podanych nazwanych parametrów. Nie można użyć co najmniej jednego wystawionego parametru razem lub podano niewystarczającą liczbę parametrów. + + + Nie można przetworzyć polecenia z powodu co najmniej jednego brakującego obowiązkowego parametru:{1}. + + + Nie można określić parametru „{1}” w zestawie parametrów „{6}”. + + + Nie można powiązać parametru, ponieważ parametr „{1}” został określony więcej niż raz. Aby podać wiele wartości parametrów, które mogą akceptować wiele wartości, użyj składni tablicy. Na przykład „-parameter value1,value2,value3”. + + + Nie można obliczyć parametru „{1}”, ponieważ jego argument jest określony jako blok skryptu i nie ma danych wejściowych. Nie można obliczyć bloku skryptu bez danych wejściowych. + + + Wprowadzanie danych wejściowych do bloku skryptu dla parametru „{1}” nie powiodło się. {6} + + + Nie można obliczyć parametru „{1}”, ponieważ jego dane wejściowe argumentu nie wygenerowały żadnych danych wyjściowych. + + + Obiekt wejściowy nie może być powiązany z żadnymi parametrami polecenia, ponieważ polecenie nie pobiera danych wejściowych potoku lub dane wejściowe i jego właściwości nie są zgodne z żadnym z parametrów, które pobierają dane wejściowe potoku. + + + Nie można powiązać obiektu wejściowego, ponieważ nie zawiera on informacji wymaganych do powiązania wszystkich obowiązkowych parametrów: {6} + + + Nie można przetworzyć danych wejściowych potoku, ponieważ nie można pobrać wartości domyślnej parametru „{1}”. {6} + + + Nie można pobrać parametrów dynamicznych dla polecenia cmdlet. {6} + + + Podaj wartości następujących parametrów: + + + polecenie cmdlet {0} na pozycji potoku poleceń {1} + + + Nie można przetworzyć przekształcenia argumentu dla parametru „{1}”. {6} + + + {6} + + + Nie można zweryfikować argumentu dla parametru „{1}”. {6} + + + Nie można powiązać parametru „{1}” z obiektem docelowym. {6} + + + Nie można powiązać argumentu z parametrem „{1}”, ponieważ ma on wartość null. + + + Nie można powiązać argumentu z parametrem „{1}”, ponieważ jest to pusty ciąg. + + + Nie można powiązać argumentu z parametrem „{1}”, ponieważ jest to pusta kolekcja. + + + Nie można powiązać argumentu z parametrem „{1}”, ponieważ jest to pusta tablica. + + + Nie można przetworzyć polecenia. Parametr „{0}” jest zdefiniowany wiele razy. + + + Nie można powiązać polecenia cmdlet {0}, ponieważ parametr „{1}” jest typu „{2}” i nie można zidentyfikować metody Add() lub istnieje wiele metod Add(). {6} + + + Nie można powiązać polecenia cmdlet {0}, ponieważ parametr „{1}” zdefiniowany w czasie wykonywania został dodany do elementu RuntimeDefinedParameterDictionary z kluczem „{6}”. Klucz musi być taki sam jak RuntimeDefinedParameter.Name. + + + Nie można powiązać argumentu z parametrem „{1}”, ponieważ parametry PSTypeNames argumentu nie są zgodne z parametrem PSTypeName wymaganym przez parametr: {6}. + + + W $PSDefaultParameterValues dla parametru pasującego do następującej nazwy lub aliasu zdefiniowano wiele różnych wartości domyślnych: {0}. Te wartości domyślne zostały zignorowane. + + + Następująca nazwa lub alias zdefiniowany w $PSDefaultParameterValues dla tego polecenia cmdlet jest rozpoznawany jako wiele parametrów: {0}. Wartość domyślna została zignorowana. + + + {6} Przyczyną tego błędu może być zastosowanie domyślnego powiązania parametrów. Możesz wyłączyć domyślne powiązanie parametrów w $PSDefaultParameterValues, ustawiając $PSDefaultParameterValues["Wyłączone"] na $true, a następnie próbując ponownie. Następujące parametry domyślne zostały pomyślnie powiązane z tym poleceniem cmdlet w przypadku wystąpienia błędu:{7} + + + {6} Ten błąd może być spowodowany zastosowaniem domyślnego powiązania parametrów. Możesz wyłączyć domyślne powiązanie parametrów w $PSDefaultParameterValues, ustawiając $PSDefaultParameterValues["Wyłączone"] na $true i ponów próbę. Następujący parametr domyślny został pomyślnie powiązany z tym poleceniem cmdlet w przypadku wystąpienia błędu:{7} + + + Powiązanie wartości domyślnej „{0}” z parametrem „{1}” nie powiodło się: {2} + + + Klucz „{0}” nie ma prawidłowego formatu. Aby uzyskać informacje o poprawnym formacie, zobacz about_Parameters_Default_Values na stronie https://go.microsoft.com/fwlink/?LinkId=228266. + + + Klucze „{0}” nie mają prawidłowych formatów. Aby uzyskać informacje o poprawnym formacie, zobacz about_Parameters_Default_Values na stronie https://go.microsoft.com/fwlink/?LinkId=228266. + + + Parametr „{0}” jest przestarzały. {1} + + + Klucz „{0}” typu „{1}” nie jest wartością ciągu. Element DefaultParameterDictionary akceptuje tylko klucze wartości ciągu. + + + Klucz „{0}” został już dodany do słownika. + + + Wywołanie metody lub właściwości jest niedozwolone + + + Wywołanie metody lub właściwości „{0}” w typie „{1}” nie będzie dozwolone w trybie ograniczonego języka dla niezaufanych skryptów. + + + Tworzenie typu jest niedozwolone + + + Tworzenie typu „{0}” nie będzie dozwolone podczas wiązania parametrów w trybie ograniczonego języka dla niezaufanych skryptów. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ParserStrings.pl.resx b/src/System.Management.Automation/resources/pl/ParserStrings.pl.resx new file mode 100644 index 00000000000..8f9f9df0625 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ParserStrings.pl.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Nie można załadować zestawu „{0}”. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PathUtilsStrings.pl.resx b/src/System.Management.Automation/resources/pl/PathUtilsStrings.pl.resx new file mode 100644 index 00000000000..f1c6fedb106 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PathUtilsStrings.pl.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Kodowanie „UTF-7” jest przestarzałe. Użyj UTF-8. + + + Plik {0} już istnieje i określono {1}. + + + Nie można otworzyć pliku, ponieważ bieżący dostawca ({0}) nie może otworzyć pliku. + + + Nie można wykonać operacji, ponieważ ścieżka wskazuje na więcej niż jeden plik. To polecenie nie może działać na wielu plikach. + + + Nie można wykonać operacji, ponieważ ścieżka z symbolami wieloznacznymi {0} nie wskazuje na plik. + + + Nieznane kodowanie {0}; prawidłowe wartości to {1}. + + + Katalog „{0}” już istnieje. Użyj parametru -Force, jeśli chcesz zastąpić katalog i znajdujące się w nim pliki. + + + Ścieżka modułu użytkownika nie istnieje, więc nie można utworzyć folderu modułu dla podanej nazwy modułu „{0}”. + + + Nie można utworzyć modułu {0} z następującego powodu: {1}. Użyj innego argumentu dla parametru -OutputModule i spróbuj ponownie. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Nie można załadować modułu, ponieważ został wygenerowany przy użyciu niezgodnej wersji polecenia cmdlet {0}. Wygeneruj moduł za pomocą polecenia cmdlet {0} z bieżącej sesji i spróbuj załadować go ponownie. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PipelineStrings.pl.resx b/src/System.Management.Automation/resources/pl/PipelineStrings.pl.resx new file mode 100644 index 00000000000..f4068aa67f4 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PipelineStrings.pl.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można przetworzyć wystąpienia polecenia cmdlet, ponieważ wystąpienie polecenia cmdlet jest używane przez inny potok. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Nie można wykonać operacji, ponieważ potok został uruchomiony. Zatrzymaj potok i spróbuj ponownie wykonać operację. + + + Nie można kontynuować uruchamiania polecenia cmdlet, ponieważ zasady zatrzymywania uniemożliwiają uruchamianie poleceń cmdlet. + + + Nie można uruchomić potoku, ponieważ pierwsze polecenie cmdlet w potoku próbuje odczytać dane wejściowe z wyników poprzedniego polecenia cmdlet. Zmodyfikuj pierwsze polecenie cmdlet, usuń pierwsze polecenie cmdlet lub dodaj do potoku polecenie cmdlet, którego dane wyjściowe są wymagane przez pierwsze polecenie cmdlet, a następnie spróbuj ponownie uruchomić potok. + + + Nie można przetworzyć numeru polecenia cmdlet. Funkcja ReadFromCommand musi określać identyfikator polecenia cmdlet, które zostało już dodane do potoku. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Nie można odczytać danych wyjściowych funkcji ReadFromCommand i ReadErrorQueue, ponieważ inne polecenie cmdlet odczytuje już dane wyjściowe. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + Nie można uruchomić potoku, ponieważ nie ma żadnych poleceń. Dodaj co najmniej jedno polecenie do potoku, a następnie uruchom je ponownie. + + + Nie można wykonać operacji potoku, ponieważ nie została jeszcze uruchomiona. Przed wywołaniem metody End() w potoku schodkowym należy wywołać metodę Begin(). + + + Metody WriteObject i WriteError nie mogą być wywoływane spoza zastąpień metod BeginProcessing, ProcessRecord i EndProcessing oraz mogą być wywoływane tylko z tego samego wątku. Sprawdź, czy polecenie cmdlet wykonuje te wywołania poprawnie, lub skontaktuj się z pomocą techniczną firmy Microsoft. + + + Polecenie cmdlet zgłosiło wyjątek po wywołaniu metody ThrowTerminatingError. +Pierwszy wyjątek to „{0}” ze śladem stosu „{1}”. +Drugi wyjątek to „{2}” ze śladem stosu „{3}”. + + + Nie można wywołać metod WriteObject i WriteError po zamknięciu potoku. Skontaktuj się z pomocą techniczną firmy Microsoft. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Wystąpił błąd podczas tworzenia potoku. + + + Ten potok nie obsługuje semantyki rozłączenia-połączenia. + + + Nie można połączyć tego potoku, ponieważ nie jest on w stanie rozłączenia. + + + Obiekt obszaru działania ma skojarzone z nim polecenie zdalne o wartości null. Nie można utworzyć rozłączonego obiektu RemotePipeline, ponieważ nie określono polecenia zdalnego. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/PowerShellStrings.pl.resx b/src/System.Management.Automation/resources/pl/PowerShellStrings.pl.resx new file mode 100644 index 00000000000..220ee154505 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/PowerShellStrings.pl.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 + + + Stan bieżącego wystąpienia programu PowerShell jest nieprawidłowy dla tej operacji. + + + Nie można wykonać operacji, ponieważ polecenie zostało już uruchomione. Poczekaj na ukończenie polecenia lub zatrzymaj je, a następnie spróbuj ponownie wykonać operację. + + + Nie określono żadnych poleceń. + + + Wystąpienie programu PowerShell nie jest w prawidłowym stanie do utworzenia zagnieżdżonego wystąpienia programu PowerShell. Zagnieżdżone wystąpienia programu PowerShell powinny być tworzone tylko w uruchomionym wystąpieniu programu PowerShell. + + + Nie można wykonać operacji, ponieważ obszar działania nie jest w stanie „{0}”. Bieżący stan obszaru działania to „{1}”. + + + Nie można asynchronicznie wywoływać zagnieżdżonych wystąpień programu PowerShell. Użyj metody Invoke. + + + Obiekt {0} nie został utworzony przez wywołanie {1} w przypadku tego wystąpienia programu PowerShell. + + + Gdy obszar działania jest skonfigurowany do ponownego użycia wątku, stan komórki w ustawieniach wywołania musi być zgodny z obszarem działania. + + + Gdy obszar działania jest ustawiony do używania bieżącego wątku, stan komórki w ustawieniach wywołania musi być zgodny z bieżącym wątkiem. + + + Do dodania parametru jest wymagane polecenie. Przed dodaniem parametru należy dodać polecenie do wystąpienia programu PowerShell. + + + Klucze w słowniku muszą być ciągami. + + + Brak dostępnego obszaru działania do uruchomienia poleceń w tym wątku. Można podać go we właściwości DefaultRunspace typu System.Management.Automation.Runspaces.Runspace. Polecenie, które próbowano wywołać, to: {0} + + + Nie można połączyć tego obiektu programu PowerShell, ponieważ nie jest on skojarzony ze zdalnym obszarem działania lub pulą obszarów działania. + + + Uruchomione polecenie zostało rozłączone, ale nadal działa na serwerze zdalnym. Połącz się ponownie, aby uzyskać stan operacji polecenia i dane wyjściowe. + + + Nie można wykonać operacji, ponieważ bieżąca sesja programu PowerShell jest w stanie Rozłączono. Połącz się z tą sesją programu PowerShell, a następnie zaczekaj na zakończenie polecenia lub zatrzymaj je. + + + Nie można wykonać operacji, ponieważ bieżąca sesja programu PowerShell jest w stanie Rozłączono. Połącz się z tą sesją programu PowerShell, a następnie spróbuj ponownie. + + + Próba nawiązania połączenia ze zdalnym poleceniem nie powiodła się. + + + Nie można wykonać operacji, ponieważ polecenie jest obecnie zatrzymywane. Poczekaj na zakończenie zatrzymywania polecenia, a następnie spróbuj ponownie wykonać operację. + + + Brak dostępnego obszaru działania do uruchomienia poleceń w tym wątku. Można podać go we właściwości DefaultRunspace typu System.Management.Automation.Runspaces.Runspace. Bieżące wystąpienie programu PowerShell nie zawiera żadnego polecenia do wywołania. + + + Nie można utworzyć obiektu programu PowerShell, który używa bieżącego obszaru działania, ponieważ nie ma dostępnego bieżącego obszaru działania. Bieżący obszar działania może być uruchamiany, na przykład po utworzeniu ze stanem sesji początkowej. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ProgressRecordStrings.pl.resx b/src/System.Management.Automation/resources/pl/ProgressRecordStrings.pl.resx new file mode 100644 index 00000000000..7d3e70ac1a5 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ProgressRecordStrings.pl.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można przetworzyć argumentu, ponieważ {0} nie może mieć wartości ujemnej. + + + Nie można przetworzyć argumentu, ponieważ wartość {0} nie może być null ani pusta. + + + Nie można ustawić procentu, ponieważ {0} nie może być większa niż 100. + + + ParentActivityId nie może być taki sam jak ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ProviderBaseSecurity.pl.resx b/src/System.Management.Automation/resources/pl/ProviderBaseSecurity.pl.resx new file mode 100644 index 00000000000..5ea4e20f07c --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ProviderBaseSecurity.pl.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 + + + Nie można użyć interfejsu, ponieważ interfejs ISecurityDescriptorCmdletProvider nie jest obsługiwany przez tego dostawcę. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/ProxyCommandStrings.pl.resx b/src/System.Management.Automation/resources/pl/ProxyCommandStrings.pl.resx new file mode 100644 index 00000000000..a4366b59720 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/ProxyCommandStrings.pl.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 + + + Parametr „help” nie jest rozpoznawany jako prawidłowy obiekt HelpInfo utworzony przez polecenie „get-help”. + + + Nie można wygenerować polecenia serwera proxy, ponieważ element CommandMetadata nie ma nazwy. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/RegistryProviderStrings.pl.resx b/src/System.Management.Automation/resources/pl/RegistryProviderStrings.pl.resx new file mode 100644 index 00000000000..ecfceb1051a --- /dev/null +++ b/src/System.Management.Automation/resources/pl/RegistryProviderStrings.pl.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ustaw element + + + Element: {0} Wartość: {1} + + + Wyczyść element + + + Element: {0} + + + Nowy element + + + Element: {0} + + + Usuń klucz + + + Element: {0} + + + Kopiuj klucz + + + Element: {0} Miejsce docelowe: {1} + + + Zmień nazwę elementu + + + Element: {0} NewName: {1} + + + Przenieś element + + + Element: {0} Miejsce docelowe: {1} + + + Ustaw właściwość + + + Element: {0} Właściwość: {1} + + + Wyczyść właściwość + + + Element: {0} Właściwość: {1} + + + Nowa właściwość + + + Element: {0} Właściwość: {1} + + + Usuń właściwość + + + Element: {0} Właściwość: {1} + + + Zmień nazwę właściwości. + + + Element: {0} SourceProperty: {1} DestinationProperty: {2} + + + Kopiuj właściwość + + + Element: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Przenieś właściwość + + + Element: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Operacja nie została przetworzona. Podana lokalizacja nie zezwala na tę operację. + + + Operacja nie jest dozwolona w lokalizacji źródłowej. + + + Operacja nie jest dozwolona w lokalizacji docelowej. + + + Ustawienia konfiguracji komputera lokalnego + + + Ustawienia oprogramowania dla bieżącego użytkownika + + + Klucz w tej ścieżce już istnieje. + + + Nie można wykonać operacji, ponieważ ścieżka docelowa jest podrzędna względem ścieżki źródłowej. + + + Właściwość już istnieje. + + + Właściwość {0} nie istnieje w ścieżce {1}. + + + Klucz rejestru w określonej ścieżce nie istnieje. + + + Nie można powiązać parametru „Type”. Nie można przekonwertować „{0}” na „{1}”. Możliwe wartości wyliczenia to „String, ExpandString, Binary, DWord, MultiString, QWord, Unknown”. + + + Klucz {0} został utworzony, ale nie można ustawić wartości domyślnej. + + + Nie można utworzyć dysku z określonym katalogiem głównym. Ścieżka katalogu głównego nie istnieje. + + + Nie można zmienić nazwy elementu, ponieważ element o tej nazwie już istnieje w tym samym kontenerze. + + + Nazwa klucza rejestru musi zaczynać się od prawidłowej nazwy klucza podstawowego. + + + Argument podklucza jest nieprawidłowy. + + + Nie można usunąć drzewa podklucza, ponieważ podklucz nie istnieje. + + + Nie istnieje żadna wartość o tej nazwie. + + + Wartość wyliczenia {0} jest nieprawidłowa. + + + Należy określić argument wartości. + + + Należy określić argument nazwy. + + + Określony element RegistryValueKind jest wartością, która jest nieprawidłowa. + + + Właściwość RegistryKey.SetValue nie zezwala na element String[], który zawiera odwołanie do ciągu o wartości null. + + + Podklucze rejestru nie powinny być dłuższe niż 255 znaków. + + + Należy określić nazwę podklucza, który nie jest pusty. + + + Typ obiektu wartości jest niezgodny z określonym typem RegistryValueKind lub nie można poprawnie przekonwertować obiektu. + + + RegistryKey.SetValue nie obsługuje tablic typu „{0}”. Obsługiwane są tylko wartości Byte[] i String[]. + + + Określony klucz rejestru nie istnieje. + + + Długość określonej nazwy wartości przekracza maksymalną liczbę 16383 znaków. + + + Rozmiar określonych danych wartości przekracza wartość maksymalną wynoszącą 1 MB. + + + Określony podklucz rejestru nie istnieje. + + + Określona wartość RegistryKeyPermissionCheck jest nieprawidłowa. + + + Klucz rejestru ma podklucze; operacje usuwania cyklicznego nie są obsługiwane przez tę metodę. + + + Nie można utworzyć dojścia KTM bez transakcji Transaction.Current lub określonej transakcji. + + + Określona transakcja lub transakcja Transaction.Current musi być zgodna z transakcją użytą do utworzenia lub otwarcia tego klucza TransactedRegistryKey. + + + Obiekt TransactedRegistryKey nie jest skojarzony z transakcją, ponieważ jest przeznaczony dla wstępnie zdefiniowanego klucza. + + + Żądany dostęp do rejestru jest niedozwolony. + + + Odmowa dostępu do klucza rejestru „{0}”. + + + Nie można zapisać w kluczu rejestru. + + + Nie można uzyskać dostępu do zamkniętego klucza rejestru. + + + Nieznany błąd: {0}. + + + Transakcje rejestru nie są obsługiwane na tej platformie. + + + Określone dojście jest nieprawidłowe. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/RemotingErrorIdStrings.pl.resx b/src/System.Management.Automation/resources/pl/RemotingErrorIdStrings.pl.resx new file mode 100644 index 00000000000..47745d0e26e --- /dev/null +++ b/src/System.Management.Automation/resources/pl/RemotingErrorIdStrings.pl.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + Symbole wieloznaczne nie są obsługiwane dla parametru FilePath. Określ ścieżkę bez symboli wieloznacznych. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + Należy określić wartość {0} dla opcji sesji {1}. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + Maksymalna liczba przekierowań identyfikatora URI WS-Man dozwolonych podczas łączenia się z komputerem zdalnym + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + Nie można użyć parametru WriteEvents bez parametru Wait. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + Komunikacja zdalna programu PowerShell nie jest obsługiwana w środowisku preinstalacji systemu Windows (WinPE). + + + Zmiany wprowadzone przez {0} nie zaczną obowiązywać, dopóki usługa WinRM nie zostanie ponownie uruchomiona. + + + {0} Może być konieczne ponowne uruchomienie usługi WinRM, jeśli konfiguracja używająca tej nazwy została niedawno wyrejestrowana, ponieważ niektóre struktury danych systemowych mogą być nadal buforowane. W takim przypadku może być wymagane ponowne uruchomienie usługi WinRM. +Wszystkie sesje WinRM połączone z konfiguracjami sesji programu PowerShell, takimi jak Microsoft.PowerShell, oraz konfiguracjami sesji utworzonymi za pomocą polecenia cmdlet Register-PSSessionConfiguration, zostaną rozłączone. + + + Korzystasz z sesji zdalnej i wybrano opcję Wymuś, co oznacza, że usługa WinRM może zostać ponownie uruchomiona. Jeśli usługa WinRM zostanie ponownie uruchomiona, ta sesja zdalna zostanie zakończona i aby kontynuować, trzeba będzie utworzyć nową sesję + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + Parametru -WriteJobInResults nie można użyć bez parametru -Wait + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + Podany strumień wejściowy jest nieprawidłowy. Jako strumień wejściowy jest obsługiwany tylko {0}. + + + Podany zestaw strumieni wyjściowych jest nieprawidłowy. Jako strumień wyjściowy obsługiwana jest tylko {0}. + + + Podany WSMAN_SENDER_DETAILS jest nieprawidłowy. Nie można przetworzyć WSMAN_SENDER_DETAILS o wartości null. + + + Podany kontekst powłoki jest nieprawidłowy. + + + {0} + + + Wartość NULL nie jest dozwolona dla {0} w metodzie wtyczki {1}. + + + Wartość NULL nie jest dozwolona dla zestawów strumieni wejściowych i wyjściowych. {0} i {1} są obsługiwanymi strumieniami wejściowymi i wyjściowymi. + + + Wartość NULL nie jest dozwolona dla {0} w metodzie wtyczki {1}. + + + Wartość NULL nie jest dozwolona dla {0} w metodzie wtyczki {1}. + + + Trwa zamykanie operacji wtyczki programu PowerShell. Może się tak zdarzyć, jeśli usługa hostująca lub aplikacja jest zamykana. + + + Wtyczka programu PowerShell nie rozumie opcji {0}. Upewnij się, że klient jest zgodny z kompilacją {1} i wersją protokołu {2} programu PowerShell. + + + Oczekiwana jest opcja o nazwie {0} od klienta. Upewnij się, że klient jest zgodny z kompilacją {1} i wersją protokołu {2} programu PowerShell. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Wtyczka programu PowerShell nie obsługuje wersji protokołu {2} żądanej przez klienta.</PSProtocolVersionError> + + + Wtyczka programu PowerShell napotkała błąd krytyczny podczas raportowania kontekstu do usługi WSMan. + + + Nie można utworzyć zarządzanej sesji serwera. + + + Wtyczka programu PowerShell napotkała błąd krytyczny podczas rejestrowania dojścia oczekiwania dla powiadomienia o zamknięciu. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + Nie znaleziono pliku wykonywalnego „{0}”. Sprawdź, czy funkcja WOW64 jest zainstalowana. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + Nie można utworzyć procesu programu Windows PowerShell, ponieważ na tym komputerze nie można znaleźć programu Windows PowerShell. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/RunspaceInit.pl.resx b/src/System.Management.Automation/resources/pl/RunspaceInit.pl.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/RunspaceInit.pl.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/RunspacePoolStrings.pl.resx b/src/System.Management.Automation/resources/pl/RunspacePoolStrings.pl.resx new file mode 100644 index 00000000000..2f99d953d42 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/RunspacePoolStrings.pl.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Maksymalny rozmiar puli nie może być mniejszy niż 1. + + + Minimalny rozmiar puli nie może być mniejszy niż 1. + + + Minimalny rozmiar puli nie może być większy od maksymalnego rozmiaru puli. + + + Stan puli obszarów działania nie jest prawidłowy dla tej operacji. + + + Nie można wykonać operacji, ponieważ obszar działania nie jest w stanie „{0}”. Bieżący stan to „{1}”. + + + Nie można otworzyć puli obszarów działania, ponieważ nie jest ona w stanie „'BeforeOpen”. Bieżący stan to „{0}”. + + + Obiekt {0} nie został utworzony przez wywołanie {1} w bieżącym wystąpieniu RunspacePool. + + + Nie można zwolnić obszaru działania do bieżącej puli, ponieważ ten obszar działania nie należy do bieżącej puli. + + + Tej właściwości nie można zmienić po otwarciu puli obszarów działania. + + + Ten obszar działania nie obsługuje operacji rozłączania i ponownego łączenia. + + + Nie można wykonać operacji, ponieważ obszar działania nie jest w stanie Disconnected. + + + Operacja Disconnect nie jest obsługiwana na serwerze. Serwer musi działać w programie PowerShell 3.0 lub nowszym, aby obsługiwać rozłączanie zdalnej puli obszarów działania. + + + Ta pula obszarów działania {0} nie jest skonfigurowana do udostępniania odłączonych obiektów programu PowerShell dla poleceń uruchamianych na serwerze zdalnym. Użyj statycznej metody GetRunspacePools() klasy RunspacePool, aby odpytać serwer i zwrócić obiekty puli obszarów działania skonfigurowane do tego celu. + + + Nie można połączyć tej puli obszarów działania, ponieważ odpowiadająca jej pula po stronie serwera jest połączona z innym klientem. + + + ResetRunspaceState nie jest obsługiwany na serwerze. Serwer musi działać w programie PowerShell 5.0 lub nowszym. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/RunspaceStrings.pl.resx b/src/System.Management.Automation/resources/pl/RunspaceStrings.pl.resx new file mode 100644 index 00000000000..06d3e00bdb2 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/RunspaceStrings.pl.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Stan obszaru uruchomieniowego jest nieprawidłowy dla tej operacji. + + + Nie można otworzyć obszaru działania, ponieważ nie jest on w stanie BeforeOpen. Bieżący stan obszaru uruchomieniowego to „{0}”. + + + Nie można wykonać operacji, ponieważ obszar runspace nie jest w stanie Opened. Bieżący stan obszaru uruchomieniowego to „{0}”. + + + Nie można wywołać potoku, ponieważ obszar działania nie jest w stanie Opened. Bieżący stan obszaru uruchomieniowego to „{0}”. + + + Stan potoku nie jest prawidłowy dla tej operacji. + + + Nie można wywołać potoku, ponieważ został już wywołany. + + + Prawidłowa wartość parametru to PipelineResultTypes.Output. + + + Potok nie zawiera polecenia. + + + Potok nie został uruchomiony, ponieważ inny potok jest już uruchomiony. Potoków nie można uruchamiać jednocześnie. + + + Potoku zagnieżdżonego nie można wywołać asynchronicznie. Użyj metody Invoke. + + + Potok zagnieżdżony należy uruchamiać tylko z poziomu uruchomionego potoku. + + + Nie można zamknąć obszaru działania, gdy trwa wywoływanie metody SessionStateProxy. + + + Nie można wywołać potoku, gdy trwa wywołanie metody SessionStateProxy. + + + Trwa wywołanie metody SessionStateProxy. Równoczesne wywołania metod SessionStateProxy są niedozwolone. + + + Potok jest już uruchomiony. Równoczesne wywołania metod SessionStateProxy są niedozwolone. + + + Nie można zmienić tej właściwości po otwarciu obszaru uruchomieniowego. + + + Wystąpił co najmniej jeden błąd podczas przetwarzania modułu „{0}” określonego w obiekcie InitialSessionState użytym do utworzenia tego obszaru działania. Zobacz właściwość ErrorRecords, aby uzyskać pełną listę błędów. Pierwszy błąd to: {1} + + + Opcje wątku można zmienić tylko wtedy, gdy stan apartamentu to wielowątkowy apartament (MTA), bieżące opcje to UseNewThread lub UseCurrentThread, a nowa wartość to ReuseThread. + + + {0} nie może mieć wartości false, gdy tryb języka to {1} lub {2}. + + + Nie można rozłączyć obszaru działania dostępnego tylko lokalnie. + + + Operacja Connect nie jest obsługiwana w lokalnych obszarach uruchomieniowych. + + + Sesja jest zajęta. Połączysz się z nią, gdy tylko będzie dostępna. Aby anulować polecenie Enter-PSSession, naciśnij Ctrl-C. + + + Nie można wykonać polecenia. Wywołanie skryptu nie jest obsługiwane w tej konfiguracji sesji. Może się tak zdarzyć, jeśli konfiguracja sesji jest w trybie bez języka. + + + Nie można używać operacji rozłączania i łączenia w lokalnych obszarach uruchomieniowych. + + + Nie można połączyć potoku, ponieważ obszar działania nie jest w stanie Opened. Bieżący stan obszaru uruchomieniowego to „{0}”. + + + Nie można utworzyć obszaru RemoteRunspace. Podany obiekt RunspacePool jest nieprawidłowy. + + + Z tym obszarem działania nie jest skojarzone żadne rozłączone polecenie. + + + Operacja rozłączenia nie jest obsługiwana na komputerze zdalnym. Aby obsługiwać rozłączanie, na komputerze zdalnym musi być uruchomiony Windows PowerShell w wersji 3.0 lub nowszej i musi być używany transport WSMan. + + + Nie można połączyć sesji PSSession, ponieważ sesja nie jest w stanie Disconnected lub nie jest dostępna do połączenia. + + + Wartość parametru nie może być równa PipelineResultTypes.None ani PipelineResultTypes.Output. + + + Prawidłowe wartości parametru to PipelineResultTypes.Output lub PipelineResultTypes.Null. + + + Przekierowywanie strumienia debugowania nie jest obsługiwane na docelowym komputerze zdalnym. + + + Pełne przekierowywanie strumienia nie jest obsługiwane na docelowym komputerze zdalnym. + + + Przekierowywanie strumienia ostrzeżenia nie jest obsługiwane na docelowym komputerze zdalnym. + + + Przekierowanie strumienia informacji nie jest obsługiwane na docelowym komputerze zdalnym. + + + Masz otwartą sesję, w której jest uruchomione polecenie lub skrypt. Ponieważ dane wyjściowe są kierowane do zadania „{0}”, nie zobaczysz ich w konsoli. Możesz poczekać na zakończenie działania polecenia lub anulować polecenie i pobrać monit wejściowy, naciskając klawisze Ctrl-C. + + + + Weszłaś/wszedłeś do sesji, w której jest właśnie uruchomione polecenie lub skrypt, a dane wyjściowe zostaną wyświetlone w konsoli. Możesz poczekać na zakończenie uruchomionego polecenia albo je anulować i wyświetlić monit wejściowy, naciskając Ctrl-C. + + + + Weszłaś/wszedłeś do sesji, która jest obecnie zatrzymana w punkcie przerwania debugowania wewnątrz uruchomionego polecenia lub skryptu. Użyj debugera wiersza polecenia programu PowerShell, aby kontynuować debugowanie. + + + + DefaultRunspace musi być obiektem LocalRunspace + + + Statyczną właściwość PrimaryRunspace można ustawić tylko raz i została już ustawiona. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/SecuritySupportStrings.pl.resx b/src/System.Management.Automation/resources/pl/SecuritySupportStrings.pl.resx new file mode 100644 index 00000000000..22360c58ccd --- /dev/null +++ b/src/System.Management.Automation/resources/pl/SecuritySupportStrings.pl.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można załadować certyfikatu. element „{0}” musi być rozpoznawany jako ścieżka systemu plików. + + + Nie można użyć certyfikatu „{0}” w celu szyfrowania. Certyfikaty szyfrowania muszą zawierać użycie klucza szyfrowania danych lub klucza szyfrowania kluczy i uwzględniać rozszerzone użycie klucza szyfrowania dokumentów ({1}). + + + Nie można załadować certyfikatu. Identyfikator „{0}” pasuje do wielu certyfikatów. Aby zaszyfrować w przypadku wielu adresatów, podaj wiele określonych wartości parametru „{1}”, a nie symbol wieloznaczny, który pasuje do wielu certyfikatów. + + + Nie można załadować certyfikatu szyfrowania. Ustawienie certyfikatu „{0}” nie reprezentuje prawidłowego certyfikatu zakodowanego w formacie base-64 ani nie reprezentuje prawidłowego certyfikatu według pliku, katalogu, odcisku palca lub nazwy podmiotu. + + + OSTRZEŻENIE: certyfikat „{0}” zawiera klucz prywatny. Certyfikaty chronionego rejestrowania zdarzeń używane do szyfrowania powinny zawierać tylko klucz publiczny. + + + BŁĄD: nie można chronić komunikatu dziennika zdarzeń „{0}”: {1} + + + BŁĄD: nie można odnaleźć certyfikatu lub użyć go: {0} + + + Klucz sesji nie jest dostępny do szyfrowania bezpiecznego ciągu. + + + Nieprawidłowe przesunięcie buforu. + + + Nieprawidłowe dane dotyczące klucza publicznego. + + + Nie można zaimportować klucza publicznego. + + + Nieprawidłowe dane dotyczące klucza sesji. + + + Plik skryptu „{0}” jest zablokowany przez zasady systemowe. + + + Zwrócono nieznaną wartość wymuszania zasad pliku skryptu: {0}. + + + Odczytanie pliku skryptu + + + Plik skryptu „{0}” nie jest zaufany przez zasady i zostanie uruchomiony w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/Serialization.pl.resx b/src/System.Management.Automation/resources/pl/Serialization.pl.resx new file mode 100644 index 00000000000..293808502ec --- /dev/null +++ b/src/System.Management.Automation/resources/pl/Serialization.pl.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Oczekiwano atrybutu {0}. + + + {0} tag XML nie został rozpoznany. + + + Nie znaleziono obiektu dla referenceId {0} + + + Atrybut Name dla klucza słownika jest nieprawidłowo określony. + + + Atrybut nazwy dla wartości słownika jest niepoprawnie określony. + + + Wersja obiektu PSObject jest nieprawidłowa. + + + Wersja przychodzącego obiektu PSObject to {0}. Oczekiwana wartość to 1. + + + Nie można przetworzyć nazw, ponieważ nie znaleziono elementów TypeNames dla elementu referenceId {0}. + + + Wartość parametru głębokości musi być większa lub równa 1. + + + Bieżący typ węzła to {0}. Oczekiwanym typ to {1}. + + + Nie określono klucza dla wpisu słownika. + + + Nie określono wartości wpisu słownika. + + + Nie ma już więcej obiektów do deserializacji. + + + Wartość null jest określona jako klucz słownika. + + + Zawartość typu pierwotnego {0} jest nieprawidłowa. + + + Serializowany kod XML jest zagnieżdżony zbyt głęboko. + + + Serializator został zamknięty. + + + Dane w poleceniu przekroczyły maksymalny rozmiar dozwolony przez konfigurację sesji. Maksymalny dozwolony rozmiar to {0} MB. Zmień dane wejściowe, użyj innej konfiguracji sesji lub zmień właściwości „{1}” i „{2}” konfiguracji sesji na komputerze zdalnym. + + + Deserializacja zaszyfrowanego bezpiecznego ciągu nie powiodła się + + + Typ klucza {0} jest nieprawidłowy. Klasa PSPrimitiveDictionary akceptuje tylko klucze typu System.String. + + + Typ wartości {0} jest nieprawidłowy. Klasa PSPrimitiveDictionary akceptuje tylko wartości typów, które są w pełni serializowalne przez zdalne komunikowanie PowerShell. Zobacz temat Pomoc about_Remoting, aby uzyskać listę typów w pełni serializowalnych. + + + Nie można odszyfrować danych. Dane nie zostały zaszyfrowane przy użyciu tego klucza. + + + Wartość parametru „{0}” nie jest prawidłowym zaszyfrowanym ciągiem. + + + Określony {0} jest nieprawidłowy. Prawidłowe ustawienia długości {0} to 128 bitów, 192 bity lub 256 bitów. + + + Deserializacja obiektu SecureString jest obecnie obsługiwana tylko w systemie Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/SessionStateProviderBaseStrings.pl.resx b/src/System.Management.Automation/resources/pl/SessionStateProviderBaseStrings.pl.resx new file mode 100644 index 00000000000..050c1c53d87 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/SessionStateProviderBaseStrings.pl.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ustaw element + + + Element: {0} Wartość: {1} + + + Wyczyść element + + + Element: {0} + + + Usuń element + + + Element: {0} + + + Nowy element + + + Element: typ {0}: wartość {1}: {2} + + + Kopiuj element + + + Element: {0} Miejsce docelowe: {1} + + + Zmień nazwę elementu + + + Element: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/SessionStateStrings.pl.resx b/src/System.Management.Automation/resources/pl/SessionStateStrings.pl.resx new file mode 100644 index 00000000000..97a89213d44 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/SessionStateStrings.pl.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można przetworzyć zwróconych informacji, ponieważ informacje zwrócone przez metodę Start dostawcy dotyczyły innego dostawcy niż ten, który przekazano. + + + Nie można przetworzyć zwróconych informacji, ponieważ informacje zwrócone przez metodę Start dostawcy miały wartość null. + + + Nie można wykonać operacji GetItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji GetItem od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji SetItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji SetItem od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji ClearItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji InvokeDefaultAction dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji InvokeDefaultAction od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji ItemExists dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji ItemExists od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji IsValidPath dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji IsItemContainer dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji RemoveItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji GetChildItems dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji GetChildItems od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji GetChildNames dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji GetChildNames od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji RenameItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji RenameItem od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji NewItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji NewItem od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji HasChildItems dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji CopyItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji CopyItem od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji GetParentPath dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji NormalizeRelativePath dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji MakePath dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji GetChildName dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji MoveItem dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji MoveItem od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji GetProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji GetProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji SetProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji SetProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji ClearProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji ClearProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji NewProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji NewProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji RemoveProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji RemoveProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji CopyProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji CopyProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji MoveProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji MoveProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji RenameProperty dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji RenameProperty od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać czytnika zawartości dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji GetContentReader od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać autora zawartości dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla operacji GetContentWriter od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać zawartości, ponieważ to katalog: „{0}”. Użyj zamiast tego polecenia „Get-ChildItem”. + + + Nie można zapisać zawartości, ponieważ to katalog: „{0}”. + + + Brak historii lokalizacji, która umożliwiałaby wsteczną nawigację. + + + Brak historii lokalizacji umożliwiającej dalszą nawigację. + + + Element BoundedStack jest pusty. + + + Nie można wykonać operacji ClearContent dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wyczyścić zawartości elementu „{0}”, ponieważ jest to katalog. Polecenie Clear-Content jest obsługiwane tylko dla plików. + + + Nie można pobrać parametrów dynamicznych dla operacji ClearContent od dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji GetSecurityDescriptor dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji SetSecurityDescriptor dla dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wykonać operacji Start dla dostawcy „{0}”. {1} + + + Nie można wykonać operacji InitializeDefaultDrives u dostawcy „{0}”. + + + Nie można wykonać operacji NewDrive dla dysku z poziomem głównym „{0}” dla ścieżki „{1}”. {2} + + + Nie można pobrać parametrów dynamicznych dla dostawcy „{0}” dla operacji NewDrive. {1} + + + Wywołanie RemoveDrive u dostawcy „{0}” zakończyło się niepowodzeniem. {1} + + + Nie można usunąć dysku „{0}”, ponieważ uniemożliwił to dostawca „{1}”. + + + Ścieżka „{0}” odwoływała się do elementu znajdującego się poza podstawą „{1}”. + + + Nie można wywołać metody Seek w module zapisu zawartości dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wywołać metody Close w module odczytu lub zapisu zawartości dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wywołać metody Read w module odczytu zawartości dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Nie można wywołać metody Write w module zapisu zawartości dostawcy „{0}” dla ścieżki „{1}”. {2} + + + Dostawcy „{0}” nie można użyć do pobierania ani ustawiania danych przy użyciu składni zmiennej. {2} + + + Składnia zmiennej nie może być używana do pobierania lub ustawiania danych w dostawcy. {2} + + + Alias nie jest zapisywalny, ponieważ alias {0} jest tylko do odczytu lub stały i nie można go zmieniać. + + + Nie można zapisać do funkcji {0}, ponieważ jest ona tylko do odczytu lub stała. + + + Nie można zastąpić zmiennej {0}, ponieważ jest tylko do odczytu lub stała. + + + Nie można uzyskać dostępu do zmiennej „${0}”, ponieważ jest to zmienna prywatna. + + + Nie można uzyskać dostępu do polecenia „{0}”, ponieważ jest ono prywatne. + + + Nie można uzyskać dostępu do polecenia, ponieważ jest ono prywatne. + + + Nie można uzyskać dostępu do zasobu stanu sesji, ponieważ jest to zasób prywatny. + + + Alias nie został usunięty, ponieważ alias {0} jest stały lub tylko do odczytu. + + + Nie można usunąć funkcji {0}, ponieważ jest stała. + + + Nie można usunąć zmiennej {0}, ponieważ jest stała lub tylko do odczytu. Jeśli zmienna jest tylko do odczytu, spróbuj ponownie, używając opcji Force. + + + Alias {0} nie może zostać zmodyfikowany ponieważ jest stały. + + + Alias {0} nie może zostać zmodyfikowany ponieważ jest tylko do odczytu. + + + Nie można zmodyfikować funkcji {0}, ponieważ jest stała. + + + Nie można zmodyfikować funkcji {0}, ponieważ jest tylko do odczytu. + + + Nie można ustawić aliasu {0} jako stałego po jego utworzeniu. Alias można ustawić jako stały tylko w momencie tworzenia. + + + Istniejącej funkcji {0} nie można ustawić jako stałej. Funkcje można oznaczyć jako stałe tylko w chwili tworzenia. + + + Istniejącej zmiennej {0} nie można ustawić jako stałej. Zmienne można oznaczyć jako stałe tylko w chwili tworzenia. + + + Nie można usunąć opcji AllScope z aliasu „{0}”. + + + Nie można usunąć opcji AllScope z funkcji „{0}”. + + + Nie można usunąć opcji AllScope ze zmiennej „{0}”. + + + Definicja funkcji „{0}” zawierała kwalifikator zakresu, ale nie zawierała nazwy funkcji. + + + Nie można usunąć dostawcy {0}. Przed usunięciem dostawcy {0} trzeba usunąć wszystkie dyski skojarzone z dostawcą {0}. + + + Nie można przetworzyć nazwy dysku, ponieważ zawiera co najmniej jeden z tych nieprawidłowych znaków: ; ~ / \ . : + + + Nie można utworzyć nowego dysku, ponieważ dostawca nie zezwala na tworzenie nowego dysku. + + + Podana wartość „{0}” została rozpoznana jako więcej niż jeden stos lokalizacji. + + + Nie można znaleźć stosu lokalizacji „{0}”. Element nie istnieje albo nie jest kontenerem. + + + Nie można odnaleźć ścieżki „{0}”, ponieważ nie istnieje. + + + Nie można znaleźć aliasu, ponieważ alias „{0}” nie istnieje. + + + Nie można ustawić lokalizacji, ponieważ ścieżka „{0}” wskazuje na wiele kontenerów. Lokalizację można ustawić tylko dla jednego kontenera na raz. + + + Nie można przetworzyć zmiennej, ponieważ ścieżka zmiennej „{0}” wskazuje wiele elementów. Wartość zmiennej można pobierać lub ustawiać tylko dla jednego elementu na raz. + + + Nie można odnaleźć dysku. Dysk o nazwie „{0}” nie istnieje. + + + Nie można znaleźć dostawcy o nazwie „{0}”. + + + Nie można znaleźć dostawcy o nazwie „{0}”. Nazwa ma nieprawidłowy format. Nazwa dostawcy może zawierać tylko znaki alfanumeryczne albo nazwę przystawki programu PowerShell, po której występuje pojedynczy znak „\”, a potem znaki alfanumeryczne. + + + Element „{0}” rozpoznano jako więcej niż jedną nazwę dostawcy. Możliwe dopasowania to: {1}. + + + Wystąpił błąd podczas próby utworzenia wystąpienia dostawcy. Nie można odnaleźć nazwy typu dostawcy „{0}” w zestawie. + + + Nie można użyć określonej nazwy dostawcy „{0}”, ponieważ zawiera co najmniej jeden z tych nieprawidłowych znaków: \ [ ] ? * : + + + Wystąpił błąd podczas próby utworzenia wystąpienia dostawcy „{0}”. {1} + + + Nie można znaleźć zmiennej o nazwie „{0}”. + + + Nie można odnaleźć źródła śledzenia o nazwie „{0}”. + + + Dysk o nazwie „{0}” już istnieje. + + + Zmienna o nazwie „{0}” już istnieje. + + + Nie można utworzyć aliasu, ponieważ alias o nazwie „{0}” już istnieje. + + + Nie można zarejestrować dostawcy poleceń cmdlet, ponieważ dostawca o nazwie „{0}” już istnieje. + + + Ścieżka nie jest ścieżką systemu plików. + + + Nie można usunąć zakresu globalnego. + + + Numer zakresu „{0}” przekracza liczbę aktywnych zakresów. + + + Nie można porównać obiektu PSDriveInfo. Wystąpienie PSDriveInfo można porównać tylko z innym wystąpieniem PSDriveInfo. + + + Dostawca poleceń cmdlet nie może przesłać wyników strumieniowo, ponieważ nie określono polecenia cmdlet, przez które można przesłać wynik strumieniowo. + + + Dostawca poleceń cmdlet nie może przesłać wyników strumieniowo, ponieważ nie określono polecenia cmdlet, przez które można przesłać błąd strumieniowo. + + + Lokalizacja główna tego dostawcy nie jest ustawiona. Aby ustawić lokalizację główną, wywołaj „(get-psprovider '{0}').Home = 'path'”. + + + Ścieżka ma niepoprawny format. Ścieżki dostawców muszą zawierać identyfikator dostawcy, po którym występuje „::”, a następnie ścieżka właściwa dla dostawcy. + + + Nie można przenieść elementu, ponieważ ścieżka docelowa może wskazywać tylko jedną ścieżkę. + + + Nie można przenieść elementu, ponieważ ścieżki źródłowa i docelowa nie zostały rozpoznane jako należące do tego samego dostawcy. + + + Nie można przenieść elementu, ponieważ ścieżka źródłowa wskazuje jeden lub więcej elementów, a ścieżka docelowa nie jest kontenerem. Sprawdź, czy ścieżka docelowa jest kontenerem, i spróbuj ponownie. + + + Nie można przenieść elementu, ponieważ miejsce docelowe zostało rozpoznane jako wiele ścieżek. Podaj ścieżkę docelową, która prowadzi do jednego miejsca docelowego, i spróbuj ponownie. + + + Nie można skopiować kontenera do istniejącego elementu końcowego. + + + Nie można skopiować kontenera do innego kontenera. Nie określono parametru -Recurse ani -Container. + + + Ścieżka źródłowa i docelowa nie wskazują na tego samego dostawcę. + + + Nie można zmienić nazwy elementu, ponieważ ścieżka została rozpoznana jako wiele elementów. Jednocześnie można zmienić nazwę tylko jednego elementu. + + + Nie można użyć dostawcy „{0}” do rozwiązania ścieżki „{1}” z powodu błędu w dostawcy. + + + Nie można użyć interfejsu. Ten dostawca nie wdraża interfejsu IContentCmdletProvider. + + + Nie można użyć interfejsu. Ten dostawca nie obsługuje interfejsu IPropertyCmdletProvider. + + + Nie można użyć interfejsu. Ten dostawca nie wdraża interfejsu IDynamicPropertyCmdletProvider. + + + Metody NavigationCmdletProvider nie są obsługiwane przez tego dostawcę. + + + Metody dostawcy nie zostały przetworzone. Metody ContainerCmdletProvider nie są obsługiwane przez tego dostawcę. + + + Nie można wywołać metod. Metody ItemCmdletProvider nie są obsługiwane przez tego dostawcę. + + + Metody DriveCmdletProvider nie są obsługiwane przez tego dostawcę. + + + Operacja dostawcy została zatrzymana, ponieważ ten dostawca nie obsługuje tej operacji. + + + Operacja dostawcy została zatrzymana, ponieważ ten dostawca nie obsługuje parametru „Depth”. + + + Nie można wywołać metody. Metoda wyszukiwania zawartości nie jest obsługiwana przez tego dostawcę. + + + Nie można wykonać operacji ClearContent. Ten dostawca nie obsługuje operacji ClearContent. + + + Dostawca nie obsługuje używania poświadczeń. Spróbuj ponownie bez podawania poświadczeń. + + + Dostawca systemu plików obsługuje poświadczenia tylko w poleceniu cmdlet New-PSDrive. Spróbuj ponownie bez podawania poświadczeń. + + + Dostawca nie obsługuje transakcji. Wykonaj operację ponownie bez parametru -UseTransaction. + + + Nie można wywołać metody. Dostawca nie obsługuje używania filtrów. + + + Nie można utworzyć dysku. Dostawca nie obsługuje używania poświadczeń. + + + Element w ścieżce „{0}” już istnieje. + + + Nie można skopiować elementu. Element na ścieżce „{0}” nie istnieje. + + + Element na ścieżce „{0}” nie istnieje. + + + Dysk zawierający widok aliasów przechowywanych w stanie sesji + + + Dysk zawierający widok zmiennych środowiskowych procesu + + + Dysk zawierający widok funkcji przechowywanych w stanie sesji + + + Dysk zawierający widok zmiennych przechowywanych w stanie sesji + + + Dysk mapowany do ścieżki katalogu tymczasowego bieżącego użytkownika + + + Nie można utworzyć łącza „{0}”, ponieważ nie określono wartości docelowej. + + + Odwołania do zmiennej null zawsze zwracają wartość null. Przypisania nie mają żadnego efektu. + + + Maksymalna liczba obiektów historii przechowywanych w sesji + + + Nie można zmienić nazwy funkcji, ponieważ funkcja {0} jest tylko do odczytu lub stała. + + + Nie można zmienić nazwy aliasu, ponieważ alias {0} jest tylko do odczytu lub stały. + + + Nie można zmienić nazwy zmiennej, ponieważ zmienna {0} jest tylko do odczytu lub stała. + + + Nie można ustawić opcji dla zmiennej lokalnej {0}. Użyj polecenia New-Variable, aby utworzyć zmienną, dla której można ustawiać opcje. + + + Polecenie cmdlet {0} nie może zostać zmodyfikowane ponieważ jest tylko do odczytu. + + + Nie można usunąć zmiennej {0}, ponieważ została zoptymalizowana i nie można jej usunąć. Spróbuj użyć polecenia cmdlet Remove-Variable (bez aliasów) albo polecenia dot-source, którego używasz do usunięcia zmiennych. + + + Nie można zastąpić zmiennej {0}, ponieważ została zoptymalizowana. Spróbuj użyć polecenia cmdlet -New-Variable lub Set-Variable (bez aliasów) albo polecenia dot-source, którego używasz do ustawienia zmiennych. + + + Parametrów {0} i {1} nie można używać razem. Określ tylko jeden parametr. + + + Parametr Tail jest obecnie obsługiwany tylko przez dostawcę FileSystem. + + + Nie można utworzyć aliasu, ponieważ polecenie o nazwie „{0}” i typie polecenia „{1}” już istnieje. + + + Nie można uruchomić oprogramowania. Odmowa uprawnień. + + + Elementy „-{0}” i „-{1}” wykluczają się wzajemnie i nie można ich podać jednocześnie. + + + Ścieżka „{0}” jest nieprawidłowa. W operacjach kopiowania zdalnego są obsługiwane tylko ścieżki bezwzględne. + + + Nie można zweryfikować ścieżki zdalnej „{0}”. + + + Nie można wykonać operacji, ponieważ sesja {0} jest ustawiona na wartość {1}. + + + Parametr „{0}” nie może mieć wartości null ani być pusty. + + + Zmienne stanu sesji + + + Zmiana zakresu zmiennej „{0}” na wartość AllScope lub utworzenie takiej zmiennej będzie blokowane w trybie ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/StringDecoratedStrings.pl.resx b/src/System.Management.Automation/resources/pl/StringDecoratedStrings.pl.resx new file mode 100644 index 00000000000..f6e8831e7f9 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/StringDecoratedStrings.pl.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Dla tej metody jest obsługiwana tylko wartość „ANSI” lub „PlainText”. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/SubsystemStrings.pl.resx b/src/System.Management.Automation/resources/pl/SubsystemStrings.pl.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/pl/SubsystemStrings.pl.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/SuggestionStrings.pl.resx b/src/System.Management.Automation/resources/pl/SuggestionStrings.pl.resx new file mode 100644 index 00000000000..afc472ca863 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/SuggestionStrings.pl.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 + + + Nie znaleziono polecenia „{0}”, ale faktycznie istnieje ono w bieżącej lokalizacji. +Program PowerShell domyślnie nie ładuje poleceń z bieżącej lokalizacji (zobacz „Get-Help about_Command_Precedence”). + +Jeśli ufasz temu poleceniu, zamiast niego uruchom następujące polecenie: + + + Najbardziej podobne polecenia to: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/TabCompletionStrings.pl.resx b/src/System.Management.Automation/resources/pl/TabCompletionStrings.pl.resx new file mode 100644 index 00000000000..d10d72329e0 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/TabCompletionStrings.pl.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można poprawnie zdeserializować wyniku uzupełniania tabulatorem, ponieważ zdalny obszar roboczy nie zawiera wystąpienia TypeTable. + + + Nie można uzyskać dostępu do właściwości pustego wystąpienia typu CompletionResult. + + + Bitowe NIE + + + Logiczne, że nie. Neguje wyrażenie, które po nim występuje. + + + Równe — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które są równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest równy prawemu operandowi. + + + Równe — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które są równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest równy prawemu operandowi. + + + Równe — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które są równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest równy prawemu operandowi. + + + Nie równa się — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które nie są równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie jest równy prawemu operandowi. + + + Nie równa się — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które nie są równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie jest równy prawemu operandowi. + + + Nie równa się — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które nie są równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie jest równy prawemu operandowi. + + + Większe niż lub równe — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które są większe lub równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest większy lub równy prawemu operandowi. + + + Większe niż lub równe — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które są większe lub równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest większy lub równy prawemu operandowi. + + + Większe niż lub równe — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości ze zbioru, które są większe lub równe prawemu operandowi; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest większy lub równy prawemu operandowi. + + + Większe niż — bez uwzględniania wielkości liter. Jeśli lewy operand jest kolekcją, zwraca wartości ze zbioru, które są większe od prawego operandu. W przeciwnym wypadku zwraca wartość PRAWDA, jeśli lewy operand jest większy od prawego operandu. + + + Większe niż — bez uwzględniania wielkości liter. Jeśli lewy operand jest kolekcją, zwraca wartości ze zbioru, które są większe od prawego operandu. W przeciwnym wypadku zwraca wartość PRAWDA, jeśli lewy operand jest większy od prawego operandu. + + + Większe niż — z uwzględnieniem wielkości liter. Jeśli lewy operand jest kolekcją, zwraca wartości ze zbioru, które są większe od prawego operandu. W przeciwnym wypadku zwraca wartość PRAWDA, jeśli lewy operand jest większy od prawego operandu. + + + Mniejsze niż — bez uwzględniania wielkości liter. Jeśli lewy operand jest kolekcją, zwraca wartości ze zbioru, które są mniejsze od prawego operandu. W przeciwnym wypadku zwraca wartość PRAWDA, jeśli lewy operand jest mniejszy od prawego operandu. + + + Mniejsze niż — bez uwzględniania wielkości liter. Jeśli lewy operand jest kolekcją, zwraca wartości ze zbioru, które są mniejsze od prawego operandu. W przeciwnym wypadku zwraca wartość PRAWDA, jeśli lewy operand jest mniejszy od prawego operandu. + + + Mniejsze niż — z uwzględnieniem wielkości liter. Jeśli lewy operand jest kolekcją, zwraca wartości ze zbioru, które są mniejsze od prawego operandu. W przeciwnym wypadku zwraca wartość PRAWDA, jeśli lewy operand jest mniejszy od prawego operandu. + + + Mniejsze niż lub równe — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które są mniejsze lub równe prawemu operandowi. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest mniejszy lub równy prawemu operandowi. + + + Mniejsze niż lub równe — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które są mniejsze lub równe prawemu operandowi. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest mniejszy lub równy prawemu operandowi. + + + Mniejsze niż lub równe — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które są mniejsze lub równe prawemu operandowi. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand jest mniejszy lub równy prawemu operandowi. + + + Operator dopasowywania symboli wieloznacznych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które pasują do prawego operandu; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand pasuje do prawego operandu. + + + Operator dopasowywania symboli wieloznacznych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które pasują do prawego operandu; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand pasuje do prawego operandu. + + + Operator dopasowywania symboli wieloznacznych — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które pasują do prawego operandu; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand pasuje do prawego operandu. + + + Operator dopasowywania symboli wieloznacznych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca z niej wartości, które nie pasują do prawego operandu. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie pasuje do prawego operandu. + + + Operator dopasowywania symboli wieloznacznych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca z niej wartości, które nie pasują do prawego operandu. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie pasuje do prawego operandu. + + + Operator dopasowywania symboli wieloznacznych — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca z niej wartości, które nie pasują do prawego operandu. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie pasuje do prawego operandu. + + + Operator dopasowywania wyrażeń regularnych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które pasują do prawego operandu; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand pasuje do prawego operandu. + + + Operator dopasowywania wyrażeń regularnych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które pasują do prawego operandu; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand pasuje do prawego operandu. + + + Operator dopasowywania wyrażeń regularnych — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca wartości z kolekcji, które pasują do prawego operandu; w przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand pasuje do prawego operandu. + + + Operator dopasowywania wyrażeń regularnych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca z niej wartości, które nie pasują do prawego operandu. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie pasuje do prawego operandu. + + + Operator dopasowywania wyrażeń regularnych — bez uwzględniania wielkości liter. Gdy lewy operand jest kolekcją, zwraca z niej wartości, które nie pasują do prawego operandu. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie pasuje do prawego operandu. + + + Operator dopasowywania wyrażeń regularnych — z uwzględnieniem wielkości liter. Gdy lewy operand jest kolekcją, zwraca z niej wartości, które nie pasują do prawego operandu. W przeciwnym razie zwraca wartość PRAWDA, jeśli lewy operand nie pasuje do prawego operandu. + + + Operator zamiany — bez uwzględniania wielkości liter. Zmienia lewy operand. Przykład: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operator zamiany — bez uwzględniania wielkości liter. Zmienia lewy operand. Przykład: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operator zamiany — z uwzględnieniem wielkości liter. Zmienia lewy operand. Przykład: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (prawy operand) dokładnie pasuje do co najmniej jednej z wartości w lewym operandzie. + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (prawy operand) dokładnie pasuje do co najmniej jednej z wartości w lewym operandzie. + + + Operator zawierania — z uwzględnieniem wielkości liter. Zwraca wartość PRAWDA tylko wtedy, gdy wartość testowa (prawy operand) dokładnie pasuje do co najmniej jednej z wartości w lewym operandzie. + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (prawy operand) nie pasuje dokładnie do żadnej wartości w lewym operandzie. + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (prawy operand) nie pasuje dokładnie do żadnej wartości w lewym operandzie. + + + Operator zawierania — z uwzględnieniem wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (prawy operand) nie pasuje dokładnie do żadnej wartości w lewym operandzie. + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (lewy operand) dokładnie pasuje do co najmniej jednej z wartości w prawym operandzie. + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (lewy operand) dokładnie pasuje do co najmniej jednej z wartości w prawym operandzie. + + + Operator zawierania — z uwzględnieniem wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (lewy operand) dokładnie pasuje do co najmniej jednej z wartości w prawym operandzie. + + + Operator zawierania — z uwzględnieniem wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (lewy operand) nie pasuje dokładnie do żadnej wartości w prawym operandzie. + + + Operator zawierania — bez uwzględniania wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (lewy operand) nie pasuje dokładnie do żadnej wartości w prawym operandzie. + + + Operator zawierania — z uwzględnieniem wielkości liter. Zwraca wartość PRAWDA, gdy wartość testowa (lewy operand) nie pasuje dokładnie do żadnej wartości w prawym operandzie. + + + Podział — z uwzględnieniem wielkości liter. Dzieli jeden lub więcej ciągów na podciągi. +-Podziel <Ciąg> + +<Ciąg> -Podziel <Ogranicznik>[,<Maks. liczba podciągów>[,"<Opcje>"]] + +<Ciąg> -Podziel {<ScriptBlock>} [,<Maks. liczba podciągów>] + + + Podział — z uwzględnieniem wielkości liter. Dzieli jeden lub więcej ciągów na podciągi. +-Podziel <Ciąg> + +<Ciąg> -Podziel <Ogranicznik>[,<Maks. liczba podciągów>[,"<Opcje>"]] + +<Ciąg> -Podziel {<ScriptBlock>} [,<Maks. liczba podciągów>] + + + Podział— z uwzględnieniem wielkości liter. Dzieli jeden lub więcej ciągów na podciągi. +-Podziel <Ciąg> + +<Ciąg> -Podziel <Ogranicznik>[,<Maks. liczba podciągów>[,"<Opcje>"]] + +<Ciąg> -Podziel {<ScriptBlock>} [,<Maks. liczba podciągów>] + + + Zwraca wartość PRAWDA, gdy lewy operand nie jest wystąpieniem określonego typu platformy .NET Framework (prawy operand). + + + Zwraca wartość PRAWDA, gdy lewy operand jest wystąpieniem określonego typu platformy .NET Framework (prawy operand). + + + Konwertuje lewy operand na określony typ platformy .NET Framework (prawy operand). + + + Formatuje ciągi przy użyciu metody formatowania obiektów ciągów. + + + Logiczne oraz. Zwraca wartość PRAWDA, gdy oba wyrażenia mają wartość PRAWDA. + + + Bitowe polecenie ORAZ + + + Logiczne lub. Zwraca wartość PRAWDA, gdy jedno lub oba wyrażenia mają wartość PRAWDA. + + + Bitowe LUB (włącznie) + + + Logiczne wyłączne lub. Zwraca wartość PRAWDA, gdy jedno z wyrażeń ma wartość PRAWDA, a drugie wartość FAŁSZ. + + + Bitowe LUB (wyłączne) + + + Dołącz — łączy wiele ciągów w jeden ciąg. +-Dołącz <Ciąg[]> +<Ciąg[]> -Dołącz <Ogranicznik> + + + Operator bitowy przesunięcia w lewo. Wstawia zero w skrajnie prawej pozycji bitowej. + + + Operator bitowy przesunięcia w prawo. Wstawia zero w skrajnie lewej pozycji bitowej. W przypadku wartości ze znakiem zachowywany jest bit znaku. + + + [ciąg] +Określa nazwę tworzonej właściwości. + + + [ciąg] +Określa nazwę tworzonej właściwości. + + + [blok skryptu] +Blok skryptu używany do obliczania wartości nowej właściwości. + + + [ciąg] +Określa sposób wyświetlania wartości w kolumnie. +Prawidłowe wartości to „left”, „center” i „right”. + + + [ciąg] +Określa ciąg formatujący, który definiuje sposób formatowania wartości wyjściowej. + + + [int] +Określa maksymalną szerokość kolumny w tabeli, gdy wyświetlana jest wartość. +Wartość musi być większa od 0. + + + [int] +Klucz głębokości określa głębokość rozwijania dla każdej właściwości. + + + [wartość logiczna] +Określa kolejność sortowania dla jednej lub kilku właściwości. + + + [wartość logiczna] +Określa kolejność sortowania dla jednej lub kilku właściwości. + + + [Ciąg[]] +Określa nazwy dzienników, z których mają być pobierane zdarzenia. +Obsługuje symbole wieloznaczne. + + + [Ciąg[]] +Określa dostawców dzienników zdarzeń, z których mają być pobierane zdarzenia. +Obsługuje symbole wieloznaczne. + + + [Ciąg[]] +Określa ścieżki plików dziennika, z których mają być pobierane zdarzenia. +Prawidłowe formaty plików to: .etl, .evt i .evtx + + + [długie[]] +Wybiera zdarzenia z określonymi maskami bitowymi słów kluczowych. +Poniżej znajdują się standardowe słowa kluczowe: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Wybiera zdarzenia o określonych identyfikatorach. + + + [int[]] +Wybiera zdarzenia z określonymi poziomami dziennika. +Prawidłowe poziomy dziennika to: +1: krytyczny +2: błąd +3: ostrzeżenie +4: w celach informacyjnych +5: pełne informacje + + + [data/godzina] +Wybiera zdarzenia utworzone po określonej dacie i godzinie. + + + [data/godzina] +Wybiera zdarzenia utworzone przed określoną datą i godziną. + + + [ciąg] +Wybiera zdarzenia wygenerowane przez określonego użytkownika. +Może to być ciąg znaków reprezentujący identyfikator SID albo domenę i nazwę użytkownika w formacie DOMENA\NAZWA_UŻYTKOWNIKA lub USERNAME@DOMAIN + + + [ciąg[]] +Wybiera zdarzenia z dowolną z wartości określonych w sekcji EventData. + + + [tablica skrótów] +Wyklucza zdarzenia zgodne z wartościami określonymi w tabeli skrótów. + + + [ciąg] lub [tabela skrótów] +Określa tablicę modułów programu PowerShell wymaganych przez skrypt. +Każdy element może być ciągiem znaków z nazwą modułu albo tabelą skrótów z następującymi kluczami: +Nazwa: Nazwa modułu +GUID: identyfikator GUID modułu +Jedno z następujących: +ModuleVersion: określa minimalną akceptowalną wersję modułu. +RequiredVersion: określa dokładną, wymaganą wersję modułu. +MaximumVersion: określa maksymalną akceptowalną wersję modułu. + + + [ciąg] +Określa wersję programu PowerShell wymaganą przez skrypt. +Prawidłowe wartości to „Core” i „Desktop” + + + [przełącznik] +Określa, że program PowerShell musi być uruchomiony jako administrator w systemie Windows. +To musi być ostatni parametr w wierszu instrukcji #requires. + + + [wersja] +Określa minimalną wersję programu PowerShell wymaganą przez skrypt. + + + Określa, że skrypt wymaga do uruchomienia programu PowerShell 7+. + + + Określa, że ​​do uruchomienia skryptu wymagany jest program Windows PowerShell 5.1. + + + [ciąg] +Wymagane. Określa nazwę modułu. + + + [ciąg] +Opcjonalne. Określa identyfikator GUID modułu. + + + [ciąg] +Określa minimalną akceptowalną wersję modułu. + + + [ciąg] +Określa dokładną, wymaganą wersję modułu. + + + [ciąg] +Określa maksymalną akceptowalną wersję modułu. + + + Krótki opis funkcji lub skryptu. +Tego słowa kluczowego można użyć tylko raz w każdym temacie. + + + Szczegółowy opis funkcji lub skryptu. +Tego słowa kluczowego można użyć tylko raz w każdym temacie. + + + .PARAMETER <Nazwa parametru> +Opis parametru. +Dodaj słowo kluczowe .PARAMETER dla każdego parametru w składni funkcji lub skryptu. + + + Przykładowe polecenie używające funkcji lub skryptu, po którym opcjonalnie następują przykładowe dane wyjściowe i opis. +Powtórz to słowo kluczowe dla każdego przykładu. + + + Typy obiektów platformy .NET, które można przekazać potokiem do funkcji lub skryptu. +Można również uwzględnić opis obiektów wejściowych. + + + Typ platformy .NET obiektów zwracanych przez polecenie cmdlet. +Możesz też dodać opis zwracanych obiektów. + + + Dodatkowe informacje o funkcji lub skrypcie. + + + Nazwa powiązanego tematu. +Powtórz słowo kluczowe funkcji .LINK dla każdego powiązanego tematu. +Zawartość słowa kluczowego funkcji .Link może też zawierać identyfikator URI do internetowej wersji tego samego tematu pomocy. + + + Nazwa technologii lub funkcji używanej przez funkcję lub skrypt bądź z którą jest powiązana. + + + Nazwa roli użytkownika dla tematu pomocy. + + + Słowa kluczowe opisujące zamierzone użycie funkcji. + + + .FORWARDHELPTARGETNAME <Command-Name> +Przekierowuje do tematu pomocy dla określonego polecenia. + + + .FORWARDHELPCATEGORY <Kategoria> +Określa kategorię pomocy elementu w elemencie .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Określa sesję zawierającą temat pomocy. +Wprowadź zmienną zawierającą obiekt PSSession. + + + .EXTERNALHELP <XML Help File> +Słowo kluczowe .ExternalHelp jest wymagane, gdy funkcja lub skrypt są udokumentowane w plikach XML. + + + Określa ścieżkę do zestawu platformy .NET do załadowania. + +używając zestawu <.NET-assembly-path> + + + Określa moduł programu PowerShell, z którego mają być ładowane klasy. + +używając modułu <ModuleName lub Path> + +używając modułu <ModuleSpecification hashtable> + + + Określa przestrzeń nazw platformy .NET, z której mają być rozpoznawane typy, albo alias przestrzeni nazw. + +używając przestrzeni nazw <.NET-namespace> + +używając przestrzeni nazw <AliasName> = <.NET-namespace> + + + Określa alias typu platformy .NET. + +używając typu <AliasName> = <.NET-type> + + + Zwykły ciąg znaków. + + + Ciąg znaków zawierający nierozwinięte odwołania do zmiennych środowiskowych, które są rozwijane podczas pobierania wartości. + + + Dane binarne w dowolnej formie. + + + 32-bitowa liczba binarna. + + + Tablica ciągów. + + + 64-bitowa liczba binarna. + + + Nieobsługiwany typ danych rejestru. + + + „-” — przecinek + + + „, ” - przecinek i spacja + + + „-” — średnik + + + „-” — średnik i spacja + + + {0} — nowy wiersz + + + „-” — kreska + + + „-” — spacja + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/TransactionStrings.pl.resx b/src/System.Management.Automation/resources/pl/TransactionStrings.pl.resx new file mode 100644 index 00000000000..c62b3e3a21e --- /dev/null +++ b/src/System.Management.Automation/resources/pl/TransactionStrings.pl.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Nie można użyć transakcji. Żadna transakcja nie jest aktywna. + + + Nie można zatwierdzić transakcji. Żadna transakcja nie jest aktywna. + + + Nie można wycofać transakcji, ponieważ nie ma aktywnej transakcji. + + + Nie można wycofać transakcji. Transakcja została już zatwierdzona. + + + Nie można zatwierdzić transakcji. Transakcja została już zatwierdzona. + + + Nie można zatwierdzić transakcji. Transakcja została wycofana lub przekroczono limit czasu. + + + Nie można wycofać transakcji. Transakcja została już wycofana lub przekroczono limit czasu. + + + Nie można ustawić aktywnej transakcji. Nie utworzono żadnej transakcji. + + + Nie można ustawić aktywnej transakcji. Aktywna transakcja została wycofana lub przekroczono limit czasu. + + + To polecenie cmdlet wymaga aktywnej transakcji. Bieżąca transakcja została już zatwierdzona lub wycofana. + + + To polecenie cmdlet wymaga transakcji. Uruchom ponownie polecenie z parametrem -UseTransaction. + + + Nie można użyć transakcji. Nie rozpoczęto żadnej transakcji. + + + Nie można użyć transakcji. Transakcja została zatwierdzona. + + + Nie można użyć transakcji. Transakcja została wycofana lub przekroczono limit czasu. + + + Nie można użyć transakcji. Przekroczono limit czasu transakcji. + + + Transakcja podstawowa nie została ustawiona. + + + Transakcja podstawowa nie jest aktywna. + + + Nie można ustawić transakcji podstawowej po utworzeniu innych transakcji. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/TypesXmlStrings.pl.resx b/src/System.Management.Automation/resources/pl/TypesXmlStrings.pl.resx new file mode 100644 index 00000000000..07e75b1e2fa --- /dev/null +++ b/src/System.Management.Automation/resources/pl/TypesXmlStrings.pl.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}): Błąd: {3} + + + {0}, {1}({2}) : Błąd w typie „{3}”: {4} + + + Węzeł „{0}” musi występować tylko raz w obszarze „{1}”. Węzeł nadrzędny „{1}” zostanie zignorowany. + + + Węzeł „{0}” jest niedozwolony. Dozwolone są następujące węzły: {1}. + + + Węzeł „{0}” nie powinien mieć wewnętrznego tekstu. + + + Węzeł „{0}” powinien mieć tekst wewnętrzny. + + + Nie znaleziono węzła „{0}”. Powinien on występować tylko raz w obszarze „{1}”. Węzeł nadrzędny „{1}” zostanie zignorowany. + + + Węzeł „Type” musi mieć wartości „Members”, „TypeConverters” lub „TypeAdapters”. + + + Nie można utworzyć wystąpienia konwertera typów dla typu {0} z powodu wyjątku: {1}. + + + Program PowerShell nie może utworzyć wystąpienia karty typu dla typu {0} z powodu następującego wyjątku: {1}. + + + Dostosowany typ „{0}” jest nieprawidłowy. + + + Element TypeConverter został zignorowany, ponieważ już występuje. + + + Element TypeAdapter został zignorowany, ponieważ już występuje. + + + Typ „{0}” powinien być typem TypeConverter lub PSTypeConverter. + + + Typem „{0}” powinno być PSPropertyAdapter. + + + Element członkowski {0} już istnieje. + + + Następująca nazwa elementu członkowskiego jest zarezerwowana: {0} + + + Wyjątek:{0} + + + Właściwość ScriptProperty powinna mieć metodę pobierającą lub ustawiającą. + + + Właściwość CodeProperty powinna mieć metodę pobierającą lub ustawiającą. + + + {0}, {1} : {2} + + + Wartość powinna mieć wartość TRUE lub FALSE zamiast {0}. + + + Węzeł „{0}” nie powinien mieć atrybutu „{1}”. + + + {0}, {1}: nie znaleziono pliku. + + + {0}, {1}: plik został pominięty, ponieważ został już załadowany przez {2}. + + + Nie można znaleźć klucza rejestru: {0}{1}. Używanie {2} do załadowania plików konfiguracji. + + + Nie można odnaleźć ścieżki {0} określonej w kluczu rejestru: {1}{2}. Używanie {3} do ładowania plików konfiguracji. + + + {0}, {1}: plik został pominięty, ponieważ nie ma rozszerzenia nazwy pliku ps1xml. + + + {0}, {1}: plik został pominięty z powodu następującego wyjątku walidacji: {2}. + + + Element członkowski „{0}”" musi być notatką. + + + Nie można przekonwertować notatki „{0}” na „{1}”. + + + Nie używaj tutaj elementu członkowskiego „{0}”. + + + Element członkowski „{0}” musi mieć typ „{1}”. + + + Wartość „{0}” musi być obecna, gdy „{1}” ma wartość „{2}”, a „{3}” to „{4}”. + + + Poprzedni błąd spowodował zignorowanie wszystkich ustawień serializacji. + + + Element „{0}” nie jest standardowym elementem członkowskim i zostanie zignorowany. + + + Ścieżka {0} nie jest w pełni kwalifikowana. Określ w pełni kwalifikowaną ścieżkę pliku typu. + + + Nie można zaktualizować elementu TypeTable, ponieważ mógł on zostać utworzony poza obszarem działania. + + + Wystąpiły błędy podczas ładowania elementu TypeTable. Poszukaj właściwości Errors, aby uzyskać szczegółowe komunikaty o błędach. + + + Błąd w TypeData „{0}”: {1} + + + Element „{0}” powinien mieć wartość dla swojej właściwości „{1}”. + + + Typ „{0}” nie powinien mieć wartości null ani mieć pustego ciągu we właściwości „{1}”. + + + Nie znaleziono typu „{0}”. Wartość nazwy typu musi być pełną nazwą typu. Sprawdź nazwę typu i ponownie uruchom polecenie. + + + Element TypeData musi mieć wartości „Members”, „TypeConverters”, „TypeAdapters” lub „StandardMembers”. + + + Tabeli typu udostępnionego nie można zaktualizować za pomocą więcej niż jednego wpisu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/VerbDescriptionStrings.pl.resx b/src/System.Management.Automation/resources/pl/VerbDescriptionStrings.pl.resx new file mode 100644 index 00000000000..af56c4f8617 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/VerbDescriptionStrings.pl.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Dodaje zasób do kontenera lub dołącza element do innego elementu + + + Potwierdza lub zatwierdza stan zasobu lub procesu + + + Potwierdza stan zasobu + + + Przechowuje dane przez replikację + + + Ogranicza dostęp do zasobu + + + Tworzy artefakt (zazwyczaj binarny lub dokument) na podstawie zestawu plików wejściowych (zwykle kodu źródłowego lub dokumentów deklaratywnych) + + + Tworzy migawkę bieżącego stanu danych lub ich konfiguracji + + + Usuwa wszystkie zasoby z kontenera, ale nie usuwa kontenera + + + Zmienia stan zasobu, czyniąc go niedostępnym, niewidocznym lub bezużytecznym + + + Porównuje dane z jednego zasobu z danymi z innego zasobu + + + Kończy operację + + + Kompresuje dane zasobu + + + Potwierdza, weryfikuje lub sprawdza stan zasobu lub procesu + + + Tworzy łącze między źródłem a miejscem docelowym + + + Zmienia dane z jednej reprezentacji na inną, gdy polecenie cmdlet obsługuje konwersję dwukierunkową lub konwersję między wieloma typami danych + + + Konwertuje jeden podstawowy typ danych wejściowych (rzeczownik polecenia cmdlet wskazuje dane wejściowe) na co najmniej jeden obsługiwany typ danych wyjściowych + + + Konwertuje co najmniej jeden typ danych wejściowych na podstawowy typ danych wyjściowych (rzeczownik polecenia cmdlet wskazuje typ danych wyjściowych) + + + Kopiuje zasób pod inną nazwą lub do innego kontenera + + + Bada zasób w celu zdiagnozowania problemów operacyjnych + + + Odrzuca, sprzeciwia się, blokuje lub przeciwstawia się stanowi zasobu lub procesu + + + Wysyła aplikację, witrynę internetową lub rozwiązanie do zdalnych miejsc docelowych w taki sposób, aby użytkownik tego rozwiązania mógł uzyskać do niego dostęp po zakończeniu wdrażania + + + Konfiguruje zasób do stanu niedostępnego lub nieaktywnego + + + Przerywa połączenie między źródłem a miejscem docelowym + + + Odłącza nazwaną jednostkę od lokalizacji + + + Modyfikuje istniejące dane, dodając lub usuwając zawartość + + + Konfiguruje zasób do stanu dostępnego lub aktywnego + + + Określa akcję umożliwiającą użytkownikowi przejście do zasobu + + + Ustawia bieżące środowisko lub kontekst na ostatnio używany kontekst + + + Przywraca dane zasobu skompresowanego do pierwotnego stanu + + + Hermetyzuje podstawowe dane wejściowe w trwałym magazynie danych, takim jak plik, lub w formacie wymiany + + + Wyszukuje obiekt w kontenerze, który jest nieznany, domniemany, opcjonalny lub określony + + + Porządkuje obiekty w określonym układzie + + + Określa akcję pobierającą zasób + + + Zezwala na dostęp do zasobu + + + Rozmieszcza lub kojarzy co najmniej jeden zasób + + + Sprawia, że zasób jest niewykrywalny + + + Tworzy zasób na podstawie danych przechowywanych w trwałym magazynie danych (takim jak plik) lub w formacie wymiany + + + Przygotowuje zasób do użycia i ustawia go w stanie domyślnym + + + Umieszcza zasób w lokalizacji i opcjonalnie go inicjuje + + + Wykonuje akcję, taką jak uruchomienie polecenia lub metody + + + Łączy zasoby w jeden zasób + + + Nakłada ograniczenia na zasób + + + Zabezpiecza zasób + + + Identyfikuje zasoby używane przez określoną operację lub pobiera statystyki dotyczące zasobu + + + Tworzy pojedynczy zasób z wielu zasobów + + + Dołącza nazwaną jednostkę do lokalizacji + + + Przenosi zasób z jednej lokalizacji do innej + + + Tworzy zasób + + + Zmienia stan zasobu, aby był dostępny, dostępny lub użyteczny + + + Zwiększa efektywność zasobu + + + Wysyła dane ze środowiska + + + Użyj zlecenia Test + + + Usuwa element ze szczytu stosu + + + Zabezpiecza zasób przed atakiem lub utratą + + + Udostępnia zasób innym osobom + + + Dodaje element na szczyt stosu + + + Pobiera informacje ze źródła + + + Przyjmuje informacje wysłane ze źródła + + + Resetuje zasób do stanu, do którego wykonano cofnięcie + + + Tworzy wpis dla zasobu w repozytorium, takim jak baza danych + + + Usuwa zasób z kontenera + + + Zmienia nazwę zasobu + + + Przywraca zasób do stanu używalności + + + Pyta o zasób lub prosi o uprawnienia + + + Przywraca zasób do stanu pierwotnego + + + Zmienia rozmiar zasobu + + + Mapuje skrótową reprezentację zasobu na pełniejszą reprezentację + + + Zatrzymuje operację, a następnie uruchamia ją ponownie + + + Ustawia zasób w uprzednio zdefiniowanym stanie, na przykład w stanie ustawionym przez punkt kontrolny + + + Uruchamia operację, która została wstrzymana + + + Określa akcję, która nie zezwala na dostęp do zasobu + + + Zachowuje dane, aby uniknąć ich utraty + + + Tworzy odwołanie do zasobu w kontenerze + + + Lokalizuje zasób w kontenerze + + + Dostarcza informacje do miejsca docelowego + + + Zastępuje dane w istniejącym zasobie lub tworzy zasób zawierający część danych + + + Sprawia, że zasób jest widoczny dla użytkownika + + + Zapewnia, że dwa lub więcej zasobów jest w tym samym stanie + + + Pomija co najmniej jeden zasób lub punkt w sekwencji + + + Oddziela części zasobu + + + Inicjuje operację + + + Przechodzi do następnego punktu lub zasobu w sekwencji + + + Przerywa działanie + + + Przedstawia zasób do zatwierdzenia + + + Wstrzymuje działanie + + + Określa akcję, która przełącza się między dwoma zasobami, na przykład aby zmienić lokalizację, zakres obowiązków lub stan + + + Weryfikuje działanie lub spójność zasobu + + + Śledzi działania zasobu + + + Usuwa ograniczenia z zasobu + + + Przywraca zasób do poprzedniego stanu + + + Usuwa zasób z określonej lokalizacji + + + Zwalnia zablokowany zasób + + + Usuwa zabezpieczenia z zasobu, które zostały dodane, aby zapobiec atakowi lub utracie + + + Sprawia, że zasób jest niedostępny dla innych + + + Usuwa wpis dotyczący zasobu z repozytorium + + + Aktualizuje zasób, aby zachować jego stan, dokładność, zgodność lub zgodność z wymaganiami + + + Używa zasobu lub dołącza go, aby coś zrobić + + + Wstrzymuje operację do czasu wystąpienia określonego zdarzenia + + + Stale sprawdza zasób lub monitoruje go pod kątem zmian + + + Dodaje informacje do elementu docelowego + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pl/WildcardPatternStrings.pl.resx b/src/System.Management.Automation/resources/pl/WildcardPatternStrings.pl.resx new file mode 100644 index 00000000000..21d8e321cf7 --- /dev/null +++ b/src/System.Management.Automation/resources/pl/WildcardPatternStrings.pl.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 + + + Określony wzorzec symboli wieloznacznych jest nieprawidłowy: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/Authenticode.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/Authenticode.pt-BR.resx new file mode 100644 index 00000000000..3f6168eafb6 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/Authenticode.pt-BR.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 + + + O arquivo {0} não pode ser carregado porque você optou por não executar este software agora. + + + O arquivo {0} não pode ser carregado porque você optou por nunca executar software deste publicador. + + + O arquivo {0} é publicado por {1}. Este publicador não é explicitamente confiável no seu sistema. O script não será executado no sistema. Para obter mais informações, execute o comando "get-help about_signing". + + + Não é possível carregar o arquivo {0} porque a execução de scripts está desabilitada neste sistema. Para obter mais informações, consulte about_Execution_Policies em https://go.microsoft.com/fwlink/?LinkID=135170. + + + O arquivo {0} não pode ser carregado. {1}. + + + O arquivo {0} não pode ser carregado porque sua operação está bloqueada por políticas de restrição de software, como aquelas criadas usando Política de Grupo. + + + O arquivo {0} não pode ser carregado porque seu conteúdo não pôde ser lido. + + + Não é possível assinar o código. O certificado especificado não é adequado para assinatura de código. + + + Não é possível assinar o código. A URL do servidor de carimbo de data/hora deve ser totalmente qualificada e estar no formato http://<server url> ou https://<server url>. + + + Não é possível assinar o código. Não há suporte para o algoritmo de hash. + + + Deseja executar o software deste publicador não confiável? + + + O arquivo {0} é publicado por {1} e não é confiável no seu sistema. Execute somente scripts de publicadores confiáveis. + + + O software {0} é publicado por um editor desconhecido. É recomendável que você não execute este software. + + + Aviso de segurança + + + Execute somente scripts nos quais você confia. Embora scripts da internet possam ser úteis, este script pode danificar seu computador. Se você confia neste script, use o cmdlet Unblock-File para permitir que ele seja executado sem esta mensagem de aviso. Deseja executar o {0}? + + + N&unca executar + + + Não execute o script deste publicador agora e não solicite que eu execute este script no futuro. Tentar executar este script novamente resultará em uma falha silenciosa. + + + &Não Executado + + + Não execute o script deste publicador agora e continue a solicitar que eu execute este script no futuro. + + + &Executar uma vez + + + Execute o script deste editor agora e continue a solicitar que eu execute esse script no futuro. + + + &Sempre executar + + + Execute o script deste publicador agora e não me solicite que eu execute este script no futuro. + + + &Suspender + + + Pause o pipeline atual e volte para o prompt de comando. Digite sair para retomar a operação quando terminar. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/AuthorizationManagerBase.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/AuthorizationManagerBase.pt-BR.resx new file mode 100644 index 00000000000..079a87f8aa5 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/AuthorizationManagerBase.pt-BR.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 + + + A verificação do AuthorizationManager falhou. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/AutomationExceptions.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/AutomationExceptions.pt-BR.resx new file mode 100644 index 00000000000..18d6f475628 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/AutomationExceptions.pt-BR.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 argument because the value of argument "{0}" is not valid. Change the value of the "{0}" argument and run the operation again. + + + Cannot process argument because the value of parameter "{0}" is not valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). Change the value of the "{0}" parameter and run the operation again. + + + Cannot process argument because the value of argument "{0}" is null. Change the value of argument "{0}" to a non-null value. + + + Cannot process argument because the value of argument "{0}" is out of range. Change argument "{0}" to a value that is within range. + + + Cannot perform operation because operation "{0}" is not valid. Remove operation "{0}", or investigate why it is not valid. + + + Cannot perform operation because operation "{0}" is not implemented. + + + Cannot perform operation because operation "{0}" is not supported. + + + Cannot perform operation because object "{0}" has already been disposed. + + + The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause. + + + The script block cannot be converted because it contains more than one clause. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + An empty script block cannot be converted. Verify that the script block contains exactly one pipeline or command. + + + Only a script block that contains exactly one pipeline or command can be converted. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + A script block that contains a top-level trap statement cannot be converted. + + + Cannot generate a PowerShell object for a ScriptBlock dereferencing variables undeclared in the param(...) block. Name of undeclared variable: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating non-constant expressions. Non-constant expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions. Dynamic expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock that tries to pass other script blocks inside argument values. + + + Cannot generate a PowerShell object for a ScriptBlock which invokes pipelines, commands or functions to evaluate arguments of the main pipeline. + + + Cannot generate a PowerShell object for a ScriptBlock that uses dot sourcing. + + + Cannot generate a PowerShell object for a ScriptBlock that invokes other script blocks. + + + The script block cannot be converted to a PowerShell object because it contains forbidden redirection operators. + + + Cannot generate a PowerShell object for a ScriptBlock that does not have an associated operation context. + + + The command was stopped by the user. + + + Object "{0}" is the wrong type to return from the dynamicparam block. The dynamicparam block must return either $null, or an object with type [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + The script block cannot be converted to an open generic type. Define an appropriate closed generic type, and then retry. + + + Cannot generate a PowerShell object for a ScriptBlock that starts a pipeline with an expression. + + + The value of the using variable '$using:{0}' cannot be retrieved because it has not been set in the local session. + + + Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CatalogStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CatalogStrings.pt-BR.resx new file mode 100644 index 00000000000..15c847caa95 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CatalogStrings.pt-BR.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não foi possível gerar o arquivo de definição de catálogo. + + + Adicionando o arquivo "{0}" ao catálogo. O caminho relativo do arquivo no catálogo é "{1}". + + + Ignorando a validação do arquivo {0} do catálogo. + + + Arquivo {0} encontrado no catálogo com hash de {1}. + + + Os caminhos do catálogo contêm vários arquivos com o mesmo caminho relativo {0}. + + + Arquivo {0} encontrado no disco com hash de {1}. + + + Ignorando a validação do arquivo {0} no caminho. + + + Não foi possível obter um identificador para um contexto de administrador do catálogo para um determinado algoritmo de hash {0}. + + + Não foi possível criar o hash para o arquivo {0}. + + + Não é possível abrir o arquivo de catálogo {0}. + + + A versão do catálogo é inválida. Damos suporte apenas às versões {0} e {1} do catálogo. + + + Não foi possível abrir o arquivo de definição de catálogo. + + + Foram encontradas várias entradas do membro do arquivo {0} no catálogo. + + + Não foi possível localizar o nome do arquivo ou o caminho do membro do catálogo {0}. + + + Não foi possível encontrar a entrada do arquivo {0} para criar o hash. + + + Não foi possível ler o arquivo {0} para calcular seu hash. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CimInstanceTypeAdapterResources.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CimInstanceTypeAdapterResources.pt-BR.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CimInstanceTypeAdapterResources.pt-BR.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CmdletizationCoreResources.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CmdletizationCoreResources.pt-BR.resx new file mode 100644 index 00000000000..5ffa2b2a66c --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CmdletizationCoreResources.pt-BR.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlets da classe "{0}" + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Não é possível processar o XML de definição do cmdlet para o seguinte arquivo: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Não foi possível processar o atributo ObjectModelWrapper. O tipo {0} define vários conjuntos de parâmetros. Verifique se o XML de definição do cmdlet especifica um tipo válido no atributo ObjectModelWrapper e tente novamente. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Não foi possível processar o atributo ObjectModelWrapper. O tipo {0} é um tipo genérico aberto. Verifique se o XML de definição do cmdlet especifica um tipo válido no atributo ObjectModelWrapper e tente novamente. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Não foi possível processar o atributo ObjectModelWrapper. O tipo {0} não é derivado da seguinte classe: {1}. Verifique se o XML de definição do cmdlet especifica um tipo válido no atributo ObjectModelWrapper e tente novamente. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Não foi possível processar o atributo ObjectModelWrapper. O tipo {0} define o parâmetro de cmdlet {1} com um parâmetro de atributo {2} que é ignorado. Verifique se o XML de definição do cmdlet especifica um tipo válido no atributo ObjectModelWrapper e tente novamente. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Não é possível definir o parâmetro {0} para o cmdlet {1}. O nome do parâmetro já está definido pela classe {2}. Altere o nome do parâmetro no XML de definição do cmdlet e tente novamente. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Não é possível definir o parâmetro {0} para o cmdlet {1}. O nome do parâmetro já está definido no elemento XML {2}. Altere o nome do parâmetro no XML de definição do cmdlet e depois tente novamente. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + O valor do atributo EnumName não é convertido em um identificador C# válido: {0}. Verifique o atributo EnumName no XML de definição do cmdlet e tente novamente. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Não é possível processar o elemento <Enum EnumName="{0}" ...>. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + O computador remoto retornou um arquivo CDXML inválido. O seguinte adaptador de cmdlet não tem suporte para importar um módulo CDXML de um computador remoto: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CommandBaseStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CommandBaseStrings.pt-BR.resx new file mode 100644 index 00000000000..4e6380032ec --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CommandBaseStrings.pt-BR.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Continuar com esta operação? + + + &Sim + + + Continue apenas com a próxima etapa da operação. + + + Sim para &Todos + + + Continue com todas as etapas da operação. + + + &Não + + + Ignore esta operação e prossiga com a próxima operação. + + + Não para To&dos + + + Ignore esta operação e todas as operações subsequentes. + + + Interrompa este comando. + + + &Suspender comando + + + &Suspender + + + Pause o pipeline atual e volte para o prompt de comando. Digite "{0}" para retomar o pipeline. + + + + O programa "{0}" terminou com código de saída diferente de zero: {1} ({2}). + + + Executando a operação "{0}" no destino "{1}". + + + What If: {0} + + + Tem certeza de que deseja executar esta ação? +{0} + + + Confirmar + + + O comando em execução foi interrompido porque a variável de preferência "{0}" ou o parâmetro comum está definido como Stop: {1} + + + O comando em execução foi interrompido porque a variável de preferência "{0}" ou o parâmetro comum está definido como Stop. + + + O comando em execução foi interrompido porque a variável de preferência "{0}" ou o parâmetro comum está definido como o seguinte valor que não é válido: "{1}". + + + O comando em execução foi interrompido porque o usuário selecionou a opção Stop. + + + O comando em execução foi interrompido porque o usuário o interrompeu. + + + Cmdlets derivados de PSCmdlet não podem ser invocados diretamente. + + + O cmdlet "{0}" não oferece suporte ao parâmetro "{1}" em uma sessão remota. + + + Contagem total: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Custo total estimado: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Contagem total desconhecida + Reviewed by TArcher on 2010-07-20 + + + comando "{0}" + + + O {0} está obsoleto. {1} + + + Falha na chamada de execução com o código de erro {0} para a linha de comando: {1} + + + O comando "{0}" não foi encontrado. O comando especificado precisa ser um executável. + + + Verificação de dot-source do processamento de bloco de script + + + O processamento de dot-source para o bloco de script "{0}" falhará no modo de linguagem restrita porque o modo de linguagem "{1}" não corresponde ao modo de linguagem atual "{2}". + + + Pesquisador de comandos + + + O comando "{0}" no módulo "{1}" não é confiável e não estará acessível no modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ConsoleInfoErrorStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ConsoleInfoErrorStrings.pt-BR.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ConsoleInfoErrorStrings.pt-BR.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CoreClrStubResources.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CoreClrStubResources.pt-BR.resx new file mode 100644 index 00000000000..e2bd8f78ca7 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CoreClrStubResources.pt-BR.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + O nome da variável de ambiente não pode conter o caractere de igual. + + + O nome ou o valor da variável de ambiente é muito longo. + + + O primeiro caractere da cadeia de caracteres é o caractere nulo. + + + A cadeia de caracteres não pode ter comprimento zero. + + + Não foi possível obter o nome do computador. + + + Não foi possível obter o nome do domínio do usuário atual. + + + Erro desconhecido "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CredUI.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CredUI.pt-BR.resx new file mode 100644 index 00000000000..ce39ec8134a --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CredUI.pt-BR.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Solicitação de credencial do PowerShell + + + Insira suas credenciais. + + + Insira suas credenciais. + + + O comprimento máximo da legenda é {0} caracteres. + + + O comprimento máximo da mensagem é {0} caracteres. + + + O comprimento máximo do valor UserName é {0} caracteres. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/Credential.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/Credential.pt-BR.resx new file mode 100644 index 00000000000..cdbef481c0d --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/Credential.pt-BR.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 + + + Não é possível serializar a credencial. Se esse comando estiver iniciando um fluxo de trabalho, as credenciais não poderão ser persistidas, pois o processo no qual o fluxo de trabalho é iniciado não tem permissão para serializar credenciais. + +-- Se o fluxo de trabalho foi iniciado em uma PSSession para o computador local, adicione o parâmetro EnableNetworkAccess ao comando que criou a sessão. +-- Se o fluxo de trabalho foi iniciado em uma PSSession para um computador remoto, adicione o parâmetro Authentication com um valor de CredSSP ao comando que criou a sessão. Ou conecte-se a uma configuração de sessão que tenha o valor da propriedade RunAsUser. + + + O valor de UserName não está no formato correto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/CredentialAttributeStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/CredentialAttributeStrings.pt-BR.resx new file mode 100644 index 00000000000..cc363c96ce5 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/CredentialAttributeStrings.pt-BR.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 + + + Solicitação de credencial do PowerShell + + + Insira suas credenciais. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/DebuggerStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/DebuggerStrings.pt-BR.resx new file mode 100644 index 00000000000..9e5e11060e7 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/DebuggerStrings.pt-BR.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Variable breakpoint on '${0}' ({1} access) + + + Variable breakpoint on '{0}:${1}' ({2} access) + + + Line breakpoint on '{0}:{1}' + + + Line breakpoint on '{0}:{1}, {2}' + + + Command breakpoint on '{0}' + + + Command breakpoint on '{0}:{1}' + + + Breakpoint {0} will not be hit + + + {0}, {1,-16} Single step (step into functions, scripts, etc.) + + + {0}, {1,-16} Step to next statement (step over functions, scripts, etc.) + + + {0}, {1,-16} Step out of the current function, script, etc. + + + {0}, {1,-16} Continue operation + + + {0}, {1,-16} Stop operation and exit the debugger + + + {0}, Get-PSCallStack Display call stack + + + {0}, {1,-16} List source code for the current script. + + + Use "list" to start from the current line, "list <m>" + + + to start from line <m>, and "list <m> <n>" to list <n> + + + lines starting from line <m> + + + <enter> Repeat last command if it was {0}, {1} or {2} + + + {0}, {1,-16} displays this help message. + + + For instructions about how to customize your debugger prompt, type "help about_prompt". + + + +The current session does not support debugging; operation will continue. + + + + + {0}: line {1} + + + There is no source code available. + + + The starting line must be a positive integer no greater than {0} + + + The line count must be a positive integer. + + + <No file> + + + at {0}, {1}: line {2} + + + The debugger cannot process commands unless it is in the Stopped state. + + + SetDebugAction is not implemented for the local script debugger. + + + The debugger cannot set a resume action because the debugger in the remote session is not in a Stopped state. + + + The job cannot be debugged because the debugger is currently busy. + + + The provided job and all child jobs were examined but no jobs were found that could be debugged. In order to debug a job or child job the job must support debugging and also be in a running state. + + + The debugger cannot be enabled for step mode because the debugger is turned off with debug mode set to None. + + + The Runspace cannot be debugged because the host debugger is currently busy. + + + Cannot debug Runspace. The Runspace debugger is currently turned off (DebugMode is 'None'). + + + Cannot debug a Runspace that is not in the Opened state. This Runspace state is {0}. + + + Cannot debug Runspace. The Runspace {0} has no associated debugger. + + + The debugger is already overridden. + + + Cannot push a debugger object onto itself. + + + The {0} command is not supported for remote use in the version of PowerShell that is running in the remote runspace. + + + Process + + + {0}, {1,-16} Continue operation and detach the debugger. + + + The debugger detach command is not applicable. The detach command only applies when debugging jobs and runspaces with the Debug-Job or Debug-Runspace cmdlets. + + + Invalid runspace id: {0} + + + Unable to get Runspace. + + + Breakpoint or BreakpointList must be specified. + + + The BreakpointList contained an item that was not a breakpoint. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/DescriptionsStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/DescriptionsStrings.pt-BR.resx new file mode 100644 index 00000000000..2c1d31b3a6c --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/DescriptionsStrings.pt-BR.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 + + + {0} não pode ser nulo ou estar vazio. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/DiscoveryExceptions.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/DiscoveryExceptions.pt-BR.resx new file mode 100644 index 00000000000..7564cde77b2 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/DiscoveryExceptions.pt-BR.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 + + + O nome do cmdlet "{0}" não pode ser validado porque não está no formato correto. Os nomes de cmdlet devem incluir um verbo e um substantivo separados por um "-", como "Get-Process". + + + O parâmetro "{0}" é declarado várias vezes no conjunto de parâmetros "{1}". + + + O alias "{0}" é declarado várias vezes. + + + Não foi possível declarar o parâmetro. Os parâmetros podem ser declarados somente em campos e propriedades. + + + Não é possível processar o cmdlet. Um nome de cmdlet deve consistir em um par verbo e substantivo separado por "-". + + + O termo "{0}" não é reconhecido como um nome de um cmdlet, função, arquivo de script ou programa executável. +Verifique a ortografia do nome ou, se um caminho foi incluído, verifique se o caminho está correto e tente novamente. + + + O argumento "{0}" não é reconhecido como um cmdlet: {1} + + + O argumento "{0}" não é reconhecido como um cmdlet, possivelmente porque não deriva das classes cmdlet ou PSCmdlet: {1} + + + Não é possível resolver o alias "{0}" porque ele se refere ao termo "{1}", que não é reconhecido como um cmdlet, função, programa executável ou arquivo de script. Verifique o termo e tente novamente. + + + O parâmetro "{0}" com o valor "{1}" não pode ser processado porque não é um cmdlet e não pode ser processado pelo CommandProcessor. + + + Já existe um cmdlet chamado "{0}". Os cmdlets devem ter nomes exclusivos. + + + Já existe um provedor de cmdlet chamado "{0}". Os provedores de cmdlets devem ter nomes exclusivos. + + + Já existe um assembly chamado "{0}". Os assemblies devem ter nomes exclusivos. + + + Já existe um script chamado "{0}". Os scripts devem ter nomes exclusivos. + + + Não é possível processar a instrução #requires porque ela não está no formato correto. +A instrução #requires deve estar em um dos seguintes formatos: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + O script "{0}" não pode ser executado porque continha uma instrução "#requires" com uma ID de shell {1} incompatível com o shell atual. Para executar esse script, você deve usar o shell localizado em "{2}". + + + O script "{0}" não pode ser executado porque continha uma instrução "#requires" com uma ID de shell {1} incompatível com o shell atual. + + + O script "{0}" não pode ser executado porque continha uma instrução "#requires" para o PowerShell {1}. A versão do PowerShell exigida pelo script não corresponde à versão em execução no momento do PowerShell {2}. + + + O script "{0}" não pode ser executado porque continha uma instrução "#requires" para as edições do PowerShell "{1}". A edição do PowerShell exigida pelo script não corresponde à edição do PowerShell {2} em execução no momento. + + + O script "{0}" não pode ser executado porque os seguintes snap-ins especificados pelas instruções "#requires" do script estão ausentes: {1}. + + + A #requires statement has specified only a shellID. #Requires statements must specify a required PowerShell snap-in when running in PowerShell. + + + O script "{0}" não pode ser executado porque contém uma instrução "#requires" para execução como Administrador. A sessão atual do PowerShell não está sendo executada como Administrador. Inicie o PowerShell usando a opção Executar como Administrador e tente executar o script novamente. + + + {0} (Versão {1}) + + + Não foi possível recuperar o comando porque o parâmetro ArgumentList só pode ser especificado ao recuperar um único cmdlet ou script. + + + O nome do parâmetro "{0}" está reservado para uso futuro. + + + O script "{0}" não pode ser executado porque os seguintes módulos especificados pelas instruções "#requires" do script estão ausentes: {1}. + + + O comando "{0}" foi encontrado no módulo "{1}", mas o módulo não pôde ser carregado. Para obter mais informações, execute "Import-Module {1}". + + + O comando "{0}" foi encontrado no módulo "{1}", mas o módulo não pôde ser carregado devido ao seguinte erro: [{2}] +Para obter mais informações, execute "Import-Module {1}". + + + Não foi possível carregar o módulo "{0}". Para obter mais informações, execute "Import-Module {0}". + + + Nenhum comando correspondente inclui um parâmetro chamado "{0}". Verifique a ortografia do nome do parâmetro e tente novamente. + + + Não é possível usar dot-source neste comando porque ele foi definido em um modo de linguagem diferente. Para invocar esse comando sem importar seu conteúdo, omita o operador ".". + + + Os parâmetros ShowCommandInfo e Syntax não podem ser especificados juntos. + + + Esse comando de script é desabilitado quando o recurso experimental "{0}" é ativado. + + + Esse comando de script é desabilitado quando o recurso experimental "{0}" foi desativado. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/EnumExpressionEvaluatorStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/EnumExpressionEvaluatorStrings.pt-BR.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/EnumExpressionEvaluatorStrings.pt-BR.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ErrorCategoryStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ErrorCategoryStrings.pt-BR.resx new file mode 100644 index 00000000000..372ec65d38c --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ErrorCategoryStrings.pt-BR.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Deadlock detectado: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Categoria de erro não reconhecida {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ErrorPackage.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ErrorPackage.pt-BR.resx new file mode 100644 index 00000000000..b8d2cb7138a --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ErrorPackage.pt-BR.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 + + + {0}…{1} + + + O texto do erro está vazio para o erro "{0}" : "{1}" + + + O objeto "{0}" é relatado como um erro. + + + O valor {0} não tem suporte para uma variável ActionPreference. O valor fornecido deve ser usado somente como valor de um parâmetro de preferência e foi substituído pelo valor padrão. Para obter mais informações, consulte o tópico da Ajuda, "about_Preference_Variables". + + + O valor {0} ActionPreference é reservado para uso futuro e ainda não tem suporte no momento. Para obter mais informações sobre variáveis de preferência, consulte o tópico da Ajuda, "about_Preference_Variables". + + + O valor {0} ActionPreference é reservado para uso futuro e ainda não tem suporte no momento. Ele foi substituído em sua variável {1} pelo valor padrão de {2}. Para obter mais informações sobre variáveis de preferência, consulte o tópico da Ajuda, "about_Preference_Variables". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/EtwLoggingStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/EtwLoggingStrings.pt-BR.resx new file mode 100644 index 00000000000..aad2de1af6a --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/EtwLoggingStrings.pt-BR.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Command {0} is {1}. + + + Engine state changed from {0} to {1}. + + + Fully Qualified Error ID = {0} + + + Error Message = {0} + + + Recommended Action = {0} + + + Execution Policy + + + Job Command = {0} + + + Job Id = {0} + + + Job Instance Id = {0} + + + Job Location = {0} + + + Job Name = {0} + + + Job State = {0} + + + Command Name = + + + Command Path = + + + Command Type = + + + Engine Version = + + + Host ID = + + + Host Name = + + + Host Application = + + + Host Version = + + + Pipeline ID = + + + Runspace ID = + + + Script Name = + + + Sequence Number = + + + Severity = + + + Shell ID = + + + Time = + + + User = + + + Connected User = + + + NULL Job + + + Provider name + + + Provider {0} changed state to {1}. + + + Script execution is {0}. + + + Variable {0} changed from {1} to {2}. + + + Variable {0} changed to {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/EventResource.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/EventResource.pt-BR.resx new file mode 100644 index 00000000000..47ef2e8b8e6 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/EventResource.pt-BR.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não foi encontrada uma mensagem para a ID de evento PowerShell.Core.Instrumentation.man. + + + Trabalho agendado {0} iniciado às {1} + + + + Trabalho agendado {0} concluído às {1} com o estado {2} + + + + Exceção de Trabalho Agendado {0}: + Mensagem: {1} + StackTrace: {2} + InnerException: {3} + + + + Inicialização de recurso experimental: ignore o recurso experimental '{0}' do arquivo de configuração. {1} + + + Inicialização de recurso experimental: falha ao ler o arquivo de configuração. + Exceção: {0} + Mensagem: {1} + StackTrace: {2} + + + + Plug-in de fluxo de trabalho carregado. + EndpointName: {0} + Usuário: {1} + HostingMode: {2} + Protocolo: {3} + Configuração: + {4} + + + Execução do fluxo de trabalho iniciada. + WorkflowId: {0} + ManagedNodes: {1} + + + Estado do fluxo de trabalho alterado. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + O plug-in de fluxo de trabalho foi solicitado para um desligamento. + EndpointName: {0} + + + Plug-in de fluxo de trabalho reiniciado. + EndpointName: {0} + + + O fluxo de trabalho está sendo retomado. + WorkflowId: {0} + + + Um limite de cota definido para o ponto de extremidade foi excedido. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + O fluxo de trabalho foi retomado. + WorkflowId: {0} + + + O pool de runspace de fluxo de trabalho foi criado. + WorkflowId: {0} + ManagedNode: {1} + + + A atividade foi colocada na fila para execução. + WorkflowId: {0} + ActivityName: {1} + + + Execução da atividade iniciada. + ActivityName: {0} + ActivityTypeName: {1} + + + O fluxo de trabalho está sendo importado de um arquivo XAML. + WorkflowId: {0} + XamlFile: {1} + + + O fluxo de trabalho foi importado de um arquivo XAML. + WorkflowId: {0} + XamlFile: {1} + + + Não foi possível importar o fluxo de trabalho de um arquivo XAML devido a um erro. + WorkflowId: {0} + ErrorDescription: {1} + + + Validação de fluxo de trabalho iniciada. + WorkflowId: {0} + + + Validação de fluxo de trabalho bem-sucedida. + WorkflowId: {0} + + + Falha na validação do fluxo de trabalho com erro. + WorkflowId: {0} + + + Atividade de fluxo de trabalho validada. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Não foi possível validar a atividade do fluxo de trabalho. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Falha na execução da atividade. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Disponibilidade do runspace alterada. + RunspaceId: {0} + Disponibilidade: {1} + + + Estado do runspace alterado. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Fluxo de trabalho carregado para execução. + WorkflowId: {0} + + + Fluxo de trabalho descarregado. + WorkflowId: {0} + + + Execução do fluxo de trabalho cancelada. + WorkflowId: {0} + + + Execução de fluxo de trabalho anulada. + WorkflowId: {0} + + + Operação de limpeza do fluxo de trabalho executada. + WorkflowId: {0} + + + Fluxo de trabalho persistente carregado do disco. + WorkflowId: {0} + Caminho: {1} + + + Os dados do fluxo de trabalho foram excluídos do disco. + WorkflowId: {0} + Caminho: {1} + + + Iniciando a remoção do trabalho. + JobId: {0} + + + Estado do trabalho alterado. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Erro de trabalho. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Trabalho criado para o fluxo de trabalho (trabalho filho). + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Trabalho pai criado para o fluxo de trabalho. + JobId: {0} + + + Todos os trabalhos necessários foram criados para a execução do fluxo de trabalho. + JobId: {0} + WorkflowId: {1} + + + Trabalho filho removido do fluxo de trabalho. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + Ocorreu um erro ao remover o trabalho. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Erro: {3} + + + Carregando fluxo de trabalho para execução. + WorkflowId: {0} + + + Execução do fluxo de trabalho concluída. + WorkflowId: {0} + + + Cancelando a execução do fluxo de trabalho. + WorkflowId: {0} + + + Anulando a execução do fluxo de trabalho. + WorkflowId: {0} + Motivo: {1} + + + Descarregando fluxo de trabalho. + WorkflowId: {0} + + + Desligamento forçado do fluxo de trabalho iniciado. + WorkflowId: {0} + + + Desligamento forçado do fluxo de trabalho concluído. + WorkflowId: {0} + + + Ocorreu um erro ao encerrar forçadamente um fluxo de trabalho. + WorkflowId: {0} + ErrorDescription: {1} + + + Persistindo o fluxo de trabalho no disco. + WorkflowId: {0} + PersistPath: {1} + + + Fluxo de trabalho persistido no disco. + WorkflowId: {0} + + + A execução da atividade foi concluída. + ActivityName: {0} + + + Erro de execução do fluxo de trabalho. + WorkflowId: {0} + ErrorDescription: {1} + + + Um novo ponto de extremidade do PowerShell foi registrado. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Configuração do ponto de extremidade modificada. + EndpointName: {0} + ModifiedBy: {1} + + + Configuração do ponto de extremidade não registrada. + EndpointName: {0} + UnregisteredBy: {1} + + + Configuração do ponto de extremidade desabilitada. + EndpointName: {0} + DisabledBy: {1} + + + Configuração do ponto de extremidade habilitada. + EndpointName: {0} + EnabledBy: {1} + + + Runspace fora do processo iniciado. + Comando: {0} + + + O nivelamento de parâmetro foi executado durante a execução do fluxo de trabalho. + Parâmetros: {0} + Computadores: {1} + + + Mecanismo de fluxo de trabalho iniciado. + EndpointName: {0} + + + Gerenciador de fluxos de trabalho instanciado com + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + Caminho: {3} + + + Nome do Computador $null ou . resolve para LocalHost + + + Resolvendo para o esquema padrão http + + + Nome do shell remoto resolvido para o PowerShellCore padrão + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + Criando texto do ScriptBlock ({0} de {1}): +{2} + +ID do ScriptBlock: {3} +Caminho: {4} + + + Invocação iniciada da ID de ScriptBlock: {0} +ID do runspace: {1} + + + Invocação concluída da ID de ScriptBlock: {0} +ID do runspace: {1} + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + {2} + +Contexto: +{0} + +Dados do usuário: +{1} + + + + Correlacionando IDs de atividade. + CurrentActivityId: {0} + ParentActivityId: {1} + + + Nome da Classe = {0} +Nome do Método = {1} +GUID do fluxo de trabalho = {2} +Mensagem = {3} +{4} +Nome da Atividade = {5} +GUID da Atividade = {6} +Parâmetros = {7} + + + Criando objeto Runspace + ID da Instância: {0} + + + Criando objeto RunspacePool + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Abrindo RunspacePool + + + Modificando a ID da atividade e correlacionando + + + Estado do runspace alterado para {0} + + + Tentando novamente a criação da sessão {0} para o código de erro {1} na ID da sessão {2} + + + O PowerShell iniciou um thread de escuta de IPC no processo: {0} no AppDomain: {1}. + + + O PowerShell encerrou um thread de escuta de IPC no processo: {0} no AppDomain: {1}. + + + Ocorreu um erro no thread de escuta de IPC do PowerShell no processo: {0} no AppDomain: {1}. Mensagem de Erro: {2}. + + + Conexão IPC do PowerShell no processo: {0} no AppDomain: {1} para Usuário: {2}. + + + Desconexão de IPC do PowerShell no processo: {0} no AppDomain: {1} para o usuário: {2}. + + + Porta resolvida para {0} + + + AppName resolvido para {0} + + + ComputerName resolvido para {0} + + + O esquema é {0} + + + Mensagem de teste analítica + + + Os Parâmetros da Conexão são + URI de conexão: {0} + URI do recurso: {1} + Usuário: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Impressão Digital: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Modificando a ID da atividade e correlacionando + + + Objeto recebido com a ID do Runspace: {0} ID do Comando: {1} Destino: {2} DataType: {3} TargetInterface: {4} + + + Ocorreu uma exceção sem tratamento no appdomain. +Tipo de Exceção: {0} +Mensagem de Exceção: {1} +StackTrace de Exceção: {2} + + + ID do Runspace: {0} ID do Pipeline: {1}. O WSMan relatou um erro com o código de erro: {2}. + Mensagem de erro: {3} + StackTrace: {4} + + + Ocorreu uma exceção sem tratamento no appdomain. +Tipo de Exceção: {0} +Mensagem de Exceção: {1} +StackTrace de Exceção: {2} + + + ID do Runspace: {0} ID do Pipeline: {1}. O WSMan relatou um erro com o código de erro: {2}. + Mensagem de erro: {3} + StackTrace: {4} + + + ID do runspace {0}. Estabelecendo uma conexão usando WSMan Create Shell + + + ID do runspace {0}. Retorno de chamada recebido para WSMan Create Shell + + + ID do runspace: {0}. Fechando shell usando WSManCloseShell + + + ID do runspace: {0}. Retorno de chamada recebido para WSManCloseShell + + + ID do Runspace: {0} ID do Pipeline: {1}. Enviando dados com tamanho {2} + + + ID do Runspace: {0} ID do Pipeline: {1}. Retorno de chamada recebido para WSManSendShellInputEx + + + ID do Runspace: {0} ID do Pipeline: {1}. Fazendo solicitação de recebimento usando WSManReceiveShellOutputEx + + + ID do Runspace: {0} ID do Pipeline: {1}. Dados recebidos com tamanho {2}. + + + ID do Runspace {0} ID do Pipeline {1}. Estabelecendo uma conexão de comando usando WSManRunShellCommandEx + + + ID do Runspace {0} ID do Pipeline {1}. Retorno de chamada recebido para conexão de comando + + + ID do Runspace: {0} ID do Pipeline {1}. Fechando o transporte do comando + + + ID do Runspace: {0} ID do Pipeline {1}. Retorno de chamada recebido para fechamento de comando + + + ID do Runspace: {0} ID do Pipeline {1}. Enviando sinal com código {2} usando WSManSignalShellEx + + + ID do Runspace: {0} ID do Pipeline {1}. Retorno de chamada recebido para WSManSignalShellEx + + + ID do runspace: {0}. A conexão está sendo redirecionada para a URI: {1} + + + ID do Runspace: {0} ID do Pipeline: {1}. O servidor está enviando dados de tamanho {2} para o cliente. DataType: {3} TargetInterface: {4} + + + Solicitação {0}. Criando uma sessão remota do servidor. UserName: {1} ID do Shell Personalizado: {2} + + + Contexto de relatório para a solicitação: {0} Contexto relatado: {0} + + + Relatando a conclusão da operação para a solicitação: {0} + Código de Erro: {1} + Mensagem de Erro: {2} + StackTrace: {3} + + + Contexto do Shell {0}. ID da solicitação {1}. Criando uma sessão comum para executar um comando. + + + Contexto do shell {0} Contexto do comando {1} ID da solicitação {2}. Parando o comando. + + + Contexto do shell {0} Contexto do comando {1} ID da solicitação {2}. Dados recebidos do cliente. + + + Contexto do shell {0} Contexto do comando {1} ID da solicitação {2}. O cliente enviou uma solicitação de recebimento para que o servidor possa enviar dados. + + + Contexto do Shell {0} Contexto do Comando {1} IsReceiveOperation {2}. Foi obtida uma solicitação de operação de fechamento. + + + Carregando assembly {0} para shell personalizado com ID de shell {1} + + + Carregando tipo {0} para shell personalizado com ID do shell {1} + + + Fragmento de comunicação remota recebido. + ID do objeto: {0} + ID do fragmento: {1} + Sinalizador de início: {2} + Sinalizador de encerramento: {3} + Comprimento da Carga: {4} + Dados da Carga: {5} + + + Fragmento de comunicação remota enviado. + ID do objeto: {0} + ID do fragmento: {1} + Sinalizador de início: {2} + Sinalizador de encerramento: {3} + Comprimento da Carga: {4} + Dados da Carga: {5} + + + Desligando o serviço winrm. + + + Um objeto foi reidratado com sucesso. + Nome do tipo desserializado: {0} + Reidratação por conversão para o tipo: {1} + O objeto reidratado é do tipo: {2} + + + Falha ao reidratar um objeto. + Nome do tipo desserializado: {0} + Reidratação por conversão para o tipo: {1} + Exceção de conversão de tipo: {2} + Exceção interna da conversão de tipo: {3} + + + A profundidade de serialização foi substituída. + Nome do tipo serializado: {0} + Profundidade original: {1} + Profundidade substituída: {2} + Profundidade atual abaixo do nível superior: {3} + + + O modo de serialização foi substituído. + Nome do tipo serializado: {0} + Modo substituído: {1} + + + A serialização de uma propriedade de script foi ignorada porque não há nenhum runspace para usar na avaliação da propriedade. + Nome da propriedade: {0} + Nome do tipo do proprietário da propriedade: {1} + Script getter: {2} + + + A serialização de uma propriedade foi ignorada porque o getter da propriedade falhou. + Nome da propriedade: {0} + Nome do tipo do proprietário da propriedade: {1} + Exceção do getter da propriedade: {2} + Exceção interna do getter da propriedade: {3} + + + A serialização de um objeto enumerável pode não estar concluída, pois o objeto que está sendo enumerado gerou uma exceção. + Tipo de objeto sendo enumerado: {0} + Exceção:{1} + + + A serialização chamou o método ToString do objeto, que falhou. + Tipo de objeto: {0} + Exceção:{1} + + + A profundidade máxima abaixo do nível superior foi atingida, forçando a serialização do objeto como cadeias de caracteres. + Tipo de objeto na profundidade máxima: {0} + Nome da propriedade na profundidade máxima: {1} + Profundidade: {2} + + + Uma XmlException foi gerada pelo desserializador (provavelmente indicando formato clixml incorreto). + Número da linha: {0} Posição da linha: {1} + Exceção:{2} + + + Falha na serialização das propriedades especificadas, pois uma das propriedades especificadas estava ausente. + Tipo de objeto: {0} + Nome da propriedade: {1} + + + O console do PowerShell está sendo iniciado + + + O console do PowerShell está pronto para entrada de usuário + + + {0} + + + Rastreando ErrorRecord: + Mensagem: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + Detalhes da Exceção: + Mensagem: {5} + Rastreamento de Pilha: {6} + InnerException {7} + + + + Exceção: + Mensagem: {0} + StackTrace: {1} + InnerException : {2} + + + + Rastreando PSObject + + + Trabalho de Rastreamento: + ID: {0} + InstanceId: {1} + Nome: {2} + Localização: {3} + Estado: {4} + Comando: {5} + + + + Informações de rastreamento: + {0} + + + Informações de rastreamento: + {0} {1} + + + INICIAR ImportWorkflowCommand::StartWorkflowApplication. Iniciando invocação da função de fluxo de trabalho. Guid de rastreamento {0} + + + ENCERRAR ImportWorkflowCommand::StartWorkflowApplication. Encerrando invocação da função de fluxo de trabalho. Guid de rastreamento {0} + + + INICIAR Criando novo trabalho em ImportWorkflowCommand::StartWorkflowApplication. Guid de rastreamento {0} + + + ENCERRAR Criando novo trabalho em ImportWorkflowCommand::StartWorkflowApplication. Guid de rastreamento {0} + + + ENCERRAR Criando novo trabalho em ImportWorkflowCommand::StartWorkflowApplication. Guid de Acompanhamento {0} : ContainerParentJob Guid {1} + + + INICIAR JobLogic ContainerParentJob Guid {0} + + + ENCERRAR JobLogic ContainerParentJob Guid {0} + + + INICIAR WorkflowExecution ContainerParentJob Guid {0} + + + ENCERRAR WorkflowExecution ContainerParentJob Guid {0} + + + WorkflowJob com Guid {0} adicionado a ContainerParentJob com Guid {1} + + + ProxyJob com Guid {0} associado ao ContainerParentJob remoto com Guid {1} + + + INICIAR Execução do ContainerParentJob com Guid {0} + + + ENCERRAR Execução do ContainerParentJob com Guid {0} + + + INICIAR Execução do trabalho de proxy com Guid {0} + + + ENCERRAR Execução de tarefa de proxy com Guid {0} + + + INICIAR Manipulador de eventos StateChanged para Proxy Job com Guid {0} + + + ENCERRAR Manipulador de eventos StateChanged para Proxy Job com Guid {0} + + + INICIAR Manipulador de eventos StateChanged para Proxy Child Job com Guid {0} + + + ENCERRAR Manipulador de eventos StateChanged para Proxy Child Job com Guid {0} + + + INICIAR Executando GC + + + ENCERRAR Executando GC + + + O repositório de persistência atingiu o tamanho máximo especificado + + + O Windows PowerShell ISE começou a executar o arquivo de script {0}. + + + O ISE do Windows PowerShell começou a executar um script selecionado pelo usuário do arquivo {0}. + + + O ISE do Windows PowerShell está interrompendo o comando atual. + + + O ISE do Windows PowerShell está retomando o depurador. + + + O ISE do Windows PowerShell está interrompendo o depurador. + + + O ISE do Windows PowerShell está entrando na depuração. + + + O ISE do Windows PowerShell está avançando na depuração. + + + O ISE do Windows PowerShell está saindo da depuração. + + + O ISE do Windows PowerShell está habilitando todos os pontos de interrupção. + + + O ISE do Windows PowerShell está desabilitando todos os pontos de interrupção. + + + O ISE do Windows PowerShell está removendo todos os pontos de interrupção. + + + O ISE do Windows PowerShell está definindo o ponto de interrupção na linha nº: {0} do arquivo {1}. + + + O ISE do Windows PowerShell está removendo o ponto de interrupção na linha nº: {0} do arquivo {1}. + + + O ISE do Windows PowerShell está habilitando o ponto de interrupção na linha nº: {0} do arquivo {1}. + + + O ISE do Windows PowerShell está desabilitando o ponto de interrupção na linha nº: {0} do arquivo {1}. + + + O Windows PowerShell ISE atingiu um ponto de interrupção na linha #: {0} do arquivo {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/EventingResources.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/EventingResources.pt-BR.resx new file mode 100644 index 00000000000..c3e24d06efb --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/EventingResources.pt-BR.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não é possível registrar para o evento especificado. Eventos que exigem um valor de retorno não têm suporte. + + + Não é possível registrar para o evento especificado. Um evento com o nome '{0}' não existe. + + + O PowerShell não pode assinar eventos do Windows RT. + + + Não é possível registrar para o evento especificado. O identificador de origem do evento '{0}' está reservado para o mecanismo do PowerShell. + + + Esta operação não tem suporte em instâncias remotas. + + + A ação não tem suporte quando você está encaminhando eventos. + + + Não é possível assinar o evento especificado. Já existe um assinante com o identificador de origem '{0}'. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ExperimentalFeatureStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ExperimentalFeatureStrings.pt-BR.resx new file mode 100644 index 00000000000..94c821d545b --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ExperimentalFeatureStrings.pt-BR.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + No experimental feature was found that matched the name '{0}'. + + + Enabling and disabling experimental features do not take effect until next start of PowerShell. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ExtendedTypeSystem.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ExtendedTypeSystem.pt-BR.resx new file mode 100644 index 00000000000..8e034fa151b --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ExtendedTypeSystem.pt-BR.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 member "{0}" is already present. + + + The member "{0}" is already present from the extended type data file. + + + The member "{0}" is not present. + + + Exception setting "{0}": "{1}" + + + Exception getting "{0}": "{1}" + + + The following exception occurred while trying to enumerate the collection: "{0}". + + + Cannot access member "{0}" outside of a PSObject. + + + Cannot change the member created from the type configuration: "{0}". + + + The member name "{0}" is reserved. + + + "{0}" cannot be changed. + + + Exception calling "{0}" with "{1}" argument(s): "{2}" + + + An exception was thrown when trying to call "{0}" to extract the contents of an object of type "{1}": "{2}" + + + Cannot find an overload for "{0}" and the argument count: "{1}". + + + Could not find a suitable generic method overload for "{0}" with "{1}" type parameters, and the argument count: "{2}". + + + Multiple ambiguous overloads found for "{0}" and the argument count: "{1}". + + + Cannot convert argument "{0}", with value: "{1}", for "{2}" to type "{3}": "{4}" + + + Get accessor for property "{0}" is unavailable. + + + Set accessor for property "{0}" is unavailable. + + + The setter method should be public, void, static, and have two parameters. The first parameter should be of the type PSObject. A second parameter is required if a getter method is also available, and should have the same type as the return type for the getter method. + + + The getter method should be public, not void, static, and have one parameter of the type PSObject. + + + CodeProperty should use a getter or setter method. + + + Cannot create a code method because of the method format. The method should be public, static, and have one parameter of type PSObject. + + + The alias with name "{0}" contains a cycle. + + + Cannot convert the "{0}" value of type "{1}" to type "{2}". + + + Cannot convert the value of type "{0}" to type "{1}". + + + Cannot convert value "{0}" to type "{1}". Error: "{2}" + + + Cannot convert value "{0}" to type "{1}" because no commas are allowed for this enumeration. + + + Cannot convert value "{0}" to type "{1}" due to enumeration values that are not valid. Specify one of the following enumeration values and try again. The possible enumeration values are "{2}". + + + Cannot convert null to type "{0}" due to enumeration values that are not valid. Specify one of the following enumeration values and try again. The possible enumeration values are "{1}". + + + Cannot convert null to type "{0}". + + + Cannot convert value to type "{0}". Error: "{1}" + + + Cannot convert value to type System.String. + + + Reference type is expected in argument. + + + Cannot compare "{0}" because it is not IComparable. + + + Could not compare "{0}" to "{1}". Error: "{2}" + + + Cannot compare "{0}" to "{1}" because the objects are not the same type or the object "{0}" does not implement "{2}". + + + Cannot convert value "{0}" to type "{1}" because at least two matches were found ({2}, {3}) and only one match is allowed for this enumeration. + + + Cannot convert value "{0}" to type "{1}". Boolean parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0. + + + Cannot get property value because "{0}" is a write-only property. + + + "{0}" is a ReadOnly property. + + + Cannot set "{0}" because only strings can be used as values to set XmlNode properties. + + + Cannot set "{0}" because only unique attributes or unique non-attributed leaf nodes can be set. + + + A PSProperty or PSMethod object cannot be added to this collection. + + + The following error occurred while loading the extended type data file: {0} + + + The following exception occurred while retrieving the string: "{0}" + + + The field or property: "{0}" for type: "{1}" differs only in letter casing from the field or property: "{2}". The type must be Common Language Specification (CLS) compliant. + + + The following exception occurred while retrieving the type name hierarchy: "{0}". + + + The following exception occurred while retrieving member "{1}": "{0}" + + + The following exception occurred while retrieving members: "{0}" + + + The following exception occurred while retrieving the read state for property "{1}": "{0}" + + + The following exception occurred while retrieving the write state for property "{1}": "{0}" + + + The following exception occurred while retrieving the type for property "{1}": "{0}" + + + The following exception occurred while retrieving the string representation for property "{1}" : "{0}" + + + The following exception occurred while retrieving the attributes for property "{1}": "{0}" + + + The following exception occurred while retrieving the definitions for method "{1}": "{0}" + + + The following exception occurred while retrieving the string representation for method "{1}": "{0}" + + + The following exception occurred while retrieving the type for parameterized property "{1}": "{0}" + + + The following exception occurred while retrieving the read state for parameterized property "{1}": "{0}" + + + The following exception occurred while retrieving the write state for parameterized property "{1}": "{0}" + + + The following exception occurred while retrieving the definitions for parameterized property "{1}": "{0}" + + + The following exception occurred while retrieving the string representation for parameterized property "{1}": "{0}" + + + Cannot set the Value property for PSMemberInfo object of type "{0}". + + + Argument: '{0}' should be a {1}. Use {2}. + + + Argument: '{0}' should not be a {1}. Do not use {2}. + + + Propriedade "{0}" não encontrada. + + + Cannot get or set the property value. The "{0}" argument should be of type "{1}" or "{2}". + + + Cannot set the value for property "{0}" because the object has type "{1}" instead of "{2}". + + + Exception calling "{0}" : "{1}" + + + {0} is not a valid class path. + + + {0} não é um caminho válido. + + + The adapter cannot determine whether property "{0}" can be changed. + + + The adapter cannot determine whether property "{0}" is gettable. + + + The adapter cannot get the value of property "{0}". + + + The adapter cannot set the value of property "{0}". + + + The adapter cannot get the type of property "{0}". + + + The adapter cannot get the type hierarchy of "{0}". + + + The adapter cannot get the properties of "{0}". + + + The adapter cannot get property "{0}" for "{1}". + + + "{0}" returned a null value. + + + The property '{0}' was not found for the '{1}' object. The settable properties are: {2}. + + + The property '{0}' was not found for the '{1}' object. There is no settable property available. + + + Cannot create object of type "{0}". {1} + + + Cannot invoke static methods or access static properties on the open generic type {0}. Specify the type parameters and retry. For example, instead of [System.Collections.Generic.HashSet``1]::CreateSetComparer() use [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + The following exception occurred while constructing the attribute "{1}": "{0}" + + + The value "{0}" cannot be converted to a string array. + + + Cannot convert value to type "{0}". Only core types are supported in this language mode. + + + Cannot convert to the ByRef-like type "{0}". ByRef-like types are not supported in PowerShell. + + + Cannot get or set the property or field "{0}" of the ByRef-like type "{1}". ByRef-like types are not supported in PowerShell. + + + Cannot invoke the method "{0}" of the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + Cannot create an instance of the ByRef-like type "{0}". ByRef-like types are not supported in PowerShell. + + + Extended Type System Hashtable Conversion + + + Type conversion from HashTable to '{0}' will not be allowed in ConstrainedLanguage mode. + + + Extended Type System Hashtable Conversion + + + Type conversion from '{0}' to '{1}' will not be allowed in ConstrainedLanguage mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/FileSystemProviderStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/FileSystemProviderStrings.pt-BR.resx new file mode 100644 index 00000000000..e94cb719cca --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/FileSystemProviderStrings.pt-BR.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Invocar Item + + + Item: {0} + + + Remover Arquivo + + + Remover Diretório + + + Copiar Arquivo + + + Item: {0} Destino: {1} + + + Copiar Diretório + + + Renomear Arquivo + + + Renomear Diretório + + + Item: {0} Destino: {1} + + + Mover Arquivo + + + Mover Diretório + + + Item: {0} Destino: {1} + + + Definir Propriedade do Arquivo + + + Definir Propriedade de Diretório + + + Item: {0} Propriedade: {1} Valor: {2} + + + Limpar Propriedade de Arquivo + + + Limpar Propriedade do Diretório + + + Item: {0} Propriedade: {1} + + + Criar Arquivo + + + Criar Diretório + + + Destino: {0} + + + Limpar Conteúdo + + + Item: {0} + + + Não foi possível localizar o item {0}. + + + Não é possível remover o item {0}: {1} + + + Não é possível restaurar os atributos do item {0}: {1} + + + Não existe um objeto no caminho especificado {0}. + + + O diretório {0} não pode ser removido porque não está vazio. + + + O tipo não é conhecido pelo sistema de arquivos. Somente "file", "directory" ou "symboliclink" podem ser especificados. + + + Não é possível processar o caminho porque o caminho especificado se refere a um item que está fora do basePath. + + + A raiz da unidade especificada "{0}" não existe ou não é uma pasta. + + + Já existe um item com o nome especificado {0}. + + + Não é possível especificar um delimitador ao ler o fluxo um byte por vez. + + + Não é possível substituir o item {0} por ele mesmo. + + + Não é possível renomear o destino especificado porque ele representa um caminho ou nome de dispositivo. + + + A propriedade {0} não existe ou não foi encontrada. + + + Você não tem direitos de acesso suficientes para executar essa operação ou o item está oculto, é do sistema ou é somente leitura. + + + O atributo não pode ser definido porque os atributos não têm suporte. Somente os seguintes atributos podem ser definidos: Archive, Hidden, Normal, ReadOnly ou System. + + + A propriedade não pode ser limpa porque não tem suporte. Somente a propriedade Atributos pode ser limpa. + + + Não é possível processar o caminho '{0}' porque o destino representa um nome de dispositivo reservado. + + + A codificação não é usada quando '-AsByteStream' é especificado. + + + Não é possível continuar com a codificação de byte. Ao usar a codificação de byte, o conteúdo deve ser do tipo byte. + + + Não é possível processar o arquivo porque o arquivo {0} não foi encontrado. + + + Diretório: + + + Não é possível detectar a codificação do arquivo. A codificação especificada {0} não tem suporte quando o conteúdo é lido de trás para frente. + + + Não foi possível abrir o fluxo de dados alternativo '{0}' do arquivo '{1}'. + + + Fluxo '{0}' do arquivo '{1}'. + + + Os parâmetros Raw e Wait não podem ser especificados no mesmo comando. + + + Para usar o parâmetro de opção Persist, o nome da unidade deve ter suporte no sistema operacional (por exemplo, letras de unidade A-Z). + + + Quando você usa o parâmetro Persist, a raiz deve ser uma localização do sistema de arquivos em um computador remoto. + + + Os parâmetros '{0}' e '{1}' não podem ser especificados no mesmo comando. + + + É necessário um diretório para a operação. O item '{0}' não é um diretório. + + + Criar Junção + + + Criar Link Simbólico + + + É necessário privilégio de administrador para essa operação. + + + Criar Link Físico + + + É necessário um arquivo para a operação. O item '{0}' não é um arquivo. + + + Links físicos não têm suporte para o caminho especificado. + + + Links simbólicos não têm suporte para o caminho especificado. + + + Copiando {0} para {1} + + + O caminho de destino {0} corresponde a um arquivo que já existe no destino. + + + Falha ao copiar o arquivo {0} para o destino remoto. + + + De {0} para {1} + + + Não é possível copiar o diretório '{0}' para o arquivo '{0}' + + + Falha ao obter os itens filho do diretório {0}. + + + Falha ao ler o arquivo remoto '{0}'. + + + Não é possível validar se o destino remoto {0} é um arquivo. + + + Falha ao criar o diretório '{0}' no destino remoto. + + + O tamanho máximo da unidade foi excedido: {0}. + + + Não é possível criar o link porque o caminho já existe: {0}. + + + Ignorar o diretório {0}, que já foi visitado. + + + O caminho de destino não pode ser um subdiretório da origem nem a própria origem: {0}. + + + O destino e o caminho não podem ser iguais. + + + Copiados {0} de {1} arquivos + + + {0} de {1} ({2:0.0} MB/s) + + + Removidos {0} de {1} arquivos + + + {0} de {1} ({2:0.0} MB/s) + + + A criação de uma junção requer um caminho absoluto para o destino. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/FormatAndOutXmlLoadingStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/FormatAndOutXmlLoadingStrings.pt-BR.resx new file mode 100644 index 00000000000..aeb0f5e6e56 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/FormatAndOutXmlLoadingStrings.pt-BR.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Erro no XPath {0} no arquivo {1}: o elemento XML {2} não permite atributos. + + + Erro no XPath {0} no arquivo {1}: o nó {2} não pode ter objetos filho. + + + Erro no XPath {0} no arquivo {1}: {2} é inválido. + + + Erro no XPath {0} no arquivo {1}: deve haver pelo menos um {2} padrão. + + + Erro no XPath {0} no arquivo {1}: não pode haver mais de um {2} padrão. + + + Erro no XPath {0} no arquivo {1}: o nome do controle não pode ser nulo nem vazio. + + + Erro no XPath {0} no arquivo {1}: modos de exibição fora da banda só podem usar CustomControl ou ListControl. + + + Erro no XPath {0} no arquivo {1}: um modo de exibição fora da banda não pode ter GroupBy. + + + Erro no XPath {0} no arquivo {1}: não é possível carregar o modo de exibição. + + + Erro no XPath {0} no arquivo {1}: "{2}" não é um valor de alinhamento válido. + + + Erro no XPath {0} no arquivo {1}: é esperado um inteiro positivo. + + + Erro no XPath {0} no arquivo {1}: a definição de cabeçalho da coluna não é válida; todos os cabeçalhos serão descartados. + + + Erro no XPath {0} no arquivo {1}: a contagem de itens da linha = {2} no conjunto alternativo #{3} não corresponde à contagem de itens da linha padrão = {4}. + + + Erro no XPath {0} no arquivo {1}: a contagem de itens do cabeçalho = {2} não corresponde à contagem de itens da linha padrão = {3}. + + + Erro no XPath {0} no arquivo {1}: é preciso especificar pelo menos um item da exibição de lista. + + + Erro no XPath {0} no arquivo {1}: a entrada de propriedade não é válida. + + + Erro no XPath {0} no arquivo {1}: a lista de definições está ausente. + + + Erro no XPath {0} no arquivo {1}: é esperado um valor booleano. + + + Erro no XPath {0} no arquivo {1}: é esperado um inteiro não negativo. + + + Erro no XPath {0} no arquivo {1}: é esperado um inteiro. + + + Erro no XPath {0} no arquivo {1}: o valor do texto interno está ausente. + + + Erro no XPath {0} no arquivo {1}: a lista de tokens de controle personalizado não pode estar vazia. + + + Erro no XPath {0} no arquivo {1}: {2} falha ao carregar. + + + Erro no XPath {0} no arquivo {1}: {2} não pode ser especificado sem uma expressão. + + + Erro no XPath {0} no arquivo {1}: {2} não pode ser especificado com uma expressão. + + + Erro no XPath {0} no arquivo {1}: uma cadeia de caracteres de formato está ausente. + + + Erro no XPath {0} no arquivo {1}: o texto do bloco de script está ausente. + + + Erro no XPath {0} no arquivo {1}: uma propriedade está ausente. + + + Erro no XPath {0} no arquivo {1}: o bloco de script "{2}" é inválido. + + + Erro no XPath {0} no arquivo {1}: a cadeia de caracteres {2} do recurso {3} no assembly {4} não foi encontrada. + + + Erro no XPath {0} no arquivo {1}: o recurso {2} no assembly {3} não foi encontrado. + + + Erro no XPath {0} no arquivo {1}: o assembly {2} não foi encontrado. + + + Erro no XPath {0} no arquivo {1}: o nó deve ser um XmlElement. + + + Erro no XPath {0} no arquivo {1}: é esperada uma expressão. + + + Erro no XPath {0} no arquivo {1}: não é possível ter control ou Label sem uma expressão. + + + Erro no XPath {0} no arquivo {1}: não é possível ter control e Label ao mesmo tempo. + + + Erro no XPath {0} no arquivo {1}: não é possível usar SelectionSetName e TypeName ao mesmo tempo. + + + Erro no XPath {0} no arquivo {1}: nenhum tipo ou condição foi especificado para aplicar o modo de exibição. + + + Erro no XPath {0} no arquivo {1}: o valor {2} é inválido. + + + Erro no XPath {0} no arquivo {1}: existe um nó duplicado. + + + Erro no XPath {0} no arquivo {1}: {2} e {3} são mutuamente exclusivos. + + + Erro no XPath {0} no arquivo {1}: {2}, {3} e {4} são mutuamente exclusivos. + + + Erro no XPath {0} no arquivo {1}: {2} é um nó desconhecido. + + + Erro no XPath {0} no arquivo {1}: {2} é um atributo desconhecido. + + + Erro no XPath {0} no arquivo {1}: {2} é um atributo ausente. + + + Erro no XPath {0} no arquivo {1}: o nó {2} está ausente. + + + Erro no XPath {0} no arquivo {1}: um nó está ausente de {2}. + + + Erro no XPath {0} no arquivo {1}: {2} é um nó vazio. + + + Erro no XPath {0} no arquivo {1}: {2} é um atributo vazio. + + + Erro no arquivo {0}: {1} + + + Há muitos erros no arquivo {0}. + + + Ocorreram erros ao carregar o arquivo de dados de formato: {0} + + + (Cache de Assembly Global) {0} + + + {0}, {1} + + + O caminho {0} não é totalmente qualificado. Especifique um caminho de arquivo de formato totalmente qualificado. + + + Não é possível atualizar a FormatTable porque ela pode ter sido criada fora do runspace. + + + Ocorreram erros ao carregar a FormatTable. Veja o conteúdo da propriedade Errors para acessar mensagens de erro detalhadas. + + + Erro nos dados de formatação "{0}": {1} + + + Erro nos dados de exibição com o nome de tipo {0} no índice {1}: a contagem de itens do cabeçalho = {2} não corresponde à contagem de itens da linha padrão = {3}. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: dados de formatação "{2}" não são válidos. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: o bloco de script "{2}" não é válido. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: {2} falha ao carregar. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: um TableControl deve conter apenas um {2}. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: deve haver pelo menos um padrão {2}. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: você deve especificar pelo menos um item de exibição de lista. + + + Erro nos dados de exibição com nome de tipo {0} no índice {1}: não pode haver mais de um {2} padrão. + + + Há muitos erros nos dados de formatação para o tipo "{0}". + + + Uma tabela de formato compartilhada não pode ser atualizada com mais de uma entrada. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/FormatAndOut_MshParameter.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/FormatAndOut_MshParameter.pt-BR.resx new file mode 100644 index 00000000000..e5bdf07e411 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/FormatAndOut_MshParameter.pt-BR.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 + + + Não é possível converter {0} em um dos seguintes tipos {1}. + + + O valor de um parâmetro era nulo; esperava-se um dos seguintes tipos: {0}. + + + A chave duplicada "{0}" está em conflito com "{1}". + + + A chave "{0}" tem um tipo, {1}, que não é válido; os tipos esperados são {2}. + + + A chave "{0}" tem um tipo, {1}, que não é válido; o tipo esperado é {2}. + + + A chave {0} é ambígua; há conflito entre {1} e {2}. + + + O valor de uma chave não pode ser nulo. + + + O tipo da chave {0} não é válido. A chave deve ser uma cadeia de caracteres. + + + A chave {0} não tem valor. + + + Falta uma entrada obrigatória para {0}. + + + A chave {0} não é válida. + + + O valor "{0}" da chave "{1}" não é válido; os valores válidos são {2}. + + + O valor "{0}" da chave "{1}" deve ser maior que 0. + + + Não é possível ter uma cadeia de caracteres de formatação vazia para a chave "{0}". + + + A chave "{0}" não pode ter um valor de cadeia de caracteres vazio. + + + Um valor de cadeia de caracteres vazio não é permitido. + + + A chave "{0}" não pode ter caracteres curinga no valor "{1}". + + + Caracteres curinga não são permitidos em "{0}". + + + O valor de EnumerableExpansion não é válido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/FormatAndOut_format_xxx.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/FormatAndOut_format_xxx.pt-BR.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/FormatAndOut_format_xxx.pt-BR.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/FormatAndOut_out_xxx.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/FormatAndOut_out_xxx.pt-BR.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/FormatAndOut_out_xxx.pt-BR.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/GetErrorText.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/GetErrorText.pt-BR.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/GetErrorText.pt-BR.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/HelpDisplayStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/HelpDisplayStrings.pt-BR.resx new file mode 100644 index 00000000000..b268bd11258 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/HelpDisplayStrings.pt-BR.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + NOME + + + SYNOPSIS + + + DESCRIPTION + + + SYNTAX + + + PARAMETERS + + + INPUTS + + + OUTPUTS + + + TERMINATING ERRORS + + + NON-TERMINATING ERRORS + + + NOTES + + + EXAMPLES + + + Exemplo + + + EXAMPLE + + + OUTPUT + + + RELATED LINKS + + + SHORT DESCRIPTION + + + Title: + + + Question: + + + Resposta + + + Term: + + + Definition: + + + Content: + + + PROVIDER NAME + + + This cmdlet supports the common parameters: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. For more information, see + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Required? + + + Position? + + + Type: + + + Target Object Type: + + + Default value + + + Accept pipeline input? + + + Accept wildcard characters? + + + (Category: + + + Suggested Action: + + + For more information, type: + + + For technical information, type: + + + To see the examples, type: + + + For online help, type: + + + <CommonParameters> + + + REMARKS + + + true + + + Named + + + DRIVES + + + CAPABILITIES + + + TASKS + + + TASK: + + + FILTERS + + + DYNAMIC PARAMETERS + + + Cmdlets Supported: + + + ALIASES + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + -- To view the Help topic for this cmdlet online, type: "Get-Help {0} -Online" or + go to {1}. + + + Nenhum + + + Aliases + + + Dynamic? + + + Parameter set name + + + Unable to retrieve the HelpInfo XML file for UI culture {0}. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + + + The ModuleBase directory cannot be found. Verify the directory and try again. + + + The path {0} is not a valid directory. Make sure the directory exists and retry. + + + A Help URI cannot contain more than 10 redirections. Specify a valid Help URI. + + + Updating Help + + + Connecting to Help Content... + + + Downloading Help Content... + + + Installing Help content... + + + Locating Help Content... + + + (All) + + + No PowerShell modules were found that match the following pattern: {0}. Verify the pattern and then try the command again. + + + No PowerShell modules were found that match the specified FullyQualifiedModule {0}. Verify the FullyQualifiedModule value and then try the command again. + + + Help content cannot be found. Make sure the server is available and the help content location is properly defined in the HelpInfo XML. + + + The Update-Help command failed because the specified module does not support updatable help. Use Get-Help -Online or look online for help for the commands in this module. + + + The following parameter must not be null or empty: Module. + + + The following parameter must not be null or empty: Path. + + + Update-Help has completed successfully. + + + Error extracting Help content. + + + Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. + + + The Help content at the specified location is not valid. Specify a location that contains valid Help Content. + + + The HelpInfo XML is not valid. Specify valid HelpInfo XML. + + + Help content was successfully saved to the following location: {0} + + + The Help content XSD file cannot be found in {0}. Verify that the XSD file exists at the specified location, and then retry the command. + + + Failed to update Help for the module(s) : +'{0}' +{1} + + + Saving Help + + + Help content contains files that are not valid. Only .txt and .xml files are supported. + + + Failed to save Help for the module(s) '{0}' : {1} + + + Failed to save Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be saved using: Save-Help -UICulture en-US. + + + Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + + + false + + + The -Recurse parameter is only available if a source path is specified. + + + The path {0} does not contain a FileSystem provider. Verify that the specified path contains the FileSystem provider, and then retry the command. + + + Searching Help for {0} ... + + + No UI culture was found that matches the following pattern: {0}. Verify the pattern and then try the command again. + + + Help was not saved for the module {0}, because the Save-Help command was run on this computer within the last 24 hours. +To save help again, add the Force parameter to your command. + + + Help was not updated for the module {0}, because the Update-Help command was run on this computer within the last 24 hours. +To update help again, add the Force parameter to your command. + + + The most current Help files are already installed. + + + {0}: {1}. Culture {2} Version {3} + + + Updated {0} + + + The value of the HelpInfoUri key in the module manifest must resolve to a container or root URL on a website where the help files are stored. The HelpInfoUri '{0}' does not resolve to a container. + + + Help content must be in the namespace {0}. + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + + + The most current Help files are already downloaded. + + + Saved {0} + + + The HelpInfoURI {0} does not start with HTTP. + + + The root level element of the help content must be "helpItems". + + + Saving Help for module {0} + + + Updating Help for module {0} + + + Resolving URI: "{0}" + + + Help URI: {0} + + + {0}, Current Version: {1}, Available Version: {2}, UICulture: {3} + + + PROPERTIES + + + METHODS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/HelpErrors.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/HelpErrors.pt-BR.resx new file mode 100644 index 00000000000..8590315b1b5 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/HelpErrors.pt-BR.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help não pôde localizar {0} em um arquivo de ajuda nesta sessão. Para baixar tópicos de ajuda atualizados, digite: "Update-Help". Para obter ajuda online, pesquise o tópico de ajuda na biblioteca do TechNet em https://go.microsoft.com/fwlink/?LinkID=107116. + + + Não é possível processar a categoria Ajuda porque "{0}" não é uma categoria de Ajuda válida. + + + Não é possível carregar o arquivo de Ajuda "{0}". Detalhes: {1}. + + + Não é possível acessar o arquivo de Ajuda "{0}" porque o usuário atual não tem permissão para acessar o arquivo. Detalhes: {1}. + + + O arquivo de Ajuda "{0}" não é um documento xml válido. Detalhes: {1}. + + + Erro ao carregar o conteúdo da Ajuda para {0} do arquivo {1}. Detalhes: {2}. Para baixar tópicos da Ajuda atualizados, execute o cmdlet Update-Help. Para obter ajuda online, pesquise o tópico da Ajuda na biblioteca do TechNet em https://go.microsoft.com/fwlink/?LinkID=107116. + + + O provedor "{0}" não pode ser carregado. Detalhes: {1}. + + + Não é possível carregar o arquivo de Ajuda. Os erros {1} a seguir ocorreram ao carregar o arquivo de Ajuda "{0}". + + + O nó "{0}" não pode ter "{1}" como um nó filho. Caminho do Nó: {2}. + + + O nó "{0}" pode ter um máximo de {2} nós filho do tipo "{1}". Caminho do Nó:{3}. + + + Não é possível localizar a chave do Registro: "{0}{1}"; usando "{2}" para carregar arquivos de Ajuda. + + + Nenhum parâmetro corresponde aos critérios {0}. + + + {0} não é compatível com a categoria de Ajuda solicitada. + + + A versão online deste tópico da Ajuda não pode ser exibida porque o endereço da Internet (URI) do tópico da Ajuda não está especificado no código do comando nem no arquivo de ajuda do comando. + + + O URI especificado {0} não é válido. + + + Falha ao iniciar um navegador para exibir a Ajuda online. Nenhum programa ou navegador está associado para abrir o URI {0}. + + + Não há suporte para o protocolo especificado no URI "{0}". Somente os protocolos "{1}" e "{2}" têm suporte. + + + Vários tópicos da Ajuda foram encontrados. Use apenas um tópico da Ajuda com a opção -{0}. + + + Não é possível obter ajuda de um runspace remoto porque o runspace não foi aberto. Abra o runspace executando um comando de comunicação remota implícita e tente executar o comando para obter Ajuda novamente. + + + Acesso negado. O comando não pôde atualizar os tópicos da Ajuda para os módulos principais do PowerShell ou para quaisquer módulos no diretório $pshome\Modules. +Para atualizar esses tópicos da Ajuda, inicie o PowerShell usando o comando "Executar como Administrador" e tente executar Update-Help novamente. + + + Para usar o {0}, verifique se o aplicativo usa 'Microsoft.NET.Sdk.WindowsDesktop' como o SDK do projeto e se o assembly 'Microsoft.PowerShell.GraphicalHost' correspondente está disponível. ({1}) + + + {0} não funciona em uma sessão remota. + + + ForwardHelpTargetName não pode fazer referência à própria função. + + + Não é possível obter ajuda de um local de rede em uma sessão restrita. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/HistoryStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/HistoryStrings.pt-BR.resx new file mode 100644 index 00000000000..7dffccf7a49 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/HistoryStrings.pt-BR.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 identifier {0} is not a valid value for a History identifier. Specify a positive number, and then try again. + + + Cannot locate the history for Id {0}. + + + The count cannot be combined with multiple Ids. + + + Cannot locate the history for command line {0}. + + + Cannot locate most recent history. + + + The Invoke-History cmdlet is called repeatedly, in a loop. + + + Cannot process multiple history commands. You can only run a single command by using Invoke-History. + + + Cannot add history because the input object has a format that is not valid. + + + The identifier {0} is not valid. Specify a positive number, and then try again. + + + This command will clear all the entries from the session history. + + + The count cannot be combined with multiple CommandLine parameters. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/HostInterfaceExceptionsStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/HostInterfaceExceptionsStrings.pt-BR.resx new file mode 100644 index 00000000000..d2005490ba2 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/HostInterfaceExceptionsStrings.pt-BR.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 + + + Ocorreu um erro do tipo "{0}". + + + Um comando que solicita interação do usuário falhou porque o programa host ou o tipo de comando não dá suporte à interação do usuário. Experimente um programa host que dê suporte à interação do usuário, como o Console do PowerShell, e remova comandos relacionados a prompts de tipos de comando que não dão suporte à interação do usuário. + + + Um comando que solicita interação do usuário falhou porque o programa host ou o tipo de comando não dá suporte à interação do usuário. O host estava tentando solicitar confirmação com a seguinte mensagem: {0} + + + Não é possível invocar o método porque o pool foi fechado ou falhou. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/InternalCommandStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/InternalCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..377a1f19d70 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/InternalCommandStrings.pt-BR.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched methods. Possible matches include:{1}. + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched members. Possible matches include:{1}. + + + Retrieve the value for key '{0}' + + + Invoke method '{0}' with arguments: {1} + + + Invoke method '{0}' + + + Retrieve the value for property '{0}' + + + InputObject: {0} + + + Cannot operate on a 'null' input object. + + + Input name "{0}" cannot be resolved to a method. + + + Cannot invoke a method in the restricted language mode. + + + The -WhatIf and -Confirm parameters are not supported for script blocks. + + + The '{0}' operation is not allowed in the RestrictedLanguage mode. + + + An operator is required to compare the two specified values. Include a valid operator in the command, and then try the command again. For example, Get-Process | Where-Object -Property Name -eq Idle + + + The input name "{0}" cannot be resolved to a property. + + + The input name "{0}" cannot be resolved to a member. + + + The specified operator requires both the -Property and -Value parameters. Provide values for both parameters, and then try the command again. + + + This method cannot be run on the current thread. It can only be called on the cmdlet thread. + + + A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + A ForEach-Object -Parallel piped input object cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + The 'TimeoutSeconds' parameter cannot be used with the 'AsJob' parameter. + + + The following common parameters are not currently supported in the Parallel parameter set: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/InternalHostStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/InternalHostStrings.pt-BR.resx new file mode 100644 index 00000000000..ef50c6411cd --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/InternalHostStrings.pt-BR.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 + + + EnterNestedPrompt não foi chamado tantas vezes quanto ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/InternalHostUserInterfaceStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/InternalHostUserInterfaceStrings.pt-BR.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/InternalHostUserInterfaceStrings.pt-BR.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/Logging.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/Logging.pt-BR.resx new file mode 100644 index 00000000000..384324abe77 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/Logging.pt-BR.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + DESCONHECIDO + + + O recurso experimental do mecanismo '{0}' declarado no arquivo de configuração não está registrado no PowerShell atual. + + + O recurso experimental '{0}' declarado no arquivo de configuração é inválido. +O nome de um recurso experimental deve seguir a convenção abaixo: + Nome do Recurso do Mecanismo: 'PS[FeatureName]' + Nome do Recurso do Módulo: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/Metadata.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/Metadata.pt-BR.resx new file mode 100644 index 00000000000..f3dbca846db --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/Metadata.pt-BR.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 initialize attributes for "{0}": "{1}" + + + The argument cannot be validated because its type "{0}" is not the same type ({1}) as the maximum and minimum limits of the parameter. Make sure the argument is of type {1} and then try the command again. + + + The argument "{0}" cannot be validated because its value is not greater than zero. + + + The argument "{0}" cannot be validated because its value is not greater than or equal to zero. + + + The argument "{0}" cannot be validated because its value is not less than zero. + + + The argument "{0}" cannot be validated because its value is not less than or equal to zero. + + + The specified minimum range ({0}) cannot be accepted because it is not the same type as the specified maximum range ({1}). Update the ValidateRange attribute for the parameter. + + + Cannot accept the MaxRange and MinRange parameter types. Both parameters must be objects that implement an IComparable interface. + + + The specified maximum range cannot be accepted because it is less than the specified minimum range. Update the ValidateRange attribute for the parameter. + + + The {0} argument is greater than the maximum allowed range of {1}. Supply an argument that is less than or equal to {1} and then try the command again. + + + The {0} argument is less than the minimum allowed range of {1}. Supply an argument that is greater than or equal to {1} and then try the command again. + + + The argument "{0}" does not match the "{1}" pattern. Supply an argument that matches "{1}" and try the command again. + + + The ValidateCount attribute cannot be applied to a non-array parameter. Either remove the attribute from the parameter or make the parameter an array parameter. + + + The parameter requires exactly {0} value(s) - {1} value(s) were provided. + + + The parameter requires at least {0} value(s) and no more than {1} value(s) - {2} value(s) were provided. + + + The specified maximum number of arguments for a parameter is fewer than the specified minimum number of arguments. Update the ValidateCount attribute for the parameter. + + + The specified maximum character length of the argument is shorter than the specified minimum argument character length. Update the ValidateLength attribute for the parameter. + + + The ValidateLength attribute cannot be applied to a parameter that is not a string or string[] parameter. Make the parameter a string or string[] parameter. + + + The character length ({1}) of the argument is too short. Specify an argument with a length that is greater than or equal to "{0}", and then try the command again. + + + The character length ({1}) of the argument is too long. Specify an argument with a length that is shorter than or equal to "{0}", and then try the command again. + + + The argument "{0}" does not belong to the set "{1}" specified by the ValidateSet attribute. Supply an argument that is in the set and then try the command again. + + + Valid values generator return a null value. + + + "{0}" failed on property "{1}" {2} + + + Cannot get or run the command. The maximum number of parameter sets for this command has been exceeded. + + + Cannot process the argument because the argument value is not a string. The values of parameter arguments that have the ArgumentTransformationAttribute specified should be strings. + + + The variable cannot be validated because the value {1} is not a valid value for the {0} variable. + + + The attribute cannot be added because variable {0} with value {1} would no longer be valid. + + + The argument is null. Provide a valid value for the argument, and then try running the command again. + + + The argument has a null value, or an element of the argument collection contains a null value. Provide a collection that does not contain any null values, and then try the command again. + + + The argument is null or empty. Provide an argument that is not null or empty, and then try the command again. + + + The argument is null, empty, or an element of the argument collection contains a null value. Supply a collection that does not contain any null values and then try the command again. + + + The argument is null, empty, or consists of only white-space characters. Provide an argument that contains non white-space characters, and then try the command again. + + + An element of the argument collection is null, empty, or consists of only white-space characters. Supply a collection that does not contain any those values and then try the command again. + + + A parameter with the name '{0}' was defined multiple times for the command. + + + The parameter alias cannot be specified because an alias with the name '{0}' was already defined multiple times for the command. + + + The parameter '{0}' cannot be specified because it conflicts with the parameter alias of the same name for parameter '{1}'. + + + The "{1}" validation script for the argument with value "{0}" did not return a result of True. Determine why the validation script failed, and then try the command again. + + + The "{0}" argument does not contain a valid PowerShell version. Supply a valid version number and then try the command again. + + + Cannot validate argument '{0}' because it is not a valid variable name. + + + The job conversion type must derive from IAstToScriptBlockConverter. + + + The path argument is invalid. Supply a path argument that is a string type. + + + The path argument drive {0} does not belong to the set of approved drives: {1}. Supply a path argument with an approved drive. + + + The path argument contains invalid characters. + + + The path argument has no root drive. Supply a full path argument with a root drive. + + + The argument value for the parameter '{0}' cannot be null or an empty string. + + + The Enum member '{0}' is not a valid value for the parameter '{1}'. Specify one of the following members and try again: {2}. + + + Cannot process input. The argument "{0}" is not trusted. + + + ValidateTrustedData Attribute Check Failure + + + The parameter argument '{0}' is not trusted and will fail the ValidateTrustedData parameter attribute check in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/MiniShellErrors.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/MiniShellErrors.pt-BR.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/MiniShellErrors.pt-BR.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/Modules.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/Modules.pt-BR.resx new file mode 100644 index 00000000000..8d63fbe6d74 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/Modules.pt-BR.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + O módulo especificado "{0}" não foi carregado porque nenhum arquivo de módulo válido foi encontrado em nenhum diretório de módulo. + + + O módulo especificado "{0}" com a versão "{1}" não foi carregado porque nenhum arquivo de módulo válido foi encontrado em nenhum diretório de módulo. + + + A MaximumVersion especificada "{0}" estava incorreta. Se você estiver usando "*", MaximumVersion dá suporte apenas a um "*" e sempre deve ser colocado no final de MaximumVersion. + + + O módulo especificado "{0}" com MaximumVersion "{1}" não foi carregado porque nenhum arquivo de módulo válido foi encontrado em nenhum diretório de módulo. + + + O módulo especificado "{0}" com MinimumVersion "{1}" e MaximumVersion "{2}" não foi carregado porque nenhum arquivo de módulo válido foi encontrado em nenhum diretório de módulo. + + + MinimumVersion "{0}" não deve ser maior que MaximumVersion "{1}". + + + O assembly "{0}" não foi carregado porque nenhum assembly com esse nome foi encontrado. Verifique o nome do assembly e tente novamente. + + + O módulo a ser processado "{0}", listado no campo "{1}" do manifesto do módulo "{2}" não foi processado porque nenhum módulo válido foi encontrado em nenhum diretório de módulo. + + + Nenhum objeto personalizado foi retornado para o módulo "{0}" porque o parâmetro -AsCustomObject só pode ser usado com módulos de script. + + + Não foi possível processar o manifesto do módulo "{0}" porque ele não é um arquivo de manifesto de módulo do PowerShell válido. Remova os elementos que não são permitidos: {1} + + + O processamento do arquivo de manifesto do módulo "{0}" não resultou em um objeto de manifesto válido. Atualize o arquivo para conter um manifesto de módulo válido do PowerShell. Um manifesto válido pode ser criado usando o cmdlet New-ModuleManifest. + + + O módulo "{0}" não pode ser importado porque seu manifesto contém um ou mais membros que não são válidos. Os membros de manifesto válidos são ({1}). Remova os membros que não são válidos ({2}) e tente importar o módulo novamente. + + + A tabela de hash que descreve um módulo contém um ou mais membros que não são válidos. Os membros válidos são ({0}). Remova os membros que não são válidos ({1}) e tente novamente. + + + Não é possível carregar o módulo "{0}" porque o limite de aninhamento do módulo foi excedido. Os módulos só podem ser aninhados em {1} níveis. Avalie e altere a ordem na qual você está carregando módulos para evitar exceder o limite de aninhamento e tente executar o script novamente. + + + O membro "ModuleVersion" não está presente no manifesto do módulo. Esse membro deve existir e receber um número de versão do formulário "n.n.n.n". Adicione o membro ausente ao arquivo "{0}". + + + O membro "{0}" não é válido no arquivo de manifesto do módulo "{2}": {1} + + + A versão "{0}" do módulo "{1}" não atende à versão mínima necessária "{2}". Verifique se há suporte para o número de versão e tente carregar o módulo novamente. + + + A versão do PowerShell neste computador é "{0}". O módulo "{1}" requer uma versão mínima do PowerShell "{2}" para ser executado. Verifique se você tem a versão mínima necessária do PowerShell instalada e tente novamente. + + + O membro do manifesto do módulo "NestedModules" não poderá ser usado se o membro "ModuleToProcess" for um módulo binário. Edite o arquivo de manifesto do módulo em "{0}" e tente novamente. + + + O membro "{0}" no manifesto do módulo não é válido: {1}. Verifique se um valor válido foi especificado para este campo no arquivo "{2}". + + + O caminho do manifesto do módulo "{0}" não é válido. O valor do argumento Path deve ser resolvido para um único arquivo que tenha uma extensão ".psd1". Altere o valor do argumento Path para apontar para um arquivo psd1 válido e tente novamente. + + + A chave ModuleVersion no manifesto do módulo "{0}" especifica a versão do módulo "{1}", que não corresponde ao nome da pasta de versão em "{2}". Altere o valor da chave ModuleVersion para corresponder ao nome da pasta de versão. + + + A entrada NestedModule especificada "{0}" no manifesto do módulo "{1}" é inválida. Tente novamente depois de atualizar esta entrada com valores válidos. + + + A entrada RequiredAssemblies especificada "{0}" no manifesto do módulo "{1}" é inválida. Tente novamente depois de atualizar esta entrada com valores válidos. + + + A entrada FileList especificada "{0}" no manifesto do módulo "{1}" é inválida. Tente novamente depois de atualizar esta entrada com valores válidos. + + + A entrada RequiredModules especificada "{0}" no manifesto do módulo "{1}" é inválida. Tente novamente depois de atualizar esta entrada com valores válidos. + + + A entrada ModuleList especificada "{0}" no manifesto do módulo "{1}" é inválida. Tente novamente depois de atualizar esta entrada com valores válidos. + + + O manifesto do módulo "{0}" é especificado com a chave CompatiblePSEditions com suporte apenas na versão do PowerShell "5.1" ou superior. Atualize o valor da chave PowerShellVersion para "5.1" ou superior e tente novamente. + + + O valor especificado "{0}" para CompatiblePSEditions contém nomes duplicados do PowerShell Edition. Tente novamente depois de remover os nomes duplicados da Edição do PowerShell. + + + A versão especificada na chave ModuleVersion é igual ao nome da pasta de versão. + + + Ignorando a pasta Versão {0} em Módulo {1}, pois ela não tem um arquivo de manifesto de módulo válido. + + + O membro "ModuleName" não existe na tabela de hash que descreve este módulo. + + + Os membros "ModuleVersion", "MaximumVersion" e "RequiredVersion" não existem na tabela de hash que descreve este módulo. Um desses três membros deve existir e receber um número de versão no formato "n.n.n.n". + + + O módulo necessário "{1}" não está carregado. Carregue o módulo ou remova-o de "RequiredModules" no arquivo "{0}". + + + O módulo necessário "{1}" com GUID "{2}" não foi carregado. Carregue o módulo ou remova-o de "RequiredModules" no arquivo "{0}". + + + O módulo necessário "{1}" com a versão "{2}" não está carregado. Carregue o módulo ou remova-o de "RequiredModules" no arquivo "{0}". + + + O módulo necessário "{1}" com MaximumVersion "{2}" não foi carregado. Carregue o módulo ou remova-o de "RequiredModules" no arquivo "{0}". + + + O módulo necessário "{1}" com MinimumVersion "{2}" e MaximumVersion "{3}" não está carregado. Carregue o módulo ou remova-o de "RequiredModules" no arquivo "{0}". + + + O módulo "{0}" não pode ser encontrado com ModuleVersion "{1}". + + + O módulo "{0}" não pode ser encontrado com RequiredVersion "{1}". + + + O módulo "{0}" não pode ser encontrado com MaximumVersion "{1}". + + + O módulo "{0}" não pode ser encontrado com ModuleVersion "{1}" e MaximumVersion "{2}". + + + O módulo "{0}" não pode ser encontrado. + + + Nenhum módulo foi removido. Verifique se a especificação dos módulos a serem removidos está correta e se esses módulos existem no runspace. + + + O membro "{0}" que foi importado do módulo "{1}", não pode ser removido pelo seguinte motivo: {2} + + + Não é possível remover o módulo "{0}" porque ele é somente leitura. Adicione o parâmetro Force ao comando para remover módulos somente leitura. + + + Não é possível remover o módulo "{0}" porque ele está marcado como "constante". Um módulo não poderá ser removido se estiver marcado como "constante". + + + Não é possível remover o módulo "{0}" porque ele é exigido por "{1}". Adicione o parâmetro Force ao comando para remover o módulo. + + + O cmdlet Export-ModuleMember só pode ser chamado de dentro de um módulo. + + + A extensão "{0}" não é uma extensão de módulo válida. As extensões de módulo com suporte são ".dll", ".ps1", ".psm1", ".psd1" e ".cdxml". Corrija a extensão e tente adicionar o arquivo "{1}" novamente. + + + Esta operação não pode ser executada em um módulo binário. Ele só pode ser executado em um módulo de script. + + + O arquivo "{0}" não é permitido porque não tem a extensão ".ps1". + + + Desconhecido + + + (c) {0}. Todos os direitos reservados. + + + Removendo a função "{0}" importada. + + + Removendo o alias "{0}" importado. + + + Removendo a variável "{0}" importada. + + + Carregando módulo do caminho "{0}". + + + Carregando "{0}" do caminho "{1}". + + + Executando dot-sourcing do arquivo de script "{0}". + + + Importando função "{0}". + + + Importando cmdlet "{0}". + + + Importando alias "{0}". + + + Importando variável "{0}". + + + Exportando cmdlet "{0}". + + + Exportando função "{0}". + + + Exportando alias "{0}". + + + Exportando variável "{0}". + + + Os nomes de alguns comandos importados do módulo "{0}" incluem verbos não aprovados que podem torná-los menos detectáveis. Para localizar os comandos com verbos não aprovados, execute o comando Import-Module novamente com o parâmetro Verbose. Para obter uma lista de verbos aprovados, digite Get-Verb. + + + O comando "{0}" no módulo "{1}" foi importado, mas como seu nome não inclui um verbo aprovado, pode ser difícil de localizar. Para obter uma lista de verbos aprovados, digite Get-Verb. + + + O comando "{0}" no módulo "{2}" foi importado, mas como seu nome não inclui um verbo aprovado, pode ser difícil de localizar. Os verbos alternativos sugeridos são "{1}". + + + Alguns nomes de comando importados contêm um ou mais dos seguintes caracteres restritos: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + O nome do comando "{0}" do módulo "{1}" contém um ou mais dos seguintes caracteres restritos: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + Criando o arquivo de manifesto do módulo "{0}". + + + {0} (Caminho: "{1}") + + + A arquitetura atual do processador é: {0}. O módulo "{1}" requer a seguinte arquitetura: {2}. + + + O nome do host atual do PowerShell é: "{0}". O módulo "{1}" requer o seguinte host do PowerShell: "{2}". + + + O host atual do PowerShell é: "{0}" (versão {1}). O módulo "{2}" requer uma versão mínima do host do PowerShell de "{3}" para ser executado. + + + Manifesto do módulo "{0}" + + + Gerado por: {0} + + + Gerado em: {0} + + + Módulo de script ou arquivo de módulo binário associado a este manifesto. + + + Módulos a serem importados como módulos aninhados do módulo especificado em RootModule/ModuleToProcess + + + ID usada para identificar exclusivamente este módulo + + + Autor deste módulo + + + Empresa ou fornecedor deste módulo + + + Declaração de direitos autorais para este módulo + + + Número de versão deste módulo. + + + Descrição da funcionalidade fornecida por este módulo + + + Versão mínima do mecanismo do PowerShell exigida por este módulo + + + Versão mínima do CLR (Common Language Runtime) exigida por este módulo. {0} + + + Módulos que devem ser importados para o ambiente global antes de importar este módulo + + + Arquivos de script (.ps1) que são executados no ambiente do chamador antes de importar este módulo. + + + Arquivos de tipo (.ps1xml) a serem carregados ao importar este módulo + + + Arquivos de formato (.ps1xml) a serem carregados ao importar este módulo + + + Assemblies que devem ser carregados antes da importação deste módulo + + + Lista de todos os arquivos empacotados com este módulo + + + Dados privados a serem passados para o módulo especificado em RootModule/ModuleToProcess. Isso também pode conter uma tabela de hash PSData com metadados de módulo adicionais usados pelo PowerShell. + + + Marcas aplicadas a este módulo. Elas ajudam na descoberta de módulos em galerias online. + + + Uma URL para o site principal deste projeto. + + + Uma URL para a licença deste módulo. + + + Uma URL para um ícone que representa este módulo. + + + ReleaseNotes deste módulo + + + Cadeia de caracteres de pré-lançamento deste módulo + + + Sinalizador para indicar se o módulo requer aceitação explícita do usuário para instalar/atualizar/salvar + + + Módulos dependentes externos deste módulo + + + Fim da tabela de hash {0} + + + O valor do parâmetro PrivateData deve ser uma tabela de hash para criar o manifesto do módulo com os seguintes valores de parâmetro Tags, ProjectUri, LicenseUri, IconUri ou ReleaseNotes. Remova os valores dos parâmetros Tags, ProjectUri, LicenseUri, IconUri ou ReleaseNotes ou encapsule o conteúdo de PrivateData em uma tabela de hash. + + + PrivateData deve ser definido como uma tabela de hash, mas esse manifesto de módulo o define como um objeto. Considere encapsular o conteúdo de PrivateData em uma tabela de hash. Isso permitirá que você adicione as propriedades Tags, ProjectUri, LicenseUri, IconUri e ReleaseNotes ao manifesto do módulo posteriormente. + + + O valor especificado "{0}" é inválido. Tente novamente com um valor válido. + + + As funções a serem exportadas deste módulo, para melhor desempenho, não usam curingas e não excluem a entrada, usem uma matriz vazia se não houver funções para exportar. + + + Aliases a serem exportados deste módulo, para melhor desempenho, não usam curingas e não excluem a entrada, usem uma matriz vazia se não houver aliases para exportar. + + + Os cmdlets a serem exportados deste módulo, para melhor desempenho, não usam curingas e não excluem a entrada, usem uma matriz vazia se não houver cmdlets para exportar. + + + Variáveis a serem exportadas deste módulo + + + Recursos DSC a serem exportados deste módulo + + + PSEditions com suporte + + + Arquitetura do processador (None, X86, Amd64) exigida por este módulo + + + Lista de todos os módulos empacotados com este módulo + + + Versão mínima do Microsoft .NET Framework exigida por este módulo. {0} + + + Nome do host do PowerShell exigido por este módulo + + + Versão mínima do host do PowerShell exigida por este módulo + + + URI de HelpInfo deste módulo + + + Como o módulo {0} está fornecendo o PSDrive na sessão atual do PowerShell, nenhum módulo foi removido. Altere o provedor do PSDrive atual e tente remover os módulos novamente. + + + O cmdlet "{0}" não foi importado porque há um membro com o mesmo nome no escopo atual. + + + O alias "{0}" não foi importado porque há um membro com o mesmo nome no escopo atual. + + + A função "{0}" não foi importada porque há um membro com o mesmo nome no escopo atual. + + + A variável "{0}" não foi importada porque há um membro com o mesmo nome no escopo atual. + + + Caracteres curinga não são permitidos nos membros "ModuleToProcess", "RootModule" ou "NestedModules" no manifesto de módulo "{0}". + + + O módulo "{0}" é um módulo principal para o PowerShell. Adicione o parâmetro Force ao comando para remover os módulos principais. + + + O manifesto do módulo não pode conter os membros "ModuleToProcess" e "RootModule". Altere o arquivo de manifesto do módulo para remover um desses membros em "{0}" e tente novamente. + + + O membro do manifesto do módulo "ModuleToProcess" foi preterido. Em vez disso, use o membro "RootModule". + + + Prefixo padrão para comandos exportados deste módulo. Substitua o prefixo padrão usando Import-Module -Prefix. + + + Os parâmetros "Global" e "Scope" não podem ser especificados juntos. Remova um desses parâmetros e tente executar o comando novamente. + + + O módulo necessário "{0}" não está carregado. O módulo "{0}" tem um requiredModule "{1}" em seu manifesto de módulo "{2}" que aponta para uma dependência cíclica. + + + O módulo necessário "{0}" não foi carregado porque nenhum arquivo de módulo válido foi encontrado em nenhum diretório de módulo. + + + Alguns comandos do módulo {0} não podem ser importados em uma CimSession. Para obter todos os comandos, verifique se o servidor remoto tem o gerenciamento remoto do PowerShell habilitado e tente adicionar o parâmetro PSSession a um cmdlet Import-Module. + + + O módulo {0} é carregado no Windows PowerShell usando {1} sessão remota; observe que toda a entrada e a saída dos comandos deste módulo serão objetos desserializados. Se você quiser carregar este módulo no PowerShell, use a sintaxe "Import-Module -SkipEditionCheck". + + + Versão {0} do Windows PowerShell detectada. O Windows PowerShell 5.1 é necessário para carregar módulos usando o recurso de compatibilidade com o Windows PowerShell. Instale o Windows Management Framework (WMF) 5.1 https://aka.ms/WMF5Download para habilitar esse recurso. + + + O módulo "{0}" está impedido de carregar usando Windows PowerShell de compatibilidade por uma configuração "WindowsPowerShellCompatibilityModuleDenyList" no arquivo de configuração do PowerShell. + + + O módulo {0} não pode ser importado em uma CimSession. Tente usar o parâmetro PSSession do cmdlet Import-Module. + + + O valor da arquitetura do processador de {0} não tem suporte. Execute o comando New-ModuleManifest novamente, especificando um dos seguintes valores de enumeração com suporte para a arquitetura do processador: None, MSIL, X86, Amd64, Arm + + + Executar o cmdlet Get-Module em um computador remoto só pode listar os módulos disponíveis. Adicione o parâmetro ListAvailable ao comando e tente novamente. + + + O módulo "{0}" não foi importado porque o snap-in "{0}" já foi importado. + + + Caracteres curinga não são permitidos no membro "RequiredAssemblies" no manifesto do módulo "{0}". + + + O valor da chave {0} em {1} é {2} e o módulo tem módulos aninhados. Quando um arquivo CDXML é o módulo raiz, o comando Import-Module falha porque os comandos em módulos aninhados não podem ser exportados. Mova o arquivo CDXML para a chave NestedModules e tente o comando novamente. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Falha do comando remoto: {0}: {{0}} + + + Falha ao gerar proxies para o módulo remoto "{0}". {{0}} + + + Falha ao processar o módulo remoto {0}. {1} + + + Falha ao receber dados do módulo da CimSession remota. {0} + + + O módulo necessário "{0}" com GUID "{1}" e versão "{2}" não foi carregado porque nenhum arquivo de módulo válido foi encontrado em nenhum diretório de módulo. + + + Um provedor CIM para descoberta de módulo não foi encontrado no servidor CIM. {0} + {0} is a placeholder for a more detailed error message + + + Não é possível verificar a versão do Microsoft .NET Framework {0} porque ela não está incluída na lista de versões permitidas. + + + Analisando {0}. + {0} should not be localized, is used to contain a file path. + + + Preparando módulos para o primeiro uso. + + + Procurando módulos disponíveis + + + Pesquisando compartilhamento UNC {0}. + {0} should not be localized, is used to contain a file path. + + + Executar o cmdlet Get-Module em um computador remoto só pode ser feito para nomes de módulo que não incluem um caminho. O parâmetro Name tem este elemento "{0}", que resolve para um caminho. Atualize o parâmetro Name para não ter elementos de caminho e tente novamente. + + + Não há suporte para a execução do cmdlet Get-Module sem o parâmetro ListAvailable em nomes de módulo que incluem um caminho. O parâmetro Name tem este elemento "{0}", que resolve para um caminho. Atualize o parâmetro Name para não ter elementos de caminho e tente novamente. + + + O módulo especificado "{0}" não foi encontrado. Atualize o parâmetro Name para apontar para um caminho válido e tente novamente. + + + Populando a propriedade RepositorySourceLocation para o módulo {0}. + + + O módulo a ser processado "{0}", listado no campo "{1}" do manifesto do módulo "{2}" não foi processado. {3} + + + Esse pré-requisito é válido apenas para a edição PowerShell Desktop. + + + O módulo "{0}" não dá suporte à edição atual do PowerShell "{1}". Suas edições com suporte são "{2}". Use "Import-Module -SkipEditionCheck" para ignorar a compatibilidade deste módulo. + + + O módulo "{0}" dá suporte à edição "{1}" do PowerShell e não pode ser carregado implicitamente usando o recurso de Compatibilidade do Windows porque está desabilitado no arquivo de configurações. Use "Import-Module -UseWindowsPowerShell" para carregar este módulo com Windows PowerShell ou "Import-Module -SkipEditionCheck" para tentar carregar o módulo com o PowerShell atual. + + + Um valor de cadeia de caracteres não vazio deve ser especificado para um recurso experimental declarado no manifesto do módulo. + + + Um ou mais nomes de recursos experimentais inválidos encontrados: {0}. Um nome de recurso experimental do módulo deve seguir esta convenção: "ModuleName.FeatureName". + + + O parâmetro de opção -SkipEditionCheck não pode ser usado sem o parâmetro de opção -ListAvailable. + + + A importação de arquivos *.ps1 como módulos não é permitida no modo ConstrainedLanguage. + + + Erro ao carregar o módulo de script {0} porque ele tem um modo de linguagem diferente do manifesto do módulo. O modo de idioma do manifesto é {1} e o modo de linguagem do módulo é {2}. Verifique se todos os arquivos de módulo estão assinados ou, de outra forma, parte da configuração da lista de permissões do aplicativo. + + + Este módulo usa o operador dot-source ao exportar funções usando caracteres curinga e isso não é permitido quando o sistema está sob a imposição de verificação do aplicativo. + + + Não é possível exportar membros de módulo de um módulo que tenha um modo de idioma diferente da sessão em execução. + + + Não é possível criar um novo módulo enquanto a sessão estiver no modo ConstrainedLanguage. + + + Não é possível localizar o módulo interno "{0}" compatível com a edição "Core". Verifique se os módulos internos do PowerShell estão disponíveis. Eles geralmente vêm com o pacote do PowerShell no caminho do módulo $PSHOME e são necessários para que o PowerShell funcione corretamente. + + + Cmdlet Export-ModuleMember + + + A exportação de membros do módulo falhará no modo idioma restrito porque o módulo "{0}", tem um modo de idioma "{1}" diferente da sessão atual "{2}". + + + Exportação de Função Implícita do Módulo + + + A exportação de função implícita para o módulo "{0}" será negada porque é confiável (é executada no modo de Idioma Completo), mas a sessão não é confiável (é executada no modo idioma restrito). É uma prática recomendada sempre exportar funções de módulo individualmente por nome completo. + + + Importando arquivo de script como módulo + + + A importação do arquivo de script "{0}" como um módulo não será permitida no modo ConstrainedLanguage. + + + Módulo Contém Operador dot-source + + + A importação do módulo "{0}" falhará no modo idioma restrito porque exporta funções usando caracteres curinga enquanto também usa o operador dot-source. + + + "Módulo exportando funções + + + O módulo "{0}" exporta funções usando caracteres curinga no nome. Todos os nomes de função de módulo aninhados serão removidos durante a execução no modo de Linguagem Restrita. + + + "Cmdlet New-Module + + + Um novo módulo de uma sessão de Idioma Restrito não confiável será impedido de fornecer o bloco de script FullLanguage. + + + "Modos de linguagem incompatíveis do módulo + + + Um módulo dependente está sendo carregado que tem um modo de idioma diferente do pai. Isso não será permitido quando estiver no modo de Idioma Restrito. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/MshHostRawUserInterfaceStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/MshHostRawUserInterfaceStrings.pt-BR.resx new file mode 100644 index 00000000000..a5c001d2d6b --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/MshHostRawUserInterfaceStrings.pt-BR.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}" não pode ser maior ou igual a "{1}". + + + "{0}" deve ser um número positivo. + + + Todas as cadeias de caracteres são nulas ou vazias. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/MshSignature.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/MshSignature.pt-BR.resx new file mode 100644 index 00000000000..201c4f5ff34 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/MshSignature.pt-BR.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 + + + Assinatura verificada. + + + O arquivo {0} não está assinado digitalmente. Não é possível executar esse script no sistema atual. Para obter mais informações sobre como executar scripts e definir a política de execução, consulte about_Execution_Policies em https://go.microsoft.com/fwlink/?LinkID=135170 + + + O conteúdo do arquivo {0} pode ter sido alterado por um usuário ou processo não autorizado, porque o hash do arquivo não corresponde ao hash armazenado na assinatura digital. O script não pode ser executado no sistema especificado. Para obter mais informações, execute Get-Help about_Signing. + + + O arquivo {0} está assinado, mas o signante não é confiável neste sistema. + + + Não é possível assinar o arquivo porque o sistema não dá suporte a operações de assinatura em {0} arquivos. + + + Não é possível assinar o arquivo porque o sistema não dá suporte a operações de assinatura em arquivos que não têm uma extensão de nome de arquivo. + + + A assinatura não pode ser verificada porque é incompatível com o sistema atual. + + + A assinatura não pode ser verificada porque é incompatível com o sistema atual. O algoritmo de hash não é válido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/MshSnapInCmdletResources.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/MshSnapInCmdletResources.pt-BR.resx new file mode 100644 index 00000000000..476942fa6bd --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/MshSnapInCmdletResources.pt-BR.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 + + + Não é possível executar a operação. O cmdlet especificado não tem suporte em um shell personalizado. + + + Nenhum snap-in do PowerShell correspondente ao padrão '{0}' foi encontrado. Verifique o padrão e tente o comando novamente. + + + O formato do nome de snap-in especificado não era válido. Os nomes de snap-in do PowerShell só podem conter caracteres alfanuméricos, hifens, sublinhados e pontos. Corrija o nome e tente a operação novamente. + + + Não é possível adicionar o snap-in do PowerShell {0} porque ele é um módulo do sistema do PowerShell. Use Import-Module para carregar o módulo. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/MshSnapinInfo.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/MshSnapinInfo.pt-BR.resx new file mode 100644 index 00000000000..c2aada8aac6 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/MshSnapinInfo.pt-BR.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 + + + Não é possível acessar as informações de registro do PowerShell. + + + Não é possível acessar as informações de registro do Mecanismo do PowerShell. + + + Não foi possível acessar as informações de PublicKeyToken. + + + A versão {0} do PowerShell não está disponível neste computador. + + + O snap-in do PowerShell "{0}" não está instalado neste computador. + + + O valor obrigatório {0} não foi especificado para a chave do Registro {1}. + + + O valor obrigatório {0} não está no formato correto para a chave do Registro {1}. O formato esperado é "string". + + + O valor obrigatório {0} não está no formato correto para a chave do Registro {1}. O formato esperado é "multistring". + + + Não é possível localizar as informações necessárias no Registro ou os arquivos de chave estão ausentes. Não é possível carregar alguns cmdlets. + + + Nenhum snap-in foi registrado para a versão {0} do PowerShell. + + + Não é possível recuperar o recurso de cadeia de caracteres porque o leitor foi descartado. + + + O valor da versão {0} não foi especificado ou está incorreto para a chave do Registro {1}. + + + Nenhum atributo [PSVersion] foi encontrado para o tipo do PowerShell {0}. Adicione um atributo PSVersion ao tipo usando [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/NativeCP.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/NativeCP.pt-BR.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/NativeCP.pt-BR.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PSCommandStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PSCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..936d1219fe1 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PSCommandStrings.pt-BR.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 + + + É necessário um comando para adicionar um parâmetro. Um comando deve ser adicionado a {0} antes de adicionar um parâmetro. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PSConfigurationStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PSConfigurationStrings.pt-BR.resx new file mode 100644 index 00000000000..45b469db758 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PSConfigurationStrings.pt-BR.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 + + + PowerShell has stopped working because of a security issue: Cannot read the configuration file: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PSDataBufferStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PSDataBufferStrings.pt-BR.resx new file mode 100644 index 00000000000..dfd22557a34 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PSDataBufferStrings.pt-BR.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 + + + O índice especificado é menor que zero ou maior que o número de itens no buffer. O índice deve estar no intervalo de {0}-{1}. + + + Não é possível converter uma referência nula em um tipo de valor. + + + Não é possível converter o valor do tipo {0} para o tipo {1}. + + + Não é possível adicionar objetos a um buffer fechado. Verifique se o buffer está aberto para que as operações Adicionar e Inserir sejam bem-sucedidas. + + + A propriedade SerializeInput só pode ser definida para o tipo PSObject de PSDataCollection. Defina a propriedade SerializeInput como false ou altere o tipo da coleção para um PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PSListModifierStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PSListModifierStrings.pt-BR.resx new file mode 100644 index 00000000000..fa3b150e430 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PSListModifierStrings.pt-BR.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 + + + O seguinte modificador de lista desconhecido foi detectado: '{0}'. Os modificadores de lista válidos são Adicionar, Remover e Substituir. + + + Não é possível aplicar a atualização porque o objeto não é um tipo de coleção com suporte. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PSStyleStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PSStyleStrings.pt-BR.resx new file mode 100644 index 00000000000..df72e8fcb39 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PSStyleStrings.pt-BR.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + A cadeia de caracteres especificada contém conteúdo imprimível quando deveria conter apenas sequências de escape ANSI: {0} + + + O valor de MaxWidth para a renderização do Progress deve ser de pelo menos 18 para que seja renderizado corretamente. + + + Ao adicionar ou remover extensões, a extensão precisa começar com um ponto. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ParameterBinderStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ParameterBinderStrings.pt-BR.resx new file mode 100644 index 00000000000..e36d85dc05a --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ParameterBinderStrings.pt-BR.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não foi possível encontrar um parâmetro correspondente ao nome de parâmetro '{1}'. + + + Não foi possível encontrar um parâmetro posicional que aceite o argumento '{1}'. + + + Falta um argumento para o parâmetro '{1}'. Especifique um parâmetro do tipo '{2}' e tente novamente. + + + O parâmetro não pode ser processado porque o nome do parâmetro '{1}' é ambíguo. As possíveis correspondências incluem:{6}. + + + Não é possível converter '{6}' para o tipo '{2}' exigido pelo parâmetro '{1}'. {7} + + + Não é possível associar o parâmetro '{1}'. {6} + + + Não é possível associar os parâmetros posicionais '{1}'. + + + Não é possível associar parâmetros posicionais porque nenhum nome foi fornecido. + + + O conjunto de parâmetros não pode ser resolvido com o uso dos parâmetros nomeados especificados. Um ou mais parâmetros emitidos não podem ser usados juntos ou um número insuficiente de parâmetros foi fornecido. + + + Não é possível processar o comando porque um ou mais parâmetros obrigatórios estão ausentes:{1}. + + + O parâmetro '{1}' não pode ser especificado no conjunto de parâmetros '{6}'. + + + Não é possível associar o parâmetro porque o parâmetro '{1}' foi especificado mais de uma vez. Para fornecer vários valores a parâmetros que aceitam vários valores, use a sintaxe de matriz. Por exemplo, "-parameter value1,value2,value3". + + + Não é possível avaliar o parâmetro '{1}' porque o argumento está especificado como um bloco de script e não há entrada. Um bloco de script não pode ser avaliado sem entrada. + + + Falha na entrada para o bloco de script do parâmetro '{1}'. {6} + + + Não é possível avaliar o parâmetro '{1}' porque a entrada do argumento não produziu nenhuma saída. + + + O objeto de entrada não pode ser associado a nenhum parâmetro para o comando porque o comando não usa entrada de pipeline ou a entrada e suas propriedades não correspondem a nenhum dos parâmetros que usam entrada de pipeline. + + + O objeto de entrada não pode ser associado porque não continha as informações necessárias para associar todos os parâmetros obrigatórios: {6} + + + A entrada do pipeline não pode ser processada porque o valor padrão do parâmetro '{1}' não pode ser recuperado. {6} + + + Não é possível recuperar os parâmetros dinâmicos para o cmdlet. {6} + + + Forneça valores para os seguintes parâmetros: + + + cmdlet {0} na posição do pipeline de comando {1} + + + Não é possível processar a transformação do argumento no parâmetro '{1}'. {6} + + + {6} + + + Não é possível validar o argumento no parâmetro '{1}'. {6} + + + Não é possível associar o parâmetro '{1}' ao destino. {6} + + + Não é possível associar o argumento ao parâmetro '{1}' porque ele é nulo. + + + Não é possível associar o argumento ao parâmetro '{1}' porque ele é uma cadeia de caracteres vazia. + + + Não é possível associar o argumento ao parâmetro '{1}' porque ele é uma coleção vazia. + + + Não é possível associar o argumento ao parâmetro '{1}' porque ele é uma matriz vazia. + + + Não é possível processar o comando. O parâmetro '{0}' foi definido várias vezes. + + + Não é possível associar o cmdlet {0} porque o parâmetro '{1}' é do tipo '{2}' e o método Add() não pode ser identificado ou existem vários métodos Add(). {6} + + + Não é possível associar o cmdlet {0} porque o parâmetro definido por runtime '{1}' foi adicionado ao RuntimeDefinedParameterDictionary com a chave '{6}'. A chave deve ser a mesma que RuntimeDefinedParameter.Name. + + + Não é possível associar o argumento ao parâmetro '{1}', porque os PSTypeNames do argumento não correspondem ao PSTypeName exigido pelo parâmetro: {6}. + + + Vários valores padrão diferentes estão definidos em $PSDefaultParameterValues para o parâmetro correspondente ao seguinte nome ou alias: {0}. Esses padrões foram ignorados. + + + O seguinte nome ou alias definido no $PSDefaultParameterValues para este cmdlet é resolvido para vários parâmetros: {0}. O padrão foi ignorado. + + + {6} Esse erro pode ter sido causado pela aplicação da associação de parâmetro padrão. Você pode desabilitar a associação de parâmetro padrão $PSDefaultParameterValues configurando $PSDefaultParameterValues["Desabilitado"] como $true e, em seguida, tentando novamente. Os seguintes parâmetros padrão foram associados com sucesso a este cmdlet quando o erro ocorreu:{7} + + + {6} Essa falha pode ter sido causada pela aplicação da associação de parâmetro padrão. Você pode desabilitar a associação de parâmetro padrão em $PSDefaultParameterValues definindo $PSDefaultParameterValues["Disabled"] como $true e tentar novamente. O seguinte parâmetro padrão foi associado com sucesso a este cmdlet quando o erro ocorreu:{7} + + + Falha na associação do valor padrão '{0}' ao parâmetro '{1}': {2} + + + A chave '{0}' não tem um formato válido. Para obter informações sobre o formato correto, consulte about_Parameters_Default_Values em https://go.microsoft.com/fwlink/?LinkId=228266. + + + As chaves '{0}' não têm formatos válidos. Para obter informações sobre o formato correto, consulte about_Parameters_Default_Values em https://go.microsoft.com/fwlink/?LinkId=228266. + + + O parâmetro '{0}' está obsoleto. {1} + + + A chave '{0}' do tipo '{1}' não é um valor de cadeia de caracteres. DefaultParameterDictionary só aceita chaves com valores de cadeia de caracteres. + + + A chave '{0}' já foi adicionada ao dicionário. + + + Método ou Invocação de Propriedade Não Permitido + + + A invocação de método ou propriedade '{0}' no tipo '{1}' não será permitida no modo de Linguagem Restrita para scripts não confiáveis. + + + Criação de Tipo Não Permitida + + + A criação do Tipo '{0}' não será permitida durante a associação de parâmetros no modo de Linguagem Restrita para scripts não confiáveis. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ParserStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ParserStrings.pt-BR.resx new file mode 100644 index 00000000000..5610de8daea --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ParserStrings.pt-BR.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Não é possível carregar o assembly '{0}'. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PathUtilsStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PathUtilsStrings.pt-BR.resx new file mode 100644 index 00000000000..63e8ff4e6a1 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PathUtilsStrings.pt-BR.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Encoding 'UTF-7' is obsolete, please use UTF-8. + + + File {0} already exists and {1} was specified. + + + Cannot open file because the current provider ({0}) cannot open a file. + + + Cannot perform operation because the path resolved to more than one file. This command cannot operate on multiple files. + + + Cannot perform operation because the wildcard path {0} did not resolve to a file. + + + Unknown encoding {0}; valid values are {1}. + + + The directory '{0}' already exists. Use the -Force parameter if you want to overwrite the directory and files within the directory. + + + The user module path does not exist, and hence a module folder cannot be created for the provided module name '{0}'. + + + Cannot create the module {0} due to the following: {1}. Use a different argument for the -OutputModule parameter and retry. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + The module cannot be loaded because it has been generated with an incompatible version of the {0} cmdlet. Generate the module with the {0} cmdlet from the current session, and try loading the module again. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PipelineStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PipelineStrings.pt-BR.resx new file mode 100644 index 00000000000..ece7c45545e --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PipelineStrings.pt-BR.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não é possível processar a instância do cmdlet porque ela está sendo usada por outro pipeline. Contate os Serviços de Atendimento ao Cliente da Microsoft. + + + Não é possível executar a operação porque o pipeline já foi iniciado. Pare o pipeline e tente a operação novamente. + + + Não é possível continuar executando o cmdlet porque a política Stop impediu a execução de cmdlets. + + + Não é possível executar o pipeline porque o primeiro cmdlet do pipeline está tentando ler a entrada dos resultados de um cmdlet anterior. Modifique o primeiro cmdlet, remova-o ou adicione ao pipeline o cmdlet cuja saída é necessária para o primeiro cmdlet e tente executar o pipeline novamente. + + + Não é possível processar o número do cmdlet. A função ReadFromCommand deve especificar a ID de um cmdlet que já tenha sido adicionado ao pipeline. Contate os Serviços de Atendimento ao Cliente da Microsoft. + + + Não é possível ler a saída das funções ReadFromCommand e ReadErrorQueue porque outro cmdlet já está lendo essa saída. Contate os Serviços de Atendimento ao Cliente da Microsoft. + + + Não é possível executar o pipeline porque não há comandos. Adicione pelo menos um comando ao pipeline e execute-o novamente. + + + Não é possível concluir a operação de pipeline porque ela ainda não foi iniciada. Você deve chamar o método Begin() antes de chamar End() em um pipeline em etapas. + + + Os métodos WriteObject e WriteError não podem ser chamados de fora das substituições dos métodos BeginProcessing, ProcessRecord e EndProcessing, e só podem ser chamados na mesma thread. Verifique se o cmdlet faz essas chamadas corretamente ou entre em contato com o Atendimento ao cliente da Microsoft. + + + Um cmdlet gerou uma exceção depois de chamar ThrowTerminatingError. +A primeira exceção foi "{0}", com rastreamento de pilha "{1}". +A segunda exceção foi "{2}", com rastreamento de pilha "{3}". + + + Os métodos WriteObject e WriteError não podem ser chamados depois que o pipeline foi fechado. Contate os Serviços de Atendimento ao Cliente da Microsoft. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Ocorreu um erro ao criar o pipeline. + + + Este pipeline não dá suporte à semântica de desconexão e reconexão. + + + Não é possível conectar este pipeline porque ele não está no estado desconectado. + + + O objeto runspace tem um comando remoto nulo associado a ele. Não é possível criar um objeto RemotePipeline desconectado porque não há nenhum comando remoto especificado. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/PowerShellStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/PowerShellStrings.pt-BR.resx new file mode 100644 index 00000000000..cbd9fd516df --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/PowerShellStrings.pt-BR.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 + + + O estado da instância atual do PowerShell não é válido para esta operação. + + + A operação não pode ser executada porque um comando já foi iniciado. Aguarde até que o comando seja concluído ou pare-o e tente a operação novamente. + + + Nenhum comando foi especificado. + + + A instância do PowerShell não está no estado correto para criar uma instância aninhada do PowerShell. Instâncias aninhadas do PowerShell só devem ser criadas em uma instância do PowerShell em execução. + + + Não é possível executar a operação porque o runspace não está no estado "{0}". O estado atual do runspace é '{1}'. + + + Instâncias aninhadas do PowerShell não podem ser invocadas de forma assíncrona. Use o método Invoke. + + + O objeto {0} não foi criado chamando {1} nesta instância do PowerShell. + + + Quando o runspace é definido para reutilizar uma thread, o estado do apartment nas configurações de invocação deve corresponder ao runspace. + + + Quando o runspace é definido para usar a thread atual, o estado do apartment nas configurações de invocação deve corresponder ao da thread atual. + + + É necessário um comando para adicionar um parâmetro. Você precisa adicionar um comando à instância do PowerShell antes de adicionar um parâmetro. + + + As chaves no dicionário devem ser cadeias de caracteres. + + + Não há nenhum Runspace disponível para executar comandos nesta thread. Você pode informar um na propriedade DefaultRunspace do tipo System.Management.Automation.Runspaces.Runspace. O comando que você tentou invocar foi: {0} + + + Este objeto do PowerShell não pode ser conectado porque não está associado a um runspace remoto ou a um pool de runspaces. + + + O comando em execução foi desconectado, mas ainda está em execução no servidor remoto. Reconecte-se para obter o status da operação do comando e os dados de saída. + + + A operação não pode ser executada porque a sessão atual do PowerShell está no estado Desconectado. Conecte esta sessão do PowerShell e depois aguarde a conclusão do comando ou pare o comando. + + + A operação não pode ser executada porque a sessão atual do PowerShell está no estado Desconectado. Conecte esta sessão do PowerShell e tente novamente. + + + Falha na tentativa de conexão com o comando remoto. + + + A operação não pode ser executada porque um comando está sendo interrompido no momento. Aguarde até que a interrupção do comando seja concluída e tente a operação novamente. + + + Não há nenhum Runspace disponível para executar comandos nesta thread. Você pode informar um na propriedade DefaultRunspace do tipo System.Management.Automation.Runspaces.Runspace. A instância atual do PowerShell não contém nenhum comando para invocar. + + + Não é possível criar um objeto do PowerShell que use o runspace atual porque não há nenhum runspace atual disponível. O runspace atual pode estar sendo iniciado, por exemplo, quando ele é criado com um Estado Inicial de Sessão. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ProgressRecordStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ProgressRecordStrings.pt-BR.resx new file mode 100644 index 00000000000..cc777b84cb2 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ProgressRecordStrings.pt-BR.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não é possível processar o argumento porque {0} não pode ser um valor negativo. + + + Não é possível processar o argumento porque o valor de {0} não pode ser nulo nem vazio. + + + Não é possível definir a porcentagem porque {0} não pode ser maior que 100. + + + ParentActivityId não pode ser igual a ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ProviderBaseSecurity.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ProviderBaseSecurity.pt-BR.resx new file mode 100644 index 00000000000..5825de68a39 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ProviderBaseSecurity.pt-BR.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 + + + Não é possível usar a interface porque a interface ISecurityDescriptorCmdletProvider não tem suporte nesse provedor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/ProxyCommandStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/ProxyCommandStrings.pt-BR.resx new file mode 100644 index 00000000000..aa5dbeb125c --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/ProxyCommandStrings.pt-BR.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 + + + O parâmetro 'help' não é reconhecido como um objeto HelpInfo válido criado pelo comando 'get-help'. + + + O comando proxy não pode ser gerado porque CommandMetadata não tem nome. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/RegistryProviderStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/RegistryProviderStrings.pt-BR.resx new file mode 100644 index 00000000000..fa7e97ec32a --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/RegistryProviderStrings.pt-BR.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Definir Item + + + Item: {0} Valor: {1} + + + Limpar Item + + + Item: {0} + + + Novo Item + + + Item: {0} + + + Remover Chave + + + Item: {0} + + + Copiar Chave + + + Item: {0} Destino: {1} + + + Renomear Item + + + Item: {0} NewName: {1} + + + Mover Item + + + Item: {0} Destino: {1} + + + Definir Propriedade + + + Item: {0} Propriedade: {1} + + + Limpar Propriedade + + + Item: {0} Propriedade: {1} + + + Nova Propriedade + + + Item: {0} Propriedade: {1} + + + Remover Propriedade + + + Item: {0} Propriedade: {1} + + + Renomear propriedade. + + + Item: {0} SourceProperty: {1} DestinationProperty: {2} + + + Copiar Propriedade + + + Item: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Mover Propriedade + + + Item: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + A operação não foi processada. O local fornecido não permite esta operação. + + + A operação não é permitida no local de origem. + + + A operação não é permitida no local de destino. + + + As configurações de configuração do computador local + + + As configurações de software do usuário atual + + + Já existe uma chave neste caminho. + + + A operação não pode ser executada porque o caminho de destino é subordinado ao caminho de origem. + + + A propriedade já existe. + + + A propriedade {0} não existe no caminho {1}. + + + A chave do Registro no caminho especificado não existe. + + + Não foi possível associar o parâmetro "Type". Não foi possível converter "{0}" em "{1}". Os valores de enumeração possíveis são "String, ExpandString, Binary, DWord, MultiString, QWord, Unknown". + + + A chave {0} foi criada, mas não foi possível definir um valor padrão. + + + Não é possível criar uma unidade com a raiz especificada. O caminho raiz não existe. + + + O item não pode ser renomeado porque já existe um item com esse nome no mesmo contêiner. + + + O nome da chave do Registro deve começar com um nome de chave base válido. + + + O argumento de subchave não é válido. + + + Não é possível excluir a árvore de uma subchave porque a subchave não existe. + + + Não existe nenhum valor com esse nome. + + + O valor de enumeração {0} não é válido. + + + É preciso especificar um argumento de valor. + + + É preciso especificar um argumento de nome. + + + O RegistryValueKind especificado não é um valor válido. + + + RegistryKey.SetValue não permite um String[] que contenha uma referência nula de String. + + + As subchaves do Registro não deve ser maior que 255 caracteres. + + + É preciso especificar um nome de subchave não vazio. + + + O tipo do objeto de valor não corresponde ao RegistryValueKind especificado ou o objeto não pôde ser convertido corretamente. + + + RegistryKey.SetValue não oferece suporte a matrizes do tipo "{0}". Há suporte apenas para Byte[] e String[]. + + + A chave do Registro especificada não existe. + + + O comprimento do nome do valor especificado excede o máximo de 16.383 caracteres. + + + O tamanho dos dados do valor especificado excede o máximo de 1 MB. + + + A subchave do Registro especificada não existe. + + + O valor especificado de RegistryKeyPermissionCheck não é válido. + + + A chave do Registro tem subchaves; este método não oferece suporte a remoções recursivas. + + + Não é possível criar um identificador KTM sem um Transaction.Current ou uma transação especificada. + + + A transação especificada ou Transaction.Current deve corresponder à transação usada para criar ou abrir esse TransactedRegistryKey. + + + O objeto TransactedRegistryKey não está associado a uma transação porque se trata de uma chave predefinida. + + + O acesso ao Registro solicitado não é permitido. + + + O acesso à chave do Registro "{0}" foi negado. + + + Não é possível gravar na chave do Registro. + + + Não é possível acessar uma chave do Registro fechada. + + + Erro desconhecido: {0}. + + + As transações do registro não têm suporte nesta plataforma. + + + O identificador especificado não é válido. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/RemotingErrorIdStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/RemotingErrorIdStrings.pt-BR.resx new file mode 100644 index 00000000000..f9ba70fb1cb --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/RemotingErrorIdStrings.pt-BR.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + Wildcard characters are not supported for the FilePath parameter. Specify a path without wildcard characters. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + A {0} value must be specified for session option {1}. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + The maximum number of WS-Man URI redirections to allow while connecting to a remote computer + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + The WriteEvents parameter cannot be used without the Wait parameter. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + PowerShell remoting is not supported in the Windows Preinstallation Environment (WinPE). + + + Changes made by {0} cannot take effect until the WinRM service is restarted. + + + {0} may need to restart the WinRM service if a configuration using this name has recently been unregistered, certain system data structures may still be cached. In that case, a restart of WinRM may be required. +All WinRM sessions connected to PowerShell session configurations, such as Microsoft.PowerShell and session configurations that are created with the Register-PSSessionConfiguration cmdlet, are disconnected. + + + You are running in a remote session and have selected the Force option which means the WinRM service may restart.If the WinRM service restarts then this remote session will be terminated and you will need to create a new session to continue + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + The -WriteJobInResults parameter cannot be used without the -Wait parameter + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + The supplied input stream is not valid. Only {0} is supported as input stream. + + + The supplied output stream set is not valid. Only {0} is supported as output stream. + + + The supplied WSMAN_SENDER_DETAILS is not valid. Cannot process null WSMAN_SENDER_DETAILS. + + + The supplied shell context is not valid. + + + {0} + + + NULL value is not allowed for {0} with the plugin method {1}. + + + NULL value is not allowed for input stream and output stream sets. {0} and {1} are the supported input and output streams. + + + NULL value is not allowed for {0} with the plugin method {1}. + + + NULL value is not allowed for {0} with the plugin method {1}. + + + PowerShell plugin operation is shutting down. This may happen if the hosting service or application is shutting down. + + + PowerShell plugin does not understand the option {0}. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + An option with name {0} is expected from the client. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Powershell plugin does not support the protocol version {2} requested by client.</PSProtocolVersionError> + + + Powershell plugin encountered a fatal error while reporting context to WSMan service. + + + Unable to create managed server session. + + + Powershell plugin encountered a fatal error registering a wait handle for shutdown notification. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + The "{0}" executable file was not found. Verify that the WOW64 feature is installed. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + Unable to create Windows PowerShell process because Windows PowerShell could not be found on this machine. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/RunspaceInit.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/RunspaceInit.pt-BR.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/RunspaceInit.pt-BR.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/RunspacePoolStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/RunspacePoolStrings.pt-BR.resx new file mode 100644 index 00000000000..9dd772ed197 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/RunspacePoolStrings.pt-BR.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + O tamanho máximo do pool não pode ser menor que 1. + + + O tamanho mínimo do pool não pode ser menor que 1. + + + O tamanho mínimo do pool não pode ser maior que o tamanho máximo do pool. + + + O estado do pool de runspaces não é válido para esta operação. + + + Não é possível executar a operação porque o pool de runspaces não está no estado "{0}". O estado atual é "{1}". + + + Não é possível abrir o pool de runspaces porque ele não está no estado "BeforeOpen". O estado atual é "{0}". + + + O objeto {0} não foi criado ao chamar {1} na instância atual de RunspacePool. + + + Não é possível liberar o runspace para o pool atual porque ele não pertence a esse pool. + + + Essa propriedade não pode ser alterada após a abertura do pool de runspaces. + + + Este runspace não oferece suporte a operações de desconexão e conexão. + + + Não é possível executar a operação porque o pool de runspaces está no estado Desconectado. + + + A operação de Desconexão não tem suporte no servidor. O servidor precisa estar executando o PowerShell 3.0 ou superior para oferecer suporte à desconexão do pool de runspaces remoto. + + + Este pool de runspaces {0} não está configurado para fornecer objetos do PowerShell desconectados para comandos em execução no servidor remoto. Use o método estático GetRunspacePools() da classe RunspacePool para consultar o servidor e retornar objetos de pool de runspaces configurados para fazer isso. + + + Este pool de runspaces não pode ser conectado porque o pool de runspaces correspondente no servidor está conectado a outro cliente. + + + ResetRunspaceState não tem suporte no servidor. O servidor precisa estar executando o PowerShell 5.0 ou superior. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/RunspaceStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/RunspaceStrings.pt-BR.resx new file mode 100644 index 00000000000..c2274ab7ed1 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/RunspaceStrings.pt-BR.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 runspace state is not valid for this operation. + + + Cannot open the runspace because the runspace is not in the BeforeOpen state. Current state of the runspace is '{0}'. + + + Cannot perform the operation because the runspace is not in the Opened state. Current state of the runspace is '{0}'. + + + Cannot invoke the pipeline because the runspace is not in the Opened state. Current state of the runspace is '{0}'. + + + The pipeline state is not valid for this operation. + + + Cannot invoke pipeline because it has already been invoked. + + + The valid value for the parameter is PipelineResultTypes.Output. + + + The pipeline does not contain a command. + + + The pipeline was not run because a pipeline is already running. Pipelines cannot be run concurrently. + + + A nested pipeline cannot be invoked asynchronously. Use the Invoke method. + + + You should only run a nested pipeline from within a running pipeline. + + + Runspace cannot be closed while a SessionStateProxy method call is in progress. + + + Pipeline cannot be invoked while a SessionStateProxy method call is in progress. + + + A SessionStateProxy method call is in progress. Concurrent SessionStateProxy method calls are not allowed. + + + A pipeline is already running. Concurrent SessionStateProxy method calls are not allowed. + + + This property cannot be changed after the runspace has been opened. + + + One or more errors occurred processing the module '{0}' specified in the InitialSessionState object used to create this runspace. See the ErrorRecords property for a complete list of errors. The first error was: {1} + + + The thread options can only be changed if the apartment state is multithreaded apartment (MTA), the current options are UseNewThread or UseCurrentThread, and the new value is ReuseThread. + + + {0} cannot be false when language mode is {1} or {2}. + + + You cannot disconnect a local-only runspace. + + + The Connect operation is not supported on local runspaces. + + + The session is busy. You will be connected to the session as soon as it is available. To cancel the Enter-PSSession command, press Ctrl-C. + + + The command cannot be completed. Script invocation is not supported in this session configuration. This can occur if the session configuration is in no-language mode. + + + You cannot use Disconnect and Connect operations on local runspaces. + + + Cannot connect the pipeline because the runspace is not in the Opened state. Current state of runspace is '{0}'. + + + Cannot construct a RemoteRunspace. The provided RunspacePool object is not valid. + + + There is no disconnected command associated with this runspace. + + + The disconnection operation is not supported on the remote computer. To support disconnecting, the remote computer must be running Windows PowerShell 3.0 or a later version of Windows PowerShell and using the WSMan transport. + + + Cannot connect the PSSession because the session is not in the Disconnected state, or is not available for connection. + + + Value for parameter cannot be PipelineResultTypes.None or PipelineResultTypes.Output. + + + Valid values for the parameter are PipelineResultTypes.Output or PipelineResultTypes.Null. + + + Debug stream redirection is not supported on the targeted remote computer. + + + Verbose stream redirection is not supported on the targeted remote computer. + + + Warning stream redirection is not supported on the targeted remote computer. + + + Information stream redirection is not supported on the targeted remote computer. + + + You have entered a session that is busy running a command or script. Because output is routed to job "{0}", you will not see output in the console. You can wait for the running command to finish, or cancel the command and get an input prompt by pressing Ctrl-C. + + + + You have entered a session that is busy running a command or script and output will be displayed in the console. You can wait for the running command to finish or cancel it and get an input prompt by pressing Ctrl-C. + + + + You have entered a session that is currently stopped at a debug breakpoint inside a running command or script. Use the PowerShell command line debugger to continue debugging. + + + + DefaultRunspace must be a LocalRunspace + + + The static PrimaryRunspace property can only be set once, and has already been set. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/SecuritySupportStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/SecuritySupportStrings.pt-BR.resx new file mode 100644 index 00000000000..48139f16ae7 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/SecuritySupportStrings.pt-BR.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não é possível carregar o certificado. "{0}" deve ser resolvido para um caminho do sistema de arquivos. + + + O certificado "{0}" não pode ser usado para criptografia. Os certificados de Criptografia devem conter o uso da chave de Criptografia de Dados ou de Criptografia de Chave e incluir o Uso Avançado de Chave de Criptografia de Documento ({1}). + + + Não foi possível carregar o certificado. O identificador "{0}" corresponde a vários certificados. Para criptografar para vários destinatários, forneça vários valores específicos para o parâmetro "{1}", em vez de um curinga que corresponda a vários certificados. + + + Não é possível carregar o certificado de criptografia. A configuração do certificado "{0}" não representa um certificado válido codificado em base64, nem um certificado válido por arquivo, diretório, impressão digital ou nome de assunto. + + + AVISO: o certificado "{0}" contém uma chave privada. Os certificados de Registro em Log de Eventos Protegidos usados para criptografia devem conter apenas a chave pública. + + + ERRO: não foi possível proteger a mensagem do log de eventos "{0}": {1} + + + ERRO: não foi possível localizar ou usar o certificado: {0} + + + A chave da sessão não está disponível para criptografar a cadeia de caracteres segura. + + + Deslocamento de buffer inválido. + + + Dados inválidos de chave pública. + + + Não foi possível importar a chave pública. + + + Dados inválidos de chave da sessão. + + + O arquivo de script "{0}" foi bloqueado pela política do sistema e não pode ser executado. + + + Foi retornado um valor desconhecido para a imposição da política de arquivo de script: {0}. + + + Arquivo de Script Lido + + + O arquivo de script "{0}" não é confiável pela política e será executado no modo ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/Serialization.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/Serialization.pt-BR.resx new file mode 100644 index 00000000000..b31323360fb --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/Serialization.pt-BR.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} attribute was expected. + + + {0} XML tag is not recognized. + + + No object found for referenceId {0} + + + Name attribute for dictionary key is incorrectly specified. + + + Name attribute for dictionary value is incorrectly specified. + + + Version of PSObject is not valid. + + + Version of incoming PSObject is {0}. Expected value is 1. + + + Cannot process names because no TypeNames were found for referenceId {0}. + + + Value of depth parameter must be greater than or equal to 1. + + + Current Node type is {0}. Expected type is {1}. + + + Key for dictionary entry is not specified. + + + Value for dictionary entry is not specified. + + + There are no more objects to deserialize. + + + Null is specified as dictionary key. + + + The contents of the {0} primitive type are not valid. + + + Serialized XML is nested too deeply. + + + Serializer was closed. + + + The data in the command exceeded the maximum size that is allowed by the session configuration. The allowed maximum is {0} MB. Change the input, use a different session configuration, or change the "{1}" and "{2}" properties of the session configuration on the remote computer. + + + Deserialization of encrypted secure string failed + + + The key type {0} is not valid. The PSPrimitiveDictionary class accepts only keys of the type System.String. + + + The type of the value {0} is not valid. The PSPrimitiveDictionary class accepts only values of types that are fully serializable over PowerShell remoting. See the Help topic about_Remoting for a list of fully-serializable types. + + + Could not decrypt data. The data was not encrypted with this key. + + + The parameter value "{0}" is not a valid encrypted string. + + + The specified {0} is not valid. Valid {0} length settings are either 128 bits, 192 bits, or 256 bits. + + + Deserialization of SecureString is currently only supported on Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/SessionStateProviderBaseStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/SessionStateProviderBaseStrings.pt-BR.resx new file mode 100644 index 00000000000..79e750f6d73 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/SessionStateProviderBaseStrings.pt-BR.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Definir Item + + + Item: {0} Valor: {1} + + + Limpar Item + + + Item: {0} + + + Remover Item + + + Item: {0} + + + Novo Item + + + Item: {0} Tipo: {1} Valor: {2} + + + Copiar Item + + + Item: {0} Destino: {1} + + + Renomear Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/SessionStateStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/SessionStateStrings.pt-BR.resx new file mode 100644 index 00000000000..06c82190adf --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/SessionStateStrings.pt-BR.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 the returned information because the information returned from the provider's Start method was for a different provider than the one passed. + + + Cannot process the returned information because the information returned from the provider's Start method was null. + + + Attempting to perform the GetItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the SetItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the SetItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the ClearItem operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the InvokeDefaultAction operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the InvokeDefaultAction operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the ItemExists operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the ItemExists operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the IsValidPath operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the IsItemContainer operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the RemoveItem operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the GetChildItems operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetChildItems operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetChildNames operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetChildNames operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the RenameItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the RenameItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the NewItem operation on the '{0}' provider failed for the path '{1}'. {2} + + + The dynamic parameters for the NewItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the HasChildItems operation on the '{0}' provider failed for the path '{1}'. {2} + + + Attempting to perform the CopyItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the CopyItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetParentPath operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the NormalizeRelativePath operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the MakePath operation operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the GetChildName operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the MoveItem operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the MoveItem operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the GetProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the SetProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the SetProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the ClearProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the ClearProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the NewProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the NewProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the RemoveProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the RemoveProperty operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the CopyProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the CopyProperty operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the MoveProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + The dynamic parameters for the MoveProperty operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the RenameProperty operation on the '{0}' provider failed for path '{1}'. {2} + + + Dynamic parameters for RenameProperty cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Content reader cannot be retrieved for the '{0}' provider for the path '{1}'. {2} + + + The dynamic parameters for the GetContentReader operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Content writer cannot be retrieved for the '{0}' provider for the path '{1}'. {2} + + + The dynamic parameters for the GetContentWriter operation cannot be retrieved for the '{0}' provider for path '{1}'. {2} + + + Unable to get content because it is a directory: '{0}'. Please use 'Get-ChildItem' instead. + + + Unable to write content because it is a directory: '{0}'. + + + There is no location history left to navigate backwards. + + + There is no location history left to navigate forwards. + + + The BoundedStack is empty. + + + Attempting to perform the ClearContent operation on the '{0}' provider failed for path '{1}'. {2} + + + Unable to clear content of '{0}' because it is a directory. Clear-Content is only supported on files. + + + The dynamic parameters for the ClearContent operation cannot be retrieved from the '{0}' provider for path '{1}'. {2} + + + Attempting to perform the GetSecurityDescriptor operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the SetSecurityDescriptor operation on the '{0}' provider failed for path '{1}'. {2} + + + Attempting to perform the Start operation on the '{0}' provider failed. {1} + + + Attempting to perform the InitializeDefaultDrives operation on the '{0}' provider failed. + + + Attempting to perform the NewDrive operation on the '{0}' provider failed for the drive with root '{1}'. {2} + + + Dynamic parameters for NewDrive cannot be retrieved for the '{0}' provider. {1} + + + The invocation of RemoveDrive on the '{0}' provider failed. {1} + + + Drive '{0}' cannot be removed because the provider '{1}' prevented it. + + + The path '{0}' referred to an item that was outside the base '{1}'. + + + The invocation of Seek on the '{0}' provider's content writer failed for path '{1}'. {2} + + + The invocation of Close on the '{0}' provider's content reader or writer failed for path '{1}'. {2} + + + The invocation of Read on the '{0}' provider's content reader failed for path '{1}'. {2} + + + The invocation of Write on the '{0}' provider's content writer failed for path '{1}'. {2} + + + The provider '{0}' cannot be used to get or set data using the variable syntax. {2} + + + The variable syntax cannot be used to get or set data in the provider. {2} + + + Alias is not writeable because alias {0} is read-only or constant and cannot be written to. + + + Cannot write to function {0} because it is read-only or constant. + + + Cannot overwrite variable {0} because it is read-only or constant. + + + Cannot access the variable '${0}' because it is a private variable. + + + Cannot access the command '{0}' because it is a private command. + + + Cannot access the command because it is a private command. + + + Cannot access the session state resource because it is a private resource. + + + Alias was not removed because alias {0} is constant or read-only. + + + Cannot remove function {0} because it is constant. + + + Cannot remove variable {0} because it is constant or read-only. If the variable is read-only, try the operation again specifying the Force option. + + + Alias {0} cannot be modified because it is constant. + + + Alias {0} cannot be modified because it is read-only. + + + Cannot modify function {0} because it is constant. + + + Cannot modify function {0} because it is read-only. + + + Alias {0} cannot be made constant after it has been created. Aliases can only be made constant at creation time. + + + Existing function {0} cannot be made constant. Functions can be made constant only at creation time. + + + Existing variable {0} cannot be made constant. Variables can be made constant only at creation time. + + + The AllScope option cannot be removed from the alias '{0}'. + + + The AllScope option cannot be removed from the function '{0}'. + + + The AllScope option cannot be removed from the variable '{0}'. + + + The function definition '{0}' contained a scope qualifier but no function name. + + + Cannot remove provider {0}. All drives associated with provider {0} must be removed before provider {0} can be removed. + + + Cannot process the drive name because the drive name contains one or more of the following characters that are not valid: ; ~ / \ . : + + + New drive creation failed because the provider does not allow the creation of the new drive. + + + The provided value '{0}' resolved to more than one location stack. + + + Cannot find location stack '{0}'. It does not exist or it is not a container. + + + Não é possível localizar o caminho '{0}' porque ele não existe. + + + Cannot find alias because alias '{0}' does not exist. + + + Cannot set the location because path '{0}' resolved to multiple containers. You can only set the location to a single container at a time. + + + Cannot process variable because variable path '{0}' resolved to multiple items. You can get or set the variable value only one item at a time. + + + Cannot find drive. A drive with the name '{0}' does not exist. + + + Cannot find a provider with the name '{0}'. + + + Cannot find a provider with the name '{0}'. The name is not in the proper format. A provider name can only be alphanumeric characters, or a PowerShell snap-in name that is followed by a single '\', followed by alphanumeric characters. + + + '{0}' resolved to more than one provider name. Possible matches include:{1}. + + + An error occurred attempting to create an instance of the provider. The provider type name of '{0}' could not be found in the assembly. + + + The specified provider name '{0}' cannot be used because it contains one or more of the following characters that are not valid: \ [ ] ? * : + + + An error occurred attempting to create an instance of the provider '{0}'. {1} + + + Cannot find a variable with the name '{0}'. + + + Cannot find a trace source with the name '{0}'. + + + A drive with the name '{0}' already exists. + + + A variable with name '{0}' already exists. + + + The alias is not allowed, because an alias with the name '{0}' already exists. + + + Cannot register the cmdlet provider because a cmdlet provider with the name '{0}' already exists. + + + The path does not refer to a file system path. + + + Global scope cannot be removed. + + + The scope number '{0}' exceeds the number of active scopes. + + + Cannot compare PSDriveInfo. A PSDriveInfo instance can be compared only to another PSDriveInfo instance. + + + The cmdlet provider cannot stream the results because no cmdlet was specified through which to stream the output. + + + The cmdlet provider cannot stream the results because no cmdlet was specified through which to stream the error. + + + Home location for this provider is not set. To set the home location, call "(get-psprovider '{0}').Home = 'path'". + + + The path is not in the correct format. Provider paths must contain a provider Id, followed by "::", followed by a provider specific path. + + + Cannot move the item because the destination path can resolve only to a single path. + + + Cannot move the item because the source and destination paths did not resolve to the same provider. + + + Cannot move the item because the source path points to one or more items and the destination path is not a container. Validate that the destination path is a container and try again. + + + Cannot move the item because the destination resolved to multiple paths. Specify a destination path that resolves to a single destination and try again. + + + Container cannot be copied onto existing leaf item. + + + Container cannot be copied to another container. The -Recurse or -Container parameter is not specified. + + + Source and destination path did not resolve to the same provider. + + + Cannot rename item because the path resolved to multiple items. Only one item can be renamed at a time. + + + The provider '{0}' cannot be used to resolve the path '{1}' because of an error in the provider. + + + Cannot use interface. The IContentCmdletProvider interface is not implemented by this provider. + + + Cannot use interface. The IPropertyCmdletProvider interface is not supported by this provider. + + + Cannot use interface. The IDynamicPropertyCmdletProvider interface is not implemented by this provider. + + + The NavigationCmdletProvider methods are not supported by this provider. + + + Provider methods not processed. The ContainerCmdletProvider methods are not supported by this provider. + + + Cannot call methods. The ItemCmdletProvider methods are not supported by this provider. + + + DriveCmdletProvider methods are not supported by this provider. + + + Provider operation stopped because the provider does not support this operation. + + + Provider operation stopped because the provider does not support the 'Depth' parameter. + + + Cannot call method. The content Seek method is not supported by this provider. + + + Cannot perform the ClearContent operation. The ClearContent operation is not supported by this provider. + + + The provider does not support the use of credentials. Perform the operation again without specifying credentials. + + + The FileSystem provider supports credentials only on the New-PSDrive cmdlet. Perform the operation again without specifying credentials. + + + The provider does not support transactions. Perform the operation again without the -UseTransaction parameter. + + + Cannot call method. The provider does not support the use of filters. + + + Cannot create drive. The provider does not support the use of credentials. + + + The item at path '{0}' already exists. + + + Cannot copy item. Item at the path '{0}' does not exist. + + + The item at the path '{0}' does not exist. + + + Drive that contains a view of the aliases stored in a session state + + + Drive that contains a view of the environment variables for the process + + + Drive that contains a view of the functions stored in a session state + + + Drive that contains a view of those variables stored in a session state + + + Drive that maps to the temporary directory path for the current user + + + Link '{0}' cannot be created because the target Value was not specified. + + + References to the null variable always return the null value. Assignments have no effect. + + + Maximum number of history objects to retain in a session + + + Cannot rename function because function {0} is read-only or constant. + + + Cannot rename alias because alias {0} is read-only or constant. + + + Cannot rename variable because variable {0} is read-only or constant. + + + Cannot set options on the local variable {0}. Use New-Variable to create a variable that allows options to be set. + + + Cmdlet {0} cannot be modified because it is read-only. + + + Cannot remove variable {0} because the variable has been optimized and is not removable. Try using the Remove-Variable cmdlet (without any aliases), or dot-sourcing the command that you are using to remove the variable. + + + Cannot overwrite variable {0} because the variable has been optimized. Try using the New-Variable or Set-Variable cmdlet (without any aliases), or dot-source the command that you are using to set the variable. + + + The parameters {0} and {1} cannot be used together. Please specify only one parameter. + + + The Tail parameter currently is supported only for the FileSystem provider. + + + The alias is not allowed, because a command with the name '{0}' and command type '{1}' already exists. + + + Cannot run software. Permission is denied. + + + '-{0}' and '-{1}' are mutually exclusive and cannot be specified at the same time. + + + The path '{0}' is not valid. Only absolute paths are supported on remote copy operations. + + + Cannot validate remote path '{0}'. + + + Cannot perform operation because the session {0} is set to {1}. + + + '{0}' parameter cannot be null or empty. + + + Session State Variables + + + Changing or creating the variable '{0}' scope to AllScope will be prevented in ConstrainedLanguage mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/StringDecoratedStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/StringDecoratedStrings.pt-BR.resx new file mode 100644 index 00000000000..0c6fbe5ad4b --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/StringDecoratedStrings.pt-BR.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Somente 'ANSI' ou 'PlainText' são compatíveis com este método. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/SubsystemStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/SubsystemStrings.pt-BR.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/SubsystemStrings.pt-BR.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/SuggestionStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/SuggestionStrings.pt-BR.resx new file mode 100644 index 00000000000..acee3004475 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/SuggestionStrings.pt-BR.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 + + + O comando "{0}" não foi encontrado, mas existe no local atual. +O PowerShell não carrega comandos do local atual por padrão (consulte 'Get-Help about_Command_Precedence'). + +Se você confiar nesse comando, execute o seguinte comando em vez disso: + + + Os comandos mais parecidos são: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/TabCompletionStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/TabCompletionStrings.pt-BR.resx new file mode 100644 index 00000000000..30debf0f2bf --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/TabCompletionStrings.pt-BR.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 tab completion result cannot be properly deserialized because the remote runspace does not contain a TypeTable instance. + + + Cannot access properties on a null instance of the type CompletionResult. + + + Bitwise NOT + + + Logical not. Negates the statement that follows it. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case sensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case sensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case sensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case sensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case sensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE only when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case sensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Returns TRUE when the left operand is not an instance of the specified .NET Framework type (right operand). + + + Returns TRUE when the left operand is an instance of the specified .NET Framework type (right operand). + + + Converts the left operand to the specified .NET Framework type (right operand). + + + Formats strings by using the format method of string objects. + + + Logical and. Returns TRUE when both statements are TRUE. + + + Bitwise AND + + + Logical or. TRUE when either or both statements are TRUE. + + + Bitwise OR (inclusive) + + + Logical exclusive or. Returns TRUE when one of the statements is TRUE and the other is FALSE. + + + Bitwise OR (exclusive) + + + Join - combine multiple strings into a single string. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Shift Left bit operator. Inserts zero in right-most bit position. + + + Shift Right bit operator. Inserts zero in the left-most bit position. For signed values, sign bit is preserved. + + + [string] +Specifies the name of the property being created. + + + [string] +Specifies the name of the property being created. + + + [scriptblock] +A script block used to calculate the value of the new property. + + + [string] +Define how the values are displayed in a column. +Valid values are 'left', 'center', or 'right'. + + + [string] +Specifies a format string that defines how the value is formatted for output. + + + [int] +Specifies the maximum column width in a table when the value is displayed. +The value must be greater than 0. + + + [int] +The depth key specifies the depth of expansion per property. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [String[]] +Specifies the log names to get events from. +Supports wildcards. + + + [String[]] +Specifies the event log providers to get events from. +Supports wildcards. + + + [String[]] +Specifies file paths to log files to get events from. +Valid file formats are: .etl, .evt, and .evtx + + + [Long[]] +Selects events with the specified keyword bitmasks. +The following are standard keywords: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Selects events with the specified event IDs. + + + [int[]] +Selects events with the specified log levels. +The following log levels are valid: +1: Critical +2: Error +3: Warning +4: Informational +5: Verbose + + + [datetime] +Selects events created after the specified date and time. + + + [datetime] +Selects events created before the specified date and time. + + + [string] +Selects events generated by the specified user. +This can either be a string representation of a SID or a domain and username in the format DOMAIN\USERNAME or USERNAME@DOMAIN + + + [string[]] +Selects events with any of the specified values in the EventData section. + + + [hashtable] +Excludes events that match the values specified in the hashtable. + + + [string] or [hashtable] +Specifies an array of PowerShell modules that the script requires. +Each element can either be a string with the module name as value or a hashtable with the following keys: +Name: Name of the module +GUID: GUID of the module +One of the following: +ModuleVersion: Specifies a minimum acceptable version of the module. +RequiredVersion: Specifies an exact, required version of the module. +MaximumVersion: Specifies the maximum acceptable version of the module. + + + [string] +Specifies a PowerShell edition that the script requires. +Valid values are "Core" and "Desktop" + + + [switch] +Specifies that PowerShell must be running as administrator on Windows. +This must be the last parameter on the #requires statement line. + + + [version] +Specifies the minimum version of PowerShell that the script requires. + + + Specifies that the script requires PowerShell 7+ to run. + + + Specifies that the script requires Windows PowerShell 5.1 to run. + + + [string] +Required. Specifies the module name. + + + [string] +Optional. Specifies the GUID of the module. + + + [string] +Specifies a minimum acceptable version of the module. + + + [string] +Specifies an exact, required version of the module. + + + [string] +Specifies the maximum acceptable version of the module. + + + A brief description of the function or script. +This keyword can be used only once in each topic. + + + A detailed description of the function or script. +This keyword can be used only once in each topic. + + + .PARAMETER <Parameter-Name> +The description of a parameter. +Add a .PARAMETER keyword for each parameter in the function or script syntax. + + + A sample command that uses the function or script, optionally followed by sample output and a description. +Repeat this keyword for each example. + + + The .NET types of objects that can be piped to the function or script. +You can also include a description of the input objects. + + + The .NET type of the objects that the cmdlet returns. +You can also include a description of the returned objects. + + + Additional information about the function or script. + + + The name of a related topic. +Repeat the .LINK keyword for each related topic. +The .Link keyword content can also include a URI to an online version of the same help topic. + + + The name of the technology or feature that the function or script uses, or to which it is related. + + + The name of the user role for the help topic. + + + The keywords that describe the intended use of the function. + + + .FORWARDHELPTARGETNAME <Command-Name> +Redirects to the help topic for the specified command. + + + .FORWARDHELPCATEGORY <Category> +Specifies the help category of the item in .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Specifies a session that contains the help topic. +Enter a variable that contains a PSSession object. + + + .EXTERNALHELP <XML Help File> +The .ExternalHelp keyword is required when a function or script is documented in XML files. + + + Specifies the path to a .NET assembly to load. + +using assembly <.NET-assembly-path> + + + Specifies a PowerShell module to load classes from. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifies a .NET namespace to resolve types from or a namespace alias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifies an alias for a .NET Type. + +using type <AliasName> = <.NET-type> + + + A normal string. + + + A string that contains unexpanded references to environment variables that are expanded when the value is retrieved. + + + Binary data in any form. + + + A 32-bit binary number. + + + An array of strings. + + + A 64-bit binary number. + + + An unsupported registry data type. + + + ',' - Comma + + + ', ' - Comma-Space + + + ';' - Semi-Colon + + + '; ' - Semi-Colon-Space + + + {0} - Newline + + + '-' - Dash + + + ' ' - Space + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/TransactionStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/TransactionStrings.pt-BR.resx new file mode 100644 index 00000000000..c3730677f85 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/TransactionStrings.pt-BR.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Não é possível usar a transação. Nenhuma transação está ativa. + + + Não é possível fazer commit da transação. Nenhuma transação está ativa. + + + Não é possível reverter a transação porque não há nenhuma transação ativa. + + + Não é possível reverter a transação. A transação já foi confirmada. + + + Não é possível fazer commit da transação. A transação já foi confirmada. + + + Não é possível fazer commit da transação. A transação foi revertida ou atingiu tempo limite. + + + Não é possível reverter a transação. A transação já foi revertida ou atingiu tempo limite. + + + Não é possível definir a transação ativa. Nenhuma transação foi criada. + + + Não é possível definir a transação ativa. A transação ativa foi revertida ou atingiu tempo limite. + + + Este cmdlet requer uma transação ativa. A transação atual já foi confirmada ou revertida. + + + Este cmdlet requer uma transação. Execute o comando novamente com o parâmetro -UseTransaction. + + + Não é possível usar a transação. Nenhuma transação foi iniciada. + + + Não é possível usar a transação. A transação foi confirmada. + + + Não é possível usar a transação. A transação foi revertida ou atingiu tempo limite. + + + Não é possível usar a transação. A transação atingiu tempo limite. + + + A transação base não foi definida. + + + A transação base não está ativa. + + + A transação base não pode ser definida depois que outras transações foram criadas. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/TypesXmlStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/TypesXmlStrings.pt-BR.resx new file mode 100644 index 00000000000..ca6e58ef89a --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/TypesXmlStrings.pt-BR.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : Erro: {3} + + + {0}, {1}({2}) : Erro no tipo "{3}": {4} + + + O nó "{0}" deve ocorrer apenas uma vez em "{1}". O nó pai, "{1}", será ignorado. + + + O nó {0} não é permitido. Os seguintes nós são permitidos: {1}. + + + O nó "{0}" não deve ter texto interno. + + + O nó "{0}" deve ter texto interno. + + + O nó "{0}" não foi encontrado. Ele deve ocorrer apenas uma vez em "{1}". O nó pai, "{1}", será ignorado. + + + O nó "Type" deve ter "Members", "TypeConverters" ou "TypeAdapters". + + + Não é possível criar uma instância do conversor de tipo para o tipo {0} devido à exceção: {1}. + + + O PowerShell não pode criar uma instância do adaptador de tipo para o tipo {0} por causa da seguinte exceção: {1}. + + + O tipo adaptado "{0}" não é válido. + + + O TypeConverter foi ignorado porque já ocorre. + + + O TypeAdapter foi ignorado porque já ocorre. + + + O tipo "{0}" deve ser TypeConverter ou PSTypeConverter. + + + O tipo "{0}" deve ser um PSPropertyAdapter. + + + O membro {0} já existe. + + + O nome de membro a seguir está reservado: {0} + + + Exceção: {0} + + + A ScriptProperty deve ter um getter ou um setter. + + + A CodeProperty deve ter um getter ou um setter. + + + {0}, {1} : {2} + + + O valor deve ser TRUE ou FALSE em vez de {0}. + + + O nó "{0}" não deve ter o atributo "{1}". + + + {0}, {1}: o arquivo não foi encontrado. + + + {0}, {1}: o arquivo foi ignorado porque já foi carregado por {2}. + + + Não é possível encontrar a chave do Registro: {0}{1}. Usando {2} para carregar os arquivos de configuração. + + + Não é possível encontrar o caminho {0} especificado na chave do Registro: {1}{2}. Usando {3} para carregar os arquivos de configuração. + + + {0}, {1}: o arquivo foi ignorado porque não tem a extensão de nome de arquivo ps1xml. + + + {0}, {1}: o arquivo foi ignorado devido à seguinte exceção de validação: {2}. + + + O membro "{0}" deve ser uma nota. + + + Não foi possível converter a nota "{0}":"{1}". + + + Não use o membro "{0}" aqui. + + + O membro "{0}" deve ter o tipo "{1}". + + + "{0}" deve estar presente quando "{1}" for "{2}" e "{3}" for "{4}". + + + Um erro anterior fez com que todas as configurações de serialização fossem ignoradas. + + + "{0}" não é um membro padrão e será ignorado. + + + O caminho {0} não é totalmente qualificado. Especifique um caminho de arquivo de tipo totalmente qualificado. + + + Não é possível atualizar a TypeTable porque ela pode ter sido criada fora do runspace. + + + Ocorreram erros ao carregar a TypeTable. Confira a propriedade Errors para acessar mensagens de erro detalhadas. + + + Erro no TypeData "{0}": {1} + + + "{0}" deve ter um valor para a propriedade "{1}". + + + "{0}" não deve ter uma cadeia de caracteres nula ou vazia em sua propriedade "{1}". + + + O tipo "{0}" não foi encontrado. O valor do nome do tipo deve ser o nome completo do tipo. Verifique o nome do tipo e execute o comando novamente. + + + O TypeData deve ter "Members", "TypeConverters", "TypeAdapters" ou "StandardMembers". + + + Uma tabela de tipo compartilhada não pode ser atualizada com mais de uma entrada. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/VerbDescriptionStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/VerbDescriptionStrings.pt-BR.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/VerbDescriptionStrings.pt-BR.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/pt-BR/WildcardPatternStrings.pt-BR.resx b/src/System.Management.Automation/resources/pt-BR/WildcardPatternStrings.pt-BR.resx new file mode 100644 index 00000000000..5c54ac9a939 --- /dev/null +++ b/src/System.Management.Automation/resources/pt-BR/WildcardPatternStrings.pt-BR.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 + + + O padrão de caractere curinga especificado não é válido: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/Authenticode.ru.resx b/src/System.Management.Automation/resources/ru/Authenticode.ru.resx new file mode 100644 index 00000000000..77460e1e326 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/Authenticode.ru.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 + + + Невозможно загрузить файл {0}, так как вы решили не запускать это программное обеспечение сейчас. + + + Невозможно загрузить файл {0}, так как вы решили никогда не запускать программное обеспечение от этого издателя. + + + Файл {0} опубликован {1}. Этот издатель явно не является доверенным в вашей системе. Скрипт не будет запущен в системе. Для получения дополнительных сведений выполните команду "get-help about_signing". + + + Невозможно загрузить файл {0}, так как выполнение скриптов отключено в этой системе. Дополнительные сведения см. в статье about_Execution_Policies на странице https://go.microsoft.com/fwlink/?LinkID=135170. + + + Невозможно загрузить файл {0}. {1}. + + + Невозможно загрузить файл {0}, так как его выполнение заблокировано политиками ограниченного использования программ, например созданными с помощью групповой политики. + + + Невозможно загрузить файл {0}, так как не удалось прочитать его содержимое. + + + Не удается подписать код. Указанный сертификат не подходит для подписания кода. + + + Не удается подписать код. URL-адрес сервера TimeStamp должен быть указан полностью в формате http://<server url> или https://<server url>. + + + Не удается подписать код. Хэш-алгоритм не поддерживается. + + + Вы действительно хотите запускать программы от этого недоверенного издателя? + + + Файл {0} опубликован {1} и не является доверенным в вашей системе. Запускайте скрипты только от доверенных издателей. + + + Программное обеспечение {0} опубликовано неизвестным издателем. Не рекомендуется запускать это программное обеспечение. + + + Предупреждение системы безопасности + + + Запускайте только скрипты, которым вы доверяете. Хотя скрипты из Интернета могут быть полезны, этот скрипт может нанести вред вашему компьютеру. Если вы доверяете этому скрипту, используйте командлет Unblock-File, чтобы разрешить его выполнение без этого предупреждающего сообщения. Вы хотите запустить {0}? + + + Н&икогда не запускать + + + Не запускать скрипт от этого издателя сейчас и не предлагать запускать этот скрипт в будущем. Дальнейшие попытки запустить этот скрипт будут завершаться без сообщения об ошибке. + + + &Не выполнять + + + Не запускать скрипт от этого издателя сейчас и предлагать запускать этот скрипт в будущем. + + + В&ыполнить однократно + + + Запустить скрипт от этого издателя сейчас и предлагать запускать этот скрипт в будущем. + + + &Всегда выполнять + + + Запустить скрипт от этого издателя сейчас и не предлагать запускать этот скрипт в будущем. + + + &Приостановить + + + Приостановить текущий конвейер и вернуться в командную строку. По завершении введите exit, чтобы возобновить работу. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/AuthorizationManagerBase.ru.resx b/src/System.Management.Automation/resources/ru/AuthorizationManagerBase.ru.resx new file mode 100644 index 00000000000..ea6398976eb --- /dev/null +++ b/src/System.Management.Automation/resources/ru/AuthorizationManagerBase.ru.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 + + + Сбой проверки AuthorizationManager. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/AutomationExceptions.ru.resx b/src/System.Management.Automation/resources/ru/AutomationExceptions.ru.resx new file mode 100644 index 00000000000..726992f2e51 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/AutomationExceptions.ru.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Не удается обработать аргумент, так как значение аргумента {0} недопустимо. Измените значение аргумента {0} и повторите операцию. + + + Не удается обработать аргумент, так как значение параметра {0} недопустимо. Допустимые значения: Global, Local, Script или число относительно текущей области (от 0 до количества областей, где 0 — это текущая область, а 1 — ее родительская область). Измените значение параметра {0} и повторите операцию. + + + Не удается обработать аргумент, так как значение аргумента {0} имеет значение NULL. Измените значение аргумента {0} на ненулевое значение. + + + Не удается обработать аргумент, так как значение аргумента {0} вне диапазона. Измените значение аргумента {0} на значение в пределах диапазона. + + + Не удается выполнить операцию, так как операция {0} недопустима. Удалите операцию {0} или выясните, почему она недопустима. + + + Не удается выполнить операцию, так как операция {0} не реализована. + + + Не удается выполнить операцию, так как операция {0} не поддерживается. + + + Не удается выполнить операцию, так как объект {0} уже удален. + + + Невозможно вызвать блок сценария, так как он содержит более одного предложения. Метод Invoke() можно использовать только для блоков сценария, содержащих одно предложение. + + + Невозможно преобразовать блок сценария, так как он содержит более одного предложения. Выражения или структуры управления не разрешены. Убедитесь, что блок сценария содержит ровно один конвейер или команду. + + + Пустой блок сценария нельзя преобразовать. Убедитесь, что блок сценария содержит ровно один конвейер или команду. + + + Преобразовать можно только блок сценария, содержащий ровно один конвейер или команду. Выражения или структуры управления не разрешены. Убедитесь, что блок сценария содержит ровно один конвейер или команду. + + + Блок сценария, содержащий оператор trap верхнего уровня, нельзя преобразовать. + + + Не удается создать объект PowerShell для блока сценария (ScriptBlock), который обращается к переменным, не объявленным в блоке param(...). Имя необъявленной переменной: {0}. + + + Невозможно создать объект PowerShell для ScriptBlock, вычисляющего неконстантные выражения. Неконстантное выражение: {0}. + + + Невозможно создать объект PowerShell для ScriptBlock, вычисляющего динамические выражения. Динамическое выражение: {0}. + + + Невозможно создать объект PowerShell для ScriptBlock, который пытается передавать другие блоки сценария в значениях аргументов. + + + Не удается создать объект PowerShell для ScriptBlock, который вызывает конвейеры, команды или функции для вычисления аргументов основного конвейера. + + + Не удается сгенерировать объект PowerShell для блока сценариев, использующего точечный поиск. + + + Невозможно создать объект PowerShell для ScriptBlock, вызывающего другие блоки сценария. + + + Блок сценария нельзя преобразовать в объект PowerShell, так как он содержит запрещенные операторы перенаправления. + + + Невозможно создать объект PowerShell для ScriptBlock, не имеющего связанного контекста операции. + + + Команда была остановлена пользователем. + + + Объект {0} имеет неверный тип для возврата из блока dynamicparam. Блок dynamicparam должен возвращать либо $null, либо объект типа [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + Блок сценария нельзя преобразовать в открытый универсальный тип. Определите подходящий закрытый универсальный тип и повторите попытку. + + + Невозможно создать объект PowerShell для ScriptBlock, который начинает конвейер с выражением. + + + Невозможно получить значение переменной $using:{0}, так как оно не задано в локальном сеансе. + + + Не удается получить значение выражения Using {0} в указанном словаре переменных. При создании экземпляра PowerShell из блока сценария выражение Using не может содержать операцию индексирования или доступ к элемента. + + + Точечное подключение скомпилированного блока сценария + + + Вызов блока сценария {0} в текущей области будет запрещен в режиме ограниченного языка. Режим языка сценария: {1}, режим языка контекста: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CatalogStrings.ru.resx b/src/System.Management.Automation/resources/ru/CatalogStrings.ru.resx new file mode 100644 index 00000000000..e24ff3a3171 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CatalogStrings.ru.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Не удалось создать файл определения каталога. + + + Добавление файла "{0}" в каталог. Относительный путь к файлу в каталоге: "{1}". + + + Пропуск проверки файла {0} из каталога. + + + В каталоге найден файл {0} с хэшем {1}. + + + Пути к каталогу содержат несколько файлов с одинаковым относительным путем {0}. + + + Найден файл {0} на диске с хэшем {1}. + + + Пропуск проверки файла {0} из пути. + + + Не удалось получить дескриптор контекста администратора каталога для заданного алгоритма хэширования {0}. + + + Не удалось создать хэш для файла {0}. + + + Не удалось открыть файл каталога {0}. + + + Неверная версия каталога. Мы поддерживаем только версию каталога {0} и версию {1}. + + + Не удалось открыть файл определения каталога. + + + Найдено несколько записей элемента файла {0} в каталоге. + + + Не удалось найти имя файла или путь для элемента каталога {0}. + + + Не удалось найти файл {0} в хэш. + + + Не удалось прочитать файл {0}, чтобы вычислить его хэш. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CimInstanceTypeAdapterResources.ru.resx b/src/System.Management.Automation/resources/ru/CimInstanceTypeAdapterResources.ru.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CimInstanceTypeAdapterResources.ru.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CmdletizationCoreResources.ru.resx b/src/System.Management.Automation/resources/ru/CmdletizationCoreResources.ru.resx new file mode 100644 index 00000000000..6d5c27a3ae4 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CmdletizationCoreResources.ru.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Командлеты над классом "{0}" + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Не удается обработать XML определения для следующего файла: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + Не удается обработать атрибут ObjectModelWrapper. Тип {0} определяет несколько наборов параметров. Убедитесь, что в XML-файле определения командлета в атрибуте ObjectModelWrapper указан допустимый тип, и повторите попытку. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Не удается обработать атрибут ObjectModelWrapper. Тип {0} является открытым универсальным типом. Убедитесь, что в XML-файле определения командлета в атрибуте ObjectModelWrapper указан допустимый тип, и повторите попытку. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + Не удается обработать атрибут ObjectModelWrapper. Тип {0} не является производным от следующего класса: {1}. Убедитесь, что в XML-файле определения командлета в атрибуте ObjectModelWrapper указан допустимый тип, и повторите попытку. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + Не удается обработать атрибут ObjectModelWrapper. Тип {0} определяет параметр командлета {1} с атрибутивным параметром {2}, который игнорируется. Убедитесь, что в XML-файле определения командлета в атрибуте ObjectModelWrapper указан допустимый тип, и повторите попытку. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + Не удается определить параметр {0} для командлета {1}. Имя параметра уже определено классом {2}. Измените имя параметра в XML-файле определения командлета и повторите попытку. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + Не удается определить параметр {0} для командлета {1}. Имя параметра уже определено в элементе XML {2}. Измените имя параметра в XML-файле определения командлета, а затем попробуйте снова. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + Значение атрибута EnumName не соответствует допустимому идентификатору C#: {0}. Проверьте атрибут EnumName в XML-файле определения командлета, а затем повторите попытку. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + Не удается обработать <Enum EnumName="{0}" ... > элемент. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + Удаленный компьютер вернул недействительный файл CDXML. Следующий адаптер командлетов не поддерживается для импорта модуля CDXML с удаленного компьютера: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CommandBaseStrings.ru.resx b/src/System.Management.Automation/resources/ru/CommandBaseStrings.ru.resx new file mode 100644 index 00000000000..95efced2386 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CommandBaseStrings.ru.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Продолжить эту операцию? + + + Д&а + + + Продолжить выполнять только следующий шаг этой операции. + + + Да для &всех + + + Продолжить выполнять все шаги этой операции. + + + &Нет + + + Пропустить эту операцию и перейти к следующей. + + + Нет для всех + + + Пропустить эту операцию и все последующие операции. + + + Остановить эту команду. + + + &Остановить команду + + + &Приостановить + + + Приостановить текущий конвейер и вернуться в командную строку. Введите "{0}", чтобы возобновить работу конвейера. + + + + Программа "{0}" завершилась с ненулевым кодом выхода: {1} ({2}). + + + Выполнение операции "{0}" для целевого объекта "{1}". + + + Что если: {0} + + + Действительно выполнить это действие? +{0} + + + Подтвердить + + + Выполнение команды остановлено, поскольку для переменной предпочтения "{0}" или для общего параметра задано значение "Stop": {1} + + + Выполнение команды остановлено, поскольку для переменной предпочтения "{0}" или для общего параметра задано значение "Stop". + + + Выполняющаяся команда остановлена, поскольку для переменной предпочтения "{0}" или для общего параметра заданно значение: "{1}". Это недопустимое значение. + + + Выполняющаяся команда остановлена, поскольку пользователь выбрал параметр "Остановить". + + + Выполняющаяся команда остановлена, поскольку пользователь прервал ее работу. + + + Нельзя вызвать напрямую командлеты, производные от PSCmdlet. + + + Командлет "{0}" не поддерживает параметр "{1}" в удаленном сеансе. + + + Общее количество: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Предполагаемое общее количество: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Неизвестное общее количество + Reviewed by TArcher on 2010-07-20 + + + команда "{0}" + + + Элемент {0} устарел. {1} + + + Сбой вызова выполнения с кодом ошибки {0} для командной строки: {1} + + + Команда "{0}" не найдена. Указанная команда должна быть исполняемым файлом. + + + Проверка обработки блока сценария Dot-Source + + + Обработка Dot-Source для блока сценария "{0}" завершится сбоем в режиме ограниченного языка, поскольку его режим языка "{1}" не совпадает с текущим режимом языка "{2}". + + + Поиск команд + + + Команда "{0}" в модуле "{1}" не является доверенной и будет недоступна в режиме ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ConsoleInfoErrorStrings.ru.resx b/src/System.Management.Automation/resources/ru/ConsoleInfoErrorStrings.ru.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ConsoleInfoErrorStrings.ru.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CoreClrStubResources.ru.resx b/src/System.Management.Automation/resources/ru/CoreClrStubResources.ru.resx new file mode 100644 index 00000000000..9b9bd19baa3 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CoreClrStubResources.ru.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Имя переменной среды не может содержать знак равенства. + + + Слишком длинное имя или значение переменной среды. + + + Первый символ в строке — символ null. + + + Строка не может быть нулевой длины. + + + Не удалось получить имя компьютера. + + + Не удалось получить доменное имя текущего пользователя. + + + Неизвестная ошибка: "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CredUI.ru.resx b/src/System.Management.Automation/resources/ru/CredUI.ru.resx new file mode 100644 index 00000000000..35f3b06c933 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CredUI.ru.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Запрос учетных данных PowerShell + + + Введите свои учетные данные. + + + Введите свои учетные данные. + + + Максимальная длина подписи в символах — {0}. + + + Максимальная длина сообщения в символах — {0}. + + + Максимальная длина имени пользователя в символах — {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/Credential.ru.resx b/src/System.Management.Automation/resources/ru/Credential.ru.resx new file mode 100644 index 00000000000..6f6393d787c --- /dev/null +++ b/src/System.Management.Automation/resources/ru/Credential.ru.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 + + + Не удается сериализовать учетные данные. Если эта команда запускает рабочий процесс, учетные данные не могут быть сохранены, поскольку процесс, в котором запускается рабочий процесс, не имеет разрешения на сериализацию учетных данных. + +— Если рабочий процесс запущен в PSSession на локальном компьютере, добавьте параметр EnableNetworkAccess к команде, создавшей сессию. +— Если рабочий процесс запущен в PSSession на удаленном компьютере, добавьте параметр Authentication со значением CredSSP к команде, создавшей сессию. Или подключитесь к конфигурации сессии, в которой значение свойства RunAsUser задано. + + + Значение поля UserName имеет неправильный формат. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/CredentialAttributeStrings.ru.resx b/src/System.Management.Automation/resources/ru/CredentialAttributeStrings.ru.resx new file mode 100644 index 00000000000..76c13967bb8 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/CredentialAttributeStrings.ru.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 + + + Запрос учетных данных PowerShell + + + Введите свои учетные данные. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/DebuggerStrings.ru.resx b/src/System.Management.Automation/resources/ru/DebuggerStrings.ru.resx new file mode 100644 index 00000000000..f56a6c225fe --- /dev/null +++ b/src/System.Management.Automation/resources/ru/DebuggerStrings.ru.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Точка останова по переменной в "${0}" (доступ {1}) + + + Точка останова по переменной в "{0}:${1}" (доступ {2}) + + + Точка останова по строке на "{0}:{1}" + + + Точка останова по строке на "{0}:{1}, {2}" + + + Точка останова по команде в "{0}" + + + Точка останова по команде в "{0}:{1}" + + + Точка останова {0} не будет достигнута + + + {0}, {1,-16} Выполнить один шаг (с заходом в функции, скрипты и т. д.) + + + {0}, {1,-16} Перейти к следующему оператору (шаг с обходом функций, скриптов и т. д.) + + + {0}, {1,-16} Выйти из текущей функции, скрипта и т. д. + + + {0}, {1,-16} Продолжить выполнение + + + {0}, {1,-16} Остановить выполнение и выйти из отладчика + + + {0}, Get-PSCallStack Отобразить стек вызовов + + + {0}, {1,-16} Перечислить исходный код текущего скрипта. + + + Используйте "list", чтобы начать с текущей строки, "list <m>" + + + чтобы начать со строки <m>, и "list <m> <n>", чтобы вывести <n> + + + строки, начиная со строки <m> + + + <enter> Повторить последнюю команду, если она была {0}, {1} или {2} + + + {0}, {1,-16} выводит это справочное сообщение. + + + Для получения инструкций по настройке запроса отладчика введите "help about_prompt". + + + +Текущий сеанс не поддерживает отладку; операция будет продолжена. + + + + + {0}: строка {1} + + + Исходный код недоступен. + + + Начальная строка должна быть положительным целым числом не больше {0} + + + Число строк должно быть положительным целым числом. + + + <Без файла> + + + в {0}, {1}: строка {2} + + + Отладчик не может обрабатывать команды, если не находится в состоянии Stopped. + + + SetDebugAction не реализовано для отладчика локальных скриптов. + + + Отладчик не может задать действие продолжения, так как отладчик в удаленном сеансе не находится в состоянии Stopped. + + + Задание невозможно отладить, так как отладчик сейчас занят. + + + Указанное задание и все дочерние задания были проверены, но задания, которые можно отладить, не найдены. Чтобы отладить задание или дочернее задание, оно должно поддерживать отладку и находиться в состоянии выполнения. + + + Отладчик нельзя включить для пошагового режима, так как он отключен, а для режима отладки задано значение None. + + + Невозможно отладить пространство выполнения, так как узловой отладчик сейчас занят. + + + Невозможно отладить пространство выполнения. Отладчик пространства выполнения сейчас отключен (DebugMode имеет значение "None"). + + + Невозможно выполнить отладку пространства выполнения, которое не находится в открытом состоянии. Данное состояние пространства выполнения: {0}. + + + Невозможно отладить пространство выполнения. У пространства выполнения {0} нет связанного отладчика. + + + Отладчик уже переопределен. + + + Невозможно поместить объект отладчика сам в себя. + + + Команда {0} не поддерживается для удаленного использования в версии PowerShell, запущенной в удаленном пространстве выполнения. + + + Процесс + + + {0}, {1,-16} Продолжить выполнение и отключить отладчик. + + + Команда отключения отладчика неприменима. Команда отключения применяется только при отладке заданий и пространств выполнения с помощью командлетов Debug-Job или Debug-Runspace. + + + Недопустимый идентификатор пространства выполнения: {0} + + + Не удалось получить пространство выполнения. + + + Необходимо указать точку останова или список точек останова. + + + BreakpointList содержит элемент, который не является точкой останова. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/DescriptionsStrings.ru.resx b/src/System.Management.Automation/resources/ru/DescriptionsStrings.ru.resx new file mode 100644 index 00000000000..2c0d32236de --- /dev/null +++ b/src/System.Management.Automation/resources/ru/DescriptionsStrings.ru.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 + + + {0} не может быть пустым или иметь значение NULL. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/DiscoveryExceptions.ru.resx b/src/System.Management.Automation/resources/ru/DiscoveryExceptions.ru.resx new file mode 100644 index 00000000000..4be4daf108f --- /dev/null +++ b/src/System.Management.Automation/resources/ru/DiscoveryExceptions.ru.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 + + + Имя командлета "{0}" не может быть проверено, поскольку оно имеет неправильный формат. Названия командлетов должны содержать глагол и существительное, разделенные дефисом, например, "Get-Process". + + + Параметр "{0}" объявлен в наборе параметров "{1}" несколько раз. + + + Псевдоним "{0}" объявлен несколько раз. + + + Не удалось объявить параметр. Параметры можно объявлять только для полей и свойств. + + + Не удается обработать командлет. Имя командлета должно состоять из пары глагола и существительного, разделенных дефисом (-). + + + Термин "{0}" не распознается как имя, которое является именем для выполнения, функции, файла сценария или исполняемой программы. +Проверьте правильность написания имени, а если включен путь, то проверьте правильность пути и повторите попытку. + + + Аргумент "{0}" не распознается как командлет: {1} + + + Аргумент "{0}" не распознается как командлет, возможно, потому что он не является производным от классов Cmdlet или PSCmdlet: {1} + + + Не удается разрешить псевдоним "{0}", поскольку он относится к термину "{1}", который не распознается как командлет, функция, исполняемая программа или файл сценария. Проверьте термин и повторите попытку. + + + Параметр "{0}" со значением "{1}" не может быть обработан, поскольку он не является командлетом и не может быть обработан обработчиком команд. + + + Командлет с именем "{0}" уже существует. Имена командлетов должны быть уникальными. + + + Поставщик с именем "{0}" уже существует. Поставщики командлетов должны иметь уникальные имена. + + + Сборка с именем "{0}" уже существует. Имена сборок должны быть уникальными. + + + Сценарий с именем "{0}" уже существует. Имена сценариев должны быть уникальными. + + + Не обеспечить обработку #requires, так как он имеет неправильный формат. +В #requires должен быть один из следующих форматов: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + Скрипт "{0}" не может быть запущен, поскольку он содержит оператор "#requires" с идентификатором оболочки {1}, несовместимым с текущей оболочкой. Для запуска этого сценария необходимо использовать оболочку, расположенную в "{2}". + + + Скрипт "{0}" не может быть запущен, поскольку он содержит оператор "#requires" с идентификатором оболочки {1}, несовместимым с текущей оболочкой. + + + Сценарий "{0}" не может быть запущен, поскольку он содержит оператор "#requires" для PowerShell {1}. Требуемая для выполнения сценария версия PowerShell не соответствует текущей запущенной версии PowerShell {2}. + + + Сценарий "{0}" не может быть запущен, поскольку он содержит оператор "#requires" для версий PowerShell "{1}". Требуемая для выполнения сценария версия PowerShell не соответствует текущей используемой версии PowerShell {2}. + + + Сценарий "{0}" не может быть запущен, поскольку отсутствуют следующие подключаемые модули, указанные в операторах "#requires" сценария: {1}. + + + В операторе #requires указан только идентификатор оболочки. Операторы #Requires должны указывать требуемую оснастку PowerShell при запуске в PowerShell. + + + Сценарий "{0}" не может быть запущен, поскольку содержит оператор "#requires" для запуска от имени администратора. Текущая сессия PowerShell запущена не от имени администратора. Запустите PowerShell, используя параметр "Запуск от имени администратора", а затем попробуйте запустить сценарий еще раз. + + + {0} (версия {1}) + + + Не удалось получить команду, поскольку параметр ArgumentList можно указать только при получении отдельного командлета или сценария. + + + Имя параметра "{0}" зарезервировано для дальнейшего использования. + + + Сценарий "{0}" не может быть запущен, поскольку отсутствуют следующие модули, указанные в операторах "#requires" сценария: {1}. + + + Команда "{0}" была найдена в модуле "{1}", но модуль не удалось загрузить. Для получения более подробной информации выполните команду "Import-Module {1}". + + + Команда "{0}" найдена в модуле "{1}", но не удалось загрузить модуль из-за следующей ошибки: [{2}] +Для получения более подробной информации выполните команду "Import-Module {1}". + + + Не удалось загрузить модуль "{0}". Для получения дополнительных сведений выполните команду "Import-Module {0}". + + + Ни одна из соответствующих команд не содержит параметра с именем "{0}". Проверьте правильность написания имени параметра и попробуйте снова. + + + Невозможно выполнить команду с помощью dot-source, поскольку она определена в другом языковом режиме. Чтобы выполнить эту команду без импорта ее содержимого, опустите оператор ".". + + + Параметры ShowCommandInfo и Syntax нельзя указывать одновременно. + + + Эта команда скрипта отключена, если включена экспериментальная функция "{0}". + + + Эта команда сценария отключена, если экспериментальная функция "{0}" выключена. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/EnumExpressionEvaluatorStrings.ru.resx b/src/System.Management.Automation/resources/ru/EnumExpressionEvaluatorStrings.ru.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/ru/EnumExpressionEvaluatorStrings.ru.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ErrorCategoryStrings.ru.resx b/src/System.Management.Automation/resources/ru/ErrorCategoryStrings.ru.resx new file mode 100644 index 00000000000..4b51fd48a38 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ErrorCategoryStrings.ru.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Обнаружена взаимоблокировка: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + Ошибка подключения: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Нераспознанная категория ошибки {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ErrorPackage.ru.resx b/src/System.Management.Automation/resources/ru/ErrorPackage.ru.resx new file mode 100644 index 00000000000..ee790ed4283 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ErrorPackage.ru.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 + + + {0}: {1} + + + Пустой текст ошибки для ошибки "{0}": "{1}" + + + Объект "{0}" отмечен как ошибка. + + + Значение {0} не поддерживается для переменной ActionPreference. Указанное значение следует использовать только как значение параметра настройки, и его заменено значением по умолчанию. Дополнительные сведения см. в разделе справки, "about_Preference_Variables". + + + Значение {0} ActionPreference зарезервировано для использования в будущем и в настоящее время не поддерживается. Подробнее о привилегированных переменных см. в разделе справки "about_Preference_Variables". + + + Значение {0} ActionPreference зарезервировано для использования в будущем и в настоящее время не поддерживается. В переменной {1} оно было заменено значением по умолчанию {2}. Подробнее о привилегированных переменных см. в разделе справки "about_Preference_Variables". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/EtwLoggingStrings.ru.resx b/src/System.Management.Automation/resources/ru/EtwLoggingStrings.ru.resx new file mode 100644 index 00000000000..fb82c0ed53e --- /dev/null +++ b/src/System.Management.Automation/resources/ru/EtwLoggingStrings.ru.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Команда {0} {1}. + + + Состояние подсистемы изменено с {0} на {1}. + + + Полный идентификатор ошибки = {0} + + + Сообщение об ошибке = {0} + + + Рекомендуемое действие = {0} + + + Политика выполнения + + + Команда задания = {0} + + + Идентификатор задания = {0} + + + Идентификатор экземпляра задания = {0} + + + Расположение задания = {0} + + + Имя задания = {0} + + + Состояние задания = {0} + + + Имя команды = + + + Путь команды = + + + Тип команды = + + + Версия подсистемы = + + + ИД узла = + + + Имя узла = + + + Ведущее приложение = + + + Версия узла = + + + ИД конвейера = + + + ИД пространства выполнения = + + + Имя скрипта = + + + Порядковый номер = + + + Уровень серьезности = + + + Идентификатор оболочки = + + + Время = + + + Пользователь = + + + Подключенный пользователь = + + + Задание NULL + + + Имя поставщика + + + Поставщик {0} изменил состояние на {1}. + + + Выполнение скрипта: {0}. + + + Переменная {0} изменилась с {1} на {2}. + + + Переменная {0} изменена на {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/EventResource.ru.resx b/src/System.Management.Automation/resources/ru/EventResource.ru.resx new file mode 100644 index 00000000000..689edfefcec --- /dev/null +++ b/src/System.Management.Automation/resources/ru/EventResource.ru.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Сообщение для события с идентификатором PowerShell.Core.Instrumentation.man не найдено. + + + Запланированное задание {0} запущено в {1} + + + + Запланированное задание завершено {0} в {1} состоянии {2} + + + + Исключение запланированного задания {0}: + Сообщение: {1} + StackTrace: {2} + InnerException: {3} + + + + Инициализация экспериментальных функций: игнорировать экспериментальную функцию "{0}" из файла конфигурации. {1} + + + Инициализация экспериментальных функций: не удалось прочитать файл конфигурации. + Исключение: {0} + Сообщение: {1} + StackTrace: {2} + + + + Подключаемый модуль рабочего процесса загружен. + EndpointName: {0} + Пользователь: {1} + HostingMode: {2} + Протокол: {3} + Конфигурация: + {4} + + + Начато выполнение рабочего процесса. + WorkflowId: {0} + ManagedNodes: {1} + + + Состояние рабочего процесса изменено. + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + Подключаемый модуль рабочего процесса запрашивается для завершения работы. + EndpointName: {0} + + + Подключаемый модуль рабочего процесса перезапущен. + EndpointName: {0} + + + Рабочий процесс возобновляется. + WorkflowId: {0} + + + Превышена квота, установленная для конечной точки. + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + Рабочий процесс возобновлен. + WorkflowId: {0} + + + Создан пул пространства выполнения рабочего процесса. + WorkflowId: {0} + ManagedNode: {1} + + + Действие поставлено в очередь на выполнение. + WorkflowId: {0} + ActivityName: {1} + + + Запущено выполнение действия. + ActivityName: {0} + ActivityTypeName: {1} + + + Рабочий процесс импортируется из файла XAML. + WorkflowId: {0} + XamlFile: {1} + + + Рабочий процесс импортирован из XAML-файла. + WorkflowId: {0} + XamlFile: {1} + + + Не удалось импортировать рабочий процесс из XAML-файла из-за ошибки. + WorkflowId: {0} + ErrorDescription: {1} + + + Начата проверка рабочего процесса. + WorkflowId: {0} + + + Проверка рабочего процесса выполнена. + WorkflowId: {0} + + + Сбой проверки рабочего процесса из-за ошибки. + WorkflowId: {0} + + + Действие рабочего процесса проверено. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Не удалось проверить действие рабочего процесса. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Сбой выполнения действия. + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Изменилась доступность пространства выполнения. + RunspaceId: {0} + Доступность: {1} + + + Состояние пространства запуска изменено. + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + Рабочий процесс загружен для выполнения. + WorkflowId: {0} + + + Рабочий процесс выгружен. + WorkflowId: {0} + + + Выполнение рабочего процесса отменено. + WorkflowId: {0} + + + Выполнение рабочего процесса прервано. + WorkflowId: {0} + + + Операция очистки рабочего процесса выполнена. + WorkflowId: {0} + + + Постоянно хранимый рабочий процесс загружен с диска. + WorkflowId: {0} + Путь: {1} + + + Данные рабочего процесса удалены с диска. + WorkflowId: {0} + Путь: {1} + + + Запуск задания удаления. + JobId: {0} + + + Состояние задания изменено. + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + Ошибка задания. + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + Создано задание для рабочего процесса (дочернее задание). + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + Родительское задание создано для рабочего процесса. + JobId: {0} + + + Все необходимые задания созданы для выполнения рабочего процесса. + JobId: {0} + WorkflowId: {1} + + + Дочернее задание удалено для рабочего процесса. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + При удалении задания произошла ошибка. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Ошибка: {3} + + + Загрузка рабочего процесса для выполнения. + WorkflowId: {0} + + + Выполнение рабочего процесса завершено. + WorkflowId: {0} + + + Отмена выполнения рабочего процесса. + WorkflowId: {0} + + + Прерывание выполнения рабочего процесса. + WorkflowId: {0} + Причина: {1} + + + Выгрузка рабочего процесса. + WorkflowId: {0} + + + Принудительное завершение рабочего процесса запущено. + WorkflowId: {0} + + + Принудительное завершение рабочего процесса завершено. + WorkflowId: {0} + + + Произошла ошибка при принудительном закрытии рабочего процесса. + WorkflowId: {0} + ErrorDescription: {1} + + + Сохранение рабочего процесса на диск. + WorkflowId: {0} + PersistPath: {1} + + + Рабочий процесс сохраняется на диске. + WorkflowId: {0} + + + Выполнение действия завершено. + ActivityName: {0} + + + Ошибка выполнения рабочего процесса. + WorkflowId: {0} + ErrorDescription: {1} + + + Зарегистрирована новая конечная точка PowerShell. + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + Изменена конфигурация конечной точки. + EndpointName: {0} + ModifiedBy: {1} + + + Настройка конечной точки не зарегистрирована. + EndpointName: {0} + UnregisteredBy: {1} + + + Конфигурация конечной точки отключена. + EndpointName: {0} + DisabledBy: {1} + + + Конфигурация конечной точки включена. + EndpointName: {0} + EnabledBy: {1} + + + Запущено внепроцессное пространство выполнения. + Команда: {0} + + + В процессе выполнения рабочего процесса применялось автоматическое распределение параметров. + Параметры: {0} + Компьютеры: {1} + + + Обработчик рабочих процессов запущен. + EndpointName: {0} + + + Диспетчер рабочего процесса с + CheckpointPath: {0} + ConfigProviderId: {1} + Имя пользователя: {2} + Путь: {3} + + + Имя компьютера $null или . разрешается в LocalHost + + + Преобразование в схему по умолчанию HTTP + + + Имя удаленной оболочки преобразовано в значение по умолчанию PowerShellCore + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + Создание текста Scriptblock ({0} из {1}): +{2} + +ScriptBlock ID: {3} +Путь: {4} + + + Запущен вызов ИД ScriptBlock: {0} +Идентификатор пространства выполнения: {1} + + + Выполнение запроса с идентификатором ScriptBlock выполнено: {0} +Идентификатор пространства выполнения: {1} + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + {2} + +Контекст: +{0} + +Данные пользователя: +{1} + + + + Сопоставление идентификаторов действий. + CurrentActivityId: {0} + ParentActivityId: {1} + + + Имя класса = {0} +Method Name = {1} +Workflow GUID = {2} +Message = {3} +{4} +Activity Name = {5} +GUID действия = {6} +Parameters = {7} + + + Создание объекта пространства выполнения + ИД экземпляра: {0} + + + Создание объекта RunspacePool + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + Открытие пула рабочих пространств + + + Изменение идентификатора действия и сопоставление + + + Состояние пространства выполнения изменено на {0} + + + Попытка повторного создания сеанса для {0} кода ошибки {1} в ИД сеанса {2} + + + PowerShell запустил поток прослушивания IPC в процессе: {0} в AppDomain: {1}. + + + PowerShell завершил поток прослушивания IPC в процессе: {0} в AppDomain: {1}. + + + Произошла ошибка в потоке прослушивания IPC PowerShell в процессе: {0} в AppDomain: {1}. Сообщение об ошибке: {2}. + + + Подключение PowerShell IPC в процессе: {0} в AppDomain: {1} для пользователя: {2}. + + + Отключение IPC PowerShell в процессе: {0} в AppDomain: {1} для пользователя: {2}. + + + Порт разрешен в {0} + + + Имя приложения разрешено в {0} + + + Имя компьютера разрешено в {0} + + + Схема: {0} + + + Тестирование аналитического сообщения + + + Параметры подключения + URI подключения: {0} + URI ресурса: {1} + Пользователь: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Отпечаток пальца: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + Изменение идентификатора действия и сопоставление + + + Получен объект с идентификатором пространства выполнения: идентификатор команды {0}: назначение {1}: тип данных {2}: целевой интерфейс {3}: {4} + + + В домене приложения произошла необработанное исключение. +Тип исключения: {0} +Сообщение об исключении: {1} +Трассировка стека исключений: {2} + + + ИД пространства запуска: {0} ИД конвейера: {1}. WSMan сообщил об ошибке с кодом ошибки: {2}. + Сообщение об ошибке: {3} + StackTrace: {4} + + + В домене приложения произошла необработанное исключение. +Тип исключения: {0} +Сообщение об исключении: {1} +Трассировка стека исключений: {2} + + + ИД пространства запуска: {0} ИД конвейера: {1}. WSMan сообщил об ошибке с кодом ошибки: {2}. + Сообщение об ошибке: {3} + StackTrace: {4} + + + ИД пространства выполнения {0}. Установление подключения с помощью WSMan Create Shell + + + ИД пространства выполнения {0}. Получен ответный вызов для создания оболочки WSMan + + + ИД пространства запуска: {0}. Закрытие оболочки с помощью WSManCloseShell + + + ИД пространства запуска: {0}. Получен ответный вызов для WSManCloseShell + + + ИД пространства запуска: {0} ИД конвейера: {1}. Отправка данных размера {2} + + + ИД пространства запуска: {0} ИД конвейера: {1}. Получен ответный вызов для WSManSendShellInputEx + + + ИД пространства запуска: {0} ИД конвейера: {1}. Отправка запроса на получение с использованием WSManReceiveShellOutputEx + + + ИД пространства запуска: {0} ИД конвейера: {1}. Получены данные размером {2}. + + + ИД конвейера {0} ИД пространства запуска {1}. Установление командного соединения с помощью WSManRunShellCommandEx + + + ИД конвейера {0} ИД пространства запуска {1}. Получен ответный вызов для подключения к команде + + + ИД пространства запуска: {0} ИД конвейера {1}. Закрытие транспорта для команды + + + ИД пространства запуска: {0} ИД конвейера {1}. Получен ответный вызов для закрытия команды + + + ИД пространства запуска: {0} ИД конвейера {1}. Отправка сигнала с кодом {2} с помощью WSManSignalShellEx + + + ИД пространства запуска: {0} ИД конвейера {1}. Получен ответный вызов для WSManSignalShellEx + + + ИД пространства запуска: {0}. Подключение перенаправляется на URI: {1} + + + ИД пространства запуска: {0} ИД конвейера: {1}. Сервер отправляет клиенту данные размером {2}. Тип данных: {3} TargetInterface: {4} + + + Запрос {0}. Создание удаленного сеанса сервера. Имя пользователя: {1} идентификатор пользовательской оболочки: {2} + + + Контекст отчетов для запроса: {0} контекст, о котором сообщается: {0} + + + Операция отчетности выполнена для запроса: {0} + Код ошибки: {1} + Сообщение об ошибке: {2} + StackTrace: {3} + + + Контекст оболочки {0}. Идентификатор запроса {1}. Создание сессии CommonAd для выполнения команды. + + + ИД контекстного {0} запроса команды контекста {1} оболочки {2}. Остановка команды. + + + ИД контекстного {0} запроса команды контекста {1} оболочки {2}. Получены данные от клиента. + + + ИД контекстного {0} запроса команды контекста {1} оболочки {2}. Клиент отправил запрос на получение, чтобы сервер отправлял данные. + + + Контекст контекстной {0} команды оболочки {1} IsReceiveOperation {2}. Запрос на операцию закрытия. + + + Загрузка сборки {0} для пользовательской оболочки с идентификатором оболочки {1} + + + Тип загрузки {0} для пользовательской оболочки с идентификатором оболочки {1} + + + Получен фрагмент удаленного взаимодействия. + Идентификатор объекта: {0} + Идентификатор фрагмента: {1} + Флаг запуска: {2} + Флаг завершения: {3} + Длина полезных данных: {4} + Полезные данные: {5} + + + Отправлен фрагмент удаленного взаимодействия. + Идентификатор объекта: {0} + Идентификатор фрагмента: {1} + Флаг запуска: {2} + Флаг завершения: {3} + Длина полезных данных: {4} + Полезные данные: {5} + + + Завершение работы службы winrm. + + + Объект восстановлен. + Имя десериализованного типа: {0} + После перенастройки приведите к типу: {1} + Тип объекта восстановлен: {2} + + + Не удалось восстановить объект. + Имя десериализованного типа: {0} + После перенастройки приведите к типу: {1} + Исключение приведения типа: {2} + Внутреннее исключение приведения типов: {3} + + + Глубина сериализации переопределена. + Неправильное имя сериализованного типа: {0} + Исходная глубина: {1} + Переопределена глубина: {2} + Текущая глубина ниже верхнего уровня: {3} + + + Режим сериализации переопределен. + Неправильное имя сериализованного типа: {0} + Переопределен режим: {1} + + + Сериализация свойства скрипта была пропущена, поскольку для его оценки отсутствует пространство выполнения. + Имя свойства: {0} + Имя типа владельца свойства: {1} + Сценарий метода получения: {2} + + + Сериализация свойства пропущена, так как не удалось получить свойство. + Имя свойства: {0} + Имя типа владельца свойства: {1} + Исключение из свойства метода получения: {2} + Внутреннее исключение из свойства метода получения {3} + + + Сериализация перечисляемого объекта может быть неполной, поскольку перечисляемый объект вызвал исключение. + Тип перечисляемого объекта: {0} + Исключение: {1} + + + При сериализации был вызван метод ToString объекта, что привело к ошибке. + Тип элемента: {0} + Исключение: {1} + + + Достигнута максимальная глубина под верхним уровнем, что вынуждает сериализовать объект в виде строк. + Тип объекта на максимальной глубине: {0} + Имя свойства на максимальной глубине: {1} + Глубина: {2} + + + Десериализатор выдал исключение XmlException (скорее всего, указывающее на некорректный формат clixml). + Номер строки: {0} положение строки: {1} + Исключение: {2} + + + Сериализация указанных свойств не удалась, поскольку одно из указанных свойств отсутствовало. + Тип элемента: {0} + Имя свойства: {1} + + + Запуск консоли PowerShell + + + Консоль PowerShell готова к вводу данных пользователем + + + {0} + + + Трассировка ErrorRecord: + Сообщение: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason: {2} + CategoryInfo.TargetName: {3} + FullyQualifiedErrorId: {4} + Сведения об исключении: + Сообщение : {5} + Трассировка стека: {6} + InnerException {7} + + + + Исключение: + Сообщение: {0} + StackTrace: {1} + InnerException : {2} + + + + Трассировка PSObject + + + Задание трассировки: + Идентификатор: {0} + InstanceID: {1} + Имя: {2} + Расположение: {3} + Состояние: {4} + Команда: {5} + + + + Сведения о трассировке: + {0} + + + Сведения о трассировке: + {0} {1} + + + Начало ImportWorkflowCommand::StartWorkflowApplication. Запуск вызовов функции рабочего процесса. Добавление GUID отслеживания {0} + + + Завершение ImportWorkflowCommand::StartWorkflowApplication. Завершение вызовов функции рабочего процесса. Добавление GUID отслеживания {0} + + + BEGIN Создание нового задания в ImportWorkflowCommand::StartWorkflowApplication. Добавление GUID отслеживания {0} + + + Завершение создания нового задания в ImportWorkflowCommand::StartWorkflowApplication. Добавление GUID отслеживания {0} + + + Завершение создания нового задания в ImportWorkflowCommand::StartWorkflowApplication. Tracking Guid {0} : ContainerParentJob Guid {1} + + + BEGIN JobLogic ContainerParentJob Guid {0} + + + Завершение JobLogic ContainerParentJob Guid {0} + + + Начало WorkflowExecution ContainerParentJob Guid {0} + + + Завершение WorkflowExecution ContainerParentJob Guid {0} + + + В ContainerParentJob с Guid {0} добавлено задание рабочего процесса с GUID {1} + + + ProxyJob с Guid {0} связан с удаленным ContainerParentJob с Guid {1} + + + Начало выполнения ContainerParentJob с Guid {0} + + + Завершение выполнения ContainerParentJob с Guid {0} + + + Начало выполнения Proxy Job с Guid {0} + + + Завершение выполнения Proxy Job с Guid {0} + + + Начало обработчика события StateChanged для прокси-задания с Guid {0} + + + Завершение обработчика события StateChanged для прокси-задания с GUID {0} + + + Начало обработчика события StateChanged для дочернего задания-прокси с Guid {0} + + + Завершение обработчика события StateChanged для дочернего задания-прокси с Guid {0} + + + Начало выполнения сборки мусора + + + Завершение выполнения сборки мусора + + + Хранилище сохраняемости достигло максимального заданного размера + + + Интегрированная среда сценариев Интегрированная среда сценариев Windows PowerShell ISE запустила файл сценария {0}. + + + Интегрированная среда сценариев Windows PowerShell ISE начала запускать выбранный пользователем сценарий из файла {0}. + + + Интегрированная среда сценариев Windows PowerShell ISE останавливает текущую команду. + + + Интегрированная среда сценариев Windows PowerShell ISE возобновляет работу отладчика. + + + Интегрированная среда сценариев Windows PowerShell ISE останавливает отладку. + + + Интегрированная среда сценариев Windows PowerShell ISE переходит в режим отладки. + + + Интегрированная среда сценариев Windows PowerShell ISE пропускает этапы отладки. + + + Интегрированная среда сценариев Windows PowerShell ISE выходит из режима отладки. + + + Интегрированная среда сценариев Windows PowerShell ISE включит все точки останова. + + + Интегрированная среда сценариев Windows PowerShell ISE отключит все точки останова. + + + Интегрированная среда сценариев Windows PowerShell ISE удаляет все точки останова. + + + Интегрированная среда сценариев Windows PowerShell ISE устанавливает точку останова в строке #: {0} файла {1}. + + + Интегрированная среда сценариев Windows PowerShell ISE удаляет точку останова в строке #: {0} файла {1}. + + + Интегрированная среда сценариев Windows PowerShell ISE включит точку останова в строке #: {0} файла {1}. + + + Интегрированная среда сценариев Windows PowerShell ISE отключает точку останова в строке #: {0} файла {1}. + + + Интегрированная среда сценариев Windows PowerShell ISE достигла точки останова в строке #: {0} файла {1}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/EventingResources.ru.resx b/src/System.Management.Automation/resources/ru/EventingResources.ru.resx new file mode 100644 index 00000000000..027b53a3dd1 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/EventingResources.ru.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} не существует. + + + PowerShell не может подписываться на события Windows RT. + + + Не удается зарегистрировать указанное событие. Идентификатор источника события {0} зарезервирован для подсистемы PowerShell. + + + Эта операция не поддерживается для удаленных экземпляров. + + + Это действие не поддерживается при пересылке событий. + + + Не удается подписаться на указанное событие. Подписчик с идентификатором источника {0} уже существует. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ExperimentalFeatureStrings.ru.resx b/src/System.Management.Automation/resources/ru/ExperimentalFeatureStrings.ru.resx new file mode 100644 index 00000000000..37a828c792b --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ExperimentalFeatureStrings.ru.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}". + + + Включение и отключение экспериментальных функций вступают в силу только при следующем запуске PowerShell. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ExtendedTypeSystem.ru.resx b/src/System.Management.Automation/resources/ru/ExtendedTypeSystem.ru.resx new file mode 100644 index 00000000000..9906dfb6ca0 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ExtendedTypeSystem.ru.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Элемент "{0}" уже присутствует. + + + Элемент "{0}" уже присутствует в файле данных расширенного типа. + + + Элемент "{0}" отсутствует. + + + Исключение при настройке "{0}": "{1}" + + + Исключение при получении "{0}": "{1}" + + + При попытке перечисления коллекции возникло следующее исключение: "{0}". + + + Нельзя получить доступ к элементу "{0}" вне PSObject. + + + Невозможно изменить элемент, созданный из конфигурации типа: "{0}". + + + Имя элемента "{0}" зарезервировано. + + + "{0}" невозможно изменить. + + + Исключение при вызове "{0}" с аргументами "{1}": "{2}" + + + Возникло исключение при попытке вызвать "{0}" для извлечения содержимого объекта типа "{1}": "{2}" + + + Не удается найти перегрузку для "{0}" с количеством аргументов: "{1}". + + + Не удалось найти подходящую перегрузку универсального метода для "{0}" с параметрами типа "{1}" и количеством аргументов: "{2}". + + + Обнаружено несколько неоднозначных перегрузок для "{0}" с количеством аргументов: "{1}". + + + Не удается преобразовать аргумент "{0}" со значением "{1}" для "{2}" в тип "{3}": "{4}" + + + Метод доступа get для свойства "{0}" недоступен. + + + Метод доступа set для свойства "{0}" недоступен. + + + Метод задания должен быть общедоступным, недействительным, статическим и содержать два параметра. Первый параметр должен относиться к типу PSObject. Второй параметр обязателен, если также доступен метод получения, и он должен относиться к тому же типу, что и возвращаемое значение метода получения. + + + Метод получения должен быть общедоступным, не аннулированным, статическим и содержать один параметр типа PSObject. + + + У свойства CodeProperty должен быть метод получения или метод задания. + + + Не удается создать метод кода из-за формата метода. Метод должен быть общедоступным, статическим и содержать один параметр типа PSObject. + + + Псевдоним с именем "{0}" содержит цикл. + + + Невозможно преобразовать значение "{0}" типа "{1}" в тип "{2}". + + + Невозможно преобразовать значение типа "{0}" в тип "{1}". + + + Невозможно преобразовать значение "{0}" в тип "{1}". Ошибка. "{2}" + + + Не удается преобразовать значение "{0}" в тип "{1}", так как в этом перечислении не допускаются запятые. + + + Не удается преобразовать значение "{0}" в тип "{1}", так как значения перечисления недопустимы. Укажите одно из следующих значений перечисления и повторите попытку. Возможные значения перечисления: "{2}". + + + Не удается преобразовать значение null в тип "{0}", так как значения перечисления недопустимы. Укажите одно из следующих значений перечисления и повторите попытку. Возможные значения перечисления: "{1}". + + + Не удается преобразовать значение null в тип "{0}". + + + Невозможно преобразовать значение в тип "{0}". Ошибка. "{1}" + + + Не удалось преобразовать значение в тип System.String. + + + Ожидается ссылочный тип в аргументе. + + + Не удается сравнить "{0}", так как он не реализует IComparable. + + + Не удалось сравнить "{0}" с "{1}". Ошибка. "{2}" + + + Не удается сравнить "{0}" с "{1}", так как объекты относятся к разным типам или объект "{0}" не реализует "{2}". + + + Не удается преобразовать значение "{0}" в тип "{1}", так как найдено как минимум два совпадения ({2}, {3}), а для этого перечисления допускается только одно совпадение. + + + Невозможно преобразовать значение "{0}" в тип "{1}". Логические параметры принимают только логические значения и числа, например $True, $False, 1 или 0. + + + Не удается получить значение свойства, так как свойство "{0}" доступно только для записи. + + + Свойство "{0}" доступно только для чтения. + + + Не удается задать "{0}", так как в качестве значений свойств XmlNode можно использовать только строки. + + + Невозможно задать "{0}", так как задавать можно только уникальные атрибуты или уникальные конечные узлы без атрибутов. + + + Нельзя добавить в эту коллекцию объект PSProperty или PSMethod. + + + При загрузке файла данных расширенного типа произошла следующая ошибка: {0} + + + При получении строки возникло следующее исключение: "{0}" + + + Поле или свойство "{0}" для типа "{1}" отличается от поля или свойства "{2}" только регистром. Тип должен соответствовать спецификации CLS. + + + При получении иерархии имен типов возникло следующее исключение: "{0}". + + + При получении элемента "{1}" возникло следующее исключение: "{0}" + + + При получении элементов возникло следующее исключение: "{0}" + + + При получении состояния доступности для чтения свойства "{1}" возникло следующее исключение: "{0}" + + + При получении состояния доступности для записи свойства "{1}" возникло следующее исключение: "{0}" + + + При получении типа свойства "{1}" возникло следующее исключение: "{0}" + + + При получении строкового представления свойства "{1}" возникло следующее исключение: "{0}" + + + При получении атрибутов свойства "{1}" возникло следующее исключение: "{0}" + + + При получении определений метода "{1}" возникло следующее исключение: "{0}" + + + При получении строкового представления метода "{1}" возникло следующее исключение: "{0}" + + + При получении типа для параметризованного свойства "{1}" возникло следующее исключение: "{0}" + + + При получении состояния доступности для чтения параметризованного свойства "{1}" возникло следующее исключение: "{0}" + + + При получении состояния доступности для записи параметризованного свойства "{1}" возникло следующее исключение: "{0}" + + + При получении определений параметризованного свойства "{1}" возникло следующее исключение: "{0}" + + + При получении строкового представления для параметризованного свойства "{1}" возникло следующее исключение: "{0}" + + + Невозможно задать свойство Value для объекта PSMemberInfo типа "{0}". + + + Аргумент "{0}" должен быть {1}. Используйте {2}. + + + Аргумент "{0}" не должен быть {1}. Не используйте {2}. + + + Свойство "{0}" не найдено. + + + Не удается получить или задать значение свойства. Аргумент "{0}" должен относиться к типу "{1}" или "{2}". + + + Не удается задать значение для свойства "{0}", так как объект относится к типу "{1}", а не "{2}". + + + Исключение при вызове "{0}": "{1}" + + + {0} не является допустимым путем к классу. + + + "{0}" не является допустимым путем. + + + Адаптер не может определить, можно ли изменить свойство "{0}". + + + Адаптер не может определить, доступно ли свойство "{0}" для чтения. + + + Адаптер не может получить значение свойства "{0}". + + + Адаптер не может задать значение свойства "{0}". + + + Адаптер не может получить тип свойства "{0}". + + + Адаптер не может получить иерархию типов "{0}". + + + Адаптер не может получить свойства "{0}". + + + Адаптер не может получить свойство "{0}" для "{1}". + + + "{0}" возвратил значение null. + + + Свойство "{0}" не найдено в объекте "{1}". Можно задать следующие свойства: {2}. + + + Свойство "{0}" не найдено в объекте "{1}". Доступное для задания свойство отсутствует. + + + Не удается создать объект типа "{0}". {1} + + + Нельзя вызывать статические методы или получать доступ к статическим свойствам общедоступного универсального типа {0}. Укажите параметры типа и повторите попытку. Например, вместо [System.Collections.Generic.HashSet``1]::CreateSetComparer() используйте [System.Collections.Generic.HashSet[int]]::CreateSetComparer(). + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + При создании атрибута "{1}" возникло следующее исключение: "{0}" + + + Значение "{0}" нельзя преобразовать в массив строк. + + + Невозможно преобразовать значение в тип "{0}". В этом языковом режиме поддерживаются только основные типы. + + + Не удается преобразовать в тип "{0}", подобный ByRef. Типы, подобные ByRef, не поддерживаются в PowerShell. + + + Не удается получить или задать свойство или поле "{0}" типа "{1}", подобного ByRef. Типы, подобные ByRef, не поддерживаются в PowerShell. + + + Не удается вызвать метод "{0}" с типом возвращаемого значения "{1}", который подобен ByRef. Типы, подобные ByRef, не поддерживаются в PowerShell. + + + Не удается создать экземпляр типа "{0}", подобного ByRef. Типы, подобные ByRef, не поддерживаются в PowerShell. + + + Преобразование хэш-таблицы расширенного типа + + + В режиме ConstrainedLanguage преобразование типа из HashTable в "{0}" не допускается. + + + Преобразование хэш-таблицы расширенного типа + + + В режиме ConstrainedLanguage преобразование типа из "{0}" в "{1}" не допускается. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/FileSystemProviderStrings.ru.resx b/src/System.Management.Automation/resources/ru/FileSystemProviderStrings.ru.resx new file mode 100644 index 00000000000..6583905d948 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/FileSystemProviderStrings.ru.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Вызвать элемент + + + Элемент: {0} + + + Удалить файл + + + Удалить каталог + + + Копировать файл + + + Элемент: {0} Назначение: {1} + + + Копировать каталог + + + Переименовать файл + + + Переименовать каталог + + + Элемент: {0} Назначение: {1} + + + Переместить файл + + + Переместить каталог + + + Элемент: {0} Назначение: {1} + + + Задать файл свойств + + + Задать каталог свойств + + + Элемент: {0} Свойство: {1} Значение: {2} + + + Очистить файл свойств + + + Очистить каталог свойств + + + Элемент: {0} Свойство: {1} + + + Создать файл + + + Создать каталог + + + Назначение: {0} + + + Очистить содержимое + + + Элемент: {0} + + + Не удалось найти элемент {0}. + + + Не удается удалить элемент {0}: {1} + + + Не удается восстановить атрибуты элемента {0}: {1} + + + Объект по указанному пути {0} не существует. + + + Невозможно удалить {0}, так как этот объект не пуст. + + + Тип не является известным типом файловой системы. Можно указать только "file", "directory" или "symboliclink". + + + Невозможно обработать путь, так как указанный путь ссылается на элемент за пределами basePath. + + + Указанный корень диска "{0}" не существует или не является папкой. + + + Файл с указанным именем {0} уже существует. + + + Невозможно указать разделитель при чтении потока по одному байту за раз. + + + Невозможно перезаписать элемент {0} самим собой. + + + Невозможно переименовать указанный целевой объект, поскольку он представляет путь или имя устройства. + + + Свойство {0} не существует или не найдено. + + + У вас недостаточно прав доступа для выполнения этой операции, либо элемент является скрытым, системным или доступным только для чтения. + + + Невозможно задать атрибут, так как атрибуты не поддерживаются. Можно задать только следующие атрибуты:: Archive, Hidden, Normal, ReadOnly или System. + + + Свойство не может быть очищено, так как оно не поддерживается. Можно очистить только свойство Attributes. + + + Невозможно обработать путь "{0}", так как целевой объект представляет зарезервированное имя устройства. + + + Кодирование не используется, если указан параметр "-AsByteStream". + + + Невозможно продолжить байтовое кодирование. При использовании байтового кодирования содержимое должно иметь тип byte. + + + Невозможно обработать файл, так как файл {0} не найден. + + + Каталог: + + + Не удается определить кодировку файла. Указанная кодировка {0} не поддерживается при чтении содержимого в обратном направлении. + + + Не удалось открыть альтернативный поток данных "{0}" файла "{1}". + + + Поток "{0}" файла "{1}". + + + Параметры Raw и Wait не могут быть указаны в одной команде. + + + Для использования параметра Persist имя диска должно поддерживаться операционной системой (например, буквы дисков A–Z). + + + При использовании параметра Persist корень должен быть расположением в файловой системе на удаленном компьютере. + + + Параметры "{0}" и "{1}" нельзя указывать в одной команде. + + + Для операции требуется каталог. Элемент "{0}" не является каталогом. + + + Создать соединение + + + Создать символьную ссылку + + + Для этой операции требуются права администратора. + + + Создать жесткую связь + + + Для операции требуется файл. Элемент "{0}" не является файлом. + + + Жесткие связи для указанного пути не поддерживаются. + + + Символьные ссылки для указанного пути не поддерживаются. + + + Копирование {0} в {1} + + + Путь назначения {0} — это файл, который уже существует в конечном расположении. + + + Не удалось скопировать файл {0} в удаленное целевое расположение. + + + Из {0} в {1} + + + Не удается скопировать каталог "{0}" в файл "{0}" + + + Не удалось получить дочерние элементы каталога {0}. + + + Не удалось прочитать удаленный файл "{0}". + + + Не удается проверить, является ли файлом удаленное назначение {0}. + + + Не удалось создать каталог "{0}" в удаленном расположении. + + + Превышен максимальный размер диска: {0}. + + + Не удается создать ссылку, так как путь уже существует: {0}. + + + Пропустить уже посещенный каталог {0}. + + + Путь назначения не может быть подкаталогом источника или самим источником: {0}. + + + Конечный объект и путь не могут совпадать. + + + Скопировано {0} из {1} файлов + + + {0} из {1} ({2:0.0} МБ/с) + + + Удалено {0} из {1} файлов + + + {0} из {1} ({2:0.0} МБ/с) + + + Для создания соединения требуется абсолютный путь к целевому объекту. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/FormatAndOutXmlLoadingStrings.ru.resx b/src/System.Management.Automation/resources/ru/FormatAndOutXmlLoadingStrings.ru.resx new file mode 100644 index 00000000000..ada6251f7ab --- /dev/null +++ b/src/System.Management.Automation/resources/ru/FormatAndOutXmlLoadingStrings.ru.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ошибка в XPath {0} в файле {1}: элемент XML {2} не допускает атрибутов. + + + Ошибка в XPath {0} в файле {1}: узел {2} не может содержать дочерние объекты. + + + Ошибка в XPath {0} в файле {1}: {2} является допустимым. + + + Ошибка в XPath {0} в файле {1}: должен быть хотя бы одно значение по умолчанию {2}. + + + Ошибка в XPath {0} в файле {1}: не может быть больше одного элемента по умолчанию {2}. + + + Ошибка в XPath {0} в файле {1}: имя элемента управления не может быть пустым или иметь значение NULL. + + + Ошибка в XPath {0} в файле {1}: представления вне диапазона могут содержать только CustomControl или ListControl. + + + Ошибка в XPath {0} в файле {1}: представление вне диапазона не может содержать GroupBy. + + + Ошибка в XPath {0} в файле {1}: не удается загрузить представление. + + + Ошибка в XPath {0} в файле {1}: {2} не является допустимым значением выравнивания. + + + Ошибка в XPath {0} в файле {1}: требуется положительное целое число. + + + Ошибка в XPath {0} в файле {1}: определение заголовка столбца недопустимо; все заголовки будут удалены. + + + Ошибка в XPath {0} в файле {1}: количество элементов строки = {2} в альтернативном наборе #{3} не соответствует количеству элементов строки по умолчанию = {4}. + + + Ошибка в XPath {0} в файле {1}: количество элементов заголовка = {2} не соответствует количеству элементов строки по умолчанию = {3}. + + + Ошибка в XPath {0} в файле {1}: необходимо указать хотя бы один элемент представления списка. + + + Ошибка в XPath {0} в файле {1}: запись свойства недопустима. + + + Ошибка в XPath {0} в файле {1}: отсутствует список определений. + + + Ошибка в XPath {0} в файле {1}: требуется логическое значение. + + + Ошибка в XPath {0} в файле {1}: ожидается неотрицательное целое число. + + + Ошибка в XPath {0} в файле {1}: требуется целое число. + + + Ошибка в XPath {0} в файле {1}: отсутствует внутреннее текстовое значение. + + + Ошибка в XPath {0} в файле {1}: список токенов пользовательского элемента управления не может быть пустым. + + + Ошибка в XPath {0} в файле {1}: {2} не удалось загрузить. + + + Ошибка в XPath {0} в файле {1}: {2} нельзя указывать без выражения. + + + Ошибка в XPath {0} в файле {1}: {2} нельзя указывать с выражением. + + + Ошибка в XPath {0} в файле {1}: строка формата отсутствует. + + + Ошибка в XPath {0} в файле {1}: отсутствует текст блока сценария. + + + Ошибка в XPath {0} в файле {1}: отсутствует свойство. + + + Ошибка в XPath {0} в файле {1}: блок сценария {2} недопустим. + + + Ошибка в XPath {0} в файле {1}: строка {2} из ресурса {3} в сборке {4} не найдена. + + + Ошибка в XPath {0} в файле {1}: ресурс {2} в сборке {3} не найдена. + + + Ошибка в XPath {0} в файле {1}: сборка {2} не найдена. + + + Ошибка в XPath {0} в файле {1}: узел должен быть XmlElement. + + + Ошибка в XPath {0} в файле {1}: требуется выражение. + + + Ошибка в XPath {0} в файле {1}: нельзя указывать элемент управления или метку без выражения. + + + Ошибка в XPath {0} в файле {1}: нельзя одновременно использовать элемент управления и метку. + + + Ошибка в XPath {0} в файле {1}: SelectionSetName и TypeName нельзя использовать одновременно. + + + Ошибка в XPath {0} в файле {1}: не указаны тип или условие для применения представления. + + + Ошибка в XPath {0} в файле {1}: значение {2} не является допустимым. + + + Ошибка в XPath {0} в файле {1}: существует повторяющийся узел. + + + Ошибка в XPath {0} в файле {1}: {2} и {3} взаимоисключают друг друга. + + + Ошибка в XPath {0} в файле {1}: {2}, {3} и {4} взаимоисключают друг друга. + + + Ошибка в XPath {0} в файле {1}: {2} — неизвестный узел. + + + Ошибка в XPath {0} в файле {1}: {2} — неизвестный атрибут. + + + Ошибка в XPath {0} в файле {1}: {2} — отсутствующий атрибут. + + + Ошибка в XPath {0} в файле {1}: отсутствует узел {2}. + + + Ошибка в XPath {0} в файле {1}: отсутствует узел из {2}. + + + Ошибка в XPath {0} в файле {1}: {2} — пустой узел. + + + Ошибка в XPath {0} в файле {1}: {2} — пустой атрибут. + + + Ошибка в файле {0}: {1} + + + Слишком много ошибок в файле {0}. + + + При загрузке файла данных форматирования произошли ошибки: {0} + + + (глобальный кэш сборок) {0} + + + {0}, {1} + + + Путь {0} неполный. Укажите полный путь к файлу форматирования. + + + Невозможно обновить FormatTable, так как FormatTable могла быть создана вне пространства выполнения. + + + При загрузке FormatTable произошли ошибки. Просмотрите содержимое свойства Errors, чтобы получить подробные сообщения об ошибках. + + + Ошибка форматирования данных {0}: {1} + + + Ошибка в данных представления с именем типа {0} по индексу {1}: число элементов заголовка = {2} не совпадает с числом элементов строки по умолчанию = {3}. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: данные форматирования {2} недопустимы. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: блок сценария {2} недопустим. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: не удалось загрузить {2}. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: TableControl должен содержать только один {2}. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: должен быть указан хотя бы один элемент по умолчанию {2}. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: необходимо указать хотя бы один элемент представления списка. + + + Ошибка в данных представления с именем типа {0} по индексу {1}: не может быть больше одного элемента по умолчанию {2}. + + + Слишком много ошибок в данных форматирования для типа {0}. + + + В таблицу общего формата нельзя добавить более одной записи. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/FormatAndOut_MshParameter.ru.resx b/src/System.Management.Automation/resources/ru/FormatAndOut_MshParameter.ru.resx new file mode 100644 index 00000000000..e656ca72a26 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/FormatAndOut_MshParameter.ru.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 + + + Невозможно преобразовать {0} в один из следующих типов {1}. + + + Значение параметра равно null; ожидался один из следующих типов: {0}. + + + Дублирующийся ключ "{0}" конфликтует с "{1}". + + + У ключа "{0}" недопустимый тип {1}. ожидаемые типы: {2}. + + + У ключа "{0}" недопустимый тип {1}. Ожидаемые типы: {2}. + + + Ключ {0} неоднозначен: {1} и {2} конфликтуют. + + + Значение ключа не может быть равно null. + + + Недопустимый тип ключа {0}. Ключ должен быть строкой. + + + У ключа {0} нет значения. + + + Отсутствует обязательная запись для {0}. + + + Недопустимый ключ {0}. + + + Значение "{0}" для ключа "{1}" недопустимо. Допустимые значения: {2}. + + + Значение "{0}" для ключа "{1}" должно быть больше 0. + + + У ключа "{0}" не может быть пустой строки форматирования. + + + У ключа "{0}" не может быть пустого строкового значения. + + + Пустое строковое значение не разрешено. + + + Ключ "{0}" не может содержать подстановочные знаки в значении "{1}". + + + Подстановочные знаки не допускаются в "{0}". + + + Недопустимое значение EnumerableExpansion. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/FormatAndOut_format_xxx.ru.resx b/src/System.Management.Automation/resources/ru/FormatAndOut_format_xxx.ru.resx new file mode 100644 index 00000000000..982137f507e --- /dev/null +++ b/src/System.Management.Automation/resources/ru/FormatAndOut_format_xxx.ru.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Параметры командлета View и Property являются взаимоисключающими. + + + Параметры командлета AutoSize и Column являются взаимоисключающими. + + + Не удается найти имя представления {0}. + + + Не удается найти имя представления {0} в {1} формате. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + Нет существующих {0} представлений для {1} объектов. + + + Не удается найти имя представления {0}. Укажите одно из следующих представлений {1} и повторите попытку: {2}. + + + Попробуйте использовать один из этих других командлетов форматирования: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + Следующий объект поддерживает IEnumerable: + + + IEnumerable не содержит объектов. + + + IEnumerable содержит следующий объект: + + + IEnumerable содержит следующие объекты {0}: + + + Неизвестный идентификатор класса {0}. + + + Тип {0} для свойства {1} недопустим. + + + Значение элемента данных {0} не может быть NULL. + + + Тип объекта не распознается. + + + Не удалось создать объект с идентификатором класса {0}. + + + Свойство {0} рекурсивно. + + + Не удалось оценить выражение {0}. + + + Не удалось интерпретировать строку формата {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/FormatAndOut_out_xxx.ru.resx b/src/System.Management.Automation/resources/ru/FormatAndOut_out_xxx.ru.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/FormatAndOut_out_xxx.ru.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/GetErrorText.ru.resx b/src/System.Management.Automation/resources/ru/GetErrorText.ru.resx new file mode 100644 index 00000000000..728c8aeadd8 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/GetErrorText.ru.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Не удается загрузить ресурс с базовым именем "{0}". + + + Не удается загрузить строку ресурса с идентификатором "{0}". + + + Параметры политики Stop запрещают выполнение команд. + + + Невозможно получить сообщение "{0}" "{1}" "{2}", так как сборка не зарегистрирована. + + + Не удается получить сообщение "{0}" "{1}" "{2}". Формат строки шаблона недопустим в строке шаблона "{3}". + + + Не удается получить сообщение "{0}" "{1}" "{2}". Строка шаблона существует, но ее значение пусто или состоит только из пробелов. + + + Конвейер остановлен. + + + Сбой скрипта из-за переполнения глубины вызовов. + + + Сбой конвейера из-за переполнения глубины вызовов. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/HelpDisplayStrings.ru.resx b/src/System.Management.Automation/resources/ru/HelpDisplayStrings.ru.resx new file mode 100644 index 00000000000..b511c01fccd --- /dev/null +++ b/src/System.Management.Automation/resources/ru/HelpDisplayStrings.ru.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Имя + + + Краткий обзор + + + ОПИСАНИЕ + + + СИНТАКСИС + + + ПАРАМЕТРЫ + + + ВХОДНЫЕ ДАННЫЕ + + + ВЫХОДНЫЕ ДАННЫЕ + + + ПРЕРЫВАЮЩИЕ ОШИБКИ + + + НЕПРЕРЫВАЮЩИЕ ОШИБКИ + + + ПРИМЕЧАНИЯ + + + ПРИМЕРЫ + + + Пример + + + ПРИМЕР + + + ВЫХОДНЫЕ ДАННЫЕ + + + СВЯЗАННЫЕ ССЫЛКИ + + + КРАТКОЕ ОПИСАНИЕ + + + Название: + + + Вопрос: + + + Ответ + + + Срок: + + + Определение: + + + Содержимое: + + + ИМЯ ПОСТАВЩИКА + + + Этот командлет поддерживает общие параметры: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable и OutVariable. Дополнительные сведения см. в разделе + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Обязательно? + + + Позиция? + + + Тип: + + + Тип целевого объекта: + + + Значение по умолчанию + + + Принимать входные данные конвейера? + + + Принимать подстановочные знаки? + + + (Категория: + + + Рекомендуемое действие: + + + Чтобы получить дополнительные сведения, введите: + + + Чтобы просмотреть технические сведения, введите: + + + Чтобы просмотреть примеры, введите: + + + Чтобы получить справку в Интернете, введите: + + + <CommonParameters> + + + ПРИМЕЧАНИЯ + + + true + + + Именованный + + + ДИСКИ + + + ВОЗМОЖНОСТИ + + + ЗАДАЧИ + + + ЗАДАЧА: + + + ФИЛЬТРЫ + + + ДИНАМИЧЕСКИЕ ПАРАМЕТРЫ + + + Поддерживаемые командлеты: + + + ПСЕВДОНИМЫ + + + Get-Help не удается найти файлы справки для указанного командлета на этом компьютере. Справка отображается частично. + -- Чтобы скачать и установить файлы справки для модуля, который включает этот командлет, используйте Update-Help. + -- Чтобы просмотреть раздел справки для этого командлета в Интернете, введите: "Get-Help {0} -Online" или + перейдите сюда: {1}. + + + Нет + + + Псевдонимы + + + Динамический? + + + Имя набора параметров + + + Не удается получить XML-файл HelpInfo для языка и региональных параметров пользовательского интерфейса {0}. Убедитесь, что свойство HelpInfoUri в манифесте модуля допустимо, или проверьте сетевое подключение, а затем повторите команду. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + Указанные язык и региональные параметры не поддерживаются: {0}. Укажите язык и региональные параметры из следующего списка: {{{1}}}. + + + Откладывание обработки ошибки и попытка использовать резервные варианты языка и региональных параметров будет отображаться как ошибка, если ни один из резервных вариантов не поддерживается: +{0} + + + Не удается найти каталог ModuleBase. Проверьте каталог и повторите попытку. + + + Путь {0} не является допустимым каталогом. Убедитесь, что каталог существует, и повторите попытку. + + + URI справки не может содержать более 10 перенаправлений. Укажите допустимый URI справки. + + + Обновление справки + + + Подключение к содержимому справки… + + + Скачивание содержимого справки… + + + Установка содержимого справки… + + + Поиск содержимого справки… + + + (все) + + + Не найдены модули PowerShell, соответствующие следующему шаблону: {0}. Проверьте шаблон и повторите команду. + + + Не найдены модули PowerShell, соответствующие указанному FullyQualifiedModule {0}. Проверьте значение FullyQualifiedModule и повторите команду. + + + Не удается найти содержимое справки. Убедитесь, что сервер доступен и что расположение содержимого справки правильно определено в XML-файле HelpInfo. + + + Не удалось выполнить команду Update-Help, так как указанный модуль не поддерживает обновляемую справку. Используйте Get-Help -Online или выполните поиск в Интернете, чтобы получить справку по командам в этом модуле. + + + Следующий параметр не должен быть пустым или иметь значение null: Модуль. + + + Следующий параметр не должен быть пустым или иметь значение null: Путь. + + + Команда Update-Help выполнена. + + + Ошибка при извлечении содержимого справки. + + + Не удается подключиться к содержимому справки. Возможно, сервер, на котором хранится содержимое справки, недоступен. Убедитесь, что сервер доступен, или дождитесь, пока он снова станет доступен, и повторите команду. + + + Содержимое справки в указанном расположении недопустимо. Укажите расположение, в котором находится допустимое содержимое справки. + + + XML-файл HelpInfo недопустим. Укажите допустимый XML-файл HelpInfo. + + + Содержимое справки сохранено в следующем расположении: {0} + + + Не удается найти XSD-файл содержимого справки в {0}. Убедитесь, что XSD-файл существует в указанном расположении, и повторите команду. + + + Не удалось обновить справку для модулей: +"{0}" +{1} + + + Сохранение справки + + + Содержимое справки включает недопустимые файлы. Поддерживаются только файлы TXT и XML. + + + Не удалось сохранить справку для модулей "{0}": {1} + + + Не удалось сохранить справку для модулей "{0}" с языком и региональными параметрами пользовательского интерфейса {{{1}}}: {2}. +Содержимое справки English-US доступно и может быть сохранено с помощью команды Save-Help -UICulture en-US. + + + Не удалось обновить справку для модулей "{0}" с языком и региональными параметрами пользовательского интерфейса {{{1}}}: {2}. +Содержимое справки English-US доступно и может быть установлено с помощью команды Update-Help -UICulture en-US. + + + Ваши текущие язык и региональные параметры — ({0}) и не связаны ни с одним языком. Попробуйте изменить язык и региональные параметры системы или установить содержимое справки English-US с помощью команды Update-Help -UICulture en-US. + + + false + + + Параметр -Recurse доступен, только если указан путь к источнику. + + + В пути {0} не указан поставщик FileSystem. Убедитесь, что в этом пути указан поставщик FileSystem, и повторите команду. + + + Поиск справки для {0}… + + + Не найдены язык и региональные параметры пользовательского интерфейса, соответствующие следующему шаблону: {0}. Проверьте шаблон и повторите команду. + + + Справка для модуля {0} не сохранена, так как команда Save-Help выполнялась на этом компьютере в течение последних 24 часов. +Чтобы снова сохранить справку, добавьте в команду параметр Force. + + + Справка для модуля {0} не обновлена, так как команда Update-Help выполнялась на этом компьютере в течение последних 24 часов. +Чтобы снова обновить справку, добавьте в команду параметр Force. + + + Самые актуальные файлы справки уже установлены. + + + {0}: {1}. Язык и региональные параметры {2} Версия {3} + + + Обновлено {0} + + + Значение ключа HelpInfoUri в манифесте модуля должно указывать на URL-адрес контейнера или корня на веб-сайте, где хранятся файлы справки. Ключ HelpInfoUri "{0}" не указывает на контейнер. + + + Содержимое справки должно находиться в пространстве имен {0}. + + + Get-Help не удается найти файлы справки для указанного командлета на этом компьютере. Справка отображается частично. + -- Чтобы скачать и установить файлы справки для модуля, который включает этот командлет, используйте Update-Help. + + + Самые актуальные файлы справки уже скачаны. + + + Сохранено {0} + + + HelpInfoURI {0} не начинается с HTTP. + + + Корневым элементом содержимого справки должен быть "helpItems". + + + Сохранение справки для модуля {0} + + + Обновление справки для модуля {0} + + + Разрешение URI: "{0}" + + + URI справки: {0} + + + {0}, текущая версия: {1}, доступная версия: {2}, UICulture: {3} + + + СВОЙСТВА + + + МЕТОДЫ + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/HelpErrors.ru.resx b/src/System.Management.Automation/resources/ru/HelpErrors.ru.resx new file mode 100644 index 00000000000..7295cefa5af --- /dev/null +++ b/src/System.Management.Automation/resources/ru/HelpErrors.ru.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help не удалось найти {0} в файле справки в этом сеансе. Для загрузки обновленных разделов справки введите: "Update-Help". Чтобы получить справку в режиме онлайн, найдите соответствующую тему в библиотеке TechNet по адресу https://go.microsoft.com/fwlink/?LinkID=107116. + + + Не удается обработать категорию справки, так как "{0}" не является допустимой категорией справки. + + + Не удается загрузить файл справки "{0}". Подробно: {1}. + + + Не удается получить доступ к файлу справки "{0}", так как текущий пользователь не имеет прав доступа к файлу. Подробно: {1}. + + + Файл справки "{0}" не является допустимым XML-документом. Подробно: {1}. + + + Произошла ошибка при загрузке содержимого справки {0} из файла {1}. Подробно: {2}. Для загрузки обновленных разделов справки выполните команду Update-Help. Чтобы получить справку в режиме онлайн, найдите соответствующую тему в библиотеке TechNet по адресу https://go.microsoft.com/fwlink/?LinkID=107116. + + + Не удается загрузить поставщик "{0}". Подробно: {1}. + + + Не удается загрузить файл справки. Произошли следующие ошибки {1} при загрузке файла справки "{0}". + + + Узел "{0}" не может иметь "{1}" в качестве дочернего узла. Путь к узлу: {2}. + + + Узел "{0}" может иметь не более {2} дочерних узлов типа "{1}". Путь к узлу: {3}. + + + Не удается найти ключ реестра: "{0}{1}"; используется "{2}" для загрузки файлов справки. + + + Нет параметров соответствующих условиям {0}. + + + {0} не поддерживается запрашиваемой категорией справки. + + + Не удается отобразить веб-версию этого раздела справки, так как веб-адрес (URI) раздела справки не указан в коде команды или в файле справки для команды. + + + Указан недопустимый URI {0}. + + + Не удалось запустить браузер для отображения веб-справки. Нет программ или браузеров, связанных с открытием URI {0}. + + + Протокол, указанный в Uri "{0}", не поддерживается. Поддерживаются только протоколы "{1}" и "{2}". + + + Найдено несколько разделов справки. Используйте только один раздел справки с параметром -{0}. + + + Не удается получить справку из удаленного рабочего пространства, поскольку рабочее пространство не открыто. Откройте рабочую область, выполнив команду неявного удаленного доступа, а затем попробуйте снова выполнить команду для получения справки. + + + В доступе отказано. Команде не удалось обновить разделы справки для основных модулей PowerShell, а также для любых модулей в каталоге $pshome\Modules. +Чтобы обновить эти разделы справки, запустите PowerShell с помощью команды "Запустить от имени администратора" и попробуйте снова запустить команду Update-Help. + + + Для использования {0} убедитесь, что ваше приложение использует"Microsoft.NET.Sdk.WindowsDesktop' в качестве SDK проекта и что соответствующая сборка"Microsoft.PowerShell.GraphicalHost' доступна. ({1}) + + + {0} не работает в удаленном сеансе. + + + Функция ForwardHelpTargetName не может ссылаться на саму функцию. + + + Невозможно получить помощь из сетевого расположения в режиме ограниченного доступа. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/HistoryStrings.ru.resx b/src/System.Management.Automation/resources/ru/HistoryStrings.ru.resx new file mode 100644 index 00000000000..da0f1524d4c --- /dev/null +++ b/src/System.Management.Automation/resources/ru/HistoryStrings.ru.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} не является допустимым значением для идентификатора истории. Укажите положительное число и повторите попытку. + + + Не удается найти историю идентификатора {0}. + + + Параметр count нельзя использовать вместе с несколькими идентификаторами. + + + Не удается найти историю командной строки {0}. + + + Не удается найти самую последнюю историю. + + + Командлет Invoke-History вызывается многократно в цикле. + + + Не удается обработать несколько команд истории. С помощью Invoke-History можно выполнить только одну команду. + + + Не удается добавить историю, так как входной объект имеет недопустимый формат. + + + Идентификатор {0} является недопустимым. Укажите положительное число и повторите попытку. + + + Эта команда удаляет все записи из истории сеанса. + + + Число нельзя использовать вместе с несколькими параметрами CommandLine. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/HostInterfaceExceptionsStrings.ru.resx b/src/System.Management.Automation/resources/ru/HostInterfaceExceptionsStrings.ru.resx new file mode 100644 index 00000000000..0638f83ccef --- /dev/null +++ b/src/System.Management.Automation/resources/ru/HostInterfaceExceptionsStrings.ru.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 + + + Произошла ошибка типа "{0}". + + + Сбой команды, которая выдает запрос пользователю, так как программа узла или тип команды не поддерживают взаимодействие с пользователем. Попробуйте использовать программу узла, поддерживающую взаимодействие с пользователем, например, консоль PowerShell, и удалите команды, связанные с приглашением командной строки, из тех типов команд, которые не поддерживают взаимодействие с пользователем. + + + Сбой команды, которая выдает запрос пользователю, так как программа узла или тип команды не поддерживают взаимодействие с пользователем. Узел попытался запросить подтверждение со следующим сообщением: {0} + + + Метод нельзя вызвать, так как пул закрыт или завершил работу с ошибкой. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/InternalCommandStrings.ru.resx b/src/System.Management.Automation/resources/ru/InternalCommandStrings.ru.resx new file mode 100644 index 00000000000..2023496b8b2 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/InternalCommandStrings.ru.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Имя входных данных {0} неоднозначно. Его можно сопоставить с несколькими найденными методами. Возможные совпадения:{1}. + + + Имя входных данных {0} неоднозначно. Его можно сопоставить с несколькими найденными элементами. Возможные совпадения:{1}. + + + Получить значение ключа {0} + + + Вызвать метод {0} с аргументами: {1} + + + Вызвать метод {0} + + + Получить значение свойства {0} + + + InputObject: {0} + + + Невозможно выполнить операцию для входного объекта со значением NULL. + + + Не удается сопоставить имя ввода {0} с методом. + + + Нельзя вызывать метод в режиме ограниченного языка. + + + Параметры -WhatIf и -Confirm не поддерживаются для блоков сценария. + + + Операция {0} не разрешена в режиме RestrictedLanguage. + + + Требуется оператор для сравнения двух указанных значений. Укажите допустимый оператор в команде и повторите попытку. Например, Get-Process | Where-Object -Property Name -eq Idle + + + Не удается сопоставить имя ввода {0} со свойством. + + + Не удается сопоставить имя ввода {0} с элементом. + + + Для указанного оператора требуются оба параметра: -Property и -Value. Укажите значения для обоих параметров и повторите команду. + + + Этот метод нельзя выполнять в текущем потоке. Его можно вызывать только в потоке командлета. + + + Переменная, используемая в ForEach-Object -Parallel, не может быть блоком сценария. Переменные, переданные в блок сценария, не поддерживаются в ForEach-Object -Parallel и могут привести к неопределенному поведению. + + + Объект, передаваемый по конвейеру в ForEach-Object -Parallel, не может быть блоком сценария. Переменные, переданные в блок сценария, не поддерживаются в ForEach-Object -Parallel и могут привести к неопределенному поведению. + + + Параметр TimeoutSeconds нельзя использовать вместе с параметром AsJob. + + + Следующие общие параметры сейчас не поддерживаются в наборе параметров Parallel: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + Во время обработки входных данных ForEach-Object -Parallel произошла непредвиденная ошибка. Это может означать, что часть входных данных, переданных через конвейер, не была обработана. Ошибка: {0}. + + + Командлет ForEach-Object + + + Вызов метода для типа {0} будет запрещен при выполнении в режиме ограниченного языка (Constrained Language). + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/InternalHostStrings.ru.resx b/src/System.Management.Automation/resources/ru/InternalHostStrings.ru.resx new file mode 100644 index 00000000000..b12ae39510c --- /dev/null +++ b/src/System.Management.Automation/resources/ru/InternalHostStrings.ru.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 + + + Функция EnterNestedPrompt вызывалась не так часто, как ExitNestedPrompt. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/InternalHostUserInterfaceStrings.ru.resx b/src/System.Management.Automation/resources/ru/InternalHostUserInterfaceStrings.ru.resx new file mode 100644 index 00000000000..740a4b4e016 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/InternalHostUserInterfaceStrings.ru.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug остановлена, так как значение переменной DebugPreference — "Stop". + + + Значение {0} не является поддерживаемым значением ActionPreference. + + + Параметр {0} должен содержать хотя бы одно значение. + + + &Да + + + Продолжить. + + + Да для &всех + + + Продолжить и больше не спрашивать, следует ли продолжать этот сеанс. + + + &Нет + + + Завершить операцию с ошибкой. + + + Нет для &всех + + + Завершить операцию с ошибкой. Не запрашивать возобновление операции для этого сеанса. + + + &Приостановить + + + Приостановить текущую операцию и перейти в командную строку. Введите "exit", чтобы возобновить приостановленную операцию. + + + Продолжить эту операцию? + + + (по умолчанию — {0}) + + + (значения по умолчанию: {0}) + + + Выбор[{0}]: + + + В {0} должен быть указан по меньшей мере один элемент. + + + {0} должен быть допустимым индексом в {1}. {2} не является допустимым индексом. + + + Не удается обработать горячую клавишу, так как вопросительный знак ("?") нельзя использовать в качестве горячей клавиши. + + + ПОДРОБНО: {0} + + + ВНИМАНИЕ! {0} + + + ОТЛАДКА: {0} + + + В настоящее время узел не выполняет расшифровку. + + + Время запуска команды: {0} + + + ********************** +Начало расшифровки PowerShell +Время начала: {0:yyyyMMddHHmmss} +Имя пользователя: {1} +Пользователь, от имени которого выполняется запуск: {2} +Имя конфигурации: {3} +Компьютер: {4} ({5}) +Ведущее приложение: {6} +Идентификатор процесса: {7} +{8} +********************** + + + ********************** +Начало расшифровки PowerShell +Время начала: {0:yyyyMMddHHmmss} +********************** + + + ********************** +Завершение расшифровки PowerShell +Время окончания: {0:yyyyMMddHHmmss} +********************** + + + Путь к файлу {0} указывает на каталог. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/Logging.ru.resx b/src/System.Management.Automation/resources/ru/Logging.ru.resx new file mode 100644 index 00000000000..d9407797418 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/Logging.ru.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1]; Значение=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2]; Значение=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + НЕИЗВЕСТНО + + + Экспериментальная функция подсистемы "{0}", объявленная в конфигурационном файле, не зарегистрирована в текущей версии PowerShell. + + + Экспериментальная функция "{0}", объявленная в файле config, недействительна. +Имя экспериментальной функции должно следовать приведенной ниже таблице. + Название функции подсистемы: 'PS[FeatureName]' + Имя функции модуля: "[ModuleName]. [FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/Metadata.ru.resx b/src/System.Management.Automation/resources/ru/Metadata.ru.resx new file mode 100644 index 00000000000..98babf1acb1 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/Metadata.ru.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Не удается инициализировать атрибуты для "{0}": "{1}" + + + Невозможно проверить аргумент, так как его тип "{0}" не совпадает с типом ({1}) максимальной и минимальной границ параметра. Убедитесь, что аргумент имеет тип {1}, а затем повторите команду. + + + Невозможно проверить аргумент "{0}", так как его значение не больше нуля. + + + Невозможно проверить аргумент "{0}", так как его значение меньше нуля. + + + Невозможно проверить аргумент "{0}", так как его значение не меньше нуля. + + + Невозможно проверить аргумент "{0}", так как его значение больше нуля. + + + Указанный минимальный диапазон ({0}) не может быть принят, так как его тип не совпадает с типом указанного максимального диапазона ({1}). Обновите атрибут ValidateRange для параметра. + + + Нельзя принять типы параметров MaxRange и MinRange. Оба параметра должны быть объектами, реализующими интерфейс IComparable. + + + Указанный максимальный диапазон не может быть принят, так как он меньше указанного минимального диапазона. Обновите атрибут ValidateRange для параметра. + + + Аргумент {0} больше максимально допустимого диапазона {1}. Укажите аргумент, который меньше или равен {1}, а затем повторите команду. + + + Аргумент {0} меньше минимально допустимого диапазона {1}. Укажите аргумент, который больше или равен {1}, а затем повторите команду. + + + Аргумент "{0}" не соответствует шаблону "{1}". Укажите аргумент, который соответствует "{1}", а затем повторите команду. + + + Атрибут ValidateCount нельзя применить к параметру, который не является массивом. Удалите атрибут из параметра или сделайте параметр массивом. + + + Требуемое количество значений для параметра: {0}, а указано {1}. + + + Требуемое количество значений для параметра: не менее {0} и не более {1}, а указано {2}. + + + Указанное максимальное число аргументов для параметра меньше указанного минимального числа аргументов. Обновите атрибут ValidateCount для параметра. + + + Указанная максимальная длина аргумента меньше указанной минимальной длины аргумента. Обновите атрибут ValidateLength для параметра. + + + Атрибут ValidateLength нельзя применить к параметру, который не является параметром string или string[]. Измените тип параметра на string или string[]. + + + Длина аргумента в символах ({1}) слишком мала. Укажите аргумент длиной не менее "{0}", а затем повторите команду. + + + Длина аргумента в символах ({1}) слишком велика. Укажите аргумент длиной не более "{0}", а затем повторите команду. + + + Аргумент "{0}" не принадлежит к набору "{1}", указанному атрибутом ValidateSet. Укажите аргумент допустимого типа и повторите попытку. + + + Генератор допустимых значений возвращает значение null. + + + У "{0}" произошел сбой в свойстве "{1}" {2} + + + Не удается получить или выполнить команду. Превышено максимальное число наборов параметров для этой команды. + + + Невозможно обработать аргумент, так как его значение не является строкой. Значения аргументов параметров, для которых указан атрибут ArgumentTransformationAttribute, должны быть строками. + + + Невозможно проверить переменную, так как значение {1} не является допустимым значением для переменной {0}. + + + Нельзя добавить атрибут, так как переменная {0} со значением {1} больше не будет допустимой. + + + Аргумент имеет значение null. Укажите допустимое значение аргумента, а затем повторите команду. + + + Аргумент имеет значение null, или элемент коллекции аргумента содержит значение null. Укажите коллекцию, не содержащую значений null, а затем повторите команду. + + + Аргумент имеет значение null или пуст. Укажите аргумент, который не имеет значения null и не пуст, а затем повторите команду. + + + Аргумент имеет значение null, пуст, или элемент коллекции аргумента содержит значение null. Укажите коллекцию, не содержащую значений NULL, а затем повторите команду. + + + Аргумент имеет значение null, пуст или состоит только из пробелов. Укажите аргумент, содержащий символы, отличные от пробела, а затем повторите команду. + + + Элемент коллекции аргумента имеет значение null, пуст или состоит только из пробелов. Укажите коллекцию, не содержащую таких значений, а затем повторите команду. + + + Параметр "{0}" был определен для команды несколько раз. + + + Нельзя указать псевдоним параметра, так как псевдоним с именем "{0}" уже был определен для этой команды несколько раз. + + + Нельзя указать параметр "{0}'" так как он конфликтует с псевдонимом того же имени для параметра "{1}". + + + Скрипт проверки "{1}" для аргумента со значением "{0}" не вернул значение True. Определите причину сбоя скрипта проверки, а затем повторите команду. + + + Аргумент "{0}" не содержит допустимую версию PowerShell. Укажите допустимый номер версии, а затем повторите команду. + + + Невозможно проверить аргумент "{0}", так как он не является допустимым именем переменной. + + + Тип преобразования задания должен наследовать IAstToScriptBlockConverter. + + + Недопустимый аргумент пути. Укажите аргумент пути строкового типа. + + + Диск аргумента пути {0} не входит в набор утвержденных дисков: {1}. Укажите аргумент пути с утвержденным диском. + + + Аргумент пути содержит недопустимые символы. + + + У аргумента пути нет корневого диска. Укажите полный путь с корневым диском. + + + Значение аргумента для параметра "{0}" не может быть null или пустой строкой. + + + Элемент перечисления "{0}" не является допустимым значением параметра "{1}". Укажите один из следующих элементов и повторите попытку: {2}.. + + + Не удается обработать входные данные. Недоверенный аргумент "{0}". + + + Ошибка проверки атрибута ValidateTrustedData + + + Аргумент параметра "{0}" не является доверенным и приведет к сбою проверки атрибута параметра ValidateTrustedData в режиме ограниченного языка. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/MiniShellErrors.ru.resx b/src/System.Management.Automation/resources/ru/MiniShellErrors.ru.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/MiniShellErrors.ru.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/Modules.ru.resx b/src/System.Management.Automation/resources/ru/Modules.ru.resx new file mode 100644 index 00000000000..b5441ba52e6 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/Modules.ru.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Указанный модуль "{0}" не был загружен, так как ни в одном каталоге модулей не найден допустимый файл модуля. + + + Указанный модуль "{0}" с версией "{1}" не был загружен, так как ни в одном каталоге модулей не найден допустимый файл модуля. + + + Указанное значение MaximumVersion "{0}" неверно. Если используется "*", MaximumVersion поддерживает только один символ "*" и он должен располагаться в конце MaximumVersion. + + + Указанный модуль "{0}" с MaximumVersion "{1}" не был загружен, так как ни в одном каталоге модулей не был найден допустимый файл модуля. + + + Указанный модуль "{0}" с MinimumVersion "{1}" и MaximumVersion "{2}" не был загружен, так как ни в одном каталоге модулей не был найден допустимый файл модуля. + + + Значение MinimumVersion "{0}" не должно быть больше значения MaximumVersion "{1}". + + + Сборка "{0}" не загружена, так как сборка с таким именем не найдена. Проверьте имя сборки и повторите попытку. + + + Модуль для обработки "{0}", указанный в поле "{1}" манифеста модуля "{2}", не был обработан, так как ни в одном каталоге модулей не был найден допустимый модуль. + + + Для модуля "{0}" не был возвращен пользовательский объект, так как параметр -AsCustomObject можно использовать только с модулями сценариев. + + + Не удалось обработать манифест модуля "{0}", так как он не является допустимым файлом манифеста модуля PowerShell. Удалите запрещенные элементы: {1} + + + Обработка файла манифеста модуля "{0}" не привела к созданию допустимого объекта манифеста. Обновите файл, чтобы он содержал допустимый манифест модуля PowerShell. Допустимый манифест можно создать с помощью командлета New-ModuleManifest. + + + Не удается импортировать модуль "{0}", так как его манифест содержит один или несколько недопустимых элементов. Допустимые элементы манифеста: ({1}). Удалите недопустимые элементы ({2}), а затем повторите попытку импорта модуля. + + + Хэш-таблица, описывающая модуль, содержит один или несколько недопустимых элементов. Допустимые элементы: ({0}). Удалите недопустимые элементы ({1}) и повторите попытку. + + + Не удается загрузить модуль "{0}", так как превышен предел вложенности модулей. Модули можно вложить только в следующее количество уровней: {1}. Оцените и измените порядок загрузки модулей, чтобы не превышать предел вложенности, а затем повторите попытку запуска сценария. + + + Элемент "ModuleVersion" отсутствует в манифесте модуля. Этот элемент должен существовать, и ему должно быть назначено значение версии в формате "n.n.n.n". Добавьте отсутствующий элемент в файл "{0}". + + + Элемент "{0}" недопустим в файле манифеста модуля "{2}": {1} + + + Версия "{0}" модуля "{1}" не соответствует требуемой минимальной версии "{2}". Проверьте, что номер версии поддерживается, а затем повторите попытку загрузки модуля. + + + Версия PowerShell на этом компьютере — "{0}". Для запуска модуля "{1}" требуется минимальная версия PowerShell "{2}". Проверьте, что установлена требуемая минимальная версия PowerShell, и повторите попытку. + + + Элемент манифеста модуля "NestedModules" нельзя использовать, если элемент "ModuleToProcess" является двоичным модулем. Измените файл манифеста модуля в "{0}" и повторите попытку. + + + Элемент "{0}" в манифесте модуля недопустим: {1}. Проверьте, что для этого поля в файле "{2}" указано допустимое значение. + + + Путь к манифесту модуля "{0}" недопустим. Значение аргумента Path должно сопоставляться с одним файлом с расширением ".psd1". Измените значение аргумента Path так, чтобы оно указывало на допустимый файл psd1, а затем повторите попытку. + + + Ключ ModuleVersion в манифесте модуля "{0}" указывает версию модуля "{1}", которая не совпадает с именем папки версии в "{2}". Измените значение ключа ModuleVersion, чтобы оно соответствовало имени папки версии. + + + Указанная запись NestedModule "{0}" в манифесте модуля "{1}" недопустима. Повторите попытку после обновления этой записи с использованием допустимых значений. + + + Указанная запись RequiredAssemblies "{0}" в манифесте модуля "{1}" недопустима. Повторите попытку после обновления этой записи с использованием допустимых значений. + + + Указанная запись FileList "{0}" в манифесте модуля "{1}" недопустима. Повторите попытку после обновления этой записи с использованием допустимых значений. + + + Указанная запись RequiredModules "{0}" в манифесте модуля "{1}" недопустима. Повторите попытку после обновления этой записи с использованием допустимых значений. + + + Указанная запись ModuleList "{0}" в манифесте модуля "{1}" недопустима. Повторите попытку после обновления этой записи с использованием допустимых значений. + + + Манифест модуля "{0}" указан с ключом CompatiblePSEditions, который поддерживается только в PowerShell версии "5.1" или более поздней. Обновите значение ключа PowerShellVersion до "5.1" или более поздней версии и повторите попытку. + + + Указанное значение "{0}" для CompatiblePSEditions содержит повторяющиеся имена выпусков PowerShell. Повторите попытку после удаления повторяющихся имен выпусков PowerShell. + + + Версия, указанная в ключе ModuleVersion, совпадает с именем папки версии. + + + Папка версии {0} в модуле {1} пропускается, так как в ней нет допустимого файла манифеста модуля. + + + Элемент "ModuleName" не существует в хэш-таблице, описывающей этот модуль. + + + Элементы "ModuleVersion", "MaximumVersion" и "RequiredVersion" отсутствуют в хэш-таблице, описывающей этот модуль. Должен существовать один из этих трех элементов, и ему должно быть присвоено значение версии в формате "n.n.n.n". + + + Требуемый модуль "{1}" не загружен. Загрузите модуль или удалите его из "RequiredModules" в файле "{0}". + + + Требуемый модуль "{1}" с GUID "{2}" не загружен. Загрузите модуль или удалите его из "RequiredModules" в файле "{0}". + + + Требуемый модуль "{1}" версии "{2}" не загружен. Загрузите модуль или удалите его из "RequiredModules" в файле "{0}". + + + Требуемый модуль "{1}" с MaximumVersion "{2}" не загружен. Загрузите модуль или удалите его из "RequiredModules" в файле "{0}". + + + Требуемый модуль "{1}" с MinimumVersion "{2}" и MaximumVersion "{3}" не загружен. Загрузите модуль или удалите его из "RequiredModules" в файле "{0}". + + + Не удается найти модуль "{0}" с ModuleVersion "{1}". + + + Не удается найти модуль "{0}" с RequiredVersion "{1}". + + + Не удается найти модуль "{0}" с MaximumVersion "{1}". + + + Не удается найти модуль "{0}" с ModuleVersion "{1}" и MaximumVersion "{2}". + + + Модуль "{0}" не найден. + + + Модули не удалены. Проверьте, что указаны правильные модули для удаления и что эти модули существуют в пространстве выполнения. + + + Элемент "{0}", импортированный из модуля "{1}", нельзя удалить по следующей причине: {2} + + + Не удалось удалить модуль "{0}", так как он доступен только для чтения. Добавьте параметр Force в команду, чтобы удалить модули, доступные только для чтения. + + + Не удалось удалить модуль "{0}", так как он помечен как "constant". Модуль нельзя удалить, если он помечен как "constant". + + + Не удалось удалить модуль "{0}", так как он требуется "{1}". Добавьте параметр Force в команду, чтобы удалить модуль. + + + Командлет Export-ModuleMember можно вызвать только изнутри модуля. + + + Расширение "{0}" не является допустимым расширением модуля. Поддерживаемые расширения модулей: ".dll", ".ps1", ".psm1", ".psd1" и ".cdxml". Исправьте расширение и попробуйте добавить файл "{1}" еще раз. + + + Эту операцию нельзя выполнить для двоичного модуля. Ее можно выполнить только для модуля сценария. + + + Файл "{0}" не допускается, так как у него нет расширения ".ps1". + + + Неизвестно + + + (c) {0}. Все права защищены. + + + Удаление импортированной функции "{0}". + + + Удаление импортированного псевдонима "{0}". + + + Удаление импортированной переменной "{0}". + + + Загрузка модуля из пути "{0}". + + + Загрузка "{0}" из пути "{1}". + + + Вызов файла сценария "{0}" с использованием точки. + + + Импорт функции "{0}". + + + Импорт командлета "{0}". + + + Импорт псевдонима "{0}". + + + Импорт переменной "{0}". + + + Экспорт командлета "{0}". + + + Экспорт функции "{0}". + + + Экспорт псевдонима "{0}". + + + Экспорт переменной "{0}". + + + Имена некоторых импортируемых команд из модуля "{0}" содержат неутвержденные глаголы, из-за чего их может быть сложнее обнаружить. Чтобы найти команды с неутвержденными глаголами, снова запустите команду Import-Module с параметром Verbose. Чтобы получить список утвержденных глаголов, введите Get-Verb. + + + Команда "{0}" в модуле "{1}" была импортирована, но ее имя не содержит утвержденного глагола, поэтому ее может быть трудно найти. Чтобы получить список утвержденных глаголов, введите Get-Verb. + + + Команда "{0}" в модуле "{2}" была импортирована, но ее имя не содержит утвержденного глагола, поэтому ее может быть трудно найти. Предлагаемые альтернативные глаголы: "{1}". + + + Некоторые импортированные имена команд содержат один или несколько следующих ограниченных символов: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " " < > | ? @ ` * % + = ~ + + + Имя команды "{0}" из модуля "{1}" содержит один или несколько следующих ограниченных символов: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " " < > | ? @ ` * % + = ~ + + + Создание файла манифеста модуля "{0}". + + + {0} (путь: "{1}") + + + Текущая архитектура процессора: {0}. Модулю "{1}" требуется следующая архитектура: {2}. + + + Имя текущего узла PowerShell: "{0}". Для модуля "{1}" требуется следующий узел PowerShell: "{2}". + + + Текущий узел PowerShell: "{0}" (версия {1}). Для запуска модуля "{2}" требуется минимальная версия узла PowerShell "{3}". + + + Манифест модуля "{0}" + + + Кем создано: {0} + + + Создано: {0} + + + Файл модуля сценария или двоичного модуля, связанный с этим манифестом. + + + Модули, которые нужно импортировать как вложенные модули модуля, указанного в RootModule/ModuleToProcess + + + Идентификатор, используемый для уникальной идентификации этого модуля + + + Автор этого модуля + + + Компания или поставщик этого модуля + + + Заявление об авторских правах для этого модуля + + + Номер версии этого модуля. + + + Описание функциональности, предоставляемой этим модулем + + + Минимальная версия подсистемы PowerShell, необходимая для этого модуля + + + Минимальная версия среды выполнения CLR, необходимая для этого модуля. {0} + + + Модули, которые нужно импортировать в глобальную среду перед импортом этого модуля + + + Файлы сценариев (.ps1), которые запускаются в среде вызывающего объекта перед импортом этого модуля. + + + Файлы типов (.ps1xml), которые нужно загрузить при импорте этого модуля + + + Файлы формата (.ps1xml), которые нужно загрузить при импорте этого модуля + + + Сборки, которые нужно загрузить перед импортом этого модуля + + + Список всех файлов, упакованных с этим модулем + + + Личные данные для передачи в модуль, указанный в RootModule/ModuleToProcess. Они также могут содержать хэш-таблицу PSData с дополнительными метаданными модуля, используемыми PowerShell. + + + Теги, применяемые к этому модулю. Они помогают находить модуль в онлайн-галереях. + + + URL-адрес основного веб-сайта этого проекта. + + + URL-адрес лицензии для этого модуля. + + + URL-адрес значка, представляющего этот модуль. + + + Заметки о выпуске этого модуля + + + Строка предварительного выпуска этого модуля + + + Флаг, указывающий, требуется ли модулю явное принятие пользователем установки, обновления или сохранения + + + Внешние зависимые модули этого модуля + + + Конец хэш-таблицы {0} + + + Значение параметра PrivateData должно быть хэш-таблицей, чтобы создать манифест модуля со следующими значениями параметров: Tags, ProjectUri, LicenseUri, IconUri или ReleaseNotes. Удалите значения параметров Tags, ProjectUri, LicenseUri, IconUri или ReleaseNotes либо поместите содержимое PrivateData в хэш-таблицу. + + + PrivateData должен быть определен как хэш-таблица, но в этом манифесте модуля он определен как объект. Рассмотрите возможность перенести содержимое PrivateData в хэш-таблицу. Это позволит позже добавить в манифест модуля свойства Tags, ProjectUri, LicenseUri, IconUri и ReleaseNotes. + + + Указанное значение "{0}" недопустимо. Повторите попытку, указав допустимое значение. + + + Функции для экспорта из этого модуля. Для оптимальной производительности не используйте подстановочные знаки и не удаляйте эту запись. Если функций для экспорта нет, используйте пустой массив. + + + Псевдонимы для экспорта из этого модуля. Для оптимальной производительности не используйте подстановочные знаки и не удаляйте этот элемент. Если псевдонимов для экспорта нет, используйте пустой массив. + + + Командлеты для экспорта из этого модуля. Для оптимальной производительности не используйте подстановочные знаки и не удаляйте эту запись. Если командлетов для экспорта нет, используйте пустой массив. + + + Переменные для экспорта из этого модуля + + + Ресурсы DSC для экспорта из этого модуля + + + Поддерживаемые PSEditions + + + Архитектура процессора (None, X86, Amd64), необходимая для этого модуля + + + Список всех модулей, упакованных с этим модулем + + + Минимальная версия Microsoft .NET Framework, необходимая для этого модуля. {0} + + + Имя узла PowerShell, требуемого для этого модуля + + + Минимальная версия узла PowerShell, необходимая для этого модуля + + + URI HelpInfo этого модуля + + + Так как модуль {0} предоставляет PSDrive в текущем сеансе PowerShell, ни один модуль не был удален. Измените текущего поставщика PSDrive, а затем повторите попытку удаления модулей. + + + Не удалось импортировать командлет "{0}", так как в текущей области есть элемент с таким же именем. + + + Псевдоним "{0}" не был импортирован, так как в текущей области есть элемент с таким же именем. + + + Функция "{0}" не была импортирована, так как в текущей области есть элемент с таким же именем. + + + Не удалось импортировать переменную "{0}", так как в текущей области есть элемент с таким же именем. + + + В элементах "ModuleToProcess", "RootModule" и "NestedModules" манифеста модуля "{0}" не допускаются подстановочные знаки. + + + Модуль "{0}" является основным модулем для PowerShell. Добавьте в команду параметр Force, чтобы удалить основные модули. + + + Манифест модуля не может одновременно содержать элементы "ModuleToProcess" и "RootModule". Измените файл манифеста модуля в "{0}", удалив один из этих элементов, и повторите попытку. + + + Элемент манифеста модуля "ModuleToProcess" является нерекомендуемым. Вместо него используйте элемент "RootModule". + + + Префикс по умолчанию для команд, экспортируемых из этого модуля. Переопределите префикс по умолчанию с помощью Import-Module -Prefix. + + + Параметры "Global" и "Scope" нельзя указывать вместе. Удалите один из этих параметров, а затем повторите попытку выполнения команды. + + + Требуемый модуль "{0}" не загружен. Модуль "{0}" содержит requiredModule "{1}" в манифесте модуля "{2}", что указывает на циклическую зависимость. + + + Требуемый модуль "{0}" не был загружен, так как ни в одном каталоге модулей не найден допустимый файл модуля. + + + Некоторые команды из модуля {0} невозможно импортировать через CimSession. Чтобы получить все команды, проверьте, что на удаленном сервере включено удаленное управление PowerShell, а затем попробуйте добавить параметр PSSession в командлет Import-Module. + + + Модуль {0} загружен в Windows PowerShell с использованием удаленного сеанса {1}; обратите внимание, что все входные и выходные данные команд из этого модуля будут представлять собой десериализованные объекты. Если вы хотите загрузить этот модуль в PowerShell, используйте синтаксис "Import-Module -SkipEditionCheck". + + + Обнаружена версия Windows PowerShell {0}. Для загрузки модулей с использованием функции совместимости с Windows PowerShell требуется Windows PowerShell 5.1. Установите Windows Management Framework (WMF) 5.1 со страницы https://aka.ms/WMF5Download, чтобы включить эту функцию. + + + Загрузка модуля "{0}" через функцию совместимости Windows PowerShell заблокирована параметром "WindowsPowerShellCompatibilityModuleDenyList" в файле конфигурации PowerShell. + + + Невозможно импортировать модуль {0} через CimSession. Попробуйте использовать параметр PSSession командлета Import-Module. + + + Значение архитектуры процессора {0} не поддерживается. Выполните команду New-ModuleManifest еще раз, указав одно из следующих поддерживаемых значений перечисления для архитектуры процессора: None, MSIL, X86, Amd64, Arm + + + При выполнении командлета Get-Module на удаленном компьютере можно получить только список доступных модулей. Добавьте в команду параметр ListAvailable и повторите попытку. + + + Модуль "{0}" не был импортирован, так как оснастка "{0}" уже импортирована. + + + В элементе "RequiredAssemblies" манифеста модуля "{0}" не допускаются подстановочные знаки. + + + Значение ключа {0} в {1} равно {2}, а модуль содержит вложенные модули. Если файл CDXML является корневым модулем, команда Import-Module завершится ошибкой, так как команды во вложенных модулях нельзя экспортировать. Переместите файл CDXML в ключ NestedModules и повторите команду. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Сбой удаленной команды: {0}: {{0}} + + + Не удалось создать прокси-серверы для удаленного модуля "{0}". {{0}} + + + Не удалось обработать удаленный модуль {0}. {1} + + + Не удалось получить данные модуля от удаленного CimSession. {0} + + + Требуемый модуль "{0}" с GUID "{1}" и версией "{2}" не был загружен, так как ни в одном каталоге модулей не найден допустимый файл модуля. + + + Поставщик CIM для обнаружения модулей не найден на сервере CIM. {0} + {0} is a placeholder for a more detailed error message + + + Не удается проверить версию Microsoft .NET Framework {0}, так как она не включена в список разрешенных версий. + + + Анализ {0}. + {0} should not be localized, is used to contain a file path. + + + Подготовка модулей к первому использованию. + + + Поиск доступных модулей + + + Поиск общей папки UNC {0}. + {0} should not be localized, is used to contain a file path. + + + Запуск командлета Get-Module на удаленном компьютере возможен только для имен модулей, которые не содержат путь. Параметр Name содержит элемент "{0}", который сопоставляется с путем. Обновите параметр Name так, чтобы он не содержал элементов пути, а затем повторите попытку. + + + Запуск командлета Get-Module без параметра ListAvailable не поддерживается для имен модулей, которые содержат путь. Параметр Name содержит элемент "{0}", который сопоставляется с путем. Обновите параметр Name так, чтобы он не содержал элементов пути, а затем повторите попытку. + + + Указанный модуль "{0}" не найден. Обновите параметр Name, чтобы он указывал на допустимый путь, и повторите попытку. + + + Заполнение свойства RepositorySourceLocation для модуля {0}. + + + Модуль для обработки "{0}", указанный в поле "{1}" манифеста модуля "{2}", не был обработан. {3} + + + Это предварительное требование действительно только для выпуска классической версии PowerShell. + + + Модуль "{0}" не поддерживает текущий выпуск PowerShell "{1}". Поддерживаемые выпуски: "{2}". Чтобы проигнорировать совместимость этого модуля, используйте "Import-Module -SkipEditionCheck". + + + Модуль "{0}" поддерживает выпуск PowerShell "{1}" и не может быть загружен неявно с помощью функции совместимости Windows, так как она отключена в файле параметров. Используйте "Import-Module -UseWindowsPowerShell", чтобы загрузить этот модуль с помощью Windows PowerShell, или "Import-Module -SkipEditionCheck", чтобы попытаться загрузить модуль с текущим PowerShell. + + + Для экспериментальной функции, объявленной в манифесте модуля, следует указать непустое строковое значение. + + + Обнаружено одно или несколько недопустимых имен экспериментальных функций: {0}. Имя экспериментальной функции модуля должно соответствовать соглашению: "ModuleName.FeatureName". + + + Параметр-переключатель -SkipEditionCheck нельзя использовать без параметра-переключателя -ListAvailable. + + + Импорт файлов *.ps1 в качестве модулей не разрешен в режиме ConstrainedLanguage. + + + Произошла ошибка при загрузке модуля сценария {0}, потому что его языковой режим отличается от языкового режима манифеста модуля. Языковой режим манифеста — {1}, а языковой режим модуля — {2}. Убедитесь, что все файлы модуля подписаны или иным образом включены в конфигурацию списка разрешений приложения. + + + В этом модуле используется оператор dot-source при экспорте функций с подстановочными знаками, что запрещено, если в системе применяется принудительная проверка приложений. + + + Нельзя экспортировать элементы модуля из модуля, языковой режим которого отличается от языкового режима текущего сеанса. + + + Нельзя создать новый модуль, пока сеанс находится в режиме ConstrainedLanguage. + + + Не удается найти встроенный модуль "{0}", совместимый с выпуском "Core". Убедитесь, что встроенные модули PowerShell доступны. Обычно они поставляются вместе с пакетом PowerShell в пути $PSHOME к модулю и необходимы для корректной работы PowerShell. + + + Командлет Export-ModuleMember + + + Экспорт элементов модуля завершится сбоем в ограниченном языковом режиме, так как модуль "{0}" использует языковой режим "{1}", отличный от текущего сеанса "{2}". + + + Неявный экспорт функций модуля + + + Неявный экспорт функций для модуля "{0}" будет запрещен, так как он является доверенным (работает в полном языковом режиме), а сеанс не является доверенным (работает в ограниченном языковом режиме). Рекомендуется всегда экспортировать функции модуля по отдельности, указывая полное имя. + + + Импорт файла сценария в виде модуля + + + Импорт файла сценария "{0}" в качестве модуля будет запрещен в режиме ConstrainedLanguage. + + + Модуль содержит оператор Dot-Source + + + Импорт модуля "{0}" завершится сбоем в ограниченном языковом режиме, так как он экспортирует функции с использованием подстановочных знаков и при этом использует оператор dot-source. + + + "Функции, экспортируемые модулем + + + Модуль "{0}" экспортирует функции с использованием подстановочных знаков в именах. Имена всех функций вложенных модулей будут удалены при работе в ограниченном языковом режиме. + + + "Командлет New-Module + + + Для нового модуля из недоверенного сеанса ограниченного языка будет заблокировано предоставление блока сценария FullLanguage. + + + "Несовместимые языковые режимы модуля + + + Загружается зависимый модуль с языковым режимом, отличным от режима родительского модуля. В ограниченном языковом режиме это будет запрещено. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/MshHostRawUserInterfaceStrings.ru.resx b/src/System.Management.Automation/resources/ru/MshHostRawUserInterfaceStrings.ru.resx new file mode 100644 index 00000000000..a691bfd10c2 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/MshHostRawUserInterfaceStrings.ru.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}". + + + Значение "{0}" должно быть положительным целым числом. + + + Все строки являются нулевыми или пустыми. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/MshSignature.ru.resx b/src/System.Management.Automation/resources/ru/MshSignature.ru.resx new file mode 100644 index 00000000000..c369d55bd9e --- /dev/null +++ b/src/System.Management.Automation/resources/ru/MshSignature.ru.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 + + + Подпись проверена. + + + Файл {0} не содержит цифровой подписи. Невозможно выполнить этот сценарий в текущей системе. Для получения дополнительной информации о запуске сценариев и настройке политики выполнения см. раздел about_Execution_Policies по адресу https://go.microsoft.com/fwlink/?LinkID=135170 + + + Содержимое файла {0} могло быть изменено неавторизованным пользователем или процессом, поскольку хэш файла не совпадает с хэшем, хранящимся в цифровой подписи. Сценарий не может быть запущен в указанной системе. Для получения дополнительных сведений выполните команду Get-Help about_Signing. + + + Файл {0} подписан, но подписант не является доверенным в этой системе. + + + Невозможно подписать файл, поскольку система не поддерживает операции подписи файлов {0}. + + + Невозможно подписать файл, поскольку система не поддерживает операции подписи файлов, не имеющих расширения имени файла. + + + Подпись не может быть проверена, поскольку она несовместима с существующей системой. + + + Подпись не может быть проверена, поскольку она несовместима с существующей системой. Алгоритм хэширования недействителен. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/MshSnapInCmdletResources.ru.resx b/src/System.Management.Automation/resources/ru/MshSnapInCmdletResources.ru.resx new file mode 100644 index 00000000000..18f280ef06c --- /dev/null +++ b/src/System.Management.Automation/resources/ru/MshSnapInCmdletResources.ru.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 + + + Не удается выполнить операцию. Указанный командлет не поддерживается в пользовательской оболочке. + + + Оснастки PowerShell, совпадающие с шаблоном "{0}", не найдены. Проверьте шаблон и попробуйте повторить команду. + + + Формат указанного имени оснастки не является допустимым. В именах оснасток PowerShell могут содержаться только буквенно-цифровые символы, дефисы, подчеркивания и точки. Исправьте имя, а затем повторите операцию. + + + Не удается добавить оснастку PowerShell, {0} так как она является системным модулем PowerShell. Используйте команду Import-Module для загрузки модуля. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/MshSnapinInfo.ru.resx b/src/System.Management.Automation/resources/ru/MshSnapinInfo.ru.resx new file mode 100644 index 00000000000..b45bd3795ac --- /dev/null +++ b/src/System.Management.Automation/resources/ru/MshSnapinInfo.ru.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 + + + Не удалось получить доступ к сведениям реестра PowerShell. + + + Не удалось получить доступ к сведениям реестра PowerShell Engine. + + + Не удалось получить доступ к сведениям PublicKeyToken. + + + Версия {0} PowerShell недоступна на этом компьютере. + + + Оснастка PowerShell "{0}" не установлена на этом компьютере. + + + Обязательное значение {0} для ключа реестра {1} не указано. + + + Обязательное значение {0} имеет некорректный формат для ключа реестра {1}. Ожидаемый формат: "string". + + + Обязательное значение {0} имеет некорректный формат для ключа реестра {1}. Ожидаемый формат: "multistring". + + + Не удается найти необходимые сведения в реестре или отсутствуют ключевые файлы. Не удается загрузить некоторые командлеты. + + + Для версии PowerShell не зарегистрировано ни одного подключаемого модуля {0}. + + + Не удается получить строковый ресурс, так как объект чтения освобожден. + + + Значение версии {0} не указано или неверно для ключа реестра {1}. + + + Не найден атрибут [PSVersion] для типа PowerShell {0}. Добавьте атрибут PSVersion к типу с помощью [PSVersion(PowerShell SnapinBase.PSEngineVersion)]. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/NativeCP.ru.resx b/src/System.Management.Automation/resources/ru/NativeCP.ru.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/NativeCP.ru.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PSCommandStrings.ru.resx b/src/System.Management.Automation/resources/ru/PSCommandStrings.ru.resx new file mode 100644 index 00000000000..2a696196f76 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PSCommandStrings.ru.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 + + + Для добавления параметра требуется команда. Перед добавлением параметра в {0} необходимо добавить команду. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PSConfigurationStrings.ru.resx b/src/System.Management.Automation/resources/ru/PSConfigurationStrings.ru.resx new file mode 100644 index 00000000000..93bdaf35be1 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PSConfigurationStrings.ru.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 + + + Windows PowerShell перестал работать из-за проблемы безопасности: Не удается прочитать файл конфигурации: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PSDataBufferStrings.ru.resx b/src/System.Management.Automation/resources/ru/PSDataBufferStrings.ru.resx new file mode 100644 index 00000000000..36a592b964b --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PSDataBufferStrings.ru.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 + + + Указанный индекс меньше нуля или больше количества элементов в буфере. Индекс должен быть в диапазоне {0}-{1}. + + + Не удается преобразовать ссылку с null в тип значения. + + + Не удается преобразовать значение из типа {0} в тип {1}. + + + Нельзя добавлять объекты в закрытый буфер. Убедись, что буфер открыт, чтобы операции "Добавить" и "Вставить" прошли успешно. + + + Свойство SerializeInput можно задать только для типа PSObject в PSDataCollection. Установите для свойства SerializeInput значение false или измените тип коллекции на PSObject. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PSListModifierStrings.ru.resx b/src/System.Management.Automation/resources/ru/PSListModifierStrings.ru.resx new file mode 100644 index 00000000000..85d7c407467 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PSListModifierStrings.ru.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 + + + Обнаружен следующий неизвестный модификатор списка: "{0}". Допустимые модификаторы списка: Add, Remove и Replace. + + + Не удается применить обновление, так как объект не является поддерживаемой коллекцией. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PSStyleStrings.ru.resx b/src/System.Management.Automation/resources/ru/PSStyleStrings.ru.resx new file mode 100644 index 00000000000..671437be320 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PSStyleStrings.ru.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Указанная строка содержит печатный контент, тогда как она должна содержать только управляющие последовательности ANSI: {0} + + + Для правильной отрисовки MaxWidth для отрисовки хода выполнения должно быть не менее 18. + + + При добавлении или удалении расширений, расширение должно начинаться с точки. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ParameterBinderStrings.ru.resx b/src/System.Management.Automation/resources/ru/ParameterBinderStrings.ru.resx new file mode 100644 index 00000000000..a5f8540b762 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ParameterBinderStrings.ru.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Не удалось найти параметр, соответствующий имени параметра "{1}". + + + Не удается найти позиционный параметр, принимающий аргумент "{1}". + + + Отсутствует аргумент для параметра "{1}". Укажите параметр типа "{2}" и повторите попытку. + + + Не удается обработать параметр, так как имя параметра "{1}" неоднозначно. Возможные совпадения:{6}. + + + Не удается преобразовать "{6}" в тип "{2}", необходимый для параметра "{1}". {7} + + + "Не удается привязать параметр "{1}". {6} + + + Не удается привязать позиционные параметры "{1}". + + + "Не удается привязать позиционные параметры, поскольку имена не предоставлены". + + + Не удается разрешить набор параметров с использованием указанных именованных параметров. Один или несколько из указанных параметров не могут использоваться одновременно, или предоставлено недостаточное число параметров. + + + Не удается обработать команду из-за одного или более отсутствующих обязательных параметров:{1}. + + + Параметр "{1}" не может быть указан в наборе параметров "{6}". + + + Невозможно привязать параметр, поскольку параметр "{1}" указан более одного раза. Для передачи нескольких значений параметрам, которые могут принимать несколько значений, используйте синтаксис массива. Например, "-parameter value1,value2,value3". + + + Не удается вывести параметр "{1}", так как его аргумент указан как блок сценария и входные данные не указаны. Блок сценария не может быть оценен без ввода. + + + Сбой ввода в блок сценария для параметра "{1}". {6} + + + Не удается вывести параметр "{1}", так как входные данные его аргумента не производят выходных данных. + + + Входной объект не может быть привязан ни к одному из параметров команды потому, что команда не принимает входные данные из конвейера, или потому, что входные данные и их свойства не соответствуют ни одному из параметров, принимающих входные данные из конвейера. + + + Не удается привязать входной объект, так как он не содержит сведений, необходимых для привязки всех обязательных параметров: {6} + + + Не удается обработать входные данные конвейера, так как не удается получить значение параметра "{1}" по умолчанию. {6} + + + Не удается получить динамические параметры для этого командлета. {6} + + + Предоставьте значения для следующих параметров: + + + командлет в позиции {0} командного конвейера {1} + + + Невозможно обработать преобразование аргумента для параметра "{1}". {6} + + + {6} + + + Не удается проверить аргумент параметра "{1}". {6} + + + Не удается привязать параметр "{1}" к целевому объекту. {6} + + + Не удается привязать аргумент к параметру "{1}", так как он имеет значение null. + + + Не удается привязать аргумент к параметру "{1}", так как это пустая строка. + + + Не удается привязать аргумент к параметру "{1}", так как это пустая коллекция. + + + Не удается привязать аргумент к параметру "{1}", так как он является пустым массивом. + + + Не удается обработать команду. Параметр "{0}" определен несколько раз. + + + Не удается привязать командлет {0}, так как параметр "{1}" имеет тип "{2}" и метод Add() не может быть определен, или существует несколько методов Add(). {6} + + + Невозможно привязать командлет {0}, поскольку параметр "{1}", определяемый средой выполнения, добавлен в RuntimeDefinedParameterDictionary с ключом "{6}". Ключ должен совпадать с RuntimeDefinedParameter.Name. + + + Не удается привязать аргумент к параметру "{1}", так как psTypeNames аргумента не соответствует psTypeName, необходимому для параметра: {6}. + + + В $PSDefaultParameterValues параметра, совпадающих со следующим именем или псевдонимом, определено несколько различных значений по умолчанию: {0}. Эти значения по умолчанию проигнорированы. + + + Следующее имя или псевдоним, определенный в $PSDefaultParameterValues для этого $PSDefaultParameterValues, соединяется с несколькими параметрами: {0}. Значение по умолчанию пропущено. + + + {6} Эта ошибка могла быть вызвана применением привязки параметра по умолчанию. Вы можете отключить привязку параметров по умолчанию в $PSDefaultParameterValues, $PSDefaultParameterValues["Отключено"], чтобы $true и повторить попытку. Следующие параметры по умолчанию успешно привязаны для этого командлета при ошибке:{7} + + + {6} Эта ошибка может быть вызвана применением привязки параметра по умолчанию. Вы можете отключить привязку параметров по умолчанию в $PSDefaultParameterValues, $PSDefaultParameterValues ["Отключено"], чтобы $true и повторить попытку. Следующий параметр по умолчанию успешно привязан для этого командлета при ошибке:{7} + + + Сбой привязки значения по умолчанию "{0}" к параметру "{1}": {2} + + + Ключ "{0}" имеет не допустимый формат. Сведения о правильном формате см. about_Parameters_Default_Values в https://go.microsoft.com/fwlink/?LinkId=228266. + + + Ключи "{0}" имеют недопустимый формат. Сведения о правильном формате см. about_Parameters_Default_Values в https://go.microsoft.com/fwlink/?LinkId=228266. + + + Параметр "{0}" устарел. {1} + + + Ключ "{0}" типа "{1}" не является строкой. DefaultParameterDictionary принимает только ключи строки значений. + + + Ключ "{0}" уже добавлен в словарь. + + + Вызов метода или свойства не разрешен + + + Вызов метода или свойства "{0}" типа "{1}" не будет разрешен в режиме ограниченного языка для ненадежных сценариев. + + + Создание типа не разрешено + + + Создание типа "{0}" не будет разрешено во время привязки параметров в режиме ограниченного языка для недоверенных сценариев. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ParserStrings.ru.resx b/src/System.Management.Automation/resources/ru/ParserStrings.ru.resx new file mode 100644 index 00000000000..81c06d94102 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ParserStrings.ru.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Не удается загрузить сборку "{0}". + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PathUtilsStrings.ru.resx b/src/System.Management.Automation/resources/ru/PathUtilsStrings.ru.resx new file mode 100644 index 00000000000..3489cd0c669 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PathUtilsStrings.ru.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Кодирование "UTF-7" устарело. Используйте UTF-8. + + + Файл {0} уже существует, и указан {1}. + + + Невозможно открыть файл, поскольку текущий поставщик ({0}) не может открывать файлы. + + + Невозможно выполнить операцию, так как путь разрешается в несколько файлов. Эта команда не может работать с несколькими файлами. + + + Невозможно выполнить операцию, так как путь с подстановочными знаками {0} не разрешен в файл. + + + Неизвестное кодирование {0}; допустимые значения — {1}. + + + Каталог "{0}" уже существует. Используйте параметр Force, если хотите перезаписать каталог и файлы в нем. + + + Путь к пользовательскому модулю не существует, поэтому невозможно создать папку модуля для указанного имени модуля "{0}". + + + Не удается создать модуль {0} по следующей причине: {1}. Используйте другой аргумент для параметра -OutputModule и повторите попытку. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Не удается загрузить модуль, так как он был создан с помощью несовместимой версии командлета {0}. Создайте модуль с помощью командлета {0} из текущего сеанса и попробуйте загрузить модуль еще раз. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PipelineStrings.ru.resx b/src/System.Management.Automation/resources/ru/PipelineStrings.ru.resx new file mode 100644 index 00000000000..dcb74b40059 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PipelineStrings.ru.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Невозможно обработать экземпляр командлета, так как он уже используется другим конвейером. Обратитесь в службы поддержки клиентов Майкрософт. + + + Невозможно выполнить операцию, так как конвейер запущен. Остановите конвейер и повторите операцию. + + + Невозможно продолжить выполнение командлета, так как политика Stop запрещает запуск командлетов. + + + Не удается запустить конвейер, так как первый командлет в нем пытается прочитать входные данные из результатов предыдущего командлета. Измените или удалите первый командлет. Либо добавьте в конвейер командлет, выходные данные которого требуются первому командлету, а затем попробуйте запустить конвейер еще раз. + + + Невозможно обработать номер командлета. Функция ReadFromCommand должна указывать идентификатор командлета, который уже добавлен в конвейер. Обратитесь в службы поддержки клиентов Майкрософт. + + + Невозможно прочитать выходные данные функций ReadFromCommand и ReadErrorQueue, так как их уже читает другой командлет. Обратитесь в службы поддержки клиентов Майкрософт. + + + Невозможно запустить конвейер, так как в нем нет команд. Добавьте в конвейер хотя бы одну команду и запустите его снова. + + + Невозможно завершить операцию конвейера, так как он еще не запущен. Перед вызовом End() для пошагового конвейера необходимо вызвать метод Begin(). + + + Методы WriteObject и WriteError нельзя вызывать вне переопределений методов BeginProcessing, ProcessRecord и EndProcessing, и их можно вызывать только из одного потока. Проверьте, что командлет вызывает их правильно, или обратитесь в службы поддержки клиентов Майкрософт. + + + После вызова ThrowTerminatingError командлет сгенерировал исключение. +Первым исключением было "{0}" с трассировкой стека "{1}". +Вторым исключением было "{2}" с трассировкой стека "{3}". + + + Методы WriteObject и WriteError нельзя вызывать после закрытия конвейера. Обратитесь в службы поддержки клиентов Майкрософт. + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + Произошла ошибка при создании конвейера. + + + Этот конвейер не поддерживает семантику отключения и подключения. + + + Невозможно подключить этот конвейер, так как он не находится в отключенном состоянии. + + + С объектом пространства выполнения связана удаленная команда со значением null. Невозможно создать отключенный объект RemotePipeline, так как удаленная команда не указана. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/PowerShellStrings.ru.resx b/src/System.Management.Automation/resources/ru/PowerShellStrings.ru.resx new file mode 100644 index 00000000000..e31340dd106 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/PowerShellStrings.ru.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 + + + Состояние текущего экземпляра PowerShell недопустимо для этой операции. + + + Невозможно выполнить эту операцию, поскольку команда уже запущена. Дождитесь полной остановки команды или остановите эту команду, затем снова попробуйте выполнить эту операцию. + + + Команды не указаны. + + + Экземпляр PowerShell находится в неподходящем состоянии для создания вложенного экземпляра PowerShell. Вложенные экземпляры PowerShell следует создавать только в работающем экземпляре PowerShell. + + + Невозможно выполнить операцию, поскольку пространство выполнения не находится в состоянии "{0}". Текущее состояние пространства выполнения: "{1}". + + + Вложенные экземпляры PowerShell невозможно вызывать асинхронно. Используйте метод Invoke. + + + Объект {0} не был создан путем вызова {1} в этом экземпляре PowerShell. + + + Если для пространства выполнения задано повторное использование потока, состояние подразделения в параметрах вызова должно совпадать с пространством выполнения. + + + Если для пространства выполнения задано использование текущего потока, состояние подразделения в параметрах вызова должно совпадать с текущим потоком. + + + Для добавления параметра требуется команда. Перед добавлением параметра необходимо добавить команду в экземпляр PowerShell. + + + Ключи в словаре должны быть строками. + + + Нет доступного пространства выполнения для выполнения команд в этом потоке. Его можно указать в свойстве DefaultRunspace типа System.Management.Automation.Runspaces.Runspace. Вы попытались вызвать команду: {0} + + + Невозможно подключить объект PowerShell, поскольку он не связан с удаленным пространством выполнения или с пулом пространств выполнения. + + + Выполняющаяся команда отключена, но по-прежнему выполняется на удаленном сервере. Повторно установите подключение, чтобы получить состояние операции команды и выходные данные. + + + Невозможно выполнить операцию, поскольку текущий сеанс PowerShell находится в отключенном состоянии. Подключите этот сеанс PowerShell, а затем дождитесь завершения этой команды или остановите ее. + + + Невозможно выполнить операцию, поскольку текущий сеанс PowerShell находится в отключенном состоянии. Подключите этот сеанс PowerShell и повторите попытку. + + + Сбой подключения к удаленной команде. + + + Невозможно выполнить эту операцию, поскольку команда в настоящее время останавливается. Дождитесь полной остановки команды, затем снова попробуйте выполнить эту операцию. + + + Нет доступного пространства выполнения для выполнения команд в этом потоке. Его можно указать в свойстве DefaultRunspace типа System.Management.Automation.Runspaces.Runspace. Текущий экземпляр PowerShell не содержит команды для вызова. + + + Невозможно создать объект PowerShell, использующий текущее пространство выполнения, поскольку текущее пространство выполнения недоступно. Текущее пространство выполнения может запускаться, например, если оно создается с начальным состоянием сеанса. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ProgressRecordStrings.ru.resx b/src/System.Management.Automation/resources/ru/ProgressRecordStrings.ru.resx new file mode 100644 index 00000000000..f4531a27dd5 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ProgressRecordStrings.ru.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} не может быть отрицательным значением. + + + Не удается обработать аргумент, так как значение {0} не может быть пустым или равным NULL. + + + Не удается задать процент, так как {0} не может быть больше 100. + + + ParentActivityId не может совпадать с ActivityId. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ProviderBaseSecurity.ru.resx b/src/System.Management.Automation/resources/ru/ProviderBaseSecurity.ru.resx new file mode 100644 index 00000000000..b0fbb8558c8 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ProviderBaseSecurity.ru.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 + + + Невозможно использовать этот интерфейс, так как данный поставщик не поддерживает интерфейс ISecurityDescriptorCmdletProvider. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/ProxyCommandStrings.ru.resx b/src/System.Management.Automation/resources/ru/ProxyCommandStrings.ru.resx new file mode 100644 index 00000000000..05af2c982c6 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/ProxyCommandStrings.ru.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 + + + Параметр "help" не распознан как допустимый объект HelpInfo, созданный командой "get-help". + + + Невозможно сгенерировать прокси-команду, поскольку у параметра CommandMetadata отсутствует имя. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/RegistryProviderStrings.ru.resx b/src/System.Management.Automation/resources/ru/RegistryProviderStrings.ru.resx new file mode 100644 index 00000000000..0247852ffcb --- /dev/null +++ b/src/System.Management.Automation/resources/ru/RegistryProviderStrings.ru.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + Очистить элемент + + + Элемент: {0} + + + Новый элемент + + + Элемент: {0} + + + Удалить раздел + + + Элемент: {0} + + + Копировать раздел + + + Элемент: {0} Назначение: {1} + + + Переименовать элемент + + + Элемент: {0} NewName: {1} + + + Переместить элемент + + + Элемент: {0} Назначение: {1} + + + Задать свойство + + + Элемент: {0} Свойство: {1} + + + Очистить свойство + + + Элемент: {0} Свойство: {1} + + + Новое свойство + + + Элемент: {0} Свойство: {1} + + + Удалить свойство + + + Элемент: {0} Свойство: {1} + + + Переименовать свойство. + + + Элемент: {0} SourceProperty: {1} DestinationProperty: {2} + + + Копировать свойство + + + Элемент: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Переместить свойство + + + Элемент: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Операция не обработана. Указанное расположение не позволяет выполнить эту операцию. + + + Операция не разрешена в исходном расположении. + + + Операция не разрешена в целевом расположении. + + + Параметры конфигурации для локального компьютера + + + Параметры программного обеспечения для текущего пользователя + + + Раздел в этом пути уже существует. + + + Операция не может быть выполнена, так как путь назначения является вложенным по отношению к исходному пути. + + + Свойство уже существует. + + + Свойство {0} не существует в пути {1}. + + + Раздел реестра по указанному пути не существует. + + + Не удалось привязать параметр Type. Не удалось преобразовать {0} в {1}. Возможные значения перечисления: "String, ExpandString, Binary, DWord, MultiString, QWord, Unknown". + + + Раздел {0} создан, но не удалось задать значение по умолчанию. + + + Не удалось создать диск с указанным корнем. Корневой путь не существует. + + + Элемент невозможно переименовать, так как элемент с таким именем уже существует в том же контейнере. + + + Имя раздела реестра должно начинаться с допустимого имени базового раздела. + + + Недопустимый аргумент подраздела. + + + Не удается удалить дерево подразделов, так как подраздел не существует. + + + Значение с таким именем не существует. + + + Недопустимое значение перечисления {0}. + + + Необходимо указать аргумент значения. + + + Необходимо указать имя аргумента. + + + Указанное значение RegistryValueKind недопустимо. + + + Метод RegistryKey.SetValue не поддерживает массив String[], содержащий ссылку null. + + + Длина подраздела реестра не должна превышать 255 символов. + + + Необходимо указать непустое имя подраздела. + + + Тип объекта значения не соответствует указанному RegistryValueKind, или объект не удалось преобразовать. + + + RegistryKey.SetValue не поддерживает массивы типа {0}. Поддерживаются только Byte[] и String[]. + + + Указанный раздел реестра не существует. + + + Длина указанного значения превышает максимальное значение в 16383 символов. + + + Размер указанных данных значения превышает 1 МБ. + + + Указанный подраздел реестра не существует. + + + Указанное значение RegistryKeyPermissionCheck недопустимо. + + + Раздел реестра содержит подразделы. Этот метод не поддерживает рекурсивное удаление. + + + Невозможно создать дескриптор KTM без Transaction.Current или указанной транзакции. + + + Указанная транзакция или Transaction.Current должны соответствовать транзакции, использованной для создания или открытия этого TransactedRegistryKey. + + + Объект TransactedRegistryKey не связан с транзакцией, так как он предназначен для предопределенного раздела. + + + Запрошенный доступ к реестру не разрешен. + + + Доступ к разделу реестра {0} запрещен. + + + Не удается выполнить запись в раздел реестра. + + + Не удается получить доступ к закрытому разделу реестра. + + + Неизвестная ошибка: {0}. + + + Транзакции реестра не поддерживаются на этой платформе. + + + Указан недопустимый дескриптор. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/RemotingErrorIdStrings.ru.resx b/src/System.Management.Automation/resources/ru/RemotingErrorIdStrings.ru.resx new file mode 100644 index 00000000000..4ec3d094ee3 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/RemotingErrorIdStrings.ru.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + Подстановочные знаки не поддерживаются для параметра FilePath. Укажите путь без подстановочных знаков. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + Необходимо указать значение {0} для параметра сеанса {1}. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + Максимальное число перенаправлений URI WS-Man, разрешенных при подключении к удаленному компьютеру + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + Параметр WriteEvents нельзя использовать без параметра Wait. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + Удаленное взаимодействие PowerShell не поддерживается в среде предустановки Windows (WinPE). + + + Изменения, внесенные {0}, не вступят в силу до перезапуска службы WinRM. + + + {0} может потребоваться перезапуск службы WinRM, если конфигурация с этим именем была недавно отменена, так как определенные структуры системных данных могут все еще находиться в кэше. В этом случае может потребоваться перезапуск WinRM. +Все сеансы WinRM, подключенные к конфигурациям сеансов PowerShell (например, Microsoft.PowerShell или конфигурациям, созданным с помощью командлета Register-PSSessionConfiguration), будут отключены. + + + Вы работаете в удаленном сеансе и выбрали параметр Force (принудительное выполнение), что может привести к перезапуску службы WinRM. Если служба WinRM перезапустится, текущий удаленный сеанс будет завершен, и для продолжения работы вам потребуется создать новый сеанс. + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + Параметр -WriteJobInResults нельзя использовать без параметра -Wait. + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + Переданный входной поток недопустим. В качестве потока ввода поддерживается только {0}. + + + Переданный набор потоков вывода недопустим. В качестве потока вывода поддерживается только {0}. + + + Предоставленные данные WSMAN_SENDER_DETAILS недействительны. Не удается обработать значение WSMAN_SENDER_DETAILS, равное нулю. + + + Указанный контекст оболочки недействителен. + + + {0} + + + Значение NULL недопустимо для {0} с методом подключаемого модуля {1}. + + + Значение NULL недопустимо для набора потоков ввода и вывода. {0} и {1} — поддерживаемые потоки ввода и вывода. + + + Значение NULL недопустимо для {0} с методом подключаемого модуля {1}. + + + Значение NULL недопустимо для {0} с методом подключаемого модуля {1}. + + + Работа подключаемого модуля PowerShell завершается. Это может произойти, если завершается работа службы размещения или приложения. + + + Подключаемый модуль PowerShell не распознает параметр {0}. Убедитесь, что клиент совместим с сборкой {1} и версией протокола {2} PowerShell. + + + От клиента ожидается параметр с именем {0}. Убедитесь, что клиент совместим с сборкой {1} и версией протокола {2} PowerShell. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">Подключаемый модуль PowerShell не поддерживает версию протокола {2}, запрошенную клиентом.</PSProtocolVersionError> + + + При передаче контекста службе WSMan в подключаемом модуле PowerShell произошла неустранимая ошибка. + + + Не удалось создать сеанс управляемого сервера. + + + При регистрации дескриптора ожидания для уведомления о завершении работы в подключаемом модуле PowerShell произошла неустранимая ошибка. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + Не удалось найти исполняемый файл {0}. Убедитесь, что установлена функция WOW64. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + Не удается создать процесс Windows PowerShell, так как Windows PowerShell не найден на этом компьютере. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/RunspaceInit.ru.resx b/src/System.Management.Automation/resources/ru/RunspaceInit.ru.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/RunspaceInit.ru.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/RunspacePoolStrings.ru.resx b/src/System.Management.Automation/resources/ru/RunspacePoolStrings.ru.resx new file mode 100644 index 00000000000..23f2d93afaf --- /dev/null +++ b/src/System.Management.Automation/resources/ru/RunspacePoolStrings.ru.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Максимальный размер пула не может быть меньше 1. + + + Минимальный размер пула не может быть меньше 1. + + + Минимальный размер пула не может быть больше максимального размера пула. + + + Состояние пула пространств выполнения недопустимо для этой операции. + + + Не удается выполнить операцию, так как пул пространств выполнения не находится в состоянии {0}. Текущее состояние: {1}. + + + Не удается открыть пул пространств выполнения, так как он не находится в состоянии BeforeOpen. Текущее состояние: {0}. + + + Объект {0} не был создан путем вызова {1} в текущем экземпляре RunspacePool. + + + Не удается освободить пространство выполнения в текущий пул, так как это пространство выполнения не принадлежит текущему пулу. + + + Это свойство нельзя изменить после открытия пула пространства выполнения. + + + Это пространство выполнения не поддерживает операции отключения и подключения. + + + Не удается выполнить операцию, так как пул пространств выполнения находится в состоянии «Отключено». + + + Операция отключения не поддерживается на сервере. Для поддержки отключения удаленного пула пространств выполнения сервер должен работать под управлением PowerShell 3.0 или более поздней версии. + + + Этот пул пространств выполнения {0} не настроен на предоставление отключенных объектов PowerShell для команд, выполняемых на удаленном сервере. Используйте статический метод GetRunspacePools() класса RunspacePool, чтобы выполнить запрос к серверу и вернуть объекты пулов пространств выполнения, настроенные для этого. + + + Не удается подключить этот пул пространств выполнения, так как соответствующий пул пространств выполнения на стороне сервера подключен к другому клиенту. + + + ResetRunspaceState не поддерживается на сервере. Сервер должен работать под управлением PowerShell 5.0 или более поздней версии. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/RunspaceStrings.ru.resx b/src/System.Management.Automation/resources/ru/RunspaceStrings.ru.resx new file mode 100644 index 00000000000..aad8128d283 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/RunspaceStrings.ru.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Указанное состояние пространства выполнения недопустимо для этой операции. + + + Не удается открыть пространство выполнения, так как оно не находится в состоянии BeforeOpen. Текущее состояние пространства выполнения: "{0}". + + + Не удается выполнить операцию, так как пространство выполнения не находится в состоянии "Открыто". Текущее состояние пространства выполнения: "{0}". + + + Не удается вызвать конвейер, так как пространство выполнения не находится в состоянии "Открыто". Текущее состояние пространства выполнения: "{0}". + + + Состояние конвейера недопустимо для этой операции. + + + Не удается вызвать конвейер, так как он уже был вызван. + + + Допустимое значение параметра — PipelineResultTypes.Output. + + + Конвейер не содержит команды. + + + Конвейер не был запущен, так как уже выполняется другой конвейер. Конвейеры не могут выполняться одновременно. + + + Вложенный конвейер не может быть вызван асинхронно. Используйте вызов метода. + + + Вложенный конвейер следует запускать только из выполняющегося конвейера. + + + Пространство выполнения невозможно закрыть, пока выполняется вызов метода SessionStateProxy. + + + Конвейер невозможно вызвать, пока выполняется вызов метода SessionStateProxy. + + + Выполняется вызов метода SessionStateProxy. Параллельные вызовы метода SessionStateProxy не разрешены. + + + Конвейер уже выполняется. Параллельные вызовы метода SessionStateProxy не разрешены. + + + Это свойство не может быть изменено после открытия пространства выполнения. + + + Произошла одна или несколько ошибок при обработке модуля "{0}", указанного в объекте InitialSessionState, который используется для создания этого пространства выполнения. Полный список ошибок см. в свойстве ErrorRecords. Первая ошибка: {1} + + + Параметры потока можно изменить, только если используется многопотоковое подразделение (MTA), текущие параметры — UseNewThread или UseCurrentThread, а новое значение — ReuseThread. + + + {0} не может иметь значение false, если языковой режим — {1} или {2}. + + + Невозможно отключить пространство выполнения, доступное только локально. + + + Операция подключения не поддерживается в локальных пространствах выполнения. + + + Сеанс занят. Подключение к сеансу будет установлено, как только он станет доступным. Чтобы отменить команду Enter-PSSession, нажмите Ctrl-C. + + + Не удается выполнить команду. В этой конфигурации сеанса вызов сценария не поддерживается. Это может происходить, если конфигурация сеанса работает в режиме без языка. + + + Операции отключения и подключения не разрешается использовать в локальных пространствах выполнения. + + + Не удается подключить конвейер, так как пространство выполнения не находится в состоянии "Открыто". Текущее состояние пространства выполнения: "{0}". + + + Не удается создать RemoteRunspace. Указанный объект RunspacePool недопустим. + + + С этим пространством выполнения не связана ни одна отключенная команда. + + + Операция отключения не поддерживается на удаленном компьютере. Чтобы поддерживать отключение, на удаленном компьютере должна быть запущена оболочка Windows PowerShell 3.0 или более поздней версии, а также должен использоваться транспорт WSMan. + + + Не удается подключить PSSession, так как сеанс не находится в состоянии "Отключено" или недоступен для подключения. + + + Параметр не может иметь значение PipelineResultTypes.None или PipelineResultTypes.Output. + + + Допустимое значение параметра — PipelineResultTypes.Output или PipelineResultTypes.Null. + + + Перенаправление потока отладки не поддерживается на целевом удаленном компьютере. + + + Перенаправление детализированного потока не поддерживается на целевом удаленном компьютере. + + + Перенаправление потока предупреждения не поддерживается на целевом удаленном компьютере. + + + Перенаправление потока информации не поддерживается на целевом удаленном компьютере. + + + Вы вошли в сеанс, который занят выполнением команды или сценария. Выходные данные направляются в задание "{0}", поэтому они не будут отображаться в консоли. Вы можете дождаться завершения выполнения команды или отменить ее и получить запрос на ввод, нажав Ctrl-C. + + + + Вы вошли в сеанс, который занят выполнением команды или сценария. Выходные данные будут отображаться в консоли. Вы можете дождаться завершения выполнения команды или отменить ее и получить запрос на ввод, нажав Ctrl-C. + + + + Вы вошли в сеанс, который сейчас остановлен в точке останова отладки в выполняемой команде или сценарии. Используйте отладчик командной строки PowerShell, чтобы продолжить отладку. + + + + Свойство DefaultRunspace должно иметь значение LocalRunspace + + + Статическое свойство PrimaryRunspace можно задать только один раз. Оно уже задано. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/SecuritySupportStrings.ru.resx b/src/System.Management.Automation/resources/ru/SecuritySupportStrings.ru.resx new file mode 100644 index 00000000000..f3f4eabd1a1 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/SecuritySupportStrings.ru.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Не удается загрузить сертификат. {0} должен разрешаться в путь файловой системы. + + + Сертификат {0} нельзя использовать для шифрования. Сертификаты шифрования должны содержать атрибуты использования ключа «Шифрование данных» или «Шифрование ключа», а также включать расширенное использование ключа (EKU) «Шифрование документа» ({1}). + + + Не удается загрузить сертификат. Идентификатор {0} соответствует нескольким сертификатам. Чтобы зашифровать данные для нескольких получателей, укажите несколько конкретных значений для параметра {1}, а не подстановочный знак, который соответствует нескольким сертификатам. + + + Не удается загрузить сертификат шифрования. Параметр сертификата {0} не является допустимым сертификатом в кодировке Base-64 и не указывает на допустимый сертификат по файлу, каталогу, отпечатку или имени субъекта. + + + ПРЕДУПРЕЖДЕНИЕ. Сертификат {0} содержит закрытый ключ. Защищенные сертификаты ведения журнала событий, используемые для шифрования, должны содержать только открытый ключ. + + + ОШИБКА: Не удалось защитить сообщение журнала событий {0}: {1} + + + ОШИБКА: не удалось найти или использовать сертификат: {0} + + + Ключ сеанса недоступен для шифрования защищенной строки. + + + Недопустимое смещение буфера. + + + Недопустимые данные открытого ключа. + + + Не удается импортировать открытый ключ. + + + Недопустимые данные сеансового ключа. + + + Файл сценария {0} заблокирован системной политикой и не будет запущен. + + + Возвращено неизвестное значение принудительного применения политики для файла сценария: {0}. + + + Чтение файла сценария + + + Файл сценария {0} не является доверенным политикой и будет работать в режиме ConstrainedLanguage. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/Serialization.ru.resx b/src/System.Management.Automation/resources/ru/Serialization.ru.resx new file mode 100644 index 00000000000..0e4510e0250 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/Serialization.ru.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} ожидался атрибут. + + + XML-тег {0} не распознается. + + + Не найден объект для referenceId {0}. + + + Атрибут Name для ключа словаря указан неверно. + + + Атрибут Name для значения словаря указан неверно. + + + Версия PSObject недопустима. + + + Версия входящего PSObject {0}. Ожидаемое значение — 1. + + + Невозможно обработать имена, так как для referenceId {0} не найдено ни одного TypeName. + + + Значение параметра глубины должно быть больше или равно 1. + + + Текущий тип узла — {0}. Ожидался тип — {1}. + + + Ключ для записи словаря не указан. + + + Значение для записи словаря не указано. + + + Больше нет объектов для десериализации. + + + В качестве ключа словаря указано значение Null. + + + Содержимое {0} примитивного типа недопустимо. + + + Сериализованный XML вложен слишком глубоко. + + + Сериализатор был закрыт. + + + Данные в команде превысили максимальный размер, разрешенный конфигурацией сеанса. Максимально допустимый размер — {0} МБ. Измените входные данные, используйте другую конфигурацию сеанса или измените свойства {1} и {2} в конфигурации сеанса на удаленном компьютере. + + + Не удалось выполнить десериализацию зашифрованной защищенной строки + + + Недопустимый тип ключа {0}. Класс PSPrimitiveDictionary принимает только ключи типа System.String. + + + Тип значения {0} недопустим. Класс PSPrimitiveDictionary принимает только значения типов, которые полностью сериализуются при удаленном взаимодействии PowerShell. Список полностью сериализуемых типов см. в разделе справки about_Remoting. + + + Не удалось расшифровать данные. Данные не были зашифрованы с помощью этого ключа. + + + Значение параметра {0} не является допустимой зашифрованной строкой. + + + Указанный {0} недопустим. Допустимые значения длины {0} — 128 бит, 192 бита или 256 бит. + + + Десериализация SecureString сейчас поддерживается только в Windows. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/SessionStateProviderBaseStrings.ru.resx b/src/System.Management.Automation/resources/ru/SessionStateProviderBaseStrings.ru.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/SessionStateProviderBaseStrings.ru.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/SessionStateStrings.ru.resx b/src/System.Management.Automation/resources/ru/SessionStateStrings.ru.resx new file mode 100644 index 00000000000..eaa87fc7490 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/SessionStateStrings.ru.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Невозможно обработать возвращенные сведения, так как сведения, возвращенные методом Start поставщика, относятся к поставщику, отличному от переданного. + + + Невозможно обработать возвращенные сведения, так как сведения, возвращенные методом Start поставщика, имеют значение null. + + + Попытка выполнить операцию GetItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции GetItem для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию SetItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции SetItem для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию ClearItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию InvokeDefaultAction с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции InvokeDefaultAction для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию ItemExists с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции ItemExists для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию IsValidPath с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию IsItemContainer с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию RemoveItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию GetChildItems с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции GetChildItems для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию GetChildNames с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции GetChildNames для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию RenameItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции RenameItem для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию NewItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции NewItem для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию HasChildItems с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию CopyItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции CopyItem для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию GetParentPath с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию NormalizeRelativePath с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию MakePath с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию GetChildName с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию MoveItem с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции MoveItem для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию GetProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции GetProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию SetProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции SetProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию ClearProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции ClearProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию NewProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции NewProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию RemoveProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции RemoveProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию CopyProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции CopyProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию MoveProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для операции MoveProperty для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию RenameProperty с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается получить динамические параметры для RenameProperty для поставщика "{0}" на пути "{1}". {2} + + + Не удается получить средство чтения содержимого для поставщика "{0}" на пути "{1}". {2} + + + Не удается получить динамические параметры для операции GetContentReader для поставщика "{0}" на пути "{1}". {2} + + + Не удается получить модуль записи содержимого для поставщика "{0}" на пути "{1}". {2} + + + Не удается получить динамические параметры для операции GetContentWriter для поставщика "{0}" на пути "{1}". {2} + + + Не удается получить содержимое, так как это каталог: "{0}". Вместо этого используйте "Get-ChildItem". + + + Не удалось записать содержимое, так как это каталог: "{0}". + + + Не осталось журнала расположений, чтобы перейти назад. + + + Не осталось журнала расположений, чтобы перейти вперед. + + + Элемент BoundedStack пустой. + + + Попытка выполнить операцию ClearContent с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Не удается очистить содержимое "{0}", так как это каталог. Clear-Content поддерживается только для файлов. + + + Не удается получить динамические параметры для операции ClearContent для поставщика "{0}" на пути "{1}". {2} + + + Попытка выполнить операцию GetSecurityDescriptor с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию SetSecurityDescriptor с поставщиком "{0}" для пути "{1}" не удалась. {2} + + + Попытка выполнить операцию Start с поставщиком "{0}" не удалась. {1} + + + Попытка выполнить операцию InitializeDefaultDrives с поставщиком "{0}" не удалась. + + + Попытка выполнить операцию NewDrive с поставщиком "{0}" для диска с корнем "{1}" не удалась. {2} + + + Не удается получить динамические параметры для NewDrive для поставщика "{0}". {1} + + + Сбой вызова RemoveDrive с поставщиком "{0}". {1} + + + Невозможно удалить диск "{0}", так как это запрещено поставщиком "{1}". + + + Путь "{0}" указывал на элемент, расположенный за пределами базы '{1}'. + + + Сбой вызова Seek в модуле записи содержимого поставщика "{0}" на пути "{1}". {2} + + + Сбой вызова Close в модуле чтения или записи содержимого поставщика "{0}" для пути "{1}". {2} + + + Сбой вызова Read в модуле чтения содержимого поставщика "{0}" для пути "{1}". {2} + + + Сбой вызова Write в модуле записи содержимого поставщика "{0}" на пути "{1}". {2} + + + Поставщик "{0}" нельзя использовать для получения или задания данных с помощью синтаксиса переменных. {2} + + + Синтаксис переменных нельзя использовать для получения или задания данных в поставщике. {2} + + + Псевдоним не подлежит записи, так как псевдоним {0} является константой или доступен только для чтения, и запись в него не может быть выполнена. + + + Невозможно записать в функцию {0}, так как она доступна только для чтения или является константой. + + + Невозможно перезаписать переменную {0}, так как она доступна только для чтения или является константой. + + + Невозможно получить доступ к переменной "${0}", так как это частная переменная. + + + Невозможно получить доступ к команде "{0}", так как это частная команда. + + + Невозможно получить доступ к команде, так как это частная команда. + + + Невозможно получить доступ к ресурсу состояния сеанса, так как это частный ресурс. + + + Псевдоним не был удален, так как псевдоним {0} является константой или доступен только для чтения. + + + Невозможно удалить функцию {0}, так как она является константой. + + + Невозможно удалить переменную {0}, так как она является константой или доступна только для чтения. Если переменная доступна только для чтения, повторите операцию, указав параметр Force. + + + Невозможно изменить псевдоним {0}, так как он является константой. + + + Псевдоним {0} нельзя изменить, поскольку он доступен только для чтения. + + + Невозможно изменить функцию {0}, так как она является константой. + + + Невозможно изменить функцию {0}, так как она доступна только для чтения. + + + После создания псевдоним {0} нельзя сделать константой. Псевдонимы можно делать константами только при создании. + + + Существующую функцию {0} нельзя сделать константой. Функции можно делать константами только при создании. + + + Существующую переменную {0} нельзя сделать константой. Переменные можно сделать константами только при создании. + + + Параметр AllScope нельзя удалить из псевдонима "{0}". + + + Параметр AllScope нельзя удалить из функции "{0}". + + + Параметр AllScope нельзя удалить из переменной "{0}". + + + Определение функции "{0}" содержало квалификатор области, но не содержало имени функции. + + + Не удается удалить поставщика {0}. Перед удалением поставщика {0} необходимо удалить все диски, связанные с поставщиком {0}. + + + Невозможно обработать имя диска, так как оно содержит один или несколько следующих недопустимых символов: ; ~ / \ . : + + + Не удалось создать новый диск, так как поставщик не разрешает создание нового диска. + + + Указанное значение "{0}" разрешено в более чем один стек расположений. + + + Не удается найти стек расположений "{0}". Он не существует или не является контейнером. + + + не удается найти путь "{0}", поскольку он не существует. + + + Невозможно найти псевдоним, так как псевдоним "{0}" не существует. + + + Невозможно задать расположение, так как путь "{0}" был разрешен в несколько контейнеров. Можно задать расположение только для одного контейнера за раз. + + + Невозможно обработать переменную, так как путь к переменной "{0}" разрешается в несколько элементов. Получать или задавать значение переменной можно только для одного элемента за раз. + + + Не удается найти диск. Диск с именем "{0}" не существует. + + + Не удается найти поставщика с именем "{0}". + + + Не удается найти поставщика с именем "{0}". Имя указано в неправильном формате. Имя поставщика может содержать только буквенно-цифровые символы или имя оснастки PowerShell, за которым следует один символ "\", а затем буквенно-цифровые символы. + + + "{0}" разрешается в несколько имен поставщиков. Возможные совпадения:{1}. + + + Произошла ошибка при попытке создать экземпляр поставщика. Имя типа поставщика "{0}" не найдено в сборке. + + + Указанное имя поставщика "{0}" нельзя использовать, так как оно содержит один или несколько следующих недопустимых символов: \ [ ] ? * : + + + Произошла ошибка при попытке создать экземпляр поставщика "{0}". {1} + + + Не удается найти переменную с именем "{0}". + + + Не удается найти источник трассировки с именем "{0}". + + + Диск с именем "{0}" уже существует. + + + Переменная с именем "{0}" уже существует. + + + Псевдоним недопустим, так как псевдоним с именем "{0}" уже существует. + + + Невозможно зарегистрировать поставщика командлетов, так как поставщик командлетов с именем "{0}" уже существует. + + + Путь не указывал на путь файловой системы. + + + Нельзя удалить глобальную область. + + + Число области "{0}" превышает количество активных областей. + + + Невозможно сравнить PSDriveInfo. Экземпляр PSDriveInfo можно сравнивать только с другим экземпляром PSDriveInfo. + + + Поставщик командлетов не может передавать результаты в виде потока, так как не указан командлет, через который следует передавать выходные данные. + + + Поставщик командлетов не может передавать результаты в виде потока, так как не указан командлет, через который следует передавать ошибку. + + + Не задано домашнее расположение для этого поставщика. Чтобы задать домашнее расположение, вызовите "(get-psprovider '{0}').Home = 'path'". + + + Неправильный формат пути. Пути поставщика должны содержать идентификатор поставщика, за которым следует "::", а затем путь, относящийся к конкретному поставщику. + + + Невозможно переместить элемент, так как путь назначения может быть разрешено только в один путь. + + + Невозможно переместить элемент, так как исходный путь и путь назначения не были разрешены в одинаковый поставщик. + + + Невозможно переместить элемент, так как исходный путь указывает на один или несколько элементов, а путь назначения не является контейнером. Убедитесь, что путь назначения является контейнером, и повторите попытку. + + + Невозможно переместить элемент, так как назначение разрешено в несколько путей. Укажите путь назначения, который разрешается в одно назначение, и повторите попытку. + + + Невозможно скопировать контейнер в существующий конечный элемент. + + + Невозможно скопировать контейнер в другой контейнер. Параметр -Recurse или -Container не указан. + + + Исходный путь и путь назначения не разрешились в одинаковый поставщик. + + + Невозможно переименовать элемент, так как путь разрешен в несколько элементов. Можно переименовать только один элемент за раз. + + + Поставщик "{0}" нельзя использовать для разрешения пути "{1}" из-за ошибки в поставщике. + + + Невозможно использовать интерфейс. Интерфейс IContentCmdletProvider не реализован этим поставщиком. + + + Невозможно использовать интерфейс. Интерфейс IPropertyCmdletProvider не поддерживается этим поставщиком. + + + Невозможно использовать интерфейс. Интерфейс IDynamicPropertyCmdletProvider не реализован этим поставщиком. + + + Методы NavigationCmdletProvider не поддерживаются этим поставщиком. + + + Методы поставщика не обработаны. Методы ContainerCmdletProvider не поддерживаются этим поставщиком. + + + Невозможно вызвать методы. Методы ItemCmdletProvider не поддерживаются этим поставщиком. + + + Методы DriveCmdletProvider не поддерживаются этим поставщиком. + + + Операция поставщика остановлена, так как этот поставщик не поддерживает ее. + + + Операция поставщика остановлена, так как поставщик не поддерживает параметр "Depth". + + + Невозможно вызвать метод. Метод Seek для содержимого не поддерживается этим поставщиком. + + + Не удается выполнить операцию ClearContent. Операция ClearContent не поддерживается этим поставщиком. + + + Поставщик не поддерживает использование учетных данных. Повторите операцию, не указывая учетные данные. + + + Поставщик FileSystem поддерживает учетные данные только в командлете New-PSDrive. Повторите операцию, не указывая учетные данные. + + + Поставщик не поддерживает транзакции. Выполните операцию еще раз без параметра -UseTransaction. + + + Невозможно вызвать метод. Поставщик не поддерживает использование фильтров. + + + Не удается создать диск. Поставщик не поддерживает использование учетных данных. + + + Элемент в пути "{0}" уже существует. + + + Невозможно скопировать элемент. Элемент на пути "{0}" не существует. + + + Элемент на пути "{0}" не существует. + + + Диск, содержащий представление псевдонимов, хранящихся в состоянии сеанса + + + Диск, содержащий представление переменных сред процесса + + + Диск, содержащий представление функций, хранящихся в состоянии сеанса + + + Диск, содержащий представление тех переменных, которые хранятся в состоянии сеанса + + + Диск, сопоставляемый с путем к временному каталогу текущего пользователя + + + Невозможно создать связь "{0}", так как не указано целевое значение. + + + Ссылки на переменную null всегда возвращают значение null. Присваивания не имеют эффекта. + + + Максимальное число объектов журнала, сохраняемых в сеансе + + + Невозможно переименовать функцию, так как функция {0} доступна только для чтения или является константой. + + + Невозможно переименовать псевдоним, так как псевдоним {0} доступен только для чтения или является константой. + + + Невозможно переименовать переменную, так как переменная {0} доступна только для чтения или является константой. + + + Не удается задать параметры для локальной переменной {0}. Используйте New-Variable, чтобы создать переменную, для которой можно задать параметры. + + + Командлет {0} нельзя изменить, поскольку он доступен только для чтения. + + + Невозможно удалить переменную {0}, так как она оптимизирована и не подлежит удалению. Попробуйте использовать командлет Remove-Variable (без псевдонимов) или вызвать с использованием точки команду, которую используете для удаления переменной. + + + Невозможно перезаписать переменную {0}, так как она была оптимизирована. Попробуйте использовать командлет New-Variable или Set-Variable (без псевдонимов) либо вызвать, с использованием точки, команду, которой задаете переменную. + + + Параметры {0} и {1} нельзя использовать вместе. Укажите только один из этих параметров. + + + Параметр Tail сейчас поддерживается только для поставщика FileSystem. + + + Псевдоним недопустим, так как команда с именем "{0}" и типом команды "{1}" уже существует. + + + Не удается запустить программное обеспечение. Разрешение отклонено. + + + Параметры "-{0}" и "-{1}" являются взаимоисключающими, то есть не могут быть указаны одновременно. + + + Путь "{0}" недопустим. В операциях удаленного копирования поддерживаются только абсолютные пути. + + + Невозможно проверить удаленный путь "{0}". + + + Невозможно выполнить операцию, так как для сеанса {0} задано значение {1}. + + + Параметр "{0}" не может быть пустым или иметь значение null. + + + Переменные состояния сеанса + + + В режиме ConstrainedLanguage будет запрещено устанавливать или изменять значение AllScope для области переменной "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/StringDecoratedStrings.ru.resx b/src/System.Management.Automation/resources/ru/StringDecoratedStrings.ru.resx new file mode 100644 index 00000000000..660d45c5122 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/StringDecoratedStrings.ru.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Для этого метода поддерживается только "ANSI" или "PlainText". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/SubsystemStrings.ru.resx b/src/System.Management.Automation/resources/ru/SubsystemStrings.ru.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/ru/SubsystemStrings.ru.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/SuggestionStrings.ru.resx b/src/System.Management.Automation/resources/ru/SuggestionStrings.ru.resx new file mode 100644 index 00000000000..16f5acc9d6b --- /dev/null +++ b/src/System.Management.Automation/resources/ru/SuggestionStrings.ru.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 + + + Команда {0} не найдена, но существует в текущем расположении. +По умолчанию PowerShell не загружает команды из текущего расположения по умолчанию (см. Get-Help about_Command_Precedence). + +Если этой команде можно доверять, вместо этого выполните следующую команду: + + + Наиболее похожие команды: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/TabCompletionStrings.ru.resx b/src/System.Management.Automation/resources/ru/TabCompletionStrings.ru.resx new file mode 100644 index 00000000000..ca874810b6a --- /dev/null +++ b/src/System.Management.Automation/resources/ru/TabCompletionStrings.ru.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Результат автодополнения по клавише Tab не может быть корректно десериализован, поскольку удаленное пространство выполнения не содержит экземпляра TypeTable. + + + Невозможно получить доступ к свойствам нулевого экземпляра типа CompletionResult. + + + Побитовое НЕ + + + Логическое не. Отрицает следующее за ним утверждение. + + + Равно - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, равные правому операнду; в противном случае возвращает TRUE, если левый операнд равен правому операнду. + + + Равно - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, равные правому операнду; в противном случае возвращает TRUE, если левый операнд равен правому операнду. + + + Равно - регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, равные правому операнду; в противном случае возвращает TRUE, если левый операнд равен правому операнду. + + + Не равно - регистр не учитывается. Если левый операнд является коллекцией, возвращает значения из коллекции, которые не равны правому операнду; в противном случае возвращает TRUE, если левый операнд не равен правому операнду. + + + Не равно - регистр не учитывается. Если левый операнд является коллекцией, возвращает значения из коллекции, которые не равны правому операнду; в противном случае возвращает TRUE, если левый операнд не равен правому операнду. + + + Не равно - регистр имеет значение. Если левый операнд является коллекцией, возвращает значения из коллекции, которые не равны правому операнду; в противном случае возвращает TRUE, если левый операнд не равен правому операнду. + + + Больше или равно - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые больше или равны правому операнду; в противном случае возвращает TRUE, если левый операнд больше или равен правому операнду. + + + Больше или равно - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые больше или равны правому операнду; в противном случае возвращает TRUE, если левый операнд больше или равен правому операнду. + + + Больше или равно - регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые больше или равны правому операнду; в противном случае возвращает TRUE, если левый операнд больше или равен правому операнду. + + + Больше чем - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые больше правого операнда; в противном случае возвращает TRUE, если левый операнд больше правого. + + + Больше чем - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые больше правого операнда; в противном случае возвращает TRUE, если левый операнд больше правого. + + + Больше чем - регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые больше правого операнда; в противном случае возвращает TRUE, если левый операнд больше правого. + + + Меньше чем — без учета регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые меньше правого операнда; в противном случае возвращает TRUE, если левый операнд меньше правого. + + + Меньше чем — без учета регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые меньше правого операнда; в противном случае возвращает TRUE, если левый операнд меньше правого. + + + Меньше — регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые меньше правого операнда; в противном случае возвращает TRUE, если левый операнд меньше правого. + + + Меньше или равно - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые меньше или равны правому операнду; в противном случае возвращает TRUE, если левый операнд меньше или равен правому операнду. + + + Меньше или равно - регистр не учитывается. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые меньше или равны правому операнду; в противном случае возвращает TRUE, если левый операнд меньше или равен правому операнду. + + + Меньше или равно - регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые меньше или равны правому операнду; в противном случае возвращает TRUE, если левый операнд меньше или равен правому операнду. + + + Оператор сопоставления с использованием подстановочных символов — регистр нечувствителен. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, соответствующие правому операнду; в противном случае возвращает TRUE, если левый операнд соответствует правому операнду. + + + Оператор сопоставления с использованием подстановочных символов — регистр нечувствителен. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, соответствующие правому операнду; в противном случае возвращает TRUE, если левый операнд соответствует правому операнду. + + + Оператор сопоставления с подстановочными знаками — регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, соответствующие правому операнду; в противном случае возвращает TRUE, если левый операнд соответствует правому операнду. + + + Оператор сопоставления с использованием подстановочных символов — регистр нечувствителен. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые не соответствуют правому операнду; в противном случае возвращает TRUE, если левый операнд не соответствует правому операнду. + + + Оператор сопоставления с использованием подстановочных символов — регистр нечувствителен. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые не соответствуют правому операнду; в противном случае возвращает TRUE, если левый операнд не соответствует правому операнду. + + + Оператор сопоставления с подстановочными знаками — регистр имеет значение. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые не соответствуют правому операнду; в противном случае возвращает TRUE, если левый операнд не соответствует правому операнду. + + + Оператор сопоставления регулярных выражений — без учета регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, соответствующие правому операнду; в противном случае возвращает TRUE, если левый операнд соответствует правому операнду. + + + Оператор сопоставления регулярных выражений — без учета регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, соответствующие правому операнду; в противном случае возвращает TRUE, если левый операнд соответствует правому операнду. + + + Оператор сопоставления регулярных выражений — с учетом регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, соответствующие правому операнду; в противном случае возвращает TRUE, если левый операнд соответствует правому операнду. + + + Оператор сопоставления регулярных выражений — без учета регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые не соответствуют правому операнду; в противном случае возвращает TRUE, если левый операнд не соответствует правому операнду. + + + Оператор сопоставления регулярных выражений — без учета регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые не соответствуют правому операнду; в противном случае возвращает TRUE, если левый операнд не соответствует правому операнду. + + + Оператор сопоставления регулярных выражений — с учетом регистра. Если левый операнд представляет собой коллекцию, возвращает значения из коллекции, которые не соответствуют правому операнду; в противном случае возвращает TRUE, если левый операнд не соответствует правому операнду. + + + Замена оператора — регистр имеет значение. Изменяет левый операнд. Пример: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Замена оператора — регистр имеет значение. Изменяет левый операнд. Пример: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Замените оператор — регистр имеет значение. Изменяет левый операнд. Пример: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (правый операнд) точно совпадает хотя бы с одним из значений левого операнда. + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (правый операнд) точно совпадает хотя бы с одним из значений левого операнда. + + + Оператор изоляции — регистр имеет значение. Возвращает TRUE только в том случае, если тестовое значение (правый операнд) точно совпадает хотя бы с одним из значений левого операнда. + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (правый операнд) точно не совпадает ни с одним из значений левого операнда. + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (правый операнд) точно не совпадает ни с одним из значений левого операнда. + + + Оператор изоляции — регистр имеет значение. Возвращает TRUE, если тестовое значение (правый операнд) точно не совпадает ни с одним из значений левого операнда. + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (левый операнд) точно совпадает хотя бы с одним из значений правого операнда. + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (левый операнд) точно совпадает хотя бы с одним из значений правого операнда. + + + Оператор изоляции — регистр имеет значение. Возвращает TRUE, если тестовое значение (левый операнд) точно совпадает хотя бы с одним из значений правого операнда. + + + Оператор изоляции — регистр имеет значение. Возвращает TRUE, если тестовое значение (левый операнд) точно не совпадает ни с одним из значений в правом операнде. + + + Оператор изоляции — регистр нечувствителен. Возвращает TRUE, если тестовое значение (левый операнд) точно не совпадает ни с одним из значений в правом операнде. + + + Оператор изоляции — регистр имеет значение. Возвращает TRUE, если тестовое значение (левый операнд) точно не совпадает ни с одним из значений в правом операнде. + + + Разделение символов — без учета регистра. Разделить одну или несколько строк на подстроки. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Разделение символов — без учета регистра. Разделить одну или несколько строк на подстроки. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Разделение текста — с учетом регистра. Разделить одну или несколько строк на подстроки. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Возвращает TRUE, если левый операнд не является экземпляром указанного типа .NET Framework (правый операнд). + + + Возвращает TRUE, если левый операнд является экземпляром указанного типа .NET Framework (правый операнд). + + + Преобразует левый операнд в указанный тип .NET Framework (правый операнд). + + + Форматирует строки, используя метод format строковых объектов. + + + Логическое "И". Возвращает TRUE, если оба утверждения истинны. + + + Побитовое И + + + Логическое или. Истина, когда истинно хотя бы одно из утверждений или оба утверждения. + + + Побитовое ИЛИ (включительно) + + + Логическое исключающее ИЛИ. Возвращает TRUE, если одно из утверждений истинно, а другое ложно. + + + Побитовое ИЛИ (исключающее) + + + Join - объединить несколько строк в одну. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Битовый оператор сдвига влево. Вставляет ноль в крайний правый бит. + + + Битовый оператор сдвига вправо. Вставляет ноль в самый левый бит. Для знаковых значений знаковый бит сохраняется. + + + [строка] +Указывает название создаваемого свойства. + + + [строка] +Указывает название создаваемого свойства. + + + [scriptblock] +Блок скрипта, используемый для вычисления значения нового свойства. + + + [строка] +Определите, как значения отображаются в столбце. +Допустимые значения: 'left', 'center' или 'right'. + + + [строка] +Указывает строку формата, определяющую способ форматирования значения для вывода. + + + [int] +Указывает максимальную ширину столбца в таблице при отображении значения. +Значение должно быть больше 0. + + + [int] +Ключ глубины определяет глубину расширения для каждого свойства. + + + [bool] +Задает порядок сортировки для одного или нескольких свойств. + + + [bool] +Задает порядок сортировки для одного или нескольких свойств. + + + [String[]] +Указывает имена журналов, из которых нужно получить события. +Поддерживает подстановочные знаки. + + + [String[]] +Указывает поставщиков журналов событий, от которых следует получать события. +Поддерживает подстановочные знаки. + + + [String[]] +Указывает пути к файлам журналов, из которых нужно получать события. +Допустимые форматы файлов: .etl, .evt и .evtx + + + [Long[]] +Выбирает события с указанными ключевыми битовыми масками. +Ниже приведены стандартные ключевые слова: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Выбирает события с указанными идентификаторами. + + + [int[]] +Выбирает события с указанными уровнями логирования. +Допустимы следующие уровни логирования: +1: Критический +2: Ошибка +3: Предупреждение +4: Информационный +5: Многословный + + + [datetime] +Выбирает события, созданные после указанной даты и времени. + + + [datetime] +Выбирает события, созданные до указанной даты и времени. + + + [строка] +Выбирает события, сгенерированные указанным пользователем. +Это может быть либо строковое представление SID, либо домен и имя пользователя в формате DOMAIN\USERNAME или USERNAME@DOMAIN. + + + [string[]] +Выбирает события, имеющие любое из указанных значений в разделе EventData. + + + [hashtable] +Исключаются события, соответствующие значениям, указанным в хэш-таблице. + + + [строка] или [хеш-таблица] +Указывает массив модулей PowerShell, необходимых для выполнения скрипта. +Каждый элемент может быть либо строкой со значением имени модуля, либо хэш-таблицей со следующими ключами: +Название: Название модуля +GUID: GUID модуля +Один из следующих вариантов: +ModuleVersion: Указывает минимально допустимую версию модуля. +RequiredVersion: Указывает точную, необходимую версию модуля. +MaximumVersion: Указывает максимально допустимую версию модуля. + + + [строка] +Указывает версию PowerShell, необходимую для выполнения скрипта. +Допустимые значения: "Core" и "Desktop". + + + [switch] +Указывает, что PowerShell должен запускаться от имени администратора в Windows. +Это должен быть последний параметр в строке оператора #requires. + + + [версия] +Указывает минимальную версию PowerShell, необходимую для выполнения скрипта. + + + Указывает, что для запуска скрипта требуется PowerShell версии 7+. + + + Указывает, что для запуска скрипта требуется Windows PowerShell 5.1. + + + [строка] +Обязательно. Указывает имя модуля. + + + [строка] +Необязательно. Указывает GUID модуля. + + + [строка] +Указывает минимально допустимую версию модуля. + + + [строка] +Указывает точную, необходимую версию модуля. + + + [строка] +Указывает максимально допустимую версию модуля. + + + Краткое описание функции или скрипта. +Это ключевое слово можно использовать только один раз в каждой теме. + + + Подробное описание функции или скрипта. +Это ключевое слово можно использовать только один раз в каждой теме. + + + . PARAMETER <Parameter-Name> +Описание параметра. +Добавьте ключевое слово .PARAMETER для каждого параметра в синтаксисе функции или скрипта. + + + Пример команды, использующей функцию или скрипт, с возможностью добавления примера вывода и описания. +Повторите это ключевое слово для каждого примера. + + + Типы объектов .NET, которые можно передавать в функцию или скрипт через конвейер. +Вы также можете добавить описание входных объектов. + + + Тип объектов .NET, возвращаемых командлетом. +Вы также можете добавить описание возвращаемых объектов. + + + Дополнительная информация о функции или скрипте. + + + Название смежной темы. +Повторите ключевое слово .LINK для каждой связанной темы. +В ключевом содержимом .Link также может содержаться URI на онлайн-версию той же справочной темы. + + + Название технологии или функции, которую использует данная функция или скрипт, или с которой она связана. + + + Название роли пользователя для данной справочной темы. + + + Ключевые слова, описывающие предполагаемое использование функции. + + + .FORWARDHELPTARGETNAME <Command-Name> +Перенаправляет на справочную страницу по указанной команде. + + + .FORWARDHELPCATEGORY <Category> +Указывает категорию справки элемента в .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Указывает сессию, содержащую раздел справки. +Введите переменную, содержащую объект PSSession. + + + .EXTERNALHELP <XML Help File> +Ключевое слово .ExternalHelp обязательно, если функция или скрипт документированы в XML-файлах. + + + Указывает путь к загружаемой сборке .NET. + +с использованием сборки <.NET-assembly-path> + + + Указывает модуль PowerShell, из которого следует загружать классы. + +используя модуль <ModuleName or Path> + +с использованием модуля <ModuleSpecification hashtable> + + + Указывает пространство имен .NET для разрешения типов или псевдоним пространства имен. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Указывает псевдоним для типа .NET. + +using type <AliasName> = <.NET-type> + + + Обычная строка. + + + Строка, содержащая неразвернутые ссылки на переменные окружения, которые разворачиваются при получении значения. + + + Двоичные данные в любой форме. + + + 32-битное двоичное число. + + + Массив строк. + + + 64-битное двоичное число. + + + Неподдерживаемый тип данных реестра. + + + ',' - Запятая + + + ', ' - Запятая-Пробел + + + ';' - точка с запятой + + + '; ' - Точка с запятой - Пробел + + + {0} - Новая строка + + + '-' - Бросаться + + + ' ' - Пробел + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/TransactionStrings.ru.resx b/src/System.Management.Automation/resources/ru/TransactionStrings.ru.resx new file mode 100644 index 00000000000..69c37d77e18 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/TransactionStrings.ru.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Невозможно использовать транзакцию. Нет активных транзакций. + + + Невозможно зафиксировать транзакцию. Нет активных транзакций. + + + Невозможно выполнить откат транзакции, так как нет активной транзакции. + + + Невозможно откатить транзакцию. Транзакция уже зафиксирована. + + + Невозможно зафиксировать транзакцию. Транзакция уже зафиксирована. + + + Невозможно зафиксировать транзакцию. Выполнен откат транзакции, или время ожидания истекло. + + + Невозможно откатить транзакцию. Для транзакции уже был выполнен откат или время ожидания истекло. + + + Не удается задать активную транзакцию. Нет созданных транзакций. + + + Не удается задать активную транзакцию. Для активной транзакции был выполнен откат или время ожидания истекло. + + + Для данного командлета необходима действующая транзакция. Для текущей транзакции уже выполнен откат или ее зафиксировано. + + + Для этого командлета требуется транзакция. Выполните команду еще раз с параметром -UseTransaction. + + + Невозможно использовать транзакцию. Нет запущенных транзакций. + + + Невозможно использовать транзакцию. Транзакция зафиксирована. + + + Невозможно использовать транзакцию. Выполнен откат транзакции, или время ожидания истекло. + + + Невозможно использовать транзакцию. Время ожидания транзакции истекло. + + + Базовая транзакция не задана. + + + Базовая транзакция неактивна. + + + Базовую транзакцию нельзя задать после создания других транзакций. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/TypesXmlStrings.ru.resx b/src/System.Management.Automation/resources/ru/TypesXmlStrings.ru.resx new file mode 100644 index 00000000000..7321b365cab --- /dev/null +++ b/src/System.Management.Automation/resources/ru/TypesXmlStrings.ru.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : ошибка: {3} + + + {0}, {1}({2}) : ошибка в типе "{3}": {4} + + + Узел "{0}" должен встречаться только один раз в "{1}". Родительский узел "{1}" будет пропущен. + + + Узел {0} не разрешен. Разрешены следующие узлы: {1}. + + + Узел "{0}" не должен содержать внутренний текст. + + + Узел "{0}" должен содержать внутренний текст. + + + Узел "{0}" не найден. Это должно произойти только один раз в разделе "{1}". Родительский узел "{1}" будет пропущен. + + + Узел "Type" должен иметь "Members", "TypeConverters" или "TypeAdapters". + + + Не удается создать экземпляр конвертера типов для типа из-за {0} исключения: {1}. + + + PowerShell не удается создать экземпляр адаптер типа {0} для этого типа из-за следующего исключения: {1}. + + + Тип адаптера "{0}" не является допустимым. + + + Объект TypeConverter был проигнорирован, поскольку он уже присутствует. + + + Объект TypeAdapter был проигнорирован, поскольку он уже присутствует. + + + Типом "{0}" должен быть TypeConverter или PSTypeConverter. + + + Тип "{0}" должен быть PSPropertyAdapter. + + + Участник {0} уже присутствует. + + + Следующее имя участника зарезервировано: {0} + + + Исключение: {0} + + + ScriptProperty должен иметь метод получения или метод задания. + + + У свойства CodeProperty должен быть метод получения или метод задания. + + + {0}, {1} : {2} + + + Вместо {0} значение должно быть ИСТИНА или ЛОЖЬ. + + + Узел "{0}" не должен иметь атрибут "{1}". + + + {0}, {1}: файл не найден. + + + {0}, {1}: файл пропущен, так как он уже загружен {2}. + + + Не удалось найти раздел реестра: {0}{1}. Используется {2} для загрузки конфигурационных файлов. + + + Не удается найти путь {0}, указанный в ключе реестра: {1}{2}. Используется {3} для загрузки конфигурационных файлов. + + + {0}, {1}: файл пропущен, так как у него нет расширения ps1xml. + + + {0}, {1}: файл пропущен из-за следующего исключения проверки: {2}. + + + Элемент "{0}" должен быть заметкой. + + + Не удается преобразовать "{0}" в "{1}". + + + Не используйте здесь элемент "{0}". + + + У элемента "{0}" должен быть тип "{1}". + + + "{0}" должно присутствовать, если "{1}" — "{2}", а "{3}" — "{4}". + + + Предыдущая ошибка привела к игнорированию всех настроек сериализации. + + + "{0}" не является стандартным элементом и будет проигнорирован. + + + Путь {0} не является полным. Укажите путь к файлу полного типа. + + + Обновить таблицу типов невозможно, поскольку она могла быть создана вне пространства выполнения. + + + При загрузке TypeTable произошли ошибки. Подробные сообщения об ошибках можно найти в свойстве Errors. + + + Ошибка в TypeData "{0}": {1} + + + "{0}" должно иметь значение для своего свойства "{1}". + + + "{0}" не должен содержать нулевую или пустую строку в свойстве "{1}". + + + Не удалось найти тип "{0}". Значение имени типа должно быть полным именем типа. Проверьте имя типа и запустите команду еще раз. + + + TypeData должен содержать "Members", "TypeConverters", "TypeAdapters" или "StandardMembers". + + + В таблицу общего типа нельзя добавить более одной записи. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/VerbDescriptionStrings.ru.resx b/src/System.Management.Automation/resources/ru/VerbDescriptionStrings.ru.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/ru/VerbDescriptionStrings.ru.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/ru/WildcardPatternStrings.ru.resx b/src/System.Management.Automation/resources/ru/WildcardPatternStrings.ru.resx new file mode 100644 index 00000000000..408ddb8ba3e --- /dev/null +++ b/src/System.Management.Automation/resources/ru/WildcardPatternStrings.ru.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 + + + Указанный шаблон подстановочных знаков недопустим: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/Authenticode.tr.resx b/src/System.Management.Automation/resources/tr/Authenticode.tr.resx new file mode 100644 index 00000000000..d07f5963fb6 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/Authenticode.tr.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 + + + Bu yazılımı şimdi çalıştırmamayı seçtiğiniz için dosya {0} yüklenemiyor. + + + Bu yayımcının yazılımını hiçbir zaman çalıştırmamayı seçtiğiniz için dosya {0} yüklenemiyor. + + + Dosya {0}, {1} tarafından yayımlanmış. Bu yayımcıya sisteminizde açıkça güvenilmiyor. Betik sistemde çalıştırılmayacak. Daha fazla bilgi için "get-help about_signing" komutunu çalıştırın. + + + Bu sistemde betiklerin çalıştırılması devre dışı bırakıldığından dosya {0} yüklenemiyor. Daha fazla bilgi için https://go.microsoft.com/fwlink/?LinkID=135170 adresindeki about_Execution_Policies sayfasına bakın. + + + Dosya {0} yüklenemiyor. {1}. + + + İşlemi, Grup İlkesi kullanılarak oluşturulanlar gibi yazılım kısıtlama ilkeleri tarafından engellendiğinden dosya {0} yüklenemiyor. + + + İçeriği okunamadığından dosya {0} yüklenemiyor. + + + Kod imzalanamıyor. Belirtilen sertifika kod imzalama için uygun değil. + + + Kod imzalanamıyor. Zaman damgası sunucusu URL'si tam olarak belirtilmeli ve http://<server url> veya https://<server url> biçiminde olmalıdır. + + + Kod imzalanamıyor. Karma algoritması desteklenmiyor. + + + Bu güvenilmeyen yayımcının yazılımını çalıştırmak istiyor musunuz? + + + Dosya {0}, {1} tarafından yayımlanmış ve sisteminizde dosyaya güvenilmiyor. Yalnızca güvenilir yayımcıların betiklerini çalıştırın. + + + Yazılım {0} bilinmeyen bir yayımcı tarafından yayımlanmış. Bu yazılımı çalıştırmamanız önerilir. + + + Güvenlik uyarısı + + + Yalnızca güvendiğiniz betikleri çalıştırın. İnternet'ten gelen betikler kullanışlı olabildiği gibi bilgisayarınıza zarar da verebilir. Bu betiğe güveniyorsanız betiğin bu uyarı iletisi olmadan çalışmasına izin vermek için Unblock-File cmdlet'ini kullanın. {0} betiğini çalıştırmak istiyor musunuz? + + + Hiçb&ir zaman çalıştırma + + + Bu yayımcının betiğini şimdi çalıştırma ve gelecekte bu betiği çalıştırmam için bana sorma. Gelecekte bu betiği çalıştırma girişimleri sessizce başarısız olur. + + + Ç&alıştırma + + + Bu yayımcının betiğini şimdi çalıştırma ve gelecekte bu betiği çalıştırmam için bana sormaya devam et. + + + &Bir kez çalıştır + + + Bu yayımcının betiğini şimdi çalıştır ve gelecekte bu betiği çalıştırmam için bana sormaya devam et. + + + &Her zaman çalıştır + + + Bu yayımcının betiğini şimdi çalıştır ve gelecekte bu betiği çalıştırmam için bana sorma. + + + &Askıya Al + + + Geçerli işlem hattını duraklatın ve komut istemine dönün. İşiniz bittiğinde işlemi sürdürmek için exit yazın. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/AuthorizationManagerBase.tr.resx b/src/System.Management.Automation/resources/tr/AuthorizationManagerBase.tr.resx new file mode 100644 index 00000000000..f721f05b082 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/AuthorizationManagerBase.tr.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 + + + AuthorizationManager kontrolü başarısız oldu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/AutomationExceptions.tr.resx b/src/System.Management.Automation/resources/tr/AutomationExceptions.tr.resx new file mode 100644 index 00000000000..18d6f475628 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/AutomationExceptions.tr.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 argument because the value of argument "{0}" is not valid. Change the value of the "{0}" argument and run the operation again. + + + Cannot process argument because the value of parameter "{0}" is not valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). Change the value of the "{0}" parameter and run the operation again. + + + Cannot process argument because the value of argument "{0}" is null. Change the value of argument "{0}" to a non-null value. + + + Cannot process argument because the value of argument "{0}" is out of range. Change argument "{0}" to a value that is within range. + + + Cannot perform operation because operation "{0}" is not valid. Remove operation "{0}", or investigate why it is not valid. + + + Cannot perform operation because operation "{0}" is not implemented. + + + Cannot perform operation because operation "{0}" is not supported. + + + Cannot perform operation because object "{0}" has already been disposed. + + + The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause. + + + The script block cannot be converted because it contains more than one clause. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + An empty script block cannot be converted. Verify that the script block contains exactly one pipeline or command. + + + Only a script block that contains exactly one pipeline or command can be converted. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + A script block that contains a top-level trap statement cannot be converted. + + + Cannot generate a PowerShell object for a ScriptBlock dereferencing variables undeclared in the param(...) block. Name of undeclared variable: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating non-constant expressions. Non-constant expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions. Dynamic expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock that tries to pass other script blocks inside argument values. + + + Cannot generate a PowerShell object for a ScriptBlock which invokes pipelines, commands or functions to evaluate arguments of the main pipeline. + + + Cannot generate a PowerShell object for a ScriptBlock that uses dot sourcing. + + + Cannot generate a PowerShell object for a ScriptBlock that invokes other script blocks. + + + The script block cannot be converted to a PowerShell object because it contains forbidden redirection operators. + + + Cannot generate a PowerShell object for a ScriptBlock that does not have an associated operation context. + + + The command was stopped by the user. + + + Object "{0}" is the wrong type to return from the dynamicparam block. The dynamicparam block must return either $null, or an object with type [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + The script block cannot be converted to an open generic type. Define an appropriate closed generic type, and then retry. + + + Cannot generate a PowerShell object for a ScriptBlock that starts a pipeline with an expression. + + + The value of the using variable '$using:{0}' cannot be retrieved because it has not been set in the local session. + + + Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CatalogStrings.tr.resx b/src/System.Management.Automation/resources/tr/CatalogStrings.tr.resx new file mode 100644 index 00000000000..906382d3471 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CatalogStrings.tr.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Katalog tanım dosyası oluşturulamıyor. + + + "{0}" dosyası kataloğa ekleniyor. Katalogdaki dosyanın göreli yolu: "{1}". + + + Katalogdaki {0} dosyası için doğrulama atlanıyor. + + + Katalogda karması {1} olan {0} dosyası bulundu. + + + Katalog yollarında aynı {0} göreli yoluna sahip birden fazla dosya var. + + + Diskte karması {1} olan {0} dosyası bulundu. + + + Yoldaki {0} dosyası için doğrulama atlanıyor. + + + Belirtilen karma algoritması için katalog yöneticisi {0} bağlamına yönelik tanıtıcı alınamıyor. + + + {0} dosyası için karma oluşturulamıyor. + + + {0} katalog dosyası açılamıyor. + + + Katalog sürümü geçerli değil. Yalnızca katalog sürüm {0} ve sürüm {1} desteklenir. + + + Katalog tanım dosyası açılamıyor. + + + Katalogda, {0} dosya üyesinin birden çok girdisi bulundu. + + + {0} katalog üyesi için dosya adı veya yol bulunamıyor. + + + Karma için {0} dosyası bulunamıyor. + + + Karma hesaplamak için {0} dosyası okunamıyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CimInstanceTypeAdapterResources.tr.resx b/src/System.Management.Automation/resources/tr/CimInstanceTypeAdapterResources.tr.resx new file mode 100644 index 00000000000..7206ed40ed5 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CimInstanceTypeAdapterResources.tr.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + “{0}" türündeki bir nesneye "{1}" dönüştürülemez. + + + “{0}" salt okunur bir özelliktir. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CmdletizationCoreResources.tr.resx b/src/System.Management.Automation/resources/tr/CmdletizationCoreResources.tr.resx new file mode 100644 index 00000000000..a33fc85e3a2 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CmdletizationCoreResources.tr.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{0}' sınıfındaki cmdlet'ler + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + Cmdlet Definition XML işlenemiyor: {0}. {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + ObjectModelWrapper öznitelik işlenemiyor. {0} türü birden çok parametre kümesi tanımlar. Cmdlet Definition XML'sinin ObjectModelWrapper özniteliğinde geçerli bir tür belirttiğini doğrulayın ve yeniden deneyin. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + ObjectModelWrapper öznitelik işlenemiyor. {0} türü açık bir genel türdür. Cmdlet Definition XML'sinin ObjectModelWrapper özniteliğinde geçerli bir tür belirttiğini doğrulayın ve yeniden deneyin. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + ObjectModelWrapper özniteliği işlenemiyor. {0} türü aşağıdaki sınıftan türetilmemiş: {1}. Cmdlet Definition XML’nin ObjectModelWrapper özniteliğinde geçerli bir tür belirttiğini doğrulayın ve yeniden deneyin. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + ObjectModelWrapper öznitelik işlenemiyor. {0} türü, yok sayılan bir {1} özniteliği parametresiyle {2} cmdlet parametresini tanımlıyor. Cmdlet Definition XML'sinin ObjectModelWrapper özniteliğinde geçerli bir tür belirttiğini doğrulayın ve yeniden deneyin. + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + {0} parametresi {1} cmdlet’i için tanımlanamaz. Parametre adı zaten {2} sınıfı tarafından tanımlanmış. Cmdlet Definition XML’de parametrenin adını değiştirin ve yeniden deneyin. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + {0} parametresi {1} cmdlet’i için tanımlanamaz. Parametre adı zaten {2} XML öğesi içinde tanımlanmış. Cmdlet Definition XML’de parametrenin adını değiştirin ve ardından yeniden deneyin. + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + EnumName özniteliğinin değeri geçerli bir C# tanımlayıCısına çevrilmiyor: {0}. Cmdlet Definition XML’deki EnumName özniteliğini doğrulayın ve ardından yeniden deneyin. + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + <Enum EnumName="{0}" ...> öğesi işlenemiyor. {1} + {StrContains="Enum"} {StrContains="EnumName"} + + + Uzak bilgisayar geçersiz bir CDXML dosyası döndürdü. Aşağıdaki cmdlet bağdaştırıcısı, uzak bilgisayardan bir CDXML modülü içe aktarmak için desteklenmiyor: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CommandBaseStrings.tr.resx b/src/System.Management.Automation/resources/tr/CommandBaseStrings.tr.resx new file mode 100644 index 00000000000..4e1b9966f8a --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CommandBaseStrings.tr.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Bu işleme devam edilsin mi? + + + &Evet + + + İşlemin yalnızca bir sonraki adımıyla devam edin. + + + &Tümüne Evet + + + İşlemin tüm adımlarıyla devam edin. + + + &Hayır + + + Bu işlemi atlayın ve sonraki işleme devam edin. + + + Tümüne &Hayır + + + Bu işlemi ve sonraki tüm işlemleri atlayın. + + + Bu komutu çalıştırın. + + + &Durdurma Komutu + + + &Askıya Al + + + Geçerli işlem hattını duraklatın ve komut istemine dönün. İşlem hattını sürdürmek için "{0}" yazın. + + + + Program "{0}", sıfır olmayan çıkış koduyla sona erdi: {1} ({2}). + + + "{1}" hedefi üzerinde "{0}" işlemi gerçekleştiriliyor. + + + What if: {0} + + + Bu işlemi gerçekleştirmek istediğinizden emin misiniz? +{0} + + + Onayla + + + Çalışan komut, tercih değişkeni "{0}" veya ortak parametre Durdur: {1} olarak ayarlandığı için durduruldu. + + + Çalışan komut, tercih değişkeni "{0}" veya ortak parametre Durdur olarak ayarlandığı için durduruldu. + + + Çalışan komut, tercih değişkeni "{0}" veya ortak parametre geçerli olmayan şu değere ayarlandığı için durduruldu: "{1}". + + + Çalışan komut, kullanıcı Durdur seçeneğini belirlediği için durduruldu. + + + Çalışan komut, kullanıcı komutu kestiği için durduruldu. + + + PSCmdlet'ten türetilen cmdlet'ler doğrudan çağrılamaz. + + + Cmdlet '{0}', uzak oturumda '{1}' parametresini desteklemiyor. + + + Toplam sayı: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + Tahmini toplam sayı: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + Toplam sayı bilinmiyor + Reviewed by TArcher on 2010-07-20 + + + komut '{0}' + + + {0} eski. {1} + + + Exec çağrısı, şu komut satırı için {0} hata numarasıyla başarısız oldu: {1} + + + '{0}' komutu bulunamadı. Belirtilen komut yürütülebilir bir dosya olmalıdır. + + + Betik Bloğu İşleme Dot-Source Denetimi + + + Betik bloğu '{0}' için Dot-Source işleme, dil modu '{1}' geçerli dil modu '{2}' ile eşleşmediği için Kısıtlı Dil modunda başarısız olur. + + + Komut Arayıcı + + + '{1}' modülündeki '{0}' komutuna güvenilmiyor ve Kısıtlı Dil modunda erişilebilir olmayacak. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ConsoleInfoErrorStrings.tr.resx b/src/System.Management.Automation/resources/tr/ConsoleInfoErrorStrings.tr.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ConsoleInfoErrorStrings.tr.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CoreClrStubResources.tr.resx b/src/System.Management.Automation/resources/tr/CoreClrStubResources.tr.resx new file mode 100644 index 00000000000..dddf2691373 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CoreClrStubResources.tr.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Ortam değişkeni adı eşittir karakteri içeremez. + + + Ortam değişkeni adı veya değeri fazla uzun. + + + Dizedeki ilk karakter null karakterdir. + + + Dize uzunluğu sıfır olamaz. + + + Bilgisayar adı alınamadı. + + + Geçerli kullanıcının etki alanı adı alınamadı. + + + Bilinmeyen hata: "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CredUI.tr.resx b/src/System.Management.Automation/resources/tr/CredUI.tr.resx new file mode 100644 index 00000000000..a2e1da22b54 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CredUI.tr.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell kimlik bilgisi isteği + + + Kimlik bilgilerinizi girin. + + + Kimlik bilgilerinizi girin. + + + Başlığın maksimum uzunluğu {0} karakterdir. + + + İletinin maksimum uzunluğu {0} karakterdir. + + + UserName değerinin maksimum uzunluğu {0} karakterdir. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/Credential.tr.resx b/src/System.Management.Automation/resources/tr/Credential.tr.resx new file mode 100644 index 00000000000..f30b28ff4b5 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/Credential.tr.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 + + + Kimlik bilgisi seri hale getirilemiyor. Bu komut bir iş akışı başlatıyorsa, iş akışının başlatıldığı işlemin kimlik bilgilerini seri hale getirme izni olmadığından kimlik bilgileri kalıcı hale getirilemez. + +-- İş akışı yerel bilgisayara bir PSSession içinde başlatıldıysa EnableNetworkAccess parametresini oturumu oluşturan komuta ekleyin. +-- İş akışı uzak bir bilgisayara bir PSSession içinde başlatıldıysa oturumu oluşturan komuta Authentication parametresini CredSSP değeriyle ekleyin. Alternatif olarak RunAsUser özellik değerine sahip bir oturum yapılandırmasına bağlanın. + + + UserName değeri doğru biçimde değil. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/CredentialAttributeStrings.tr.resx b/src/System.Management.Automation/resources/tr/CredentialAttributeStrings.tr.resx new file mode 100644 index 00000000000..c6ba6291d3b --- /dev/null +++ b/src/System.Management.Automation/resources/tr/CredentialAttributeStrings.tr.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 + + + PowerShell kimlik bilgisi isteği + + + Kimlik bilgilerinizi girin. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/DebuggerStrings.tr.resx b/src/System.Management.Automation/resources/tr/DebuggerStrings.tr.resx new file mode 100644 index 00000000000..0faff0cf5c4 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/DebuggerStrings.tr.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '${0}' üzerinde değişken kesme noktası ({1} erişimi) + + + '{0}:${1}' üzerinde değişken kesme noktası ({2} erişimi) + + + '{0}:{1}' üzerinde satır kesme noktası + + + '{0}:{1}, {2}' üzerinde satır kesme noktası + + + '{0}' üzerinde komut kesme noktası + + + '{0}:{1}' üzerinde komut kesme noktası + + + {0} kesme noktasına isabet edilmeyecek + + + {0}, {1,-16} Tek adım (işlevlere, betiklere vb. gir) + + + {0}, {1,-16} Sonraki deyime geç (işlevlerin, betiklerin vb. üzerinden adımla) + + + {0}, {1,-16} Geçerli işlevin, betiğin vb. dışına çık. + + + {0}, {1,-16} İşlemi sürdür + + + {0}, {1,-16} İşlemi durdur ve hata ayıklayıcıdan çık + + + {0}, Get-PSCallStack Çağrı yığınını görüntüle + + + {0}, {1,-16} Geçerli betik için kaynak kodu listele. + + + Geçerli satırdan başlamak için "list" kullanın, "list <m>" + + + <m> satırından başlamak için ve <n> öğesini listelemek için "list <m> <n>" + + + <m> satırından başlayarak + + + <enter> Son komut {0}, {1} veya {2} ise tekrarla + + + {0}, {1,-16} bu yardım iletisini görüntüler. + + + Hata ayıklayıcı isteminizi özelleştirmeyle ilgili yönergeler için "help about_prompt" yazın. + + + +Geçerli oturum hata ayıklamayı desteklemiyor; işlem devam edecek. + + + + + {0}: satır {1} + + + Kullanılabilir kaynak kodu yok. + + + Başlangıç satırı, {0} değerinden büyük olmayan pozitif bir tam sayı olmalıdır + + + Satır sayısı pozitif bir tamsayı olmalıdır. + + + <Dosya yok> + + + {0} konumunda, {1}: satır {2} + + + Hata ayıklayıcı, Durduruldu durumunda olmadığı sürece komutları işleyemez. + + + SetDebugAction yerel betik hata ayıklayıcısı için uygulanmadı. + + + Uzak oturumdaki hata ayıklayıcı Durduruldu durumunda olmadığından, hata ayıklayıcısı bir sürdürme eylemi ayarlayamıyor. + + + Hata ayıklayıcısı şu anda meşgul olduğundan işte hata ayıklanamıyor. + + + Sağlanan iş ve tüm alt işler incelendi ancak hata ayıklanabilecek iş bulunamadı. Bir iş veya alt işte hata ayıklamak için işin hata ayıklamayı desteklemesi ve çalışır durumda olması gerekir. + + + Hata ayıklayıcı, hata ayıklama modu None olarak ayarlandığında kapalı olduğu için adım modu için etkinleştirilemiyor. + + + Konak hata ayıklayıcısı şu anda meşgul olduğundan Çalışma alanında hata ayıklanamıyor. + + + Çalışma alanında hata ayıklanamıyor. Çalışma alanı hata ayıklayıcısı şu anda kapalı (DebugMode değeri 'None'). + + + Açık durumda olmayan bir Çalışma alanında hata ayıklanamıyor. Bu Çalışma alanının durumu {0}. + + + Çalışma alanında hata ayıklanamıyor. Çalışma alanı {0} ile ilişkili bir hata ayıklayıcı yok. + + + Hata ayıklayıcı zaten geçersiz kılınmış. + + + Hata ayıklayıcı nesnesi kendisi üzerine gönderilemez. + + + {0} komutu, uzak çalışma alanında çalışan PowerShell sürümünde uzak kullanım için desteklenmiyor. + + + İşlem + + + {0}, {1,-16} İşleme devam et ve hata ayıklayıcıyı ayır. + + + Hata ayıklayıcı ayırma komutu uygulanamaz. Ayırma komutu yalnızca Debug-Job veya Debug-Runspace cmdlet'leriyle işlerde ve çalışma alanlarında hata ayıklanırken geçerlidir. + + + Geçersiz çalışma alanı kimliği: {0} + + + Çalışma alanı alınamıyor. + + + Breakpoint veya BreakpointList belirtilmelidir. + + + BreakpointList, kesme noktası olmayan bir öğe içeriyordu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/DescriptionsStrings.tr.resx b/src/System.Management.Automation/resources/tr/DescriptionsStrings.tr.resx new file mode 100644 index 00000000000..3de18d3c34d --- /dev/null +++ b/src/System.Management.Automation/resources/tr/DescriptionsStrings.tr.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 + + + {0} null veya boş olamaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/DiscoveryExceptions.tr.resx b/src/System.Management.Automation/resources/tr/DiscoveryExceptions.tr.resx new file mode 100644 index 00000000000..86c5efb23b2 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/DiscoveryExceptions.tr.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 + + + "{0}" cmdlet adı doğru biçimde olmadığından doğrulanamıyor. Cmdlet adları, "Get-Process" gibi "-" ile ayrılmış bir fiil ve ad içermelidir. + + + "{0}" parametresi, "{1}" parametre kümesinde birden çok kez bildirildi. + + + "{0}" diğer adı birden çok kez bildirildi. + + + Parametre bildirilemedi. Parametreler yalnızca alanlarda ve özelliklerde bildirilebilir. + + + Cmdlet işlenemiyor. Cmdlet adı '-' ile ayrılmış bir fiil ve ad çiftinden oluşmalıdır. + + + '{0}' terimi bir cmdlet, işlev, betik dosyası veya yürütülebilir program adı olarak tanınmıyor. +Adın yazımını denetleyin veya yol eklenmişse yolun doğru olduğundan emin olun ve yeniden deneyin. + + + '{0}' bağımsız değişkeni bir cmdlet olarak tanınmıyor: {1} + + + '{0}' bağımsız değişkeni cmdlet olarak tanınmıyor. Bunun nedeni büyük olasılıkla Cmdlet veya PSCmdlet sınıflarından türetilmemiş olmasıdır: {1} + + + '{0}' diğer adı, bir cmdlet, işlev, yürütülebilir program veya betik dosyası olarak tanınmayan '{1}' terimine başvurduğu için çözümlenemiyor. Terimi doğrulayın ve yeniden deneyin. + + + Değeri '{1}' olan '{0}' parametresi işlenemiyor çünkü bir cmdlet değil ve CommandProcessor tarafından işlenemez. + + + "{0}" adlı bir cmdlet zaten var. Cmdlet'lerin adları benzersiz olmalıdır. + + + '{0}' adlı bir cmdlet sağlayıcısı zaten var. Cmdlet sağlayıcılarının adları benzersiz olmalıdır. + + + '{0}' adlı bir derleme zaten var. Derlemelerin adları benzersiz olmalıdır. + + + "{0}" adlı bir betik zaten var. Betiklerin adları benzersiz olmalıdır. + + + #requires deyimi doğru biçimde olmadığı için işlenemiyor. +#requires deyimi şu biçimlerden birinde olmalıdır: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + '{0}' betiği, geçerli kabukla uyumlu olmayan {1} kabuk kimliğine sahip bir "#requires" deyimi içerdiğinden çalıştırılamıyor. Bu betiği çalıştırmak için '{2}' konumundaki kabuğu kullanmanız gerekir. + + + '{0}' betiği, geçerli kabukla uyumlu olmayan {1} kabuk kimliğine sahip bir "#requires" deyimi içerdiğinden çalıştırılamıyor. + + + '{0}' betiği, PowerShell {1} için bir "#requires" deyimi içerdiğinden çalıştırılamıyor. Betik için gereken PowerShell sürümü, şu anda çalışan PowerShell {2} sürümüyle eşleşmiyor. + + + '{0}' betiği, PowerShell '{1}' sürümleri için bir "#requires" deyimi içerdiğinden çalıştırılamıyor. Betik için gereken PowerShell sürümü, şu anda çalışan PowerShell {2} sürümüyle eşleşmiyor. + + + '{0}' betiğinin "#requires" deyimleri tarafından belirtilen şu ek bileşenler eksik olduğundan betik çalıştırılamıyor: {1}. + + + Bir #Requires deyimi yalnızca shellID belirtti. PowerShell'de çalıştırılırken, #requires deyimleri gerekli PowerShell ek bileşenini belirtmelidir. + + + '{0}' betiği, Yönetici olarak çalıştırmak için bir "#requires" deyimi içerdiğinden çalıştırılamıyor. Geçerli PowerShell oturumu Yönetici olarak çalıştırılmıyor. PowerShell'i Yönetici olarak çalıştır seçeneğini kullanarak başlatın ve ardından betiği çalıştırmayı yeniden deneyin. + + + {0} (Sürüm {1}) + + + ArgumentList parametresi yalnızca tek bir cmdlet veya betik alınırken belirtilebildiği için komut alınamadı. + + + "{0}" parametre adı ileride kullanılmak üzere ayrılmıştır. + + + '{0}' betiğinin "#requires" deyimleri tarafından belirtilen şu modüller eksik olduğundan betik çalıştırılamıyor: {1}. + + + '{0}' komutu '{1}' modülünde bulundu ancak modül yüklenemedi. Daha fazla bilgi için 'Import-Module {1}' komutunu çalıştırın. + + + '{0}' komutu '{1}' modülünde bulundu ancak şu hata nedeniyle modül yüklenemedi: [{2}] +Daha fazla bilgi için 'Import-Module {1}' komutunu çalıştırın. + + + '{0}' modülü yüklenemedi. Daha fazla bilgi için 'Import-Module {0}' komutunu çalıştırın. + + + Eşleşen komutlardan hiçbirinde '{0}' adlı parametre yok. Parametre adının yazımını denetleyip yeniden deneyin. + + + Bu komut farklı bir dil modunda tanımlandığından, komutta Dot-Source kullanılamıyor. Bu komutun içeriğini içeri aktarmadan komutu çağırmak için '.' işlecini atlayın. + + + ShowCommandInfo ve Syntax parametreleri birlikte belirtilemez. + + + '{0}' deneysel özelliği açıldığında bu betik komutu devre dışı bırakılır. + + + '{0}' deneysel özelliği kapatıldığında bu betik komutu devre dışı bırakılır. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/EnumExpressionEvaluatorStrings.tr.resx b/src/System.Management.Automation/resources/tr/EnumExpressionEvaluatorStrings.tr.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/tr/EnumExpressionEvaluatorStrings.tr.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ErrorCategoryStrings.tr.resx b/src/System.Management.Automation/resources/tr/ErrorCategoryStrings.tr.resx new file mode 100644 index 00000000000..70c6622f8e5 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ErrorCategoryStrings.tr.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 + + + Kapatma hatası: ({1}:{2}) [{0}], {3} + + + Kilitlenme algılandı: ({1}:{2}) [{0}], {3} + + + Aygıt hatası: ({1}:{2}) [{0}], {3} + + + GeçersizBağımsızDeğişken: ({1}:{2}) [{0}], {3} + + + Geçersiz veri: ({1}:{2}) [{0}], {3} + + + Geçersiz işlem: ({1}:{2}) [{0}], {3} + + + GeçersizSonuç: ({1}:{2}) [{0}], {3} + + + GeçersizTür: ({1}:{2}) [{0}], {3} + + + Meta veri hatası: ({1}:{2}) [{0}], {3} + + + Uygulanmadı: ({1}:{2}) [{0}], {3} + + + Yüklü değil: ({1}:{2}) [{0}], {3} + + + Nesne bulunamadı: ({1}:{2}) [{0}], {3} + + + Açma hatası: ({1}:{2}) [{0}], {3} + + + İşlem durduruldu: ({1}:{2}) [{0}], {3} + + + İşlem zaman aşımına uğradı: ({1}:{2}) [{0}], {3} + + + AyrıştırıcıHatası: ({1}:{2}) [{0}], {3} + + + İzin reddedildi: ({1}:{2}) [{0}], {3} + + + Okuma hatası: ({1}:{2}) [{0}], {3} + + + Kaynak kullanılamıyor: ({1}:{2}) [{0}], {3} + + + Kaynak mevcut: ({1}:{2}) [{0}], {3} + + + Kaynak kullanılamıyor: ({1}:{2}) [{0}], {3} + + + Sözdizimi hatası: ({1}:{2}) [{0}], {3} + + + Yazma hatası: ({1}:{2}) [{0}], {3} + + + Standart hatadan: ({1}:{2}) [{0}], {3} + + + Güvenlik hatası: ({1}:{2}) [{0}], {3} + + + Protokol hatası: ({1}:{2}) [{0}], {3} + + + Bağlantı hatası: ({1}:{2}) [{0}], {3} + + + Kimlik doğrulama hatası: ({1}:{2}) [{0}], {3} + + + Sınırlar aşıldı: ({1}:{2}) [{0}], {3} + + + Kota aşıldı: ({1}:{2}) [{0}], {3} + + + Etkin değil: ({1}:{2}) [{0}], {3} + + + Belirtilmedi: ({1}:{2}) [{0}], {3} + + + Tanınmayan hata kategorisi {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ErrorPackage.tr.resx b/src/System.Management.Automation/resources/tr/ErrorPackage.tr.resx new file mode 100644 index 00000000000..10ba5f1fe77 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ErrorPackage.tr.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 + + + {0}…{1} + + + “{0}” hatası için hata metni boş: “{1}” + + + Nesne "{0}" hata olarak bildirildi. + + + {0} değeri, bir ActionPreference değişkeni için desteklenmiyor. Sağlanan değer yalnızca bir tercih parametresi için değer olarak kullanılmalıdır ve varsayılan değerle değiştirilmiştir. Daha fazla bilgi için, "about_Preference_Variables" Yardım konusuna bakın. + + + {0} ActionPreference değeri gelecekte kullanılmak üzere ayrılmıştır ve şu anda desteklenmemektedir. Tercih değişkenleri hakkında daha fazla bilgi için Yardım konusundaki "about_Preference_Variables." bölümüne bakın. + + + {0} ActionPreference değeri gelecekte kullanılmak üzere ayrılmıştır ve şu anda desteklenmemektedir. Bu, {1} değişkeninizde {2} varsayılan değeriyle değiştirilmiştir. Tercih değişkenleri hakkında daha fazla bilgi için Yardım konusundaki "about_Preference_Variables." bölümüne bakın. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/EtwLoggingStrings.tr.resx b/src/System.Management.Automation/resources/tr/EtwLoggingStrings.tr.resx new file mode 100644 index 00000000000..e3d3bcf4cad --- /dev/null +++ b/src/System.Management.Automation/resources/tr/EtwLoggingStrings.tr.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} komutu: {1}. + + + {0} altyapı durumu {1} olarak değiştirildi. + + + Tam Hata Kimliği = {0} + + + Hata İletisi = {0} + + + Önerilen Eylem = {0} + + + Yürütme İlkesi + + + İş Komutu = {0} + + + İş Kimliği = {0} + + + İş Örneği Kimliği = {0} + + + İş Yeri = {0} + + + İş Adı = {0} + + + İş Durumu = {0} + + + Komut Adı = + + + Komut Yolu = + + + Komut Türü = + + + Altyapı Sürümü = + + + Konak Kimliği = + + + Ana Bilgisayar Adı = + + + Konak Uygulama = + + + Konak Sürümü = + + + İşlem Hattı Kimliği = + + + Çalışma Alanı Kimliği = + + + Betik Adı = + + + Sıra Numarası = + + + Önem derecesi = + + + Kabuk Kimliği = + + + Saat = + + + Kullanıcı = + + + Bağlı Kullanıcı = + + + NULL İş + + + Sağlayıcı adı + + + {0} sağlayıcısı durumu {1} olarak değiştirdi. + + + Betik yürütme: {0}. + + + {1} olan {0} değişkeni {2} olarak değiştirildi. + + + {0} değişkeni {1} olarak değiştirildi. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/EventResource.tr.resx b/src/System.Management.Automation/resources/tr/EventResource.tr.resx new file mode 100644 index 00000000000..28c0cdda26f --- /dev/null +++ b/src/System.Management.Automation/resources/tr/EventResource.tr.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell.Core.Instrumentation.man olay kimliği için bir ileti bulunamadı. + + + Zamanlanmış İş {0}, {1} tarihinde başlatıldı + + + + Zamanlanmış İş {0}, {1} tarihinde {2} durumuyla tamamlandı + + + + Zamanlanmış İş Özel Durumu {0}: + İleti: {1} + Yığın İzleme: {2} + İç Özel Durum: {3} + + + + Deneysel Özellik Başlatma: Yapılandırma dosyasındaki deneysel Özellik '{0}' yoksay. {1} + + + Deneysel Özellik Başlatma: Yapılandırma dosyası okunamadı. + Özel durum: {0} + İleti: {1} + Yığın İzleme: {2} + + + + İş akışı eklentisi yüklendi. + EndpointName: {0} + Kullanıcı: {1} + Barındırma modu: {2} + Protokol: {3} + Yapılandırma: + {4} + + + İş akışı yürütmesi başlatıldı. + WorkflowId: {0} + YönetilenDüğümler: {1} + + + İş akışı durumu değişti. + WorkflowId: {0} + YeniDurum: {1} + EskiDurum: {2} + + + İş akışı eklentisinin kapatılması istendi. + Uç nokta adı: {0} + + + Workflow eklentisi yeniden başlatıldı. + Uç nokta adı: {0} + + + İş akışı devam ediyor. + WorkflowId: {0} + + + Uç nokta için ayarlanan kota sınırı Aşıldı. + EndpointName: {0} + Yapılandırma Adı: {1} + İzin Verilen Değer: {2} + Söz Konusu Değer: {3} + + + İş akışı yeniden başlatıldı. + WorkflowId: {0} + + + İş akışı çalışma alanı havuzu oluşturuldu. + WorkflowId: {0} + ManagedNode: {1} + + + Etkinlik yürütme için sıraya alındı. + WorkflowId: {0} + ActivityName: {1} + + + Etkinlik yürütmesi başladı. + ActivityName: {0} + ActivityTypeName: {1} + + + İş akışı bir XAML dosyasından içe aktarılıyor. + WorkflowId: {0} + XamlFile: {1} + + + İş akışı bir XAML dosyasından içe aktarıldı. + WorkflowId: {0} + XamlFile: {1} + + + XAML dosyasındaki bir hata nedeniyle iş akışı içe aktarılamadı. + WorkflowId: {0} + Hata Açıklaması: {1} + + + İş akışı doğrulaması başlatıldı. + WorkflowId: {0} + + + İş akışı doğrulaması başarılı oldu. + WorkflowId: {0} + + + İş akışı doğrulaması hatayla başarısız oldu. + WorkflowId: {0} + + + İş akışı etkinliği doğrulandı. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + İş akışı etkinliği doğrulanamadı. + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + Etkinlik yürütmesi başarısız oldu. + WorkflowId: {0} + EtkinlikAdı: {1} + HataAçıklaması: {2} + + + Çalışma alanı kullanılabilirliği değişti. + Çalışma alanı kimliği: {0} + Kullanılabilirlik: {1} + + + Çalışma alanı durumu değişti. + Çalışma alanı kimliği: {0} + YeniDurum: {1} + EskiDurum: {2} + + + Yürütme için iş akışı yüklendi. + WorkflowId: {0} + + + İş akışı yüklendi. + WorkflowId: {0} + + + İş akışı yürütmesi iptal edildi. + WorkflowId: {0} + + + İş akışı yürütmesi iptal edildi. + WorkflowId: {0} + + + İş akışı temizleme işlemi yürütüldü. + WorkflowId: {0} + + + Diskten kalıcılaştırılmış iş akışı yüklendi. + WorkflowId: {0} + Yol: {1} + + + İş akışı verileri diskten silindi. + WorkflowId: {0} + Yol: {1} + + + İş kaldırılıyor. + İş Kimliği: {0} + + + İş durumu değişti. + İş Kimliği: {0} + WorkflowId: {1} + YeniDurum: {2} + EskiDurum: {3} + + + İş hatası. + İş Kimliği: {0} + WorkflowId: {1} + Hata Açıklaması: {2} + + + İş akışı için alt iş oluşturuldu. + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + İş akışı için üst iş oluşturuldu. + İş Kimliği: {0} + + + İş akışı yürütmesi için gerekli tüm işler oluşturuldu. + İş Kimliği: {0} + WorkflowId: {1} + + + İş akışı için alt iş kaldırıldı. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + İş kaldırılırken bir hata oluştu. + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + Error: {3} + + + Yürütme için iş akışı yükleniyor. + WorkflowId: {0} + + + İş akışı yürütmesi tamamlandı. + WorkflowId: {0} + + + İş akışı yürütmesi iptal ediliyor. + WorkflowId: {0} + + + İş akışı yürütmesi sonlandırılıyor. + WorkflowId: {0} + Neden: {1} + + + İş akışı boşaltılıyor. + WorkflowId: {0} + + + Zorunlu iş akışı kapatması başlatıldı. + WorkflowId: {0} + + + Zorlanan iş akışı kapatma tamamlandı. + WorkflowId: {0} + + + Bir iş akışı zorla kapatılırken bir hata oluştu. + WorkflowId: {0} + Hata Açıklaması: {1} + + + İş akışı diske kaydediliyor. + WorkflowId: {0} + PersistPath: {1} + + + İş akışı diske kaydedildi. + WorkflowId: {0} + + + Etkinlik yürütmesi tamamlandı. + ActivityName: {0} + + + İş akışı yürütme hatası. + WorkflowId: {0} + Hata Açıklaması: {1} + + + Yeni bir PowerShell uç noktası kaydedildi. + EndpointName: {0} + Uç Nokta Türü: {1} + Kayıt Yapan: {2} + + + Uç nokta yapılandırması değiştirildi. + EndpointName: {0} + Değiştiren: {1} + + + Uç nokta yapılandırması kaydı kaldırıldı. + EndpointName: {0} + Kaydı kaldıran: {1} + + + Uç nokta yapılandırması devre dışı. + EndpointName: {0} + Devre Dışı Bırakan: {1} + + + Uç nokta yapılandırması etkinleştirildi. + EndpointName: {0} + EnabledBy: {1} + + + İşlem dışı çalışma alanı başlatıldı. + Komut: {0} + + + İş akışı yürütmesi sırasında parametre dağıtımı yapıldı. + Parametreler: {0} + Bilgisayarlar: {1} + + + İş akışı altyapısı başlatıldı. + Uç nokta adı: {0} + + + İş akışı yöneticisi ile örneklendi + Denetim noktası yolu: {0} + Yapılandırma sağlayıcı kimliği: {1} + Kullanıcı adı: {2} + Yol: {3} + + + Bilgisayar adı $null veya . LocalHost olarak çözümlensin + + + Varsayılan şemaya http olarak çözümleniyor + + + Uzak kabuk adı varsayılan PowerShellCore olarak çözümlendi + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + Scriptblock metni oluşturuluyor ({0} / {1}): +{2} + +ScriptBlock kimliği: {3} +Yol: {4} + + + ScriptBlock kimliği: {0} için başlatılan çağrı +Çalışma alanı kimliği: {1} + + + Bitenler ScriptBlock kimliği: {0} +Çalışma alanı kimliği: {1} + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + {2} + +Bağlam: +{0} + +Kullanıcı Verileri: +{1} + + + + Etkinlik kimliklerini ilişkilendiriliyor. + Geçerli Etkinlik Kimliği: {0} + Üst Etkinlik Kimliği: {1} + + + Sınıf Adı = {0} +Metot Adı = {1} +İş akışı GUID'si = {2} +İleti = {3} +{4} +Etkinlik Adı = {5} +Etkinlik GUID'si = {6} +Parametreler = {7} + + + Çalışma Alanı nesnesi oluşturuluyor + Örnek Kimliği: {0} + + + RunspacePool nesnesi oluşturuluyor + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + RunspacePool açılıyor + + + Etkinlik kimliğini değiştiriyor ve ilişkilendiriyor + + + Çalışma alanı durumu {0} olarak değiştirildi + + + Hata kodu {1} için oturum kimliği {2} üzerinde oturum oluşturma yeniden deneniyor {0} + + + Windows PowerShell, işlem: {0} AppDomain: {1} içinde bir IPC dinleme iş parçacığı başlattı. + + + Windows PowerShell, işlem: {0} üzerinde AppDomain: {1} içinde IPC dinleme iş parçacığını sonlandırdı. + + + İşlem: {0} içindeki AppDomain: {1} üzerinde PowerShell IPC dinleme iş parçacığında bir hata oluştu. Hata İletisi: {2}. + + + Windows PowerShell, işlem: {0} üzerinde AppDomain: {1} için Kullanıcı: {2} ile IPC bağlantısı kuruyor. + + + Windows PowerShell, işlem {0} için AppDomain: {1} içindeki Kullanıcı: {2} üzerinde IPC bağlantısını kesiyor. + + + Bağlantı noktası {0} olarak çözümlendi + + + AppName {0} olarak çözümlendi + + + Bilgisayar adı {0} olarak çözüldü + + + Şema {0} + + + Analitik test iletisi + + + Bağlantı parametreleri şunlardır + Bağlantı URI'si: {0} + Kaynak URI'si: {1} + Kullanıcı: {2} + Açılma zaman aşımı: {3} + Boşta kalma zaman aşımı: {4} + İptal zaman aşımı: {5} + Kimlik doğrulama mekanizması: {6} + Parmak izi: {7} + Maksimum URI yeniden yönlendirme sayısı: {8} + Maksimum alınan veri boyutu/komut: {0}0 + Maksimum alınan nesne boyutu: {0}1 + + + Etkinlik kimliğini değiştiriyor ve ilişkilendiriyor + + + Çalışma Alanı kimliği: {0} Komut kimliği: {1} Hedef: {2} Veri türü: {3} Hedef arabirim: {4} + + + Uygulamada işlenmeyen bir özel durum oluştu. +Özel durum türü: {0} +Özel durum İletisi: {1} +Özel durum yığın izlemesi: {2} + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. WSMan hata koduyla bir hata bildirdi: {2}. + Hata iletisi: {3} + StackTrace: {4} + + + Uygulamada işlenmeyen bir özel durum oluştu. +Özel durum türü: {0} +Özel durum İletisi: {1} +Özel durum yığın izlemesi: {2} + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. WSMan hata koduyla bir hata bildirdi: {2}. + Hata iletisi: {3} + StackTrace: {4} + + + Çalışma alanı kimliği {0}. WSMan Create Shell kullanılarak bir bağlantı kuruluyor + + + Çalışma alanı kimliği {0}. WSMan Create Shell için geri arama alındı + + + Çalışma alanı kimliği: {0}. WSManCloseShell kullanılarak kabuk kapatılıyor + + + Çalışma alanı kimliği: {0}. WSManCloseShell için geri arama alındı + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. Boyutu {2} olan veri gönderiliyor + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. WSManSendShellInputEx için geri arama alındı + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. WSManReceiveShellOutputEx kullanılarak alma isteği gönderiliyor + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. Boyutu {2} olan Veri alındı. + + + Çalışma alanı kimliği {0} İşlem Zinciri kimliği {1}. WSManRunShellCommandEx kullanılarak komut bağlantısı kuruluyor + + + Çalışma alanı kimliği {0} İşlem Zinciri kimliği {1}. Komut bağlantısı için geri arama alındı + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği {1}. Komut için taşıma kapatılıyor + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği {1}. Komut kapanması için geri arama getirildi + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği {1}. Kod {2} kullanılarak sinyal gönderiliyor WSManSignalShellEx + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği {1}. WSManSignalShellEx için geri arama alındı + + + Çalışma alanı kimliği: {0}. Bağlantı şu Uri'ye yönlendiriliyor: {1} + + + Çalışma alanı kimliği: {0} İşlem Zinciri kimliği: {1}. Sunucu, {2} boyutunda veri gönderiyor istemciye. Veri türü: {3} Hedef arabirim: {4} + + + İstek {0}. Bir sunucu uzak oturumu oluşturuluyor. Kullanıcı adı: {1} Özel Kabuk kimliği: {2} + + + İstek için raporlama bağlamı: {0} bağlam bildirildi: {0} + + + İstek için raporlama işlemi tamamlandı: {0} + Hata kodu: {1} + Hata İletisi: {2} + StackTrace: {3} + + + Kabuk Bağlamı {0}. İstek Kimliği {1}. Komut çalıştırmak için bir komut oturumu oluşturuluyor. + + + Kabuk Bağlamı {0} Komut Bağlamı {1} İstek Kimliği {2}. Komut durduruluyor. + + + Kabuk Bağlamı {0} Komut Bağlamı {1} İstek Kimliği {2}. İstemciden veri alındı. + + + Kabuk Bağlamı {0} Komut Bağlamı {1} İstek Kimliği {2}. İstemci, sunucunun veri gönderebilmesi için bir alma isteği gönderdi. + + + Kabuk Bağlamı {0} Komut Bağlamı {1} IsReceiveOperation {2}. Kapatma işlemi isteği alındı. + + + Özel kabuk için {0} derlemesi, kabuk kimliği {1} ile yükleniyor + + + Özel kabuk için {0} derlemesi, kabuk kimliği {1} ile yükleniyor + + + Uzak ileti parçası alındı. + Nesne kimliği: {0} + Parça kimliği: {1} + Başlangıç bayrağı: {2} + Bitiş bayrağı: {3} + Yük Süresi: {4} + Yük Verisi: {5} + + + Uzak ileti parçası gönderildi. + Nesne kimliği: {0} + Parça kimliği: {1} + Başlangıç bayrağı: {2} + Bitiş bayrağı: {3} + Yük Süresi: {4} + Yük Verisi: {5} + + + winrm hizmeti kapatılıyor. + + + Bir nesne başarıyla yeniden canlandırıldı. + Serileştirilmiş tür adı: {0} + Tür olarak yeniden oluşturuldu: {1} + Yeniden oluşturulan nesnenin türü: {2} + + + Bir nesne yeniden oluşturulamadı. + Serileştirilmiş tür adı: {0} + Tür olarak yeniden oluşturuldu: {1} + Tür dönüştürme özel durumu: {2} + Tür dönüştürme özel iç durum: {3} + + + Serileştirme derinliği geçersiz kılındı. + Serileştirilmiş tür adı: {0} + Orijinal derinlik: {1} + Geçersiz kılınan derinlik: {2} + Geçerli düzey üst düzeyin altında: {3} + + + Serileştirme modu geçersiz kılındı. + Serileştirilmiş tür adı: {0} + Geçersiz kılınan mod: {1} + + + Bir betik özelliğinin serileştirilmesi atlandı; çünkü özelliğin değerlendirilmesi için kullanılacak bir çalışma alanı yok. + Özellik adı: {0} + Özellik sahibinin tür adı: {1} + Alıcı betik: {2} + + + Bir özelliğin serileştirilmesi atlandı, çünkü özellik alıcısı başarısız oldu. + Özellik adı: {0} + Özellik sahibinin tür adı: {1} + Özellik alıcısından özel durum: {2} + Özellik alıcısından gelen özel iç durum: {3} + + + Bir numaralandırılabilir nesnenin serileştirilmesi tamamlanmamış olabilir; çünkü numaralandırılan nesne bir özel durum oluşturdu. + Numaralandırılan nesnenin türü: {0} + Özel durum: {1} + + + Serileştirme, nesnenin ToString metodunu çağırdı ve bu başarısız oldu. + Nesne türü: {0} + Özel durum: {1} + + + Üst düzeyin altındaki maksimum derinliğe ulaşıldı, nesne dizeler olarak serileştirilmeye zorlanıyor. + Maksimum derinlikteki nesne türü: {0} + Maksimum derinlikteki özellik adı: {1} + Derinlik: {2} + + + Seri durumdan çıkarıcı tarafından bir XmlException oluşturuldu (büyük olasılıkla yanlış clixml biçimi gösteriyor). + Satır numarası: {0} satır konumu: {1} + Özel durum: {2} + + + Belirtilen özelliklerin serileştirilmesi başarısız oldu, çünkü belirtilen özelliklerden biri eksikti. + Nesne türü: {0} + Özellik adı: {1} + + + Windows PowerShell konsolu başlatılıyor + + + Windows PowerShell konsolu kullanıcı girişi için hazır + + + {0} + + + İzleme Hatası Kaydı: + İleti: {0} + Kategori Bilgisi.Kategori: {1} + Kategori Bilgisi.Neden : {2} + Kategori Bilgisi.Hedef Adı : {3} + Tam Nitelikli Hata Kimliği: {4} + Özel durum Ayrıntıları: + İleti : {5} + Yığın İzleme: {6} + İç Özel Durum {7} + + + + Özel durum: + İleti: {0} + Yığın İzleme: {1} + İç Özel Durum : {2} + + + + PSObject izleme + + + İzleme işi: + Kimlik: {0} + InstanceId: {1} + Ad: {2} + Konum: {3} + Durum: {4} + Komut: {5} + + + + İzleme Bilgileri: + {0} + + + İzleme Bilgileri: + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication. İş akışı işlevinin çağrılması başlatılıyor. İzleme Guid'si {0} + + + END ImportWorkflowCommand::StartWorkflowApplication. İş akışı işlevinin çağrılması sonlandırılıyor. İzleme Guid'si {0} + + + Yeni iş ImportWorkflowCommand::StartWorkflowApplication içinde oluşturuluyor. İzleme Guid'si {0} + + + ImportWorkflowCommand::StartWorkflowApplication içinde yeni iş oluşturuluyor. İzleme Guid'si {0} + + + ImportWorkflowCommand::StartWorkflowApplication içinde yeni iş oluşturuluyor. İzleme Guid {0} : ContainerParentJob Guid {1} + + + BEGIN JobLogic ContainerParentJob Guid {0} + + + JobLogic ContainerParentJob Guid {0} + + + Guid {0} ile BEGIN WorkflowExecution ContainerParentJob + + + BİTİŞ WorkflowExecution ContainerParentJob Guid {0} + + + Benzersiz Tanıtıcı {0} ile WorkflowJob, Benzersiz Tanıtıcı {1} ile ContainerParentJob’a eklendi + + + Guid {0} olan ProxyJob, Guid {1} olan uzak ContainerParentJob ile ilişkilendirildi + + + Guid {0} ile BEGIN ContainerParentJob Yürütmesi + + + BİTİŞ ContainerParentJob Yürütmesi Guid {0} ile + + + Guid {0} ile Proxy İş Yürütmesi BEGIN + + + BİTİŞ Proxy İşinin yürütülmesi, Guid {0} ile + + + Guid {0} için Proxy İş için BEGIN StateChanged olay işleyicisi + + + BİTİŞ Durum Değiştirme olay işleyicisi, Guid {0} için Ara Sunucu İş İşi + + + Başlangıç Ara Sunucu Çocuk İş için Benzersiz Tanıtıcı {0} olan olay işleyicisi + + + Guid {0} ile Proxy Child Job için StateChanged olay işleyicisi sonlandırılıyor + + + Koşu atık toplama başlatılıyor + + + BİTİŞ atık toplama çalıştırılıyor + + + Kalıcılık deposu belirtilen en büyük boyutuna ulaştı + + + Windows PowerShell ISE, betik dosyası {0} çalıştırmaya başladı. + + + Windows PowerShell ISE, dosya {0} içindeki kullanıcı tarafından seçilen bir betiği çalıştırmaya başladı. + + + Windows PowerShell ISE geçerli komutu durduruyor. + + + Windows PowerShell ISE hata ayıklayıcısını sürdürüyor. + + + Windows PowerShell ISE hata ayıklayıcısını durduruyor. + + + Windows PowerShell ISE hata ayıklamaya giriyor. + + + Windows PowerShell ISE hata ayıklamanın üzerinden geçiyor. + + + Windows PowerShell ISE hata ayıklamadan çıkıyor. + + + Windows PowerShell ISE tüm kesme noktalarını etkinleştiriyor. + + + Windows PowerShell ISE tüm kesme noktalarını devre dışı bırakıyor. + + + Windows PowerShell ISE tüm kesme noktalarını kaldırıyor. + + + Windows PowerShell ISE, {0} satırındaki {1} dosyasında kesme noktası ayarlıyor. + + + Windows PowerShell ISE, {1} dosyasında {0} numaralı satırdaki kesme noktasını kaldırıyor. + + + Windows PowerShell ISE, {0} satırındaki {1} dosyasında kesme noktası ayarlıyor. + + + Windows PowerShell ISE, {1} dosyasının {0} numaralı satırındaki kesme noktasını devre dışı bırakıyor. + + + Windows PowerShell ISE, {0} satırındaki {1} dosyasında bir kesme noktasına isabet etti. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/EventingResources.tr.resx b/src/System.Management.Automation/resources/tr/EventingResources.tr.resx new file mode 100644 index 00000000000..1a54e237f0c --- /dev/null +++ b/src/System.Management.Automation/resources/tr/EventingResources.tr.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Belirtilen olay için kayıt yapılamıyor. Dönüş değeri gerektiren olaylar desteklenmez. + + + Belirtilen olay için kayıt yapılamıyor. '{0}' adlı bir olay yok. + + + PowerShell, Windows RT olaylarına abone olamaz. + + + Belirtilen olay için kayıt yapılamıyor. '{0}' olay kaynak tanımlayıcısı PowerShell altyapısı için ayrılmıştır. + + + Bu işlem uzak örneklerde desteklenmez. + + + Olayları iletirken eylem desteklenmez. + + + Belirtilen olaya abone olunamıyor. Kaynak tanımlayıcısı '{0}' olan bir abone zaten var. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ExperimentalFeatureStrings.tr.resx b/src/System.Management.Automation/resources/tr/ExperimentalFeatureStrings.tr.resx new file mode 100644 index 00000000000..1acaed0e205 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ExperimentalFeatureStrings.tr.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}' adıyla eşleşen deneysel özellik bulunamadı. + + + Deneysel özellikleri etkinleştirme ve devre dışı bırakma işlemleri, PowerShell bir sonraki kez başlatılana kadar etkili olmaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ExtendedTypeSystem.tr.resx b/src/System.Management.Automation/resources/tr/ExtendedTypeSystem.tr.resx new file mode 100644 index 00000000000..29427f38e7f --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ExtendedTypeSystem.tr.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + “{0}" üyesi zaten var. + + + Genişletilmiş tür veri dosyasından "{0}" boyut üyesi zaten mevcut. + + + “{0}" üyesi mevcut değil. + + + “{0}" özelliğini ayarlarken özel durum oluştu: "{1}” + + + “{0}" alınırken özel durum oluştu: "{1}” + + + Aşağıdaki özel durum, koleksiyon numaralandırılırken oluştu: "{0}". + + + “{0}" üyesine PSObject dışında erişilemez. + + + Tür yapılandırmasından oluşturulan üye değiştirilemiyor: "{0}” + + + “{0}" üye adı ayrılmıştır. + + + Bağdaştırıcı, "{0}" özelliğinin türünü alamıyor. + + + “{0}" araması sırasında "{1}" bağımsız değişkeniyle özel durum oluştu: "{2}” + + + “{1}” türündeki bir nesnenin içeriğini ayıklamak için “{0}” çağrılmaya çalışılırken özel durum oluştu: “{2}” + + + “{0}" için ve bağımsız değişken sayısı "{1}" için bir aşırı yükleme bulunamadı. + + + “{0}" için "{1}" tür parametreleri ve bağımsız değişken sayısı "{2}" ile uygun bir genel metot aşırı yüklemesi bulunamadı. + + + “{0}" ve bağımsız değişken sayısı "{1}" için birden çok belirsiz aşırı yükleme bulundu. + + + “{0}" bağımsız değişkeni, "{1}" değeriyle, "{2}" için "{3}" türüne dönüştürülemez: "{4}” + + + “{0}" özelliğinin get erişimcisi kullanılamaz. + + + “{0}" özelliğinin Set erişimcisi kullanılamaz. + + + Ayarlayıcı metot genel, void, statik olmalı ve iki parametreye sahip olmalıdır. İlk parametre PSObject türünde olmalıdır. Alıcı metot da kullanılabiliyorsa ikinci bir parametre gerekir ve alıcı metodun dönüş türüyle aynı türe sahip olmalıdır. + + + Alıcı metot genel olmalı, void olmamalı, statik olmalı ve PSObject türünde bir parametreye sahip olmalıdır. + + + CodeProperty bir alıcı veya ayarlayıcı yöntem kullanmalıdır. + + + Yöntem biçimi nedeniyle kod yöntemi oluşturulamıyor. Yöntem public, static olmalı ve PSObject türünde bir parametreye sahip olmalıdır. + + + “{0}" adlı diğer ad bir tekil anket içeriyor. + + + “{0}" değerinin "{1}" türünden "{2}" türüne dönüştürülmesi mümkün değil. + + + “{0}" değerinin türü "{1}" türüne dönüştürülemiyor. + + + “{0}" değerini "{1}" türüne dönüştürülemiyor. Hata: "{2}" + + + “{0}" değerini "{1}" türüne dönüştürülemez; çünkü bu numaralandırma için virgüllere izin verilmez. + + + “{0}" değerini "{1}" türüne dönüştürülemez; çünkü bu numaralandırma için geçersiz değerler var. Lütfen aşağıdaki numaralandırma değerlerinden birini belirtin ve yeniden deneyin. Olası numaralandırma değerleri "{2}". + + + Geçersiz numaralandırma değerleri nedeniyle null, "{0}" türüne dönüştürülemez. Lütfen aşağıdaki numaralandırma değerlerinden birini belirtin ve yeniden deneyin. Olası numaralandırma değerleri "{1}". + + + null değeri "{0}" türüne dönüştürülemiyor. + + + Değer “{0}” türüne dönüştürülemiyor. Hata: "{1}" + + + Değer System.String türüne dönüştürülemiyor. + + + Bağımsız değişkende başvuru türü bekleniyor. + + + “{0}" IComparable olmadığı için karşılaştırılamıyor. + + + “{0}" ile "{1}" karşılaştırılamadı. Hata: "{2}" + + + Nesneler aynı türde olmadığından veya “{0}” nesnesi “{2}” öğesini uygulamadığından “{0}” ile “{1}” karşılaştırılamaz. + + + “{0}" değerini "{1}" türüne dönüştürülemez; çünkü en az iki eşleşme bulundu ({2}, {3}) ve bu sabit listesi için yalnızca bir eşleşmeye izin verilir. + + + “{0}" değerini "{1}" türüne dönüştürülemiyor. Boolean parametreler yalnızca boolean değerleri ve $True, $False, 1 veya 0 gibi sayıları kabul eder. + + + “{0}" bir yazma amaçlı özelliktir, bu nedenle özellik değeri alınamıyor. + + + “{0}" salt okunur bir özelliktir. + + + “{0}" ayarlanamıyor çünkü XmlNode özelliklerinin değeri olarak yalnızca dizeler kullanılabilir. + + + “{0}" ayarlanamıyor çünkü yalnızca benzersiz özellikler veya özniteliği olmayan benzersiz yaprak düğümler ayarlanabilir. + + + Bu koleksiyona bir PSProperty veya PSMethod nesnesi eklenemez. + + + “{0}" değiştirilemez. + + + Dize alınırken aşağıdaki özel durum oluştu: "{0}” + + + “{1}” türü için “{0}” alanı veya özelliği, “{2}” alanı veya özelliğinden yalnızca büyük/küçük harf kullanımı bakımından farklıdır. Tür Common Language Specification (CLS) ile uyumlu olmalıdır. + + + Aşağıdaki özel durum, tür adı hiyerarşisi alınırken oluştu: "{0}". + + + Aşağıdaki özel durum, "{1}" üyesi alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, üyeler alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, "{1}" özelliği için okuma durumu alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, "{1}" özelliği için yazma durumu alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, "{1}" özelliği için tür alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, "{1}" özelliği için dize beyanı alınırken oluştu: "{0}” + + + “{1}" özelliği için öznitelikler alınırken aşağıdaki özel durum oluştu: "{0}” + + + Aşağıdaki özel durum, "{1}" metodu için tanımlar alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, "{1}" özelliği için dize beyanı alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, parametreli özellik "{1}" için tür alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, parametreli özellik "{1}" için okuma durumu alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, parametreli özellik "{1}" için yazma durumu alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, parametreli özellik "{1}" için tanımlar alınırken oluştu: "{0}” + + + Aşağıdaki özel durum, parametreli özellik "{1}" için dize beyanı alınırken oluştu: "{0}” + + + Türü "{0}" olan PSMemberInfo nesnesi için Value özelliği ayarlanamıyor. + + + Bağımsız değişken: '{0}' bir {1} olmalıdır. Şunu kullanın: {2}. + + + Bağımsız değişken: '{0}' bir {1} olmamalıdır. {2} kullanmayın. + + + Özellik "{0}" bulunamadı. + + + Özellik değerini almak veya kümelemek mümkün değil. “{0}" bağımsız değişkeni "{1}" veya "{2}" türünde olmalıdır. + + + “{0}" özelliğinin değerini ayarlayamıyorum çünkü nesnenin türü "{1}" ve "{2}" değil. + + + “{0}" çağrılırken özel durum oluştu: "{1}” + + + “{0}" geçerli bir sınıf yolu değil. + + + {0} geçerli bir yol değil. + + + Bağdaştırıcı, "{0}" özelliğinin değiştirilebilir olup olmadığını belirleyemiyor. + + + Bağdaştırıcı, "{0}" özelliğinin alınabilir olup olmadığını belirleyemiyor. + + + Bağdaştırıcı, "{0}" özelliğinin değerini alamıyor. + + + Bağdaştırıcı, "{0}" özelliğinin değerini ayarlayamıyor. + + + Bağdaştırıcı, "{0}" özelliğinin türünü alamıyor. + + + Bağdaştırıcı, "{0}" öğesinin tür hiyerarşisini alamıyor. + + + Bağdaştırıcı, "{0}" öğesinin özelliklerini alamıyor. + + + Bağdaştırıcı, “{1}” için “{0}” özelliğini alamıyor. + + + “{0}" null değerini döndürdü. + + + ‘{0}' özelliği, '{1}' nesnesi için bulunamadı. Ayarlanabilir özellikler şunlardır: {2}. + + + ‘{0}' özelliği, '{1}' nesnesi için bulunamadı. Kullanılabilir bir ayarlanabilir özellik yok. + + + “{0}" türünde nesne oluşturulamıyor. {1} + + + Açık genel tür {0} üzerinde statik yöntemler çağrılamaz veya statik özelliklere erişilemez. Tür parametrelerini belirtin ve yeniden deneyin. Örneğin, [System.Collections.Generic.HashSet``1]::CreateSetComparer() yerine [System.Collections.Generic.HashSet[int]]::CreateSetComparer() kullanın. + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + Aşağıdaki özel durum, "{1}" özniteliği oluşturulurken oluştu: "{0}” + + + “{0}" değeri bir dize dizisine dönüştürülemiyor. + + + Değer “{0}” türüne dönüştürülemiyor. Bu dil modunda yalnızca çekirdek türler desteklenir. + + + ByRef benzeri türe "{0}" dönüştürme yapılamaz. ByRef benzeri türler Windows PowerShell'de desteklenmez. + + + “{0}" özelliğini veya alanını ByRef benzeri "{1}" türünden alamaz veya ayarlayamaz. ByRef benzeri türler PowerShell'de desteklenmez. + + + “{1}” ByRef benzeri dönüş türünün “{0}” yöntemi çağrılamıyor. ByRef benzeri türler PowerShell'de desteklenmez. + + + ByRef benzeri türe sahip bir örnek oluşturulamıyor: "{0}” ByRef benzeri türler Windows PowerShell'de desteklenmez. + + + Genişletilmiş Tür Sistemi Hashtable Dönüşümü + + + HashTable'dan '{0}' türüne dönüştürme, ConstrainedLanguage modunda izin verilmeyecektir. + + + Genişletilmiş Tür Sistemi Hashtable Dönüşümü + + + KısıtlanmışDil modunda '{0}' türünden '{1}' türüne dönüştürmeye izin verilmeyecek. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/FileSystemProviderStrings.tr.resx b/src/System.Management.Automation/resources/tr/FileSystemProviderStrings.tr.resx new file mode 100644 index 00000000000..cbd54390600 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/FileSystemProviderStrings.tr.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Öğeyi Çağır + + + Öğe: {0} + + + Dosyayı Kaldır + + + Dizini Kaldır + + + Dosyayı Kopyala + + + Öğe: {0} Hedef: {1} + + + Dizini Kopyala + + + Dosyayı Yeniden Adlandır + + + Dizini Yeniden Adlandır + + + Öğe: {0} Hedef: {1} + + + Dosyayı Taşı + + + Dizini Taşı + + + Öğe: {0} Hedef: {1} + + + Özellik Dosyasını Ayarla + + + Özellik Dizinini Ayarla + + + Öğe: {0} Özellik: {1} Değer: {2} + + + Özellik Dosyasını Temizle + + + Özellik Dizinini Temizle + + + Öğe: {0} Özellik: {1} + + + Dosya Oluştur + + + Dizin Oluştur + + + Hedef: {0} + + + İçeriği Temizle + + + Öğe: {0} + + + {0} öğesi bulunamadı. + + + {0} öğesi kaldırılamıyor: {1} + + + {0} öğesinde öznitelikler geri yüklenemiyor: {1} + + + Belirtilen {0} yolunda bir nesne yok. + + + {0} dizini boş olmadığından kaldırılamıyor. + + + Tür, dosya sistemi için bilinen bir tür değil. Yalnızca "file", "directory" veya "symboliclink" belirtilebilir. + + + Belirtilen yol basePath dışındaki bir öğeye başvurduğundan, yol işlenemiyor. + + + Belirtilen "{0}" sürücü kökü yok veya bir klasör değil. + + + Belirtilen {0} adına sahip bir öğe zaten var. + + + Akış her seferinde bir bayt okunurken sınırlayıcı belirtilemez. + + + {0} öğesi kendi üzerinde yazılamaz. + + + Belirtilen hedef bir yol veya cihaz adını temsil ettiğinden, yeniden adlandırılamıyor. + + + {0} özelliği yok veya bulunamadı. + + + Bu işlemi gerçekleştirmek için yeterli erişim hakkınız yok veya öğe gizli, sistem öğesi veya salt okunur. + + + Öznitelikler desteklenmediğinden öznitelik ayarlanamıyor. Yalnızca şu öznitelikler ayarlanabilir: Archive, Hidden, Normal, ReadOnly veya System. + + + Özellik desteklenmediğinden temizlenemiyor. Yalnızca Attributes özelliği temizlenebilir. + + + Hedef ayrılmış bir cihaz adını temsil ettiğinden '{0}' yolu işlenemiyor. + + + '-AsByteStream' belirtildiğinde kodlama kullanılmaz. + + + Bayt kodlamasına devam edilemiyor. Bayt kodlaması kullanılırken içerik bayt türünde olmalıdır. + + + {0} dosyası bulunamadığı için dosya işlenemiyor. + + + Dizin: + + + Dosyanın kodlaması algılanamadı. Belirtilen {0} kodlaması, içerik tersten okunduğunda desteklenmez. + + + '{1}' dosyasının '{0}' alternatif veri akışı açılamadı. + + + '{1}' dosyasının '{0}' akışı. + + + Raw ve Wait parametreleri aynı komutta belirtilemez. + + + Persist anahtar parametresini kullanmak için sürücü adının işletim sistemi tarafından desteklenmesi gerekir (örneğin, A-Z sürücü harfleri). + + + Persist parametresini kullandığınızda, kök uzak bilgisayardaki bir dosya sistemi konumu olmalıdır. + + + '{0}' ve '{1}' parametreleri aynı komutta belirtilemez. + + + İşlem için bir dizin gerekiyor. '{0}' öğesi bir dizin değil. + + + Birleşim Oluştur + + + Sembolik Bağlantı Oluştur + + + Bu işlem için Yönetici ayrıcalığı gerekir. + + + Sabit Bağlantı Oluştur + + + İşlem için bir dosya gerekiyor. '{0}' öğesi bir dosya değil. + + + Belirtilen yol için sabit bağlantılar desteklenmiyor. + + + Belirtilen yol için sembolik bağlantılar desteklenmiyor. + + + {0} dosyasını {1} klasörüne kopyalama + + + {0} hedef yolu, hedef konumda zaten mevcut olan bir dosyadır. + + + {0} dosyası uzak hedef konuma kopyalanamadı. + + + Başlangıç: {0} Bitiş: {1} + + + '{0}' dizini '{0}' dosyasına kopyalanamıyor + + + {0} dizini alt öğeleri alınamadı. + + + '{0}' uzak dosyası okunamadı. + + + {0} uzak hedefinin bir dosya olup olmadığı doğrulanamıyor. + + + Uzak hedefte '{0}' dizini oluşturulamadı. + + + Sürücü için maksimum boyut aşıldı: {0}. + + + Yol zaten mevcut olduğundan bağlantı oluşturulamıyor: {0}. + + + Daha önce ziyaret edilmiş olan {0} dizinini atlayın. + + + Hedef yol, kaynağın bir alt dizini veya kaynağın kendisi olamaz: {0}. + + + Hedef ve yol aynı olamaz. + + + {1} dosyasının {0} tanesi kopyalandı + + + {0}/{1} ({2:0.0} MB/sn) + + + {1} dosyanın {0} tanesi kaldırıldı + + + {0}/{1} ({2:0.0} MB/sn) + + + Bir birleşim oluşturmak için hedefin mutlak bir yolu olması gerekir. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/FormatAndOutXmlLoadingStrings.tr.resx b/src/System.Management.Automation/resources/tr/FormatAndOutXmlLoadingStrings.tr.resx new file mode 100644 index 00000000000..f117db8925a --- /dev/null +++ b/src/System.Management.Automation/resources/tr/FormatAndOutXmlLoadingStrings.tr.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {1} dosyasındaki {0} XPath'inde hata: {2} XML öğesi özniteliklere izin vermiyor. + + + {1} dosyasındaki {0} XPath'inde hata: {2} düğümü alt nesnelere sahip olamaz. + + + {1} dosyasındaki {0} XPath'inde hata: {2} geçerli değil. + + + {1} dosyasındaki {0} XPath'inde hata: En az bir varsayılan {2} bulunmalıdır. + + + {1} dosyasındaki {0} XPath'inde hata: Birden fazla varsayılan {2} olamaz. + + + {1} dosyasındaki {0} XPath'inde hata: Kontrol adı null veya boş olamaz. + + + {1} dosyasındaki {0} XPath'inde hata: Out Of Band görünümleri yalnızca CustomControl veya ListControl içerebilir. + + + {1} dosyasındaki {0} XPath'inde hata: Bir Out Of Band görünümü GroupBy içermemelidir. + + + {1} dosyasındaki {0} XPath'inde hata: Görünüm yüklenemiyor. + + + {1} dosyasındaki {0} XPath'inde hata: “{2}” geçerli bir hizalama değeri değildir. + + + {1} dosyasındaki {0} XPath'inde hata: Pozitif bir tamsayı bekleniyor. + + + {1} dosyasındaki {0} XPath'inde hata: Sütun başlığı tanımı geçerli değil; tüm başlıklar göz ardı edildi. + + + {1} dosyasındaki {0} XPath'inde hata: Alternatif küme #{3}'teki satır öğesi sayısı = {2}, varsayılan satır öğesi sayısı = {4} ile eşleşmiyor. + + + {1} dosyasındaki {0} XPath'inde hata: {2} başlık öğesi sayısı, {3} varsayılan satır öğesi sayısı ile eşleşmiyor. + + + {1} dosyasındaki {0} XPath'inde hata: En az bir liste görünümü öğesi belirtilmelidir. + + + {1} dosyasındaki {0} XPath'inde hata: Özellik girişi geçerli değil. + + + {1} dosyasındaki {0} XPath'inde hata: Tanım listesi eksik. + + + {1} dosyasındaki {0} XPath'inde hata: Boole değeri bekleniyor. + + + {1} dosyasındaki {0} XPath'inde hata: Negatif olmayan bir tamsayı bekleniyor. + + + {1} dosyasındaki {0} XPath'inde hata: Bir tamsayı bekleniyor. + + + {1} dosyasındaki {0} XPath'inde hata: İç metin değeri eksik. + + + {1} dosyasındaki {0} XPath'inde hata: Özel denetim belirteç listesi boş olamaz. + + + {1} dosyasındaki {0} XPath'inde hata: {2} yüklenemedi. + + + {1} dosyasındaki {0} XPath'inde hata: {2}, bir ifade olmadan belirtilemez. + + + {1} dosyasındaki {0} XPath'inde hata: {2} bir ifadeyle belirtilemez. + + + {1} dosyasındaki {0} XPath'inde hata: Bir biçim dizesi eksik. + + + {1} dosyasındaki {0} XPath'inde hata: Komut dosyası bloğu metni eksik. + + + {1} dosyasındaki {0} XPath'inde hata: Bir özellik eksik. + + + {1} dosyasındaki {0} XPath'inde hata: “{2}” komut dosyası bloğu geçersiz. + + + {1} dosyasındaki {0} XPath'inde hata: {4} derlemesindeki {3} kaynağından gelen {2} dizesi bulunamadı. + + + {1} dosyasındaki {0} XPath'inde hata: {2} derlemesindeki {3} kaynağı bulunamadı. + + + {1} dosyasındaki {0} XPath'inde hata: {2} derlemesi bulunamadı. + + + {1} dosyasındaki {0} XPath'inde hata: Düğüm bir XmlElement olmalıdır. + + + {1} dosyasındaki {0} XPath'inde hata: Bir ifade bekleniyor. + + + {1} dosyasındaki {0} XPath'inde hata: İfade içermeyen bir kontrol veya etiket olamaz. + + + {1} dosyasındaki {0} XPath'inde hata: Kontrol ve Etiket aynı anda bulunamaz. + + + {1} dosyasındaki {0} XPath'inde hata: SelectionSetName ve TypeName aynı anda kullanılamaz. + + + {1} dosyasındaki {0} XPath'inde hata: Görünümü uygulamak için herhangi bir tür veya koşul belirtilmemiştir. + + + {1} dosyasındaki {0} XPath'inde hata: {2} değeri geçerli değil. + + + {1} dosyasındaki {0} XPath'inde hata: Yinelenen bir düğüm var. + + + {1} dosyasındaki {0} XPath'inde hata: {2} ve {3} birbirini dışlar. + + + {1} dosyasındaki {0} XPath'inde hata: {2}, {3} ve {4} birbirini dışlar. + + + {1} dosyasındaki {0} XPath'inde hata: {2} bilinmeyen bir düğümdür. + + + {1} dosyasındaki {0} XPath'inde hata: {2} bilinmeyen bir özniteliktir. + + + {1} dosyasındaki {0} XPath'inde hata: {2} özniteliği eksik. + + + {1} dosyasındaki {0} XPath'inde hata: {2} düğümü eksik. + + + {1} dosyasındaki {0} XPath'inde hata: {2}'te bir düğüm eksik. + + + {1} dosyasındaki {0} XPath'inde hata: {2} boş bir düğümdür. + + + {1} dosyasındaki {0} XPath'inde hata: {2} boş bir özniteliktir. + + + {0} dosyasında hata: {1} + + + {0} dosyasında çok fazla hata var. + + + Biçim veri dosyası yüklenirken hatalar oluştu: {0} + + + (Genel Bütünleştirilmiş Kod Önbelleği) {0} + + + {0}, {1} + + + {0} yolu tam olarak belirtilmemiştir. Tam nitelikli bir format dosyası yolu belirtin. + + + FormatTable güncelleştirilemiyor; çünkü FormatTable, çalışma alanı dışında oluşturulmuş olabilir. + + + FormatTable yüklenirken hatalar oluştu. Ayrıntılı hata mesajlarını görmek için Hatalar özelliğinin içeriğini görüntüleyin. + + + “{0}” verisinin biçimlendirilmesinde hata: {1} + + + {0} türündeki verilerin {1} indeksinde bir hata oluştu: Başlık öğe sayısı = {2}, varsayılan satır öğe sayısı = {3} ile eşleşmiyor. + + + {0} türündeki verilerin {1} indeksinde bir hata oluştu: “{2}” verisinin biçimlendirilmesi geçerli değil. + + + {0} türündeki verilerin {1} indeksinde bir hata oluştu: “{2}” komut dosyası bloğu geçersiz. + + + {0} türündeki verilerin {1} indeksinde bir hata oluştu: {2} yüklenemedi. + + + {0} türündeki verilerin {1} indeksinde bir hata: Bir TableControl öğesi yalnızca bir {2} içermelidir. + + + {0} türündeki verilerin {1} indeksinde bir hata: En az bir varsayılan {2} olmalıdır. + + + {0} türündeki verilerin {1} indeksinde bir hata oluştu: En az bir liste görünümü öğesi belirtilmelidir. + + + {0} tür adındaki verilerin {1} indeksinde bir hata: Birden fazla varsayılan {2} olamaz. + + + “{0}” türü için veri biçimlendirmede çok fazla hata var. + + + Paylaşılan bir biçim tablosu, birden fazla girişle güncelleştirilemez. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/FormatAndOut_MshParameter.tr.resx b/src/System.Management.Automation/resources/tr/FormatAndOut_MshParameter.tr.resx new file mode 100644 index 00000000000..d15d161d792 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/FormatAndOut_MshParameter.tr.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 + + + {0}, şu türlerden birine dönüştürülemiyor: {1}. + + + Bir parametrenin değeri null idi; şu türlerden biri bekleniyordu: {0}. + + + Yinelenen "{0}" anahtarı "{1}" ile çakışıyor. + + + "{0}" anahtarının türü {1} ve geçerli değil; beklenen türler: {2}. + + + "{0}" anahtarının türü {1} ve geçerli değil; beklenen tür: {2}. + + + {0} anahtarı belirsiz; {1} ve {2} çakışıyor. + + + Bir anahtarın değeri null olamaz. + + + {0} anahtarının türü geçerli değil. Anahtar bir dize olmalıdır. + + + {0} anahtarının değeri yok. + + + {0} için zorunlu bir girdi eksik. + + + {0} anahtarı geçerli değil. + + + "{1}" anahtarı için "{0}" değeri geçerli değil; geçerli değerler: {2}. + + + "{1}" anahtarı için "{0}" değeri 0'dan büyük olmalıdır. + + + "{0}" anahtarı için boş bir biçimlendirme dizesi olamaz. + + + "{0}" anahtarında boş bir dize değeri olamaz. + + + Burada boş dizeye izin verilmiyor. + + + "{0}" anahtarında "{1}" değerinde joker karakterler olamaz. + + + "{0}" için joker karakterlere izin verilmez. + + + EnumerableExpansion değeri geçerli değil. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/FormatAndOut_format_xxx.tr.resx b/src/System.Management.Automation/resources/tr/FormatAndOut_format_xxx.tr.resx new file mode 100644 index 00000000000..3dfe2b4c7f3 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/FormatAndOut_format_xxx.tr.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parametreleri View ve Property birbirini dışlar. + + + Cmdlet parametreleri AutoSize ve Column birbirini dışlar. + + + {0} görünüm adı bulunamadı. + + + {0} görünüm adı {1} biçimlendirmesinde bulunamadı. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + {1} nesne için mevcut {0} görünüm yok. + + + {0} görünüm adı bulunamadı. Aşağıdaki {1} görünümden birini belirtin ve yeniden deneyin: {2}. + + + Şu diğer biçim cmdlet'lerinden birini kullanmayı deneyin: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + Aşağıdaki nesne IEnumerable'ı destekliyor: + + + IEnumerable nesne içermiyor. + + + IEnumerable aşağıdaki nesneyi içeriyor: + + + IEnumerable şu {0} nesneyi içeriyor: + + + Bilinmeyen {0} sınıf kimliği. + + + {1} özelliği için {0} türü geçerli değil. + + + {0} veri üyesinin değeri null olamaz. + + + Nesne türü tanınmıyor. + + + Sınıf kimliği {0} olan nesne oluşturulamadı. + + + {0} özelliği özyinelemeli. + + + "{0}" ifadesi değerlendirilemedi. + + + "{0}" biçim dizesi yorumlanamadı. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/FormatAndOut_out_xxx.tr.resx b/src/System.Management.Automation/resources/tr/FormatAndOut_out_xxx.tr.resx new file mode 100644 index 00000000000..fffaf26691c --- /dev/null +++ b/src/System.Management.Automation/resources/tr/FormatAndOut_out_xxx.tr.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> sonraki sayfa; <CR> sonraki satır; Q çık + + + SatırOutput değeri null olmamalıdır. + + + lineOutput türü {0} beklenmiyordu; LineOutput tür {1} bekler. + + + “{0}" türündeki nesne geçersiz veya doğru sırada değil. Bunun nedeni büyük olasılıkla varsayılan biçimlendirmeyle çakışan kullanıcı tarafından belirtilen "{1}" komutudur. + + + “{0}" dosyası açılamıyor. + + + Dosyaya çıktı + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/GetErrorText.tr.resx b/src/System.Management.Automation/resources/tr/GetErrorText.tr.resx new file mode 100644 index 00000000000..6a95c900cc6 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/GetErrorText.tr.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Temel adı "{0}" olan bir kaynak yüklenemiyor. + + + “{0}" kimlikli bir kaynak dizesi yüklenemiyor. + + + Durdur ilkesi ayarları komutların çalıştırılmasını engelliyor. + + + Bir derleme kaydedilmediği için "{0}" "{1}" "{2}" iletisi alınamıyor. + + + “{0}" "{1}" "{2}" iletisi alınamıyor. Şablon dizesi biçimi, şablon dizesi "{3}" içinde geçersiz. + + + “{0}" "{1}" "{2}" iletisi alınamıyor. Bir şablon dize var, ancak değeri boş veya boşluklardan oluşuyor. + + + Ardışık düzen durduruldu. + + + Betik, çağrı derinliği taşması nedeniyle başarısız oldu. + + + Ardışık düzen, çağrı derinliği taşması nedeniyle başarısız oldu. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/HelpDisplayStrings.tr.resx b/src/System.Management.Automation/resources/tr/HelpDisplayStrings.tr.resx new file mode 100644 index 00000000000..eafca05664f --- /dev/null +++ b/src/System.Management.Automation/resources/tr/HelpDisplayStrings.tr.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + AD + + + ÖZET + + + AÇIKLAMA + + + SÖZ DİZİMİ + + + PARAMETRELER + + + GİRİŞLER + + + ÇIKIŞLAR + + + SONLANDIRICI HATALAR + + + SONLANDIRICI OLMAYAN HATALAR + + + NOTLAR + + + ÖRNEKLER + + + Örnek + + + ÖRNEK + + + ÇIKTI + + + İLGİLİ BAĞLANTILAR + + + KISA AÇIKLAMA + + + Başlık: + + + Soru: + + + Yanıt + + + Dönem: + + + Tanım: + + + İçerik: + + + SAĞLAYICI ADI + + + Bu cmdlet, ortak parametreleri destekler: Ayrıntılı, Hata Ayıklamak, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable ve OutVariable. Daha fazla bilgi için bkz + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Gerekli mi? + + + Konum? + + + Tür: + + + Hedef Nesne Türü: + + + Varsayılan değer + + + Ardışık düzen girişi kabul edilsin mi? + + + Joker karakterler kabul edilsin mi? + + + (Kategori: + + + Önerilen Eylem: + + + Daha fazla bilgi için şunu yazın: + + + Teknik bilgi için, yazın: + + + Örnekleri görmek için, yazın: + + + Çevrimiçi yardım için şunu yazın: + + + <CommonParameters> + + + AÇIKLAMALAR + + + true + + + Adlandırılmış + + + SÜRÜCÜLER + + + Özellikler + + + GÖREVLER + + + Görev: + + + FİLTRELER + + + DİNAMİK PARAMETRELER + + + Desteklenen Cmdlet'ler: + + + Diğer adlar + + + Get-Help bu bilgisayarda bu cmdlet için Yardım dosyalarını bulamıyor. Yalnızca kısmi yardım gösteriliyor. + -- Bu cmdlet’i içeren modül için Yardım dosyalarını indirmek ve yüklemek için Update-Help kullanın. + -- Bu cmdlet için Yardım konusunu çevrimiçi görüntülemek için şunu yazın: "Get-Help {0} -Online" veya + şuraya gidin: {1}. + + + Yok + + + Diğer adlar + + + Dinamik mi? + + + Parametre kümesi adı + + + UI kültürü {0} için HelpInfo XML dosyası alınamıyor. Modül bildirimindeki HelpInfoUri özelliğinin geçerli olduğundan emin olun veya ağ bağlantınızı denetleyin ve ardından komutu yeniden deneyin. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + Belirtilen kültür desteklenmiyor: {0}. Aşağıdaki listeden bir kültür belirtin: {{{1}}}. + + + Hata ayıklanıyor ve yedek kültürler deneniyor; hiçbiri desteklenmezse hata olarak gösterilecek: +{0} + + + ModuleBase dizini bulunamıyor. Dizini doğrulayın ve yeniden deneyin. + + + {0} yolu geçerli bir dizin değil. Dizinin var olduğundan emin olun ve yeniden deneyin. + + + Bir Yardım URI'si 10'dan fazla yönlendirme içeremez. Geçerli bir Yardım URI'si belirtin. + + + Yardım güncelleştiriliyor + + + Yardım içeriğine bağlanılıyor... + + + Yardım içeriği indiriliyor... + + + Yardım içeriği yükleniyor... + + + Yardım içeriği yükleniyor... + + + (Tümü) + + + Aşağıdaki desene uyan hiçbir Windows PowerShell modülü bulunamadı: {0}. Deseni doğrulayın ve ardından komutu yeniden deneyin. + + + Windows PowerShell ile eşleşen belirtilen FullyQualifiedModule {0} bulunamadı. FullyQualifiedModule değerini doğrulayın ve ardından komutu yeniden deneyin. + + + Yardım içeriği bulunamıyor. Sunucunun kullanılabilir olduğundan ve yardım içeriği konumunun HelpInfo XML’de doğru şekilde tanımlandığından emin olun. + + + Update-Help komutu başarısız oldu çünkü belirtilen modül Güncelleştirilebilir Yardım'ı desteklemiyor. Bu modüldeki komutlar için Get-Help -Online kullanın veya Çevrimiçi Yardım arayın. + + + Aşağıdaki parametre null veya boş olamaz: Module. + + + Aşağıdaki parametre null veya boş olamaz: Yol. + + + Update-Help başarıyla tamamlandı. + + + Yardım içeriği ayıklanırken hata oluştu. + + + Yardım içeriğine bağlanılamıyor. Yardım içeriğinin depolandığı sunucu kullanılamıyor olabilir. Sunucunun kullanılabilir olduğunu doğrulayın veya sunucu yeniden çevrimiçi olana kadar bekleyin ve ardından komutu yeniden deneyin. + + + Belirtilen konumdaki Yardım içeriği geçerli değil. Geçerli Yardım İçeriği içeren bir konum belirtin. + + + YardımInfo XML'i geçersiz. Geçerli HelpInfo XML belirtin. + + + Yardım içeriği şu konuma başarıyla kaydedildi: {0} + + + Yardım içeriği XSD dosyası {0} konumunda bulunamıyor. Belirtilen konumda XSD dosyasının var olduğunu doğrulayın ve ardından komutu yeniden deneyin. + + + Modül(ler) için Yardım güncelleştirilemedi : +'{0}' +{1} + + + Yardım kaydediliyor + + + Yardım içeriği geçersiz dosyalar içeriyor. Yalnızca .txt ve .xml dosyaları desteklenir. + + + {0} modül(ler)i için Yardım kaydedilemedi : {1} + + + {0} modül(ler)i için Yardım kaydedilemedi; kullanıcı arabirimi dili(leri) {{{1}}} : {2}. +İngilizce-ABD yardım içeriği kullanılabilir ve şu komut kullanılarak kaydedilebilir: Save-Help -UICulture en-US. + + + {0} modül(ler)i için kullanıcı arabirimi dili(leri) {{{1}}} ile Yardım güncellemesi başarısız oldu: {2}. +İngilizce-ABD yardım içeriği kullanılabilir ve şu komut kullanılarak yüklenebilir: Update-Help -UICulture en-US. + + + Geçerli bilgisayar diliniz ({0}); bu dil herhangi bir dille ilişkilendirilmemiştir. Sistem dilinizi değiştirmeyi veya İngilizce-ABD yardım içeriğini şu komutla yüklemeyi düşünün: Update-Help -UICulture en-US. + + + yanlış + + + -Recurse parametresi yalnızca bir kaynak sağlayıcı yolu belirtildiğinde kullanılabilir. + + + Belirtilen yol {0} bir FileSystem sağlayıcısı içermez. Yolun FileSystem sağlayıcısı içerdiğini doğrulayın ve ardından komutu yeniden deneyin. + + + Yardım için {0} aranıyor ... + + + Aşağıdaki desenle eşleşen bir UI kültürü bulunamadı: {0}. Deseni doğrulayın ve ardından komutu yeniden deneyin. + + + {0} modülü için yardım kaydedilmedi çünkü Save-Help komutu bu bilgisayarda son 24 saat içinde çalıştırıldı. +Yardımı yeniden kaydetmek için komutunuza Force parametresini ekleyin.Yardımı yeniden güncelleştirmek için komutunuza Force parametresini ekleyin. + + + Modül {0} için yardım güncelleştirilmedi; çünkü bu bilgisayarda son 24 saat içinde Update-Help komutu çalıştırıldı. +Yardımı yeniden güncelleştirmek için komutunuza Force parametresini ekleyin. + + + En güncel Yardım dosyaları zaten yüklü. + + + {0}: {1}. Kültür {2} Sürüm {3} + + + {0} güncelleştirildi + + + Modül bildirimindeki HelpInfoUri anahtarının değeri, yardım dosyalarının depolandığı bir web sitesindeki kapsayıcıya veya kök URL’ye çözülmelidir. HelpInfoUri '{0}' bir kapsayıcıya çözümlenmiyor. + + + Yardım içeriği {0} ad alanında olmalıdır. + + + Get-Help bu bilgisayarda bu cmdlet için Yardım dosyalarını bulamıyor. Yalnızca kısmi yardım gösteriliyor. + -- Bu cmdlet'i içeren modül için Yardım dosyalarını indirmek ve yüklemek için Update-Help kullanın. + + + En güncel Yardım dosyaları zaten indirildi. + + + {0} kaydedildi + + + HelpInfoURI {0} HTTP ile başlamaz. + + + Yardım içeriğinin kök düzey öğesi "helpItems" olmalıdır. + + + Modül için Yardım kaydediliyor {0} + + + Modül {0} için Yardım güncelleştiriliyor + + + URI çözümleniyor: "{0}” + + + Yardım URI'si: {0} + + + {0}, Geçerli Sürüm: {1}, Kullanılabilir Sürüm: {2}, UICulture: {3} + + + ÖZELLİKLER + + + YÖNTEMLER + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/HelpErrors.tr.resx b/src/System.Management.Automation/resources/tr/HelpErrors.tr.resx new file mode 100644 index 00000000000..ab1799bf1e4 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/HelpErrors.tr.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help bu oturumda bir Yardım dosyasında {0} öğesini bulamadı. Güncelleştirilmiş yardım konularını indirmek için "Update-Help" yazın. Çevrimiçi yardım almak için, yardım konusunu https://go.microsoft.com/fwlink/?LinkID=107116 adresindeki TechNet kitaplığında arayın. + + + Yardım kategorisi işlenemiyor; çünkü "{0}" geçerli bir Yardım kategorisi değil. + + + Yardım dosyası "{0}" yüklenemiyor. Ayrıntılar: {1}. + + + Geçerli kullanıcı dosya için erişim haklarına sahip olmadığından, "{0}" Yardım dosyasına erişilemiyor. Ayrıntılar: {1}. + + + Yardım dosyası "{0}" geçerli bir xml belgesi değil. Ayrıntılar: {1}. + + + {0} için Yardım içeriği dosya {1} yüklenirken bir hata oluştu. Ayrıntılar: {2}. Güncelleştirilmiş Yardım konularını indirmek için Update-Help cmdlet'ini çalıştırın. Çevrimiçi yardım almak için, yardım konusunu https://go.microsoft.com/fwlink/?LinkID=107116 adresindeki TechNet kitaplığında arayın. + + + “{0}" sağlayıcısı yüklenemiyor. Ayrıntılar: {1}. + + + Yardım dosyası yüklenemiyor. Aşağıdaki {1} hata, Yardım dosyası "{0}" yüklenirken oluştu. + + + “{0}" düğümü, alt düğüm olarak "{1}" öğesini içeremez. Düğüm Yolu: {2}. + + + "{0}" düğümü, "{1}" türünde en fazla {2} alt düğüme sahip olabilir. Düğüm Yolu: {3}. + + + Kayıt defteri anahtarı bulunamıyor: "{0}{1}"; Yardım dosyalarını yüklemek için "{2}" kullanılıyor. + + + Ölçütler {0} ile eşleşen parametre bulunamadı. + + + {0}, istenen Yardım kategorisi tarafından desteklenmiyor. + + + Bu Yardım konusunun çevrimiçi sürümü, Yardım konusunun İnternet Adresi (URI) komut kodunda veya komutun Yardım dosyasında belirtilmediği için görüntülenemiyor. + + + Belirtilen URI {0} geçersiz. + + + Çevrimiçi Yardım'ı görüntülemek için bir tarayıcı başlatılamadı. URI {0} öğesini açmak için ilişkilendirilmiş bir program veya tarayıcı yok. + + + Uri "{0}" içinde belirtilen protokol desteklenmiyor. Yalnızca "{1}" ve "{2}" protokolleri desteklenir. + + + Birden çok Yardım konusu bulundu. -{0} seçeneğiyle yalnızca bir Yardım konusu kullanın. + + + Uzak çalışma alanından Yardım Alın alınamıyor; çünkü çalışma alanı açılmamış. Çalışma alanını, örtük uzak komut çalıştırarak açın ve ardından Yardım Alın komutunu yeniden çalıştırmayı deneyin. + + + Erişim reddedildi. Komut, PowerShell çekirdek modülleri için veya $pshome\Modules dizinindeki herhangi bir modül için Yardım konularını güncelleştiremedi. +Bu Yardım konularını güncelleştirmek için, PowerShell'i "Yönetici olarak çalıştır" komutunu kullanarak başlatın ve Update-Help komutunu yeniden çalıştırmayı deneyin. + + + {0} öğesini kullanmak için, uygulamanızın proje sdk'sı olarak 'Microsoft.NET.Sdk.WindowsDesktop' kullandığından ve ilgili 'Microsoft.PowerShell.GraphicalHost' derlemesinin kullanılabilir olduğundan emin olun. ({1}) + + + {0} uzak oturumda çalışmaz. + + + ForwardHelpTargetName, işlevin kendisine başvuramaz. + + + Kısıtlanmış bir oturumdayken ağ konumundan yardım alınamaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/HistoryStrings.tr.resx b/src/System.Management.Automation/resources/tr/HistoryStrings.tr.resx new file mode 100644 index 00000000000..e2fe3203ecb --- /dev/null +++ b/src/System.Management.Automation/resources/tr/HistoryStrings.tr.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} tanımlayıcısı, Geçmiş tanımlayıcısı için geçerli bir değer değil. Pozitif bir sayı belirtin ve sonra yeniden deneyin. + + + {0} kimliği geçmişinin yeri belirlenemiyor. + + + Sayı, birden çok kimlikle birleştirilemez. + + + {0} komut satırının geçmişi bulunamıyor. + + + En son geçmişin yeri belirlenemiyor. + + + Invoke-History cmdlet'i bir döngü içinde tekrar tekrar çağrılıyor. + + + Birden çok geçmiş komutu işlenemiyor. Invoke-History kullanarak tek bir komut çalıştırabilirsiniz. + + + Girdi nesnesinin biçimi geçerli olmadığı için geçmiş eklenemiyor. + + + {0} tanımlayıcısı geçerli değil. Pozitif bir sayı belirtin ve sonra yeniden deneyin. + + + Bu komut, oturum geçmişindeki tüm girdileri temizler. + + + Sayı, birden çok CommandLine parametresiyle birleştirilemez. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/HostInterfaceExceptionsStrings.tr.resx b/src/System.Management.Automation/resources/tr/HostInterfaceExceptionsStrings.tr.resx new file mode 100644 index 00000000000..75f24f9f5ab --- /dev/null +++ b/src/System.Management.Automation/resources/tr/HostInterfaceExceptionsStrings.tr.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 + + + "{0}" türünde bir hata oluştu. + + + Kullanıcıdan giriş isteyen bir komut başarısız oldu çünkü ana bilgisayar programı ya da komut türü kullanıcı etkileşimini desteklemiyor. Windows PowerShell Konsolu gibi kullanıcı etkileşimini destekleyen bir ana bilgisayar programı deneyin ve kullanıcı etkileşimini desteklemeyen komut türlerinden istemle ilgili komutları kaldırın. + + + Kullanıcıdan giriş isteyen bir komut başarısız oldu çünkü ana bilgisayar programı ya da komut türü kullanıcı etkileşimini desteklemiyor. Ana bilgisayar, şu mesajla onay istemeye çalışıyordu: {0} + + + Havuz kapatıldığı veya başarısız olduğu için yöntem çağrılamıyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/InternalCommandStrings.tr.resx b/src/System.Management.Automation/resources/tr/InternalCommandStrings.tr.resx new file mode 100644 index 00000000000..d737425fbca --- /dev/null +++ b/src/System.Management.Automation/resources/tr/InternalCommandStrings.tr.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + "{0}" giriş adı belirsiz. Birden çok eşleşen yönteme çözümlenebilir. Olası eşleşmeler şunlardır:{1}. + + + "{0}" giriş adı belirsiz. Birden çok eşleşen üyeye çözümlenebilir. Olası eşleşmeler şunlardır:{1}. + + + '{0}' anahtarı için değeri alın + + + '{0}' yöntemini bağımsız değişkenlerle çağırın: {1} + + + '{0}' yöntemini çağır + + + '{0}' özelliği için değeri alın + + + InputObject: {0} + + + 'null' giriş nesnesi üzerinde çalışamaz. + + + "{0}" giriş adı bir yönteme çözümlenemiyor. + + + Kısıtlı dil modunda yöntem çağrılamaz. + + + -WhatIf ve -Confirm parametreleri betik blokları için desteklenmez. + + + Kısıtlı Dil modunda '{0}' işlemine izin verilmiyor. + + + Belirtilen iki değeri karşılaştırmak için bir işleç gerekiyor. Komuta geçerli bir işleç ekleyin ve sonra komutu yeniden deneyin. Örneğin, Get-Process | Where-Object -Property Name -eq Idle + + + "{0}" giriş adı bir özelliğe çözümlenemiyor. + + + "{0}" giriş adı bir üyeye çözümlenemiyor. + + + Belirtilen işleç hem -Property hem de -Value parametrelerini gerektirir. Her iki parametre için de değer sağlayın ve sonra komutu yeniden deneyin. + + + Bu yöntem geçerli iş parçacığında çalıştırılamaz. Yalnızca cmdlet iş parçacığında çağrılabilir. + + + Değişken kullanan ForEach-Object -Parallel bir betik bloğu olamaz. Geçirilen betik bloğu değişkenleri ForEach-Object -Parallel ile desteklenmez ve tanımsız bir davranışla sonuçlanabilir. + + + ForEach-Object -Parallel kanallı giriş nesnesi bir betik bloğu olamaz. Geçirilen betik bloğu değişkenleri ForEach-Object -Parallel ile desteklenmez ve tanımsız bir davranışla sonuçlanabilir. + + + 'TimeoutSeconds' parametresi 'AsJob' parametresiyle birlikte kullanılamaz. + + + Aşağıdaki ortak parametreler şu anda Paralel parametre kümesinde desteklenmiyor: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + ForEach-Object -Parallel girişi işlenirken beklenmeyen bir hata oluştu. Bu, kanallı girişin bir bölümünün işlenmemiş olabileceği anlamına geliyor. Hata: {0}. + + + ForEach-Object Cmdlet'i + + + Kısıtlı Dil modunda çalıştırıldığında, '{0}' türünde yöntem çağrısına izin verilmez. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/InternalHostStrings.tr.resx b/src/System.Management.Automation/resources/tr/InternalHostStrings.tr.resx new file mode 100644 index 00000000000..8c140acf4de --- /dev/null +++ b/src/System.Management.Automation/resources/tr/InternalHostStrings.tr.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 + + + EnterNestedPrompt, ExitNestedPrompt kadar çok kez çağrılmadı. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/InternalHostUserInterfaceStrings.tr.resx b/src/System.Management.Automation/resources/tr/InternalHostUserInterfaceStrings.tr.resx new file mode 100644 index 00000000000..caeccd2ab80 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/InternalHostUserInterfaceStrings.tr.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug, DebugPreference değişkeninin değeri 'Stop' olduğu için Durduruldu. + + + {0} desteklenen bir ActionPreference değeri değil. + + + “{0}" parametresi en az bir değer içermelidir. + + + &Evet + + + Devam. + + + &Tümüne Evet + + + Bu oturumda devam et ve devam edip etmeyeceğin yeniden sorulmasın. + + + &Hayır + + + İşlemi bir hatayla sonlandırın. + + + Tümüne &Hayır + + + İşlemi bir hatayla sonlandırın. Bu oturum için işlemi sürdürme isteğinde bulunmayın. + + + &Askıya Al + + + Geçerli işlemi duraklatın ve komut istemine girin. Duraklatılan işlemi sürdürmek için “exit” yazın. + + + Bu işleme devam edilsin mi? + + + (varsayılan "{0}"dur) + + + (varsayılan seçenekler {0}) + + + Seçim[{0}]: + + + “{0}" en az bir öğe içermelidir. + + + “{0}" "{1}" içinde geçerli bir dizin olmalıdır. "{2}" geçerli bir dizin değil. + + + Soru işareti ("?") sık erişim tuşu olarak kullanılamadığı için bu sık erişim tuşu işlenemiyor. + + + AYRINTILI: {0} + + + UYARI: {0} + + + HATA AYIKLA: {0} + + + Barındırma şu anda döküm yapmıyor. + + + Komut başlatma zamanı: {0} + + + ********************** +Windows PowerShell döküm başlangıcı +Başlangıç saati: {0:yyyyMMddHHmmss} +Kullanıcı adı: {1} +RunAs Kullanıcısı: {2} +Yapılandırma adı: {3} +Makine: {4} ({5}) +Konak uygulama: {6} +İşlem Kimliği: {7} +{8} +********************** + + + ********************** +Windows PowerShell döküm başlangıcı +Başlangıç saati: {0:yyyyMMddHHmmss} +********************** + + + ********************** +Windows PowerShell döküm sonu +Bitiş saati: {0:yyyyMMddHHmmss} +********************** + + + Dosya yolu {0} bir dizine çözümleniyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/Logging.tr.resx b/src/System.Management.Automation/resources/tr/Logging.tr.resx new file mode 100644 index 00000000000..1eaa075d942 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/Logging.tr.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + BİLİNMİYOR + + + Yapılandırma dosyasında bildirilen altyapı deneysel '{0}' özelliği geçerli PowerShell'de kayıtlı değil. + + + Yapılandırma dosyasında bildirilen deneysel '{0}' özelliği geçersizdir. +Deneysel özelliğin adı şu kurala uymalıdır: + Altyapı Özellik Adı: 'PS[FeatureName]' + Modül Özellik Adı: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/Metadata.tr.resx b/src/System.Management.Automation/resources/tr/Metadata.tr.resx new file mode 100644 index 00000000000..2b9f481c3fd --- /dev/null +++ b/src/System.Management.Automation/resources/tr/Metadata.tr.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + “{0}" için "{1}" özellikleri başlatılamıyor + + + "{0}" türü, parametrenin maksimum ve minimum sınırlarıyla aynı türde ({1}) olmadığından bağımsız değişken doğrulanamıyor. Bağımsız değişkenin {1} türünde olduğundan emin olun ve sonra komutu tekrar deneyin. + + + ‘{0}' bağımsız değişkeni, değeri sıfırdan büyük olmadığı için doğrulanamıyor. + + + “{0}" bağımsız değişkeni doğrulanamıyor çünkü değeri sıfıra eşit veya sıfırdan büyük değil. + + + “{0}" bağımsız değişkeni, değeri sıfırdan küçük olmadığı için doğrulanamıyor. + + + “{0}" bağımsız değişkeni doğrulanamıyor çünkü değeri sıfıra eşit veya sıfırdan küçük değil. + + + Belirtilen en küçük aralık ({0}), belirtilen en büyük aralık ({1}) ile aynı türde olmadığı için kabul edilemiyor. Parametre için ValidateRange özniteliğini güncelleştirin. + + + MaxRange ve MinRange parametre türleri kabul edilemez. Her iki parametre de IComparable arabirimini uygulayan nesneler olmalıdır. + + + Belirtilen en büyük aralık, belirtilen en küçük aralıktan küçük olduğu için kabul edilemiyor. Parametre için ValidateRange özniteliğini güncelleştirin. + + + {0} bağımsız değişkeni, {1} için izin verilen en büyük aralıktan büyüktür. {1} değerinden küçük veya ona eşit bir bağımsız değişken sağlayın ve ardından komutu yeniden deneyin. + + + {0} bağımsız değişkeni, {1} için izin verilen en küçük aralıktan küçüktür. {1} değerinden büyük veya ona eşit bir bağımsız değişken sağlayın ve ardından komutu yeniden deneyin. + + + “{0}" bağımsız değişkeni "{1}" desenine uymuyor. “{1}" ile eşleşen bir bağımsız değişken sağlayın ve komutu yeniden deneyin. + + + ValidateCount özniteliği, dizi olmayan bir parametreye uygulanamaz. Özniteliği parametreden kaldırın veya parametreyi dizi parametresi yapın. + + + Parametre tam olarak {0} değer gerektirir - {1} değer sağlandı. + + + Parametre en az {0} değer ve en fazla {1} değer gerektirir - {2} değer sağlandı. + + + Bir parametre için belirtilen en büyük bağımsız değişken sayısı, belirtilen en küçük bağımsız değişken sayısından azdır. Parametre için ValidateCount özniteliğini güncelleştirin. + + + Belirtilen bağımsız değişken karakter süresi üst sınırı, belirtilen bağımsız değişken karakter süresi alt sınırından kısadır. Parametre için ValidateLength özniteliğini güncelleştirin. + + + ValidateLength özniteliği, dize veya dize[] parametresi olmayan bir parametreye uygulanamaz. Parametreyi dize veya dize[] parametresi yapın. + + + Bağımsız değişkenin karakter süresi ({1}) çok kısa. Uzunluğu "{0}" değerinden büyük veya buna eşit olan bir bağımsız değişken belirtin ve ardından komutu yeniden deneyin. + + + Bağımsız değişkenin karakter süresi ({1}) çok uzundur. Uzunluğu "{0}" değerinden kısa veya buna eşit olan bir bağımsız değişken belirtin ve sonra komutu tekrar deneyin. + + + “{0}" bağımsız değişkeni, ValidateSet özniteliği tarafından belirtilen "{1}" kümesine ait değil. Kümede olan bir bağımsız değişken sağlayın ve sonra komutu yeniden deneyin. + + + Geçerli değerler oluşturucu null bir değer geri gönderir. + + + “{0}" özelliğinde "{1}" için başarısız oldu {2} + + + Komut alınamıyor veya çalıştırılamıyor. Bu komut için en fazla parametre kümesi sayısı aşıldı. + + + Bağımsız değişkeni işleyemiyor çünkü bağımsız değişken değeri bir dize değil. ArgumentTransformationAttribute belirtilmiş olan parametre bağımsız değişkenlerinin değerleri dize olmalıdır. + + + {1} değeri {0} değişkeni için geçerli bir değer olmadığından değişken doğrulanamıyor. + + + {1} değerine sahip {0} değişkeni artık geçerli olmayacağından öznitelik eklenemiyor. + + + Bağımsız değişken null. Bağımsız değişken için geçerli bir değer sağlayın ve sonra komutu tekrar deneyin. + + + Bağımsız değişken null bir değer içeriyor veya bağımsız değişken koleksiyonundaki bir öğe null bir değer içeriyor. Null değer içermeyen bir koleksiyon sağlayın ve ardından komutu yeniden deneyin. + + + Bağımsız değişken null veya boş. Null veya boş olmayan bir bağımsız değişken sağlayın ve ardından komutu yeniden deneyin. + + + Bağımsız değişken null, boş ya da bağımsız değişken koleksiyonundaki bir öğe null değer içeriyor. Null değer içermeyen bir koleksiyon sağlayın ve sonra komutu tekrar deneyin. + + + Bağımsız değişken null, boş veya yalnızca boşluk karakterlerinden oluşuyor. Boşluk olmayan karakterler içeren bir bağımsız değişken sağlayın ve sonra komutu tekrar deneyin. + + + Bağımsız değişken koleksiyonundaki bir öğe null, boş ya da yalnızca boşluk karakterlerinden oluşuyor. Null değer içermeyen bir koleksiyon sağlayın ve sonra komutu tekrar deneyin. + + + ‘{0}' adlı bir parametre komut için birden çok kez tanımlandı. + + + Parametre diğer adı '{0}' adlı bir diğer ad komut için zaten birden çok kez tanımlandığından belirtilemez. + + + ‘{0}' parametresi, '{1}' parametresi için aynı adlı parametre diğer adıyla çakıştığı için belirtilemez. + + + "{0}" değerine sahip bağımsız değişken için "{1}" doğrulama betiği True sonucu döndürmedi. Doğrulama betiğinin neden başarısız olduğunu belirleyin ve ardından komutu yeniden deneyin. + + + “{0}" bağımsız değişkeni geçerli bir Windows PowerShell sürümü içermiyor. Geçerli bir sürüm numarası sağlayın ve sonra komutu yeniden deneyin. + + + '{0}' geçerli bir değişken adı olmadığından bağımsız değişken doğrulanamıyor. + + + İş dönüşüm türü, IAstToScriptBlockConverter'dan türetilmelidir. + + + Yol bağımsız değişkeni geçersiz. Dize türünde bir yol bağımsız değişkeni sağlayın. + + + Yol bağımsız değişkeni sürücü {0}, onaylanmış sürücüler kümesine ait değil: {1}. Onaylanmış bir sürücüye sahip bir yol bağımsız değişkeni sağlayın. + + + Yol bağımsız değişkeni geçersiz karakterler içeriyor. + + + Yol bağımsız değişkeninin kök sürücüsü yok. Kök sürücüsü olan tam bir yol bağımsız değişkeni sağlayın. + + + ‘{0}' parametresi için bağımsız değişken değeri null ya da boş bir dize olamaz. + + + Sabit Listesi üyesi '{0}', '{1}' parametresi için geçerli bir değer değil. Aşağıdaki üyelerden birini belirtin ve yeniden deneyin: {2}. + + + Giriş işlenemiyor. “{0}" bağımsız değişkeni güvenilir değil. + + + ValidateTrustedData Öznitelik Denetimi Hatası + + + “{0}" parametre bağımsız değişkeni güvenilir değil ve Kısıtlanmış Dil modunda ValidateTrustedData parametre özniteliği denetiminde başarısız olacak. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/MiniShellErrors.tr.resx b/src/System.Management.Automation/resources/tr/MiniShellErrors.tr.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/MiniShellErrors.tr.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/Modules.tr.resx b/src/System.Management.Automation/resources/tr/Modules.tr.resx new file mode 100644 index 00000000000..e3ec0cb6379 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/Modules.tr.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Herhangi bir modül dizininde geçerli bir modül dosyası bulunamadığından belirtilen '{0}' modülü yüklenmedi. + + + Herhangi bir modül dizininde geçerli bir modül dosyası bulunamadığından '{1}' sürümü ile belirtilen '{0}' modülü yüklenmedi. + + + Belirtilen MaximumVersion '{0}' yanlıştı. '*' kullanıyorsanız, MaximumVersion yalnızca bir '*' destekler ve bu karakter her zaman MaximumVersion'ın sonunda yer almalıdır. + + + Herhangi bir modül dizininde geçerli bir modül dosyası bulunamadığından MaximumVersion '{1}' ile belirtilen '{0}' modülü yüklenmedi. + + + Herhangi bir modül dizininde geçerli bir modül dosyası bulunamadığından MinimumVersion '{1}' ve MaximumVersion '{2}' ile belirtilen '{0}' modülü yüklenmedi. + + + MinimumVersion '{0}', MaximumVersion '{1}' değerinden büyük olmamalıdır. + + + Bu ada sahip bir derleme bulunamadığından '{0}' derlemesi yüklenmedi. Derleme adını doğrulayın ve yeniden deneyin. + + + '{2}' modül bildiriminin '{1}' alanında listelenen, '{0}' öğesini işleyecek modül, herhangi bir modül dizininde geçerli bir modül bulunamadığından işlenmedi. + + + -AsCustomObject parametresi yalnızca betik modülleriyle kullanılabildiğinden '{0}' modülü için özel nesne döndürülmedi. + + + '{0}' modül bildirimi, geçerli bir PowerShell modül bildirim dosyası olmadığından işlenemedi. İzin verilmeyen öğeleri kaldırın: {1} + + + '{0}' modül bildirim dosyasının işlenmesi geçerli bir bildirim nesnesi ile sonuçlanmadı. Dosyayı geçerli bir PowerShell modül bildirimi içerecek şekilde güncelleştirin. Geçerli bir bildirim, New-ModuleManifest cmdlet'i kullanılarak oluşturulabilir. + + + Bildirimi bir veya daha fazla geçersiz üye içerdiğinden '{0}' modülü içeri aktarılamıyor. Geçerli bildirim üyeleri: ({1}). Geçerli olmayan üyeleri ({2}) kaldırın ve ardından modülü yeniden içeri aktarmayı deneyin. + + + Bir modül açıklayan hashtable bir veya daha fazla geçersiz üye içeriyor. Geçerli üyeler: ({0}). Geçerli olmayan üyeleri ({1}) kaldırın, ardından yeniden deneyin. + + + Modül iç içe yerleştirme sınırı aşıldığından '{0}' modülü yüklenemiyor. Modüller yalnızca {1} düzey iç içe yerleştirilebilir. İç içe yerleştirme sınırının aşılmasını önlemek için modülleri yüklediğiniz sırayı değerlendirip değiştirin ve sonra betiğinizi yeniden çalıştırmayı deneyin. + + + 'ModuleVersion' üyesi modül bildiriminde yok. Bu üye mevcut olmalı ve üyeye 'n.n.n.n' biçiminde bir sürüm numarası atanmalıdır. Eksik üyeyi '{0}' dosyasına ekleyin. + + + '{2}' modül bildirimindeki '{0}' üyesi geçerli değil: {1} + + + '{1}' modülünün '{0}' sürümü, gereken en düşük '{2}' sürümünü karşılamıyor. Sürüm numarasının desteklendiğini doğrulayın ve modülü yeniden yüklemeyi deneyin. + + + Bu bilgisayardaki PowerShell sürümü: '{0}'. '{1}' modülünü çalıştırmak için en düşük PowerShell sürümü '{2}' gerekir. Gerekli en düşük PowerShell sürümünün yüklü olduğunu doğrulayın ve ardından yeniden deneyin. + + + 'ModuleToProcess' üyesi ikili bir modülse 'NestedModules' modül bildirimi üyesi kullanılamaz. '{0}' konumundaki modül bildirimi dosyasını düzenleyin ve ardından yeniden deneyin. + + + Modül bildirimindeki '{0}' üyesi geçerli değil: {1}. Lütfen '{2}' dosyasında bu alan için geçerli bir değer belirtildiğini doğrulayın. + + + '{0}' modül bildirim yolu geçerli değil. Path bağımsız değişkeninin değeri, uzantısı '.psd1' olan tek bir dosyaya çözümlenmelidir. Path bağımsız değişkeninin değerini geçerli bir psd1 dosyasına işaret edecek şekilde değiştirin ve ardından yeniden deneyin. + + + '{0}' modül bildirimindeki ModuleVersion anahtarı, '{2}' konumundaki sürüm klasörü adıyla eşleşmeyen '{1}' modül sürümünü belirtiyor. ModuleVersion anahtarının değerini sürüm klasörü adıyla eşleşecek şekilde değiştirin. + + + '{1}' modül bildiriminde belirtilen '{0}' NestedModule girdisi geçersiz. Bu girdiyi geçerli değerlerle güncelleştirdikten sonra yeniden deneyin. + + + '{1}' modül bildiriminde belirtilen '{0}' RequiredAssemblies girdisi geçersiz. Bu girdiyi geçerli değerlerle güncelleştirdikten sonra yeniden deneyin. + + + '{1}' modül bildiriminde belirtilen '{0}' FileList girdisi geçersiz. Bu girdiyi geçerli değerlerle güncelleştirdikten sonra yeniden deneyin. + + + '{1}' modül bildiriminde belirtilen '{0}' RequiredModules girdisi geçersiz. Bu girdiyi geçerli değerlerle güncelleştirdikten sonra yeniden deneyin. + + + '{1}' modül bildiriminde belirtilen '{0}' ModuleList girdisi geçersiz. Bu girdiyi geçerli değerlerle güncelleştirdikten sonra yeniden deneyin. + + + '{0}' modül bildirimi, yalnızca PowerShell '5.1' veya üzeri bir sürümünde desteklenen CompatiblePSEditions anahtarıyla belirtilir. PowerShellVersion anahtarının değerini '5.1' veya üzeri olacak şekilde güncelleştirin ve yeniden deneyin. + + + CompatiblePSEditions için belirtilen '{0}' değeri yinelenen PowerShell Edition adları içeriyor. Yinelenen PowerShell Edition adlarını kaldırdıktan sonra yeniden deneyin. + + + ModuleVersion anahtarında belirtilen sürüm, sürüm klasörü adıyla aynı. + + + Geçerli bir modül bildirim dosyasına sahip olmadığından {1} Modülü altındaki {0} Sürüm klasörü atlanıyor. + + + 'ModuleName' üyesi, bu modülü açıklayan karma tabloda yoktur. + + + 'ModuleVersion', 'MaximumVersion' ve 'RequiredVersion' üyeleri bu modülü açıklayan karma tabloda yok. Bu üç üyeden biri mevcut olmalı ve ona 'n.n.n.n' biçiminde bir sürüm numarası atanmalıdır. + + + Gerekli '{1}' modülü yüklenmedi. Modülü yükleyin veya '{0}' dosyasındaki 'RequiredModules' içinden modülü kaldırın. + + + GUID'si '{2}' olan gerekli '{1}' modülü yüklenmedi. Modülü yükleyin veya '{0}' dosyasındaki 'RequiredModules' içinden modülü kaldırın. + + + '{2}' sürümüne sahip gerekli '{1}' modülü yüklenmedi. Modülü yükleyin veya '{0}' dosyasındaki 'RequiredModules' içinden modülü kaldırın. + + + MaximumVersion '{2}' değerine sahip gerekli '{1}' modülü yüklenmedi. Modülü yükleyin veya '{0}' dosyasındaki 'RequiredModules' içinden modülü kaldırın. + + + MinimumVersion '{2}' ve MaximumVersion '{3}' değerlerine sahip gerekli '{1}' modülü yüklenmedi. Modülü yükleyin veya '{0}' dosyasındaki 'RequiredModules' içinden modülü kaldırın. + + + '{0}' modülü, ModuleVersion '{1}' ile bulunamadı. + + + '{0}' modülü, RequiredVersion '{1}' ile bulunamadı. + + + '{0}' modülü, MaximumVersion '{1}' ile bulunamadı. + + + '{0}' modülü, ModuleVersion '{1}' ve MaximumVersion '{2}' ile bulunamıyor. + + + '{0}' modülü bulunamıyor. + + + Hiçbir modül kaldırılmadı. Kaldırılacak modüllerin belirtiminin doğru olduğunu ve bu modüllerin çalışma alanında bulunduğunu denetleyin. + + + '{1}' modülünden içeri aktarılan '{0}' üyesi şu nedenle kaldırılamıyor: {2} + + + '{0}' modülü salt okunur olduğundan kaldırılamıyor. Salt okunur modülleri kaldırmak için komutunuza Force parametresini ekleyin. + + + '{0}' modülü 'constant' olarak işaretlendiğinden kaldırılamıyor. Bir modül 'constant' olarak işaretlendiyse kaldırılamaz. + + + '{0}' modülü '{1}' için gerekli olduğundan kaldırılamıyor. Modülü kaldırmak için komutunuza Force parametresini ekleyin. + + + Export-ModuleMember cmdlet'i yalnızca bir modülün içinden çağrılabilir. + + + '{0}' uzantısı geçerli bir modül uzantısı değil. Desteklenen modül uzantıları şunlardır: '.dll', '.ps1', '.psm1', '.psd1' ve '.cdxml'. Uzantıyı düzeltin ve ardından '{1}' dosyasını yeniden eklemeyi deneyin. + + + Bu işlem ikili modülde gerçekleştirilemez. Yalnızca bir betik modülünde gerçekleştirilebilir. + + + '.ps1' uzantısına sahip olmadığından '{0}' dosyasına izin verilmiyor. + + + Bilinmiyor + + + (c) {0}. Tüm hakları saklıdır. + + + İçeri aktarılan "{0}" işlevi kaldırılıyor. + + + İçeri aktarılan "{0}" diğer adı kaldırılıyor. + + + İçeri aktarılan "{0}" değişkeni kaldırılıyor. + + + Modül, '{0}' yolundan yükleniyor. + + + '{0}', '{1}' yolundan yükleniyor. + + + '{0}' betik dosyası nokta kaynak olarak kullanılıyor. + + + '{0}' işlevi içeri aktarılıyor. + + + '{0}' cmdlet'i içeri aktarılıyor. + + + '{0}' diğer adı içeri aktarılıyor. + + + '{0}' değişkeni içeri aktarılıyor. + + + '{0}' cmdlet'i dışarı aktarılıyor. + + + '{0}' işlevi dışarı aktarılıyor. + + + '{0}' diğer adı dışarı aktarılıyor. + + + '{0}' değişkeni dışarı aktarılıyor. + + + '{0}' modülünden içeri aktarılan bazı komutların adları, onaylanmamış fiiller içeriyor ve bu da komutların bulunmasını zorlaştırabilir. Onaylanmamış fiil içeren komutları bulmak için Import-Module komutunu Verbose parametresiyle yeniden çalıştırın. Onaylanan fiillerin listesi için Get-Verb yazın. + + + '{1}' modülündeki '{0}' komutu içeri aktarıldı, ancak adı onaylanmış bir fiil içermediğinden bulunması zor olabilir. Onaylanan fiillerin listesi için Get-Verb yazın. + + + '{2}' modülündeki '{0}' komutu içeri aktarıldı, ancak adı onaylanmış bir fiil içermediğinden bulunması zor olabilir. Önerilen alternatif fiiller: "{1}". + + + İçeri aktarılan bazı komut adları, şu kısıtlanmış karakterlerden bir veya daha fazlasını içeriyor: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + '{1}' modülündeki '{0}' komut adı, şu kısıtlanmış karakterlerden bir veya daha fazlasını içeriyor: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + "{0}" modülü bildirim dosyası oluşturuluyor. + + + {0} (Yol: '{1}') + + + Geçerli işlemci mimarisi: {0}. '{1}' modülü şu mimariyi gerektiriyor: {2}. + + + Geçerli PowerShell konağının adı: '{0}'. '{1}' modülü için gerekli PowerShell konağı: '{2}'. + + + Geçerli PowerShell konağı: '{0}' (sürüm {1}). '{2}' modülünü çalıştırmak için en düşük PowerShell konak sürümü '{3}' gerekir. + + + '{0}' modülü için modül bildirimi + + + Oluşturan: {0} + + + {0} tarihinde oluşturuldu + + + Bu bildirimle ilişkilendirilmiş betik modülü veya ikili modül dosyası. + + + RootModule/ModuleToProcess içinde belirtilen modülün iç içe modülleri olarak içeri aktarılacak modüller + + + Bu modülü benzersiz olarak tanımlamak için kullanılan kimlik + + + Bu modülün yazarı + + + Bu modülün şirketi veya satıcısı + + + Bu modül için telif hakkı bildirimi + + + Bu modülün sürüm numarası. + + + Bu modülün sağladığı işlevselliğin açıklaması + + + Bu modülün gerektirdiği PowerShell altyapısının en düşük sürümü + + + Bu modülün gerektirdiği en düşük ortak dil çalışma zamanı (CLR) sürümü. {0} + + + Bu modül içeri aktarılmadan önce genel ortama aktarılması gereken modüller + + + Bu modül içeri aktarılmadan önce çağıranın ortamında çalıştırılan betik dosyaları (.ps1). + + + Bu modül içeri aktarılırken yüklenecek tür dosyaları (.ps1xml) + + + Bu modül içeri aktarılırken yüklenecek biçim dosyaları (.ps1xml) + + + Bu modül içeri aktarılmadan önce yüklenmesi gereken derlemeler + + + Bu modülle paketlenmiş tüm dosyaların listesi + + + RootModule/ModuleToProcess içinde belirtilen modüle geçirilecek özel veriler. Bu, PowerShell tarafından kullanılan ek modül meta verilerine sahip bir PSData karma tablosu da içerebilir. + + + Bu modüle uygulanan etiketler. Bunlar, çevrimiçi galerilerde modül bulmaya yardımcı olur. + + + Bu proje için ana web sitesinin URL'si. + + + Bu modül lisansının URL'si. + + + Bu modülü temsil eden simgenin URL'si. + + + Bu modülün sürüm notları + + + Bu modülün ön sürüm dizesi + + + Modülün yükleme/güncelleştirme/kaydetme işlemleri için kullanıcıdan açık onay gerektirip gerektirmediğini gösteren bayrak + + + Bu modülün dış bağımlı modülleri + + + {0} hashtable'ın sonu + + + PrivateData parametre değeri, modül bildirimini Tags, ProjectUri, LicenseUri, IconUri veya ReleaseNotes parametre değerleriyle oluşturmak için bir karma tablo olmalıdır. Tags, ProjectUri, LicenseUri, IconUri veya ReleaseNotes parametre değerlerini kaldırın ya da PrivateData içeriklerini bir karma tablo içinde sarmalayın. + + + PrivateData bir karma tablo olarak tanımlanmalıdır, ancak bu modül bildirimi bunu bir nesne olarak tanımlıyor. Lütfen PrivateData içeriklerini bir karma tablo içinde sarmalamayı deneyin. Bu, daha sonra modül bildirimine Tags, ProjectUri, LicenseUri, IconUri ve ReleaseNotes özelliklerini eklemenizi sağlar. + + + Belirtilen '{0}' değeri geçersiz. Geçerli bir değerle yeniden deneyin. + + + Bu modülden dışarı aktarılacak işlevler için en iyi performansı elde etmek amacıyla joker karakterler kullanmayın ve girdiyi silmeyin. Dışarı aktarılacak işlev yoksa boş bir dizi kullanın. + + + Bu modülden dışarı aktarılacak diğer adlar için en iyi performansı elde etmek amacıyla joker karakterler kullanmayın ve girdiyi silmeyin. Dışarı aktarılacak diğer ad yoksa boş bir dizi kullanın. + + + Bu modülden dışarı aktarılacak cmdlet'ler için en iyi performansı elde etmek amacıyla joker karakterler kullanmayın ve girdiyi silmeyin. Dışarı aktarılacak cmdlet yoksa boş bir dizi kullanın. + + + Bu modülden dışarı aktarılacak değişkenler + + + Bu modülden dışarı aktarılacak DSC kaynakları + + + Desteklenen PSEdition'lar + + + Bu modülün gerektirdiği işlemci mimarisi (None, X86, Amd64) + + + Bu modülle paketlenmiş tüm modüllerin listesi + + + Bu modül için gereken en düşük Microsoft .NET Framework sürümü. {0} + + + Bu modül için gerekli PowerShell konağının adı + + + Bu modülün gerektirdiği PowerShell konağının en düşük sürümü + + + Bu modülün HelpInfo URI'si + + + {0} modülü geçerli PowerShell oturumunda PSDrive'ı sağladığından, hiçbir modül kaldırılmadı. Geçerli PSDrive sağlayıcısını değiştirin ve ardından modülleri yeniden kaldırmayı deneyin. + + + Geçerli kapsamda aynı ada sahip bir üye olduğundan '{0}' cmdlet'i içeri aktarılmadı. + + + Geçerli kapsamda aynı ada sahip bir üye olduğundan '{0}' diğer adı içeri aktarılmadı. + + + Geçerli kapsamda aynı ada sahip bir üye olduğundan '{0}' işlevi içeri aktarılmadı. + + + Geçerli kapsamda aynı ada sahip bir üye olduğundan '{0}' değişkeni içeri aktarılmadı. + + + '{0}' modül bildirimindeki 'ModuleToProcess', 'RootModule' veya 'NestedModules' üyelerinde joker karakterlere izin verilmiyor. + + + '{0}' modülü PowerShell için bir çekirdek modüldür. Çekirdek modülleri kaldırmak için komutunuza Force parametresini ekleyin. + + + Modül bildirimi hem 'ModuleToProcess' hem de 'RootModule' üyelerini içeremez. Modül bildirimi dosyasını değiştirerek '{0}' konumundaki bu üyelerden birini kaldırın ve ardından yeniden deneyin. + + + 'ModuleToProcess' modül bildirimi üyesi kullanım dışı bırakıldı. Bunun yerine 'RootModule' üyesini kullanın. + + + Bu modülden dışarı aktarılan komutlar için varsayılan ön ek. Varsayılan ön eki Import-Module -Prefix kullanarak geçersiz kılın. + + + 'Global' ve 'Scope' parametreleri birlikte belirtilemez. Bu parametrelerden birini kaldırın ve ardından komutu yeniden çalıştırmayı deneyin. + + + Gerekli '{0}' modülü yüklenmedi. '{0}' modülü, '{2}' modül bildiriminde döngüsel bağımlılığa işaret eden requiredModule '{1}' içeriyor. + + + Herhangi bir modül dizininde geçerli bir modül dosyası bulunamadığından gerekli '{0}' modülü yüklenmedi. + + + {0} modülündeki bazı komutlar CimSession üzerinden içeri aktarılamıyor. Tüm komutları almak için uzak sunucuda PowerShell uzaktan yönetiminin etkin olduğunu doğrulayın ve ardından Import-Module cmdlet'ine PSSession parametresini eklemeyi deneyin. + + + {0} modülü, {1} uzaktan iletişim oturumu kullanılarak Windows PowerShell'de yüklenir. Lütfen bu modüldeki tüm komut giriş ve çıkışlarının seri durumdan çıkarılmış nesneler olacağını unutmayın. Bu modülü PowerShell'e yüklemek istiyorsanız lütfen 'Import-Module -SkipEditionCheck' söz dizimini kullanın. + + + Windows PowerShell sürümü {0} algılandı. Windows PowerShell uyumluluk özelliğini kullanarak modülleri yüklemek için Windows PowerShell 5.1 gerekir. Bu özelliği etkinleştirmek için https://aka.ms/WMF5Download adresinden Windows Management Framework (WMF) 5.1 yükleyin. + + + '{0}' modülünün, PowerShell yapılandırma dosyasındaki 'WindowsPowerShellCompatibilityModuleDenyList' ayarı tarafından Windows PowerShell uyumluluk özelliği kullanılarak yüklenmesi engellendi. + + + {0} modülü CimSession üzerinden içeri aktarılamıyor. Import-Module cmdlet'inin PSSession parametresini kullanmayı deneyin. + + + {0} işlemci mimarisi değeri desteklenmiyor. İşlemci mimarisi için desteklenen şu numaralandırma değerlerinden birini belirterek New-ModuleManifest komutunu yeniden çalıştırın: None, MSIL, X86, Amd64, Arm + + + Get-Module cmdlet'i uzak bilgisayarda çalıştırıldığında yalnızca kullanılabilir modüller listelenebilir. Komutunuza ListAvailable parametresini ekleyin ve ardından yeniden deneyin. + + + '{0}' ek bileşeni zaten içeri aktarıldığından '{0}' modülü içeri aktarılmadı. + + + '{0}' modül bildirimindeki 'RequiredAssemblies' üyesinde joker karakterlere izin verilmiyor. + + + {1} içindeki {0} anahtarının değeri {2} ve modülde iç içe modüller var. CDXML dosyası kök modül olduğunda, iç içe modüllerdeki komutlar dışarı aktarılamadığından Import-Module komutu başarısız olur. CDXML dosyasını NestedModules anahtarına taşıyın ve komutu yeniden deneyin. + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + Uzak komuttaki hata: {0}: {{0}} + + + '{0}' uzak modülü için ara sunucular oluşturulamadı. {{0}} + + + {0} uzak modülü işlenemedi. {1} + + + Uzak CimSession'dan modül verileri alınamadı. {0} + + + Herhangi bir modül dizininde geçerli bir modül dosyası bulunamadığından GUID'si '{1}' ve sürümü '{2}' olan gerekli '{0}' modülü yüklenmedi. + + + CIM sunucusunda modül bulmaya yönelik bir CIM sağlayıcısı bulunamadı. {0} + {0} is a placeholder for a more detailed error message + + + İzin verilen sürümler listesinde yer almadığı için Microsoft .NET Framework sürümü {0} doğrulanamıyor. + + + {0} analiz ediliyor. + {0} should not be localized, is used to contain a file path. + + + Modüller ilk kullanım için hazırlanıyor. + + + Kullanılabilir modüller aranıyor + + + {0} UNC paylaşımı aranıyor. + {0} should not be localized, is used to contain a file path. + + + Bir uzak bilgisayarda Get-Module cmdlet’ini çalıştırmak yalnızca yol içermeyen modül adları için yapılabilir. Name parametresi, bir yola çözümlenen şu öğeyi içeriyor: '{0}'. Name parametresini yol öğeleri içermeyecek şekilde güncelleştirin ve sonra yeniden deneyin. + + + Get-Module cmdlet’inin ListAvailable parametresi olmadan çalıştırılması, yol içeren modül adları için desteklenmiyor. Name parametresi, bir yola çözümlenen şu öğeyi içeriyor: '{0}'. Name parametresini yol öğeleri içermeyecek şekilde güncelleştirin ve sonra yeniden deneyin. + + + Belirtilen '{0}' modülü bulunamadı. Name parametresini geçerli bir yola işaret edecek şekilde güncelleştirin ve yeniden deneyin. + + + RepositorySourceLocation özelliği {0} modülü için dolduruluyor. + + + '{2}' modül bildiriminin '{1}' alanında listelenen, '{0}' öğesini işleyecek modül işlenmedi. {3} + + + Bu önkoşul yalnızca PowerShell Desktop sürümü için geçerlidir. + + + '{0}' modülü, geçerli PowerShell sürümü '{1}' için desteklenmiyor. Desteklenen sürümleri: '{2}'. Bu modülün uyumluluk denetimini yoksaymak için 'Import-Module -SkipEditionCheck' kullanın. + + + '{0}' modülü, PowerShell '{1}' sürümünü destekler ve ayarlar dosyasında devre dışı bırakıldığı için Windows Uyumluluk özelliği kullanılarak örtük olarak yüklenemez. Bu modülü Windows PowerShell ile yüklemek için 'Import-Module -UseWindowsPowerShell' komutunu ya da modülü geçerli PowerShell ile yüklemeyi denemek için 'Import-Module -SkipEditionCheck' komutunu kullanın. + + + Modül bildiriminde tanımlanan deneysel bir özellik için boş olmayan bir dize değeri belirtilmelidir. + + + Bir veya daha fazla geçersiz deneysel özellik adı bulundu: {0}. Modül deneysel özellik adı şu kuralı izlemelidir: 'ModuleName.FeatureName'. + + + -SkipEditionCheck anahtar parametresi, -ListAvailable anahtar parametresi olmadan kullanılamaz. + + + ConstrainedLanguage modunda *.ps1 dosyalarının modül olarak içeri aktarılmasına izin verilmiyor. + + + {0} betik modülü, modül bildiriminden farklı bir dil moduna sahip olduğundan betik modülü yüklenirken bir hata oluştu. Bildirim dil modu {1} ve modül dil modu {2}. Tüm modül dosyalarının imzalı olduğundan veya uygulamanızın izin verilenler listesi yapılandırmasının bir parçası olduğundan emin olun. + + + Bu modül, joker karakterler kullanarak işlevleri dışarı aktarırken nokta kaynak işlecini kullanıyor ve sistem uygulama doğrulama zorlaması altındayken buna izin verilmiyor. + + + Modül üyeleri, çalışan oturumdan farklı bir dil moduna sahip bir modülden dışarı aktarılamaz. + + + Oturum ConstrainedLanguage modundayken yeni modül oluşturulamaz. + + + 'Core' sürümüyle uyumlu yerleşik '{0}' modülü bulunamıyor. Lütfen PowerShell yerleşik modüllerinin kullanılabilir olduğundan emin olun. Bunlar genellikle PowerShell paketinin içinde, $PSHOME modül yolunun altında yer alır ve PowerShell’in düzgün çalışması için gereklidir. + + + Export-ModuleMember Cmdlet'i + + + '{0}' modülü, geçerli '{2}' oturumundan farklı olan '{1}' dil moduna sahip olduğundan modül üyelerinin dışarı aktarılması Kısıtlı Dil modunda başarısız olur. + + + Modül Örtük İşlev Dışarı Aktarma + + + '{0}' modülü güvenilir (Tam Dil modunda çalışıyor) ancak oturum güvenilir olmadığından (Kısıtlı Dil modunda çalışıyor) bu modül için örtük işlev dışarı aktarma işlemi reddedilecek. En iyi uygulama olarak, modül işlevlerini her zaman tam ada göre tek tek dışarı aktarın. + + + Betik Dosyası Modül Olarak İçeri Aktarılıyor + + + '{0}' betik dosyasının modül olarak içeri aktarılmasına ConstrainedLanguage modunda izin verilmeyecek. + + + Modül Nokta Kaynak İşleci İçeriyor + + + '{0}' modülünün içeri aktarılması, joker karakterler kullanırken aynı zamanda nokta kaynak işlecini de kullanarak işlevleri dışarı aktardığından Kısıtlı Dil modunda başarısız olacak. + + + "Modül Dışarı Aktaran İşlevler + + + '{0}' modülü, işlevleri ad joker karakterleri kullanarak dışarı aktarır. Kısıtlı Dil modunda çalıştırıldığında iç içe modül işlev adlarının tümü kaldırılır. + + + "Yeni Modül Cmdlet'i + + + Güvenilmeyen bir Kısıtlı Dil oturumundaki yeni bir modülün FullLanguage betik bloğu sağlaması engellenir. + + + "Modül Eşleşmeyen Dil Modları + + + Üst modülden farklı bir dil moduna sahip bağımlı bir modül yükleniyor. Kısıtlı Dil modunda buna izin verilmez. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/MshHostRawUserInterfaceStrings.tr.resx b/src/System.Management.Automation/resources/tr/MshHostRawUserInterfaceStrings.tr.resx new file mode 100644 index 00000000000..1c782050a5f --- /dev/null +++ b/src/System.Management.Automation/resources/tr/MshHostRawUserInterfaceStrings.tr.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}" değeri "{1}" değerinden büyük veya buna eşit olamaz. + + + "{0}" pozitif bir sayı olmalıdır. + + + Tüm dizeler null veya boş. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/MshSignature.tr.resx b/src/System.Management.Automation/resources/tr/MshSignature.tr.resx new file mode 100644 index 00000000000..158810e01c9 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/MshSignature.tr.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 + + + İmza doğrulandı. + + + {0} dosyası dijital imzalı değil. Bu betiği geçerli sistemde çalıştıramazsınız. Betikleri çalıştırma ve yürütme ilkesi ayarları hakkında daha fazla bilgi için https://go.microsoft.com/fwlink/?LinkID=135170 adresindeki about_Execution_Policies bölümüne bakın + + + Dosyanın karması dijital imzada depolanan karma ile eşleşmediğinden, {0} dosyasının içeriği yetkisiz bir kullanıcı veya işlem tarafından değiştirilmiş olabilir. Betik belirtilen sistemde çalıştırılamıyor. Daha fazla bilgi için Get-Help about_Signing komutunu çalıştırın. + + + {0} dosyası imzalanmış ancak imzalayana bu sistemde güvenilmiyor. + + + Sistem {0} dosyalarında imzalama işlemlerini desteklemediğinden dosya imzalanamıyor. + + + Sistem, dosya adı uzantısı olmayan dosyalarda imzalama işlemlerini desteklemediğinden dosya imzalanamıyor. + + + İmza, geçerli sistemle uyumsuz olduğundan doğrulanamıyor. + + + İmza, geçerli sistemle uyumsuz olduğundan doğrulanamıyor. Karma algoritması geçerli değil. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/MshSnapInCmdletResources.tr.resx b/src/System.Management.Automation/resources/tr/MshSnapInCmdletResources.tr.resx new file mode 100644 index 00000000000..584577bec88 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/MshSnapInCmdletResources.tr.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 + + + İşlem gerçekleştirilemez. Belirtilen cmdlet, özel bir kabukta desteklenmiyor. + + + ‘{0}' desenine uyan Windows PowerShell ek bileşeni bulunamadı. Deseni denetleyin ve ardından komutu yeniden deneyin. + + + Belirtilen ek bileşen adının biçimi geçerli değildi. Windows PowerShell ek bileşen adları yalnızca alfasayısal karakterler, kısa çizgiler, alt çizgiler ve noktalar içerebilir. Adı düzeltip ardından işlemi yeniden deneyin. + + + Windows PowerShell ek bileşeni {0} bir sistem Windows PowerShell modülü olduğu için eklenemiyor. Modülü yüklemek için Import-Module kullanın. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/MshSnapinInfo.tr.resx b/src/System.Management.Automation/resources/tr/MshSnapinInfo.tr.resx new file mode 100644 index 00000000000..50da02768ae --- /dev/null +++ b/src/System.Management.Automation/resources/tr/MshSnapinInfo.tr.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 + + + Windows PowerShell kayıt defteri bilgilerine erişilemiyor. + + + Windows PowerShell Altyapısı kayıt defteri bilgilerine erişilemiyor. + + + PublicKeyToken bilgilerine erişilemiyor. + + + Windows PowerShell {0} sürümü bu bilgisayarda kullanılabilir değil. + + + Windows PowerShell ek bileşeni "{0}" bu bilgisayarda yüklü değil. + + + {1} kayıt defteri anahtarı için zorunlu değer {0} belirtilmedi. + + + {0} zorunlu değeri kayıt defteri anahtarı {1} için doğru biçimde değil. Beklenen biçim: "string." + + + {0} zorunlu değeri kayıt defteri anahtarı {1} için doğru biçimde değil. Beklenen biçim "multistring." + + + Gerekli bilgiler kayıt defterinde bulunamıyor veya anahtar dosyaları eksik. Bazı cmdlet'ler yüklenemiyor. + + + Windows PowerShell sürümü {0} için hiçbir ek bileşen kaydedilmedi. + + + Okuyucu kapatıldığından dize kaynağı alınamıyor. + + + Sürüm değeri {0} belirtilmemiş veya kayıt defteri anahtarı {1} için yanlış. + + + Windows PowerShell türü {0} için [PSVersion] özniteliği bulunamadı. [PSVersion(PowerShell SnapinBase.PSEngineVersion)] kullanarak türe bir PSVersion özniteliği ekleyin. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/NativeCP.tr.resx b/src/System.Management.Automation/resources/tr/NativeCP.tr.resx new file mode 100644 index 00000000000..99044592c58 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/NativeCP.tr.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 + + + ScriptBlock yalnızca Command parametresinin bir değeri olarak belirtilmelidir. + + + Command parametresi için hiçbir değer belirtilmedi. + + + Geçersiz bir değer ({6}) {7} parametresi için belirtildi. Geçerli değerler Metin ve Xml'dir. + + + InputFormat parametresi için hiçbir değer belirtilmedi. Geçerli değerler Metin ve Xml'dir. + + + OutputFormat parametresi için hiçbir değer belirtilmedi. Geçerli değerler metin ve XML'dir. + + + {6} parametresi bir dize değeri gerektirir. + + + OutputFormat parametresi için hiçbir değer belirtilmedi. + + + {6} parametresi zaten belirtilmişti. + + + ‘{0}' akışından '{1}' XML'i işlenemiyor: {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PSCommandStrings.tr.resx b/src/System.Management.Automation/resources/tr/PSCommandStrings.tr.resx new file mode 100644 index 00000000000..e65ac9029a5 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PSCommandStrings.tr.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 + + + Parametre eklemek için bir komut gereklidir. Parametre eklenmeden önce {0} öğesine bir komut eklenmelidir. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PSConfigurationStrings.tr.resx b/src/System.Management.Automation/resources/tr/PSConfigurationStrings.tr.resx new file mode 100644 index 00000000000..63176ae2286 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PSConfigurationStrings.tr.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 + + + PowerShell, bir güvenlik sorunu nedeniyle çalışmayı durdurdu: Yapılandırma dosyası okunamıyor: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PSDataBufferStrings.tr.resx b/src/System.Management.Automation/resources/tr/PSDataBufferStrings.tr.resx new file mode 100644 index 00000000000..ad3991dec8d --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PSDataBufferStrings.tr.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 + + + Belirtilen dizin sıfırdan küçük ya da arabellekteki öğe sayısından büyük. Dizin {0}-{1} aralığında olmalıdır. + + + Null başvuru bir değer türüne dönüştürülemiyor. + + + Değer, {0} türünden {1} türüne dönüştürülemiyor. + + + Nesneler, kapalı bir arabelleğe eklenemez. Ekle ve Yerleştir işlemlerinin başarılı olması için arabelleğin açık olduğundan emin olun. + + + SerializeInput özelliği yalnızca PSDataCollection öğesinin PSObject türü için ayarlanabilir. SerializeInput özelliğini false olarak ayarlayın veya veri kümesi türünü PSObject olarak değiştirin. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PSListModifierStrings.tr.resx b/src/System.Management.Automation/resources/tr/PSListModifierStrings.tr.resx new file mode 100644 index 00000000000..baed14ef6ad --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PSListModifierStrings.tr.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 + + + Aşağıdaki bilinmeyen liste değiştiricisi algılandı: '{0}'. Geçerli liste değiştiricileri Ekle, Kaldır ve Değiştir. + + + Nesne, desteklenen bir koleksiyon türü olmadığı için güncelleştirme uygulanamıyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PSStyleStrings.tr.resx b/src/System.Management.Automation/resources/tr/PSStyleStrings.tr.resx new file mode 100644 index 00000000000..d01a81e8cb4 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PSStyleStrings.tr.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Belirtilen dize, yalnızca ANSI kaçış dizileri içermesi gerekirken yazdırılabilir içerik içeriyor: {0} + + + Sürüyor işleme için MaxWidth, doğru şekilde işlemek için en az 18 olmalıdır. + + + Uzantılar eklenirken veya kaldırılırken, uzantı bir nokta ile başlamalıdır. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ParameterBinderStrings.tr.resx b/src/System.Management.Automation/resources/tr/ParameterBinderStrings.tr.resx new file mode 100644 index 00000000000..52e7725a336 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ParameterBinderStrings.tr.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{1}' parametre adıyla eşleşen bir parametre bulunamadı. + + + '{1}' bağımsız değişkenini kabul eden bir konumsal parametre bulunamadı. + + + '{1}' parametresi için bir bağımsız değişken eksik. '{2}' türünde bir parametre belirtin ve yeniden deneyin. + + + '{1}' parametre adı belirsiz olduğundan parametre işlenemiyor. Olası eşleşmeler şunlardır:{6}. + + + '{6}', '{1}' parametresinin gerektirdiği '{2}' türüne dönüştürülemiyor. {7} + + + '{1}' parametresi bağlanamıyor. {6} + + + '{1}' konumsal parametreleri bağlanamıyor. + + + Hiçbir ad verilmediğinden konum parametreleri bağlanamıyor. + + + Parametre kümesi belirtilen adlandırılmış parametreler kullanılarak çözümlenemiyor. Verilen bir veya birden fazla parametre birlikte kullanılamıyor ya da yetersiz sayıda parametre sağlandı. + + + Bir veya birden fazla zorunlu parametre eksik olduğundan komut işlenemiyor:{1}. + + + '{1}' parametresi '{6}' parametre kümesinde belirtilemez. + + + '{1}' parametresi birden çok kez belirtildiğinden parametre bağlanamıyor. Birden çok değer kabul edebilen parametrelere birden çok değer sağlamak için, dizi söz dizimini kullanın. Örneğin, "-parametre değeri1,değer2,değer3". + + + Bağımsız değişkeni bir betik bloğu olarak belirtildiğinden ve giriş olmadığından '{1}' parametresi değerlendirilemiyor. Giriş olmadan betik bloğu değerlendirilemez. + + + '{1}' parametresi için betik bloğu girişi başarısız oldu. {6} + + + Bağımsız değişken girişi hiçbir çıktı üretmediğinden '{1}' parametresi değerlendirilemiyor. + + + Komut işlem hattı girişi almadığından veya giriş ve özellikleri işlem hattı girişi alan parametrelerin hiçbiriyle eşleşmediğinden, giriş nesnesi komut için hiçbir parametreye bağlanamıyor. + + + Giriş nesnesi, tüm zorunlu parametreleri bağlamak için gereken bilgileri içermediğinden bağlanamıyor: {6} + + + '{1}' parametresinin varsayılan değeri alınamadığından işlem hattı girişi işlenemiyor. {6} + + + Cmdlet için dinamik parametreler alınamıyor. {6} + + + Şu parametreler için değer girin: + + + {0} cmdlet'i komut işlem hattı {1} konumunda + + + '{1}' parametresinde bağımsız değişken dönüşümü işlenemiyor. {6} + + + {6} + + + '{1}' parametresinde bağımsız değişken doğrulanamıyor. {6} + + + '{1}' parametresi hedefe bağlanamıyor. {6} + + + '{1}' parametresi dolu olduğundan bağımsız değişken bağlanamıyor. + + + Boş bir dize olduğundan bağımsız değişken '{1}' parametresine bağlanamıyor. + + + Boş bir koleksiyon olduğundan bağımsız değişken '{1}' parametresine bağlanamıyor. + + + Boş bir dizi olduğundan bağımsız değişken '{1}' parametresine bağlanamıyor. + + + Komut işlenemiyor. '{0}' parametresi birden çok kez tanımlandı. + + + '{1}' parametresi '{2}' türünde olduğu ve Add() yöntemi belirlenemediği veya birden çok Add() yöntemi mevcut olduğu için {0} cmdlet'i bağlanamıyor. {6} + + + Çalışma zamanı tanımlı '{0}' parametresi RuntimeDefinedParameterDictionary'ye '{1}' anahtarıyla eklendiğinden {6} cmdlet'i bağlanamıyor. Anahtar RuntimeDefinedParameter.Name ile aynı olmalıdır. + + + Bağımsız değişkenin PSTypeNames değeri, '{6}' parametresinin gerektirdiği PSTypeName ile eşleşmediğinden bağımsız değişken '{1}' parametresine bağlanamıyor. + + + Şu ad veya diğer adla eşleşen parametre için $PSDefaultParameterValues içinde birden çok farklı varsayılan değer tanımlandı: {0}. Bu varsayılan değerler yoksayıldı. + + + Bu cmdlet için $PSDefaultParameterValues içinde tanımlanan şu ad veya diğer ad birden çok parametreye çözümleniyor: {0}. Varsayılan değer yoksayıldı. + + + {6} Varsayılan parametre bağlamalarının uygulanması bu hataya neden olmuş olabilir. $PSDefaultParameterValues["Disabled"] değerini $true olarak ayarlayarak $PSDefaultParameterValues varsayılan parametre bağlamasını devre dışı bırakabilir ve sonra yeniden deneyebilirsiniz. Hata oluştuğunda bu cmdlet için şu varsayılan parametreler başarıyla bağlanmıştı:{7} + + + {6} Varsayılan parametre bağlamasının uygulanması bu hataya neden olmuş olabilir. $PSDefaultParameterValues["Disabled"] değerini $true olarak ayarlayarak $PSDefaultParameterValues varsayılan parametre bağlamasını devre dışı bırakabilir ve yeniden deneyebilirsiniz. Hata oluştuğunda bu cmdlet için şu varsayılan parametre başarıyla bağlanmıştı:{7} + + + '{0}' varsayılan değeri '{1}' parametresine bağlanamadı: {2} + + + '{0}' anahtarının biçimi geçerli değil. Doğru biçim hakkında bilgi için https://go.microsoft.com/fwlink/?LinkId=228266 adresindeki about_Parameters_Default_Values bölümüne bakın. + + + '{0}' anahtarlarının biçimleri geçerli değil. Doğru biçim hakkında bilgi için https://go.microsoft.com/fwlink/?LinkId=228266 adresindeki about_Parameters_Default_Values bölümüne bakın. + + + '{0}' parametresi artık kullanılmıyor. {1} + + + '{1}' türündeki '{0}' anahtarı bir dize değeri değil. DefaultParameterDictionary yalnızca dize değeri olan anahtarları kabul eder. + + + '{0}' anahtarı zaten sözlüğe eklenmiş. + + + Yöntem veya Özellik Çağrısına İzin Verilmiyor + + + Güvenilmeyen betikler için Kısıtlı Dil modunda, '{1}' türündeki '{0}' Yöntemi veya Özelliğinin çağrılmasına izin verilmez. + + + Tür Oluşturmaya İzin Verilmiyor + + + Güvenilmeyen betikler için Kısıtlı Dil modunda parametre bağlama sırasında '{0}' türünün oluşturulmasına izin verilmez. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ParserStrings.tr.resx b/src/System.Management.Automation/resources/tr/ParserStrings.tr.resx new file mode 100644 index 00000000000..e6d5c6a7777 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ParserStrings.tr.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + Derleme yüklenemiyor '{0}'. + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PathUtilsStrings.tr.resx b/src/System.Management.Automation/resources/tr/PathUtilsStrings.tr.resx new file mode 100644 index 00000000000..c4273e1687a --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PathUtilsStrings.tr.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 'UTF-7' kodlaması kullanım dışıdır, lütfen UTF-8 kullanın. + + + Dosya {0} zaten var ve {1} belirtildi. + + + Geçerli sağlayıcı ({0}) bir dosya açamadığı için dosya açılamıyor. + + + Yol birden fazla dosyaya çözümlendiği için işlem gerçekleştirilemiyor. Bu komut birden fazla dosya üzerinde çalışamaz. + + + Joker karakter yolu {0} bir dosyaya çözümlenemediği için işlem gerçekleştirilemiyor. + + + Bilinmeyen kodlama {0}; geçerli değerler {1}. + + + ‘{0}' dizini zaten var. Dizini ve dizin içindeki dosyaları üzerine yazmak istiyorsanız -Force parametresini kullanın. + + + Kullanıcı modülü yolu mevcut değil ve bu nedenle sağlanan modül adı '{0}' için bir modül klasörü oluşturulamıyor. + + + Aşağıdaki nedenle {0} modülü oluşturulamıyor: {1}. -OutputModule parametresi için farklı bir bağımsız değişken kullanın ve yeniden deneyin. + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + Modül, {0} cmdlet'inin uyumsuz bir sürümüyle oluşturulduğu için yüklenemiyor. Geçerli oturumdaki {0} cmdlet'iyle modülü oluşturun ve modülü yeniden yüklemeyi deneyin. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PipelineStrings.tr.resx b/src/System.Management.Automation/resources/tr/PipelineStrings.tr.resx new file mode 100644 index 00000000000..0a05816d0d5 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PipelineStrings.tr.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet örneği başka bir işlem hattı tarafından kullanıldığından işlenemiyor. Lütfen Microsoft Müşteri Destek Hizmetleri ile iletişime geçin. + + + İşlem, işlem hattı başlatılmış olduğu için gerçekleştirilemiyor. İşlem hattını durdurun ve işlemi tekrar deneyin. + + + Dur ilkesi nedeniyle cmdlet'lerin çalıştırılması engellendiğinden, cmdlet'in çalıştırılmasına devam edilemiyor. + + + İşlem hattı çalıştırılamıyor çünkü işlem hattındaki ilk cmdlet, kendinden önceki bir cmdlet’in sonuçlarından girdi okumaya çalışıyor. Ya ilk cmdlet’i değiştirin, ya da ilk cmdlet’i kaldırın ya da ilk cmdlet’in çıktısına ihtiyaç duyan cmdlet’i işlem hattına ekleyin ve ardından işlem hattını tekrar çalıştırmayı deneyin. + + + Cmdlet numarası işlenemiyor. ReadFromCommand işlevi, işlem hattına önceden eklenmiş bir cmdlet’in kimliğini belirtmelidir. Lütfen Microsoft Müşteri Destek Hizmetleri ile iletişime geçin. + + + ReadFromCommand ve ReadErrorQueue işlevlerinin çıktısı, başka bir cmdlet tarafından halihazırda okunmakta olduğu için okunamıyor. Lütfen Microsoft Müşteri Destek Hizmetleri ile iletişime geçin. + + + Komut bulunmadığı için işlem hattı çalıştırılamıyor. İşlem hattına en az bir komut ekleyin ve ardından yeniden çalıştırın. + + + İşlem hattı işlemi henüz başlatılmadığı için tamamlanamıyor. Adım adım ilerleyebilen bir işlem hattında End() yöntemini çağırmadan önce Begin() yöntemini çağırmanız gerekir. + + + WriteObject ve WriteError yöntemleri, BeginProcessing, ProcessRecord ve EndProcessing yöntemlerinin yeniden tanımlamalarının dışından çağrılamaz ve yalnızca aynı iş parçacığı içinden çağrılabilir. Cmdlet’in bu çağrıları doğru bir şekilde gerçekleştirdiğini doğrulayın veya Microsoft Müşteri Destek Hizmetleri ile iletişime geçin. + + + Bir cmdlet, ThrowTerminatingError çağrıldıktan sonra bir istisna oluşturdu. +İlk istisna, yığın izlemesi “{1}” olan “{0}” idi. +İkinci istisna, yığın izlemesi “{3}” olan “{2}” idi. + + + WriteObject ve WriteError yöntemleri, işlem hattı kapatıldıktan sonra çağrılamaz. Lütfen Microsoft Müşteri Destek Hizmetleri ile iletişime geçin. + + + CommandInvocation({0}): “{1}” + + + NonTerminatingError({0}): “{1}” + + + TerminatingError({0}): “{1}” + + + ParameterBinding({0}): name="{1}"; value="{2}” + + + İşlem hattı oluşturulurken bir hata oluştu. + + + Bu işlem hattı, bağlantı kesme-bağlantı kurma semantiğini desteklemez. + + + Bu işlem hattı, bağlantısı kesik durumda olmadığı için bağlanamıyor. + + + Runspace nesnesine ilişkili bir null uzaktan komut bulunmaktadır. Uzak komut belirtilmediğinden, bağlantısı kesilmiş bir RemotePipeline nesnesi oluşturulamaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/PowerShellStrings.tr.resx b/src/System.Management.Automation/resources/tr/PowerShellStrings.tr.resx new file mode 100644 index 00000000000..d075cb0ef20 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/PowerShellStrings.tr.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 + + + Geçerli PowerShell örneğinin durumu bu işlem için geçerli değil. + + + Bir komut zaten başlatıldığı için işlem gerçekleştirilemiyor. Komutun tamamlanmasını bekleyin veya komutu durdurun ve ardından işlemi yeniden deneyin. + + + Komut belirtilmedi. + + + PowerShell örneği, iç içe geçmiş PowerShell örneği oluşturmak için doğru durumda değil. İç içe geçmiş PowerShell örnekleri yalnızca çalışan bir PowerShell örneğinde oluşturulmalıdır. + + + Çalışma alanı '{0}' durumunda olmadığından işlem gerçekleştirilemiyor. Çalışma alanının geçerli durumu '{1}'. + + + İç içe geçmiş PowerShell örnekleri zaman uyumsuz olarak çağrılamaz. Invoke yöntemini kullanın. + + + {0} nesnesi, bu PowerShell örneğinde {1} çağrılarak oluşturulmadı. + + + Çalışma alanı bir iş parçacığını yeniden kullanacak şekilde ayarlandığında, çağırma ayarlarındaki bölme durumu çalışma alanıyla eşleşmelidir. + + + Çalışma alanı geçerli iş parçacığını kullanacak şekilde ayarlandığında, çağırma ayarlarındaki bölme durumu geçerli iş parçacığın durumuyla eşleşmelidir. + + + Parametre eklemek için bir komut gereklidir. Parametre eklemeden önce PowerShell örneğine bir komut eklenmelidir. + + + Sözlükteki anahtarlar dize olmalıdır. + + + Bu iş parçacığında komutları çalıştırmak için kullanılabilir Çalışma Alanı yok. System.Management.Automation.Runspaces.Runspace türünün DefaultRunspace özelliğinde bir tane sağlayabilirsiniz. Çağırmaya çalıştığınız komut: {0} + + + Bu PowerShell nesnesi, uzak çalışma alanı veya çalışma alanı havuzuyla ilişkili olmadığından bağlanamıyor. + + + Çalışan komutun bağlantısı kesildi ancak uzak sunucuda hala çalışıyor. Komutun işlem durumunu ve çıkış verilerini almak için yeniden bağlanın. + + + Geçerli PowerShell oturumu Bağlantısı Kesik durumunda olduğundan işlem gerçekleştirilemiyor. Bu PowerShell oturumunu bağlayın, ardından komutun tamamlanmasını bekleyin veya komutu durdurun. + + + Geçerli PowerShell oturumu Bağlantısı Kesik durumunda olduğundan işlem gerçekleştirilemiyor. Bu PowerShell oturumunu bağlayın, ardından yeniden deneyin. + + + Uzak komuta bağlanma denemesi başarısız oldu. + + + Bir komut şu anda durdurulduğu için işlem gerçekleştirilemiyor. Komutun durdurma işlemini tamamlamasını bekleyin, ardından işlemi yeniden deneyin. + + + Bu iş parçacığında komutları çalıştırmak için kullanılabilir Çalışma Alanı yok. System.Management.Automation.Runspaces.Runspace türünün DefaultRunspace özelliğinde bir tane sağlayabilirsiniz. Geçerli PowerShell örneğinde çağrılacak komut yok. + + + Kullanılabilir bir geçerli çalışma alanı olmadığından, geçerli çalışma alanını kullanan bir PowerShell nesnesi oluşturulamıyor. Geçerli çalışma alanı, bir İlk Oturum Durumu ile oluşturulduğunda olduğu gibi başlatılıyor olabilir. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ProgressRecordStrings.tr.resx b/src/System.Management.Automation/resources/tr/ProgressRecordStrings.tr.resx new file mode 100644 index 00000000000..e8dfd2c18c3 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ProgressRecordStrings.tr.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} negatif bir değer olamayacağı için bağımsız değişken işlenemiyor. + + + {0} değeri null veya boş olamayacağı için bağımsız değişken işlenemiyor. + + + Yüzde, {0} 100'den büyük olamayacağı için ayarlanamıyor. + + + ParentActivityId, ActivityId ile aynı olamaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ProviderBaseSecurity.tr.resx b/src/System.Management.Automation/resources/tr/ProviderBaseSecurity.tr.resx new file mode 100644 index 00000000000..f86a84c0cdb --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ProviderBaseSecurity.tr.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 + + + ISecurityDescriptorCmdletProvider arabirimi bu sağlayıcı tarafından desteklenmediğinden arabirim kullanılamıyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/ProxyCommandStrings.tr.resx b/src/System.Management.Automation/resources/tr/ProxyCommandStrings.tr.resx new file mode 100644 index 00000000000..5050b1373bb --- /dev/null +++ b/src/System.Management.Automation/resources/tr/ProxyCommandStrings.tr.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 + + + 'help' parametresi, 'get-help' komutunun oluşturduğu geçerli bir HelpInfo nesnesi olarak tanınmıyor. + + + CommandMetadata'nın adı olmadığı içi ara sunucu komutu oluşturulamıyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/RegistryProviderStrings.tr.resx b/src/System.Management.Automation/resources/tr/RegistryProviderStrings.tr.resx new file mode 100644 index 00000000000..64d8ad9a448 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/RegistryProviderStrings.tr.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Öğeyi Ayarla + + + Öğe: {0} Değer: {1} + + + Öğeyi Temizle + + + Öğe: {0} + + + Yeni Öğe + + + Öğe: {0} + + + Anahtarı Kaldır + + + Öğe: {0} + + + Anahtarı Kopyala + + + Öğe: {0} Hedef: {1} + + + Öğeyi Yeniden Adlandır + + + Öğe: {0} NewName: {1} + + + Öğeyi Taşı + + + Öğe: {0} Hedef: {1} + + + Özelliği Ayarla + + + Öğe: {0} Özellik: {1} + + + Özelliği Temizle + + + Öğe: {0} Özellik: {1} + + + Yeni Özellik + + + Öğe: {0} Özellik: {1} + + + Özelliği Kaldır + + + Öğe: {0} Özellik: {1} + + + Özelliği yeniden adlandırın. + + + Öğe: {0} SourceProperty: {1} DestinationProperty: {2} + + + Özelliği Kopyala + + + Öğe: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + Özelliği Taşı + + + Öğe: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + İşlem işlenmedi. Sağlanan konum bu işleme izin vermiyor. + + + İşleme kaynak konumda izin verilmiyor. + + + İşleme hedef konumda izin verilmiyor. + + + Yerel bilgisayarın yapılandırma ayarları + + + Geçerli kullanıcı için yazılım ayarları + + + Bu yolda zaten bir anahtar var. + + + Hedef yol kaynak yola bağlı olduğundan işlem gerçekleştirilemiyor. + + + Özellik zaten var. + + + {0} özelliği {1} yolunda yok. + + + Belirtilen yoldaki kayıt defteri anahtarı yok. + + + 'Type' parametresi bağlanamadı. "{0}", "{1}" öğesine dönüştürülemedi. Olası sabit listesi değerleri şunlardır: "String, ExpandString, Binary, DWord, MultiString, QWord, Unknown". + + + Anahtar {0} oluşturuldu ancak varsayılan değer ayarlanamadı. + + + Belirtilen köke sahip bir sürücü oluşturulamıyor. Kök yol yok. + + + Aynı kapsayıcıda bu adla bir öğe zaten bulunduğundan öğe yeniden adlandırılamıyor. + + + Kayıt defteri anahtarı adı geçerli bir temel anahtar adıyla başlamalıdır. + + + Alt anahtar bağımsız değişkeni geçerli değil. + + + Alt anahtar mevcut olmadığından alt anahtar ağacı silinemiyor. + + + Bu ada sahip bir değer yok. + + + {0} sabit listesi değeri geçerli değil. + + + Bir bağımsız değişken belirtilmelidir. + + + Bir ad bağımsız değişkeni belirtilmelidir. + + + Belirtilen RegistryValueKind geçerli bir değer değil. + + + RegistryKey.SetValue, null dize başvurusu içeren bir String[] öğesine izin vermez. + + + Kayıt defteri alt anahtarları 255 karakterden büyük olmamalıdır. + + + Boş olmayan bir alt anahtar adı belirtilmelidir. + + + Değer nesnesinin türü, belirtilen RegistryValueKind ile eşleşmedi veya nesne düzgün dönüştürülemedi. + + + RegistryKey.SetValue, '{0}' türündeki dizileri desteklemez. Yalnızca Byte[] ve String[] desteklenir. + + + Belirtilen kayıt defteri anahtarı yok. + + + Belirtilen değer adı uzunluğu 16383 karakterlik üst sınırı aşıyor. + + + Belirtilen değer verilerinin boyutu 1 MB'lık üst sınırı aşıyor. + + + Belirtilen kayıt defteri alt anahtarı yok. + + + Belirtilen RegistryKeyPermissionCheck değeri geçerli değil. + + + Kayıt defteri anahtarının alt anahtarları var; bu yöntem özyinelemeli silmeyi desteklemez. + + + Transaction.Current veya belirtilen işlem olmadan KTM tanıtıcısı oluşturulamaz. + + + Belirtilen işlem veya Transaction.Current, bu TransactedRegistryKey'i oluşturmak veya açmak için kullanılan işle eşleşmelidir. + + + TransactedRegistryKey nesnesi önceden tanımlanmış bir anahtar olduğu için bir işlemle ilişkilendirilmiyor. + + + İstenen kayıt defteri erişimine izin verilmiyor. + + + '{0}' kayıt defteri anahtarına erişim reddedildi. + + + Kayıt defteri anahtarına yazılamıyor. + + + Kapalı bir kayıt defteri anahtarına erişilemiyor. + + + Bilinmeyen hata: {0}. + + + Kayıt defteri işlemleri bu platformda desteklenmiyor. + + + Belirtilen tanıtıcı geçerli değil. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/RemotingErrorIdStrings.tr.resx b/src/System.Management.Automation/resources/tr/RemotingErrorIdStrings.tr.resx new file mode 100644 index 00000000000..849df622a80 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/RemotingErrorIdStrings.tr.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 error of type "{0}" has occurred. + + + Out of process memory. + + + Remote PSSession enumeration with -ComputerName is only supported on Windows and not "{0}". + + + Pipeline ID "{0}" does not match the InstanceId of the pipeline that is currently running, "{1}". + + + Pipeline Id "{0}" was not found on the server. + + + The remote pipeline has been stopped. + + + The session already exists. Trying to create the session again with the same InstanceId {0} is not allowed. + + + The specified client session InstanceId "{0}" does not match the existing session's InstanceId "{1}". + + + Opening the remote session failed. + + + The specified remote session with a client InstanceId of "{0}" cannot be found. + + + Prompt response has a prompt id "{0}" that cannot be found. + + + Remote host call to "{0}" failed. + + + Remote host method {0} is not implemented. + + + Remote host method data encoding is not supported for type {0}. + + + Remote host method data decoding is not supported for type {0}. + + + Creation of nested pipelines is not supported. + + + Relative URIs are not supported in the creation of remote sessions. + + + A failure occurred while decoding data from the remote host. There was an error in the network data. + + + Only administrators can override the Thread Options remotely. + + + PowerShell Credential Request: {0} + + + Warning: A script or application on the remote computer {0} is requesting your credentials. Enter your credentials only if you trust the remote computer and the application or script that is requesting them. + +{1} + + + A script or application on the remote computer {0} is asking to read a line securely. Enter sensitive information, such as your credentials, only if you trust the remote computer and the application or script that is requesting it. + + + A script or application on the remote computer {0} is attempting to read the buffer contents on the PowerShell host. For security reasons, this is not allowed; the call has been suppressed. + + + A script or application on the remote computer {0} is sending a prompt request. When you are prompted, enter sensitive information, such as credentials or passwords, only if you trust the remote computer and the application or script that is requesting the data. + + + Received unsupported remote host call: {0}. + + + Received remoting data with unsupported action: {0}. + + + Received remoting data with unsupported data type: {0}. + + + Remoting data is missing the destination property. + + + Remoting data is missing target interface property. + + + Remoting data is missing Session InstanceId property. + + + Remoting data is missing RemotingDataType property. + + + Remoting data is missing CallId property. + + + Remoting data is missing MethodName property. + + + The IsStartFragment flag for the first fragment is not set. + + + Remoting data is missing {0} property. + + + Unexpected ObjectId received. This can happen if the fragments are not properly constructed by the remote computer, or the data might have been corrupted or changed. + + + ObjectId cannot be less than or equal to 0. This can happen if the fragments are not properly constructed by the remote computer, or the data has been changed by unauthorized users. + + + The FragmentIDs of the same object must be in sequence, incrementally changing by 1. This can happen if the fragments are not properly constructed by the remote computer. The data might also have been corrupted or changed. + + + Remoting data is too large to be reassembled from the fragments. This can happen if the length of the data in a fragment is greater than Int32.Max. It can also occur if the data was changed by unauthorized users. + + + The IsEndFragment flag is not set for the last fragment. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Deserialized remoting data is null. + + + Fragment blob length is out of range: {0} + + + Error in decoding ErrorRecord. + + + Error in decoding PipelineStateInfo. + + + Error in decoding RunspaceStateInfo. + + + Received unsupported RemotingTargetInterface type: {0} + + + Remote host method was invoked on an unknown target class: {0} + + + Remote host method was invoked without specifying a target class. + + + Error in decoding RunspacePoolStateInfo. + + + Error in decoding Minimum runspaces. + + + Error in decoding Maximum runspaces. + + + Error in decoding PowerShellStateInfo. + + + Unexpected type of {0} property (expected {1}, got {2}). + + + Unexpected type of remoting data (expected PSObject, got {0}). + + + Unexpected type of encoded command (expected PSObject, got {0}). + + + Unexpected type of encoded command parameter (expected PSObject, got {0}). + + + An error occurred while decoding data received from the remote computer. At least {0} bytes of data are required to decode a deserialized object that is received from a remote computer. This can happen if the fragments are not properly constructed by the remote computer, or if the data was corrupted or changed. + + + Received packet not destined for logged-on user: user = {0}, packet destination = {1}. + + + The client negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + PowerShell client does not support the {0} {1} negotiated by the server. Make sure the server is compatible with the build {2} and the protocol version {3} of PowerShell. + + + {0}. Negotiation with the server failed. Make sure the server is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The destination server has sent a request to close the session. + + + The server that is running PowerShell does not support the {0} {1} negotiated by the client computer. Verify that the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell does not support connect operations on the {0} {1} that is negotiated by the client computer. Make sure the client computer is compatible with the build {2} and the protocol version {3} of PowerShell. + + + The server that is running PowerShell cannot process the connect operation because the following information is not found or not valid: Client Capability information and Connect RunspacePool information. + + + The server that is running PowerShell cannot process the connect operation because the server has either not been started, or it is shutting down. + + + The server that is running PowerShell cannot process the connect operation because the server runspace pool properties did not match the client computer specified properties. + + + {0}. Negotiation with the client failed. Make sure the client is compatible with the build {1} and the protocol version {2} of PowerShell. + + + The server negotiation timer has expired. The negotiation time-out interval is {0} milliseconds. + + + The client computer has sent a request to close the session. + + + An error has occurred which PowerShell cannot handle. A remote session might have ended. + + + The server did not respond with an encrypted session key within the specified time-out period. + + + The client did not respond with a public key within the specified time-out period. + + + Connection attempt failed. + + + Attempting to close the session. + + + PowerShell cannot close the remote session properly. The session is in an undefined state because it was not opened or connected after being disconnected. PowerShell will try to force the session to close on the local computer, but the session might not be closed on the remote computer. To close a remote session properly, first open it or connect it. + + + Could not close the session. + + + The session is closed. + + + The Wait handle type "{0}" is not supported. + + + Received data has a stream ID index of "{0}". Only a Standard Output stream ID index of "0" is supported. + + + The Standard Input handle is not open. + + + Native API call to WriteFile failed. Error code is {0}. + + + Native API call to ReadFile failed. Error code is {0}. + + + {0} is not a valid schema value. Valid values are "http" and "https". + + + Client side receive call failed. + + + Client side send call failed. + + + The command handle returned from the WinRS API WSManRunShellCommand is null. + + + The Standard Input handle cannot be set to the 'no wait' state. The system error code is {0}. + + + The port number {0} is not within the range of valid values. The range of valid values is between 1 and 65535. + + + The server process has exited. + + + The call to Windows API GetStdHandle to get the Standard Input handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Output handle resulted in an error code: {0}. + + + The call to Windows API GetStdHandle to get the Standard Error handle resulted in an error code: {0}. + + + Connecting to remote server {0} failed. + + + Connecting to remote server {0} failed with the following error message : {1} + + + Closing the remote server shell instance failed with the following error message : {0} + + + Sending data to remote server {0} failed. + + + Sending data to remote server {0} failed with the following error message : {1} + + + Receiving data from remote server {0} failed. + + + Processing data from remote server {0} failed with the following error message: {1} + + + Starting a command on the remote server failed. + + + Starting a command on the remote server failed with the following error message : {0} + + + Reconnecting to a command on the remote server failed with the following error message : {0} + + + Sending data to a remote command failed. + + + Sending data to a remote command failed with the following error message: {0} + + + Receiving data for a remote command failed. + + + Processing data for a remote command failed with the following error message: {0} + + + Error with error code {0} occurred while calling method {1}. + + + {0} For more information, see the about_Remote_Troubleshooting Help topic. + + + Failed to disconnect from the remote server {0}. + + + Disconnecting from the remote server failed with the following error message : {0} + + + Reconnecting to the remote server failed. + + + Reconnecting to the remote server {0} failed with the following error message : {1} + + + Inter-process communication (IPC) transport does not support connect operations. + + + An EndpointConfiguration with Id {0} does not exist on the remote server. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The EndpointConfiguration with the {0} identifier is not in a valid initial session state on the remote computer. Contact your PowerShell administrator, or the owner or creator of the endpoint configuration. + + + The mandatory value {0} is not specified for the {1} registry key. + + + The mandatory value {0} is not in the correct format for registry key {1}. The expected format is 'string'. + + + "{0}" must specify a PowerShell script file that ends with extension ".ps1". + + + The {0} parameter is already specified in the {1} section. Contact your administrator to make sure that {0} is specified only once. + + + Expected "{0}" and "{1}" attributes in the "{2}" element. + + + "{0}", "{1}" must be specified in the "{2}" section to dynamically load the assembly. + + + Unable to load the assembly "{0}" specified in the "{1}" section. + + + Unable to load the type "{0}" specified in the "{1}" section. + + + Both "{0}" and "{1}" must be specified in the "{2}" section. + + + The destination "{0}" requested the connection to be redirected to "{1}". However "{1}" is not a well formatted URI. + + + {0}Redirect location reported: {1}. + + + Your connection has been redirected to the following URI: "{0}" + + + {0} To automatically connect to the redirected URI, verify the "{1}" property of the session preference variable "{2}", and use the "{3}" parameter on the cmdlet. + + + The current deserialized object size of the data received from the remote server exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote server exceeded the allowed maximum. The allowed maximum is {0}. + + + The current deserialized object size of the data received from the remote client computer exceeded the allowed maximum object size. The current deserialized object size is {0}. The allowed maximum object size is {1}. + + + The total data received from the remote client exceeded the allowed maximum. The allowed maximum is {0}. + + + Running startup script threw an error: {0}. + + + Specified RemoteRunspaceInfo objects have duplicates. + + + Specified RemoteRunspaceInfo objects have exceeded the maximum allowable limit. + + + Opening the remote session failed with an unexpected state. State {0}. + + + Specified Uri {0} is not valid. + + + Remote Session closed for Uri {0}. + + + Remote session is not available for ComputerName {0}. + + + Remote session is not available for {0}. + + + Remote Command: {0}, associated with the job that has an ID of "{1}". + + + A {0} cannot be specified when {1} is specified. + + + FilePath parametresi için joker karakterler desteklenmez. Joker karakter içermeyen bir yol belirtin. + + + The path specified as the value of the FilePath parameter is not from the FileSystem provider. + + + The value of the FilePath parameter must be a PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again. + + + One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects instead of strings. + + + The state of the current job instance is not valid for this operation. + + + The command cannot find the job because the job name {0} was not found. Verify the value of the Name parameter, and then try the command again. + + + The command cannot find a job with the instance identifier {0}. Verify the value of the InstanceId parameter, and then try the command again. + + + The command cannot find a job with the job ID {0}. Verify the value of the Id parameter and then try the command again. + + + The command cannot remove the job with the job ID {0} and the name {1} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} because the job is not finished. To remove the job, first stop the job, or use the Force parameter. + + + The command cannot remove the job with the job ID {0} and the instance identifier {1} because the job is not finished. To remove the job, first stop the job or use the Force parameter. + + + Remote Command: {0}, associated with a job that has an ID of "{1}". + + + The command cannot retrieve the jobs of the specified computers. The ComputerName parameter can be used only with jobs created by using PowerShell remoting. + + + The Session parameter can be used only with PSRemotingJob objects. + + + The remote session with the name {0} is not available. + + + The remote session with the session ID {0} is not available. + + + {0} does not contain an item with ID of {1}. + + + The command cannot remove the job because it does not exist or because it is a child job. Child jobs can be removed only by removing the parent job. + + + {0} is not a valid value for the parameter {1}. The value must be greater than or equal to 0. + + + {0} cannot be specified as a proxy authentication mechanism. Only {1},{2} or {3} are supported for proxy authentication. + + + Proxy credentials cannot be specified when using the following proxy access type: {0}. Either specify a different access type, or do not specify proxy credentials. + + + {1} oturum seçeneği için bir {0} değeri belirtilmelidir. + + + Session must be open. + + + The host does not support Enter-PSSession and Exit-PSSession. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for session ID {0}. + + + Multiple matches found for name {0}. + + + Enter-PSSession failed because the remote session does not provide required commands. + + + You cannot run Enter-PSSession from a nested prompt. + + + Uzak bilgisayara bağlanırken izin verilecek en fazla WS-Man URI yeniden yönlendirmesi sayısı + + + Default session options for new remote sessions + + + Name of the session configuration which will be loaded on the remote computer + + + AppName where the remote connection will be established + + + Contains information about the remote user starting the remote session. This variable is available only from a remote session. + + + Either "{0}" and "{1}" must both be specified, or neither must not be specified. + + + Session configuration "{0}" was not found. + + + Session configuration "{0}" is not a PowerShell-based shell. + + + Session configuration "{0}" is a PowerShell-based shell. Please use PowerShell 6+ to modify it. + + + Session configuration "{0}" is a Windows PowerShell-based shell. Please use Windows PowerShell to modify it. + + + No session configuration matches criteria "{0}". + + + {0} + + + Name: {0} + + + Name: {0}. This lets administrators remotely run PowerShell commands on this computer. + + + Cannot delete temporary file {0}. Reason for failure: {1}. + + + The new shell was successfully registered, but PowerShell cannot delete the temporary file {0}. Reason for failure: {1}. + + + Cannot write the shell configuration data into the temporary file {0}. Reason for failure: {1}. + + + Running command "{0}" to create a new session configuration. + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to remove a session configuration. + + + Running command "{0}" to get PowerShell-based session configurations. + + + Running command "{0}" to update the session configuration properties. + + + Name: {0} SDDL: {1} + + + Running command "{0}" to enable the session configuration. + + + WinRM Quick Configuration + + + Running command "{0}" to enable remote management of this computer by using the Windows Remote Management (WinRM) service. + This includes: + 1. Starting or restarting (if already started) the WinRM service + 2. Setting the WinRM service startup type to Automatic + 3. Creating a listener to accept requests on any IP address + 4. Enabling Windows Firewall inbound rule exceptions for WS-Management traffic (for http only). + +Do you want to continue? + + + Performing operation "{0}". + + + Name: {0} SDDL: {1}. This lets selected users remotely run PowerShell commands on this computer. + + + Running command "{0}" to disable the session configuration. + + + Name: {0} SDDL: {1}. This denies access to this session configuration for everyone. + + + Disabling the session configurations does not undo all the changes made by the Enable-PSRemoting or Enable-PSSessionConfiguration cmdlet. You might have to manually undo the changes by following these steps: + 1. Stop and disable the WinRM service. + 2. Delete the listener that accepts requests on any IP address. + 3. Disable the firewall exceptions for WS-Management communications. + 4. Restore the value of the LocalAccountTokenFilterPolicy to 0, which restricts remote access to members of the Administrators group on the computer. + + + Access is denied. To run this cmdlet, start PowerShell with the "Run as administrator" option. + + + Restarting WinRM service + + + "Restart-Service" + + + Name: {0} + + + The WinRM service must be restarted before a UI can be displayed for the SecurityDescriptor selection. Restart the WinRM service, and then run the following command: "{0}" + + + Registering session configuration + + + The session configuration "{0}" was not found. Running command "{1}" to create the "{0}" session configuration. Running this command restarts the WinRM service. + + + "{0}" and "{1}" parameters cannot be specified together. Specify either "{0}" or "{1}" parameter. + + + This operation might restart the WinRM service. Do you want to continue? + + + Cannot process an element with node type "{0}". Only {1} and {2} node types are supported. + + + Not enough data is available to process the {0} element. + + + Expected only two attributes with the names "{0}" and "{1}" in the {2} element. + + + Node type "{0}" is unknown in the {1} element. Only the "{2}" node type is expected in the {1} element. + + + Expected only one attribute with the name "{0}" in the {1} element. + + + An unknown element "{0}" was received. This can happen if the remote process closed or ended abnormally. + + + The specified authentication mechanism "{0}" is not supported. Only "{1}" is supported for this operation. + + + The pwsh executable cannot be found at "{0}". +Note that 'Start-Job' is not supported by design in scenarios where PowerShell is being hosted in other applications. Instead, usage of the 'ThreadJob' module is recommended in such scenarios. + + + Cannot start a 32-bit 'pwsh' process from the 64-bit 'pwsh' installation. Install the 32-bit 'pwsh' if you need to run PowerShell in a 32-bit process. + + + The background process reported an error with the following message: {0}. + + + The background process closed or ended abnormally: {0}. + + + There is an error processing data from the background process. Error reported: {0}. + + + Data for an inactive command with the identifier {0} was received. Received data: {1}. + + + A {0} message to a session is not supported. A {0} message can be sent only to a command. + + + The client did not receive a response for a signal operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + The client did not receive a response for a Close operation in the specified time interval. This can happen when a command is not responding to a Stop message in a timely manner. + + + An error occurred while starting the background process. Error reported: {0}. + + + The ThrottlingJob.AddChildJob method accepts only child jobs in the NotStarted state. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + The ThrottlingJob.AddChildJob method cannot be called after a call to the ThrottlingJob.EndOfChildJobs method. + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} completed + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + Invoking a nested pipeline requires a valid runspace. + + + A {1} job source adapter threw an exception with the following message: {0} + + + The value {0} is not valid for the {1} parameter. The only allowed value is 5.1. + + + The Wait and Keep parameters cannot be used together in the same command. + + + WriteEvents parametresi Wait parametresi olmadan kullanılamaz. + + + PowerShell remoting endpoint versioning is not supported on PowerShell 7+. + + + The following type cannot be instantiated because its constructor is not public: {0}. + + + The job operation (Create, Get, or Remove) could not be performed because the JobSourceAdapter type specified in the JobDefinition is not registered. Register the JobSourceAdapter type either by using an explicit call, or by calling the Import-Module cmdlet, and then specifying an assembly. + + + The job could not be created because the JobInvocationInfo does not contain a JobDefinition. Start the JobInvocationInfo with a JobDefinition. + + + The state of the current job instance is {0}. This state is not valid for the attempted operation. {1} + + + Unable to connect job "{0}" to the remote server. + + + The Disconnect-PSSession operation failed for runspace Id = {0}. + + + The connect operation failed for session {0}. The Runspace state is {1} instead of Opened. + + + The Disconnected PSSession query failed for computer "{0}". + + + Cannot connect PSSession "{0}", either because it is not in the Disconnected state, or it is not available for connection. + + + Session connect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Cannot disconnect PSSession "{0}" because it is not in the Opened state. + + + Session disconnect is not supported for PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + Receive-PSSession does not support PSSession "{0}" on target "{1}" because the target computer type is "{2}". + + + The command cannot finish because the ChildJobs property contains a value that is not valid. + + + Cannot suspend the job that has an ID of {0}. Suspending jobs is not supported for some job types. For more information about support for suspending jobs, see the Help topic for the job type. + + + Cannot resume the job that has an ID of {0}. Resuming jobs is not supported for some job types. For more information about support for resuming jobs, see the Help topic for the job type. + + + You cannot use the Invoke-Command cmdlet with both the AsJob and Disconnected parameters in the same command. + + + The remote session query failed for {0} with the following error message: {1} + + + Attempted to create a job with ID {0}. A job with this ID cannot be created now. Verify that the ID has already been assigned once on this computer. + + + Cannot create a job with an ID of {0}; this is not a valid ID. Provide an integer for the job ID that is greater than 0. + + + The JobIdentifier provided must not be null. Please provide a valid JobIdentifier. + + + The Wait-Job cmdlet cannot finish working, because one or more jobs are blocked waiting for user interaction. Process interactive job output by using the Receive-Job cmdlet, and then try again. + + + Remote session {0} could not be connected and could not be removed from the server. The client remote session object will be removed from the server, but the state of the remote session on the server is unknown. + + + Disconnect-PSSession operation failed for runspace Id = {0} for the following reason: {1} + + + Job "{0}" could not be connected to the server and so could not be stopped. + + + The command cannot find a PSSession with an InstanceId value of "{0}". + + + The command cannot find a PSSession that has the name "{0}". + + + PowerShell uzaktan iletişimi, Windows Önyükleme Ortamı'nda (WinPE) desteklenmiyor. + + + {0} tarafından yapılan değişiklikler, WinRM hizmeti yeniden başlatılana kadar etkili olamaz. + + + {0}, bu adı kullanan bir yapılandırmanın kaydı yakın zamanda kaldırıldıysa, WinRM hizmetinin yeniden başlatılması gerekebilir. Bazı sistem veri yapıları hala önbellekte olabilir. Bu durumda, WinRM’nin yeniden başlatılması gerekebilir. +Microsoft.PowerShell gibi PowerShell oturum yapılandırmalarına ve Register-PSSessionConfiguration cmdlet’iyle oluşturulan oturum yapılandırmalarına bağlı tüm WinRM oturumlarının bağlantısı kesilir. + + + Uzak bir oturumda çalışıyorsunuz ve Zorla seçeneğini belirlediniz. Bu, WinRM hizmetinin yeniden başlatılabileceği anlamına gelir. WinRM hizmeti yeniden başlatılırsa bu uzak oturum sonlandırılır ve devam etmek için yeni bir oturum oluşturmanız gerekir + + + The job was null when trying to save identifiers. Specify a job to save its identifiers. + + + A running command could not be found for this PSSession. + + + The Microsoft .NET Framework 2.0, which is required for Windows PowerShell 2.0, is not installed. Install the .NET Framework 2.0 and retry. + + + The remote pipeline failed. + + + The remote pipeline failed for the following reason: {0} + + + One or more jobs could not be resumed because the state was not valid for the operation. + + + No client computer was specified for the remote runspace that is running a client-side method. + + + Name: {0} SDDL: {1}. This denies remote access to this session configuration. + + + Enabled: False. This configures the WS-Management service to deny the connection request. + + + Enabled: True. This configures the WS-Management service to accept the connection request. + + + Aliases to be defined when applied to a session + + + Assemblies to load when applied to a session + + + Author of this document + + + Version of the CLR to use when applied to a session + + + Company associated with this document + + + Copyright statement for this document + + + Description of the functionality provided by these settings + + + Environment variables to define when applied to a session + + + Execution policy to apply when applied to a session + + + Format files (.ps1xml) to load when applied to a session + + + Functions to define when applied to a session + + + ID used to uniquely identify this document + + + Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' + + + Directory to place session transcripts for this session configuration + + + Whether to run this session configuration as the machine's (virtual) administrator account + + + Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' + + + Modules to import when applied to a session + + + Version of the PowerShell engine to use when applied to a session + + + Processor architecture to use when applied to a session + + + Version number of the schema used for this document + + + Scripts to run when applied to a session + + + Types to add when applied to a session + + + Type files (.ps1xml) to load when applied to a session + + + Variables to define when applied to a session + + + User roles (security groups), and the role capabilities that should be applied to them when applied to a session + + + Aliases to make visible when applied to a session + + + Cmdlets to make visible when applied to a session + + + Could not parse visible command definition for '{0}'. The visible command definition must be a hashtable with the keys of 'Name' and 'Parameters'. The value of the 'Parameters' key must be a collection of hashtables with the keys 'Name', and optionally either 'ValidateSet' or 'ValidatePattern'. + + + Functions to make visible when applied to a session + + + Providers to make visible when applied to a session + + + External commands (scripts and applications) to make visible when applied to a session + + + PSSession Configuration file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.pssc' extension. Please fix the path specification and try again. + + + Role Capability file path '{0}' is not valid. The path argument must resolve to a single file in the file system with a '.psrc' extension. Please fix the path specification and try again. + + + The 'Roles' entry must be a hashtable, but was a {0}. + + + Could not convert the value of the '{0}' role entry to a hashtable. The 'Roles' entry must be a hashtable with group names for keys, where the value associated with each key is another hashtable of session configuration properties for that role. + + + Could not find the role capability, '{0}'. The role capability must be a file named '{1}' within a 'RoleCapabilities' directory in a module in the current module path. + + + Cannot find module path to import. The value of the ModulesToImport parameter {0} does not exist or is not a module directory. Correct the value and try the command again. + + + The specified configuration file '{0}' was not loaded because no valid configuration file was found. + + + Computer {0} has been successfully disconnected. + + + The reconnection attempt to {0} failed. Attempting to disconnect the session... + + + Attempting to reconnect to {0} ... + + + Network connectivity to {0} has been lost and the attempt to reconnect has failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + The network connection to {0} has been interrupted. Attempting to reconnect for up to {1} minutes... + + + The network connection to {0} has been restored. + + + {0} authentication requires an explicit user name and password. Specify the user name and password by using the -Credential parameter and try the command again. + + + Basic authentication is not supported over HTTP on Unix. + + + Cannot find a scheduled job with name {0}. + {0} is the job definition name + + + More than one job definition was found with name {0}. Try including the -DefinitionType parameter to Start-Job in order to narrow the search for the job definition to a single job source adapter. + + + The member 'SchemaVersion' is not present in the configuration file. This member must exist and be assigned a version number of the form 'n.n.n.n'. Please add the missing member to the file {0}. + + + The member '{0}' must be a string. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a string array. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable. Change the member to the correct type in the file {1}. + + + The member '{0}' must be a hashtable array. Change the member to the correct type in the file {1}. + + + The member '{0}' is not a valid key. Please change the member to a valid key in the file {1}. + + + The member '{0}' must be a valid enumeration type "{1}". Valid enumeration values are "{2}". Change the member to the correct type in the file {3}. + + + Error parsing configuration file {0} with the following message: {1} + + + -WriteJobInResults parametresi -Wait parametresi olmadan kullanılamaz + + + The member '{0}' is not an absolute path {1}. Change the member to an absolute path in the file {2}. + + + The key '{0}' in the member '{1}' is not valid. Change the key in the file {2}. + + + The member '{0}' must contain the required key '{1}'. Add the require key to the file {2}. + + + The key '{0}' contains an extension {1} that is not valid. Specify an extension from the following list: {{{2}}}. + + + The key '{0}' in the member '{1}' must be a script block. Change the key to the correct type in the file {2}. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. + + + Network connection interrupted + + + Attempting to reconnect to {0} ... + + + Job {0} has been created for reconnection. + + + Session {0} with instance ID {1} on computer {2} has been successfully disconnected. + + + Session {0} with instance ID {1} has been created for reconnection. + + + The SessionName parameter can only be used with the Disconnected switch parameter. + + + A failure occurred while attempting to connect the PSSession. + + + A failure occurred while attempting to connect to the target virtual machine. + + + A failure occurred while attempting to connect to the target container. + + + The PSSession is in a disconnected state and is not available for connection. + + + The Hyper-V Module for PowerShell is not available on this machine. + + + Failed to launch PowerShell process ({1}) inside container with id {0} with error: {2}. + + + The Containers feature may not be enabled on this machine. + + + Failed to terminate PowerShell process with id {0} inside container with id {1}. + + + The input ContainerId {0} does not exist, or the corresponding container is not running. + + + The input VMId parameter does not resolve to a single virtual machine. + + + The input VMId {0} does not resolve to a single virtual machine. + + + The input VMName parameter does not resolve to any virtual machine. + + + The input VMName parameter resolves to multiple virtual machines. + + + The input VMName {0} does not resolve to a single virtual machine. + + + The virtual machine {0} is not in running state. + + + The credential is invalid. + + + The input username cannot be empty. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Retrieve the remote session using Get-PSSession -ComputerName {1} -InstanceId {2}. + + + Cannot enter session {0} because it is not in the disconnected state or is not available for connection. Reconnect using Connect-PSSession or Receive-PSSession. + + + Network connectivity to {0} has been lost and the reconnection attempt failed. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + Failed to create an instance of RemoteSessionHyperVSocketClient due to SetSocketOption failure. + + + Failed to create an instance of RemoteSessionHyperVSocketServer. + + + Reconnection attempt canceled. Please repair the network connection and reconnect using Connect-PSSession or Receive-PSSession. + + + One or more jobs could not be suspended because the state was not valid for the operation. + + + The -AutoRemoveJob parameter cannot be used without the -Wait parameter + + + The WS-Management service cannot process the request. Cannot find the {0} session configuration in the WSMan: drive on the {1} computer. For more information, see the about_Remote_Troubleshooting Help topic. + + + A job could not be created from the {0} specification because the provided runspace is not a local runspace. Try again using a local runspace, or specify a RunspaceMode argument. + + + The session {0} cannot be disconnected because the specified idle time-out value {1} (seconds) is either greater than the server maximum allowed {2} (seconds), or less than the minimum allowed {3} (seconds). Specify an idle time-out value that is within the allowed range, and try again. + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + The specified IdleTimeout session option {0} (seconds) is not a valid period. Specify an IdleTimeout value that is greater than or equal to the minimum allowed {1} (seconds). + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + The cmdlet "{0}" or the alias "{1}" cannot be present when "{2}","{3}","{4}" or "{5}" keys are specified in the session configuration file. + + + "The transport option is not valid. Parameter "{0}" can be non-zero only if parameter "{1}" is set to true." + + + The member '{0}' must be an array consisting of either string or hashtable elements. + + + The member '{0}' must be an array consisting of either string or hashtable elements. Change the member to the correct type in the file {1}. + + + Cannot retrieve the job definition '{0}' because path '{1}' refers to a '{2}' provider path. Change the path parameter to a file system path. + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + Cannot retrieve the job definition '{0}' because path '{1}' resolves to multiple file paths. Change the path parameter so that it is a single path. + {0} is job definition name +{1} is the user provided path + + + Cannot find a scheduled job with type {0} and name {1}. + {0} is the job definition type and {1} is the job definition name. + + + Cannot find the WorkingDirectory path {0}. + + + Cannot connect to session {0}. The session no longer exists on computer {1}. + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + The connect operation failed for session {0} with the following error message: {1} + + + The -Force parameter cannot be used without the -Wait parameter. + + + One or more jobs are in a suspended or disconnected state, and cannot continue without additional user input. Specify the -Force parameter to continue to a completed, failed, or stopped state. + + + When RunAs is enabled in a PowerShell session configuration, the Windows security model cannot enforce a security boundary between different user sessions that are created by using this endpoint. Verify that the PowerShell runspace configuration is restricted to only the necessary set of cmdlets and capabilities. + + + The job was suspended successfully by adding the Force parameter. + + + The session configuration file {0} is not valid. Specify a valid session configuration file and try the command again. Error parsing configuration file: {1}. + + + Register-PSSessionConfiguration : The '{0}' key in the {1}. session configuration file contains a value that is not valid. Correct the file and try the command again. + + + Disconnected sessions are supported only when the remote computer is running PowerShell 3.0 or a later version of PowerShell. + + + Memory usage of a cmdlet has exceeded a warning level. To avoid this situation, try one of the following: 1) Lower the rate at which CIM operations produce data (for example, by passing a low value to the ThrottleLimit parameter), 2) Increase the rate at which data is consumed by downstream cmdlets, or 3) Use the Invoke-Command cmdlet to run the whole pipeline on the server. The cmdlet that exceeded a warning level of memory usage was started by the following command line: {0} + + + PSSession {0} was created using the EnableNetworkAccess parameter and can only be reconnected from the local computer. + + + Cannot start job. The language mode for this session is incompatible with the system-wide language mode. + + + Cannot create runspace. The language mode for this configuration is incompatible with the system-wide language mode. + + + Cannot exit a nested pipeline because the pipeline is not in the nested state. + + + The PowerShell server session is not in a valid state for running nested commands. No nested commands can be run in this session. + + + Cannot invoke a nested command on the remote session because a nested command is already running. + + + The remote session was unable to invoke command {0} with error: {1}. + + + The remote session command is currently stopped in the debugger. Use the Enter-PSSession cmdlet to connect interactively to the remote session and automatically enter into the console debugger. + + + The remote session to which you are connected does not support remote debugging. You must connect to a remote computer that is running PowerShell 4.0 or greater. + + + Because the session state for session {0}, {1}, {2} is not equal to Open, you cannot run a command in the session. The session state is {3}. + + + No valid sessions were specified. Ensure you provide valid sessions that are in the Opened state and are available to run commands. + + + The session {0}, {1}, {2} is not available to run commands. The session availability is {3}. + + + The command cannot run because the ChildJobs property is empty. + + + The job cannot be debugged because there is no PowerShell host debugger available. Make sure you are running this command in a host that supports debugging. + + + Cannot find job with id {0}. + + + Cannot find job with Instance Id {0}. + + + Cannot find job with name {0}. + + + The job cannot be debugged because there is no host UI available. Make sure you are running this command in a PowerShell host that implements PSHostUserInterface. + + + The job cannot be debugged because the host debugger mode is set to None or Default. The host debugger mode must be LocalScript and/or RemoteScript. + + + Multiple jobs were found with Id {0}. Debug-Job can debug only one job at a time. + + + Multiple jobs were found with the name {0}. Debug-Job can debug only one job at a time. + + + The Named Pipe server listener used for process attach is already running. + + + Enter-PSHostProcess does not support entering the same PowerShell session it is running in. + + + Multiple processes were found with this name {0}. Use the process Id to specify a single process to enter. + + + Cannot enter process with Id '{0}' because it has not loaded the PowerShell engine or the named-pipe listener was disabled. + + + No process was found with Id: {0}. + + + No process was found with Name: {0}. + + + No named pipe was found with CustomPipeName: {0}. + + + Cannot process the command because the pipeName specified is too long. Pipe names on this platform can be up to {0} characters long. Your pipe name '{1}' is {2} characters. + + + The current host does not support the Enter-PSHostProcess cmdlet. + + + "The named pipe target process has ended." + + + "The Hyper-V socket target process has ended." + + + {0}[Process:{1}]: {2} + + + {0}[{1}]: {2} + + + Unable to connect to application domain name {0} of process {1}. Error: {2}. + + + Unable to connect to pipe with name {0}. Error: {1}. + + + PowerShell plugin cannot process the Connect operation as required negotiation information is either missing or not complete. + + + PowerShell plugin failed to process to connect operation. + + + The supplied plugin context is not valid. + + + Powershell plugin encountered a fatal error while processing {0} arguments. + + + The supplied command context is not valid. + + + The supplied input data is not valid. Only input data of type {0} is supported. + + + Sağlanan giriş akışı geçerli değil. Giriş akışı olarak yalnızca {0} desteklenir. + + + Sağlanan çıkış akışı kümesi geçerli değil. Çıkış akışı olarak yalnızca {0} desteklenir. + + + Sağlanan WSMAN_SENDER_DETAILS geçerli değil. Null WSMAN_SENDER_DETAILS işlenemiyor. + + + Sağlanan kabuk bağlamı geçerli değil. + + + {0} + + + {1} eklenti yöntemine sahip {0} için NULL değerine izin verilmez. + + + Giriş akışı ve çıkış akışı kümeleri için NULL değerine izin verilmez. {0} ve {1}, desteklenen giriş ve çıkış akışlarıdır. + + + {1} eklenti yöntemine sahip {0} için NULL değerine izin verilmez. + + + {1} eklenti yöntemine sahip {0} için NULL değerine izin verilmez. + + + PowerShell eklentisi işlemi kapatılıyor. Bu durum, barındırma hizmeti veya uygulama kapatılıyorsa oluşabilir. + + + PowerShell eklentisi {0} seçeneğini anlamıyor. İstemcinin PowerShell'in derleme {1} ve protokol sürümü {2} ile uyumlu olduğundan emin olun. + + + İstemciden {0} adlı bir seçenek bekleniyor. İstemcinin PowerShell'in derleme {1} ve protokol sürümü {2} ile uyumlu olduğundan emin olun. + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">PowerShell eklentisi, istemci tarafından istenen {2} protokol sürümünü desteklemiyor.</PSProtocolVersionError> + + + PowerShell eklentisi, WSMan hizmetine bağlam bildirirken önemli bir hatayla karşılaştı. + + + Yönetilen sunucu oturumu oluşturulamıyor. + + + PowerShell eklentisi, kapatma bildirimi için bekleme tanıtıcısını kaydederken önemli bir hatayla karşılaştı. + + + Cannot enter Runspace because a Runspace is already pushed in this session. + + + Cannot enter Runspace because there is no server remote debugger available. + + + Cannot enter Runspace because it is not a remote Runspace. + + + Remote transport error: {0} + + + Unable to open pipe connection for PowerShell in container. Error code: {0}. + + + Unable to create PowerShell IPC named pipe. Error code: {0}. + + + Timeout expired before connection could be made to named pipe. + + + WSMan Initialization failed with error code: {0}. + + + Unable to start named pipe server while in server mode. + + + Could not grant remote access to '{0}': '{1}'. The session configuration has been registered, but this group does not have access. To resolve this error, provide a valid group name and register the session configuration again. + + + Could not get the session capabilities for the session configuration '{0}': this configuration was not registered with a session configuration file (.pssc), such as one created by the New-PSSessionConfigurationFile cmdlet. + + + Could not resolve username '{0}'. Verify the username and try again. + + + Groups associated with machine's (virtual) administrator account + + + Cannot create or open the configuration session {0}. + + + Enforces script input parameter validation. This is automatically enabled when MountUserDrive is specified. + + + Creates a 'User' PSDrive in the session for use with Copy-Item when File System provider is not visible. + + + The member '{0}' must be a boolean. Change the member to the correct type in the file {1}. + + + The member '{0}' must be an integer. Change the member to the correct type in the file {1}. + + + Processing the User drive threw an error {0}. + + + Optional maximum size in bytes of user drive created with MountUserDrive parameter. Default maximum size for User drive is 50MB. + + + Cannot find the file system provider. + + + Group managed service account name under which the configuration will run + + + Invalid Group Managed Service account name. Account name must be of the form 'DomainName\UserName'. + + + Group accounts for which membership is required to use the session. + + + Cannot parse sddl string because it contains mismatched parentheses: {0}. + + + RequiredGroups property hashtable must contain only a single key. + + + The RequiredGroups property is not in a name/value pair hashtable format. This must be a hashtable of the form (using PowerShell syntax): RequiredGroups = @{ Or = 'Administrators' }. + + + Unknown key in Required Groups configuration. Required Groups hashtable can only contain 'And' and 'Or' hash keys for logical membership groupings. + + + Unknown value in Required Groups configuration. Required Groups hashtable can only contain values that are either group names or another logical hashtable. + + + Malformed ACE {0}. Regular ACEs must have exactly 6 sections. + + + Cannot create a session User Drive because the current user name contains invalid file path characters. + + + Invalid role capability key: {0}. Make sure the role capability name is spelled correctly and is a valid session configuration property. + + + Invalid role capability key type: {0}. Role capability keys must be strings that identify a valid session configuration property. + + + Invalid role key type: {0}. Role keys must be strings that identify a security group. + + + Other Possible Cause: + -The domain or computer name was not included with the specified credential, for example: DOMAIN\UserName or COMPUTER\UserName. + + + Failed to start the SSH client process needed for the remoting connection with error: {0}. + + + The specified key file {0} was not found. + + + The SSH client session has ended with error message: {0} + + + SSH connection attempt failed after time out: {0} seconds. + + + +SSH client process terminated before connection could be established. + + + The provided SSHConnection hashtable is missing the required ComputerName or HostName parameter. + + + The provided SSHConnection hashtable parameter name or element is null or empty. + + + The provided SSHConnection hashtable parameter {0} is not supported. + + + The provided SSHConnection hashtable contains both a ComputerName and HostName parameter. Only one can be specified. + + + The provided SSHConnection hashtable contains both a KeyFilePath and IdentityFilePath parameter. Only one can be specified. + + + Could not find the provided role capability file {0}. + + + The provided role capability file {0} does not have the required .psrc extension. + + + The SSH transport process has abruptly terminated causing this remote session to break. + + + PowerShell 6+ does not support WOW64. The binary must match the architecture of the processor. + + + "{0}" yürütülebilir dosyası bulunamadı. WOW64 özelliğinin yüklü olduğunu doğrulayın. + + + Unable to install plugin {0} to directory {1}. + + + The WinRM plugin DLL {0} is missing for PowerShell. Please run Enable-PSRemoting and then retry this command. + + + This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system. + + + + Exit code: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + Information about the process could not be read: '{0}'. + + + Host system does not have the correct version of Hyper-V schema. + + + HTTPS on Unix does not currently support CA or CN checks. Use the PSSessionOption -SkipCACheck and -SkipCNCheck if you are certain you trust the server you are connecting to and the network in between. + + + PowerShell remoting has been disabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + + PowerShell remoting has been enabled only for PowerShell 6+ configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. + + + Enter-PSHostProcess cmdlet is disabled because an application control policy such as 'AppLocker' or 'Windows Defender Application Control' is in enforcement. + + + Remote debugger exception: {0}, error message: {1} + + + Bu makinede Windows PowerShell bulunamadığından Windows PowerShell işlemi oluşturulamıyor. + + + The Runspace argument to Create must be a non-null RemoteRunspace object. + + + The session configuration hash table contains an invalid key type. Keys should be string types. + + + The session configuration file contains an unsupported configuration option: {0}. This is a remoting endpoint configuration option, that does not apply to PowerShell session state. + + + The session configuration file contains an unknown configuration option: {0}. + + + Expression Evaluation May Fail + + + Creating a PowerShell object from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Failed to get Hyper-V VM State. The value was of the type {0} but was expected to be Microsoft.HyperV.PowerShell.VMState or System.String. + + + Hyper-V {0} sent an invalid {1} response during the connection negotiation. + + + Negotiating a secure connection to Hyper-V failed. Make sure the Host and Guest are updated with all relevant Microsoft Updates. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/RunspaceInit.tr.resx b/src/System.Management.Automation/resources/tr/RunspaceInit.tr.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/RunspaceInit.tr.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/RunspacePoolStrings.tr.resx b/src/System.Management.Automation/resources/tr/RunspacePoolStrings.tr.resx new file mode 100644 index 00000000000..2f5b1a868f8 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/RunspacePoolStrings.tr.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Maksimum havuz boyutu 1'den küçük olamaz. + + + Minimum havuz boyutu 1'den küçük olamaz. + + + Minimum havuz boyutu maksimum havuz boyutundan büyük olamaz. + + + Çalışma alanı havuzunun durumu bu işlem için geçerli değil. + + + Çalışma alanı havuzu "{0}" durumunda olmadığından işlem gerçekleştirilemiyor. Geçerli durum: "{1}". + + + Çalışma alanı havuzu "BeforeOpen" durumunda olmadığından açılamıyor. Geçerli durum: "{0}". + + + {0} nesnesi, geçerli RunspacePool örneğinde {1} çağrılarak oluşturulmadı. + + + Çalışma alanı geçerli havuza ait olmadığından, çalışma alanı geçerli havuza bırakılamıyor. + + + Bu özellik, çalışma alanı havuzu açıldıktan sonra değiştirilemez. + + + Bu çalışma alanı bağlantı kesme ve bağlanma işlemlerini desteklemiyor. + + + Çalışma alanı havuzu Bağlantı Kesildi durumunda olduğundan işlem gerçekleştirilemiyor. + + + Bağlantıyı Kesme işlemi sunucuda desteklenmiyor. Uzak çalışma alanı havuzu bağlantı kesme desteği için sunucuda Windows PowerShell 3.0 veya daha yeni bir sürüm çalışıyor olmalıdır. + + + Bu {0} çalışma alanı havuzu, uzak sunucuda çalışan komutlar için bağlantısı kesilmiş Windows PowerShell nesneleri sağlamak üzere yapılandırılmadı. Sunucuyu sorgulamak ve bu işlem için yapılandırılmış çalışma alanı havuzu nesnelerini döndürmek üzere RunspacePool sınıfının GetRunspacePools() statik yöntemini kullanın. + + + Karşılık gelen sunucu tarafı çalışma alanı havuzu başka bir istemciye bağlı olduğundan bu çalışma alanı havuzu bağlanamıyor. + + + ResetRunspaceState sunucuda desteklenmiyor. Sunucuda Windows PowerShell 5.0 veya daha yeni bir sürüm çalışıyor olmalıdır. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/RunspaceStrings.tr.resx b/src/System.Management.Automation/resources/tr/RunspaceStrings.tr.resx new file mode 100644 index 00000000000..83cb75ae192 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/RunspaceStrings.tr.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Çalışma alanı durumu bu işlem için geçerli değil. + + + Çalışma alanı BeforeOpen durumunda olmadığından açılamıyor. Çalışma alanının geçerli durumu '{0}'. + + + Çalışma alanı Açıldı durumunda olmadığından işlem gerçekleştirilemiyor. Çalışma alanının geçerli durumu '{0}'. + + + Çalışma alanı Açıldı durumunda olmadığından işlem hattı çağrılamıyor. Çalışma alanının geçerli durumu '{0}'. + + + İşlem hattı durumu bu işlem için geçerli değil. + + + İşlem hattı zaten çağrılmış olduğundan çağrılamıyor. + + + Parametre için geçerli değer: PipelineResultTypes.Output. + + + İşlem hattı bir komut içermiyor. + + + Bir işlem hattı zaten çalıştığından işlem hattı çalıştırılmadı. İşlem hatları eş zamanlı olarak çalıştırılamaz. + + + İç içe geçmiş bir işlem hattı zaman uyumsuz olarak çağrılamaz. Invoke yöntemini kullanın. + + + İç içe geçmiş bir işlem hattını yalnızca çalışan bir işlem hattının içinden çalıştırmalısınız. + + + Bir SessionStateProxy metot çağrısı sürerken çalışma alanı kapatılamaz. + + + Bir SessionStateProxy metot çağrısı sürerken işlem hattı çağrılamaz. + + + SessionStateProxy metot çağrısı devam ediyor. Eş zamanlı SessionStateProxy metot çağrılarına izin verilmiyor. + + + Bir işlem hattı zaten çalışıyor. Eş zamanlı SessionStateProxy metot çağrılarına izin verilmiyor. + + + Bu özellik, çalışma alanı açıldıktan sonra değiştirilemez. + + + Bu çalışma alanını oluşturmak için kullanılan InitialSessionState nesnesinde belirtilen '{0}' modülü işlenirken bir veya daha fazla hata oluştu. Hataların tam listesi için ErrorRecords özelliğine bakın. İlk hata şuydu: {1} + + + İş parçacığı seçenekleri yalnızca bölme durumu çok iş parçacıklı bölme (MTA) ise, geçerli seçenekler UseNewThread veya UseCurrentThread ise ve yeni değer ReuseThread ise değiştirilebilir. + + + Dil modu {1} veya {2} olduğunda {0} false olamaz. + + + Yalnızca yerel bir çalışma alanının bağlantısını kesemezsiniz. + + + Bağlan işlemi yerel çalışma alanlarında desteklenmez. + + + Oturum meşgul. Kullanılabilir olduğu anda oturuma bağlanacaksınız. Enter-PSSession komutunu iptal etmek için Ctrl-C tuşlarına basın. + + + Komut tamamlanamıyor. Betik çağrısı bu oturum yapılandırmasında desteklenmiyor. Oturum yapılandırması dil yok modundaysa bu durum oluşabilir. + + + Yerel çalışma alanlarında Bağlantıyı Kes ve Bağlan işlemlerini kullanamazsınız. + + + Çalışma alanı Açıldı durumunda olmadığından işlem hattına bağlanılamıyor. Çalışma alanının geçerli durumu '{0}'. + + + RemoteRunspace oluşturulamıyor. Sağlanan RunspacePool nesnesi geçerli değil. + + + Bu çalışma alanıyla ilişkili bağlantısı kesilmiş komut yok. + + + Bağlantıyı kesme işlemi uzak bilgisayarda desteklenmiyor. Bağlantıyı kesmeyi desteklemek için uzak bilgisayarda Windows PowerShell 3.0 veya Windows PowerShell'in sonraki bir sürümü çalışıyor olmalı ve WSMan taşıma kullanılmalıdır. + + + Oturum Bağlantısı kesik durumunda olmadığından veya bağlantı için kullanılamadığından PSSession'a bağlanılamıyor. + + + Parametre değeri PipelineResultTypes.None veya PipelineResultTypes.Output olamaz. + + + Parametre için geçerli değerler: PipelineResultTypes.Output veya PipelineResultTypes.Null. + + + Hata ayıklama akışı yeniden yönlendirmesi hedeflenen uzak bilgisayarda desteklenmez. + + + Ayrıntılı akış yeniden yönlendirmesi hedeflenen uzak bilgisayarda desteklenmez. + + + Uyarı akışı yeniden yönlendirmesi hedeflenen uzak bilgisayarda desteklenmez. + + + Bilgi akışı yeniden yönlendirmesi hedeflenen uzak bilgisayarda desteklenmez. + + + Bir komut veya betik çalıştırmakla meşgul olan bir oturuma girdiniz. Çıkış "{0}" işine yönlendirildiğinden konsolda çıkış görmezsiniz. Çalışan komutun bitmesini bekleyebilir veya Ctrl-C tuşlarına basarak komutu iptal edip bir giriş istemi alabilirsiniz. + + + + Bir komut veya betik çalıştırmakla meşgul olan bir oturuma girdiniz ve çıktı konsolda görüntülenecek. Çalışan komutun bitmesini bekleyebilir veya Ctrl-C tuşlarına basarak komutu iptal edip bir giriş istemi alabilirsiniz. + + + + Çalışan bir komut veya betik içindeki hata ayıklama kesme noktasında şu anda durdurulmuş bir oturuma girdiniz. Hata ayıklamaya devam etmek için PowerShell komut satırı hata ayıklayıcısını kullanın. + + + + DefaultRunspace bir LocalRunspace olmalıdır + + + Statik PrimaryRunspace özelliği yalnızca bir kez ayarlanabilir ve zaten ayarlanmıştır. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/SecuritySupportStrings.tr.resx b/src/System.Management.Automation/resources/tr/SecuritySupportStrings.tr.resx new file mode 100644 index 00000000000..22ac9e48b7e --- /dev/null +++ b/src/System.Management.Automation/resources/tr/SecuritySupportStrings.tr.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Sertifika yüklenemiyor. '{0}' bir dosya sistemi yoluna çözümlenmelidir. + + + '{0}' sertifikası şifreleme için kullanılamaz. Şifreleme sertifikaları, Veri Şifreleme veya Anahtar Şifreleme anahtar kullanımını ve Belge Şifreleme Gelişmiş Anahtar Kullanımı ({1}) değerini içermelidir. + + + Sertifika yüklenemiyor. '{0}' tanımlayıcısı birden çok sertifikayla eşleşiyor. Birden çok alıcıya şifrelemek için, birden çok sertifikayla eşleşen bir joker karakter yerine '{1}' parametresine birden çok belirli değer sağlayın. + + + Şifreleme sertifikası yüklenemiyor. '{0}' sertifika ayarı, base-64 ile kodlanmış geçerli bir sertifikayı temsil etmiyor ve dosya, dizin, parmak izi veya konu adına göre geçerli bir sertifikayı temsil etmiyor. + + + UYARI: '{0}' sertifikası özel anahtar içeriyor. Şifreleme için kullanılan Korumalı Olay Günlüğü sertifikaları yalnızca ortak anahtarı içermelidir. + + + HATA: Olay günlüğü iletisi '{0}' korunamadı: {1} + + + HATA: Sertifika bulunamadı veya kullanılamadı: {0} + + + Güvenli dizeyi şifrelemek için oturum anahtarı kullanılamıyor. + + + Geçersiz arabellek uzaklığı. + + + Ortak anahtar verileri geçersiz. + + + Ortak anahtar içeri aktarılamıyor. + + + Oturum anahtarı verileri geçersiz. + + + '{0}' betik dosyasının çalıştırılması sistem ilkesi tarafından engellendi. + + + Bilinmeyen bir betik dosyası ilke zorlaması değeri döndürüldü: {0}. + + + Betik Dosyası Okundu + + + '{0}' betik dosyasına ilke tarafından güvenilmiyor ve ConstrainedLanguage modunda çalışacak. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/Serialization.tr.resx b/src/System.Management.Automation/resources/tr/Serialization.tr.resx new file mode 100644 index 00000000000..b545ea0f998 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/Serialization.tr.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} özniteliği bekleniyordu. + + + {0} XML etiketi tanınmıyor. + + + {0} başvurusu için nesne bulunamadı. + + + Sözlük anahtarı için ad özniteliği yanlış belirtilmiş. + + + Sözlük değeri için ad özniteliği yanlış belirtilmiş. + + + PSObject sürümü geçersiz. + + + Gelen PSObject sürümü {0}. Beklenen değer 1. + + + {0} başvurusu için TypeName bulunamadığından adlar işlenemiyor. + + + depth parametresinin değeri 1’den büyük veya 1’e eşit olmalıdır. + + + Geçerli Düğüm türü {0}. Beklenen tür: {1}. + + + Sözlük girdisinin anahtarı belirtilmedi. + + + Sözlük girdisi için değer belirtilmemiş. + + + Seri durumdan çıkarılacak başka nesne yok. + + + Null, sözlük anahtarı olarak belirtilmiştir. + + + {0} ilkel türünün içeriği geçersiz. + + + Serileştirilmiş XML çok derine yuvalanmış. + + + Serileştirici kapatıldı. + + + Komuttaki veri, oturum yapılandırmasının izin verdiği en büyük boyutu aştı. İzin verilen en büyük değer {0} MB'dir. Girişi değiştirin, farklı bir oturum yapılandırması kullanın veya uzak bilgisayardaki oturum yapılandırmasının "{1}" ve "{2}" özelliklerini değiştirin. + + + Şifrelenmiş güvenli dize seri durumundan çıkarılamadı. + + + {0} anahtar türü geçersiz. PSPrimitiveDictionary sınıfı yalnızca System.String türündeki anahtarları kabul eder. + + + {0} değerinin türü geçerli değil. PSPrimitiveDictionary sınıfı, Windows PowerShell uzak iletişimi üzerinden tam olarak seri durumuna alınabilir türlerdeki değerleri yalnızca kabul eder. Tam olarak seri durumuna alınabilir türlerin bir listesi için about_Remoting Yardım konusuna bakın. + + + Verinin şifresi çözülemedi. Veri bu anahtarla şifrelenmedi. + + + “{0}” parametre değeri geçerli bir şifrelenmiş dize değil. + + + Belirtilen {0} geçerli değil. Geçerli {0} uzunluk ayarları 128 bit, 192 bit veya 256 bittir. + + + SecureString'in seri durumdan çıkarılması şu anda yalnızca Windows'ta destekleniyor. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/SessionStateProviderBaseStrings.tr.resx b/src/System.Management.Automation/resources/tr/SessionStateProviderBaseStrings.tr.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/SessionStateProviderBaseStrings.tr.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/SessionStateStrings.tr.resx b/src/System.Management.Automation/resources/tr/SessionStateStrings.tr.resx new file mode 100644 index 00000000000..90f700ff9a1 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/SessionStateStrings.tr.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Sağlayıcının Start yönteminden döndürülen bilgi geçirilenden farklı bir sağlayıcıya ait olduğundan döndürülen bilgiler işlenemiyor. + + + Sağlayıcının Start yönteminden döndürülen bilgi null olduğundan döndürülen bilgiler işlenemiyor. + + + '{0}' sağlayıcısında GetItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + GetItem işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında SetItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + SetItem işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında ClearItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında InvokeDefaultAction işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + InvokeDefaultAction işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında ItemExists işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + ItemExists işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında IsValidPath işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında IsItemContainer işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında RemoveItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında GetChildItems işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + GetChildItems işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında GetChildNames işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + GetChildNames işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında RenameItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + RenameItem işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında NewItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + NewItem işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında HasChildItems işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında CopyItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + CopyItem işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında GetParentPath işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında NormalizeRelativePath işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında MakePath işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında GetChildName işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında MoveItem işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + MoveItem işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında GetProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + GetProperty işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında SetProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + SetProperty işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında ClearProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + ClearProperty işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında NewProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + NewProperty işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında RemoveProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + RemoveProperty işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında CopyProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + CopyProperty işleminin dinamik parametreleri '{1}' yolunun '{0}' sağlayıcısı için alınamıyor. {2} + + + '{0}' sağlayıcısında MoveProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + MoveProperty işleminin dinamik parametreleri '{1}' yolunun '{0}' sağlayıcısı için alınamıyor. {2} + + + '{0}' sağlayıcısında RenameProperty işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{1}' yolunun '{0}' sağlayıcısında RenameProperty için dinamik parametreler alınamıyor. {2} + + + '{1}' yolunun '{0}' sağlayıcısı için içerik okuyucu alınamıyor. {2} + + + GetContentReader işleminin dinamik parametreleri '{1}' yolunun '{0}' sağlayıcısı için alınamıyor. {2} + + + '{1}' yolunun '{0}' sağlayıcısı için içerik yazıcı alınamıyor. {2} + + + GetContentWriter işleminin dinamik parametreleri '{1}' yolunun '{0}' sağlayıcısı için alınamıyor. {2} + + + İçerik dizin olduğundan alınamıyor: '{0}'. Lütfen bunun yerine 'Get-ChildItem' kullanın. + + + İçerik dizin olduğundan yazılamıyor: '{0}'. + + + Geriye gitmek için kalan konum geçmişi yok. + + + İleriye gitmek için kalan konum geçmişi yok. + + + BoundedStack boş. + + + '{0}' sağlayıcısında ClearContent işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' içeriği bir dizin olduğundan temizlenemiyor. Clear-Content yalnızca dosyalarda desteklenir. + + + ClearContent işleminin dinamik parametreleri '{1}' yolu için '{0}' sağlayıcısından alınamıyor. {2} + + + '{0}' sağlayıcısında GetSecurityDescriptor işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında SetSecurityDescriptor işlemini gerçekleştirme girişimi '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısında Start işlemini gerçekleştirme girişimi başarısız oldu. {1} + + + '{0}' sağlayıcısında InitializeDefaultDrives işlemini gerçekleştirme girişimi başarısız oldu. + + + '{0}' sağlayıcısında NewDrive işlemini gerçekleştirme girişimi '{1}' köküne sahip sürücü için başarısız oldu. {2} + + + NewDrive için dinamik parametreler '{0}' sağlayıcısı için alınamıyor. {1} + + + '{0}' sağlayıcısında RemoveDrive çağrısı başarısız oldu. {1} + + + '{1}' sağlayıcısı engellediğinden '{0}' sürücüsü kaldırılamıyor. + + + '{0}' yolu, '{1}' tabanının dışındaki bir öğeye başvurdu. + + + '{0}' sağlayıcısının içerik yazıcısında Seek çağrısı '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısının içerik okuyucusunda veya yazıcısında Close çağrısı '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısının içerik okuyucusunda Read çağrısı '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısının içerik yazıcısında Write çağrısı '{1}' yolu için başarısız oldu. {2} + + + '{0}' sağlayıcısı, değişken söz dizimi kullanılarak veri almak veya ayarlamak için kullanılamaz. {2} + + + Değişken söz dizimi sağlayıcıda veri almak veya ayarlamak için kullanılamaz. {2} + + + {0} diğer adı salt okunur veya sabit olduğundan ve üzerine yazılamadığından diğer ad yazılabilir değil. + + + Salt okunur veya sabit olduğundan {0} işlevine yazılamıyor. + + + {0} değişkeni salt okunur veya sabit olduğundan değişken üzerine yazılamıyor. + + + '${0}' değişkeni özel bir değişken olduğundan bu değişkene erişilemiyor. + + + Özel bir komut olduğundan '{0}' komutuna erişilemiyor. + + + Özel bir komut olduğundan komuta erişilemiyor. + + + Özel bir kaynak olduğundan oturum durumu kaynağına erişilemiyor. + + + {0} diğer adı sabit veya salt okunur olduğundan diğer ad kaldırılmadı. + + + {0} işlevi sabit olduğundan kaldırılamıyor. + + + Sabit veya salt okunur olduğundan {0} değişkeni kaldırılamıyor. Değişken salt okunursa, Zorla seçeneğini belirterek işlemi yeniden deneyin. + + + {0} diğer adı sabit olduğundan değiştirilemiyor. + + + {0} diğer adı salt okunur olduğundan değiştirilemiyor. + + + {0} işlevi sabit olduğundan değiştirilemiyor. + + + {0} işlevi salt okunur olduğundan değiştirilemiyor. + + + {0} diğer adı oluşturulduktan sonra sabit hale getirilemez. Diğer adlar yalnızca oluşturma sırasında sabit hale getirilebilir. + + + Mevcut {0} işlevi sabit hale getirilemiyor. İşlevler yalnızca oluşturulurken sabit hale getirilebilir. + + + Mevcut {0} değişkeni sabit hale getirilemiyor. Değişkenler yalnızca oluşturulurken sabit hale getirilebilir. + + + AllScope seçeneği '{0}' diğer adından kaldırılamıyor. + + + AllScope seçeneği '{0}' işlevinden kaldırılamıyor. + + + AllScope seçeneği '{0}' değişkeninden kaldırılamıyor. + + + '{0}' işlev tanımı kapsam niteleyicisi içeriyordu ancak işlev adı içermiyordu. + + + {0} sağlayıcısı kaldırılamıyor. {0} sağlayıcısı kaldırılmadan önce {0} sağlayıcısı ile ilişkili tüm sürücüler kaldırılmalıdır. + + + Sürücü adı şu geçersiz karakterlerden birini veya daha fazlasını içerdiğinden işlenemiyor: ; ~ / \ . : + + + Sağlayıcı yeni sürücünün oluşturulmasına izin vermediğinden yeni sürücü oluşturulamadı. + + + Sağlanan '{0}' değeri birden fazla konum yığınına çözümlendi. + + + '{0}' konum yığını bulunamıyor. Bu yığın yok veya bir kapsayıcı değil. + + + ‘{0}' yolu mevcut olmadığından bulunamıyor. + + + '{0}' diğer adı mevcut olmadığından diğer ad bulunamıyor. + + + '{0}' yolu birden çok kapsayıcıya çözümlendiğinden konum ayarlanamıyor. Konumu bir seferde yalnızca tek bir kapsayıcıya ayarlayabilirsiniz. + + + '{0}' değişken yolu birden çok öğeye çözümlendiğinden değişken işlenemiyor. Değişken değerini aynı anda yalnızca bir öğe için alabilir veya ayarlayabilirsiniz. + + + Sürücü bulunamıyor. '{0}' adlı bir sürücü yok. + + + '{0}' adlı bir sağlayıcı bulunamıyor. + + + '{0}' adlı bir sağlayıcı bulunamıyor. Ad doğru biçimde değil. Sağlayıcı adı yalnızca alfasayısal karakterlerden oluşabilir ya da arkasından tek bir '\' ve ardından alfasayısal karakterler gelen bir PowerShell ek bileşeni adı olabilir. + + + '{0}' birden fazla sağlayıcı adına çözümlendi. Olası eşleşmeler şunlardır:{1}. + + + Sağlayıcının bir örneği oluşturulmaya çalışılırken bir hata oluştu. '{0}' sağlayıcı türü adı derlemede bulunamadı. + + + Belirtilen '{0}' sağlayıcı adı, geçerli olmayan şu karakterlerden birini veya daha fazlasını içerdiğinden kullanılamıyor: \ [ ] ? * : + + + '{0}' sağlayıcısının bir örneği oluşturulmaya çalışılırken bir hata oluştu. {1} + + + '{0}' adlı bir değişken bulunamıyor. + + + '{0}' adlı bir izleme kaynağı bulunamıyor. + + + '{0}' adında bir sürücü zaten var. + + + '{0}' adlı bir değişken zaten var. + + + '{0}' adlı bir diğer ad zaten bulunduğundan diğer ada izin verilmiyor. + + + '{0}' adlı bir cmdlet sağlayıcısı zaten mevcut olduğundan cmdlet sağlayıcısı kaydedilemiyor. + + + Yol bir dosya sistemi yoluna başvurmuyor. + + + Genel kapsam kaldırılamıyor. + + + Kapsam numarası '{0}' etkin kapsam sayısını aşıyor. + + + PSDriveInfo karşılaştırılamıyor. Bir PSDriveInfo örneği yalnızca başka bir PSDriveInfo örneğiyle karşılaştırılabilir. + + + Çıkışın akışla aktarılacağı bir cmdlet belirtilmediğinden cmdlet sağlayıcısı sonuçları akışla aktaramıyor. + + + Hatanın akışla aktarılacağı bir cmdlet belirtilmediğinden cmdlet sağlayıcısı sonuçları akışla aktaramıyor. + + + Bu sağlayıcı için giriş konumu ayarlanmadı. Giriş konumunu ayarlamak için "(get-psprovider '{0}').Home = 'path'" komutunu çağırın. + + + Yol doğru biçimde değil. Sağlayıcı yolları bir sağlayıcı kimliği, ardından "::" ve ardından sağlayıcıya özgü bir yol içermelidir. + + + Hedef yol yalnızca tek bir yola çözümlenebildiğinden öğe taşınamıyor. + + + Kaynak ve hedef yollar aynı sağlayıcıya çözümlenmediğinden öğe taşınamıyor. + + + Kaynak yol bir veya daha fazla öğeye işaret ettiğinden ve hedef yol bir kapsayıcı olmadığından öğe taşınamıyor. Hedef yolun bir kapsayıcı olduğunu doğrulayın ve yeniden deneyin. + + + Hedef birden çok yola çözümlendiğinden öğe taşınamıyor. Tek bir hedefe çözümlenen bir hedef yolu belirtin ve yeniden deneyin. + + + Kapsayıcı mevcut olan yaprak öğenin üzerine kopyalanamıyor. + + + Kapsayıcı başka bir kapsayıcıya kopyalanamıyor. -Recurse veya -Container parametresi belirtilmemiş. + + + Kaynak ve hedef yol aynı sağlayıcıya çözülmedi. + + + Yol birden çok öğeye çözümlendiğinden öğe yeniden adlandırılamıyor. Bir kerede yalnızca bir öğe yeniden adlandırılabilir. + + + '{0}' sağlayıcısındaki bir hata nedeniyle sağlayıcı '{1}' yolunu çözümlemek için kullanılamıyor. + + + Arabirim kullanılamıyor. IContentCmdletProvider arabirimi bu sağlayıcı tarafından uygulanmıyor. + + + Arabirim kullanılamıyor. IPropertyCmdletProvider arabirimi bu sağlayıcı tarafından desteklenmiyor. + + + Arabirim kullanılamıyor. IDynamicPropertyCmdletProvider arabirimi bu sağlayıcı tarafından uygulanmıyor. + + + NavigationCmdletProvider yöntemleri bu sağlayıcı tarafından desteklenmiyor. + + + Sağlayıcı yöntemleri işlenmedi. ContainerCmdletProvider yöntemleri bu sağlayıcı tarafından desteklenmiyor. + + + Yöntemler çağrılamıyor. ItemCmdletProvider yöntemleri bu sağlayıcı tarafından desteklenmiyor. + + + DriveCmdletProvider yöntemleri bu sağlayıcı tarafından desteklenmiyor. + + + Sağlayıcı bu işlemi desteklemediğinden sağlayıcı işlemi durduruldu. + + + Sağlayıcı 'Depth' parametresini desteklemediğinden sağlayıcı işlemi durduruldu. + + + Yöntem çağrılamıyor. İçerik Seek yöntemi bu sağlayıcı tarafından desteklenmiyor. + + + ClearContent işlemi gerçekleştirilemiyor. ClearContent işlemi bu sağlayıcı tarafından desteklenmiyor. + + + Sağlayıcı kimlik bilgilerinin kullanımını desteklemiyor. İşlemi kimlik bilgileri belirtmeden yeniden gerçekleştirin. + + + FileSystem sağlayıcısı kimlik bilgilerini yalnızca New-PSDrive cmdlet'inde destekler. İşlemi kimlik bilgileri belirtmeden yeniden gerçekleştirin. + + + Sağlayıcı işlemleri desteklemiyor. İşlemi -UseTransaction parametresi olmadan yeniden gerçekleştirin. + + + Yöntem çağrılamıyor. Sağlayıcı filtrelerin kullanımını desteklemiyor. + + + Sürücü oluşturulamıyor. Sağlayıcı kimlik bilgilerinin kullanımını desteklemiyor. + + + '{0}' yolundaki öğe zaten var. + + + Öğe kopyalanamıyor. '{0}' yolundaki öğe yok. + + + '{0}' yolundaki öğe yok. + + + Oturum durumunda depolanan diğer adların görünümünü içeren sürücü + + + İşlem için ortam değişkenlerinin görünümünü içeren sürücü + + + Oturum durumunda depolanan işlevlerin görünümünü içeren sürücü + + + Oturum durumunda depolanan bu değişkenlerin görünümünü içeren sürücü + + + Geçerli kullanıcı için geçici dizin yoluyla eşlenen sürücü + + + Hedef Değer belirtilmediğinden '{0}' bağlantısı oluşturulamıyor. + + + Null değişkenine yapılan başvurular her zaman null değeri döndürür. Atamaların etkisi yoktur. + + + Bir oturumda saklanacak en fazla geçmiş nesnesi sayısı + + + {0} işlevi salt okunur veya sabit olduğundan işlev yeniden adlandırılamıyor. + + + {0} diğer adı salt okunur veya sabit olduğundan diğer ad yeniden adlandırılamıyor. + + + {0} değişkeni salt okunur veya sabit olduğundan değişken yeniden adlandırılamıyor. + + + Yerel {0} değişkeninde seçenekler ayarlanamıyor. Seçeneklerin ayarlanmasına olanak tanıyan bir değişken oluşturmak için New-Variable kullanın. + + + {0} cmdlet'i salt okunur olduğundan değiştirilemiyor. + + + {0} değişkeni iyileştirildiğinden ve kaldırılamadığından değişken kaldırılamıyor. Remove-Variable cmdlet'ini (diğer ad olmadan) kullanmayı veya değişkeni kaldırmak için kullandığınız komutu nokta kaynaklı çalıştırmayı deneyin. + + + {0} değişkeni iyileştirildiğinden değişkenin üzerine yazılamıyor. New-Variable veya Set-Variable cmdlet'ini (diğer ad olmadan) kullanmayı deneyin veya değişkeni ayarlamak için kullandığınız komutu nokta kaynaklı çalıştırın. + + + {0} ve {1} parametreleri birlikte kullanılamaz. Lütfen yalnızca bir parametre belirtin. + + + Tail parametresi şu anda yalnızca FileSystem sağlayıcısı için destekleniyor. + + + Adı '{0}' ve komut türü '{1}' olan bir komut zaten mevcut olduğundan diğer ada izin verilmiyor. + + + Yazılım çalıştırılamıyor. İzin reddedildi. + + + '-{0}' ve '-{1}' birbirini dışlar ve aynı anda belirtilemez. + + + '{0}' yolu geçerli değil. Uzak kopyalama işlemlerinde yalnızca mutlak yollar desteklenir. + + + '{0}' uzak yolu doğrulanamıyor. + + + {0} oturumu {1} olarak ayarlandığından işlem gerçekleştirilemiyor. + + + '{0}' parametresi null veya boş olamaz. + + + Oturum Durumu Değişkenleri + + + ConstrainedLanguage modunda, '{0}' değişkeninin kapsamını AllScope olarak değiştirmek veya bu kapsamda oluşturmak engellenir. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/StringDecoratedStrings.tr.resx b/src/System.Management.Automation/resources/tr/StringDecoratedStrings.tr.resx new file mode 100644 index 00000000000..345be9b927d --- /dev/null +++ b/src/System.Management.Automation/resources/tr/StringDecoratedStrings.tr.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Bu yöntem için yalnızca 'ANSI' veya 'PlainText' desteklenir. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/SubsystemStrings.tr.resx b/src/System.Management.Automation/resources/tr/SubsystemStrings.tr.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/tr/SubsystemStrings.tr.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/SuggestionStrings.tr.resx b/src/System.Management.Automation/resources/tr/SuggestionStrings.tr.resx new file mode 100644 index 00000000000..f2300e9af09 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/SuggestionStrings.tr.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 + + + "{0}" komutu bulunamadı ancak geçerli konumda var. +PowerShell, varsayılan olarak geçerli konumdan komutları yüklemez (bkz. 'Get-Help about_Command_Precedence'). + +Bu komuta güveniyorsanız, bunun yerine aşağıdaki komutu çalıştırın: + + + En benzer komutlar şunlardır: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/TabCompletionStrings.tr.resx b/src/System.Management.Automation/resources/tr/TabCompletionStrings.tr.resx new file mode 100644 index 00000000000..30debf0f2bf --- /dev/null +++ b/src/System.Management.Automation/resources/tr/TabCompletionStrings.tr.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 tab completion result cannot be properly deserialized because the remote runspace does not contain a TypeTable instance. + + + Cannot access properties on a null instance of the type CompletionResult. + + + Bitwise NOT + + + Logical not. Negates the statement that follows it. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case sensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case sensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case sensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case sensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case sensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE only when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case sensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Returns TRUE when the left operand is not an instance of the specified .NET Framework type (right operand). + + + Returns TRUE when the left operand is an instance of the specified .NET Framework type (right operand). + + + Converts the left operand to the specified .NET Framework type (right operand). + + + Formats strings by using the format method of string objects. + + + Logical and. Returns TRUE when both statements are TRUE. + + + Bitwise AND + + + Logical or. TRUE when either or both statements are TRUE. + + + Bitwise OR (inclusive) + + + Logical exclusive or. Returns TRUE when one of the statements is TRUE and the other is FALSE. + + + Bitwise OR (exclusive) + + + Join - combine multiple strings into a single string. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Shift Left bit operator. Inserts zero in right-most bit position. + + + Shift Right bit operator. Inserts zero in the left-most bit position. For signed values, sign bit is preserved. + + + [string] +Specifies the name of the property being created. + + + [string] +Specifies the name of the property being created. + + + [scriptblock] +A script block used to calculate the value of the new property. + + + [string] +Define how the values are displayed in a column. +Valid values are 'left', 'center', or 'right'. + + + [string] +Specifies a format string that defines how the value is formatted for output. + + + [int] +Specifies the maximum column width in a table when the value is displayed. +The value must be greater than 0. + + + [int] +The depth key specifies the depth of expansion per property. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [String[]] +Specifies the log names to get events from. +Supports wildcards. + + + [String[]] +Specifies the event log providers to get events from. +Supports wildcards. + + + [String[]] +Specifies file paths to log files to get events from. +Valid file formats are: .etl, .evt, and .evtx + + + [Long[]] +Selects events with the specified keyword bitmasks. +The following are standard keywords: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Selects events with the specified event IDs. + + + [int[]] +Selects events with the specified log levels. +The following log levels are valid: +1: Critical +2: Error +3: Warning +4: Informational +5: Verbose + + + [datetime] +Selects events created after the specified date and time. + + + [datetime] +Selects events created before the specified date and time. + + + [string] +Selects events generated by the specified user. +This can either be a string representation of a SID or a domain and username in the format DOMAIN\USERNAME or USERNAME@DOMAIN + + + [string[]] +Selects events with any of the specified values in the EventData section. + + + [hashtable] +Excludes events that match the values specified in the hashtable. + + + [string] or [hashtable] +Specifies an array of PowerShell modules that the script requires. +Each element can either be a string with the module name as value or a hashtable with the following keys: +Name: Name of the module +GUID: GUID of the module +One of the following: +ModuleVersion: Specifies a minimum acceptable version of the module. +RequiredVersion: Specifies an exact, required version of the module. +MaximumVersion: Specifies the maximum acceptable version of the module. + + + [string] +Specifies a PowerShell edition that the script requires. +Valid values are "Core" and "Desktop" + + + [switch] +Specifies that PowerShell must be running as administrator on Windows. +This must be the last parameter on the #requires statement line. + + + [version] +Specifies the minimum version of PowerShell that the script requires. + + + Specifies that the script requires PowerShell 7+ to run. + + + Specifies that the script requires Windows PowerShell 5.1 to run. + + + [string] +Required. Specifies the module name. + + + [string] +Optional. Specifies the GUID of the module. + + + [string] +Specifies a minimum acceptable version of the module. + + + [string] +Specifies an exact, required version of the module. + + + [string] +Specifies the maximum acceptable version of the module. + + + A brief description of the function or script. +This keyword can be used only once in each topic. + + + A detailed description of the function or script. +This keyword can be used only once in each topic. + + + .PARAMETER <Parameter-Name> +The description of a parameter. +Add a .PARAMETER keyword for each parameter in the function or script syntax. + + + A sample command that uses the function or script, optionally followed by sample output and a description. +Repeat this keyword for each example. + + + The .NET types of objects that can be piped to the function or script. +You can also include a description of the input objects. + + + The .NET type of the objects that the cmdlet returns. +You can also include a description of the returned objects. + + + Additional information about the function or script. + + + The name of a related topic. +Repeat the .LINK keyword for each related topic. +The .Link keyword content can also include a URI to an online version of the same help topic. + + + The name of the technology or feature that the function or script uses, or to which it is related. + + + The name of the user role for the help topic. + + + The keywords that describe the intended use of the function. + + + .FORWARDHELPTARGETNAME <Command-Name> +Redirects to the help topic for the specified command. + + + .FORWARDHELPCATEGORY <Category> +Specifies the help category of the item in .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Specifies a session that contains the help topic. +Enter a variable that contains a PSSession object. + + + .EXTERNALHELP <XML Help File> +The .ExternalHelp keyword is required when a function or script is documented in XML files. + + + Specifies the path to a .NET assembly to load. + +using assembly <.NET-assembly-path> + + + Specifies a PowerShell module to load classes from. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifies a .NET namespace to resolve types from or a namespace alias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifies an alias for a .NET Type. + +using type <AliasName> = <.NET-type> + + + A normal string. + + + A string that contains unexpanded references to environment variables that are expanded when the value is retrieved. + + + Binary data in any form. + + + A 32-bit binary number. + + + An array of strings. + + + A 64-bit binary number. + + + An unsupported registry data type. + + + ',' - Comma + + + ', ' - Comma-Space + + + ';' - Semi-Colon + + + '; ' - Semi-Colon-Space + + + {0} - Newline + + + '-' - Dash + + + ' ' - Space + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/TransactionStrings.tr.resx b/src/System.Management.Automation/resources/tr/TransactionStrings.tr.resx new file mode 100644 index 00000000000..624d621f29b --- /dev/null +++ b/src/System.Management.Automation/resources/tr/TransactionStrings.tr.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + İşlem kullanılamıyor. Hiçbir işlem etkin değil. + + + İşlem yürütülemiyor. Hiçbir işlem etkin değil. + + + Etkin işlem olmadığından işlem geri alınamıyor. + + + İşlem geri alınamıyor. İşlem zaten yürütüldü. + + + İşlem yürütülemiyor. İşlem zaten yürütüldü. + + + İşlem yürütülemiyor. İşlem geri alındı veya zaman aşımına uğradı. + + + İşlem geri alınamıyor. İşlem zaten geri alındı veya zaman aşımına uğradı. + + + Etkin işlem ayarlanamıyor. İşlem oluşturulmadı. + + + Etkin işlem ayarlanamıyor. Etkin işlem geri alındı veya zaman aşımına uğradı. + + + Bu cmdlet için etkin bir işlem gerekiyor. Geçerli işlem zaten yürütüldü veya geri alındı. + + + Bu cmdlet için bir işlem gerekiyor. Komutu -UseTransaction parametresiyle yeniden çalıştırın. + + + İşlem kullanılamıyor. İşlem başlatılmadı. + + + İşlem kullanılamıyor. İşlem yürütüldü. + + + İşlem kullanılamıyor. İşlem geri alındı veya zaman aşımına uğradı. + + + İşlem kullanılamıyor. İşlem zaman aşımına uğradı. + + + Temel işlem ayarlanmadı. + + + Temel işlem etkin değil. + + + Diğer işlemler oluşturulduktan sonra temel işlem ayarlanamaz. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/TypesXmlStrings.tr.resx b/src/System.Management.Automation/resources/tr/TypesXmlStrings.tr.resx new file mode 100644 index 00000000000..1bebd946f88 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/TypesXmlStrings.tr.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : Hata: {3} + + + {0}, {1}({2}) : "{3}" türünde hata: {4} + + + "{0}" düğümü, "{1}" altında yalnızca bir kez bulunmalıdır. "{1}" üst düğümü yoksayılacak. + + + {0} düğümüne izin verilmiyor. Şu düğümlere izin veriliyor: {1}. + + + "{0}" düğümünün bir iç metni olmamalıdır. + + + "{0}" düğümünün bir iç metni olmalıdır. + + + "{0}" düğümü bulunamadı. "{1}" altında yalnızca bir kez bulunmalıdır. "{1}" üst düğümü yoksayılacak. + + + "Type" düğümünde "Members", "TypeConverters" veya "TypeAdapters" olmalıdır. + + + Şu özel durumu nedeniyle {0} türü için tür dönüştürücüsünün örneği oluşturulamıyor: {1}. + + + Windows PowerShell, şu özel durum nedeniyle {0} türü için tür bağdaştırıcısının bir örneğini oluşturamıyor: {1}. + + + Uyarlanan tür "{0}" geçerli değil. + + + TypeConverter zaten bulunduğu için yoksayıldı. + + + TypeAdapter zaten bulunduğu için yoksayıldı. + + + "{0}" türü, TypeConverter ya da PSTypeConverter olmalıdır. + + + "{0}" türü bir PSPropertyAdapter olmalıdır. + + + {0} üyesi zaten var. + + + Şu üye adı ayrılmış: {0} + + + Özel durum: {0} + + + CodeProperty bir alıcıya veya ayarlayıcıya sahip olmalıdır. + + + CodeProperty bir alıcıya veya ayarlayıcıya sahip olmalıdır. + + + {0}, {1} : {2} + + + Değer, {0} yerine TRUE ya da FALSE olmalıdır. + + + "{0}" düğümü "{1}" özniteliğine sahip olmamalıdır. + + + {0}, {1}: Dosya bulunamadı. + + + {0}, {1}: Dosya zaten {2} tarafından yüklendiği için atlandı. + + + Kayıt defteri anahtarı bulunamadı: {0}{1}. Yapılandırma dosyalarını yüklemek için {2} kullanılıyor. + + + Kayıt defteri anahtarında belirtilen {0} yolu bulunamıyor: {1}{2}. Yapılandırma dosyalarını yüklemek için {3} kullanılıyor. + + + {0}, {1}: Dosya, ps1xml dosya adı uzantısına sahip olmadığından atlandı. + + + {0}, {1}: Dosya şu doğrulama özel durumu nedeniyle atlandı: {2}. + + + "{0}" üyesi bir not olmalıdır. + + + "{0}" notu dönüştürülemiyor: "{1}". + + + "{0}" üyesini burada kullanmayın. + + + "{0}" üyesi "{1}" türünde olmalıdır. + + + "{1}", "{2}" olduğunda ve "{3}", "{4}" olduğunda "{0}" mevcut olmalıdır. + + + Önceki bir hata nedeniyle tüm serileştirme ayarları yoksayıldı. + + + "{0}" standart bir üye değil ve yoksayılacak. + + + {0} yolu tam değil. Tam bir tür dosyası yolu belirtin. + + + TypeTable, çalışma alanı dışında oluşturulmuş olabileceği için TypeTable güncelleştirilemiyor. + + + TypeTable yüklenirken hatalar oluştu. Ayrıntılı hata mesajları için Hatalar özelliğine bakın. + + + TypeData "{0}" hatası: {1} + + + "{0}", "{1}" özelliği için bir değere sahip olmalıdır. + + + "{0}" öğesinin "{1}" özelliğinde null ya da boş bir dize olmamalıdır. + + + "{0}" türü bulunamadı. Tür adı değeri, türün tam adı olmalıdır. Tür adını doğrulayın ve komutu yeniden çalıştırın. + + + TypeData öğesinde "Members", "TypeConverters", "TypeAdapters" veya "StandardMembers" olmalıdır. + + + Paylaşılan tür tablosu birden fazla girdiyle güncelleştirilemez. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/VerbDescriptionStrings.tr.resx b/src/System.Management.Automation/resources/tr/VerbDescriptionStrings.tr.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/tr/VerbDescriptionStrings.tr.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/tr/WildcardPatternStrings.tr.resx b/src/System.Management.Automation/resources/tr/WildcardPatternStrings.tr.resx new file mode 100644 index 00000000000..2f03044837f --- /dev/null +++ b/src/System.Management.Automation/resources/tr/WildcardPatternStrings.tr.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 + + + Belirtilen joker karakter desen geçersiz: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/Authenticode.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/Authenticode.zh-Hans.resx new file mode 100644 index 00000000000..566009bb305 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/Authenticode.zh-Hans.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 + + + 无法加载文件 {0} ,因为你选择现在不运行此软件。 + + + 无法加载文件 {0},因为你选择从不运行来自此发布者的软件。 + + + 文件 {0} 由 {1} 发布。系统明确不信任此发布者。脚本不会在系统上运行。有关详细信息,请运行命令“get-help about_signing”。 + + + 无法加载文件 {0},因为此系统上已禁用脚本运行。有关详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkID=135170. 处的 about_Execution_Policies。 + + + 无法加载文件 {0}。 {1}。 + + + 无法加载文件 {0} ,因为软件限制策略阻止了其操作,例如通过组策略创建的策略。 + + + 无法加载文件 {0} ,因为无法读取其内容。 + + + 无法对代码进行签名。指定的证书不适用于代码签名。 + + + 无法对代码进行签名。TimeStamp 服务器 URL 必须是完全限定的,格式应为 http://<server url> 或 https://<server url>。 + + + 无法对代码进行签名。不支持哈希算法。 + + + 是否要运行来自此不受信任发布者的软件? + + + 文件 {0} 由 {1} 发布,在你的系统上不受信任。仅运行来自受信任发布者的脚本。 + + + 软件 {0} 由未知发布者发布。建议不要运行此软件。 + + + 安全警告 + + + 仅运行你信任的脚本。来自 Internet 的脚本虽然很有用,但此脚本可能会损害你的计算机。如果你信任此脚本,请使用 Unblock-File cmdlet 允许脚本运行而不显示此警告消息。是否要运行 {0}? + + + 永不运行(&V) + + + 请勿现在运行来自此发布者的脚本,今后也不要提示我运行此脚本。将来尝试运行此脚本将导致无提示失败。 + + + 不运行(&D) + + + 请勿现在运行来自此发布者的脚本,并在以后继续提示我运行此脚本。 + + + 运行一次(&R) + + + 立即运行来自此发布者的脚本,并在以后继续提示我运行此脚本。 + + + 始终运行(&A) + + + 立即运行来自此发布者的脚本,以后不再提示我运行此脚本。 + + + 暂停(&S) + + + 暂停当前管道并返回到命令提示符。完成后,键入 exit 以恢复操作。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/AuthorizationManagerBase.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/AuthorizationManagerBase.zh-Hans.resx new file mode 100644 index 00000000000..16557eb73e4 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/AuthorizationManagerBase.zh-Hans.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 + + + AuthorizationManager 检查失败。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/AutomationExceptions.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/AutomationExceptions.zh-Hans.resx new file mode 100644 index 00000000000..18d6f475628 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/AutomationExceptions.zh-Hans.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 argument because the value of argument "{0}" is not valid. Change the value of the "{0}" argument and run the operation again. + + + Cannot process argument because the value of parameter "{0}" is not valid. Valid values are "Global", "Local", or "Script", or a number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent). Change the value of the "{0}" parameter and run the operation again. + + + Cannot process argument because the value of argument "{0}" is null. Change the value of argument "{0}" to a non-null value. + + + Cannot process argument because the value of argument "{0}" is out of range. Change argument "{0}" to a value that is within range. + + + Cannot perform operation because operation "{0}" is not valid. Remove operation "{0}", or investigate why it is not valid. + + + Cannot perform operation because operation "{0}" is not implemented. + + + Cannot perform operation because operation "{0}" is not supported. + + + Cannot perform operation because object "{0}" has already been disposed. + + + The script block cannot be invoked because it contains more than one clause. The Invoke() method can only be used on script blocks that contain a single clause. + + + The script block cannot be converted because it contains more than one clause. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + An empty script block cannot be converted. Verify that the script block contains exactly one pipeline or command. + + + Only a script block that contains exactly one pipeline or command can be converted. Expressions or control structures are not permitted. Verify that the script block contains exactly one pipeline or command. + + + A script block that contains a top-level trap statement cannot be converted. + + + Cannot generate a PowerShell object for a ScriptBlock dereferencing variables undeclared in the param(...) block. Name of undeclared variable: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating non-constant expressions. Non-constant expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock evaluating dynamic expressions. Dynamic expression: {0}. + + + Cannot generate a PowerShell object for a ScriptBlock that tries to pass other script blocks inside argument values. + + + Cannot generate a PowerShell object for a ScriptBlock which invokes pipelines, commands or functions to evaluate arguments of the main pipeline. + + + Cannot generate a PowerShell object for a ScriptBlock that uses dot sourcing. + + + Cannot generate a PowerShell object for a ScriptBlock that invokes other script blocks. + + + The script block cannot be converted to a PowerShell object because it contains forbidden redirection operators. + + + Cannot generate a PowerShell object for a ScriptBlock that does not have an associated operation context. + + + The command was stopped by the user. + + + Object "{0}" is the wrong type to return from the dynamicparam block. The dynamicparam block must return either $null, or an object with type [System.Management.Automation.RuntimeDefinedParameterDictionary]. + + + The script block cannot be converted to an open generic type. Define an appropriate closed generic type, and then retry. + + + Cannot generate a PowerShell object for a ScriptBlock that starts a pipeline with an expression. + + + The value of the using variable '$using:{0}' cannot be retrieved because it has not been set in the local session. + + + Cannot get the value of the Using expression '{0}' in the specified variable dictionary. When creating a PowerShell instance from a script block, the Using expression cannot contain an indexing operation or member-accessing operation. + + + Compiled Script Block Dot Source + + + Script block '{0}' invocation into current scope will be disallowed in Constrained Language mode. Script language mode: {1}, Context language mode: {2}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CatalogStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CatalogStrings.zh-Hans.resx new file mode 100644 index 00000000000..11254c168a6 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CatalogStrings.zh-Hans.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法生成目录定义文件。 + + + 正在将文件“{0}”添加到目录。目录中文件的相对路径为“{1}”。 + + + 正在跳过验证目录中的文件 {0}。 + + + 在目录中找到哈希为 {1} 的文件 {0}。 + + + 目录的路径包含多个相对路径 {0} 相同的文件。 + + + 在磁盘上找到哈希为 {1} 的文件 {0}。 + + + 正在跳过验证路径中的文件 {0}。 + + + 无法获取给定哈希算法 {0} 的目录管理员上下文的句柄。 + + + 无法为文件 {0} 创建哈希。 + + + 无法打开目录文件 {0}。 + + + 目录版本无效。我们仅支持目录版本 {0} 和版本 {1}。 + + + 无法打开目录定义文件。 + + + 在目录中找到文件成员 {0} 的多个条目。 + + + 找不到目录成员 {0} 的文件名或路径。 + + + 找不到要进行哈希处理的文件 {0}。 + + + 无法读取文件 {0} 以计算其哈希。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CimInstanceTypeAdapterResources.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CimInstanceTypeAdapterResources.zh-Hans.resx new file mode 100644 index 00000000000..a6a7ca95072 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CimInstanceTypeAdapterResources.zh-Hans.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法将“{0}”转换为类型为“{1}”的对象。 + + + “{0}”是 ReadOnly 属性。 + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CmdletizationCoreResources.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CmdletizationCoreResources.zh-Hans.resx new file mode 100644 index 00000000000..59cc6af640c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CmdletizationCoreResources.zh-Hans.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 基于“{0}”类的 Cmdlet + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + 无法处理以下文件的 Cmdlet 定义 XML: {0}。{1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + 无法处理 ObjectModelWrapper 属性。{0} 类型可定义多个参数集。验证 Cmdlet 定义 XML 是否在 ObjectModelWrapper 属性中指定了有效类型,然后重试。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + 无法处理 ObjectModelWrapper 属性。{0} 类型为开放泛型类型。 验证 Cmdlet 定义 XML 是否在 ObjectModelWrapper 属性中指定了有效类型,然后重试。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + 无法处理 ObjectModelWrapper 属性。{0} 类型不是从以下类派生的: {1}。 验证 Cmdlet 定义 XML 是否在 ObjectModelWrapper 属性中指定了有效类型,然后重试。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + 无法处理 ObjectModelWrapper 属性。{0} 类型使用被忽略的 {2} 特性参数定义 cmdlet 参数 {1}。 验证 Cmdlet 定义 XML 是否在 ObjectModelWrapper 属性中指定了有效类型,然后重试。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + 无法定义 {1} cmdlet 的 {0} 参数。 参数名称已由 {2} 类定义。 在 Cmdlet 定义 XML 中更改参数的名称,然后重试。 + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + 无法定义 {1} cmdlet 的 {0} 参数。参数名称已在 {2} XML 元素中定义。在 Cmdlet 定义 XML 中更改参数的名称,然后重试。 + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + EnumName 属性的值未转换为有效的 C# 标识符: {0}。验证 Cmdlet 定义 XML 中的 EnumName 属性,然后重试。 + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + 无法处理 <Enum EnumName="{0}" ...> 元素。{1} + {StrContains="Enum"} {StrContains="EnumName"} + + + 远程计算机返回的 CDXML 文件无效。不支持以下 cmdlet 适配器从远程计算机导入 CDXML 模块: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CommandBaseStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CommandBaseStrings.zh-Hans.resx new file mode 100644 index 00000000000..8e2c977e3f8 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CommandBaseStrings.zh-Hans.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 继续执行此操作? + + + 是(&Y) + + + 仅继续执行操作的下一步。 + + + 全是(&A) + + + 继续执行操作的所有步骤。 + + + 否(&N) + + + 跳过此操作并继续执行下一个操作。 + + + 全否(&L) + + + 跳过此操作和所有后续操作。 + + + 停止此命令。 + + + 停止命令(&H) + + + 暂停(&S) + + + 暂停当前管道并返回到命令提示符。键入“{0}”以恢复管道。 + + + + 程序“{0}”以非零退出代码结束: {1} ({2})。 + + + 正在对目标“{1}”执行操作“{0}”。 + + + What if: {0} + + + 是否确实要执行此操作? +{0} + + + 确认 + + + 已停止正在运行的命令,因为首选变量“{0}”或通用参数设置为“停止”: {1} + + + 已停止正在运行的命令,因为首选变量“{0}”或通用参数设置为“停止”。 + + + 已停止正在运行的命令,因为首选变量“{0}”或通用参数设置以下无效值:“{1}”。 + + + 已停止正在运行的命令,因为用户选择了“停止”选项。 + + + 已停止正在运行的命令,因为用户中断了该命令。 + + + 无法直接调用派生自 PSCmdlet 的 Cmdlet。 + + + Cmdlet“{0}”不支持远程会话中的参数“{1}”。 + + + 总计: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + 估计总计数: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + 总计数未知 + Reviewed by TArcher on 2010-07-20 + + + 命令“{0}” + + + {0} 已过时。{1} + + + 对以下命令行的执行调用失败,errorno 为 {0}: {1} + + + 找不到命令“{0}”。指定的命令必须是可执行的。 + + + 脚本块处理点源检查 + + + 脚本块“{0}”的点源处理将会在受约束语言模式下失败,因为其语言模式“{1}”与当前语言模式“{2}”不匹配。 + + + 命令搜索器 + + + 模块“{1}”中的命令“{0}”不受信任,无法在 ConstrainedLanguage 模式下访问。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ConsoleInfoErrorStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ConsoleInfoErrorStrings.zh-Hans.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ConsoleInfoErrorStrings.zh-Hans.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CoreClrStubResources.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CoreClrStubResources.zh-Hans.resx new file mode 100644 index 00000000000..f62e94c0e7e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CoreClrStubResources.zh-Hans.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 环境变量名不能包含等号字符。 + + + 环境变量名称或值太长。 + + + 字符串中的第一个字符是空字符。 + + + 字符串长度不能为零。 + + + 无法获取计算机名称。 + + + 无法获取当前用户的域名。 + + + 未知错误: {0}。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CredUI.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CredUI.zh-Hans.resx new file mode 100644 index 00000000000..0d298a33da6 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CredUI.zh-Hans.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell 凭据请求 + + + 输入凭据。 + + + 输入凭据。 + + + 字幕的最大长度为 {0} 个字符。 + + + 消息的最大长度为 {0} 个字符。 + + + UserName 值的最大长度为 {0} 个字符。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/Credential.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/Credential.zh-Hans.resx new file mode 100644 index 00000000000..913b5fdfa02 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/Credential.zh-Hans.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 + + + 无法序列化凭据。如果此命令正在启动工作流,则无法保留凭据,因为启动工作流的进程没有序列化凭据的权限。 + +-- 如果工作流是在本地计算机的 PSSession 中启动的,请将 EnableNetworkAccess 参数添加到创建该会话的命令中。 +-- 如果工作流是在远程计算机的 PSSession 中启动的,请将值为 CredSSP 的身份验证参数添加到创建会话的命令。-- 或者,连接到具有 RunAsUser 属性值的会话配置。 + + + UserName 的值格式不正确。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/CredentialAttributeStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/CredentialAttributeStrings.zh-Hans.resx new file mode 100644 index 00000000000..3d89c3dd023 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/CredentialAttributeStrings.zh-Hans.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 + + + PowerShell 凭据请求 + + + 输入凭据。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/DebuggerStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/DebuggerStrings.zh-Hans.resx new file mode 100644 index 00000000000..9025e64338e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/DebuggerStrings.zh-Hans.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + “${0}”上的变量断点({1} 访问) + + + “{0}:${1}”上的变量短点({2} 访问) + + + “{0}:{1}”上的行断点 + + + “{0}:{1}”上的行断点,{2} + + + “{0}”上的命令断点 + + + “{0}:{1}”上的命令断点 + + + 不会命中断点 {0} + + + {0},{1,-16} 单步执行(步入函数、脚本等) + + + {0},{1,-16} 单步执行下一个语句(步过函数、脚本等) + + + {0},{1,-16} 跳出当前函数、脚本等。 + + + {0},{1,-16} 继续操作 + + + {0},{1,-16} 停止操作并退出调试程序 + + + {0},Get-PSCallStack 显示调用堆栈 + + + {0},{1,-16} 列出当前脚本的源代码。 + + + 使用 “list” 从当前行开始,使用 “list <m>” 则从 <m> 开始 + + + 以从行 <m> 开始,并执行 “list <m> <n>” 以列出 <n> + + + 从行 <m> 开始的行 + + + <enter> 如果为它为 {0}、{1} 或 {2},则重复上一个命令 + + + {0},{1,-16} 显示此帮助消息。 + + + 有关如何自定义调试程序提示的说明,请键入 “help about_prompt”。 + + + +当前会话不支持调试;操作将继续。 + + + + + {0}: 行 {1} + + + 没有可用的源代码。 + + + 起始行必须是不大于 {0} 的正整数 + + + 行计数必须是正整数。 + + + <No file> + + + 位于 {0},{1}: 行 {2} + + + 调试程序无法处理命令,除非它处于“已停止”状态。 + + + 未针对本地脚本调试程序实现 SetDebugAction。 + + + 调试程序无法设置恢复操作,因为远程会话中的调试程序未处于“已停止”状态。 + + + 无法调试作业,因为调试程序当前正忙。 + + + 已检查提供的作业和所有子作业,但未找到可调试的作业。 要调试作业或子作业,作业必须支持调试,并且还必须处于运行状态。 + + + 无法在单步模式下启用调试程序,因为调试程序处于关闭状态,并且调试模式设置为“无”。 + + + 无法调试运行空间,因为主机调试程序当前正忙。 + + + 无法调试运行空间。运行空间调试程序当前已关闭(DebugMode 为“无”)。 + + + 无法调试未处于“已打开”状态的运行空间。此运行空间状态为 {0}。 + + + 无法调试运行空间。运行空间 {0} 没有关联的调试程序。 + + + 已替代调试程序。 + + + 无法将调试程序对象推送到其自身。 + + + 在远程运行空间中运行的 PowerShell 版本不支持远程使用 {0} 命令。 + + + 进程 + + + {0},{1,-16} 继续执行操作并分离调试程序。 + + + 调试程序分离命令不适用。 分离命令仅适用于使用 Debug-Job 或 Debug-Runspace cmdlet 调试作业和运行空间的情况。 + + + 无效的运行空间 ID: {0} + + + 无法获取运行空间。 + + + 必须指定断点或 BreakpointList。 + + + BreakpointList 包含了不是断点的项。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/DescriptionsStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/DescriptionsStrings.zh-Hans.resx new file mode 100644 index 00000000000..4737ee11e8e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/DescriptionsStrings.zh-Hans.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 + + + {0} 不能为 NULL 或为空。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/DiscoveryExceptions.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/DiscoveryExceptions.zh-Hans.resx new file mode 100644 index 00000000000..de7a4ea8951 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/DiscoveryExceptions.zh-Hans.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 + + + 无法验证 cmdlet 名称 "{0}",因为其格式不正确。cmdlet 名称必须包含一个动词和一个名词,且它们之间用 "-" 分隔,例如 "Get-Process"。 + + + 在参数集 "{1}" 中多次声明了参数 "{0}"。 + + + 多次声明了别名 "{0}"。 + + + 无法声明参数。只能在字段和属性上声明参数。 + + + 无法处理该 cmdlet。cmdlet 名称必须由用 '-' 分隔的动词和名词组成。 + + + 术语 '{0}' 不会被识别为 cmdlet、函数、脚本文件或可执行程序的名称。 +请检查名称的拼写或验证路径是否正确(如果包含路径),然后重试。 + + + 自变量 '{0}' 未被识别为 cmdlet: {1} + + + 自变量 '{0}' 未被识别为 cmdlet,这可能是因为它并非派生自 Cmdlet 或 PSCmdlet 类: {1} + + + 无法解析别名 '{0}',因为它引用了术语 '{1}',而该术语不会被识别为 cmdlet、函数、可执行程序或脚本文件。请验证该术语,然后重试。 + + + 无法处理值为 '{1}' 的参数 '{0}',因为它不是 cmdlet,无法由 CommandProcessor 处理。 + + + 名为 '{0}' 的 cmdlet 已存在。Cmdlet 必须具有唯一名称。 + + + 名为 '{0}' 的 cmdlet 提供程序已存在。cmdlet 提供程序必须具有唯一名称。 + + + 名为 '{0}' 的程序集已存在。程序集必须具有唯一名称。 + + + 名为 '{0}' 的脚本已存在。脚本必须具有唯一名称。 + + + 无法处理 #requires 语句,因为其格式不正确。 +#requires 语句必须采用以下格式之一: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + 无法运行脚本 '{0}',因为它包含 shell ID 为 {1} 且与当前 shell 不兼容的 "#requires" 语句。若要运行此脚本,必须使用位于 '{2}' 的 shell。 + + + 无法运行脚本 '{0}',因为它包含 shell ID 为 {1} 且与当前 shell 不兼容的 "#requires" 语句。 + + + 无法运行脚本 '{0}',因为它包含 PowerShell {1} 的 "#requires" 语句。该脚本所需的 PowerShell 版本与当前运行的 PowerShell 版本 {2} 不匹配。 + + + 无法运行脚本 '{0}',因为它包含 PowerShell 版本 '{1}' 的 "#requires" 语句。该脚本所需的 PowerShell 版本与当前运行的 PowerShell {2} 版本不匹配。 + + + 无法运行脚本 '{0}',因为该脚本的 "#requires" 语句指定了以下缺失管理单元: {1}。 + + + #requires 语句仅指定了 shellID。在 PowerShell 中运行时,#Requires 语句必须指定所需的 PowerShell 管理单元。 + + + 脚本 '{0}' 无法运行,因为它包含用于以管理员身份运行的 "#requires" 语句。当前 PowerShell 会话并非以管理员身份运行。请使用“以管理员身份运行”选项启动 PowerShell,然后再次尝试运行该脚本。 + + + {0} (版本 {1}) + + + 无法检索该命令,因为只有在检索单个 cmdlet 或脚本时才能指定 ArgumentList 参数。 + + + 已保留参数名称 "{0}" 以供将来使用。 + + + 无法运行脚本 '{0}',因为该脚本的 "#requires" 语句指定了以下缺失模块: {1}。 + + + 在模块 '{1}' 中找到了 '{0}' 命令,但无法加载该模块。有关详细信息,请运行 'Import-Module {1}'。 + + + 在模块 '{1}' 中找到了 '{0}' 命令,但由于以下错误而无法加载该模块: [{2}] +有关详细信息,请运行 'Import-Module {1}'。 + + + 无法加载模块 '{0}'。有关详细信息,请运行 'Import-Module {0}'。 + + + 没有匹配的命令包含名为 '{0}' 的参数。 请检查参数名称的拼写,然后重试。 + + + 无法使用点号加载此命令,因为它是在不同的语言模式下定义的。若要调用此命令而不导入其内容,请省略 '.' 运算符。 + + + 不能同时指定 ShowCommandInfo 和 Syntax 参数。 + + + 启用实验性功能 '{0}' 时,将禁用此脚本命令。 + + + 禁用实验性功能 '{0}' 时,将禁用此脚本命令。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/EnumExpressionEvaluatorStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/EnumExpressionEvaluatorStrings.zh-Hans.resx new file mode 100644 index 00000000000..f7ea564f749 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/EnumExpressionEvaluatorStrings.zh-Hans.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 输入表达式不得为空。请在每个输入表达式中至少指定一个标识符名称。 + + + 无法将空标识符名称与有效的枚举器名称匹配。请指定以下其中一个枚举器名称并重试: {0}。 + + + 为表达式指定的泛型类型必须表示枚举。请指定有效的枚举类型。 + + + 无法处理标识符名称 {0},因为它与以下枚举器名称过于相似或完全相同: {1}。请使用更具体的标识符名称。 + + + 无法将标识符名称 {0} 与有效的枚举器名称匹配。请指定以下其中一个枚举器名称并重试: +{1} + + + 表达式中不能使用括号,因为不允许将标识符分组。请尝试删除括号;如果括号包围的是子表达式,请尝试展开该表达式。 + + + 由于出现意外标记,无法分析表达式。标识符名称后只能使用 OR (,)运算符或 AND (+)运算符。 + + + 由于 NOT (!)运算符出现意外标记,无法分析表达式。NOT (!)运算符后应为标识符名称。 + + + 由于出现意外标记,无法分析表达式。在表达式开头,或在 OR (,)运算符或AND (+)运算符之后,表达式必须以标识符名称或 NOT (!)运算符开头。此外,表达式不能以 OR (,)、AND (+)或 NOT (!)运算符结尾。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ErrorCategoryStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ErrorCategoryStrings.zh-Hans.resx new file mode 100644 index 00000000000..41f61a889c5 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ErrorCategoryStrings.zh-Hans.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Deadlock detected: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3} + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Unrecognized error category {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ErrorPackage.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ErrorPackage.zh-Hans.resx new file mode 100644 index 00000000000..2976f3a0a34 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ErrorPackage.zh-Hans.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 + + + {0}…{1} + + + 错误“{0}”的错误文本为空: “{1}” + + + 对象“{0}”报告为错误。 + + + ActionPreference 变量不支持值 {0}。提供的值应仅用作首选项参数的值,并且已替换为默认值。有关详细信息,请参阅帮助主题 "about_Preference_Variables"。 + + + {0} ActionPreference 值将保留以供将来使用,目前不受支持。有关首选项变量的详细信息,请参阅帮助主题 "about_Preference_Variables"。 + + + {0} ActionPreference 值将保留以供将来使用,目前不受支持。它已在你的 {1} 变量中替换为默认值 {2}。有关首选项变量的详细信息,请参阅帮助主题 "about_Preference_Variables"。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/EtwLoggingStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/EtwLoggingStrings.zh-Hans.resx new file mode 100644 index 00000000000..962691d1fbe --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/EtwLoggingStrings.zh-Hans.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 命令 {0} 为 {1}。 + + + 引擎状态已从“{0}”更改为“{1}”。 + + + 完全限定错误 ID = {0} + + + 错误消息 = {0} + + + 建议的操作 = {0} + + + 执行策略 + + + 作业命令 = {0} + + + 作业 ID = {0} + + + 作业实例 ID = {0} + + + 作业位置 = {0} + + + 作业名称 = {0} + + + 作业状态 = {0} + + + 命令名称 = + + + 命令路径 = + + + 命令类型 = + + + 引擎版本 = + + + 主机 ID = + + + 主机名 = + + + 主机应用程序 = + + + 主机版本 = + + + 管道 ID = + + + 运行空间 ID = + + + 脚本名称 = + + + 序列号 = + + + 严重性 = + + + Shell ID = + + + 时间 = + + + 用户 = + + + 已连接的用户 = + + + NULL 作业 + + + 提供程序名称 + + + 提供程序 {0} 状态已更改为“{1}”。 + + + 脚本执行为 {0}。 + + + 变量“{0}”已从“{1}”更改为“{2}”。 + + + 变量 {0} 已更改为“{1}”。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/EventResource.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/EventResource.zh-Hans.resx new file mode 100644 index 00000000000..6cbec7023a5 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/EventResource.zh-Hans.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 未找到事件 ID PowerShell.Core.Instrumentation.man 的消息。 + + + 计划作业 {0} 已于 {1}开始 + + + + 计划作业 {0} 已于 {1}完成,状态为 {2} + + + + 计划作业异常 {0}: + 消息: {1} + StackTrace: {2} + InnerException: {3} + + + + 实验性功能初始化: 忽略配置文件中的实验性功能 '{0}'。{1} + + + 实验性功能初始化: 未能读取配置文件。 + 异常: {0} + 消息: {1} + StackTrace: {2} + + + + 已加载工作流插件。 + EndpointName: {0} + 用户: {1} + HostingMode: {2} + 协议: {3} + 配置: + {4} + + + 工作流执行已开始。 + WorkflowId: {0} + ManagedNodes: {1} + + + 已更改工作流状态。 + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + 已请求关闭工作流插件。 + EndpointName: {0} + + + 已重启工作流插件。 + EndpointName: {0} + + + 正在恢复工作流。 + WorkflowId: {0} + + + 已超出为终结点设置的配额限制。 + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + 工作流已恢复。 + WorkflowId: {0} + + + 已创建工作流运行空间池。 + WorkflowId: {0} + ManagedNode: {1} + + + 活动已排队等待执行。 + WorkflowId: {0} + ActivityName: {1} + + + 活动执行已开始。 + ActivityName: {0} + ActivityTypeName: {1} + + + 正在从 XAML 文件导入工作流。 + WorkflowId: {0} + XamlFile: {1} + + + 已从 XAML 文件导入工作流。 + WorkflowId: {0} + XamlFile: {1} + + + 由于出现错误,无法从 XAML 文件导入工作流。 + WorkflowId: {0} + ErrorDescription: {1} + + + 已启动工作流验证。 + WorkflowId: {0} + + + 工作流验证成功。 + WorkflowId: {0} + + + 工作流验证失败,出现错误。 + WorkflowId: {0} + + + 已验证工作流活动。 + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + 无法验证工作流活动。 + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + 活动执行失败。 + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + 运行空间可用性已更改。 + RunspaceId: {0} + 可用性: {1} + + + 已更改运行空间状态。 + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + 已加载工作流以供执行。 + WorkflowId: {0} + + + 已卸载工作流。 + WorkflowId: {0} + + + 工作流执行已取消。 + WorkflowId: {0} + + + 工作流执行已中止。 + WorkflowId: {0} + + + 已执行工作流清理操作。 + WorkflowId: {0} + + + 已从磁盘加载持久化工作流。 + WorkflowId: {0} + 路径: {1} + + + 已从磁盘中删除工作流数据。 + WorkflowId: {0} + 路径: {1} + + + 正在开始移除作业。 + JobId: {0} + + + 已更改作业状态。 + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + 作业错误。 + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + 已为工作流创建作业(子作业)。 + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + 已为工作流创建父作业。 + JobId: {0} + + + 已创建执行工作流所需的所有作业。 + JobId: {0} + WorkflowId: {1} + + + 已为工作流移除子作业。 + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + 移除作业时出错。 + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + 错误: {3} + + + 正在加载工作流以供执行。 + WorkflowId: {0} + + + 工作流执行已完成。 + WorkflowId: {0} + + + 正在取消工作流执行。 + WorkflowId: {0} + + + 正在中止工作流执行。 + WorkflowId: {0} + 原因: {1} + + + 正在卸载工作流。 + WorkflowId: {0} + + + 强制工作流关闭已开始。 + WorkflowId: {0} + + + 强制工作流关闭已完成。 + WorkflowId: {0} + + + 强制关闭工作流时出错。 + WorkflowId: {0} + ErrorDescription: {1} + + + 正在将工作流持久保存到磁盘。 + WorkflowId: {0} + PersistPath: {1} + + + 已将工作流持久保存到磁盘。 + WorkflowId: {0} + + + 活动执行已完成。 + ActivityName: {0} + + + 工作流执行错误。 + WorkflowId: {0} + ErrorDescription: {1} + + + 已注册新的 PowerShell 终结点。 + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + 已修改终结点配置。 + EndpointName: {0} + ModifiedBy: {1} + + + 终结点配置已注销。 + EndpointName: {0} + UnregisteredBy: {1} + + + 已禁用终结点配置。 + EndpointName: {0} + DisabledBy: {1} + + + 已启用终结点配置。 + EndpointName: {0} + EnabledBy: {1} + + + 已启动进程外运行空间。 + 命令: {0} + + + 在工作流执行期间执行了参数展开。 + 参数: {0} + 计算机: {1} + + + 已启动工作流引擎。 + EndpointName: {0} + + + 工作流管理器已使用以下值实例化 + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + Path: {3} + + + 计算机名称 $null 或 . 解析为 LocalHost + + + 正在解析为默认方案 http + + + 远程 shell 名称已解析为默认 PowerShellCore + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + 正在创建脚本块文本({0}/{1}): +{2} + +ScriptBlock ID: {3} +路径: {4} + + + 已开启对 ScriptBlock ID 的调用: {0} +运行空间 ID: {1} + + + 已完成对 ScriptBlock ID 的调用: {0} +运行空间 ID: {1} + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + {2} + +上下文: +{0} + +用户数据: +{1} + + + + 正在关联活动 ID。 + CurrentActivityId: {0} + ParentActivityId: {1} + + + 类名 = {0} +方法名称 = {1} +工作流 GUID = {2} +消息 = {3} +{4} +活动名称 = {5} +活动 GUID = {6} +参数 = {7} + + + 正在创建 Runspace 对象 + 实例 ID: {0} + + + 正在创建 RunspacePool 对象 + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + 正在打开 RunspacePool + + + 正在修改活动 ID 并建立关联 + + + 运行空间状态已更改为 {0} + + + 正在尝试为会话 ID {2} 上的错误代码 {1} 进行第 {0} 次会话创建重试 + + + PowerShell 已在 AppDomain {1} 中的进程 {0} 上开启 IPC 侦听线程。 + + + PowerShell 已在 AppDomain {1} 中的进程 {0} 上结束 IPC 侦听线程。 + + + 在 PowerShell IPC 侦听线程中,AppDomain {1} 中的进程 {0} 上发生错误。 错误消息: {2}。 + + + PowerShell IPC 在 AppDomain {1} 中的进程 {0} 上为用户 {2} 建立连接。 + + + PowerShell IPC 在 AppDomain {1} 中的进程 {0} 上为用户 {2} 断开连接。 + + + 端口已解析为 {0} + + + AppName 已解析为 {0} + + + ComputerName 已解析为 {0} + + + 方案为 {0} + + + 测试分析消息 + + + 连接参数包括 + Connection URI: {0} + Resource URI: {1} + User: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Thumb Print: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + 正在修改活动 ID 并建立关联 + + + 已接收的对象,该对象的运行空间 ID: {0} 命令 ID: {1} 目标: {2} DataType: {3} TargetInterface: {4} + + + appdomain 中发生未经处理的异常。 +异常类型: {0} +异常消息: {1} +异常 StackTrace: {2} + + + 运行空间 ID: {0} 管道 ID: {1}。WSMan 报告了一个错误,错误代码为: {2}。 + 错误消息: {3} + StackTrace: {4} + + + appdomain 中发生未经处理的异常。 +异常类型: {0} +异常消息: {1} +异常 StackTrace: {2} + + + 运行空间 ID: {0} 管道 ID: {1}。WSMan 报告了一个错误,错误代码为: {2}。 + 错误消息: {3} + StackTrace: {4} + + + 运行空间 ID {0}。正在使用 WSMan Create Shell 建立连接 + + + 运行空间 ID {0}。已收到 WSMan Create Shell 的回叫 + + + 运行空间 ID: {0}。正在使用 WSManCloseShell 关闭 shell + + + 运行空间 ID: {0}。已收到 WSManCloseShell 的回叫 + + + 运行空间 ID: {0} 管道 ID: {1}。正在发送大小为 {2} 的数据 + + + 运行空间 ID: {0} 管道 ID: {1}。已收到 WSManSendShellInputEx 的回叫 + + + 运行空间 ID: {0} 管道 ID: {1}。正在使用 WSManReceiveShellOutputEx 发送接收请求 + + + 运行空间 ID: {0} 管道 ID: {1}。已接收大小为 {2} 的数据。 + + + 运行空间 ID {0} 管道 ID {1}。正在使用 WSManRunShellCommandEx 建立命令连接 + + + 运行空间 ID {0} 管道 ID {1}。已收到命令连接的回叫 + + + 运行空间 ID: {0} 管道 ID {1}。正在关闭命令的传输 + + + 运行空间 ID: {0} 管道 ID {1}。已收到命令关闭的回叫 + + + 运行空间 ID: {0} 管道 ID {1}。正在使用 WSManSignalShellEx 来通过代码 {2} 发送信号 + + + 运行空间 ID: {0} 管道 ID {1}。已收到 WSManSignalShellEx 的回叫 + + + 运行空间 ID: {0}。连接正在重定向到 URI: {1} + + + 运行空间 ID: {0} 管道 ID: {1}。服务器正在向客户端发送大小为 {2} 的数据。DataType: {3} TargetInterface: {4} + + + 请求 {0}。正在创建服务器远程会话。UserName: {1} 自定义 Shell ID: {2} + + + 正在报告请求的上下文: {0} 已报告的上下文: {0} + + + 针对请求 {0} 的报告操作已完成 + 错误代码: {1} + 错误消息: {2} + StackTrace: {3} + + + Shell 上下文 {0}。请求 ID {1}。正在创建用于运行命令的命令会话。 + + + Shell 上下文 {0} 命令上下文 {1} 请求 ID {2}。停止命令。 + + + Shell 上下文 {0} 命令上下文 {1} 请求 ID {2}。已收到来自客户端的数据。 + + + Shell 上下文 {0} 命令上下文 {1} 请求 ID {2}。客户端发送了接收请求,以便服务器可以发送数据。 + + + Shell 上下文 {0} 命令上下文 {1} IsReceiveOperation {2}。已收到关闭操作请求。 + + + 正在加载 shell ID 为 {1} 的自定义 shell 的程序集 {0} + + + 正在为 shell ID 为 {1} 的自定义 shell 加载类型 {0} + + + 已收到远程处理片段。 + 对象 ID: {0} + 片段 ID: {1} + 起始标志: {2} + 结束标志: {3} + 有效负载长度: {4} + 有效负载数据: {5} + + + 已发送远程处理片段。 + 对象 ID: {0} + 片段 ID: {1} + 起始标志: {2} + 结束标志: {3} + 有效负载长度: {4} + 有效负载数据: {5} + + + 正在关闭 WinRM 服务。 + + + 已成功解除冻结对象。 + 反序列化类型名称: {0} + 通过强制转换为类型 {1} 解除冻结 + 解除冻结的对象的类型为: {2} + + + 未能解除冻结对象。 + 反序列化类型名称: {0} + 通过强制转换为类型 {1} 解除冻结 + 类型强制转换异常: {2} + 类型强制转换内部异常: {3} + + + 已覆盖序列化深度。 + 序列化类型名称: {0} + 原始深度: {1} + 覆盖后的深度: {2} + 顶层以下的当前深度: {3} + + + 已覆盖序列化模式。 + 序列化类型名称: {0} + 覆盖后的模式: {1} + + + 已跳过脚本属性的序列化,因为没有可用于计算属性的运行空间。 + 属性名称: {0} + 属性所有者的类型名称: {1} + Getter 脚本: {2} + + + 已跳过属性序列化,因为属性 getter 失败。 + 属性名称: {0} + 属性所有者的类型名称: {1} + 来自属性 getter 的异常: {2} + 来自属性 getter 的内部异常: {3} + + + 可能无法完成可枚举对象的序列化,因为枚举的对象引发了异常。 + 正在枚举的对象的类型: {0} + 异常: {1} + + + 序列化调用了对象的 ToString 方法,但该方法失败。 + 对象类型: {0} + 异常: {1} + + + 已达到顶层以下的最大深度,正在强制将对象序列化为字符串。 + 最大深度处的对象类型: {0} + 最大深度处的属性名称: {1} + 深度: {2} + + + 反序列化程序引发了 XmlException(很可能表明 clixml 格式不正确)。 + 行号: {0} 行位置: {1} + 异常:{2} + + + 指定属性的序列化失败,因为指定的某个属性缺失。 + 对象类型: {0} + 属性名称: {1} + + + 正在启动 PowerShell 控制台 + + + PowerShell 控制台已准备好接受用户输入 + + + {0} + + + 跟踪错误记录: + 消息: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + 异常详细信息: + 消息 : {5} + 堆栈跟踪: {6} + InnerException {7} + + + + 异常: + 消息: {0} + StackTrace: {1} + InnerException : {2} + + + + 跟踪 PSObject + + + 跟踪作业: + ID: {0} + InstanceId: {1} + 名称: {2} + 位置: {3} + 状态: {4} + 命令: {5} + + + + 跟踪信息: + {0} + + + 跟踪信息: + {0} {1} + + + 开始 ImportWorkflowCommand::StartWorkflowApplication。正在开始工作流函数的调用。跟踪 Guid {0} + + + 结束 ImportWorkflowCommand::StartWorkflowApplication。正在结束工作流函数的调用。跟踪 Guid {0} + + + 开始在 ImportWorkflowCommand::StartWorkflowApplication 中创建新作业。跟踪 Guid {0} + + + 结束在 ImportWorkflowCommand::StartWorkflowApplication 中创建新作业。跟踪 Guid {0} + + + 结束在 ImportWorkflowCommand::StartWorkflowApplication 中创建新作业。跟踪 Guid {0} : ContainerParentJob Guid {1} + + + 开始 JobLogic ContainerParentJob Guid {0} + + + 结束 JobLogic ContainerParentJob Guid {0} + + + 开始 WorkflowExecution ContainerParentJob Guid {0} + + + 结束 WorkflowExecution ContainerParentJob Guid {0} + + + 已将 Guid 为 {0} 的 WorkflowJob 添加到 Guid 为 {1} 的 ContainerParentJob + + + Guid 为 {0} 的 ProxyJob 与 Guid 为 {1} 的远程 ContainerParentJob 关联 + + + 开始 Guid 为 {0} 的 ContainerParentJob 执行 + + + 结束 Guid 为 {0} 的 ContainerParentJob 执行 + + + 开始 Guid 为 {0} 的代理作业执行 + + + 结束 Guid 为 {0} 的代理作业执行 + + + 开始 Guid 为 {0} 的代理作业的 StateChanged 事件处理程序 + + + 结束 Guid 为 {0} 的代理作业的 StateChanged 事件处理程序 + + + 开始 Guid 为 {0} 的代理子作业的 StateChanged 事件处理程序 + + + 结束 Guid 为 {0} 的代理子作业的 StateChanged 事件处理程序 + + + 开始运行垃圾回收 + + + 结束运行垃圾回收 + + + 持久性存储已达到指定的最大大小 + + + Windows PowerShell ISE 已开始运行脚本文件 {0}。 + + + Windows PowerShell ISE 已开始从文件 {0} 运行用户选择的脚本。 + + + Windows PowerShell ISE 正在停止当前命令。 + + + Windows PowerShell ISE 正在恢复调试程序。 + + + Windows PowerShell ISE 正在停止调试程序。 + + + Windows PowerShell ISE 正在进入调试过程。 + + + Windows PowerShell ISE 正在跳过调试过程。 + + + Windows PowerShell ISE 正在退出调试过程。 + + + Windows PowerShell ISE 将启用所有断点。 + + + Windows PowerShell ISE 将禁用所有断点。 + + + Windows PowerShell ISE 正在移除所有断点。 + + + Windows PowerShell ISE 正在为文件 {1} 的第 {0} 行设置断点。 + + + Windows PowerShell ISE 正在为文件 {1} 的第 {0} 行移除断点。 + + + Windows PowerShell ISE 正在为文件 {1} 的第 {0} 行启用断点。 + + + Windows PowerShell ISE 正在为文件 {1} 的第 {0} 行禁用断点。 + + + Windows PowerShell ISE 已在文件 {1} 的第 {0} 行命中断点。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/EventingResources.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/EventingResources.zh-Hans.resx new file mode 100644 index 00000000000..65cc0a24d5d --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/EventingResources.zh-Hans.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}' 的事件不存在。 + + + PowerShell 无法订阅 Windows RT 事件。 + + + 无法注册指定的事件。已为 PowerShell 引擎保留事件源标识符 '{0}'。 + + + 远程实例不支持此操作。 + + + 在转发事件时,不支持此操作。 + + + 无法订阅指定事件。源标识符为 '{0}' 的订阅者已存在。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ExperimentalFeatureStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ExperimentalFeatureStrings.zh-Hans.resx new file mode 100644 index 00000000000..e3f5baa4350 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ExperimentalFeatureStrings.zh-Hans.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}”匹配的实验性功能。 + + + 启用和禁用实验性功能将在下次启动 PowerShell 时生效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ExtendedTypeSystem.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ExtendedTypeSystem.zh-Hans.resx new file mode 100644 index 00000000000..f4707e3d69c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ExtendedTypeSystem.zh-Hans.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 成员 {0} 已存在。 + + + 扩展类型数据文件中已存在成员“{0}”。 + + + 成员“{0}”不存在。 + + + 设置“{0}”时出现异常:“{1}” + + + 获取“{0}”时出现异常:“{1}” + + + 尝试枚举集合时发生以下异常:“{0}”。 + + + 无法访问 PSObject 外部的成员“{0}”。 + + + 无法更改从类型配置创建的成员:“{0}”。 + + + 成员名称“{0}”为保留名称。 + + + 无法更改“{0}”。 + + + 调用“{0}”并传入“{1}”个参数时发生异常:“{2}” + + + 尝试调用“{0}”以提取类型为“{1}”的对象的内容时引发了异常:“{2}” + + + 找不到“{0}”的参数计数为“{1}”的重载。 + + + 对于类型参数“{0}”和参数计数“{1}”的“{2}”,找不到合适的泛型方法重载。 + + + 为“{0}”和参数计数“{1}”找到了多个不明确的重载。 + + + 无法将参数“{0}”转换为类型“{1}”,其值为“{2}”,用于“{3}”:“{4}” + + + 属性“{0}”的 Get 访问器不可用。 + + + 属性“{0}”的 Set 访问器不可用。 + + + setter 方法应为 public、void、static,并具有两个参数。第一个参数应为 PSObject 类型。如果 getter 方法也可用,则需要第二个参数,并且其类型应与 getter 方法的返回类型相同。 + + + getter 方法应为 public、非 void、static,并且只有一个 PSObject 类型的参数。 + + + CodeProperty 应使用 getter 或 setter 方法。 + + + 由于方法格式问题,无法创建代码方法。该方法应为 public、static,并且只有一个 PSObject 类型的参数。 + + + 别名名为“{0}”的别名包含循环。 + + + 无法将类型“{0}”的“{1}”值转换为类型“{2}”。 + + + 无法将类型“{0}”的值转换为类型“{1}”。 + + + 无法将值 "{0}" 转换为类型 "{1}"。错误:“{2}” + + + 无法将值“{0}”转换为类型“{1}”,因为此枚举不允许使用逗号。 + + + 由于枚举值无效,无法将值“{0}”转换为类型“{1}”。请指定以下枚举值之一,然后重试。可用的枚举值为“{2}”。 + + + 由于枚举值无效,无法将 null 转换为类型“{0}”。请指定以下枚举值之一,然后重试。可用的枚举值为“{1}”。 + + + 无法将 null 转换为类型“{0}”。 + + + 无法将值转换为类型 "{0}"。 错误:“{1}” + + + 无法将值转换为 System.String 类型。 + + + 参数中应为引用类型。 + + + 无法比较“{0}”,因为它不是 IComparable。 + + + 无法将“{0}”与“{1}”进行比较。错误:“{2}” + + + 无法将“{0}”与“{1}”进行比较,因为对象不是同一类型,或者对象“{0}”未实现“{2}”。 + + + 无法将值“{0}”转换为类型“{1}”,因为至少找到两个匹配项({2}、 {3}),而此枚举只允许一个匹配项。 + + + 无法将值 "{0}" 转换为类型 "{1}"。布尔参数只接受布尔值和数字,例如 $True、$False、1 或 0。 + + + 无法获取属性值,因为“{0}”是只写属性。 + + + “{0}”是 ReadOnly 属性。 + + + 无法设置“{0}”,因为只有字符串才能用作值来设置 XmlNode 属性。 + + + 无法设置“{0}”,因为只能设置唯一属性或唯一的非属性化叶节点。 + + + 无法将 PSProperty 或 PSMethod 对象添加到此集合。 + + + 加载扩展类型数据文件时出现以下错误: {0} + + + 检索字符串时发生以下异常:“{0}” + + + 类型“{0}”的字段或属性“{1}”仅在字母大小写上与字段或属性“{2}”不同。类型必须符合公共语言规范 (CLS)。 + + + 检索类型名称层次结构时发生以下异常:“{0}”。 + + + 检索成员“{1}”时发生以下异常:“{0}” + + + 检索成员时发生以下异常:“{0}” + + + 检索属性“{1}”的读取状态时发生以下异常: "{0}" + + + 检索属性“{1}”的写入状态时发生以下异常:“{0}” + + + 检索属性“{1}”的类型时发生以下异常:“{0}” + + + 检索属性“{1}”的字符串表示形式时发生以下异常:“{0}” + + + 检索属性“{1}”的属性时发生以下异常:“{0}” + + + 检索方法“{1}”的定义时发生以下异常:“{0}” + + + 检索方法“{1}”的字符串表示形式时发生以下异常:“{0}” + + + 检索参数化属性“{1}”的类型时发生以下异常:“{0}” + + + 检索参数化属性“{1}”的读取状态时发生以下异常:“{0}” + + + 检索参数化属性“{1}”的写入状态时发生以下异常:“{0}” + + + 检索参数化属性“{1}”的定义时发生以下异常:“{0}” + + + 检索参数化属性“{1}”的字符串表示形式时发生以下异常:“{0}” + + + 无法为类型为“{0}”的 PSMemberInfo 对象设置 Value 属性。 + + + 参数“{0}”应为 {1}。使用 {2}。 + + + 参数“{0}”不应为 {1}。请勿使用 {2}。 + + + 找不到属性“{0}”。 + + + 无法获取或设置属性值。“{0}”参数应为“{1}”或“{2}”类型。 + + + 无法设置属性“{0}”的值,因为对象的类型为“{1}”,而不是“{2}”。 + + + 调用“{0}”时出现异常:“{1}” + + + {0} 不是有效的类路径。 + + + {0} 不是有效的路径。 + + + 适配器无法确定属性“{0}”是否可以更改。 + + + 适配器无法确定属性“{0}”是否可读写。 + + + 适配器无法获取属性“{0}”的值。 + + + 适配器无法设置属性“{0}”的值。 + + + 适配器无法获取属性“{0}”的类型。 + + + 适配器无法获取“{0}”的类型层次结构。 + + + 适配器无法获取“{0}”的属性。 + + + 适配器无法获取“{0}”的属性“{1}”。 + + + “{0}”返回了 null 值。 + + + 找不到“{0}”对象的属性“{1}”。可设置的属性为: {2}。 + + + 找不到“{0}”对象的属性“{1}”。没有可设置的属性。 + + + 无法创建类型“{0}”的对象。 {1} + + + 无法在开放泛型类型 {0}上调用静态方法或访问静态属性。 请指定类型参数,然后重试。 例如,请使用 [System.Collections.Generic.HashSet[int]]::CreateSetComparer(),而不是 [System.Collections.Generic.HashSet``1]::CreateSetComparer()。 + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + 构造属性“{1}”时发生以下异常:“{0}” + + + 无法将值“{0}”转换为字符串数组。 + + + 无法将值转换为类型 "{0}"。此语言模式仅支持核心类型。 + + + 无法转换为类似 ByRef 的类型“{0}”。PowerShell 不支持类似 ByRef 的类型。 + + + 无法获取或设置 ByRef-like 类型“{0}”的属性或字段“{1}”。PowerShell 不支持类似 ByRef 的类型。 + + + 无法调用 ByRef-like 返回类型“{0}”的方法“{1}”。PowerShell 不支持类似 ByRef 的类型。 + + + 无法创建 ByRef-like 类型“{0}”的实例。PowerShell 不支持类似 ByRef 的类型。 + + + 扩展类型系统哈希表转换 + + + 在 ConstrainedLanguage 模式下,不允许将类型从 HashTable 转换为“{0}”。 + + + 扩展类型系统哈希表转换 + + + 在 ConstrainedLanguage 模式下,不允许将类型从“{0}”转换为“{1}”。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/FileSystemProviderStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/FileSystemProviderStrings.zh-Hans.resx new file mode 100644 index 00000000000..941e1b8bd2f --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/FileSystemProviderStrings.zh-Hans.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Invoke Item + + + Item: {0} + + + Remove File + + + Remove Directory + + + Copy File + + + Item: {0} Destination: {1} + + + Copy Directory + + + Rename File + + + Rename Directory + + + Item: {0} Destination: {1} + + + Move File + + + Move Directory + + + Item: {0} Destination: {1} + + + Set Property File + + + Set Property Directory + + + Item: {0} Property: {1} Value: {2} + + + Clear Property File + + + Clear Property Directory + + + Item: {0} Property: {1} + + + Create File + + + Create Directory + + + Destination: {0} + + + Clear Content + + + Item: {0} + + + Could not find item {0}. + + + Cannot remove item {0}: {1} + + + Cannot restore attributes on item {0}: {1} + + + An object at the specified path {0} does not exist. + + + Directory {0} cannot be removed because it is not empty. + + + The type is not a known type for the file system. Only "file","directory" or "symboliclink" can be specified. + + + Cannot process the path because the specified path refers to an item that is outside the basePath. + + + The specified drive root "{0}" either does not exist, or it is not a folder. + + + An item with the specified name {0} already exists. + + + A delimiter cannot be specified when reading the stream one byte at a time. + + + Cannot overwrite the item {0} with itself. + + + Cannot rename the specified target, because it represents a path or device name. + + + The property {0} does not exist or was not found. + + + You do not have sufficient access rights to perform this operation or the item is hidden, system, or read only. + + + The attribute cannot be set because attributes are not supported. Only the following attributes can be set: Archive, Hidden, Normal, ReadOnly, or System. + + + The property cannot be cleared because the property is not supported. Only the Attributes property can be cleared. + + + Cannot process path '{0}' because the target represents a reserved device name. + + + Encoding not used when '-AsByteStream' specified. + + + Cannot proceed with byte encoding. When using byte encoding the content must be of type byte. + + + Cannot process the file because the file {0} was not found. + + + Directory: + + + Cannot detect the encoding of the file. The specified encoding {0} is not supported when the content is read in reverse. + + + Could not open the alternate data stream '{0}' of the file '{1}'. + + + Stream '{0}' of file '{1}'. + + + The Raw and Wait parameters cannot be specified in the same command. + + + To use the Persist switch parameter, the drive name must be supported by the operating system (for example, drive letters A-Z). + + + When you use the Persist parameter, the root must be a file system location on a remote computer. + + + The '{0}' and '{1}' parameters cannot be specified in the same command. + + + A directory is required for the operation. The item '{0}' is not a directory. + + + Create Junction + + + Create Symbolic Link + + + Administrator privilege required for this operation. + + + Create Hard Link + + + A file is required for the operation. The item '{0}' is not a file. + + + Hard links are not supported for the specified path. + + + Symbolic links are not supported for the specified path. + + + 正在将 {0} 复制到 {1} + + + Destination path {0} is a file that already exists on the target destination. + + + Failed to copy file {0} to remote target destination. + + + 从 {0} 到 {1} + + + Cannot copy a directory '{0}' to file '{0}' + + + Failed to get directory {0} child items. + + + Failed to read remote file '{0}'. + + + Cannot validate if remote destination {0} is a file. + + + Failed to create directory '{0}' on remote destination. + + + Maximum size for drive has been exceeded: {0}. + + + Cannot create link because the path already exists: {0}. + + + Skip already-visited directory {0}. + + + Destination path cannot be a subdirectory of the source or the source itself: {0}. + + + The target and path cannot be the same. + + + Copied {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Removed {0} of {1} files + + + {0} of {1} ({2:0.0} MB/s) + + + Creating a junction requires an absolute path for the target. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/FormatAndOutXmlLoadingStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/FormatAndOutXmlLoadingStrings.zh-Hans.resx new file mode 100644 index 00000000000..27bc822ad4a --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/FormatAndOutXmlLoadingStrings.zh-Hans.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 文件 {1} 中的 XPath {0} 存在错误: XML 元素 {2} 不允许使用属性。 + + + 文件 {1} 中的 XPath {0} 存在错误: 节点 {2} 不能具有子对象。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 无效。 + + + 文件 {1} 中的 XPath {0} 存在错误: 必须至少存在一个默认的 {2} 值。 + + + 文件 {1} 中的 XPath {0} 存在错误: 不能存在多个默认的 {2} 值。 + + + 文件 {1} 中的 XPath {0} 存在错误: 控件名称不能为 null 或为空。 + + + 文件 {1} 中的 XPath {0} 存在错误: 带外视图只能具有 CustomControl 或 ListControl。 + + + 文件 {1} 中的 XPath {0} 存在错误: 带外视图不能具有 GroupBy。 + + + 文件 {1} 中的 XPath {0} 存在错误: 无法加载视图。 + + + 文件 {1} 中的 XPath {0} 存在错误:“{2}”不是有效的对齐值。 + + + 文件 {1} 中的 XPath {0} 存在错误: 应为正整数。 + + + 文件 {1} 中的 XPath {0} 存在错误: 列标头定义无效;已丢弃所有标头。 + + + 文件 {1} 中的 XPath {0} 存在错误: 备用集 #{3} 上的行项计数 = {2} 与默认行项计数 = {4} 不匹配。 + + + 文件 {1} 中的 XPath {0} 存在错误: 标头项计数 = {2} 与默认行项计数 = {3} 不匹配。 + + + 文件 {1} 中的 XPath {0} 存在错误: 必须至少指定一个列表视图项。 + + + 文件 {1} 中的 XPath {0} 存在错误: 属性条目无效。 + + + 文件 {1} 中的 XPath {0} 存在错误: 缺少定义列表。 + + + 文件 {1} 中的 XPath {0} 存在错误: 应为布尔值。 + + + 文件 {1} 中的 XPath {0} 存在错误: 应为非负整数。 + + + 文件 {1} 中的 XPath {0} 存在错误: 应为整数。 + + + 文件 {1} 中的 XPath {0} 存在错误: 缺少内部文本值。 + + + 文件 {1} 中的 XPath {0} 存在错误: 自定义控件令牌列表不能为空。 + + + 文件 {1} 中的 XPath {0} 存在错误: 无法加载 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: 无法在没有表达式的情况下指定 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: 无法使用表达式指定 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: 缺少格式字符串。 + + + 文件 {1} 中的 XPath {0} 存在错误: 缺少脚本块文本。 + + + 文件 {1} 中的 XPath {0} 存在错误: 缺少属性。 + + + 文件 {1} 中的 XPath {0} 存在错误: 脚本块“{2}”无效。 + + + 文件 {1} 中的 XPath {0} 存在错误: 找不到程序集 {4} 中资源 {3} 的字符串 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: 找不到程序集 {3} 中资源 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: 找不到程序集 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: 节点必须是 XmlElement。 + + + 文件 {1} 中的 XPath {0} 存在错误: 应使用表达式。 + + + 文件 {1} 中的 XPath {0} 存在错误: 无法在没有表达式的情况下具有控件或标签。 + + + 文件 {1} 中的 XPath {0} 存在错误: 不能同时具有控件和标签。 + + + 文件 {1} 中的 XPath {0} 存在错误: 不能同时具有 SelectionSetName 和 TypeName。 + + + 文件 {1} 中的 XPath {0} 存在错误: 未指定任何类型或条件来应用视图。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 值无效。 + + + 文件 {1} 中的 XPath {0} 存在错误: 存在重复的节点。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 和 {3} 是互斥的。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2}、{3} 和 {4} 是互斥的。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 是未知节点。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 是未知属性。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 是缺失的属性。 + + + 文件 {1} 中的 XPath {0} 存在错误: 缺少节点 {2}。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 中缺少节点。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 为空节点。 + + + 文件 {1} 中的 XPath {0} 存在错误: {2} 为空属性。 + + + 文件 {0} 存在错误: {1} + + + 文件 {0} 中的错误太多。 + + + 加载格式数据文件时出错: {0} + + + (全局程序集缓存) {0} + + + {0},{1} + + + 未完全限定路径 {0}。指定完全限定的格式化文件路径。 + + + 无法更新 FormatTable,因为可能已在运行空间外部创建 FormatTable。 + + + 加载 FormatTable 时出错。查看 Errors 属性的内容以获取详细的错误消息。 + + + 设置数据“{0}”的格式时出错: {1} + + + 位于索引 {1} 处且类型名称为 {0} 的视图数据中存在错误: 标头项计数 = {2} 与默认行项计数 = {3} 不匹配。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据中存在错误: 设置数据“{2}”的格式无效。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据存在错误: 脚本块“{2}”无效。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据存在错误: 无法加载 {2}。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据存在错误: TableControl 应只包含一个 {2}。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据存在错误: 必须至少存在一个默认的 {2}。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据存在错误: 必须至少指定一个列表视图项。 + + + 位于索引 {1} 且类型名称为 {0} 的视图数据存在错误: 不能存在多个默认的 {2}。 + + + 类型“{0}”的格式设置数据中错误过多。 + + + 无法使用多个条目更新共享格式表。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_MshParameter.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_MshParameter.zh-Hans.resx new file mode 100644 index 00000000000..a835a7bf9f1 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_MshParameter.zh-Hans.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 + + + 无法将 {0} 转换为以下类型 {1} 之一。 + + + 参数的值为 null;应为以下类型之一: {0}。 + + + 复制的键“{0}”与“{1}”冲突。 + + + “{0}”键具有无效的类型 {1};预期类型为 {2}。 + + + “{0}”键具有无效的类型 {1};预期类型为 {2}。 + + + {0} 键不明确;{1} 和 {2} 冲突。 + + + 键的值不能为 null。 + + + {0} 键类型无效。该键必须是字符串。 + + + {0} 键没有值。 + + + {0} 缺少必需的条目。 + + + {0} 键无效。 + + + 键“{0}”的值“{1}”无效;有效值为 {2}。 + + + 键“{1}”的值“{0}”应大于 0。 + + + 键“{0}”的格式字符串不能为空。 + + + “{0}”键不能具有空字符串值。 + + + 不允许使用空字符串值。 + + + “{0}”键的值“{1}”中不能包含通配符。 + + + “{0}”不允许使用通配符。 + + + EnumerableExpansion 值无效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_format_xxx.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_format_xxx.zh-Hans.resx new file mode 100644 index 00000000000..612afc99349 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_format_xxx.zh-Hans.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet parameters View and Property are mutually exclusive. + + + Cmdlet parameters AutoSize and Column are mutually exclusive. + + + The view name {0} cannot be found. + + + The view name {0} cannot be found in the {1} formatting. + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + There are no existing {0} views for {1} objects. + + + The view name {0} cannot be found. Specify one of the following {1} views and try again: {2}. + + + Try using one of these other format cmdlets: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + The following object supports IEnumerable: + + + The IEnumerable contains no objects. + + + The IEnumerable contains the following object: + + + The IEnumerable contains the following {0} objects: + + + Unknown class Id {0}. + + + The type {0} for property {1} is not valid. + + + The value of the {0} data member cannot be null. + + + The object type is not recognized. + + + Failed to create object with class Id {0}. + + + The {0} property is recursive. + + + Failed to evaluate expression "{0}". + + + Failed to interpret format string "{0}". + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_out_xxx.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_out_xxx.zh-Hans.resx new file mode 100644 index 00000000000..94f22248141 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/FormatAndOut_out_xxx.zh-Hans.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> next page; <CR> next line; Q quit + + + The value of LineOutput should not be null. + + + The lineOutput type {0} was not expected; LineOutput expects type {1}. + + + The object of type "{0}" is not valid or not in the correct sequence. This is likely caused by a user-specified "{1}" command which is conflicting with the default formatting. + + + Cannot open file "{0}". + + + Output to File + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/GetErrorText.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/GetErrorText.zh-Hans.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/GetErrorText.zh-Hans.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/HelpDisplayStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/HelpDisplayStrings.zh-Hans.resx new file mode 100644 index 00000000000..f935574ac9a --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/HelpDisplayStrings.zh-Hans.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 名称 + + + SYNOPSIS + + + DESCRIPTION + + + SYNTAX + + + PARAMETERS + + + INPUTS + + + OUTPUTS + + + TERMINATING ERRORS + + + NON-TERMINATING ERRORS + + + NOTES + + + EXAMPLES + + + 示例 + + + EXAMPLE + + + OUTPUT + + + RELATED LINKS + + + SHORT DESCRIPTION + + + Title: + + + Question: + + + 答案 + + + Term: + + + Definition: + + + Content: + + + PROVIDER NAME + + + This cmdlet supports the common parameters: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. For more information, see + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Required? + + + Position? + + + Type: + + + Target Object Type: + + + Default value + + + Accept pipeline input? + + + Accept wildcard characters? + + + (Category: + + + Suggested Action: + + + For more information, type: + + + For technical information, type: + + + To see the examples, type: + + + For online help, type: + + + <CommonParameters> + + + REMARKS + + + true + + + Named + + + DRIVES + + + CAPABILITIES + + + TASKS + + + TASK: + + + FILTERS + + + DYNAMIC PARAMETERS + + + Cmdlets Supported: + + + ALIASES + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + -- To view the Help topic for this cmdlet online, type: "Get-Help {0} -Online" or + go to {1}. + + + + + + Aliases + + + Dynamic? + + + Parameter set name + + + Unable to retrieve the HelpInfo XML file for UI culture {0}. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + + + The ModuleBase directory cannot be found. Verify the directory and try again. + + + The path {0} is not a valid directory. Make sure the directory exists and retry. + + + A Help URI cannot contain more than 10 redirections. Specify a valid Help URI. + + + Updating Help + + + Connecting to Help Content... + + + Downloading Help Content... + + + Installing Help content... + + + Locating Help Content... + + + (All) + + + No PowerShell modules were found that match the following pattern: {0}. Verify the pattern and then try the command again. + + + No PowerShell modules were found that match the specified FullyQualifiedModule {0}. Verify the FullyQualifiedModule value and then try the command again. + + + Help content cannot be found. Make sure the server is available and the help content location is properly defined in the HelpInfo XML. + + + The Update-Help command failed because the specified module does not support updatable help. Use Get-Help -Online or look online for help for the commands in this module. + + + The following parameter must not be null or empty: Module. + + + The following parameter must not be null or empty: Path. + + + Update-Help has completed successfully. + + + Error extracting Help content. + + + Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. + + + The Help content at the specified location is not valid. Specify a location that contains valid Help Content. + + + The HelpInfo XML is not valid. Specify valid HelpInfo XML. + + + Help content was successfully saved to the following location: {0} + + + The Help content XSD file cannot be found in {0}. Verify that the XSD file exists at the specified location, and then retry the command. + + + Failed to update Help for the module(s) : +'{0}' +{1} + + + Saving Help + + + Help content contains files that are not valid. Only .txt and .xml files are supported. + + + Failed to save Help for the module(s) '{0}' : {1} + + + Failed to save Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be saved using: Save-Help -UICulture en-US. + + + Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + + + false + + + The -Recurse parameter is only available if a source path is specified. + + + The path {0} does not contain a FileSystem provider. Verify that the specified path contains the FileSystem provider, and then retry the command. + + + Searching Help for {0} ... + + + No UI culture was found that matches the following pattern: {0}. Verify the pattern and then try the command again. + + + Help was not saved for the module {0}, because the Save-Help command was run on this computer within the last 24 hours. +To save help again, add the Force parameter to your command. + + + Help was not updated for the module {0}, because the Update-Help command was run on this computer within the last 24 hours. +To update help again, add the Force parameter to your command. + + + The most current Help files are already installed. + + + {0}: {1}. Culture {2} Version {3} + + + Updated {0} + + + The value of the HelpInfoUri key in the module manifest must resolve to a container or root URL on a website where the help files are stored. The HelpInfoUri '{0}' does not resolve to a container. + + + Help content must be in the namespace {0}. + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + + + The most current Help files are already downloaded. + + + Saved {0} + + + The HelpInfoURI {0} does not start with HTTP. + + + The root level element of the help content must be "helpItems". + + + Saving Help for module {0} + + + Updating Help for module {0} + + + Resolving URI: "{0}" + + + Help URI: {0} + + + {0}, Current Version: {1}, Available Version: {2}, UICulture: {3} + + + PROPERTIES + + + METHODS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/HelpErrors.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/HelpErrors.zh-Hans.resx new file mode 100644 index 00000000000..2c4d4e79a5c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/HelpErrors.zh-Hans.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help 无法在此会话的帮助文件中找到 {0}。若要下载更新的帮助主题,请键入: "Update-Help"。若要联机获取帮助,请在 TechNet 库中搜索帮助主题,网址为 https://go.microsoft.com/fwlink/?LinkID=107116。 + + + 无法处理该帮助类别,因为 "{0}" 不是有效的帮助类别。 + + + 无法加载帮助文件 "{0}"。详细信息: {1}。 + + + 无法访问帮助文件 "{0}",因为当前用户没有该文件的访问权限。详细信息: {1}。 + + + 帮助文件 "{0}" 不是有效的 XML 文档。详细信息: {1}。 + + + 从文件 {1} 加载 {0} 的帮助内容时出错。详细信息: {2}。若要下载更新的帮助主题,请运行 Update-Help cmdlet。若要联机获取帮助,请在 TechNet 库中搜索帮助主题,网址为 https://go.microsoft.com/fwlink/?LinkID=107116。 + + + 无法加载提供程序 "{0}"。详细信息: {1}。 + + + 无法加载帮助文件。加载帮助文件 "{0}" 时出现以下 {1} 错误。 + + + 节点 "{0}" 不能将 "{1}" 作为子节点。节点路径: {2}。 + + + 节点 "{0}" 最多可以有 {2} 个 "{1}" 类型的子节点。节点路径: {3}。 + + + 找不到注册表项: "{0}{1}";将使用 "{2}" 加载帮助文件。 + + + 没有参数符合条件 {0}。 + + + 请求的帮助类别不支持 {0}。 + + + 无法显示此帮助主题的联机版本,因为未在命令代码或该命令的帮助文件中指定此帮助主题的 Internet 地址(URI)。 + + + 指定的 URI {0} 无效。 + + + 启动浏览器以显示联机帮助失败。没有关联的程序或浏览器可用于打开 URI {0}。 + + + 不支持 URI "{0}" 中指定的协议。仅支持 "{1}" 和 "{2}" 协议。 + + + 找到了多个帮助主题。请仅使用一个带有 -{0} 选项的帮助主题。 + + + 无法从远程运行空间获取帮助,因为尚未打开该运行空间。 请通过运行隐式远程处理命令来打开该运行空间,然后再次尝试运行该命令以获取帮助。 + + + 访问被拒绝。此命令无法更新关于 PowerShell 核心模块或 $pshome\Modules 目录中的任何模块的帮助主题。 +若要更新这些帮助主题,请使用“以管理员身份运行”命令启动 PowerShell,然后再次尝试运行 Update-Help。 + + + 若要使用 {0},请确保你的应用程序使用 'Microsoft.NET.Sdk.WindowsDesktop' 作为项目 SDK,并且相应的程序集 'Microsoft.PowerShell.GraphicalHost' 可用。({1}) + + + {0} 在远程会话中不起作用。 + + + ForwardHelpTargetName 无法引用函数本身。 + + + 在受限会话中,无法从网络位置获取帮助。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/HistoryStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/HistoryStrings.zh-Hans.resx new file mode 100644 index 00000000000..f837cd90ad9 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/HistoryStrings.zh-Hans.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}”不是有效的 History 标识符值。请指定一个正数,然后重试。 + + + 找不到 ID {0} 的历史记录。 + + + 计数不能与多个 ID 组合使用。 + + + 找不到命令行 {0} 的历史记录。 + + + 找不到最近的历史记录。 + + + 循环中重复调用 Invoke-History cmdlet。 + + + 无法处理多个历史记录命令。只能使用 Invoke-History 运行单个命令。 + + + 无法添加历史记录,因为输入对象的格式无效。 + + + 标识符“{0}”无效。请指定一个正数,然后重试。 + + + 此命令将清除会话历史记录中的所有条目。 + + + 计数不能与多个 CommandLine 参数组合。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/HostInterfaceExceptionsStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/HostInterfaceExceptionsStrings.zh-Hans.resx new file mode 100644 index 00000000000..ce5e8bd5cb2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/HostInterfaceExceptionsStrings.zh-Hans.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 + + + 已发生类型为“{0}”的错误。 + + + 提示用户的命令失败,因为主机程序或命令类型不支持用户交互。请尝试使用支持用户交互的主机程序,例如 PowerShell 控制台,并从不支持用户交互的命令类型中删除与提示相关的命令。 + + + 提示用户的命令失败,因为主机程序或命令类型不支持用户交互。主机正在尝试通过以下消息请求确认: {0} + + + 无法调用该方法,因为池已关闭或已失败。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/InternalCommandStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/InternalCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..6223104bb0c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/InternalCommandStrings.zh-Hans.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 输入名称“{0}”不明确。它可以解析为多个匹配的方法。可能的匹配项包括: {1}。 + + + 输入名称“{0}”不明确。它可以解析为多个匹配的成员。可能的匹配项包括: {1}。 + + + 检索键“{0}”的值 + + + 使用参数的调用方法“{0}”: {1} + + + 调用方法“{0}” + + + 检索属性“{0}”的值 + + + InputObject: {0} + + + 无法对 'null' 输入对象执行操作。 + + + 无法将输入名称“{0}”解析为方法。 + + + 无法在受限语言模式下调用方法。 + + + 脚本块不支持 -WhatIf 和 -Confirm 参数。 + + + RestrictedLanguage 模式下不允许执行“{0}”操作。 + + + 需要使用运算符来比较两个指定的值。在命令中包含有效的运算符,然后重试该命令。例如,Get-Process | Where-Object -Property Name -eq Idle + + + 无法将输入名称“{0}”解析为属性。 + + + 无法将输入名称“{0}”解析为成员。 + + + 指定的运算符同时需要 -Property 和 -Value 参数。提供这两个参数的值,然后重试该命令。 + + + 此方法不能在当前线程上运行。只能在 cmdlet 线程上调用它。 + + + ForEach-Object -Parallel using 变量不能是脚本块。ForEach-Object -Parallel 不支持传入脚本块变量,并且可能导致未定义的行为。 + + + ForEach-Object -Parallel 管道输入对象不能是脚本块。ForEach-Object -Parallel 不支持传入脚本块变量,并且可能导致未定义的行为。 + + + 'TimeoutSeconds' 参数不能与 'AsJob' 参数一起使用。 + + + Parallel 参数集当前不支持以下常用参数: +ErrorAction、WarningAction、 InformationAction、PipelineVariable + + + 处理 ForEach-Object -Parallel 输入时发生意外错误。这可能意味着部分管道输入未得到处理。错误: {0}。 + + + ForEach-Object Cmdlet + + + 在约束语言模式下运行时,不允许对类型“{0}”进行方法调用。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/InternalHostStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/InternalHostStrings.zh-Hans.resx new file mode 100644 index 00000000000..7fedf51cc33 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/InternalHostStrings.zh-Hans.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 + + + EnterNestedPrompt 的调用次数没有 ExitNestedPrompt 的调用次数多。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/InternalHostUserInterfaceStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/InternalHostUserInterfaceStrings.zh-Hans.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/InternalHostUserInterfaceStrings.zh-Hans.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/Logging.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/Logging.zh-Hans.resx new file mode 100644 index 00000000000..eb4c7086028 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/Logging.zh-Hans.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + 未知 + + + 配置文件中声明的引擎实验性功能 '{0}' 未在当前 PowerShell 中注册。 + + + 配置文件中声明的实验性功能 '{0}' 无效。 +实验性功能的名称应遵循以下约定: + 引擎功能名称: 'PS[FeatureName]' + 模块功能名称: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/Metadata.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/Metadata.zh-Hans.resx new file mode 100644 index 00000000000..e7f3dcaf233 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/Metadata.zh-Hans.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法初始化“{0}”的属性:“{1}” + + + 无法验证该参数,因为其类型“{0}”与参数的最大和最小限制类型({1})不同。请确保参数类型为 {1},然后重试该命令。 + + + 无法验证参数“{0}”,因为其值不大于零。 + + + 无法验证参数“{0}”,因为其值不大于或等于零。 + + + 无法验证参数“{0}”,因为其值不小于零。 + + + 无法验证参数“{0}”,因为其值不小于或等于零。 + + + 无法接受指定的最小范围({0}),因为它与指定的最大范围({1})的类型不同。更新参数的 ValidateRange 属性。 + + + 无法接受 MaxRange 和 MinRange 参数类型。这两个参数都必须是实现 IComparable 接口的对象。 + + + 无法接受指定的最大范围,因为它小于指定的最小范围。更新参数的 ValidateRange 属性。 + + + 参数 {0} 大于允许的最大范围 {1}。提供小于或等于 {1} 的参数,然后重试该命令。 + + + 参数 {0} 小于允许的最小范围 {1}。提供大于或等于 {1} 的参数,然后重试该命令。 + + + 参数“{0}”与“{1}”模式不匹配。提供与“{1}”匹配的参数,然后重试该命令。 + + + ValidateCount 属性不能应用于非数组参数。从参数中移除属性或将参数设为数组参数。 + + + 该参数确切需要 {0} 个值 - 系统提供了 {1} 个值。 + + + 参数至少需要 {0} 个值,并且不超过 {1} 个值 - 已提供 {2} 个值。 + + + 参数的指定最大实参数小于指定的最小实参数。更新参数的 ValidateCount 属性。 + + + 参数的指定最大字符长度短于指定的最小参数字符长度。更新参数的 ValidateLength 属性。 + + + 无法将 ValidateLength 属性应用于不是字符串的参数或 string[] 参数。将参数设为字符串或 string[] 参数。 + + + 参数的字符长度({1})太短。指定长度大于或等于“{0}”的参数,然后重试该命令。 + + + 参数的字符长度({1})太长。指定长度小于或等于“{0}”的参数,然后重试该命令。 + + + 参数“{0}”不属于 ValidateSet 属性指定的集“{1}”。请提供位于集中的参数,然后重试该命令。 + + + 有效值生成器返回 null 值。 + + + 属性“{1}”{2} 上的“{0}”失败 + + + 无法获取或运行该命令。已超过此命令的最大参数集数。 + + + 无法处理参数,因为参数值不是字符串。指定了 ArgumentTransformationAttribute 的参数实参值应为字符串。 + + + 无法验证该变量,因为该值 {1} 不是变量 {0} 的有效值。 + + + 无法添加属性,因为值为 {1} 的变量 {0} 将不再有效。 + + + 参数为 null。提供参数的有效值,然后再次尝试运行该命令。 + + + 参数具有 null 值,或者参数集合的元素包含 null 值。提供不包含任何 null 值的集合,然后重试该命令。 + + + 参数为 Null 或空。提供不为 Null 或空的参数,然后重试该命令。 + + + 参数为 null、空,或参数集合的元素包含 null 值。提供不包含任何 null 值的集合,然后重试该命令。 + + + 参数为 null、空或仅由空格字符组成。提供包含非空空格字符的参数,然后重试该命令。 + + + 参数集合的元素为 null、空或仅由空格字符组成。提供不包含任何这些值的集合,然后重试该命令。 + + + 已为命令多次定义名为“{0}”的参数。 + + + 无法指定参数别名,因为已为命令多次定义名为“{0}”的别名。 + + + 无法指定参数“{0}”,因为它与参数“{1}”的同名参数别名冲突。 + + + 值为“{0}”的参数的“{1}”验证脚本未返回结果 True。确定验证脚本失败的原因,然后重试该命令。 + + + “{0}”参数不包含有效的 PowerShell 版本。提供有效的版本号,然后重试该命令。 + + + 无法验证参数“{0}”,因为它不是有效的变量名称。 + + + 作业转换类型必须派生自 IAstToScriptBlockConverter。 + + + 路径参数无效。提供字符串类型的路径参数。 + + + 路径参数驱动器 {0} 不属于已批准的驱动器集: {1}。使用批准的驱动器提供路径参数。 + + + 路径参数包含无效字符。 + + + 路径参数没有根驱动器。 提供包含根驱动器的完整路径参数。 + + + 参数“{0}”的参数值不能为 null 或空字符串。 + + + 枚举成员“{0}”不是参数“{1}”的有效值。请指定以下成员之一,然后重试: {2}。 + + + 无法处理输入。参数“{0}”不受信任。 + + + ValidateTrustedData 属性检查失败 + + + 参数实参“{0}”不受信任,且在约束语言模式下无法通过 ValidateTrustedData 参数属性检查。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/MiniShellErrors.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/MiniShellErrors.zh-Hans.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/MiniShellErrors.zh-Hans.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/Modules.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/Modules.zh-Hans.resx new file mode 100644 index 00000000000..1643903efc3 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/Modules.zh-Hans.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 未加载指定的模块 "{0}",因为在所有模块目录中都未找到有效的模块文件。 + + + 未加载指定的模块 "{0}" (版本为 "{1}"),因为在所有模块目录中都未找到有效的模块文件。 + + + 指定的 MaximumVersion "{0}" 不正确。如果使用 "*",则 MaximumVersion 只支持一个 "*",并且它应始终位于 MaximumVersion 的末尾。 + + + 未加载指定的模块 "{0}" (MinimumVersion 为 "{1}"),因为在所有模块目录中都未找到有效的模块文件。 + + + 未加载指定的模块 "{0}" (MinimumVersion 为 "{1}",MaximumVersion 为 "{2}"),因为在所有模块目录中都未找到有效的模块文件。 + + + MinimumVersion "{0}" 不应大于 MaximumVersion "{1}"。 + + + 未加载程序集 "{0}",因为找不到具有该名称的程序集。请验证程序集名称,然后重试。 + + + 未处理模块清单 "{2}" 的字段 "{1}" 中列出的要处理的模块 "{0}",因为在所有模块目录中都未找到有效模块。 + + + 未为模块 "{0}" 返回自定义对象,因为 -AsCustomObject 参数只能用于脚本模块。 + + + 无法处理模块清单 "{0}",因为它不是有效的 PowerShell 模块清单文件。请删除不允许的元素: {1} + + + 处理模块清单文件 "{0}" 后未得到有效的清单对象。请更新该文件,使其包含有效的 PowerShell 模块清单。可以使用 New-ModuleManifest cmdlet 创建有效的清单。 + + + 无法导入 "{0}" 模块,因为其清单包含一个或多个无效成员。有效的清单成员为({1})。请删除无效成员({2}),然后再次尝试导入该模块。 + + + 描述模块的哈希表包含一个或多个无效成员。有效成员为({0})。请删除无效成员({1}),然后重试。 + + + 无法加载模块 "{0}",因为已超过模块嵌套限制。模块只能嵌套到 {1} 级。请评估并调整加载模块的顺序,以避免超过嵌套限制,然后再次尝试运行脚本。 + + + 模块清单中不存在成员 "ModuleVersion"。此成员必须存在并分配有 "n.n.n.n" 格式的版本号。请将缺少的成员添加到文件 "{0}" 中。 + + + 模块清单文件 "{2}" 中的成员 "{0}" 无效: {1} + + + 模块 "{1}" 的版本 "{0}" 不符合所需的最低版本 "{2}"。请验证该版本号是否受支持,然后再次尝试加载该模块。 + + + 此计算机上的 PowerShell 版本为 "{0}"。模块 "{1}" 运行所需的最低 PowerShell 版本为 {2}。请验证是否已安装所需的最低 PowerShell 版本,然后重试。 + + + 如果 "ModuleToProcess" 成员是二进制模块,则无法使用模块清单成员 "NestedModules"。请编辑 "{0}" 处的模块清单文件,然后重试。 + + + 模块清单中的成员 "{0}" 无效: {1}。请验证是否在 "{2}" 文件中为此字段指定了有效值。 + + + 模块清单路径 "{0}" 无效。Path 参数的值必须解析为一个扩展名为 ".psd1" 的单个文件。请更改 Path 参数的值,使其指向有效的 psd1 文件,然后重试。 + + + 模块清单 "{0}" 中的 ModuleVersion 键指定的模块版本 "{1}" 与 "{2}" 中的版本文件夹名称不匹配。请更改 ModuleVersion 键的值,使其与版本文件夹名称一致。 + + + 模块清单 "{1}" 中指定的 NestedModule 条目 "{0}" 无效。请使用有效值更新此条目,然后重试。 + + + 模块清单 "{1}" 中指定的 RequiredAssemblies 条目 "{0}" 无效。请使用有效值更新此条目,然后重试。 + + + 模块清单 "{1}" 中指定的 FileList 条目 "{0}" 无效。请使用有效值更新此条目,然后重试。 + + + 模块清单 "{1}" 中指定的 RequiredModules 条目 "{0}" 无效。请使用有效值更新此条目,然后重试。 + + + 模块清单 "{1}" 中指定的 ModuleList 条目 "{0}" 无效。请使用有效值更新此条目,然后重试。 + + + 模块清单 "{0}" 指定了 CompatiblePSEditions 键。此键仅在 PowerShell 5.1 或更高版本中受支持。请将 PowerShellVersion 键的值更新为 5.1 或更高版本,然后重试。 + + + CompatiblePSEditions 的指定值 "{0}" 包含重复的 PowerShell 版本名称。请先删除重复的 PowerShell 版本名称,然后重试。 + + + ModuleVersion 键中指定的版本等于版本文件夹名称。 + + + 正在跳过 Module {1} 下的 Version 文件夹 {0},因为它没有有效的模块清单文件。 + + + 描述此模块的哈希表中不存在 "ModuleName" 成员。 + + + 描述此模块的哈希表中不存在 "ModuleVersion"、"MaximumVersion" 和 "RequiredVersion" 成员。这三个成员中必须存在一个,并分配了格式为 "n.n.n.n" 的版本号。 + + + 未加载所需模块 "{1}"。请加载该模块,或从文件 "{0}" 中的 "RequiredModules" 删除该模块。 + + + 未加载 GUID 为 "{2}" 的所需模块 "{1}"。请加载该模块,或从文件 "{0}" 中的 "RequiredModules" 删除该模块。 + + + 未加载版本 "{2}" 的所需模块 "{1}"。请加载该模块,或从文件 "{0}" 中的 "RequiredModules" 删除该模块。 + + + 未加载 MaximumVersion 为 "{2}" 的所需模块 "{1}"。请加载该模块,或从文件 "{0}" 中的 "RequiredModules" 删除该模块。 + + + 未加载 MinimumVersion 为 "{2}" 且 MaximumVersion 为 "{3}" 的所需模块 "{1}"。请加载该模块,或从文件 "{0}" 中的 "RequiredModules" 删除该模块。 + + + 找不到 ModuleVersion 为 "{1}" 的模块 "{0}"。 + + + 找不到 RequiredVersion 为 "{1}" 的模块 "{0}"。 + + + 找不到 MaximumVersion 为 "{1}" 的模块 "{0}"。 + + + 找不到 ModuleVersion 为 "{1}" 且 MaximumVersion 为 "{2}" 的模块 "{0}"。 + + + 找不到模块 "{0}"。 + + + 未删除任何模块。请验证要删除的模块规范是否正确,以及这些模块是否存在于运行空间中。 + + + 无法删除从模块 "{1}" 导入的 "{0}" 成员,原因如下: {2} + + + 无法删除模块 "{0}",因为它是只读的。请在命令中添加 Force 参数,以删除只读模块。 + + + 无法删除模块 "{0}",因为它被标记为 "constant"。如果模块被标记为 "constant",则无法将其删除。 + + + 无法删除模块 "{0}",因为它是 "{1}" 需要的。请在命令中添加 Force 参数,以删除该模块。 + + + 只能从模块内部调用 Export-ModuleMember cmdlet。 + + + "{0}" 扩展不是有效的模块扩展。支持的模块扩展名为 ".dll"'、".ps1"、".psm1"、".psd1" 和 ".cdxml"。请更正扩展名,然后再次尝试添加文件 "{1}"。 + + + 无法在二进制模块上执行此操作。它只能在脚本模块上执行。 + + + 不允许使用文件 "{0}",因为它没有扩展名 ".ps1"。 + + + 未知 + + + (c) {0}。保留所有权利。 + + + 正在删除已导入的 "{0}" 函数。 + + + 正在删除已导入的 "{0}" 别名。 + + + 正在删除已导入的 "{0}" 变量。 + + + 正在从路径 "{0}" 加载模块。 + + + 正在从路径 "{1}" 加载 "{0}"。 + + + 正在点源脚本文件 "{0}"。 + + + 正在导入函数 "{0}"。 + + + 正在导入 cmdlet "{0}"。 + + + 正在导入别名 "{0}"。 + + + 正在导入变量 "{0}"。 + + + 正在导出 cmdlet "{0}"。 + + + 正在导出函数 "{0}"。 + + + 正在导出别名 "{0}"。 + + + 正在导出变量 "{0}"。 + + + 来自模块 "{0}" 的某些导入命令名称包含未经批准的谓词,这可能会降低它们的可发现性。若要查找带有未经批准谓词的命令,请使用 Verbose 参数再次运行 Import-Module 命令。若要查看已批准谓词的列表,请输入 Get-Verb。 + + + 已导入模块 "{1}" 中的 "{0}" 命令,但由于其名称不包含已批准的谓词,可能很难找到。若要查看已批准谓词的列表,请输入 Get-Verb。 + + + 已导入模块 "{2}" 中的 "{0}" 命令,但由于其名称不包含已批准的谓词,可能很难找到。建议的替代谓词为“{1}”。 + + + 某些已导入的命令名称包含以下一个或多个受限字符: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + 模块 "{1}" 中的命令名称 "{0}" 包含一个或多个以下受限字符: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + 创建 "{0}" 模块清单文件。 + + + {0}(路径: "{1}") + + + 当前处理器体系结构为: {0}。模块 "{1}" 需要以下体系结构: {2}。 + + + 当前 PowerShell 主机名称为 "{0}"。模块 "{1}" 需要以下 PowerShell 主机: "{2}"。 + + + 当前 PowerShell 主机为: {0}(版本 {1})。模块 "{2}" 运行所需的最低 PowerShell 主机版本为 {3}。 + + + 模块 "{0}" 的模块清单 + + + 生成者: {0} + + + 生成于: {0} + + + 与此清单关联的脚本模块或二进制模块文件。 + + + 要作为 RootModule/ModuleToProcess 中指定模块的嵌套模块导入的模块 + + + 用于唯一标识此模块的 ID + + + 此模块的作者 + + + 此模块的公司或供应商 + + + 此模块的版权声明 + + + 此模块的版本号。 + + + 此模块提供的功能说明 + + + 此模块要求的 PowerShell 引擎的最低版本 + + + 此模块所需的公共语言运行时(CLR)的最低版本。{0} + + + 在导入此模块之前必须导入全局环境的模块 + + + 在导入此模块之前在调用方环境中运行的脚本文件(.ps1)。 + + + 导入此模块时要加载的类型文件(.ps1xml) + + + 导入此模块时要加载的格式化文件 (.ps1xml) + + + 在导入此模块之前必须加载的程序集 + + + 使用此模块打包的所有文件列表 + + + 要传递给 RootModule/ModuleToProcess 中指定的模块的私有数据。这还可能包含一个 PSData 哈希表,其中包含 PowerShell 使用的其他模块元数据。 + + + 应用于此模块的标记。这些标记有助于在联机库中发现模块。 + + + 指向此项目主网站的 URL。 + + + 指向此模块许可证的 URL。 + + + 指向表示此模块的图标的 URL。 + + + 此模块的发行说明 + + + 此模块的预发行版字符串 + + + 此标志指示模块是否要求用户明确同意安装、更新或保存。 + + + 此模块的外部依赖模块 + + + {0} 哈希表末尾 + + + PrivateData 参数值必须是哈希表,才能使用以下参数值创建模块清单: Tags、ProjectUri、LicenseUri、IconUri 或 ReleaseNotes。请删除 Tags、ProjectUri、LicenseUri、IconUri 或 ReleaseNotes 参数值,或将 PrivateData 的内容包装在哈希表中。 + + + 应将 PrivateData 定义为哈希表,但此模块清单将其定义为对象。请考虑将 PrivateData 的内容包装在哈希表中。这样,后续就可以向模块清单添加 Tags、ProjectUri、LicenseUri、IconUri 和 ReleaseNotes 属性。 + + + 指定的值 "{0}" 无效,请使用有效值重试。 + + + 要从此模块导出的函数。为获得最佳性能,请不要使用通配符,也不要删除此条目。如果没有要导出的函数,请使用空数组。 + + + 要从此模块导出的别名。为获得最佳性能,请不要使用通配符,也不要删除此条目。如果没有要导出的别名,请使用空数组。 + + + 要从此模块导出的 cmdlet。为获得最佳性能,请不要使用通配符,也不要删除此条目。如果没有要导出的 cmdlet,请使用空数组。 + + + 要从此模块导出的变量 + + + 要从此模块导出的 DSC 资源 + + + 受支持的 PSEditions + + + 此模块要求处理器体系结构(无、X86、Amd64) + + + 使用此模块打包的所有模块列表 + + + 此模块所需的 Microsoft .NET Framework 最低版本。{0} + + + 此模块所需的 PowerShell 主机名称 + + + 此模块要求的 PowerShell 主机的最低版本 + + + 此模块的 HelpInfo URI + + + 因为 {0} 模块在当前 PowerShell 会话中提供 PSDrive,所以未删除任何模块。请更改当前 PSDrive 提供程序,然后再次尝试删除模块。 + + + 未导入 cmdlet "{0}",因为当前作用域中存在同名成员。 + + + 未导入别名 "{0}",因为当前作用域中存在同名成员。 + + + 未导入函数 "{0}",因为当前作用域中存在同名成员。 + + + 未导入变量 "{0}",因为当前作用域中存在同名成员。 + + + 模块清单 "{0}" 中的成员 "ModuleToProcess"、"RootModule" 或 "NestedModules" 不允许使用通配符。 + + + 模块 "{0}" 是 PowerShell 的核心模块。请在命令中添加 Force 参数,以删除核心模块。 + + + 模块清单不能同时包含 "ModuleToProcess" 和 "RootModule" 成员。请修改模块清单文件以删除 "{0}" 处的其中一个成员,然后重试。 + + + 模块清单成员 "ModuleToProcess" 已被弃用。请改用 "RootModule" 成员。 + + + 从此模块导出的命令的默认前缀。可使用 Import-Module -Prefix 覆盖默认前缀。 + + + 不能同时指定 "Global" 和 "Scope" 参数。请删除其中一个参数,然后再次运行该命令。 + + + 未加载所需模块 "{0}"。模块 "{0}" 在其模块清单 "{2}" 中的 requiredModule "{1}" 指向循环依赖项。 + + + 未加载所需模块 "{0}",因为在所有模块目录中都未找到有效的模块文件。 + + + 模块 {0} 中的某些命令无法通过 CimSession 导入。若要获取所有命令,请验证远程服务器是否已启用 PowerShell 远程管理,然后尝试在 Import-Module cmdlet 中添加 PSSession 参数。 + + + 模块 {0} 使用 {1} 远程会话在 Windows PowerShell 中加载;请注意,该模块中所有命令的输入和输出都将是反序列化对象。如果要将此模块加载到 PowerShell 中,请使用 Import-Module -SkipEditionCheck 语法。 + + + 检测到的 Windows PowerShell 版本 {0}。使用 Windows PowerShell 兼容性功能加载模块需要 Windows PowerShell 5.1。请从 https://aka.ms/WMF5Download 安装 Windows Management Framework (WMF) 5.1 以启用此功能。 + + + PowerShell 配置文件中的 "WindowsPowerShellCompatibilityModuleDenyList" 设置已阻止使用 Windows PowerShell 兼容性功能加载模块 "{0}"。 + + + 无法通过 CimSession 导入模块 {0}。请尝试使用 Import-Module cmdlet 的 PSSession 参数。 + + + 不支持 {0} 的处理器体系结构值。请再次运行 New-ModuleManifest 命令,并为处理器体系结构指定以下受支持的枚举值之一: None、MSIL、X86、Amd64、Arm + + + 对远程计算机运行 Get-Module cmdlet 只能列出可用模块。请将 ListAvailable 参数添加到命令中,然后重试。 + + + 未导入 "{0}" 模块,因为已导入 "{0}" 管理单元。 + + + 模块清单 "{0}" 中的成员 "RequiredAssemblies" 不允许使用通配符。 + + + {1} 中 {0} 键的值为 {2} ,并且该模块具有嵌套模块。当 CDXML 文件是根模块时,Import-Module 命令会失败,因为无法导出嵌套模块中的命令。请将 CDXML 文件移到 NestedModules 键下,然后再次尝试运行该命令。 + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + 远程命令失败: {0}:{{0}} + + + 无法为远程模块 "{0}" 生成代理。{{0}} + + + 未能处理远程模块 {0}。{1} + + + 未能从远程 CimSession 接收模块数据。{0} + + + 未加载所需模块 "{0}" (GUID 为 "{1}",版本为 {2}),因为在所有模块目录中都未找到有效的模块文件。 + + + 在 CIM 服务器上找不到用于模块发现的 CIM 提供程序。{0} + {0} is a placeholder for a more detailed error message + + + 无法验证 Microsoft .NET Framework 版本 {0},因为它不在允许的版本列表中。 + + + 正在分析 {0}。 + {0} should not be localized, is used to contain a file path. + + + 正在为首次使用准备模块。 + + + 正在搜索可用模块 + + + 正在搜索 UNC 共享 {0}。 + {0} should not be localized, is used to contain a file path. + + + 只能针对不包含路径的模块名称对远程计算机运行 Get-Module cmdlet。Name 参数中的元素 "{0}" 会解析为路径。请更新 Name 参数,使其不包含路径元素,然后重试。 + + + 对于包含路径的模块名称,不支持在不使用 ListAvailable 参数的情况下运行 Get-Module cmdlet。Name 参数中的元素 "{0}" 会解析为路径。请更新 Name 参数,使其不包含路径元素,然后重试。 + + + 找不到指定的模块 "{0}"。请更新 Name 参数,使其指向有效路径,然后重试。 + + + 正在填充模块 {0} 的 RepositorySourceLocation 属性。 + + + 未处理在模块清单 "{2}" 的字段 "{1}" 中列出的要处理模块 "{0}"。{3} + + + 此先决条件仅适用于 PowerShell Desktop 版本。 + + + 模块 "{0}" 不支持当前的 PowerShell 版本 "{1}"。其支持的版本为 "{2}"。使用 "Import-Module -SkipEditionCheck" 可忽略此模块的兼容性。 + + + 模块 "{0}" 支持 PowerShell 版本 "{1}",由于设置文件中已禁用 Windows 兼容性功能,因此无法使用该功能隐式加载。请使用 "Import-Module -UseWindowsPowerShell" 通过 Windows PowerShell 加载此模块,或使用 "Import-Module -SkipEditionCheck" 尝试使用当前 PowerShell 加载此模块。 + + + 应为模块清单中声明的实验性功能指定非空字符串值。 + + + 找到一个或多个无效的实验性功能名称: {0}。模块实验性功能名称应遵循此约定: "ModuleName.FeatureName"。 + + + 不能在不使用 -ListAvailable 开关参数的情况下使用 -SkipEditionCheck 开关参数。 + + + 在 ConstrainedLanguage 模式下,不允许将 *.ps1 文件作为模块导入。 + + + 加载脚本模块 {0} 时发生错误,因为它的语言模式与模块清单不同。清单语言模式为 {1},模块语言模式为 {2}。请确保所有模块文件都已签名,或以其他方式包含在应用允许列表配置中。 + + + 此模块在使用通配符导出函数时使用点源运算符,而在系统强制执行应用程序验证时,这是不允许的。 + + + 无法从语言模式与正在运行的会话不同的模块导出模块成员。 + + + 当会话处于 ConstrainedLanguage 模式时,无法创建新模块。 + + + 找不到与“核心”版本兼容的内置模块 "{0}"。请确保 PowerShell 内置模块可用。它们通常随 PowerShell 包一起位于 $PSHOME 模块路径下,并且是 PowerShell 正常运行所必需的。 + + + Export-ModuleMember Cmdlet + + + 在 Constrained Language 模式下导出模块成员将会失败,因为模块 "{0}" 的语言模式 "{1}" 与当前会话 "{2}" 的模式不同。 + + + 模块隐式函数导出 + + + 由于模块 "{0}" 受信任(在完整语言模式下运行),但会话不受信任(在受约束语言模式下运行),因此将拒绝隐式导出函数。最佳做法是始终按完整名称单独导出模块函数。 + + + 正在将脚本文件作为模块导入 + + + 在 ConstrainedLanguage 模式下,不允许将脚本文件 "{0}" 作为模块导入。 + + + 模块包含点源运算符 + + + 模块 "{0}" 的导入在 Constrained Language 模式下会失败,因为它在使用点源运算符的同时,还使用通配符导出函数。 + + + “模块导出函数 + + + 模块 "{0}" 使用名称通配符导出函数。在 Constrained Language 模式下运行时,任何嵌套模块的函数名称都将被删除。 + + + "New-Module Cmdlet + + + 系统将阻止来自不受信任的 Constrained Language 会话的新模块提供 FullLanguage 脚本块。 + + + “模块语言模式不匹配 + + + 正在加载的依赖模块的语言模式与父模块的不同。在受约束语言模式下,不允许这样做。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/MshHostRawUserInterfaceStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/MshHostRawUserInterfaceStrings.zh-Hans.resx new file mode 100644 index 00000000000..c0de2fd84a0 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/MshHostRawUserInterfaceStrings.zh-Hans.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}"。 + + + "{0}" 必须是一个正数。 + + + 所有字符串均为 null 或为空。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/MshSignature.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/MshSignature.zh-Hans.resx new file mode 100644 index 00000000000..ebc51d7e7af --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/MshSignature.zh-Hans.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 + + + 已验证签名。 + + + 文件 {0} 未进行数字签名。无法在当前系统上运行此脚本。有关运行脚本和设置执行策略的详细信息,请参阅 https://go.microsoft.com/fwlink/?LinkID=135170 处的 about_Execution_Policies + + + 文件 {0} 的内容可能已被未经授权的用户或进程更改,因为该文件的哈希与数字签名中存储的哈希不匹配。该脚本无法在指定的系统上运行。有关详细信息,请运行 Get-Help about_Signing。 + + + 文件 {0} 已签名,但此系统不信任签名者。 + + + 无法对文件进行签名,因为系统不支持对 {0} 文件执行签名操作。 + + + 无法对文件进行签名,因为系统不支持对没有文件扩展名的文件执行签名操作。 + + + 无法验证签名,因为它与当前系统不兼容。 + + + 无法验证签名,因为它与当前系统不兼容。哈希算法无效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/MshSnapInCmdletResources.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/MshSnapInCmdletResources.zh-Hans.resx new file mode 100644 index 00000000000..f5667fd0c09 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/MshSnapInCmdletResources.zh-Hans.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 + + + 无法执行操作。自定义 shell 不支持指定的 cmdlet。 + + + 找不到与模式“{0}”匹配的 PowerShell 管理单元。检查模式,然后重试该命令。 + + + 指定的管理单元名称的格式无效。 PowerShell 管理单元名称只能包含字母数字字符、短划线、下划线和句点。请更正名称,然后重试该操作。 + + + 无法添加 PowerShell 管理单元 {0},因为它是系统 PowerShell 模块。使用 Import-Module 加载模块。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/MshSnapinInfo.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/MshSnapinInfo.zh-Hans.resx new file mode 100644 index 00000000000..44e7be76ba9 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/MshSnapinInfo.zh-Hans.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 + + + 无法访问 PowerShell 注册表信息。 + + + 无法访问 PowerShell 引擎注册表信息。 + + + 无法访问 PublicKeyToken 信息。 + + + PowerShell 的版本 {0} 在此计算机上不可用。 + + + 此计算机上未安装 PowerShell 管理单元“{0}”。 + + + 没有指定注册表项 {1} 的必需值 {0}。 + + + 注册表项 {1} 的必需值 {0} 格式不正确。 格式应为 'string'。 + + + 注册表项 {1} 的必需值 {0} 格式不正确。 预期格式为 'multistring'。 + + + 在注册表中找不到所需的信息或缺少密钥文件。 无法加载部分 cmdlet。 + + + 尚未为 PowerShell 版本 {0} 注册任何管理单元。 + + + 无法检索字符串资源,因为阅读器已被释放。 + + + 未指定注册表项 {1} 的版本值 {0},或者该值不正确。 + + + 找不到 PowerShell 类型 {0} 的 [PSVersion] 属性。使用 [PSVersion(PowerShell SnapinBase.PSEngineVersion)] 将 PSVersion 属性添加到类型。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/NativeCP.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/NativeCP.zh-Hans.resx new file mode 100644 index 00000000000..0104024c3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/NativeCP.zh-Hans.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 + + + ScriptBlock should only be specified as a value of the Command parameter. + + + No value was specified for the Command parameter. + + + A value that is not valid ({6}) was specified for the {7} parameter. Valid values are Text and Xml. + + + No value was specified for the InputFormat parameter. Valid values are Text and Xml. + + + No value was specified for the OutputFormat parameter. Valid values are text and XML. + + + The {6} parameter requires a string value. + + + No value was specified for the Args parameter. + + + The {6} parameter was already specified. + + + Cannot process the XML from the '{0}' stream of '{1}': {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PSCommandStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PSCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..3360265e171 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PSCommandStrings.zh-Hans.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 + + + 添加参数需要命令。添加参数之前,必须首先向 {0} 添加命令。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PSConfigurationStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PSConfigurationStrings.zh-Hans.resx new file mode 100644 index 00000000000..bcff924d325 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PSConfigurationStrings.zh-Hans.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 + + + 由于安全问题,PowerShell 已停止工作: 无法读取配置文件: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PSDataBufferStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PSDataBufferStrings.zh-Hans.resx new file mode 100644 index 00000000000..57c14b71662 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PSDataBufferStrings.zh-Hans.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 + + + 指定的索引小于零或大于缓冲区中的项数。索引应在以下范围内: {0}-{1}。 + + + 无法将 null 引用转换为值类型。 + + + 无法将值从 {0} 类型转换为 {1} 类型。 + + + 无法将对象添加到已关闭的缓冲区。请确保缓冲区处于打开状态,以便成功执行“添加”和“插入”操作。 + + + 只有 PSObject 类型的 PSDataCollection 才能设置 SerializeInput 属性。请将 SerializeInput 属性设为 false,或将集合类型更改为 PSObject。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PSListModifierStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PSListModifierStrings.zh-Hans.resx new file mode 100644 index 00000000000..59889d4f7aa --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PSListModifierStrings.zh-Hans.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 + + + 检测到以下未知列表修饰符:“{0}”。有效的列表修饰符为“添加”、“移除”和“替换”。 + + + 无法应用更新,因为该对象不是受支持的集合类型。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PSStyleStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PSStyleStrings.zh-Hans.resx new file mode 100644 index 00000000000..c0e158b4817 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PSStyleStrings.zh-Hans.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 指定的字符串在仅应包含 ANSI 转义序列的情况下包含了可打印内容: {0} + + + 进度呈现的 MaxWidth 必须至少为 18 才能正确呈现。 + + + 添加或移除扩展时,扩展必须以句点开头。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ParameterBinderStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ParameterBinderStrings.zh-Hans.resx new file mode 100644 index 00000000000..2407ad71e59 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ParameterBinderStrings.zh-Hans.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 找不到与参数名称 '{1}' 匹配的参数。 + + + 找不到接受自变量 '{1}' 的位置参数。 + + + 参数 '{1}' 缺少自变量。请指定一个类型为 '{2}' 的参数,然后重试。 + + + 无法处理参数,因为参数名称 '{1}' 存在歧义。可能的匹配项包括:{6}。 + + + 无法将 '{6}' 转换为参数 '{1}' 所需的类型 '{2}'。{7} + + + 无法绑定参数 '{1}'。{6} + + + 无法绑定位置参数 '{1}'。 + + + 无法绑定位置参数,因为未提供名称。 + + + 无法使用指定的命名参数解析参数集。发出的一个或多个参数不能一起使用,或者提供的参数数量不足。 + + + 无法处理命令,因为缺少一个或多个必需参数:{1}。 + + + 无法在参数集 '{6}' 中指定参数 '{1}'。 + + + 无法绑定参数,因为多次指定了参数 '{1}'。若要向可接受多个值的参数提供多个值,请使用数组语法。例如,"-parameter value1,value2,value3"。 + + + 无法计算参数 '{1}',因为其自变量被指定为脚本块,并且没有输入。在没有输入的情况下,无法计算脚本块。 + + + 参数 '{1}' 的脚本块输入失败。{6} + + + 无法计算参数 '{1}',因为它的自变量输入未产生任何输出。 + + + 输入对象无法绑定到该命令的任何参数,因为该命令不接受管道输入,或者输入及其属性与任何接受管道输入的参数都不匹配。 + + + 无法绑定该输入对象,因为它不包含绑定所有必需参数所需的信息: {6} + + + 无法处理管道输入,因为无法检索参数 '{1}' 的默认值。{6} + + + 无法检索该 cmdlet 的动态参数。{6} + + + 请提供以下参数的值: + + + cmdlet {0} 位于命令管道位置 {1} + + + 无法处理参数 '{1}' 上的自变量转换。{6} + + + {6} + + + 无法验证参数 '{1}' 上的自变量。{6} + + + 无法将参数 '{1}' 绑定到目标。{6} + + + 无法将自变量绑定到参数 '{1}',因为它为 null。 + + + 无法将自变量绑定到参数 '{1}',因为它是空字符串。 + + + 无法将自变量绑定到参数 '{1}',因为它是空集合。 + + + 无法将自变量绑定到参数 '{1}',因为它是空数组。 + + + 无法处理命令。多次定义了参数 '{0}'。 + + + 无法绑定 cmdlet {0},因为参数 '{1}' 的类型为 '{2}',且无法识别 Add() 方法,或存在多个 Add() 方法。{6} + + + 无法绑定 cmdlet {0},因为运行时定义的参数 '{1}' 已使用键 '{6}' 添加到 RuntimeDefinedParameterDictionary。该键必须与 RuntimeDefinedParameter.Name 相同。 + + + 无法将自变量绑定到参数 '{1}',因为该自变量的 PSTypeNames 与参数所需的 PSTypeName 不匹配: {6}。 + + + 在 $PSDefaultParameterValues 中,为匹配以下名称或别名的参数定义了多个不同的默认值: {0}。已忽略这些默认值。 + + + 在 $PSDefaultParameterValues 中为此 cmdlet 定义的以下名称或别名将解析为多个参数: {0}。已忽略默认值。 + + + {6} 此错误可能是由于应用默认参数绑定造成的。你可以通过将 $PSDefaultParameterValues["Disabled"] 设置为 $true 来禁用 $PSDefaultParameterValues 中的默认参数绑定,然后重试。发生错误时,已成功为此 cmdlet 绑定以下默认参数:{7} + + + {6} 此失败可能是由于应用默认参数绑定造成的。你可以通过将 $PSDefaultParameterValues["Disabled"] 设置为 $true 来禁用 $PSDefaultParameterValues 中的默认参数绑定,然后重试。发生错误时,已成功为此 cmdlet 绑定以下默认参数:{7} + + + 将默认值 '{0}' 绑定到参数 '{1}' 失败: {2} + + + 键 '{0}' 的格式无效。有关正确格式的信息,请参阅 https://go.microsoft.com/fwlink/?LinkId=228266 处的 about_Parameters_Default_Values。 + + + 键 '{0}' 的格式无效。有关正确格式的信息,请参阅 https://go.microsoft.com/fwlink/?LinkId=228266 处的 about_Parameters_Default_Values。 + + + 参数 '{0}' 已过时。{1} + + + 类型为 '{1}' 的键 '{0}' 不是字符串值。DefaultParameterDictionary 仅接受字符串值键。 + + + 已将键 '{0}' 添加到字典。 + + + 不允许方法或属性调用 + + + 对于不受信任的脚本,在受约束语言模式下,不允许调用类型 '{1}' 上的方法或属性 '{0}'。 + + + 不允许创建类型 + + + 在受约束语言模式下,不允许在为不受信任的脚本进行参数绑定时创建类型 '{0}'。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ParserStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ParserStrings.zh-Hans.resx new file mode 100644 index 00000000000..ffa44b7718e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ParserStrings.zh-Hans.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Unable to find type [{0}]. + + + Unable to find type [{0}]. Details: {1} + + + Incomplete string token. + + + The Unicode escape sequence is not valid. A valid sequence is `u{ followed by one to six hex digits and a closing '}'. + + + The Unicode escape sequence value is out of range. The maximum value is 0x10FFFF. + + + The Unicode escape sequence is missing the closing '}'. + + + The Unicode escape sequence contains more than the maximum of six hex digits between braces. + + + Cannot use [ref] with other types in a type constraint. + + + [ref] can only be the final type in type conversion sequence. + + + Cannot have two occurrences of [ref] in a type sequence. + + + The numeric constant {0} is not valid. + + + The regular expression pattern {0} is not valid. + + + An empty ${} variable reference was found. A name is required inside the braces. + + + Variable reference is not valid. '$' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + You cannot call a method on a null-valued expression. + + + Method invocation failed because [{0}] does not contain a method named '{1}'. + + + Assignment failed because [{0}] does not contain a property '{1}()' that can be set. + + + Unexpected token '{0}' in expression or statement. + + + The splatting operator '@' cannot be used to reference variables in an expression. '@{0}' can be used only as an argument to a command. To reference variables in an expression use '${0}'. + + + Parameter '{0}' is not valid + + + Missing expression after '{0}' in pipeline element. + + + The expression after '{0}' in a pipeline element produced an object that was not valid. It must result in a command name, a script block, or a CommandInfo object. + + + Parameter {0} requires an argument. + + + Parameter {0} cannot have an argument. + + + Duplicate parameter ${0} in parameter list. + + + Missing argument in parameter list. + + + Splatted variables like '@{0}' cannot be part of a comma-separated list of arguments. + + + Missing file specification after redirection operator. + + + The '{0}' operator is reserved for future use. + + + Redirection to '{0}' failed: {1} + + + Expressions are only allowed as the first element of a pipeline. + + + An empty pipe element is not allowed. + + + The assignment expression is not valid. The input to an assignment operator must be an object that is able to accept assignments, such as a variable or a property. + + + A hash table can only be added to another hash table. + + + The right operand of '-is' must be a type. + + + The right operand of '-as' must be a type. + + + Error formatting a string: {0}. + + + The argument to operator '{0}' is not valid: {1}. + + + The '{0}' operator failed: {1}. + + + The {0} operator allows only two elements to follow it, not {1}. + + + You must provide a value expression following the '{0}' operator. + + + The '{0}' operator works only on variables or on properties. + + + The {0} attribute can be specified only on a hash literal node. + + + Array index expression is missing or not valid. + + + Missing property name after reference operator. + + + The property '{0}' cannot be found on this object. Verify that the property exists and can be set. + + + The property '{0}' cannot be found on this object. Verify that the property exists. + + + Index operation failed; the array index evaluated to null. + + + Cannot index into a null array. + + + Unable to index into an object of type "{0}". + + + Unable to index into an object of type "{0}" with the ByRef-like return type "{1}". ByRef-like types are not supported in PowerShell. + + + The array has too many dimensions: {0}. The number of dimensions for an array must be less than or equal to 32. + + + Array assignment to [{0}] failed because assignment to slices is not supported. + + + You cannot index into a {0} dimensional array with index [{1}]. + + + Array assignment failed because index '{0}' was out of range. + + + Missing expression after '{0}'. + + + ${{variable}} reference starting is missing the closing '}}'. + + + $(subexpression) is missing the closing ')'. + + + Internal error - unexpected unary operator {0}. + + + [ref] cannot be applied to a variable that does not exist. + + + The variable '${0}' cannot be retrieved because it has not been set. + + + Duplicate keys '{0}' are not allowed in hash literals. + + + Duplicate named arguments '{0}' are not allowed. + + + The '{0}' operator works only on numbers. The operand is a '{1}'. + + + An expression was expected after '('. + + + Missing '=' operator after key in hash literal. + + + Missing statement after '=' in hash literal. + + + Missing statement after '=' in named argument. + + + Missing ';' or end-of-line in property definition. + + + Missing expression after unary operator '{0}'. + + + Missing condition in if statement after '{0} ('. + + + Missing statement block after {0} ( condition ). + + + Missing statement block after 'else' keyword. + + + The file could not be read: {0}. + + + The current provider ({0}) cannot open a file. + + + No files matching '{0}' were found. + + + The path cannot be processed because it resolved to more than one file; only one file at a time can be processed. + + + The {0} '-{1}' parameter is reserved for future use. + + + Cannot process the 'switch' statement because of a missing file name argument to the -file option. + + + The file name argument to -file in the switch statement is not valid. + + + The parameter {0} is not valid for the switch statement. + + + The parameter {0} is not valid for the foreach statement. + + + A switch statement must have one of the following: '-file file_name' or '( expression )'. + + + Missing condition in switch statement clause. + + + A switch statement can have only one default clause. + + + Missing statement block in switch statement clause. + + + Missing expression in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing statement body in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + The param statement cannot be used if arguments were specified in the function declaration. + + + The operation '[{0}] {1} [{2}]' is not defined. + + + An error occurred while enumerating through a collection: {0}. + + + An unhandled COM interop exception occurred: {0} + + + A COM object was accessed after it was already released: {0} + + + Processing was stopped because the script is too complex. + + + The syntax is not supported by this runspace. This can occur if the runspace is in no-language mode. + + + The combination of options with the -split operator is not valid. + + + Options are not allowed on the -split operator with a predicate. + + + The token '{0}' is not a valid statement separator in this version. + + + The '{0}' keyword is not supported in this version of the language. + + + Missing expression after '{0}' in loop. + + + Missing statement body in {0} loop. + + + The 'trap' statement was incomplete. A trap statement requires a body. + + + Incomplete 'try' statement. A try statement requires a body. + + + Parameter declarations are a comma-separated list of variable names with optional initializer expressions. + + + Missing function body in function declaration. + + + Script command clause '{0}' has already been defined. + + + unexpected token '{0}', expected 'begin', 'process', 'end', 'clean', or 'dynamicparam'. + + + Missing closing '}' in statement block or type definition. + + + Missing ')' in method call. + + + Missing ']' after array index expression. + + + Missing closing ')' in expression. + + + Missing closing ')' in subexpression. + + + Missing '(' after '{0}' in if statement. + + + Missing ')' after expression in switch statement. + + + Missing '{' in switch statement. + + + Missing variable name after foreach. +The correct form is: foreach ($a in $b) {...} + + + Missing 'in' after variable in foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing closing ')' after expression part of foreach loop. +The correct form is: foreach ($a in $b) {...} + + + Missing opening '(' after keyword '{0}'. + + + Missing while or until keyword in do loop. + + + Missing closing ')' after expression in '{0}' statement. + + + Missing name after {0} keyword. + + + Missing ')' in function parameter list. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded. + + + An error '{0}' occurred while processing this script. Text describing this error could not be loaded due to error '{1}'. + + + There is no Runspace available to run scripts in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to invoke was: {0} + + + Unrecognized token in source text. + + + Action to take for this exception: + + + &Continue + + + Report the error then continue with the next script statement. + + + S&ilently Continue + + + Do not report this error, just continue with the next script statement. + + + &Break + + + Do not continue processing, throw the exception instead. + + + &Suspend + + + Pause the current pipeline and return to the command prompt. Type exit to resume operation when you are done. + + + Cannot run a document in the middle of a pipeline: {0}. + + + Program '{0}' failed to run: {1}{2}. + + + Cannot use '&' to invoke in the context of binary module '{0}'. Specify a non-binary module after the '&' and try the operation again. + + + Cannot use '&' to invoke in the context of module '{0}' because it is not imported. Import the module '{0}' and try the operation again. + + + Executable script code found in signature block. + + + line + + + At {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'. + + + ! CALL function '{0}' + + + ! CALL function '{0}' (defined in file '{1}') + + + ! CALL method '{0}' + + + The string is missing the terminator: {0}. + + + White space is not allowed before the string terminator. + + + Missing ] at end of type token. + + + Use `{ instead of { in variable names. + + + The Data section is missing its statement block. + + + The "{0}" parameter of the Data section is not valid. The valid Data section parameter is SupportedCommand. + + + Array references are not allowed in restricted language mode or a Data section. + + + Assignment statements are not allowed in restricted language mode or a Data section. + + + Redirection is not allowed in restricted language mode or a Data section. + + + The Do and While statements are not allowed in restricted language mode or a Data section. + + + Expandable strings are not allowed in restricted language mode or a Data section. + + + The '{0}' operator is not allowed in restricted language mode or a Data section. + + + The Trap statement is not allowed in restricted language mode or a Data section. + + + The Try statement is not allowed in restricted language mode or a Data section. + + + Flow control statements such as Break, Continue, Return, Exit, and Throw are not allowed in restricted language mode or a Data section. + + + Foreach statements are not allowed in restricted language mode or a Data section. + + + For and While statements are not allowed in restricted language mode or a Data section. + + + Function declarations are not allowed in restricted language mode or a Data section. + + + Method calls are not allowed in restricted language mode or a Data section. + + + Parameter declarations are not allowed in restricted language mode or a Data section. + + + Property references are not allowed in restricted language mode or a Data section. + + + Script block literals are not allowed in restricted language mode or a Data section. + + + The switch statement is not allowed in restricted language mode or a Data section. + + + A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: {0}. + + + The command '{0}' is not allowed in restricted language mode or a Data section. + + + The data statement is not allowed in restricted language mode or another Data section. + + + The SupportedCommand parameter of the Data section is missing a value. Supply a cmdlet or function name to the parameter. + + + A Begin statement block, Process statement block, or parameter statement is not allowed in a Data section. + + + String multiplication results with more than "{0}" characters are not allowed in restricted language mode or a Data section. + + + Array multiplication resulting in more than {0} elements is not allowed in restricted language mode or a Data section. + + + Dot sourcing is not allowed in restricted language mode or a Data section. + + + Attribute argument must be a constant or a script block. + + + Cannot find the type for custom attribute '{0}'. Make sure that the assembly that contains this type is loaded. + + + Property '{0}' cannot be found for type '{1}'. + + + Unexpected attribute '{0}'. + + + Missing ] at end of attribute or type literal. + + + The function or command was called as if it were a method. Parameters should be separated by spaces. For information about parameters, see the about_Parameters Help topic. + + + The Try statement is missing its statement block. + + + The Try statement is missing its Catch or Finally block. + + + The Catch block is missing its statement block. + + + The Finally block is missing its statement block. + + + Exception type {0} is already handled by a previous handler. + + + Catch block must be the last catch block. + + + Missing type literal. + + + The terminator '#>' is missing from the multiline comment. + + + No characters are allowed after a here-string header but before the end of the line. + + + Parser errors were detected. + + + Missing statement block after '{0}'. + + + Unexpected type [{0}] was found in the parameter statement. + + + Unexpected type [{0}] was found before statement. + + + A null key is not allowed in a hash literal. + + + Attributes are not allowed in restricted language mode or a Data section. + + + The type {0} is not allowed in restricted language mode or a Data section. + + + '{0}' is a ReadOnly property. + + + The type name is missing the assembly name specification. + + + Flow of control cannot leave a Finally block. + + + Unrecoverable error in PowerShell. + + + An AST cannot be used as the child of more than one AST. To use this AST in another AST, call the Copy() method and use its result. + + + Expression is not allowed in a Using expression. + + + A Using variable cannot be retrieved. A Using variable can be used only with Invoke-Command, Start-Job, or InlineScript in the script workflow. When it is used with Invoke-Command, the Using variable is valid only if the script block is invoked on a remote computer. + + + Variable reference is not valid. The variable name is missing. + + + Variable reference is not valid. ':' was not followed by a valid variable name character. Consider using ${} to delimit the name. + + + Not all parse errors were reported. Correct the reported errors and try again. + + + Missing type name after '['. + + + * stream + + + debug stream + + + error stream + + + output stream + + + The {0} for this command is already redirected. + + + verbose stream + + + warning stream + + + Missing statement body after keyword '{0}'. + + + Parallel and sequence blocks are not allowed in restricted language mode or a Data section. + + + Unexpected keyword '{0}'. + + + [void] cannot be used as a parameter type, or on the left side of an assignment. + + + The method cannot be invoked. + + + Cannot convert hashtable to an object of the following type: {0}. Hashtable-to-Object conversion is not supported in restricted language mode or a Data section. + + + Argument must be constant. + + + The argument for the {0} parameter is not valid. Specify a valid string argument. + + + The argument for the Module parameter is not valid. {0} + + + The argument for the Version parameter is not valid. Specify a valid PowerShell version, in the format major.minor version. + + + The argument for the {0} parameter is not valid. Specify a valid PowerShell edition. + + + The argument for the {0} parameter contains duplicate values. Do not specify duplicate PowerShell edition values. + + + Wildcard characters are not supported for module names. + + + Cannot invoke method. Method invocation is supported only on core types in this language mode. + + + Cannot set property. Property setting is supported only on core types in this language mode. + + + An attribute name for resource '{0}' was found that is not valid. An attribute name must be a simple string, and cannot contain variables or expressions. Replace '{1}' with a simple string. + + + The member '{0}' is not valid. Valid members are +'{1}'. + + + Missing '{' in object definition. + + + A required name or expression was missing. + + + The schema file {0} was not found. Verify that any modules specified in a configuration statement contain a schema.mof file, and then try running the script again. + + + Cannot define data section. Definition of additional supported commands is not supported in this language mode. + + + Missing '{' in configuration statement. + + + Exception parsing MOF file '{0}':{1}. + + + The name for the configuration is missing. Provide the missing name as a simple name, string, or string-valued expression. + + + Could not find the module '{0}'. + + + Multiple versions of the module '{0}' were found. You can run 'Get-Module -ListAvailable -FullyQualifiedName {0}' to see available versions on the system, and then use the fully qualified name '@{{ModuleName="{0}"; RequiredVersion="Version"}}'. + + + The ThrottleLimit parameter of the foreach statement is missing a value. Supply a throttle limit to the parameter. + 'ThrottleLimit' must not be localized. + + + The ThrottleLimit parameter is only supported on foreach statements that use the Parallel parameter. + 'ThrottleLimit' and 'Parallel' must not be localized. + + + The configuration block results were null or empty. Verify that configurations were defined in the block. + + + The '{0}' resource can only be used once per configuration, and therefore cannot have a name. Remove '{1}', and then run the script again. + + + There is an incomplete property assignment block in the instance definition. + + + Missing '=' operator after key in property assignment. + + + Duplicate property assignments are not allowed in an instance definition. + + + A second CIM class definition for '{0}' was found while processing the schema file '{1}'. This class was already defined in the file(s) '{2}'. Remove the redundant definition, and then try again. + + + Resource name '{0}' is already being used by another Resource or Configuration. + + + The class name '{0}' does not match '{1}', the name of the file in which it is defined. Rename either the file name to match the class name or vice versa + + + A duplicate resource identifier '{0}' was found while processing the specification for node '{1}'. Change the name of this resource so that it is unique within the node specification. + + + There is no whitespace between the name and the scriptblock in dynamic keyword '{0}' body statement. + + + The key property for an entry in the dictionary of functions to define cannot be empty because the key property is used as the function name. Specify a non-empty string as the value of the key property, and then try the operation again. + + + The format of the resource reference '{0}' in the Requires list for resource '{1}' is not valid. A required resource name should be in the format '[<typename>]<name>', with alphanumeric characters, spaces, '_', '-', '.' and '\'. + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + The format of the resource reference '{0}' in the exclusive list for resource '{1}' is not valid. An exclusive resource name should be in the format '<typename>\<name>', with no spaces. + + + The PartialConfiguration '{0}' is set to pull mode which requires a ConfigurationSource property. + + + A null entry was found in the list of variable entries to create in the script block scope. Remove the entry at index {0}, or replace it with a non-null entry, and then try again. + + + The script block that defines function '{0}' cannot be null or empty. Provide a non-empty script block in the function definition dictionary, and then try the operation again. + + + The syntax of the Import-DscResource dynamic keyword is: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]. + +Name : Names of one or more resources to import. +ModuleName : Module names or ModuleSpecification objects of one or more modules to import. +ModuleVersion : Version of module to import. If used, ModuleName must represent only one module by name. + + + Import-DscResource dynamic keyword supports only one module when Name parameter is specified. + + + Positional parameters are not supported for the Import-DscResource dynamic keyword. The syntax of Import-DscResource dynamic keyword is: "Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + Unable to load resource '{0}': Resource not found. + + + Configuration keyword is not allowed in constrainedLanguage mode. + + + The configuration name '{0}' is not valid. Standard names may only contain letters (a-z, A-Z), numbers (0-9), period (.), hyphen (-) and underscore (_). The name may not be null or empty, and should start with a letter. + + + Configuration only supports the End block in its body. Begin, Process and DynamicParam blocks are not allowed in a configuration. + + + Cim deserializer threw an error when deserializing file {0}. + + + '{0}' is not a valid value for property '{1}' on class '{2}'. Please change the value to one of the following strings: {3}. + + + At least one of the values '{0}' is not supported or valid for property '{1}' on class '{2}'. Please specify only supported values: +{3}. + + + Resource '{0}' requires that a value of type '{1}' be provided for property '{2}'. + + + Property '{0}' of Resource '{1}' has value '{2}' which is not between valid range '{3}' and '{4}'. + + + Failed to load the PowerShell data file '{0}' with the following error: +{1} + + + Cannot resolve the path '{0}' to a single .psd1 file. + + + The PowerShell data file '{0}' is invalid since it cannot be evaluated into a Hashtable object. + + + Configuration is not supported on WinPE. + + + If the expression passed to the Where() operator is null then you must specify a non-Default value for the selection mode argument. Please change the value of the mode argument to a value other than Default and try running your script again. + + + The generic collection type [{0}] passed to ForEach() has too many type arguments. Please change the specified type to be a generic collection with only one type argument then try running your script again. + + + Unable to convert input to the target type [{0}] passed to the ForEach() operator. Please check the specified type and try running your script again. + + + Script block with a 'clean' block is not supported by the 'ForEach' method. + + + The 'numberToReturn' value provided to the third argument of the Where() operator must be greater than zero. Please correct the argument's value and try running your script again. + + + Redirection only allows another stream to be merged with the output stream. Please correct the redirection operation to merge into the output stream then try running your script again. + + + The ForEach() operator could not find a member '{0}' on the target object. Please verify that the named member exists and then try running your script again. + + + The '{0}' keyword is not supported in this version of the language. + + + The '{0}' property is not supported in this version of the language. + + + Duplicate '{0}' qualifier + + + Modifier '{0}' cannot be combined with '{1}' + + + Missing using directive + + + Missing namespace alias + + + Missing '=' operator + + + Missing using name + + + Variable is not assigned in the method. + + + Missing a property name or method definition. + + + The member '{0}' is already defined. + + + Only one type may be specified on class members. + + + Error during creation of type "{0}". Error message: +{1} + + + Cannot convert the value to type "{0}". + + + Property '{0}' cannot be found for attribute '{1}'. Specify one of the following properties: {2}. + + + Attribute '{0}' is not valid on this declaration. It is valid on '{1}' declarations only. + + + Attribute argument must be a constant. + + + Undefined DSC resource '{0}'. Use Import-DSCResource to import the resource. + + + Exception occurred when pre-parsing dynamic keyword '{0}' with details '{1}'. + + + Exception occurred when post-parsing dynamic keyword '{0}' with details '{1}'. + + + Workflow is not supported in PowerShell 6+. + + + Meta Configuration resource {0} is not allowed in the regular configuration. Use meta configuration resources in a configuration with [DscLocalConfigurationManager()] attribute. + + + Regular DSC resource {0} is not allowed in the meta configuration. + + + There is no Runspace available to get and run the SteppablePipeline in this thread. You can provide one in the DefaultRunspace property of the System.Management.Automation.Runspaces.Runspace type. The script block you attempted to get SteppablePipeline from was: {0} + + + There are valid conversions from {0} to {1}. + + + Cannot perform call. + + + Cannot retrieve type information. + + + Could not get dispatch ID for {0} (error: {1}). + + + Cannot find an overload for "{0}" and the argument count: "{1}" + + + Error while invoking {0}. Could not find member. + + + Error while invoking {0}. Named arguments are not supported. + + + Error while invoking {0}. Overflow detected. + + + Error while invoking {0}. A required parameter was omitted. + + + Exception setting "{0}": Cannot convert the "{1}" value of type "{2}" to type "{3}". + + + IDispatch::GetIDsOfNames behaved unexpectedly for {0}. + + + Marshal.SetComObjectData failed. + + + Unexpected VarEnum {0}. + + + Attempting to pass an event handler of an unsupported type. + + + Configuration keyword is not supported in PowerShell 6+. + + + Not all code path returns value within method. + + + Invalid return statement within void method. + + + Invalid return statement within non-void method. + + + Missing '{0}' body in '{0}' declaration. + + + Cannot define enum because of a cycle in the initialization expressions. + + + Enumerator value is either too large or too small for {0}. + + + Enumerator value must be a constant value. + + + Exception occurred when performing semantic check for dynamic keyword '{0}' with details '{1}'. + + + The '{0}' property with type '{1}' of DSC resource class '{2}' is not supported. + + + Missing '(' in class method parameter list. + + + A named block is not allowed in a class method. + + + A param block is not allowed in a class method. + + + Cannot inherit from sealed class '{0}'. + + + Type name expected. + + + '{0}' is not a valid underlying type for enums. Expected a builtin integral type (one of byte, sbyte, short, ushort, int, uint, long or ulong) + + + '{0}': Interface name expected. + + + Base class '{0}' does not contain a parameterless constructor. + + + Invalid base type '{0}'. Base type cannot be an array. + + + Invalid base type '{0}'. Base type cannot be a generic with unspecified parameters. + + + Missing 'base' after ':' in a base class constructor call. + + + A constructor cannot specify a return type. + + + The DSC resource '{0}' has no default constructor. + + + The DSC resource '{0}' is missing a Get method that returns [{0}] and accepts no parameters. + + + The DSC resource '{0}' must have at least one key property (using the syntax [DscProperty(Key)].) + + + The DSC resource '{0}' is missing a Set method that returns [void] and accepts no parameters. + + + The DSC resource '{0}' is missing a Test method that returns [bool] and accepts no parameters. + + + A static constructor cannot have any parameters. + + + The type '{0}' is not allowed on a property. + + + The type '{0}' is not allowed on a parameter. + + + Cannot access the non-static member '{0}' in a static method or initializer of a static property. + + + Failed to parse module script file '{0}' with error +'{1}'. + + + Cannot run a document in PowerShell: {0}. + + + Multiple type constraints are not allowed on a method parameter. + + + This script contains malicious content and has been blocked by your antivirus software. + + + '{0}' cannot be specified in LocalConfigurationManager resource. Please switch to Settings instead or use only following values: {1}. + + + '{0}' is defined in a generic type. + + + Type name '{0}' is ambiguous, it could be '{1}' or '{2}'. + + + A 'using' statement must appear before any other statements in a script. + + + This syntax of the 'using' statement is not supported. + + + The specified namespace in the 'using' statement contains invalid characters. + + + information stream + + + Invalid key property. The key property must be of [string], signed/unsigned integer, or Enum types. + + + Invalid Get method. Get method must return [{0}] and accepts no parameters. + + + 无法加载程序集“{0}”。 + + + Cannot use assembly with an UNC path: '{0}'. + + + Cannot use assembly with uri schema '{0}'. + + + Missing a newline or semicolon. + + + Cannot assign property, use '{0}{1}'. + + + '{0}' is not a valid value for using name. + + + Cannot assign property, use '{0}{1}'. + + + DebugMode should only have one value. + + + Label '{0}' not found inside the method. + + + Failed to convert the value of CimProperty {0} to the property value of class {1}. + + + Property {0} of PowerShell class {1} is not declared as array type, but defined in its configuration instance as instance array type. + + + Failed to create an object of PowerShell class {0}. + + + The hashtable supplied to the Desired State Configuration resource {0} is not valid. The key or value cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + The username supplied to the Desired State Configuration resource {0} is not valid. The username cannot be null or empty. + + + Property {0} is not declared in PowerShell class {1}, but defined in its configuration instance. + + + PartialConfiguration '{0}' has a Refresh Mode set to Disabled which is not a valid mode for Partial Configurations. Use Pull or Push refresh mode. + + + Cannot create type. Only core types are supported in this language mode. + + + Import-DscResource cannot be specified inside of Node context + + + $PSCulture, $PSUICulture, $true, $false, $null + + + Cannot assign automatic variable '{0}' with type '{1}' + + + Conflict in using PsDscRunAsCredential for Resource {0} because it already specifies PsDscRunAsCredential value. We can only use one PsDscRunAsCredential for the composite resource. + + + Unable to find DSC schema store at "{0}". Please ensure PSDesiredStateConfiguration v3 module is installed. + + + {0} + + + This script contains content that has been flagged as suspicious through a policy setting and has been blocked with error code {0}. Contact your administrator for more information. + + + Cannot use '&' or '.' operators to invoke a module scope command across language boundaries. + + + Class keyword is not allowed in ConstrainedLanguage mode. + + + Missing ':' in the ternary expression. + + + A pipeline chain operator must be followed by a pipeline. + + + Background operators can only be used at the end of a pipeline chain. + + + Directly invoking the 'clean' block of a script block is not supported. + + + Parser Configuration Keyword + + + The Configuration keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Class Keyword + + + The Class keyword will not be allowed in Constrained Language mode for untrusted script. + + + Parser Data Section SupportedCommand + + + The Data Section that includes the SupportedCommand parameter would be disallowed in Constrained Language mode for untrusted script. + + + Module Scope Call Operator + + + The module scope call operator will be denied in Constrained Language mode. + + + ForEach Keyword Method Invocation + + + The ForEach keyword will fail '{0}' iteration item method invocation when run in Constrained Language mode. + + + Expression Evaluation May Fail + + + Creating a steppable pipeline from a script block may require evaluating some expressions within the script block. The expression evaluation will silently fail and return 'null' in Constrained Language mode, unless the expression represents a constant value. + + + Configuration keyword is not supported on ARM64 processors. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PathUtilsStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PathUtilsStrings.zh-Hans.resx new file mode 100644 index 00000000000..5eb24717cb8 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PathUtilsStrings.zh-Hans.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 编码 "UTF-7" 已过时,请使用 UTF-8。 + + + 文件 {0} 已存在,且已指定 {1}。 + + + 无法打开文件,因为当前提供程序({0})无法打开文件。 + + + 无法执行操作,因为路径解析为多个文件。此命令无法对多个文件执行操作。 + + + 无法执行操作,因为通配符路径 {0} 未解析为文件。 + + + 未知编码 {0}; 有效值为 {1}。 + + + 目录“{0}”已存在。 如果要覆盖目录及其中的文件,请使用 -Force 参数。 + + + 用户模块路径不存在,因此无法为所提供的模块名称“{0}”创建模块文件夹。 + + + 由于以下原因,无法创建模块 {0}: {1}。请为 -OutputModule 参数使用其他自变量,然后重试。 + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + 无法加载该模块,因为它是使用与 {0} cmdlet 不兼容的版本生成的。请使用当前会话中的 {0} cmdlet 生成该模块,然后再次尝试加载该模块。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PipelineStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PipelineStrings.zh-Hans.resx new file mode 100644 index 00000000000..b7f4a97b0b0 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PipelineStrings.zh-Hans.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法处理 cmdlet 实例,因为该 cmdlet 实例正由另一个管道使用。请与 Microsoft 客户支持服务联系。 + + + 无法执行该操作,因为管道已启动。停止管道,然后重试该操作。 + + + 无法继续运行 cmdlet,因为停止策略已阻止运行 cmdlet。 + + + 无法运行管道,因为管道中的第一个 cmdlet 正在尝试从前面的 cmdlet 结果中读取输入。修改第一个 cmdlet,移除第一个 cmdlet,或将第一个 cmdlet 需要其输出的 cmdlet 添加到管道,然后尝试再次运行管道。 + + + 无法处理 cmdlet 编号。ReadFromCommand 函数必须指定已添加到管道的 cmdlet 的 ID。请与 Microsoft 客户支持服务联系。 + + + 无法读取 ReadFromCommand 和 ReadErrorQueue 函数的输出,因为另一个 cmdlet 已在读取该输出。请与 Microsoft 客户支持服务联系。 + + + 无法运行管道,因为不存在命令。将至少一个命令添加到管道,然后再次运行它。 + + + 无法完成管道操作,因为它尚未启动。在可分步执行管道上调用 End()之前,必须调用 Begin()方法。 + + + 无法从 BeginProcessing、ProcessRecord 和 EndProcessing 方法的替代项之外调用 WriteObject 和 WriteError 方法,并且只能从同一线程内部调用它们。验证 cmdlet 是否正确进行这些调用,或与 Microsoft 客户支持服务联系。 + + + cmdlet 在调用 ThrowTerminatingError 后引发了异常。 +第一个异常为“{0}”,堆栈跟踪为“{1}”。 +第二个异常为“{2}”,堆栈跟踪为“{3}”。 + + + 关闭管道后,无法调用 WriteObject 和 WriteError 方法。请与 Microsoft 客户支持服务联系。 + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}";value="{2}" + + + 创建管道时发生错误。 + + + 此管道不支持断开连接-连接语义。 + + + 无法连接此管道,因为它未处于断开连接的状态。 + + + 运行空间对象具有与之关联的 null 远程命令。 无法创建断开连接的 RemotePipeline 对象,因为未指定远程命令。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/PowerShellStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/PowerShellStrings.zh-Hans.resx new file mode 100644 index 00000000000..aee0e5ea389 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/PowerShellStrings.zh-Hans.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 + + + 当前 PowerShell 实例的状态对此操作无效。 + + + 无法执行该操作,因为已启动命令。请等待命令完成,或停止该命令,然后重试该操作。 + + + 未指定任何命令。 + + + PowerShell 实例未处于正确状态,无法创建嵌套 PowerShell 实例。应仅在正在运行的 PowerShell 实例中创建嵌套 PowerShell 实例。 + + + 无法执行操作,因为运行空间未处于“{0}”状态。运行空间的当前状态为“{1}”。 + + + 无法异步调用嵌套 PowerShell 实例。使用 Invoke 方法。 + + + {0} 对象不是通过在此 PowerShell 实例上调用 {1} 来创建的。 + + + 当运行空间设置为重用线程时,调用设置中的单元状态必须与运行空间匹配。 + + + 当运行空间设置为使用当前线程时,调用设置中的单元状态必须与当前线程的单元状态匹配。 + + + 添加参数需要命令。在添加参数之前,必须将命令添加到 PowerShell 实例。 + + + 字典中的键必须是字符串。 + + + 没有可在此线程中运行命令的运行空间。可以在 System.Management.Automation.Runspaces.Runspace 类型的 DefaultRunspace 属性中提供一个。尝试调用的命令为: {0} + + + 无法连接此 PowerShell 对象,因为它未与远程运行空间或运行空间池关联。 + + + 已断开正在运行的命令已断开连接,但仍在远程服务器上运行。 重新连接以获取命令操作状态和输出数据。 + + + 无法执行此操作,因为当前 PowerShell 会话处于“已断开连接”状态。 连接此 PowerShell 会话,然后等待命令完成或停止该命令。 + + + 无法执行此操作,因为当前 PowerShell 会话处于“已断开连接”状态。 连接此 PowerShell 会话,然后重试。 + + + 对远程命令的连接尝试失败。 + + + 无法执行该操作,因为命令当前正在停止。等待命令完成停止,然后重试该操作。 + + + 没有可在此线程中运行命令的运行空间。可以在 System.Management.Automation.Runspaces.Runspace 类型的 DefaultRunspace 属性中提供一个。当前 PowerShell 实例不包含要调用的命令。 + + + 无法创建使用当前运行空间的 PowerShell 对象,因为当前没有可用的运行空间。 当前运行空间可能正在启动,例如在初始会话状态下创建它时会出现此情况。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ProgressRecordStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ProgressRecordStrings.zh-Hans.resx new file mode 100644 index 00000000000..ccc175ee58a --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ProgressRecordStrings.zh-Hans.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} 不能为负值。 + + + 无法处理参数,因为 {0} 的值不能为 null 或为空。 + + + 无法设置百分比,因为 {0} 不能大于 100。 + + + ParentActivityId 不能与 ActivityId 相同。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ProviderBaseSecurity.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ProviderBaseSecurity.zh-Hans.resx new file mode 100644 index 00000000000..766324f75e0 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ProviderBaseSecurity.zh-Hans.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 + + + 无法使用接口,因为此提供程序不支持 ISecurityDescriptorCmdletProvider 接口。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/ProxyCommandStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/ProxyCommandStrings.zh-Hans.resx new file mode 100644 index 00000000000..c4d74726f95 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/ProxyCommandStrings.zh-Hans.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 + + + 未将 'help' 参数识别为由 'get-help' 命令创建的有效 HelpInfo 对象。 + + + 无法生成代理命令,因为 CommandMetadata 没有名称。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/RegistryProviderStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/RegistryProviderStrings.zh-Hans.resx new file mode 100644 index 00000000000..63cca6e64ce --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/RegistryProviderStrings.zh-Hans.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + 清除项 + + + 项: {0} + + + 新建项 + + + 项: {0} + + + 移除键 + + + 项: {0} + + + 复制键 + + + 项: {0} 目标: {1} + + + 重命名项 + + + 项: {0} NewName: {1} + + + 移动项 + + + 项: {0} 目标: {1} + + + 设置属性 + + + 项: {0} 属性: {1} + + + 清除属性 + + + 项: {0} 属性: {1} + + + 新属性 + + + 项: {0} 属性: {1} + + + 移除属性 + + + 项: {0} 属性: {1} + + + 重命名属性。 + + + 项: {0} SourceProperty: {1} DestinationProperty: {2} + + + 复制属性 + + + Item: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 移动属性 + + + Item: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 未处理该操作。所提供的位置不允许执行此操作。 + + + 不允许对源位置执行此操作。 + + + 不允许对目标位置执行该操作。 + + + 本地计算机的配置设置 + + + 当前用户的软件设置 + + + 此路径中的键已存在。 + + + 无法执行该操作,因为目标路径从属于源路径。 + + + 属性已存在。 + + + 路径 {1} 中不存在属性 {0}。 + + + 指定路径中的注册表项不存在。 + + + 无法绑定参数 'Type'。无法将“{0}”转换为“{1}”。可能的枚举值为“String、ExpandString、Binary、DWord、MultiString、QWord、Unknown”。 + + + 已创建键 {0},但无法设置默认值。 + + + 无法创建具有指定根的驱动器。根路径不存在。 + + + 无法重命名该项,因为同一容器中已存在具有该名称的项。 + + + 注册表项名称必须以有效的基项名称开头。 + + + 子项参数无效。 + + + 无法删除子项树,因为子项不存在。 + + + 不存在具有该名称的值。 + + + 枚举值 {0} 无效。 + + + 必须指定值参数。 + + + 必须指定名称参数。 + + + 指定的 RegistryValueKind 是无效的值。 + + + RegistryKey.SetValue 不允许使用包含 null 字符串引用的 String[]。 + + + 注册表子项不应超过 255 个字符。 + + + 必须指定非空子项名称。 + + + 值对象的类型与指定的 RegistryValueKind 不匹配,或者无法正确转换该对象。 + + + RegistryKey.SetValue 不支持类型为“{0}”的数组。仅支持 Byte[] 和 String[]。 + + + 指定的注册表项不存在。 + + + 指定值名称的长度超过了最大 16383 个字符。 + + + 指定值数据的大小超出了最大值 1 MB。 + + + 指定的注册表子项不存在。 + + + 指定的 RegistryKeyPermissionCheck 值无效。 + + + 注册表项包含子项;此方法不支持递归移除。 + + + 如果没有 Transaction.Current 或指定的事务,则无法创建 KTM 句柄。 + + + 指定的事务或 Transaction.Current 必须与用于创建或打开此 TransactedRegistryKey 的事务匹配。 + + + TransactedRegistryKey 对象未与事务关联,因为它用于预定义的键。 + + + 不允许请求的注册表访问。 + + + 已拒绝访问注册表项“{0}”。 + + + 无法写入注册表项。 + + + 无法访问已关闭的注册表项。 + + + 未知错误: {0}。 + + + 此平台不支持注册表事务。 + + + 指定的句柄无效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/RemotingErrorIdStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/RemotingErrorIdStrings.zh-Hans.resx new file mode 100644 index 00000000000..917ffd46890 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/RemotingErrorIdStrings.zh-Hans.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 出现类型为 "{0}" 的错误。 + + + 进程内存不足。 + + + 使用 -ComputerName 的远程 PSSession 枚举仅在 Windows 上受支持,在 "{0}" 上不受支持。 + + + 管道 ID "{0}" 与当前正在运行的管道的 InstanceId "{1}" 不匹配。 + + + 在服务器上找不到管道 ID "{0}"。 + + + 远程管道已停止。 + + + 该会话已存在。不允许再次尝试使用相同的 InstanceId {0} 创建会话。 + + + 指定的客户端会话 InstanceId "{0}" 与现有会话的 InstanceId "{1}" 不匹配。 + + + 打开远程会话失败。 + + + 找不到客户端 InstanceId 为 "{0}" 的指定远程会话。 + + + 提示响应具有找不到的提示 ID "{0}"。 + + + 对 "{0}" 的远程主机调用失败。 + + + 未实现远程主机方法 {0}。 + + + 类型 {0} 不支持远程主机方法数据编码。 + + + 类型 {0} 不支持远程主机方法数据解码。 + + + 不支持创建嵌套管道。 + + + 创建远程会话时不支持相对 URI。 + + + 从远程主机解码数据时发生故障。网络数据中存在错误。 + + + 只有管理员可以远程覆盖线程选项。 + + + PowerShell 凭据请求: {0} + + + 警告: 远程计算机 {0} 上的脚本或应用程序正在请求凭据。请仅在信任远程计算机以及请求凭据的应用程序或脚本时,输入凭据。 + +{1} + + + 远程计算机 {0} 上的脚本或应用程序要求安全地读取一行。请仅在以下情况下输入敏感信息(如凭据): 信任远程计算机以及请求此类信息的应用程序或脚本。 + + + 远程计算机 {0} 上的脚本或应用程序正在尝试读取 PowerShell 主机上的缓冲区内容。出于安全原因,不允许这样做;调用已取消。 + + + 远程计算机 {0} 上的脚本或应用程序正在发送提示请求。出现提示时,请仅在信任远程计算机以及请求数据的应用程序或脚本时,输入敏感信息(如凭据或密码)。 + + + 收到不受支持的远程主机调用: {0}。 + + + 已收到远程处理数据,但以下操作不受支持: {0}。 + + + 收到的远程处理数据具有不受支持的数据类型: {0}。 + + + 远程处理数据缺少目标属性。 + + + 远程处理数据缺少目标接口属性。 + + + 远程处理数据缺少 Session InstanceId 属性。 + + + 远程处理数据缺少 RemotingDataType 属性。 + + + 远程处理数据缺少 CallId 属性。 + + + 远程处理数据缺少 MethodName 属性。 + + + 未为第一个片段设置 IsStartFragment 标志。 + + + 远程处理数据缺少 {0} 属性。 + + + 收到意外的 ObjectId。如果远程计算机未正确构造这些片段,或者数据可能已损坏或已更改,则可能会发生这种情况。 + + + ObjectId 不能小于或等于 0。如果远程计算机未正确构造这些片段,或者未经授权的用户更改了数据,则可能会发生这种情况。 + + + 同一对象的 FragmentID 必须按顺序排列,每次递增 1。如果远程计算机未正确构造这些片段,则可能会发生这种情况。数据可能也已损坏或已更改。 + + + 远程处理数据太大,无法基于片段进行重组。如果一个片段中的数据长度大于 Int32.Max,则可能会发生这种情况。如果未经授权的用户更改了数据,也可能会发生这种情况。 + + + 未为最后一个片段设置 IsEndFragment 标志。如果远程计算机未正确构造这些片段,或者数据已损坏或已更改,则可能会发生这种情况。 + + + 反序列化远程处理数据为 null。 + + + 片段 Blob 长度超出范围: {0} + + + 解码 ErrorRecord 时出错。 + + + 解码 PipelineStateInfo 时出错。 + + + 解码 RunspaceStateInfo 时出错。 + + + 收到不受支持的 RemotingTargetInterface 类型: {0} + + + 在未知目标类上调用了远程主机方法: {0} + + + 在未指定目标类的情况下,调用了远程主机方法。 + + + 解码 RunspacePoolStateInfo 时出错。 + + + 解码最小运行空间时出错。 + + + 解码最大运行空间时出错。 + + + 解码 PowerShellStateInfo 时出错。 + + + 意外的 {0} 属性类型(应为 {1},实际为 {2})。 + + + 意外的远程处理数据类型(应为 PSObject,实际为 {0})。 + + + 意外的编码命令类型(应为 PSObject,实际为 {0})。 + + + 意外的编码命令参数类型(应为 PSObject,实际为 {0})。 + + + 解码从远程计算机接收的数据时出错。要对从远程计算机接收的反序列化对象进行解码,至少需要 {0} 字节的数据。如果远程计算机未正确构造这些片段,或者数据已损坏或已更改,则可能会发生这种情况。 + + + 接收到的数据包并非发往已登录用户: 用户 = {0},数据包目标 = {1}。 + + + 客户端协商计时器已过期。协商超时间隔为 {0} 毫秒。 + + + PowerShell 客户端不支持服务器协商的 {0} {1}。请确保服务器与 PowerShell 的内部版本 {2} 和协议版本 {3} 兼容。 + + + {0}。与服务器协商失败。请确保服务器与 PowerShell 的内部版本 {1} 和协议版本 {2} 兼容。 + + + 目标服务器已发送关闭会话的请求。 + + + 运行 PowerShell 的服务器不支持客户端计算机协商的 {0} {1}。请验证客户端计算机是否与 PowerShell 的内部版本 {2} 和协议版本 {3} 兼容。 + + + 运行 PowerShell 的服务器不支持客户端计算机协商的 {0} {1} 上的连接操作。请确保客户端计算机与 PowerShell 的内部版本 {2} 和协议版本 {3} 兼容。 + + + 运行 PowerShell 的服务器无法处理连接操作,因为找不到以下信息,或这些信息无效:“客户端功能”信息和“连接 RunspacePool”信息。 + + + 运行 PowerShell 的服务器无法处理连接操作,因为该服务器尚未启动或正在关闭。 + + + 运行 PowerShell 的服务器无法处理连接操作,因为服务器运行空间池属性与客户端计算机的指定属性不匹配。 + + + {0}。与客户端协商失败。请确保客户端与 PowerShell 的内部版本 {1} 和协议版本 {2} 兼容。 + + + 服务器协商计时器已过期。协商超时间隔为 {0} 毫秒。 + + + 客户端计算机已发送关闭会话的请求。 + + + 发生 PowerShell 无法处理的错误。远程会话可能已结束。 + + + 服务器未在指定的超时期限内返回加密会话密钥。 + + + 客户端未在指定的超时期限内返回公钥。 + + + 连接尝试失败。 + + + 正在尝试关闭会话。 + + + PowerShell 无法正确关闭远程会话。会话处于未定义状态,因为它在断开连接后未被打开或连接。PowerShell 将尝试在本地计算机上强制关闭该会话,但该会话可能不会在远程计算机上关闭。若要正确关闭远程会话,请先打开或连接该会话。 + + + 无法关闭会话。 + + + 会话已关闭。 + + + 不支持 Wait 句柄类型 "{0}"。 + + + 接收的数据的流 ID 索引为 "{0}"。仅支持标准输出流 ID 索引 "0"。 + + + 标准输入句柄未打开。 + + + 对 WriteFile 的本机 API 调用失败。错误代码为 {0}。 + + + 对 ReadFile 的本机 API 调用失败。错误代码为 {0}。 + + + {0} 不是有效的架构值。可能的值为 "http" 和 "https"。 + + + 客户端接收调用失败。 + + + 客户端发送调用失败。 + + + 从 WinRS API WSManRunShellCommand 返回的命令句柄为 null。 + + + 无法将标准输入句柄设置为 'no wait' 状态。系统错误代码为 {0}。 + + + 端口号 {0} 不在有效值范围内。有效值的范围为 1 到 65535。 + + + 已退出该服务器进程。 + + + 调用 Windows API GetStdHandle 来获取标准输入句柄时返回了错误代码: {0}。 + + + 调用 Windows API GetStdHandle 来获取标准输出句柄时返回了错误代码: {0}。 + + + 调用 Windows API GetStdHandle 来获取标准错误句柄时返回了错误代码: {0}。 + + + 连接到远程服务器 {0} 失败。 + + + 连接到远程服务器 {0} 失败,出现以下错误消息: {1} + + + 关闭远程服务器 shell 实例失败,出现以下错误消息: {0} + + + 向远程服务器 {0} 发送数据失败。 + + + 将数据发送到远程服务器 {0} 失败,出现以下错误消息: {1} + + + 从远程服务器 {0} 接收数据失败。 + + + 从远程服务器 {0} 处理数据失败,出现以下错误消息: {1} + + + 在远程服务器上启动命令失败。 + + + 在远程服务器上启动命令失败,出现以下错误消息: {0} + + + 重新连接到远程服务器上的命令失败,出现以下错误消息: {0} + + + 向远程命令发送数据失败。 + + + 向远程命令发送数据失败,出现以下错误消息: {0} + + + 接收远程命令的数据失败。 + + + 处理远程命令的数据失败,出现以下错误消息: {0} + + + 调用方法 {1} 时出错,错误代码为 {0}。 + + + {0} 有关详细信息,请参阅 about_Remote_Troubleshooting 帮助主题。 + + + 无法断开与远程服务器 {0} 的连接。 + + + 与远程服务器断开连接失败,出现以下错误消息: {0} + + + 重新连接到远程服务器失败。 + + + 重新连接到远程服务器 {0} 失败,出现以下错误消息: {1} + + + 进程间通信(IPC)传输不支持连接操作。 + + + 远程服务器上不存在 ID 为 {0} 的 EndpointConfiguration。请与 PowerShell 管理员或终结点配置的所有者或创建者联系。 + + + 具有 {0} 标识符的 EndpointConfiguration 在远程计算机上未处于有效的初始会话状态。请与 PowerShell 管理员或终结点配置的所有者或创建者联系。 + + + 未为 {1} 注册表项指定必需值 {0}。 + + + 注册表项 {1} 的必需值 {0} 格式不正确。预期格式为 'string'。 + + + "{0}" 必须指定以扩展名 ".ps1" 结尾的 PowerShell 脚本文件。 + + + {0} 参数已在 {1} 部分中指定。请与管理员联系,确保只指定一次 {0}。 + + + 应为 "{2}" 元素中的 "{0}" 和 "{1}" 属性。 + + + 必须在 "{2}" 部分中指定 "{0}" 和 "{1}",才能动态加载程序集。 + + + 无法加载在 "{1}" 部分中指定的程序集 "{0}"。 + + + 无法加载在 "{1}" 部分中指定的类型 "{0}"。 + + + 在 "{2}" 部分中,必须同时指定 "{0}" 和 "{1}"。 + + + 目标 "{0}" 请求将连接重定向到 "{1}"。但是,"{1}" 不是格式正确的 URI。 + + + {0}报告的重定向位置: {1}。 + + + 连接已重定向到以下 URI: "{0}" + + + {0} 若要自动连接到重定向的 URI,请验证会话首选项变量 "{2}" 的 "{1}" 属性,并在 cmdlet 上使用 "{3}" 参数。 + + + 从远程服务器接收的数据的当前反序列化对象大小超出了允许的最大对象大小。当前反序列化的对象大小为 {0}。允许的最大对象大小为 {1}。 + + + 从远程服务器接收的数据总量超出了允许的最大配额。允许的最大配额为 {0}。 + + + 从远程客户端计算机接收的数据的当前反序列化对象大小超出了允许的最大对象大小。当前反序列化的对象大小为 {0}。允许的最大对象大小为 {1}。 + + + 从远程客户端接收到的数据总量超出了允许的最大配额。允许的最大配额为 {0}。 + + + 运行启动脚本时引发错误: {0}。 + + + 指定的 RemoteRunspaceInfo 对象具有重复项。 + + + 指定的 RemoteRunspaceInfo 对象已超过允许的最大限制。 + + + 打开远程会话失败,出现意外状态。状态 {0}。 + + + 指定的 URI {0} 无效。 + + + URI {0} 的远程会话已关闭。 + + + 远程会话不适用于 ComputerName {0}。 + + + 远程会话不可用于 {0}。 + + + 远程命令: {0},与 ID 为 "{1}" 的作业相关联。 + + + 指定 {1} 时,无法指定 {0}。 + + + FilePath 参数不支持通配符。指定一个不包含通配符的路径。 + + + 指定为 FilePath 参数值的路径不是来自 FileSystem 提供程序。 + + + FilePath 参数的值必须是 PowerShell 脚本文件。输入扩展名为 .ps1 的文件的路径,然后重试该命令。 + + + 一个或多个计算机名称无效。如果要传递 URI,请使用 -ConnectionUri 参数;或者也可以传递 URI 对象,而不是字符串。 + + + 当前作业实例的状态对此操作无效。 + + + 该命令找不到作业,因为找不到作业名称 {0}。请验证 Name 参数的值,然后重试该命令。 + + + 该命令找不到具有实例标识符 {0} 的作业。请验证 InstanceId 参数的值,然后重试该命令。 + + + 该命令找不到作业 ID 为 {0} 的作业。请验证该 ID 参数的值,然后重试该命令。 + + + 该命令无法移除具有作业 ID {0} 和名称 {1} 的作业,因为该作业尚未完成。若要移除该作业,请先将其停止或使用 Force 参数。 + + + 该命令无法移除作业 ID 为 {0} 的作业,因为该作业尚未完成。若要移除该作业,请先将其停止或使用 Force 参数。 + + + 该命令无法移除作业 ID 为 {0} 且实例标识符为 {1} 的作业,因为该作业尚未完成。若要移除该作业,请先将其停止或使用 Force 参数。 + + + 远程命令: {0},与 ID 为 "{1}" 的作业相关联。 + + + 该命令无法检索指定计算机的作业。ComputerName 参数只能用于通过 PowerShell 远程处理创建的作业。 + + + Session 参数只能与 PSRemotingJob 对象一起使用。 + + + 具有名称 {0} 的远程会话不可用。 + + + 会话 ID 为 {0} 的远程会话不可用。 + + + {0} 不包含 ID 为 {1} 的项。 + + + 该命令无法移除该作业,因为它不存在或是子作业。子作业只能通过移除父作业来进行移除。 + + + {0} 不是参数 {1} 的有效值。该值必须大于或等于 0。 + + + {0} 不能指定为代理身份验证机制。代理身份验证仅支持 {1}、{2} 或 {3}。 + + + 使用以下代理访问类型时,无法指定代理凭据: {0}。请指定其他访问类型,或者不指定代理凭据。 + + + 会话选项 {1} 必须指定 {0} 值。 + + + 会话必须处于打开状态。 + + + 主机不支持 Enter-PSSession 和 Exit-PSSession。 + + + 找到会话 ID 为 {0} 的多个匹配项。 + + + 找到会话 ID 为 {0} 的多个匹配项。 + + + 找到多个与名称 {0} 匹配的项。 + + + Enter-PSSession 失败,因为远程会话不提供所需的命令。 + + + 无法从嵌套提示符运行 Enter-PSSession。 + + + 连接到远程计算机时允许的最大 WS-Man URI 重定向次数 + + + 新远程会话的默认会话选项 + + + 将在远程计算机上加载的会话配置的名称 + + + 将用于建立远程连接的 AppName + + + 包含有关启动远程会话的远程用户的信息。此变量仅在远程会话中可用。 + + + 必须同时指定 "{0}" 和 "{1}",或者两者都不指定。 + + + 找不到会话配置 "{0}"。 + + + 会话配置 "{0}" 不是基于 PowerShell 的 shell。 + + + 会话配置 "{0}" 是基于 PowerShell 的 shell。请使用 PowerShell 6+ 对其进行修改。 + + + 会话配置 "{0}" 是基于 Windows PowerShell 的 shell。请使用 Windows PowerShell 进行修改。 + + + 没有与条件 "{0}" 匹配的会话配置。 + + + {0} + + + 名称: {0} + + + 名称: {0}。这使管理员能够在此计算机上远程运行 PowerShell 命令。 + + + 无法删除临时文件 {0}。失败原因: {1}。 + + + 已成功注册新的 shell,但 PowerShell 无法删除临时文件 {0}。失败原因: {1}。 + + + 无法将 shell 配置数据写入临时文件 {0} 中。失败原因: {1}。 + + + 正在运行命令 "{0}" 以创建新的会话配置。 + + + 名称: {0} SDDL: {1}。这使所选用户能够在此计算机上远程运行 PowerShell 命令。 + + + 正在运行命令 "{0}" 以移除会话配置。 + + + 正在运行命令 "{0}" 以获取基于 PowerShell 的会话配置。 + + + 正在运行命令 "{0}" 以更新会话配置属性。 + + + 名称: {0} SDDL: {1} + + + 正在运行命令 "{0}" 以启用会话配置。 + + + WinRM 快速配置 + + + 正在运行命令 "{0}",以使用 Windows 远程管理(WinRM)服务实现对此计算机的远程管理。 + 这包括: + 1. 启动或重新启动(如果已启动) WinRM 服务 + 2. 将 WinRM 服务启动类型设置为“自动” + 3. 创建一个可接受任何 IP 地址上的请求的侦听器 + 4. 为 WS-Management 流量启用 Windows 防火墙入站规则例外(仅限 http)。 + +是否要继续? + + + 正在执行操作 "{0}"。 + + + 名称: {0} SDDL: {1}。这使所选用户能够在此计算机上远程运行 PowerShell 命令。 + + + 正在运行命令 "{0}" 以禁用会话配置。 + + + 名称: {0} SDDL: {1}。这会拒绝所有人访问此会话配置。 + + + 禁用会话配置不会撤消 Enable-PSRemoting 或 Enable-PSSessionConfiguration cmdlet 所做的所有更改。你可能需要按照以下步骤手动撤消这些更改: + 1. 停止并禁用 WinRM 服务。 + 2. 删除可接受任何 IP 地址上的请求的侦听器。 + 3. 禁用 WS-Management 通信的防火墙例外。 + 4. 将 LocalAccountTokenFilterPolicy 的值还原为 0,这会限制对计算机上 Administrators 组成员的远程访问。 + + + 访问被拒绝。若要运行此 cmdlet,请使用“以管理员身份运行”选项启动 PowerShell。 + + + 正在重启 WinRM 服务 + + + "Restart-Service" + + + 名称: {0} + + + 必须重启 WinRM 服务,然后才能为 SecurityDescriptor 选项显示 UI。请重启 WinRM 服务,然后运行以下命令: "{0}" + + + 正在注册会话配置 + + + 找不到会话配置 "{0}"。正在运行命令 "{1}" 以创建 "{0}" 会话配置。运行此命令将会重启 WinRM 服务。 + + + 不能同时指定 "{0}" 和 "{1}" 参数。请指定 "{0}" 或 "{1}" 参数。 + + + 此操作可能会重启 WinRM 服务。是否要继续? + + + 无法处理节点类型为 "{0}" 的元素。仅支持 {1} 和 {2} 节点类型。 + + + 没有足够的数据可用于处理 {0} 元素。 + + + {2} 元素中应只有两个名称为 "{0}" 和 "{1}" 的属性。 + + + {1} 元素中的节点类型 "{0}" 未知。{1} 元素中仅应有 "{2}" 节点类型。 + + + {1} 元素中应只有一个名为 "{0}" 的属性。 + + + 收到未知元素 "{0}"。如果远程进程异常关闭或结束,则可能会发生这种情况。 + + + 不支持指定的身份验证机制 "{0}"。此操作仅支持 "{1}"。 + + + 在 "{0}" 中找不到 pwsh 可执行文件。 +请注意,在 PowerShell 托管在其他应用程序中的情况下,设计上不支持 'Start-Job'。在这种情况下,建议改用 'ThreadJob' 模块。 + + + 无法从 64 位 'pwsh' 安装启动 32 位 'pwsh' 进程。如果需要在 32 位进程中运行 PowerShell,请安装 32 位 'pwsh'。 + + + 后台进程报告了一个错误,并显示以下消息: {0}。 + + + 后台进程异常关闭或结束: {0}。 + + + 处理来自后台进程的数据时出错。报告的错误: {0}。 + + + 已收到具有标识符 {0} 的非活动命令的数据。收到的数据: {1}。 + + + 不支持向会话发送 {0} 消息。只能向命令发送 {0} 消息。 + + + 客户端未在指定时间间隔内收到关于信号操作的响应。当命令未及时响应 Stop 消息时,可能会发生这种情况。 + + + 客户端未在指定的时间间隔内收到关于 Close 操作的响应。当命令未及时响应 Stop 消息时,可能会发生这种情况。 + + + 启动后台进程时出错。报告的错误: {0}。 + + + ThrottlingJob.AddChildJob 方法仅接受处于 NotStarted 状态的子作业。 + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + 调用 ThrottlingJob.EndOfChildJobs 方法后,无法调用 ThrottlingJob.AddChildJob 方法。 + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + 已完成 {0}/{1} + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + 调用嵌套管道需要有效的运行空间。 + + + {1} 作业源适配器引发了异常,并显示以下消息: {0} + + + 值 {0} 对 {1} 参数无效。唯一允许的值为 5.1。 + + + 不能在同一命令中同时使用 Wait 和 Keep 参数。 + + + WriteEvents 参数必须与 Wait 参数一起使用。 + + + PowerShell 7+ 不支持 PowerShell 远程处理终结点版本控制。 + + + 无法实例化以下类型,因为其构造函数不是公共的: {0}。 + + + 无法执行作业操作(Create、Get 或 Remove),因为未注册 JobDefinition 中指定的 JobSourceAdapter 类型。请使用显式调用或调用 Import-Module cmdlet,然后指定程序集,从而注册 JobSourceAdapter 类型。 + + + 无法创建作业,因为 JobInvocationInfo 不包含 JobDefinition。请使用 JobDefinition 启动 JobInvocationInfo。 + + + 当前作业实例的状态为 {0}。此状态对尝试的操作无效。{1} + + + 无法将作业 "{0}" 连接到远程服务器。 + + + 运行空间 ID = {0} 的 Disconnect-PSSession 操作失败。 + + + 会话 {0} 的连接操作失败。运行空间状态为 {1},而不是 Opened。 + + + 计算机 "{0}" 的已断开连接的 PSSession 查询失败。 + + + 无法连接 PSSession "{0}",因为它未处于断开连接状态或无法建立连接。 + + + 目标 "{1}" 上的 PSSession "{0}" 不支持会话连接,因为目标计算机类型为 "{2}"。 + + + 无法断开 PSSession "{0}" 的连接,因为该会话未处于 Opened 状态。 + + + 目标 "{1}" 上的 PSSession "{0}" 不支持会话断开连接,因为目标计算机类型为 "{2}"。 + + + Receive-PSSession 不支持目标 "{1}" 上的 PSSession "{0}",因为目标计算机类型为 "{2}"。 + + + 该命令无法完成,因为 ChildJobs 属性包含无效的值。 + + + 无法挂起 ID 为 {0} 的作业。某些作业类型不支持挂起作业。有关对挂起作业的支持的详细信息,请参阅关于作业类型的帮助主题。 + + + 无法恢复 ID 为 {0} 的作业。某些作业类型不支持恢复作业。有关对恢复作业的支持的详细信息,请参阅关于作业类型的帮助主题。 + + + 在同一命令中,Invoke-Command cmdlet 不能同时与 AsJob 和 Disconnected 这两个参数一起使用。 + + + {0} 的远程会话查询失败,出现以下错误消息: {1} + + + 已尝试创建 ID 为 {0} 的作业。现在无法创建具有此 ID 的作业。请验证是否已在此计算机上分配过一次该 ID。 + + + 无法创建 ID 为 {0} 的作业;这不是有效的 ID。请为作业 ID 提供一个大于 0 的整数。 + + + 提供的 JobIdentifier 不得为 null。请提供有效的 JobIdentifier。 + + + Wait-Job cmdlet 无法完成工作,因为一个或多个作业被阻止,正在等待用户交互。 请使用 Receive-Job cmdlet 处理交互式作业输出,然后重试。 + + + 无法连接远程会话 {0},因此无法将其从服务器中移除。将从服务器中移除客户端远程会话对象,但服务器上的远程会话状态未知。 + + + 运行空间 ID = {0} 的 Disconnect-PSSession 操作失败,原因如下: {1} + + + 作业 "{0}" 无法连接到服务器,因此无法停止。 + + + 该命令找不到 InstanceId 值为 "{0}" 的 PSSession。 + + + 该命令找不到名为 "{0}" 的 PSSession。 + + + Windows 预安装环境(WinPE)不支持 PowerShell 远程处理。 + + + {0} 所做的更改在重启 WinRM 服务后才会生效。 + + + 如果最近已取消注册使用此名称的配置,则 {0} 可能需要重启 WinRM 服务,因为某些系统数据结构可能仍处于缓存状态。在这种情况下,可能需要重启 WinRM。 +所有连接到 PowerShell 会话配置的 WinRM 会话(例如 Microsoft.PowerShell 和使用 Register-PSSessionConfiguration cmdlet 创建的会话配置)都会断开连接。 + + + 你正在远程会话中运行,并选择了“强制”选项,这意味着 WinRM 服务可能会重新启动。如果 WinRM 服务重新启动,则此远程会话将终止,你需要创建新会话才能继续 + + + 尝试保存标识符时,作业为 null。请指定一个作业,以保存其标识符。 + + + 找不到此 PSSession 的正在运行的命令。 + + + 未安装 Windows PowerShell 2.0 所需的 Microsoft .NET Framework 2.0。请安装 .NET Framework 2.0,然后重试。 + + + 远程管道失败。 + + + 由于以下原因,远程管道失败: {0} + + + 无法恢复一个或多个作业,因为该状态对该操作无效。 + + + 未为正在运行客户端方法的远程运行空间指定客户端计算机。 + + + 名称: {0} SDDL: {1}。这会拒绝远程访问此会话配置。 + + + 已启用: False。这会将 WS-Management 服务配置为拒绝连接请求。 + + + 已启用: True。这会将 WS-Management 服务配置为接受连接请求。 + + + 应用于会话时要定义的别名 + + + 应用于会话时要加载的程序集 + + + 本文档的作者 + + + 应用于会话时要使用的 CLR 版本 + + + 与此文档关联的公司 + + + 此文档的版权声明 + + + 关于这些设置所提供的功能的说明 + + + 应用于会话时要定义的环境变量 + + + 应用于会话时要应用的执行策略 + + + 应用于会话时要加载的格式文件(.ps1xml) + + + 应用于会话时要定义的函数 + + + 用于唯一标识此文档的 ID + + + 会话类型默认应用于此会话配置。可以是 'RestrictedRemoteServer' (推荐)、'Empty' 或 'Default' + + + 用于放置此会话配置的会话脚本的目录 + + + 是否以计算机的(虚拟)管理员帐户的身份运行此会话配置 + + + 应用于会话时要应用的语言模式。可以是 'NoLanguage' (推荐)、'RestrictedLanguage'、'ConstrainedLanguage' 或 'FullLanguage' + + + 应用于会话时要导入的模块 + + + 应用于会话时要使用的 PowerShell 引擎版本 + + + 应用于会话时要使用的处理器体系结构 + + + 此文档使用的架构版本号 + + + 应用于会话时要运行的脚本 + + + 应用于会话时要添加的类型 + + + 应用于会话时要加载的类型文件(.ps1xml) + + + 应用于会话时要定义的变量 + + + 用户角色(安全组),以及应该在应用于会话时应用于这些角色的角色功能 + + + 应用于会话时要显示的别名 + + + 应用于会话时要显示的 Cmdlet + + + 无法分析 '{0}' 的可见命令定义。可见命令定义必须是具有 'Name' 和 'Parameters' 键的哈希表。'Parameters' 键的值必须是一个哈希表集合,其中必须包含 'Name' 键,并且还可以包含 'ValidateSet' 或 'ValidatePattern'。 + + + 应用于会话时要显示的函数 + + + 应用到会话时要显示的提供程序 + + + 应用于会话时要显示的外部命令(脚本和应用程序) + + + PSSession 配置文件路径 '{0}' 无效。路径自变量必须解析为文件系统中具有 '.pssc' 扩展名的单个文件。请修复路径规范,然后重试。 + + + 角色功能文件路径 '{0}' 无效。路径自变量必须解析为文件系统中具有 '.psrc' 扩展名的单个文件。请修复路径规范,然后重试。 + + + 'Roles' 条目必须是哈希表,但实际为 {0}。 + + + 无法将 '{0}' 角色条目的值转换为哈希表。'Roles' 条目必须是以组名称为键的哈希表,其中每个键对应的值是包含该角色的会话配置属性的另一个哈希表。 + + + 找不到角色功能 '{0}'。角色功能必须是一个名为 '{1}' 的文件,且位于当前模块路径中某个模块内的 'RoleCapabilities' 目录中。 + + + 找不到要导入的模块路径。ModulesToImport 参数 {0} 的值不存在或不是模块目录。请更正该值,然后重试该命令。 + + + 未加载指定的配置文件 '{0}',因为找不到有效的配置文件。 + + + 计算机 {0} 已成功断开连接。 + + + 到 {0} 的重新连接尝试失败。正在尝试断开会话连接... + + + 正在尝试重新连接到 {0} ... + + + 到 {0} 的网络连接已丢失,且重新连接尝试失败。请修复该网络连接,并使用 Connect-PSSession 或 Receive-PSSession 重新进行连接。 + + + 到 {0} 的网络连接已中断。正在尝试重新连接,最多等待 {1} 几分钟... + + + 已还原到 {0} 的网络连接。 + + + {0} 身份验证需要显式用户名和密码。 请使用 -Credential 参数指定用户名和密码,然后重试该命令。 + + + Unix 上不支持通过 HTTP 进行基本身份验证。 + + + 找不到名为 {0} 的计划作业。 + {0} is the job definition name + + + 找到多个名为 {0} 的作业定义。请尝试在 Start-Job 中包含 -DefinitionType 参数,以便将作业定义的搜索范围缩小到单个作业源适配器。 + + + 配置文件中不存在成员 'SchemaVersion'。此成员必须存在并分配有 'n.n.n.n' 格式的版本号。请将缺少的成员添加到文件 {0} 中。 + + + 成员 '{0}' 必须是字符串。请在文件 {1} 中将该成员更改为正确类型。 + + + 成员 '{0}' 必须是字符串数组。请在文件 {1} 中将该成员更改为正确类型。 + + + 成员 '{0}' 必须是哈希表。请在文件 {1} 中将该成员更改为正确类型。 + + + 成员 '{0}' 必须是哈希表数组。请在文件 {1} 中将该成员更改为正确类型。 + + + 成员 '{0}' 不是有效键。请在文件 {1} 中将该成员更改为有效键。 + + + 成员 '{0}' 必须是有效的枚举类型 "{1}"。有效的枚举值为 "{2}"。请在文件 {3} 中将该成员更改为正确类型。 + + + 分析配置文件 {0} 时出错,出现以下错误消息: {1} + + + -WriteJobInResults 参数必须与 -Wait parameter 参数一起使用 + + + 成员 '{0}' 不是绝对路径 {1}。请在文件 {2} 中将该成员更改为绝对路径。 + + + 成员 '{1}' 中的键 '{0}' 无效。请在文件 {2} 中更改该键。 + + + 成员 '{0}' 必须包含所需的键 '{1}'。请将该键添加到文件 {2}。 + + + 键 '{0}' 包含无效的扩展名 {1}。请指定以下列表中的扩展名: {{{2}}}。 + + + 成员 '{1}' 中的键 '{0}' 必须是脚本块。请在文件 {2} 中将该键更改为正确类型。 + + + 会话配置文件 {0} 无效。请指定有效的会话配置文件,然后重试该命令。 + + + 网络连接中断 + + + 正在尝试重新连接到 {0} ... + + + 已创建用于进行重新连接的作业 {0}。 + + + 已成功断开计算机 {2} 上实例 ID 为 {1} 的会话 {0}。 + + + 已创建具有实例 ID {1} 的会话 {0},以便进行重新连接。 + + + SessionName 参数只能与 Disconnected 开关参数一起使用。 + + + 尝试连接 PSSession 时发生故障。 + + + 尝试连接到目标虚拟机时发生故障。 + + + 尝试连接到目标容器时发生故障。 + + + PSSession 处于断开连接状态,且无法建立连接。 + + + 适用于 PowerShell 的 Hyper-V 模块在此计算机上不可用。 + + + 在 ID 为 {0} 的容器内启动 PowerShell 进程({1})失败,出现错误: {2}。 + + + 此计算机上可能未启用“容器”功能。 + + + 未能在 ID 为 {1} 的容器内终止 ID 为 {0} 的 PowerShell 进程。 + + + 输入 ContainerId {0} 不存在,或者相应的容器未运行。 + + + 输入 VMId 参数未解析为单个虚拟机。 + + + 输入 VMId {0} 未解析为单个虚拟机。 + + + 输入 VMName 参数未解析为任何虚拟机。 + + + 输入 VMName 参数将解析为多个虚拟机。 + + + 输入 VMName {0} 未解析为单个虚拟机。 + + + 虚拟机 {0} 未处于正在运行状态。 + + + 凭据无效。 + + + 输入用户名不能为空。 + + + 无法进入会话 {0},因为它未处于断开连接状态或无法建立连接。使用 Get-PSSession -ComputerName {1} -InstanceId {2} 检索远程会话。 + + + 无法进入会话 {0},因为它未处于断开连接状态或无法建立连接。请使用 Connect-PSSession 或 Receive-PSSession 重新建立连接。 + + + 到 {0} 的网络连接已丢失,且重新连接尝试失败。请修复该网络连接,并使用 Connect-PSSession 或 Receive-PSSession 重新进行连接。 + + + 由于 SetSocketOption 失败,未能创建 RemoteSessionHyperVSocketClient 的实例。 + + + 未能创建 RemoteSessionHyperVSocketServer 的实例。 + + + 已取消重新连接尝试。请修复该网络连接,并使用 Connect-PSSession 或 Receive-PSSession 重新进行连接。 + + + 无法挂起一个或多个作业,因为该状态对该操作无效。 + + + 如果没有 -Wait 参数,则不能使用 -AutoRemoveJob 参数 + + + WS-Management 服务无法处理该请求。在 {1} 计算机上的 WSMan: 驱动器中找不到 {0} 会话配置。有关详细信息,请参阅 about_Remote_Troubleshooting 帮助主题。 + + + 无法根据 {0} 规范创建作业,因为提供的运行空间不是本地运行空间。请使用本地运行空间重试,或指定 RunspaceMode 自变量。 + + + 无法断开会话 {0},因为指定的空闲超时值({1} 秒)大于允许的服务器最大值({2} 秒)或小于允许的最小值({3} 秒)。 请指定处于允许范围内的空闲超时值,然后重试。 + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + 指定的 IdleTimeout 会话选项({0} 秒)不是有效的时段。 请指定大于或等于允许的最小值({1} 秒)的 IdleTimeout 值。 + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + 如果在会话配置文件中指定了 "{2}"、"{3}"、"{4}" 或 "{5}" 键,则不能存在 cmdlet "{0}" 或别名 "{1}"。 + + + “传输选项无效。仅当参数 "{1}" 设置为 true 时,参数 "{0}" 才能为非零值。 + + + 成员 '{0}' 必须是由字符串或哈希表元素组成的数组。 + + + 成员 '{0}' 必须是由字符串或哈希表元素组成的数组。请在文件 {1} 中将该成员更改为正确类型。 + + + 无法检索作业定义 '{0}',因为路径 '{1}' 引用了 '{2}' 提供程序路径。 请将该路径参数更改为文件系统路径。 + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + 无法检索作业定义 '{0}',因为路径 '{1}' 会解析为多个文件路径。 请更改路径参数,使其为单个路径。 + {0} is job definition name +{1} is the user provided path + + + 找不到类型为 {0}、名称为 {1} 的计划作业。 + {0} is the job definition type and {1} is the job definition name. + + + 找不到 WorkingDirectory 路径 {0}。 + + + 无法连接到会话 {0}。 计算机 {1} 上不再存在该会话。 + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + 会话 {0} 的连接操作失败,出现以下错误消息: {1} + + + 如果没有 -Wait 参数,则无法使用 -Force 参数。 + + + 一个或多个作业处于挂起或断开连接状态,无法在没有其他用户输入的情况下继续。 请指定 -Force 参数以继续,从而进入已完成、失败或已停止状态。 + + + 在 PowerShell 会话配置中启用 RunAs 时,Windows 安全模型无法在使用此终结点创建的不同用户会话之间强制实施安全边界。请验证 PowerShell 运行空间配置是否仅限于所需的一组 cmdlet 和功能。 + + + 通过添加 Force 参数,作业已成功挂起。 + + + 会话配置文件 {0} 无效。请指定有效的会话配置文件,然后重试该命令。分析配置文件时出错: {1}。 + + + Register-PSSessionConfiguration: {1}. 会话配置文件中的 '{0}' 键包含无效的值。请更正该文件,然后重试该命令。 + + + 仅当远程计算机运行 PowerShell 3.0 或更高版本的 PowerShell 时,才支持断开连接的会话。 + + + cmdlet 的内存使用量已超出警告级别。若要避免这种情况,请尝试以下操作之一: 1) 降低 CIM 操作生成数据的速率(例如,通过将一个较低的值传递给 ThrottleLimit 参数),2) 提高下游 cmdlet 使用数据的速率,3) 使用 Invoke-Command cmdlet 在服务器上运行整个管道。超过内存使用量警告级别的 cmdlet 是由以下命令行启动的: {0} + + + PSSession {0} 是使用 EnableNetworkAccess 参数创建的,只能从本地计算机重新连接。 + + + 无法启动作业。此会话的语言模式与系统范围的语言模式不兼容。 + + + 无法创建运行空间。此配置的语言模式与系统范围的语言模式不兼容。 + + + 无法退出嵌套管道,因为该管道未处于嵌套状态。 + + + PowerShell 服务器会话未处于运行嵌套命令的有效状态。 此会话中不能运行任何嵌套命令。 + + + 无法在远程会话上调用嵌套命令,因为已有正在运行的嵌套命令。 + + + 远程会话无法调用命令 {0},出现错误: {1}。 + + + 远程会话命令当前已在调试器中停止。 请使用 Enter-PSSession cmdlet 以交互方式连接到远程会话,并自动进入控制台调试器。 + + + 连接到的远程会话不支持远程调试。你必须连接到运行 PowerShell 4.0 或更高版本的远程计算机。 + + + 由于会话 {0}、{1}、{2} 的会话状态不等于 Open,你无法在该会话中运行命令。 会话状态为 {3}。 + + + 未指定有效的会话。 请确保提供处于 Opened 状态且可用于运行命令的有效会话。 + + + 会话 {0}、{1}、{2} 不可用于运行命令。 会话可用性为 {3}。 + + + 无法运行该命令,因为 ChildJobs 属性为空。 + + + 无法调试作业,因为没有可用的 PowerShell 主机调试器。 请确保是在支持调试的主机中运行此命令。 + + + 找不到 ID 为 {0} 的作业。 + + + 找不到实例 ID 为 {0} 的作业。 + + + 找不到名为 {0} 的作业。 + + + 无法调试作业,因为没有可用的主机 UI。 请确保是在实现 PSHostUserInterface 的 PowerShell 主机中运行此命令。 + + + 无法调试作业,因为主机调试器模式设置为 None 或 Default。 主机调试器模式必须是 LocalScript 和/或 RemoteScript。 + + + 找到多个 ID 为 {0} 的作业。 Debug-Job 一次只能调试一个作业。 + + + 找到多个名为 {0} 的作业。 Debug-Job 一次只能调试一个作业。 + + + 用于进程附加的命名管道服务器侦听器已在运行。 + + + Enter-PSHostProcess 不支持进入它正在运行的同一个 PowerShell 会话。 + + + 找到多个名为 {0} 的进程。使用进程 ID 指定要进入的单个进程。 + + + 无法进入 ID 为 '{0}' 的进程,因为它尚未加载 PowerShell 引擎,或者已禁用命名管道侦听器。 + + + 找不到 ID 为 {0} 的进程。 + + + 找不到名称为 {0} 的进程。 + + + 找不到 CustomPipeName 为 {0} 的命名管道。 + + + 无法处理该命令,因为指定的 pipeName 太长。此平台上的管道名称最长可包含 {0} 个字符。管道名称 '{1}' 包含 {2} 个字符。 + + + 当前主机不支持 Enter-PSHostProcess cmdlet。 + + + “命名管道目标进程已结束。” + + + “Hyper-V 套接字目标进程已结束。” + + + {0}[进程:{1}]: {2} + + + {0}[{1}]: {2} + + + 无法连接到进程 {1} 的应用程序域名 {0}。 错误: {2}。 + + + 无法连接到名为 {0} 的管道。 错误: {1}。 + + + PowerShell 插件无法处理 Connect 操作,因为所需的协商信息缺失或不完整。 + + + PowerShell 插件未能处理连接操作。 + + + 提供的插件上下文无效。 + + + Powershell 插件在处理 {0} 自变量时遇到严重错误。 + + + 提供的命令上下文无效。 + + + 提供的输入数据无效。仅支持 {0} 类型的输入数据。 + + + 提供的输入流无效。仅支持 {0} 作为输入流。 + + + 提供的输出流集无效。仅支持 {0} 作为输出流。 + + + 提供的 WSMAN_SENDER_DETAILS 无效。无法处理 null WSMAN_SENDER_DETAILS。 + + + 提供的 shell 上下文无效。 + + + {0} + + + 插件方法 {1} 不允许 {0} 为 NULL 值。 + + + 输入流和输出流集不允许使用 NULL 值。{0} 和 {1} 是受支持的输入流和输出流。 + + + 插件方法 {1} 不允许 {0} 为 NULL 值。 + + + 插件方法 {1} 不允许 {0} 为 NULL 值。 + + + PowerShell 插件操作正在关闭。如果托管服务或应用程序正在关闭,则可能会发生这种情况。 + + + PowerShell 插件无法识别选项 {0}。请确保客户端与 PowerShell 的内部版本 {1} 和协议版本 {2} 兼容。 + + + 客户端应提供具有名称 {0} 的选项。请确保客户端与 PowerShell 的内部版本 {1} 和协议版本 {2} 兼容。 + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">PowerShell 插件不支持客户端请求的协议版本 {2}。</PSProtocolVersionError> + + + PowerShell 插件在向 WSMan 服务报告上下文时遇到错误。 + + + 无法创建托管服务器会话。 + + + PowerShell 插件在注册关闭通知的等待句柄时遇到错误。 + + + 无法进入运行空间,因为已在此会话中推送了一个运行空间。 + + + 无法进入运行空间,因为没有可用的服务器远程调试器。 + + + 无法进入运行空间,因为它不是远程运行空间。 + + + 远程传输错误: {0} + + + 无法在容器中打开 PowerShell 的管道连接。错误代码: {0}。 + + + 无法创建 PowerShell IPC 命名管道。错误代码: {0}。 + + + 在与命名管道建立连接之前超时。 + + + WSMan 初始化失败,错误代码为: {0}。 + + + 无法在服务器模式下启动命名管道服务器。 + + + 无法授予对 '{0}' 的远程访问权限: '{1}'。已注册会话配置,但此组没有访问权限。若要解决此错误,请提供有效的组名称并重新注册会话配置。 + + + 无法获取会话配置 '{0}' 的会话功能: 此配置未使用会话配置文件(.pssc)注册,例如使用由 New-PSSessionConfigurationFile cmdlet 创建的配置文件。 + + + 无法解析用户名 '{0}'。请验证用户名,然后重试。 + + + 与计算机的(虚拟)管理员帐户关联的组 + + + 无法创建或打开配置会话 {0}。 + + + 强制执行脚本输入参数验证。指定 MountUserDrive 时会自动启用此功能。 + + + 在会话中创建一个 'User' PSDrive,以便在文件系统提供程序不可见时搭配 Copy-Item 使用。 + + + 成员 '{0}' 必须是布尔值。请在文件 {1} 中将该成员更改为正确类型。 + + + 成员 '{0}' 必须是整数。请在文件 {1} 中将该成员更改为正确类型。 + + + 处理用户驱动器时出错 {0}。 + + + 使用 MountUserDrive 参数创建的 User 驱动器的可选最大大小(以字节为单位)。User 驱动器的默认最大大小为 50MB。 + + + 找不到文件系统提供程序。 + + + 用于运行该配置的组托管服务帐户名称 + + + 组托管服务帐户名称无效。帐户名称必须采用 'DomainName\UserName' 格式。 + + + 必须加入才能使用该会话的组帐户。 + + + 无法分析 sddl 字符串,因为其中包含不匹配的括号: {0}。 + + + RequiredGroups 属性哈希表必须仅包含单个键。 + + + RequiredGroups 属性不采用名称/值对哈希表格式。 这必须是以下哈希表格式(使用 PowerShell 语法): RequiredGroups = @{ Or = 'Administrators' }。 + + + 必需组配置中的未知键。 必需组哈希表只能包含逻辑成员身份分组的 'And' 和 'Or' 哈希键。 + + + 必需组配置中的未知值。 必需组哈希表只能包含以下值: 组名称或其他逻辑哈希表。 + + + ACE {0} 格式不正确。 常规 ACE 必须正好有 6 个部分。 + + + 无法创建会话用户驱动器,因为当前用户名包含无效的文件路径字符。 + + + 无效的角色功能键: {0}。请确保角色功能名称拼写正确,并且是有效的会话配置属性。 + + + 无效的角色功能键类型: {0}。角色功能键必须是标识有效会话配置属性的字符串。 + + + 无效的角色键类型: {0}。角色键必须是标识安全组的字符串。 + + + 其他可能的原因: + -指定凭据中未包含域名或计算机名称,例如:DOMAIN\UserName 或 COMPUTER\UserName。 + + + 未能启动远程处理连接所需的 SSH 客户端进程,出现错误: {0}。 + + + 找不到指定的密钥文件 {0}。 + + + SSH 客户端会话已结束,出现错误消息: {0} + + + SSH 连接尝试在超时({0} 秒)后失败。 + + + +SSH 客户端进程已在建立连接之前终止。 + + + 提供的 SSHConnection 哈希表缺少所需的 ComputerName 或 HostName 参数。 + + + 提供的 SSHConnection 哈希表参数名称或元素为 null 或为空。 + + + 提供的 SSHConnection 哈希表参数 {0} 不受支持。 + + + 提供的 SSHConnection 哈希表同时包含 ComputerName 和 HostName 参数。 你只能指定一个。 + + + 提供的 SSHConnection 哈希表同时包含 KeyFilePath 和 IdentityFilePath 参数。 你只能指定一个。 + + + 找不到所提供的角色功能文件 {0}。 + + + 提供的角色功能文件 {0} 没有所需的 .psrc 扩展名。 + + + SSH 传输进程突然终止,导致此远程会话中断。 + + + PowerShell 6+ 不支持 WOW64。二进制文件必须与处理器的体系结构匹配。 + + + 找不到“{0}”可执行文件。请验证是否已安装 WOW64 功能。 + + + 无法将插件 {0} 安装到目录 {1}。 + + + PowerShell 缺少 WinRM 插件 DLL {0}。请运行 Enable-PSRemoting,然后重试此命令。 + + + 此参数集需要 WSMan,但未找到受支持的 WSMan 客户端库。WSMan 要么未安装,要么在此系统上不可用。 + + + + 退出代码: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + 无法读取有关该进程的信息: '{0}'。 + + + 主机系统没有正确版本的 Hyper-V 架构。 + + + Unix 上的 HTTPS 当前不支持 CA 或 CN 检查。如果你确定信任要连接的服务器以及中间的网络,请使用 PSSessionOption -SkipCACheck 和 -SkipCNCheck。 + + + 仅对 PowerShell 6+ 配置禁用了 PowerShell 远程处理,不会影响 Windows PowerShell 远程处理配置。请在 Windows PowerShell 中运行此 cmdlet,以影响所有 PowerShell 远程处理配置。 + + + + 仅对 PowerShell 6+ 配置启用了 PowerShell 远程处理,不会影响 Windows PowerShell 远程处理配置。请在 Windows PowerShell 中运行此 cmdlet,以影响所有 PowerShell 远程处理配置。 + + + 由于已强制执行 AppLocker 或 Windows Defender 应用程序控制等应用程序控制策略,因此已禁用 Enter-PSHostProcess cmdlet。 + + + 远程调试器异常: {0},错误消息: {1} + + + 由于在此计算机上找不到 Windows PowerShell,因此无法创建 Windows PowerShell 进程。 + + + 要创建的 Runspace 自变量必须是非 null RemoteRunspace 对象。 + + + 会话配置哈希表包含无效的键类型。键应为字符串类型。 + + + 会话配置文件包含不受支持的配置选项: {0}。这是一个远程处理终结点配置选项,不适用于 PowerShell 会话状态。 + + + 会话配置文件包含未知的配置选项: {0}。 + + + 表达式计算可能失败 + + + 基于脚本块创建 PowerShell 对象可能需要计算脚本块中的某些表达式。除非表达式表示常量值,否则在“受限语言”模式下,表达式计算会静默失败并返回 'null'。 + + + 未能获取 Hyper-V VM 状态。该值的类型为 {0},但应为 Microsoft.HyperV.PowerShell.VMState 或 System.String。 + + + Hyper-V {0} 在连接协商期间发送了无效的 {1} 响应。 + + + 协商与 Hyper-V 的安全连接失败。请确保主机和客机已使用所有相关的 Microsoft 更新进行更新。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/RunspaceInit.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/RunspaceInit.zh-Hans.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/RunspaceInit.zh-Hans.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/RunspacePoolStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/RunspacePoolStrings.zh-Hans.resx new file mode 100644 index 00000000000..63e61c017c3 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/RunspacePoolStrings.zh-Hans.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 最大池大小不能小于 1。 + + + 最小池大小不能小于 1。 + + + 最小池大小不能大于最大池大小。 + + + 运行空间池的状态不适用于此操作。 + + + 无法执行该操作,因为运行空间池未处于“{0}”状态。当前状态为“{1}”。 + + + 无法打开运行空间池,因为它未处于 'BeforeOpen' 状态。当前状态为“{0}”。 + + + {0} 对象不是通过调用当前 RunspacePool 实例上的 {1} 创建的。 + + + 无法将运行空间释放到当前池,因为该运行空间不属于当前池。 + + + 打开运行空间池后,无法更改此属性。 + + + 此运行空间不支持断开连接和连接操作。 + + + 无法执行该操作,因为运行空间池处于已断开连接状态。 + + + 服务器不支持断开连接操作。 服务器必须运行 PowerShell 3.0 或更高版本,才能支持远程运行空间池断开连接。 + + + 未配置此运行空间池 {0} 为远程服务器上运行的命令提供断开连接的 PowerShell 对象。 使用 RunspacePool 类的 GetRunspacePools() 静态方法查询服务器,并返回已配置为执行此操作的运行空间池对象。 + + + 无法连接此运行空间池,因为相应的服务器端运行空间池已连接到另一个客户端。 + + + 服务器不支持 ResetRunspaceState。 服务器必须运行 PowerShell 5.0 或更高版本。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/RunspaceStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/RunspaceStrings.zh-Hans.resx new file mode 100644 index 00000000000..bccbac4a172 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/RunspaceStrings.zh-Hans.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 运行空间状态对此操作无效。 + + + 无法打开运行空间,因为运行空间未处于 BeforeOpen 状态。运行空间的当前状态为 '{0}'。 + + + 无法执行此操作,因为运行空间未处于“已打开”状态。运行空间的当前状态为 '{0}'。 + + + 无法调用管道,因为运行空间未处于“已打开”状态。运行空间的当前状态为 '{0}'。 + + + 管道状态对此操作无效。 + + + 无法调用管道,因为它已被调用。 + + + 参数的有效值为 PipelineResultTypes.Output。 + + + 管道不包含命令。 + + + 由于已有一个管道正在运行,因此未运行该管道。管道不能并发运行。 + + + 无法异步调用嵌套管道。使用 Invoke 方法。 + + + 只能从正在运行的管道中运行嵌套管道。 + + + 在进行 SessionStateProxy 方法调用时,无法关闭运行空间。 + + + 在进行 SessionStateProxy 方法调用时,无法调用管道。 + + + 正在进行 SessionStateProxy 方法调用。不允许并发 SessionStateProxy 方法调用。 + + + 管道已在运行。不允许并发 SessionStateProxy 方法调用。 + + + 打开运行空间之后无法更改此属性。 + + + 处理用于创建此运行空间的 InitialSessionState 对象中指定的模块 '{0}' 时出现一个或多个错误。有关错误的完整列表,请参阅 ErrorRecords 属性。第一个错误是: {1} + + + 仅当单元状态为多线程单元 (MTA)、当前选项为 UseNewThread 或 UseCurrentThread,且新值为 ReuseThread 时,才能更改线程选项。 + + + 当语言模式为 {0} 或 {1}时,{2} 不能为 false。 + + + 无法断开仅本地运行空间的连接。 + + + 本地运行空间不支持 Connect 操作。 + + + 会话正忙。会话可用后,你将立即连接到会话。若要取消 Enter-PSSession 命令,请按 Ctrl-C。 + + + 无法完成该命令。此会话配置中不支持脚本调用。如果会话配置处于无语言模式,则可能会发生这种情况。 + + + 无法在本地运行空间上使用 Disconnect 和 Connect 操作。 + + + 无法连接管道,因为运行空间未处于“已打开”状态。 运行空间的当前状态为 '{0}'。 + + + 无法构造 RemoteRunspace。提供的 RunspacePool 对象无效。 + + + 没有与此运行空间关联的断开连接命令。 + + + 远程计算机上不支持断开连接操作。若要支持断开连接,远程计算机必须运行 Windows PowerShell 3.0 或更高版本的 Windows PowerShell,并使用 WSMan 传输。 + + + 无法连接 PSSession,因为会话未处于 Disconnected 状态,或者无法连接。 + + + 参数值不能为 PipelineResultTypes.None 或 PipelineResultTypes.Output。 + + + 参数的有效值为 PipelineResultTypes.Output 或 PipelineResultTypes.Null。 + + + 目标远程计算机上不支持调试流重定向。 + + + 目标远程计算机上不支持详细流重定向。 + + + 目标远程计算机上不支持警告流重定向。 + + + 目标远程计算机上不支持信息流重定向。 + + + 你已进入一个正在忙于运行命令或脚本的会话。 由于输出已路由到作业“{0}”,因此你不会在控制台中看到输出。 你可以等待正在运行的命令完成,也可以按 Ctrl-C 取消命令并获取输入提示符。 + + + + 进入的会话正忙于运行命令或脚本,输出将显示在控制台中。 可以等待正在运行的命令完成,也可以按 Ctrl-C 取消它并获取输入提示符。 + + + + 你进入的会话当前在运行的命令或脚本中的调试断点处停止。 使用 PowerShell 命令行调试程序继续调试。 + + + + 默认运行空间必须是本地运行空间 + + + 静态 PrimaryRunspace 属性只能设置一次,并且已设置。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/SecuritySupportStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/SecuritySupportStrings.zh-Hans.resx new file mode 100644 index 00000000000..6a7008ed704 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/SecuritySupportStrings.zh-Hans.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法加载证书。“{0}”必须解析为文件系统路径。 + + + 证书“{0}”无法用于加密。加密证书必须包含数据加密或密钥加密密钥用法,并包括文档加密增强型密钥用法({1})。 + + + 无法加载证书。标识符“{0}”匹配多个证书。要加密发送给多个收件人,请为“{1}”参数提供多个具体值,而不要使用会匹配多个证书的通配符。 + + + 无法加载加密证书。证书设置“{0}”不代表有效的 base-64 编码证书,也不代表通过文件、目录、指纹或使用者名称指定的有效证书。 + + + 警告: 证书“{0}”包含私钥。用于加密的受保护事件日志证书应仅包含公钥。 + + + 错误: 无法保护事件日志消息“{0}”: {1} + + + 错误: 找不到或无法使用证书: {0} + + + 会话密钥不可用于加密安全字符串。 + + + 缓冲区偏移无效。 + + + 公钥数据无效。 + + + 无法导入公钥。 + + + 会话密钥数据无效。 + + + 脚本文件“{0}”被系统策略阻止运行。 + + + 返回了未知的脚本文件策略强制值: {0}。 + + + 脚本文件读取 + + + 脚本文件“{0}”不受策略信任,将在 ConstrainedLanguage 模式下运行。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/Serialization.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/Serialization.zh-Hans.resx new file mode 100644 index 00000000000..406c6d9141c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/Serialization.zh-Hans.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0} 属性是预期的。 + + + 无法识别 {0} XML 标记。 + + + 找不到 referenceId {0} 的对象 + + + 未正确指定字典键的名称属性。 + + + 未正确指定字典值的名称属性。 + + + PSObject 的版本无效。 + + + 传入的 PSObject 的版本为 {0}。预期值为 1。 + + + 无法处理名称,因为找不到 referenceId {0} 的 TypeNames。 + + + 深度参数的值必须大于或等于 1。 + + + 当前节点类型为 {0}。所需类型为 {1}。 + + + 未指定字典项的键。 + + + 未指定字典项的值。 + + + 不再存在要反序列化的对象。 + + + 已将 Null 指定为字典键。 + + + {0} 基元类型的内容无效。 + + + 序列化的 XML 嵌套太深。 + + + 序列化程序已关闭。 + + + 命令中的数据超出了会话配置允许的最大大小。允许的最大值为 {0} MB。更改输入、使用其他会话配置,或更改远程计算机上会话配置的“{1}”和“{2}”属性。 + + + 加密安全字符串反序列化失败 + + + 键类型 {0} 无效。PSPrimitiveDictionary 类仅接受 System.String 类型的键。 + + + 值 {0} 的类型无效。PSPrimitiveDictionary 类仅接受可通过 PowerShell 远程处理完全序列化的类型的值。有关完全可序列化类型的列表,请参阅帮助主题 about_Remoting。 + + + 无法解密数据。数据未使用此密钥进行加密。 + + + 参数值“{0}”不是有效的加密字符串。 + + + 指定的 {0} 无效。有效 {0} 长度为 128 位、192 位或 256 位。 + + + 目前只有 Windows 支持反序列化 SecureString。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/SessionStateProviderBaseStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/SessionStateProviderBaseStrings.zh-Hans.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/SessionStateProviderBaseStrings.zh-Hans.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/SessionStateStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/SessionStateStrings.zh-Hans.resx new file mode 100644 index 00000000000..a7eef750830 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/SessionStateStrings.zh-Hans.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法处理返回的信息,因为提供程序 Start 方法返回的信息属于其他提供程序,而不是传入的提供程序。 + + + 无法处理返回的信息,因为从提供程序的 Start 方法返回的信息为 null。 + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 GetItem 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 GetItem 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 SetItem 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 SetItem 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 ClearItem 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 InvokeDefaultAction 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 InvokeDefaultAction 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 ItemExists 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 ItemExists 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 IsValidPath 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 IsItemContainer 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 RemoveItem 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 GetChildItems 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 GetChildItems 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 GetChildNames 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 GetChildNames 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 RenameItem 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 RenameItem 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 NewItem 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 NewItem 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 HasChildItems 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 CopyItem 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 CopyItem 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 GetParentPath 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 NormalizeRelativePath 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 MakePath 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 GetChildName 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 MoveItem 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 MoveItem 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 GetProperty 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 GetProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 SetProperty 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 SetProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 ClearProperty 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 ClearProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 NewProperty 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 NewProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 RemoveProperty 操作失败。 {2} + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 RemoveProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 CopyProperty 操作失败。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索 CopyProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 MoveProperty 操作失败。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索 MoveProperty 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 RenameProperty 操作失败。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索 RenameProperty 的动态参数。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索内容读取器。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索 GetContentReader 操作的动态参数。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索内容编写器。 {2} + + + 无法为路径 '{0}' 的 '{1}' 提供程序检索 GetContentWriter 操作的动态参数。 {2} + + + 无法获取内容,因为它是目录:'{0}'。请改用 'Get-ChildItem'。 + + + 无法写入内容,因为它是目录:'{0}'。 + + + 没有可继续向后导航的位置历史记录。 + + + 没有可继续向前导航的位置历史记录。 + + + BoundedStack 为空。 + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 ClearContent 操作失败。 {2} + + + 无法清除 '{0}' 的内容,因为它是一个目录。Clear-Content 仅支持文件。 + + + 无法从路径 '{0}' 的 '{1}' 提供程序检索 ClearContent 操作的动态参数。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 ClearProperty 操作失败。 {2} + + + 尝试对路径 '{0}' 的 '{1}' 提供程序执行 SetSecurityDescriptor 操作失败。 {2} + + + 尝试对 '{0}' 提供程序执行 Start 操作失败。 {1} + + + 尝试对 '{0}' 提供程序执行 InitializeDefaultDrives 操作失败。 + + + 尝试在 '{0}' 提供程序上对根为 '{1}' 的驱动器执行 NewDrive 操作失败。 {2} + + + 无法检索 '{0}' 提供程序的 NewDrive 动态参数。 {1} + + + 在 '{0}' 提供程序上调用 RemoveDrive 失败。 {1} + + + 无法删除驱动器 '{0}',因为提供程序 '{1}' 阻止了它。 + + + 路径 '{0}' 引用了基 '{1}' 之外的项。 + + + 对路径 '{0}' 调用 '{1}' 提供程序的内容编写器上的 Seek 失败。 {2} + + + 在 '{0}' 提供程序的内容读取器或写入器上对路径 '{1}' 调用 Close 失败。 {2} + + + 对路径 '{0}' 调用 '{1}' 提供程序的内容读取器上的 Read 失败。 {2} + + + 对路径 '{0}' 调用 '{1}' 提供程序的内容编写器上的 Write 失败。 {2} + + + 提供程序 '{0}' 不能用于使用变量语法获取或设置数据。 {2} + + + 变量语法不能用于获取或设置提供程序中的数据。 {2} + + + S别名不可编写,因为别名 {0} 为只读或常量,且无法写入。 + + + 无法写入函数 {0} ,因为它是只读的或常量。 + + + 无法覆盖变量 {0} ,因为它是只读变量或常量。 + + + 无法访问变量 '${0}',因为它是私有变量。 + + + 无法访问命令 {0},因为它是专用命令。 + + + 无法访问该命令,因为它是专用命令。 + + + 无法访问会话状态资源,因为它是专用资源。 + + + 未删除别名,因为别名 {0} 是常量或只读的。 + + + 无法删除函数 {0} ,因为它是常量。 + + + 无法删除变量 {0} ,因为它是常量或只读变量。如果变量是只读的,请指定 Force 选项后重试。 + + + 无法修改别名 {0},因为它是常量。 + + + 别名 {0} 无法修改,因为它是只读的。 + + + 无法修改函数 {0} ,因为它是常量。 + + + 无法修改函数 {0} ,因为它是只读的。 + + + 别名 {0} 创建后不能设置为常量。只能在创建别名时将其设置为常量。 + + + 无法将现有函数 {0} 设为常量。只能在创建函数时将其设为常量。 + + + 现有变量 {0} 不能设为常量。变量只能在创建时设为常量。 + + + Option 键无法从别名“{0}”中删除 AllScope 选项。 + + + 无法从函数 '{0}' 中删除 AllScope 选项。 + + + 无法从变量, '{0}' 中删除 AllScope 选项。 + + + 函数定义 '{0}' 包含作用域限定符,但没有函数名称。 + + + 无法删除提供程序 {0}。必须先删除与提供程序 {0} 关联的所有驱动器,然后才能删除提供程序 {0}。 + + + 无法处理驱动器名称,因为驱动器名称包含一个或多个以下无效字符:; ~ / \ . : + + + 新驱动器创建失败,因为提供程序不允许创建新驱动器。 + + + 提供的值 '{0}' 解析为多个位置堆栈。 + + + 找不到位置堆栈 '{0}'。它不存在或不是容器。 + + + 找不到路径“{0}”,因为该路径不存在。 + + + 找不到别名,因为别名 '{0}' 不存在。 + + + 无法设置位置,因为路径 '{0}' 解析为多个容器。一次只能将位置设置为一个容器。 + + + 无法处理变量,因为变量路径 '{0}' 解析为多个项。一次只能获取或设置一个变量值。 + + + 找不到驱动器。名为“{0}”的驱动器不存在。 + + + 找不到名称为 '{0}' 的提供程序。 + + + 找不到名称为 '{0}' 的提供程序。名称的格式不正确。提供程序名称只能包含字母数字字符,或者是后跟单个 '\' 再后跟字母数字字符的 PowerShell 管理单元名称。 + + + '{0}' 解析为多个提供程序名称。可能的匹配项包括: {1}。 + + + 尝试创建提供程序的实例时出错。在程序集中找不到 '{0}' 的提供程序类型名称。 + + + 无法使用指定的提供程序名称 '{0}',因为它包含一个或多个以下无效字符:\ [ ] ? * : + + + 尝试创建提供程序 '{0}' 的实例时出错。 {1} + + + 找不到名称为“{0}”的变量。 + + + 找不到名称为“{0}”的跟踪源。 + + + 名为 '{0}' 的驱动器已存在。 + + + 已存在名称为“{0}”的变量。 + + + 不允许使用该别名,因为名为 '{0}' 的别名已存在。 + + + 无法注册 cmdlet 提供程序,因为名为 '{0}' 的 cmdlet 提供程序已存在。 + + + 路径不是文件系统路径。 + + + 无法删除全局范围。 + + + 作用域编号 '{0}' 超过活动作用域数。 + + + 无法比较 PSDriveInfo。PSDriveInfo 实例只能与另一个 PSDriveInfo 实例进行比较。 + + + cmdlet 提供程序无法流式传输结果,因为未指定用于流式传输输出的 cmdlet。 + + + cmdlet 提供程序无法流式传输结果,因为未指定用于流式传输错误的 cmdlet。 + + + 未设置此提供程序的主位置。若要设置主位置,请调用"(get-psprovider '{0}').Home = 'path'"。 + + + 路径的格式不正确。提供程序路径必须包含提供程序 ID,后跟 "::",再后跟提供程序特定路径。 + + + 无法移动该项,因为目标路径只能解析为单个路径。 + + + 无法移动该项,因为源路径和目标路径未解析为同一提供程序。 + + + 无法移动该项,因为源路径指向一个或多个项,而目标路径不是容器。请验证目标路径是否为容器,然后重试。 + + + 无法移动该项,因为目标已解析为多个路径。请指定会解析为单个目标的目标路径,然后重试。 + + + 无法将容器复制到现有叶项上。 + + + 无法将容器复制到其他容器。未指定 -Recurse 或 -Container 参数。 + + + 源路径和目标路径未解析为同一提供程序。 + + + 无法重命名项,因为路径已解析为多个项。一次只能重命名一个项。 + + + 由于提供程序中发生错误,因此无法使用提供程序 '{0}' 解析路径 '{1}'。 + + + 无法使用接口。此提供程序未实现 IContentCmdletProvider 接口。 + + + 无法使用接口。此提供程序不支持 IPropertyCmdletProvider 接口。 + + + 无法使用接口。此提供程序未实现 IDynamicPropertyCmdletProvider 接口。 + + + 此提供程序不支持 NavigationCmdletProvider 方法。 + + + 未处理提供程序方法。此提供程序不支持 ContainerCmdletProvider 方法。 + + + 无法调用方法。此提供程序不支持 ItemCmdletProvider 方法。 + + + 此提供程序不支持 DriveCmdletProvider 方法。 + + + 提供程序操作已停止,因为提供程序不支持此操作。 + + + 提供程序操作已停止,因为提供程序不支持“Depth”参数。 + + + 无法调用方法。此提供程序不支持内容 Seek 方法。 + + + 无法执行 ClearContent 操作。此提供程序不支持 ClearContent 操作。 + + + 提供程序不支持使用凭据。请在不指定凭据的情况下再次执行该操作。 + + + FileSystem 提供程序仅在 New-PSDrive cmdlet 上支持凭据。请在不指定凭据的情况下再次执行该操作。 + + + 提供程序不支持事务。请在不使用 -UseTransaction 参数的情况下再次执行该操作。 + + + 无法调用方法。提供程序不支持使用筛选器。 + + + 无法创建驱动器。提供程序不支持使用凭据。 + + + 路径“{0}”处的项已存在。 + + + 无法复制项。路径 '{0}' 处的项不存在。 + + + 路径“{0}”处的项不存在。 + + + 包含存储在会话状态中的别名视图的驱动器 + + + 包含进程环境变量视图的驱动器 + + + 包含存储在会话状态中的函数视图的驱动器 + + + 包含存储在会话状态中的这些变量视图的驱动器 + + + 映射到当前用户临时目录路径的驱动器 + + + 无法创建链接 '{0}',因为未指定目标值。 + + + 对 null 变量的引用始终返回 null 值。赋值没有效果。 + + + 会话中保留的最大历史记录对象数 + + + 无法重命名函数,因为函数 {0} 是只读的或常量。 + + + 无法重命名别名,因为别名 {0} 是只读的或常量。 + + + 无法重命名变量,因为变量 {0} 是只读的或常量。 + + + 无法在局部变量 {0}上设置选项。请使用 New-Variable 创建允许设置选项的变量。 + + + Cmdlet {0} 无法修改,因为它是只读的。 + + + 无法删除变量 {0} ,因为该变量已优化且不可删除。请尝试使用 Remove-Variable cmdlet(不要使用任何别名),或对用于删除变量的命令进行点源。 + + + 无法覆盖变量 {0} ,因为该变量已优化。请尝试使用 New-Variable 或 Set-Variable cmdlet(不要使用任何别名),或者对用于设置变量的命令进行点源。 + + + 参数 {0} 和 {1} 不能一起使用。请仅指定一个参数。 + + + 目前仅 FileSystem 提供程序支持 Tail 参数。 + + + 不允许使用该别名,因为名为 '{0}' 且命令类型为 '{1}' 的命令已存在。 + + + 无法运行软件。权限被拒绝。 + + + “-{0}”和“-{1}”是互斥的,不能同时指定。 + + + 路径 '{0}' 无效。远程复制操作仅支持绝对路径。 + + + 无法验证远程路径“{0}”。 + + + 无法执行操作,因为会话 {0} 设置为 {1}。 + + + '{0}' 参数不能为 null 或为空。 + + + 会话状态变量 + + + 在 ConstrainedLanguage 模式下,更改或创建变量 '{0}' 的作用域为 AllScope 将被阻止。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/StringDecoratedStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/StringDecoratedStrings.zh-Hans.resx new file mode 100644 index 00000000000..4e678a09522 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/StringDecoratedStrings.zh-Hans.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 此方法仅支持 "‌ANSI"‌ 或 "‌PlainText"‌。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/SubsystemStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/SubsystemStrings.zh-Hans.resx new file mode 100644 index 00000000000..6fbbda319de --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/SubsystemStrings.zh-Hans.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 + + + The subsystem '{0}' does not allow more than one implementation to be registered. + + + The implementation with Id '{0}' was already registered for the subsystem '{1}'. + + + The subsystem '{0}' does not allow the unregistration of an implementation. + + + No implementation was registered for the subsystem '{0}'. + + + A registered implementation with the Id '{0}' was not found. + + + The specified subsystem type '{0}' is unknown. + + + You must specify a concrete subsystem type instead of the base interface 'ISubsystem'. + + + The specified subsystem kind '{0}' is unknown. + + + For the target subsystem kind '{0}', the specified subsystem instance needs to implement the corresponding concrete interface or abstract class '{1}'. + + + The declared metadata for subsystem kind '{0}' is invalid. A subsystem that requires cmdlets or functions to be defined cannot allow multiple registrations because that would result in one implementation overwriting the commands defined by another implementation. + + + The 'Id' property of an implementation for the subsystem '{0}' cannot be an empty GUID. + + + The 'Name' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + + The 'Description' property of an implementation for the subsystem '{0}' cannot be null or an empty string. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/SuggestionStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/SuggestionStrings.zh-Hans.resx new file mode 100644 index 00000000000..ae0b24613a6 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/SuggestionStrings.zh-Hans.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 + + + 未找到命令“{0}”,但它确实存在于当前位置。 +默认情况下,PowerShell 不会从当前位置加载命令(请参阅 "Get-Help about_Command_Precedence")。 + +如果你信任此命令,请改为运行以下命令: + + + 最相似的命令是: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/TabCompletionStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/TabCompletionStrings.zh-Hans.resx new file mode 100644 index 00000000000..30debf0f2bf --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/TabCompletionStrings.zh-Hans.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 tab completion result cannot be properly deserialized because the remote runspace does not contain a TypeTable instance. + + + Cannot access properties on a null instance of the type CompletionResult. + + + Bitwise NOT + + + Logical not. Negates the statement that follows it. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case insensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Equal to - case sensitive. When the left operand is a collection, returns values from the collection that equal the right operand, otherwise returns TRUE if the left operand equals the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case insensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Not equal to - case sensitive. When the left operand is a collection, returns values from the collection that do not equal the right operand, otherwise returns TRUE if the left operand does not equal the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are greater than or equal to the right operand, otherwise returns TRUE if the left operand is greater than or equal to the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case insensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Greater than - case sensitive. When the left operand is a collection, returns values from the collection that are greater than the right operand, otherwise returns TRUE if the left operand is greater than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case insensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than - case sensitive. When the left operand is a collection, returns values from the collection that are less than the right operand, otherwise returns TRUE if the left operand is less than the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case insensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Less than or equal to - case sensitive. When the left operand is a collection, returns values from the collection that are less than or equal to the right operand, otherwise returns TRUE if the left operand is less than or equal to the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Wildcard matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that match the right hand operand, otherwise returns TRUE if the left operand matches the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case insensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Regular expression matching operator - case sensitive. When the left operand is a collection, returns values from the collection that do not match the right hand operand, otherwise returns TRUE if the left operand does not match the right operand. + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case insensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Replace operator - case sensitive. Changes the left operand. Example: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE only when the test value (right operand) exactly matches at least one of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (right operand) exactly matches none of the values in the left operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches at least one of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case insensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Containment operator - case sensitive. Returns TRUE when the test value (left operand) exactly matches none of the values in the right operand. + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case insensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Split - case sensitive. Split one or more strings into substrings. +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + Returns TRUE when the left operand is not an instance of the specified .NET Framework type (right operand). + + + Returns TRUE when the left operand is an instance of the specified .NET Framework type (right operand). + + + Converts the left operand to the specified .NET Framework type (right operand). + + + Formats strings by using the format method of string objects. + + + Logical and. Returns TRUE when both statements are TRUE. + + + Bitwise AND + + + Logical or. TRUE when either or both statements are TRUE. + + + Bitwise OR (inclusive) + + + Logical exclusive or. Returns TRUE when one of the statements is TRUE and the other is FALSE. + + + Bitwise OR (exclusive) + + + Join - combine multiple strings into a single string. +-Join <String[]> +<String[]> -Join <Delimiter> + + + Shift Left bit operator. Inserts zero in right-most bit position. + + + Shift Right bit operator. Inserts zero in the left-most bit position. For signed values, sign bit is preserved. + + + [string] +Specifies the name of the property being created. + + + [string] +Specifies the name of the property being created. + + + [scriptblock] +A script block used to calculate the value of the new property. + + + [string] +Define how the values are displayed in a column. +Valid values are 'left', 'center', or 'right'. + + + [string] +Specifies a format string that defines how the value is formatted for output. + + + [int] +Specifies the maximum column width in a table when the value is displayed. +The value must be greater than 0. + + + [int] +The depth key specifies the depth of expansion per property. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [bool] +Specifies the order of sorting for one or more properties. + + + [String[]] +Specifies the log names to get events from. +Supports wildcards. + + + [String[]] +Specifies the event log providers to get events from. +Supports wildcards. + + + [String[]] +Specifies file paths to log files to get events from. +Valid file formats are: .etl, .evt, and .evtx + + + [Long[]] +Selects events with the specified keyword bitmasks. +The following are standard keywords: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +Selects events with the specified event IDs. + + + [int[]] +Selects events with the specified log levels. +The following log levels are valid: +1: Critical +2: Error +3: Warning +4: Informational +5: Verbose + + + [datetime] +Selects events created after the specified date and time. + + + [datetime] +Selects events created before the specified date and time. + + + [string] +Selects events generated by the specified user. +This can either be a string representation of a SID or a domain and username in the format DOMAIN\USERNAME or USERNAME@DOMAIN + + + [string[]] +Selects events with any of the specified values in the EventData section. + + + [hashtable] +Excludes events that match the values specified in the hashtable. + + + [string] or [hashtable] +Specifies an array of PowerShell modules that the script requires. +Each element can either be a string with the module name as value or a hashtable with the following keys: +Name: Name of the module +GUID: GUID of the module +One of the following: +ModuleVersion: Specifies a minimum acceptable version of the module. +RequiredVersion: Specifies an exact, required version of the module. +MaximumVersion: Specifies the maximum acceptable version of the module. + + + [string] +Specifies a PowerShell edition that the script requires. +Valid values are "Core" and "Desktop" + + + [switch] +Specifies that PowerShell must be running as administrator on Windows. +This must be the last parameter on the #requires statement line. + + + [version] +Specifies the minimum version of PowerShell that the script requires. + + + Specifies that the script requires PowerShell 7+ to run. + + + Specifies that the script requires Windows PowerShell 5.1 to run. + + + [string] +Required. Specifies the module name. + + + [string] +Optional. Specifies the GUID of the module. + + + [string] +Specifies a minimum acceptable version of the module. + + + [string] +Specifies an exact, required version of the module. + + + [string] +Specifies the maximum acceptable version of the module. + + + A brief description of the function or script. +This keyword can be used only once in each topic. + + + A detailed description of the function or script. +This keyword can be used only once in each topic. + + + .PARAMETER <Parameter-Name> +The description of a parameter. +Add a .PARAMETER keyword for each parameter in the function or script syntax. + + + A sample command that uses the function or script, optionally followed by sample output and a description. +Repeat this keyword for each example. + + + The .NET types of objects that can be piped to the function or script. +You can also include a description of the input objects. + + + The .NET type of the objects that the cmdlet returns. +You can also include a description of the returned objects. + + + Additional information about the function or script. + + + The name of a related topic. +Repeat the .LINK keyword for each related topic. +The .Link keyword content can also include a URI to an online version of the same help topic. + + + The name of the technology or feature that the function or script uses, or to which it is related. + + + The name of the user role for the help topic. + + + The keywords that describe the intended use of the function. + + + .FORWARDHELPTARGETNAME <Command-Name> +Redirects to the help topic for the specified command. + + + .FORWARDHELPCATEGORY <Category> +Specifies the help category of the item in .ForwardHelpTargetName + + + .REMOTEHELPRUNSPACE <PSSession-variable> +Specifies a session that contains the help topic. +Enter a variable that contains a PSSession object. + + + .EXTERNALHELP <XML Help File> +The .ExternalHelp keyword is required when a function or script is documented in XML files. + + + Specifies the path to a .NET assembly to load. + +using assembly <.NET-assembly-path> + + + Specifies a PowerShell module to load classes from. + +using module <ModuleName or Path> + +using module <ModuleSpecification hashtable> + + + Specifies a .NET namespace to resolve types from or a namespace alias. + +using namespace <.NET-namespace> + +using namespace <AliasName> = <.NET-namespace> + + + Specifies an alias for a .NET Type. + +using type <AliasName> = <.NET-type> + + + A normal string. + + + A string that contains unexpanded references to environment variables that are expanded when the value is retrieved. + + + Binary data in any form. + + + A 32-bit binary number. + + + An array of strings. + + + A 64-bit binary number. + + + An unsupported registry data type. + + + ',' - Comma + + + ', ' - Comma-Space + + + ';' - Semi-Colon + + + '; ' - Semi-Colon-Space + + + {0} - Newline + + + '-' - Dash + + + ' ' - Space + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/TransactionStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/TransactionStrings.zh-Hans.resx new file mode 100644 index 00000000000..7047d4986ee --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/TransactionStrings.zh-Hans.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 无法使用事务。没有活动的事务。 + + + 无法提交事务。没有活动的事务。 + + + 由于没有活动事务,因此无法回滚事务。 + + + 无法回滚事务。事务已提交。 + + + 无法提交事务。事务已提交。 + + + 无法提交事务。事务已回滚或已超时。 + + + 无法回滚事务。事务已回滚或超时。 + + + 无法设置活动事务。尚未创建任何事务。 + + + 无法设置活动事务。活动事务已回滚或已超时。 + + + 此 cmdlet 需要一个活动事务。当前事务已提交或已回滚。 + + + 此 cmdlet 需要一个事务。使用 -UseTransaction 参数再次运行该命令。 + + + 无法使用事务。尚未启动任何事务。 + + + 无法使用事务。事务已提交。 + + + 无法使用事务。事务已回滚或已超时。 + + + 无法使用事务。事务已超时。 + + + 尚未设置基本事务。 + + + 基本事务未处于活动状态。 + + + 创建其他事务后,无法设置基本事务。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/TypesXmlStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/TypesXmlStrings.zh-Hans.resx new file mode 100644 index 00000000000..8aa4a9b8cf2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/TypesXmlStrings.zh-Hans.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0}, {1}({2}) : 错误: {3} + + + {0}, {1}({2}) : 类型“{3}”出错: {4} + + + 节点“{0}”在“{1}”下只能出现一次。将忽略父节点“{1}”。 + + + 不允许节点 {0}。允许以下节点: {1}。 + + + 节点“{0}”不应有内部文本。 + + + 节点“{0}”应具有内部文本。 + + + 找不到节点“{0}”。在“{1}”下应只出现一次。将忽略父节点“{1}”。 + + + "Type" 节点必须包含 "Members"、"TypeConverters" 或 "TypeAdapters"。 + + + 由于异常: {1},无法为类型 {0} 创建类型转换器实例。 + + + 由于发生以下异常: {1},PowerShell 无法为类型 {0} 创建类型适配器实例。 + + + 适配的类型“{0}”无效。 + + + TypeConverter 被忽略,因为它已发生。 + + + TypeAdapter 被忽略,因为它已发生。 + + + 类型“{0}”应为 TypeConverter 或 PSTypeConverter。 + + + 类型“{0}”应为 PSPropertyAdapter。 + + + 成员 {0} 已存在。 + + + 以下成员名称已保留: {0} + + + 异常: {0} + + + ScriptProperty 应具有 getter 或 setter。 + + + CodeProperty 应具有 getter 或 setter。 + + + {0}, {1} : {2} + + + 该值应为 TRUE 或 FALSE,而不是 {0}。 + + + 节点“{0}”不应具有“{1}”属性。 + + + {0}, {1}: 找不到该文件。 + + + {0}, {1}: 已跳过该文件,因为它已由 {2} 加载。 + + + 无法找到注册表项: {0}{1}。使用 {2} 加载配置文件。 + + + 找不到注册表项中指定的路径 {0}: {1}{2}。使用 {3} 加载配置文件。 + + + {0}, {1}: 已跳过该文件,因为它没有 ps1xml 文件扩展名。 + + + {0}, {1}: 已跳过该文件,因为出现以下验证异常: {2}。 + + + 成员“{0}”必须是注释。 + + + 无法转换注释“{0}”:“{1}”。 + + + 请勿在此处使用成员“{0}”。 + + + 成员“{0}”必须具有类型“{1}”。 + + + 当“{1}”为“{2}”且“{3}”为“{4}”时,“{0}”必须存在。 + + + 先前的错误导致忽略所有序列化设置。 + + + “{0}”不是标准成员,将被忽略。 + + + {0} 路径未完全限定。请指定完全限定的类型文件路径。 + + + 无法更新 TypeTable,因为 TypeTable 可能是在运行空间外部创建的。 + + + 加载 TypeTable 时出错。请查看 Errors 属性以获取详细错误消息。 + + + TypeData “{0}” 中出错: {1} + + + “{0}”应具有其属性“{1}”的值。 + + + “{0}”的属性“{1}”中不应包含 null 或空字符串。 + + + 找不到类型“{0}”。类型名称值必须是该类型的全名。请验证类型名称,然后再次运行该命令。 + + + TypeData 必须具有 "Members"、"TypeConverters"、"TypeAdapters" 或 "StandardMembers"。 + + + 无法使用多个条目更新共享类型表。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/VerbDescriptionStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/VerbDescriptionStrings.zh-Hans.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/VerbDescriptionStrings.zh-Hans.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hans/WildcardPatternStrings.zh-Hans.resx b/src/System.Management.Automation/resources/zh-Hans/WildcardPatternStrings.zh-Hans.resx new file mode 100644 index 00000000000..c475da88955 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hans/WildcardPatternStrings.zh-Hans.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 + + + 指定的通配符模式无效: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/Authenticode.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/Authenticode.zh-Hant.resx new file mode 100644 index 00000000000..f705bf226ae --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/Authenticode.zh-Hant.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 + + + 無法載入檔案 {0},因為您選擇現在不執行此軟體。 + + + 無法載入檔案 {0},因為您選擇一律不執行來自此發行者的軟體。 + + + 檔案 {0} 由 {1} 發行。此發行者在您的系統上明確不受信任。此指令碼將不會在系統上執行。如需詳細資訊,請執行命令 "get-help about_signing"。 + + + 無法載入檔案 {0},因為此系統已停用指令碼執行。如需詳細資訊,請參閱 https://go.microsoft.com/fwlink/?LinkID=135170 中的 about_Execution_Policies。 + + + 無法載入檔案 {0}。{1}。 + + + 無法載入檔案 {0},因為軟體限制原則封鎖了其作業,例如使用群組原則所建立的原則。 + + + 無法載入檔案 {0},因為無法讀取其內容。 + + + 無法簽署程式碼。指定的憑證不適合程式碼簽署。 + + + 無法簽署程式碼。TimeStamp 伺服器 URL 必須完整且格式為 http://<server url> 或 https://<server url>。 + + + 無法簽署程式碼。不支援雜湊演算法。 + + + 您要執行來自這個不受信任的發行者的軟體嗎? + + + 檔案 {0} 由 {1} 發行,且在您的系統上不受信任。只執行來自受信任發行者的指令碼。 + + + 軟體 {0} 的發行者未知。建議您不要執行此軟體。 + + + 安全性警告 + + + 只執行您信任的指令碼。雖然這些來自網際網路的指令碼可能很有用,但是此指令碼也可能對您的電腦造成傷害。如果您信任此指令碼,請使用 Unblock-File cmdlet,讓指令碼在沒有此警告訊息的情況下執行。是否要執行 {0}? + + + 一律不執行(&V) + + + 現在請不要執行來自此發行者的指令碼,且未來請勿提示我執行此指令碼。未來嘗試執行此指令碼將會無訊息失敗。 + + + 不要執行(&D) + + + 現在請不要執行來自此發行者的指令碼,並在未來繼續提示我執行此指令碼。 + + + 執行一次(&R) + + + 請立即執行來自此發行者的指令碼,並在未來繼續提示我執行此指令碼。 + + + 一律執行(&A) + + + 執行來自此發行者的指令碼,且未來請勿提示我執行此指令碼。 + + + 暫止(&S) + + + 暫停目前的管線並返回命令提示字元。完成後,輸入 exit 以繼續作業。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/AuthorizationManagerBase.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/AuthorizationManagerBase.zh-Hant.resx new file mode 100644 index 00000000000..e559474087e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/AuthorizationManagerBase.zh-Hant.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 + + + AuthorizationManager 檢查失敗。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/AutomationExceptions.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/AutomationExceptions.zh-Hant.resx new file mode 100644 index 00000000000..c1d7833ade0 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/AutomationExceptions.zh-Hant.resx @@ -0,0 +1,210 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法處理引數,因為引數 "{0}" 的值無效。請將 "{0}" 引數的值變更後,再次執行作業。 + + + 無法處理引數,因為參數 "{0}" 的值無效。有效值為 "Global"、"Local" 或 "Script",或相對於目前範圍的數字 (0 至範圍數目,0 為目前範圍,1 為其父系)。請將 "{0}" 參數的值變更後,再次執行作業。 + + + 無法處理引數,因為引數 "{0}" 的值為 Null。請將引數 "{0}" 的值變更為非 null 值。 + + + 無法處理引數,因為引數 "{0}" 的值超出範圍。請將引數 "{0}" 變更為範圍內的值。 + + + 無法執行作業,因為作業 "{0}" 無效。請移除作業 "{0}",或調查其無效的原因。 + + + 無法執行作業,因為未實作作業 "{0}"。 + + + 無法執行作業,因為不支援作業 "{0}"。 + + + 無法執行作業,因為物件 "{0}" 已經處置。 + + + 無法啟動指令碼區塊,因為它包含一個以上的子句。Invoke() 方法只能用於包含單一子句的指令碼區塊。 + + + 無法轉換指令碼區塊,因為它包含一個以上的子句。不允許表情符號或控制項結構。請確認指令碼區塊剛好包含一個管線或命令。 + + + 空白的指令碼區塊無法轉換。請確認指令碼區塊剛好包含一個管線或命令。 + + + 只能轉換剛好包含一個管線或命令的指令碼區塊。不允許表情符號或控制項結構。請確認指令碼區塊剛好包含一個管線或命令。 + + + 包含最上層 trap 陳述式的指令碼區塊無法轉換。 + + + 無法為在 param(...)區塊中參照未宣告變數的 ScriptBlock 產生 PowerShell 物件。 未宣告的變數名稱: {0}。 + + + 無法為評估非常數運算式的 ScriptBlock 產生 PowerShell 物件。非常數運算式: {0}。 + + + 無法為評估動態運算式的 ScriptBlock 產生 PowerShell 物件。動態運算式: {0}。 + + + 無法為嘗試在引數值內傳遞其他指令碼區塊的 ScriptBlock 產生 PowerShell 物件。 + + + 無法為會叫用管線、命令或函式來評估主管線引數的 ScriptBlock 產生 PowerShell 物件。 + + + 無法為使用點來源執行的 ScriptBlock 產生 PowerShell 物件。 + + + 無法為叫用其他指令碼區塊的 ScriptBlock 產生 PowerShell 物件。 + + + 指令碼區塊無法轉換成 PowerShell 物件,因為它包含禁止的重新導向運算子。 + + + 無法為沒有相關聯作業內容的 ScriptBlock 產生 PowerShell 物件。 + + + 使用者已中止命令。 + + + 物件 "{0}" 的類型不正確,無法從 dynamicparam 區塊傳回。dynamicparam 區塊必須傳回 $null,或傳回類型為 [System.Management.Automation.RuntimeDefinedParameterDictionary] 的物件。 + + + 指令碼區塊無法轉換成開放泛型類型。請先定義適當的關閉泛型類型,然後重試。 + + + 無法為以運算式啟動管線的 ScriptBlock 產生 PowerShell 物件。 + + + 無法擷取 using 變數 '$using:{0}' 的值,因為它尚未在本機工作階段中設定。 + + + 無法取得指定變數字典中 Using 運算式 '{0}' 的值。從指令碼區塊建立 PowerShell 執行個體時,Using 運算式不能包含索引作業或成員存取作業。 + + + 編譯的指令碼區塊點來源 + + + 在受限語言模式中,將不允許將指令碼區塊 '{0}' 呼叫至目前範圍。指令碼語言模式: {1},內容語言模式: {2}。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CatalogStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CatalogStrings.zh-Hant.resx new file mode 100644 index 00000000000..c0bd95ed0a1 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CatalogStrings.zh-Hant.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法產生目錄定義檔。 + + + 正在將檔案 '{0}' 新增至目錄中。檔案在目錄中的相對路徑為 '{1}'。 + + + 正在略過驗證來自目錄的檔案 {0}。 + + + 在目錄中找到檔案 {0},其雜湊為 {1}。 + + + 目錄的路徑包含多個具有相同相對路徑 {0} 的檔案。 + + + 在磁碟上找到檔案 {0},其雜湊為 {1}。 + + + 正在略過驗證來自路徑的檔案 {0}。 + + + 無法為指定的雜湊演算法 {0} 取得目錄管理員內容的控制代碼。 + + + 無法建立檔案 {0} 的雜湊。 + + + 無法開啟類別目錄檔案 {0}。 + + + 目錄版本無效。我們只支援目錄版本 {0} 和版本 {1}。 + + + 無法開啟目錄定義檔。 + + + 在目錄中找到檔案成員 {0} 的多個項目。 + + + 找不到目錄成員 {0} 的檔案名稱或路徑。 + + + 找不到要進行雜湊演算的檔案 {0}。 + + + 無法讀取檔案 {0} 以計算其雜湊。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CimInstanceTypeAdapterResources.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CimInstanceTypeAdapterResources.zh-Hant.resx new file mode 100644 index 00000000000..4f3fda63c2e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CimInstanceTypeAdapterResources.zh-Hant.resx @@ -0,0 +1,127 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 convert "{0}" to an object of type "{1}". + + + "{0}" is a ReadOnly property. + {0} gets property name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CmdletizationCoreResources.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CmdletizationCoreResources.zh-Hant.resx new file mode 100644 index 00000000000..2d2918620f0 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CmdletizationCoreResources.zh-Hant.resx @@ -0,0 +1,199 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '{0}' 類別的 Cmdlet + {0} is a placeholder for a name of a CIM class. Example: "ROOT\cimv2\Win32_Process" + + + + Two cmdlet parameters defined within the {0} element have the same name: {1}. Resolve the conflict in the Cmdlet Definition XML and retry. + {StrContains="CmdletParameterMetadata"} {StrContains="PSName"} +{0} is a placeholder for a name of an XML element. Example: <GetCmdletParameters> +{1} is a placeholder for a cmdlet parameter name. Example: Name + + + 無法處理下列檔案的 Cmdlet 定義 XML: {0}。 {1} + {0} is a placeholder for a file name. +{1} is an exception message copied from an XmlException or XmlSchemaException + + + The {0} cmdlet defines the {1} parameter set more than once. Verify that the Cmdlet Definition XML does not have duplicate parameter set names and retry. + {StrContains="CmdletParameterSet"} +{0} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{1} is a placeholder for a parameter set name. Example: 'foo' + + + 無法處理 ObjectModelWrapper 屬性。{0} 類型定義了多個參數集。請確認 Cmdlet 定義 XML 在 ObjectModelWrapper 屬性中指定有效的類型,然後再試一次。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + 無法處理 ObjectModelWrapper 屬性。{0} 類型是開放式泛型類型。 請確認 Cmdlet 定義 XML 在 ObjectModelWrapper 屬性中指定有效的類型,然後再試一次。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress + + + 無法處理 ObjectModelWrapper 屬性。{0} 類型不是從下列類別衍生: {1}。 請確認 Cmdlet 定義 XML 在 ObjectModelWrapper 屬性中指定有效的類型,然後再試一次。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a .NET class name. Example: Microsoft.PowerShell.Cmdletization.ObjectModelWrapper + + + 無法處理 ObjectModelWrapper 屬性。{0} 類型定義了 {1} Cmdlet 參數,且帶有一個會被忽略的 {2} 屬性參數。 請確認 Cmdlet 定義 XML 在 ObjectModelWrapper 屬性中指定有效的類型,然後再試一次。 + {StrContains="ObjectModelWrapper"} +{0} is a placeholder for a .NET class name. Example: System.Net.IPAddress +{1} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{2} is a placeholder for a name of a property of ParameterAttribute class. Example: ValueFromPipelineByPropertyName + + + 無法為 {1} Cmdlet 定義 {0} 參數。 參數名稱已由 {2} 類別定義。 請在 Cmdlet 定義 XML 中變更參數名稱,然後再試一次。 + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for a .NET class name. Example: 'Microsoft.PowerShell.Cmdletization.Cim.CimWrapper' + + + 無法為 {1} Cmdlet 定義 {0} 參數。參數名稱已在 {2} XML 元素內定義。請變更 Cmdlet 定義 XML 中的參數名稱,然後再試一次。 + {0} is a placeholder for a cmdlet parameter name. Example: 'ProcessId' +{1} is a placeholder for a cmdlet name. Example: 'Get-Win32Process' +{2} is a placeholder for an xml element name. Example: <GetCmdletParameters> + + + {0} {1} + This is a resource string, to support locales where the order of placeholders might need to be reversed. +{0} is a placeholder for a top-level exception message (i.e. "There is an error in XML document (2, 2).") +{1} is a placeholder for a secondary exception message (i.e. "") + + + EnumName 屬性的值無法轉換為有效的 C# 識別碼: {0}。請在 Cmdlet 定義 XML 中確認 EnumName 屬性,然後再試一次。 + {StrContains="EnumName"} + + + The value of the Name attribute is not a valid C# identifier: {0}. Verify the Name attribute in the Cmdlet Definition XML, and then try again. + {StrContains="Enum"} {StrContains="Value"} {StrContains="Name"} + + + 無法處理 <Enum EnumName="{0}" ...> 元素。{1} + {StrContains="Enum"} {StrContains="EnumName"} + + + 遠端電腦傳回了無效的 CDXML 檔案。不支援下列 Cmdlet 配接器用於從遠端電腦匯入 CDXML 模組: {0} + {0} is a placeholder for a fully qualified type name + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CommandBaseStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CommandBaseStrings.zh-Hant.resx new file mode 100644 index 00000000000..13ba4e1f789 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CommandBaseStrings.zh-Hant.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 要繼續此作業嗎? + + + 是(&Y) + + + 只繼續執行作業的下一個步驟。 + + + 全部皆是(&A) + + + 繼續執行此作業的所有步驟。 + + + 否(&N) + + + 略過此作業並繼續執行下一個作業。 + + + 全部皆否(&L) + + + 略過此作業和所有後續作業。 + + + 停止此命令。 + + + 終止命令(&H) + + + 暫止(&S) + + + 暫停目前的管線並返回命令提示字元。輸入 "{0}" 以繼續管線。 + + + + 程式 "{0}" 以非零結束代碼結束: {1} ({2})。 + + + 正在目標 "{1}" 上執行作業 "{0}" 。 + + + 假設狀況: {0} + + + 確定要執行此動作嗎? +{0} + + + 確認 + + + 執行中的命令已停止,因為喜好設定變數 "{0}" 或一般參數設定為「停止」: {1} + + + 執行中的命令已停止,因為喜好設定變數 "{0}" 或一般參數設定為「停止」。 + + + 執行中的命令已停止,因為喜好設定變數 "{0}" 或一般參數設定為下列無效值: "{1}"。 + + + 執行中的命令已停止,因為使用者選取了 [停止] 選項。 + + + 執行中的命令已停止,因為使用者中斷了命令。 + + + 無法直接叫用衍生自 PSCmdlet 的 Cmdlet。 + + + Cmdlet '{0}' 不支援遠端工作階段中的參數 '{1}'。 + + + 總計數: {0} + {0} is a placeholder for an integer number. + +Reviewed by TArcher on 2010-07-20 + + + 預估的總計數: {0} + {0} is a placeholder for an integer number + +Reviewed by TArcher on 2010-07-20 + + + + 未知的總計數 + Reviewed by TArcher on 2010-07-20 + + + 命令 '{0}' + + + {0} 已過時。{1} + + + Exec 呼叫失敗,命令列錯誤碼為 {0}: {1} + + + 找不到命令 '{0}'。指定的命令必須是可執行檔。 + + + 指令碼區塊處理 Dot-Source 檢查 + + + 在受限語言模式中,指令碼區塊 '{0}' 的 Dot-Source 處理將會失敗,因為其語言模式 '{1}' 與目前的語言模式 '{2}' 不符。 + + + 命令搜尋程式 + + + 模組 '{1}' 中的命令 '{0}' 不受信任,因此無法在 ConstrainedLanguage 模式中存取。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ConsoleInfoErrorStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ConsoleInfoErrorStrings.zh-Hant.resx new file mode 100644 index 00000000000..2b7c8007e1e --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ConsoleInfoErrorStrings.zh-Hant.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Incorrect PowerShell version {0}. PowerShell version {1} is supported on this computer. + + + The following errors occurred when loading console {0}: {1} + + + Cannot load PowerShell snap-in {0} because of the following error: {1} + + + PowerShell snap-in "{0}" loaded with the following warnings: {1} + + + The PowerShell snap-in module {0} does not have the required PowerShell snap-in strong name {1}. + + + The cmdlet '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell provider '{0}' should not occur more than once in PowerShell snap-in '{1}'. + + + PowerShell {0} is not supported in the current console. PowerShell {1} is supported in the current console. + + + File {0} already exists and {1} was specified. + + + The provided configuration file '{0}' does not exist. + + + The provided configuration file '{0}' must have a .pssc file extension. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CoreClrStubResources.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CoreClrStubResources.zh-Hant.resx new file mode 100644 index 00000000000..c33a793dd25 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CoreClrStubResources.zh-Hant.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 環境變數名稱不能包含等號。 + + + 環境變數名稱或值過長。 + + + 字串中的第一個字元是 null 字元。 + + + 字串長度不可為零。 + + + 無法取得電腦名稱。 + + + 無法取得目前使用者的網域名稱。 + + + 未知的錯誤 "{0}"。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CredUI.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CredUI.zh-Hant.resx new file mode 100644 index 00000000000..f40930644a5 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CredUI.zh-Hant.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + PowerShell 認證要求 + + + 請輸入您的認證。 + + + 請輸入您的認證。 + + + 標題的長度上限為 {0} 個字元。 + + + 訊息的長度上限為 {0} 個字元。 + + + UserName 值的長度上限為 {0} 個字元。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/Credential.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/Credential.zh-Hant.resx new file mode 100644 index 00000000000..240973d4c73 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/Credential.zh-Hant.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 + + + Cannot serialize the credential. If this command is starting a workflow, the credentials cannot be persisted, because the process in which the workflow is started does not have permission to serialize credentials. + +-- If the workflow was started in a PSSession to the local computer, add the EnableNetworkAccess parameter to the command that created the session. +-- If the workflow was started in a PSSession to a remote computer, add the Authentication parameter with a value of CredSSP to the command that created the session. Or, connect to a session configuration that has a RunAsUser property value. + + + The value for UserName is not in the correct format. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/CredentialAttributeStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/CredentialAttributeStrings.zh-Hant.resx new file mode 100644 index 00000000000..187bfd6dde4 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/CredentialAttributeStrings.zh-Hant.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 + + + PowerShell 認證要求 + + + 輸入認證。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/DebuggerStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/DebuggerStrings.zh-Hant.resx new file mode 100644 index 00000000000..70cf2f92164 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/DebuggerStrings.zh-Hant.resx @@ -0,0 +1,264 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + '${0}' 上的變數中斷點 ({1} 存取) + + + '{0}:${1}' 上的變數中斷點 ({2} 存取) + + + '{0}:{1}' 上的行中斷點 + + + '{0}:{1}, {2}' 上的行中斷點 + + + 在 '{0}' 上的命令中斷點 + + + 在 '{0}:{1}' 上的命令中斷點 + + + 中斷點 {0} 將不會命中 + + + {0}, {1,-16} 單一步驟 (逐步執行函式、指令碼等) + + + {0}, {1,-16} 逐步執行至下一個陳述式 (不進入函式、指令碼等) + + + {0}, {1,-16} 跳出目前的函式、指令碼等。 + + + {0},{1,-16} 繼續作業 + + + {0},{1,-16} 停止作業並結束偵錯工具 + + + {0},Get-PSCallStack 顯示呼叫堆疊 + + + {0}, {1,-16} 列出目前指令碼的原始程式碼。 + + + 使用 "list" 從目前行開始,"list <m>" + + + 從第 <m>行開始,並使用「list <m> <n>」列出 <n> + + + 從第 <m> 行開始的行數 + + + <enter> 如果是 {0}、{1} 或 {2},則重複上一個命令 + + + {0},{1,-16} 顯示此說明訊息。 + + + 如需如何自訂偵錯工具提示的指示,請輸入 "help about_prompt"。 + + + +目前的工作階段不支援偵錯;作業將繼續。 + + + + + {0}: 第 {1} 行 + + + 沒有可用的原始程式碼。 + + + 起始行必須是不大於 {0} 的正整數 + + + 行計數必須是正整數。 + + + <沒有檔案> + + + 位於 {0},{1}: 第 {2} 行 + + + 除非偵錯工具處於 Stopped 狀態,否則無法處理命令。 + + + 未針對本機指令碼偵錯工具實作 SetDebugAction。 + + + 偵錯工具無法設定繼續動作,因為遠端工作階段中的偵錯工具不是處於 Stopped 狀態。 + + + 無法偵錯工作,因為偵錯工具目前忙碌中。 + + + 已檢查提供的作業及所有子作業,但找不到可偵錯的作業。 若要偵錯作業或子作業,作業必須支援偵錯,而且也必須處於執行中狀態。 + + + 無法為逐步模式啟用偵錯工具,因為偵錯工具已關閉,且偵錯模式設定為 None。 + + + 無法偵錯 Runspace,因為主機偵錯工具目前忙碌中。 + + + 無法偵錯 Runspace。Runspace 偵錯工具目前已關閉 (DebugMode 為 'None')。 + + + 無法偵錯不是處於「已開啟」狀態的 Runspace。此 Runspace 狀態為 {0}。 + + + 無法偵錯 Runspace。Runspace {0} 沒有相關聯的偵錯工具。 + + + 偵錯工具已經覆寫。 + + + 無法將偵錯工具物件推送到自身。 + + + 在遠端 Runspace 中執行的 PowerShell 版本不支援遠端使用 {0} 命令。 + + + 處理序 + + + {0}, {1,-16} 繼續操作並中斷連結偵錯工具。 + + + 偵錯工具中斷連結命令不適用。 只有在使用 Debug-Job 或 Debug-Runspace Cmdlet 偵錯工作和 Runspace 時,才會套用中斷連結命令。 + + + Runspace 識別碼無效: {0} + + + 無法取得 Runspace。 + + + 必須指定中斷點或 BreakpointList。 + + + BreakpointList 包含不是中斷點的項目。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/DescriptionsStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/DescriptionsStrings.zh-Hant.resx new file mode 100644 index 00000000000..bd5ca51d091 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/DescriptionsStrings.zh-Hant.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 + + + {0} 不可為 Null 或空白。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/DiscoveryExceptions.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/DiscoveryExceptions.zh-Hant.resx new file mode 100644 index 00000000000..071f3fbedfa --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/DiscoveryExceptions.zh-Hant.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 + + + 無法驗證 cmdlet 名稱“{0}”,因為它的格式不正確。Cmdlet 名稱必須包括以 "-" 分隔的動詞和名詞,例如 "Get-Process"。 + + + 參數 “{0}” 在參數集 “{1}” 中宣告多次。 + + + 別名 "{0}" 已宣告多次。 + + + 無法宣告參數。只能在欄位和屬性上宣告參數。 + + + 無法處理 cmdlet。Cmdlet 名稱必須包含以 '-' 分隔的動詞和名詞組。 + + + 無法將 '{0}' 字詞辨識為 Cmdlet、函式、指令檔或可執行程式的名稱。 +請檢查名稱拼字,如果名稱含有路徑,請確認路徑正確,然後再試一次。 + + + 引數 '{0}' 無法辨識為 cmdlet: {1} + + + 無法將引數 '{0}' 辨識為 Cmdlet,可能是因為它並非衍生自 Cmdlet 或 PSCmdlet 類別: {1} + + + 無法解析別名 '{0}',因為它是指 '{1}' 字詞,無法辨識為 Cmdlet、函式、可執行程式或指令檔。請驗證字詞,然後再試一次。 + + + 無法處理值為 '{1}' 的參數 '{0}',因為它不是 Cmdlet 且無法由 CommandProcessor 處理。 + + + 名為 '{0}' 的 Cmdlet 已經存在。Cmdlet 必須具有唯一的名稱。 + + + 名為 '{0}' 的 Cmdlet 提供者已經存在。Cmdlet 提供者必須具有唯一的名稱。 + + + 名為 '{0}' 的組件已經存在。組件必須具有唯一的名稱。 + + + 名為 '{0}' 的指令碼已經存在。指令碼必須具有唯一的名稱。 + + + 無法處理 #requires 陳述式,因為它的格式不正確。 +#requires 陳述式必須為下列其中一種格式: + "#requires -shellid <shellID>" + "#requires -version <major.minor>" + "#requires -psedition <edition>" + "#requires -pssnapin <psSnapInName> [-version <major.minor>]" + "#requires -modules <ModuleSpecification>" + "#requires -runasadministrator" + + + 無法執行指令碼 '{0}',因為其中包含的 "#requires" 陳述式中有與目前殼層不相容之 {1} 的殼層識別碼。若要執行此指令碼,您必須使用位於 '{2}' 的殼層。 + + + 無法執行指令碼 '{0}',因為其中包含的 "#requires" 陳述式中有與目前殼層不相容之 {1} 的殼層識別碼。 + + + 無法執行指令碼 '{0}',因為其中包含 PowerShell {1}'的 "#requires" 陳述式。指令碼所需的 PowerShell 版本與目前執行中的PowerShell {2} 版本不符。 + + + 無法執行指令碼 '{0}',因為其中包含 PowerShell 版本 ‘{1}'的 "#requires" 陳述式。指令碼所需的 PowerShell 版本與目前執行中的PowerShell {2} 版本不符。 + + + 無法執行指令碼 '{0}',因為遺漏指令碼的 "#requires" 陳述式所指定的下列嵌入式管理單元: {1}。 + + + #requires 陳述式僅指定了 shellID。在 PowerShell 中執行時,#Requires 陳述式必須指定必要的 PowerShell 嵌入式管理單元。 + + + 無法執行指令碼 '{0}',因為其中包含可以系統管理員身分執行的 "#requires" 陳述式。目前的 PowerShell 工作階段不是以系統管理員身分執行。使用 [以系統管理員身分執行] 選項啟動 Powershell,然後嘗試再次執行指令碼。 + + + {0} (版本 {1}) + + + 無法擷取命令,因為只有在擷取單一 cmdlet 或指令碼時才能指定 ArgumentList 參數。 + + + 參數名稱 "{0}" 保留給未來使用。 + + + 無法執行指令碼 '{0}',因為遺漏指令碼的 "#requires" 陳述式所指定的下列模組: {1}。 + + + 在模組 '{1}' 中找到 '{0}' 命令,但無法載入模組。如需詳細資訊,請執行 'Import-Module {1}'。 + + + 在模組 '{1}' 中找到 '{0}' 命令,但因為以下錯誤而無法載入模組: [{2}] +如需詳細資訊,請執行 'Import-Module {1}'。 + + + 無法載入模組 '{0}'。如需詳細資訊,請執行 'Import-Module {0}'。 + + + 沒有相符的命令包含名為 '{0}' 的參數。 檢查參數名稱的拼字,然後再試一次。 + + + 無法將此命令以點為來源,因為它是以不同的語言模式定義。若要在不匯入其內容的情況下叫用此命令,請省略 '.' 運算子。 + + + 無法同時指定 ShowCommandInfo 和 Syntax 參數。 + + + 已開啟實驗性功能 '{0}' 時,此指令碼命令會停用。 + + + 已關閉實驗性功能 '{0}' 時,此指令碼命令會停用。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/EnumExpressionEvaluatorStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/EnumExpressionEvaluatorStrings.zh-Hant.resx new file mode 100644 index 00000000000..8faa9a881bd --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/EnumExpressionEvaluatorStrings.zh-Hant.resx @@ -0,0 +1,148 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 input expression must not be empty. Specify at least one identifier name in each input expression. + + + Unable to match an empty identifier name to a valid enumerator name. Specify one of the following enumerator names and retry: {0}. + + + The generic type specified for the expression must represent an enum. Specify a valid enum type. + + + The identifier name {0} cannot be processed because it is either too similar or identical to the following enumerator names: {1}. Use a more specific identifier name. + + + Unable to match the identifier name {0} to a valid enumerator name. Specify one of the following enumerator names and try again: +{1} + + + Use of parentheses is not valid in the expression because identifier grouping is not allowed. Try removing the parentheses, or if a subexpression is enclosed, try expanding the expression. + + + Unable to parse the expression due to an unexpected token. Only an OR (,) operator or AND (+) operator is expected after an identifier name. + + + Unable to parse the expression due to an unexpected token after a NOT (!) operator. An identifier name is expected after a NOT (!) operator. + + + Unable to parse the expression due to an unexpected token. An identifier name or a NOT (!) operator is expected at the start of the expression, or after an OR (,) operator or an AND (+) operator. Also, an expression must not end with an OR (,), AND (+) or NOT (!) operator. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ErrorCategoryStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ErrorCategoryStrings.zh-Hant.resx new file mode 100644 index 00000000000..a127441bfcd --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ErrorCategoryStrings.zh-Hant.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 + + + CloseError: ({1}:{2}) [{0}], {3} + + + Deadlock detected: ({1}:{2}) [{0}], {3} + + + DeviceError: ({1}:{2}) [{0}], {3} + + + InvalidArgument: ({1}:{2}) [{0}], {3}I + + + InvalidData: ({1}:{2}) [{0}], {3} + + + InvalidOperation: ({1}:{2}) [{0}], {3} + + + InvalidResult: ({1}:{2}) [{0}], {3} + + + InvalidType: ({1}:{2}) [{0}], {3} + + + MetadataError: ({1}:{2}) [{0}], {3} + + + NotImplemented: ({1}:{2}) [{0}], {3} + + + NotInstalled: ({1}:{2}) [{0}], {3} + + + ObjectNotFound: ({1}:{2}) [{0}], {3} + + + OpenError: ({1}:{2}) [{0}], {3} + + + OperationStopped: ({1}:{2}) [{0}], {3} + + + OperationTimeout: ({1}:{2}) [{0}], {3} + + + ParserError: ({1}:{2}) [{0}], {3} + + + PermissionDenied: ({1}:{2}) [{0}], {3} + + + ReadError: ({1}:{2}) [{0}], {3} + + + ResourceBusy: ({1}:{2}) [{0}], {3} + + + ResourceExists: ({1}:{2}) [{0}], {3} + + + ResourceUnavailable: ({1}:{2}) [{0}], {3} + + + SyntaxError: ({1}:{2}) [{0}], {3} + + + WriteError: ({1}:{2}) [{0}], {3} + + + FromStdErr: ({1}:{2}) [{0}], {3} + + + SecurityError: ({1}:{2}) [{0}], {3} + + + ProtocolError: ({1}:{2}) [{0}], {3} + + + ConnectionError: ({1}:{2}) [{0}], {3} + + + AuthenticationError: ({1}:{2}) [{0}], {3} + + + LimitsExceeded: ({1}:{2}) [{0}], {3} + + + QuotaExceeded: ({1}:{2}) [{0}], {3} + + + NotEnabled: ({1}:{2}) [{0}], {3} + + + NotSpecified: ({1}:{2}) [{0}], {3} + + + Unrecognized error category {4}: ({1}:{2}) [{0}], {3} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ErrorPackage.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ErrorPackage.zh-Hant.resx new file mode 100644 index 00000000000..9f151c67afa --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ErrorPackage.zh-Hant.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 + + + {0}…{1} + + + 錯誤 "{0}" 的錯誤文字為空白: "{1}" + + + 物件 "{0}" 已回報為錯誤。 + + + 值 {0} 不支援 ActionPreference 變數。提供的值只能用作喜好設定參數的值,並已由預設值取代。如需詳細資訊,請參閱 "about_Preference_Variables" 說明主題。 + + + 已保留 {0} ActionPreference 值供未來使用,所以目前不支援。如需喜好設定變數的詳細資訊,請參閱 "about_Preference_Variables" 說明主題。 + + + 已保留 {0} ActionPreference 值供未來使用,所以目前不支援。{1} 變數中的值已由 {2} 的預設值取代。如需喜好設定變數的詳細資訊,請參閱 "about_Preference_Variables" 說明主題。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/EtwLoggingStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/EtwLoggingStrings.zh-Hant.resx new file mode 100644 index 00000000000..b23d52ed3f5 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/EtwLoggingStrings.zh-Hant.resx @@ -0,0 +1,225 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 命令 {0} 已 {1}。 + + + 引擎狀態已從 {0} 變更為 {1}。 + + + 完整限定錯誤識別碼 = {0} + + + 錯誤訊息 = {0} + + + 建議的動作 = {0} + + + 執行原則 + + + 作業命令 = {0} + + + 工作識別碼 = {0} + + + 工作執行個體識別碼 = {0} + + + 工作位置 = {0} + + + 作業名稱 = {0} + + + 作業狀態 = {0} + + + 命令名稱 = + + + 命令路徑 = + + + 命令類型 = + + + 引擎版本 = + + + 主機識別碼 = + + + 主機名稱 = + + + 主應用程式 = + + + 主機版本 = + + + 管線識別碼 = + + + Runspace 識別碼 = + + + 指令碼名稱 = + + + 序號 = + + + 嚴重性 = + + + 殼層識別碼 = + + + 時間 = + + + 使用者 = + + + 已連線的使用者 = + + + NULL 作業 + + + 提供者名稱 + + + 提供者 {0} 狀態已變更為 {1}。 + + + 指令碼執行為 {0}。 + + + 變數 {0} 已從 {1} 變更為 {2}。 + + + 變數 {0} 已變更為 {1}。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/EventResource.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/EventResource.zh-Hant.resx new file mode 100644 index 00000000000..9247e9dc17a --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/EventResource.zh-Hant.resx @@ -0,0 +1,924 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 找不到事件識別碼 PowerShell.Core.Instrumentation.man 的訊息。 + + + 排定工作 {0} 開始於 {1} + + + + 排定工作 {0} 在 {1} 完成,狀態為 {2} + + + + 排定工作例外狀況 {0}: + 訊息: {1} + StackTrace: {2} + InnerException: {3} + + + + 實驗性功能初始化: 忽略組態檔中的實驗性功能 '{0}'。{1} + + + 實驗性功能初始化: 無法讀取組態檔。 + 例外狀況: {0} + 訊息: {1} + StackTrace: {2} + + + + 已載入工作流程外掛程式。 + EndpointName: {0} + 使用者: {1} + HostingMode: {2} + 通訊協定: {3} + 設定: + {4} + + + 工作流程執行已開始。 + WorkflowId: {0} + ManagedNodes: {1} + + + 工作流程狀態已變更。 + WorkflowId: {0} + NewState: {1} + OldState: {2} + + + 已要求關閉的工作流程外掛程式。 + EndpointName: {0} + + + 已重新啟動工作流程工作流程。 + EndpointName: {0} + + + 正在繼續工作流程。 + WorkflowId: {0} + + + 已超過針對端點設定的配額限制。 + EndpointName: {0} + ConfigName: {1} + AllowedValue: {2} + ValueInQuestion: {3} + + + 工作流程已繼續。 + WorkflowId: {0} + + + 已建立工作流程 runspace 集區。 + WorkflowId: {0} + ManagedNode: {1} + + + 活動已排入佇列以供執行。 + WorkflowId: {0} + ActivityName: {1} + + + 活動執行已開始。 + ActivityName: {0} + ActivityTypeName: {1} + + + 正在從 XAML 檔案匯入工作流程。 + WorkflowId: {0} + XamlFile: {1} + + + 工作流程已從 XAML 檔案匯入。 + WorkflowId: {0} + XamlFile: {1} + + + 工作流程無法從 XAML 檔案匯入,因為發生錯誤。 + WorkflowId: {0} + ErrorDescription: {1} + + + 已開始工作流程驗證。 + WorkflowId: {0} + + + 工作流程驗證成功。 + WorkflowId: {0} + + + 工作流程驗證因錯誤而失敗。 + WorkflowId: {0} + + + 已驗證工作流程活動。 + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + 無法驗證工作流程活動。 + WorkflowId: {0} + ActivityDisplayName: {1} + ActivityTypeName: {2} + + + 活動執行已完成。 + WorkflowId: {0} + ActivityName: {1} + FailureDescription: {2} + + + Runspace 可用性已變更。 + RunspaceId: {0} + 可用性: {1} + + + Runspace 狀態已變更。 + RunspaceId: {0} + NewState: {1} + OldState: {2} + + + 已載入工作流程以供執行。 + WorkflowId: {0} + + + 工作流程已卸載。 + WorkflowId: {0} + + + 工作流程執行已取消。 + WorkflowId: {0} + + + 已中止工作流程執行。 + WorkflowId: {0} + + + 已執行工作流程清理作業。 + WorkflowId: {0} + + + 從磁碟載入的保存工作流程。 + WorkflowId: {0} + 路徑: {1} + + + 工作流程資料已從磁盤中刪除。 + WorkflowId: {0} + 路徑: {1} + + + 正在開始移除工作。 + JobId: {0} + + + 工作狀態已變更。 + JobId: {0} + WorkflowId: {1} + NewState: {2} + OldState: {3} + + + 工作錯誤。 + JobId: {0} + WorkflowId: {1} + ErrorDescription: {2} + + + 為工作流程建立的工作 (子系工作)。 + ParentJobId: {0} + ChildJobId: {1} + ChildWorkflowId: {2} + + + 已針對工作流程建立父代工作。 + JobId: {0} + + + 已建立工作流程執行所需的所有工作。 + JobId: {0} + WorkflowId: {1} + + + 已移除工作流程的子系工作。 + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + + + 移除工作時發生錯誤。 + ParentJobId: {0} + ChildJobId: {1} + WorkflowId: {2} + 錯誤:{3} + + + 正在載入工作流程以供執行。 + WorkflowId: {0} + + + 工作流程執行已完成。 + WorkflowId: {0} + + + 正在取消工作流程執行。 + WorkflowId: {0} + + + 正在中止工作流程執行。 + WorkflowId: {0} + 原因: {1} + + + 正在載入工作流程。 + WorkflowId: {0} + + + 已開始強制關閉工作流程。 + WorkflowId: {0} + + + 已完成強制關閉工作流程。 + WorkflowId: {0} + + + 強制關閉工作流程時發生錯誤。 + WorkflowId: {0} + ErrorDescription: {1} + + + 正將工作流程保存至磁碟。 + WorkflowId: {0} + PersistPath: {1} + + + 工作流程保存至磁碟。 + WorkflowId: {0} + + + 活動執行已完成。 + ActivityName: {0} + + + 工作流程執行錯誤。 + WorkflowId: {0} + ErrorDescription: {1} + + + 已註冊新的 PowerShell 端點。 + EndpointName: {0} + EndpointType: {1} + RegisteredBy: {2} + + + 已修改端點設定。 + EndpointName: {0} + ModifiedBy: {1} + + + 端點設定已取消註冊。 + EndpointName: {0} + UnregisteredBy: {1} + + + 端點設定已停用。 + EndpointName: {0} + DisabledBy: {1} + + + 已啟用端點設定。 + EndpointName: {0} + EnabledBy: {1} + + + 外部處理序 runspace 已開始。 + 命令: {0} + + + 在工作流程執行期間已執行參數展開。 + 參數: {0} + 電腦: {1} + + + 工作流程引擎已啟動。 + EndpointName: {0} + + + 已使用具有現化工作流程管理員 + CheckpointPath: {0} + ConfigProviderId: {1} + UserName: {2} + 路徑: {3} + + + 電腦名稱 $null 或 . 解析為 LocalHost + + + 正在解析為預設配置 http + + + 遠端殼層名稱已解析為預設 PowerShellCore + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + 正在建立 Scriptblock 文字 ({1} 的 {0}): +{2} + +ScriptBlock ID: {3} +路徑: {4} + + + 已開始 ScriptBlock 識別碼的引動過程: {0} +Runspace ID: {1} + + + 已完成 ScriptBlock 識別碼的引動過程: {0} +Runspace ID: {1} + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + {2} + +內容: +{0} + +使用者資料: +{1} + + + + 正在關聯活動的識別碼。 + CurrentActivityId: {0} + ParentActivityId: {1} + + + 類別名稱 = {0} +方法名稱 = {1} +工作流程 GUID = {2} +訊息 = {3} +{4} +活動名稱 = {5} +活動 GUID = {6} +參數 = {7} + + + 正在建立 Runspace 物件 + 執行個體識別碼: {0} + + + 正在建立 RunspacePool 物件 + InstanceId {0} + MinRunspaces {1} + MaxRunspaces {2} + + + 正在開啟 RunspacePool + + + 修改活動識別碼和關聯 + + + Runspace 狀態已變更為 {0} + + + 正在針對工作階段識別碼 {2} 上的錯誤碼 {1} 嘗試工作階段建立重試 {0} + + + PowerShell 已在 AppDomain: {1} 中處理序: {0} 上開始 IPC 接聽執行緒。 + + + PowerShell 已在 AppDomain: {1} 中處理序: {0} 上結束 IPC 接聽執行緒。 + + + AppDomain: {1} 中處理序: {0} 上的 PowerShell IPC 接聽執行緒發生錯誤。 錯誤訊息: {2}。 + + + 使用者: {2} 在 AppDomain: {1} 中的處理序: {0} 上 PowerShell IPC 連線。 + + + 使用者: {2} 在 AppDomain: {1} 中的處理序: {0} 上 PowerShell IPC 中斷連線。 + + + 連接埠已解析為 {0} + + + AppName 已解析為 {0} + + + ComputerName 已解析為 {0} + + + 配置為 {0} + + + 測試分析訊息 + + + 連線參數為 + 連線 URI: {0} + 資源 URI: {1} + 使用者: {2} + OpenTimeout: {3} + IdleTimeout: {4} + CancelTimeout: {5} + AuthenticationMechanism: {6} + Thumb Print: {7} + MaxUriRedirectionCount: {8} + MaxReceivedDataSizePerCommand: {0}0 + MaxReceivedObjectSize: {0}1 + + + 修改活動識別碼和關聯 + + + 收到的物件具有 Runspace 識別碼: {0} 命令識別碼: {1} 目的地: {2} DataType: {3} TargetInterface: {4} + + + appdomain 中發生未處理的例外狀況。 +例外狀況類型: {0} +例外狀況訊息: {1} +例外狀況 StackTrace: {2} + + + Runspace 識別碼: {0} 管線識別碼: {1}。WSMan 回報錯誤,錯誤碼為: {2}。 + 錯誤訊息: {3} + StackTrace: {4} + + + appdomain 中發生未處理的例外狀況。 +例外狀況類型: {0} +例外狀況訊息: {1} +例外狀況 StackTrace: {2} + + + Runspace 識別碼: {0} 管線識別碼: {1}。WSMan 回報錯誤,錯誤碼為: {2}。 + 錯誤訊息: {3} + StackTrace: {4} + + + Runspace 識別碼 {0}。正在使用 WSMan 建立殼層來建立連線 + + + Runspace 識別碼 {0}。收到 WSMan 建立殼層的回撥 + + + Runspace 識別碼: {0}。使用 WSManCloseShell 關閉殼層 + + + Runspace 識別碼: {0}。收到 WSManCloseShell 的回撥 + + + Runspace 識別碼: {0} 管線識別碼: {1}。正在傳送大小為 {2} 的資料 + + + Runspace 識別碼: {0} 管線識別碼: {1}。收到 WSManSendShellInputEx 的回撥 + + + Runspace 識別碼: {0} 管線識別碼: {1}。正在使用 WSManReceiveShellOutputEx 提出接收要求 + + + Runspace 識別碼: {0} 管線識別碼: {1}。收到大小為 {2} 的資料。 + + + Runspace 識別碼 {0} 管線識別碼 {1}。正在使用 WSManRunShellCommandEx 建立命令連線 + + + Runspace 識別碼 {0} 管線識別碼 {1}。收到命令連線的回撥 + + + Runspace 識別碼: {0} 管線識別碼 {1}。正在關閉命令的傳輸 + + + Runspace 識別碼: {0} 管線識別碼 {1}。收到命令關閉的回撥 + + + Runspace 識別碼: {0} 管線識別碼 {1}。正在使用 WSManSignalShellEx 傳送代碼為 {2} 的訊號 + + + Runspace 識別碼: {0} 管線識別碼 {1}。收到 WSManSignalShellEx 的回撥 + + + Runspace 識別碼: {0}。連線正重新導向至 Uri: {1} + + + Runspace 識別碼: {0} 管線識別碼: {1}。服務器正在將大小為 {2} 的資料傳送至用戶端。資料類型: {3} TargetInterface: {4} + + + 要求 {0}。正在建立伺服器遠端工作階段。UserName: {1} 自訂殼層識別碼: {2} + + + 正在報告要求的內容: {0} 回報的內容: {0} + + + 正在報告要求的作業完成: {0} + 錯誤碼: {1} + 錯誤訊息: {2} + StackTrace: {3} + + + 殼層內容 {0}。要求識別碼 {1}。正在建立可供執行命令的命令工作階段。 + + + 殼層內容 {0} 命令內容 {1} 要求識別碼 {2}。正在停止命令。 + + + 殼層內容 {0} 命令內容 {1} 要求識別碼 {2}。從用戶端接收資料。 + + + 殼層內容 {0} 命令內容 {1} 要求識別碼 {2}。客戶端傳送了接收要求,以便伺服器傳送資料。 + + + 殼層內容 {0} 命令內容 {1} IsReceiveOperation {2}。取得關閉作業要求。 + + + 正在為殼層識別碼為 {1} 的自訂殼層載入組件 {0} + + + 正在為殼層識別碼為 {1} 的自訂殼層載入類型 {0} + + + 收到元端片段。 + 物件識別碼: {0} + 片段識別碼: {1} + 開始旗標: {2} + 結束旗標: {3} + 承載長度: {4} + 承載資料: {5} + + + 正在傳送遠端片段。 + 物件識別碼: {0} + 片段識別碼: {1} + 開始旗標: {2} + 結束旗標: {3} + 承載長度: {4} + 承載資料: {5} + + + 正在關閉 winrm 服務。 + + + 已成功將物件解除凍結。 + 已將類型名稱還原序列化: {0} + 藉由轉換類型解除凍結: {1} + 解除凍結的物件類型: {2} + + + 無法將物件解除凍結。 + 已將類型名稱還原序列化: {0} + 藉由轉換類型解除凍結: {1} + 類型轉換例外狀況: {2} + 類型轉換內部例外狀況: {3} + + + 已覆寫序列化深度。 + 序列化的類型名稱: {0} + 原始深度: {1} + 覆寫的深度: {2} + 目前深度低於最上層: {3} + + + 已覆寫序列化模式。 + 序列化的類型名稱: {0} + 覆寫的模式: {1} + + + 已略過指令碼屬性的序列化,因為沒有 runspace 可用於評估屬性。 + 屬性名稱: {0} + 屬性擁有者的類型名稱: {1} + Getter 指令碼: {2} + + + 已略過屬性的序列化,因為屬性 getter 失敗。 + 屬性名稱: {0} + 屬性擁有者的類型名稱: {1} + 屬性 getter 的例外狀況: {2} + 屬性 getter 的內部例外狀況: {3} + + + 可列舉物件的序列化可能未完成,因為正在列舉的物件擲回例外狀況。 + 正在列舉的物件類型: {0} + 例外狀況: {1} + + + 序列化呼叫的物件 ToString 方法失敗。 + 物件類型: {0} + 例外狀況: {1} + + + 已達到低於最上層的最大深度,強制將物件序列化為字串。 + 最大深度的物件類型: {0} + 最大深度的屬性名稱: {1} + 深度: {2} + + + 還原序列化程式已擲回 XmlException (最可能表示 clixml 格式不正確)。 + 行號: {0} 行位置: {1} + 例外: {2} + + + 指定屬性的序列化失敗,因為遺漏其中一個指定的屬性。 + 物件類型: {0} + 屬性名稱: {1} + + + PowerShell 主控台正在啟動 + + + PowerShell 主控台已準備進行使用者輸入 + + + {0} + + + 追蹤 ErrorRecord: + 訊息: {0} + CategoryInfo.Category: {1} + CategoryInfo.Reason : {2} + CategoryInfo.TargetName : {3} + FullyQualifiedErrorId: {4} + 例外狀況詳細資料: + 訊息 : {5} + 堆疊追蹤: {6} + InnerException {7} + + + + 例外狀況: + 訊息: {0} + StackTrace: {1} + InnerException : {2} + + + + 追蹤 PSObject + + + 追蹤工作: + 識別碼: {0} + InstanceId: {1} + 名稱: {2} + 位置: {3} + 狀態: {4} + 命令: {5} + + + + 追蹤資訊: + {0} + + + 追蹤資訊: + {0} {1} + + + BEGIN ImportWorkflowCommand::StartWorkflowApplication.正在開始工作流程函式的引動過程。追蹤 Guid {0} + + + END ImportWorkflowCommand::StartWorkflowApplication.正在結束工作流程函式的引動過程。追蹤 Guid {0} + + + BEGIN 在 ImportWorkflowCommand::StartWorkflowApplication 中建立新工作。追蹤 Guid {0} + + + END 在 ImportWorkflowCommand::StartWorkflowApplication 中建立新工作。追蹤 Guid {0} + + + END 在 ImportWorkflowCommand::StartWorkflowApplication 中建立新工作。追蹤 Guid {0} : ContainerParentJob Guid {1} + + + BEGIN JobLogic ContainerParentJob Guid {0} + + + END JobLogic ContainerParentJob Guid {0} + + + BEGIN WorkflowExecution ContainerParentJob Guid {0} + + + END WorkflowExecution ContainerParentJob Guid {0} + + + 具有 Guid {0} 的 WorkflowJob 已新增至具有 Guid {1} 的 ContainerParentJob + + + 具有 Guid {0} 的 ProxyJob 與具有 Guid {1} 的遠端 ContainerParentJob 相關聯 + + + BEGIN 執行具有 Guid {0} 的 ContainerParentJob + + + END 執行具有 Guid {0} 的 ContainerParentJob + + + BEGIN 執行具有 Guid {0} 的 Proxy 工作 + + + END 執行具有 Guid {0} 的 Proxy 工作 + + + BEGIN 具有 Guid {0} 的 Proxy 工作的 StateChanged 事件處理常式 + + + END 具有 Guid {0} 的 Proxy 工作的 StateChanged 事件處理常式 + + + BEGIN 具有 Guid {0} 的 Proxy 子系工作的 StateChanged 事件處理常式 + + + END 具有 Guid {0} 的 Proxy 子系工作的 StateChanged 事件處理常式 + + + BEGIN 正在執行記憶體回收 + + + END 正在執行記憶體回收 + + + 持續性存放區已達到其指定的大小上限 + + + Windows PowerShell ISE 已開始執行指令檔 {0}。 + + + Windows PowerShell ISE 已開始從檔案 {0} 執行使用者選取的指令碼。 + + + Windows PowerShell ISE 正在停止目前的命令。 + + + Windows PowerShell ISE 正在繼續偵錯工具。 + + + Windows PowerShell ISE 正在停止偵錯工具。 + + + Windows PowerShell ISE 正在進入偵錯。 + + + Windows PowerShell ISE 正在越過偵錯。 + + + Windows PowerShell ISE 正在退出偵錯。 + + + Windows PowerShell ISE 正在啟用所有中斷點。 + + + Windows PowerShell ISE 正在停用所有中斷點。 + + + Windows PowerShell ISE 正在移除所有中斷點。 + + + Windows PowerShell ISE 正在檔案 {1} 的行號: {0} 設定中斷點。 + + + Windows PowerShell ISE 正在檔案 {1} 的行號: {0} 上移除中斷點。 + + + Windows PowerShell ISE 正在檔案 {1} 的行號: {0} 上啟用中斷點。 + + + Windows PowerShell ISE 正在檔案 {1} 的行號: {0} 上停用中斷點。 + + + Windows PowerShell ISE 已在檔案 {1} 的行號: {0} 上命中中斷點。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/EventingResources.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/EventingResources.zh-Hant.resx new file mode 100644 index 00000000000..77d63de8874 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/EventingResources.zh-Hant.resx @@ -0,0 +1,141 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}' 的事件不存在。 + + + PowerShell 無法訂閱 Windows RT 事件。 + + + 無法登錄指定的事件。事件來源識別碼 '{0}' 已保留給 PowerShell 引擎。 + + + 遠端執行個體不支援此作業。 + + + 轉送事件時,不支援此動作。 + + + 無法訂閱指定的事件。來源識別碼為 '{0}' 的訂閱者已經存在。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ExperimentalFeatureStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ExperimentalFeatureStrings.zh-Hant.resx new file mode 100644 index 00000000000..76e785d3196 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ExperimentalFeatureStrings.zh-Hant.resx @@ -0,0 +1,67 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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}' 相符的實驗性功能。 + + + 啟用或停用實驗性功能後,須待下次啟動 PowerShell 才會生效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ExtendedTypeSystem.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ExtendedTypeSystem.zh-Hant.resx new file mode 100644 index 00000000000..977149a8dca --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ExtendedTypeSystem.zh-Hant.resx @@ -0,0 +1,406 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 成員 "{0}" 已經存在。 + + + 延伸類型資料檔案中已經有成員 "{0}"。 + + + 成員 "{0}" 不存在。 + + + 例外狀況設定 "{0}": "{1}" + + + 取得 "{0}" 時發生例外狀況: "{1}" + + + 嘗試列舉集合時發生下列例外狀況: “{0}”。 + + + 無法存取 PSObject 之外的成員 "{0}"。 + + + 無法變更從類型設定建立的成員:“{0}”。 + + + 已保留成員名稱 “{0}”。 + + + 無法變更 "{0}"。 + + + 使用 "{1}" 引數: "{2}" 呼叫 “{0}” 時發生例外狀況 + + + 嘗試呼叫 “{0}” 以擷取 “{1}” 類型的物件內容時擲回例外狀況: "{2}" + + + 找不到適用於 "{0}" 的多載且引數計數為 "{1}"。 + + + 對於具 "{1}" 類型參數的 "{0}",找不到合適的泛型方法多載,且引數計數為 "{2}"。 + + + 找到適用於 “{0}” 的多個不明確多載,且引數計數為 “{1}”。 + + + 無法將適用於 “{2}” 的引數 "{0}" (值為 "{1}") 轉換為 "{3}" 類型: "{4}" + + + 無法取得屬性 “{0}” 的存取子。 + + + 無法設定屬性 “{0}” 的存取子。 + + + Setter 方法應為公用、無效、靜態,且具有兩個參數。第一個參數應為 PSObject 類型。如果 getter 方法也可用,則第二個參數為必要,且其類型應該與 getter 方法的傳回類型相同。 + + + Getter 方法應為公用,非無效、靜態,且具有一個 PSObject 類型的參數。 + + + CodeProperty 應該使用 getter 或 setter 方法。 + + + 因為方法格式,無法建立程式碼方法。此方法應為公用、靜態,且具有一個 PSObject 類型的參數。 + + + 名稱為 “{0}” 的別名包含循環。 + + + 無法將 "{1}" 類型的 "{0}" 值轉換為 "{2}" 類型。 + + + 無法將 "{0}" 類型的值轉換為 "{1}" 類型。 + + + 無法將值 "{0}" 轉換為 "{1}" 類型。錯誤: "{2}" + + + 無法將值 “{0}” 轉換為 “{1}” 類型,因為此列舉不允許使用逗號。 + + + 由於列舉值無效,因此無法將值 "{0}" 轉換為 “{1}” 類型。指定下列其中一個列舉值,然後再試一次。可能的列舉值為 “{2}”。 + + + 由於列舉值無效,因此無法將 null 轉換為 “{0}” 類型。指定下列其中一個列舉值,然後再試一次。可能的列舉值為 “{1}”。 + + + 無法將 null 轉換為 "{0}" 類型。 + + + 無法將值轉換為 "{0}" 類型。 錯誤: "{1}" + + + 無法將值轉換為 System.String 類型。 + + + 引數中預期有參考類型。 + + + 無法比較 “{0}”,因為它不是 IComparable。 + + + 無法比較 "{0}" 與 "{1}"。錯誤: "{2}" + + + 無法比較 “{0}” 與 “{1}”,因為物件不是相同的類型或物件 “{0}” 未實作 “{2}“。 + + + 無法將值 “{0}” 轉換為 “{1}”類型,因為找到至少兩個相符項目 ({2}、{3}),而且此列舉只允許一個相符項目。 + + + 無法將值 "{0}" 轉換為 "{1}" 類型。布林值參數只接受布林值和數字,例如 $True、$False、1 或 0。 + + + 無法取得屬性值,因為 “{0}” 是僅限寫入的屬性。 + + + "{0}" 是唯讀屬性。 + + + 無法設定 "{0}",因為只能使用字串做為值來設定 XmlNode 屬性。 + + + 無法設定“{0}”,因為只能設定唯一屬性或唯一非屬性分頁節點。 + + + PSProperty 或 PSMethod 物件無法新增到此集合。 + + + 載入延伸類型資料檔案時發生下列錯誤: {0} + + + 在擷取字串時發生下列例外狀況: “{0}” + + + 類型 “{1}” 的欄位或屬性 “{0}” 只與欄位或屬性 “{2}” 的字母大小寫不同。此類型必須符合通用語言規格 (CLS) 規範。 + + + 擷取類型名稱階層時發生下列例外狀況: "{0}"。 + + + 在擷取成員 "{1}" 時發生下列例外狀況: "{0}" + + + 在擷取成員時發生下列例外狀況: “{0}” + + + 擷取屬性 "{1}" 的讀取狀態時發生下列例外狀況: "{0}" + + + 擷取屬性 "{1}" 的寫入狀態時發生下列例外狀況: "{0}" + + + 擷取屬性 "{1}" 的類型時發生下列例外狀況: "{0}"。 + + + 擷取屬性 "{1}" 的字串表示法時發生下列例外狀況: "{0}" + + + 針對屬性 (Property) "{1}" 擷取屬性 (Attribute) 時發生下列例外狀況: "{0}" + + + 擷取方法 "{1}" 的定義時發生下列例外狀況: “{0}” + + + 擷取方法 "{1}" 的字串表示法時發生下列例外狀況: "{0}" + + + 擷取參數化屬性 "{1}" 的類型時發生下列例外狀況: “{0}” + + + 擷取參數化屬性 "{1}" 的讀取狀態時發生下列例外狀況: “{0}” + + + 擷取參數化屬性 "{1}" 的寫入狀態時發生下列例外狀況: “{0}” + + + 擷取參數化屬性 "{1}" 的定義時發生下列例外狀況: “{0}” + + + 擷取參數化屬性 "{1}" 的字串表示法時發生下列例外狀況: "{0}" + + + 無法為 "{0}" 類型的 PSMemberInfo 物件設定 Value 屬性。 + + + 引數 '{0}' 應為 {1}。使用 {2}。 + + + 引數 '{0}' 不應該是 {1}。請勿使用 {2}。 + + + 找不到屬性 "{0}"。 + + + 無法取得或設定屬性值。"{0}" 引數的類型應為 "{1}" 或 "{2}"。 + + + 無法設定屬性 “{0}”的值,因為物件的類型是 “{1}” 而不是 “{2}”。 + + + 呼叫 “{0}” 時發生例外狀況: “{1}” + + + {0} 不是有效的類別路徑。 + + + {0} 不是有效的路徑。 + + + 配接器無法判斷是否可變更屬性 “{0}”。 + + + 配接器無法判斷是否可取得屬性 “{0}”。 + + + 配接器無法取得屬性 “{0}” 的值。 + + + 配接器無法設定屬性 “{0}” 的值。 + + + 配接器無法取得屬性 “{0}” 的類型。 + + + 配接器無法取得 “{0}” 的類型階層。 + + + 配接器無法取得 “{0}” 的屬性。 + + + 配接器無法取得 “{1}” 的屬性 “{0}”。 + + + "{0}" 傳回了 Null 值。 + + + 找不到 '{1}' 物件的屬性 '{0}'。可設定的屬性為: {2}。 + + + 找不到 '{1}' 物件的屬性 '{0}'。沒有可設定的屬性可用。 + + + 無法建立 "{0}" 類型的物件。{1} + + + 無法叫用靜態方法或存取開放泛型類型 {0} 上的靜態屬性。 指定類型參數,然後重試。 例如,不使用 [System.Collections.Generic.HashSet``1]::CreateSetComparer(),而使用 [System.Collections.Generic.HashSet[int]]::CreateSetComparer()。 + Error message shown when somebody tries to access a property or invoke a static method on an uninstantiated generic type: +PS> [System.Collections.Generic.Comparer``1]::get_Default() + +{0} is a placeholder for a type name (for example: System.Collections.Generic.Comparer`1) + + + 建構屬性 “{1}” 時發生下列例外狀況: "{0}" + + + 值 "{0}" 無法轉換為字串陣列。 + + + 無法將值轉換為 "{0}" 類型。此語言模式只支援核心類型。 + + + 無法轉換為類似 ByRef 的類型 “{0}”。PowerShell 不支援 ByRef 類型。 + + + 無法取得或設定類似 ByRef 類型 “{1}” 的屬性或欄位 “{0}”。PowerShell 不支援 ByRef 類型。 + + + 無法叫用類似 ByRef 傳回類型 "{1}" 的方法 "{0}"。PowerShell 不支援 ByRef 類型。 + + + 無法建立類似 ByRef 類型 “{0}” 的執行個體。PowerShell 不支援 ByRef 類型。 + + + 延伸類型系統雜湊表轉換 + + + ConstrainedLanguage 模式不允許類型從 HashTable 轉換為 '{0}'。 + + + 延伸類型系統雜湊表轉換 + + + ConstrainedLanguage 模式不允許類型從 '{0}' 轉換為 '{1}'。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/FileSystemProviderStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/FileSystemProviderStrings.zh-Hant.resx new file mode 100644 index 00000000000..f386a965f57 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/FileSystemProviderStrings.zh-Hant.resx @@ -0,0 +1,357 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 叫用項目 + + + 項目: {0} + + + 移除檔案 + + + 移除目錄 + + + 複製檔案 + + + 項目: {0} 目的地: {1} + + + 複製目錄 + + + 重新命名檔案 + + + 重新命名目錄 + + + 項目: {0} 目的地: {1} + + + 移動檔案 + + + 移動目錄 + + + 項目: {0} 目的地: {1} + + + 設定屬性檔案 + + + 設定屬性目錄 + + + 項目: {0} 屬性: {1} 值: {2} + + + 清除屬性檔案 + + + 清除屬性目錄 + + + 項目: {0} 屬性: {1} + + + 建立檔案 + + + 建立目錄 + + + 目的地: {0} + + + 清除內容 + + + 項目: {0} + + + 找不到項目 {0}。 + + + 無法移除項目 {0}: {1} + + + 無法還原項目 {0} 上的屬性: {1} + + + 指定路徑 {0} 上的物件不存在。 + + + 目錄 {0} 非空白,因此無法移除。 + + + 此類型不是檔案系統的已知類型。只能指定 "file"、"directory" 或 "symboliclink"。 + + + 無法處理路徑,因為指定的路徑參考 basePath 外的項目。 + + + 指定的磁碟機根目錄 "{0}" 不存在,或不是資料夾。 + + + 具有指定名稱 {0} 的項目已存在。 + + + 一次一個位元組讀取資料流時,無法指定分隔符號。 + + + 無法以項目 {0} 本身覆寫自己。 + + + 無法重新命名指定的目標,因為它代表路徑或裝置名稱。 + + + 屬性 {0} 不存在或找不到。 + + + 您沒有足夠的存取權限可執行此作業,或項目為隱藏、系統或唯讀。 + + + 無法設定屬性,因為不支援屬性。只能設定下列屬性: 封存、隱藏、一般、唯讀或系統。 + + + 無法清除屬性,因為不支援該屬性。只能清除 Attributes 屬性。 + + + 無法處理路徑 '{0}',因為目標代表保留的裝置名稱。 + + + 指定 '-AsByteStream' 時不使用編碼。 + + + 無法繼續進行位元組編碼。使用位元組編碼時,內容必須是位元組類型。 + + + 無法處理檔案,因為找不到檔案 {0}。 + + + 目錄: + + + 無法偵測檔案的編碼。反向讀取內容時,不支援指定的編碼 {0}。 + + + 無法開啟檔案 '{1}' 的替代資料流 '{0}'。 + + + 檔案 '{1}' 的資料流 '{0}'。 + + + 不能在同一個命令中同時指定 Raw 和 Wait 參數。 + + + 若要使用 Persist 切換參數,磁碟機名稱必須是作業系統支援的名稱 (例如,磁碟機代號 A-Z)。 + + + 使用 Persist 參數時,根目錄必須是遠端電腦上的檔案系統位置。 + + + 不能在同一個命令中同時指定 '{0}' 和 '{1}' 參數。 + + + 作業需要目錄。項目 '{0}' 不是目錄。 + + + 建立連接點 + + + 建立符號連結 + + + 此作業需要系統管理員權限。 + + + 建立硬式連結 + + + 作業需要檔案。項目 '{0}' 不是檔案。 + + + 指定的路徑不支援硬式連結。 + + + 指定的路徑不支援符號連結。 + + + 正在將 {0} 複製到 {1} + + + 目的地路徑 {0} 是目標位置中已存在的檔案。 + + + 無法將檔案 {0} 複製到遠端目標。 + + + 從 {0} 到 {1} + + + 無法將目錄 '{0}' 複製到檔案 '{0}' + + + 無法取得目錄 {0} 的子項目。 + + + 無法讀取遠端檔案 '{0}'。 + + + 無法驗證遠端目的地 {0} 是否為檔案。 + + + 無法在遠端目的地建立目錄 '{0}'。 + + + 磁碟機已超過大小上限: {0}。 + + + 無法建立連結,因為路徑已存在: {0}。 + + + 跳過已瀏覽的目錄 {0}。 + + + 目的地路徑不能是來源的子目錄或來源本身: {0}。 + + + 目標和路徑不能相同。 + + + 已複製 {0}/{1} 個檔案 + + + {0}/{1} ({2:0.0} MB/秒) + + + 已移除 {0}/{1} 個檔案 + + + {0}/{1} ({2:0.0} MB/秒) + + + 建立接合需要目標的絕對路徑。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/FormatAndOutXmlLoadingStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/FormatAndOutXmlLoadingStrings.zh-Hant.resx new file mode 100644 index 00000000000..810a885f910 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/FormatAndOutXmlLoadingStrings.zh-Hant.resx @@ -0,0 +1,324 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: XML 元素 {2} 不允許屬性。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 節點 {2} 不能有子物件。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 無效。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須至少有一個預設 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 不能有超過一個預設 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 控制項名稱不可為 null 或空白。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 超出範圍檢視只能有 CustomControl 或 ListControl。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 超出範圍檢視不能有 GroupBy。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 無法載入檢視。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: "{2}" 不是有效的對齊值。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須是正整數。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 資料行標頭定義無效; 已捨棄所有標頭。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 替代集 #{3} 上的資料列項目計數 = {2} 與預設資料列項目計數 = {4}不符。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 標頭項目計數 = {2} 與預設資料列項目計數 = {3}不符。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 至少必須指定一個清單檢視項目。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 屬性項目無效。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 遺漏定義清單。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須是布林值。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須是非負數。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須是整數。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 遺漏內部文字值。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 自訂控制項權杖清單不可為空白。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 無法載入 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須有運算式,才能指定 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 有運算式時無法指定 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 遺漏格式字串。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 遺漏指令碼區塊文字。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 遺漏屬性。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 指令碼區塊 "{2}" 無效。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 在組件 {4} 中找不到資源 {3} 的字串 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 在組件 {3} 中找不到資源 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 找不到組件 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 節點必須是 XmlElement。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 必須是運算式。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 沒有運算式時,不能有控制項或標籤。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 不能同時有控制項和標籤。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 不能同時有 SelectionSetName 和 TypeName。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 未指定要套用檢視的類型或條件。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 值無效。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 有重複的節點。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 和 {3} 互斥。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2}、{3} 和 {4} 互斥。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 是未知節點。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 是未知屬性。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 是遺漏屬性。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: 遺漏節點 {2}。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 中遺漏節點。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 是空白節點。 + + + 檔案 {1} 中的 XPath {0} 發生錯誤: {2} 是空白屬性。 + + + 檔案 {0} 中發生錯誤: {1} + + + 檔案 {0} 中的錯誤太多。 + + + 載入格式資料檔案時發生錯誤: {0} + + + (全域組件快取) {0} + + + {0},{1} + + + 路徑 {0} 不完整。請指定完整的格式檔案路徑。 + + + 因為 FormatTable 可能是在 Runspace 之外建立,所以無法更新 FormatTable。 + + + 載入 FormatTable 時發生錯誤。檢視 Errors 屬性的內容,以取得詳細的錯誤訊息。 + + + 格式化資料 "{0}" 時發生錯誤: {1} + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 標頭項目計數 = {2} 與預設資料列項目計數 = {3} 不符。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 格式化資料 "{2}" 無效。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 指令碼區塊 "{2}" 無效。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 無法載入 {2}。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: TableControl 只能包含一個 {2}。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 必須至少有一個預設 {2}。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 必須至少指定一個清單檢視項目。 + + + 位於索引 {1},類型名稱為 {0} 的檢視資料發生錯誤: 不能有一個以上的預設 {2}。 + + + 類型 "{0}" 的格式化資料錯誤太多。 + + + 無法使用一個以上的項目更新共用格式資料表。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_MshParameter.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_MshParameter.zh-Hant.resx new file mode 100644 index 00000000000..3ba5a8593aa --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_MshParameter.zh-Hant.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 + + + 無法將 {0} 轉換為下列其中一種型別 {1}。 + + + 參數值為 null; 預期為下列其中一種型別: {0}。 + + + 重複的機碼 "{0}" 與 "{1}" 衝突。 + + + "{0}" 機碼的型別 {1} 無效; 需要的型別為 {2}。 + + + "{0}" 機碼的型別 {1} 無效; 需要的型別為 {2}。 + + + {0} 機碼不明確; {1} 和 {2} 發生衝突。 + + + 機碼的值不可為 null。 + + + {0} 機碼型別無效。機碼必須是字串。 + + + {0} 機碼沒有值。 + + + 缺少 {0} 的必要項目。 + + + {0} 機碼無效。 + + + 機碼 "{1}" 的值 "{0}" 無效; 有效值為 {2}。 + + + 機碼 "{1}" 的值 "{0}" 應大於 0。 + + + 機碼 "{0}" 不能有空的格式設定字串。 + + + "{0}" 機碼不能有空白字串值。 + + + 不允許空字串值。 + + + "{0}" 機碼的值 "{1}" 中不能有萬用字元。 + + + "{0}" 中不允許萬用字元。 + + + EnumerableExpansion 值無效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_format_xxx.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_format_xxx.zh-Hant.resx new file mode 100644 index 00000000000..4080de87909 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_format_xxx.zh-Hant.resx @@ -0,0 +1,182 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Cmdlet 參數 View 和 Property 無法同時使用。 + + + Cmdlet 參數 AutoSize 和 Column 無法同時使用。 + + + 找不到檢視名稱 {0}。 + + + 找不到檢視名稱 {0},因為它不在 {1} 格式設定中。 + {0} indicates one of the valid formating types such as Table, List, Wide or Custom. + + + 沒有任何現有的 {0} 檢視可供 {1} 物件使用。 + + + 找不到檢視名稱 {0}。請指定下列其中一個 {1} 檢視,然後再試一次: {2}。 + + + 請嘗試使用下列其中一個其他格式 Cmdlet: + Prefix text to suggest user to use one of the valid view names. + + + {0}: + + + 下列物件支援 IEnumerable: + + + IEnumerable 不包含任何物件。 + + + IEnumerable 包含下列物件: + + + IEnumerable 包含下列 {0} 個物件: + + + 未知的類別識別碼 {0}。 + + + 屬性 {1} 的類型 {0} 無效。 + + + {0} 資料成員的值不能是 Null。 + + + 無法辨識物件類型。 + + + 無法使用類別識別碼 {0} 建立物件。 + + + {0} 屬性為遞迴。 + + + 無法評估運算式 "{0}"。 + + + 無法剖析格式字串 "{0}"。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_out_xxx.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_out_xxx.zh-Hant.resx new file mode 100644 index 00000000000..7618cae398f --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/FormatAndOut_out_xxx.zh-Hant.resx @@ -0,0 +1,138 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + <SPACE> 下一頁; <CR> 下一行; Q 結束 + + + LineOutput 的值不應為 null。 + + + lineOutput 類型 {0} 不符合預期; LineOutput 需要類型 {1}。 + + + 類型 "{0}" 的物件無效或順序不正確。這很可能是因為使用者指定的 "{1}" 命令與預設格式發生衝突。 + + + 無法開啟檔案 "{0}"。 + + + 輸出至檔案 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/GetErrorText.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/GetErrorText.zh-Hant.resx new file mode 100644 index 00000000000..a4acd582337 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/GetErrorText.zh-Hant.resx @@ -0,0 +1,147 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 load a resource with base name "{0}". + + + Cannot load a resource string with ID "{0}". + + + Running commands is prevented by Stop policy settings. + + + Cannot retrieve the message "{0}" "{1}" "{2}" because an assembly was not registered. + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string format is not valid in template string "{3}". + + + Cannot retrieve the message "{0}" "{1}" "{2}". A template string exists, but its value is empty or blank. + + + The pipeline has been stopped. + + + The script failed due to call depth overflow. + + + The pipeline failed due to call depth overflow. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/HelpDisplayStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/HelpDisplayStrings.zh-Hant.resx new file mode 100644 index 00000000000..298478ccd73 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/HelpDisplayStrings.zh-Hant.resx @@ -0,0 +1,473 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 名稱 + + + SYNOPSIS + + + DESCRIPTION + + + SYNTAX + + + PARAMETERS + + + INPUTS + + + OUTPUTS + + + TERMINATING ERRORS + + + NON-TERMINATING ERRORS + + + NOTES + + + EXAMPLES + + + 範例 + + + EXAMPLE + + + OUTPUT + + + RELATED LINKS + + + SHORT DESCRIPTION + + + Title: + + + Question: + + + 答案 + + + Term: + + + Definition: + + + Content: + + + PROVIDER NAME + + + This cmdlet supports the common parameters: Verbose, Debug, + ErrorAction, ErrorVariable, WarningAction, WarningVariable, + OutBuffer, PipelineVariable, and OutVariable. For more information, see + about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). + + + Required? + + + Position? + + + Type: + + + Target Object Type: + + + Default value + + + Accept pipeline input? + + + Accept wildcard characters? + + + (Category: + + + Suggested Action: + + + For more information, type: + + + For technical information, type: + + + To see the examples, type: + + + For online help, type: + + + <CommonParameters> + + + REMARKS + + + true + + + Named + + + DRIVES + + + CAPABILITIES + + + TASKS + + + TASK: + + + FILTERS + + + DYNAMIC PARAMETERS + + + Cmdlets Supported: + + + ALIASES + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + -- To view the Help topic for this cmdlet online, type: "Get-Help {0} -Online" or + go to {1}. + + + + + + Aliases + + + Dynamic? + + + Parameter set name + + + Unable to retrieve the HelpInfo XML file for UI culture {0}. Make sure the HelpInfoUri property in the module manifest is valid or check your network connection and then try the command again. + + + ByPropertyName + + + ByValue + + + FromRemainingArguments + + + The specified culture is not supported: {0}. Specify a culture from the following list: {{{1}}}. + + + Postponing error and trying fallback cultures, will show as error if none of fallbacks are supported: +{0} + + + The ModuleBase directory cannot be found. Verify the directory and try again. + + + The path {0} is not a valid directory. Make sure the directory exists and retry. + + + A Help URI cannot contain more than 10 redirections. Specify a valid Help URI. + + + Updating Help + + + Connecting to Help Content... + + + Downloading Help Content... + + + Installing Help content... + + + Locating Help Content... + + + (All) + + + No PowerShell modules were found that match the following pattern: {0}. Verify the pattern and then try the command again. + + + No PowerShell modules were found that match the specified FullyQualifiedModule {0}. Verify the FullyQualifiedModule value and then try the command again. + + + Help content cannot be found. Make sure the server is available and the help content location is properly defined in the HelpInfo XML. + + + The Update-Help command failed because the specified module does not support updatable help. Use Get-Help -Online or look online for help for the commands in this module. + + + The following parameter must not be null or empty: Module. + + + The following parameter must not be null or empty: Path. + + + Update-Help has completed successfully. + + + Error extracting Help content. + + + Unable to connect to Help content. The server on which Help content is stored might not be available. Verify that the server is available, or wait until the server is back online, and then try the command again. + + + The Help content at the specified location is not valid. Specify a location that contains valid Help Content. + + + The HelpInfo XML is not valid. Specify valid HelpInfo XML. + + + Help content was successfully saved to the following location: {0} + + + The Help content XSD file cannot be found in {0}. Verify that the XSD file exists at the specified location, and then retry the command. + + + Failed to update Help for the module(s) : +'{0}' +{1} + + + Saving Help + + + Help content contains files that are not valid. Only .txt and .xml files are supported. + + + Failed to save Help for the module(s) '{0}' : {1} + + + Failed to save Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be saved using: Save-Help -UICulture en-US. + + + Failed to update Help for the module(s) '{0}' with UI culture(s) {{{1}}} : {2}. +English-US help content is available and can be installed using: Update-Help -UICulture en-US. + + + Your current culture is ({0}), which is not associated with any language, consider changing your system culture or install the English-US help content using: Update-Help -UICulture en-US. + + + false + + + The -Recurse parameter is only available if a source path is specified. + + + The path {0} does not contain a FileSystem provider. Verify that the specified path contains the FileSystem provider, and then retry the command. + + + Searching Help for {0} ... + + + No UI culture was found that matches the following pattern: {0}. Verify the pattern and then try the command again. + + + Help was not saved for the module {0}, because the Save-Help command was run on this computer within the last 24 hours. +To save help again, add the Force parameter to your command. + + + Help was not updated for the module {0}, because the Update-Help command was run on this computer within the last 24 hours. +To update help again, add the Force parameter to your command. + + + The most current Help files are already installed. + + + {0}: {1}. Culture {2} Version {3} + + + Updated {0} + + + The value of the HelpInfoUri key in the module manifest must resolve to a container or root URL on a website where the help files are stored. The HelpInfoUri '{0}' does not resolve to a container. + + + Help content must be in the namespace {0}. + + + Get-Help cannot find the Help files for this cmdlet on this computer. It is displaying only partial help. + -- To download and install Help files for the module that includes this cmdlet, use Update-Help. + + + The most current Help files are already downloaded. + + + Saved {0} + + + The HelpInfoURI {0} does not start with HTTP. + + + The root level element of the help content must be "helpItems". + + + Saving Help for module {0} + + + Updating Help for module {0} + + + Resolving URI: "{0}" + + + Help URI: {0} + + + {0}, Current Version: {1}, Available Version: {2}, UICulture: {3} + + + PROPERTIES + + + METHODS + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/HelpErrors.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/HelpErrors.zh-Hant.resx new file mode 100644 index 00000000000..b816c8af7d2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/HelpErrors.zh-Hant.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Get-Help 在此工作階段的說明檔中找不到 {0}。若要下載更新的說明主題,請輸入 "Update-Help"。若要線上取得說明,請在 TechNet 文件庫中搜尋說明主題,網址為 https://go.microsoft.com/fwlink/?LinkID=107116。 + + + 無法處理說明類別,因為 "{0}" 不是有效的說明類別。 + + + 無法載入說明檔 "{0}"。詳細資料: {1}。 + + + 無法存取說明檔 "{0}",因為目前的使用者沒有該檔案的存取權限。詳細資料: {1}。 + + + 說明檔 "{0}" 不是有效的 XML 文件。詳細資料: {1}。 + + + 載入來自檔案 {1} 的 {0} 說明內容時發生錯誤。詳細資料: {2}。若要下載更新的說明主題,請執行 Update-Help Cmdlet。若要線上取得說明,請在 TechNet 文件庫中搜尋說明主題,網址為 https://go.microsoft.com/fwlink/?LinkID=107116。 + + + 無法載入提供者 "{0}"。詳細資料: {1}。 + + + 無法載入說明檔。載入說明檔案 "{0}" 時發生下列 {1} 個錯誤。 + + + 節點 "{0}" 不能有 "{1}" 作為子節點。節點路徑: {2}。 + + + 節點 "{0}" 最多可以有 {2} 個類型為 "{1}" 的子節點。節點路徑: {3}。 + + + 找不到登錄機碼: "{0}{1}";改用 "{2}" 載入說明檔。 + + + 沒有任何參數符合條件 {0}。 + + + 要求的說明類別不支援 {0}。 + + + 無法顯示此說明主題的線上版本,因為命令程式碼或命令的說明檔中未指定此說明主題的網際網路位址 (URI)。 + + + 指定的 URI {0} 無效。 + + + 啟動瀏覽器以顯示線上說明失敗。沒有可用來開啟 URI {0} 的程式或瀏覽器。 + + + Uri "{0}" 中指定的通訊協定不受支援。僅支援 "{1}" 和 "{2}" 通訊協定。 + + + 找到多個說明主題。使用 -{0} 選項時,只能指定一個說明主題。 + + + 無法從遠端 Runspace 取得說明,因為 Runspace 尚未開啟。 請執行隱含遠端命令以開啟 Runspace,然後再試一次取得說明的命令。 + + + 存取遭到拒絕。此命令無法更新 PowerShell 核心模組或 $pshome\Modules 目錄中的任何模組的說明主題。 +若要更新這些說明主題,請使用「以系統管理員身分執行」命令啟動 PowerShell,然後再次嘗試執行 Update-Help。 + + + 若要使用 {0},請確定您的應用程式使用 'Microsoft.NET.Sdk.WindowsDesktop' 作為專案 SDK,而且對應的組件 'Microsoft.PowerShell.GraphicalHost' 可供使用。({1}) + + + {0} 無法在遠端工作階段中使用。 + + + ForwardHelpTargetName 不能參考函式本身。 + + + 在受限制的工作階段中,無法從網路位置取得說明。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/HistoryStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/HistoryStrings.zh-Hant.resx new file mode 100644 index 00000000000..7dffccf7a49 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/HistoryStrings.zh-Hant.resx @@ -0,0 +1,153 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 identifier {0} is not a valid value for a History identifier. Specify a positive number, and then try again. + + + Cannot locate the history for Id {0}. + + + The count cannot be combined with multiple Ids. + + + Cannot locate the history for command line {0}. + + + Cannot locate most recent history. + + + The Invoke-History cmdlet is called repeatedly, in a loop. + + + Cannot process multiple history commands. You can only run a single command by using Invoke-History. + + + Cannot add history because the input object has a format that is not valid. + + + The identifier {0} is not valid. Specify a positive number, and then try again. + + + This command will clear all the entries from the session history. + + + The count cannot be combined with multiple CommandLine parameters. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/HostInterfaceExceptionsStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/HostInterfaceExceptionsStrings.zh-Hant.resx new file mode 100644 index 00000000000..d0aca61419c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/HostInterfaceExceptionsStrings.zh-Hant.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 + + + 發生類型 "{0}" 的錯誤。 + + + 提示使用者的命令失敗,因為主機程式或命令類型不支援使用者互動。請嘗試使用支援使用者互動的主機程式,例如 PowerShell 主控台,並從不支援使用者互動的命令類型中移除與提示相關的命令。 + + + 提示使用者的命令失敗,因為主機程式或命令類型不支援使用者互動。主機當時正嘗試以以下訊息要求確認: {0} + + + 無法叫用此方法,因為集區已關閉或失敗。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/InternalCommandStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/InternalCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..377a1f19d70 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/InternalCommandStrings.zh-Hant.resx @@ -0,0 +1,193 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched methods. Possible matches include:{1}. + + + Input name "{0}" is ambiguous. It can be resolved to multiple matched members. Possible matches include:{1}. + + + Retrieve the value for key '{0}' + + + Invoke method '{0}' with arguments: {1} + + + Invoke method '{0}' + + + Retrieve the value for property '{0}' + + + InputObject: {0} + + + Cannot operate on a 'null' input object. + + + Input name "{0}" cannot be resolved to a method. + + + Cannot invoke a method in the restricted language mode. + + + The -WhatIf and -Confirm parameters are not supported for script blocks. + + + The '{0}' operation is not allowed in the RestrictedLanguage mode. + + + An operator is required to compare the two specified values. Include a valid operator in the command, and then try the command again. For example, Get-Process | Where-Object -Property Name -eq Idle + + + The input name "{0}" cannot be resolved to a property. + + + The input name "{0}" cannot be resolved to a member. + + + The specified operator requires both the -Property and -Value parameters. Provide values for both parameters, and then try the command again. + + + This method cannot be run on the current thread. It can only be called on the cmdlet thread. + + + A ForEach-Object -Parallel using variable cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + A ForEach-Object -Parallel piped input object cannot be a script block. Passed-in script block variables are not supported with ForEach-Object -Parallel, and can result in undefined behavior. + + + The 'TimeoutSeconds' parameter cannot be used with the 'AsJob' parameter. + + + The following common parameters are not currently supported in the Parallel parameter set: +ErrorAction, WarningAction, InformationAction, PipelineVariable + + + An unexpected error has occurred while processing ForEach-Object -Parallel input. This may mean that some of the piped input did not get processed. Error: {0}. + + + ForEach-Object Cmdlet + + + Method invocation on type '{0}' will not be allowed when run in Constrained Language mode. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/InternalHostStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/InternalHostStrings.zh-Hant.resx new file mode 100644 index 00000000000..e483f8fe9e8 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/InternalHostStrings.zh-Hant.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 + + + EnterNestedPrompt 的呼叫次數少於 ExitNestedPrompt。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/InternalHostUserInterfaceStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/InternalHostUserInterfaceStrings.zh-Hant.resx new file mode 100644 index 00000000000..19396dacc2c --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/InternalHostUserInterfaceStrings.zh-Hant.resx @@ -0,0 +1,223 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + WriteDebug stopped because the value of the DebugPreference variable was 'Stop'. + + + The value {0} is not a supported ActionPreference value. + + + The "{0}" parameter must contain at least one value. + + + &Yes + + + Continue. + + + Yes to &All + + + Continue, and do not ask again whether to continue in this session. + + + &No + + + End the operation with an error. + + + No to A&ll + + + End the operation with an error. Do not request to resume operation for this session. + + + &Suspend + + + Pause the current operation and enter a command prompt. Type "exit" to resume the paused operation. + + + Continue with this operation? + + + (default is "{0}") + + + (default choices are {0}) + + + Choice[{0}]: + + + "{0}" should have at least one element. + + + "{0}" must be a valid index into "{1}". "{2}" is not a valid index. + + + Cannot process the hot key because a question mark ("?") cannot be used as a hot key. + + + VERBOSE: {0} + + + WARNING: {0} + + + DEBUG: {0} + + + The host is not currently transcribing. + + + Command start time: {0} + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +Username: {1} +RunAs User: {2} +Configuration Name: {3} +Machine: {4} ({5}) +Host Application: {6} +Process ID: {7} +{8} +********************** + + + ********************** +PowerShell transcript start +Start time: {0:yyyyMMddHHmmss} +********************** + + + ********************** +PowerShell transcript end +End time: {0:yyyyMMddHHmmss} +********************** + + + File path {0} resolves to a directory. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/Logging.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/Logging.zh-Hant.resx new file mode 100644 index 00000000000..007baaff712 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/Logging.zh-Hant.resx @@ -0,0 +1,300 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + +AdditionalInfo: + Name=[AdditionalInfo_Name1];Value=[AdditionalInfo_Value1] + Name=[AdditionalInfo_Name2];Value=[AdditionalInfo_Value2] + Name=[AdditionalInfo_Name3];Value=[AdditionalInfo_Value3] + + + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + ExceptionClass=[ExceptionClass] + ErrorCategory=[ErrorCategory] + ErrorId=[ErrorId] + ErrorMessage=[ErrorMessage] + + Severity=[Severity] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewEngineState=[NewEngineState] + PreviousEngineState=[PreviousEngineState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + NewCommandState=[NewCommandState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + ProviderName=[ProviderName] + NewProviderState=[NewProviderState] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + VariableName=[VariableName] + NewValue=[NewValue] + PreviousValue=[PreviousValue] + + SequenceNumber=[SequenceNumber] + + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + CommandName=[CommandName] + CommandType=[CommandType] + ScriptName=[ScriptName] + CommandPath=[CommandPath] + CommandLine=[CommandLine] + + + DetailSequence=[DetailSequence] + DetailTotal=[DetailTotal] + + SequenceNumber=[SequenceNumber] + + UserId=[User] + HostName=[HostName] + HostVersion=[HostVersion] + HostId=[HostId] + HostApplication=[HostApplication] + EngineVersion=[EngineVersion] + RunspaceId=[RunspaceId] + PipelineId=[PipelineId] + ScriptName=[ScriptName] + CommandLine=[CommandLine] + + + 未知 + + + 在組態檔中宣告的引擎實驗性功能 '{0}' 未在目前的 PowerShell 中註冊。 + + + 在組態檔中宣告的實驗性功能 '{0}' 無效。 +實驗性功能的名稱應該遵循以下慣例: + 引擎功能名稱: 'PS[FeatureName]' + 模組功能名稱: '[ModuleName].[FeatureName]' + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/Metadata.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/Metadata.zh-Hant.resx new file mode 100644 index 00000000000..c54193b62dd --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/Metadata.zh-Hant.resx @@ -0,0 +1,267 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法初始化 "{0}" 的屬性: "{1}" + + + 無法驗證引數,因為其型別 "{0}" 與參數上限和下限的型別 ({1}) 不同。請確定引數的型別為 {1},然後再試一次命令。 + + + 無法驗證引數 "{0}",因為其值不是大於零。 + + + 無法驗證引數 "{0}",因為其值不是大於或等於零。 + + + 無法驗證引數 "{0}",因為其值不是小於零。 + + + 無法驗證引數 "{0}",因為其值不是小於或等於零。 + + + 無法接受指定的最小範圍 ({0}),因為其型別與指定的最大範圍 ({1}) 不同。請更新該參數的 ValidateRange 屬性。 + + + 無法接受 MaxRange 和 MinRange 參數型別。這兩個參數都必須是實作 IComparable 介面的物件。 + + + 無法接受指定的最大範圍,因為它小於指定的最小範圍。請更新該參數的 ValidateRange 屬性。 + + + {0} 引數大於允許範圍的上限 {1}。請提供小於或等於 {1} 的引數,然後再試一次命令。 + + + {0} 引數小於允許範圍的下限 {1}。請提供大於或等於 {1} 的引數,然後再試一次命令。 + + + 引數 "{0}" 不符合 "{1}" 模式。請提供符合 "{1}" 的引數,然後再試一次命令。 + + + ValidateCount 屬性無法套用至非陣列參數。請從參數移除該屬性,或將參數設為陣列參數。 + + + 參數需要剛好 {0} 個值 - 提供了 {1} 個值。 + + + 參數需要至少 {0} 個值且不超過 {1} 個值 - 提供了 {2} 個值。 + + + 指定的參數引數數目上限少於指定的引數數目下限。請更新參數的 ValidateCount 屬性。 + + + 指定的引數字元長度上限短於指定的引數字元長度下限。請更新參數的 ValidateLength 屬性。 + + + ValidateLength 屬性無法套用至不是 string 或 string[] 的參數。請將參數設為 string 或 string[] 參數。 + + + 引數的字元長度 ({1}) 太短。請指定長度大於或等於 "{0}" 的引數,然後再試一次命令。 + + + 引數的字元長度 ({1}) 太長。請指定長度小於或等於 "{0}" 的引數,然後再試一次命令。 + + + 引數 "{0}" 不屬於 ValidateSet 屬性指定的集合 "{1}"。請提供該集合中的引數,然後再試一次命令。 + + + 有效值產生器傳回 null 值。 + + + "{0}" 在屬性 "{1}" 上失敗 {2} + + + 無法取得或執行命令。已超過此命令的參數集數目上限。 + + + 無法處理引數,因為引數值不是字串。已指定 ArgumentTransformationAttribute 的參數引數值應為字串。 + + + 無法驗證變數,因為值 {1} 不是 {0} 變數的有效值。 + + + 無法新增屬性,因為值為 {1} 的變數 {0} 將不再有效。 + + + 引數為 null。請提供有效的引數值,然後再嘗試執行命令。 + + + 引數具有 null 值,或引數集合中的某個元素包含 null 值。請提供不包含任何 null 值的集合,然後再試一次命令。 + + + 引數為 null 或空白。請提供非 null 且非空白的引數,然後再試一次命令。 + + + 引數為 null、空白,或引數集合中的某個元素包含 null 值。請提供不包含任何 null 值的集合,然後再試一次命令。 + + + 引數為 null、空白,或僅包含空白字元。請提供包含非空白字元的引數,然後再試一次命令。 + + + 引數集合中的某個元素為 null、空白,或僅包含空白字元。請提供不包含任何這些值的集合,然後再試一次命令。 + + + 已為該命令多次定義名稱為 '{0}' 的參數。 + + + 無法指定參數別名,因為已為該命令多次定義名稱為 '{0}' 的別名。 + + + 無法指定參數 '{0}',因為它與參數 '{1}' 的同名參數別名衝突。 + + + 用於值為 "{0}" 之引數的 "{1}" 驗證指令碼未傳回 True 結果。請判斷驗證指令碼失敗的原因,然後再試一次命令。 + + + "{0}" 引數不包含有效的 PowerShell 版本。請提供有效的版本號碼,然後再試一次命令。 + + + 無法驗證引數 '{0}',因為它不是有效的變數名稱。 + + + 作業轉換型別必須衍生自 IAstToScriptBlockConverter。 + + + 路徑引數無效。請提供字串型別的路徑引數。 + + + 路徑引數的磁碟機 {0} 不屬於核准的磁碟機集合: {1}。請提供具有核准磁碟機的路徑引數。 + + + 路徑引數包含無效字元。 + + + 路徑引數沒有根磁碟機。 請提供具有根磁碟機的完整路徑引數。 + + + 參數 '{0}' 的引數值不能為 null 或空字串。 + + + 列舉成員 '{0}' 不是參數 '{1}' 的有效值。請指定下列其中一個成員,然後再試一次: {2}。 + + + 無法處理輸入。引數 "{0}" 不受信任。 + + + ValidateTrustedData 屬性檢查失敗 + + + 參數引數 '{0}' 不受信任,且在限制語言模式下將無法通過 ValidateTrustedData 參數屬性檢查。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/MiniShellErrors.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/MiniShellErrors.zh-Hant.resx new file mode 100644 index 00000000000..b7d2e849e72 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/MiniShellErrors.zh-Hant.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 update is not supported for the runspace configuration category {0}. + + + The following errors occurred when updating the assembly list for the runspace: {0}. + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/Modules.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/Modules.zh-Hant.resx new file mode 100644 index 00000000000..198d85777d7 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/Modules.zh-Hant.resx @@ -0,0 +1,687 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 未載入指定的模組 '{0}',因為在任何模組目錄中都找不到有效的模組檔案。 + + + 未載入版本為 '{0}' 的指定模組 '{1}',因為在任何模組目錄中都找不到有效的模組檔案。 + + + 指定的 MaximumVersion '{0}' 不正確。如果您使用 '*',MaximumVersion 只支援一個 '*',而且一律應放在 MaximumVersion 的結尾。 + + + 未載入 MaximumVersion '{1}' 的指定模組 '{0}',因為在任何模組目錄中都找不到有效的模組檔案。 + + + 未載入具有 MinimumVersion '{1}' 和 MaximumVersion '{2}' 的指定模組 '{0}',因為在任何模組目錄中都找不到有效的模組檔案。 + + + MinimumVersion '{0}' 不應大於 MaximumVersion '{1}'。 + + + 未載入組件 '{0}',因為找不到該名稱的組件。請確認組件名稱,然後再試一次。 + + + 模組資訊清單 '{2}' 的欄位 '{1}' 中列出的待處理模組 '{0}' 未處理,因為在任何模組目錄中都找不到有效的模組。 + + + 沒有傳回模組 '{0}' 的自訂物件,因為 -AsCustomObject 參數只能與指令碼模組搭配使用。 + + + 無法處理模組資訊清單 '{0}',因為它不是有效的 PowerShell 模組資訊清單檔。請移除不允許的元素: {1} + + + 處理模組資訊清單檔 '{0}' 時,未產生有效的資訊清單物件。請更新檔案,使其包含有效的 PowerShell 模組資訊清單。您可以使用 New-ModuleManifest Cmdlet 建立有效的資訊清單。 + + + 無法匯入 '{0}' 模組,因為其資訊清單包含一或多個無效的成員。有效的資訊清單成員為 ({1})。請移除無效的成員 ({2}),然後再次嘗試匯入模組。 + + + 描述模組的雜湊表包含一或多個無效的成員。有效的成員為 ({0})。請移除無效的成員 ({1}),然後再試一次。 + + + 無法載入模組 '{0}',因為已超過模組巢狀限制。模組最多只能巢狀到 {1} 層。請評估並變更載入模組的順序,以避免超過巢狀限制,然後再次嘗試執行您的指令碼。 + + + 模組資訊清單中沒有成員 'ModuleVersion'。此成員必須存在,且值必須是格式為 'n.n.n.n' 的版本號碼。請將遺漏的成員新增至檔案 '{0}'。 + + + 模組資訊清單檔 '{2}' 中的 '{0}' 成員無效: {1} + + + 模組 '{1}' 的版本 '{0}' 不符合所需的最低版本 '{2}'。請確認版本號碼受支援,然後再次嘗試載入模組。 + + + 此電腦上的 PowerShell 版本為 '{0}'。模組 '{1}' 需要至少 PowerShell 版本 '{2}' 才能執行。請確認您已安裝所需的最低版本 PowerShell,然後再試一次。 + + + 如果 'ModuleToProcess' 成員是二進位模組,則無法使用模組資訊清單成員 'NestedModules'。請編輯位於 '{0}' 的模組資訊清單檔,然後再試一次。 + + + 模組資訊清單中的成員 '{0}' 無效: {1}。請確認已在 '{2}' 檔案中為此欄位指定有效值。 + + + 模組資訊清單路徑 '{0}' 無效。Path 引數的值必須解析為副檔名為 '.psd1' 的單一檔案。請將 Path 引數的值變更為指向有效的 psd1 檔案,然後再試一次。 + + + 模組資訊清單 '{0}' 中的 ModuleVersion 索引鍵指定了模組版本 '{1}',但這與 '{2}' 的版本資料夾名稱不符。請變更 ModuleVersion 索引鍵的值,使其與版本資料夾名稱一致。 + + + 模組資訊清單 '{1}' 中指定的 NestedModule 項目 '{0}' 無效。請使用有效值更新此項目,然後再試一次。 + + + 模組資訊清單 '{1}' 中指定的 RequiredAssemblies 項目 '{0}' 無效。請使用有效值更新此項目,然後再試一次。 + + + 模組資訊清單 '{1}' 中指定的 FileList 項目 '{0}' 無效。請使用有效值更新此項目,然後再試一次。 + + + 模組資訊清單 '{1}' 中指定的 RequiredModules 項目 '{0}' 無效。請使用有效值更新此項目,然後再試一次。 + + + 模組資訊清單 '{1}' 中指定的 ModuleList 項目 '{0}' 無效。請使用有效值更新此項目,然後再試一次。 + + + 模組資訊清單 '{0}' 使用了 CompatiblePSEditions 索引鍵,但此索引鍵只支援 PowerShell '5.1' 或更新版本。請將 PowerShellVersion 索引鍵的值更新為 '5.1' 或更新版本,然後再試一次。 + + + CompatiblePSEditions 的指定值 '{0}' 包含重複的 PowerShell 版本名稱。請移除重複的 PowerShell 版本名稱,然後再試一次。 + + + ModuleVersion 索引鍵中指定的版本等於版本資料夾名稱。 + + + 正在略過模組 {1} 下的版本資料夾 {0},因為其中沒有有效的模組資訊清單檔。 + + + 描述此模組的雜湊表中不存在 'ModuleName' 成員。 + + + 描述此模組的雜湊表中沒有 'ModuleVersion'、'MaximumVersion' 和 'RequiredVersion' 成員。這三個成員中必須有一個存在,並以 'n.n.n.n' 格式指派版本號碼。 + + + 未載入必要模組 '{1}'。請載入該模組,或從檔案 '{0}' 中的 'RequiredModules' 移除該模組。 + + + 未載入具有 GUID '{1}' 的必要模組 '{2}'。請載入該模組,或從檔案 '{0}' 中的 'RequiredModules' 移除該模組。 + + + 未載入版本為 '{2}' 的必要模組 '{1}'。請載入該模組,或從檔案 '{0}' 中的 'RequiredModules' 移除該模組。 + + + 未載入具有 MaximumVersion '{2}' 的必要模組 '{1}'。請載入該模組,或從檔案 '{0}' 中的 'RequiredModules' 移除該模組。 + + + 未載入具有 MaximumVersion '{2}' 和 MaximumVersion '{3}' 的必要模組 '{1}'。請載入該模組,或從檔案 '{0}' 中的 'RequiredModules' 移除該模組。 + + + 找不到符合 ModuleVersion '{1}' 的模組 '{0}。 + + + 找不到符合 RequiredVersion '{1}' 的模組 '{0}'。 + + + 找不到符合 MaximumVersion '{1}' 的模組 '{0}'。 + + + 找不到符合 ModuleVersion '{1}' 和 MaximumVersion '{2}' 的模組 '{0}。 + + + 找不到模組 '{0}'。 + + + 未移除任何模組。請確認要移除的模組規格正確,且這些模組存在於 Runspace 中。 + + + 無法移除從模組 '{1}' 匯入的 '{0}' 成員,原因如下: {2} + + + 無法移除模組 '{0}',因為它是唯讀的。若要移除唯讀模組,請在命令中加入 Force 參數。 + + + 無法移除模組 '{0}',因為它標記為 'constant'。標記為 'constant' 的模組無法移除。 + + + 無法移除模組 '{0}',因為 '{1}' 需要它。若要移除該模組,請在命令中加入 Force 參數。 + + + 只能從模組內部呼叫 Export-ModuleMember Cmdlet。 + + + 副檔名 '{0}' 不是有效的模組副檔名。支援的模組副檔名為 '.dll'、'.ps1'、'.psm1'、'.psd1' 和 '.cdxml'。請更正副檔名,然後再次嘗試新增檔案 '{1}'。 + + + 無法在二進位模組上執行此作業。它只能在指令碼模組上執行。 + + + 不允許檔案 '{0}',因為它沒有副檔名 '.ps1'。 + + + 未知 + + + (c) {0}。著作權所有,並保留一切權利。 + + + 正在移除已匯入的 "{0}" 函式。 + + + 正在移除已匯入的 "{0}" 別名。 + + + 正在移除已匯入的 "{0}" 變數。 + + + 正在從路徑 '{0}' 載入模組。 + + + 正在從路徑 '{1}' 載入 '{0}'。 + + + 正在點執行指令檔 '{0}'。 + + + 正在匯入函式 '{0}'。 + + + 正在匯入 Cmdlet '{0}'。 + + + 正在匯入別名 '{0}'。 + + + 正在匯入變數 '{0}'。 + + + 正在匯出 Cmdlet '{0}'。 + + + 正在匯出函式 '{0}'。 + + + 正在匯出別名 '{0}'。 + + + 正在匯出變數 '{0}'。 + + + 某些從模組 '{0}' 匯入的命令名稱包含未核准的動詞,這可能會降低命令的可探索性。若要找出使用未核准動詞的命令,請使用 Verbose 參數再次執行 Import-Module 命令。如需核准動詞的清單,請輸入 Get-Verb。 + + + 已匯入模組 '{1}' 中的 '{0}' 命令,但因為其名稱未包含核准的動詞,可能較難找到。如需核准動詞的清單,請輸入 Get-Verb。 + + + 已匯入模組 '{2}' 中的 '{0}' 命令,但因為其名稱未包含核准的動詞,可能較難找到。建議的替代動詞為 "{1}"。 + + + 某些匯入的命令名稱包含下列一或多個限制字元: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + 模組 '{1}' 中的命令名稱 '{0}' 包含下列一或多個限制字元: # , ( ) {{ }} [ ] & - / \ $ ^ ; : " ' < > | ? @ ` * % + = ~ + + + 正在建立 "{0}" 模組資訊清單檔。 + + + {0} (路徑: '{1}') + + + 目前的處理器結構為: {0}。模組 '{1}' 需要下列結構: {2}。 + + + 目前 PowerShell 主機的名稱為: '{0}'。模組 '{1}' 需要下列 PowerShell 主機: '{2}'。 + + + 目前的 PowerShell 主機為: '{0}'(版本 {1})。模組 '{2}' 需要至少 PowerShell 主機版本 '{3}' 才能執行。 + + + 模組 '{0}' 的模組資訊清單 + + + 產生者: {0} + + + 產生於: {0} + + + 與此資訊清單相關聯的指令碼模組或二進位模組檔案。 + + + 要匯入為 RootModule/ModuleToProcess 中指定模組之巢狀模組的模組 + + + 用於唯一識別此模組的識別碼 + + + 此模組的作者 + + + 此模組的公司或廠商 + + + 此模組的著作權聲明 + + + 此模組的版本號碼。 + + + 此模組所提供功能的描述 + + + 此模組所需的最低 PowerShell 引擎版本 + + + 此模組所需的通用語言執行平台 (CLR) 最低版本。{0} + + + 匯入此模組之前,必須先匯入全域環境的模組 + + + 匯入此模組之前,會在呼叫者環境中執行的指令碼檔案 (.ps1)。 + + + 匯入此模組時要載入的類型檔案 (.ps1xml) + + + 匯入此模組時要載入的格式檔案 (.ps1xml) + + + 匯入此模組前必須載入的組件 + + + 此模組所封裝的所有檔案清單 + + + 要傳遞至 RootModule/ModuleToProcess 中指定模組的私人資料。這也可能包含 PSData 雜湊表,其中含有 PowerShell 使用的其他模組中繼資料。 + + + 套用至此模組的標籤。這些項目有助於在線上資源庫中探索模組。 + + + 此專案主要網站的 URL。 + + + 此模組授權的 URL。 + + + 代表此模組的圖示 URL。 + + + 此模組的 ReleaseNotes + + + 此模組的預先發行版字串 + + + 表示此模組是否需要使用者明確接受才能安裝/更新/儲存的旗標 + + + 此模組的外部相依模組 + + + {0} 雜湊表結尾 + + + PrivateData 參數值必須是雜湊表,才能使用下列參數值建立模組資訊清單: Tags、ProjectUri、LicenseUri、IconUri 或 ReleaseNotes。請移除 Tags、ProjectUri、LicenseUri、IconUri 或 ReleaseNotes 參數值,或將 PrivateData 的內容包裝在雜湊表中。 + + + PrivateData 應定義為雜湊表,但這個模組資訊清單將其定義為物件。請考慮將 PrivateData 的內容包裝在雜湊表中。這樣您之後就能將 Tags、ProjectUri、LicenseUri、IconUri 和 ReleaseNotes 屬性新增到模組資訊清單中。 + + + 指定的值 '{0}' 無效,請使用有效的值再試一次。 + + + 若要從此模組匯出的函式,為了達到最佳效能,請勿使用萬用字元,也不要刪除該項目。如果沒有要匯出的函式,則請使用空陣列。 + + + 若要從此模組匯出的別名,為了達到最佳效能,請勿使用萬用字元,也不要刪除該項目。如果沒有要匯出的別名,則請使用空陣列。 + + + 若要從此模組匯出的 Cmdlet,為了達到最佳效能,請勿使用萬用字元,也不要刪除該項目。如果沒有要匯出的 Cmdlet,則請使用空陣列。 + + + 要從此模組匯出的變數 + + + 要從此模組匯出的 DSC 資源 + + + 支援的 PSEditions + + + 此模組需要的處理器結構為 (None、X86、Amd64) + + + 此模組所封裝的所有模組清單 + + + 此模組所需的最低 Microsoft .NET Framework 版本。{0} + + + 此模組所需的 PowerShell 主機名稱 + + + 此模組所需的最低 PowerShell 主機版本 + + + 此模組的 HelpInfo URI + + + 因為 {0} 模組在目前的 PowerShell 工作階段中提供 PSDrive,所以沒有移除任何模組。請變更目前的 PSDrive 提供者,然後再次嘗試移除模組。 + + + 未匯入 Cmdlet '{0}',因為目前範圍中有成員具有相同名稱。 + + + 未匯入別名 '{0}',因為目前範圍中有成員具有相同名稱。 + + + 未匯入函式 '{0}',因為目前範圍中有成員具有相同名稱。 + + + 未匯入變數 '{0}',因為目前範圍中有成員具有相同名稱。 + + + 模組資訊清單 '{0}' 中的成員 'ModuleToProcess'、'RootModule' 或 'NestedModules' 不允許使用萬用字元。 + + + 模組 '{0}' 是 PowerShell 的核心模組。若要移除核心模組,請在命令中加入 Force 參數。 + + + 模組資訊清單不能同時包含 'ModuleToProcess' 和 'RootModule' 成員。請變更模組資訊清單檔,移除位於 '{0}' 的其中一個成員,然後再試一次。 + + + 模組資訊清單成員 'ModuleToProcess' 已棄用。請改為使用 'RootModule' 成員。 + + + 從此模組匯出之命令的預設前置詞。您可以使用 Import-Module -Prefix 覆寫預設前置詞。 + + + 無法同時指定 'Global' 和 'Scope' 參數。請移除其中一個參數,然後嘗試再次執行該指令。 + + + 未載入必要模組 '{0}'。模組 '{0}' 在其模組資訊清單 '{2}' 中的 requiredModule '{1}' 指向循環相依性。 + + + 未載入必要的模組 '{0}',因為在任何模組目錄中都找不到有效的模組檔案。 + + + 無法透過 CimSession 匯入模組 {0} 中的某些命令。若要取得所有命令,請確認遠端伺服器已啟用 PowerShell 遠端管理,然後嘗試在 Import-Module Cmdlet 中加入 PSSession 參數。 + + + 模組 {1} 已使用 {0} 遠端處理工作階段載入 Windows PowerShell; 請注意,此模組中所有命令的輸入和輸出都會是還原序列化的物件。如果您想將此模組載入 PowerShell,請使用 'Import-Module -SkipEditionCheck' 語法。 + + + 偵測到 Windows PowerShell 版本 {0}。若要使用 Windows PowerShell 相容性功能載入模組,則需要 Windows PowerShell 5.1。請從 https://aka.ms/WMF5Download 安裝 Windows Management Framework (WMF) 5.1 以啟用此功能。 + + + PowerShell 設定檔中的 'WindowsPowerShellCompatibilityModuleDenyList' 設定已封鎖使用 Windows PowerShell 相容性功能載入模組 '{0}'。 + + + 無法透過 CimSession 匯入模組 {0}。請嘗試使用 Import-Module Cmdlet 的 PSSession 參數。 + + + 不支援處理器結構值 {0}。請再次執行 New-ModuleManifest 命令,並指定下列其中一個支援的處理器結構列舉值: None、MSIL、X86、Amd64、Arm + + + 在遠端電腦上執行 Get-Module Cmdlet 只能列出可用的模組。請將 ListAvailable 參數加入您的命令,然後再試一次。 + + + 未匯入 '{0}' 模組,因為已先匯入 '{0}' 嵌入式管理單元。 + + + 模組資訊清單 '{0}' 中的成員 'RequiredAssemblies' 不允許使用萬用字元。 + + + {1} 中 {0} 索引鍵的值為 {2},且模組具有巢狀模組。當 CDXML 檔案是根模組時,Import-Module 命令會失敗,因為無法匯出巢狀模組中的命令。請將 CDXML 檔案移到 NestedModules 索引鍵,然後再次嘗試命令。 + {0} is equal to either ModuleToProcess or RootModule +{1} is a placeholder for a file path to psd1 file +{2} is a placeholder for a file path to cdxml file + + + 遠端命令失敗: {0}: {{0}} + + + 無法為遠端模組 '{0}' 產生 Proxy。{{0}} + + + 無法處理遠端模組 {0}。{1} + + + 無法從遠端 CimSession 接收模組資料。{0} + + + 未載入具有 GUID '{1}' 及版本 '{2}' 的必要模組 '{0}',因為在任何模組目錄中都找不到有效的模組檔案。 + + + 在 CIM 伺服器上找不到用於模組探索的 CIM 提供者。{0} + {0} is a placeholder for a more detailed error message + + + 無法驗證 Microsoft .NET Framework 版本 {0},因為它不在允許的版本清單中。 + + + 正在分析 {0}。 + {0} should not be localized, is used to contain a file path. + + + 正在準備模組以供首次使用。 + + + 正在搜尋可用的模組 + + + 正在搜尋 UNC 共用 {0}。 + {0} should not be localized, is used to contain a file path. + + + 對遠端電腦執行 Get-Module cmdlet 只能用於不包含路徑的模組名稱。Name 參數中的元素 '{0}' 會解析為路徑。請更新 Name 參數,移除路徑元素,然後再試一次。 + + + 對於包含路徑的模組名稱,不支援在未使用 ListAvailable 參數的情況下執行 Get-Module Cmdlet。Name 參數中的元素 '{0}' 會解析為路徑。請更新 Name 參數,移除路徑元素,然後再試一次。 + + + 找不到指定的模組 '{0}'。請更新 Name 參數,使其指向有效路徑,然後再試一次。 + + + 正在填入模組 {0} 的 RepositorySourceLocation 屬性。 + + + 未處理模組資訊清單 '{0}' 的欄位 '{1}' 中列出的要處理模組 '{2}'。 {3} + + + 此必要條件僅適用於 PowerShell Desktop 版本。 + + + 模組 '{0}' 不支援目前的 PowerShell 版本 '{1}'。其支援的版本為 '{2}'。請使用 'Import-Module -SkipEditionCheck' 忽略此模組的相容性。 + + + 模組 '{0}' 支援 PowerShell 版本 '{1}',因為設定檔已停用 Windows 相容性功能,所以無法隱含載入。請使用 'Import-Module -UseWindowsPowerShell' 以 Windows PowerShell 載入此模組,或使用 'Import-Module -SkipEditionCheck' 嘗試以目前的 PowerShell 載入此模組。 + + + 應為模組資訊清單中宣告的實驗性功能指定非空白字串值。 + + + 找到一或多個無效的實驗性功能名稱: {0}。模組實驗性功能名稱應遵循此慣例: 'ModuleName.FeatureName'。 + + + 必須搭配 -ListAvailable 切換參數,才能使用 -SkipEditionCheck 切換參數。 + + + 在 ConstrainedLanguage 模式中,不允許將 *.ps1 檔案匯入為模組。 + + + 載入指令碼模組 {0} 時發生錯誤,因為其語言模式與模組資訊清單不同。資訊清單語言模式為 {1},而模組語言模式為 {2}。請確定所有模組檔案都已簽署,或已納入應用程式允許清單設定中。 + + + 此模組在使用萬用字元匯出函式時,會使用 dot-source 運算子,而在系統啟用應用程式驗證強制執行時,這是不允許的。 + + + 無法從語言模式與執行中工作階段不同的模組匯出模組成員。 + + + 當工作階段處於 ConstrainedLanguage 模式時,無法建立新模組。 + + + 找不到與 'Core' 版本相容的內建模組 '{0}'。請確認 PowerShell 內建模組可供使用。它們通常隨 PowerShell 套件一起提供,位於 $PSHOME 模組路徑下,而且是 PowerShell 正常運作所需。 + + + Export-ModuleMember Cmdlet + + + 在限制語言模式中匯出模組成員將會失敗,因為模組 '{0}' 的語言模式 '{1}' 與目前的工作階段 '{2}' 的語言模式不同。 + + + 模組隱含函式匯出 + + + 模組 '{0}' 的隱含函式匯出將會遭到拒絕,因為它是受信任的 (以完整語言模式執行),但工作階段不是受信任的 (以限制語言模式執行)。最佳做法是一律以完整名稱個別匯出模組函式。 + + + 正在將指令檔匯入為模組 + + + 在 ConstrainedLanguage 模式中,不允許將指令碼檔案 '{0}' 匯入為模組。 + + + 模組包含 Dot-Source 運算子 + + + 模組 '{0}' 的匯入在限制語言模式中將會失敗,因為它使用萬用字元匯出函式,同時也使用 dot-source 運算子。 + + + "模組匯出函式 + + + 模組 '{0}' 使用名稱萬用字元匯出函式。在限制語言模式下執行時,任何巢狀模組函式名稱都會移除。 + + + "New-Module Cmdlet + + + 來自未受信任的限制語言工作階段的新模組,將無法提供 FullLanguage 指令碼區塊。 + + + "模組語言模式不相符 + + + 正在載入的相依模組與父模組的語言模式不同。在限制語言模式中將不允許此動作。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/MshHostRawUserInterfaceStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/MshHostRawUserInterfaceStrings.zh-Hant.resx new file mode 100644 index 00000000000..601435e296b --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/MshHostRawUserInterfaceStrings.zh-Hant.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}。 + + + "{0}" 必須是正數。 + + + 所有字串都為 null 或空字串。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/MshSignature.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/MshSignature.zh-Hant.resx new file mode 100644 index 00000000000..e589f82687a --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/MshSignature.zh-Hant.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 + + + 已驗證簽章。 + + + 檔案 {0} 並未數位簽章。您無法在目前的系統上執行此指令碼。如需執行指令碼和設定執行原則的相關資訊,請參閱 about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170 + + + 檔案 {0} 的內容可能已被未經授權的使用者或處理序變更,因為檔案的雜湊與數位簽章中儲存的雜湊不相符。此指令碼無法在指定的系統上執行。如需詳細資訊,請執行 Get-Help about_Signing。 + + + 已簽署檔案 {0},但此系統不信任簽署者。 + + + 無法簽署檔案,因為系統不支援對 {0} 檔案執行簽署作業。 + + + 無法簽署檔案,因為系統不支援在沒有副檔名的檔案上執行簽署作業。 + + + 無法驗證簽章,因為它與目前系統不相容。 + + + 無法驗證簽章,因為它與目前系統不相容。雜湊演算法無效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/MshSnapInCmdletResources.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/MshSnapInCmdletResources.zh-Hant.resx new file mode 100644 index 00000000000..2f934767c34 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/MshSnapInCmdletResources.zh-Hant.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 + + + 無法執行作業。指定的 Cmdlet 不支援自訂殼層。 + + + 找不到符合模式 '{0}' 的 PowerShell 嵌入式管理單元。請檢查模式,然後再試一次命令。 + + + 指定的嵌入式管理單元名稱格式無效。 PowerShell 嵌入式管理單元名稱只能包含英數字元、連字號、底線和句點。請更正名稱,然後再次嘗試操作。 + + + 無法新增 PowerShell 嵌入式管理單元 {0} ,因為它是系統 PowerShell 模組。請使用 Import-Module 載入該模組。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/MshSnapinInfo.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/MshSnapinInfo.zh-Hant.resx new file mode 100644 index 00000000000..87751f6ddc0 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/MshSnapinInfo.zh-Hant.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 + + + 無法存取 PowerShell 登錄資訊。 + + + 無法存取 PowerShell 引擎登錄資訊。 + + + 無法存取 PublicKeyToken 資訊。 + + + 這部電腦上沒有版本 {0} 的 PowerShell。 + + + 這部電腦上未安裝 PowerShell 嵌入式管理單元 '{0}'。 + + + 未為登錄機碼 {1} 指定強制值 {0}。 + + + 強制值 {0} 不是登錄機碼 {1} 的正確格式。 預期格式為 'string'。 + + + 強制值 {0} 不是登錄機碼 {1} 的正確格式。 預期格式為 'multistring'。 + + + 在登錄中找不到必要資訊,或缺少機碼檔案。 無法載入某些 Cmdlet。 + + + 尚未為 PowerShell 版本 {0} 註冊任何嵌入式管理單元。 + + + 無法擷取字串資源,因為讀取器已經處置。 + + + 登錄機碼 {1} 的版本值 {0} 未指定或不正確。 + + + 找不到 PowerShell 類型 {0} 的 [PSVersion] 屬性。請使用 [PSVersion(PowerShell SnapinBase.PSEngineVersion)] 將 PSVersion 屬性新增至該類型。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/NativeCP.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/NativeCP.zh-Hant.resx new file mode 100644 index 00000000000..ab752b680a1 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/NativeCP.zh-Hant.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 + + + ScriptBlock 只能指定為 Command 參數的值。 + + + Command 參數沒有指定值。 + + + 為 {7} 參數指定的值無效 ({6})。有效值為 Text 和 Xml。 + + + 未指定 InputFormat 參數的值。有效值為 Text 和 Xml。 + + + 未指定 OutputFormat 參數的值。有效值為 text 和 XML。 + + + {6} 參數需要字串值。 + + + Args 參數沒有指定值。 + + + 已指定 {6} 參數。 + + + 無法處理 '{1}' 的 '{0}' 資料流中的 XML: {2} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PSCommandStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PSCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..59ad72f6961 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PSCommandStrings.zh-Hant.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 + + + 需要命令才能新增參數。新增參數之前,必須先將命令新增至 {0}。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PSConfigurationStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PSConfigurationStrings.zh-Hant.resx new file mode 100644 index 00000000000..3cc5246e898 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PSConfigurationStrings.zh-Hant.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 + + + PowerShell 已因安全性問題而停止運作: 無法讀取設定檔: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PSDataBufferStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PSDataBufferStrings.zh-Hant.resx new file mode 100644 index 00000000000..cbeb5aa4cf8 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PSDataBufferStrings.zh-Hant.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 + + + 指定的索引小於零或大於緩衝區中的項目數。索引應在範圍 {0}-{1} 內。 + + + 無法將 null 參考轉換成實值型別。 + + + 無法將值從型別 {0} 轉換為型別 {1}。 + + + 無法將物件新增至已關閉的緩衝區。請確定緩衝區已開啟,才能成功執行 Add 和 Insert 作業。 + + + 只有 PSDataCollection 的 PSObject 型別可以設定 SerializeInput 屬性。請將 SerializeInput 屬性設為 false,或將集合型別變更為 PSObject。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PSListModifierStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PSListModifierStrings.zh-Hant.resx new file mode 100644 index 00000000000..091f331e204 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PSListModifierStrings.zh-Hant.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 + + + 偵測到下列未知的清單修飾元: '{0}'。有效的清單修飾元為 Add、Remove 和 Replace。 + + + 無法套用此更新,因為該物件不是支援的集合類型。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PSStyleStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PSStyleStrings.zh-Hant.resx new file mode 100644 index 00000000000..de5598c5894 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PSStyleStrings.zh-Hant.resx @@ -0,0 +1,70 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 指定的字串包含可列印的內容,但它應該只包含 ANSI 逸出序列: {0} + + + Progress 呈現的 MaxWidth 必須至少為 18,才能正確呈現。 + + + 新增或移除副檔名時,副檔名必須以句點開頭。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ParameterBinderStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ParameterBinderStrings.zh-Hant.resx new file mode 100644 index 00000000000..0aaf9b920c3 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ParameterBinderStrings.zh-Hant.resx @@ -0,0 +1,261 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 找不到符合參數名稱 '{1}' 的參數。 + + + 找不到接受引數 '{1}' 的位置參數。 + + + 遺漏參數 '{1}' 的引數。指定類型 '{2}' 的參數,然後再試一次。 + + + 無法處理參數,因為參數名稱 '{1}' 不明確。可能的符合項目包括: {6}。 + + + 無法將 '{6}' 轉換為參數 '{1}' 所需的類型 '{2}'。{7} + + + 無法繫結參數 '{1}'。{6} + + + 無法繫結位置參數 '{1}'。 + + + 無法繫結位置參數,因為未指定任何名稱。 + + + 無法使用指定的具名參數來解析參數集。一或多個發出的參數無法一起使用,或提供的參數數目不足。 + + + 無法處理命令,因為遺漏一或多個必要參數: {1}。 + + + 無法在參數集 '{6}' 中指定參數 '{1}'。 + + + 無法繫結參數,因為參數 '{1}' 指定了一次以上。若要為可接受多個值的參數提供多個值,請使用陣列語法。例如,"-parameter value1,value2,value3"。 + + + 無法評估參數 '{1}',因為其引數被指定為指令碼區塊,且沒有輸入。無法評估沒有輸入的指令碼區塊。 + + + 參數 '{1}' 的指令碼區塊輸入失敗。{6} + + + 無法評估參數 '{1}',因為其引數輸入未產生任何輸出。 + + + 輸入物件無法繫結至命令的任何參數,因為命令未採用管線輸入,或輸入及其屬性不符合任何採用管線輸入的參數。 + + + 無法繫結輸入物件,因為它未包含要繫結所有必要參數的資訊: {6} + + + 無法處理管線輸入,因為無法擷取參數 '{1}' 的預設值。{6} + + + 無法擷取此 Cmdlet 的動態參數。{6} + + + 為下列參數提供值: + + + Cmdlet {0} 位於命令管線位置 {1} + + + 無法處理參數 '{1}' 的引數轉換。{6} + + + {6} + + + 無法驗證參數 '{1}' 上的引數。{6} + + + 無法將參數 '{1}' 繫結至目標。{6} + + + 無法將引數繫結至參數 '{1}',因為它為 null。 + + + 無法將引數繫結至參數 '{1}',因為它是空的字串。 + + + 無法將引數繫結至參數 '{1}',因為它是空的集合。 + + + 無法將引數繫結至參數 '{1}',因為它是空的陣列。 + + + 無法處理命令。參數 '{0}' 已定義多次。 + + + 無法繫結 Cmdlet {0},因為參數 '{1}' 的類型為 '{2}'且無法識別 Add() 方法,或有多個 Add() 方法存在。{6} + + + 無法繫結 Cmdlet {0} ,因為執行階段定義的參數 '{1}' 已新增至具有索引鍵 '{6}' 的 RuntimeDefinedParameterDictionary。索引鍵必須與 RuntimeDefinedParameter.Name 相同。 + + + 無法將引數繫結至參數 '{1}',因為引數的 PSTypeNames 與參數所需的 PSTypeName 不相符: {6}。 + + + 在 $PSDefaultParameterValues 中針對符合下列名稱或別名的參數定義了多個不同的預設值: {0}。已忽略這些預設值。 + + + 為此 Cmdlet 在 $PSDefaultParameterValues 中定義的下列名稱或別名解析為多個參數: {0}。已忽略預設值。 + + + {6} 此錯誤可能是由套用預設參數繫結所造成。您可將 $PSDefaultParameterValues["Disabled"] 設定為 $true 以在 $PSDefaultParameterValues 中停用預設參數繫結,然後再試一次。發生錯誤時,已順利為此 Cmdlet 繫結下列預設參數: {7} + + + {6} 此失敗可能是由套用預設參數繫結所造成。您可將 $PSDefaultParameterValues["Disabled"] 設定為 $true 以在 $PSDefaultParameterValues 中停用預設參數繫結,然後重試。發生錯誤時,已順利為此 Cmdlet 繫結下列預設參數: {7} + + + 預設值 '{0}' 繫結至參數 '{1}' 失敗: {2} + + + 索引鍵 '{0}' 的格式無效。如需正確格式的詳細資訊,請參閱 about_Parameters_Default_Values at https://go.microsoft.com/fwlink/?LinkId=228266。 + + + 索引鍵 '{0}' 沒有有效的格式。如需正確格式的詳細資訊,請參閱 about_Parameters_Default_Values at https://go.microsoft.com/fwlink/?LinkId=228266。 + + + 參數 '{0}' 已經過時。{1} + + + 類型 '{1}' 的索引鍵 '{0}' 不是字串值。DefaultParameterDictionary 只接受字串值索引鍵。 + + + 索引鍵 '{0}' 已新增到字典中。 + + + 不允許叫用方法或屬性 + + + 在未受信任指令碼的限制語言模式中,不允許在類型 '{1}' 上叫用方法或屬性 '{0}'。 + + + 不允許建立類型 + + + 在未受信任指令碼的限制語言模式中,不允許在參數繫結其間建立類型 '{0}'。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ParserStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ParserStrings.zh-Hant.resx new file mode 100644 index 00000000000..58202256c46 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ParserStrings.zh-Hant.resx @@ -0,0 +1,1376 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 找不到型別 [{0}]。 + + + 找不到型別 [{0}]。詳細資料: {1} + + + 字串語彙基元不完整。 + + + Unicode 逸出序列無效。有效的序列是 `u{,後接一到六個十六進位數字,並以 '}' 結尾。 + + + Unicode 逸出序列值超出範圍。最大值為 0x10FFFF。 + + + Unicode 逸出序列缺少結尾 '}'。 + + + Unicode 逸出序列在大括號之間包含超過六個十六進位數字。 + + + 無法在類型條件約束中將 [ref] 與其他類型一起使用。 + + + [ref] 只能是類型轉換序列中的最後一個類型。 + + + 類型序列中不能有兩個 [ref]。 + + + 數值常數 {0} 無效。 + + + 規則運算式模式 {0} 無效。 + + + 找到空白的 ${} 變數參考。大括號內需要名稱。 + + + 變數參考無效。'$' 後面沒有接有效的變數名稱字元。請考慮使用 ${} 來界定名稱。 + + + 您無法在 null 值運算式上呼叫方法。 + + + 方法叫用失敗,因為 [{0}] 不包含名為 '{1}' 的方法。 + + + 指派失敗,因為 [{0}] 不包含可設定的屬性 '{1}()'。 + + + 運算式或陳述式中有未預期的語彙基元 '{0}'。 + + + 展開運算子 '@' 不能用來參考運算式中的變數。'@{0}' 只能做為命令的引數。若要在運算式中參考變數,請使用 '${0}'。 + + + 參數 '{0}' 無效 + + + 管線元素中 '{0}' 後缺少運算式。 + + + 管線元素中 '{0}' 後面的運算式產生了無效的物件。它必須是命令名稱、指令碼區塊,或 CommandInfo 物件。 + + + 參數 {0} 需要引數。 + + + 參數 {0} 不能有引數。 + + + 參數清單中有重複的參數 ${0}。 + + + 參數清單中缺少引數。 + + + 像 '@{0}' 這類已展開的變數不能是逗點分隔的引數清單的一部分。 + + + 重新導向運算子後面缺少檔案規格。 + + + '{0}' 運算子已保留供未來使用。 + + + 重新導向至 '{0}' 失敗: {1} + + + 運算式只允許作為管線的第一個元素。 + + + 不允許空白管道元素。 + + + 指派運算式無效。指派運算子的輸入必須是可接受指派的物件,例如變數或屬性。 + + + 只能將雜湊表新增至另一個雜湊表。 + + + '-is' 的右運算元必須是類型。 + + + '-as' 的右運算元必須是類型。 + + + 格式化字串時發生錯誤: {0}。 + + + 運算子 '{0}' 的引數無效: {1}。 + + + '{0}' 運算子失敗: {1}。 + + + {0} 運算子後面只允許兩個元素,非 {1}。 + + + 您必須在 '{0}' 運算子後提供值運算式。 + + + '{0}' 運算子只能用於變數或屬性。 + + + 只能在雜湊常值節點上指定 {0} 屬性。 + + + 陣列索引運算式缺少或無效。 + + + 參考運算子後面缺少屬性名稱。 + + + 在這個物件上找不到屬性 '{0}'。請確認屬性存在且可設定。 + + + 在這個物件上找不到屬性 '{0}'。驗證屬性存在。 + + + 索引作業失敗;陣列索引的評估結果為 Null。 + + + 無法為 null 陣列編製索引。 + + + 無法為類型 "{0}" 的物件編入索引。 + + + 無法使用 ByRef 類型傳回類型 "{0}",對類型為 "{1}" 的物件進行索引。PowerShell 不支援 ByRef 類型。 + + + 陣列的維度太多: {0}。陣列的維度數目必須小於或等於 32。 + + + 因為不支援對分段指派,所以無法將陣列指派給 [{0}]。 + + + 您無法使用索引 [{0}] 索引編製 {1} 維度陣列。 + + + 陣列指派失敗,因為索引 '{0}' 超出範圍。 + + + '{0}' 後面缺少運算式。 + + + ${{variable}} 參考開頭缺少結尾 '}}'。 + + + $(subexpression) 缺少結尾的 ')'。 + + + 內部錯誤 - 未預期的一元運算子 {0}。 + + + [ref] 無法套用至不存在的變數。 + + + 無法擷取變數 '${0}',因為它尚未設定。 + + + 雜湊常值中不允許重複的索引鍵 '{0}'。 + + + 不允許重複的具名引數 '{0}'。 + + + '{0}' 運算子只能用於數字。運算元是 '{1}'。 + + + '(' 後必須是運算式。 + + + 雜湊常值中的索引鍵後面缺少 '=' 運算子。 + + + 雜湊常值中的 '=' 後面遺漏陳述式。 + + + 具名引數中 '=' 後面缺少陳述式。 + + + 屬性定義中缺少 ';' 或行尾。 + + + 一元運算子 '{0}' 後面缺少運算式。 + + + if 陳述式中,'{0} (' 後面缺少條件。 + + + {0} (條件) 後面缺少陳述式區塊。 + + + 'else' 關鍵字後面缺少陳述式區塊。 + + + 無法讀取檔案: {0}。 + + + 目前的提供者 ({0}) 無法開啟檔案。 + + + 找不到符合 '{0}' 的檔案。 + + + 無法處理路徑,因為它解析成超過一個檔案;一次只能處理一個檔案。 + + + {0} '-{1}' 參數保留給未來使用。 + + + 無法處理 'switch' 陳述式,因為 -file 選項缺少檔案名稱引數。 + + + switch 陳述式中 -file 的檔案名稱引數無效。 + + + 參數 {0} 對 switch 陳述式無效。 + + + 參數 {0} 對 foreach 陳述式無效。 + + + switch 陳述式必須具有下列其中一項: '-file file_name' 或 '( expression )'。 + + + switch 陳述式子句中缺少條件。 + + + switch 陳述式只能有一個 default 子句。 + + + switch 陳述式子句中缺少陳述式區塊。 + + + foreach 迴圈中缺少運算式。 +正確格式為: foreach ($a in $b) {...} + + + foreach 迴圈中缺少陳述式主體。 +正確格式為: foreach ($a in $b) {...} + + + 如果在函式宣告中指定了引數,就不能使用 param 陳述式。 + + + 未定義作業 '[{0}] {1} [{2}]'。 + + + 透過集合列舉時發生錯誤: {0}。 + + + 發生未處理的 COM Interop 例外狀況: {0} + + + COM 物件在釋放後又被存取: {0} + + + 已停止處理,因為指令碼太複雜。 + + + 此 Runspace 不支援此語法。如果 Runspace 處於無語言模式,就會發生這種情況。 + + + 選項與 -split 運算子的組合無效。 + + + 具有述詞的 -split 運算子不允許使用選項。 + + + 在此版本中,語彙基元 '{0}' 不是有效的陳述式分隔符號。 + + + 此語言版本不支援 '{0}' 關鍵字。 + + + 迴圈中的 '{0}' 後面缺少運算式。 + + + {0} 迴圈中缺少陳述式主體。 + + + 'trap' 陳述式不完整。trap 陳述式需要主體。 + + + 不完整的 'try' 陳述式。try 陳述式需要主體。 + + + 參數宣告是以逗號分隔的變數名稱清單,並可包含選擇性的初始設定運算式。 + + + 函式宣告中遺漏函式主體。 + + + 指令碼命令子句 '{0}' 已經定義。 + + + 未預期的語彙基元 '{0}',預期為 'begin'、'process'、'end'、'clean' 或 'dynamicparam'。 + + + 陳述式區塊或類型定義中缺少結尾 '}'。 + + + 方法呼叫中缺少 ')'。 + + + 陣列索引運算式後面缺少 ']'。 + + + 子運算式中缺少結尾 ')'。 + + + 子運算式中缺少結尾 ')'。 + + + if 陳述式中,'{0}' 後面缺少 '('。 + + + switch 陳述式中的運算式後面缺少 ')'。 + + + switch 陳述式中缺少 '{'。 + + + foreach 後面缺少變數名稱。 +正確格式為: foreach ($a in $b) {...} + + + foreach 迴圈中的變數後面缺少 'in'。 +正確格式為: foreach ($a in $b) {...} + + + foreach 迴圈的運算式部分後面缺少右括號 ')'。 +正確格式為: foreach ($a in $b) {...} + + + 關鍵字 '{0}' 後面缺少開頭 '('。 + + + do 迴圈中缺少 while 或 until 關鍵字。 + + + '{0}' 陳述式中的運算式後面缺少右括號 ')'。 + + + 關鍵字 {0} 後面缺少名稱。 + + + 函式參數清單中缺少 ')'。 + + + 處理此指令碼時發生錯誤 '{0}'。無法載入描述此錯誤的文字。 + + + 處理此指令碼時發生錯誤 '{0}'。由於錯誤 '{1}',所以無法載入描述此錯誤的文字。 + + + 沒有可用的 Runspace 可在此執行緒中執行指令碼。您可以在 System.Management.Automation.Runspaces.Runspace 類型的 DefaultRunspace 屬性中提供一個。您嘗試叫用的指令碼區塊為: {0} + + + 來源文字中有無法辨識的語彙基元。 + + + 針對此例外狀況要採取的動作: + + + 繼續(&C) + + + 回報錯誤,然後繼續執行下一個指令碼陳述式。 + + + 以無訊息方式繼續(&I) + + + 請勿回報此錯誤,請直接繼續執行下一個指令碼陳述式。 + + + 中斷(&B) + + + 不要繼續處理,改為擲回例外狀況。 + + + 暫止(&S) + + + 暫停目前的管線並返回命令提示字元。完成後,輸入 exit 以繼續作業。 + + + 無法在管線中間執行文件: {0}。 + + + 程式 '{0}' 無法執行: {1}{2}。 + + + 無法在二進位模組 '{0}' 的內容中使用 '&' 叫用。請在 '&' 後面指定非二進位模組,然後再試一次。 + + + 無法在模組 '{0}' 的內容中使用 '&' 來叫用,因為該模組尚未匯入。請匯入模組 '{0}',然後再次嘗試此操作。 + + + 在簽章區塊中找到可執行的指令碼程式碼。 + + + + + + 位於 {0}:{1} char:{2} ++ {3} + + + {0,4}+ {1} + + + ! SET ${0} = '{1}'。 + + + ! CALL 函式 '{0}' + + + ! CALL 函式 '{0}' (定義於檔案 '{1}') + + + ! CALL 方法 '{0}' + + + 字串缺少結尾字元: {0}。 + + + 字串結束字元前不允許有空白字元。 + + + 類型語彙基元結尾處缺少 ]。 + + + 變數名稱中請使用 `{,不要使用 {。 + + + Data 區段缺少陳述式區塊。 + + + Data 區段的 "{0}" 參數無效。有效的 Data 區段參數為 SupportedCommand。 + + + 限制語言模式或 Data 區段中不允許陣列參考。 + + + 限制語言模式或 Data 區段中不允許 Assignment 陳述式。 + + + 限制語言模式或 Data 區段中不允許重新導向。 + + + 限制語言模式或 Data 區段中不允許 Do 和 While 陳述式。 + + + 限制語言模式或 Data 區段中不允許可擴充字串。 + + + 限制語言模式或 Data 區段中不允許 '{0}' 運算子。 + + + 限制語言模式或 Data 區段中不允許 Trap 陳述式。 + + + 限制語言模式或 Data 區段中不允許 Try 陳述式。 + + + 限制語言模式中或 Data 區段中不允許流程控制陳述式,例如 Break、Continue、Return、Exit 和 Throw。 + + + 限制語言模式或 Data 區段中不允許 Foreach 陳述式。 + + + 限制語言模式或 Data 區段中不允許 For 和 While 陳述式。 + + + 限制語言模式或 Data 區段中不允許函式宣告。 + + + 限制語言模式或 Data 區段中不允許方法呼叫。 + + + 限制語言模式或 Data 區段中不允許參數宣告。 + + + 限制語言模式或 Data 區段中不允許屬性參考。 + + + 限制語言模式或 Data 區段中不允許指令碼區塊文字。 + + + 限制語言模式或 Data 區段中不允許 switch 陳述式。 + + + 正在參考無法在限制語言模式或 Data 區段中參考的變數。可參考的變數包括下列項目: {0}。 + + + 限制語言模式或 Data 區段中不允許命令 '{0}'。 + + + 限制語言模式或其他 Data 區段中不允許資料陳述式。 + + + Data 區段的 SupportedCommand 參數缺少值。請為該參數提供 Cmdlet 或函數名稱。 + + + Data 區段中不允許 Begin 陳述式區塊、Process 陳述式區塊或參數陳述式。 + + + 限制語言模式或 Data 區段中不允許超過 "{0}" 個字元的字串乘法結果。 + + + 限制語言模式中或 Data 區段中不允許陣列相乘導致超過 {0} 個元素。 + + + 限制語言模式或 Data 區段中不允許點來源。 + + + 屬性引數必須是常數或指令碼區塊。 + + + 找不到自訂屬性 '{0}' 的類型。確認已經載入包含此類型的組件。 + + + 找不到類型 '{1}' 的屬性 '{0}'。 + + + 未預期的屬性 '{0}'。 + + + 屬性或類型常值結尾缺少 ]。 + + + 呼叫函式或命令時,彷彿它是方法。參數應該以空格分隔。如需參數的相關資訊,請參閱 about_Parameters 說明主題。 + + + Try 陳述式缺少陳述式區塊。 + + + Try 陳述式缺少 Catch 或 Finally 區塊。 + + + Catch 區塊缺少陳述式區塊。 + + + Finally 區塊缺少陳述式區塊。 + + + 例外狀況類型 {0} 已由先前的處理常式處理。 + + + Catch 區塊必須是最後一個 Catch 區塊。 + + + 缺少類型常值。 + + + 多行註解中缺少結尾字元 '#>'。 + + + here-string 標頭之後、行尾之前不可有任何字元。 + + + 已偵測到剖析器錯誤。 + + + '{0}' 後面缺少陳述式區塊。 + + + 在參數陳述式中找到非預期的類型 [{0}]。 + + + 在陳述式之前找到非預期的類型 [{0}]。 + + + 雜湊常值中不允許使用 null 索引鍵。 + + + 限制語言模式或 Data 區段中不允許屬性。 + + + 限制語言模式或 Data 區段中不允許類型 {0}。 + + + '{0}' 是唯讀屬性。 + + + 類型名稱缺少組件名稱規格。 + + + 控制流程不可離開 Finally 區塊。 + + + PowerShell 中發生無法復原的錯誤。 + + + AST 不能作為另一個 AST 的子系。若要在另一個 AST 中使用這個 AST,請呼叫 Copy() 方法,並使用其結果。 + + + Using 運算式中不允許運算式。 + + + 無法擷取 Using 變數。Using 變數只能搭配 Invoke-Command、Start-Job 或指令碼工作流程中的 InlineScript 使用。搭配 Invoke-Command 使用時,只有在遠端電腦上叫用指令碼區塊時,Using 變數才有效。 + + + 變數參照無效。缺少變數名稱。 + + + 變數參考無效。':' 後面沒有接有效的變數名稱字元。請考慮使用 ${} 來界定名稱。 + + + 並非所有剖析錯誤都已回報。 請更正已回報的錯誤,然後再試一次。 + + + '[' 後缺少類型名稱。 + + + * 串流 + + + 偵錯資料流 + + + 錯誤資料流 + + + 輸出資料流 + + + 此命令的 {0} 已重新導向。 + + + 詳細資訊資料流 + + + 警告資料流 + + + 關鍵字 '{0}' 後面缺少陳述式主體。 + + + 限制語言模式或 Data 區段中不允許平行和循序區塊。 + + + 未預期的關鍵字 '{0}'。 + + + [void] 不能做為參數類型使用,或用在指派的左側。 + + + 無法叫用此方法。 + + + 無法將雜湊表轉換為下列類型的物件: {0}。限制語言模式中或 Data 區段不支援 Hashtable-to-Object 轉換。 + + + 引數必須是常數。 + + + {0} 參數的引數無效。請指定有效的字串引數。 + + + Module 參數的引數無效。{0} + + + Version 參數的引數無效。請指定有效的 PowerShell 版本,格式為 major.minor 版本。 + + + {0} 參數的引數無效。請指定有效的 PowerShell 版本。 + + + {0} 參數的引數包含重複的值。請勿指定重複的 PowerShell 版本值。 + + + 模組名稱不支援萬用字元。 + + + 無法叫用方法。僅在此語言模式的核心類型上才支援方法叫用。 + + + 無法設定屬性。僅在此語言模式的核心類型上才支援屬性設定。 + + + 找到資源 '{0}' 的無效屬性名稱。屬性名稱必須是簡單字串,而且不能包含變數或運算式。請以簡單字串取代 '{1}'。 + + + 成員 '{0}' 無效。有效的成員為 +'{1}'。 + + + 物件定義中缺少 '{'。 + + + 缺少必要的名稱或運算式。 + + + 找不到結構描述檔案 {0}。請確認組態陳述式中指定的任何模組都包含 schema.mof 檔案,然後再次嘗試執行指令碼。 + + + 無法定義資料區段。此語言模式不支援定義額外支援的命令。 + + + 組態陳述式中缺少 '{'。 + + + 剖析 MOF 檔案 '{0}' 時發生例外狀況:{1}。 + + + 缺少設定的名稱。請以簡單名稱、字串或字串值運算式提供缺少的名稱。 + + + 找不到此模組 '{0}'。 + + + 找到模組 '{0}' 的多個版本。您可以執行 'Get-Module -ListAvailable -FullyQualifiedName {0}' 來查看系統上的可用版本,然後使用完整名稱 '@{{ModuleName="{0}"; RequiredVersion="Version"}}'。 + + + foreach 陳述式的 ThrottleLimit 參數缺少值。請為該參數提供節流限制。 + 'ThrottleLimit' must not be localized. + + + 只有使用 Parallel 參數的 foreach 陳述式支援 ThrottleLimit 參數。 + 'ThrottleLimit' and 'Parallel' must not be localized. + + + 設定區塊結果為 null 或空白。請確認已在區塊中定義設定。 + + + 每個組態只能使用一次 '{0}' 資源,因此不能有名稱。請移除 '{1}',然後再次執行指令碼。 + + + 執行個體定義中有不完整的屬性指派區塊。 + + + 屬性指派中的索引鍵後面缺少 '=' 運算子。 + + + 執行個體定義中不允許重複的屬性指派。 + + + 處理架構檔案 '{0}' 時,找到 '{1}' 的第二個 CIM 類別定義。這個類別已在檔案 '{2}' 中定義。請移除多餘的定義,然後再試一次。 + + + 資源名稱 '{0}' 已由其他資源或組態使用。 + + + 類別名稱 '{0}' 與定義它的檔案名稱 '{1}' 不符。請重新命名檔案以符合類別名稱,或重新命名類別名稱以符合檔案名稱 + + + 處理節點 '{0}' 的規格時發現重複的資源識別碼 '{1}'。請變更此資源的名稱,使其在節點規格中具有唯一性。 + + + 動態關鍵字 '{0}' 的 body 陳述式中,名稱與指令碼區塊之間沒有空白字元。 + + + 要在函式字典中定義的項目,其 key 屬性不可為空白,因為該 key 屬性會用作函式名稱。請指定非空白字串作為 key 屬性的值,然後再次嘗試操作。 + + + 資源 '{1}' 的 Requires 清單中的資源參考 '{0}' 格式無效。必要的資源名稱格式應為 '[<typename>]<name>',且只能包含英數字元、空格、'_'、'-'、'.' 和 '\'。 + The capitalized word Requires should not be localized. The words <typename> and <name> should be localized but the <> characters must be preserved. + + + 資源 '{1}' 的獨佔清單中的資源參考 '{0}' 格式無效。獨佔資源名稱的格式應為 '<typename>\<name>',且不得包含空格。 + + + PartialConfiguration '{0}' 設定為提取模式,這需要 ConfigurationSource 屬性。 + + + 要在指令碼區塊範圍中建立的變數項目清單中找到 null 項目。請移除索引 {0} 的項目,或以非 null 項目取代,然後再試一次。 + + + 定義函式 '{0}' 的指令碼區塊不可為 null 或空白。請在函式定義字典中提供非空白的指令碼區塊,然後再次嘗試操作。 + + + Import-DscResource 動態關鍵字的語法如下: + +Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>]。 + +名稱 : 要匯入之一個或多個資源的名稱。 +ModuleName : 要匯入之一個或多個模組的名稱或 ModuleSpecification 物件。 +ModuleVersion: 要匯入的模組版本。如果使用這個參數,ModuleName 必須只依名稱代表一個模組。 + + + 如果指定 Name 參數,Import-DscResource 動態關鍵字只支援一個模組。 + + + Import-DscResource 動態關鍵字不支援位置參數。Import-DscResource 動態關鍵字的語法是:"Import-DscResource [-Name <ResourceName(s)>] [-ModuleName <ModuleName(s)>] [-ModuleVersion <ModuleVersion>] + + + 無法載入資源 '{0}': 找不到資源。 + + + ConstrainedLanguage 模式中不允許使用 Configuration 關鍵字。 + + + 設定名稱 '{0}' 無效。Standard 名稱只能包含字母 (a-z、A-Z)、數字 (0-9)、句點 (.)、連字號 (-) 和底線 (_)。名稱不可為 null 或空白,且應以字母開頭。 + + + 組態的主體只支援 End 區塊。組態中不允許 Begin、Process 和 DynamicParam 區塊。 + + + 還原序列化檔案 {0} 時,CIM 還原序列化程式擲回錯誤。 + + + '{0}' 對類別 '{2}' 上的屬性 '{1}' 來說,並非有效的值。請將值變更為下列其中一個字串: {3}。 + + + 在類別 '{2}' 上,屬性 '{1}' 的值 '{0}' 至少有一個不受支援或無效。請只指定支援的值: +{3}。 + + + 資源 '{0}' 要求為屬性 '{2}' 提供類型為 '{1}' 的值。 + + + 資源 '{1}' 的屬性 '{0}' 的值 '{2}' 不在有效範圍 '{3}' 到 '{4}' 之間。 + + + 無法載入 PowerShell 資料檔案 '{0}',發生下列錯誤: +{1} + + + 無法將路徑 '{0}' 解析為單一 .psd1 檔案。 + + + PowerShell 資料檔案 '{0}' 無效,因為無法將它評估為 Hashtable 物件。 + + + WinPE 不支援設定。 + + + 如果傳遞給 Where() 運算子的運算式是 null,您必須為選取模式引數指定非 Default 的值。請將模式引數的值變更為 Default 以外的值,然後再試一次。 + + + 傳遞給 ForEach() 的泛型集合類型 [{0}] 有太多型別引數。請將指定的型別變更為只有一個型別引數的泛型集合,然後再次嘗試執行您的指令碼。 + + + 無法將輸入轉換成傳遞至 ForEach() 運算子的目標類型 [{0}]。請檢查指定的類型,然後再次嘗試執行您的指令碼。 + + + 'ForEach' 方法不支援具有 'clean' 區塊的指令碼區塊。 + + + 提供給 Where() 運算子第三個引數的 'numberToReturn' 值必須大於零。請更正引數值,然後再次執行您的指令碼。 + + + 重新導向只允許將另一個資料流與輸出資料流合併。請更正重新導向作業,將其合併到輸出資料流,然後再次嘗試執行您的指令碼。 + + + ForEach() 運算子在目標物件上找不到成員 '{0}'。請確認具名成員存在,然後再次嘗試執行您的指令碼。 + + + 此語言版本不支援 '{0}' 關鍵字。 + + + 此語言版本不支援 '{0}' 屬性。 + + + 重複的 '{0}' 限定詞 + + + 修飾元 '{0}' 無法和 '{1}' 相結合 + + + 缺少 using 指示詞 + + + 缺少命名空間別名 + + + 缺少 '=' 運算子 + + + 缺少 using 名稱 + + + 方法中未指派變數。 + + + 缺少屬性名稱或方法定義。 + + + 成員 '{0}' 已遭拒。 + + + 只能在類別成員上指定一個類型。 + + + 建立類型 "{0}" 期間發生錯誤。錯誤訊息: +{1} + + + 無法將值轉換成類型 "{0}"。 + + + 找不到屬性 '{1}' 的屬性 '{0}'。請指定下列其中一個屬性: {2}。 + + + 屬性 '{0}' 在此宣告上無效。其僅在 '{1}' 宣告上有效。 + + + 屬性引數必須是常數。 + + + 未定義的 DSC 資源 '{0}'。請使用 Import-DSCResource 匯入資源。 + + + 在預先剖析動態關鍵字 '{0}' 時發生例外狀況,詳細資料為 '{1}'。 + + + 對動態關鍵字 '{0}' 進行後續剖析時發生例外狀況,詳細資料為 '{1}'。 + + + PowerShell 6+ 不支援工作流程。 + + + 一般設定中不允許中繼設定資源 {0}。請在具有 [DscLocalConfigurationManager()] 屬性的設定中使用中繼設定資源。 + + + 中繼設定中不允許一般 DSC 資源 {0}。 + + + 這個執行緒中沒有可用的 Runspace 可供取得及執行 SteppablePipeline。您可以在 System.Management.Automation.Runspaces.Runspace 類型的 DefaultRunspace 屬性中提供一個。您嘗試從中取得 SteppablePipeline 的指令碼區塊為: {0} + + + 從 {0} 到 {1} 是有效的轉換。 + + + 無法執行呼叫。 + + + 無法擷取類型資訊。 + + + 無法取得 {0} 的分派識別碼 (錯誤: {1})。 + + + 找不到 "{0}" 與引數計數 "{1}" 的多載 + + + 叫用 {0} 時發生錯誤。找不到成員。 + + + 叫用 {0} 時發生錯誤。不支援具名引數。 + + + 叫用 {0} 時發生錯誤。偵測到溢位。 + + + 叫用 {0} 時發生錯誤。缺少必要參數。 + + + 設定 "{0}" 時發生例外狀況: 無法將類型為 "{1}" 的值 "{2}" 轉換成類型 "{3}"。 + + + IDispatch::GetIDsOfNames 的表現出乎 {0} 的意料。 + + + Marshal.SetComObjectData 失敗。 + + + 未預期的 VarEnum {0}。 + + + 正在嘗試傳遞不支援的類型的事件處理常式。 + + + PowerShell 6+ 中不支援 Configuration 關鍵字。 + + + 方法中的所有程式碼路徑都沒有傳回值。 + + + void 方法中的 return 陳述式無效。 + + + 非 void 方法中的 return 陳述式無效。 + + + '{0}' 宣告中缺少 '{0}' 主體。 + + + 無法定義列舉,因為初始化運算式中有循環。 + + + {0} 的列舉程式值太大或太小。 + + + 列舉值必須是常數值。 + + + 在執行動態關鍵字 '{0}' 的語意檢查時發生例外狀況,詳細資料為 '{1}'。 + + + DSC 資源類別 '{2}' 中類型為 '{1}' 的 '{0}' 屬性不支援。 + + + 類別方法參數清單中缺少 '('。 + + + 類別方法中不允許具名區塊。 + + + 類別方法中不允許參數區塊。 + + + 無法繼承密封類別 '{0}'。 + + + 預期的類型名稱。 + + + '{0}' 不是列舉的有效基礎類型。必須是內建整數型別 (byte、sbyte、short、ushort、int、uint、long 或 ulong) + + + '{0}': 必須指定介面名稱。 + + + 基底類別 '{0}' 不包含無參數的建構函式。 + + + 基底類型 '{0}' 無效。基底類型不可為陣列。 + + + 基底類型 '{0}' 無效。基底類型不能是未指定參數的泛型。 + + + 基底類別建構函式呼叫中的 ':' 後面缺少 'base'。 + + + 建構函式不能指定傳回類型。 + + + DSC 資源 '{0}' 沒有預設建構函式。 + + + DSC 資源 '{0}' 缺少 Get 方法。此方法必須傳回 [{0}],且不接受任何參數。 + + + DSC 資源 '{0}' 必須至少有一個索引鍵屬性 (使用 [DscProperty(Key)] 語法。) + + + DSC 資源 '{0}' 缺少 Set 方法。此方法必須傳回 [void],且不接受任何參數。 + + + DSC 資源 '{0}' 缺少 Test 方法。此方法必須傳回 [bool],且不接受任何參數。 + + + 靜態建構函式不能有任何參數。 + + + 屬性不允許類型 '{0}'。 + + + 參數不允許類型 '{0}'。 + + + 在靜態方法或靜態屬性的初始設定式中,無法存取非靜態成員 '{0}'。 + + + 無法剖析模組指令碼檔案 '{0}',發生錯誤 +'{1}'。 + + + 無法在 PowerShell 中執行文件: {0}。 + + + 方法參數上不允許多重類型條件約束。 + + + 此指令碼包含惡意內容,已被您的防毒軟體封鎖。 + + + 無法在 LocalConfigurationManager 資源中指定 '{0}'。請改為切換至 [設定],或僅使用下列值: {1}。 + + + '{0}' 是在泛型類型中定義的。 + + + 類型名稱 '{0}' 不明確,可能是 '{1}' 或 '{2}'。 + + + 'using' 陳述式必須出現在指令碼中任何其他陳述式之前。 + + + 不支援此 'using' 陳述式語法。 + + + 'using' 陳述式中指定的命名空間包含無效的字元。 + + + 資訊流 + + + 無效的索引鍵屬性。索引鍵屬性必須是 [string]、帶正負號或不帶正負號的整數,或列舉類型。 + + + 無效的 Get 方法。Get 方法必須傳回 [{0}],且不接受任何參數。 + + + 無法載入組件 '{0}'。 + + + 無法使用 UNC 路徑為 '{0}' 的組件。 + + + 無法使用 URI 結構描述為 '{0}' 的組件。 + + + 缺少新行或分號。 + + + 無法指派屬性,請使用 '{0}{1}'。 + + + '{0}' 不是使用名稱的有效值。 + + + 無法指派屬性,請使用 '{0}{1}'。 + + + DebugMode 應該只有一個值。 + + + 在方法內找不到標籤 '{0}'。 + + + 無法將 CimProperty {0} 的值轉換成類別 {1} 的屬性值。 + + + PowerShell 類別的屬性 {0} {1} 未宣告為陣列類型,但在其設定執行個體中定義為執行個體陣列類型。 + + + 無法建立 PowerShell 類別 {0} 的物件。 + + + 提供給 Desired State Configuration 資源 {0} 的雜湊表無效。金鑰或值不可為 null 或空白。 + + + 提供給 Desired State Configuration 資源 {0} 的使用者名稱無效。使用者名稱不可是 Null 或空白。 + + + 提供給 Desired State Configuration 資源 {0} 的使用者名稱無效。使用者名稱不可是 Null 或空白。 + + + 屬性 {0} 未在 PowerShell 類別 {1} 中宣告,但已在其設定執行個體中定義。 + + + PartialConfiguration '{0}' 的重新整理模式設為 Disabled,這不是部分設定的有效模式。請使用 Pull 或 Push 重新整理模式。 + + + 無法建立類型。此語言模式只支援核心類型。 + + + 無法在 Node 內容內指定 Import-DscResource + + + $PSCulture、$PSUICulture、$true、$false、$null + + + 無法將類型為 '{1}' 的值指派給自動變數 '{0}' + + + 將 PsDscRunAsCredential 用於資源 {0} 時發生衝突,因為它已指定 PsDscRunAsCredential 值。複合資源只能使用一個 PsDscRunAsCredential。 + + + 在 "{0}" 找不到 DSC 結構描述存放區。請確定已安裝 PSDesiredStateConfiguration v3 模組。 + + + {0} + + + 此指令碼包含的內容已透過原則設定標示為可疑,並已遭封鎖,錯誤碼為 {0}。如需詳細資訊,請連絡系統管理員。 + + + 無法使用 '&' 或 '.' 運算子,跨語言界限叫用模組範圍命令。 + + + ConstrainedLanguage 模式中不允許使用 Class 關鍵字。 + + + 三元運算式中遺漏 ':'。 + + + 管線鏈結運算子後面必須接著管線。 + + + 背景運算子只能用在管線鏈結的結尾。 + + + 不支援直接叫用指令碼區塊的 'clean' 區塊。 + + + 剖析器組態關鍵字 + + + 在 Constrained Language 模式中,不受信任的指令碼不允許使用 Configuration 關鍵字。 + + + 剖析器類別關鍵字 + + + 在 Constrained Language 模式中,不受信任的指令碼不允許使用 Class 關鍵字。 + + + 剖析器資料區段 SupportedCommand + + + 對於不受信任的指令碼,在 Constrained Language 模式中不允許包含 SupportedCommand 參數的 Data 區段。 + + + 模組範圍呼叫運算子 + + + 在 Constrained Language 模式中,模組範圍呼叫運算子將會被拒絕。 + + + ForEach 關鍵字方法呼叫 + + + 在 Constrained Language 模式中執行時,ForEach 關鍵字會使 '{0}' 反覆項目項目方法叫用失敗。 + + + 運算式評估可能失敗 + + + 從指令碼區塊建立可逐步執行管線可能需要評估指令碼區塊中的一些運算式。除非運算式代表常數值,否則在受限語言模式下,運算式評估會悄悄失敗,並傳回 'null'。 + + + ARM64 處理器不支援 Configuration 關鍵字。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PathUtilsStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PathUtilsStrings.zh-Hant.resx new file mode 100644 index 00000000000..7e4967a3430 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PathUtilsStrings.zh-Hant.resx @@ -0,0 +1,166 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 編碼 'UTF-7' 已過時,請使用 UTF-8。 + + + 檔案 {0} 已經存在,且已指定 {1}。 + + + 無法開啟檔案,因為目前的提供者 ({0}) 無法開啟檔案。 + + + 無法執行作業,因為路徑已解析為多個檔案。此命令無法針對多個檔案執行。 + + + 無法執行作業,因為萬用字元路徑 {0} 未解析為檔案。 + + + 未知的編碼 {0}; 有效值為 {1}。 + + + 目錄 '{0}' 已經存在。 如果您想要覆寫此目錄及其中的檔案,請使用 -Force 參數。 + + + 使用者模組路徑不存在,因此無法為提供的模組名稱 '{0}' 建立模組資料夾。 + + + 無法建立模組 {0},原因如下: {1}。請針對 -OutputModule 參數使用不同的引數,然後重試。 + {StrContains="OutputModule"} +{0} is a placeholder for the name of a directory +{1} is a placeholder for an error message from the inner exception + +Reviewed by TArcher on 2010-07-21 + +Example usage: +PS C:\> $s = New-PSSession +PS C:\> Export-PSSession -Session $s -OutputModule gibberish:here +Export-PSSession : Cannot create the module 'gibberish:here' due to the following: Cannot find drive. A drive with the name 'gibberish' does not exist. Use a different argument for the -OutputModule parameter and try again. +At line:1 char:1 ++ Export-PSSession -Session $s -OutputModule gibberish:here ++ ^ + + CategoryInfo : ResourceExists: (gibberish:here:String) [Export-PSSession], ArgumentException + + FullyQualifiedErrorId : ExportProxyCommand_CannotCreateOutputDirectory,Microsoft.PowerShell.Commands.ExportPSSessionCommand + + + + 無法載入模組,因為它是由不相容的 {0} Cmdlet 版本產生。請使用目前工作階段中的 {0} Cmdlet 產生模組,然後再次嘗試載入模組。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PipelineStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PipelineStrings.zh-Hant.resx new file mode 100644 index 00000000000..509bc767802 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PipelineStrings.zh-Hant.resx @@ -0,0 +1,179 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法處理 Cmdlet 執行個體,因為另一個管線正在使用該 Cmdlet 執行個體。請連絡 Microsoft 客戶支援服務。 + + + 無法執行作業,因為管線已開始。請停止管線,然後再試一次。 + + + 無法繼續執行 Cmdlet,因為停止原則已禁止執行 Cmdlet。 + + + 無法執行管線,因為管線中的第一個 Cmdlet 正嘗試從前一個 Cmdlet 的結果讀取輸入。請修改第一個 Cmdlet、移除第一個 Cmdlet,或將第一個 Cmdlet 所需輸出的 Cmdlet 新增至管線,然後再次嘗試執行管線。 + + + 無法處理 Cmdlet 編號。ReadFromCommand 函式必須指定已新增至管線的 Cmdlet 識別碼。請連絡 Microsoft 客戶支援服務。 + + + 無法讀取 ReadFromCommand 和 ReadErrorQueue 函式的輸出,因為另一個 Cmdlet 已在讀取該輸出。請連絡 Microsoft 客戶支援服務。 + + + 無法執行管線,因為其中沒有命令。請至少將一個命令新增至管線,然後再執行一次。 + + + 無法完成管線作業,因為尚未開始。您必須先呼叫 Begin() 方法,才能在可逐步執行的管線上呼叫 End()。 + + + 無法從 BeginProcessing、ProcessRecord 和 EndProcessing 方法的覆寫之外呼叫 WriteObject 和 WriteError 方法,而且只能在相同的執行緒中呼叫。請確認 Cmdlet 是否正確進行這些呼叫,或連絡 Microsoft 客戶支援服務。 + + + Cmdlet 在呼叫 ThrowTerminatingError 之後擲回例外狀況。 +第一個例外狀況為 "{0}",堆疊追蹤為 "{1}"。 +第二個例外狀況為 "{2}",堆疊追蹤為 "{3}"。 + + + 關閉管線後,就無法再呼叫 WriteObject 和 WriteError 方法。請連絡 Microsoft 客戶支援服務。 + + + CommandInvocation({0}): "{1}" + + + NonTerminatingError({0}): "{1}" + + + TerminatingError({0}): "{1}" + + + ParameterBinding({0}): name="{1}"; value="{2}" + + + 建立管線時發生錯誤。 + + + 此管線不支援「中斷連線與連線」語意。 + + + 無法連線到此管線,因為它不處於中斷連線狀態。 + + + Runspace 物件具備一個相關聯的 null 遠端命令。 由於未指定遠端命令,因此無法建立已中斷連線的 RemotePipeline 物件。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/PowerShellStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/PowerShellStrings.zh-Hant.resx new file mode 100644 index 00000000000..5abe0da4e91 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/PowerShellStrings.zh-Hant.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 + + + 目前 PowerShell 執行個體的狀態不適用於此作業。 + + + 無法執行作業,因為已經啟動命令。請等候命令完成或停止命令,然後再試一次。 + + + 未指定任何命令。 + + + PowerShell 執行個體的狀態不適合建立巢狀 PowerShell 執行個體。只有在執行中的 PowerShell 執行個體中,才能建立巢狀 PowerShell 執行個體。 + + + 無法執行作業,因為 Runspace 不處於 '{0}' 狀態。Runspace 目前的狀態為 '{1}'。 + + + 無法以非同步方式叫用巢狀 PowerShell 執行個體。請使用 Invoke 方法。 + + + 未透過在此 PowerShell 執行個體上呼叫 {1} 來建立 {0} 物件。 + + + 當 Runspace 設定為重複使用執行緒時,叫用設定中的 Apartment 狀態必須與 Runspace 相符。 + + + 當 Runspace 設定為使用目前的執行緒時,叫用設定中的 Apartment 狀態必須與目前執行緒的狀態相符。 + + + 需要命令才能新增參數。必須先將命令新增至 PowerShell 執行個體,才能新增參數。 + + + 字典中的索引鍵必須是字串。 + + + 沒有可用的 Runspace 可在此執行緒中執行命令。您可以在 System.Management.Automation.Runspaces.Runspace 類型的 DefaultRunspace 屬性中提供一個。您嘗試叫用的命令為: {0} + + + 無法連線此 PowerShell 物件,因為它與遠端 Runspace 或 Runspace 集區沒有關聯。 + + + 執行中的命令已中斷連線,但仍在遠端伺服器上執行。 請重新連線,以取得命令作業狀態和輸出資料。 + + + 無法執行作業,因為目前的 PowerShell 工作階段處於「已中斷連線」狀態。 請連線此 PowerShell 工作階段,然後等候命令完成或停止命令。 + + + 無法執行作業,因為目前的 PowerShell 工作階段處於「已中斷連線」狀態。 請連線此 PowerShell 工作階段,然後再試一次。 + + + 連線遠端命令的嘗試失敗。 + + + 無法執行作業,因為命令目前正在停止。請等候命令完成停止,然後再試一次。 + + + 沒有可用的 Runspace 可在此執行緒中執行命令。您可以在 System.Management.Automation.Runspaces.Runspace 類型的 DefaultRunspace 屬性中提供一個。目前的 PowerShell 執行個體不包含任何可叫用的命令。 + + + 無法建立使用目前 Runspace 的 PowerShell 物件,因為目前沒有可用的 Runspace。 目前的 Runspace 可能正在啟動,例如在使用初始工作階段狀態建立時。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ProgressRecordStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ProgressRecordStrings.zh-Hant.resx new file mode 100644 index 00000000000..4fde4d20634 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ProgressRecordStrings.zh-Hant.resx @@ -0,0 +1,132 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} 不能為負值。 + + + 無法處理引數,因為 {0} 的值不能為 null 或空白。 + + + 無法設定百分比,因為 {0} 不能大於 100。 + + + ParentActivityId 不能與 ActivityId 相同。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ProviderBaseSecurity.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ProviderBaseSecurity.zh-Hant.resx new file mode 100644 index 00000000000..42acca18dc2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ProviderBaseSecurity.zh-Hant.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 + + + 無法使用此介面,因為此提供者不支援 ISecurityDescriptorCmdletProvider 介面。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/ProxyCommandStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/ProxyCommandStrings.zh-Hant.resx new file mode 100644 index 00000000000..8ca2c9acdb2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/ProxyCommandStrings.zh-Hant.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 + + + 無法將 'help' 參數辨識為 'get-help' 命令所建立的有效 HelpInfo 物件。 + + + 無法產生 Proxy 命令,因為 CommandMetadata 沒有名稱。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/RegistryProviderStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/RegistryProviderStrings.zh-Hant.resx new file mode 100644 index 00000000000..0b536ab8ce1 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/RegistryProviderStrings.zh-Hant.resx @@ -0,0 +1,333 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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} + + + 清除項目 + + + 項目: {0} + + + 新增項目 + + + 項目: {0} + + + 移除機碼 + + + 項目: {0} + + + 複製機碼 + + + 項目: {0} 目的地: {1} + + + 重新命名項目 + + + 項目: {0} NewName: {1} + + + 移動項目 + + + 項目: {0} 目的地: {1} + + + 設定屬性 + + + 項目: {0} 屬性: {1} + + + 清除屬性 + + + 項目: {0} 屬性: {1} + + + 新增屬性 + + + 項目: {0} 屬性: {1} + + + 移除屬性 + + + 項目: {0} 屬性: {1} + + + 重新命名屬性。 + + + 項目: {0} SourceProperty: {1} DestinationProperty: {2} + + + 複製屬性 + + + 項目: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 移動屬性 + + + 項目: {0} SourceProperty: {1} DestinationItem: {2} DestinationProperty: {3} + + + 未處理作業。提供的位置不允許此作業。 + + + 來源位置不允許此作業。 + + + 目的地位置不允許此作業。 + + + 本機電腦的組態設定 + + + 目前使用者的軟體設定 + + + 此路徑中已存在機碼。 + + + 無法執行作業,因為目的地路徑是來源路徑的子路徑。 + + + 屬性已存在。 + + + 屬性 {0} 不存在於路徑 {1}。 + + + 指定路徑的登錄機碼不存在。 + + + 無法繫結參數 'Type'。無法將 "{0}" 轉換成 "{1}"。可用的列舉值為「String、ExpandString、Binary、DWord、MultiString、QWord、Unknown」。 + + + 已建立機碼 {0},但無法設定預設值。 + + + 無法使用指定的根目錄建立磁碟機。根路徑不存在。 + + + 無法重新命名項目,因為同一個容器中已存在名稱相同的項目。 + + + 登錄機碼名稱必須以有效的基底機碼名稱開頭。 + + + 子機碼引數無效。 + + + 無法刪除子機碼樹狀,因為子機碼不存在。 + + + 找不到具有該名稱的值。 + + + 列舉值 {0} 無效。 + + + 必須指定值引數。 + + + 必須指定名稱引數。 + + + 指定的 RegistryValueKind 為無效的值。 + + + RegistryKey.SetValue 不允許包含 null 字串參考的 String[]。 + + + 登錄子機碼不應超過 255 個字元。 + + + 必須指定非空白的子機碼名稱。 + + + 值物件的型別與指定的 RegistryValueKind 不符,或無法正確轉換該物件。 + + + RegistryKey.SetValue 不支援型別為 '{0}' 的陣列。僅支援 Byte[] 和 String[]。 + + + 指定的登錄機碼不存在。 + + + 指定的值名稱長度超過 16383 個字元上限。 + + + 指定的值資料大小超過 1 MB 上限。 + + + 指定的登錄子機碼不存在。 + + + 指定的 RegistryKeyPermissionCheck 值無效。 + + + 登錄機碼有子機碼; 此方法不支援遞迴移除。 + + + 無法在沒有 Transaction.Current 或指定交易的情況下建立 KTM 控制代碼。 + + + 指定的交易或 Transaction.Current 必須與用來建立或開啟此 TransactedRegistryKey 的交易相符。 + + + TransactedRegistryKey 物件與交易沒有關聯,因為它是針對預先定義的機碼。 + + + 不允許要求的登錄存取。 + + + 存取登錄機碼 '{0}' 遭拒。 + + + 無法寫入登錄機碼。 + + + 無法存取已關閉的登錄機碼。 + + + 未知的錯誤: {0}。 + + + 此平台不支援登錄交易。 + + + 指定的控制代碼無效。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/RemotingErrorIdStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/RemotingErrorIdStrings.zh-Hant.resx new file mode 100644 index 00000000000..002e6ad7b83 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/RemotingErrorIdStrings.zh-Hant.resx @@ -0,0 +1,1735 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 發生類型 "{0}" 的錯誤。 + + + 處理程序記憶體不足。 + + + 只有 Windows 支援使用 -ComputerName 列舉遠端 PSSession,"{0}" 不支援。 + + + 管線識別碼 "{0}" 不符合目前正在執行之管線的 InstanceId "{1}"。 + + + 在伺服器上找不到管線識別碼 "{0}"。 + + + 遠端管線已停止。 + + + 工作階段已存在。不允許使用相同的 InstanceId {0} 再次建立工作階段。 + + + 指定的用戶端工作階段 InstanceId "{0}" 不符合現有工作階段的 InstanceId "{1}"。 + + + 開啟遠端工作階段失敗。 + + + 找不到用戶端 InstanceId 為 "{0}" 的指定遠端工作階段。 + + + 提示回應包含找不到的提示識別碼 "{0}"。 + + + 遠端主機對 "{0}" 的呼叫失敗。 + + + 未實作遠端主機方法 {0}。 + + + 不支援類型 {0} 的遠端主機方法資料編碼。 + + + 不支援類型 {0} 的遠端主機方法資料解碼。 + + + 不支援建立巢狀管線。 + + + 建立遠端工作階段時不支援相對 URI。 + + + 從遠端主機解碼資料時發生失敗。網路資料有錯誤。 + + + 只有系統管理員可以從遠端覆寫執行選項。 + + + PowerShell 認證要求: {0} + + + 警告: 遠端電腦 {0} 上的指令碼或應用程式正在要求您的認證。只有在您信任遠端電腦,以及提出要求的應用程式或指令碼時,才輸入您的認證。 + +{1} + + + 遠端電腦 {0} 上的指令碼或應用程式要求安全地讀取一行。只有在您信任遠端電腦,以及提出要求的應用程式或指令碼時,才輸入機密資訊,例如您的認證。 + + + 遠端電腦 {0} 上的指令碼或應用程式正在嘗試讀取 PowerShell 主機上的緩衝區內容。基於安全原因,不允許這項作業;已抑制此呼叫。 + + + 遠端電腦 {0} 上的指令碼或應用程式正在傳送提示要求。當系統提示您時,請僅在您信任遠端電腦,以及要求資料的應用程式或指令碼的情況下,才輸入機密資訊,例如您的認證或密碼。 + + + 收到不支援的遠端主機呼叫: {0}。 + + + 收到遠端資料,但動作不支援: {0}。 + + + 收到遠端資料,但不支援資料類型: {0}。 + + + 遠端資料遺漏目的地屬性。 + + + 遠端資料缺少目標介面屬性。 + + + 遠端資料缺少 Session InstanceId 屬性。 + + + 遠端資料缺少 RemotingDataType 屬性。 + + + 遠端資料缺少 CallId 屬性。 + + + 遠端資料遺漏 MethodName 屬性。 + + + 第一個片段未設定 IsStartFragment 旗標。 + + + 遠端資料缺少 {0} 屬性。 + + + 收到未預期的 ObjectId。如果遠端電腦未正確建構分段,或若資料已損毀或變更,就可能發生此情況。 + + + ObjectId 不可小於或等於 0。如果遠端電腦未正確建構片段,或資料已遭未經授權的使用者變更,就可能發生這種情況。 + + + 相同物件的 FragmentIDs 必須依序以 1 遞增變更。如果遠端電腦未正確建構片段,就可能發生這種情況。資料也可能已損毀或變更。 + + + 遠端資料太大,無法從片段重組。如果片段中的資料長度大於 Int32.Max,就可能發生此情況。如果資料已遭未經授權的使用者變更,也可能發生這種情況。 + + + 最後一個片段未設定 IsEndFragment 旗標。如果遠端電腦未正確建構分段,或資料已損毀或變更,就可能發生此情況。 + + + 還原序列化的遠端資料為 null。 + + + 片段 blob 長度超出範圍: {0} + + + 解碼 ErrorRecord 時發生錯誤。 + + + 解碼 PipelineStateInfo 時發生錯誤。 + + + 解碼 RunspaceStateInfo 時發生錯誤。 + + + 收到不支援的 RemotingTargetInterface 類型: {0} + + + 在未知的目標類別上叫用遠端主機方法: {0} + + + 叫用遠端主機方法時,未指定目標類別。 + + + 解碼 RunspacePoolStateInfo 時發生錯誤。 + + + 解碼 Minimum runspaces 時發生錯誤。 + + + 解碼 Maximum runspaces 時發生錯誤。 + + + 解碼 PowerShellStateInfo 時發生錯誤。 + + + 未預期的 {0} 屬性類型 (預期為 {1},實際收到 {2})。 + + + 未預期的遠端資料類型 (預期為 PSObject,實際收到 {0})。 + + + 未預期的已編碼命令類型 (預期為 PSObject,實際收到 {0})。 + + + 未預期的已編碼命令參數類型 (預期為 PSObject,實際收到 {0})。 + + + 解碼從遠端電腦接收的資料時發生錯誤。解碼從遠端電腦接收的還原序列化物件至少需要 {0} 位元組的資料。如果遠端電腦未正確建構分段,或資料已損毀或變更,就可能發生此情況。 + + + 收到的封包不是登入使用者的目的地:使用者 = {0},封包目的地 = {1}。 + + + 用戶端交涉計時器已到期。交涉逾時間隔為 {0} 毫秒。 + + + PowerShell 用戶端不支援伺服器所交涉的 {0} {1}。請確定伺服器與 PowerShell 的組建 {2} 和通訊協定版本 {3} 相容。 + + + {0}。與伺服器的交涉失敗。請確定伺服器與 PowerShell 的組建 {1} 和通訊協定版本 {2} 相容。 + + + 目的地伺服器已傳送關閉工作階段的要求。 + + + 執行 PowerShell 的伺服器不支援用戶端電腦所交涉的 {0} {1}。請確定用戶端電腦與 PowerShell 的組建 {2} 和通訊協定版本 {3} 相容。 + + + 執行 PowerShell 的伺服器不支援用戶端電腦所交涉的 {0} {1} 上的連線作業。請確定用戶端電腦與 PowerShell 的組建 {2} 和通訊協定版本 {3} 相容。 + + + 執行 PowerShell 的伺服器無法處理連線作業,因為找不到下列資訊或資訊無效: 用戶端功能資訊和 Connect RunspacePool 資訊。 + + + 執行 PowerShell 的伺服器無法處理連線作業,因為伺服器尚未啟動,或正在關機。 + + + 執行 PowerShell 的伺服器無法處理連線作業,因為伺服器 Runspace 集區屬性與用戶端電腦指定的屬性不符。 + + + {0}。與用戶端的交涉失敗。請確定用戶端與 PowerShell 的組建 {1} 和通訊協定版本 {2} 相容。 + + + 伺服器交涉計時器已到期。交涉逾時間隔為 {0} 毫秒。 + + + 用戶端電腦已傳送關閉工作階段的要求。 + + + 發生 PowerShell 無法處理的錯誤。遠端工作階段可能已結束。 + + + 伺服器未在指定的逾時期間內以加密的工作階段金鑰回應。 + + + 用戶端未在指定的逾時期間內傳回公開金鑰。 + + + 連線嘗試失敗。 + + + 正在嘗試關閉工作階段。 + + + PowerShell 無法正確關閉遠端工作階段。工作階段處於未定義狀態,因為它在中斷連線後並未開啟或連線。PowerShell 會嘗試強制在本機電腦上關閉工作階段,但遠端電腦上的工作階段可能無法關閉。若要正確關閉遠端工作階段,請先開啟或連線。 + + + 無法關閉工作階段。 + + + 工作階段已關閉。 + + + 不支援類型為 "{0}" 的等候控制代碼。 + + + 收到的資料具有 "{0}" 的串流識別碼索引。僅支援 "0" 的 Standard Output 串流識別碼索引。 + + + 標準輸入控制代碼未開啟。 + + + 原生 API 呼叫 WriteFile 失敗。錯誤碼為 {0}。 + + + 原生 API 呼叫 ReadFile 失敗。錯誤碼為 {0}。 + + + {0} 不是有效的結構描述值。有效的值為 "http" 和 "https"。 + + + 用戶端接收呼叫失敗。 + + + 用戶端傳送呼叫失敗。 + + + 從 WinRS API WSManRunShellCommand 傳回的命令控制代碼是 null。 + + + 無法將 Standard Input 控制代碼設定為 'no wait' 狀態。系統錯誤碼為 {0}。 + + + 連接埠號碼 {0} 不在有效值範圍內。有效值範圍介於 1 到 65535 之間。 + + + 伺服器處理程序已結束。 + + + 呼叫 Windows API GetStdHandle 以取得標準輸入控制代碼時發生錯誤,錯誤碼: {0}。 + + + 呼叫 Windows API GetStdHandle 以取得標準輸出控制代碼時發生錯誤,錯誤碼: {0}。 + + + 呼叫 Windows API GetStdHandle 以取得標準錯誤控制代碼時發生錯誤,錯誤碼: {0}。 + + + 連線至遠端伺服器 {0} 失敗。 + + + 連線至遠端伺服器 {0} 失敗,出現下列錯誤訊息: {1} + + + 關閉遠端伺服器殼層執行個體失敗,錯誤訊息如下: {0} + + + 傳送資料到遠端伺服器 {0} 失敗。 + + + 傳送資料至遠端伺服器 {0} 失敗,出現下列錯誤訊息: {1} + + + 從遠端伺服器 {0} 接收資料失敗。 + + + 處理來自遠端伺服器 {0} 的資料失敗,出現下列錯誤訊息: {1} + + + 在遠端伺服器上啟動命令失敗。 + + + 啟動遠端伺服器上的命令失敗,出現下列錯誤訊息: {0} + + + 重新連線至遠端伺服器上的命令失敗,出現下列錯誤訊息: {0} + + + 傳送資料到遠端命令失敗。 + + + 傳送資料到遠端命令失敗,錯誤訊息如下: {0} + + + 接收遠端命令的資料失敗。 + + + 處理遠端命令資料失敗,錯誤訊息如下: {0} + + + 呼叫方法 {1} 時發生錯誤代碼 {0} 的錯誤。 + + + {0}如需詳細資訊,請參閱 about_Remote_Troubleshooting 說明主題。 + + + 無法與遠端伺服器 {0} 中斷連線。 + + + 中斷與遠端伺服器的連線失敗,出現下列錯誤訊息: {0} + + + 重新連線至遠端伺服器失敗。 + + + 重新連線至遠端伺服器 {0} 失敗,出現下列錯誤訊息: {1} + + + 處理序間通訊 (IPC) 傳輸不支援連線作業。 + + + 遠端伺服器上不存在識別碼為 {0} 的 EndpointConfiguration。請連絡您的 PowerShell 系統管理員,或該端點設定的擁有者或建立者。 + + + 具有 {0} 識別碼的 EndpointConfiguration 在遠端電腦上不是有效的初始工作階段狀態。請連絡您的 PowerShell 系統管理員,或該端點設定的擁有者或建立者。 + + + 未為登錄機碼 {1} 指定強制值 {0}。 + + + 強制值 {0} 不是登錄機碼 {1} 的正確格式。預期格式為 'string'。 + + + "{0}" 必須指定副檔名為 ".ps1" 的 PowerShell 指令碼檔案。 + + + {0} 參數已在 {1} 區段中指定。請連絡您的系統管理員,確認 {0} 只指定一次。 + + + 預期在 "{2}" 元素中包含 "{0}" 和 "{1}" 屬性。 + + + 必須在 "{2}" 區段中指定 "{0}"、"{1}",才能動態載入組件。 + + + 無法載入 "{1}" 區段中指定的組件 "{0}"。 + + + 無法載入 "{1}" 區段中指定的類型 "{0}"。 + + + 必須在 "{2}" 區段中同時指定 "{0}" 和 "{1}"。 + + + 目的地 "{0}" 要求將連線重新導向至 "{1}"。不過,"{1}" 不是格式正確的 URI。 + + + {0}回報的重新導向位置: {1}。 + + + 您的連線已重新導向至下列 URI: "{0}" + + + {0} 若要自動連線到重新導向的 URI,請確認工作階段喜好設定變數 "{1}" 的 "{2}" 屬性,並在 Cmdlet 上使用 "{3}" 參數。 + + + 從遠端伺服器接收的資料,其目前還原序列化物件大小超過允許的物件大小上限。目前的還原序列化物件大小為 {0}。允許的物件大小上限為 {1}。 + + + 從遠端伺服器接收的資料總量超過允許的最大值。允許的最大值為 {0}。 + + + 從遠端用戶端電腦接收的資料,其目前還原序列化物件大小超過允許的物件大小上限。目前的還原序列化物件大小為 {0}。允許的物件大小上限為 {1}。 + + + 從遠端用戶端接收的資料總量超過允許的最大值。允許的最大值為 {0}。 + + + 執行啟動指令碼時擲回錯誤: {0}。 + + + 指定的 RemoteRunspaceInfo 物件有重複。 + + + 指定的 RemoteRunspaceInfo 物件已超過允許的上限。 + + + 開啟遠端工作階段時發生非預期的狀態。狀態 {0}。 + + + 指定的 URI {0} 無效。 + + + 已關閉 URI {0} 的遠端工作階段。 + + + ComputerName {0} 無法使用遠端工作階段。 + + + {0} 無法使用遠端工作階段。 + + + 遠端命令: {0},與識別碼為 "{1}" 的工作相關聯。 + + + 當指定 {1} 時,無法指定 {0}。 + + + FilePath 參數不支援萬用字元。請指定不含萬用字元的路徑。 + + + 指定為 FilePath 參數值的路徑不是來自 FileSystem 提供者。 + + + FilePath 參數的值必須是 PowerShell 指令碼檔案。請輸入副檔名為 .ps1 的檔案路徑,然後再次執行命令。 + + + 一或多個電腦名稱無效。如果您要傳遞 URI,請使用 -ConnectionUri 參數,或傳遞 URI 物件,而不是字串。 + + + 目前工作執行個體的狀態不適用於此作業。 + + + 命令找不到工作,因為找不到工作名稱 {0}。請確認 Name 參數的值,然後再次嘗試命令。 + + + 命令找不到執行個體識別碼為 {0} 的工作。請確認 InstanceId 參數的值,然後再次嘗試命令。 + + + 命令找不到工作識別碼為 {0} 的工作。請確認 Id 參數的值,然後再次嘗試命令。 + + + 命令無法移除工作識別碼為 {0} 且名稱為 {1} 的工作,因為工作尚未完成。若要移除工作,請先停止該工作,或使用 Force 參數。 + + + 命令無法移除工作識別碼為 {0} 的工作,因為工作尚未完成。若要移除工作,請先停止該工作,或使用 Force 參數。 + + + 命令無法移除工作識別碼為 {0} 且執行個體識別碼為 {1} 的工作,因為工作尚未完成。若要移除工作,請先停止該工作,或使用 Force 參數。 + + + 遠端命令: {0},與識別碼為 "{1}" 的工作相關聯。 + + + 該命令無法擷取指定電腦的工作。ComputerName 參數只能與使用 PowerShell 遠端執行功能建立的工作搭配使用。 + + + 工作階段參數只能與 PSRemotingJob 物件搭配使用。 + + + 名稱為 {0} 的遠端工作階段無法使用。 + + + 工作階段識別碼為 {0} 的遠端工作階段無法使用。 + + + {0} 不包含識別碼為 {1} 的項目。 + + + 命令無法移除工作,因為工作不存在,或因為它是子工作。子工作只能透過移除父工作來移除。 + + + {0} 不是參數 {1} 的有效值。值必須大於或等於 0。 + + + {0} 不能指定為 Proxy 驗證機制。Proxy 驗證僅支援 {1}、{2} 或 {3}。 + + + 使用下列 Proxy 存取類型時,無法指定 Proxy 認證: {0}。請指定不同的存取類型,或不要指定 Proxy 認證。 + + + 必須為工作階段選項 {1} 指定 {0} 值。 + + + 工作階段必須開啟。 + + + 主機不支援 Enter-PSSession 和 Exit-PSSession。 + + + 找到工作階段識別碼 {0} 的多個符合項目。 + + + 找到工作階段識別碼 {0} 的多個符合項目。 + + + 找到名稱 {0} 的多個符合項目。 + + + Enter-PSSession 失敗,因為遠端工作階段未提供必要的命令。 + + + 您無法從巢狀提示執行 Enter-PSSession。 + + + 連線至遠端電腦時允許的 WS-Man URI 重新導向數目上限 + + + 新遠端工作階段的預設工作階段選項 + + + 將載入到遠端電腦上的工作階段組態名稱 + + + 將建立遠端連線的 AppName + + + 包含啟動遠端工作階段的遠端使用者相關資訊。此變數只能從遠端工作階段使用。 + + + 必須同時指定 "{0}" 和 "{1}",或兩者都不指定。 + + + 找不到工作階段設定 "{0}"。 + + + 工作階段設定 "{0}" 不是以 PowerShell 為基礎的殼層。 + + + 工作階段設定 "{0}" 是以 PowerShell 為基礎的殼層。請使用 PowerShell 6+ 加以修改。 + + + 工作階段設定 "{0}" 是以 Windows PowerShell 為基礎的殼層。請使用 Windows PowerShell 加以修改。 + + + 沒有任何工作階段設定符合條件 "{0}"。 + + + {0} + + + 名稱: {0} + + + 名稱: {0}。這可讓系統管理員從遠端在此電腦上執行 PowerShell 命令。 + + + 無法刪除暫存檔案 {0}。失敗原因: {1}。 + + + 已成功註冊新的殼層,但 PowerShell 無法刪除暫存檔案 {0}。失敗原因: {1}。 + + + 無法將殼層設定資料寫入暫存檔案 {0}。失敗原因: {1}。 + + + 正在執行命令 "{0}" 以建立新工作階段設定。 + + + 名稱: {0} SDDL: {1}。這可讓所選使用者從遠端在此電腦上執行 PowerShell 命令。 + + + 正在執行命令 "{0}" 以移除工作階段設定。 + + + 正在執行命令 "{0}" 以取得以 PowerShell 為基礎的工作階段設定。 + + + 正在執行命令 "{0}" 以更新工作階段設定屬性。 + + + 名稱: {0} SDDL: {1} + + + 正在執行命令 "{0}" 以啟用工作階段設定。 + + + WinRM 快速設定 + + + 正在執行命令 "{0}",以使用 Windows 遠端管理 (WinRM) 服務啟用此電腦的遠端管理。 + 這包括: + 1. 啟動或重新啟動 WinRM 服務 (如果已啟動) + 2. 將 WinRM 服務的啟動類型設定為自動 + 3. 建立接聽程式,以接受任何 IP 位址的要求 + 4. 為 WS-Management 流量啟用 Windows 防火牆輸入規則例外 (僅限 HTTP)。 + +要繼續嗎? + + + 正在執行作業 "{0}"。 + + + 名稱: {0} SDDL: {1}。這可讓所選使用者從遠端在此電腦上執行 PowerShell 命令。 + + + 正在執行命令 "{0}" 以停用工作階段設定。 + + + 名稱: {0} SDDL: {1}。這會拒絕所有人存取此工作階段設定。 + + + 停用工作階段設定不會復原由 Enable-PSRemoting 或 Enable-PSSessionConfiguration Cmdlet 所做的所有變更。您可能必須依照下列步驟手動還原這些變更: + 1. 停止並停用 WinRM 服務。 + 2. 刪除接受任何 IP 位址上之要求的接聽程式。 + 3. 停用 WS-Management 通訊的防火牆例外。 + 4. 將 LocalAccountTokenFilterPolicy 的值還原為 0,這會限制電腦上系統管理員群組成員的遠端存取。 + + + 存取遭到拒絕。若要執行此 Cmdlet,請使用 [以系統管理員身分執行] 選項啟動 PowerShell。 + + + 正在重新啟動 WinRM 服務 + + + "Restart-Service" + + + 名稱: {0} + + + 必須重新啟動 WinRM 服務,才能顯示 SecurityDescriptor 選取的 UI。重新啟動 WinRM 服務,然後執行下列命令: "{0}" + + + 正在註冊工作階段設定 + + + 找不到工作階段設定 "{0}"。正在執行命令 "{1}" 以建立 "{0}" 工作階段設定。執行此命令會重新啟動 WinRM 服務。 + + + 不能同時指定 "{0}" 和 "{1}" 參數。請指定 "{0}" 或 "{1}" 參數。 + + + 此作業可能會重新啟動 WinRM 服務。要繼續嗎? + + + 無法處理節點類型為 "{0}" 的元素。只支援 {1} 和 {2} 節點類型。 + + + 可用的資料不足,無法處理 {0} 元素。 + + + 在 {2} 元素中,只能有兩個屬性,名稱分別為 "{0}" 和 "{1}"。 + + + {1} 元素中的節點類型 "{0}" 未知。{1} 元素中只預期 "{2}" 節點類型。 + + + 在 {1} 元素中,只能有一個名為 "{0}" 的屬性。 + + + 收到未知元素 "{0}"。如果遠端處理序意外關閉或結束,就可能發生這種情況。 + + + 不支援指定的驗證機制 "{0}"。此作業只支援 "{1}"。 + + + 在 "{0}" 找不到 pwsh 可執行檔。 +請注意,在 PowerShell 以其他應用程式裝載的情況下,依設計不支援 'Start-Job'。在這類情況下,建議改用 'ThreadJob' 模組。 + + + 無法從 64 位元 'pwsh' 安裝啟動 32 位元 'pwsh' 處理序。如果您需要在 32 位元處理序中執行 PowerShell,請安裝 32 位元 'pwsh'。 + + + 背景程序回報錯誤,訊息如下: {0}。 + + + 背景處理程序異常關閉或結束: {0}。 + + + 處理背景處理序中的資料時發生錯誤。已回報錯誤: {0}。 + + + 收到識別碼為 {0} 的非使用中命令資料。收到的資料: {1}。 + + + 不支援傳送 {0} 訊息到工作階段。只有 {0} 訊息可以傳送至命令。 + + + 用戶端未在指定的時間間隔內收到訊號作業的回應。當命令未及時回應 Stop 訊息時,就可能發生這種情況。 + + + 用戶端未在指定的時間間隔內收到 Close 作業的回應。當命令未及時回應 Stop 訊息時,就可能發生這種情況。 + + + 啟動背景處理序時發生錯誤。已回報錯誤: {0}。 + + + ThrottlingJob.AddChildJob 方法只接受處於 NotStarted 狀態的子工作。 + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="NotStarted"} + + + 在呼叫 ThrottlingJob.EndOfChildJobs 方法後,無法呼叫 ThrottlingJob.AddChildJob 方法。 + {StrContains="ThrottlingJob.AddChildJob"} +{StrContains="ThrottlingJob.EndOfChildJobs"} + + + {0}/{1} 已完成 + {0} is a placeholder for a number of completed child jobs +{1} is a placeholder for a total number of child jobs + + + 叫用巢狀管線需要有效的 Runspace。 + + + {1} 工作來源配接器擲回例外狀況,訊息如下: {0} + + + {1} 參數的值 {0} 無效。唯一允許的值是 5.1。 + + + Wait 和 Keep 參數不能在同一個命令中同時使用。 + + + 未使用 Wait 參數時,無法使用 WriteEvents 參數。 + + + PowerShell 7+ 不支援 PowerShell 遠端端點版本設定。 + + + 無法具現化下列類型,因為其建構函式不是公用的: {0}。 + + + 無法執行工作作業 (Create、Get 或 Remove),因為 JobDefinition 中指定的 JobSourceAdapter 類型尚未註冊。請使用明確呼叫,或呼叫 Import-Module Cmdlet,然後指定組件來註冊 JobSourceAdapter 類型。 + + + 無法建立工作,因為 JobInvocationInfo 不包含 JobDefinition。請使用 JobDefinition 啟動 JobInvocationInfo。 + + + 目前工作執行個體的狀態為 {0}。此狀態不適用於嘗試的作業。{1} + + + 無法將公作 "{0}" 連線到遠端伺服器。 + + + Runspace 識別碼 = {0}的 Disconnect-PSSession 作業失敗。 + + + 工作階段 {0} 的連線作業失敗。Runspace 狀態為 {1},而不是 Opened。 + + + 電腦 "{0}" 的 Disconnected PSSession 查詢失敗。 + + + 無法連接 PSSession "{0}",因為它不是處於中斷連線狀態,或無法供連線使用。 + + + 工作階段連線不支援目標 "{1}" 上的 PSSession "{0}",因為目標電腦類型為 "{2}"。 + + + 無法中斷 PSSession "{0}" 的連線,因為它不是處於已開啟狀態。 + + + 工作階段中斷連線不支援目標 "{1}" 上的 PSSession "{0}",因為目標電腦類型為 "{2}"。 + + + Receive-PSSession 不支援目標 "{1}" 上的 PSSession "{0}",因為目標電腦類型為 "{2}"。 + + + 命令無法完成,因為 ChildJobs 屬性包含無效的值。 + + + 無法暫停識別碼為 {0} 的工作。某些工作類型不支援暫停工作。如需有關暫停工作的支援詳細資訊,請參閱該工作類型的說明主題。 + + + 無法繼續識別碼為 {0} 的工作。某些工作類型不支援恢復工作。如需有關恢復工作的支援詳細資訊,請參閱該工作類型的說明主題。 + + + 您無法在同一個命令中同時將 Invoke-Command Cmdlet 與 AsJob 和 Disconnected 參數搭配使用。 + + + {0} 的遠端工作階段查詢失敗,錯誤訊息如下: {1} + + + 嘗試建立識別碼為 {0} 的工作。現在無法建立這個識別碼的工作。請確認這個識別碼是否已經在這部電腦上指派過一次。 + + + 無法建立識別碼為 {0} 的工作;這不是有效的識別碼。請為工作識別碼提供大於 0 的整數。 + + + 提供的 JobIdentifier 不可為 null。請提供有效的 JobIdentifier。 + + + Wait-Job Cmdlet 無法完成工作,因為一或多個工作已被封鎖,正在等候使用者互動。 請使用 Receive-Job Cmdlet 處理互動式工作的輸出,然後再試一次。 + + + 遠端工作階段 {0} 無法連線,也無法從伺服器移除。用戶端遠端工作階段物件將從伺服器移除,但伺服器上遠端工作階段的狀態不明。 + + + Runspace 識別碼 = {0} 的 Disconnect-PSSession 作業失敗,原因如下: {1} + + + 作業 "{0}" 無法連線到伺服器,因此無法停止。 + + + 命令找不到 InstanceId 值為 "{0}" 的 PSSession。 + + + 命令找不到名稱為 "{0}" 的 PSSession。 + + + Windows 預先安裝環境 (WinPE) 不支援 PowerShell 遠端處理。 + + + {0} 所做的變更必須等到 WinRM 服務重新啟動後才會生效。 + + + {0} 如果最近已取消註冊使用此名稱的設定,可能需要重新啟動 WinRM 服務,因為某些系統資料結構可能仍在快取中。在那樣的情況下,可能需要重新啟動 WinRM。 +所有連線至 PowerShell 工作階段設定 (例如 Microsoft.PowerShell,以及使用 Register-PSSessionConfiguration Cmdlet 建立的工作階段設定) 的 WinRM 工作階段都會中斷連線。 + + + 您正在遠端工作階段中執行,且已選取 Force 選項,這表示 WinRM 服務可能會重新啟動。如果 WinRM 服務重新啟動,此遠端工作階段就會終止,而您需要建立新的工作階段才能繼續 + + + 嘗試儲存識別碼時,工作為 null。請指定工作以儲存其識別碼。 + + + 找不到此 PSSession 的執行中命令。 + + + 未安裝 Windows PowerShell 2.0 所需的 Microsoft .NET Framework 2.0。請安裝 .NET Framework 2.0,然後重試。 + + + 遠端管線失敗。 + + + 遠端管線失敗,原因如下: {0} + + + 無法繼續一或多個工作,因為狀態對此作業無效。 + + + 執行用戶端方法的遠端 Runspace 未指定用戶端電腦。 + + + 名稱: {0} SDDL: {1}。這會拒絕此工作階段設定的遠端存取權。 + + + 已啟用: False。這會將 WS-Management 服務設定為拒絕連線要求。 + + + 已啟用: True。這會將 WS-Management 服務設定為接受連線要求。 + + + 套用到工作階段時要定義的別名 + + + 套用到工作階段時要載入的組件 + + + 此文件的作者 + + + 套用到工作階段時要使用的 CLR 版本 + + + 與此文件相關聯的公司 + + + 此文件的著作權聲明 + + + 這些設定所提供功能的描述 + + + 套用到工作階段時要定義的環境變數 + + + 套用到工作階段時要使用的執行原則 + + + 套用到工作階段時要載入的格式檔案 (.ps1xml) + + + 套用到工作階段時要定義的函式 + + + 用於唯一識別此文件的識別碼 + + + 此工作階段設定要套用的工作階段類型預設值。可以是 'RestrictedRemoteServer' (建議)、'Empty' 或 'Default' + + + 放置此工作階段設定的工作階段文字記錄的目錄 + + + 是否要以電腦的 (虛擬) 系統管理員帳戶執行此工作階段設定 + + + 套用到工作階段時要使用的語言模式。可以是 'NoLanguage'(建議)、'RestrictedLanguage'、'ConstrainedLanguage' 或 'FullLanguage' + + + 套用到工作階段時要匯入的模組 + + + 套用到工作階段時要使用的 PowerShell 引擎版本 + + + 套用到工作階段時要使用的處理器架構 + + + 此文件所使用的結構描述版本號碼 + + + 套用到工作階段時要執行的指令碼 + + + 套用到工作階段時要新增的類型 + + + 套用到工作階段時要載入的輸入檔案 (.ps1xml) + + + 套用到工作階段時要定義的變數 + + + 使用者角色 (安全性群組),以及套用到工作階段時應套用到這些群組的角色功能 + + + 套用到工作階段時要設為可見的別名 + + + 套用到工作階段時要設為可見的 Cmdlet + + + 無法剖析 '{0}' 的可見命令定義。可見命令定義必須是具有 'Name' 和 'Parameters' 索引鍵的雜湊表。'Parameters' 索引鍵的值必須是具有 'Name' 索引鍵的雜湊表集合,並且可選擇使用 'ValidateSet' 或 'ValidatePattern'。 + + + 套用到工作階段時要設為可見的函式 + + + 套用到工作階段時要設為可見的提供者 + + + 套用到工作階段時要顯示的外部命令 (指令碼和應用程式) + + + PSSession 組態檔路徑 '{0}' 無效。路徑引數必須解析為檔案系統中的單一檔案,且副檔名必須是 '.pssc'。請修正路徑規格,然後再試一次。 + + + 角色功能檔案路徑 '{0}' 無效。路徑引數必須解析為檔案系統中的單一檔案,且副檔名必須是 '.psrc'。請修正路徑規格,然後再試一次。 + + + 'Roles' 項目必須是雜湊表,但實際上是 {0}。 + + + 無法將 '{0}' 角色項目的值轉換成雜湊表。'Roles' 項目必須是以群組名稱作為索引鍵的雜湊表,其中與每個索引鍵相關聯的值,都是該角色的工作階段設定屬性所構成的另一個雜湊表。 + + + 找不到角色功能 '{0}'。角色功能必須是目前模組路徑中模組內 'RoleCapabilities' 目錄中的檔案 '{1}'。 + + + 找不到要匯入的模組路徑。ModulesToImport 參數 {0} 的值不存在,或不是模組目錄。請更正值,然後再次執行命令。 + + + 未載入指定的組態檔 '{0}',因為找不到有效的組態檔。 + + + 已成功中斷電腦 {0} 的連線。 + + + 重新連線到 {0} 失敗。正在嘗試中斷工作階段的連線... + + + 正在嘗試重新連線至 {0}... + + + 與 {0} 的網路連線已中斷,重新連線嘗試已失敗。請修復網路連線,然後使用 Connect-PSSession 或 Receive-PSSession 重新連線。 + + + {0} 的網路連線已中斷。正在嘗試重新連線,最多 {1} 分鐘... + + + {0} 的網路連線已還原。 + + + {0} 驗證需要明確的使用者名稱和密碼。 請使用 -Credential 參數指定使用者名稱和密碼,然後再次嘗試命令。 + + + 在 Unix 上,HTTP 不支援基本驗證。 + + + 找不到名稱為 {0} 的已排程工作。 + {0} is the job definition name + + + 找到多個名稱為 {0} 的工作定義。請嘗試在 Start-Job 中加入 -DefinitionType 參數,以便將工作定義的搜尋範圍縮小為單一工作來源配接器。 + + + 組態檔中沒有 'SchemaVersion' 成員。此成員必須存在,且值必須是格式為 'n.n.n.n' 的版本號碼。請將遺漏的成員新增至檔案 {0}。 + + + 成員 '{0}' 必須是字串。請在檔案 {1} 中將成員變更為正確的類型。 + + + 成員 '{0}' 必須是字串陣列。請在檔案 {1} 中將成員變更為正確的類型。 + + + 成員 '{0}' 必須是雜湊表。請在檔案 {1} 中將成員變更為正確的類型。 + + + 成員 '{0}' 必須是雜湊表陣列。請在檔案 {1} 中將成員變更為正確的類型。 + + + 成員 '{0}' 不是有效的索引鍵。請將成員變更為檔案 {1} 中的有效索引鍵。 + + + 成員 '{0}' 必須是有效的列舉型別 "{1}"。有效的列舉值為 "{2}"。請在檔案 {3} 中將成員變更為正確的類型。 + + + 剖析設定檔 {0} 時發生錯誤,訊息如下: {1} + + + 未使用 -Wait 參數時,無法使用 -WriteJobInResults 參數 + + + 成員 '{0}' 不是絕對路徑 {1}。請將成員變更為檔案 {2} 中的絕對路徑。 + + + 成員 '{0}' 中的索引鍵 '{1}' 無效。請變更檔案 {2} 中的索引鍵。 + + + 成員 '{0}' 必須包含必要的索引鍵 '{1}'。請將必要的索引鍵新增至檔案 {2}。 + + + 索引鍵 '{0}' 包含無效的延伸模組 {1}。請從下列清單中指定延伸模組: {{{2}}}。 + + + 成員 '{0}' 中的索引鍵 '{1}' 必須是指令碼區塊。請在檔案 {2} 中將索引鍵變更為正確的類型。 + + + 工作階段組態檔 {0} 無效。請指定有效的工作階段組態檔,然後再試一次命令。 + + + 網路連線中斷 + + + 正在嘗試重新連線至 {0}... + + + 已建立工作 {0} 以便重新連線。 + + + 已成功中斷電腦 {2} 上執行個體識別碼為 {1} 的工作階段 {0}。 + + + 已建立用於重新連線的工作階段 {0},其執行個體識別碼為 {1}。 + + + SessionName 參數只能搭配 Disconnected 開關參數使用。 + + + 嘗試連接 PSSession 時失敗。 + + + 嘗試連線到目標虛擬機器時發生失敗。 + + + 嘗試連線到目標容器時發生失敗。 + + + PSSession 處於中斷連線狀態,無法用於連線。 + + + 此電腦上沒有適用於 PowerShell 的 Hyper-V 模組。 + + + 無法在識別碼為 {1} 的容器內啟動 PowerShell 處理序 ({0}),錯誤為: {2}。 + + + 此電腦上可能未啟用容器功能。 + + + 無法在識別碼為 {1} 的容器內終止識別碼為 {0} 的 PowerShell 處理序。 + + + 輸入的 ContainerId {0} 不存在,或對應的容器未執行。 + + + 輸入的 VMId 參數無法解析為單一虛擬機器。 + + + 輸入的 VMId {0} 無法解析為單一虛擬機器。 + + + 輸入的 VMName 參數無法解析為任何虛擬機器。 + + + 輸入的 VMName 參數可解析為多部虛擬機器。 + + + 輸入的 VMName {0} 無法解析為單一虛擬機器。 + + + 虛擬機器 {0} 未在執行狀態中。 + + + 認證無效。 + + + 輸入使用者名稱不可為空白。 + + + 無法進入工作階段 {0},因為它不是處於中斷連線狀態,或無法供連線使用。請使用 Get-PSSession -ComputerName {1} -InstanceId {2} 擷取遠端工作階段。 + + + 無法進入工作階段 {0},因為它不是處於中斷連線狀態,或無法供連線使用。請使用 Connect-PSSession 或 Receive-PSSession 重新連線。 + + + 與 {0} 的網路連線已中斷,重新連線嘗試失敗。請修復網路連線,然後使用 Connect-PSSession 或 Receive-PSSession 重新連線。 + + + 因為 SetSocketOption 失敗,所以無法建立 RemoteSessionHyperVSocketClient 的執行個體。 + + + 無法建立 RemoteSessionHyperVSocketServer 的執行個體。 + + + 已取消重新連線嘗試。請修復網路連線,然後使用 Connect-PSSession 或 Receive-PSSession 重新連線。 + + + 無法暫停一或多個工作,因為狀態對此作業無效。 + + + -AutoRemoveJob 參數必須搭配 -Wait 參數使用 + + + WS-Management 服務無法處理該要求。在 {0} 電腦上的 WSMan: 磁碟機中找不到 {1} 工作階段設定。如需詳細資訊,請參閱 about_Remote_Troubleshooting 說明主題。 + + + 無法從 {0} 規格建立工作,因為所提供的 runspace 不是本機 runspace。請改用本機 runspace,或指定 RunspaceMode 引數。 + + + 無法中斷工作階段 {0},因為指定的閒置逾時值 {1} (秒) 大於伺服器允許的上限 {2} (秒),或小於允許的下限 {3} (秒)。 請指定在允許範圍內的閒置逾時值,然後再試一次。 + {0} is a placeholder for the session name +{1} is a placeholder for the provided idletimeout value +{2} is a placeholder for the maximum allowed idletimeout value +{3} is a placeholder for the minimum allowed idletimeout value + + + 指定的 IdleTimeout 工作階段選項 {0} (秒) 不是有效的期間。 請指定大於或等於允許最小值 {1} (秒) 的 IdleTimeout 值。 + {0} is a placeholder for the provided idletimeout +{1} is a placeholder for the minimum allowed idletimeout value + + + 在工作階段設定檔中指定 "{2}"、"{3}"、"{4}" 或 "{5}" 索引鍵時,不能存在 Cmdlet "{0}" 或別名 "{1}"。 + + + 「傳輸選項無效。只有當參數 "{0}" 設定為 true 時,參數 "{1}" 才可以是非零值。」 + + + 成員 '{0}' 必須是由字串或雜湊表元素組成的陣列。 + + + 成員 '{0}' 必須是由字串或雜湊表元素組成的陣列。請在檔案 {1} 中將成員變更為正確的類型。 + + + 無法擷取工作定義 '{0}',因為路徑 '{1}' 參考的是 '{2}' 提供者路徑。 請將路徑參數變更為檔案系統路徑。 + {0} is job definition name +{1} is the user provided path +{2} is the path provider + + + 無法擷取工作定義 '{0}',因為路徑 '{1}' 會解析為多個檔案路徑。 請將路徑參數變更為單一路徑。 + {0} is job definition name +{1} is the user provided path + + + 找不到類型為 {0} 且名稱為 {1} 的已排程工作。 + {0} is the job definition type and {1} is the job definition name. + + + 找不到 WorkingDirectory 路徑 {0}。 + + + 無法連接到工作階段 {0}。 該工作階段已不再存在於電腦 {1} 上。 + {0} is the session name that cannot be found. +{1} is the computer name where the session was. + + + 工作階段 {0} 的連線作業失敗,錯誤訊息如下: {1} + + + -Force 參數必須搭配 -Wait 參數使用。 + + + 一或多個工作處於暫停或已中斷連線狀態,且沒有其他使用者輸入就無法繼續。 請指定 -Force 參數,以繼續並移至已完成、失敗或已停止狀態。 + + + 在 PowerShell 工作階段設定中啟用 RunAs 時,Windows 安全性模型無法在使用此端點建立的不同使用者工作階段之間強制執行安全性界限。請確認 PowerShell runspace 設定只限制為必要的 Cmdlet 和功能。 + + + 已透過新增 Force 參數成功暫停工作。 + + + 工作階段組態檔 {0} 無效。請指定有效的工作階段組態檔,然後再試一次命令。剖析組態檔時發生錯誤: {1}。 + + + Register-PSSessionConfiguration: {1} 中的 '{0}' 索引鍵。工作階段設定檔包含無效的值。請更正檔案,然後再次執行命令。 + + + 只有在遠端電腦執行 PowerShell 3.0 或更新版本時,才支援中斷連線的工作階段。 + + + Cmdlet 的記憶體使用量已超過警告層級。若要避免此情況,請嘗試下列其中一項: 1) 降低 CIM 作業產生資料的速率 (例如,將較低的值傳遞給 ThrottleLimit 參數),2) 提高下游 Cmdlet 消耗資料的速率;或 3) 使用 Invoke-Command Cmdlet 在伺服器上執行整個管線。下列命令列啟動了記憶體使用量超過警告層級的 Cmdlet: {0} + + + PSSession {0} 是使用 EnableNetworkAccess 參數建立的,只能從本機電腦重新連線。 + + + 無法啟動作業。此工作階段的語言模式與全系統的語言模式不相容。 + + + 無法建立 runspace。此組態的語言模式與全系統的語言模式不相容。 + + + 無法結束巢狀管線,因為管線不在巢狀狀態。 + + + PowerShell 伺服器工作階段不是執行巢狀命令的有效狀態。 此工作階段中無法執行任何巢狀命令。 + + + 無法在遠端工作階段上叫用巢狀命令,因為已有巢狀命令正在執行。 + + + 遠端工作階段無法叫用命令 {0},錯誤如下: {1}。 + + + 遠端工作階段命令目前已在偵錯工具中停止。 使用 Enter-PSSession Cmdlet 以互動方式連線到遠端工作階段,並自動進入主控台偵錯工具。 + + + 您連線的遠端工作階段不支援遠端偵錯。您必須連線到執行 PowerShell 4.0 或更新版本的遠端電腦。 + + + 因為工作階段 {0}、{1}、{2} 的工作階段狀態不是 Open,所以您無法在該工作階段中執行命令。 工作階段狀態為 {3}。 + + + 未指定有效的工作階段。 請確認您提供的是處於 Opened 狀態且可用來執行命令的有效工作階段。 + + + 工作階段 {0}、{1}、{2} 無法用來執行命令。 工作階段可用性為 {3}。 + + + 無法執行命令,因為 ChildJobs 屬性為空白。 + + + 無法偵錯工作,因為沒有可用的 PowerShell 主機偵錯工具。 請確定您是在支援偵錯的主機中執行此命令。 + + + 找不到識別碼為 {0} 的工作。 + + + 找不到執行個體識別碼為 {0} 的工作。 + + + 找不到名稱為 {0} 的工作。 + + + 無法偵錯工作,因為沒有可用的主機 UI。 請確定您是在實作 PSHostUserInterface 的 PowerShell 主機中執行此命令。 + + + 無法偵錯工作,因為主機偵錯工具模式設定為 None 或 Default。 主機偵錯工具模式必須是 LocalScript 和/或 RemoteScript。 + + + 找到多個識別碼為 {0} 的工作。 Debug-Job 一次只能偵錯一個工作。 + + + 找到多個名稱為 {0} 的工作。 Debug-Job 一次只能偵錯一個工作。 + + + 用於處理序附加的具名管道伺服器接聽程式已在執行中。 + + + Enter-PSHostProcess 不支援進入它正在執行的相同 PowerShell 工作階段。 + + + 找到多個具有此名稱的處理序 {0}。請使用處理序識別碼來指定要進入的單一處理序。 + + + 無法進入識別碼為 '{0}' 的處理序,因為它尚未載入 PowerShell 引擎,或已停用具名管道接聽程式。 + + + 找不到識別碼為 {0} 的處理序。 + + + 找不到名稱為 {0} 的處理序。 + + + 找不到具有 CustomPipeName: {0} 的具名管道。 + + + 無法處理命令,因為指定的 pipeName 太長。此平台上的管道名稱長度最多可為 {0} 個字元。您的管道名稱 '{1}' 長度為 {2} 個字元。 + + + 目前的主機不支援 Enter-PSHostProcess Cmdlet。 + + + 「具名管道目標處理序已結束。」 + + + 「Hyper-V 通訊端目標處理序已結束。」 + + + {0}[處理序:{1}]: {2} + + + {0}[{1}]: {2} + + + 無法連線到處理序 {1} 的應用程式網域名稱 {0}。 錯誤: {2}。 + + + 無法連線到名稱為 {0} 的管道。 錯誤: {1}。 + + + PowerShell 外掛程式無法處理連線作業,因為必要的交涉資訊遺失或不完整。 + + + PowerShell 外掛程式無法處理連線作業。 + + + 提供的外掛程式內容無效。 + + + Powershell 外掛程式在處理 {0} 引數時發生嚴重錯誤。 + + + 提供的命令內容無效。 + + + 提供的輸入資料無效。僅支援類型為 {0} 的輸入資料。 + + + 提供的輸入資料流無效。只支援 {0} 作為輸入資料流。 + + + 提供的輸出資料流集合無效。只支援 {0} 作為輸出資料流。 + + + 提供的 WSMAN_SENDER_DETAILS 無效。無法處理 Null WSMAN_SENDER_DETAILS。 + + + 提供的殼層內容無效。 + + + {0} + + + 外掛程式方法 {1} 中的 {0} 不允許為 NULL 值。 + + + 輸入資料流與輸出資料流集合不允許為 NULL 值。{0} 和 {1} 是支援的輸入與輸出資料流。 + + + 外掛程式方法 {1} 中的 {0} 不允許為 NULL 值。 + + + 外掛程式方法 {1} 中的 {0} 不允許為 NULL 值。 + + + PowerShell 外掛程式作業正在關閉。如果主控服務或應用程式正在關閉,就可能發生此情況。 + + + PowerShell 外掛程式無法理解選項 {0}。請確定用戶端與 PowerShell 的組建 {1} 和通訊協定版本 {2} 相容。 + + + 用戶端必須提供名稱為 {0} 的選項。請確定用戶端與 PowerShell 的組建 {1} 和通訊協定版本 {2} 相容。 + + + <PSProtocolVersionError ServerProtocolVersion="{0}" ServerBuildVersion="{1}">PowerShell 外掛程式不支援用戶端要求的通訊協定版本 {2}。</PSProtocolVersionError> + + + PowerShell 外掛程式向 WSMan 服務回報內容時發生嚴重錯誤。 + + + 無法建立受控伺服器工作階段。 + + + PowerShell 外掛程式在註冊用於關閉通知的等候控制代碼時發生嚴重錯誤。 + + + 無法進入 Runspace,因為此工作階段中已推入 Runspace。 + + + 無法進入 Runspace,因為沒有可用的伺服器遠端偵錯工具。 + + + 無法進入 Runspace,因為它不是遠端 Runspace。 + + + 遠端傳輸錯誤: {0} + + + 無法在容器中開啟 PowerShell 的管道連線。錯誤碼: {0}。 + + + 無法建立 PowerShell IPC 具名管道。錯誤碼: {0}。 + + + 在與具名管道建立連線前,逾時已到期。 + + + WSMan 初始化失敗,錯誤碼為: {0}。 + + + 在伺服器模式中無法啟動具名管道伺服器。 + + + 無法將遠端存取權授與 '{0}':'{1}'。工作階段設定已登錄,但此群組沒有存取權。若要解決此錯誤,請提供有效的群組名稱,然後重新登錄工作階段設定。 + + + 無法取得工作階段設定 '{0}' 的工作階段功能:此設定未使用工作階段設定檔 (.pssc) 註冊,例如由 New-PSSessionConfigurationFile Cmdlet 建立的設定檔。 + + + 無法解析使用者名稱 '{0}'。請確認使用者名稱,然後再試一次。 + + + 與電腦的 (虛擬) 系統管理員帳戶相關聯的群組 + + + 無法建立或開啟設定工作階段 {0}。 + + + 強制執行指令碼輸入參數驗證。指定 MountUserDrive 時會自動啟用此功能。 + + + 在工作階段中建立 'User' PSDrive,以便在檔案系統提供者不可見時搭配 Copy-Item 使用。 + + + 成員 '{0}' 必須是布林值。請在檔案 {1} 中將成員變更為正確的類型。 + + + 成員 '{0}' 必須是整數。請在檔案 {1} 中將成員變更為正確的類型。 + + + 處理使用者磁碟機時擲回錯誤 {0}。 + + + 使用 MountUserDrive 參數建立的使用者磁碟機的選擇性最大位元組大小。User drive 的預設大小上限為 50 MB。 + + + 找不到檔案系統提供者。 + + + 設定將使用的群組受控服務帳戶名稱 + + + 無效的群組受控服務帳戶名稱。帳戶名稱必須符合 'DomainName\UserName' 格式。 + + + 需要具有成員資格的群組帳戶才能使用此工作階段。 + + + 無法剖析 SDDL 字串,因為其中包含不成對的括號: {0}。 + + + RequiredGroups 屬性雜湊表只能包含一個索引鍵。 + + + RequiredGroups 屬性不是名稱/值組雜湊表格式。 這必須是下列格式的雜湊表 (使用 PowerShell 語法): RequiredGroups = @{ Or = 'Administrators' }。 + + + 必要群組設定中有未知的索引鍵。 必要群組雜湊表只能包含 'And' 和 'Or' 這類邏輯成員資格分組的雜湊鍵。 + + + 必要群組設定中有未知的值。 必要的群組雜湊表只能包含群組名稱或其他邏輯雜湊表的值。 + + + ACE {0} 格式不正確。 一般 ACE 必須正好有 6 個區段。 + + + 無法建立工作階段使用者磁碟機,因為目前的使用者名稱包含無效的檔案路徑字元。 + + + 無效的角色功能金鑰: {0}。請確定角色功能名稱拼字正確,而且是有效的工作階段設定屬性。 + + + 無效的角色功能金鑰類型: {0}。角色功能金鑰必須是可識別有效工作階段設定屬性的字串。 + + + 無效的角色金鑰類型: {0}。角色金鑰必須是可識別安全性群組的字串。 + + + 其他可能的原因: + -指定的認證未包含網域或電腦名稱,例如: DOMAIN\UserName 或 COMPUTER\UserName。 + + + 無法啟動遠端連線所需的 SSH 用戶端處理序,錯誤為: {0}。 + + + 找不到指定的關鍵檔案 {0}。 + + + SSH 用戶端工作階段已結束,錯誤訊息如下: {0} + + + SSH 連線嘗試在逾時後失敗: {0} 秒。 + + + +SSH 用戶端處理序在建立連線之前就已終止。 + + + 提供的 SSHConnection 雜湊表缺少必要的 ComputerName 或 HostName 參數。 + + + 提供的 SSHConnection 雜湊表參數名稱或元素為 null 或空白。 + + + 不支援提供的 SSHConnection 雜湊表參數 {0}。 + + + 提供的 SSHConnection 雜湊表同時包含 ComputerName 和 HostName 參數。 只可指定一個。 + + + 提供的 SSHConnection 雜湊表同時包含 KeyFilePath 和 IdentityFilePath 參數。 只可指定一個。 + + + 找不到提供的角色功能檔案 {0}。 + + + 提供的角色功能檔案 {0} 沒有必要的 .psrc 副檔名。 + + + SSH 傳輸處理程序突然終止,導致此遠端工作階段中斷。 + + + PowerShell 6+ 不支援 WOW64。二進位檔必須與處理器架構相符。 + + + 找不到 "{0}" 可執行檔。請確認已安裝 WOW64 功能。 + + + 無法將外掛程式 {0} 安裝到目錄 {1}。 + + + PowerShell 缺少 WinRM 外掛程式 DLL {0}。請執行 Enable-PSRemoting,然後重試此命令。 + + + 此參數集需要 WSMan,但找不到支援的 WSMan 用戶端程式庫。WSMan 可能未安裝,或此系統無法使用。 + + + + 結束代碼: {0} + Stdout: '{1}' + Stderr: '{2}' + + + + 無法讀取處理序的相關資訊: '{0}'。 + + + 主機系統沒有正確版本的 Hyper-V 架構。 + + + Unix 上的 HTTPS 目前不支援 CA 或 CN 檢查。如果您確定信任要連線的伺服器以及兩者之間的網路,請使用 PSSessionOption -SkipCACheck 和 -SkipCNCheck。 + + + 已針對 PowerShell 6+ 組態停用 PowerShell 遠端功能,而且不會影響 Windows PowerShell 遠端組態。在 Windows PowerShell 中執行此 Cmdlet,會影響所有 PowerShell 遠端組態。 + + + + 已針對 PowerShell 6+ 組態啟用 PowerShell 遠端功能,而且不會影響 Windows PowerShell 遠端組態。在 Windows PowerShell 中執行此 Cmdlet,會影響所有 PowerShell 遠端組態。 + + + 因為正在強制執行應用程式控制原則,例如 'AppLocker' 或 'Windows Defender Application Control',所以已停用 Enter-PSHostProcess Cmdlet。 + + + 遠端偵錯工具例外狀況: {0},錯誤訊息: {1} + + + 無法建立 Windows PowerShell 處理序,因為在此機器上找不到 Windows PowerShell。 + + + Create 的 Runspace 引數必須是非 Null 的 RemoteRunspace 物件。 + + + 工作階段設定雜湊表包含無效的索引鍵類型。索引鍵應為字串類型。 + + + 工作階段設定檔包含不支援的組態選項: {0}。這是遠端端點設定選項,不適用於 PowerShell 工作階段狀態。 + + + 工作階段設定檔包含未知的組態選項: {0}。 + + + 運算式評估可能失敗 + + + 從指令碼區塊建立 PowerShell 物件可能需要評估指令碼區塊中的一些運算式。除非運算式代表常數值,否則在受限語言模式下,運算式評估會悄悄失敗,並傳回 'null'。 + + + 無法取得 Hyper-V VM 狀態。值的類型為 {0},但預期為 Microsoft.HyperV.PowerShell.VMState 或 System.String。 + + + Hyper-V {0} 在連線交涉期間傳送了無效的 {1} 回應。 + + + 與 Hyper-V 建立安全連線時失敗。請確定主機和來賓已套用所有相關的 Microsoft 更新。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/RunspaceInit.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/RunspaceInit.zh-Hant.resx new file mode 100644 index 00000000000..acfb5605bb6 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/RunspaceInit.zh-Hant.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 + + + Variable to hold the enabled experimental feature names + + + Parent folder of the host application of the current runspace + + + Folder containing the current user's profile + + + A reference to the host of the current runspace + + + The run objects available to cmdlets + + + Version information for current PowerShell session + + + Current process ID + + + Status of last command + + + Parent process ID + + + The ShellID identifies the current shell. This is used by #Requires. + + + Name of the current console file + + + The text encoding used when piping text to a native executable file + + + The text encoding used when reading output text from a native executable file + + + Configuration controlling how text is rendered. + + + Variable to contain the name of the email server. This can be used instead of the HostName parameter in the Send-MailMessage cmdlet. + + + Dictates when confirmation should be requested. Confirmation is requested when the ConfirmImpact of the operation is equal to or greater than $ConfirmPreference. If $ConfirmPreference is None, actions will only be confirmed when Confirm is specified. + + + Dictates the action taken when a Debug message is delivered + + + Dictates the action taken when an error message is delivered + + + Dictates the action taken when progress records are delivered + + + Dictates the action taken when a Verbose message is delivered + + + Dictates the action taken when a Warning message is delivered + + + Dictates the action taken when a command generates an item in the Information stream + + + Dictates the view mode to use when displaying errors + + + Dictates what type of prompt should be displayed for the current nesting level + + + If true, $ErrorActionPreference applies to native executables, so that non-zero exit codes will generate cmdlet-style errors governed by error action settings + + + If true, WhatIf is considered to be enabled for all commands. + + + Dictates how arguments are passed to native executables. + + + Dictates the limit of enumeration on formatting IEnumerable objects + + + Displays errors with a stack trace + + + Displays errors with inner exceptions + + + Displays errors with their sources + + + Displays errors with a description of the error class + + + Culture of the current PowerShell session + + + UI culture of the current PowerShell session + + + Variable to hold all default <cmdlet:parameter, value> pairs + + + Press Enter to continue... + + + Edition information for the current PowerShell session + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/RunspacePoolStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/RunspacePoolStrings.zh-Hant.resx new file mode 100644 index 00000000000..5d544775de2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/RunspacePoolStrings.zh-Hant.resx @@ -0,0 +1,165 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 集區大小上限不得小於 1。 + + + 集區大小下限不得小於 1。 + + + 集區大小下限不能大於集區大小上限。 + + + Runspace 集區的狀態不適用於此作業。 + + + 無法執行作業,因為 Runspace 集區不處於 '{0}' 狀態。目前的狀態為 '{1}'。 + + + 無法開啟 Runspace 集區,因為它不處於 'BeforeOpen' 狀態。目前的狀態為 '{0}'。 + + + {0} 物件不是透過在目前的 RunspacePool 執行個體上呼叫 {1} 所建立。 + + + 無法將 Runspace 釋出至目前的集區,因為該 Runspace 不屬於目前的集區。 + + + 開啟 Runspace 集區之後,就無法變更此屬性。 + + + 此 Runspace 不支援中斷連線和連線作業。 + + + 無法執行作業,因為 Runspace 集區處於已中斷連線狀態。 + + + 伺服器不支援中斷連線作業。 伺服器必須執行 PowerShell 3.0 或更新版本,才能支援遠端 Runspace 集區中斷連線。 + + + 此 Runspace 集區 {0} 未設定為針對在遠端伺服器上執行的命令提供已中斷連線的 PowerShell 物件。 請使用 RunspacePool 類別的 GetRunspacePools() 靜態方法查詢伺服器,並傳回已設定為執行此作業的 Runspace 集區物件。 + + + 無法連線此 Runspace 集區,因為對應的伺服器端 Runspace 集區已連線至另一個用戶端。 + + + 伺服器不支援 ResetRunspaceState。 伺服器必須執行 PowerShell 5.0 或更新版本。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/RunspaceStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/RunspaceStrings.zh-Hant.resx new file mode 100644 index 00000000000..e0b84689972 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/RunspaceStrings.zh-Hant.resx @@ -0,0 +1,243 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Runspace 狀態不適用於此作業。 + + + 無法開啟 Runspace,因為 Runspace 不是 BeforeOpen 狀態。Runspace 目前的狀態為 '{0}'。 + + + 無法執行此作業,因為 Runspace 不是 Opened 狀態。Runspace 目前的狀態為 '{0}'。 + + + 無法叫用管道,因為 Runspace 不是 Opened 狀態。Runspace 目前的狀態為 '{0}'。 + + + 管道狀態不適用於此作業。 + + + 無法叫用管道,因為已叫用過該管道。 + + + 此參數的有效值為 PipelineResultTypes.Output。 + + + 管道不包含命令。 + + + 管道未執行,因為已有管道正在執行。無法同時執行多個管道。 + + + 無法以非同步方式叫用巢狀管道。請使用 Invoke 方法。 + + + 您只能從正在執行的管道內執行巢狀管道。 + + + SessionStateProxy 方法呼叫進行中時,無法關閉 Runspace。 + + + SessionStateProxy 方法呼叫進行中時,無法叫用管道。 + + + SessionStateProxy 方法呼叫進行中。不允許同時進行多個 SessionStateProxy 方法呼叫。 + + + 已有管道正在執行。不允許同時進行多個 SessionStateProxy 方法呼叫。 + + + 開啟 Runspace 之後,便無法變更此屬性。 + + + 處理用於建立此 Runspace 之 InitialSessionState 物件中所指定的模組 '{0}' 時,發生一或多個錯誤。如需完整的錯誤清單,請參閱 ErrorRecords 屬性。第一個錯誤為: {1} + + + 只有在 Apartment 狀態為多執行緒 Apartment (MTA),目前的選項為 UseNewThread 或 UseCurrentThread,且新值為 ReuseThread 時,才能變更執行緒選項。 + + + 當語言模式為 {1} 或 {2} 時,{0} 不能是 false。 + + + 您無法中斷僅限本機 Runspace 的連線。 + + + 本機 Runspace 不支援 Connect 作業。 + + + 工作階段忙碌中。工作階段一旦可供使用,您就會連線至該工作階段。若要取消 Enter-PSSession 命令,請按 Ctrl-C。 + + + 無法完成命令。此工作階段設定不支援指令碼叫用。如果工作階段設定處於無語言模式,就可能發生此情況。 + + + 您無法在本機 Runspace 上使用 Disconnect 和 Connect 作業。 + + + 無法連線管道,因為 Runspace 不是 Opened 狀態。 Runspace 目前的狀態為 '{0}'。 + + + 無法建構 RemoteRunspace。提供的 RunspacePool 物件無效。 + + + 沒有與此 Runspace 相關聯的已中斷連線命令。 + + + 遠端電腦不支援中斷連線作業。若要支援中斷連線,遠端電腦必須執行 Windows PowerShell 3.0 或更新版本的 Windows PowerShell,並使用 WSMan 傳輸。 + + + 無法連線 PSSession,因為工作階段不是 Disconnected 狀態,或無法供連線使用。 + + + 參數值不能是 PipelineResultTypes.None 或 PipelineResultTypes.Output。 + + + 此參數的有效值為 PipelineResultTypes.Output 或 PipelineResultTypes.Null。 + + + 目標遠端電腦不支援偵錯資料流重新導向。 + + + 目標遠端電腦不支援詳細資訊資料流重新導向。 + + + 目標遠端電腦不支援警告資料流重新導向。 + + + 目標遠端電腦不支援資訊資料流重新導向。 + + + 您已進入正忙於執行命令或指令碼的工作階段。 因為輸出會路由至作業 "{0}",所以您不會在主控台中看到輸出。 您可以等待正在執行的命令完成,或按 Ctrl-C 取消該命令並取得輸入提示。 + + + + 您已進入正忙於執行命令或指令碼的工作階段,輸出會顯示在主控台中。 您可以等待正在執行的命令完成,或按 Ctrl-C 取消該命令並取得輸入提示。 + + + + 您已進入目前在執行中命令或指令碼內停於偵錯中斷點的工作階段。 請使用 PowerShell 命令列偵錯工具繼續偵錯。 + + + + DefaultRunspace 必須是 LocalRunspace + + + 靜態 PrimaryRunspace 屬性只能設定一次,且已設定。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/SecuritySupportStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/SecuritySupportStrings.zh-Hant.resx new file mode 100644 index 00000000000..e8da001e2b2 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/SecuritySupportStrings.zh-Hant.resx @@ -0,0 +1,168 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法載入憑證。'{0}' 必須解析為檔案系統路徑。 + + + 憑證 '{0}' 無法用於加密。加密憑證必須包含「資料加密」或「金鑰編密」金鑰使用方式,並包含「文件加密增強金鑰使用方法」({1})。 + + + 無法載入憑證。識別碼 '{0}' 符合多個憑證。若要加密給多個收件者,請將多個特定值提供給 '{1}' 參數,而不要使用會比對多個憑證的萬用字元。 + + + 無法載入加密憑證。憑證設定 '{0}' 不是有效的 Base-64 編碼憑證,也不代表任何有效的憑證 (無論是根據檔案、目錄、指紋或主體名稱)。 + + + 警告: 憑證 '{0}' 包含私密金鑰。用於加密的受保護事件記錄憑證只應包含公開金鑰。 + + + 錯誤: 無法保護事件記錄檔訊息 '{0}': {1} + + + 錯誤: 找不到或無法使用憑證: {0} + + + 無法使用工作階段金鑰加密安全字串。 + + + 緩衝區位移無效。 + + + 公開金鑰資料無效。 + + + 無法匯入公開金鑰。 + + + 工作階段金鑰資料無效。 + + + 系統原則已封鎖指令檔 '{0}' 執行。 + + + 系統傳回未知的指令檔原則強制值: {0}。 + + + 指令碼檔案大小 + + + 指令檔 '{0}' 不受原則信任,將以 ConstrainedLanguage 模式執行。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/Serialization.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/Serialization.zh-Hant.resx new file mode 100644 index 00000000000..979923a2942 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/Serialization.zh-Hant.resx @@ -0,0 +1,195 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 需要 {0} 屬性。 + + + 無法辨識 {0} XML 標籤。 + + + 找不到 referenceId {0} 的物件 + + + 字典索引鍵的名稱屬性指定錯誤。 + + + 字典值的名稱屬性指定錯誤。 + + + PSObject 的版本無效。 + + + 傳入 PSObject 的版本為 {0}。預期的值為 1。 + + + 因為找不到 referenceId {0} 的 TypeNames,所以無法處理名稱。 + + + 深度參數的值必須大於或等於 1。 + + + 目前的節點類型是 {0}。需要的型別是 {1}。 + + + 未指定字典項目的索引鍵。 + + + 未指定字典項目的值。 + + + 沒有可供反序列化的其他物件。 + + + 指定 Null 作為字典索引鍵。 + + + {0} 基本類型的內容無效。 + + + 序列化 XML 的巢狀層級太深。 + + + 序列化程式已關閉。 + + + 命令中的資料超過工作階段組態允許的大小上限。允許的最大值為 {0} MB。請變更輸入、使用不同的工作階段組態,或變更遠端電腦上工作階段組態的 "{1}" 和 "{2}" 屬性。 + + + 加密的安全字串還原序列化失敗 + + + 索引鍵類型 {0} 無效。PSPrimitiveDictionary 類別只接受 System.String 類型的索引鍵。 + + + 值 {0} 的類型無效。PSPrimitiveDictionary 類別只接受可透過 PowerShell 遠端執行完整序列化的值類型。請參閱說明主題 about_Remoting,以取得可完整序列化的類型清單。 + + + 無法解密資料。資料未使用此索引鍵加密。 + + + 參數值 "{0}" 不是有效的加密字串。 + + + 指定的 {0} 無效。有效的 {0} 長度設定為 128 位元、192 位元或 256 位元。 + + + 目前只有 Windows 支援 SecureString 的還原序列化。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/SessionStateProviderBaseStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/SessionStateProviderBaseStrings.zh-Hant.resx new file mode 100644 index 00000000000..f42f935cec9 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/SessionStateProviderBaseStrings.zh-Hant.resx @@ -0,0 +1,156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 Item + + + Item: {0} Value: {1} + + + Clear Item + + + Item: {0} + + + Remove Item + + + Item: {0} + + + New Item + + + Item: {0} Type: {1} Value: {2} + + + Copy Item + + + Item: {0} Destination: {1} + + + Rename Item + + + Item: {0} NewName: {1} + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/SessionStateStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/SessionStateStrings.zh-Hant.resx new file mode 100644 index 00000000000..50d050451d7 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/SessionStateStrings.zh-Hant.resx @@ -0,0 +1,657 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法處理所傳回的資訊,因為從提供者的 Start 方法傳回的資訊適用於與通過提供者不同的提供者。 + + + 無法處理所傳回的資訊,因為從提供者的 Start 方法傳回的資訊為 Null。 + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetItem 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 GetItem 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 SetItem 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 SetItem 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 ClearItem 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 InvokeDefaultAction 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 InvokeDefaultAction 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 ItemExists 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 ItemExists 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 IsValidPath 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 IsItemContainer 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 RemoveItem 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetChildItems 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 GetChildItems 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetChildNames 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 GetChildNames 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 RenameItem 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 RenameItem 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 NewItem 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 NewItem 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 HasChildItems 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 CopyItem 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 CopyItem 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetParentPath 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 NormalizeRelativePath 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 MakePath 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetChildName 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 MoveItem 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 MoveItem 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetProperty 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 GetProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 SetProperty 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 SetProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 ClearProperty 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 ClearProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 NewProperty 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 NewProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 RemoveProperty 作業失敗。{2} + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 RemoveProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 CopyProperty 作業失敗。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取 CopyProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 MoveProperty 作業失敗。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取 MoveProperty 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 RenameProperty 作業失敗。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取 RenameProperty 的參數。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取內容讀取器。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取 GetContentReader 作業的動態參數。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取內容寫入器。{2} + + + 無法針對路徑 '{1}' 的 '{0}' 提供者,擷取 GetContentWriter 作業的動態參數。{2} + + + 無法取得內容,因為它是目錄: '{0}'。請改為使用 'Get-ChildItem'。 + + + 無法寫入內容,因為它是目錄: '{0}'。 + + + 沒有可供向後瀏覽的位置歷程記錄。 + + + 沒有可供向前瀏覽的位置歷程記錄。 + + + BoundedStack 是空的。 + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 ClearContent 作業失敗。{2} + + + 無法清除 '{0}' 的內容,因為它是目錄。僅在檔案上支援 Clear-Content。 + + + 無法從路徑 '{1}' 的 '{0}' 提供者,擷取 ClearContent 作業的動態參數。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 GetSecurityDescriptor 作業失敗。{2} + + + 嘗試針對路徑 '{1}' 在 '{0}' 提供者上執行 SetSecurityDescriptor 作業失敗。{2} + + + 嘗試在 '{0}' 提供者上執行 Start 作業失敗。{1} + + + 嘗試在 '{0}' 提供者上執行 InitializDefaultDrives 作業失敗。 + + + 嘗試針對根目錄為 '{1}' 的磁碟機在 '{0}' 提供者上執行 NewDrive 作業失敗。{2} + + + 無法為 '{0}' 提供者擷取 NewDrive 的動態參數。{1} + + + 在 '{0}' 提供者上叫用 RemoveDrive 失敗。{1} + + + 無法移除磁碟機 '{0}',因為提供者 '{1}' 防止這麼做。 + + + 路徑 '{0}' 是指基底 '{1}' 以外的項目。 + + + 針對 '{1}' 路徑在 '{0}' 提供者的內容寫入器上叫用 Seek 失敗。{2} + + + 針對 '{1}' 路徑在 '{0}' 提供者的內容讀取器或寫入器上叫用 Close 失敗。{2} + + + 針對 '{1}' 路徑在 '{0}' 提供者的內容讀取器上叫用 Read 失敗。{2} + + + 針對 '{1}' 路徑在 '{0}' 提供者的內容寫入器上叫用 Write 失敗。{2} + + + 提供者 '{0}' 無法使用變數語法來取得或設定資料。{2} + + + 變數語法無法用於在提供者中取得或設定資料。{2} + + + 無法寫入別名,因為別名 {0} 是唯讀或常數,因此無法寫入其中。 + + + 無法寫入至函式 {0},因為它是唯讀或常數。 + + + 無法覆寫變數 {0},因為它是唯讀或常數。 + + + 無法存取變數 '${0}',因為它是私人變數。 + + + 無法存取命令 '{0}',因為它是私人命令。 + + + 無法存取命令,因為它是私人命令。 + + + 無法存取工作階段狀態資源,因為它是私人資源。 + + + 未移除別名,因為別名 {0} 為常數或唯讀。 + + + 無法移除函式 {0},因為它是常數。 + + + 無法移除變數 {0},因為它是常數或唯讀。如果變數是唯讀,請再次嘗試指定 Force 選項的作業。 + + + 無法修改別名 {0},因為它是常數。 + + + 無法修改別名 {0},因為它是唯讀。 + + + 無法修改函式 {0},因為它是常數。 + + + 無法修改函式 {0},因為它是唯讀。 + + + 別名 {0} 在建立後就無法成為常數。別名只能在建立時成為常數。 + + + 現有函式 {0} 不能成為常數。函式只能在建立時成為常數。 + + + 現有變數 {0} 不能成為常數。變數只能在建立時成為常數。 + + + AllScope 選項無法從別名 '{0}' 移除。 + + + AllScope 選項無法從函式 '{0}' 移除。 + + + AllScope 選項無法從變數 '{0}' 移除。 + + + 函式定義 '{0}' 包含範圍限定詞,但沒有函式名稱。 + + + 無法移除提供者 {0}。必須先移除與提供者 {0} 相關聯的所有磁碟機,才能移除提供者 {0}。 + + + 無法處理磁碟機名稱,因為磁碟機名稱包含下列一或多個無效字元: ; ~ / \ . : + + + 新磁碟機建立失敗,因為提供者不允許建立新磁碟機。 + + + 提供的值 '{0}' 解析為多個位置堆疊。 + + + 找不到位置堆疊 '{0}'。它不存在或不是容器。 + + + 找不到路徑 '{0}',因為它不存在。 + + + 找不到別名,因為別名 '{0}' 不存在。 + + + 無法設定位置,因為路徑 '{0}' 解析為多個容器。您一次只能將位置設定為單一容器。 + + + 無法處理變數,因為變數路徑 '{0}' 解析為多個項目。您一次只能取得或設定一個項目的變數值。 + + + 找不到磁碟機。沒有名為 '{0}' 的磁碟機。 + + + 找不到名稱為 '{0}' 的提供者。 + + + 找不到名稱為 '{0}' 的提供者。名稱的格式不正確。提供者名稱只能是英數字元,或後面依序接著單一 '\' 和英數字元的 PowerShell 嵌入式管理單元名稱。 + + + '{0}' 解析為多個提供者名稱。可能的相符項目包括: {1}。 + + + 嘗試建立提供者的執行個體時發生錯誤。在組件中找不到 '{0}' 的提供者類型名稱。 + + + 無法使用指定的提供者名稱 '{0}',因為它包含下列一或多個無效的字元: \ [ ] ? * : + + + 嘗試建立提供者 '{0}' 的執行個體時發生錯誤。{1} + + + 找不到名稱為 '{0}' 的變數。 + + + 找不到名稱為 '{0}' 的追蹤來源。 + + + 名稱為 '{0}' 的磁碟機已經存在。 + + + 具有名稱 '{0}' 的變數已存在。 + + + 不允許別名,因為名稱為 '{0}' 的別名已經存在。 + + + 無法登錄 Cmdlet 提供者,因為名稱為 '{0}' 的 Cmdlet 提供者已存在。 + + + 路徑未參考檔案系統路徑。 + + + 無法移除全域範圍。 + + + 範圍編號 '{0}' 超過使用中範圍的數目。 + + + 無法比較 PSDriveInfo。PSDriveInfo 執行個體只能與另一個 PSDriveInfo 執行個體進行比較。 + + + Cmdlet 提供者無法串流處理結果,因為未指定任何 Cmdlet 來串流處理輸出。 + + + Cmdlet 提供者無法串流處理結果,因為未指定任何 Cmdlet 來串流處理錯誤。 + + + 未設定此提供者的首頁位置。若要設定首頁位置,請呼叫 "(get-psprovider '{0}').Home = 'path'”。 + + + 路徑的格式不正確。提供者路徑必須包含提供者識別碼,後面接著 "::",再接著提供者特定路徑。 + + + 無法移動項目,因為目的地路徑只能解析為單一路徑。 + + + 無法移動項目,因為來源和目的地路徑未解析為相同的提供者。 + + + 無法移動項目,因為來源路徑指向一或多個項目,而且目的地路徑不是容器。驗證目的地路徑是否為容器,然後再試一次。 + + + 無法移動項目,因為目的地解析為多個路徑。指定解析為單一目的地的目的地路徑,然後再試一次。 + + + 容器無法複製到現有的分葉項目。 + + + 容器無法複製到另一個容器。未指定 -Recurse 或 -Container 參數。 + + + 來源和目的地路徑未解析為相同的提供者。 + + + 無法將項目重新命名,因為路徑解析為多個項目。一次只能重新命名一個項目。 + + + 提供者 '{0}' 無法用來解析 '{1}' 路徑,因為提供者發生錯誤。 + + + 無法使用介面。此提供者未實作 IContentCmdletProvider 介面。 + + + 無法使用介面。此提供者不支援 IPropertyCmdletProvider 介面。 + + + 無法使用介面。此提供者未實作 IDynamicPropertyCmdletProvider 介面。 + + + 此提供者不支援 NavigationCmdletProvider 方法。 + + + 未處理提供者方法。此提供者不支援 ContainerCmdletProvider 方法。 + + + 無法呼叫方法。此提供者不支援 ItemCmdletProvider 方法。 + + + 此提供者不支援 DriveCmdletProvider 方法。 + + + 提供者作業已停止,因為提供者不支援此作業。 + + + 提供者作業已停止,因為提供者不支援 'Depth' 參數。 + + + 無法呼叫方法。此提供者不支援內容 Seek 方法。 + + + 無法執行 ClearContent 作業。此提供者不支援 ClearContent 作業。 + + + 提供者不支援使用認證。請再次執行作業,而不指定認證。 + + + FileSystem 提供者僅在 New-PSDrive Cmdlet 上支援認證。請再次執行作業,而不指定認證。 + + + 提供者不支援交易。在沒有 UseTransaction 參數的情況下再次執行作業。 + + + 無法呼叫方法。提供者不支援使用篩選條件。 + + + 無法建立磁碟機。提供者不支援使用認證。 + + + 路徑 '{0}' 上已有此項目。 + + + 無法複製項目。位於 '{0}' 路徑的項目不存在。 + + + 位於 '{0}' 路徑的項目不存在。 + + + 包含工作階段狀態中儲存之別名檢視的磁碟機 + + + 包含處理序環境變數檢視的磁碟機 + + + 包含工作階段狀態中儲存之函式檢視的磁碟機 + + + 包含工作階段狀態中儲存之變數檢視的磁碟機 + + + 對應至目前使用者之暫存目錄路徑的磁碟機 + + + 因為未指定目標值,所以無法建立連結 '{0}'。 + + + null 變數的參考一律會傳回 null 值。指派沒有作用。 + + + 工作階段中要保留的歷程記錄物件數目上限 + + + 無法將函式重新命名,因為函式 {0} 是唯讀或常數。 + + + 無法重新命名別名,因為別名 {0} 是唯讀或常數。 + + + 無法將變數重新命名,因為變數 {0} 是唯讀或常數。 + + + 無法在本機變數 {0} 上設定選項。使用 New-Variable 建立允許設定選項的變數。 + + + 無法修改 Cmdlet {0},因為它是唯讀。 + + + 無法移除變數 {0},因為變數已最佳化且不可移除。請嘗試使用 Remove-Variable Cmdlet (不含任何別名),或對您用於移除變數的命令執行點號載入。 + + + 無法覆寫變數 {0},因為變數已最佳化。請嘗試使用 New-Variable 或 Set-Variable Cmdlet (不含任何別名),或對您用於設定變數的命令執行點號載入。 + + + 無法同時使用 {0} 和 {1} 參數。請僅指定一個參數。 + + + 目前只有 FileSystem 提供者支援 Tail 參數。 + + + 不允許別名,因為名稱為 '{0}' 且命令類型為 '{1}' 的命令已經存在。 + + + 無法執行軟體。權限被拒; 目前的使用者沒有足夠的權限可執行此作業。 + + + '-{0}' 和 '-{1}' 互斥,無法同時指定。 + + + 路徑 '{0}' 無效。遠端複製作業僅支援絕對路徑。 + + + 無法驗證遠端路徑 '{0}'。 + + + 無法執行作業,因為工作階段 {0} 設定為 {1}。 + + + '{0}' 參數不得為 null 或空白。 + + + 工作階段狀態變數 + + + 在 ConstrainedLanguage 模式中會防止建立變數 '{0}' 範圍或將其變更為 AllScope。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/StringDecoratedStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/StringDecoratedStrings.zh-Hant.resx new file mode 100644 index 00000000000..e1601826492 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/StringDecoratedStrings.zh-Hant.resx @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 此方法只支援 'ANSI' 或 'PlainText'。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/SubsystemStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/SubsystemStrings.zh-Hant.resx new file mode 100644 index 00000000000..53fc06f3617 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/SubsystemStrings.zh-Hant.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 + + + 子系統 '{0}' 不允許註冊多個實作。 + + + 子系統 '{1}' 已註冊識別碼為 '{0}' 的實作。 + + + 子系統 '{0}' 不允許取消註冊實作。 + + + 子系統 '{0}' 未註冊任何實作。 + + + 找不到識別碼為 '{0}' 的已註冊實作。 + + + 指定的子系統類型 '{0}' 未知。 + + + 您必須指定具體的子系統類型,而不是基底介面 'ISubsystem'。 + + + 指定的子系統種類 '{0}' 未知。 + + + 對於目標子系統種類 '{0}',指定的子系統執行個體必須實作對應的具體介面或抽象類別 '{1}'。 + + + 子系統種類 '{0}' 的宣告中繼資料無效。需要定義 Cmdlet 或函式的子系統,不可允許多個登錄,因為這樣會導致一個實作覆寫另一個實作所定義的命令。 + + + 子系統 '{0}' 的實作 'Id' 屬性不能為空白 GUID。 + + + 子系統 '{0}' 的實作 'Name' 屬性不能為 null 或空字串。 + + + 子系統 '{0}' 的實作 'Description' 屬性不能為 null 或空字串。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/SuggestionStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/SuggestionStrings.zh-Hant.resx new file mode 100644 index 00000000000..092b7483dec --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/SuggestionStrings.zh-Hant.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 + + + 找不到命令 "{0}",但它確實存在於目前的位置。 +PowerShell 預設不會從目前的位置載入命令 (請參閱 'Get-Help about_Command_Precedence')。 + +如果您信任此命令,請改為執行下列命令: + + + 最相似的命令為: + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/TabCompletionStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/TabCompletionStrings.zh-Hant.resx new file mode 100644 index 00000000000..22afc9bf5bc --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/TabCompletionStrings.zh-Hant.resx @@ -0,0 +1,610 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 因為遠端 Runspace 未包含 TypeTable 執行個體,所以無法正確還原序列化索引標籤完成結果。 + + + 無法存取 CompletionResult 類型之 null 執行個體上的屬性。 + + + 位元 NOT + + + 邏輯 Not。否定其後的陳述式。 + + + 等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中等於右運算元的值,否則,如果左運算元等於右運算元,則傳回 TRUE。 + + + 等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中等於右運算元的值,否則,如果左運算元等於右運算元,則傳回 TRUE。 + + + 等於 - 區分大小寫。當左運算元是集合時,傳回該集合中等於右運算元的值,否則,如果左運算元等於右運算元,則傳回 TRUE。 + + + 不等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中不等於右運算元的值,否則,如果左運算元不等於右運算元,則傳回 TRUE。 + + + 不等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中不等於右運算元的值,否則,如果左運算元不等於右運算元,則傳回 TRUE。 + + + 不等於 - 區分大小寫。當左運算元是集合時,傳回該集合中不等於右運算元的值,否則,如果左運算元不等於右運算元,則傳回 TRUE。 + + + 大於或等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中大於或等於右運算元的值,否則,如果左運算元大於或等於右運算元,則傳回 TRUE。 + + + 大於或等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中大於或等於右運算元的值,否則,如果左運算元大於或等於右運算元,則傳回 TRUE。 + + + 大於或等於 - 區分大小寫。當左運算元是集合時,傳回該集合中大於或等於右運算元的值,否則,如果左運算元大於或等於右運算元,則傳回 TRUE。 + + + 大於 - 不區分大小寫。當左運算元是集合時,傳回該集合中大於右運算元的值,否則,如果左運算元大於右運算元,則傳回 TRUE。 + + + 大於 - 不區分大小寫。當左運算元是集合時,傳回該集合中大於右運算元的值,否則,如果左運算元大於右運算元,則傳回 TRUE。 + + + 大於 - 區分大小寫。當左運算元是集合時,傳回該集合中大於右運算元的值,否則,如果左運算元大於右運算元,則傳回 TRUE。 + + + 小於 - 不區分大小寫。當左運算元是集合時,傳回該集合中小於右運算元的值,否則,如果左運算元小於右運算元,則傳回 TRUE。 + + + 小於 - 不區分大小寫。當左運算元是集合時,傳回該集合中小於右運算元的值,否則,如果左運算元小於右運算元,則傳回 TRUE。 + + + 小於 - 區分大小寫。當左運算元是集合時,傳回該集合中小於右運算元的值,否則,如果左運算元小於右運算元,則傳回 TRUE。 + + + 小於或等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中小於或等於右運算元的值,否則,如果左運算元小於或等於右運算元,則傳回 TRUE。 + + + 小於或等於 - 不區分大小寫。當左運算元是集合時,傳回該集合中小於或等於右運算元的值,否則,如果左運算元小於或等於右運算元,則傳回 TRUE。 + + + 小於或等於 - 區分大小寫。當左運算元是集合時,傳回該集合中小於或等於右運算元的值,否則,如果左運算元小於或等於右運算元,則傳回 TRUE。 + + + 萬用字元比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中符合右運算元的值,否則,如果左運算元符合右運算元,則傳回 TRUE。 + + + 萬用字元比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中符合右運算元的值,否則,如果左運算元符合右運算元,則傳回 TRUE。 + + + 萬用字元比對運算子 - 區分大小寫。當左運算元是集合時,傳回該集合中符合右運算元的值,否則,如果左運算元符合右運算元,則傳回 TRUE。 + + + 萬用字元比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中與右運算元不相符的值,否則,如果左運算元與右運算元不相符,則傳回 TRUE。 + + + 萬用字元比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中與右運算元不相符的值,否則,如果左運算元與右運算元不相符,則傳回 TRUE。 + + + 萬用字元比對運算子 - 區分大小寫。當左運算元是集合時,傳回該集合中與右運算元不相符的值,否則,如果左運算元與右運算元不相符,則傳回 TRUE。 + + + 規則運算式比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中符合右運算元的值,否則,如果左運算元符合右運算元,則傳回 TRUE。 + + + 規則運算式比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中符合右運算元的值,否則,如果左運算元符合右運算元,則傳回 TRUE。 + + + 規則運算式比對運算子 - 區分大小寫。當左運算元是集合時,傳回該集合中符合右運算元的值,否則,如果左運算元符合右運算元,則傳回 TRUE。 + + + 規則運算式比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中與右運算元不相符的值,否則,如果左運算元與右運算元不相符,則傳回 TRUE。 + + + 規則運算式比對運算子 - 不區分大小寫。當左運算元是集合時,傳回該集合中與右運算元不相符的值,否則,如果左運算元與右運算元不相符,則傳回 TRUE。 + + + 規則運算式比對運算子 - 區分大小寫。當左運算元是集合時,傳回該集合中與右運算元不相符的值,否則,如果左運算元與右運算元不相符,則傳回 TRUE。 + + + 取代運算子 - 不區分大小寫。變更左運算元。範例: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + 取代運算子 - 不區分大小寫。變更左運算元。範例: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + 取代運算子 - 區分大小寫。變更左運算元。範例: (dir *.ps1).FullName -replace '.ps1$','.ps1.bak' + + + 內含項目運算子 - 不區分大小寫。當測試值 (右運算元) 至少與右運算元中的其中一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 不區分大小寫。當測試值 (右運算元) 至少與右運算元中的其中一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 區分大小寫。只有當測試值 (右運算元) 至少與左運算元中的其中一個值完全相符時,才傳回 TRUE。 + + + 內含項目運算子 - 不區分大小寫。當測試值 (右運算元) 並未與右運算元中的任何一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 不區分大小寫。當測試值 (右運算元) 並未與右運算元中的任何一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 區分大小寫。當測試值 (右運算元) 並未與右運算元中的任何一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 不區分大小寫。當測試值 (左運算元) 至少與右運算元中的其中一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 不區分大小寫。當測試值 (左運算元) 至少與右運算元中的其中一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 區分大小寫。當測試值 (左運算元) 至少與右運算元中的其中一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 區分大小寫。當測試值 (左運算元) 並未與右運算元中的任何一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 不區分大小寫。當測試值 (左運算元) 並未與右運算元中的任何一個值完全相符時,傳回 TRUE。 + + + 內含項目運算子 - 區分大小寫。當測試值 (左運算元) 並未與右運算元中的任何一個值完全相符時,傳回 TRUE。 + + + 分割 - 不區分大小寫。將一或多個字串分割成子字串。 +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + 分割 - 不區分大小寫。將一或多個字串分割成子字串。 +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + 分割 - 區分大小寫。將一或多個字串分割成子字串。 +-Split <String> + +<String> -Split <Delimiter>[,<Max-substrings>[,"<Options>"]] + +<String> -Split {<ScriptBlock>} [,<Max-substrings>] + + + 當左運算元不是指定 .NET Framework 類型 (右運算元) 的執行個體時,傳回 TRUE。 + + + 當左運算元是指定 .NET Framework 類型 (右運算元) 的執行個體時,傳回 TRUE。 + + + 將左運算元轉換成指定的 .NET Framework 類型 (右運算元)。 + + + 使用字串物件的格式方法來設定字串格式。 + + + 邏輯 AND。當兩個陳述式皆為 TRUE 時,傳回 TRUE。 + + + 位元 AND + + + 邏輯 OR。當其中一個或兩個陳述式皆為 TRUE 時,傳回 TRUE。 + + + 位元 OR (包含) + + + 邏輯互斥 OR。當其中一個陳述式為 TRUE 而另一個陳述式為 FALSE 時,傳回 TRUE。 + + + 位元 OR (排除) + + + 聯結 - 將多個字串結合成單一字串。 +-Join <String[]> +<String[]> -Join <Delimiter> + + + Shift Left 位元運算子。在最右邊的位元位置插入零。 + + + Shift Right 位元運算子。在最左邊的位元位置插入零。對於帶正負號的值,會保留正負號位元。 + + + [string] +指定正在建立的屬性名稱。 + + + [string] +指定正在建立的屬性名稱。 + + + [scriptblock] +用來計算新屬性值的指令碼區塊。 + + + [string] +定義值在資料行中的顯示方式。 +有效值為 'left'、'center' 或 'right'。 + + + [string] +指定格式字串,其定義輸出值的格式設定方式。 + + + [int] +指定顯示值時,資料表中的最大資料行寬度。 +值必須大於 0。 + + + [int] +深度索引鍵,指定每個屬性的展開深度。 + + + [bool] +指定一或多個屬性的排序順序。 + + + [bool] +指定一或多個屬性的排序順序。 + + + [String[]] +指定要從中取得事件的記錄名稱。 +支援萬用字元。 + + + [String[]] +指定要從中取得事件的事件記錄檔提供者。 +支援萬用字元。 + + + [String[]] +指定要從中取得事件的記錄檔案路徑。 +有效的檔案格式為: .etl、.evt 和 .evtx + + + [Long[]] +選取具有指定關鍵字位元遮罩的事件。 +以下是標準關鍵字: +4503599627370496: AuditFailure +9007199254740992: AuditSuccess +4503599627370496: CorrelationHint +18014398509481984: CorrelationHint2 +36028797018963968: EventLogClassic +281474976710656: ResponseTime +2251799813685248: Sqm +562949953421312: WdiContext +1125899906842624: WdiDiagnostic + + + [int[]] +選取具有指定記錄識別碼的事件。 + + + [int[]] +選取具有指定記錄層級的事件。 +下列記錄層級有效: +1: 危急 +2: 錯誤 +3: 警告 +4: 資訊性 +5: 詳細資訊 + + + [datetime] +選取在指定日期和時間之後建立的事件。 + + + [datetime] +選取在指定日期和時間之前建立的事件。 + + + [string] +選取指定使用者產生的事件。 +這可以是 SID 的字串表示法,或是使用 DOMAIN\USERNAME 或 USERNAME@DOMAIN 格式的網域和使用者名稱 + + + [string[]] +選取 EventData 區段中具有任何指定值的事件。 + + + [hashtable] +排除符合雜湊表中指定值的事件。 + + + [string] 或 [hashtable] +指定指令碼所需的 PowerShell 模組陣列。 +每個元素都可以是以模組名稱為值的字串,或具有下列索引鍵的雜湊表: +Name: 模組的名稱 +GUID: 模組的 GUID +下列其中一項: +ModuleVersion: 指定模組的最小可接受版本。 +ModuleVersion: 指定模組所需的確切版本。 +MaximumVersion: 指定模組的最大可接受版本。 + + + [string] +指定指令碼所需的 PowerShell 版本。 +有效值為 "Core" 和 "Desktop" + + + [switch] +指定 PowerShell 必須在 Windows 上以系統管理員身分執行。 +這必須是 #requires 陳述式行的最後一個參數。 + + + [version] +指定指令碼所需的最低 PowerShell 版本。 + + + 指定指令碼需要 PowerShell 7+ 才能執行。 + + + 指定指令碼需要 Windows PowerShell 5.1 才能執行。 + + + [string] +必要項目。指定模組名稱。 + + + [string] +選用。指定模組的 GUID。 + + + [string] +指定模組的最小可接受版本。 + + + [string] +指定模組所需的確切版本。 + + + [string] +指定模組的最大可接受版本。 + + + 函式或指令碼的簡短描述。 +此關鍵字在每個主題中只能使用一次。 + + + 函式或指令碼的詳細描述。 +此關鍵字在每個主題中只能使用一次。 + + + .PARAMETER <Parameter-Name> +參數的描述。 +針對函式或指令碼語法中的每個參數新增 .PARAMETER 關鍵字。 + + + 使用函式或指令碼的範例命令,後面可選擇性地接著範例輸出和描述。 +針對每個範例重複此關鍵字。 + + + 可透過管道傳送到函式或指令碼的 .NET 物件類型。 +您也可以包含輸入物件的描述。 + + + Cmdlet 傳回之物件的 .NET 類型。 +您也可以包含傳回物件的描述。 + + + 函式或指令碼的其他資訊。 + + + 相關主題的名稱。 +針對每個相關主題,重複使用 .LINK 關鍵字。 +.Link 關鍵字內容也可以包含相同說明主題線上版本的 URI。 + + + 函式或指令碼所使用或相關的技術或功能名稱。 + + + 說明主題的使用者角色名稱。 + + + 描述函式預期用途的關鍵字。 + + + .FORWARDHELPTARGETNAME <Command-Name> +重新導向至指定命令的說明主題。 + + + .FORWARDHELPCATEGORY <Category> +指定 .ForwardHelpTargetName 中項目的說明類別 + + + .REMOTEHELPRUNSPACE <PSSession-variable> +指定包含說明主題的工作階段。 +輸入包含 PSSession 物件的變數。 + + + .EXTERNALHELP <XML Help File> +當函式或指令碼的文件為 XML 檔案中時,需要 .ExternalHelp 關鍵字。 + + + 指定要載入之 .NET 組件的路徑。 + +使用組件 <.NET-assembly-path> + + + 指定要從中載入類別的 PowerShell 模組。 + +使用模組 <ModuleName 或 Path> + +使用模組 <ModuleSpecification hashtable> + + + 指定要解析類型的 .NET 命名空間或命名空間別名。 + +使用命名空間 <.NET-namespace> + +使用命名空間 <AliasName> = <.NET-namespace> + + + 指定 .NET 類型的別名。 + +使用類型 <AliasName> = <.NET-type> + + + 一般字串。 + + + 包含環境變數的未展開參照的字串,且只有在擷取值時才會展開。 + + + 任何形式的二進位資料。 + + + 32 位元二進位數字。 + + + 字串的陣列。 + + + 64 位元二進位數字。 + + + 不支援的登錄資料類型。 + + + ',' - Comma + + + ', ' - Comma-Space + + + ';' - Semi-Colon + + + '; ' - Semi-Colon-Space + + + {0} - 新行 + + + '-' - Dash + + + ' ' - Space + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/TransactionStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/TransactionStrings.zh-Hant.resx new file mode 100644 index 00000000000..49ba411a1a9 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/TransactionStrings.zh-Hant.resx @@ -0,0 +1,174 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + 無法使用交易。沒有使用中的交易。 + + + 無法提交交易。沒有使用中的交易。 + + + 無法復原交易,因為沒有使用中的交易。 + + + 無法復原交易。異動已提交。 + + + 無法提交交易。異動已提交。 + + + 無法提交交易。交易已復原或已逾時。 + + + 無法復原交易。交易已復原或已逾時。 + + + 無法設定使用中交易。尚未建立任何交易。 + + + 無法設定使用中交易。使用中交易已復原或已逾時。 + + + 此 cmdlet 需要一個使用中的交易。目前的交易已經認可或復原。 + + + 此 Cmdlet 需要交易。請使用 -UseTransaction 參數再次執行命令。 + + + 無法使用交易。尚未開始任何交易。 + + + 無法使用交易。異動已提交。 + + + 無法使用交易。交易已復原或已逾時。 + + + 無法使用交易。交易已逾時。 + + + 尚未設定基礎交易。 + + + 基底交易未啟用。 + + + 在建立其他交易之後,無法設定基底交易。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/TypesXmlStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/TypesXmlStrings.zh-Hant.resx new file mode 100644 index 00000000000..a7383f61e86 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/TypesXmlStrings.zh-Hant.resx @@ -0,0 +1,255 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + {0},{1}({2}) : 錯誤: {3} + + + {0},{1}({2}):型別 "{3}" 發生錯誤: {4} + + + 節點 "{0}" 在 "{1}" 下只能出現一次。將忽略父節點 "{1}"。 + + + 不允許節點 {0}。允許下列節點: {1}。 + + + 節點 "{0}" 不應有內部文字。 + + + 節點 "{0}" 應該有內部文字。 + + + 找不到節點 '{0}'。它在 "{1}" 下只能出現一次。將忽略父節點 "{1}"。 + + + "Type" 節點必須包含 "Members"、"TypeConverters" 或 "TypeAdapters"。 + + + 無法為型別 {0} 建立型別轉換器的執行個體,因為例外狀況: {1}。 + + + PowerShell 無法為型別 {0} 建立型別配接器的執行個體,因為下列例外狀況: {1}。 + + + 調整後的型別 "{0}" 無效。 + + + 已忽略 TypeConverter,因為它已存在。 + + + 已忽略 TypeAdapter,因為它已存在。 + + + 型別 "{0}" 應該是 TypeConverter 或 PSTypeConverter。 + + + 型別 "{0}" 應該是 PSPropertyAdapter。 + + + 成員 {0} 已經存在。 + + + 已保留下列成員名稱: {0} + + + 例外狀況: {0} + + + ScriptProperty 應具備 getter 或 setter。 + + + CodeProperty 應具備 getter 或 setter。 + + + {0},{1} : {2} + + + 值應該是 TRUE 或 FALSE,而不是 {0}。 + + + 節點 "{0}" 不應有 "{1}" 屬性。 + + + {0},{1}: 找不到檔案。 + + + {0},{1}: 因為檔案已由 {2} 載入,所以已略過。 + + + 找不到登錄機碼: {0}{1}。使用 {2} 載入組態檔。 + + + 找不到登錄機碼 {1}{2} 中指定的路徑 {0}。使用 {3} 載入組態檔。 + + + {0},{1}: 已略過檔案,因為它沒有 ps1xml 檔案副檔名。 + + + {0},{1}: 因為下列驗證例外狀況,所以已略過檔案: {2}。 + + + 成員 "{0}" 必須是備註。 + + + 無法轉換備注 "{0}":"{1}"。 + + + 請勿在此使用成員 "{0}"。 + + + 成員 "{0}" 必須有型別 "{1}"。 + + + 當 "{1}" 為 "{2}" 且 "{3}" 為 "{4}" 時,"{0}" 必須存在。 + + + 先前的錯誤導致所有序列化設定都被忽略。 + + + "{0}" 不是標準成員,將會忽略。 + + + {0} 路徑不完整。請指定完整型別檔案路徑。 + + + 因為 TypeTable 可能是在 Runspace 之外建立,所以無法更新 TypeTable。 + + + 載入 TypeTable 時發生錯誤。請查看 Errors 屬性,以取得詳細的錯誤訊息。 + + + TypeData "{0}" 中發生錯誤: {1} + + + "{0}" 的屬性 "{1}" 應具有一個值。 + + + "{0}" 的 "{1}" 屬性不應為 null 或空字串。 + + + 找不到型別 "{0}"。型別名稱值必須是該型別的完整名稱。請確認型別名稱,然後再次執行命令。 + + + TypeData 必須包含 "Members"、"TypeConverters"、"TypeAdapters" 或 "StandardMembers"。 + + + 無法使用一個以上的項目更新共用型別資料表。 + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/VerbDescriptionStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/VerbDescriptionStrings.zh-Hant.resx new file mode 100644 index 00000000000..175483ed225 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/VerbDescriptionStrings.zh-Hant.resx @@ -0,0 +1,420 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 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 + + + Adds a resource to a container, or attaches an item to another item + + + Confirms or agrees to the status of a resource or process + + + Affirms the state of a resource + + + Stores data by replicating it + + + Restricts access to a resource + + + Creates an artifact (usually a binary or document) out of some set of input files (usually source code or declarative documents) + + + Creates a snapshot of the current state of the data or of its configuration + + + Removes all the resources from a container but does not delete the container + + + Changes the state of a resource to make it inaccessible, unavailable, or unusable + + + Evaluates the data from one resource against the data from another resource + + + Concludes an operation + + + Compacts the data of a resource + + + Acknowledges, verifies, or validates the state of a resource or process + + + Creates a link between a source and a destination + + + Changes the data from one representation to another when the cmdlet supports bidirectional conversion or when the cmdlet supports conversion between multiple data types + + + Converts one primary type of input (the cmdlet noun indicates the input) to one or more supported output types + + + Converts from one or more types of input to a primary output type (the cmdlet noun indicates the output type) + + + Copies a resource to another name or to another container + + + Examines a resource to diagnose operational problems + + + Refuses, objects, blocks, or opposes the state of a resource or process + + + Sends an application, website, or solution to a remote target[s] in such a way that a consumer of that solution can access it after deployment is complete + + + Configures a resource to an unavailable or inactive state + + + Breaks the link between a source and a destination + + + Detaches a named entity from a location + + + Modifies existing data by adding or removing content + + + Configures a resource to an available or active state + + + Specifies an action that allows the user to move into a resource + + + Sets the current environment or context to the most recently used context + + + Restores the data of a resource that has been compressed to its original state + + + Encapsulates the primary input into a persistent data store, such as a file, or into an interchange format + + + Looks for an object in a container that is unknown, implied, optional, or specified + + + Arranges objects in a specified form or layout + + + Specifies an action that retrieves a resource + + + Allows access to a resource + + + Arranges or associates one or more resources + + + Makes a resource undetectable + + + Creates a resource from data that is stored in a persistent data store (such as a file) or in an interchange format + + + Prepares a resource for use, and sets it to a default state + + + Places a resource in a location, and optionally initializes it + + + Performs an action, such as running a command or a method + + + Combines resources into one resource + + + Applies constraints to a resource + + + Secures a resource + + + Identifies resources that are consumed by a specified operation, or retrieves statistics about a resource + + + Creates a single resource from multiple resources + + + Attaches a named entity to a location + + + Moves a resource from one location to another + + + Creates a resource + + + Changes the state of a resource to make it accessible, available, or usable + + + Increases the effectiveness of a resource + + + Sends data out of the environment + + + Use the Test verb + + + Removes an item from the top of a stack + + + Safeguards a resource from attack or loss + + + Makes a resource available to others + + + Adds an item to the top of a stack + + + Acquires information from a source + + + Accepts information sent from a source + + + Resets a resource to the state that was undone + + + Creates an entry for a resource in a repository such as a database + + + Deletes a resource from a container + + + Changes the name of a resource + + + Restores a resource to a usable condition + + + Asks for a resource or asks for permissions + + + Sets a resource back to its original state + + + Changes the size of a resource + + + Maps a shorthand representation of a resource to a more complete representation + + + Stops an operation and then starts it again + + + Sets a resource to a predefined state, such as a state set by Checkpoint + + + Starts an operation that has been suspended + + + Specifies an action that does not allow access to a resource + + + Preserves data to avoid loss + + + Creates a reference to a resource in a container + + + Locates a resource in a container + + + Delivers information to a destination + + + Replaces data on an existing resource or creates a resource that contains some data + + + Makes a resource visible to the user + + + Assures that two or more resources are in the same state + + + Bypasses one or more resources or points in a sequence + + + Separates parts of a resource + + + Initiates an operation + + + Moves to the next point or resource in a sequence + + + Discontinues an activity + + + Presents a resource for approval + + + Pauses an activity + + + Specifies an action that alternates between two resources, such as to change between two locations, responsibilities, or states + + + Verifies the operation or consistency of a resource + + + Tracks the activities of a resource + + + Removes restrictions to a resource + + + Sets a resource to its previous state + + + Removes a resource from an indicated location + + + Releases a resource that was locked + + + Removes safeguards from a resource that were added to prevent it from attack or loss + + + Makes a resource unavailable to others + + + Removes the entry for a resource from a repository + + + Brings a resource up-to-date to maintain its state, accuracy, conformance, or compliance + + + Uses or includes a resource to do something + + + Pauses an operation until a specified event occurs + + + Continually inspects or monitors a resource for changes + + + Adds information to a target + + \ No newline at end of file diff --git a/src/System.Management.Automation/resources/zh-Hant/WildcardPatternStrings.zh-Hant.resx b/src/System.Management.Automation/resources/zh-Hant/WildcardPatternStrings.zh-Hant.resx new file mode 100644 index 00000000000..ccb0c0d0e77 --- /dev/null +++ b/src/System.Management.Automation/resources/zh-Hant/WildcardPatternStrings.zh-Hant.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 + + + 指定的萬用字元模式無效: {0} + + \ No newline at end of file diff --git a/src/System.Management.Automation/security/Authenticode.cs b/src/System.Management.Automation/security/Authenticode.cs index 70b6778c37e..3a7720616d1 100644 --- a/src/System.Management.Automation/security/Authenticode.cs +++ b/src/System.Management.Automation/security/Authenticode.cs @@ -4,13 +4,18 @@ #pragma warning disable 1634, 1691 #pragma warning disable 56523 -using Dbg = System.Management.Automation; +#if !UNIX +using Microsoft.Security.Extensions; +#endif +using System.ComponentModel; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Security; +using System.Management.Automation.Win32Native; using System.Runtime.InteropServices; using System.Security.Cryptography.X509Certificates; -using DWORD = System.UInt32; + +using Dbg = System.Management.Automation; namespace System.Management.Automation { @@ -48,6 +53,8 @@ public enum SigningOption /// internal static class SignatureHelper { + private static Guid WINTRUST_ACTION_GENERIC_VERIFY_V2 = new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); + /// /// Tracer for SignatureHelper. /// @@ -89,7 +96,6 @@ internal static class SignatureHelper /// /// Thrown if the file specified by argument fileName is not found /// - [ArchitectureSensitive] internal static Signature SignFile(SigningOption option, string fileName, X509Certificate2 certificate, @@ -99,17 +105,18 @@ internal static Signature SignFile(SigningOption option, bool result = false; Signature signature = null; IntPtr pSignInfo = IntPtr.Zero; - DWORD error = 0; + uint error = 0; string hashOid = null; Utils.CheckArgForNullOrEmpty(fileName, "fileName"); Utils.CheckArgForNull(certificate, "certificate"); - // If given, TimeStamp server URLs must begin with http:// + // If given, TimeStamp server URLs must begin with http:// or https:// if (!string.IsNullOrEmpty(timeStampServerUrl)) { - if ((timeStampServerUrl.Length <= 7) || - (timeStampServerUrl.IndexOf("http://", StringComparison.OrdinalIgnoreCase) != 0)) + if ((timeStampServerUrl.Length <= 7) || ( + !timeStampServerUrl.StartsWith("http://", StringComparison.OrdinalIgnoreCase) && + !timeStampServerUrl.StartsWith("https://", StringComparison.OrdinalIgnoreCase))) { throw PSTraceSource.NewArgumentException( nameof(certificate), @@ -185,7 +192,7 @@ internal static Signature SignFile(SigningOption option, // able to see that. #pragma warning disable 56523 result = NativeMethods.CryptUIWizDigitalSign( - (DWORD)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI, + (uint)NativeMethods.CryptUIFlags.CRYPTUI_WIZ_NO_UI, IntPtr.Zero, IntPtr.Zero, pSignInfo, @@ -241,7 +248,7 @@ internal static Signature SignFile(SigningOption option, } else { - signature = new Signature(fileName, (DWORD)error); + signature = new Signature(fileName, (uint)error); } } finally @@ -268,19 +275,18 @@ internal static Signature SignFile(SigningOption option, /// /// Thrown if the file specified by argument fileName is not found. /// - [ArchitectureSensitive] - internal static Signature GetSignature(string fileName, string fileContent) + internal static Signature GetSignature(string fileName, byte[] fileContent) { Signature signature = null; if (fileContent == null) { - // First, try to get the signature from the catalog signature APIs. - signature = GetSignatureFromCatalog(fileName); + // First, try to get the signature from the latest dotNet signing API. + signature = GetSignatureFromMSSecurityExtensions(fileName); } // If there is no signature or it is invalid, go by the file content - // with the older WinVerifyTrust APIs + // with the older WinVerifyTrust APIs. if ((signature == null) || (signature.Status != SignatureStatus.Valid)) { signature = GetSignatureFromWinVerifyTrust(fileName, fileContent); @@ -289,159 +295,121 @@ internal static Signature GetSignature(string fileName, string fileContent) return signature; } + /// + /// Gets the file signature using the dotNet Microsoft.Security.Extensions package. + /// This supports both Windows catalog file signatures and embedded file signatures. + /// But it is not supported on all Windows platforms/skus, noteably Win7 and nanoserver. + /// [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] - private static Signature GetSignatureFromCatalog(string filename) + private static Signature GetSignatureFromMSSecurityExtensions(string filename) { +#if UNIX + return null; +#else if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value) { - // Signature.CatalogApiAvailable would be set to false the first time it is detected that - // WTGetSignatureInfo API does not exist on the platform, or if the API is not functional on the target platform. - // Just return from the function instead of revalidating. return null; } - Signature signature = null; - Utils.CheckArgForNullOrEmpty(filename, "fileName"); SecuritySupport.CheckIfFileExists(filename); - try + Signature signature = null; + FileSignatureInfo fileSigInfo; + using (FileStream fileStream = File.OpenRead(filename)) { - using (FileStream stream = File.OpenRead(filename)) + try + { + fileSigInfo = FileSignatureInfo.GetFromFileStream(fileStream); + System.Diagnostics.Debug.Assert(fileSigInfo is not null, "Returned FileSignatureInfo should never be null."); + } + catch (Exception) { - NativeMethods.SIGNATURE_INFO sigInfo = new NativeMethods.SIGNATURE_INFO(); - sigInfo.cbSize = (uint)Marshal.SizeOf(sigInfo); + // For any API error, enable fallback to WinVerifyTrust APIs. + Signature.CatalogApiAvailable = false; + return null; + } + } - IntPtr ppCertContext = IntPtr.Zero; - IntPtr phStateData = IntPtr.Zero; + uint error = GetErrorFromSignatureState(fileSigInfo.State); - try - { - int hresult = NativeMethods.WTGetSignatureInfo(filename, stream.SafeFileHandle.DangerousGetHandle(), - NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_SIGNED | - NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CATALOG_FIRST | - NativeMethods.SIGNATURE_INFO_FLAGS.SIF_AUTHENTICODE_SIGNED | - NativeMethods.SIGNATURE_INFO_FLAGS.SIF_BASE_VERIFICATION | - NativeMethods.SIGNATURE_INFO_FLAGS.SIF_CHECK_OS_BINARY, - ref sigInfo, ref ppCertContext, ref phStateData); - - if (Utils.Succeeded(hresult)) - { - DWORD error = GetErrorFromSignatureState(sigInfo.nSignatureState); - - X509Certificate2 cert = null; - - if (ppCertContext != IntPtr.Zero) - { - cert = new X509Certificate2(ppCertContext); - - // Get the time stamper certificate if available - TryGetProviderSigner(phStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert); - if (timestamperCert != null) - { - signature = new Signature(filename, error, cert, timestamperCert); - } - else - { - signature = new Signature(filename, error, cert); - } - - switch (sigInfo.nSignatureType) - { - case NativeMethods.SIGNATURE_INFO_TYPE.SIT_AUTHENTICODE: signature.SignatureType = SignatureType.Authenticode; break; - case NativeMethods.SIGNATURE_INFO_TYPE.SIT_CATALOG: signature.SignatureType = SignatureType.Catalog; break; - } - - if (sigInfo.fOSBinary == 1) - { - signature.IsOSBinary = true; - } - } - else - { - signature = new Signature(filename, error); - } - - if (!Signature.CatalogApiAvailable.HasValue) - { - string productFile = Path.Combine(Utils.DefaultPowerShellAppBase, "Modules\\PSDiagnostics\\PSDiagnostics.psm1"); - if (signature.Status != SignatureStatus.Valid) - { - if (string.Equals(filename, productFile, StringComparison.OrdinalIgnoreCase)) - { - Signature.CatalogApiAvailable = false; - } - else - { - // ProductFile has to be Catalog signed. Hence validating - // to see if the Catalog API is functional using the ProductFile. - Signature productFileSignature = GetSignatureFromCatalog(productFile); - Signature.CatalogApiAvailable = (productFileSignature != null && productFileSignature.Status == SignatureStatus.Valid); - } - } - } - } - else - { - // If calling NativeMethods.WTGetSignatureInfo failed (returned a non-zero value), we still want to set Signature.CatalogApiAvailable to false. - Signature.CatalogApiAvailable = false; - } - } - finally - { - if (phStateData != IntPtr.Zero) - { - NativeMethods.FreeWVTStateData(phStateData); - } + if (fileSigInfo.SigningCertificate is null) + { + signature = new Signature(filename, error); + } + else + { + signature = fileSigInfo.TimestampCertificate is null ? + new Signature(filename, error, fileSigInfo.SigningCertificate) : + new Signature(filename, error, fileSigInfo.SigningCertificate, fileSigInfo.TimestampCertificate); + } - if (ppCertContext != IntPtr.Zero) - { - NativeMethods.CertFreeCertificateContext(ppCertContext); - } - } - } + switch (fileSigInfo.Kind) + { + case SignatureKind.None: + signature.SignatureType = SignatureType.None; + break; + + case SignatureKind.Embedded: + signature.SignatureType = SignatureType.Authenticode; + break; + + case SignatureKind.Catalog: + signature.SignatureType = SignatureType.Catalog; + break; + + default: + System.Diagnostics.Debug.Fail("Signature type can only be None, Authenticode or Catalog."); + break; } - catch (TypeLoadException) + + signature.IsOSBinary = fileSigInfo.IsOSBinary; + + if (signature.SignatureType == SignatureType.Catalog && !Signature.CatalogApiAvailable.HasValue) { - // If we don't have WTGetSignatureInfo, don't return a Signature. - Signature.CatalogApiAvailable = false; - return null; + Signature.CatalogApiAvailable = fileSigInfo.State != SignatureState.Invalid; } return signature; +#endif } - private static DWORD GetErrorFromSignatureState(NativeMethods.SIGNATURE_STATE state) +#if !UNIX + private static uint GetErrorFromSignatureState(SignatureState signatureState) { - switch (state) + switch (signatureState) { - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_MISSING: return Win32Errors.TRUST_E_NOSIGNATURE; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_UNSUPPORTED: return Win32Errors.TRUST_E_NOSIGNATURE; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNSIGNED_POLICY: return Win32Errors.TRUST_E_NOSIGNATURE; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_INVALID_CORRUPT: return Win32Errors.TRUST_E_BAD_DIGEST; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_INVALID_POLICY: return Win32Errors.CRYPT_E_BAD_MSG; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_VALID: return Win32Errors.NO_ERROR; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_TRUSTED: return Win32Errors.NO_ERROR; - case NativeMethods.SIGNATURE_STATE.SIGNATURE_STATE_UNTRUSTED: return Win32Errors.TRUST_E_EXPLICIT_DISTRUST; - - // Should not happen + case SignatureState.Unsigned: + return Win32Errors.TRUST_E_NOSIGNATURE; + + case SignatureState.SignedAndTrusted: + return Win32Errors.NO_ERROR; + + case SignatureState.SignedAndNotTrusted: + return Win32Errors.TRUST_E_EXPLICIT_DISTRUST; + + case SignatureState.Invalid: + return Win32Errors.TRUST_E_BAD_DIGEST; + default: - System.Diagnostics.Debug.Fail("Should not get here - could not map SIGNATURE_STATE"); + System.Diagnostics.Debug.Fail("Should not get here - could not map FileSignatureInfo.State"); return Win32Errors.TRUST_E_NOSIGNATURE; } } +#endif - private static Signature GetSignatureFromWinVerifyTrust(string fileName, string fileContent) + private static Signature GetSignatureFromWinVerifyTrust(string fileName, byte[] fileContent) { Signature signature = null; - NativeMethods.WINTRUST_DATA wtd; - DWORD error = Win32Errors.E_FAIL; + WinTrustMethods.WINTRUST_DATA wtd; + uint error = Win32Errors.E_FAIL; if (fileContent == null) { Utils.CheckArgForNullOrEmpty(fileName, "fileName"); SecuritySupport.CheckIfFileExists(fileName); + // SecurityUtils.CheckIfFileSmallerThan4Bytes(fileName); } @@ -456,7 +424,11 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string signature = GetSignatureFromWintrustData(fileName, error, wtd); - error = NativeMethods.DestroyWintrustDataStruct(wtd); + wtd.dwStateAction = WinTrustAction.WTD_STATEACTION_CLOSE; + error = WinTrustMethods.WinVerifyTrust( + IntPtr.Zero, + ref WINTRUST_ACTION_GENERIC_VERIFY_V2, + ref wtd); if (error != Win32Errors.NO_ERROR) { @@ -471,90 +443,82 @@ private static Signature GetSignatureFromWinVerifyTrust(string fileName, string return signature; } - [ArchitectureSensitive] - private static DWORD GetWinTrustData(string fileName, string fileContent, - out NativeMethods.WINTRUST_DATA wtData) + private static uint GetWinTrustData( + string fileName, + byte[] fileContent, + out WinTrustMethods.WINTRUST_DATA wtData) { - DWORD dwResult = Win32Errors.E_FAIL; - IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; - IntPtr wtdBuffer = IntPtr.Zero; - - Guid actionVerify = - new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); - - try + wtData = new() { - WINTRUST_ACTION_GENERIC_VERIFY_V2 = - Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); - Marshal.StructureToPtr(actionVerify, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - false); - - NativeMethods.WINTRUST_DATA wtd; + cbStruct = (uint)Marshal.SizeOf(), + dwUIChoice = WinTrustUIChoice.WTD_UI_NONE, + dwStateAction = WinTrustAction.WTD_STATEACTION_VERIFY, + }; - if (fileContent == null) - { - NativeMethods.WINTRUST_FILE_INFO wfi = NativeMethods.InitWintrustFileInfoStruct(fileName); - wtd = NativeMethods.InitWintrustDataStructFromFile(wfi); - } - else + unsafe + { + fixed (char* fileNamePtr = fileName) { - NativeMethods.WINTRUST_BLOB_INFO wbi = NativeMethods.InitWintrustBlobInfoStruct(fileName, fileContent); - wtd = NativeMethods.InitWintrustDataStructFromBlob(wbi); - } - - wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); - Marshal.StructureToPtr(wtd, wtdBuffer, false); - - // The result is returned to the caller, and handled generically. - // Disable the PreFast check for Win32 error codes, as we don't care. -#pragma warning disable 56523 - dwResult = NativeMethods.WinVerifyTrust( - IntPtr.Zero, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - wtdBuffer); -#pragma warning restore 56523 + if (fileContent == null) + { + WinTrustMethods.WINTRUST_FILE_INFO wfi = new() + { + cbStruct = (uint)Marshal.SizeOf(), + pcwszFilePath = fileNamePtr, + }; + wtData.dwUnionChoice = WinTrustUnionChoice.WTD_CHOICE_FILE; + wtData.pChoice = &wfi; + + return WinTrustMethods.WinVerifyTrust( + IntPtr.Zero, + ref WINTRUST_ACTION_GENERIC_VERIFY_V2, + ref wtData); + } - wtData = Marshal.PtrToStructure(wtdBuffer); - } - finally - { - Marshal.DestroyStructure(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.DestroyStructure(wtdBuffer); - Marshal.FreeCoTaskMem(wtdBuffer); + fixed (byte* contentPtr = fileContent) + { + Guid pwshSIP = new("603BCC1F-4B59-4E08-B724-D2C6297EF351"); + WinTrustMethods.WINTRUST_BLOB_INFO wbi = new() + { + cbStruct = (uint)Marshal.SizeOf(), + gSubject = pwshSIP, + pcwszDisplayName = fileNamePtr, + cbMemObject = (uint)fileContent.Length, + pbMemObject = contentPtr, + }; + wtData.dwUnionChoice = WinTrustUnionChoice.WTD_CHOICE_BLOB; + wtData.pChoice = &wbi; + + return WinTrustMethods.WinVerifyTrust( + IntPtr.Zero, + ref WINTRUST_ACTION_GENERIC_VERIFY_V2, + ref wtData); + } + } } - - return dwResult; } - [ArchitectureSensitive] private static X509Certificate2 GetCertFromChain(IntPtr pSigner) { - X509Certificate2 signerCert = null; - - // We don't care about the Win32 error code here, so disable - // the PreFast complaint that we're not retrieving it. -#pragma warning disable 56523 - IntPtr pCert = - NativeMethods.WTHelperGetProvCertFromChain(pSigner, 0); -#pragma warning restore 56523 - - if (pCert != IntPtr.Zero) + try { + IntPtr pCert = WinTrustMethods.WTHelperGetProvCertFromChain(pSigner, 0); NativeMethods.CRYPT_PROVIDER_CERT provCert = Marshal.PtrToStructure(pCert); - signerCert = new X509Certificate2(provCert.pCert); + return new X509Certificate2(provCert.pCert); + } + catch (Win32Exception) + { + // We don't care about the Win32 error code here, so return + // null on a failure and let the caller handle it. + return null; } - - return signerCert; } - [ArchitectureSensitive] private static Signature GetSignatureFromWintrustData( string filePath, - DWORD error, - NativeMethods.WINTRUST_DATA wtd) + uint error, + WinTrustMethods.WINTRUST_DATA wtd) { s_tracer.WriteLine("GetSignatureFromWintrustData: error: {0}", error); @@ -596,45 +560,40 @@ private static Signature GetSignatureFromWintrustData( return signature; } - [ArchitectureSensitive] private static bool TryGetProviderSigner(IntPtr wvtStateData, out IntPtr pProvSigner, out X509Certificate2 timestamperCert) { pProvSigner = IntPtr.Zero; timestamperCert = null; - // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be - // able to see that. -#pragma warning disable 56523 - IntPtr pProvData = - NativeMethods.WTHelperProvDataFromStateData(wvtStateData); -#pragma warning restore 56523 - - if (pProvData != IntPtr.Zero) + try { - pProvSigner = - NativeMethods.WTHelperGetProvSignerFromChain(pProvData, 0, 0, 0); + IntPtr pProvData = WinTrustMethods.WTHelperProvDataFromStateData(wvtStateData); - if (pProvSigner != IntPtr.Zero) - { - NativeMethods.CRYPT_PROVIDER_SGNR provSigner = - Marshal.PtrToStructure(pProvSigner); - if (provSigner.csCounterSigners == 1) - { - // - // time stamper cert available - // - timestamperCert = GetCertFromChain(provSigner.pasCounterSigners); - } + pProvSigner = WinTrustMethods.WTHelperGetProvSignerFromChain( + pProvData, + signerIdx: 0, + counterSigner: false, + counterSignerIdx: 0); - return true; + NativeMethods.CRYPT_PROVIDER_SGNR provSigner = + Marshal.PtrToStructure(pProvSigner); + if (provSigner.csCounterSigners == 1) + { + // + // time stamper cert available + // + timestamperCert = GetCertFromChain(provSigner.pasCounterSigners); } - } - return false; + return true; + } + catch (Win32Exception) + { + return false; + } } - [ArchitectureSensitive] - private static DWORD GetLastWin32Error() + private static uint GetLastWin32Error() { int error = Marshal.GetLastWin32Error(); diff --git a/src/System.Management.Automation/security/CatalogHelper.cs b/src/System.Management.Automation/security/CatalogHelper.cs index 0c1c76b63e4..4892f7434e4 100644 --- a/src/System.Management.Automation/security/CatalogHelper.cs +++ b/src/System.Management.Automation/security/CatalogHelper.cs @@ -6,12 +6,13 @@ using System.Security.Cryptography; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.ComponentModel; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Security; +using System.Management.Automation.Win32Native; using System.Runtime.InteropServices; -using DWORD = System.UInt32; namespace System.Management.Automation { @@ -68,14 +69,14 @@ public class CatalogInformation internal static class CatalogHelper { // Catalog Version is (0X100 = 256) for Catalog Version 1 - private static int catalogVersion1 = 256; + private const int catalogVersion1 = 256; // Catalog Version is (0X200 = 512) for Catalog Version 2 - private static int catalogVersion2 = 512; + private const int catalogVersion2 = 512; // Hash Algorithms supported by Windows Catalog - private static string HashAlgorithmSHA1 = "SHA1"; - private static string HashAlgorithmSHA256 = "SHA256"; + private const string HashAlgorithmSHA1 = "SHA1"; + private const string HashAlgorithmSHA256 = "SHA256"; private static PSCmdlet _cmdlet = null; /// @@ -83,12 +84,11 @@ internal static class CatalogHelper /// /// Handle to open catalog file. /// Version of the catalog. - private static int GetCatalogVersion(IntPtr catalogHandle) + private static int GetCatalogVersion(SafeCATHandle catalogHandle) { int catalogVersion = -1; - IntPtr catalogData = NativeMethods.CryptCATStoreFromHandle(catalogHandle); - NativeMethods.CRYPTCATSTORE catalogInfo = Marshal.PtrToStructure(catalogData); + WinTrustMethods.CRYPTCATSTORE catalogInfo = WinTrustMethods.CryptCATStoreFromHandle(catalogHandle); if (catalogInfo.dwPublicVersion == catalogVersion2) { @@ -220,9 +220,8 @@ internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileTo relativePath = fileToHash.Name; } - if (!relativePaths.Contains(relativePath)) + if (relativePaths.Add(relativePath)) { - relativePaths.Add(relativePath); if (fileToHash.Length != 0) { cdfFilesContent += "" + fileToHash.FullName + "=" + fileToHash.FullName + Environment.NewLine; @@ -248,20 +247,32 @@ internal static void ProcessFileToBeAddedInCatalogDefinitionFile(FileInfo fileTo /// Path to the Input .cdf file. internal static void GenerateCatalogFile(string cdfFilePath) { - string pwszFilePath = cdfFilePath; - NativeMethods.CryptCATCDFOpenCallBack catOpenCallBack = new NativeMethods.CryptCATCDFOpenCallBack(ParseErrorCallback); - // Open CDF File - IntPtr resultCDF = NativeMethods.CryptCATCDFOpen(pwszFilePath, catOpenCallBack); + SafeCATCDFHandle resultCDF; + try + { + resultCDF = WinTrustMethods.CryptCATCDFOpen(cdfFilePath, ParseErrorCallback); + } + catch (Win32Exception e) + { + // If we are not able to open CDF file we can not continue generating catalog + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile, e), + "UnableToOpenCatalogDefinitionFile", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); + return; + } // navigate CDF header and files sections - if (resultCDF != IntPtr.Zero) + using (resultCDF) { // First navigate all catalog level attributes entries first, they represent zero size files IntPtr catalogAttr = IntPtr.Zero; do { - catalogAttr = NativeMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, catOpenCallBack); + catalogAttr = WinTrustMethods.CryptCATCDFEnumCatAttributes(resultCDF, catalogAttr, ParseErrorCallback); if (catalogAttr != IntPtr.Zero) { @@ -272,51 +283,38 @@ internal static void GenerateCatalogFile(string cdfFilePath) // navigate all the files hash entries in the .cdf file IntPtr memberInfo = IntPtr.Zero; - try + IntPtr memberFile = IntPtr.Zero; + string fileName = string.Empty; + do { - IntPtr memberFile = IntPtr.Zero; - NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack memberCallBack = new NativeMethods.CryptCATCDFEnumMembersByCDFTagExErrorCallBack(ParseErrorCallback); - string fileName = string.Empty; - do - { - memberFile = NativeMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, memberCallBack, ref memberInfo, true, IntPtr.Zero); - fileName = Marshal.PtrToStringUni(memberFile); + memberFile = WinTrustMethods.CryptCATCDFEnumMembersByCDFTagEx(resultCDF, memberFile, ParseErrorCallback, ref memberInfo, + fContinueOnError: true, pvReserved: IntPtr.Zero); + fileName = Marshal.PtrToStringUni(memberFile); - if (!string.IsNullOrEmpty(fileName)) + if (!string.IsNullOrEmpty(fileName)) + { + IntPtr memberAttr = IntPtr.Zero; + string fileRelativePath = string.Empty; + do { - IntPtr memberAttr = IntPtr.Zero; - string fileRelativePath = string.Empty; - do - { - memberAttr = NativeMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, memberCallBack); + memberAttr = WinTrustMethods.CryptCATCDFEnumAttributesWithCDFTag(resultCDF, memberFile, memberInfo, memberAttr, ParseErrorCallback); - if (memberAttr != IntPtr.Zero) + if (memberAttr != IntPtr.Zero) + { + fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr); + if (!string.IsNullOrEmpty(fileRelativePath)) { - fileRelativePath = ProcessFilePathAttributeInCatalog(memberAttr); - if (!string.IsNullOrEmpty(fileRelativePath)) - { - // Found the attribute we are looking for - // Filename we read from the above API has appended to its name as per CDF file tags convention - // Truncating that Information from the string. - string itemName = fileName.Substring(6); - _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); - break; - } + // Found the attribute we are looking for + // Filename we read from the above API has appended to its name as per CDF file tags convention + // Truncating that Information from the string. + string itemName = fileName.Substring(6); + _cmdlet.WriteVerbose(StringUtil.Format(CatalogStrings.AddFileToCatalog, itemName, fileRelativePath)); + break; } - } while (memberAttr != IntPtr.Zero); - } - } while (fileName != null); - } - finally - { - NativeMethods.CryptCATCDFClose(resultCDF); - } - } - else - { - // If we are not able to open CDF file we can not continue generating catalog - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(CatalogStrings.UnableToOpenCatalogDefinitionFile), "UnableToOpenCatalogDefinitionFile", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + } + } while (memberAttr != IntPtr.Zero); + } + } while (fileName != null); } } @@ -374,7 +372,7 @@ internal static string ProcessFilePathAttributeInCatalog(IntPtr memberAttrInfo) { string relativePath = string.Empty; - NativeMethods.CRYPTCATATTRIBUTE currentMemberAttr = Marshal.PtrToStructure(memberAttrInfo); + WinTrustMethods.CRYPTCATATTRIBUTE currentMemberAttr = Marshal.PtrToStructure(memberAttrInfo); // check if this is the attribute we are looking for // catalog generated other way not using New-FileCatalog can have attributes we don't understand @@ -400,69 +398,65 @@ internal static string ProcessFilePathAttributeInCatalog(IntPtr memberAttrInfo) internal static string CalculateFileHash(string filePath, string hashAlgorithm) { string hashValue = string.Empty; - IntPtr catAdmin = IntPtr.Zero; // To get handle to the hash algorithm to be used to calculate hashes - if (!NativeMethods.CryptCATAdminAcquireContext2(ref catAdmin, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0)) + SafeCATAdminHandle catAdmin; + try { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm)), "UnableToAcquireHashAlgorithmContext", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + catAdmin = WinTrustMethods.CryptCATAdminAcquireContext2(hashAlgorithm); } + catch (Win32Exception e) + { + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToAcquireHashAlgorithmContext, hashAlgorithm), e), + "UnableToAcquireHashAlgorithmContext", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); - const DWORD GENERIC_READ = 0x80000000; - const DWORD OPEN_EXISTING = 3; - IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); + // The method returns an empty string on a failure. + return hashValue; + } // Open the file that is to be hashed for reading and get its handle - IntPtr fileHandle = NativeMethods.CreateFile(filePath, GENERIC_READ, 0, 0, OPEN_EXISTING, 0, IntPtr.Zero); - if (fileHandle != INVALID_HANDLE_VALUE) + FileStream fileStream; + try { - try - { - DWORD hashBufferSize = 0; - IntPtr hashBuffer = IntPtr.Zero; - - // Call first time to get the size of expected buffer to hold new hash value - if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); - } + fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); + } + catch (Exception e) + { + // If we are not able to open file that is to be hashed we can not continue with catalog validation + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath), e), + "UnableToReadFileToHash", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); - int size = (int)hashBufferSize; - hashBuffer = Marshal.AllocHGlobal(size); - try - { - // Call second time to actually get the hash value - if (!NativeMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileHandle, ref hashBufferSize, hashBuffer, 0)) - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath)), "UnableToCreateFileHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); - } + // The method returns an empty string on a failure. + return hashValue; + } - byte[] hashBytes = new byte[size]; - Marshal.Copy(hashBuffer, hashBytes, 0, size); - hashValue = BitConverter.ToString(hashBytes).Replace("-", string.Empty); - } - finally - { - if (hashBuffer != IntPtr.Zero) - { - Marshal.FreeHGlobal(hashBuffer); - } - } + using (catAdmin) + using (fileStream) + { + byte[] hashBytes = Array.Empty(); + try + { + hashBytes = WinTrustMethods.CryptCATAdminCalcHashFromFileHandle2(catAdmin, fileStream.SafeFileHandle); } - finally + catch (Win32Exception e) { - NativeMethods.CryptCATAdminReleaseContext(catAdmin, 0); - NativeMethods.CloseHandle(fileHandle); + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToCreateFileHash, filePath), e), + "UnableToCreateFileHash", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); } - } - else - { - // If we are not able to open file that is to be hashed we can not continue with catalog validation - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToReadFileToHash, filePath)), "UnableToReadFileToHash", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + + hashValue = Convert.ToHexString(hashBytes); } return hashValue; @@ -477,90 +471,92 @@ internal static string CalculateFileHash(string filePath, string hashAlgorithm) /// Dictionary mapping files relative paths to HashValues. internal static Dictionary GetHashesFromCatalog(string catalogFilePath, WildcardPattern[] excludedPatterns, out int catalogVersion) { - IntPtr resultCatalog = NativeMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); - IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); Dictionary catalogHashes = new Dictionary(StringComparer.CurrentCultureIgnoreCase); catalogVersion = 0; - if (resultCatalog != INVALID_HANDLE_VALUE) + SafeCATHandle resultCatalog; + try { - try + resultCatalog = WinTrustMethods.CryptCATOpen(catalogFilePath, 0, IntPtr.Zero, 1, 0); + } + catch (Win32Exception e) + { + ErrorRecord errorRecord = new ErrorRecord( + new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath), e), + "UnableToOpenCatalogFile", + ErrorCategory.InvalidOperation, + null); + _cmdlet.ThrowTerminatingError(errorRecord); + return catalogHashes; + } + + using (resultCatalog) + { + IntPtr catAttrInfo = IntPtr.Zero; + + // First traverse all catalog level attributes to get information about zero size file. + do { - IntPtr catAttrInfo = IntPtr.Zero; + catAttrInfo = WinTrustMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo); - // First traverse all catalog level attributes to get information about zero size file. - do + // If we found attribute it is a file information retrieve its relative path + // and add it to catalog hash collection if its not in excluded files criteria + if (catAttrInfo != IntPtr.Zero) { - catAttrInfo = NativeMethods.CryptCATEnumerateCatAttr(resultCatalog, catAttrInfo); - - // If we found attribute it is a file information retrieve its relative path - // and add it to catalog hash collection if its not in excluded files criteria - if (catAttrInfo != IntPtr.Zero) + string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo); + if (!string.IsNullOrEmpty(relativePath)) { - string relativePath = ProcessFilePathAttributeInCatalog(catAttrInfo); - if (!string.IsNullOrEmpty(relativePath)) - { - ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes); - } + ProcessCatalogFile(relativePath, string.Empty, excludedPatterns, ref catalogHashes); } - } while (catAttrInfo != IntPtr.Zero); + } + } while (catAttrInfo != IntPtr.Zero); - catalogVersion = GetCatalogVersion(resultCatalog); + catalogVersion = GetCatalogVersion(resultCatalog); - IntPtr memberInfo = IntPtr.Zero; - // Next Navigate all members in Catalog files and get their relative paths and hashes - do + IntPtr memberInfo = IntPtr.Zero; + // Next Navigate all members in Catalog files and get their relative paths and hashes + do + { + memberInfo = WinTrustMethods.CryptCATEnumerateMember(resultCatalog, memberInfo); + if (memberInfo != IntPtr.Zero) { - memberInfo = NativeMethods.CryptCATEnumerateMember(resultCatalog, memberInfo); - if (memberInfo != IntPtr.Zero) - { - NativeMethods.CRYPTCATMEMBER currentMember = Marshal.PtrToStructure(memberInfo); - NativeMethods.SIP_INDIRECT_DATA pIndirectData = Marshal.PtrToStructure(currentMember.pIndirectData); + WinTrustMethods.CRYPTCATMEMBER currentMember = Marshal.PtrToStructure(memberInfo); + WinTrustMethods.SIP_INDIRECT_DATA pIndirectData = Marshal.PtrToStructure(currentMember.pIndirectData); - // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well - // We validate those along with file hashes so we are skipping duplicate entries - if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) + // For Catalog version 2 CryptoAPI puts hashes of file attributes(relative path in our case) in Catalog as well + // We validate those along with file hashes so we are skipping duplicate entries + if (!((catalogVersion == 2) && (pIndirectData.DigestAlgorithm.pszObjId.Equals(new Oid("SHA1").Value, StringComparison.OrdinalIgnoreCase)))) + { + string relativePath = string.Empty; + IntPtr memberAttrInfo = IntPtr.Zero; + do { - string relativePath = string.Empty; - IntPtr memberAttrInfo = IntPtr.Zero; - do - { - memberAttrInfo = NativeMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo); + memberAttrInfo = WinTrustMethods.CryptCATEnumerateAttr(resultCatalog, memberInfo, memberAttrInfo); - if (memberAttrInfo != IntPtr.Zero) + if (memberAttrInfo != IntPtr.Zero) + { + relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo); + if (!string.IsNullOrEmpty(relativePath)) { - relativePath = ProcessFilePathAttributeInCatalog(memberAttrInfo); - if (!string.IsNullOrEmpty(relativePath)) - { - break; - } + break; } } - while (memberAttrInfo != IntPtr.Zero); - - // If we did not find any Relative Path for the item in catalog we should quit - // This catalog must not be valid for our use as catalogs generated using New-FileCatalog - // always contains relative file Paths - if (string.IsNullOrEmpty(relativePath)) - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); - } + } + while (memberAttrInfo != IntPtr.Zero); - ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); + // If we did not find any Relative Path for the item in catalog we should quit + // This catalog must not be valid for our use as catalogs generated using New-FileCatalog + // always contains relative file Paths + if (string.IsNullOrEmpty(relativePath)) + { + ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); + _cmdlet.ThrowTerminatingError(errorRecord); } + + ProcessCatalogFile(relativePath, currentMember.pwszReferenceTag, excludedPatterns, ref catalogHashes); } - } while (memberInfo != IntPtr.Zero); - } - finally - { - NativeMethods.CryptCATClose(resultCatalog); - } - } - else - { - ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.UnableToOpenCatalogFile, catalogFilePath)), "UnableToOpenCatalogFile", ErrorCategory.InvalidOperation, null); - _cmdlet.ThrowTerminatingError(errorRecord); + } + } while (memberInfo != IntPtr.Zero); } return catalogHashes; @@ -692,8 +688,8 @@ internal static bool CompareDictionaries(Dictionary catalogItems List relativePathsFromFolder = pathItems.Keys.ToList(); List relativePathsFromCatalog = catalogItems.Keys.ToList(); - // Find entires those are not in both list lists. These should be empty lists for success - // Hashes in Catalog should be exact similar to the ones from folder + // Find entries that are not in both lists. These should be empty lists for success + // Hashes in Catalog should be exactly similar to the ones from folder List relativePathsNotInFolder = relativePathsFromFolder.Except(relativePathsFromCatalog, StringComparer.CurrentCultureIgnoreCase).ToList(); List relativePathsNotInCatalog = relativePathsFromCatalog.Except(relativePathsFromFolder, StringComparer.CurrentCultureIgnoreCase).ToList(); @@ -785,14 +781,18 @@ internal static bool CheckExcludedCriteria(string filename, WildcardPattern[] ex /// /// Call back when error is thrown by catalog API's. /// - private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, string pwszLine) + private static void ParseErrorCallback(uint dwErrorArea, uint dwLocalError, string pwszLine) { switch (dwErrorArea) { - case NativeConstants.CRYPTCAT_E_AREA_HEADER: break; - case NativeConstants.CRYPTCAT_E_AREA_MEMBER: break; - case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: break; - default: break; + case NativeConstants.CRYPTCAT_E_AREA_HEADER: + break; + case NativeConstants.CRYPTCAT_E_AREA_MEMBER: + break; + case NativeConstants.CRYPTCAT_E_AREA_ATTRIBUTE: + break; + default: + break; } switch (dwLocalError) @@ -815,18 +815,24 @@ private static void ParseErrorCallback(DWORD dwErrorArea, DWORD dwLocalError, st _cmdlet.ThrowTerminatingError(errorRecord); break; } - case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: break; - case NativeConstants.CRYPTCAT_E_CDF_ATTR_TYPECOMBO: break; - case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: break; - case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: break; + case NativeConstants.CRYPTCAT_E_CDF_BAD_GUID_CONV: + break; + case NativeConstants.CRYPTCAT_E_CDF_ATTR_TYPECOMBO: + break; + case NativeConstants.CRYPTCAT_E_CDF_ATTR_TOOFEWVALUES: + break; + case NativeConstants.CRYPTCAT_E_CDF_UNSUPPORTED: + break; case NativeConstants.CRYPTCAT_E_CDF_DUPLICATE: { ErrorRecord errorRecord = new ErrorRecord(new InvalidOperationException(StringUtil.Format(CatalogStrings.FoundDuplicateFileMemberInCatalog, pwszLine)), "FoundDuplicateFileMemberInCatalog", ErrorCategory.InvalidOperation, null); _cmdlet.ThrowTerminatingError(errorRecord); break; } - case NativeConstants.CRYPTCAT_E_CDF_TAGNOTFOUND: break; - default: break; + case NativeConstants.CRYPTCAT_E_CDF_TAGNOTFOUND: + break; + default: + break; } } } diff --git a/src/System.Management.Automation/security/CredentialParameter.cs b/src/System.Management.Automation/security/CredentialParameter.cs index 0d48e4fa738..1ea19691ae7 100644 --- a/src/System.Management.Automation/security/CredentialParameter.cs +++ b/src/System.Management.Automation/security/CredentialParameter.cs @@ -89,4 +89,3 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input } #pragma warning restore 56506 - diff --git a/src/System.Management.Automation/security/MshSignature.cs b/src/System.Management.Automation/security/MshSignature.cs index 96ff8a9638a..7cbaf98d3a5 100644 --- a/src/System.Management.Automation/security/MshSignature.cs +++ b/src/System.Management.Automation/security/MshSignature.cs @@ -110,7 +110,7 @@ public sealed class Signature // Three states: // - True: we can rely on the catalog API to check catalog signature. - // - False: we cannot rely on the catalog API, either because it doesn't exist in the OS (win7), + // - False: we cannot rely on the catalog API, either because it doesn't exist in the OS (win7, nano), // or it's not working properly (OneCore SKUs or dev environment where powershell might // be updated/refreshed). // - Null: it's not determined yet whether catalog API can be relied on or not. @@ -185,6 +185,11 @@ public string Path /// public bool IsOSBinary { get; internal set; } + /// + /// Gets the Subject Alternative Name from the signer certificate. + /// + public string[] SubjectAlternativeName { get; private set; } + /// /// Constructor for class Signature /// @@ -277,6 +282,9 @@ private void Init(string filePath, _statusMessage = GetSignatureStatusMessage(isc, error, filePath); + + // Extract Subject Alternative Name from the signer certificate + SubjectAlternativeName = GetSubjectAlternativeName(signer); } private static SignatureStatus GetSignatureStatusFromWin32Error(DWORD error) @@ -389,5 +397,34 @@ private static string GetSignatureStatusMessage(SignatureStatus status, return message; } + + /// + /// Extracts the Subject Alternative Name from the certificate. + /// + /// The certificate to extract SAN from. + /// Array of SAN entries or null if not found. + private static string[] GetSubjectAlternativeName(X509Certificate2 certificate) + { + if (certificate == null) + { + return null; + } + + foreach (X509Extension extension in certificate.Extensions) + { + if (extension.Oid != null && extension.Oid.Value == CertificateFilterInfo.SubjectAlternativeNameOid) + { + string formatted = extension.Format(multiLine: true); + if (string.IsNullOrEmpty(formatted)) + { + return null; + } + + return formatted.Split(new[] { "\r\n", "\n", "\r" }, StringSplitOptions.RemoveEmptyEntries); + } + } + + return null; + } } } diff --git a/src/System.Management.Automation/security/SecureStringHelper.cs b/src/System.Management.Automation/security/SecureStringHelper.cs index 4611463ae0e..5ff5881bab4 100644 --- a/src/System.Management.Automation/security/SecureStringHelper.cs +++ b/src/System.Management.Automation/security/SecureStringHelper.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Management.Automation; @@ -30,7 +31,7 @@ internal static class SecureStringHelper /// /// Input data. /// A SecureString . - private static SecureString New(byte[] data) + internal static SecureString New(byte[] data) { if ((data.Length % 2) != 0) { @@ -67,7 +68,6 @@ private static SecureString New(byte[] data) /// /// Input string. /// Contents of s (char[]) converted to byte[]. - [ArchitectureSensitive] internal static byte[] GetData(SecureString s) { // @@ -216,8 +216,6 @@ internal static SecureString Unprotect(string input) /// A string (see summary). internal static EncryptionResult Encrypt(SecureString input, SecureString key) { - EncryptionResult output = null; - // // get clear text key from the SecureString key // @@ -226,14 +224,14 @@ internal static EncryptionResult Encrypt(SecureString input, SecureString key) // // encrypt the data // - output = Encrypt(input, keyBlob); - - // - // clear the clear text key - // - Array.Clear(keyBlob, 0, keyBlob.Length); - - return output; + try + { + return Encrypt(input, keyBlob); + } + finally + { + Array.Clear(keyBlob); + } } /// @@ -253,48 +251,43 @@ internal static EncryptionResult Encrypt(SecureString input, byte[] key, byte[] Utils.CheckSecureStringArg(input, "input"); Utils.CheckKeyArg(key, "key"); - byte[] encryptedData = null; - MemoryStream ms = null; - ICryptoTransform encryptor = null; - CryptoStream cs = null; - // // prepare the crypto stuff. Initialization Vector is // randomized by default. // - Aes aes = Aes.Create(); - if (iv == null) - iv = aes.IV; - - encryptor = aes.CreateEncryptor(key, iv); - ms = new MemoryStream(); - - using (cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write)) + using (Aes aes = Aes.Create()) { + iv ??= aes.IV; + // // get clear text data from the input SecureString // byte[] data = GetData(input); + try + { + using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv)) + using (var sourceStream = new MemoryStream(data)) + using (var encryptedStream = new MemoryStream()) + { + // + // encrypt it + // + using (var cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write)) + { + sourceStream.CopyTo(cryptoStream); + } - // - // encrypt it - // - cs.Write(data, 0, data.Length); - cs.FlushFinalBlock(); - - // - // clear the clear text data array - // - Array.Clear(data, 0, data.Length); - - // - // convert the encrypted blob to a string - // - encryptedData = ms.ToArray(); - - EncryptionResult output = new EncryptionResult(ByteArrayToString(encryptedData), Convert.ToBase64String(iv)); - - return output; + // + // return encrypted data + // + byte[] encryptedData = encryptedStream.ToArray(); + return new EncryptionResult(ByteArrayToString(encryptedData), Convert.ToBase64String(iv)); + } + } + finally + { + Array.Clear(data, 0, data.Length); + } } } @@ -310,8 +303,6 @@ internal static EncryptionResult Encrypt(SecureString input, byte[] key, byte[] /// SecureString . internal static SecureString Decrypt(string input, SecureString key, byte[] IV) { - SecureString output = null; - // // get clear text key from the SecureString key // @@ -320,14 +311,14 @@ internal static SecureString Decrypt(string input, SecureString key, byte[] IV) // // decrypt the data // - output = Decrypt(input, keyBlob, IV); - - // - // clear the clear text key - // - Array.Clear(keyBlob, 0, keyBlob.Length); - - return output; + try + { + return Decrypt(input, keyBlob, IV); + } + finally + { + Array.Clear(keyBlob); + } } /// @@ -345,46 +336,55 @@ internal static SecureString Decrypt(string input, byte[] key, byte[] IV) Utils.CheckArgForNullOrEmpty(input, "input"); Utils.CheckKeyArg(key, "key"); - byte[] decryptedData = null; - byte[] encryptedData = null; - SecureString s = null; - // // prepare the crypto stuff // - Aes aes = Aes.Create(); - encryptedData = ByteArrayFromString(input); - - var decryptor = aes.CreateDecryptor(key, IV ?? aes.IV); - - MemoryStream ms = new MemoryStream(encryptedData); - - using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read)) + using (var aes = Aes.Create()) { - byte[] tempDecryptedData = new byte[encryptedData.Length]; - - int numBytesRead = 0; - - // - // decrypt the data - // - numBytesRead = cs.Read(tempDecryptedData, 0, - tempDecryptedData.Length); - - decryptedData = new byte[numBytesRead]; - - for (int i = 0; i < numBytesRead; i++) + using (ICryptoTransform decryptor = aes.CreateDecryptor(key, IV ?? aes.IV)) + using (var encryptedStream = new MemoryStream(ByteArrayFromString(input))) + using (var targetStream = new MemoryStream()) { - decryptedData[i] = tempDecryptedData[i]; + // + // decrypt the data and return as SecureString + // + using (var sourceStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read)) + { + sourceStream.CopyTo(targetStream); + } + + byte[] decryptedData = targetStream.ToArray(); + try + { + return New(decryptedData); + } + finally + { + Array.Clear(decryptedData); + } } + } + } - s = New(decryptedData); - Array.Clear(decryptedData, 0, decryptedData.Length); - Array.Clear(tempDecryptedData, 0, tempDecryptedData.Length); +#nullable enable + /// Creates a new from a . + /// Plain text string. Must not be null. + /// A new SecureString. + internal static unsafe SecureString FromPlainTextString(string plainTextString) + { + Debug.Assert(plainTextString is not null); - return s; + if (plainTextString.Length == 0) + { + return new SecureString(); + } + + fixed (char* charsPtr = plainTextString) + { + return new SecureString(charsPtr, plainTextString.Length); } } +#nullable restore } /// @@ -430,10 +430,7 @@ internal static class ProtectedData /// public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtectionScope scope) { - if (userData == null) - { - throw new ArgumentNullException(nameof(userData)); - } + ArgumentNullException.ThrowIfNull(userData); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); @@ -518,10 +515,7 @@ public static byte[] Protect(byte[] userData, byte[] optionalEntropy, DataProtec /// public static byte[] Unprotect(byte[] encryptedData, byte[] optionalEntropy, DataProtectionScope scope) { - if (encryptedData == null) - { - throw new ArgumentNullException(nameof(encryptedData)); - } + ArgumentNullException.ThrowIfNull(encryptedData); GCHandle pbDataIn = new GCHandle(); GCHandle pOptionalEntropy = new GCHandle(); @@ -600,7 +594,7 @@ internal static class CAPI internal const int E_FILENOTFOUND = unchecked((int)0x80070002); // File not found internal const int ERROR_FILE_NOT_FOUND = 2; // File not found - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct CRYPTOAPI_BLOB { internal uint cbData; diff --git a/src/System.Management.Automation/security/SecurityManager.cs b/src/System.Management.Automation/security/SecurityManager.cs index 5d7295354be..137daecc5b4 100644 --- a/src/System.Management.Automation/security/SecurityManager.cs +++ b/src/System.Management.Automation/security/SecurityManager.cs @@ -19,7 +19,7 @@ namespace Microsoft.PowerShell { /// /// Defines the authorization policy that controls the way scripts - /// (and other command types) are handled by Monad. This authorization + /// (and other command types) are handled by PowerShell. This authorization /// policy enforces one of four levels, as defined by the 'ExecutionPolicy' /// value in one of the following locations: /// @@ -40,14 +40,14 @@ namespace Microsoft.PowerShell /// signed, and by a trusted publisher. If you haven't made a trust decision /// on the publisher yet, prompting is done as in AllSigned mode. /// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If - /// signed and executed, Monad prompts to determine if files from the + /// signed and executed, PowerShell prompts to determine if files from the /// signing publisher should be run or not. /// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet - /// must be digitally signed. If remote, signed, and executed, Monad + /// must be digitally signed. If remote, signed, and executed, PowerShell /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. /// Unrestricted - No files must be signed. If a file originates from the - /// internet, Monad provides a warning prompt to alert the user. To + /// internet, PowerShell provides a warning prompt to alert the user. To /// suppress this warning message, right-click on the file in File Explorer, /// select "Properties," and then "Unblock." Requires Shell. /// Bypass - No files must be signed, and internet origin is not verified. @@ -69,7 +69,7 @@ internal enum RunPromptDecision private ExecutionPolicy _executionPolicy; // shellId supplied by runspace configuration - private string _shellId; + private readonly string _shellId; /// /// Initializes a new instance of the PSAuthorizationManager @@ -160,7 +160,10 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r } catch (System.ComponentModel.Win32Exception) { - if (saferAttempt > 4) { throw; } + if (saferAttempt > 4) + { + throw; + } saferAttempt++; System.Threading.Thread.Sleep(100); @@ -180,7 +183,7 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r } } - // WLDP and Applocker takes priority over powershell exeuction policy. + // WLDP and Applocker takes priority over powershell execution policy. // See if they want to bypass the authorization manager if (_executionPolicy == ExecutionPolicy.Bypass) { @@ -328,9 +331,10 @@ private bool CheckPolicy(ExternalScriptInfo script, PSHost host, out Exception r if (string.Equals(fi.Extension, ".ps1xml", StringComparison.OrdinalIgnoreCase)) { string[] trustedDirectories = new string[] - { Platform.GetFolderPath(Environment.SpecialFolder.System), - Platform.GetFolderPath(Environment.SpecialFolder.ProgramFiles) - }; + { + Environment.GetFolderPath(Environment.SpecialFolder.System), + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + }; foreach (string trustedDirectory in trustedDirectories) { @@ -442,7 +446,12 @@ private static bool IsTrustedPublisher(Signature signature, string file) foreach (X509Certificate2 trustedCertificate in trustedPublishers.Certificates) { if (string.Equals(trustedCertificate.Thumbprint, thumbprint, StringComparison.OrdinalIgnoreCase)) - if (!IsUntrustedPublisher(signature, file)) return true; + { + if (!IsUntrustedPublisher(signature, file)) + { + return true; + } + } } return false; @@ -533,16 +542,16 @@ private static Signature GetSignatureWithEncodingRetry(string path, ExternalScri // try harder to validate the signature by being explicit about encoding // and providing the script contents - string verificationContents = Encoding.Unicode.GetString(script.OriginalEncoding.GetPreamble()) + script.ScriptContents; - signature = SignatureHelper.GetSignature(path, verificationContents); + byte[] bytesWithBom = GetContentBytesWithBom(script.OriginalEncoding, script.ScriptContents); + signature = SignatureHelper.GetSignature(path, bytesWithBom); // A last ditch effort - // If the file was originally ASCII or UTF8, the SIP may have added the Unicode BOM if (signature.Status != SignatureStatus.Valid && script.OriginalEncoding != Encoding.Unicode) { - verificationContents = Encoding.Unicode.GetString(Encoding.Unicode.GetPreamble()) + script.ScriptContents; - Signature fallbackSignature = SignatureHelper.GetSignature(path, verificationContents); + bytesWithBom = GetContentBytesWithBom(Encoding.Unicode, script.ScriptContents); + Signature fallbackSignature = SignatureHelper.GetSignature(path, bytesWithBom); if (fallbackSignature.Status == SignatureStatus.Valid) signature = fallbackSignature; @@ -551,6 +560,17 @@ private static Signature GetSignatureWithEncodingRetry(string path, ExternalScri return signature; } + private static byte[] GetContentBytesWithBom(Encoding encoding, string scriptContent) + { + ReadOnlySpan bomBytes = encoding.Preamble; + byte[] contentBytes = encoding.GetBytes(scriptContent); + byte[] bytesWithBom = new byte[bomBytes.Length + contentBytes.Length]; + + bomBytes.CopyTo(bytesWithBom); + contentBytes.CopyTo(bytesWithBom, index: bomBytes.Length); + return bytesWithBom; + } + #endregion signing check /// @@ -631,17 +651,23 @@ protected internal override bool ShouldRun(CommandInfo commandInfo, break; case CommandTypes.ExternalScript: - ExternalScriptInfo si = commandInfo as ExternalScriptInfo; - if (si == null) + if (commandInfo is not ExternalScriptInfo si) { reason = PSTraceSource.NewArgumentException("scriptInfo"); } else { bool etwEnabled = ParserEventSource.Log.IsEnabled(); - if (etwEnabled) ParserEventSource.Log.CheckSecurityStart(si.Path); + if (etwEnabled) + { + ParserEventSource.Log.CheckSecurityStart(si.Path); + } + allowRun = CheckPolicy(si, host, out reason); - if (etwEnabled) ParserEventSource.Log.CheckSecurityStop(si.Path); + if (etwEnabled) + { + ParserEventSource.Log.CheckSecurityStop(si.Path); + } } break; diff --git a/src/System.Management.Automation/security/SecuritySupport.cs b/src/System.Management.Automation/security/SecuritySupport.cs index 4afb15be55d..dc6d048c5b1 100644 --- a/src/System.Management.Automation/security/SecuritySupport.cs +++ b/src/System.Management.Automation/security/SecuritySupport.cs @@ -32,23 +32,23 @@ namespace Microsoft.PowerShell public enum ExecutionPolicy { /// Unrestricted - No files must be signed. If a file originates from the - /// internet, Monad provides a warning prompt to alert the user. To + /// internet, PowerShell provides a warning prompt to alert the user. To /// suppress this warning message, right-click on the file in File Explorer, /// select "Properties," and then "Unblock." Unrestricted = 0, - /// RemoteSigned - Only .msh and .mshxml files originating from the internet - /// must be digitally signed. If remote, signed, and executed, Monad + /// RemoteSigned - Only .ps1 and .ps1xml files originating from the internet + /// must be digitally signed. If remote, signed, and executed, PowerShell /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. RemoteSigned = 1, - /// AllSigned - All .msh and .mshxml files must be digitally signed. If - /// signed and executed, Monad prompts to determine if files from the + /// AllSigned - All .ps1 and .ps1xml files must be digitally signed. If + /// signed and executed, PowerShell prompts to determine if files from the /// signing publisher should be run or not. AllSigned = 2, - /// Restricted - All .msh files are blocked. Mshxml files must be digitally + /// Restricted - All .ps1 files are blocked. Ps1xml files must be digitally /// signed, and by a trusted publisher. If you haven't made a trust decision /// on the publisher yet, prompting is done as in AllSigned mode. Restricted = 3, @@ -248,7 +248,7 @@ private static bool IsCurrentProcessLaunchedByGpScript() while (currentProcess != null) { if (string.Equals(gpScriptPath, - PsUtils.GetMainModule(currentProcess).FileName, StringComparison.OrdinalIgnoreCase)) + currentProcess.MainModule.FileName, StringComparison.OrdinalIgnoreCase)) { foundGpScriptParent = true; break; @@ -412,7 +412,7 @@ public static bool IsProductBinary(string file) return true; } - // WTGetSignatureInfo is used to verify catalog signature. + // WTGetSignatureInfo, via Microsoft.Security.Extensions, is used to verify catalog signature. // On Win7, catalog API is not available. // On OneCore SKUs like NanoServer/IoT, the API has a bug that makes it not able to find the // corresponding catalog file for a given product file, so it doesn't work properly. @@ -495,7 +495,6 @@ private static string GetLocalPreferenceValue(string shellId, ExecutionPolicySco /// /// The path to the file in question. /// A file handle to the file in question, if available. - [ArchitectureSensitive] [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle) { @@ -664,8 +663,7 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa { foreach (X509Extension extension in c.Extensions) { - X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension; - if (keyUsageExtension != null) + if (extension is X509KeyUsageExtension keyUsageExtension) { if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage) { @@ -682,7 +680,6 @@ private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsa /// /// Certificate object. /// A collection of cert eku strings. - [ArchitectureSensitive] internal static Collection GetCertEKU(X509Certificate2 cert) { Collection ekus = new Collection(); @@ -818,6 +815,7 @@ internal DateTime Expiring // The OID arc 1.3.6.1.4.1.311.80 is assigned to PowerShell. If we need // new OIDs, we can assign them under this branch. internal const string DocumentEncryptionOid = "1.3.6.1.4.1.311.80.1"; + internal const string SubjectAlternativeNameOid = "2.5.29.17"; } } @@ -856,6 +854,7 @@ internal enum CertificatePurpose namespace System.Management.Automation { + using System.Management.Automation.Tracing; using System.Security.Cryptography.Pkcs; /// @@ -995,7 +994,7 @@ public CmsMessageRecipient(string identifier) this.Certificates = new X509Certificate2Collection(); } - private string _identifier = null; + private readonly string _identifier; /// /// Creates an instance of the CmsMessageRecipient class. @@ -1007,7 +1006,7 @@ public CmsMessageRecipient(X509Certificate2 certificate) this.Certificates = new X509Certificate2Collection(); } - private X509Certificate2 _pendingCertificate = null; + private readonly X509Certificate2 _pendingCertificate; /// /// Gets the certificate associated with this recipient. @@ -1106,7 +1105,10 @@ private void ResolveFromBase64Encoding(ResolutionPurpose purpose, out ErrorRecor var certificatesToProcess = new X509Certificate2Collection(); try { + #pragma warning disable SYSLIB0057 X509Certificate2 newCertificate = new X509Certificate2(messageBytes); + #pragma warning restore SYSLIB0057 + certificatesToProcess.Add(newCertificate); } catch (Exception) @@ -1184,7 +1186,9 @@ private void ResolveFromPath(SessionState sessionState, ResolutionPurpose purpos try { + #pragma warning disable SYSLIB0057 certificate = new X509Certificate2(path); + #pragma warning restore SYSLIB0057 } catch (Exception) { @@ -1213,7 +1217,7 @@ private void ResolveFromStoreById(ResolutionPurpose purpose, out ErrorRecord err storeCU.Open(OpenFlags.ReadOnly); X509Certificate2Collection storeCerts = storeCU.Certificates; - if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + if (Platform.IsWindows) { using (var storeLM = new X509Store("my", StoreLocation.LocalMachine)) { @@ -1336,9 +1340,22 @@ public enum ResolutionPurpose internal static class AmsiUtils { - private static string GetProcessHostName(string processName) + static AmsiUtils() { - return string.Concat("PowerShell_", processName, ".exe_0.0.0.0"); +#if !UNIX + try + { + s_amsiInitFailed = !CheckAmsiInit(); + } + catch (DllNotFoundException) + { + PSEtwLog.LogAmsiUtilStateEvent("DllNotFoundException", $"{s_amsiContext}-{s_amsiSession}"); + s_amsiInitFailed = true; + return; + } + + PSEtwLog.LogAmsiUtilStateEvent($"init-{s_amsiInitFailed}", $"{s_amsiContext}-{s_amsiSession}"); +#endif } internal static int Init() @@ -1347,34 +1364,21 @@ internal static int Init() lock (s_amsiLockObject) { - Process currentProcess = Process.GetCurrentProcess(); - string hostname; + string appName; try { - var processModule = PsUtils.GetMainModule(currentProcess); - hostname = string.Concat("PowerShell_", processModule.FileName, "_", - processModule.FileVersionInfo.ProductVersion); - } - catch (ComponentModel.Win32Exception) - { - // This exception can be thrown during thread impersonation (Access Denied for process module access). - hostname = GetProcessHostName(currentProcess.ProcessName); + appName = string.Concat("PowerShell_", Environment.ProcessPath, "_", PSVersionInfo.ProductVersion); } - catch (FileNotFoundException) + catch (Exception) { - // This exception can occur if the file is renamed or moved to some other folder - // (This has occurred during Exchange set up). - hostname = GetProcessHostName(currentProcess.ProcessName); + // Fall back to 'Process.ProcessName' in case 'Environment.ProcessPath' throws exception. + Process currentProcess = Process.GetCurrentProcess(); + appName = string.Concat("PowerShell_", currentProcess.ProcessName, ".exe_", PSVersionInfo.ProductVersion); } AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; - var hr = AmsiNativeMethods.AmsiInitialize(hostname, ref s_amsiContext); - if (!Utils.Succeeded(hr)) - { - s_amsiInitFailed = true; - } - + var hr = AmsiNativeMethods.AmsiInitialize(appName, ref s_amsiContext); return hr; } } @@ -1396,7 +1400,10 @@ internal static AmsiNativeMethods.AMSI_RESULT ScanContent(string content, string #endif } - internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, string sourceMetadata, bool warmUp) + internal static AmsiNativeMethods.AMSI_RESULT WinScanContent( + string content, + string sourceMetadata, + bool warmUp) { if (string.IsNullOrEmpty(sourceMetadata)) { @@ -1415,6 +1422,7 @@ internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, str // If we had a previous initialization failure, just return the neutral result. if (s_amsiInitFailed) { + PSEtwLog.LogAmsiUtilStateEvent("ScanContent-InitFail", $"{s_amsiContext}-{s_amsiSession}"); return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } @@ -1422,38 +1430,15 @@ internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, str { if (s_amsiInitFailed) { + PSEtwLog.LogAmsiUtilStateEvent("ScanContent-InitFail", $"{s_amsiContext}-{s_amsiSession}"); return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } try { - int hr = 0; - - // Initialize AntiMalware Scan Interface, if not already initialized. - // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") - if (s_amsiContext == IntPtr.Zero) - { - hr = Init(); - - if (!Utils.Succeeded(hr)) - { - s_amsiInitFailed = true; - return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; - } - } - - // Initialize the session, if one isn't already started. - // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") - if (s_amsiSession == IntPtr.Zero) + if (!CheckAmsiInit()) { - hr = AmsiNativeMethods.AmsiOpenSession(s_amsiContext, ref s_amsiSession); - AmsiInitialized = true; - - if (!Utils.Succeeded(hr)) - { - s_amsiInitFailed = true; - return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; - } + return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } if (warmUp) @@ -1466,6 +1451,7 @@ internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, str AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_CLEAN; // Run AMSI content scan + int hr; unsafe { fixed (char* buffer = content) @@ -1484,6 +1470,7 @@ internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, str if (!Utils.Succeeded(hr)) { // If we got a failure, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") + PSEtwLog.LogAmsiUtilStateEvent($"AmsiScanBuffer-{hr}", $"{s_amsiContext}-{s_amsiSession}"); return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } @@ -1491,12 +1478,127 @@ internal static AmsiNativeMethods.AMSI_RESULT WinScanContent(string content, str } catch (DllNotFoundException) { - s_amsiInitFailed = true; + PSEtwLog.LogAmsiUtilStateEvent("DllNotFoundException", $"{s_amsiContext}-{s_amsiSession}"); return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } } + /// + /// Reports provided content to AMSI (Antimalware Scan Interface). + /// + /// Name of content being reported. + /// Content being reported. + /// True if content was successfully reported. + internal static bool ReportContent( + string name, + string content) + { +#if UNIX + return false; +#else + return WinReportContent(name, content); +#endif + } + + private static bool WinReportContent( + string name, + string content) + { + if (string.IsNullOrEmpty(name) || + string.IsNullOrEmpty(content) || + s_amsiInitFailed || + s_amsiNotifyFailed) + { + return false; + } + + lock (s_amsiLockObject) + { + if (s_amsiNotifyFailed) + { + return false; + } + + try + { + if (!CheckAmsiInit()) + { + return false; + } + + int hr; + AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; + unsafe + { + fixed (char* buffer = content) + { + var buffPtr = new IntPtr(buffer); + hr = AmsiNativeMethods.AmsiNotifyOperation( + amsiContext: s_amsiContext, + buffer: buffPtr, + length: (uint)(content.Length * sizeof(char)), + contentName: name, + ref result); + } + } + + if (Utils.Succeeded(hr)) + { + if (result == AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED) + { + // If malware is detected, throw to prevent method invoke expression from running. + throw new PSSecurityException(ParserStrings.ScriptContainedMaliciousContent); + } + + return true; + } + + return false; + } + catch (DllNotFoundException) + { + s_amsiNotifyFailed = true; + return false; + } + catch (System.EntryPointNotFoundException) + { + s_amsiNotifyFailed = true; + return false; + } + } + } + + private static bool CheckAmsiInit() + { + // Initialize AntiMalware Scan Interface, if not already initialized. + // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") + if (s_amsiContext == IntPtr.Zero) + { + int hr = Init(); + + if (!Utils.Succeeded(hr)) + { + return false; + } + } + + // Initialize the session, if one isn't already started. + // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") + if (s_amsiSession == IntPtr.Zero) + { + int hr = AmsiNativeMethods.AmsiOpenSession(s_amsiContext, ref s_amsiSession); + AmsiInitialized = true; + + if (!Utils.Succeeded(hr)) + { + return false; + } + } + + return true; + } + internal static void CurrentDomain_ProcessExit(object sender, EventArgs e) { if (AmsiInitialized && !AmsiUninitializeCalled) @@ -1505,14 +1607,13 @@ internal static void CurrentDomain_ProcessExit(object sender, EventArgs e) } } - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr s_amsiContext = IntPtr.Zero; - [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr s_amsiSession = IntPtr.Zero; - private static bool s_amsiInitFailed = false; - private static object s_amsiLockObject = new object(); + private static readonly bool s_amsiInitFailed = false; + private static bool s_amsiNotifyFailed = false; + private static readonly object s_amsiLockObject = new object(); /// /// Reset the AMSI session (used to track related script invocations) @@ -1601,29 +1702,29 @@ internal enum AMSI_RESULT /// Return Type: HRESULT->LONG->int ///appName: LPCWSTR->WCHAR* ///amsiContext: HAMSICONTEXT* - [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] - [DllImportAttribute("amsi.dll", EntryPoint = "AmsiInitialize", CallingConvention = CallingConvention.StdCall)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiInitialize", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiInitialize( - [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string appName, ref System.IntPtr amsiContext); + [In][MarshalAs(UnmanagedType.LPWStr)] string appName, ref System.IntPtr amsiContext); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* - [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] - [DllImportAttribute("amsi.dll", EntryPoint = "AmsiUninitialize", CallingConvention = CallingConvention.StdCall)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiUninitialize", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiUninitialize(System.IntPtr amsiContext); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION* - [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] - [DllImportAttribute("amsi.dll", EntryPoint = "AmsiOpenSession", CallingConvention = CallingConvention.StdCall)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiOpenSession", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiOpenSession(System.IntPtr amsiContext, ref System.IntPtr amsiSession); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION->HAMSISESSION__* - [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] - [DllImportAttribute("amsi.dll", EntryPoint = "AmsiCloseSession", CallingConvention = CallingConvention.StdCall)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiCloseSession", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiCloseSession(System.IntPtr amsiContext, System.IntPtr amsiSession); /// Return Type: HRESULT->LONG->int @@ -1633,11 +1734,30 @@ internal static extern int AmsiInitialize( ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* - [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] - [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanBuffer", CallingConvention = CallingConvention.StdCall)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiScanBuffer", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanBuffer( - System.IntPtr amsiContext, System.IntPtr buffer, uint length, - [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); + System.IntPtr amsiContext, + System.IntPtr buffer, + uint length, + [In][MarshalAs(UnmanagedType.LPWStr)] string contentName, + System.IntPtr amsiSession, + ref AMSI_RESULT result); + + /// Return Type: HRESULT->LONG->int + /// amsiContext: HAMSICONTEXT->HAMSICONTEXT__* + /// buffer: PVOID->void* + /// length: ULONG->unsigned int + /// contentName: LPCWSTR->WCHAR* + /// result: AMSI_RESULT* + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiNotifyOperation", CallingConvention = CallingConvention.StdCall)] + internal static extern int AmsiNotifyOperation( + System.IntPtr amsiContext, + System.IntPtr buffer, + uint length, + [In][MarshalAs(UnmanagedType.LPWStr)] string contentName, + ref AMSI_RESULT result); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* @@ -1645,11 +1765,11 @@ internal static extern int AmsiScanBuffer( ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* - [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] - [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanString", CallingConvention = CallingConvention.StdCall)] + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [DllImport("amsi.dll", EntryPoint = "AmsiScanString", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanString( - System.IntPtr amsiContext, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string @string, - [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); + System.IntPtr amsiContext, [In][MarshalAs(UnmanagedType.LPWStr)] string @string, + [In][MarshalAs(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); } } } diff --git a/src/System.Management.Automation/security/Win32Native/WinTrust.cs b/src/System.Management.Automation/security/Win32Native/WinTrust.cs new file mode 100644 index 00000000000..a0ae8bc0e99 --- /dev/null +++ b/src/System.Management.Automation/security/Win32Native/WinTrust.cs @@ -0,0 +1,440 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.ComponentModel; +using System.Runtime.InteropServices; + +namespace System.Management.Automation.Win32Native; + +internal class SafeCATAdminHandle : SafeHandle +{ + internal SafeCATAdminHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid => handle == IntPtr.Zero; + + protected override bool ReleaseHandle() => WinTrustMethods.CryptCATAdminReleaseContext(handle, 0); +} + +internal class SafeCATHandle : SafeHandle +{ + internal SafeCATHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid => handle == (IntPtr)(-1); + + protected override bool ReleaseHandle() => WinTrustMethods.CryptCATClose(handle); +} + +internal class SafeCATCDFHandle : SafeHandle +{ + internal SafeCATCDFHandle() : base(IntPtr.Zero, true) { } + + public override bool IsInvalid => handle == IntPtr.Zero; + + protected override bool ReleaseHandle() => WinTrustMethods.CryptCATCDFClose(handle); +} + +[Flags] +internal enum WinTrustUIChoice +{ + WTD_UI_ALL = 1, + WTD_UI_NONE = 2, + WTD_UI_NOBAD = 3, + WTD_UI_NOGOOD = 4 +} + +[Flags] +internal enum WinTrustUnionChoice +{ + WTD_CHOICE_FILE = 1, + WTD_CHOICE_CATALOG = 2, + WTD_CHOICE_BLOB = 3, + WTD_CHOICE_SIGNER = 4, + WTD_CHOICE_CERT = 5, +} + +[Flags] +internal enum WinTrustAction +{ + WTD_STATEACTION_IGNORE = 0x00000000, + WTD_STATEACTION_VERIFY = 0x00000001, + WTD_STATEACTION_CLOSE = 0x00000002, + WTD_STATEACTION_AUTO_CACHE = 0x00000003, + WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004 +} + +[Flags] +internal enum WinTrustProviderFlags +{ + WTD_PROV_FLAGS_MASK = 0x0000FFFF, + WTD_USE_IE4_TRUST_FLAG = 0x00000001, + WTD_NO_IE4_CHAIN_FLAG = 0x00000002, + WTD_NO_POLICY_USAGE_FLAG = 0x00000004, + WTD_REVOCATION_CHECK_NONE = 0x00000010, + WTD_REVOCATION_CHECK_END_CERT = 0x00000020, + WTD_REVOCATION_CHECK_CHAIN = 0x00000040, + WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x00000080, + WTD_SAFER_FLAG = 0x00000100, + WTD_HASH_ONLY_FLAG = 0x00000200, + WTD_USE_DEFAULT_OSVER_CHECK = 0x00000400, + WTD_LIFETIME_SIGNING_FLAG = 0x00000800, + WTD_CACHE_ONLY_URL_RETRIEVAL = 0x00001000 +} + +/// +/// Pinvoke methods from wintrust.dll +/// +internal static class WinTrustMethods +{ + private const string WinTrustDll = "wintrust.dll"; + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPT_ATTR_BLOB + { + public uint cbData; + public IntPtr pbData; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPT_ALGORITHM_IDENTIFIER + { + [MarshalAs(UnmanagedType.LPStr)] public string pszObjId; + public CRYPT_ATTR_BLOB Parameters; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPT_ATTRIBUTE_TYPE_VALUE + { + [MarshalAs(UnmanagedType.LPStr)] public string pszObjId; + public CRYPT_ATTR_BLOB Value; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct SIP_INDIRECT_DATA + { + public CRYPT_ATTRIBUTE_TYPE_VALUE Data; + public CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; + public CRYPT_ATTR_BLOB Digest; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPTCATMEMBER + { + public uint cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszReferenceTag; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszFileName; + public Guid gSubjectType; + public uint fdwMemberFlags; + public IntPtr pIndirectData; + public uint dwCertVersion; + public uint dwReserved; + public IntPtr hReserved; + public CRYPT_ATTR_BLOB sEncodedIndirectData; + public CRYPT_ATTR_BLOB sEncodedMemberInfo; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPTCATATTRIBUTE + { + public uint cbStruct; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszReferenceTag; + public uint dwAttrTypeAndAction; + public uint cbValue; + public IntPtr pbValue; + public uint dwReserved; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct CRYPTCATSTORE + { + public uint cbStruct; + public uint dwPublicVersion; + [MarshalAs(UnmanagedType.LPWStr)] public string pwszP7File; + public IntPtr hProv; + public uint dwEncodingType; + public uint fdwStoreFlags; + public IntPtr hReserved; + public IntPtr hAttrs; + public IntPtr hCryptMsg; + public IntPtr hSorted; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct WINTRUST_DATA + { + public uint cbStruct; + public IntPtr pPolicyCallbackData; + public IntPtr pSIPClientData; + public WinTrustUIChoice dwUIChoice; + public uint fdwRevocationChecks; + public WinTrustUnionChoice dwUnionChoice; + public unsafe void* pChoice; + public WinTrustAction dwStateAction; + public IntPtr hWVTStateData; + public IntPtr pwszURLReference; + public WinTrustProviderFlags dwProvFlags; + public uint dwUIContext; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct WINTRUST_FILE_INFO + { + public uint cbStruct; + public unsafe char* pcwszFilePath; + public IntPtr hFile; + public IntPtr pgKnownSubject; + } + + [StructLayout(LayoutKind.Sequential)] + internal struct WINTRUST_BLOB_INFO + { + public uint cbStruct; + public Guid gSubject; + public unsafe char* pcwszDisplayName; + public uint cbMemObject; + public unsafe byte* pbMemObject; + public uint cbMemSignedMsg; + public IntPtr pbMemSignedMsg; + } + + [DllImport( + WinTrustDll, + CharSet = CharSet.Unicode, + EntryPoint = "CryptCATAdminAcquireContext2", + SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool NativeCryptCATAdminAcquireContext2( + out SafeCATAdminHandle phCatAdmin, + IntPtr pgSubsystem, + [MarshalAs(UnmanagedType.LPWStr)] string pwszHashAlgorithm, + IntPtr pStrongHashPolicy, + uint dwFlags + ); + + internal static SafeCATAdminHandle CryptCATAdminAcquireContext2(string hashAlgorithm) + { + if (!NativeCryptCATAdminAcquireContext2(out var adminHandle, IntPtr.Zero, hashAlgorithm, IntPtr.Zero, 0)) + { + throw new Win32Exception(); + } + + return adminHandle; + } + + [DllImport( + WinTrustDll, + CharSet = CharSet.Unicode, + EntryPoint = "CryptCATAdminCalcHashFromFileHandle2", + SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern unsafe bool NativeCryptCATAdminCalcHashFromFileHandle2( + SafeCATAdminHandle hCatAdmin, + SafeHandle hFile, + [In, Out] ref int pcbHash, + byte* pbHash, + uint dwFlags + ); + + internal static byte[] CryptCATAdminCalcHashFromFileHandle2(SafeCATAdminHandle catAdmin, SafeHandle file) + { + unsafe + { + int hashLength = 0; + NativeCryptCATAdminCalcHashFromFileHandle2(catAdmin, file, ref hashLength, null, 0); + + byte[] hash = new byte[hashLength]; + fixed (byte* hashPtr = hash) + { + if (!NativeCryptCATAdminCalcHashFromFileHandle2(catAdmin, file, ref hashLength, hashPtr, 0)) + { + throw new Win32Exception(); + } + } + + return hash; + } + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CryptCATAdminReleaseContext( + IntPtr phCatAdmin, + uint dwFlags + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "CryptCATCDFOpen")] + private static extern SafeCATCDFHandle NativeCryptCATCDFOpen( + [MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, + CryptCATCDFParseErrorCallBack pfnParseError + ); + + internal static SafeCATCDFHandle CryptCATCDFOpen(string filePath, CryptCATCDFParseErrorCallBack parseError) + { + SafeCATCDFHandle handle = NativeCryptCATCDFOpen(filePath, parseError); + if (handle.IsInvalid) + { + throw new Win32Exception(); + } + + return handle; + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATCDFEnumCatAttributes( + SafeCATCDFHandle pCDF, + IntPtr pPrevAttr, + CryptCATCDFParseErrorCallBack pfnParseError + ); + + [DllImport(WinTrustDll)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CryptCATCDFClose( + IntPtr pCDF + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATCDFEnumMembersByCDFTagEx( + SafeCATCDFHandle pCDF, + IntPtr pwszPrevCDFTag, + CryptCATCDFParseErrorCallBack fn, + ref IntPtr ppMember, + bool fContinueOnError, + IntPtr pvReserved + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATCDFEnumAttributesWithCDFTag( + SafeCATCDFHandle pCDF, + IntPtr pwszMemberTag, + IntPtr pMember, + IntPtr pPrevAttr, + CryptCATCDFParseErrorCallBack fn + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATEnumerateCatAttr( + SafeCATHandle hCatalog, + IntPtr pPrevAttr + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "CryptCATOpen", SetLastError = true)] + internal static extern SafeCATHandle NativeCryptCATOpen( + [MarshalAs(UnmanagedType.LPWStr)] string pwszFilePath, + uint fdwOpenFlags, + IntPtr hProv, + uint dwPublicVersion, + uint dwEncodingType + ); + + internal static SafeCATHandle CryptCATOpen(string filePath, uint openFlags, IntPtr provider, uint publicVersion, + uint encodingType) + { + SafeCATHandle handle = NativeCryptCATOpen(filePath, openFlags, provider, publicVersion, encodingType); + if (handle.IsInvalid) + { + throw new Win32Exception(); + } + + return handle; + } + + [DllImport(WinTrustDll)] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CryptCATClose( + IntPtr hCatalog + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "CryptCATStoreFromHandle")] + private static extern IntPtr NativeCryptCATStoreFromHandle( + SafeCATHandle hCatalog + ); + + internal static CRYPTCATSTORE CryptCATStoreFromHandle(SafeCATHandle catalog) + { + IntPtr catStore = NativeCryptCATStoreFromHandle(catalog); + return Marshal.PtrToStructure(catStore); + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATEnumerateMember( + SafeCATHandle hCatalog, + IntPtr pPrevMember + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern IntPtr CryptCATEnumerateAttr( + SafeCATHandle hCatalog, + IntPtr pCatMember, + IntPtr pPrevAttr + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode)] + internal static extern uint WinVerifyTrust( + IntPtr hWnd, + ref Guid pgActionID, + ref WINTRUST_DATA pWVTData + ); + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "WTHelperGetProvCertFromChain")] + private static extern IntPtr NativeWTHelperGetProvCertFromChain( + IntPtr pSgnr, + uint idxCert + ); + + internal static IntPtr WTHelperGetProvCertFromChain(IntPtr signer, uint certIdx) + { + IntPtr data = NativeWTHelperGetProvCertFromChain(signer, certIdx); + if (data == IntPtr.Zero) + { + throw new Win32Exception("WTHelperGetProvCertFromChain failed"); + } + + return data; + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "WTHelperGetProvSignerFromChain")] + private static extern IntPtr NativeWTHelperGetProvSignerFromChain( + IntPtr pProvData, + uint idxSigner, + bool fCounterSigner, + uint idxCounterSigner + ); + + internal static IntPtr WTHelperGetProvSignerFromChain(IntPtr providerData, uint signerIdx, bool counterSigner, + uint counterSignerIdx) + { + IntPtr data = NativeWTHelperGetProvSignerFromChain(providerData, signerIdx, counterSigner, counterSignerIdx); + if (data == IntPtr.Zero) + { + throw new Win32Exception("WTHelperGetProvSignerFromChain failed"); + } + + return data; + } + + [DllImport(WinTrustDll, CharSet = CharSet.Unicode, EntryPoint = "WTHelperProvDataFromStateData")] + private static extern IntPtr NativeWTHelperProvDataFromStateData( + IntPtr hStateData + ); + + internal static IntPtr WTHelperProvDataFromStateData(IntPtr stateData) + { + IntPtr data = NativeWTHelperProvDataFromStateData(stateData); + if (data == IntPtr.Zero) + { + throw new Win32Exception("WTHelperProvDataFromStateData failed"); + } + + return data; + } + + /// + /// Signature of call back function used by CryptCATCDFOpen, + /// CryptCATCDFEnumCatAttributes, CryptCATCDFEnumAttributesWithCDFTag, and + /// and CryptCATCDFEnumMembersByCDFTagEx. + /// + internal delegate void CryptCATCDFParseErrorCallBack( + uint dwErrorArea, + uint dwLocalArea, + [MarshalAs(UnmanagedType.LPWStr)] string pwszLine + ); +} diff --git a/src/System.Management.Automation/security/nativeMethods.cs b/src/System.Management.Automation/security/nativeMethods.cs index 69f018bb7bc..6dd8f59d613 100644 --- a/src/System.Management.Automation/security/nativeMethods.cs +++ b/src/System.Management.Automation/security/nativeMethods.cs @@ -620,7 +620,6 @@ internal struct CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO internal IntPtr psUnauthenticatedNotUsed; // PCRYPT_ATTRIBUTES } - [ArchitectureSensitive] internal static CRYPTUI_WIZ_DIGITAL_SIGN_EXTENDED_INFO InitSignInfoExtendedStruct(string description, string moreInfoUrl, @@ -654,11 +653,11 @@ internal struct CRYPT_OID_INFO public uint cbSize; /// LPCSTR->CHAR* - [MarshalAsAttribute(UnmanagedType.LPStr)] + [MarshalAs(UnmanagedType.LPStr)] public string pszOID; /// LPCWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] public string pwszName; /// DWORD->unsigned int @@ -724,7 +723,6 @@ internal static extern IntPtr CryptFindOIDInfo( System.IntPtr pvKey, uint dwGroupId); - [ArchitectureSensitive] internal static DWORD GetCertChoiceFromSigningOption( SigningOption option) { @@ -752,7 +750,6 @@ internal static DWORD GetCertChoiceFromSigningOption( return cc; } - [ArchitectureSensitive] internal static CRYPTUI_WIZ_DIGITAL_SIGN_INFO InitSignInfoStruct(string fileName, X509Certificate2 signingCert, @@ -779,424 +776,41 @@ internal static CRYPTUI_WIZ_DIGITAL_SIGN_INFO return si; } - // ----------------------------------------------------------------- - // wintrust.dll stuff - // - - // - // WinVerifyTrust() function and associated structures/enums - // - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - DWORD WinVerifyTrust( - IntPtr hWndNotUsed, // HWND - IntPtr pgActionID, // GUID* - IntPtr pWinTrustData // WINTRUST_DATA* - ); - - [StructLayout(LayoutKind.Sequential)] - internal struct WINTRUST_FILE_INFO - { - internal DWORD cbStruct; // = sizeof(WINTRUST_FILE_INFO) - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pcwszFilePath; // LPCWSTR - - internal IntPtr hFileNotUsed; // optional, HANDLE to pcwszFilePath - internal IntPtr pgKnownSubjectNotUsed; // optional: GUID* : fill if the - // subject type is known - } - - [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct WINTRUST_BLOB_INFO - { - /// DWORD->unsigned int - internal uint cbStruct; - - /// GUID->_GUID - internal Guid gSubject; - - /// LPCWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] - internal string pcwszDisplayName; - - /// DWORD->unsigned int - internal uint cbMemObject; - - /// BYTE* - internal System.IntPtr pbMemObject; - - /// DWORD->unsigned int - internal uint cbMemSignedMsg; - - /// BYTE* - internal System.IntPtr pbMemSignedMsg; - } - - [ArchitectureSensitive] - internal static WINTRUST_FILE_INFO InitWintrustFileInfoStruct(string fileName) - { - WINTRUST_FILE_INFO fi = new WINTRUST_FILE_INFO(); - - fi.cbStruct = (DWORD)Marshal.SizeOf(fi); - fi.pcwszFilePath = fileName; - fi.hFileNotUsed = IntPtr.Zero; - fi.pgKnownSubjectNotUsed = IntPtr.Zero; - - return fi; - } - - [ArchitectureSensitive] - internal static WINTRUST_BLOB_INFO InitWintrustBlobInfoStruct(string fileName, string content) - { - WINTRUST_BLOB_INFO bi = new WINTRUST_BLOB_INFO(); - byte[] contentBytes = System.Text.Encoding.Unicode.GetBytes(content); - - // The GUID of the PowerShell SIP - bi.gSubject = new Guid(0x603bcc1f, 0x4b59, 0x4e08, new byte[] { 0xb7, 0x24, 0xd2, 0xc6, 0x29, 0x7e, 0xf3, 0x51 }); - bi.cbStruct = (DWORD)Marshal.SizeOf(bi); - bi.pcwszDisplayName = fileName; - bi.cbMemObject = (uint)contentBytes.Length; - bi.pbMemObject = Marshal.AllocCoTaskMem(contentBytes.Length); - Marshal.Copy(contentBytes, 0, bi.pbMemObject, contentBytes.Length); - - return bi; - } - - [Flags] - internal enum WintrustUIChoice - { - WTD_UI_ALL = 1, - WTD_UI_NONE = 2, - WTD_UI_NOBAD = 3, - WTD_UI_NOGOOD = 4 - } - - [Flags] - internal enum WintrustUnionChoice - { - WTD_CHOICE_FILE = 1, - // WTD_CHOICE_CATALOG = 2, - WTD_CHOICE_BLOB = 3, - // WTD_CHOICE_SIGNER = 4, - // WTD_CHOICE_CERT = 5, - } - - [Flags] - internal enum WintrustProviderFlags - { - WTD_PROV_FLAGS_MASK = 0x0000FFFF, - WTD_USE_IE4_TRUST_FLAG = 0x00000001, - WTD_NO_IE4_CHAIN_FLAG = 0x00000002, - WTD_NO_POLICY_USAGE_FLAG = 0x00000004, - WTD_REVOCATION_CHECK_NONE = 0x00000010, - WTD_REVOCATION_CHECK_END_CERT = 0x00000020, - WTD_REVOCATION_CHECK_CHAIN = 0x00000040, - WTD_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x00000080, - WTD_SAFER_FLAG = 0x00000100, - WTD_HASH_ONLY_FLAG = 0x00000200, - WTD_USE_DEFAULT_OSVER_CHECK = 0x00000400, - WTD_LIFETIME_SIGNING_FLAG = 0x00000800, - WTD_CACHE_ONLY_URL_RETRIEVAL = 0x00001000 - } - - [Flags] - internal enum WintrustAction - { - WTD_STATEACTION_IGNORE = 0x00000000, - WTD_STATEACTION_VERIFY = 0x00000001, - WTD_STATEACTION_CLOSE = 0x00000002, - WTD_STATEACTION_AUTO_CACHE = 0x00000003, - WTD_STATEACTION_AUTO_CACHE_FLUSH = 0x00000004 - } - - [StructLayoutAttribute(LayoutKind.Explicit)] - internal struct WinTrust_Choice - { - /// WINTRUST_FILE_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pFile; - - /// WINTRUST_CATALOG_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pCatalog; - - /// WINTRUST_BLOB_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pBlob; - - /// WINTRUST_SGNR_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pSgnr; - - /// WINTRUST_CERT_INFO_* - [FieldOffsetAttribute(0)] - internal System.IntPtr pCert; - } - - [StructLayoutAttribute(LayoutKind.Sequential)] - internal struct WINTRUST_DATA - { - /// DWORD->unsigned int - internal uint cbStruct; - - /// LPVOID->void* - internal System.IntPtr pPolicyCallbackData; - - /// LPVOID->void* - internal System.IntPtr pSIPClientData; - - /// DWORD->unsigned int - internal uint dwUIChoice; - - /// DWORD->unsigned int - internal uint fdwRevocationChecks; - - /// DWORD->unsigned int - internal uint dwUnionChoice; - - /// WinTrust_Choice struct - internal WinTrust_Choice Choice; - - /// DWORD->unsigned int - internal uint dwStateAction; - - /// HANDLE->void* - internal System.IntPtr hWVTStateData; - - /// WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] - internal string pwszURLReference; - - /// DWORD->unsigned int - internal uint dwProvFlags; - - /// DWORD->unsigned int - internal uint dwUIContext; - } - - [ArchitectureSensitive] - internal static WINTRUST_DATA InitWintrustDataStructFromFile(WINTRUST_FILE_INFO wfi) - { - WINTRUST_DATA wtd = new WINTRUST_DATA(); - - wtd.cbStruct = (DWORD)Marshal.SizeOf(wtd); - wtd.pPolicyCallbackData = IntPtr.Zero; - wtd.pSIPClientData = IntPtr.Zero; - wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; - wtd.fdwRevocationChecks = 0; - wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_FILE; - - IntPtr pFileBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wfi)); - Marshal.StructureToPtr(wfi, pFileBuffer, false); - wtd.Choice.pFile = pFileBuffer; - - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY; - wtd.hWVTStateData = IntPtr.Zero; - wtd.pwszURLReference = null; - wtd.dwProvFlags = 0; - - return wtd; - } - - [ArchitectureSensitive] - internal static WINTRUST_DATA InitWintrustDataStructFromBlob(WINTRUST_BLOB_INFO wbi) - { - WINTRUST_DATA wtd = new WINTRUST_DATA(); - - wtd.cbStruct = (DWORD)Marshal.SizeOf(wbi); - wtd.pPolicyCallbackData = IntPtr.Zero; - wtd.pSIPClientData = IntPtr.Zero; - wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; - wtd.fdwRevocationChecks = 0; - wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB; - - IntPtr pBlob = Marshal.AllocCoTaskMem(Marshal.SizeOf(wbi)); - Marshal.StructureToPtr(wbi, pBlob, false); - wtd.Choice.pBlob = pBlob; - - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_VERIFY; - wtd.hWVTStateData = IntPtr.Zero; - wtd.pwszURLReference = null; - wtd.dwProvFlags = 0; - - return wtd; - } - - [ArchitectureSensitive] - internal static DWORD DestroyWintrustDataStruct(WINTRUST_DATA wtd) - { - DWORD dwResult = Win32Errors.E_FAIL; - IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; - IntPtr wtdBuffer = IntPtr.Zero; - - Guid actionVerify = - new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); - - try - { - WINTRUST_ACTION_GENERIC_VERIFY_V2 = - Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); - Marshal.StructureToPtr(actionVerify, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - false); - - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_CLOSE; - wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); - Marshal.StructureToPtr(wtd, wtdBuffer, false); - - // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be - // able to see that. -#pragma warning disable 56523 - dwResult = WinVerifyTrust( - IntPtr.Zero, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - wtdBuffer); -#pragma warning restore 56523 - - wtd = Marshal.PtrToStructure(wtdBuffer); - } - finally - { - Marshal.DestroyStructure(wtdBuffer); - Marshal.FreeCoTaskMem(wtdBuffer); - Marshal.DestroyStructure(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); - } - - // Clear the blob or file info, depending on the type of - // verification that was done. - if (wtd.dwUnionChoice == (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB) - { - WINTRUST_BLOB_INFO originalBlob = - (WINTRUST_BLOB_INFO)Marshal.PtrToStructure(wtd.Choice.pBlob); - Marshal.FreeCoTaskMem(originalBlob.pbMemObject); - - Marshal.DestroyStructure(wtd.Choice.pBlob); - Marshal.FreeCoTaskMem(wtd.Choice.pBlob); - } - else - { - Marshal.DestroyStructure(wtd.Choice.pFile); - Marshal.FreeCoTaskMem(wtd.Choice.pFile); - } - - return dwResult; - } - [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_CERT { +#pragma warning disable IDE0044 private DWORD _cbStruct; +#pragma warning restore IDE0044 internal IntPtr pCert; // PCCERT_CONTEXT - private BOOL _fCommercial; - private BOOL _fTrustedRoot; - private BOOL _fSelfSigned; - private BOOL _fTestCert; - private DWORD _dwRevokedReason; - private DWORD _dwConfidence; - private DWORD _dwError; - private IntPtr _pTrustListContext; // CTL_CONTEXT* - private BOOL _fTrustListSignerCert; - private IntPtr _pCtlContext; // PCCTL_CONTEXT - private DWORD _dwCtlError; - private BOOL _fIsCyclic; - private IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT + private readonly BOOL _fCommercial; + private readonly BOOL _fTrustedRoot; + private readonly BOOL _fSelfSigned; + private readonly BOOL _fTestCert; + private readonly DWORD _dwRevokedReason; + private readonly DWORD _dwConfidence; + private readonly DWORD _dwError; + private readonly IntPtr _pTrustListContext; // CTL_CONTEXT* + private readonly BOOL _fTrustListSignerCert; + private readonly IntPtr _pCtlContext; // PCCTL_CONTEXT + private readonly DWORD _dwCtlError; + private readonly BOOL _fIsCyclic; + private readonly IntPtr _pChainElement; // PCERT_CHAIN_ELEMENT } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_PROVIDER_SGNR { - private DWORD _cbStruct; + private readonly DWORD _cbStruct; private FILETIME _sftVerifyAsOf; - private DWORD _csCertChain; - private IntPtr _pasCertChain; // CRYPT_PROVIDER_CERT* - private DWORD _dwSignerType; - private IntPtr _psSigner; // CMSG_SIGNER_INFO* - private DWORD _dwError; + private readonly DWORD _csCertChain; + private readonly IntPtr _pasCertChain; // CRYPT_PROVIDER_CERT* + private readonly DWORD _dwSignerType; + private readonly IntPtr _psSigner; // CMSG_SIGNER_INFO* + private readonly DWORD _dwError; internal DWORD csCounterSigners; internal IntPtr pasCounterSigners; // CRYPT_PROVIDER_SGNR* - private IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT - } - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - IntPtr // CRYPT_PROVIDER_DATA* - WTHelperProvDataFromStateData(IntPtr hStateData); - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - IntPtr // CRYPT_PROVIDER_SGNR* - WTHelperGetProvSignerFromChain( - IntPtr pProvData, // CRYPT_PROVIDER_DATA* - DWORD idxSigner, - BOOL fCounterSigner, - DWORD idxCounterSigner - ); - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern - IntPtr // CRYPT_PROVIDER_CERT* - WTHelperGetProvCertFromChain( - IntPtr pSgnr, // CRYPT_PROVIDER_SGNR* - DWORD idxCert - ); - - /// Return Type: HRESULT->LONG->int - ///pszFile: PCWSTR->WCHAR* - ///hFile: HANDLE->void* - ///sigInfoFlags: SIGNATURE_INFO_FLAGS->Anonymous_5157c654_2076_48e7_9241_84ac648615e9 - ///psiginfo: SIGNATURE_INFO* - ///ppCertContext: void** - ///phWVTStateData: HANDLE* - [DllImportAttribute("wintrust.dll", EntryPoint = "WTGetSignatureInfo", CallingConvention = CallingConvention.StdCall)] - internal static extern int WTGetSignatureInfo([InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string pszFile, [InAttribute()] System.IntPtr hFile, SIGNATURE_INFO_FLAGS sigInfoFlags, ref SIGNATURE_INFO psiginfo, ref System.IntPtr ppCertContext, ref System.IntPtr phWVTStateData); - - internal static void FreeWVTStateData(System.IntPtr phWVTStateData) - { - WINTRUST_DATA wtd = new WINTRUST_DATA(); - DWORD dwResult = Win32Errors.E_FAIL; - IntPtr WINTRUST_ACTION_GENERIC_VERIFY_V2 = IntPtr.Zero; - IntPtr wtdBuffer = IntPtr.Zero; - - Guid actionVerify = - new Guid("00AAC56B-CD44-11d0-8CC2-00C04FC295EE"); - - try - { - WINTRUST_ACTION_GENERIC_VERIFY_V2 = - Marshal.AllocCoTaskMem(Marshal.SizeOf(actionVerify)); - Marshal.StructureToPtr(actionVerify, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - false); - - wtd.cbStruct = (DWORD)Marshal.SizeOf(wtd); - wtd.dwUIChoice = (DWORD)WintrustUIChoice.WTD_UI_NONE; - wtd.fdwRevocationChecks = 0; - wtd.dwUnionChoice = (DWORD)WintrustUnionChoice.WTD_CHOICE_BLOB; - wtd.dwStateAction = (DWORD)WintrustAction.WTD_STATEACTION_CLOSE; - wtd.hWVTStateData = phWVTStateData; - - wtdBuffer = Marshal.AllocCoTaskMem(Marshal.SizeOf(wtd)); - Marshal.StructureToPtr(wtd, wtdBuffer, false); - - // The GetLastWin32Error of this is checked, but PreSharp doesn't seem to be - // able to see that. -#pragma warning disable 56523 - dwResult = WinVerifyTrust( - IntPtr.Zero, - WINTRUST_ACTION_GENERIC_VERIFY_V2, - wtdBuffer); -#pragma warning restore 56523 - } - finally - { - Marshal.DestroyStructure(wtdBuffer); - Marshal.FreeCoTaskMem(wtdBuffer); - Marshal.DestroyStructure(WINTRUST_ACTION_GENERIC_VERIFY_V2); - Marshal.FreeCoTaskMem(WINTRUST_ACTION_GENERIC_VERIFY_V2); - } + private readonly IntPtr _pChainContext; // PCCERT_CHAIN_CONTEXT } // @@ -1284,7 +898,7 @@ internal enum SIGNATURE_INFO_TYPE SIT_CATALOG, } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct SIGNATURE_INFO { /// DWORD->unsigned int @@ -1303,21 +917,21 @@ internal struct SIGNATURE_INFO internal uint dwInfoAvailability; /// PWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] internal string pszDisplayName; /// DWORD->unsigned int internal uint cchDisplayName; /// PWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] internal string pszPublisherName; /// DWORD->unsigned int internal uint cchPublisherName; /// PWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] internal string pszMoreInfoURL; /// DWORD->unsigned int @@ -1333,7 +947,7 @@ internal struct SIGNATURE_INFO internal int fOSBinary; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct CERT_INFO { /// DWORD->unsigned int @@ -1373,18 +987,18 @@ internal struct CERT_INFO internal System.IntPtr rgExtension; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { /// LPSTR->CHAR* - [MarshalAsAttribute(UnmanagedType.LPStr)] + [MarshalAs(UnmanagedType.LPStr)] internal string pszObjId; /// CRYPT_OBJID_BLOB->_CRYPTOAPI_BLOB internal CRYPT_ATTR_BLOB Parameters; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct FILETIME { /// DWORD->unsigned int @@ -1394,7 +1008,7 @@ internal struct FILETIME internal uint dwHighDateTime; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { /// CRYPT_ALGORITHM_IDENTIFIER->_CRYPT_ALGORITHM_IDENTIFIER @@ -1404,7 +1018,7 @@ internal struct CERT_PUBLIC_KEY_INFO internal CRYPT_BIT_BLOB PublicKey; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_BIT_BLOB { /// DWORD->unsigned int @@ -1417,11 +1031,11 @@ internal struct CRYPT_BIT_BLOB internal uint cUnusedBits; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct CERT_EXTENSION { /// LPSTR->CHAR* - [MarshalAsAttribute(UnmanagedType.LPStr)] + [MarshalAs(UnmanagedType.LPStr)] internal string pszObjId; /// BOOL->int @@ -1472,15 +1086,15 @@ internal static partial class NativeMethods ///pCodeProperties: PSAFER_CODE_PROPERTIES->_SAFER_CODE_PROPERTIES* ///pLevelHandle: SAFER_LEVEL_HANDLE* ///lpReserved: LPVOID->void* - [DllImportAttribute("advapi32.dll", EntryPoint = "SaferIdentifyLevel", SetLastError = true)] - [return: MarshalAsAttribute(UnmanagedType.Bool)] + [DllImport("advapi32.dll", EntryPoint = "SaferIdentifyLevel", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SaferIdentifyLevel( uint dwNumProperties, - [InAttribute()] + [In] ref SAFER_CODE_PROPERTIES pCodeProperties, out IntPtr pLevelHandle, - [InAttribute()] - [MarshalAsAttribute(UnmanagedType.LPWStr)] + [In] + [MarshalAs(UnmanagedType.LPWStr)] string bucket); /// Return Type: BOOL->int @@ -1489,12 +1103,12 @@ internal static extern bool SaferIdentifyLevel( ///OutAccessToken: PHANDLE->HANDLE* ///dwFlags: DWORD->unsigned int ///lpReserved: LPVOID->void* - [DllImportAttribute("advapi32.dll", EntryPoint = "SaferComputeTokenFromLevel", SetLastError = true)] - [return: MarshalAsAttribute(UnmanagedType.Bool)] + [DllImport("advapi32.dll", EntryPoint = "SaferComputeTokenFromLevel", SetLastError = true)] + [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SaferComputeTokenFromLevel( - [InAttribute()] + [In] IntPtr LevelHandle, - [InAttribute()] + [In] System.IntPtr InAccessToken, ref System.IntPtr OutAccessToken, uint dwFlags, @@ -1502,18 +1116,18 @@ internal static extern bool SaferComputeTokenFromLevel( /// Return Type: BOOL->int ///hLevelHandle: SAFER_LEVEL_HANDLE->SAFER_LEVEL_HANDLE__* - [DllImportAttribute("advapi32.dll", EntryPoint = "SaferCloseLevel")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - internal static extern bool SaferCloseLevel([InAttribute()] IntPtr hLevelHandle); + [DllImport("advapi32.dll", EntryPoint = "SaferCloseLevel")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool SaferCloseLevel([In] IntPtr hLevelHandle); /// Return Type: BOOL->int ///hObject: HANDLE->void* - [DllImportAttribute(PinvokeDllNames.CloseHandleDllName, EntryPoint = "CloseHandle")] - [return: MarshalAsAttribute(UnmanagedType.Bool)] - internal static extern bool CloseHandle([InAttribute()] System.IntPtr hObject); + [DllImport(PinvokeDllNames.CloseHandleDllName, EntryPoint = "CloseHandle")] + [return: MarshalAs(UnmanagedType.Bool)] + internal static extern bool CloseHandle([In] System.IntPtr hObject); } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct SAFER_CODE_PROPERTIES { /// DWORD->unsigned int @@ -1523,7 +1137,7 @@ internal struct SAFER_CODE_PROPERTIES public uint dwCheckFlags; /// LPCWSTR->WCHAR* - [MarshalAsAttribute(UnmanagedType.LPWStr)] + [MarshalAs(UnmanagedType.LPWStr)] public string ImagePath; /// HANDLE->void* @@ -1533,7 +1147,7 @@ internal struct SAFER_CODE_PROPERTIES public uint UrlZoneId; /// BYTE[SAFER_MAX_HASH_SIZE] - [MarshalAsAttribute( + [MarshalAs( UnmanagedType.ByValArray, SizeConst = NativeConstants.SAFER_MAX_HASH_SIZE, ArraySubType = UnmanagedType.I1)] @@ -1558,30 +1172,30 @@ internal struct SAFER_CODE_PROPERTIES public uint dwWVTUIChoice; } - [StructLayoutAttribute(LayoutKind.Explicit)] + [StructLayout(LayoutKind.Explicit)] internal struct LARGE_INTEGER { /// Anonymous_9320654f_2227_43bf_a385_74cc8c562686 - [FieldOffsetAttribute(0)] + [FieldOffset(0)] public Anonymous_9320654f_2227_43bf_a385_74cc8c562686 Struct1; /// Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 - [FieldOffsetAttribute(0)] + [FieldOffset(0)] public Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 u; /// LONGLONG->__int64 - [FieldOffsetAttribute(0)] + [FieldOffset(0)] public long QuadPart; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct HWND__ { /// int public int unused; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct Anonymous_9320654f_2227_43bf_a385_74cc8c562686 { /// DWORD->unsigned int @@ -1591,7 +1205,7 @@ internal struct Anonymous_9320654f_2227_43bf_a385_74cc8c562686 public int HighPart; } - [StructLayoutAttribute(LayoutKind.Sequential)] + [StructLayout(LayoutKind.Sequential)] internal struct Anonymous_947eb392_1446_4e25_bbd4_10e98165f3a9 { /// DWORD->unsigned int @@ -1673,28 +1287,28 @@ internal enum SecurityInformation : uint UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000 } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct LUID { internal uint LowPart; internal uint HighPart; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct LUID_AND_ATTRIBUTES { internal LUID Luid; internal uint Attributes; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct TOKEN_PRIVILEGE { internal uint PrivilegeCount; internal LUID_AND_ATTRIBUTES Privilege; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct ACL { internal byte AclRevision; @@ -1704,7 +1318,7 @@ internal struct ACL internal ushort Sbz2; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct ACE_HEADER { internal byte AceType; @@ -1712,7 +1326,7 @@ internal struct ACE_HEADER internal ushort AceSize; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct SYSTEM_AUDIT_ACE { internal ACE_HEADER Header; @@ -1720,7 +1334,7 @@ internal struct SYSTEM_AUDIT_ACE internal uint SidStart; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct LSA_UNICODE_STRING { internal ushort Length; @@ -1728,7 +1342,7 @@ internal struct LSA_UNICODE_STRING internal IntPtr Buffer; } - [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + [StructLayout(LayoutKind.Sequential)] internal struct CENTRAL_ACCESS_POLICY { internal IntPtr CAPID; @@ -1853,42 +1467,6 @@ internal static extern bool AdjustTokenPrivileges( internal const uint LOAD_LIBRARY_SEARCH_USER_DIRS = 0x00000400; internal const uint LOAD_LIBRARY_SEARCH_SYSTEM32 = 0x00000800; internal const uint LOAD_LIBRARY_SEARCH_DEFAULT_DIRS = 0x00001000; - - [DllImport(PinvokeDllNames.LoadLibraryEx, CharSet = CharSet.Unicode, SetLastError = true)] - internal static extern IntPtr LoadLibraryExW( - string DllName, - IntPtr reserved, - uint Flags); - - [DllImport(PinvokeDllNames.FreeLibrary, CharSet = CharSet.Unicode, SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool FreeLibrary( - IntPtr Module); - - internal static bool IsSystem32DllPresent(string DllName) - { - bool DllExists = false; - - try - { - IntPtr module = LoadLibraryExW( - DllName, - IntPtr.Zero, - NativeMethods.LOAD_LIBRARY_AS_DATAFILE | - NativeMethods.LOAD_LIBRARY_AS_IMAGE_RESOURCE | - NativeMethods.LOAD_LIBRARY_SEARCH_SYSTEM32); - if (module != IntPtr.Zero) - { - FreeLibrary(module); - DllExists = true; - } - } - catch (Exception) - { - } - - return DllExists; - } } // Constants needed for Catalog Error Handling @@ -1930,234 +1508,6 @@ internal partial class NativeConstants // CRYPTCAT_E_CDF_ATTR_TYPECOMBO = "0x00020004"; public const int CRYPTCAT_E_CDF_ATTR_TYPECOMBO = 131076; } - - /// - /// Pinvoke methods from wintrust.dll - /// These are added to Generate and Validate Window Catalog Files. - /// - internal static partial class NativeMethods - { - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPT_ATTRIBUTE_TYPE_VALUE - { - [MarshalAs(UnmanagedType.LPStr)] - internal string pszObjId; - - internal CRYPT_ATTR_BLOB Value; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct SIP_INDIRECT_DATA - { - internal CRYPT_ATTRIBUTE_TYPE_VALUE Data; - internal CRYPT_ALGORITHM_IDENTIFIER DigestAlgorithm; - internal CRYPT_ATTR_BLOB Digest; - } - - [StructLayout(LayoutKind.Sequential)] - internal readonly struct CRYPTCATCDF - { - private readonly DWORD _cbStruct; - private readonly IntPtr _hFile; - private readonly DWORD _dwCurFilePos; - private readonly DWORD _dwLastMemberOffset; - private readonly BOOL _fEOF; - - [MarshalAs(UnmanagedType.LPWStr)] - private readonly string _pwszResultDir; - - private readonly IntPtr _hCATStore; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATMEMBER - { - internal DWORD cbStruct; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszReferenceTag; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszFileName; - - internal Guid gSubjectType; - internal DWORD fdwMemberFlags; - internal IntPtr pIndirectData; - internal DWORD dwCertVersion; - internal DWORD dwReserved; - internal IntPtr hReserved; - internal CRYPT_ATTR_BLOB sEncodedIndirectData; - internal CRYPT_ATTR_BLOB sEncodedMemberInfo; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATATTRIBUTE - { - private DWORD _cbStruct; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszReferenceTag; - - private DWORD _dwAttrTypeAndAction; - internal DWORD cbValue; - internal System.IntPtr pbValue; - private DWORD _dwReserved; - } - - [StructLayout(LayoutKind.Sequential)] - internal struct CRYPTCATSTORE - { - private DWORD _cbStruct; - internal DWORD dwPublicVersion; - - [MarshalAs(UnmanagedType.LPWStr)] - internal string pwszP7File; - - private IntPtr _hProv; - private DWORD _dwEncodingType; - private DWORD _fdwStoreFlags; - private IntPtr _hReserved; - private IntPtr _hAttrs; - private IntPtr _hCryptMsg; - private IntPtr _hSorted; - } - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFOpen( - [MarshalAs(UnmanagedType.LPWStr)] - string pwszFilePath, - CryptCATCDFOpenCallBack pfnParseError - ); - - [DllImport("wintrust.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATCDFClose( - IntPtr pCDF - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFEnumCatAttributes( - IntPtr pCDF, - IntPtr pPrevAttr, - CryptCATCDFOpenCallBack pfnParseError - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFEnumMembersByCDFTagEx( - IntPtr pCDF, - IntPtr pwszPrevCDFTag, - CryptCATCDFEnumMembersByCDFTagExErrorCallBack fn, - ref IntPtr ppMember, - bool fContinueOnError, - IntPtr pvReserved - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATCDFEnumAttributesWithCDFTag( - IntPtr pCDF, - IntPtr pwszMemberTag, - IntPtr pMember, - IntPtr pPrevAttr, - CryptCATCDFEnumMembersByCDFTagExErrorCallBack fn - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATOpen( - [MarshalAs(UnmanagedType.LPWStr)] - string pwszFilePath, - DWORD fdwOpenFlags, - IntPtr hProv, - DWORD dwPublicVersion, - DWORD dwEncodingType - ); - - [DllImport("wintrust.dll")] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATClose( - IntPtr hCatalog - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATStoreFromHandle( - IntPtr hCatalog - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATAdminAcquireContext2( - ref IntPtr phCatAdmin, - IntPtr pgSubsystem, - [MarshalAs(UnmanagedType.LPWStr)] - string pwszHashAlgorithm, - IntPtr pStrongHashPolicy, - DWORD dwFlags - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATAdminReleaseContext( - IntPtr phCatAdmin, - DWORD dwFlags - ); - - [DllImport("kernel32", SetLastError = true, CharSet = CharSet.Unicode)] - internal static extern unsafe IntPtr CreateFile( - string lpFileName, - DWORD dwDesiredAccess, - DWORD dwShareMode, - DWORD lpSecurityAttributes, - DWORD dwCreationDisposition, - DWORD dwFlagsAndAttributes, - IntPtr hTemplateFile - ); - - [DllImport("wintrust.dll", SetLastError = true, CharSet = CharSet.Unicode)] - [return: MarshalAs(UnmanagedType.Bool)] - internal static extern bool CryptCATAdminCalcHashFromFileHandle2( - IntPtr hCatAdmin, - IntPtr hFile, - [In, Out] ref DWORD pcbHash, - IntPtr pbHash, - DWORD dwFlags - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATEnumerateCatAttr( - IntPtr hCatalog, - IntPtr pPrevAttr - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATEnumerateMember( - IntPtr hCatalog, - IntPtr pPrevMember - ); - - [DllImport("wintrust.dll", CharSet = CharSet.Unicode)] - internal static extern IntPtr CryptCATEnumerateAttr( - IntPtr hCatalog, - IntPtr pCatMember, - IntPtr pPrevAttr - ); - - /// - /// Signature of call back function used by CryptCATCDFOpen. - /// - internal delegate - void CryptCATCDFOpenCallBack(DWORD NotUsedDWORD1, - DWORD NotUsedDWORD2, - [MarshalAs(UnmanagedType.LPWStr)] - string NotUsedString); - - /// - /// Signature of call back function used by CryptCATCDFEnumMembersByCDFTagEx. - /// - internal delegate - void CryptCATCDFEnumMembersByCDFTagExErrorCallBack(DWORD NotUsedDWORD1, - DWORD NotUsedDWORD2, - [MarshalAs(UnmanagedType.LPWStr)] - string NotUsedString); - } } #pragma warning restore 56523 diff --git a/src/System.Management.Automation/security/wldpNativeMethods.cs b/src/System.Management.Automation/security/wldpNativeMethods.cs index 3e0edc58fd0..fa104fc0b6b 100644 --- a/src/System.Management.Automation/security/wldpNativeMethods.cs +++ b/src/System.Management.Automation/security/wldpNativeMethods.cs @@ -6,12 +6,46 @@ // #if !UNIX +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Management.Automation.Internal; +using System.Management.Automation.Runspaces; +using System.Management.Automation.Tracing; using System.Runtime.InteropServices; -using System.Diagnostics.CodeAnalysis; namespace System.Management.Automation.Security { + /// + /// System wide policy enforcement for a specific script file. + /// + public enum SystemScriptFileEnforcement + { + /// + /// No policy enforcement. + /// + None = 0, + + /// + /// Script file is blocked from running. + /// + Block = 1, + + /// + /// Script file is allowed to run without restrictions (FullLanguage mode). + /// + Allow = 2, + + /// + /// Script file is allowed to run in ConstrainedLanguage mode only. + /// + AllowConstrained = 3, + + /// + /// Script file is allowed to run in FullLanguage mode but will emit ConstrainedLanguage restriction audit logs. + /// + AllowConstrainedAudit = 4 + } + /// /// How the policy is being enforced. /// @@ -35,12 +69,122 @@ public enum SystemEnforcementMode /// Support class for dealing with the Windows Lockdown Policy, /// Device Guard, and Constrained PowerShell. /// - public sealed class SystemPolicy + public sealed partial class SystemPolicy { private SystemPolicy() { } + // The S in PowerShell must be lower case to match the manifest. + private const string AppManifestId = "Powershell"; + + private static bool? s_isFileOnlyEntryEnabled; + + /// + /// Determines if the WLDP setting "FileOnlyEntry" is enabled. + /// + internal static bool IsFileOnlyEntryEnabled() + { + if (s_isFileOnlyEntryEnabled.HasValue) + { + return s_isFileOnlyEntryEnabled.Value; + } + + const string SettingName = "FileOnlyEntry"; + s_isFileOnlyEntryEnabled = TestBooleanWldpSetting(SettingName); + return s_isFileOnlyEntryEnabled.Value; + } + + private static bool TestBooleanWldpSetting(string settingName) + { + int hr = WldpNativeMethods.WldpGetApplicationSettingBoolean( + AppManifestId, + settingName, + out bool result); + + PSEtwLog.LogWDACQueryEvent( + "WldpGetApplicationSettingBoolean", + settingName, + hr, + result ? 1 : 0); + + if (hr is not 0) + { + result = false; + } + + if (!result) + { + string debugValue = Environment.GetEnvironmentVariable( + $"__PSLockdownPolicy_{settingName}", + EnvironmentVariableTarget.Machine); + + if (debugValue is "1") + { + result = true; + } + } + + return result; + } + + /// + /// Writes to PowerShell WDAC Audit mode ETW log. + /// + /// Current execution context. + /// Audit message title. + /// Audit message message. + /// Fully Qualified ID. + /// Stops code execution and goes into debugger mode. + internal static void LogWDACAuditMessage( + ExecutionContext context, + string title, + string message, + string fqid, + bool dropIntoDebugger = false) + { + string messageToWrite = message; + + // Augment the log message with current script information from the script debugger, if available. + context ??= LocalPipeline.GetExecutionContextFromTLS(); + bool debuggerAvailable = context is not null && + context._debugger is ScriptDebugger; + + if (debuggerAvailable) + { + var scriptPosMessage = context._debugger.GetCurrentScriptPosition(); + if (!string.IsNullOrEmpty(scriptPosMessage)) + { + messageToWrite = message + scriptPosMessage; + } + } + + PSEtwLog.LogWDACAuditEvent(title, messageToWrite, fqid); + + // We drop into the debugger only if requested and we are running in the interactive host session runspace (Id == 1). + if (debuggerAvailable && dropIntoDebugger && + context._debugger.DebugMode.HasFlag(DebugModes.LocalScript) && + Runspace.DefaultRunspace?.Id == 1 && + context.DebugPreferenceVariable.HasFlag(ActionPreference.Break) && + context.InternalHost?.UI is not null) + { + try + { + context.InternalHost.UI.WriteLine(); + context.InternalHost.UI.WriteLine("WDAC Audit Log:"); + context.InternalHost.UI.WriteLine($"Title: {title}"); + context.InternalHost.UI.WriteLine($"Message: {message}"); + context.InternalHost.UI.WriteLine($"FullyQualifedId: {fqid}"); + context.InternalHost.UI.WriteLine("Stopping script execution in debugger..."); + context.InternalHost.UI.WriteLine(); + + context._debugger.Break(); + } + catch + { } + } + } + /// /// Gets the system lockdown policy. /// @@ -51,26 +195,121 @@ public static SystemEnforcementMode GetSystemLockdownPolicy() { lock (s_systemLockdownPolicyLock) { - if (s_systemLockdownPolicy == null) - { - s_systemLockdownPolicy = GetLockdownPolicy(path: null, handle: null); - } + s_systemLockdownPolicy ??= GetLockdownPolicy(path: null, handle: null); } } else if (s_allowDebugOverridePolicy) { lock (s_systemLockdownPolicyLock) { - s_systemLockdownPolicy = GetDebugLockdownPolicy(path: null); + s_systemLockdownPolicy = GetDebugLockdownPolicy(path: null, out _); } } return s_systemLockdownPolicy.Value; } - private static object s_systemLockdownPolicyLock = new object(); + private static readonly object s_systemLockdownPolicyLock = new object(); private static SystemEnforcementMode? s_systemLockdownPolicy = null; private static bool s_allowDebugOverridePolicy = false; + private static bool s_wldpCanExecuteAvailable = true; + + /// + /// Gets the system wide script file policy enforcement for an open file. + /// Based on system WDAC (Windows Defender Application Control) or AppLocker policies. + /// + /// Script file path for policy check. + /// FileStream object to script file path. + /// Policy check result for script file. + public static SystemScriptFileEnforcement GetFilePolicyEnforcement( + string filePath, + System.IO.FileStream fileStream) + { + SafeHandle fileHandle = fileStream.SafeFileHandle; + SystemEnforcementMode systemLockdownPolicy = GetSystemLockdownPolicy(); + + // First check latest WDAC APIs if available. + if (systemLockdownPolicy is SystemEnforcementMode.Enforce + && s_wldpCanExecuteAvailable + && TryGetWldpCanExecuteFileResult(filePath, fileHandle, out SystemScriptFileEnforcement wldpFilePolicy)) + { + return GetLockdownPolicy(filePath, fileHandle, wldpFilePolicy); + } + + // Failed to invoke WldpCanExecuteFile, revert to legacy APIs. + if (systemLockdownPolicy is SystemEnforcementMode.None) + { + return SystemScriptFileEnforcement.None; + } + + // WldpCanExecuteFile was invoked successfully so we can skip running + // legacy WDAC APIs. AppLocker must still be checked in case it is more + // strict than the current WDAC policy. + return GetLockdownPolicy(filePath, fileHandle, canExecuteResult: null); + } + + private static SystemScriptFileEnforcement ConvertToModernFileEnforcement(SystemEnforcementMode legacyMode) + { + return legacyMode switch + { + SystemEnforcementMode.None => SystemScriptFileEnforcement.Allow, + SystemEnforcementMode.Audit => SystemScriptFileEnforcement.AllowConstrainedAudit, + SystemEnforcementMode.Enforce => SystemScriptFileEnforcement.AllowConstrained, + _ => SystemScriptFileEnforcement.Block, + }; + } + + private static bool TryGetWldpCanExecuteFileResult(string filePath, SafeHandle fileHandle, out SystemScriptFileEnforcement result) + { + try + { + string fileName = System.IO.Path.GetFileNameWithoutExtension(filePath); + string auditMsg = $"PowerShell ExternalScriptInfo reading file: {fileName}"; + + int hr = WldpNativeMethods.WldpCanExecuteFile( + host: PowerShellHost, + options: WLDP_EXECUTION_EVALUATION_OPTIONS.WLDP_EXECUTION_EVALUATION_OPTION_NONE, + fileHandle: fileHandle.DangerousGetHandle(), + auditInfo: auditMsg, + result: out WLDP_EXECUTION_POLICY canExecuteResult); + + PSEtwLog.LogWDACQueryEvent("WldpCanExecuteFile", filePath, hr, (int)canExecuteResult); + + if (hr >= 0) + { + switch (canExecuteResult) + { + case WLDP_EXECUTION_POLICY.WLDP_CAN_EXECUTE_ALLOWED: + result = SystemScriptFileEnforcement.Allow; + return true; + + case WLDP_EXECUTION_POLICY.WLDP_CAN_EXECUTE_BLOCKED: + result = SystemScriptFileEnforcement.Block; + return true; + + case WLDP_EXECUTION_POLICY.WLDP_CAN_EXECUTE_REQUIRE_SANDBOX: + result = SystemScriptFileEnforcement.AllowConstrained; + return true; + + default: + // Fall through to legacy system policy checks. + Debug.Assert(false, $"Unknown policy result returned from WldCanExecute: {canExecuteResult}"); + break; + } + } + + // If HResult is unsuccessful (such as E_NOTIMPL (0x80004001)), fall through to legacy system checks. + } + catch (Exception ex) when (ex is DllNotFoundException or EntryPointNotFoundException) + { + // Fall back to legacy system policy checks. + s_wldpCanExecuteAvailable = false; + PSEtwLog.LogWDACQueryEvent("WldpCanExecuteFile_Failed", filePath, ex.HResult, 0); + } + + result = default; + return false; + } /// /// Gets lockdown policy as applied to a file. @@ -78,9 +317,32 @@ public static SystemEnforcementMode GetSystemLockdownPolicy() /// An EnforcementMode that describes policy. public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle handle) { + SystemScriptFileEnforcement modernMode = GetLockdownPolicy(path, handle, canExecuteResult: null); + Debug.Assert( + modernMode is not SystemScriptFileEnforcement.Block, + "Block should never be converted to legacy file enforcement."); + + return modernMode switch + { + SystemScriptFileEnforcement.Block => SystemEnforcementMode.Enforce, + SystemScriptFileEnforcement.AllowConstrained => SystemEnforcementMode.Enforce, + SystemScriptFileEnforcement.AllowConstrainedAudit => SystemEnforcementMode.Audit, + SystemScriptFileEnforcement.Allow => SystemEnforcementMode.None, + SystemScriptFileEnforcement.None => SystemEnforcementMode.None, + _ => throw new ArgumentOutOfRangeException(nameof(modernMode)), + }; + } + + private static SystemScriptFileEnforcement GetLockdownPolicy( + string path, + SafeHandle handle, + SystemScriptFileEnforcement? canExecuteResult) + { + SystemScriptFileEnforcement wldpFilePolicy = canExecuteResult + ?? ConvertToModernFileEnforcement(GetWldpPolicy(path, handle)); + // Check the WLDP File policy via API - var wldpFilePolicy = GetWldpPolicy(path, handle); - if (wldpFilePolicy == SystemEnforcementMode.Enforce) + if (wldpFilePolicy is SystemScriptFileEnforcement.Block or SystemScriptFileEnforcement.AllowConstrained) { return wldpFilePolicy; } @@ -92,29 +354,28 @@ public static SystemEnforcementMode GetLockdownPolicy(string path, SafeHandle ha var appLockerFilePolicy = GetAppLockerPolicy(path, handle); if (appLockerFilePolicy == SystemEnforcementMode.Enforce) { - return appLockerFilePolicy; + return ConvertToModernFileEnforcement(appLockerFilePolicy); } // At this point, LockdownPolicy = Audit or Allowed. // If there was a WLDP policy, but WLDP didn't block it, // then it was explicitly allowed. Therefore, return the result for the file. - SystemEnforcementMode systemWldpPolicy = s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); - if ((systemWldpPolicy == SystemEnforcementMode.Audit) || - (systemWldpPolicy == SystemEnforcementMode.Enforce)) + if (s_cachedWldpSystemPolicy is SystemEnforcementMode.Audit or SystemEnforcementMode.Enforce + || wldpFilePolicy is SystemScriptFileEnforcement.AllowConstrainedAudit) { return wldpFilePolicy; } // If there was a system-wide AppLocker policy, but AppLocker didn't block it, // then return AppLocker's status. - if (s_cachedSaferSystemPolicy.GetValueOrDefault(SaferPolicy.Allowed) == - SaferPolicy.Disallowed) + if (s_cachedSaferSystemPolicy is SaferPolicy.Disallowed) { - return appLockerFilePolicy; + return ConvertToModernFileEnforcement(appLockerFilePolicy); } // If it's not set to 'Enforce' by the platform, allow debug overrides - return GetDebugLockdownPolicy(path); + GetDebugLockdownPolicy(path, out SystemScriptFileEnforcement debugPolicy); + return debugPolicy; } [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", @@ -156,6 +417,7 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl uint pdwLockdownState = 0; int result = WldpNativeMethods.WldpGetLockdownPolicy(ref hostInformation, ref pdwLockdownState, 0); + PSEtwLog.LogWDACQueryEvent("WldpGetLockdownPolicy", path, result, (int)pdwLockdownState); if (result >= 0) { SystemEnforcementMode resultingLockdownPolicy = GetLockdownPolicyForResult(pdwLockdownState); @@ -174,9 +436,10 @@ private static SystemEnforcementMode GetWldpPolicy(string path, SafeHandle handl return SystemEnforcementMode.Enforce; } } - catch (DllNotFoundException) + catch (DllNotFoundException ex) { s_hadMissingWldpAssembly = true; + PSEtwLog.LogWDACQueryEvent("WldpGetLockdownPolicy_Failed", path, ex.HResult, 0); return s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None); } } @@ -237,23 +500,38 @@ private static SystemEnforcementMode GetAppLockerPolicy(string path, SafeHandle IO.File.WriteAllText(testPathScript, dtAppLockerTestFileContents); IO.File.WriteAllText(testPathModule, dtAppLockerTestFileContents); } - catch (System.IO.IOException) + catch (IO.IOException) { - if (iteration == 2) throw; + if (iteration == 2) + { + throw; + } + error = true; } - catch (System.UnauthorizedAccessException) + catch (UnauthorizedAccessException) { - if (iteration == 2) throw; + if (iteration == 2) + { + throw; + } + error = true; } catch (System.Security.SecurityException) { - if (iteration == 2) throw; + if (iteration == 2) + { + throw; + } + error = true; } - if (!error) { break; } + if (!error) + { + break; + } // Try again with the AppData\LocalLow\Temp path using known folder id: // https://msdn.microsoft.com/library/dd378457.aspx @@ -352,7 +630,7 @@ private static SaferPolicy TestSaferPolicy(string testPathScript, string testPat return result; } - private static SystemEnforcementMode GetDebugLockdownPolicy(string path) + private static SystemEnforcementMode GetDebugLockdownPolicy(string path, out SystemScriptFileEnforcement modernEnforcement) { s_allowDebugOverridePolicy = true; @@ -363,10 +641,19 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) // check so that we can actually put it in the filename during testing. if (path.Contains("System32", StringComparison.OrdinalIgnoreCase)) { + modernEnforcement = SystemScriptFileEnforcement.Allow; return SystemEnforcementMode.None; } // No explicit debug allowance for the file, so return the system policy if there is one. + modernEnforcement = s_systemLockdownPolicy switch + { + SystemEnforcementMode.Enforce => SystemScriptFileEnforcement.AllowConstrained, + SystemEnforcementMode.Audit => SystemScriptFileEnforcement.AllowConstrainedAudit, + SystemEnforcementMode.None => SystemScriptFileEnforcement.None, + _ => SystemScriptFileEnforcement.None, + }; + return s_systemLockdownPolicy.GetValueOrDefault(SystemEnforcementMode.None); } @@ -376,10 +663,13 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) if (result != null) { pdwLockdownState = LanguagePrimitives.ConvertTo(result); - return GetLockdownPolicyForResult(pdwLockdownState); + SystemEnforcementMode policy = GetLockdownPolicyForResult(pdwLockdownState); + modernEnforcement = ConvertToModernFileEnforcement(policy); + return policy; } // If the system-wide debug policy had no preference, then there is no enforcement. + modernEnforcement = SystemScriptFileEnforcement.None; return SystemEnforcementMode.None; } @@ -391,6 +681,14 @@ private static SystemEnforcementMode GetDebugLockdownPolicy(string path) /// True if the COM object is allowed, False otherwise. internal static bool IsClassInApprovedList(Guid clsid) { + // This method is called only if there is an AppLocker and/or WLDP system wide lock down enforcement policy. + if (s_cachedWldpSystemPolicy.GetValueOrDefault(SystemEnforcementMode.None) != SystemEnforcementMode.Enforce) + { + // No WLDP policy implies only AppLocker policy enforcement. Disallow all COM object instantiation. + return false; + } + + // WLDP policy must be in system wide enforcement, look up COM Id in WLDP approval list. try { WLDP_HOST_INFORMATION hostInformation = new WLDP_HOST_INFORMATION(); @@ -538,18 +836,75 @@ internal struct WLDP_HOST_INFORMATION internal IntPtr hSource; } + /// + /// Options for WldpCanExecuteFile method. + /// + [Flags] + internal enum WLDP_EXECUTION_EVALUATION_OPTIONS + { + WLDP_EXECUTION_EVALUATION_OPTION_NONE = 0x0, + WLDP_EXECUTION_EVALUATION_OPTION_EXECUTE_IN_INTERACTIVE_SESSION = 0x1 + } + + /// + /// Results from WldpCanExecuteFile method. + /// + internal enum WLDP_EXECUTION_POLICY + { + WLDP_CAN_EXECUTE_BLOCKED = 0, + WLDP_CAN_EXECUTE_ALLOWED = 1, + WLDP_CAN_EXECUTE_REQUIRE_SANDBOX = 2 + } + + /// + /// Powershell Script Host. + /// + internal static readonly Guid PowerShellHost = new Guid("8E9AAA7C-198B-4879-AE41-A50D47AD6458"); + /// /// Native methods for dealing with the lockdown policy. /// - internal static class WldpNativeMethods + internal static partial class WldpNativeMethods { + [DefaultDllImportSearchPaths(DllImportSearchPath.System32)] + [LibraryImport("wldp.dll", StringMarshalling = StringMarshalling.Utf16)] + internal static partial int WldpGetApplicationSettingBoolean( + string id, + string setting, + [MarshalAs(UnmanagedType.Bool)] + out bool result); + + /// + /// Returns a WLDP_EXECUTION_POLICY enum value indicating if and how a script file + /// should be executed. + /// + /// Host guid. + /// Evaluation options. + /// Evaluated file handle. + /// Auditing information string. + /// Evaluation result. + /// HResult value. + [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] + [DllImportAttribute("wldp.dll", EntryPoint = "WldpCanExecuteFile")] + internal static extern int WldpCanExecuteFile( + [MarshalAs(UnmanagedType.LPStruct)] + Guid host, + WLDP_EXECUTION_EVALUATION_OPTIONS options, + IntPtr fileHandle, + [MarshalAs(UnmanagedType.LPWStr)] + string auditInfo, + out WLDP_EXECUTION_POLICY result); + /// Return Type: HRESULT->LONG->int /// pHostInformation: PWLDP_HOST_INFORMATION->_WLDP_HOST_INFORMATION* /// pdwLockdownState: PDWORD->DWORD* /// dwFlags: DWORD->unsigned int [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("wldp.dll", EntryPoint = "WldpGetLockdownPolicy")] - internal static extern int WldpGetLockdownPolicy(ref WLDP_HOST_INFORMATION pHostInformation, ref uint pdwLockdownState, uint dwFlags); + internal static extern int WldpGetLockdownPolicy( + ref WLDP_HOST_INFORMATION pHostInformation, + ref uint pdwLockdownState, + uint dwFlags); /// Return Type: HRESULT->LONG->int /// rclsid: IID* @@ -558,7 +913,11 @@ internal static class WldpNativeMethods /// dwFlags: DWORD->unsigned int [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("wldp.dll", EntryPoint = "WldpIsClassInApprovedList")] - internal static extern int WldpIsClassInApprovedList(ref Guid rclsid, ref WLDP_HOST_INFORMATION pHostInformation, ref int ptIsApproved, uint dwFlags); + internal static extern int WldpIsClassInApprovedList( + ref Guid rclsid, + ref WLDP_HOST_INFORMATION pHostInformation, + ref int ptIsApproved, + uint dwFlags); [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)] internal static extern int SHGetKnownFolderPath( diff --git a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs index 7e5a675a2b3..be4fa6c2edb 100644 --- a/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshConsoleLoadException.cs @@ -20,7 +20,6 @@ namespace System.Management.Automation.Runspaces /// 1. PSSnapin name /// 2. Inner exception. /// --> - [Serializable] public class PSConsoleLoadException : SystemException, IContainsErrorRecord { /// @@ -86,7 +85,7 @@ private void CreateErrorRecord() _errorRecord = new ErrorRecord(new ParentContainsErrorRecordException(this), "ConsoleLoadFailure", ErrorCategory.ResourceUnavailable, null); } - private Collection _PSSnapInExceptions = new Collection(); + private readonly Collection _PSSnapInExceptions = new Collection(); internal Collection PSSnapInExceptions { diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs index db45a12b378..df01b053665 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinInfo.cs @@ -69,7 +69,7 @@ internal static class RegistryStrings } /// - /// Contains information about a mshsnapin. + /// Contains information about a PSSnapin. /// public class PSSnapInInfo { @@ -118,25 +118,13 @@ string vendorFallback version = new Version("0.0"); } - if (types == null) - { - types = new Collection(); - } + types ??= new Collection(); - if (formats == null) - { - formats = new Collection(); - } + formats ??= new Collection(); - if (descriptionFallback == null) - { - descriptionFallback = string.Empty; - } + descriptionFallback ??= string.Empty; - if (vendorFallback == null) - { - vendorFallback = string.Empty; - } + vendorFallback ??= string.Empty; Name = name; IsDefault = isDefault; @@ -201,22 +189,22 @@ string vendorIndirect } /// - /// Unique Name of the mshsnapin. + /// Unique Name of the PSSnapin. /// public string Name { get; } /// - /// Is this mshsnapin default mshsnapin. + /// Is this PSSnapin default PSSnapin. /// public bool IsDefault { get; } /// - /// Returns applicationbase for mshsnapin. + /// Returns applicationbase for PSSnapin. /// public string ApplicationBase { get; } /// - /// Strong name of mshSnapIn assembly. + /// Strong name of PSSnapin assembly. /// public string AssemblyName { get; } @@ -243,12 +231,12 @@ internal string AbsoluteModulePath } /// - /// Monad version used by mshsnapin. + /// PowerShell version used by PSSnapin. /// public Version PSVersion { get; } /// - /// Version of mshsnapin. + /// Version of PSSnapin. /// public Version Version { get; } @@ -262,11 +250,11 @@ internal string AbsoluteModulePath /// public Collection Formats { get; } - private string _descriptionIndirect; - private string _descriptionFallback = string.Empty; + private readonly string _descriptionIndirect; + private readonly string _descriptionFallback = string.Empty; private string _description; /// - /// Description of mshsnapin. + /// Description of PSSnapin. /// public string Description { @@ -281,11 +269,11 @@ public string Description } } - private string _vendorIndirect; - private string _vendorFallback = string.Empty; + private readonly string _vendorIndirect; + private readonly string _vendorFallback = string.Empty; private string _vendor; /// - /// Vendor of mshsnapin. + /// Vendor of PSSnapin. /// public string Vendor { @@ -419,8 +407,9 @@ internal PSSnapInInfo Clone() } /// - /// Returns true if the PSSnapIn Id is valid. A PSSnapIn is valid iff it contains only - /// "Alpha Numeric","-","_","." characters. + /// Returns true if the PSSnapIn Id is valid. A PSSnapIn is valid + /// if-and-only-if it contains only "Alpha Numeric","-","_","." + /// characters. /// /// PSSnapIn Id to validate. internal static bool IsPSSnapinIdValid(string psSnapinId) @@ -434,8 +423,8 @@ internal static bool IsPSSnapinIdValid(string psSnapinId) } /// - /// Validates the PSSnapIn Id. A PSSnapIn is valid iff it contains only - /// "Alpha Numeric","-","_","." characters. + /// Validates the PSSnapIn Id. A PSSnapIn is valid if-and-only-if it + /// contains only "Alpha Numeric","-","_","." characters. /// /// PSSnapIn Id to validate. /// @@ -773,8 +762,7 @@ private static Collection ReadMultiStringValue(RegistryKey mshsnapinKey, if (msv == null) { // Check if the value is in string format - string singleValue = value as string; - if (singleValue != null) + if (value is string singleValue) { msv = new string[1]; msv[0] = singleValue; @@ -877,18 +865,18 @@ internal static Version ReadVersionValue(RegistryKey mshsnapinKey, string name, return v; } - internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string architecture, out string applicationBase, out Version psVersion) + internal static void ReadRegistryInfo(out Version assemblyVersion, out string publicKeyToken, out string culture, out string applicationBase, out Version psVersion) { applicationBase = Utils.DefaultPowerShellAppBase; Dbg.Assert( !string.IsNullOrEmpty(applicationBase), - string.Format(CultureInfo.CurrentCulture, "{0} is empty or null", RegistryStrings.MonadEngine_ApplicationBase)); + string.Create(CultureInfo.CurrentCulture, $"{RegistryStrings.MonadEngine_ApplicationBase} is empty or null")); // Get the PSVersion from Utils..this is hardcoded psVersion = PSVersionInfo.PSVersion; Dbg.Assert( psVersion != null, - string.Format(CultureInfo.CurrentCulture, "{0} is null", RegistryStrings.MonadEngine_MonadVersion)); + string.Create(CultureInfo.CurrentCulture, $"{RegistryStrings.MonadEngine_MonadVersion} is null")); // Get version number in x.x.x.x format // This information is available from the executing assembly @@ -897,8 +885,7 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu // culture, publickeytoken...This will break the scenarios where only one of // the assemblies is patched. ie., all monad assemblies should have the // same version number. - Assembly currentAssembly = typeof(PSSnapInReader).Assembly; - AssemblyName assemblyName = currentAssembly.GetName(); + AssemblyName assemblyName = typeof(PSSnapInReader).Assembly.GetName(); assemblyVersion = assemblyName.Version; byte[] publicTokens = assemblyName.GetPublicKeyToken(); if (publicTokens.Length == 0) @@ -911,11 +898,6 @@ internal static void ReadRegistryInfo(out Version assemblyVersion, out string pu // save some cpu cycles by hardcoding the culture to neutral // assembly should never be targeted to a particular culture culture = "neutral"; - - // Hardcoding the architecture MSIL as PowerShell assemblies are architecture neutral, this should - // be changed if the assumption is broken. Preferred hardcoded string to using (for perf reasons): - // string architecture = currentAssembly.GetName().ProcessorArchitecture.ToString() - architecture = "MSIL"; } /// @@ -943,23 +925,27 @@ internal static string ConvertByteArrayToString(byte[] tokens) /// internal static PSSnapInInfo ReadCoreEngineSnapIn() { - Version assemblyVersion, psVersion; - string publicKeyToken = null; - string culture = null; - string architecture = null; - string applicationBase = null; - - ReadRegistryInfo(out assemblyVersion, out publicKeyToken, out culture, out architecture, out applicationBase, out psVersion); + ReadRegistryInfo( + out Version assemblyVersion, + out string publicKeyToken, + out string culture, + out string applicationBase, + out Version psVersion); // System.Management.Automation formats & types files Collection types = new Collection(new string[] { "types.ps1xml", "typesv3.ps1xml" }); Collection formats = new Collection(new string[] - {"Certificate.format.ps1xml","DotNetTypes.format.ps1xml","FileSystem.format.ps1xml", - "Help.format.ps1xml","HelpV3.format.ps1xml","PowerShellCore.format.ps1xml","PowerShellTrace.format.ps1xml", + {"Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml", + "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); - string strongName = string.Format(CultureInfo.InvariantCulture, "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", - s_coreSnapin.AssemblyName, assemblyVersion, culture, publicKeyToken, architecture); + string strongName = string.Format( + CultureInfo.InvariantCulture, + "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", + s_coreSnapin.AssemblyName, + assemblyVersion, + culture, + publicKeyToken); string moduleName = Path.Combine(applicationBase, s_coreSnapin.AssemblyName + ".dll"); @@ -997,18 +983,17 @@ internal static PSSnapInInfo ReadCoreEngineSnapIn() /// internal static Collection ReadEnginePSSnapIns() { - Version assemblyVersion, psVersion; - string publicKeyToken = null; - string culture = null; - string architecture = null; - string applicationBase = null; - - ReadRegistryInfo(out assemblyVersion, out publicKeyToken, out culture, out architecture, out applicationBase, out psVersion); + ReadRegistryInfo( + out Version assemblyVersion, + out string publicKeyToken, + out string culture, + out string applicationBase, + out Version psVersion); // System.Management.Automation formats & types files Collection smaFormats = new Collection(new string[] - {"Certificate.format.ps1xml","DotNetTypes.format.ps1xml","FileSystem.format.ps1xml", - "Help.format.ps1xml","HelpV3.format.ps1xml","PowerShellCore.format.ps1xml","PowerShellTrace.format.ps1xml", + {"Certificate.format.ps1xml", "DotNetTypes.format.ps1xml", "FileSystem.format.ps1xml", + "Help.format.ps1xml", "HelpV3.format.ps1xml", "PowerShellCore.format.ps1xml", "PowerShellTrace.format.ps1xml", "Registry.format.ps1xml"}); Collection smaTypes = new Collection(new string[] { "types.ps1xml", "typesv3.ps1xml" }); @@ -1022,12 +1007,11 @@ internal static Collection ReadEnginePSSnapIns() string strongName = string.Format( CultureInfo.InvariantCulture, - "{0}, Version={1}, Culture={2}, PublicKeyToken={3}, ProcessorArchitecture={4}", + "{0}, Version={1}, Culture={2}, PublicKeyToken={3}", defaultMshSnapinInfo.AssemblyName, assemblyVersionString, culture, - publicKeyToken, - architecture); + publicKeyToken); Collection formats = null; Collection types = null; @@ -1296,7 +1280,9 @@ private static IList DefaultMshSnapins { lock (s_syncObject) { +#pragma warning disable IDE0074 // Disabling the rule because it can't be applied on non Unix if (s_defaultMshSnapins == null) +#pragma warning restore IDE0074 { s_defaultMshSnapins = new List() { @@ -1305,18 +1291,18 @@ private static IList DefaultMshSnapins "GetEventResources,Description", "GetEventResources,Vendor"), #endif new DefaultPSSnapInInformation("Microsoft.PowerShell.Host", "Microsoft.PowerShell.ConsoleHost", null, - "HostMshSnapInResources,Description","HostMshSnapInResources,Vendor"), + "HostMshSnapInResources,Description", "HostMshSnapInResources,Vendor"), s_coreSnapin, new DefaultPSSnapInInformation("Microsoft.PowerShell.Utility", "Microsoft.PowerShell.Commands.Utility", null, - "UtilityMshSnapInResources,Description","UtilityMshSnapInResources,Vendor"), + "UtilityMshSnapInResources,Description", "UtilityMshSnapInResources,Vendor"), new DefaultPSSnapInInformation("Microsoft.PowerShell.Management", "Microsoft.PowerShell.Commands.Management", null, - "ManagementMshSnapInResources,Description","ManagementMshSnapInResources,Vendor"), + "ManagementMshSnapInResources,Description", "ManagementMshSnapInResources,Vendor"), new DefaultPSSnapInInformation("Microsoft.PowerShell.Security", "Microsoft.PowerShell.Security", null, - "SecurityMshSnapInResources,Description","SecurityMshSnapInResources,Vendor") + "SecurityMshSnapInResources,Description", "SecurityMshSnapInResources,Vendor") }; #if !UNIX @@ -1335,10 +1321,10 @@ private static IList DefaultMshSnapins } private static IList s_defaultMshSnapins = null; - private static object s_syncObject = new object(); + private static readonly object s_syncObject = new object(); #endregion - private static PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); + private static readonly PSTraceSource s_mshsnapinTracer = PSTraceSource.GetTracer("MshSnapinLoadUnload", "Loading and unloading mshsnapins", false); } } diff --git a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs index b7b38254f29..71c81611440 100644 --- a/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs +++ b/src/System.Management.Automation/singleshell/config/MshSnapinLoadException.cs @@ -19,7 +19,6 @@ namespace System.Management.Automation.Runspaces /// 1. PSSnapin name /// 2. Inner exception. /// --> - [Serializable] public class PSSnapInException : RuntimeException { /// @@ -116,7 +115,7 @@ private void CreateErrorRecord() } } - private bool _warning = false; + private readonly bool _warning = false; private ErrorRecord _errorRecord; private bool _isErrorRecordOriginallyNull; @@ -146,8 +145,8 @@ public override ErrorRecord ErrorRecord } } - private string _PSSnapin = string.Empty; - private string _reason = string.Empty; + private readonly string _PSSnapin = string.Empty; + private readonly string _reason = string.Empty; /// /// Gets message for this exception. @@ -172,32 +171,11 @@ public override string Message /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSSnapInException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _PSSnapin = info.GetString("PSSnapIn"); - _reason = info.GetString("Reason"); - - CreateErrorRecord(); - } - - /// - /// Get object data from serialization information. - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw PSTraceSource.NewArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - - info.AddValue("PSSnapIn", _PSSnapin); - info.AddValue("Reason", _reason); + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs b/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs deleted file mode 100644 index eecde27926c..00000000000 --- a/src/System.Management.Automation/utils/ArchitectureSensitiveAttribute.cs +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace System.Management.Automation.Internal -{ - /// - /// This attribute is used for Design For Testability. - /// It should be placed on any method containing code - /// which is likely to be sensitive to X86/X64/IA64 issues, - /// primarily code which calls DllImports or otherwise uses - /// NativeMethods. This allows us to generate code coverage - /// data specific to architecture sensitive code. - /// - [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] - internal class ArchitectureSensitiveAttribute : Attribute - { - /// - /// Constructor for the ArchitectureSensitiveAttribute class. - /// - internal ArchitectureSensitiveAttribute() - { - } - } -} diff --git a/src/System.Management.Automation/utils/BackgroundDispatcher.cs b/src/System.Management.Automation/utils/BackgroundDispatcher.cs deleted file mode 100644 index 583eecfa836..00000000000 --- a/src/System.Management.Automation/utils/BackgroundDispatcher.cs +++ /dev/null @@ -1,137 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. - -namespace System.Management.Automation -{ - using System; - using System.Diagnostics.Eventing; - using System.Management.Automation.Tracing; - using System.Threading; - - /// - /// An object that can be used to execute a method on a threadpool thread while correctly - /// managing system state, such as flowing ETW activities from the current thread to the - /// threadpool thread. - /// - public interface IBackgroundDispatcher - { - /// - /// Works the same as , except that it - /// also manages system state correctly. - /// - bool QueueUserWorkItem(WaitCallback callback); - - /// - /// Works the same as , except that it - /// also manages system state correctly. - /// - bool QueueUserWorkItem(WaitCallback callback, object state); - - /// - /// Works the same as BeginInvoke would for any other delegate, except that it also manages system state correctly. - /// - IAsyncResult BeginInvoke(WaitCallback callback, object state, AsyncCallback completionCallback, object asyncState); - - /// - /// Works the same as EndInvoke would for any other delegate, except that it also manages system state correctly. - /// - void EndInvoke(IAsyncResult asyncResult); - } - - /// - /// A simple implementation of . - /// - public class BackgroundDispatcher : - IBackgroundDispatcher - { - #region Instance Data - - private readonly IMethodInvoker _etwActivityMethodInvoker; - private readonly WaitCallback _invokerWaitCallback; - - #endregion - - #region Creation/Cleanup - - /// - /// Creates a that uses an - /// for activity creation and correlation. - /// - /// The to use when logging transfer events - /// during activity correlation. - /// The to use when logging transfer events - /// during activity correlation. - public BackgroundDispatcher(EventProvider transferProvider, EventDescriptor transferEvent) - : this(new EtwActivityReverterMethodInvoker(new EtwEventCorrelator(transferProvider, transferEvent))) - { - // nothing - } - - // internal for unit testing only. Otherwise, would be private. - internal BackgroundDispatcher(IMethodInvoker etwActivityMethodInvoker) - { - if (etwActivityMethodInvoker == null) - { - throw new ArgumentNullException("etwActivityMethodInvoker"); - } - - _etwActivityMethodInvoker = etwActivityMethodInvoker; - _invokerWaitCallback = DoInvoker; - } - - #endregion - - #region Instance Utilities - - private void DoInvoker(object invokerArgs) - { - var invokerArgsArray = (object[])invokerArgs; - - _etwActivityMethodInvoker.Invoker.DynamicInvoke(invokerArgsArray); - } - - #endregion - - #region Instance Access - - /// - /// Implements . - /// - public bool QueueUserWorkItem(WaitCallback callback) - { - return QueueUserWorkItem(callback, null); - } - - /// - /// Implements . - /// - public bool QueueUserWorkItem(WaitCallback callback, object state) - { - var invokerArgs = _etwActivityMethodInvoker.CreateInvokerArgs(callback, new object[] { state }); - - var result = ThreadPool.QueueUserWorkItem(_invokerWaitCallback, invokerArgs); - return result; - } - - /// - /// Implements . - /// - public IAsyncResult BeginInvoke(WaitCallback callback, object state, AsyncCallback completionCallback, object asyncState) - { - var invokerArgs = _etwActivityMethodInvoker.CreateInvokerArgs(callback, new object[] { state }); - - var result = _invokerWaitCallback.BeginInvoke(invokerArgs, completionCallback, asyncState); - return result; - } - - /// - /// Implements . - /// - public void EndInvoke(IAsyncResult asyncResult) - { - _invokerWaitCallback.EndInvoke(asyncResult); - } - - #endregion - } -} diff --git a/src/System.Management.Automation/utils/ClrFacade.cs b/src/System.Management.Automation/utils/ClrFacade.cs index 0372b249ca1..058c33a68bf 100644 --- a/src/System.Management.Automation/utils/ClrFacade.cs +++ b/src/System.Management.Automation/utils/ClrFacade.cs @@ -7,7 +7,6 @@ using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Reflection; -using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Security; using System.Text; @@ -23,13 +22,23 @@ internal static class ClrFacade { /// /// Initialize powershell AssemblyLoadContext and register the 'Resolving' event, if it's not done already. - /// If powershell is hosted by a native host such as DSC, then PS ALC might be initialized via 'SetPowerShellAssemblyLoadContext' before loading S.M.A. + /// If powershell is hosted by a native host such as DSC, then PS ALC may be initialized via 'SetPowerShellAssemblyLoadContext' before loading S.M.A. /// + /// + /// We do this both here and during the initialization of the 'RunspaceBase' type. + /// This is because we want to make sure the assembly/library resolvers are: + /// 1. registered before any script/cmdlet can run. + /// 2. registered before 'ClrFacade' gets used for assembly related operations. + /// + /// The 'ClrFacade' type may be used without a Runspace created, for example, by calling type conversion methods in the 'LanguagePrimitive' type. + /// And at the mean time, script or cmdlet may run without the 'ClrFacade' type initialized. + /// That's why we attempt to create the singleton of 'PowerShellAssemblyLoadContext' at both places. + /// static ClrFacade() { - if (PowerShellAssemblyLoadContext.Instance == null) + if (PowerShellAssemblyLoadContext.Instance is null) { - PowerShellAssemblyLoadContext.InitializeSingleton(string.Empty); + PowerShellAssemblyLoadContext.InitializeSingleton(string.Empty, throwOnReentry: false); } } @@ -100,23 +109,6 @@ private static IEnumerable GetPSVisibleAssemblies() #region Encoding - /// - /// Facade for getting default encoding. - /// - internal static Encoding GetDefaultEncoding() - { - if (s_defaultEncoding == null) - { - // load all available encodings - EncodingRegisterProvider(); - s_defaultEncoding = new UTF8Encoding(false); - } - - return s_defaultEncoding; - } - - private static volatile Encoding s_defaultEncoding; - /// /// Facade for getting OEM encoding /// OEM encodings work on all platforms, or rather codepage 437 is available on both Windows and Non-Windows. @@ -125,12 +117,10 @@ internal static Encoding GetOEMEncoding() { if (s_oemEncoding == null) { - // load all available encodings - EncodingRegisterProvider(); #if UNIX - s_oemEncoding = new UTF8Encoding(false); + s_oemEncoding = Encoding.Default; #else - uint oemCp = NativeMethods.GetOEMCP(); + uint oemCp = Interop.Windows.GetOEMCP(); s_oemEncoding = Encoding.GetEncoding((int)oemCp); #endif } @@ -140,14 +130,6 @@ internal static Encoding GetOEMEncoding() private static volatile Encoding s_oemEncoding; - private static void EncodingRegisterProvider() - { - if (s_defaultEncoding == null && s_oemEncoding == null) - { - Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); - } - } - #endregion Encoding #if !UNIX @@ -263,7 +245,7 @@ private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath) } // If we successfully get the zone data stream, try to read the ZoneId information - using (StreamReader zoneDataReader = new StreamReader(zoneDataStream, GetDefaultEncoding())) + using (StreamReader zoneDataReader = new StreamReader(zoneDataStream, Encoding.Default)) { string line = null; bool zoneTransferMatched = false; @@ -288,12 +270,18 @@ private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath) else { Match match = Regex.Match(line, @"^ZoneId\s*=\s*(.*)", RegexOptions.IgnoreCase); - if (!match.Success) { continue; } + if (!match.Success) + { + continue; + } // Match found. Validate ZoneId value. string zoneIdRawValue = match.Groups[1].Value; match = Regex.Match(zoneIdRawValue, @"^[+-]?\d+", RegexOptions.IgnoreCase); - if (!match.Success) { return SecurityZone.NoZone; } + if (!match.Success) + { + return SecurityZone.NoZone; + } string zoneId = match.Groups[0].Value; SecurityZone result; @@ -356,7 +344,7 @@ internal static string ToDmtfDateTime(DateTime date) dmtfDateTime += date.Second.ToString(frmInt32).PadLeft(2, '0'); dmtfDateTime += "."; - // Construct a DateTime with with the precision to Second as same as the passed DateTime and so get + // Construct a DateTime with the precision to Second as same as the passed DateTime and so get // the ticks difference so that the microseconds can be calculated DateTime dtTemp = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); Int64 microsec = ((date.Ticks - dtTemp.Ticks) * 1000) / TimeSpan.TicksPerMillisecond; @@ -379,17 +367,5 @@ internal static string ToDmtfDateTime(DateTime date) } #endregion Misc - - /// - /// Native methods that are used by facade methods. - /// - private static class NativeMethods - { - /// - /// Pinvoke for GetOEMCP to get the OEM code page. - /// - [DllImport(PinvokeDllNames.GetOEMCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] - internal static extern uint GetOEMCP(); - } } } diff --git a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs index e08d8e1a65c..89580932359 100644 --- a/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs +++ b/src/System.Management.Automation/utils/CommandDiscoveryExceptions.cs @@ -11,7 +11,6 @@ namespace System.Management.Automation /// /// This exception is thrown when a command cannot be found. /// - [Serializable] public class CommandNotFoundException : RuntimeException { /// @@ -70,7 +69,6 @@ public CommandNotFoundException(string message) : base(message) { } /// public CommandNotFoundException(string message, Exception innerException) : base(message, innerException) { } - #region Serialization /// /// Serialization constructor for class CommandNotFoundException. /// @@ -80,39 +78,13 @@ public CommandNotFoundException(string message, Exception innerException) : base /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CommandNotFoundException(SerializationInfo info, StreamingContext context) - : base(info, context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - _commandName = info.GetString("CommandName"); + throw new NotSupportedException(); } - /// - /// Serializes the CommandNotFoundException. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("CommandName", _commandName); - } - #endregion Serialization - #region Properties /// /// Gets the ErrorRecord information for this exception. @@ -121,14 +93,11 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - _errorCategory, - _commandName); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + _errorCategory, + _commandName); return _errorRecord; } @@ -181,7 +150,6 @@ params object[] messageArgs /// Defines the exception thrown when a script's requirements to run specified by the #requires /// statements are not met. /// - [Serializable] public class ScriptRequiresException : RuntimeException { /// @@ -368,39 +336,13 @@ public ScriptRequiresException(string message, Exception innerException) : base( /// /// streaming context /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptRequiresException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _commandName = info.GetString("CommandName"); - _requiresPSVersion = (Version)info.GetValue("RequiresPSVersion", typeof(Version)); - _missingPSSnapIns = (ReadOnlyCollection)info.GetValue("MissingPSSnapIns", typeof(ReadOnlyCollection)); - _requiresShellId = info.GetString("RequiresShellId"); - _requiresShellPath = info.GetString("RequiresShellPath"); + throw new NotSupportedException(); } - /// - /// Gets the serialized data for the exception. - /// - /// - /// serialization information - /// - /// - /// streaming context - /// - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - base.GetObjectData(info, context); - info.AddValue("CommandName", _commandName); - info.AddValue("RequiresPSVersion", _requiresPSVersion, typeof(Version)); - info.AddValue("MissingPSSnapIns", _missingPSSnapIns, typeof(ReadOnlyCollection)); - info.AddValue("RequiresShellId", _requiresShellId); - info.AddValue("RequiresShellPath", _requiresShellPath); - } #endregion Serialization #region Properties diff --git a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs index 4aebe05af59..668c95a25e6 100644 --- a/src/System.Management.Automation/utils/CommandProcessorExceptions.cs +++ b/src/System.Management.Automation/utils/CommandProcessorExceptions.cs @@ -8,7 +8,6 @@ namespace System.Management.Automation /// /// Defines the exception that is thrown if a native command fails. /// - [Serializable] public class ApplicationFailedException : RuntimeException { #region private @@ -25,10 +24,11 @@ public class ApplicationFailedException : RuntimeException /// The serialization information to use when initializing this object. /// The streaming context to use when initializing this object. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ApplicationFailedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization diff --git a/src/System.Management.Automation/utils/CryptoUtils.cs b/src/System.Management.Automation/utils/CryptoUtils.cs index e121dd62b6d..c82c96ecdc3 100644 --- a/src/System.Management.Automation/utils/CryptoUtils.cs +++ b/src/System.Management.Automation/utils/CryptoUtils.cs @@ -5,7 +5,6 @@ using System.IO; using System.Linq; using System.Management.Automation.Remoting; -using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security; using System.Security.Cryptography; @@ -43,7 +42,7 @@ internal static class PSCryptoNativeConverter /// public const uint PUBLICKEYBLOB = 0x00000006; - /// + /// /// PUBLICKEYBLOB header length. /// public const int PUBLICKEYBLOB_HEADER_LEN = 20; @@ -53,7 +52,7 @@ internal static class PSCryptoNativeConverter /// public const uint SIMPLEBLOB = 0x00000001; - /// + /// /// SIMPLEBLOB header length. /// public const int SIMPLEBLOB_HEADER_LEN = 12; @@ -97,10 +96,7 @@ internal static RSA FromCapiPublicKeyBlob(byte[] blob) private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (offset > blob.Length) { @@ -123,10 +119,7 @@ private static RSA FromCapiPublicKeyBlob(byte[] blob, int offset) private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int offset) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (offset > blob.Length) { @@ -175,10 +168,7 @@ private static RSAParameters GetParametersFromCapiPublicKeyBlob(byte[] blob, int internal static byte[] ToCapiPublicKeyBlob(RSA rsa) { - if (rsa == null) - { - throw new ArgumentNullException(nameof(rsa)); - } + ArgumentNullException.ThrowIfNull(rsa); RSAParameters p = rsa.ExportParameters(false); int keyLength = p.Modulus.Length; // in bytes @@ -221,10 +211,7 @@ internal static byte[] ToCapiPublicKeyBlob(RSA rsa) internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) { - if (blob == null) - { - throw new ArgumentNullException(nameof(blob)); - } + ArgumentNullException.ThrowIfNull(blob); if (blob.Length < SIMPLEBLOB_HEADER_LEN) { @@ -237,10 +224,7 @@ internal static byte[] FromCapiSimpleKeyBlob(byte[] blob) internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) { - if (encryptedKey == null) - { - throw new ArgumentNullException(nameof(encryptedKey)); - } + ArgumentNullException.ThrowIfNull(encryptedKey); // formulate the PUBLICKEYSTRUCT byte[] blob = new byte[SIMPLEBLOB_HEADER_LEN + encryptedKey.Length]; @@ -250,9 +234,9 @@ internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) // [2], [3] // RESERVED - Always 0 blob[4] = (byte)CALG_AES_256; // AES-256 algo id (0x10) blob[5] = 0x66; // ?? - // [6], [7], [8] // 0x00 + // [6], [7], [8] // 0x00 blob[9] = (byte)CALG_RSA_KEYX; // 0xa4 - // [10], [11] // 0x00 + // [10], [11] // 0x00 // create a reversed copy and add the encrypted key byte[] reversedKey = CreateReverseByteArray(encryptedKey); @@ -273,7 +257,6 @@ internal static byte[] ToCapiSimpleKeyBlob(byte[] encryptedKey) /// to the user when something fails on the remote end, then this /// can be turned public [SuppressMessage("Microsoft.Design", "CA1064:ExceptionsShouldBePublic")] - [Serializable] internal class PSCryptoException : Exception { #region Private Members @@ -344,33 +327,20 @@ public PSCryptoException(string message, Exception innerException) /// Context in which this constructor is called. /// Currently no custom type-specific serialization logic is /// implemented + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSCryptoException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorCode = unchecked(0xFFFFFFF); - Dbg.Assert(false, "type-specific serialization logic not implemented and so this constructor should not be called"); + throw new NotSupportedException(); } #endregion Constructors - - #region ISerializable Overrides - /// - /// Returns base implementation. - /// - /// Serialization info. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - base.GetObjectData(info, context); - } - #endregion ISerializable Overrides } /// /// A reverse compatible implementation of session key exchange. This supports the CAPI /// keyblob formats but uses dotnet std abstract AES and RSA classes for all crypto operations. /// - internal class PSRSACryptoServiceProvider : IDisposable + internal sealed class PSRSACryptoServiceProvider : IDisposable { #region Private Members @@ -380,7 +350,7 @@ internal class PSRSACryptoServiceProvider : IDisposable // handle to the AES provider object (houses session key and iv) private readonly Aes _aes; - // this flag indicates that this class has a key imported from the + // this flag indicates that this class has a key imported from the // remote end and so can be used for encryption private bool _canEncrypt; @@ -438,7 +408,7 @@ internal void GenerateSessionKey() { if (!_sessionKeyGenerated) { - // Aes object gens key automatically on construction, so this is somewhat redundant, + // Aes object gens key automatically on construction, so this is somewhat redundant, // but at least the actionable key will not be in-memory until it's requested fwiw. _aes.GenerateKey(); _sessionKeyGenerated = true; @@ -463,6 +433,7 @@ internal string SafeExportSessionKey() GenerateSessionKey(); // encrypt it + // codeql[cs/cryptography/rsa-unapproved-encryption-padding-scheme] - PowerShell v7.4 and later versions have deprecated the key exchange in the remoting protocol. This code is kept only for backward compatibility reason. byte[] encryptedKey = _rsa.Encrypt(_aes.Key, RSAEncryptionPadding.Pkcs1); // convert the key to capi simpleblob format before exporting @@ -496,6 +467,7 @@ internal void ImportSessionKeyFromBase64EncodedString(string sessionKey) byte[] sessionKeyBlob = Convert.FromBase64String(sessionKey); byte[] rsaEncryptedKey = PSCryptoNativeConverter.FromCapiSimpleKeyBlob(sessionKeyBlob); + // codeql[cs/cryptography/rsa-unapproved-encryption-padding-scheme] - PowerShell v7.4 and later versions have deprecated the key exchange in the remoting protocol. This code is kept only for backward compatibility reason. _aes.Key = _rsa.Decrypt(rsaEncryptedKey, RSAEncryptionPadding.Pkcs1); // now we have imported the key and will be able to @@ -604,28 +576,12 @@ internal static PSRSACryptoServiceProvider GetRSACryptoServiceProviderForServer( #region IDisposable /// - /// Dispose resources. + /// Release all resources. /// public void Dispose() { - Dispose(true); - System.GC.SuppressFinalize(this); - } - - protected void Dispose(bool disposing) - { - if (disposing) - { - if (_rsa != null) - { - _rsa.Dispose(); - } - - if (_aes != null) - { - _aes.Dispose(); - } - } + _rsa?.Dispose(); + _aes?.Dispose(); } #endregion IDisposable @@ -635,7 +591,7 @@ protected void Dispose(bool disposing) /// Helper for exchanging keys and encrypting/decrypting /// secure strings for serialization in remoting. /// - internal abstract class PSRemotingCryptoHelper : IDisposable + public abstract class PSRemotingCryptoHelper : IDisposable { #region Protected Members @@ -645,7 +601,7 @@ internal abstract class PSRemotingCryptoHelper : IDisposable /// it and performing symmetric key operations using the /// session key. /// - protected PSRSACryptoServiceProvider _rsaCryptoProvider; + internal PSRSACryptoServiceProvider _rsaCryptoProvider; /// /// Key exchange has been completed and both keys @@ -694,6 +650,78 @@ protected void RunKeyExchangeIfRequired() } } + /// + /// Gets the bytes of a secure string. + /// + private static byte[] GetBytesFromSecureString(SecureString secureString) + { + return secureString is null + ? null + : Microsoft.PowerShell.SecureStringHelper.GetData(secureString); + } + + /// + /// Gets a secure string from the specified byte array. + /// + private static SecureString GetSecureStringFromBytes(byte[] data) + { + Dbg.Assert(data is not null, "The passed-in data cannot be null."); + + try + { + return Microsoft.PowerShell.SecureStringHelper.New(data); + } + finally + { + // zero out the contents + Array.Clear(data); + } + } + + /// + /// Convert a secure string to a base64 encoded string. + /// + protected string ConvertSecureStringToBase64String(SecureString secureString) + { + string dataAsString = null; + byte[] data = GetBytesFromSecureString(secureString); + + if (data is not null) + { + try + { + dataAsString = Convert.ToBase64String(data); + } + finally + { + Array.Clear(data); + } + } + + return dataAsString; + } + + /// + /// Convert a base64 encoded string to a secure string. + /// + /// + /// + protected SecureString ConvertBase64StringToSecureString(string base64String) + { + try + { + byte[] data = Convert.FromBase64String(base64String); + return GetSecureStringFromBytes(data); + } + catch (FormatException) + { + // do nothing + // this catch is to ensure that the exception doesn't + // go unhandled leading to a crash + throw new PSCryptoException(); + } + } + /// /// Core logic to encrypt a string. Assumes session key is already generated. /// @@ -707,18 +735,10 @@ protected string EncryptSecureStringCore(SecureString secureString) if (_rsaCryptoProvider.CanEncrypt) { - IntPtr ptr = Marshal.SecureStringToCoTaskMemUnicode(secureString); + byte[] data = GetBytesFromSecureString(secureString); - if (ptr != IntPtr.Zero) + if (data is not null) { - byte[] data = new byte[secureString.Length * 2]; - for (int i = 0; i < data.Length; i++) - { - data[i] = Marshal.ReadByte(ptr, i); - } - - Marshal.ZeroFreeCoTaskMemUnicode(ptr); - try { byte[] encryptedData = _rsaCryptoProvider.EncryptWithSessionKey(data); @@ -726,10 +746,7 @@ protected string EncryptSecureStringCore(SecureString secureString) } finally { - for (int j = 0; j < data.Length; j++) - { - data[j] = 0; - } + Array.Clear(data); } } } @@ -759,10 +776,11 @@ protected SecureString DecryptSecureStringCore(string encryptedString) // happened successfully if (_rsaCryptoProvider.CanEncrypt) { - byte[] data = null; try { - data = Convert.FromBase64String(encryptedString); + byte[] data = Convert.FromBase64String(encryptedString); + byte[] decryptedData = _rsaCryptoProvider.DecryptWithSessionKey(data); + secureString = GetSecureStringFromBytes(decryptedData); } catch (FormatException) { @@ -771,36 +789,6 @@ protected SecureString DecryptSecureStringCore(string encryptedString) // go unhandled leading to a crash throw new PSCryptoException(); } - - if (data != null) - { - byte[] decryptedData = _rsaCryptoProvider.DecryptWithSessionKey(data); - - secureString = new SecureString(); - UInt16 value = 0; - try - { - for (int i = 0; i < decryptedData.Length; i += 2) - { - value = (UInt16)(decryptedData[i] + (UInt16)(decryptedData[i + 1] << 8)); - secureString.AppendChar((char)value); - value = 0; - } - } - finally - { - // if there was an exception for whatever reason, - // clear the last value store in Value - value = 0; - - // zero out the contents - for (int i = 0; i < decryptedData.Length; i += 2) - { - decryptedData[i] = 0; - decryptedData[i + 1] = 0; - } - } - } } else { @@ -851,11 +839,7 @@ public void Dispose(bool disposing) { if (disposing) { - if (_rsaCryptoProvider != null) - { - _rsaCryptoProvider.Dispose(); - } - + _rsaCryptoProvider?.Dispose(); _rsaCryptoProvider = null; _keyExchangeCompleted.Dispose(); @@ -906,17 +890,30 @@ internal PSRemotingCryptoHelperServer() internal override string EncryptSecureString(SecureString secureString) { - ServerRemoteSession session = Session as ServerRemoteSession; - // session!=null check required for DRTs TestEncryptSecureString* entries in CryptoUtilsTest/UTUtils.dll - // for newer clients, server will never initiate key exchange. - // for server, just the session key is required to encrypt/decrypt anything - if ((session != null) && (session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersionWin8RTM)) + bool initiateKeyExchange = true; + + if (Session is ServerRemoteSession session) { - _rsaCryptoProvider.GenerateSessionKey(); + Version clientProtocolVersion = session.Context.ClientCapability.ProtocolVersion; + if (clientProtocolVersion >= RemotingConstants.ProtocolVersion_2_4) + { + // For client v2.4+, we no longer encrypt secure strings, but rely on the underlying secure transport to do the right thing. + return ConvertSecureStringToBase64String(secureString); + } + + if (clientProtocolVersion >= RemotingConstants.ProtocolVersion_2_2) + { + // For client v2.2+, server will never initiate key exchange. + // For server, just the session key is required to encrypt/decrypt anything + initiateKeyExchange = false; + _rsaCryptoProvider.GenerateSessionKey(); + } } - else // older clients + + if (initiateKeyExchange) { + // older clients. RunKeyExchangeIfRequired(); } @@ -925,6 +922,12 @@ internal override string EncryptSecureString(SecureString secureString) internal override SecureString DecryptSecureString(string encryptedString) { + if (Session is ServerRemoteSession session && session.Context.ClientCapability.ProtocolVersion >= RemotingConstants.ProtocolVersion_2_4) + { + // For client v2.4+, we no longer encrypt secure strings, but rely on the underlying secure transport to do the right thing. + return ConvertBase64StringToSecureString(encryptedString); + } + RunKeyExchangeIfRequired(); return DecryptSecureStringCore(encryptedString); @@ -1036,6 +1039,12 @@ internal PSRemotingCryptoHelperClient() internal override string EncryptSecureString(SecureString secureString) { + if (Session is ClientRemoteSession session && session.ServerProtocolVersion >= RemotingConstants.ProtocolVersion_2_4) + { + // For server v2.4+, we no longer encrypt secure strings, but rely on the underlying secure transport to do the right thing. + return ConvertSecureStringToBase64String(secureString); + } + RunKeyExchangeIfRequired(); return EncryptSecureStringCore(secureString); @@ -1043,6 +1052,12 @@ internal override string EncryptSecureString(SecureString secureString) internal override SecureString DecryptSecureString(string encryptedString) { + if (Session is ClientRemoteSession session && session.ServerProtocolVersion >= RemotingConstants.ProtocolVersion_2_4) + { + // For server v2.4+, we no longer encrypt secure strings, but rely on the underlying secure transport to do the right thing. + return ConvertBase64StringToSecureString(encryptedString); + } + RunKeyExchangeIfRequired(); return DecryptSecureStringCore(encryptedString); diff --git a/src/System.Management.Automation/utils/EncodingUtils.cs b/src/System.Management.Automation/utils/EncodingUtils.cs index e9802488006..cdb467d213a 100644 --- a/src/System.Management.Automation/utils/EncodingUtils.cs +++ b/src/System.Management.Automation/utils/EncodingUtils.cs @@ -2,6 +2,7 @@ // Licensed under the MIT License. using System.Collections.Generic; +using System.Globalization; using System.Text; using System.Management.Automation.Internal; @@ -10,41 +11,43 @@ namespace System.Management.Automation { internal static class EncodingConversion { - internal const string Unknown = "unknown"; - internal const string String = "string"; - internal const string Unicode = "unicode"; + internal const string ANSI = "ansi"; + internal const string Ascii = "ascii"; internal const string BigEndianUnicode = "bigendianunicode"; internal const string BigEndianUtf32 = "bigendianutf32"; - internal const string Ascii = "ascii"; + internal const string Default = "default"; + internal const string OEM = "oem"; + internal const string String = "string"; + internal const string Unicode = "unicode"; + internal const string Unknown = "unknown"; + internal const string Utf7 = "utf7"; internal const string Utf8 = "utf8"; - internal const string Utf8NoBom = "utf8NoBOM"; internal const string Utf8Bom = "utf8BOM"; - internal const string Utf7 = "utf7"; + internal const string Utf8NoBom = "utf8NoBOM"; internal const string Utf32 = "utf32"; - internal const string Default = "default"; - internal const string OEM = "oem"; internal static readonly string[] TabCompletionResults = { - Ascii, BigEndianUnicode, BigEndianUtf32, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 + ANSI, Ascii, BigEndianUnicode, BigEndianUtf32, OEM, Unicode, Utf7, Utf8, Utf8Bom, Utf8NoBom, Utf32 }; - internal static readonly Dictionary encodingMap = new Dictionary(StringComparer.OrdinalIgnoreCase) + internal static readonly Dictionary encodingMap = new(StringComparer.OrdinalIgnoreCase) { - { Ascii, System.Text.Encoding.ASCII }, - { BigEndianUnicode, System.Text.Encoding.BigEndianUnicode }, + { ANSI, Encoding.GetEncoding(CultureInfo.CurrentCulture.TextInfo.ANSICodePage) }, + { Ascii, Encoding.ASCII }, + { BigEndianUnicode, Encoding.BigEndianUnicode }, { BigEndianUtf32, new UTF32Encoding(bigEndian: true, byteOrderMark: true) }, - { Default, ClrFacade.GetDefaultEncoding() }, + { Default, Encoding.Default }, { OEM, ClrFacade.GetOEMEncoding() }, - { Unicode, System.Text.Encoding.Unicode }, + { String, Encoding.Unicode }, + { Unicode, Encoding.Unicode }, + { Unknown, Encoding.Unicode }, #pragma warning disable SYSLIB0001 - { Utf7, System.Text.Encoding.UTF7 }, + { Utf7, Encoding.UTF7 }, #pragma warning restore SYSLIB0001 - { Utf8, ClrFacade.GetDefaultEncoding() }, - { Utf8Bom, System.Text.Encoding.UTF8 }, - { Utf8NoBom, ClrFacade.GetDefaultEncoding() }, - { Utf32, System.Text.Encoding.UTF32 }, - { String, System.Text.Encoding.Unicode }, - { Unknown, System.Text.Encoding.Unicode }, + { Utf8, Encoding.Default }, + { Utf8Bom, Encoding.UTF8 }, + { Utf8NoBom, Encoding.Default }, + { Utf32, Encoding.UTF32 }, }; /// @@ -57,11 +60,10 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) if (string.IsNullOrEmpty(encoding)) { // no parameter passed, default to UTF8 - return ClrFacade.GetDefaultEncoding(); + return Encoding.Default; } - Encoding foundEncoding; - if (encodingMap.TryGetValue(encoding, out foundEncoding)) + if (encodingMap.TryGetValue(encoding, out Encoding foundEncoding)) { // Write a warning if using utf7 as it is obsolete in .NET5 if (string.Equals(encoding, Utf7, StringComparison.OrdinalIgnoreCase)) @@ -96,7 +98,7 @@ internal static Encoding Convert(Cmdlet cmdlet, string encoding) internal static void WarnIfObsolete(Cmdlet cmdlet, Encoding encoding) { // Check for UTF-7 by checking for code page 65000 - // See: https://docs.microsoft.com/en-us/dotnet/core/compatibility/corefx#utf-7-code-paths-are-obsolete + // See: https://learn.microsoft.com/dotnet/core/compatibility/corefx#utf-7-code-paths-are-obsolete if (encoding != null && encoding.CodePage == 65000) { cmdlet.WriteWarning(PathUtilsStrings.Utf7EncodingObsolete); @@ -113,6 +115,8 @@ internal sealed class ArgumentToEncodingTransformationAttribute : ArgumentTransf { public override object Transform(EngineIntrinsics engineIntrinsics, object inputData) { + inputData = PSObject.Base(inputData); + switch (inputData) { case string stringName: @@ -122,10 +126,10 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input } else { - return System.Text.Encoding.GetEncoding(stringName); + return Encoding.GetEncoding(stringName); } case int intName: - return System.Text.Encoding.GetEncoding(intName); + return Encoding.GetEncoding(intName); } return inputData; @@ -138,6 +142,7 @@ public override object Transform(EngineIntrinsics engineIntrinsics, object input internal sealed class ArgumentEncodingCompletionsAttribute : ArgumentCompletionsAttribute { public ArgumentEncodingCompletionsAttribute() : base( + EncodingConversion.ANSI, EncodingConversion.Ascii, EncodingConversion.BigEndianUnicode, EncodingConversion.BigEndianUtf32, diff --git a/src/System.Management.Automation/utils/ExecutionExceptions.cs b/src/System.Management.Automation/utils/ExecutionExceptions.cs index 226a9cb8cdd..ff41e045bbb 100644 --- a/src/System.Management.Automation/utils/ExecutionExceptions.cs +++ b/src/System.Management.Automation/utils/ExecutionExceptions.cs @@ -19,7 +19,6 @@ namespace System.Management.Automation /// /// InnerException is the error which the cmdlet hit. /// - [Serializable] public class CmdletInvocationException : RuntimeException { #region ctor @@ -30,10 +29,7 @@ public class CmdletInvocationException : RuntimeException internal CmdletInvocationException(ErrorRecord errorRecord) : base(RetrieveMessage(errorRecord), RetrieveException(errorRecord)) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; if (errorRecord.Exception != null) @@ -55,14 +51,10 @@ internal CmdletInvocationException(Exception innerException, InvocationInfo invocationInfo) : base(RetrieveMessage(innerException), innerException) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } + ArgumentNullException.ThrowIfNull(innerException); // invocationInfo may be null - IContainsErrorRecord icer = innerException as IContainsErrorRecord; - if (icer != null && icer.ErrorRecord != null) + if (innerException is IContainsErrorRecord icer && icer.ErrorRecord != null) { _errorRecord = new ErrorRecord(icer.ErrorRecord, innerException); } @@ -122,32 +114,11 @@ public CmdletInvocationException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CmdletInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - bool hasErrorRecord = info.GetBoolean("HasErrorRecord"); - if (hasErrorRecord) - _errorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord)); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - bool hasErrorRecord = (_errorRecord != null); - info.AddValue("HasErrorRecord", hasErrorRecord); - if (hasErrorRecord) - info.AddValue("ErrorRecord", _errorRecord); + throw new NotSupportedException(); } #endregion Serialization #endregion ctor @@ -161,14 +132,11 @@ public override ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - "CmdletInvocationException", - ErrorCategory.NotSpecified, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + "CmdletInvocationException", + ErrorCategory.NotSpecified, + null); return _errorRecord; } @@ -187,7 +155,6 @@ public override ErrorRecord ErrorRecord /// This is generally reported from the standard provider navigation cmdlets /// such as get-childitem. /// - [Serializable] public class CmdletProviderInvocationException : CmdletInvocationException { #region ctor @@ -204,10 +171,7 @@ internal CmdletProviderInvocationException( InvocationInfo myInvocation) : base(GetInnerException(innerException), myInvocation) { - if (innerException == null) - { - throw new ArgumentNullException(nameof(innerException)); - } + ArgumentNullException.ThrowIfNull(innerException); _providerInvocationException = innerException; } @@ -229,11 +193,11 @@ public CmdletProviderInvocationException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected CmdletProviderInvocationException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _providerInvocationException = InnerException as ProviderInvocationException; + throw new NotSupportedException(); } /// @@ -310,15 +274,14 @@ private static Exception GetInnerException(Exception e) /// user hitting CTRL-C, or by a call to /// . /// - /// When a cmdlet or provider sees this exception thrown from a Monad API such as + /// When a cmdlet or provider sees this exception thrown from a PowerShell API such as /// WriteObject(object) /// this means that the command was already stopped. The cmdlet or provider /// should clean up and return. /// Catching this exception is optional; if the cmdlet or providers chooses not to /// handle PipelineStoppedException and instead allow it to propagate to the - /// Monad Engine's call to ProcessRecord, the Monad Engine will handle it properly. + /// PowerShell Engine's call to ProcessRecord, the PowerShell Engine will handle it properly. /// - [Serializable] public class PipelineStoppedException : RuntimeException { #region ctor @@ -341,12 +304,11 @@ public PipelineStoppedException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PipelineStoppedException(SerializationInfo info, StreamingContext context) - : base(info, context) { - // no properties, nothing more to serialize - // no need for a GetObjectData implementation + throw new NotSupportedException(); } /// @@ -381,7 +343,6 @@ public PipelineStoppedException(string message, /// been stopped. /// /// - [Serializable] public class PipelineClosedException : RuntimeException { #region ctor @@ -426,10 +387,11 @@ public PipelineClosedException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PipelineClosedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization } @@ -444,7 +406,6 @@ protected PipelineClosedException(SerializationInfo info, /// For example, if $WarningPreference is "Stop", the command will fail with /// this error if a cmdlet calls WriteWarning. /// - [Serializable] public class ActionPreferenceStopException : RuntimeException { #region ctor @@ -467,10 +428,7 @@ public ActionPreferenceStopException() internal ActionPreferenceStopException(ErrorRecord error) : this(RetrieveMessage(error)) { - if (error == null) - { - throw new ArgumentNullException(nameof(error)); - } + ArgumentNullException.ThrowIfNull(error); _errorRecord = error; } @@ -495,10 +453,7 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, string message) : this(invocationInfo, message) { - if (errorRecord == null) - { - throw new ArgumentNullException(nameof(errorRecord)); - } + ArgumentNullException.ThrowIfNull(errorRecord); _errorRecord = errorRecord; } @@ -512,46 +467,11 @@ internal ActionPreferenceStopException(InvocationInfo invocationInfo, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ActionPreferenceStopException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - bool hasErrorRecord = info.GetBoolean("HasErrorRecord"); - if (hasErrorRecord) - _errorRecord = (ErrorRecord)info.GetValue("ErrorRecord", typeof(ErrorRecord)); - - // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 - // The interpreter prompt CommandBaseStrings:InquireHalt - // should be suppressed when this flag is set. This will be set - // when this prompt has already occurred and Break was chosen, - // or for ActionPreferenceStopException in all cases. - this.SuppressPromptInInterpreter = true; - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - base.GetObjectData(info, context); - if (info != null) - { - bool hasErrorRecord = (_errorRecord != null); - info.AddValue("HasErrorRecord", hasErrorRecord); - if (hasErrorRecord) - { - info.AddValue("ErrorRecord", _errorRecord); - } - } - - // fix for BUG: Windows Out Of Band Releases: 906263 and 906264 - // The interpreter prompt CommandBaseStrings:InquireHalt - // should be suppressed when this flag is set. This will be set - // when this prompt has already occurred and Break was chosen, - // or for ActionPreferenceStopException in all cases. - this.SuppressPromptInInterpreter = true; + throw new NotSupportedException(); } #endregion Serialization @@ -619,15 +539,14 @@ public override ErrorRecord ErrorRecord #region ParentContainsErrorRecordException /// /// ParentContainsErrorRecordException is the exception contained by the ErrorRecord - /// which is associated with a Monad engine custom exception through + /// which is associated with a PowerShell engine custom exception through /// the IContainsErrorRecord interface. /// /// /// We use this exception class /// so that there is not a recursive "containment" relationship - /// between the Monad engine exception and its ErrorRecord. + /// between the PowerShell engine exception and its ErrorRecord. /// - [Serializable] public class ParentContainsErrorRecordException : SystemException { #region Constructors @@ -693,11 +612,11 @@ public ParentContainsErrorRecordException(string message, /// Streaming context. /// Doesn't return. /// Always. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParentContainsErrorRecordException( SerializationInfo info, StreamingContext context) - : base(info, context) { - _message = info.GetString("ParentContainsErrorRecordException_Message"); + throw new NotSupportedException(); } #endregion Serialization /// @@ -711,22 +630,6 @@ public override string Message } } - /// - /// Serializer for - /// - /// Serialization information. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ParentContainsErrorRecordException_Message", this.Message); - } - #region Private Data private readonly Exception _wrapperException; @@ -746,7 +649,6 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont /// /// in the ErrorRecord which contains this exception. /// - [Serializable] public class RedirectedException : RuntimeException { #region constructors @@ -795,10 +697,11 @@ public RedirectedException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected RedirectedException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion constructors } @@ -811,13 +714,12 @@ protected RedirectedException(SerializationInfo info, /// exceeds the configured maximum. /// /// - /// When one Monad command or script calls another, this creates an additional - /// scope. Some script expressions also create a scope. Monad imposes a maximum + /// When one PowerShell command or script calls another, this creates an additional + /// scope. Some script expressions also create a scope. PowerShell imposes a maximum /// call depth to prevent stack overflows. The maximum call depth is configurable /// but generally high enough that scripts which are not deeply recursive /// should not have a problem. /// - [Serializable] public class ScriptCallDepthException : SystemException, IContainsErrorRecord { #region ctor @@ -863,19 +765,11 @@ public ScriptCallDepthException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ScriptCallDepthException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - /// - /// Serializer for - /// - /// Serialization information. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - base.GetObjectData(info, context); + throw new NotSupportedException(); } #endregion Serialization @@ -891,14 +785,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - "CallDepthOverflow", - ErrorCategory.InvalidOperation, - CallDepth); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + "CallDepthOverflow", + ErrorCategory.InvalidOperation, + CallDepth); return _errorRecord; } @@ -925,7 +816,6 @@ public int CallDepth /// /// /// - [Serializable] public class PipelineDepthException : SystemException, IContainsErrorRecord { #region ctor @@ -970,19 +860,11 @@ public PipelineDepthException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PipelineDepthException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } - /// - /// Serializer for - /// - /// Serialization information. - /// Context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) { - base.GetObjectData(info, context); + throw new NotSupportedException(); } #endregion Serialization @@ -999,14 +881,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - "CallDepthOverflow", - ErrorCategory.InvalidOperation, - CallDepth); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + "CallDepthOverflow", + ErrorCategory.InvalidOperation, + CallDepth); return _errorRecord; } @@ -1040,7 +919,6 @@ public int CallDepth /// Note that HaltCommandException does not define IContainsErrorRecord. /// This is because it is not reported to the user. /// - [Serializable] public class HaltCommandException : SystemException { #region ctor @@ -1085,10 +963,11 @@ public HaltCommandException(string message, /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HaltCommandException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion Serialization } diff --git a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs index d4d877355c4..87da1d2a1d7 100644 --- a/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs +++ b/src/System.Management.Automation/utils/FormatAndTypeDataHelper.cs @@ -73,7 +73,7 @@ internal static class FormatAndTypeDataHelper private static string GetBaseFolder(Collection independentErrors) { - return Path.GetDirectoryName(PsUtils.GetMainModule(System.Diagnostics.Process.GetCurrentProcess()).FileName); + return Path.GetDirectoryName(Environment.ProcessPath); } private static string GetAndCheckFullFileName( diff --git a/src/System.Management.Automation/utils/FuzzyMatch.cs b/src/System.Management.Automation/utils/FuzzyMatch.cs index 5b21022a6ef..c4e542a3ca5 100644 --- a/src/System.Management.Automation/utils/FuzzyMatch.cs +++ b/src/System.Management.Automation/utils/FuzzyMatch.cs @@ -1,23 +1,38 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. +using System.Collections.Generic; using System.Globalization; namespace System.Management.Automation { - internal static class FuzzyMatcher + internal class FuzzyMatcher { - public const int MinimumDistance = 5; + internal readonly uint MinimumDistance; + + internal FuzzyMatcher(uint minimumDistance) + { + MinimumDistance = minimumDistance; + } /// /// Determine if the two strings are considered similar. /// - /// The first string to compare. - /// The second string to compare. + internal bool IsFuzzyMatch(string candidate, string pattern) + { + return IsFuzzyMatch(candidate, pattern, out _); + } + + /// + /// Determine if the two strings are considered similar, and return the similarity score. + /// + /// The candidate string to be compared. + /// The pattern string to be compared with. /// True if the two strings have a distance <= MinimumDistance. - public static bool IsFuzzyMatch(string string1, string string2) + internal bool IsFuzzyMatch(string candidate, string pattern, out int score) { - return GetDamerauLevenshteinDistance(string1, string2) <= MinimumDistance; + score = GetDamerauLevenshteinDistance(candidate, pattern); + return score <= MinimumDistance; } /// @@ -27,7 +42,7 @@ public static bool IsFuzzyMatch(string string1, string string2) /// The first string to compare. /// The second string to compare. /// The distance value where the lower the value the shorter the distance between the two strings representing a closer match. - public static int GetDamerauLevenshteinDistance(string string1, string string2) + internal static int GetDamerauLevenshteinDistance(string string1, string string2) { string1 = string1.ToUpper(CultureInfo.CurrentCulture); string2 = string2.ToUpper(CultureInfo.CurrentCulture); @@ -36,8 +51,15 @@ public static int GetDamerauLevenshteinDistance(string string1, string string2) int[,] matrix = new int[bounds.Height, bounds.Width]; - for (int height = 0; height < bounds.Height; height++) { matrix[height, 0] = height; } - for (int width = 0; width < bounds.Width; width++) { matrix[0, width] = width; } + for (int height = 0; height < bounds.Height; height++) + { + matrix[height, 0] = height; + } + + for (int width = 0; width < bounds.Width; width++) + { + matrix[0, width] = width; + } for (int height = 1; height < bounds.Height; height++) { diff --git a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs index f38bdb18f87..ec780222345 100644 --- a/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs +++ b/src/System.Management.Automation/utils/GraphicalHostReflectionWrapper.cs @@ -18,7 +18,7 @@ namespace System.Management.Automation.Internal /// 2) show-command window implementation (the actual cmdlet is in Microsoft.PowerShell.Commands.Utility.dll) /// 3) the help window used in the System.Management.Automation.dll's get-help cmdlet when -ShowWindow is specified. /// - internal class GraphicalHostReflectionWrapper + internal sealed class GraphicalHostReflectionWrapper { /// /// Initialized in GetGraphicalHostReflectionWrapper with the Microsoft.PowerShell.GraphicalHost.dll assembly. @@ -55,7 +55,7 @@ private GraphicalHostReflectionWrapper() /// When it was not possible to load Microsoft.PowerShell.GraphicalHost.dlly. internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName) { - return GraphicalHostReflectionWrapper.GetGraphicalHostReflectionWrapper(parentCmdlet, graphicalHostHelperTypeName, parentCmdlet.CommandInfo.Name); + return GetGraphicalHostReflectionWrapper(parentCmdlet, graphicalHostHelperTypeName, parentCmdlet.CommandInfo.Name); } /// @@ -73,9 +73,9 @@ internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Assembly.Load has been found to throw unadvertised exceptions")] internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper(PSCmdlet parentCmdlet, string graphicalHostHelperTypeName, string featureName) { - GraphicalHostReflectionWrapper returnValue = new GraphicalHostReflectionWrapper(); + GraphicalHostReflectionWrapper returnValue = new(); - if (GraphicalHostReflectionWrapper.IsInputFromRemoting(parentCmdlet)) + if (IsInputFromRemoting(parentCmdlet)) { ErrorRecord error = new ErrorRecord( new NotSupportedException(StringUtil.Format(HelpErrors.RemotingNotSupportedForFeature, featureName)), @@ -87,9 +87,10 @@ internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper } // Prepare the full assembly name. - AssemblyName graphicalHostAssemblyName = new AssemblyName(); + AssemblyName smaAssemblyName = typeof(PSObject).Assembly.GetName(); + AssemblyName graphicalHostAssemblyName = new(); graphicalHostAssemblyName.Name = "Microsoft.PowerShell.GraphicalHost"; - graphicalHostAssemblyName.Version = new Version(3, 0, 0, 0); + graphicalHostAssemblyName.Version = smaAssemblyName.Version; graphicalHostAssemblyName.CultureInfo = new CultureInfo(string.Empty); // Neutral culture graphicalHostAssemblyName.SetPublicKeyToken(new byte[] { 0x31, 0xbf, 0x38, 0x56, 0xad, 0x36, 0x4e, 0x35 }); @@ -124,7 +125,7 @@ internal static GraphicalHostReflectionWrapper GetGraphicalHostReflectionWrapper returnValue._graphicalHostHelperType = returnValue._graphicalHostAssembly.GetType(graphicalHostHelperTypeName); - Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type exists in Microsoft.PowerShell.GraphicalHost"); + Diagnostics.Assert(returnValue._graphicalHostHelperType != null, "the type should exist in Microsoft.PowerShell.GraphicalHost"); ConstructorInfo constructor = returnValue._graphicalHostHelperType.GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, diff --git a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs index 91e742fa3c5..df36d248d18 100644 --- a/src/System.Management.Automation/utils/HostInterfacesExceptions.cs +++ b/src/System.Management.Automation/utils/HostInterfacesExceptions.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation.Host /// Defines the exception thrown when the Host cannot complete an operation /// such as checking whether there is any input available. /// - [Serializable] public class HostException : RuntimeException { @@ -101,10 +100,11 @@ class HostException : RuntimeException /// /// The contextual information about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected HostException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion @@ -121,7 +121,6 @@ private void SetDefaultErrorRecord() /// /// Defines the exception thrown when an error occurs from prompting for a command parameter. /// - [Serializable] public class PromptingException : HostException { @@ -210,10 +209,11 @@ class PromptingException : HostException /// /// The contextual information about the source or destination. /// + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PromptingException(SerializationInfo info, StreamingContext context) - : base(info, context) { + throw new NotSupportedException(); } #endregion diff --git a/src/System.Management.Automation/utils/MetadataExceptions.cs b/src/System.Management.Automation/utils/MetadataExceptions.cs index 53f2328fc3d..24660d348e7 100644 --- a/src/System.Management.Automation/utils/MetadataExceptions.cs +++ b/src/System.Management.Automation/utils/MetadataExceptions.cs @@ -10,7 +10,6 @@ namespace System.Management.Automation /// /// Defines the exception thrown for all Metadata errors. /// - [Serializable] public class MetadataException : RuntimeException { internal const string MetadataMemberInitialization = "MetadataMemberInitialization"; @@ -21,9 +20,10 @@ public class MetadataException : RuntimeException /// /// Serialization information. /// Streaming context. - protected MetadataException(SerializationInfo info, StreamingContext context) : base(info, context) + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected MetadataException(SerializationInfo info, StreamingContext context) { - SetErrorCategory(ErrorCategory.MetadataError); + throw new NotSupportedException(); } /// @@ -48,7 +48,7 @@ public MetadataException(string message) : base(message) /// Initializes a new instance of MetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public MetadataException(string message, Exception innerException) : base(message, innerException) { SetErrorCategory(ErrorCategory.MetadataError); @@ -71,8 +71,6 @@ internal MetadataException( /// /// Defines the exception thrown for all Validate attributes. /// - [Serializable] - [SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")] public class ValidationMetadataException : MetadataException { internal const string ValidateRangeElementType = "ValidateRangeElementType"; @@ -109,7 +107,12 @@ public class ValidationMetadataException : MetadataException /// /// Serialization information. /// Streaming context. - protected ValidationMetadataException(SerializationInfo info, StreamingContext context) : base(info, context) { } + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected ValidationMetadataException(SerializationInfo info, StreamingContext context) + { + throw new NotSupportedException(); + } + /// /// Initializes a new instance of ValidationMetadataException with the message set /// to typeof(ValidationMetadataException).FullName. @@ -124,7 +127,7 @@ public ValidationMetadataException(string message) : this(message, false) { } /// Initializes a new instance of ValidationMetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ValidationMetadataException(string message, Exception innerException) : base(message, innerException) { } internal ValidationMetadataException( @@ -167,7 +170,6 @@ internal bool SwallowException /// /// Defines the exception thrown for all ArgumentTransformation attributes. /// - [Serializable] public class ArgumentTransformationMetadataException : MetadataException { internal const string ArgumentTransformationArgumentsShouldBeStrings = "ArgumentTransformationArgumentsShouldBeStrings"; @@ -177,8 +179,11 @@ public class ArgumentTransformationMetadataException : MetadataException /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ArgumentTransformationMetadataException(SerializationInfo info, StreamingContext context) - : base(info, context) { } + { + throw new NotSupportedException(); + } /// /// Initializes a new instance of ArgumentTransformationMetadataException with the message set @@ -198,7 +203,7 @@ public ArgumentTransformationMetadataException(string message) /// Initializes a new instance of ArgumentTransformationMetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ArgumentTransformationMetadataException(string message, Exception innerException) : base(message, innerException) { } @@ -215,7 +220,6 @@ internal ArgumentTransformationMetadataException( /// /// Defines the exception thrown for all parameter binding exceptions related to metadata attributes. /// - [Serializable] public class ParsingMetadataException : MetadataException { internal const string ParsingTooManyParameterSets = "ParsingTooManyParameterSets"; @@ -225,8 +229,11 @@ public class ParsingMetadataException : MetadataException /// /// Serialization information. /// Streaming context. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected ParsingMetadataException(SerializationInfo info, StreamingContext context) - : base(info, context) { } + { + throw new NotSupportedException(); + } /// /// Initializes a new instance of ParsingMetadataException with the message set @@ -246,7 +253,7 @@ public ParsingMetadataException(string message) /// Initializes a new instance of ParsingMetadataException setting the message and innerException. /// /// The exception's message. - /// The exceptions's inner exception. + /// The exception's inner exception. public ParsingMetadataException(string message, Exception innerException) : base(message, innerException) { } diff --git a/src/System.Management.Automation/utils/MshArgumentException.cs b/src/System.Management.Automation/utils/MshArgumentException.cs index d9c9ce725eb..452527d1c18 100644 --- a/src/System.Management.Automation/utils/MshArgumentException.cs +++ b/src/System.Management.Automation/utils/MshArgumentException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSArgumentException : ArgumentException, IContainsErrorRecord { @@ -69,30 +68,13 @@ public PSArgumentException(string message, string paramName) /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSArgumentException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - _message = info.GetString("PSArgumentException_MessageOverride"); + throw new NotSupportedException(); } - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - info.AddValue("PSArgumentException_MessageOverride", _message); - } #endregion Serialization /// @@ -121,14 +103,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.InvalidArgument, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.InvalidArgument, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshArgumentNullException.cs b/src/System.Management.Automation/utils/MshArgumentNullException.cs index be20163607b..16ef442e5ec 100644 --- a/src/System.Management.Automation/utils/MshArgumentNullException.cs +++ b/src/System.Management.Automation/utils/MshArgumentNullException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSArgumentNullException : ArgumentNullException, IContainsErrorRecord { @@ -80,29 +79,11 @@ public PSArgumentNullException(string paramName, string message) /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSArgumentNullException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - _message = info.GetString("PSArgumentNullException_MessageOverride"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - info.AddValue("PSArgumentNullException_MessageOverride", _message); + throw new NotSupportedException(); } #endregion Serialization #endregion ctor @@ -119,14 +100,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.InvalidArgument, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.InvalidArgument, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs index 2bf48e9047f..4e65ed0acb1 100644 --- a/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs +++ b/src/System.Management.Automation/utils/MshArgumentOutOfRangeException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSArgumentOutOfRangeException : ArgumentOutOfRangeException, IContainsErrorRecord { @@ -68,28 +67,13 @@ public PSArgumentOutOfRangeException(string paramName, object actualValue, strin /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSArgumentOutOfRangeException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); + throw new NotSupportedException(); } - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } #endregion Serialization /// @@ -117,14 +101,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.InvalidArgument, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.InvalidArgument, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshInvalidOperationException.cs b/src/System.Management.Automation/utils/MshInvalidOperationException.cs index f9a65fcf8aa..8400e762360 100644 --- a/src/System.Management.Automation/utils/MshInvalidOperationException.cs +++ b/src/System.Management.Automation/utils/MshInvalidOperationException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSInvalidOperationException : InvalidOperationException, IContainsErrorRecord { @@ -39,27 +38,11 @@ public PSInvalidOperationException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSInvalidOperationException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); + throw new NotSupportedException(); } #endregion Serialization @@ -115,14 +98,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - _errorCategory, - _target); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + _errorCategory, + _target); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshNotImplementedException.cs b/src/System.Management.Automation/utils/MshNotImplementedException.cs index 6c2dd504cf0..1b925053410 100644 --- a/src/System.Management.Automation/utils/MshNotImplementedException.cs +++ b/src/System.Management.Automation/utils/MshNotImplementedException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSNotImplementedException : NotImplementedException, IContainsErrorRecord { @@ -39,27 +38,11 @@ public PSNotImplementedException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSNotImplementedException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); - } - - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); + throw new NotSupportedException(); } #endregion Serialization @@ -98,14 +81,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.NotImplemented, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.NotImplemented, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshNotSupportedException.cs b/src/System.Management.Automation/utils/MshNotSupportedException.cs index 7614080dcff..a1e519a960e 100644 --- a/src/System.Management.Automation/utils/MshNotSupportedException.cs +++ b/src/System.Management.Automation/utils/MshNotSupportedException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSNotSupportedException : NotSupportedException, IContainsErrorRecord { @@ -39,28 +38,13 @@ public PSNotSupportedException() /// Serialization information. /// Streaming context. /// Constructed object. + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] protected PSNotSupportedException(SerializationInfo info, StreamingContext context) - : base(info, context) { - _errorId = info.GetString("ErrorId"); + throw new NotSupportedException(); } - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } #endregion Serialization /// @@ -98,14 +82,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.NotImplemented, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.NotImplemented, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshObjectDisposedException.cs b/src/System.Management.Automation/utils/MshObjectDisposedException.cs index b8d4ab421cc..1bbf1f846d4 100644 --- a/src/System.Management.Automation/utils/MshObjectDisposedException.cs +++ b/src/System.Management.Automation/utils/MshObjectDisposedException.cs @@ -13,10 +13,9 @@ namespace System.Management.Automation /// /// /// Instances of this exception class are usually generated by the - /// Monad Engine. It is unusual for code outside the Monad Engine + /// PowerShell Engine. It is unusual for code outside the PowerShell Engine /// to create an instance of this class. /// - [Serializable] public class PSObjectDisposedException : ObjectDisposedException, IContainsErrorRecord { @@ -67,28 +66,12 @@ public PSObjectDisposedException(string message, Exception innerException) /// Serialization information. /// Streaming context. /// Constructed object. - protected PSObjectDisposedException(SerializationInfo info, - StreamingContext context) - : base(info, context) + [Obsolete("Legacy serialization support is deprecated since .NET 8", DiagnosticId = "SYSLIB0051")] + protected PSObjectDisposedException(SerializationInfo info, StreamingContext context) : base(info, context) { - _errorId = info.GetString("ErrorId"); + throw new NotSupportedException(); } - /// - /// Serializer for - /// - /// Serialization information. - /// Streaming context. - public override void GetObjectData(SerializationInfo info, StreamingContext context) - { - if (info == null) - { - throw new PSArgumentNullException(nameof(info)); - } - - base.GetObjectData(info, context); - info.AddValue("ErrorId", _errorId); - } #endregion Serialization #endregion ctor @@ -104,14 +87,11 @@ public ErrorRecord ErrorRecord { get { - if (_errorRecord == null) - { - _errorRecord = new ErrorRecord( - new ParentContainsErrorRecordException(this), - _errorId, - ErrorCategory.InvalidOperation, - null); - } + _errorRecord ??= new ErrorRecord( + new ParentContainsErrorRecordException(this), + _errorId, + ErrorCategory.InvalidOperation, + null); return _errorRecord; } diff --git a/src/System.Management.Automation/utils/MshTraceSource.cs b/src/System.Management.Automation/utils/MshTraceSource.cs index 8ed5949c31a..dd7d3214ff3 100644 --- a/src/System.Management.Automation/utils/MshTraceSource.cs +++ b/src/System.Management.Automation/utils/MshTraceSource.cs @@ -10,14 +10,14 @@ namespace System.Management.Automation { /// /// An PSTraceSource is a representation of a System.Diagnostics.TraceSource instance - /// that is used in the Monad components to produce trace output. + /// that is used in the PowerShell components to produce trace output. /// /// /// It is permitted to subclass /// but there is no established scenario for doing this, nor has it been tested. /// /// @@ -22,6 +21,12 @@ + + + + + + diff --git a/test/hosting/test_HostingBasic.cs b/test/hosting/test_HostingBasic.cs index efd3043d514..1b4a67707e2 100644 --- a/test/hosting/test_HostingBasic.cs +++ b/test/hosting/test_HostingBasic.cs @@ -51,7 +51,7 @@ public static void TestCommandFromCore() foreach (dynamic item in results) { - Assert.Equal(6,item); + Assert.Equal(6, item); } } } @@ -183,6 +183,19 @@ public static void TestConsoleShellScenario() Assert.Equal(42, ret); } + /* Test disabled because CommandLineParser is static and can only be initialized once (above in TestConsoleShellScenario) + /// + /// ConsoleShell cannot start with both InitialSessionState and -ConfigurationFile argument configurations specified. + /// + [Fact] + public static void TestConsoleShellConfigConflictError() + { + var iss = System.Management.Automation.Runspaces.InitialSessionState.CreateDefault2(); + int ret = ConsoleShell.Start(iss, "BannerText", string.Empty, new string[] { @"-ConfigurationFile ""noneSuch""" }); + Assert.Equal(70, ret); // ExitCodeInitFailure. + } + */ + [Fact] public static void TestBuiltInModules() { diff --git a/test/infrastructure/ciModule.Tests.ps1 b/test/infrastructure/ciModule.Tests.ps1 new file mode 100644 index 00000000000..b7320ff49b7 --- /dev/null +++ b/test/infrastructure/ciModule.Tests.ps1 @@ -0,0 +1,246 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# NOTE: This test file tests the Test-MergeConflictMarker function which detects Git merge conflict markers. +# IMPORTANT: Do NOT use here-strings or literal conflict markers (e.g., "<<<<<<<", "=======", ">>>>>>>") +# in this file, as they will trigger conflict marker detection in CI pipelines. +# Instead, use string multiplication (e.g., '<' * 7) to dynamically generate these markers at runtime. + +Describe "Test-MergeConflictMarker" { + BeforeAll { + # Import the module + Import-Module "$PSScriptRoot/../../tools/ci.psm1" -Force + + # Create a temporary test workspace + $script:testWorkspace = Join-Path $TestDrive "workspace" + New-Item -ItemType Directory -Path $script:testWorkspace -Force | Out-Null + + # Create temporary output files + $script:testOutputPath = Join-Path $TestDrive "outputs.txt" + $script:testSummaryPath = Join-Path $TestDrive "summary.md" + } + + AfterEach { + # Clean up test files after each test + if (Test-Path $script:testWorkspace) { + Get-ChildItem $script:testWorkspace -File -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue + } + Remove-Item $script:testOutputPath -Force -ErrorAction SilentlyContinue + Remove-Item $script:testSummaryPath -Force -ErrorAction SilentlyContinue + } + + Context "When no files are provided" { + It "Should handle empty file array gracefully" { + # The function now accepts empty arrays to handle cases like delete-only PRs + $emptyArray = @() + Test-MergeConflictMarker -File $emptyArray -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "files-checked=0" + $outputs | Should -Contain "conflicts-found=0" + + $summary = Get-Content $script:testSummaryPath -Raw + $summary | Should -Match "No Files to Check" + } + } + + Context "When files have no conflicts" { + It "Should pass for clean files" { + $testFile = Join-Path $script:testWorkspace "clean.txt" + "This is a clean file" | Out-File $testFile -Encoding utf8 + + Test-MergeConflictMarker -File @("clean.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "files-checked=1" + $outputs | Should -Contain "conflicts-found=0" + + $summary = Get-Content $script:testSummaryPath -Raw + $summary | Should -Match "No Conflicts Found" + } + } + + Context "When files have conflict markers" { + It "Should detect <<<<<<< marker" { + $testFile = Join-Path $script:testWorkspace "conflict1.txt" + "Some content`n" + ('<' * 7) + " HEAD`nConflicting content" | Out-File $testFile -Encoding utf8 + + { Test-MergeConflictMarker -File @("conflict1.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath } | Should -Throw + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "files-checked=1" + $outputs | Should -Contain "conflicts-found=1" + } + + It "Should detect ======= marker" { + $testFile = Join-Path $script:testWorkspace "conflict2.txt" + "Some content`n" + ('=' * 7) + "`nMore content" | Out-File $testFile -Encoding utf8 + + { Test-MergeConflictMarker -File @("conflict2.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath } | Should -Throw + } + + It "Should detect >>>>>>> marker" { + $testFile = Join-Path $script:testWorkspace "conflict3.txt" + "Some content`n" + ('>' * 7) + " branch-name`nMore content" | Out-File $testFile -Encoding utf8 + + { Test-MergeConflictMarker -File @("conflict3.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath } | Should -Throw + } + + It "Should detect multiple markers in one file" { + $testFile = Join-Path $script:testWorkspace "conflict4.txt" + $content = "Some content`n" + ('<' * 7) + " HEAD`nContent A`n" + ('=' * 7) + "`nContent B`n" + ('>' * 7) + " branch`nMore content" + $content | Out-File $testFile -Encoding utf8 + + { Test-MergeConflictMarker -File @("conflict4.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath } | Should -Throw + + $summary = Get-Content $script:testSummaryPath -Raw + $summary | Should -Match "Conflicts Detected" + $summary | Should -Match "conflict4.txt" + } + + It "Should detect conflicts in multiple files" { + $testFile1 = Join-Path $script:testWorkspace "conflict5.txt" + ('<' * 7) + " HEAD" | Out-File $testFile1 -Encoding utf8 + + $testFile2 = Join-Path $script:testWorkspace "conflict6.txt" + ('=' * 7) | Out-File $testFile2 -Encoding utf8 + + { Test-MergeConflictMarker -File @("conflict5.txt", "conflict6.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath } | Should -Throw + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "files-checked=2" + $outputs | Should -Contain "conflicts-found=2" + } + } + + Context "When markers are not at line start" { + It "Should not detect markers in middle of line" { + $testFile = Join-Path $script:testWorkspace "notconflict.txt" + "This line has <<<<<<< in the middle" | Out-File $testFile -Encoding utf8 + + Test-MergeConflictMarker -File @("notconflict.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "conflicts-found=0" + } + + It "Should not detect markers with wrong number of characters" { + $testFile = Join-Path $script:testWorkspace "wrongcount.txt" + ('<' * 6) + " Only 6`n" + ('<' * 8) + " 8 characters" | Out-File $testFile -Encoding utf8 + + Test-MergeConflictMarker -File @("wrongcount.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "conflicts-found=0" + } + } + + Context "When handling special file scenarios" { + It "Should skip non-existent files" { + Test-MergeConflictMarker -File @("nonexistent.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "files-checked=0" + } + + It "Should handle absolute paths" { + $testFile = Join-Path $script:testWorkspace "absolute.txt" + "Clean content" | Out-File $testFile -Encoding utf8 + + Test-MergeConflictMarker -File @($testFile) -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "conflicts-found=0" + } + + It "Should handle mixed relative and absolute paths" { + $testFile1 = Join-Path $script:testWorkspace "relative.txt" + "Clean" | Out-File $testFile1 -Encoding utf8 + + $testFile2 = Join-Path $script:testWorkspace "absolute.txt" + "Clean" | Out-File $testFile2 -Encoding utf8 + + Test-MergeConflictMarker -File @("relative.txt", $testFile2) -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Should -Contain "files-checked=2" + $outputs | Should -Contain "conflicts-found=0" + } + } + + Context "When summary and output generation" { + It "Should generate proper GitHub Actions outputs format" { + $testFile = Join-Path $script:testWorkspace "test.txt" + "Clean file" | Out-File $testFile -Encoding utf8 + + Test-MergeConflictMarker -File @("test.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath + + $outputs = Get-Content $script:testOutputPath + $outputs | Where-Object {$_ -match "^files-checked=\d+$"} | Should -Not -BeNullOrEmpty + $outputs | Where-Object {$_ -match "^conflicts-found=\d+$"} | Should -Not -BeNullOrEmpty + } + + It "Should generate markdown summary with conflict details" { + $testFile = Join-Path $script:testWorkspace "marked.txt" + $content = "Line 1`n" + ('<' * 7) + " HEAD`nLine 3`n" + ('=' * 7) + "`nLine 5" + $content | Out-File $testFile -Encoding utf8 + + { Test-MergeConflictMarker -File @("marked.txt") -WorkspacePath $script:testWorkspace -OutputPath $script:testOutputPath -SummaryPath $script:testSummaryPath } | Should -Throw + + $summary = Get-Content $script:testSummaryPath -Raw + $summary | Should -Match "# Merge Conflict Marker Check Results" + $summary | Should -Match "marked.txt" + $summary | Should -Match "\| Line \| Marker \|" + } + } +} + +Describe "Install-CIPester" { + BeforeAll { + # Import the module + Import-Module "$PSScriptRoot/../../tools/ci.psm1" -Force + } + + Context "When checking function exists" { + It "Should export Install-CIPester function" { + $function = Get-Command Install-CIPester -ErrorAction SilentlyContinue + $function | Should -Not -BeNullOrEmpty + $function.ModuleName | Should -Be 'ci' + } + + It "Should have expected parameters" { + $function = Get-Command Install-CIPester + $function.Parameters.Keys | Should -Contain 'MinimumVersion' + $function.Parameters.Keys | Should -Contain 'MaximumVersion' + $function.Parameters.Keys | Should -Contain 'Force' + } + + It "Should accept version parameters" { + $function = Get-Command Install-CIPester + $function.Parameters['MinimumVersion'].ParameterType.Name | Should -Be 'String' + $function.Parameters['MaximumVersion'].ParameterType.Name | Should -Be 'String' + $function.Parameters['Force'].ParameterType.Name | Should -Be 'SwitchParameter' + } + } + + Context "When validating real execution" { + # These tests only run in CI where we can safely install/test Pester + + It "Should successfully run without errors when Pester exists" { + if (!$env:CI) { + Set-ItResult -Skipped -Because "Test requires CI environment to safely install Pester" + } + + { Install-CIPester -ErrorAction Stop } | Should -Not -Throw + } + + It "Should accept custom version parameters" { + if (!$env:CI) { + Set-ItResult -Skipped -Because "Test requires CI environment to safely install Pester" + } + + { Install-CIPester -MinimumVersion '4.0.0' -MaximumVersion '5.99.99' -ErrorAction Stop } | Should -Not -Throw + } + } +} + diff --git a/test/packaging/linux/package-validation.tests.ps1 b/test/packaging/linux/package-validation.tests.ps1 new file mode 100644 index 00000000000..3b961120f2f --- /dev/null +++ b/test/packaging/linux/package-validation.tests.ps1 @@ -0,0 +1,118 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Linux Package Name Validation" { + BeforeAll { + # Determine artifacts directory (GitHub Actions or Azure DevOps) + $artifactsDir = if ($env:GITHUB_ACTIONS -eq 'true') { + "$env:GITHUB_WORKSPACE/../packages" + } else { + $env:SYSTEM_ARTIFACTSDIRECTORY + } + + if (-not $artifactsDir) { + throw "Artifacts directory not found. GITHUB_WORKSPACE or SYSTEM_ARTIFACTSDIRECTORY must be set." + } + + Write-Verbose "Artifacts directory: $artifactsDir" -Verbose + } + + Context "RPM Package Names" { + It "Should have valid RPM package names" { + $rpmPackages = Get-ChildItem -Path $artifactsDir -Recurse -Filter *.rpm -ErrorAction SilentlyContinue + + $rpmPackages.Count | Should -BeGreaterThan 0 -Because "At least one RPM package should exist in the artifacts directory" + + $invalidPackages = @() + # Regex pattern for valid RPM package names. + # Breakdown: + # ^powershell\- : Starts with 'powershell-' + # (preview-|lts-)? : Optionally 'preview-' or 'lts-' + # \d+\.\d+\.\d+ : Version number (e.g., 7.6.0) + # (_[a-z]*\.\d+)? : Optional underscore, letters, dot, and digits (e.g., _alpha.1) + # -1\. : Literal '-1.' + # (preview\.\d+\.)? : Optional 'preview.' and digits, followed by a dot + # (rh|cm)\. : Either 'rh.' or 'cm.' + # (x86_64|aarch64)\.rpm$ : Architecture and file extension + $rpmPackageNamePattern = 'powershell\-(preview-|lts-)?\d+\.\d+\.\d+(_[a-z]*\.\d+)?-1\.(preview\.\d+\.)?(rh|cm)\.(x86_64|aarch64)\.rpm' + + foreach ($package in $rpmPackages) { + if ($package.Name -notmatch $rpmPackageNamePattern) { + $invalidPackages += "$($package.Name) is not a valid RPM package name" + Write-Warning "$($package.Name) is not a valid RPM package name" + } + } + + if ($invalidPackages.Count -gt 0) { + throw ($invalidPackages | Out-String) + } + } + } + + Context "DEB Package Names" { + It "Should have valid DEB package names" { + $debPackages = Get-ChildItem -Path $artifactsDir -Recurse -Filter *.deb -ErrorAction SilentlyContinue + + $debPackages.Count | Should -BeGreaterThan 0 -Because "At least one DEB package should exist in the artifacts directory" + + $invalidPackages = @() + # Regex pattern for valid DEB package names. + # Valid examples: + # - powershell-preview_7.6.0-preview.6-1.deb_amd64.deb + # - powershell-lts_7.4.13-1.deb_amd64.deb + # - powershell_7.4.13-1.deb_amd64.deb + # - powershell_7.6.0-1.deb_arm64.deb + # Breakdown: + # ^powershell : Starts with 'powershell' + # (-preview|-lts)? : Optionally '-preview' or '-lts' + # _\d+\.\d+\.\d+ : Underscore followed by version number (e.g., _7.6.0) + # (-[a-z]+\.\d+)? : Optional dash, letters, dot, and digits (e.g., -preview.6) + # -1 : Literal '-1' + # \.deb_ : Literal '.deb_' + # (amd64|arm64) : Architecture + # \.deb$ : File extension + $debPackageNamePattern = '^powershell(-preview|-lts)?_\d+\.\d+\.\d+(-[a-z]+\.\d+)?-1\.deb_(amd64|arm64)\.deb$' + + foreach ($package in $debPackages) { + if ($package.Name -notmatch $debPackageNamePattern) { + $invalidPackages += "$($package.Name) is not a valid DEB package name" + Write-Warning "$($package.Name) is not a valid DEB package name" + } + } + + if ($invalidPackages.Count -gt 0) { + throw ($invalidPackages | Out-String) + } + } + } + + Context "Tar.Gz Package Names" { + It "Should have valid tar.gz package names" { + $tarPackages = Get-ChildItem -Path $artifactsDir -Recurse -Filter *.tar.gz -ErrorAction SilentlyContinue + + $tarPackages.Count | Should -BeGreaterThan 0 -Because "At least one tar.gz package should exist in the artifacts directory" + + $invalidPackages = @() + foreach ($package in $tarPackages) { + # Pattern matches: powershell-7.6.0-preview.6-linux-x64.tar.gz or powershell-7.6.0-linux-x64.tar.gz + # Also matches various runtime configurations + if ($package.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)') { + $invalidPackages += "$($package.Name) is not a valid tar.gz package name" + Write-Warning "$($package.Name) is not a valid tar.gz package name" + } + } + + if ($invalidPackages.Count -gt 0) { + throw ($invalidPackages | Out-String) + } + } + } + + Context "Package Existence" { + It "Should find at least one package in artifacts directory" { + $allPackages = Get-ChildItem -Path $artifactsDir -Recurse -Include *.rpm, *.tar.gz, *.deb -ErrorAction SilentlyContinue + + $allPackages.Count | Should -BeGreaterThan 0 -Because "At least one package should exist in the artifacts directory" + } + } +} diff --git a/test/packaging/macos/package-validation.tests.ps1 b/test/packaging/macos/package-validation.tests.ps1 new file mode 100644 index 00000000000..945ffea6f7a --- /dev/null +++ b/test/packaging/macos/package-validation.tests.ps1 @@ -0,0 +1,186 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Verify macOS Package" { + BeforeAll { + Write-Verbose "In Describe BeforeAll" -Verbose + Import-Module $PSScriptRoot/../../../build.psm1 + + # Find the macOS package + $packagePath = $env:PACKAGE_FOLDER + if (-not $packagePath) { + $packagePath = Get-Location + } + + Write-Verbose "Looking for package in: $packagePath" -Verbose + $package = Get-ChildItem -Path $packagePath -Filter "*.pkg" -ErrorAction SilentlyContinue | Select-Object -First 1 + + if (-not $package) { + Write-Warning "No .pkg file found in $packagePath" + } else { + Write-Verbose "Found package: $($package.FullName)" -Verbose + } + + # Set up test directories + $script:package = $package + $script:expandDir = $null + $script:payloadDir = $null + $script:extractedFiles = @() + + if ($package) { + # Use TestDrive for temporary directories - pkgutil will create the expand directory + $script:expandDir = Join-Path "TestDrive:" -ChildPath "package-contents-test" + $expandDirResolved = (Resolve-Path "TestDrive:").ProviderPath + $script:expandDir = Join-Path $expandDirResolved -ChildPath "package-contents-test" + + Write-Verbose "Expanding package to: $($script:expandDir)" -Verbose + # pkgutil will create the directory itself, so don't pre-create it + Start-NativeExecution { + pkgutil --expand $package.FullName $script:expandDir + } + + # Extract the payload to verify files + $script:payloadDir = Join-Path "TestDrive:" -ChildPath "package-payload-test" + $payloadDirResolved = (Resolve-Path "TestDrive:").ProviderPath + $script:payloadDir = Join-Path $payloadDirResolved -ChildPath "package-payload-test" + + # Create payload directory since cpio needs it + if (-not (Test-Path $script:payloadDir)) { + $null = New-Item -ItemType Directory -Path $script:payloadDir -Force + } + + $componentPkg = Get-ChildItem -Path $script:expandDir -Filter "*.pkg" -Recurse | Select-Object -First 1 + if ($componentPkg) { + Write-Verbose "Extracting payload from: $($componentPkg.FullName)" -Verbose + Push-Location $script:payloadDir + try { + $payloadFile = Join-Path $componentPkg.FullName "Payload" + Get-Content -Path $payloadFile -Raw -AsByteStream | & cpio -i 2>&1 | Out-Null + } finally { + Pop-Location + } + } + + # Get all extracted files for verification + $script:extractedFiles = Get-ChildItem -Path $script:payloadDir -Recurse -ErrorAction SilentlyContinue + Write-Verbose "Extracted $($script:extractedFiles.Count) files" -Verbose + } + } + + AfterAll { + # TestDrive automatically cleans up, but we can ensure cleanup happens + # No manual cleanup needed as TestDrive handles it + } + + Context "Package existence and structure" { + It "Package file should exist" { + $script:package | Should -Not -BeNullOrEmpty -Because "A .pkg file should be created" + $script:package.Extension | Should -Be ".pkg" + } + + It "Package name should follow correct naming convention" { + $script:package | Should -Not -BeNullOrEmpty + + # Regex pattern for valid macOS PKG package names. + # This pattern matches the validation used in release-validate-packagenames.yml + # Valid examples: + # - powershell-7.4.13-osx-x64.pkg (Stable release) + # - powershell-7.6.0-preview.6-osx-x64.pkg (Preview version string) + # - powershell-7.4.13-rebuild.5-osx-arm64.pkg (Rebuild version) + # - powershell-lts-7.4.13-osx-arm64.pkg (LTS package) + $pkgPackageNamePattern = '^powershell-(lts-)?\d+\.\d+\.\d+\-([a-z]*.\d+\-)?osx\-(x64|arm64)\.pkg$' + + $script:package.Name | Should -Match $pkgPackageNamePattern -Because "Package name should follow the standard naming convention" + } + + It "Package name should NOT use x86_64 with underscores" { + $script:package | Should -Not -BeNullOrEmpty + + $script:package.Name | Should -Not -Match 'x86_64' -Because "Package should use 'x64' not 'x86_64' (with underscores) for compatibility" + } + + It "Package should expand successfully" { + $script:expandDir | Should -Exist + Get-ChildItem -Path $script:expandDir | Should -Not -BeNullOrEmpty + } + + It "Package should have a component package" { + $componentPkg = Get-ChildItem -Path $script:expandDir -Filter "*.pkg" -Recurse -ErrorAction SilentlyContinue + $componentPkg | Should -Not -BeNullOrEmpty -Because "Package should contain a component.pkg" + } + + It "Payload should extract successfully" { + $script:payloadDir | Should -Exist + $script:extractedFiles | Should -Not -BeNullOrEmpty -Because "Package payload should contain files" + } + } + + Context "Required files in package" { + BeforeAll { + $expectedFilePatterns = @{ + "PowerShell executable" = "usr/local/microsoft/powershell/*/pwsh" + "PowerShell symlink in /usr/local/bin" = "usr/local/bin/pwsh*" + "Man page" = "usr/local/share/man/man1/pwsh*.gz" + "Launcher application plist" = "Applications/PowerShell*.app/Contents/Info.plist" + } + + $testCases = @() + foreach ($key in $expectedFilePatterns.Keys) { + $testCases += @{ + Description = $key + Pattern = $expectedFilePatterns[$key] + } + } + + $script:testCases = $testCases + } + + It "Should contain " -TestCases $script:testCases { + param($Description, $Pattern) + + $found = $script:extractedFiles | Where-Object { $_.FullName -like "*$Pattern*" } + $found | Should -Not -BeNullOrEmpty -Because "$Description should exist in the package at path matching '$Pattern'" + } + } + + Context "PowerShell binary verification" { + It "PowerShell executable should be executable" { + $pwshBinary = $script:extractedFiles | Where-Object { $_.FullName -like "*/pwsh" -and $_.FullName -like "*/microsoft/powershell/*" } + $pwshBinary | Should -Not -BeNullOrEmpty + + # Check if file has executable permissions (on Unix-like systems) + if ($IsLinux -or $IsMacOS) { + $permissions = (Get-Item $pwshBinary[0].FullName).UnixFileMode + # Executable bit should be set + $permissions.ToString() | Should -Match 'x' -Because "pwsh binary should have execute permissions" + } + } + } + + Context "Launcher application" { + It "Launcher app should have proper bundle structure" { + $plistFile = $script:extractedFiles | Where-Object { $_.FullName -like "*PowerShell*.app/Contents/Info.plist" } + $plistFile | Should -Not -BeNullOrEmpty + + # Verify the bundle has required components + $appPath = Split-Path (Split-Path $plistFile[0].FullName -Parent) -Parent + $macOSDir = Join-Path $appPath "Contents/MacOS" + $resourcesDir = Join-Path $appPath "Contents/Resources" + + Test-Path $macOSDir | Should -Be $true -Because "App bundle should have Contents/MacOS directory" + Test-Path $resourcesDir | Should -Be $true -Because "App bundle should have Contents/Resources directory" + } + + It "Launcher script should exist and be executable" { + $launcherScript = $script:extractedFiles | Where-Object { + $_.FullName -like "*PowerShell*.app/Contents/MacOS/PowerShell.sh" + } + $launcherScript | Should -Not -BeNullOrEmpty -Because "Launcher script should exist" + + if ($IsLinux -or $IsMacOS) { + $permissions = (Get-Item $launcherScript[0].FullName).UnixFileMode + $permissions.ToString() | Should -Match 'x' -Because "Launcher script should have execute permissions" + } + } + } +} diff --git a/test/packaging/packaging.tests.ps1 b/test/packaging/packaging.tests.ps1 new file mode 100644 index 00000000000..a7d322205bc --- /dev/null +++ b/test/packaging/packaging.tests.ps1 @@ -0,0 +1,64 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Packaging Module Functions" { + BeforeAll { + Import-Module $PSScriptRoot/../../build.psm1 -Force + Import-Module $PSScriptRoot/../../tools/packaging/packaging.psm1 -Force + } + + Context "Test-IsPreview function" { + It "Should return True for preview versions" { + Test-IsPreview -Version "7.6.0-preview.6" | Should -Be $true + Test-IsPreview -Version "7.5.0-rc.1" | Should -Be $true + } + + It "Should return False for stable versions" { + Test-IsPreview -Version "7.6.0" | Should -Be $false + Test-IsPreview -Version "7.5.0" | Should -Be $false + } + + It "Should return False for LTS builds regardless of version string" { + Test-IsPreview -Version "7.6.0-preview.6" -IsLTS | Should -Be $false + Test-IsPreview -Version "7.5.0" -IsLTS | Should -Be $false + } + } + + Context "Get-MacOSPackageIdentifierInfo function (New-MacOSPackage logic)" { + It "Should detect preview builds and return preview identifier" { + $result = Get-MacOSPackageIdentifierInfo -Version "7.6.0-preview.6" -LTS:$false + + $result.IsPreview | Should -Be $true + $result.PackageIdentifier | Should -Be "com.microsoft.powershell-preview" + } + + It "Should detect stable builds and return stable identifier" { + $result = Get-MacOSPackageIdentifierInfo -Version "7.6.0" -LTS:$false + + $result.IsPreview | Should -Be $false + $result.PackageIdentifier | Should -Be "com.microsoft.powershell" + } + + It "Should treat LTS builds as stable even with preview version string" { + $result = Get-MacOSPackageIdentifierInfo -Version "7.4.0-preview.1" -LTS:$true + + $result.IsPreview | Should -Be $false + $result.PackageIdentifier | Should -Be "com.microsoft.powershell" + } + + It "Should NOT use package name for preview detection (bug fix verification) - " -TestCases @( + @{ Version = "7.6.0-preview.6"; Name = "Preview" } + @{ Version = "7.6.0-rc.1"; Name = "RC" } + ) { + # This test verifies the fix for issue #26673 + # The bug was using ($Name -like '*-preview') which always returned false + # because preview builds use Name="powershell" not "powershell-preview" + param($Version) + + # The CORRECT logic (the fix): uses version string + $result = Get-MacOSPackageIdentifierInfo -Version $Version -LTS:$false + $result.IsPreview | Should -Be $true -Because "Version string correctly identifies preview" + $result.PackageIdentifier | Should -Be "com.microsoft.powershell-preview" + } + } +} diff --git a/test/packaging/windows/msi.tests.ps1 b/test/packaging/windows/msi.tests.ps1 index 19df125691b..14dc40a6ff2 100644 --- a/test/packaging/windows/msi.tests.ps1 +++ b/test/packaging/windows/msi.tests.ps1 @@ -3,6 +3,7 @@ Describe -Name "Windows MSI" -Fixture { BeforeAll { + Set-StrictMode -Off function Test-Elevated { [CmdletBinding()] [OutputType([bool])] @@ -14,6 +15,62 @@ Describe -Name "Windows MSI" -Fixture { return (([Security.Principal.WindowsIdentity]::GetCurrent()).Groups -contains "S-1-5-32-544") } + function Test-IsMuEnabled { + $sm = (New-Object -ComObject Microsoft.Update.ServiceManager) + $mu = $sm.Services | Where-Object { $_.ServiceId -eq '7971f918-a847-4430-9279-4a52d1efe18d' } + if ($mu) { + return $true + } + return $false + } + + function Invoke-TestAndUploadLogOnFailure { + param ( + [scriptblock] $Test + ) + + try { + & $Test + } + catch { + Send-VstsLogFile -Path $msiLog + throw + } + } + + function Get-UseMU { + $useMu = $null + $key = 'HKLM:\SOFTWARE\Microsoft\PowerShellCore\' + if ($runtime -like '*x86*') { + $key = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\PowerShellCore\' + } + + try { + $useMu = Get-ItemPropertyValue -Path $key -Name UseMU -ErrorAction SilentlyContinue + } catch {} + + if (!$useMu) { + $useMu = 0 + } + + return $useMu + } + + function Set-UseMU { + param( + [int] + $Value + ) + $key = 'HKLM:\SOFTWARE\Microsoft\PowerShellCore\' + if ($runtime -like '*x86*') { + $key = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\PowerShellCore\' + } + + Set-ItemProperty -Path $key -Name UseMU -Value $Value -Type DWord + + return $useMu + } + function Invoke-Msiexec { param( [Parameter(ParameterSetName = 'Install', Mandatory)] @@ -45,6 +102,7 @@ Describe -Name "Windows MSI" -Fixture { } $argumentList = "$switch $MsiPath /quiet /l*vx $msiLog $additionalOptions" + Write-Verbose -Message "running msiexec $argumentList" $msiExecProcess = Start-Process msiexec.exe -Wait -ArgumentList $argumentList -NoNewWindow -PassThru if ($msiExecProcess.ExitCode -ne 0) { $exitCode = $msiExecProcess.ExitCode @@ -55,6 +113,28 @@ Describe -Name "Windows MSI" -Fixture { $msiX64Path = $env:PsMsiX64Path $channel = $env:PSMsiChannel $runtime = $env:PSMsiRuntime + $muEnabled = Test-IsMuEnabled + + if ($runtime -like '*x86*') { + $propertiesRegKeyParent = "HKLM:\SOFTWARE\Wow6432Node\Microsoft\PowerShellCore" + } else { + $propertiesRegKeyParent = "HKLM:\SOFTWARE\Microsoft\PowerShellCore" + } + + if ($channel -eq "preview") { + $propertiesRegKeyName = "PreviewInstallerProperties" + } else { + $propertiesRegKeyName = "InstallerProperties" + } + + # Rename the registry key that contains the saved installer + # properties so that the tests don't overwrite them. + $propertiesRegKeyPath = Join-Path -Path $propertiesRegKeyParent -ChildPath $propertiesRegKeyName + $propertiesBackupRegKeyName = "BackupInstallerProperties" + $propertiesBackupRegKeyPath = Join-Path -Path $propertiesRegKeyParent -ChildPath $propertiesBackupRegKeyName + if (Test-Path -Path $propertiesRegKeyPath) { + Rename-Item -Path $propertiesRegKeyPath -NewName $propertiesBackupRegKeyName + } # Get any existing powershell in the path $beforePath = @(([System.Environment]::GetEnvironmentVariable('PATH', 'MACHINE')) -split ';' | @@ -71,32 +151,53 @@ Describe -Name "Windows MSI" -Fixture { } $uploadedLog = $false } + + AfterAll { + Set-StrictMode -Version 3.0 + + # Restore the original saved installer properties registry key. + Remove-Item -Path $propertiesRegKeyPath -ErrorAction SilentlyContinue + if (Test-Path -Path $propertiesBackupRegKeyPath) { + Rename-Item -Path $propertiesBackupRegKeyPath -NewName $propertiesRegKeyName + } + } + BeforeEach { $error.Clear() - } - AfterEach { - if ($error.Count -ne 0 -and !$uploadedLog) { - Copy-Item -Path $msiLog -Destination $env:temp -Force - Write-Verbose "MSI log is at $env:temp\msilog.txt" -Verbose - $uploadedLog = $true - } + Remove-Item -Path $propertiesRegKeyPath -ErrorAction SilentlyContinue } Context "Upgrade code" { BeforeAll { Write-Verbose "cr-$channel-$runtime" -Verbose + $pwshPath = Join-Path $env:ProgramFiles -ChildPath "PowerShell" + $pwshx86Path = Join-Path ${env:ProgramFiles(x86)} -ChildPath "PowerShell" + $regKeyPath = "HKLM:\SOFTWARE\Microsoft\PowerShellCore\InstalledVersions" + switch ("$channel-$runtime") { "preview-win7-x64" { + $versionPath = Join-Path -Path $pwshPath -ChildPath '7-preview' + $revisionRange = 0, 99 $msiUpgradeCode = '39243d76-adaf-42b1-94fb-16ecf83237c8' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } "stable-win7-x64" { + $versionPath = Join-Path -Path $pwshPath -ChildPath '7' + $revisionRange = 500, 500 $msiUpgradeCode = '31ab5147-9a97-4452-8443-d9709f0516e1' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } "preview-win7-x86" { + $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7-preview' + $revisionRange = 0, 99 $msiUpgradeCode = '86abcfbd-1ccc-4a88-b8b2-0facfde29094' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } "stable-win7-x86" { + $versionPath = Join-Path -Path $pwshx86Path -ChildPath '7' + $revisionRange = 500, 500 $msiUpgradeCode = '1d00683b-0f84-4db8-a64f-2f98ad42fe06' + $regKeyPath = Join-Path $regKeyPath -ChildPath $msiUpgradeCode } default { throw "'$_' not a valid channel runtime combination" @@ -120,6 +221,35 @@ Describe -Name "Windows MSI" -Fixture { $result.Count | Should -Be 1 -Because "Query should return 1 result if Upgrade code is for $runtime $channel" } + It "Revision should be in correct range" -Skip:(!(Test-Elevated)) { + $pwshDllPath = Join-Path -Path $versionPath -ChildPath "pwsh.dll" + [version] $version = (Get-ChildItem $pwshDllPath).VersionInfo.FileVersion + Write-Verbose "pwsh.dll version: $version" -Verbose + $version.Revision | Should -BeGreaterOrEqual $revisionRange[0] -Because "$channel revision should between $($revisionRange[0]) and $($revisionRange[1])" + $version.Revision | Should -BeLessOrEqual $revisionRange[1] -Because "$channel revision should between $($revisionRange[0]) and $($revisionRange[1])" + } + + It 'MSI should add ProductCode in registry' -Skip:(!(Test-Elevated)) { + + $productCode = if ($msiUpgradeCode -eq '39243d76-adaf-42b1-94fb-16ecf83237c8' -or + $msiUpgradeCode -eq '31ab5147-9a97-4452-8443-d9709f0516e1') { + # x64 + $regKeyPath | Should -Exist + Get-ItemPropertyValue -Path $regKeyPath -Name 'ProductCode' + } elseif ($msiUpgradeCode -eq '86abcfbd-1ccc-4a88-b8b2-0facfde29094' -or + $msiUpgradeCode -eq '1d00683b-0f84-4db8-a64f-2f98ad42fe06') { + # x86 - need to open the 32bit reghive + $wow32RegKey = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::LocalMachine, [Microsoft.Win32.RegistryView]::Registry32) + $subKey = $wow32RegKey.OpenSubKey("Software\Microsoft\PowerShellCore\InstalledVersions\$msiUpgradeCode") + $subKey.GetValue("ProductCode") + } + + $productCode | Should -Not -BeNullOrEmpty + $productCodeGuid = [Guid]$productCode + $productCodeGuid | Should -BeOfType "Guid" + $productCodeGuid.Guid | Should -Not -Be $msiUpgradeCode + } + It "MSI should uninstall without error" -Skip:(!(Test-Elevated)) { { Invoke-MsiExec -Uninstall -MsiPath $msiX64Path @@ -128,9 +258,18 @@ Describe -Name "Windows MSI" -Fixture { } Context "Add Path disabled" { + BeforeAll { + Set-UseMU -Value 0 + } + + It "UseMU should be 0 before install" -Skip:(!(Test-Elevated)) { + $useMu = Get-UseMU + $useMu | Should -Be 0 + } + It "MSI should install without error" -Skip:(!(Test-Elevated)) { { - Invoke-MsiExec -Install -MsiPath $msiX64Path -Properties @{ADD_PATH = 0} + Invoke-MsiExec -Install -MsiPath $msiX64Path -Properties @{ADD_PATH = 0; USE_MU = 1; ENABLE_MU = 1} } | Should -Not -Throw } @@ -141,6 +280,43 @@ Describe -Name "Windows MSI" -Fixture { $psPath | Should -BeNullOrEmpty } + It "UseMU should be 1" -Skip:(!(Test-Elevated)) { + Invoke-TestAndUploadLogOnFailure -Test { + $useMu = Get-UseMU + $useMu | Should -Be 1 + } + } + + It "MSI should uninstall without error" -Skip:(!(Test-Elevated)) { + { + Invoke-MsiExec -Uninstall -MsiPath $msiX64Path + } | Should -Not -Throw + } + } + + Context "USE_MU disabled" { + BeforeAll { + Set-UseMU -Value 0 + } + + It "UseMU should be 0 before install" -Skip:(!(Test-Elevated)) { + $useMu = Get-UseMU + $useMu | Should -Be 0 + } + + It "MSI should install without error" -Skip:(!(Test-Elevated)) { + { + Invoke-MsiExec -Install -MsiPath $msiX64Path -Properties @{USE_MU = 0} + } | Should -Not -Throw + } + + It "UseMU should be 0" -Skip:(!(Test-Elevated)) { + Invoke-TestAndUploadLogOnFailure -Test { + $useMu = Get-UseMU + $useMu | Should -Be 0 + } + } + It "MSI should uninstall without error" -Skip:(!(Test-Elevated)) { { Invoke-MsiExec -Uninstall -MsiPath $msiX64Path @@ -179,5 +355,43 @@ Describe -Name "Windows MSI" -Fixture { Invoke-MsiExec -Uninstall -MsiPath $msiX64Path } | Should -Not -Throw } + + Context "Disable Telemetry" { + It "MSI should set POWERSHELL_TELEMETRY_OPTOUT env variable when MSI property DISABLE_TELEMETRY is set to 1" -Skip:(!(Test-Elevated)) { + try { + $originalValue = [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', '0', [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Install -MsiPath $msiX64Path -Properties @{DISABLE_TELEMETRY = 1 } + } | Should -Not -Throw + [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) | + Should -Be 1 + } + finally { + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', $originalValue, [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Uninstall -MsiPath $msiX64Path + } | Should -Not -Throw + } + } + + It "MSI should not change POWERSHELL_TELEMETRY_OPTOUT env variable when MSI property DISABLE_TELEMETRY not set" -Skip:(!(Test-Elevated)) { + try { + $originalValue = [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', 'untouched', [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Install -MsiPath $msiX64Path + } | Should -Not -Throw + [System.Environment]::GetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', [System.EnvironmentVariableTarget]::Machine) | + Should -Be 'untouched' + } + finally { + [System.Environment]::SetEnvironmentVariable('POWERSHELL_TELEMETRY_OPTOUT', $originalValue, [System.EnvironmentVariableTarget]::Machine) + { + Invoke-MsiExec -Uninstall -MsiPath $msiX64Path + } | Should -Not -Throw + } + } + } } } diff --git a/test/perf/benchmarks/Categories.cs b/test/perf/benchmarks/Categories.cs new file mode 100644 index 00000000000..09f71064930 --- /dev/null +++ b/test/perf/benchmarks/Categories.cs @@ -0,0 +1,28 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +namespace MicroBenchmarks +{ + public static class Categories + { + /// + /// Benchmarks belonging to this category are executed for CI jobs. + /// + public const string Components = "Components"; + + /// + /// Benchmarks belonging to this category are executed for CI jobs. + /// + public const string Engine = "Engine"; + + /// + /// Benchmarks belonging to this category are targeting internal APIs. + /// + public const string Internal = "Internal"; + + /// + /// Benchmarks belonging to this category are targeting public APIs. + /// + public const string Public = "Public"; + } +} diff --git a/test/perf/benchmarks/Engine.Compiler.cs b/test/perf/benchmarks/Engine.Compiler.cs new file mode 100644 index 00000000000..68385847f5b --- /dev/null +++ b/test/perf/benchmarks/Engine.Compiler.cs @@ -0,0 +1,78 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +#if NET6_0 + +using System; +using System.Collections.Generic; +using System.IO; +using System.Management.Automation; +using System.Management.Automation.Language; + +using BenchmarkDotNet.Attributes; +using MicroBenchmarks; + +namespace Engine +{ + [BenchmarkCategory(Categories.Engine, Categories.Internal)] + public class Compiler + { + private static readonly Dictionary s_scriptBlocksDict; + private static readonly List s_functionNames; + private ScriptBlockAst _currentAst; + + static Compiler() + { + string pattern = string.Format("{0}test{0}perf{0}benchmarks", Path.DirectorySeparatorChar); + string location = typeof(Compiler).Assembly.Location; + string testFilePath = null; + + int start = location.IndexOf(pattern, StringComparison.Ordinal); + if (start > 0) + { + testFilePath = Path.Join(location.AsSpan(0, start + pattern.Length), "assets", "compiler.test.ps1"); + } + + var topScriptBlockAst = Parser.ParseFile(testFilePath, tokens: out _, errors: out _); + var allFunctions = topScriptBlockAst.FindAll(ast => ast is FunctionDefinitionAst, searchNestedScriptBlocks: false); + + s_scriptBlocksDict = new Dictionary(capacity: 16); + s_functionNames = new List(capacity: 16); + + foreach (FunctionDefinitionAst function in allFunctions) + { + s_functionNames.Add(function.Name); + s_scriptBlocksDict.Add(function.Name, function.Body); + } + } + + [ParamsSource(nameof(FunctionName))] + public string FunctionsToCompile { get; set; } + + public IEnumerable FunctionName() => s_functionNames; + + [GlobalSetup(Target = nameof(CompileFunction))] + public void GlobalSetup() + { + _currentAst = s_scriptBlocksDict[FunctionsToCompile]; + + // Run it once to get the C# code jitted. + // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly + // believe that there is no need to run many ops in each iteration. However, the subsequent runs + // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings + // to our benchmarks and make the benchmark results not reliable. + // Calling this method once in 'GlobalSetup' is a workaround. + // See https://github.com/dotnet/BenchmarkDotNet/issues/837#issuecomment-828600157 + CompileFunction(); + } + + [Benchmark] + public bool CompileFunction() + { + var compiledData = new CompiledScriptBlockData(_currentAst, isFilter: false); + return compiledData.Compile(true); + } + } +} + +#endif diff --git a/test/perf/benchmarks/Engine.Parser.cs b/test/perf/benchmarks/Engine.Parser.cs new file mode 100644 index 00000000000..10538e3201a --- /dev/null +++ b/test/perf/benchmarks/Engine.Parser.cs @@ -0,0 +1,23 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Management.Automation.Language; +using BenchmarkDotNet.Attributes; +using MicroBenchmarks; + +namespace Engine +{ + [BenchmarkCategory(Categories.Engine, Categories.Public)] + public class Parsing + { + [Benchmark] + public Ast UsingStatement() + { + const string Script = @" + using module moduleA + using Assembly assemblyA + using namespace System.IO"; + return Parser.ParseInput(Script, out _, out _); + } + } +} diff --git a/test/perf/benchmarks/Engine.ScriptBlock.cs b/test/perf/benchmarks/Engine.ScriptBlock.cs new file mode 100644 index 00000000000..dfd7beb865f --- /dev/null +++ b/test/perf/benchmarks/Engine.ScriptBlock.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Management.Automation; +using System.Management.Automation.Runspaces; +using System.Runtime.InteropServices; +using BenchmarkDotNet.Attributes; +using MicroBenchmarks; + +namespace Engine +{ + [BenchmarkCategory(Categories.Engine, Categories.Public)] + public class Scripting + { + private Runspace runspace; + private ScriptBlock scriptBlock; + + private void SetupRunspace() + { + // Unless you want to run commands from any built-in modules, using 'CreateDefault2' is enough. + runspace = RunspaceFactory.CreateRunspace(InitialSessionState.CreateDefault2()); + runspace.Open(); + Runspace.DefaultRunspace = runspace; + } + + #region Invoke-Method + + [ParamsSource(nameof(ValuesForScript))] + public string InvokeMethodScript { get; set; } + + public IEnumerable ValuesForScript() + { + yield return @"'String'.GetType()"; + yield return @"[System.IO.Path]::HasExtension('')"; + + // Test on COM method invocation. + if (Platform.IsWindows) + { + yield return @"$sh=New-Object -ComObject Shell.Application; $sh.Namespace('c:\')"; + yield return @"$fs=New-Object -ComObject scripting.filesystemobject; $fs.Drives"; + } + } + + [GlobalSetup(Target = nameof(InvokeMethod))] + public void GlobalSetup() + { + SetupRunspace(); + scriptBlock = ScriptBlock.Create(InvokeMethodScript); + + // Run it once to get the C# code jitted and the script compiled. + // The first call to this takes relatively too long, which makes the BDN's heuristic incorrectly + // believe that there is no need to run many ops in each iteration. However, the subsequent runs + // of this method is much faster than the first run, and this causes 'MinIterationTime' warnings + // to our benchmarks and make the benchmark results not reliable. + // Calling this method once in 'GlobalSetup' is a workaround. + // See https://github.com/dotnet/BenchmarkDotNet/issues/837#issuecomment-828600157 + scriptBlock.Invoke(); + } + + [Benchmark] + public Collection InvokeMethod() + { + return scriptBlock.Invoke(); + } + + #endregion + + [GlobalCleanup] + public void GlobalCleanup() + { + runspace.Dispose(); + Runspace.DefaultRunspace = null; + } + } +} diff --git a/test/perf/benchmarks/Program.cs b/test/perf/benchmarks/Program.cs new file mode 100644 index 00000000000..53f9a3ce95b --- /dev/null +++ b/test/perf/benchmarks/Program.cs @@ -0,0 +1,56 @@ +// Copyright (c) Microsoft Corporation. +// Licensed under the MIT License. + +using System; +using System.Collections.Generic; +using System.Collections.Immutable; +using System.IO; +using BenchmarkDotNet.Running; +using BenchmarkDotNet.Extensions; + +namespace MicroBenchmarks +{ + public sealed class Program + { + public static int Main(string[] args) + { + var argsList = new List(args); + int? partitionCount; + int? partitionIndex; + List exclusionFilterValue; + List categoryExclusionFilterValue; + bool getDiffableDisasm; + + // Parse and remove any additional parameters that we need that aren't part of BDN (BenchmarkDotnet) + try + { + CommandLineOptions.ParseAndRemoveIntParameter(argsList, "--partition-count", out partitionCount); + CommandLineOptions.ParseAndRemoveIntParameter(argsList, "--partition-index", out partitionIndex); + CommandLineOptions.ParseAndRemoveStringsParameter(argsList, "--exclusion-filter", out exclusionFilterValue); + CommandLineOptions.ParseAndRemoveStringsParameter(argsList, "--category-exclusion-filter", out categoryExclusionFilterValue); + CommandLineOptions.ParseAndRemoveBooleanParameter(argsList, "--disasm-diff", out getDiffableDisasm); + + CommandLineOptions.ValidatePartitionParameters(partitionCount, partitionIndex); + } + catch (ArgumentException e) + { + Console.WriteLine("ArgumentException: {0}", e.Message); + return 1; + } + + return BenchmarkSwitcher + .FromAssembly(typeof(Program).Assembly) + .Run( + argsList.ToArray(), + RecommendedConfig.Create( + artifactsPath: new DirectoryInfo(Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "BenchmarkDotNet.Artifacts")), + mandatoryCategories: ImmutableHashSet.Create(Categories.Components, Categories.Engine), + partitionCount: partitionCount, + partitionIndex: partitionIndex, + exclusionFilterValue: exclusionFilterValue, + categoryExclusionFilterValue: categoryExclusionFilterValue, + getDiffableDisasm: getDiffableDisasm)) + .ToExitCode(); + } + } +} diff --git a/test/perf/benchmarks/README.md b/test/perf/benchmarks/README.md new file mode 100644 index 00000000000..cf2b96c184c --- /dev/null +++ b/test/perf/benchmarks/README.md @@ -0,0 +1,92 @@ +## Micro Benchmarks + +This folder contains micro benchmarks that test the performance of PowerShell Engine. + +### Requirement + +1. A good suite of benchmarks + Something that measures only the thing that we are interested in and _produces accurate, stable and repeatable results_. +2. A set of machine with the same configurations. +3. Automation for regression detection. + +### Design Decision + +1. This project is internal visible to `System.Management.Automation`. + We want to be able to target some internal APIs to get measurements on specific scoped scenarios, + such as measuring the time to compile AST to a delegate by the compiler. +2. This project makes `ProjectReference` to other PowerShell assemblies. + This makes it easy to run benchmarks with the changes made in the codebase. + To run benchmarks with a specific version of PowerShell, + just replace the `ProjectReference` with a `PackageReference` to the `Microsoft.PowerShell.SDK` NuGet package of the corresponding version. + +### Quick Start + +You can run the benchmarks directly using `dotnet run` in this directory: +1. To run the benchmarks in Interactive Mode, where you will be asked which benchmark(s) to run: + ``` + dotnet run -c Release -f net6.0 + ``` + +2. To list all available benchmarks ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Listing-the-Benchmarks)): + ``` + dotnet run -c Release -f net6.0 --list [flat/tree] + ``` + +3. To filter the benchmarks using a glob pattern applied to `namespace.typeName.methodName` ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Filtering-the-Benchmarks)]): + ``` + dotnet run -c Release -f net6.0 --filter *script* --list flat + ``` + +4. To profile the benchmarked code and produce an ETW Trace file ([read more](https://github.com/dotnet/performance/blob/main/docs/benchmarkdotnet.md#Profiling)) + ``` + dotnet run -c Release -f net6.0 --filter *script* --profiler ETW + ``` + +You can also use the function `Start-Benchmarking` from the module [`perf.psm1`](../perf.psm1) to run the benchmarks: +```powershell +Start-Benchmarking [-TargetFramework ] [-List ] [-Filter ] [-Artifacts ] [-KeepFiles] [] + +Start-Benchmarking [-TargetPSVersion ] [-Filter ] [-Artifacts ] [-KeepFiles] [] + +Start-Benchmarking -Runtime [-Filter ] [-Artifacts ] [-KeepFiles] [] +``` +Run `Get-Help Start-Benchmarking -Full` to see the description of each parameter. + +### Regression Detection + +We use the tool [`ResultsComparer`](../dotnet-tools/ResultsComparer) to compare the provided benchmark results. +See the [README.md](../dotnet-tools/ResultsComparer/README.md) for `ResultsComparer` for more details. + +The module `perf.psm1` also provides `Compare-BenchmarkResult` that wraps `ResultsComparer`. +Here is an example of using it: + +``` +## Run benchmarks targeting the current code base +PS:1> Start-Benchmarking -Filter *script* -Artifacts C:\arena\tmp\BenchmarkDotNet.Artifacts\current\ + +## Run benchmarks targeting the 7.1.3 version of PS package +PS:2> Start-Benchmarking -Filter *script* -Artifacts C:\arena\tmp\BenchmarkDotNet.Artifacts\7.1.3 -TargetPSVersion 7.1.3 + +## Compare the results using 5% threshold +PS:3> Compare-BenchmarkResult -BaseResultPath C:\arena\tmp\BenchmarkDotNet.Artifacts\7.1.3\ -DiffResultPath C:\arena\tmp\BenchmarkDotNet.Artifacts\current\ -Threshold 1% +summary: +better: 4, geomean: 1.057 +total diff: 4 + +No Slower results for the provided threshold = 1% and noise filter = 0.3ns. + +| Faster | base/diff | Base Median (ns) | Diff Median (ns) | Modality| +| -------------------------------------------------------------------------------- | ---------:| ----------------:| ----------------:| --------:| +| Engine.Scripting.InvokeMethod(Script: "$fs=New-Object -ComObject scripting.files | 1.07 | 50635.77 | 47116.42 | | +| Engine.Scripting.InvokeMethod(Script: "$sh=New-Object -ComObject Shell.Applicati | 1.07 | 1063085.23 | 991602.08 | | +| Engine.Scripting.InvokeMethod(Script: "'String'.GetType()") | 1.06 | 1329.93 | 1252.51 | | +| Engine.Scripting.InvokeMethod(Script: "[System.IO.Path]::HasExtension('')") | 1.02 | 1322.04 | 1297.72 | | + +No file given +``` + +## References + +- [Getting started with BenchmarkDotNet](https://benchmarkdotnet.org/articles/guides/getting-started.html) +- [Micro-benchmark Design Guidelines](https://github.com/dotnet/performance/blob/main/docs/microbenchmark-design-guidelines.md) +- [Adam SITNIK: Powerful benchmarking in .NET](https://www.youtube.com/watch?v=pdcrSG4tOLI&t=351s) diff --git a/test/perf/benchmarks/assets/compiler.test.ps1 b/test/perf/benchmarks/assets/compiler.test.ps1 new file mode 100644 index 00000000000..be731373036 --- /dev/null +++ b/test/perf/benchmarks/assets/compiler.test.ps1 @@ -0,0 +1,2665 @@ +## Copyright (c) Microsoft Corporation. +## Licensed under the MIT License. + +function Get-EnvInformation +{ + $environment = @{'IsWindows' = [System.Environment]::OSVersion.Platform -eq [System.PlatformID]::Win32NT} + # PowerShell will likely not be built on pre-1709 nanoserver + if ('System.Management.Automation.Platform' -as [type]) { + $environment += @{'IsCoreCLR' = [System.Management.Automation.Platform]::IsCoreCLR} + $environment += @{'IsLinux' = [System.Management.Automation.Platform]::IsLinux} + $environment += @{'IsMacOS' = [System.Management.Automation.Platform]::IsMacOS} + } else { + $environment += @{'IsCoreCLR' = $false} + $environment += @{'IsLinux' = $false} + $environment += @{'IsMacOS' = $false} + } + + if ($environment.IsWindows) + { + $environment += @{'IsAdmin' = (New-Object Security.Principal.WindowsPrincipal ([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)} + $environment += @{'nugetPackagesRoot' = "${env:USERPROFILE}\.nuget\packages", "${env:NUGET_PACKAGES}"} + } + else + { + $environment += @{'nugetPackagesRoot' = "${env:HOME}/.nuget/packages"} + } + + if ($environment.IsMacOS) { + $environment += @{'UsingHomebrew' = [bool](Get-Command brew -ErrorAction ignore)} + $environment += @{'UsingMacports' = [bool](Get-Command port -ErrorAction ignore)} + + $environment += @{ + 'OSArchitecture' = if ((uname -v) -match 'ARM64') { 'arm64' } else { 'x64' } + } + + if (-not($environment.UsingHomebrew -or $environment.UsingMacports)) { + throw "Neither Homebrew nor MacPorts is installed on this system, visit https://brew.sh/ or https://www.macports.org/ to continue" + } + } + + if ($environment.IsLinux) { + $LinuxInfo = Get-Content /etc/os-release -Raw | ConvertFrom-StringData + $lsb_release = Get-Command lsb_release -Type Application -ErrorAction Ignore | Select-Object -First 1 + if ($lsb_release) { + $LinuxID = & $lsb_release -is + } + else { + $LinuxID = "" + } + + $environment += @{'LinuxInfo' = $LinuxInfo} + $environment += @{'IsDebian' = $LinuxInfo.ID -match 'debian' -or $LinuxInfo.ID -match 'kali'} + $environment += @{'IsDebian9' = $environment.IsDebian -and $LinuxInfo.VERSION_ID -match '9'} + $environment += @{'IsDebian10' = $environment.IsDebian -and $LinuxInfo.VERSION_ID -match '10'} + $environment += @{'IsDebian11' = $environment.IsDebian -and $LinuxInfo.PRETTY_NAME -match 'bullseye'} + $environment += @{'IsUbuntu' = $LinuxInfo.ID -match 'ubuntu' -or $LinuxID -match 'Ubuntu'} + $environment += @{'IsUbuntu16' = $environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '16.04'} + $environment += @{'IsUbuntu18' = $environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '18.04'} + $environment += @{'IsUbuntu20' = $environment.IsUbuntu -and $LinuxInfo.VERSION_ID -match '20.04'} + $environment += @{'IsCentOS' = $LinuxInfo.ID -match 'centos' -and $LinuxInfo.VERSION_ID -match '7'} + $environment += @{'IsFedora' = $LinuxInfo.ID -match 'fedora' -and $LinuxInfo.VERSION_ID -ge 24} + $environment += @{'IsOpenSUSE' = $LinuxInfo.ID -match 'opensuse'} + $environment += @{'IsSLES' = $LinuxInfo.ID -match 'sles'} + $environment += @{'IsRedHat' = $LinuxInfo.ID -match 'rhel'} + $environment += @{'IsRedHat7' = $environment.IsRedHat -and $LinuxInfo.VERSION_ID -match '7' } + $environment += @{'IsOpenSUSE13' = $environment.IsOpenSUSE -and $LinuxInfo.VERSION_ID -match '13'} + $environment += @{'IsOpenSUSE42.1' = $environment.IsOpenSUSE -and $LinuxInfo.VERSION_ID -match '42.1'} + $environment += @{'IsDebianFamily' = $environment.IsDebian -or $environment.IsUbuntu} + $environment += @{'IsRedHatFamily' = $environment.IsCentOS -or $environment.IsFedora -or $environment.IsRedHat} + $environment += @{'IsSUSEFamily' = $environment.IsSLES -or $environment.IsOpenSUSE} + $environment += @{'IsAlpine' = $LinuxInfo.ID -match 'alpine'} + + # Workaround for temporary LD_LIBRARY_PATH hack for Fedora 24 + # https://github.com/PowerShell/PowerShell/issues/2511 + if ($environment.IsFedora -and (Test-Path ENV:\LD_LIBRARY_PATH)) { + Remove-Item -Force ENV:\LD_LIBRARY_PATH + Get-ChildItem ENV: + } + + if( -not( + $environment.IsDebian -or + $environment.IsUbuntu -or + $environment.IsRedHatFamily -or + $environment.IsSUSEFamily -or + $environment.IsAlpine) + ) { + if ($SkipLinuxDistroCheck) { + Write-Warning "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell." + } else { + throw "The current OS : $($LinuxInfo.ID) is not supported for building PowerShell. Import this module with '-ArgumentList `$true' to bypass this check." + } + } + } + + return [PSCustomObject] $environment +} + +function Start-PSBuild { + [CmdletBinding(DefaultParameterSetName="Default")] + param( + # When specified this switch will stops running dev powershell + # to help avoid compilation error, because file are in use. + [switch]$StopDevPowerShell, + + [switch]$Restore, + # Accept a path to the output directory + # When specified, --output will be passed to dotnet + [string]$Output, + [switch]$ResGen, + [switch]$TypeGen, + [switch]$Clean, + [Parameter(ParameterSetName="Legacy")] + [switch]$PSModuleRestore, + [Parameter(ParameterSetName="Default")] + [switch]$NoPSModuleRestore, + [switch]$CI, + [switch]$ForMinimalSize, + + # Skips the step where the pwsh that's been built is used to create a configuration + # Useful when changing parsing/compilation, since bugs there can mean we can't get past this step + [switch]$SkipExperimentalFeatureGeneration, + + # this switch will re-build only System.Management.Automation.dll + # it's useful for development, to do a quick changes in the engine + [switch]$SMAOnly, + + # These runtimes must match those in project.json + # We do not use ValidateScript since we want tab completion + # If this parameter is not provided it will get determined automatically. + [ValidateSet("alpine-x64", + "fxdependent", + "fxdependent-win-desktop", + "linux-arm", + "linux-arm64", + "linux-x64", + "osx-arm64", + "osx-x64", + "win-arm", + "win-arm64", + "win7-x64", + "win7-x86")] + [string]$Runtime, + + [ValidateSet('Debug', 'Release', 'CodeCoverage', '')] # We might need "Checked" as well + [string]$Configuration, + + [switch]$CrossGen, + + [ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d{1,2})?)?$")] + [ValidateNotNullOrEmpty()] + [string]$ReleaseTag, + [switch]$Detailed, + [switch]$InteractiveAuth, + [switch]$SkipRoslynAnalyzers + ) + + if ($ReleaseTag -and $ReleaseTag -notmatch "^v\d+\.\d+\.\d+(-(preview|rc)(\.\d{1,2})?)?$") { + Write-Warning "Only preview or rc are supported for releasing pre-release version of PowerShell" + } + + if ($PSCmdlet.ParameterSetName -eq "Default" -and !$NoPSModuleRestore) + { + $PSModuleRestore = $true + } + + if ($Runtime -eq "linux-arm" -and $environment.IsLinux -and -not $environment.IsUbuntu) { + throw "Cross compiling for linux-arm is only supported on Ubuntu environment" + } + + if ("win-arm","win-arm64" -contains $Runtime -and -not $environment.IsWindows) { + throw "Cross compiling for win-arm or win-arm64 is only supported on Windows environment" + } + + if ($ForMinimalSize) { + if ($CrossGen) { + throw "Build for the minimal size requires the minimal disk footprint, so `CrossGen` is not allowed" + } + + if ($Runtime -and "linux-x64", "win7-x64", "osx-x64" -notcontains $Runtime) { + throw "Build for the minimal size is enabled only for following runtimes: 'linux-x64', 'win7-x64', 'osx-x64'" + } + } + + function Stop-DevPowerShell { + Get-Process pwsh* | + Where-Object { + $_.Modules | + Where-Object { + $_.FileName -eq (Resolve-Path $script:Options.Output).Path + } + } | + Stop-Process -Verbose + } + + if ($Clean) { + Write-Log -message "Cleaning your working directory. You can also do it with 'git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3'" + Push-Location $PSScriptRoot + try { + # Excluded sqlite3 folder is due to this Roslyn issue: https://github.com/dotnet/roslyn/issues/23060 + # Excluded src/Modules/nuget.config as this is required for release build. + # Excluded nuget.config as this is required for release build. + git clean -fdX --exclude .vs/PowerShell/v16/Server/sqlite3 --exclude src/Modules/nuget.config --exclude nuget.config + } finally { + Pop-Location + } + } + + # Add .NET CLI tools to PATH + Find-Dotnet + + # Verify we have git in place to do the build, and abort if the precheck failed + $precheck = precheck 'git' "Build dependency 'git' not found in PATH. See " + if (-not $precheck) { + return + } + + # Verify we have .NET SDK in place to do the build, and abort if the precheck failed + $precheck = precheck 'dotnet' "Build dependency 'dotnet' not found in PATH. Run Start-PSBootstrap. Also see " + if (-not $precheck) { + return + } + + # Verify if the dotnet in-use is the required version + $dotnetCLIInstalledVersion = Start-NativeExecution -sb { dotnet --version } -IgnoreExitcode + If ($dotnetCLIInstalledVersion -ne $dotnetCLIRequiredVersion) { + Write-Warning @" +The currently installed .NET Command Line Tools is not the required version. + +Installed version: $dotnetCLIInstalledVersion +Required version: $dotnetCLIRequiredVersion + +Fix steps: + +1. Remove the installed version from: + - on windows '`$env:LOCALAPPDATA\Microsoft\dotnet' + - on macOS and linux '`$env:HOME/.dotnet' +2. Run Start-PSBootstrap or Install-Dotnet +3. Start-PSBuild -Clean +`n +"@ + return + } + + # set output options + $OptionsArguments = @{ + CrossGen=$CrossGen + Output=$Output + Runtime=$Runtime + Configuration=$Configuration + Verbose=$true + SMAOnly=[bool]$SMAOnly + PSModuleRestore=$PSModuleRestore + ForMinimalSize=$ForMinimalSize + } + $script:Options = New-PSOptions @OptionsArguments + + if ($StopDevPowerShell) { + Stop-DevPowerShell + } + + # setup arguments + # adding ErrorOnDuplicatePublishOutputFiles=false due to .NET SDk issue: https://github.com/dotnet/sdk/issues/15748 + # removing --no-restore due to .NET SDK issue: https://github.com/dotnet/sdk/issues/18999 + # $Arguments = @("publish","--no-restore","/property:GenerateFullPaths=true", "/property:ErrorOnDuplicatePublishOutputFiles=false") + $Arguments = @("publish","/property:GenerateFullPaths=true", "/property:ErrorOnDuplicatePublishOutputFiles=false") + if ($Output -or $SMAOnly) { + $Arguments += "--output", (Split-Path $Options.Output) + } + + # Add --self-contained due to "warning NETSDK1179: One of '--self-contained' or '--no-self-contained' options are required when '--runtime' is used." + if ($Options.Runtime -like 'fxdependent*') { + $Arguments += "--no-self-contained" + } + else { + $Arguments += "--self-contained" + } + + if ($Options.Runtime -like 'win*' -or ($Options.Runtime -like 'fxdependent*' -and $environment.IsWindows)) { + $Arguments += "/property:IsWindows=true" + } + else { + $Arguments += "/property:IsWindows=false" + } + + # Framework Dependent builds do not support ReadyToRun as it needs a specific runtime to optimize for. + # The property is set in Powershell.Common.props file. + # We override the property through the build command line. + if($Options.Runtime -like 'fxdependent*' -or $ForMinimalSize) { + $Arguments += "/property:PublishReadyToRun=false" + } + + $Arguments += "--configuration", $Options.Configuration + $Arguments += "--framework", $Options.Framework + + if ($Detailed.IsPresent) + { + $Arguments += '--verbosity', 'd' + } + + if (-not $SMAOnly -and $Options.Runtime -notlike 'fxdependent*') { + # libraries should not have runtime + $Arguments += "--runtime", $Options.Runtime + } + + if ($ReleaseTag) { + $ReleaseTagToUse = $ReleaseTag -Replace '^v' + $Arguments += "/property:ReleaseTag=$ReleaseTagToUse" + } + + if ($SkipRoslynAnalyzers) { + $Arguments += "/property:RunAnalyzersDuringBuild=false" + } + + # handle Restore + Restore-PSPackage -Options $Options -Force:$Restore -InteractiveAuth:$InteractiveAuth + + # handle ResGen + # Heuristic to run ResGen on the fresh machine + if ($ResGen -or -not (Test-Path "$PSScriptRoot/src/Microsoft.PowerShell.ConsoleHost/gen")) { + Write-Log -message "Run ResGen (generating C# bindings for resx files)" + Start-ResGen + } + + # Handle TypeGen + # .inc file name must be different for Windows and Linux to allow build on Windows and WSL. + $incFileName = "powershell_$($Options.Runtime).inc" + if ($TypeGen -or -not (Test-Path "$PSScriptRoot/src/TypeCatalogGen/$incFileName")) { + Write-Log -message "Run TypeGen (generating CorePsTypeCatalog.cs)" + Start-TypeGen -IncFileName $incFileName + } + + # Get the folder path where pwsh.exe is located. + if ((Split-Path $Options.Output -Leaf) -like "pwsh*") { + $publishPath = Split-Path $Options.Output -Parent + } + else { + $publishPath = $Options.Output + } + + try { + # Relative paths do not work well if cwd is not changed to project + Push-Location $Options.Top + + if ($Options.Runtime -notlike 'fxdependent*') { + $sdkToUse = 'Microsoft.NET.Sdk' + if ($Options.Runtime -like 'win7-*' -and !$ForMinimalSize) { + ## WPF/WinForm and the PowerShell GraphicalHost assemblies are included + ## when 'Microsoft.NET.Sdk.WindowsDesktop' is used. + $sdkToUse = 'Microsoft.NET.Sdk.WindowsDesktop' + } + + $Arguments += "/property:SDKToUse=$sdkToUse" + + Write-Log -message "Run dotnet $Arguments from $PWD" + Start-NativeExecution { dotnet $Arguments } + Write-Log -message "PowerShell output: $($Options.Output)" + + if ($CrossGen) { + # fxdependent package cannot be CrossGen'ed + Start-CrossGen -PublishPath $publishPath -Runtime $script:Options.Runtime + Write-Log -message "pwsh.exe with ngen binaries is available at: $($Options.Output)" + } + } else { + $globalToolSrcFolder = Resolve-Path (Join-Path $Options.Top "../Microsoft.PowerShell.GlobalTool.Shim") | Select-Object -ExpandProperty Path + + if ($Options.Runtime -eq 'fxdependent') { + $Arguments += "/property:SDKToUse=Microsoft.NET.Sdk" + } elseif ($Options.Runtime -eq 'fxdependent-win-desktop') { + $Arguments += "/property:SDKToUse=Microsoft.NET.Sdk.WindowsDesktop" + } + + Write-Log -message "Run dotnet $Arguments from $PWD" + Start-NativeExecution { dotnet $Arguments } + Write-Log -message "PowerShell output: $($Options.Output)" + + try { + Push-Location $globalToolSrcFolder + $Arguments += "--output", $publishPath + Write-Log -message "Run dotnet $Arguments from $PWD to build global tool entry point" + Start-NativeExecution { dotnet $Arguments } + } + finally { + Pop-Location + } + } + } finally { + Pop-Location + } + + # No extra post-building task will run if '-SMAOnly' is specified, because its purpose is for a quick update of S.M.A.dll after full build. + if ($SMAOnly) { + return + } + + # publish reference assemblies + try { + Push-Location "$PSScriptRoot/src/TypeCatalogGen" + $refAssemblies = Get-Content -Path $incFileName | Where-Object { $_ -like "*microsoft.netcore.app*" } | ForEach-Object { $_.TrimEnd(';') } + $refDestFolder = Join-Path -Path $publishPath -ChildPath "ref" + + if (Test-Path $refDestFolder -PathType Container) { + Remove-Item $refDestFolder -Force -Recurse -ErrorAction Stop + } + New-Item -Path $refDestFolder -ItemType Directory -Force -ErrorAction Stop > $null + Copy-Item -Path $refAssemblies -Destination $refDestFolder -Force -ErrorAction Stop + } finally { + Pop-Location + } + + if ($ReleaseTag) { + $psVersion = $ReleaseTag + } + else { + $psVersion = git --git-dir="$PSScriptRoot/.git" describe + } + + if ($environment.IsLinux) { + if ($environment.IsRedHatFamily -or $environment.IsDebian) { + # Symbolic links added here do NOT affect packaging as we do not build on Debian. + # add two symbolic links to system shared libraries that libmi.so is dependent on to handle + # platform specific changes. This is the only set of platforms needed for this currently + # as Ubuntu has these specific library files in the platform and macOS builds for itself + # against the correct versions. + + if ($environment.IsDebian10 -or $environment.IsDebian11){ + $sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.1" + $cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1" + } + elseif ($environment.IsDebian9){ + # NOTE: Debian 8 doesn't need these symlinks + $sslTarget = "/usr/lib/x86_64-linux-gnu/libssl.so.1.0.2" + $cryptoTarget = "/usr/lib/x86_64-linux-gnu/libcrypto.so.1.0.2" + } + else { #IsRedHatFamily + $sslTarget = "/lib64/libssl.so.10" + $cryptoTarget = "/lib64/libcrypto.so.10" + } + + if ( ! (Test-Path "$publishPath/libssl.so.1.0.0")) { + $null = New-Item -Force -ItemType SymbolicLink -Target $sslTarget -Path "$publishPath/libssl.so.1.0.0" -ErrorAction Stop + } + if ( ! (Test-Path "$publishPath/libcrypto.so.1.0.0")) { + $null = New-Item -Force -ItemType SymbolicLink -Target $cryptoTarget -Path "$publishPath/libcrypto.so.1.0.0" -ErrorAction Stop + } + } + } + + # download modules from powershell gallery. + # - PowerShellGet, PackageManagement, Microsoft.PowerShell.Archive + if ($PSModuleRestore) { + Restore-PSModuleToBuild -PublishPath $publishPath + } + + # publish powershell.config.json + $config = @{} + if ($environment.IsWindows) { + $config = @{ "Microsoft.PowerShell:ExecutionPolicy" = "RemoteSigned"; + "WindowsPowerShellCompatibilityModuleDenyList" = @("PSScheduledJob","BestPractices","UpdateServices") } + } + + # When building preview, we want the configuration to enable all experiemental features by default + # ARM is cross compiled, so we can't run pwsh to enumerate Experimental Features + if (-not $SkipExperimentalFeatureGeneration -and + (Test-IsPreview $psVersion) -and + -not (Test-IsReleaseCandidate $psVersion) -and + -not $Runtime.Contains("arm") -and + -not ($Runtime -like 'fxdependent*')) { + + $json = & $publishPath\pwsh -noprofile -command { + # Special case for DSC code in PS; + # this experimental feature requires new DSC module that is not inbox, + # so we don't want default DSC use case be broken + [System.Collections.ArrayList] $expFeatures = Get-ExperimentalFeature | Where-Object Name -NE PS7DscSupport | ForEach-Object -MemberName Name + + $expFeatures | Out-String | Write-Verbose -Verbose + + # Make sure ExperimentalFeatures from modules in PSHome are added + # https://github.com/PowerShell/PowerShell/issues/10550 + $ExperimentalFeaturesFromGalleryModulesInPSHome = @() + $ExperimentalFeaturesFromGalleryModulesInPSHome | ForEach-Object { + if (!$expFeatures.Contains($_)) { + $null = $expFeatures.Add($_) + } + } + + ConvertTo-Json $expFeatures + } + + $config += @{ ExperimentalFeatures = ([string[]] ($json | ConvertFrom-Json)) } + } + + if ($config.Count -gt 0) { + $configPublishPath = Join-Path -Path $publishPath -ChildPath "powershell.config.json" + Set-Content -Path $configPublishPath -Value ($config | ConvertTo-Json) -Force -ErrorAction Stop + } + + # Restore the Pester module + if ($CI) { + Restore-PSPester -Destination (Join-Path $publishPath "Modules") + } +} + +function New-PSOptions { + [CmdletBinding()] + param( + [ValidateSet("Debug", "Release", "CodeCoverage", '')] + [string]$Configuration, + + [ValidateSet("net6.0")] + [string]$Framework = "net6.0", + + # These are duplicated from Start-PSBuild + # We do not use ValidateScript since we want tab completion + [ValidateSet("", + "alpine-x64", + "fxdependent", + "fxdependent-win-desktop", + "linux-arm", + "linux-arm64", + "linux-x64", + "osx-arm64", + "osx-x64", + "win-arm", + "win-arm64", + "win7-x64", + "win7-x86")] + [string]$Runtime, + + [switch]$CrossGen, + + # Accept a path to the output directory + # If not null or empty, name of the executable will be appended to + # this path, otherwise, to the default path, and then the full path + # of the output executable will be assigned to the Output property + [string]$Output, + + [switch]$SMAOnly, + + [switch]$PSModuleRestore, + + [switch]$ForMinimalSize + ) + + # Add .NET CLI tools to PATH + Find-Dotnet + + if (-not $Configuration) { + $Configuration = 'Debug' + } + + Write-Verbose "Using configuration '$Configuration'" + Write-Verbose "Using framework '$Framework'" + + if (-not $Runtime) { + if ($environment.IsLinux) { + $Runtime = "linux-x64" + } elseif ($environment.IsMacOS) { + if ($PSVersionTable.OS.Contains('ARM64')) { + $Runtime = "osx-arm64" + } + else { + $Runtime = "osx-x64" + } + } else { + $RID = dotnet --info | ForEach-Object { + if ($_ -match "RID") { + $_ -split "\s+" | Select-Object -Last 1 + } + } + + # We plan to release packages targeting win7-x64 and win7-x86 RIDs, + # which supports all supported windows platforms. + # So we, will change the RID to win7- + $Runtime = $RID -replace "win\d+", "win7" + } + + if (-not $Runtime) { + Throw "Could not determine Runtime Identifier, please update dotnet" + } else { + Write-Verbose "Using runtime '$Runtime'" + } + } + + $PowerShellDir = if ($Runtime -like 'win*' -or ($Runtime -like 'fxdependent*' -and $environment.IsWindows)) { + "powershell-win-core" + } else { + "powershell-unix" + } + + $Top = [IO.Path]::Combine($PSScriptRoot, "src", $PowerShellDir) + Write-Verbose "Top project directory is $Top" + + $Executable = if ($Runtime -like 'fxdependent*') { + "pwsh.dll" + } elseif ($environment.IsLinux -or $environment.IsMacOS) { + "pwsh" + } elseif ($environment.IsWindows) { + "pwsh.exe" + } + + # Build the Output path + if (!$Output) { + if ($Runtime -like 'fxdependent*') { + $Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, "publish", $Executable) + } else { + $Output = [IO.Path]::Combine($Top, "bin", $Configuration, $Framework, $Runtime, "publish", $Executable) + } + } else { + $Output = [IO.Path]::Combine($Output, $Executable) + } + + if ($SMAOnly) + { + $Top = [IO.Path]::Combine($PSScriptRoot, "src", "System.Management.Automation") + } + + $RootInfo = @{RepoPath = $PSScriptRoot} + + # the valid root is the root of the filesystem and the folder PowerShell + $RootInfo['ValidPath'] = Join-Path -Path ([system.io.path]::GetPathRoot($RootInfo.RepoPath)) -ChildPath 'PowerShell' + + if($RootInfo.RepoPath -ne $RootInfo.ValidPath) + { + $RootInfo['Warning'] = "Please ensure your repo is at the root of the file system and named 'PowerShell' (example: '$($RootInfo.ValidPath)'), when building and packaging for release!" + $RootInfo['IsValid'] = $false + } + else + { + $RootInfo['IsValid'] = $true + } + + return New-PSOptionsObject ` + -RootInfo ([PSCustomObject]$RootInfo) ` + -Top $Top ` + -Runtime $Runtime ` + -Crossgen $Crossgen.IsPresent ` + -Configuration $Configuration ` + -PSModuleRestore $PSModuleRestore.IsPresent ` + -Framework $Framework ` + -Output $Output ` + -ForMinimalSize $ForMinimalSize +} + +function Start-PSPester { + [CmdletBinding(DefaultParameterSetName='default')] + param( + [Parameter(Position=0)] + [string[]]$Path = @("$PSScriptRoot/test/powershell"), + [string]$OutputFormat = "NUnitXml", + [string]$OutputFile = "pester-tests.xml", + [string[]]$ExcludeTag = 'Slow', + [string[]]$Tag = @("CI","Feature"), + [switch]$ThrowOnFailure, + [string]$BinDir = (Split-Path (Get-PSOptions -DefaultToNew).Output), + [string]$powershell = (Join-Path $BinDir 'pwsh'), + [string]$Pester = ([IO.Path]::Combine($BinDir, "Modules", "Pester")), + [Parameter(ParameterSetName='Unelevate',Mandatory=$true)] + [switch]$Unelevate, + [switch]$Quiet, + [switch]$Terse, + [Parameter(ParameterSetName='PassThru',Mandatory=$true)] + [switch]$PassThru, + [Parameter(ParameterSetName='PassThru',HelpMessage='Run commands on Linux with sudo.')] + [switch]$Sudo, + [switch]$IncludeFailingTest, + [switch]$IncludeCommonTests, + [string]$ExperimentalFeatureName, + [Parameter(HelpMessage='Title to publish the results as.')] + [string]$Title = 'PowerShell 7 Tests', + [Parameter(ParameterSetName='Wait', Mandatory=$true, + HelpMessage='Wait for the debugger to attach to PowerShell before Pester starts. Debug builds only!')] + [switch]$Wait, + [switch]$SkipTestToolBuild + ) + + if (-not (Get-Module -ListAvailable -Name $Pester -ErrorAction SilentlyContinue | Where-Object { $_.Version -ge "4.2" } )) + { + Restore-PSPester + } + + if ($IncludeFailingTest.IsPresent) + { + $Path += "$PSScriptRoot/tools/failingTests" + } + + if($IncludeCommonTests.IsPresent) + { + $path = += "$PSScriptRoot/test/common" + } + + # we need to do few checks and if user didn't provide $ExcludeTag explicitly, we should alternate the default + if ($Unelevate) + { + if (-not $environment.IsWindows) + { + throw '-Unelevate is currently not supported on non-Windows platforms' + } + + if (-not $environment.IsAdmin) + { + throw '-Unelevate cannot be applied because the current user is not Administrator' + } + + if (-not $PSBoundParameters.ContainsKey('ExcludeTag')) + { + $ExcludeTag += 'RequireAdminOnWindows' + } + } + elseif ($environment.IsWindows -and (-not $environment.IsAdmin)) + { + if (-not $PSBoundParameters.ContainsKey('ExcludeTag')) + { + $ExcludeTag += 'RequireAdminOnWindows' + } + } + elseif (-not $environment.IsWindows -and (-not $Sudo.IsPresent)) + { + if (-not $PSBoundParameters.ContainsKey('ExcludeTag')) + { + $ExcludeTag += 'RequireSudoOnUnix' + } + } + elseif (-not $environment.IsWindows -and $Sudo.IsPresent) + { + if (-not $PSBoundParameters.ContainsKey('Tag')) + { + $Tag = 'RequireSudoOnUnix' + } + } + + Write-Verbose "Running pester tests at '$path' with tag '$($Tag -join ''', ''')' and ExcludeTag '$($ExcludeTag -join ''', ''')'" -Verbose + if(!$SkipTestToolBuild.IsPresent) + { + $publishArgs = @{ } + # if we are building for Alpine, we must include the runtime as linux-x64 + # will not build runnable test tools + if ( $environment.IsLinux -and $environment.IsAlpine ) { + $publishArgs['runtime'] = 'alpine-x64' + } + Publish-PSTestTools @publishArgs | ForEach-Object {Write-Host $_} + } + + # All concatenated commands/arguments are suffixed with the delimiter (space) + + # Disable telemetry for all startups of pwsh in tests + $command = "`$env:POWERSHELL_TELEMETRY_OPTOUT = 'yes';" + if ($Terse) + { + $command += "`$ProgressPreference = 'silentlyContinue'; " + } + + # Autoload (in subprocess) temporary modules used in our tests + $newPathFragment = $TestModulePath + $TestModulePathSeparator + $command += '$env:PSModulePath = '+"'$newPathFragment'" + '+$env:PSModulePath;' + + # Windows needs the execution policy adjusted + if ($environment.IsWindows) { + $command += "Set-ExecutionPolicy -Scope Process Unrestricted; " + } + + $command += "Import-Module '$Pester'; " + + if ($Unelevate) + { + if ($environment.IsWindows) { + $outputBufferFilePath = [System.IO.Path]::GetTempFileName() + } + else { + # Azure DevOps agents do not have Temp folder setup on Ubuntu 20.04, hence using HOME directory + $outputBufferFilePath = (Join-Path $env:HOME $([System.IO.Path]::GetRandomFileName())) + } + } + + $command += "Invoke-Pester " + + $command += "-OutputFormat ${OutputFormat} -OutputFile ${OutputFile} " + if ($ExcludeTag -and ($ExcludeTag -ne "")) { + $command += "-ExcludeTag @('" + (${ExcludeTag} -join "','") + "') " + } + if ($Tag) { + $command += "-Tag @('" + (${Tag} -join "','") + "') " + } + # sometimes we need to eliminate Pester output, especially when we're + # doing a daily build as the log file is too large + if ( $Quiet ) { + $command += "-Quiet " + } + if ( $PassThru ) { + $command += "-PassThru " + } + + $command += "'" + ($Path -join "','") + "'" + if ($Unelevate) + { + $command += " *> $outputBufferFilePath; '__UNELEVATED_TESTS_THE_END__' >> $outputBufferFilePath" + } + + Write-Verbose $command + + $script:nonewline = $true + $script:inerror = $false + function Write-Terse([string] $line) + { + $trimmedline = $line.Trim() + if ($trimmedline.StartsWith("[+]")) { + Write-Host "+" -NoNewline -ForegroundColor Green + $script:nonewline = $true + $script:inerror = $false + } + elseif ($trimmedline.StartsWith("[?]")) { + Write-Host "?" -NoNewline -ForegroundColor Cyan + $script:nonewline = $true + $script:inerror = $false + } + elseif ($trimmedline.StartsWith("[!]")) { + Write-Host "!" -NoNewline -ForegroundColor Gray + $script:nonewline = $true + $script:inerror = $false + } + elseif ($trimmedline.StartsWith("Executing script ")) { + # Skip lines where Pester reports that is executing a test script + return + } + elseif ($trimmedline -match "^\d+(\.\d+)?m?s$") { + # Skip the time elapse like '12ms', '1ms', '1.2s' and '12.53s' + return + } + else { + if ($script:nonewline) { + Write-Host "`n" -NoNewline + } + if ($trimmedline.StartsWith("[-]") -or $script:inerror) { + Write-Host $line -ForegroundColor Red + $script:inerror = $true + } + elseif ($trimmedline.StartsWith("VERBOSE:")) { + Write-Host $line -ForegroundColor Yellow + $script:inerror = $false + } + elseif ($trimmedline.StartsWith("Describing") -or $trimmedline.StartsWith("Context")) { + Write-Host $line -ForegroundColor Magenta + $script:inerror = $false + } + else { + Write-Host $line -ForegroundColor Gray + } + $script:nonewline = $false + } + } + + $PSFlags = @("-noprofile") + if (-not [string]::IsNullOrEmpty($ExperimentalFeatureName)) { + + if ($environment.IsWindows) { + $configFile = [System.IO.Path]::GetTempFileName() + } + else { + $configFile = (Join-Path $env:HOME $([System.IO.Path]::GetRandomFileName())) + } + + $configFile = [System.IO.Path]::ChangeExtension($configFile, ".json") + + ## Create the config.json file to enable the given experimental feature. + ## On Windows, we need to have 'RemoteSigned' declared for ExecutionPolicy because the ExecutionPolicy is 'Restricted' by default. + ## On Unix, ExecutionPolicy is not supported, so we don't need to declare it. + if ($environment.IsWindows) { + $content = @" +{ + "Microsoft.PowerShell:ExecutionPolicy":"RemoteSigned", + "ExperimentalFeatures": [ + "$ExperimentalFeatureName" + ] +} +"@ + } else { + $content = @" +{ + "ExperimentalFeatures": [ + "$ExperimentalFeatureName" + ] +} +"@ + } + + Set-Content -Path $configFile -Value $content -Encoding Ascii -Force + $PSFlags = @("-settings", $configFile, "-noprofile") + } + + # -Wait is only available on Debug builds + # It is used to allow the debugger to attach before PowerShell + # runs pester in this case + if($Wait.IsPresent){ + $PSFlags += '-wait' + } + + # To ensure proper testing, the module path must not be inherited by the spawned process + try { + $originalModulePath = $env:PSModulePath + $originalTelemetry = $env:POWERSHELL_TELEMETRY_OPTOUT + $env:POWERSHELL_TELEMETRY_OPTOUT = 'yes' + if ($Unelevate) + { + Start-UnelevatedProcess -process $powershell -arguments ($PSFlags + "-c $Command") + $currentLines = 0 + while ($true) + { + $lines = Get-Content $outputBufferFilePath | Select-Object -Skip $currentLines + if ($Terse) + { + foreach ($line in $lines) + { + Write-Terse -line $line + } + } + else + { + $lines | Write-Host + } + if ($lines | Where-Object { $_ -eq '__UNELEVATED_TESTS_THE_END__'}) + { + break + } + + $count = ($lines | Measure-Object).Count + if ($count -eq 0) + { + Start-Sleep -Seconds 1 + } + else + { + $currentLines += $count + } + } + } + else + { + if ($PassThru.IsPresent) + { + if ($environment.IsWindows) { + $passThruFile = [System.IO.Path]::GetTempFileName() + } + else { + $passThruFile = Join-Path $env:HOME $([System.IO.Path]::GetRandomFileName()) + } + + try + { + $command += "| Export-Clixml -Path '$passThruFile' -Force" + + $passThruCommand = { & $powershell $PSFlags -c $command } + if ($Sudo.IsPresent) { + # -E says to preserve the environment + $passThruCommand = { & sudo -E $powershell $PSFlags -c $command } + } + + $writeCommand = { Write-Host $_ } + if ($Terse) + { + $writeCommand = { Write-Terse $_ } + } + + Start-NativeExecution -sb $passThruCommand | ForEach-Object $writeCommand + Import-Clixml -Path $passThruFile | Where-Object {$_.TotalCount -is [Int32]} + } + finally + { + Remove-Item $passThruFile -ErrorAction SilentlyContinue -Force + } + } + else + { + if ($Terse) + { + Start-NativeExecution -sb {& $powershell $PSFlags -c $command} | ForEach-Object { Write-Terse -line $_ } + } + else + { + Start-NativeExecution -sb {& $powershell $PSFlags -c $command} + } + } + } + } finally { + $env:PSModulePath = $originalModulePath + $env:POWERSHELL_TELEMETRY_OPTOUT = $originalTelemetry + if ($Unelevate) + { + Remove-Item $outputBufferFilePath + } + } + + Publish-TestResults -Path $OutputFile -Title $Title + + if($ThrowOnFailure) + { + Test-PSPesterResults -TestResultsFile $OutputFile + } +} + +function Install-Dotnet { + [CmdletBinding()] + param( + [string]$Channel = $dotnetCLIChannel, + [string]$Version = $dotnetCLIRequiredVersion, + [string]$Quality = $dotnetCLIQuality, + [switch]$NoSudo, + [string]$InstallDir, + [string]$AzureFeed, + [string]$FeedCredential + ) + + # This allows sudo install to be optional; needed when running in containers / as root + # Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly + $sudo = if (!$NoSudo) { "sudo" } + + $installObtainUrl = "https://dotnet.microsoft.com/download/dotnet-core/scripts/v1" + $uninstallObtainUrl = "https://raw.githubusercontent.com/dotnet/cli/master/scripts/obtain" + + # Install for Linux and OS X + if ($environment.IsLinux -or $environment.IsMacOS) { + $wget = Get-Command -Name wget -CommandType Application -TotalCount 1 -ErrorAction Stop + + # Uninstall all previous dotnet packages + $uninstallScript = if ($environment.IsLinux -and $environment.IsUbuntu) { + "dotnet-uninstall-debian-packages.sh" + } elseif ($environment.IsMacOS) { + "dotnet-uninstall-pkgs.sh" + } + + if ($uninstallScript) { + Start-NativeExecution { + & $wget $uninstallObtainUrl/uninstall/$uninstallScript + Invoke-Expression "$sudo bash ./$uninstallScript" + } + } else { + Write-Warning "This script only removes prior versions of dotnet for Ubuntu and OS X" + } + + # Install new dotnet 1.1.0 preview packages + $installScript = "dotnet-install.sh" + Start-NativeExecution { + Write-Verbose -Message "downloading install script from $installObtainUrl/$installScript ..." -Verbose + & $wget $installObtainUrl/$installScript + + if ((Get-ChildItem "./$installScript").Length -eq 0) { + throw "./$installScript was 0 length" + } + + if ($Version) { + $bashArgs = @("./$installScript", '-v', $Version, '-q', $Quality) + } + elseif ($Channel) { + $bashArgs = @("./$installScript", '-c', $Channel, '-q', $Quality) + } + + if ($InstallDir) { + $bashArgs += @('-i', $InstallDir) + } + + if ($AzureFeed) { + $bashArgs += @('-AzureFeed', $AzureFeed, '-FeedCredential', $FeedCredential) + } + + bash @bashArgs + } + } elseif ($environment.IsWindows) { + Remove-Item -ErrorAction SilentlyContinue -Recurse -Force ~\AppData\Local\Microsoft\dotnet + $installScript = "dotnet-install.ps1" + Invoke-WebRequest -Uri $installObtainUrl/$installScript -OutFile $installScript + if (-not $environment.IsCoreCLR) { + $installArgs = @{ + Quality = $Quality + } + + if ($Version) { + $installArgs += @{ Version = $Version } + } elseif ($Channel) { + $installArgs += @{ Channel = $Channel } + } + + if ($InstallDir) { + $installArgs += @{ InstallDir = $InstallDir } + } + + if ($AzureFeed) { + $installArgs += @{ + AzureFeed = $AzureFeed + $FeedCredential = $FeedCredential + } + } + + & ./$installScript @installArgs + } + else { + # dotnet-install.ps1 uses APIs that are not supported in .NET Core, so we run it with Windows PowerShell + $fullPSPath = Join-Path -Path $env:windir -ChildPath "System32\WindowsPowerShell\v1.0\powershell.exe" + $fullDotnetInstallPath = Join-Path -Path $PWD.Path -ChildPath $installScript + Start-NativeExecution { + + if ($Version) { + $psArgs = @('-NoLogo', '-NoProfile', '-File', $fullDotnetInstallPath, '-Version', $Version, '-Quality', $Quality) + } + elseif ($Channel) { + $psArgs = @('-NoLogo', '-NoProfile', '-File', $fullDotnetInstallPath, '-Channel', $Channel, '-Quality', $Quality) + } + + if ($InstallDir) { + $psArgs += @('-InstallDir', $InstallDir) + } + + if ($AzureFeed) { + $psArgs += @('-AzureFeed', $AzureFeed, '-FeedCredential', $FeedCredential) + } + + & $fullPSPath @psArgs + } + } + } +} + +function Start-PSBootstrap { + [CmdletBinding()] + param( + [string]$Channel = $dotnetCLIChannel, + # we currently pin dotnet-cli version, and will + # update it when more stable version comes out. + [string]$Version = $dotnetCLIRequiredVersion, + [switch]$Package, + [switch]$NoSudo, + [switch]$BuildLinuxArm, + [switch]$Force + ) + + Write-Log -message "Installing PowerShell build dependencies" + + Push-Location $PSScriptRoot/tools + + try { + if ($environment.IsLinux -or $environment.IsMacOS) { + # This allows sudo install to be optional; needed when running in containers / as root + # Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly + $sudo = if (!$NoSudo) { "sudo" } + + if ($BuildLinuxArm -and $environment.IsLinux -and -not $environment.IsUbuntu) { + Write-Error "Cross compiling for linux-arm is only supported on Ubuntu environment" + return + } + + # Install ours and .NET's dependencies + $Deps = @() + if ($environment.IsLinux -and $environment.IsUbuntu) { + # Build tools + $Deps += "curl", "g++", "make" + + if ($BuildLinuxArm) { + $Deps += "gcc-arm-linux-gnueabihf", "g++-arm-linux-gnueabihf" + } + + # .NET Core required runtime libraries + $Deps += "libunwind8" + if ($environment.IsUbuntu16) { $Deps += "libicu55" } + elseif ($environment.IsUbuntu18) { $Deps += "libicu60"} + + # Packaging tools + if ($Package) { $Deps += "ruby-dev", "groff", "libffi-dev" } + + # Install dependencies + # change the fontend from apt-get to noninteractive + $originalDebianFrontEnd=$env:DEBIAN_FRONTEND + $env:DEBIAN_FRONTEND='noninteractive' + try { + Start-NativeExecution { + Invoke-Expression "$sudo apt-get update -qq" + Invoke-Expression "$sudo apt-get install -y -qq $Deps" + } + } + finally { + # change the apt frontend back to the original + $env:DEBIAN_FRONTEND=$originalDebianFrontEnd + } + } elseif ($environment.IsLinux -and $environment.IsRedHatFamily) { + # Build tools + $Deps += "which", "curl", "gcc-c++", "make" + + # .NET Core required runtime libraries + $Deps += "libicu", "libunwind" + + # Packaging tools + if ($Package) { $Deps += "ruby-devel", "rpm-build", "groff", 'libffi-devel' } + + $PackageManager = Get-RedHatPackageManager + + $baseCommand = "$sudo $PackageManager" + + # On OpenSUSE 13.2 container, sudo does not exist, so don't use it if not needed + if($NoSudo) + { + $baseCommand = $PackageManager + } + + # Install dependencies + Start-NativeExecution { + Invoke-Expression "$baseCommand $Deps" + } + } elseif ($environment.IsLinux -and $environment.IsSUSEFamily) { + # Build tools + $Deps += "gcc", "make" + + # Packaging tools + if ($Package) { $Deps += "ruby-devel", "rpmbuild", "groff", 'libffi-devel' } + + $PackageManager = "zypper --non-interactive install" + $baseCommand = "$sudo $PackageManager" + + # On OpenSUSE 13.2 container, sudo does not exist, so don't use it if not needed + if($NoSudo) + { + $baseCommand = $PackageManager + } + + # Install dependencies + Start-NativeExecution { + Invoke-Expression "$baseCommand $Deps" + } + } elseif ($environment.IsMacOS) { + if ($environment.UsingHomebrew) { + $PackageManager = "brew" + } elseif ($environment.UsingMacports) { + $PackageManager = "$sudo port" + } + + # .NET Core required runtime libraries + $Deps += "openssl" + + # Install dependencies + # ignore exitcode, because they may be already installed + Start-NativeExecution ([ScriptBlock]::Create("$PackageManager install $Deps")) -IgnoreExitcode + } elseif ($environment.IsLinux -and $environment.IsAlpine) { + $Deps += 'libunwind', 'libcurl', 'bash', 'clang', 'build-base', 'git', 'curl' + + Start-NativeExecution { + Invoke-Expression "apk add $Deps" + } + } + + # Install [fpm](https://github.com/jordansissel/fpm) and [ronn](https://github.com/rtomayko/ronn) + if ($Package) { + try { + # We cannot guess if the user wants to run gem install as root on linux and windows, + # but macOs usually requires sudo + $gemsudo = '' + if($environment.IsMacOS -or $env:TF_BUILD) { + $gemsudo = $sudo + } + Start-NativeExecution ([ScriptBlock]::Create("$gemsudo gem install ffi -v 1.12.0 --no-document")) + Start-NativeExecution ([ScriptBlock]::Create("$gemsudo gem install fpm -v 1.11.0 --no-document")) + Start-NativeExecution ([ScriptBlock]::Create("$gemsudo gem install ronn -v 0.7.3 --no-document")) + } catch { + Write-Warning "Installation of fpm and ronn gems failed! Must resolve manually." + } + } + } + + # Try to locate dotnet-SDK before installing it + Find-Dotnet + + # Install dotnet-SDK + $dotNetExists = precheck 'dotnet' $null + $dotNetVersion = [string]::Empty + if($dotNetExists) { + $dotNetVersion = Start-NativeExecution -sb { dotnet --version } -IgnoreExitcode + } + + if(!$dotNetExists -or $dotNetVersion -ne $dotnetCLIRequiredVersion -or $Force.IsPresent) { + if($Force.IsPresent) { + Write-Log -message "Installing dotnet due to -Force." + } + elseif(!$dotNetExists) { + Write-Log -message "dotnet not present. Installing dotnet." + } + else { + Write-Log -message "dotnet out of date ($dotNetVersion). Updating dotnet." + } + + $DotnetArguments = @{ Channel=$Channel; Version=$Version; NoSudo=$NoSudo } + Install-Dotnet @DotnetArguments + } + else { + Write-Log -message "dotnet is already installed. Skipping installation." + } + + # Install Windows dependencies if `-Package` or `-BuildWindowsNative` is specified + if ($environment.IsWindows) { + ## The VSCode build task requires 'pwsh.exe' to be found in Path + if (-not (Get-Command -Name pwsh.exe -CommandType Application -ErrorAction Ignore)) + { + Write-Log -message "pwsh.exe not found. Install latest PowerShell release and add it to Path" + $psInstallFile = [System.IO.Path]::Combine($PSScriptRoot, "tools", "install-powershell.ps1") + & $psInstallFile -AddToPath + } + } + } finally { + Pop-Location + } +} + +function Start-CrossGen { + [CmdletBinding()] + param( + [Parameter(Mandatory= $true)] + [ValidateNotNullOrEmpty()] + [String] + $PublishPath, + + [Parameter(Mandatory=$true)] + [ValidateSet("alpine-x64", + "linux-arm", + "linux-arm64", + "linux-x64", + "osx-arm64", + "osx-x64", + "win-arm", + "win-arm64", + "win7-x64", + "win7-x86")] + [string] + $Runtime + ) + + function New-CrossGenAssembly { + param ( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [String[]] + $AssemblyPath, + + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [String] + $CrossgenPath, + + [Parameter(Mandatory = $true)] + [ValidateSet("alpine-x64", + "linux-arm", + "linux-arm64", + "linux-x64", + "osx-arm64", + "osx-x64", + "win-arm", + "win-arm64", + "win7-x64", + "win7-x86")] + [string] + $Runtime + ) + + $platformAssembliesPath = Split-Path $AssemblyPath[0] -Parent + + $targetOS, $targetArch = $Runtime -split '-' + + # Special cases where OS / Arch does not conform with runtime names + switch ($Runtime) { + 'alpine-x64' { + $targetOS = 'linux' + $targetArch = 'x64' + } + 'win-arm' { + $targetOS = 'windows' + $targetArch = 'arm' + } + 'win-arm64' { + $targetOS = 'windows' + $targetArch = 'arm64' + } + 'win7-x64' { + $targetOS = 'windows' + $targetArch = 'x64' + } + 'win7-x86' { + $targetOS = 'windows' + $targetArch = 'x86' + } + } + + $generatePdb = $targetos -eq 'windows' + + # The path to folder must end with directory separator + $dirSep = [System.IO.Path]::DirectorySeparatorChar + $platformAssembliesPath = if (-not $platformAssembliesPath.EndsWith($dirSep)) { $platformAssembliesPath + $dirSep } + + Start-NativeExecution { + $crossgen2Params = @( + "-r" + $platformAssembliesPath + "--out-near-input" + "--single-file-compilation" + "-O" + "--targetos" + $targetOS + "--targetarch" + $targetArch + ) + + if ($generatePdb) { + $crossgen2Params += "--pdb" + } + + $crossgen2Params += $AssemblyPath + + & $CrossgenPath $crossgen2Params + } + } + + if (-not (Test-Path $PublishPath)) { + throw "Path '$PublishPath' does not exist." + } + + # Get the path to crossgen + $crossGenExe = if ($environment.IsWindows) { "crossgen2.exe" } else { "crossgen2" } + + # The crossgen tool is only published for these particular runtimes + $crossGenRuntime = if ($environment.IsWindows) { + # for windows the tool architecture is the host machine architecture, so it is always x64. + # we can cross compile for x86, arm and arm64 + "win-x64" + } else { + $Runtime + } + + if (-not $crossGenRuntime) { + throw "crossgen is not available for this platform" + } + + $dotnetRuntimeVersion = $script:Options.Framework -replace 'net' + + # Get the CrossGen.exe for the correct runtime with the latest version + $crossGenPath = Get-ChildItem $script:Environment.nugetPackagesRoot $crossGenExe -Recurse | ` + Where-Object { $_.FullName -match $crossGenRuntime } | ` + Where-Object { $_.FullName -match $dotnetRuntimeVersion } | ` + Where-Object { (Split-Path $_.FullName -Parent).EndsWith('tools') } | ` + Sort-Object -Property FullName -Descending | ` + Select-Object -First 1 | ` + ForEach-Object { $_.FullName } + if (-not $crossGenPath) { + throw "Unable to find latest version of crossgen2.exe. 'Please run Start-PSBuild -Clean' first, and then try again." + } + Write-Verbose "Matched CrossGen2.exe: $crossGenPath" -Verbose + + # Common assemblies used by Add-Type or assemblies with high JIT and no pdbs to crossgen + $commonAssembliesForAddType = @( + "Microsoft.CodeAnalysis.CSharp.dll" + "Microsoft.CodeAnalysis.dll" + "System.Linq.Expressions.dll" + "Microsoft.CSharp.dll" + "System.Runtime.Extensions.dll" + "System.Linq.dll" + "System.Collections.Concurrent.dll" + "System.Collections.dll" + "Newtonsoft.Json.dll" + "System.IO.FileSystem.dll" + "System.Diagnostics.Process.dll" + "System.Threading.Tasks.Parallel.dll" + "System.Security.AccessControl.dll" + "System.Text.Encoding.CodePages.dll" + "System.Private.Uri.dll" + "System.Threading.dll" + "System.Security.Principal.Windows.dll" + "System.Console.dll" + "Microsoft.Win32.Registry.dll" + "System.IO.Pipes.dll" + "System.Diagnostics.FileVersionInfo.dll" + "System.Collections.Specialized.dll" + "Microsoft.ApplicationInsights.dll" + ) + + $fullAssemblyList = $commonAssembliesForAddType + + $assemblyFullPaths = @() + $assemblyFullPaths += foreach ($assemblyName in $fullAssemblyList) { + Join-Path $PublishPath $assemblyName + } + + New-CrossGenAssembly -CrossgenPath $crossGenPath -AssemblyPath $assemblyFullPaths -Runtime $Runtime + + # + # With the latest dotnet.exe, the default load context is only able to load TPAs, and TPA + # only contains IL assembly names. In order to make the default load context able to load + # the NI PS assemblies, we need to replace the IL PS assemblies with the corresponding NI + # PS assemblies, but with the same IL assembly names. + # + Write-Verbose "PowerShell Ngen assemblies have been generated. Deploying ..." -Verbose + foreach ($assemblyName in $fullAssemblyList) { + + # Remove the IL assembly and its symbols. + $assemblyPath = Join-Path $PublishPath $assemblyName + $symbolsPath = [System.IO.Path]::ChangeExtension($assemblyPath, ".pdb") + + Remove-Item $assemblyPath -Force -ErrorAction Stop + + # Rename the corresponding ni.dll assembly to be the same as the IL assembly + $niAssemblyPath = [System.IO.Path]::ChangeExtension($assemblyPath, "ni.dll") + Rename-Item $niAssemblyPath $assemblyPath -Force -ErrorAction Stop + + # No symbols are available for Microsoft.CodeAnalysis.CSharp.dll, Microsoft.CodeAnalysis.dll, + # Microsoft.CodeAnalysis.VisualBasic.dll, and Microsoft.CSharp.dll. + if ($commonAssembliesForAddType -notcontains $assemblyName) { + Remove-Item $symbolsPath -Force -ErrorAction Stop + } + } +} + +function Use-PSClass { + [CmdletBinding()] + param ( + [Parameter(ValueFromPipeline = $true, Mandatory = $true, Position = 0)] + [string[]]$Logfile, + [Parameter()][switch]$IncludeEmpty, + [Parameter()][switch]$MultipleLog + ) + <# +Convert our test logs to +xunit schema - top level assemblies +Pester conversion +foreach $r in "test-results"."test-suite".results."test-suite" +assembly + name = $r.Description + config-file = log file (this is the only way we can determine between admin/nonadmin log) + test-framework = Pester + environment = top-level "test-results.environment.platform + run-date = date (doesn't exist in pester except for beginning) + run-time = time + time = +#> + + BEGIN { + # CLASSES + class assemblies { + # attributes + [datetime]$timestamp + # child elements + [System.Collections.Generic.List[testAssembly]]$assembly + assemblies() { + $this.timestamp = [datetime]::now + $this.assembly = [System.Collections.Generic.List[testAssembly]]::new() + } + static [assemblies] op_Addition([assemblies]$ls, [assemblies]$rs) { + $newAssembly = [assemblies]::new() + $newAssembly.assembly.AddRange($ls.assembly) + $newAssembly.assembly.AddRange($rs.assembly) + return $newAssembly + } + [string]ToString() { + $sb = [text.stringbuilder]::new() + $sb.AppendLine('' -f $this.timestamp) + foreach ( $a in $this.assembly ) { + $sb.Append("$a") + } + $sb.AppendLine(""); + return $sb.ToString() + } + # use Write-Output to emit these into the pipeline + [array]GetTests() { + return $this.Assembly.collection.test + } + } + + class testAssembly { + # attributes + [string]$name # path to pester file + [string]${config-file} + [string]${test-framework} # Pester + [string]$environment + [string]${run-date} + [string]${run-time} + [decimal]$time + [int]$total + [int]$passed + [int]$failed + [int]$skipped + [int]$errors + testAssembly ( ) { + $this."config-file" = "no config" + $this."test-framework" = "Pester" + $this.environment = $script:environment + $this."run-date" = $script:rundate + $this."run-time" = $script:runtime + $this.collection = [System.Collections.Generic.List[collection]]::new() + } + # child elements + [error[]]$error + [System.Collections.Generic.List[collection]]$collection + [string]ToString() { + $sb = [System.Text.StringBuilder]::new() + $sb.AppendFormat(' ") + if ( $this.error ) { + $sb.AppendLine(" ") + foreach ( $e in $this.error ) { + $sb.AppendLine($e.ToString()) + } + $sb.AppendLine(" ") + } else { + $sb.AppendLine(" ") + } + foreach ( $col in $this.collection ) { + $sb.AppendLine($col.ToString()) + } + $sb.AppendLine(" ") + return $sb.ToString() + } + } + + class collection { + # attributes + [string]$name + [decimal]$time + [int]$total + [int]$passed + [int]$failed + [int]$skipped + # child element + [System.Collections.Generic.List[test]]$test + # constructor + collection () { + $this.test = [System.Collections.Generic.List[test]]::new() + } + [string]ToString() { + $sb = [Text.StringBuilder]::new() + if ( $this.test.count -eq 0 ) { + $sb.AppendLine(" ") + } else { + $sb.AppendFormat(' ' + "`n", + $this.total, $this.passed, $this.failed, $this.skipped, [security.securityelement]::escape($this.name), $this.time) + foreach ( $t in $this.test ) { + $sb.AppendLine(" " + $t.ToString()); + } + $sb.Append(" ") + } + return $sb.ToString() + } + } + + class errors { + [error[]]$error + } + class error { + # attributes + [string]$type + [string]$name + # child elements + [failure]$failure + [string]ToString() { + $sb = [system.text.stringbuilder]::new() + $sb.AppendLine('' -f $this.type, [security.securityelement]::escape($this.Name)) + $sb.AppendLine($this.failure -as [string]) + $sb.AppendLine("") + return $sb.ToString() + } + } + + class cdata { + [string]$text + cdata ( [string]$s ) { $this.text = $s } + [string]ToString() { + return '' + } + } + + class failure { + [string]${exception-type} + [cdata]$message + [cdata]${stack-trace} + failure ( [string]$message, [string]$stack ) { + $this."exception-type" = "Pester" + $this.Message = [cdata]::new($message) + $this."stack-trace" = [cdata]::new($stack) + } + [string]ToString() { + $sb = [text.stringbuilder]::new() + $sb.AppendLine(" ") + $sb.AppendLine(" " + ($this.message -as [string]) + "") + $sb.AppendLine(" " + ($this."stack-trace" -as [string]) + "") + $sb.Append(" ") + return $sb.ToString() + } + } + + enum resultenum { + Pass + Fail + Skip + } + + class trait { + # attributes + [string]$name + [string]$value + } + class traits { + [trait[]]$trait + } + class test { + # attributes + [string]$name + [string]$type + [string]$method + [decimal]$time + [resultenum]$result + # child elements + [trait[]]$traits + [failure]$failure + [cdata]$reason # skip reason + [string]ToString() { + $sb = [text.stringbuilder]::new() + $sb.appendformat(' ") + $sb.AppendLine($this.failure -as [string]) + $sb.append(' ') + } else { + $sb.Append("/>") + } + return $sb.ToString() + } + } + + function convert-pesterlog ( [xml]$x, $logpath, [switch]$includeEmpty ) { + <#$resultMap = @{ + Success = "Pass" + Ignored = "Skip" + Failure = "Fail" + }#> + + $resultMap = @{ + Success = "Pass" + Ignored = "Skip" + Failure = "Fail" + Inconclusive = "Skip" + } + + $configfile = $logpath + $runtime = $x."test-results".time + $environment = $x."test-results".environment.platform + "-" + $x."test-results".environment."os-version" + $rundate = $x."test-results".date + $suites = $x."test-results"."test-suite".results."test-suite" + $assemblies = [assemblies]::new() + foreach ( $suite in $suites ) { + $tCases = $suite.SelectNodes(".//test-case") + # only create an assembly group if we have tests + if ( $tCases.count -eq 0 -and ! $includeEmpty ) { continue } + $tGroup = $tCases | Group-Object result + $total = $tCases.Count + $asm = [testassembly]::new() + $asm.environment = $environment + $asm."run-date" = $rundate + $asm."run-time" = $runtime + $asm.Name = $suite.name + $asm."config-file" = $configfile + $asm.time = $suite.time + $asm.total = $suite.SelectNodes(".//test-case").Count + $asm.Passed = $tGroup| Where-Object -FilterScript {$_.Name -eq "Success"} | ForEach-Object -Process {$_.Count} + $asm.Failed = $tGroup| Where-Object -FilterScript {$_.Name -eq "Failure"} | ForEach-Object -Process {$_.Count} + $asm.Skipped = $tGroup| Where-Object -FilterScript { $_.Name -eq "Ignored" } | ForEach-Object -Process {$_.Count} + $asm.Skipped += $tGroup| Where-Object -FilterScript { $_.Name -eq "Inconclusive" } | ForEach-Object -Process {$_.Count} + $c = [collection]::new() + $c.passed = $asm.Passed + $c.failed = $asm.failed + $c.skipped = $asm.skipped + $c.total = $asm.total + $c.time = $asm.time + $c.name = $asm.name + foreach ( $tc in $suite.SelectNodes(".//test-case")) { + if ( $tc.result -match "Success|Ignored|Failure" ) { + $t = [test]::new() + $t.name = $tc.Name + $t.time = $tc.time + $t.method = $tc.description # the pester actually puts the name of the "it" as description + $t.type = $suite.results."test-suite".description | Select-Object -First 1 + $t.result = $resultMap[$tc.result] + if ( $tc.failure ) { + $t.failure = [failure]::new($tc.failure.message, $tc.failure."stack-trace") + } + $null = $c.test.Add($t) + } + } + $null = $asm.collection.add($c) + $assemblies.assembly.Add($asm) + } + $assemblies + } + + # convert it to our object model + # a simple conversion + function convert-xunitlog { + param ( $x, $logpath ) + $asms = [assemblies]::new() + $asms.timestamp = $x.assemblies.timestamp + foreach ( $assembly in $x.assemblies.assembly ) { + $asm = [testAssembly]::new() + $asm.environment = $assembly.environment + $asm."test-framework" = $assembly."test-framework" + $asm."run-date" = $assembly."run-date" + $asm."run-time" = $assembly."run-time" + $asm.total = $assembly.total + $asm.passed = $assembly.passed + $asm.failed = $assembly.failed + $asm.skipped = $assembly.skipped + $asm.time = $assembly.time + $asm.name = $assembly.name + foreach ( $coll in $assembly.collection ) { + $c = [collection]::new() + $c.name = $coll.name + $c.total = $coll.total + $c.passed = $coll.passed + $c.failed = $coll.failed + $c.skipped = $coll.skipped + $c.time = $coll.time + foreach ( $t in $coll.test ) { + $test = [test]::new() + $test.name = $t.name + $test.type = $t.type + $test.method = $t.method + $test.time = $t.time + $test.result = $t.result + $c.test.Add($test) + } + $null = $asm.collection.add($c) + } + $null = $asms.assembly.add($asm) + } + $asms + } + $Logs = @() + } + + PROCESS { + #### MAIN #### + foreach ( $log in $Logfile ) { + foreach ( $logpath in (Resolve-Path $log).path ) { + Write-Progress "converting file $logpath" + if ( ! $logpath) { throw "Cannot resolve $Logfile" } + $x = [xml](Get-Content -Raw -ReadCount 0 $logpath) + + if ( $x.psobject.properties['test-results'] ) { + $Logs += convert-pesterlog $x $logpath -includeempty:$includeempty + } elseif ( $x.psobject.properties['assemblies'] ) { + $Logs += convert-xunitlog $x $logpath -includeEmpty:$includeEmpty + } else { + Write-Error "Cannot determine log type" + } + } + } + } + + END { + if ( $MultipleLog ) { + $Logs + } else { + $combinedLog = $Logs[0] + for ( $i = 1; $i -lt $logs.count; $i++ ) { + $combinedLog += $Logs[$i] + } + $combinedLog + } + } +} + +function Start-PSPackage { + [CmdletBinding(DefaultParameterSetName='Version',SupportsShouldProcess=$true)] + param( + # PowerShell packages use Semantic Versioning https://semver.org/ + [Parameter(ParameterSetName = "Version")] + [string]$Version, + + [Parameter(ParameterSetName = "ReleaseTag")] + [ValidatePattern("^v\d+\.\d+\.\d+(-\w+(\.\d{1,2})?)?$")] + [ValidateNotNullOrEmpty()] + [string]$ReleaseTag, + + # Package name + [ValidatePattern("^powershell")] + [string]$Name = "powershell", + + # Ubuntu, CentOS, Fedora, macOS, and Windows packages are supported + [ValidateSet("msix", "deb", "osxpkg", "rpm", "msi", "zip", "zip-pdb", "nupkg", "tar", "tar-arm", "tar-arm64", "tar-alpine", "fxdependent", "fxdependent-win-desktop", "min-size")] + [string[]]$Type, + + # Generate windows downlevel package + [ValidateSet("win7-x86", "win7-x64", "win-arm", "win-arm64")] + [ValidateScript({$Environment.IsWindows})] + [string] $WindowsRuntime, + + [ValidateSet('osx-x64', 'osx-arm64')] + [ValidateScript({$Environment.IsMacOS})] + [string] $MacOSRuntime, + + [Switch] $Force, + + [Switch] $SkipReleaseChecks, + + [switch] $NoSudo, + + [switch] $LTS + ) + + DynamicParam { + if ($Type -in ('zip', 'min-size') -or $Type -like 'fxdependent*') { + # Add a dynamic parameter '-IncludeSymbols' when the specified package type is 'zip' only. + # The '-IncludeSymbols' parameter can be used to indicate that the package should only contain powershell binaries and symbols. + $ParameterAttr = New-Object "System.Management.Automation.ParameterAttribute" + $Attributes = New-Object "System.Collections.ObjectModel.Collection``1[System.Attribute]" + $Attributes.Add($ParameterAttr) > $null + + $Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("IncludeSymbols", [switch], $Attributes) + $Dict = New-Object "System.Management.Automation.RuntimeDefinedParameterDictionary" + $Dict.Add("IncludeSymbols", $Parameter) > $null + return $Dict + } + } + + End { + $IncludeSymbols = $null + if ($PSBoundParameters.ContainsKey('IncludeSymbols')) { + Write-Log 'setting IncludeSymbols' + $IncludeSymbols = $PSBoundParameters['IncludeSymbols'] + } + + # Runtime and Configuration settings required by the package + ($Runtime, $Configuration) = if ($WindowsRuntime) { + $WindowsRuntime, "Release" + } elseif ($MacOSRuntime) { + $MacOSRuntime, "Release" + } elseif ($Type -eq "tar-alpine") { + New-PSOptions -Configuration "Release" -Runtime "alpine-x64" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } + } elseif ($Type -eq "tar-arm") { + New-PSOptions -Configuration "Release" -Runtime "Linux-ARM" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } + } elseif ($Type -eq "tar-arm64") { + if ($IsMacOS) { + New-PSOptions -Configuration "Release" -Runtime "osx-arm64" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } + } else { + New-PSOptions -Configuration "Release" -Runtime "Linux-ARM64" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } + } + } else { + New-PSOptions -Configuration "Release" -WarningAction SilentlyContinue | ForEach-Object { $_.Runtime, $_.Configuration } + } + + if ($Environment.IsWindows) { + # Runtime will be one of win7-x64, win7-x86, "win-arm" and "win-arm64" on Windows. + # Build the name suffix for universal win-plat packages. + switch ($Runtime) { + "win-arm" { $NameSuffix = "win-arm32" } + "win-arm64" { $NameSuffix = "win-arm64" } + default { $NameSuffix = $_ -replace 'win\d+', 'win' } + } + } + + if ($Type -eq 'fxdependent') { + $NameSuffix = "win-fxdependent" + Write-Log "Packaging : '$Type'; Packaging Configuration: '$Configuration'" + } elseif ($Type -eq 'fxdependent-win-desktop') { + $NameSuffix = "win-fxdependentWinDesktop" + Write-Log "Packaging : '$Type'; Packaging Configuration: '$Configuration'" + } elseif ($MacOSRuntime) { + $NameSuffix = $MacOSRuntime + } else { + Write-Log "Packaging RID: '$Runtime'; Packaging Configuration: '$Configuration'" + } + + $Script:Options = Get-PSOptions + $actualParams = @() + + $crossGenCorrect = $false + if ($Runtime -match "arm" -or $Type -eq 'min-size') { + ## crossgen doesn't support arm32/64; + ## For the min-size package, we intentionally avoid crossgen. + $crossGenCorrect = $true + } + elseif ($Script:Options.CrossGen) { + $actualParams += '-CrossGen' + $crossGenCorrect = $true + } + + $PSModuleRestoreCorrect = $false + + # Require PSModuleRestore for packaging without symbols + # But Disallow it when packaging with symbols + if (!$IncludeSymbols.IsPresent -and $Script:Options.PSModuleRestore) { + $actualParams += '-PSModuleRestore' + $PSModuleRestoreCorrect = $true + } + elseif ($IncludeSymbols.IsPresent -and !$Script:Options.PSModuleRestore) { + $PSModuleRestoreCorrect = $true + } + else { + $actualParams += '-PSModuleRestore' + } + + $precheckFailed = if ($Type -like 'fxdependent*' -or $Type -eq 'tar-alpine') { + ## We do not check for runtime and crossgen for framework dependent package. + -not $Script:Options -or ## Start-PSBuild hasn't been executed yet + -not $PSModuleRestoreCorrect -or ## Last build didn't specify '-PSModuleRestore' correctly + $Script:Options.Configuration -ne $Configuration -or ## Last build was with configuration other than 'Release' + $Script:Options.Framework -ne $script:netCoreRuntime ## Last build wasn't for CoreCLR + } else { + -not $Script:Options -or ## Start-PSBuild hasn't been executed yet + -not $crossGenCorrect -or ## Last build didn't specify '-CrossGen' correctly + -not $PSModuleRestoreCorrect -or ## Last build didn't specify '-PSModuleRestore' correctly + $Script:Options.Runtime -ne $Runtime -or ## Last build wasn't for the required RID + $Script:Options.Configuration -ne $Configuration -or ## Last build was with configuration other than 'Release' + $Script:Options.Framework -ne $script:netCoreRuntime ## Last build wasn't for CoreCLR + } + + # Make sure the most recent build satisfies the package requirement + if ($precheckFailed) { + # It's possible that the most recent build doesn't satisfy the package requirement but + # an earlier build does. + # It's also possible that the last build actually satisfies the package requirement but + # then `Start-PSPackage` runs from a new PS session or `build.psm1` was reloaded. + # + # In these cases, the user will be asked to build again even though it's technically not + # necessary. However, we want it that way -- being very explict when generating packages. + # This check serves as a simple gate to ensure that the user knows what he is doing, and + # also ensure `Start-PSPackage` does what the user asks/expects, because once packages + # are generated, it'll be hard to verify if they were built from the correct content. + + + $params = @('-Clean') + + # CrossGen cannot be done for framework dependent package as it is runtime agnostic. + if ($Type -notlike 'fxdependent*') { + $params += '-CrossGen' + } + + if (!$IncludeSymbols.IsPresent) { + $params += '-PSModuleRestore' + } + + $actualParams += '-Runtime ' + $Script:Options.Runtime + + if ($Type -eq 'fxdependent') { + $params += '-Runtime', 'fxdependent' + } elseif ($Type -eq 'fxdependent-win-desktop') { + $params += '-Runtime', 'fxdependent-win-desktop' + } else { + $params += '-Runtime', $Runtime + } + + $params += '-Configuration', $Configuration + $actualParams += '-Configuration ' + $Script:Options.Configuration + + Write-Warning "Build started with unexpected parameters 'Start-PSBuild $actualParams" + throw "Please ensure you have run 'Start-PSBuild $params'!" + } + + if ($SkipReleaseChecks.IsPresent) { + Write-Warning "Skipping release checks." + } + elseif (!$Script:Options.RootInfo.IsValid){ + throw $Script:Options.RootInfo.Warning + } + + # If ReleaseTag is specified, use the given tag to calculate Version + if ($PSCmdlet.ParameterSetName -eq "ReleaseTag") { + $Version = $ReleaseTag -Replace '^v' + } + + # Use Git tag if not given a version + if (-not $Version) { + $Version = (git --git-dir="$RepoRoot/.git" describe) -Replace '^v' + } + + $Source = Split-Path -Path $Script:Options.Output -Parent + + # Copy the ThirdPartyNotices.txt so it's part of the package + Copy-Item "$RepoRoot/ThirdPartyNotices.txt" -Destination $Source -Force + + # Copy the default.help.txt so it's part of the package + Copy-Item "$RepoRoot/assets/default.help.txt" -Destination "$Source/en-US" -Force + + # If building a symbols package, we add a zip of the parent to publish + if ($IncludeSymbols.IsPresent) + { + $publishSource = $Source + $buildSource = Split-Path -Path $Source -Parent + $Source = New-TempFolder + $symbolsSource = New-TempFolder + + try + { + # Copy files which go into the root package + Get-ChildItem -Path $publishSource | Copy-Item -Destination $Source -Recurse + + $signingXml = [xml] (Get-Content (Join-Path $PSScriptRoot "..\releaseBuild\signing.xml" -Resolve)) + # Only include the files we sign for compliance scanning, those are the files we build. + $filesToInclude = $signingXml.SignConfigXML.job.file.src | Where-Object { -not $_.endswith('pwsh.exe') -and ($_.endswith(".dll") -or $_.endswith(".exe")) } | ForEach-Object { ($_ -split '\\')[-1] } + $filesToInclude += $filesToInclude | ForEach-Object { $_ -replace '.dll', '.pdb' } + Get-ChildItem -Path $buildSource | Where-Object { $_.Name -in $filesToInclude } | Copy-Item -Destination $symbolsSource -Recurse + + # Zip symbols.zip to the root package + $zipSource = Join-Path $symbolsSource -ChildPath '*' + $zipPath = Join-Path -Path $Source -ChildPath 'symbols.zip' + Save-PSOptions -PSOptionsPath (Join-Path -Path $source -ChildPath 'psoptions.json') -Options $Script:Options + Compress-Archive -Path $zipSource -DestinationPath $zipPath + } + finally + { + Remove-Item -Path $symbolsSource -Recurse -Force -ErrorAction SilentlyContinue + } + } + + Write-Log "Packaging Source: '$Source'" + + # Decide package output type + if (-not $Type) { + $Type = if ($Environment.IsLinux) { + if ($Environment.LinuxInfo.ID -match "ubuntu") { + "deb", "nupkg", "tar" + } elseif ($Environment.IsRedHatFamily) { + "rpm", "nupkg" + } elseif ($Environment.IsSUSEFamily) { + "rpm", "nupkg" + } else { + throw "Building packages for $($Environment.LinuxInfo.PRETTY_NAME) is unsupported!" + } + } elseif ($Environment.IsMacOS) { + "osxpkg", "nupkg", "tar" + } elseif ($Environment.IsWindows) { + "msi", "nupkg", "msix" + } + Write-Warning "-Type was not specified, continuing with $Type!" + } + Write-Log "Packaging Type: $Type" + + # Add the symbols to the suffix + # if symbols are specified to be included + if ($IncludeSymbols.IsPresent -and $NameSuffix) { + $NameSuffix = "symbols-$NameSuffix" + } + elseif ($IncludeSymbols.IsPresent) { + $NameSuffix = "symbols" + } + + switch ($Type) { + "zip" { + $Arguments = @{ + PackageNameSuffix = $NameSuffix + PackageSourcePath = $Source + PackageVersion = $Version + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create Zip Package")) { + New-ZipPackage @Arguments + } + } + "zip-pdb" { + $Arguments = @{ + PackageNameSuffix = $NameSuffix + PackageSourcePath = $Source + PackageVersion = $Version + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create Symbols Zip Package")) { + New-PdbZipPackage @Arguments + } + } + "min-size" { + # Remove symbol files, xml document files. + Remove-Item "$Source\*.pdb", "$Source\*.xml" -Force + + # Add suffix '-gc' because this package is for the Guest Config team. + if ($Environment.IsWindows) { + $Arguments = @{ + PackageNameSuffix = "$NameSuffix-gc" + PackageSourcePath = $Source + PackageVersion = $Version + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create Zip Package")) { + New-ZipPackage @Arguments + } + } + elseif ($Environment.IsLinux) { + $Arguments = @{ + PackageSourcePath = $Source + Name = $Name + PackageNameSuffix = 'gc' + Version = $Version + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { + New-TarballPackage @Arguments + } + } + } + { $_ -like "fxdependent*" } { + ## Remove PDBs from package to reduce size. + if(-not $IncludeSymbols.IsPresent) { + Get-ChildItem $Source -Filter *.pdb | Remove-Item -Force + } + + if ($Environment.IsWindows) { + $Arguments = @{ + PackageNameSuffix = $NameSuffix + PackageSourcePath = $Source + PackageVersion = $Version + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create Zip Package")) { + New-ZipPackage @Arguments + } + } elseif ($Environment.IsLinux) { + $Arguments = @{ + PackageSourcePath = $Source + Name = $Name + PackageNameSuffix = 'fxdependent' + Version = $Version + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { + New-TarballPackage @Arguments + } + } + } + "msix" { + $Arguments = @{ + ProductNameSuffix = $NameSuffix + ProductSourcePath = $Source + ProductVersion = $Version + Architecture = $WindowsRuntime.Split('-')[1] + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create MSIX Package")) { + New-MSIXPackage @Arguments + } + } + 'nupkg' { + $Arguments = @{ + PackageNameSuffix = $NameSuffix + PackageSourcePath = $Source + PackageVersion = $Version + PackageRuntime = $Runtime + PackageConfiguration = $Configuration + Force = $Force + } + + if ($PSCmdlet.ShouldProcess("Create NuPkg Package")) { + New-NugetContentPackage @Arguments + } + } + "tar" { + $Arguments = @{ + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + } + + if ($MacOSRuntime) { + $Arguments['Architecture'] = $MacOSRuntime.Split('-')[1] + } + + if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { + New-TarballPackage @Arguments + } + } + "tar-arm" { + $Arguments = @{ + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + Architecture = "arm32" + ExcludeSymbolicLinks = $true + } + + if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { + New-TarballPackage @Arguments + } + } + "tar-arm64" { + $Arguments = @{ + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + Architecture = "arm64" + ExcludeSymbolicLinks = $true + } + + if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { + New-TarballPackage @Arguments + } + } + "tar-alpine" { + $Arguments = @{ + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + Architecture = "alpine-x64" + ExcludeSymbolicLinks = $true + } + + if ($PSCmdlet.ShouldProcess("Create tar.gz Package")) { + New-TarballPackage @Arguments + } + } + 'deb' { + $Arguments = @{ + Type = 'deb' + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + NoSudo = $NoSudo + LTS = $LTS + } + foreach ($Distro in $Script:DebianDistributions) { + $Arguments["Distribution"] = $Distro + if ($PSCmdlet.ShouldProcess("Create DEB Package for $Distro")) { + New-UnixPackage @Arguments + } + } + } + 'rpm' { + $Arguments = @{ + Type = 'rpm' + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + NoSudo = $NoSudo + LTS = $LTS + } + foreach ($Distro in $Script:RedhatDistributions) { + $Arguments["Distribution"] = $Distro + if ($PSCmdlet.ShouldProcess("Create RPM Package for $Distro")) { + New-UnixPackage @Arguments + } + } + } + default { + $Arguments = @{ + Type = $_ + PackageSourcePath = $Source + Name = $Name + Version = $Version + Force = $Force + NoSudo = $NoSudo + LTS = $LTS + } + + if ($PSCmdlet.ShouldProcess("Create $_ Package")) { + New-UnixPackage @Arguments + } + } + } + + if ($IncludeSymbols.IsPresent) + { + # Source is a temporary folder when -IncludeSymbols is present. So, we should remove it. + Remove-Item -Path $Source -Recurse -Force -ErrorAction SilentlyContinue + } + } +} + +function New-UnixPackage { + [CmdletBinding(SupportsShouldProcess=$true)] + param( + [Parameter(Mandatory)] + [ValidateSet("deb", "osxpkg", "rpm")] + [string]$Type, + + [Parameter(Mandatory)] + [string]$PackageSourcePath, + + # Must start with 'powershell' but may have any suffix + [Parameter(Mandatory)] + [ValidatePattern("^powershell")] + [string]$Name, + + [Parameter(Mandatory)] + [string]$Version, + + # Package iteration version (rarely changed) + # This is a string because strings are appended to it + [string]$Iteration = "1", + + [Switch] + $Force, + + [switch] + $NoSudo, + + [switch] + $LTS, + + [string] + $CurrentLocation = (Get-Location) + ) + + DynamicParam { + if ($Type -eq "deb" -or $Type -eq 'rpm') { + # Add a dynamic parameter '-Distribution' when the specified package type is 'deb'. + # The '-Distribution' parameter can be used to indicate which Debian distro this pacakge is targeting. + $ParameterAttr = New-Object "System.Management.Automation.ParameterAttribute" + if($type -eq 'deb') + { + $ValidateSetAttr = New-Object "System.Management.Automation.ValidateSetAttribute" -ArgumentList $Script:DebianDistributions + } + else + { + $ValidateSetAttr = New-Object "System.Management.Automation.ValidateSetAttribute" -ArgumentList $Script:RedHatDistributions + } + $Attributes = New-Object "System.Collections.ObjectModel.Collection``1[System.Attribute]" + $Attributes.Add($ParameterAttr) > $null + $Attributes.Add($ValidateSetAttr) > $null + + $Parameter = New-Object "System.Management.Automation.RuntimeDefinedParameter" -ArgumentList ("Distribution", [string], $Attributes) + $Dict = New-Object "System.Management.Automation.RuntimeDefinedParameterDictionary" + $Dict.Add("Distribution", $Parameter) > $null + return $Dict + } + } + + End { + # This allows sudo install to be optional; needed when running in containers / as root + # Note that when it is null, Invoke-Expression (but not &) must be used to interpolate properly + $sudo = if (!$NoSudo) { "sudo" } + + # Validate platform + $ErrorMessage = "Must be on {0} to build '$Type' packages!" + switch ($Type) { + "deb" { + $packageVersion = Get-LinuxPackageSemanticVersion -Version $Version + if (!$Environment.IsUbuntu -and !$Environment.IsDebian) { + throw ($ErrorMessage -f "Ubuntu or Debian") + } + + if ($PSBoundParameters.ContainsKey('Distribution')) { + $DebDistro = $PSBoundParameters['Distribution'] + } elseif ($Environment.IsUbuntu16) { + $DebDistro = "ubuntu.16.04" + } elseif ($Environment.IsUbuntu18) { + $DebDistro = "ubuntu.18.04" + } elseif ($Environment.IsUbuntu20) { + $DebDistro = "ubuntu.20.04" + } elseif ($Environment.IsDebian9) { + $DebDistro = "debian.9" + } else { + throw "The current Debian distribution is not supported." + } + + # iteration is "debian_revision" + # usage of this to differentiate distributions is allowed by non-standard + $Iteration += ".$DebDistro" + } + "rpm" { + if ($PSBoundParameters.ContainsKey('Distribution')) { + $DebDistro = $PSBoundParameters['Distribution'] + + } elseif ($Environment.IsRedHatFamily) { + $DebDistro = "rhel.7" + } else { + throw "The current distribution is not supported." + } + + $packageVersion = Get-LinuxPackageSemanticVersion -Version $Version + } + "osxpkg" { + $packageVersion = $Version + if (!$Environment.IsMacOS) { + throw ($ErrorMessage -f "macOS") + } + + $DebDistro = 'macOS' + } + } + + # Determine if the version is a preview version + $IsPreview = Test-IsPreview -Version $Version -IsLTS:$LTS + + # Preview versions have preview in the name + $Name = if($LTS) { + "powershell-lts" + } + elseif ($IsPreview) { + "powershell-preview" + } + else { + "powershell" + } + + # Verify dependencies are installed and in the path + Test-Dependencies + + $Description = $packagingStrings.Description + + # Break the version down into its components, we are interested in the major version + $VersionMatch = [regex]::Match($Version, '(\d+)(?:.(\d+)(?:.(\d+)(?:-preview(?:.(\d+))?)?)?)?') + $MajorVersion = $VersionMatch.Groups[1].Value + + # Suffix is used for side-by-side preview/release package installation + $Suffix = if ($IsPreview) { $MajorVersion + "-preview" } elseif ($LTS) { $MajorVersion + "-lts" } else { $MajorVersion } + + # Setup staging directory so we don't change the original source directory + $Staging = "$PSScriptRoot/staging" + if ($PSCmdlet.ShouldProcess("Create staging folder")) { + New-StagingFolder -StagingPath $Staging -PackageSourcePath $PackageSourcePath + } + + # Follow the Filesystem Hierarchy Standard for Linux and macOS + $Destination = if ($Environment.IsLinux) { + "/opt/microsoft/powershell/$Suffix" + } elseif ($Environment.IsMacOS) { + "/usr/local/microsoft/powershell/$Suffix" + } + + # Destination for symlink to powershell executable + $Link = Get-PwshExecutablePath -IsPreview:$IsPreview + $links = @(New-LinkInfo -LinkDestination $Link -LinkTarget "$Destination/pwsh") + + if($LTS) { + $links += New-LinkInfo -LinkDestination (Get-PwshExecutablePath -IsLTS:$LTS) -LinkTarget "$Destination/pwsh" + } + + if ($PSCmdlet.ShouldProcess("Create package file system")) + { + # Generate After Install and After Remove scripts + $AfterScriptInfo = New-AfterScripts -Link $Link -Distribution $DebDistro -Destination $Destination + + # there is a weird bug in fpm + # if the target of the powershell symlink exists, `fpm` aborts + # with a `utime` error on macOS. + # so we move it to make symlink broken + # refers to executable, does not vary by channel + $symlink_dest = "$Destination/pwsh" + $hack_dest = "./_fpm_symlink_hack_powershell" + if ($Environment.IsMacOS) { + if (Test-Path $symlink_dest) { + Write-Warning "Move $symlink_dest to $hack_dest (fpm utime bug)" + Start-NativeExecution ([ScriptBlock]::Create("$sudo mv $symlink_dest $hack_dest")) + } + } + + # Generate gzip of man file + $ManGzipInfo = New-ManGzip -IsPreview:$IsPreview -IsLTS:$LTS + + # Change permissions for packaging + Write-Log "Setting permissions..." + Start-NativeExecution { + find $Staging -type d | xargs chmod 755 + find $Staging -type f | xargs chmod 644 + chmod 644 $ManGzipInfo.GzipFile + # refers to executable, does not vary by channel + chmod 755 "$Staging/pwsh" #only the executable file should be granted the execution permission + } + } + + # Add macOS powershell launcher + if ($Type -eq "osxpkg") + { + Write-Log "Adding macOS launch application..." + if ($PSCmdlet.ShouldProcess("Add macOS launch application")) + { + # Generate launcher app folder + $AppsFolder = New-MacOSLauncher -Version $Version + } + } + + $packageDependenciesParams = @{} + if ($DebDistro) + { + $packageDependenciesParams['Distribution']=$DebDistro + } + + # Setup package dependencies + $Dependencies = @(Get-PackageDependencies @packageDependenciesParams) + + $Arguments = Get-FpmArguments ` + -Name $Name ` + -Version $packageVersion ` + -Iteration $Iteration ` + -Description $Description ` + -Type $Type ` + -Dependencies $Dependencies ` + -AfterInstallScript $AfterScriptInfo.AfterInstallScript ` + -AfterRemoveScript $AfterScriptInfo.AfterRemoveScript ` + -Staging $Staging ` + -Destination $Destination ` + -ManGzipFile $ManGzipInfo.GzipFile ` + -ManDestination $ManGzipInfo.ManFile ` + -LinkInfo $Links ` + -AppsFolder $AppsFolder ` + -Distribution $DebDistro ` + -ErrorAction Stop + + # Build package + try { + if ($PSCmdlet.ShouldProcess("Create $type package")) { + Write-Log "Creating package with fpm..." + $Output = Start-NativeExecution { fpm $Arguments } + } + } finally { + if ($Environment.IsMacOS) { + Write-Log "Starting Cleanup for mac packaging..." + if ($PSCmdlet.ShouldProcess("Cleanup macOS launcher")) + { + Clear-MacOSLauncher + } + + # this is continuation of a fpm hack for a weird bug + if (Test-Path $hack_dest) { + Write-Warning "Move $hack_dest to $symlink_dest (fpm utime bug)" + Start-NativeExecution -sb ([ScriptBlock]::Create("$sudo mv $hack_dest $symlink_dest")) -VerboseOutputOnError + } + } + if ($AfterScriptInfo.AfterInstallScript) { + Remove-Item -ErrorAction 'silentlycontinue' $AfterScriptInfo.AfterInstallScript -Force + } + if ($AfterScriptInfo.AfterRemoveScript) { + Remove-Item -ErrorAction 'silentlycontinue' $AfterScriptInfo.AfterRemoveScript -Force + } + Remove-Item -Path $ManGzipInfo.GzipFile -Force -ErrorAction SilentlyContinue + } + + # Magic to get path output + $createdPackage = Get-Item (Join-Path $CurrentLocation (($Output[-1] -split ":path=>")[-1] -replace '["{}]')) + + if ($Environment.IsMacOS) { + if ($PSCmdlet.ShouldProcess("Add distribution information and Fix PackageName")) + { + $createdPackage = New-MacOsDistributionPackage -FpmPackage $createdPackage -IsPreview:$IsPreview + } + } + + if (Test-Path $createdPackage) + { + Write-Verbose "Created package: $createdPackage" -Verbose + return $createdPackage + } + else + { + throw "Failed to create $createdPackage" + } + } +} diff --git a/test/perf/benchmarks/powershell-perf.csproj b/test/perf/benchmarks/powershell-perf.csproj new file mode 100644 index 00000000000..93c164b98b8 --- /dev/null +++ b/test/perf/benchmarks/powershell-perf.csproj @@ -0,0 +1,68 @@ + + + + + + + PowerShell Performance Tests + powershell-perf + Exe + + $(NoWarn);CS8002 + true + + AnyCPU + portable + true + + + $(PERF_TARGET_VERSION) + + + + netcoreapp3.1;net5.0;net6.0 + + 7.1.3 + 7.0.6 + + + + true + ../../../src/signing/visualstudiopublic.snk + true + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj new file mode 100644 index 00000000000..92c3f13d290 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/BenchmarkDotNet.Extensions.csproj @@ -0,0 +1,17 @@ + + + + Library + netstandard2.0 + + + + + + + + + + + + diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs new file mode 100644 index 00000000000..48856632317 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/CommandLineOptions.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; + +namespace BenchmarkDotNet.Extensions +{ + public class CommandLineOptions + { + // Find and parse given parameter with expected int value, then remove it and its value from the list of arguments to then pass to BenchmarkDotNet + // Throws ArgumentException if the parameter does not have a value or that value is not parsable as an int + public static List ParseAndRemoveIntParameter(List argsList, string parameter, out int? parameterValue) + { + int parameterIndex = argsList.IndexOf(parameter); + parameterValue = null; + + if (parameterIndex != -1) + { + if (parameterIndex + 1 < argsList.Count && Int32.TryParse(argsList[parameterIndex+1], out int parsedParameterValue)) + { + // remove --partition-count args + parameterValue = parsedParameterValue; + argsList.RemoveAt(parameterIndex+1); + argsList.RemoveAt(parameterIndex); + } + else + { + throw new ArgumentException($"{parameter} must be followed by an integer"); + } + } + + return argsList; + } + + public static List ParseAndRemoveStringsParameter(List argsList, string parameter, out List parameterValue) + { + int parameterIndex = argsList.IndexOf(parameter); + parameterValue = new List(); + + if (parameterIndex + 1 < argsList.Count) + { + while (parameterIndex + 1 < argsList.Count && !argsList[parameterIndex + 1].StartsWith('-')) + { + // remove each filter string and stop when we get to the next argument flag + parameterValue.Add(argsList[parameterIndex + 1]); + argsList.RemoveAt(parameterIndex + 1); + } + } + //We only want to remove the --exclusion-filter if it exists + if (parameterIndex != -1) + { + argsList.RemoveAt(parameterIndex); + } + + return argsList; + } + + public static void ParseAndRemoveBooleanParameter(List argsList, string parameter, out bool parameterValue) + { + int parameterIndex = argsList.IndexOf(parameter); + + if (parameterIndex != -1) + { + argsList.RemoveAt(parameterIndex); + + parameterValue = true; + } + else + { + parameterValue = false; + } + } + + public static void ValidatePartitionParameters(int? count, int? index) + { + // Either count and index must both be specified or neither specified + if (!(count.HasValue == index.HasValue)) + { + throw new ArgumentException("If either --partition-count or --partition-index is specified, both must be specified"); + } + // Check values of count and index parameters + else if (count.HasValue && index.HasValue) + { + if (count < 2) + { + throw new ArgumentException("When specified, value of --partition-count must be greater than 1"); + } + else if (!(index < count)) + { + throw new ArgumentException("Value of --partition-index must be less than --partition-count"); + } + else if (index < 0) + { + throw new ArgumentException("Value of --partition-index must be greater than or equal to 0"); + } + } + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/DiffableDisassemblyExporter.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/DiffableDisassemblyExporter.cs new file mode 100644 index 00000000000..d45977ed5bf --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/DiffableDisassemblyExporter.cs @@ -0,0 +1,90 @@ +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Disassemblers; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; + +namespace BenchmarkDotNet.Extensions +{ + // a simplified copy of internal BDN type: https://github.com/dotnet/BenchmarkDotNet/blob/0445917bf93059f17cb09e7d48cdb5e27a096c37/src/BenchmarkDotNet/Disassemblers/Exporters/GithubMarkdownDisassemblyExporter.cs#L35-L80 + internal static class DiffableDisassemblyExporter + { + private static readonly Lazy> GetSource = new Lazy>(() => GetElementGetter("Source")); + private static readonly Lazy> GetTextRepresentation = new Lazy>(() => GetElementGetter("TextRepresentation")); + + private static readonly Lazy>> Prettify + = new Lazy>>(GetPrettifyMethod); + + internal static string BuildDisassemblyString(DisassemblyResult disassemblyResult, DisassemblyDiagnoserConfig config) + { + StringBuilder sb = new StringBuilder(); + + int methodIndex = 0; + foreach (var method in disassemblyResult.Methods.Where(method => string.IsNullOrEmpty(method.Problem))) + { + sb.AppendLine("```assembly"); + + sb.AppendLine($"; {method.Name}"); + + var pretty = Prettify.Value.Invoke(method, disassemblyResult, config, $"M{methodIndex++:00}"); + + ulong totalSizeInBytes = 0; + foreach (var element in pretty) + { + if (element.Source() is Asm asm) + { + checked + { + totalSizeInBytes += (uint)asm.Instruction.Length; + } + + sb.AppendLine($" {element.TextRepresentation()}"); + } + else // it's a DisassemblyPrettifier.Label (internal type..) + { + sb.AppendLine($"{element.TextRepresentation()}:"); + } + } + + sb.AppendLine($"; Total bytes of code {totalSizeInBytes}"); + sb.AppendLine("```"); + } + + return sb.ToString(); + } + + private static SourceCode Source(this object element) => GetSource.Value.Invoke(element); + + private static string TextRepresentation(this object element) => GetTextRepresentation.Value.Invoke(element); + + private static Func GetElementGetter(string name) + { + var type = typeof(DisassemblyDiagnoser).Assembly.GetType("BenchmarkDotNet.Disassemblers.Exporters.DisassemblyPrettifier"); + + type = type.GetNestedType("Element", BindingFlags.Instance | BindingFlags.NonPublic); + + var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.NonPublic); + + var method = property.GetGetMethod(nonPublic: true); + + var generic = typeof(Func<,>).MakeGenericType(type, typeof(T)); + + var @delegate = method.CreateDelegate(generic); + + return (obj) => (T)@delegate.DynamicInvoke(obj); // cast to (Func) throws + } + + private static Func> GetPrettifyMethod() + { + var type = typeof(DisassemblyDiagnoser).Assembly.GetType("BenchmarkDotNet.Disassemblers.Exporters.DisassemblyPrettifier"); + + var method = type.GetMethod("Prettify", BindingFlags.Static | BindingFlags.NonPublic); + + var @delegate = method.CreateDelegate(typeof(Func>)); + + return (Func>)@delegate; + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/ExclusionFilter.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/ExclusionFilter.cs new file mode 100644 index 00000000000..b3ee453123f --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/ExclusionFilter.cs @@ -0,0 +1,52 @@ +using BenchmarkDotNet.Filters; +using BenchmarkDotNet.Running; +using System; +using System.Collections.Generic; +using System.Text; + +namespace BenchmarkDotNet.Extensions +{ + class ExclusionFilter : IFilter + { + private readonly GlobFilter globFilter; + + public ExclusionFilter(List _filter) + { + if (_filter != null && _filter.Count != 0) + { + globFilter = new GlobFilter(_filter.ToArray()); + } + } + + public bool Predicate(BenchmarkCase benchmarkCase) + { + if(globFilter == null) + { + return true; + } + return !globFilter.Predicate(benchmarkCase); + } + } + + class CategoryExclusionFilter : IFilter + { + private readonly AnyCategoriesFilter filter; + + public CategoryExclusionFilter(List patterns) + { + if (patterns != null) + { + filter = new AnyCategoriesFilter(patterns.ToArray()); + } + } + + public bool Predicate(BenchmarkCase benchmarkCase) + { + if (filter == null) + { + return true; + } + return !filter.Predicate(benchmarkCase); + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/Extensions.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/Extensions.cs new file mode 100644 index 00000000000..9bc477bc4fe --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/Extensions.cs @@ -0,0 +1,26 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Linq; +using BenchmarkDotNet.Reports; + +namespace BenchmarkDotNet.Extensions +{ + public static class SummaryExtensions + { + public static int ToExitCode(this IEnumerable summaries) + { + // an empty summary means that initial filtering and validation did not allow to run + if (!summaries.Any()) + return 1; + + // if anything has failed, it's an error + if (summaries.Any(summary => summary.HasCriticalValidationErrors || summary.Reports.Any(report => !report.BuildResult.IsBuildSuccess || !report.AllMeasurements.Any()))) + return 1; + + return 0; + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/MandatoryCategoryValidator.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/MandatoryCategoryValidator.cs new file mode 100644 index 00000000000..6f84b3f5767 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/MandatoryCategoryValidator.cs @@ -0,0 +1,35 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using BenchmarkDotNet.Validators; + +namespace BenchmarkDotNet.Extensions +{ + /// + /// this class makes sure that every benchmark belongs to a mandatory category + /// categories are used by the CI for filtering + /// + public class MandatoryCategoryValidator : IValidator + { + private readonly ImmutableHashSet _mandatoryCategories; + + public bool TreatsWarningsAsErrors => true; + + public MandatoryCategoryValidator(ImmutableHashSet categories) => _mandatoryCategories = categories; + + public IEnumerable Validate(ValidationParameters validationParameters) + => validationParameters.Benchmarks + .Where(benchmark => !benchmark.Descriptor.Categories.Any(category => _mandatoryCategories.Contains(category))) + .Select(benchmark => benchmark.Descriptor.GetFilterName()) + .Distinct() + .Select(benchmarkId => + new ValidationError( + isCritical: TreatsWarningsAsErrors, + $"{benchmarkId} does not belong to one of the mandatory categories: {string.Join(", ", _mandatoryCategories)}. Use [BenchmarkCategory(Categories.$)]") + ); + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PartitionFilter.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PartitionFilter.cs new file mode 100644 index 00000000000..d7089f6f5a8 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PartitionFilter.cs @@ -0,0 +1,27 @@ +using BenchmarkDotNet.Filters; +using System; +using System.Collections.Generic; +using System.Linq; +using BenchmarkDotNet.Running; + + +public class PartitionFilter : IFilter +{ + private readonly int? _partitionsCount; + private readonly int? _partitionIndex; // indexed from 0 + private int _counter = 0; + + public PartitionFilter(int? partitionCount, int? partitionIndex) + { + _partitionsCount = partitionCount; + _partitionIndex = partitionIndex; + } + + public bool Predicate(BenchmarkCase benchmarkCase) + { + if (!_partitionsCount.HasValue || !_partitionIndex.HasValue) + return true; // the filter is not enabled so it does not filter anything out and can be added to RecommendedConfig + + return _counter++ % _partitionsCount.Value == _partitionIndex.Value; // will return true only for benchmarks that belong to it’s partition + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs new file mode 100644 index 00000000000..86306da342a --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/PerfLabExporter.cs @@ -0,0 +1,115 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Exporters; +using BenchmarkDotNet.Loggers; +using BenchmarkDotNet.Reports; +using Reporting; +using System.Linq; + +namespace BenchmarkDotNet.Extensions +{ + internal class PerfLabExporter : ExporterBase + { + protected override string FileExtension => "json"; + protected override string FileCaption => "perf-lab-report"; + + public PerfLabExporter() + { + } + + public override void ExportToLog(Summary summary, ILogger logger) + { + var reporter = Reporter.CreateReporter(); + + DisassemblyDiagnoser disassemblyDiagnoser = summary.Reports + .FirstOrDefault()? // disassembler was either enabled for all or none of them (so we use the first one) + .BenchmarkCase.Config.GetDiagnosers().OfType().FirstOrDefault(); + + foreach (var report in summary.Reports) + { + var test = new Test(); + test.Name = FullNameProvider.GetBenchmarkName(report.BenchmarkCase); + test.Categories = report.BenchmarkCase.Descriptor.Categories; + + var results = from result in report.AllMeasurements + where result.IterationMode == Engines.IterationMode.Workload && result.IterationStage == Engines.IterationStage.Result + orderby result.LaunchIndex, result.IterationIndex + select new { result.Nanoseconds, result.Operations}; + + var overheadResults = from result in report.AllMeasurements + where result.IsOverhead() && result.IterationStage != Engines.IterationStage.Jitting + orderby result.LaunchIndex, result.IterationIndex + select new { result.Nanoseconds, result.Operations }; + + test.Counters.Add(new Counter + { + Name = "Duration of single invocation", + TopCounter = true, + DefaultCounter = true, + HigherIsBetter = false, + MetricName = "ns", + Results = (from result in results + select result.Nanoseconds / result.Operations).ToList() + }); + test.Counters.Add(new Counter + { + Name = "Overhead invocation", + TopCounter = false, + DefaultCounter = false, + HigherIsBetter = false, + MetricName = "ns", + Results = (from result in overheadResults + select result.Nanoseconds / result.Operations).ToList() + }); + test.Counters.Add(new Counter + { + Name = "Duration", + TopCounter = false, + DefaultCounter = false, + HigherIsBetter = false, + MetricName = "ms", + Results = (from result in results + select result.Nanoseconds).ToList() + }); + + test.Counters.Add(new Counter + { + Name = "Operations", + TopCounter = false, + DefaultCounter = false, + HigherIsBetter = true, + MetricName = "Count", + Results = (from result in results + select (double)result.Operations).ToList() + }); + + foreach (var metric in report.Metrics.Keys) + { + var m = report.Metrics[metric]; + test.Counters.Add(new Counter + { + Name = m.Descriptor.DisplayName, + TopCounter = false, + DefaultCounter = false, + HigherIsBetter = m.Descriptor.TheGreaterTheBetter, + MetricName = m.Descriptor.Unit, + Results = new[] { m.Value } + }); + } + + if (disassemblyDiagnoser != null && disassemblyDiagnoser.Results.TryGetValue(report.BenchmarkCase, out var disassemblyResult)) + { + string disassembly = DiffableDisassemblyExporter.BuildDisassemblyString(disassemblyResult, disassemblyDiagnoser.Config); + test.AdditionalData["disasm"] = disassembly; + } + + reporter.AddTest(test); + } + + logger.WriteLine(reporter.GetJson()); + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs new file mode 100644 index 00000000000..a8aac9700b0 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/RecommendedConfig.cs @@ -0,0 +1,86 @@ +using System.Collections.Immutable; +using System.IO; +using BenchmarkDotNet.Columns; +using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Diagnosers; +using BenchmarkDotNet.Exporters.Json; +using Perfolizer.Horology; +using BenchmarkDotNet.Jobs; +using BenchmarkDotNet.Reports; +using System.Collections.Generic; +using Reporting; +using BenchmarkDotNet.Loggers; +using System.Linq; +using BenchmarkDotNet.Exporters; + +namespace BenchmarkDotNet.Extensions +{ + public static class RecommendedConfig + { + public static IConfig Create( + DirectoryInfo artifactsPath, + ImmutableHashSet mandatoryCategories, + int? partitionCount = null, + int? partitionIndex = null, + List exclusionFilterValue = null, + List categoryExclusionFilterValue = null, + Job job = null, + bool getDiffableDisasm = false) + { + if (job is null) + { + job = Job.Default + .WithWarmupCount(1) // 1 warmup is enough for our purpose + .WithIterationTime(TimeInterval.FromMilliseconds(250)) // the default is 0.5s per iteration, which is slightly too much for us + .WithMinIterationCount(15) + .WithMaxIterationCount(20) // we don't want to run more that 20 iterations + .DontEnforcePowerPlan(); // make sure BDN does not try to enforce High Performance power plan on Windows + + // See https://github.com/dotnet/roslyn/issues/42393 + job = job.WithArguments(new Argument[] { new MsBuildArgument("/p:DebugType=portable") }); + } + + var config = ManualConfig.CreateEmpty() + .AddLogger(ConsoleLogger.Default) // log output to console + .AddValidator(DefaultConfig.Instance.GetValidators().ToArray()) // copy default validators + .AddAnalyser(DefaultConfig.Instance.GetAnalysers().ToArray()) // copy default analysers + .AddExporter(MarkdownExporter.GitHub) // export to GitHub markdown + .AddColumnProvider(DefaultColumnProviders.Instance) // display default columns (method name, args etc) + .AddJob(job.AsDefault()) // tell BDN that this are our default settings + .WithArtifactsPath(artifactsPath.FullName) + .AddDiagnoser(MemoryDiagnoser.Default) // MemoryDiagnoser is enabled by default + .AddFilter(new PartitionFilter(partitionCount, partitionIndex)) + .AddFilter(new ExclusionFilter(exclusionFilterValue)) + .AddFilter(new CategoryExclusionFilter(categoryExclusionFilterValue)) + .AddExporter(JsonExporter.Full) // make sure we export to Json + .AddColumn(StatisticColumn.Median, StatisticColumn.Min, StatisticColumn.Max) + .AddValidator(TooManyTestCasesValidator.FailOnError) + .AddValidator(new UniqueArgumentsValidator()) // don't allow for duplicated arguments #404 + .AddValidator(new MandatoryCategoryValidator(mandatoryCategories)) + .WithSummaryStyle(SummaryStyle.Default.WithMaxParameterColumnWidth(36)); // the default is 20 and trims too aggressively some benchmark results + + if (Reporter.CreateReporter().InLab) + { + config = config.AddExporter(new PerfLabExporter()); + } + + if (getDiffableDisasm) + { + config = config.AddDiagnoser(CreateDisassembler()); + } + + return config; + } + + private static DisassemblyDiagnoser CreateDisassembler() + => new DisassemblyDiagnoser(new DisassemblyDiagnoserConfig( + maxDepth: 1, // TODO: is depth == 1 enough? + formatter: null, // TODO: enable diffable format + printSource: false, // we are not interested in getting C# + printInstructionAddresses: false, // would make the diffing hard, however could be useful to determine alignment + exportGithubMarkdown: false, + exportHtml: false, + exportCombinedDisassemblyReport: false, + exportDiff: false)); + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs new file mode 100644 index 00000000000..cd9c3a424ce --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/TooManyTestCasesValidator.cs @@ -0,0 +1,33 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Linq; +using BenchmarkDotNet.Validators; + +namespace BenchmarkDotNet.Extensions +{ + /// + /// we need to tell our users that having more than 16 test cases per benchmark is a VERY BAD idea + /// + public class TooManyTestCasesValidator : IValidator + { + private const int Limit = 16; + + public static readonly IValidator FailOnError = new TooManyTestCasesValidator(); + + public bool TreatsWarningsAsErrors => true; + + public IEnumerable Validate(ValidationParameters validationParameters) + { + var byDescriptor = validationParameters.Benchmarks.GroupBy(benchmark => (benchmark.Descriptor, benchmark.Job)); // descriptor = type + method + + return byDescriptor.Where(benchmarkCase => benchmarkCase.Count() > Limit).Select(group => + new ValidationError( + isCritical: true, + message: $"{group.Key.Descriptor.Type.Name}.{group.Key.Descriptor.WorkloadMethod.Name} has {group.Count()} test cases. It MUST NOT have more than {Limit} test cases. We don't have infinite amount of time to run all the benchmarks!!", + benchmarkCase: group.First())); + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/UniqueArgumentsValidator.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/UniqueArgumentsValidator.cs new file mode 100644 index 00000000000..0309e1e9065 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/UniqueArgumentsValidator.cs @@ -0,0 +1,42 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using BenchmarkDotNet.Validators; +using System.Collections.Generic; +using System.Linq; +using BenchmarkDotNet.Running; + +namespace BenchmarkDotNet.Extensions +{ + public class UniqueArgumentsValidator : IValidator + { + public bool TreatsWarningsAsErrors => true; + + public IEnumerable Validate(ValidationParameters validationParameters) + => validationParameters.Benchmarks + .Where(benchmark => benchmark.HasArguments || benchmark.HasParameters) + .GroupBy(benchmark => (benchmark.Descriptor.Type, benchmark.Descriptor.WorkloadMethod, benchmark.Job)) + .Where(sameBenchmark => + { + int numberOfUniqueTestCases = sameBenchmark.Distinct(new BenchmarkArgumentsComparer()).Count(); + int numberOfTestCases = sameBenchmark.Count(); + + return numberOfTestCases != numberOfUniqueTestCases; + }) + .Select(duplicate => new ValidationError(true, $"Benchmark Arguments should be unique, {duplicate.Key.Type}.{duplicate.Key.WorkloadMethod} has duplicate arguments.", duplicate.First())); + + private class BenchmarkArgumentsComparer : IEqualityComparer + { + public bool Equals(BenchmarkCase x, BenchmarkCase y) + => Enumerable.SequenceEqual( + x.Parameters.Items.Select(argument => argument.Value), + y.Parameters.Items.Select(argument => argument.Value)); + + public int GetHashCode(BenchmarkCase obj) + => obj.Parameters.Items + .Where(item => item.Value != null) + .Aggregate(seed: 0, (hashCode, argument) => hashCode ^= argument.Value.GetHashCode()); + } + } +} diff --git a/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/ValuesGenerator.cs b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/ValuesGenerator.cs new file mode 100644 index 00000000000..85f5d98af59 --- /dev/null +++ b/test/perf/dotnet-tools/BenchmarkDotNet.Extensions/ValuesGenerator.cs @@ -0,0 +1,148 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; + +namespace BenchmarkDotNet.Extensions +{ + public static class ValuesGenerator + { + private const int Seed = 12345; // we always use the same seed to have repeatable results! + + public static T GetNonDefaultValue() + { + if (typeof(T) == typeof(byte)) // we can't use ArrayOfUniqueValues for byte + return Array(byte.MaxValue).First(value => !value.Equals(default)); + else + return ArrayOfUniqueValues(2).First(value => !value.Equals(default)); + } + + /// + /// does not support byte because there are only 256 unique byte values + /// + public static T[] ArrayOfUniqueValues(int count) + { + // allocate the array first to try to take advantage of memory randomization + // as it's usually the first thing called from GlobalSetup method + // which with MemoryRandomization enabled is the first method called right after allocation + // of random-sized memory by BDN engine + T[] result = new T[count]; + + var random = new Random(Seed); + + var uniqueValues = new HashSet(); + + while (uniqueValues.Count != count) + { + T value = GenerateValue(random); + + if (!uniqueValues.Contains(value)) + uniqueValues.Add(value); + } + + uniqueValues.CopyTo(result); + + return result; + } + + public static T[] Array(int count) + { + var result = new T[count]; + + var random = new Random(Seed); + + if (typeof(T) == typeof(byte) || typeof(T) == typeof(sbyte)) + { + random.NextBytes(Unsafe.As(result)); + } + else + { + for (int i = 0; i < result.Length; i++) + { + result[i] = GenerateValue(random); + } + } + + return result; + } + + public static Dictionary Dictionary(int count) + { + var dictionary = new Dictionary(); + + var random = new Random(Seed); + + while (dictionary.Count != count) + { + TKey key = GenerateValue(random); + + if (!dictionary.ContainsKey(key)) + dictionary.Add(key, GenerateValue(random)); + } + + return dictionary; + } + + private static T GenerateValue(Random random) + { + if (typeof(T) == typeof(char)) + return (T)(object)(char)random.Next(char.MinValue, char.MaxValue); + if (typeof(T) == typeof(short)) + return (T)(object)(short)random.Next(short.MaxValue); + if (typeof(T) == typeof(ushort)) + return (T)(object)(ushort)random.Next(short.MaxValue); + if (typeof(T) == typeof(int)) + return (T)(object)random.Next(); + if (typeof(T) == typeof(uint)) + return (T)(object)(uint)random.Next(); + if (typeof(T) == typeof(long)) + return (T)(object)(long)random.Next(); + if (typeof(T) == typeof(ulong)) + return (T)(object)(ulong)random.Next(); + if (typeof(T) == typeof(float)) + return (T)(object)(float)random.NextDouble(); + if (typeof(T) == typeof(double)) + return (T)(object)random.NextDouble(); + if (typeof(T) == typeof(bool)) + return (T)(object)(random.NextDouble() > 0.5); + if (typeof(T) == typeof(string)) + return (T)(object)GenerateRandomString(random, 1, 50); + if (typeof(T) == typeof(Guid)) + return (T)(object)GenerateRandomGuid(random); + + throw new NotImplementedException($"{typeof(T).Name} is not implemented"); + } + + private static string GenerateRandomString(Random random, int minLength, int maxLength) + { + var length = random.Next(minLength, maxLength); + + var builder = new StringBuilder(length); + for (int i = 0; i < length; i++) + { + var rangeSelector = random.Next(0, 3); + + if (rangeSelector == 0) + builder.Append((char) random.Next('a', 'z')); + else if (rangeSelector == 1) + builder.Append((char) random.Next('A', 'Z')); + else + builder.Append((char) random.Next('0', '9')); + } + + return builder.ToString(); + } + + private static Guid GenerateRandomGuid(Random random) + { + byte[] bytes = new byte[16]; + random.NextBytes(bytes); + return new Guid(bytes); + } + } +} diff --git a/test/perf/dotnet-tools/README.md b/test/perf/dotnet-tools/README.md new file mode 100644 index 00000000000..fa3ce3b2a78 --- /dev/null +++ b/test/perf/dotnet-tools/README.md @@ -0,0 +1,14 @@ +## Tools + +The tools here are copied from [dotnet/performance](https://github.com/dotnet/performance), +the performance testing repository for the .NET runtime and framework libraries. + +- [BenchmarkDotNet.Extensions](https://github.com/dotnet/performance/tree/main/src/harness/BenchmarkDotNet.Extensions) + - It provides the needed extensions for running benchmarks, + such as the `RecommendedConfig` which defines the set of recommended configurations for running the dotnet benchmarks. +- [Reporting](https://github.com/dotnet/performance/tree/main/src/tools/Reporting) + - It provides additional result reporting support + which may be useful to us when running our benchmarks in lab. +- [ResultsComparer](https://github.com/dotnet/performance/tree/main/src/tools/ResultsComparer) + - It's a tool for comparing different benchmark results. + It's very useful to show the regression of new changes by comparing its benchmark results to the baseline results. diff --git a/test/perf/dotnet-tools/Reporting/Build.cs b/test/perf/dotnet-tools/Reporting/Build.cs new file mode 100644 index 00000000000..c98ac254f34 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Build.cs @@ -0,0 +1,31 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Runtime.Serialization; +using System.Text; + +namespace Reporting +{ + public sealed class Build + { + public string Repo { get; set; } + + public string Branch { get; set; } + + public string Architecture { get; set; } + + public string Locale { get; set; } + + public string GitHash { get; set; } + + public string BuildName { get; set; } + + public DateTime TimeStamp { get; set; } + + public Dictionary AdditionalData { get; set; } = new Dictionary(); + } +} diff --git a/test/perf/dotnet-tools/Reporting/Counter.cs b/test/perf/dotnet-tools/Reporting/Counter.cs new file mode 100644 index 00000000000..f97f0771b99 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Counter.cs @@ -0,0 +1,23 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; + +namespace Reporting +{ + public class Counter + { + public string Name { get; set; } + + public bool TopCounter { get; set; } + + public bool DefaultCounter { get; set; } + + public bool HigherIsBetter { get; set; } + + public string MetricName { get; set; } + + public IList Results { get; set; } + } +} diff --git a/test/perf/dotnet-tools/Reporting/EnvironmentProvider.cs b/test/perf/dotnet-tools/Reporting/EnvironmentProvider.cs new file mode 100644 index 00000000000..90d28729284 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/EnvironmentProvider.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Reporting +{ + public class EnvironmentProvider : IEnvironment + { + public string GetEnvironmentVariable(string variable) => Environment.GetEnvironmentVariable(variable); + } +} diff --git a/test/perf/dotnet-tools/Reporting/IEnvironment.cs b/test/perf/dotnet-tools/Reporting/IEnvironment.cs new file mode 100644 index 00000000000..c7dbfb9b002 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/IEnvironment.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Reporting +{ + public interface IEnvironment + { + string GetEnvironmentVariable(string variable); + } +} diff --git a/test/perf/dotnet-tools/Reporting/Os.cs b/test/perf/dotnet-tools/Reporting/Os.cs new file mode 100644 index 00000000000..760142d3137 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Os.cs @@ -0,0 +1,15 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +namespace Reporting +{ + public class Os + { + public string Locale { get; set; } + + public string Architecture { get; set; } + + public string Name { get; set; } + } +} diff --git a/test/perf/dotnet-tools/Reporting/Reporter.cs b/test/perf/dotnet-tools/Reporting/Reporter.cs new file mode 100644 index 00000000000..d99ecfaf47c --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Reporter.cs @@ -0,0 +1,153 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using RuntimeEnvironment = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment; + +namespace Reporting +{ + public class Reporter + { + private Run run; + private Os os; + private Build build; + private List tests = new List(); + protected IEnvironment environment; + + private Reporter() { } + + public void AddTest(Test test) + { + if (tests.Any(t => t.Name.Equals(test.Name))) + throw new Exception($"Duplicate test name, {test.Name}"); + tests.Add(test); + } + + /// + /// Get a Reporter. Relies on environment variables. + /// + /// Optional environment variable provider + /// A Reporter instance or null if the environment is incorrect. + public static Reporter CreateReporter(IEnvironment environment = null) + { + var ret = new Reporter(); + ret.environment = environment == null ? new EnvironmentProvider() : environment; + if (ret.InLab) + { + ret.Init(); + } + + return ret; + } + + private void Init() + { + run = new Run + { + CorrelationId = environment.GetEnvironmentVariable("HELIX_CORRELATION_ID"), + PerfRepoHash = environment.GetEnvironmentVariable("PERFLAB_PERFHASH"), + Name = environment.GetEnvironmentVariable("PERFLAB_RUNNAME"), + Queue = environment.GetEnvironmentVariable("PERFLAB_QUEUE"), + }; + Boolean.TryParse(environment.GetEnvironmentVariable("PERFLAB_HIDDEN"), out bool hidden); + run.Hidden = hidden; + var configs = environment.GetEnvironmentVariable("PERFLAB_CONFIGS"); + if (!String.IsNullOrEmpty(configs)) // configs should be optional. + { + foreach (var kvp in configs.Split(';')) + { + var split = kvp.Split('='); + run.Configurations.Add(split[0], split[1]); + } + } + + os = new Os() + { + Name = $"{RuntimeEnvironment.OperatingSystem} {RuntimeEnvironment.OperatingSystemVersion}", + Architecture = RuntimeInformation.OSArchitecture.ToString(), + Locale = CultureInfo.CurrentUICulture.ToString() + }; + + build = new Build + { + Repo = environment.GetEnvironmentVariable("PERFLAB_REPO"), + Branch = environment.GetEnvironmentVariable("PERFLAB_BRANCH"), + Architecture = environment.GetEnvironmentVariable("PERFLAB_BUILDARCH"), + Locale = environment.GetEnvironmentVariable("PERFLAB_LOCALE"), + GitHash = environment.GetEnvironmentVariable("PERFLAB_HASH"), + BuildName = environment.GetEnvironmentVariable("PERFLAB_BUILDNUM"), + TimeStamp = DateTime.Parse(environment.GetEnvironmentVariable("PERFLAB_BUILDTIMESTAMP")), + }; + build.AdditionalData["productVersion"] = environment.GetEnvironmentVariable("DOTNET_VERSION"); + } + public string GetJson() + { + if (!InLab) + { + return null; + } + var jsonobj = new + { + build, + os, + run, + tests + }; + var settings = new JsonSerializerSettings(); + var resolver = new DefaultContractResolver(); + resolver.NamingStrategy = new CamelCaseNamingStrategy() { ProcessDictionaryKeys = false }; + settings.ContractResolver = resolver; + return JsonConvert.SerializeObject(jsonobj, Formatting.Indented, settings); + } + + public string WriteResultTable() + { + StringBuilder ret = new StringBuilder(); + foreach (var test in tests) + { + var defaultCounter = test.Counters.Single(c => c.DefaultCounter); + var topCounters = test.Counters.Where(c => c.TopCounter && !c.DefaultCounter); + var restCounters = test.Counters.Where(c => !(c.TopCounter || c.DefaultCounter)); + var counterWidth = Math.Max(test.Counters.Max(c => c.Name.Length) + 1, 15); + var resultWidth = Math.Max(test.Counters.Max(c => c.Results.Max().ToString("F3").Length + c.MetricName.Length) + 2, 15); + ret.AppendLine(test.Name); + ret.AppendLine($"{LeftJustify("Metric", counterWidth)}|{LeftJustify("Average",resultWidth)}|{LeftJustify("Min", resultWidth)}|{LeftJustify("Max",resultWidth)}"); + ret.AppendLine($"{new String('-', counterWidth)}|{new String('-', resultWidth)}|{new String('-', resultWidth)}|{new String('-', resultWidth)}"); + + + ret.AppendLine(Print(defaultCounter, counterWidth, resultWidth)); + foreach(var counter in topCounters) + { + ret.AppendLine(Print(counter, counterWidth, resultWidth)); + } + foreach (var counter in restCounters) + { + ret.AppendLine(Print(counter, counterWidth, resultWidth)); + } + } + return ret.ToString(); + } + private string Print(Counter counter, int counterWidth, int resultWidth) + { + string average = $"{counter.Results.Average():F3} {counter.MetricName}"; + string max = $"{counter.Results.Max():F3} {counter.MetricName}"; + string min = $"{counter.Results.Min():F3} {counter.MetricName}"; + return $"{LeftJustify(counter.Name, counterWidth)}|{LeftJustify(average, resultWidth)}|{LeftJustify(min, resultWidth)}|{LeftJustify(max, resultWidth)}"; + } + + private string LeftJustify(string str, int width) + { + return String.Format("{0,-" + width + "}", str); + } + + public bool InLab => environment.GetEnvironmentVariable("PERFLAB_INLAB")?.Equals("1") ?? false; + } +} diff --git a/test/perf/dotnet-tools/Reporting/Reporting.csproj b/test/perf/dotnet-tools/Reporting/Reporting.csproj new file mode 100644 index 00000000000..b11b5e36ec4 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Reporting.csproj @@ -0,0 +1,13 @@ + + + + Library + netstandard2.0 + + + + + + + + diff --git a/test/perf/dotnet-tools/Reporting/Run.cs b/test/perf/dotnet-tools/Reporting/Run.cs new file mode 100644 index 00000000000..d39d30e5801 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Run.cs @@ -0,0 +1,24 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Text; + +namespace Reporting +{ + public class Run + { + public bool Hidden { get; set; } + + public string CorrelationId { get; set; } + + public string PerfRepoHash { get; set; } + + public string Name { get; set; } + + public string Queue { get; set; } + public IDictionary Configurations { get; set; } = new Dictionary(); + } +} diff --git a/test/perf/dotnet-tools/Reporting/Test.cs b/test/perf/dotnet-tools/Reporting/Test.cs new file mode 100644 index 00000000000..e22529de2b1 --- /dev/null +++ b/test/perf/dotnet-tools/Reporting/Test.cs @@ -0,0 +1,43 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Reporting +{ + public class Test + { + public IList Categories { get; set; } = new List(); + + public string Name { get; set; } + public Dictionary AdditionalData { get; set; } = new Dictionary(); + + public IList Counters { get; set; } = new List(); + + public void AddCounter(Counter counter) + { + if (counter.DefaultCounter && Counters.Any(c => c.DefaultCounter)) + { + throw new Exception($"Duplicate default counter, name: ${counter.Name}"); + } + + if (Counters.Any(c => c.Name.Equals(counter.Name))) + { + throw new Exception($"Duplicate counter name, name: ${counter.Name}"); + } + + Counters.Add(counter); + } + + public void AddCounter(IEnumerable counters) + { + foreach (var counter in counters) + AddCounter(counter); + } + } +} diff --git a/test/perf/dotnet-tools/ResultsComparer/CommandLineOptions.cs b/test/perf/dotnet-tools/ResultsComparer/CommandLineOptions.cs new file mode 100644 index 00000000000..90a439f66cc --- /dev/null +++ b/test/perf/dotnet-tools/ResultsComparer/CommandLineOptions.cs @@ -0,0 +1,54 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.IO; +using CommandLine; +using CommandLine.Text; + +namespace ResultsComparer +{ + public class CommandLineOptions + { + [Option("base", HelpText = "Path to the folder/file with base results.")] + public string BasePath { get; set; } + + [Option("diff", HelpText = "Path to the folder/file with diff results.")] + public string DiffPath { get; set; } + + [Option("threshold", Required = true, HelpText = "Threshold for Statistical Test. Examples: 5%, 10ms, 100ns, 1s.")] + public string StatisticalTestThreshold { get; set; } + + [Option("noise", HelpText = "Noise threshold for Statistical Test. The difference for 1.0ns and 1.1ns is 10%, but it's just a noise. Examples: 0.5ns 1ns.", Default = "0.3ns" )] + public string NoiseThreshold { get; set; } + + [Option("top", HelpText = "Filter the diff to top/bottom N results. Optional.")] + public int? TopCount { get; set; } + + [Option("csv", HelpText = "Path to exported CSV results. Optional.")] + public FileInfo CsvPath { get; set; } + + [Option("xml", HelpText = "Path to exported XML results. Optional.")] + public FileInfo XmlPath { get; set; } + + [Option('f', "filter", HelpText = "Filter the benchmarks by name using glob pattern(s). Optional.")] + public IEnumerable Filters { get; set; } + + [Usage(ApplicationAlias = "")] + public static IEnumerable Examples + { + get + { + yield return new Example(@"Compare the results stored in 'C:\results\win' (base) vs 'C:\results\unix' (diff) using 5% threshold.", + new CommandLineOptions { BasePath = @"C:\results\win", DiffPath = @"C:\results\unix", StatisticalTestThreshold = "5%" }); + yield return new Example(@"Compare the results stored in 'C:\results\win' (base) vs 'C:\results\unix' (diff) using 5% threshold and show only top/bottom 10 results.", + new CommandLineOptions { BasePath = @"C:\results\win", DiffPath = @"C:\results\unix", StatisticalTestThreshold = "5%", TopCount = 10 }); + yield return new Example(@"Compare the results stored in 'C:\results\win' (base) vs 'C:\results\unix' (diff) using 5% threshold and 0.5ns noise filter.", + new CommandLineOptions { BasePath = @"C:\results\win", DiffPath = @"C:\results\unix", StatisticalTestThreshold = "5%", NoiseThreshold = "0.5ns" }); + yield return new Example(@"Compare the System.Math benchmark results stored in 'C:\results\ubuntu16' (base) vs 'C:\results\ubuntu18' (diff) using 5% threshold.", + new CommandLineOptions { Filters = new[] { "System.Math*" }, BasePath = @"C:\results\win", DiffPath = @"C:\results\unix", StatisticalTestThreshold = "5%" }); + } + } + } +} diff --git a/test/perf/dotnet-tools/ResultsComparer/DataTransferContracts.cs b/test/perf/dotnet-tools/ResultsComparer/DataTransferContracts.cs new file mode 100644 index 00000000000..94511488efd --- /dev/null +++ b/test/perf/dotnet-tools/ResultsComparer/DataTransferContracts.cs @@ -0,0 +1,133 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +// + +using System.Collections.Generic; +using System.Linq; + +namespace DataTransferContracts // generated with http://json2csharp.com/# +{ + public class ChronometerFrequency + { + public int Hertz { get; set; } + } + + public class HostEnvironmentInfo + { + public string BenchmarkDotNetCaption { get; set; } + public string BenchmarkDotNetVersion { get; set; } + public string OsVersion { get; set; } + public string ProcessorName { get; set; } + public int? PhysicalProcessorCount { get; set; } + public int? PhysicalCoreCount { get; set; } + public int? LogicalCoreCount { get; set; } + public string RuntimeVersion { get; set; } + public string Architecture { get; set; } + public bool? HasAttachedDebugger { get; set; } + public bool? HasRyuJit { get; set; } + public string Configuration { get; set; } + public string JitModules { get; set; } + public string DotNetCliVersion { get; set; } + public ChronometerFrequency ChronometerFrequency { get; set; } + public string HardwareTimerKind { get; set; } + } + + public class ConfidenceInterval + { + public int N { get; set; } + public double Mean { get; set; } + public double StandardError { get; set; } + public int Level { get; set; } + public double Margin { get; set; } + public double Lower { get; set; } + public double Upper { get; set; } + } + + public class Percentiles + { + public double P0 { get; set; } + public double P25 { get; set; } + public double P50 { get; set; } + public double P67 { get; set; } + public double P80 { get; set; } + public double P85 { get; set; } + public double P90 { get; set; } + public double P95 { get; set; } + public double P100 { get; set; } + } + + public class Statistics + { + public int N { get; set; } + public double Min { get; set; } + public double LowerFence { get; set; } + public double Q1 { get; set; } + public double Median { get; set; } + public double Mean { get; set; } + public double Q3 { get; set; } + public double UpperFence { get; set; } + public double Max { get; set; } + public double InterquartileRange { get; set; } + public List LowerOutliers { get; set; } + public List UpperOutliers { get; set; } + public List AllOutliers { get; set; } + public double StandardError { get; set; } + public double Variance { get; set; } + public double StandardDeviation { get; set; } + public double Skewness { get; set; } + public double Kurtosis { get; set; } + public ConfidenceInterval ConfidenceInterval { get; set; } + public Percentiles Percentiles { get; set; } + } + + public class Memory + { + public int Gen0Collections { get; set; } + public int Gen1Collections { get; set; } + public int Gen2Collections { get; set; } + public long TotalOperations { get; set; } + public long BytesAllocatedPerOperation { get; set; } + } + + public class Measurement + { + public string IterationStage { get; set; } + public int LaunchIndex { get; set; } + public int IterationIndex { get; set; } + public long Operations { get; set; } + public double Nanoseconds { get; set; } + } + + public class Benchmark + { + public string DisplayInfo { get; set; } + public object Namespace { get; set; } + public string Type { get; set; } + public string Method { get; set; } + public string MethodTitle { get; set; } + public string Parameters { get; set; } + public string FullName { get; set; } + public Statistics Statistics { get; set; } + public Memory Memory { get; set; } + public List Measurements { get; set; } + + /// + /// this method was not auto-generated by a tool, it was added manually + /// + /// an array of the actual workload results (not warmup, not pilot) + internal double[] GetOriginalValues() + => Measurements + .Where(measurement => measurement.IterationStage == "Result") + .Select(measurement => measurement.Nanoseconds / measurement.Operations) + .ToArray(); + } + + public class BdnResult + { + public string Title { get; set; } + public HostEnvironmentInfo HostEnvironmentInfo { get; set; } + public List Benchmarks { get; set; } + } +} diff --git a/test/perf/dotnet-tools/ResultsComparer/Program.cs b/test/perf/dotnet-tools/ResultsComparer/Program.cs new file mode 100644 index 00000000000..a0c14e0057a --- /dev/null +++ b/test/perf/dotnet-tools/ResultsComparer/Program.cs @@ -0,0 +1,290 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text.RegularExpressions; +using System.Threading; +using System.Xml; +using Perfolizer.Mathematics.Multimodality; +using Perfolizer.Mathematics.SignificanceTesting; +using Perfolizer.Mathematics.Thresholds; +using CommandLine; +using DataTransferContracts; +using MarkdownLog; +using Newtonsoft.Json; + +namespace ResultsComparer +{ + public sealed class Program + { + private const string FullBdnJsonFileExtension = "full.json"; + + public static void Main(string[] args) + { + // we print a lot of numbers here and we want to make it always in invariant way + Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; + + Parser.Default.ParseArguments(args).WithParsed(Compare); + } + + private static void Compare(CommandLineOptions args) + { + if (!Threshold.TryParse(args.StatisticalTestThreshold, out var testThreshold)) + { + Console.WriteLine($"Invalid Threshold {args.StatisticalTestThreshold}. Examples: 5%, 10ms, 100ns, 1s."); + return; + } + if (!Threshold.TryParse(args.NoiseThreshold, out var noiseThreshold)) + { + Console.WriteLine($"Invalid Noise Threshold {args.NoiseThreshold}. Examples: 0.3ns 1ns."); + return; + } + + var notSame = GetNotSameResults(args, testThreshold, noiseThreshold).ToArray(); + + if (!notSame.Any()) + { + Console.WriteLine($"No differences found between the benchmark results with threshold {testThreshold}."); + return; + } + + PrintSummary(notSame); + + PrintTable(notSame, EquivalenceTestConclusion.Slower, args); + PrintTable(notSame, EquivalenceTestConclusion.Faster, args); + + ExportToCsv(notSame, args.CsvPath); + ExportToXml(notSame, args.XmlPath); + } + + private static IEnumerable<(string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion)> GetNotSameResults(CommandLineOptions args, Threshold testThreshold, Threshold noiseThreshold) + { + foreach ((string id, Benchmark baseResult, Benchmark diffResult) in ReadResults(args) + .Where(result => result.baseResult.Statistics != null && result.diffResult.Statistics != null)) // failures + { + var baseValues = baseResult.GetOriginalValues(); + var diffValues = diffResult.GetOriginalValues(); + + var userTresholdResult = StatisticalTestHelper.CalculateTost(MannWhitneyTest.Instance, baseValues, diffValues, testThreshold); + if (userTresholdResult.Conclusion == EquivalenceTestConclusion.Same) + continue; + + var noiseResult = StatisticalTestHelper.CalculateTost(MannWhitneyTest.Instance, baseValues, diffValues, noiseThreshold); + if (noiseResult.Conclusion == EquivalenceTestConclusion.Same) + continue; + + yield return (id, baseResult, diffResult, userTresholdResult.Conclusion); + } + } + + private static void PrintSummary((string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion)[] notSame) + { + var better = notSame.Where(result => result.conclusion == EquivalenceTestConclusion.Faster); + var worse = notSame.Where(result => result.conclusion == EquivalenceTestConclusion.Slower); + var betterCount = better.Count(); + var worseCount = worse.Count(); + + // If the baseline doesn't have the same set of tests, you wind up with Infinity in the list of diffs. + // Exclude them for purposes of geomean. + worse = worse.Where(x => GetRatio(x) != double.PositiveInfinity); + better = better.Where(x => GetRatio(x) != double.PositiveInfinity); + + Console.WriteLine("summary:"); + + if (betterCount > 0) + { + var betterGeoMean = Math.Pow(10, better.Skip(1).Aggregate(Math.Log10(GetRatio(better.First())), (x, y) => x + Math.Log10(GetRatio(y))) / better.Count()); + Console.WriteLine($"better: {betterCount}, geomean: {betterGeoMean:F3}"); + } + + if (worseCount > 0) + { + var worseGeoMean = Math.Pow(10, worse.Skip(1).Aggregate(Math.Log10(GetRatio(worse.First())), (x, y) => x + Math.Log10(GetRatio(y))) / worse.Count()); + Console.WriteLine($"worse: {worseCount}, geomean: {worseGeoMean:F3}"); + } + + Console.WriteLine($"total diff: {notSame.Length}"); + Console.WriteLine(); + } + + private static void PrintTable((string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion)[] notSame, EquivalenceTestConclusion conclusion, CommandLineOptions args) + { + var data = notSame + .Where(result => result.conclusion == conclusion) + .OrderByDescending(result => GetRatio(conclusion, result.baseResult, result.diffResult)) + .Take(args.TopCount ?? int.MaxValue) + .Select(result => new + { + Id = result.id.Length > 80 ? result.id.Substring(0, 80) : result.id, + DisplayValue = GetRatio(conclusion, result.baseResult, result.diffResult), + BaseMedian = result.baseResult.Statistics.Median, + DiffMedian = result.diffResult.Statistics.Median, + Modality = GetModalInfo(result.baseResult) ?? GetModalInfo(result.diffResult) + }) + .ToArray(); + + if (!data.Any()) + { + Console.WriteLine($"No {conclusion} results for the provided threshold = {args.StatisticalTestThreshold} and noise filter = {args.NoiseThreshold}."); + Console.WriteLine(); + return; + } + + var table = data.ToMarkdownTable().WithHeaders(conclusion.ToString(), conclusion == EquivalenceTestConclusion.Faster ? "base/diff" : "diff/base", "Base Median (ns)", "Diff Median (ns)", "Modality"); + + foreach (var line in table.ToMarkdown().Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries)) + Console.WriteLine($"| {line.TrimStart()}|"); // the table starts with \t and does not end with '|' and it looks bad so we fix it + + Console.WriteLine(); + } + + private static IEnumerable<(string id, Benchmark baseResult, Benchmark diffResult)> ReadResults(CommandLineOptions args) + { + var baseFiles = GetFilesToParse(args.BasePath); + var diffFiles = GetFilesToParse(args.DiffPath); + + if (!baseFiles.Any() || !diffFiles.Any()) + throw new ArgumentException($"Provided paths contained no {FullBdnJsonFileExtension} files."); + + var baseResults = baseFiles.Select(ReadFromFile); + var diffResults = diffFiles.Select(ReadFromFile); + + var filters = args.Filters.Select(pattern => new Regex(WildcardToRegex(pattern), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant)).ToArray(); + + var benchmarkIdToDiffResults = diffResults + .SelectMany(result => result.Benchmarks) + .Where(benchmarkResult => !filters.Any() || filters.Any(filter => filter.IsMatch(benchmarkResult.FullName))) + .ToDictionary(benchmarkResult => benchmarkResult.FullName, benchmarkResult => benchmarkResult); + + return baseResults + .SelectMany(result => result.Benchmarks) + .ToDictionary(benchmarkResult => benchmarkResult.FullName, benchmarkResult => benchmarkResult) // we use ToDictionary to make sure the results have unique IDs + .Where(baseResult => benchmarkIdToDiffResults.ContainsKey(baseResult.Key)) + .Select(baseResult => (baseResult.Key, baseResult.Value, benchmarkIdToDiffResults[baseResult.Key])); + } + + private static void ExportToCsv((string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion)[] notSame, FileInfo csvPath) + { + if (csvPath == null) + return; + + if (csvPath.Exists) + csvPath.Delete(); + + using (var textWriter = csvPath.CreateText()) + { + foreach (var (id, baseResult, diffResult, conclusion) in notSame) + { + textWriter.WriteLine($"\"{id.Replace("\"", "\"\"")}\";base;{conclusion};{string.Join(';', baseResult.GetOriginalValues())}"); + textWriter.WriteLine($"\"{id.Replace("\"", "\"\"")}\";diff;{conclusion};{string.Join(';', diffResult.GetOriginalValues())}"); + } + } + + Console.WriteLine($"CSV results exported to {csvPath.FullName}"); + } + + private static void ExportToXml((string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion)[] notSame, FileInfo xmlPath) + { + if (xmlPath == null) + { + Console.WriteLine("No file given"); + return; + } + + if (xmlPath.Exists) + xmlPath.Delete(); + + using (XmlWriter writer = XmlWriter.Create(xmlPath.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))) + { + writer.WriteStartElement("performance-tests"); + foreach (var (id, baseResult, diffResult, conclusion) in notSame.Where(x => x.conclusion == EquivalenceTestConclusion.Slower)) + { + writer.WriteStartElement("test"); + writer.WriteAttributeString("name", id); + writer.WriteAttributeString("type", baseResult.Type); + writer.WriteAttributeString("method", baseResult.Method); + writer.WriteAttributeString("time", "0"); + writer.WriteAttributeString("result", "Fail"); + writer.WriteStartElement("failure"); + writer.WriteAttributeString("exception-type", "Regression"); + writer.WriteElementString("message", $"{id} has regressed, was {baseResult.Statistics.Median} is {diffResult.Statistics.Median}."); + writer.WriteEndElement(); + } + + foreach (var (id, baseResult, diffResult, conclusion) in notSame.Where(x => x.conclusion == EquivalenceTestConclusion.Faster)) + { + writer.WriteStartElement("test"); + writer.WriteAttributeString("name", id); + writer.WriteAttributeString("type", baseResult.Type); + writer.WriteAttributeString("method", baseResult.Method); + writer.WriteAttributeString("time", "0"); + writer.WriteAttributeString("result", "Skip"); + writer.WriteElementString("reason", $"{id} has improved, was {baseResult.Statistics.Median} is {diffResult.Statistics.Median}."); + writer.WriteEndElement(); + } + + writer.WriteEndElement(); + writer.Flush(); + } + + Console.WriteLine($"XML results exported to {xmlPath.FullName}"); + } + + private static string[] GetFilesToParse(string path) + { + if (Directory.Exists(path)) + return Directory.GetFiles(path, $"*{FullBdnJsonFileExtension}", SearchOption.AllDirectories); + else if (File.Exists(path) || !path.EndsWith(FullBdnJsonFileExtension)) + return new[] { path }; + else + throw new FileNotFoundException($"Provided path does NOT exist or is not a {path} file", path); + } + + // code and magic values taken from BenchmarkDotNet.Analysers.MultimodalDistributionAnalyzer + // See http://www.brendangregg.com/FrequencyTrails/modes.html + private static string GetModalInfo(Benchmark benchmark) + { + if (benchmark.Statistics.N < 12) // not enough data to tell + return null; + + double mValue = MValueCalculator.Calculate(benchmark.GetOriginalValues()); + if (mValue > 4.2) + return "multimodal"; + else if (mValue > 3.2) + return "bimodal"; + else if (mValue > 2.8) + return "several?"; + + return null; + } + + private static double GetRatio((string id, Benchmark baseResult, Benchmark diffResult, EquivalenceTestConclusion conclusion) item) => GetRatio(item.conclusion, item.baseResult, item.diffResult); + + private static double GetRatio(EquivalenceTestConclusion conclusion, Benchmark baseResult, Benchmark diffResult) + => conclusion == EquivalenceTestConclusion.Faster + ? baseResult.Statistics.Median / diffResult.Statistics.Median + : diffResult.Statistics.Median / baseResult.Statistics.Median; + + private static BdnResult ReadFromFile(string resultFilePath) + { + try + { + return JsonConvert.DeserializeObject(File.ReadAllText(resultFilePath)); + } + catch (JsonSerializationException) + { + Console.WriteLine($"Exception while reading the {resultFilePath} file."); + + throw; + } + } + + // https://stackoverflow.com/a/6907849/5852046 not perfect but should work for all we need + private static string WildcardToRegex(string pattern) => $"^{Regex.Escape(pattern).Replace(@"\*", ".*").Replace(@"\?", ".")}$"; + } +} diff --git a/test/perf/dotnet-tools/ResultsComparer/README.md b/test/perf/dotnet-tools/ResultsComparer/README.md new file mode 100644 index 00000000000..109ba901422 --- /dev/null +++ b/test/perf/dotnet-tools/ResultsComparer/README.md @@ -0,0 +1,41 @@ +# Results Comparer + +This simple tool allows for easy comparison of provided benchmark results. + +It can be used to compare: +* historical results (eg. before and after my changes) +* results for different OSes (eg. Windows vs Ubuntu) +* results for different CPU architectures (eg. x64 vs ARM64) +* results for different target frameworks (eg. .NET Core 3.1 vs 5.0) + +All you need to provide is: +* `--base` - path to folder/file with baseline results +* `--diff` - path to folder/file with diff results +* `--threshold` - threshold for Statistical Test. Examples: 5%, 10ms, 100ns, 1s + +Optional arguments: +* `--top` - filter the diff to top/bottom `N` results +* `--noise` - noise threshold for Statistical Test. The difference for 1.0ns and 1.1ns is 10%, but it's just a noise. Examples: 0.5ns 1ns. The default value is 0.3ns. +* `--csv` - path to exported CSV results. Optional. +* `-f|--filter` - filter the benchmarks by name using glob pattern(s). Optional. + +Sample: compare the results stored in `C:\results\windows` vs `C:\results\ubuntu` using `1%` threshold and print only TOP 10. + +```cmd +dotnet run --base "C:\results\windows" --diff "C:\results\ubuntu" --threshold 1% --top 10 +``` + +**Note**: the tool supports only `*full.json` results exported by BenchmarkDotNet. This exporter is enabled by default in this repository. + +## Sample results + +| Slower | diff/base | Base Median (ns) | Diff Median (ns) | Modality| +| --------------------------------------------------------------- | ---------:| ----------------:| ----------------:| -------:| +| PerfLabTests.BlockCopyPerf.CallBlockCopy(numElements: 100) | 1.60 | 9.22 | 14.76 | | +| System.Tests.Perf_String.Trim_CharArr(s: "Test", c: [' ', ' ']) | 1.41 | 6.18 | 8.72 | | + +| Faster | base/diff | Base Median (ns) | Diff Median (ns) | Modality| +| ----------------------------------- | ---------:| ----------------:| ----------------:| -------:| +| System.Tests.Perf_Array.ArrayCopy3D | 1.31 | 372.71 | 284.73 | | + +If there is no difference or if there is no match (we use full benchmark names to match the benchmarks), then the results are omitted. diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj new file mode 100644 index 00000000000..af366fa52e5 --- /dev/null +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.csproj @@ -0,0 +1,15 @@ + + + Exe + $(PERFLAB_TARGET_FRAMEWORKS) + net5.0 + preview + + + + + + + + + diff --git a/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.sln b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.sln new file mode 100644 index 00000000000..951a4d0fb5d --- /dev/null +++ b/test/perf/dotnet-tools/ResultsComparer/ResultsComparer.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResultsComparer", "ResultsComparer.csproj", "{00859394-44F8-466B-8624-41578CA94009}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {00859394-44F8-466B-8624-41578CA94009}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {00859394-44F8-466B-8624-41578CA94009}.Debug|Any CPU.Build.0 = Debug|Any CPU + {00859394-44F8-466B-8624-41578CA94009}.Release|Any CPU.ActiveCfg = Release|Any CPU + {00859394-44F8-466B-8624-41578CA94009}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal diff --git a/test/perf/perf.psm1 b/test/perf/perf.psm1 new file mode 100644 index 00000000000..5b1ab239160 --- /dev/null +++ b/test/perf/perf.psm1 @@ -0,0 +1,207 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +$repoRoot = git rev-parse --show-toplevel +Import-Module "$repoRoot/build.psm1" + +function Start-Benchmarking +{ + <# + .SYNOPSIS + Start a benchmark run. + + .PARAMETER TargetPSVersion + The version of 'Microsoft.PowerShell.SDK' package that we want the benchmark to target. + The supported versions are 7.0.x and above, including preview versions. + + .PARAMETER TargetFramework + The target framework to run benchmarks against. + + .PARAMETER List + List the available benchmarks, in either 'flat' or 'tree' views. + + .PARAMETER Runtime + Run benchmarks against multiple .NET runtimes. + + .PARAMETER Filter + One or more wildcard patterns to filter the benchmarks to be executed or to be listed. + + .PARAMETER Artifacts + Path to the folder where you want to store the artifacts produced from running benchmarks. + + .PARAMETER KeepFiles + Indicates to keep all temporary files produced for running benchmarks. + #> + [CmdletBinding(DefaultParameterSetName = 'TargetFramework')] + param( + [Parameter(ParameterSetName = 'TargetPSVersion')] + [ValidatePattern( + '^7\.(0|1|2)\.\d+(-preview\.\d{1,2})?$', + ErrorMessage = 'The package version is invalid or not supported')] + [string] $TargetPSVersion, + + [Parameter(ParameterSetName = 'TargetFramework')] + [ValidateSet('netcoreapp3.1', 'net5.0', 'net6.0')] + [string] $TargetFramework = 'net6.0', + + [Parameter(ParameterSetName = 'TargetFramework')] + [ValidateSet('flat', 'tree')] + [string] $List, + + [Parameter(Mandatory, ParameterSetName = 'Runtimes')] + [ValidateSet('netcoreapp3.1', 'net5.0', 'net6.0')] + [string[]] $Runtime, + + [string[]] $Filter = '*', + [string] $Artifacts, + [switch] $KeepFiles + ) + + Begin { + Find-Dotnet + + if ($Artifacts) { + $Artifacts = $PSCmdlet.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Artifacts) + } else { + $Artifacts = Join-Path $PSScriptRoot 'BenchmarkDotNet.Artifacts' + } + + if (Test-Path -Path $Artifacts) { + Remove-Item -Path $Artifacts -Recurse -Force -ErrorAction Stop + } + + if ($Runtime) { + ## Remove duplicate values. + $hash = [ordered]@{} + foreach ($item in $Runtime) { + if (-not $hash.Contains($item)) { + $hash.Add($item, $null) + } + } + $Runtime = $hash.Keys + } + } + + End { + try { + Push-Location -Path "$PSScriptRoot/benchmarks" + $savedOFS = $OFS; $OFS = $null + + ## Aggregate BDN arguments. + $runArgs = @('--filter') + foreach ($entry in $Filter) { $runArgs += $entry } + $runArgs += '--artifacts', $Artifacts + $runArgs += '--envVars', 'POWERSHELL_TELEMETRY_OPTOUT:1' + + if ($List) { $runArgs += '--list', $List } + if ($KeepFiles) { $runArgs += "--keepFiles" } + + switch ($PSCmdlet.ParameterSetName) { + 'TargetPSVersion' { + Write-Log -message "Run benchmarks targeting '$TargetFramework' and the 'Microsoft.PowerShell.SDK' version '$TargetPSVersion' ..." + $env:PERF_TARGET_VERSION = $TargetPSVersion + + ## Use 'Release' instead of 'release' (note the capital case) because BDN uses 'Release' when building the auto-generated + ## project, and MSBuild somehow recognizes 'release' and 'Release' as two different configurations and thus will rebuild + ## all dependencies unnecessarily. + dotnet run -c Release -f $TargetFramework $runArgs + } + + 'TargetFramework' { + $message = if ($TargetFramework -eq 'net6.0') { 'the current PowerShell code base ...' } else { "the corresponding latest version of 'Microsoft.PowerShell.SDK' ..." } + Write-Log -message "Run benchmarks targeting '$TargetFramework' and $message" + + ## Use 'Release' instead of 'release' (note the capital case) because BDN uses 'Release' when building the auto-generated + ## project, and MSBuild somehow recognizes 'release' and 'Release' as two different configurations and thus will rebuild + ## all dependencies unnecessarily. + dotnet run -c Release -f $TargetFramework $runArgs + } + + 'Runtimes' { + Write-Log -message "Run benchmarks targeting multiple .NET runtimes: $Runtime ..." + + ## Use 'Release' instead of 'release' (note the capital case) because BDN uses 'Release' when building the auto-generated + ## project, and MSBuild somehow recognizes 'release' and 'Release' as two different configurations and thus will rebuild + ## all dependencies unnecessarily. + dotnet run -c Release -f net6.0 --runtimes $Runtime $runArgs + } + } + + if (Test-Path $Artifacts) { + Write-Log -message "`nBenchmark artifacts can be found at $Artifacts" + } + } + finally { + $OFS = $savedOFS + $env:PERF_TARGET_VERSION = $null + Pop-Location + } + } +} + +function Compare-BenchmarkResult +{ + <# + .SYNOPSIS + Compare two benchmark run results to find possible regressions. + + When running benchmarks with 'Start-Benchmarking', you can define the result folder + where to save the artifacts by specifying '-Artifacts'. + + To compare two benchmark run results, you need to specify the result folder paths + for both runs, one as the base and one as the diff. + + .PARAMETER BaseResultPath + Path to the benchmark result used as baseline. + + .PARAMETER DiffResultPath + Path to the benchmark result to be compared with the baseline. + + .PARAMETER Threshold + Threshold for Statistical Test. Examples: 5%, 10ms, 100ns, 1s + + .PARAMETER Noise + Noise threshold for Statistical Test. + The difference for 1.0ns and 1.1ns is 10%, but it's really just noise. Examples: 0.5ns 1ns. + The default value is 0.3ns. + + .PARAMETER Top + Filter the diff to top `N` results + #> + param( + [Parameter(Mandatory)] + [string] $BaseResultPath, + + [Parameter(Mandatory)] + [string] $DiffResultPath, + + [Parameter(Mandatory)] + [ValidatePattern('^\d{1,2}%$|^\d+(ms|ns|s)$')] + [string] $Threshold, + + [ValidatePattern('^(\d\.)?\d+(ms|ns|s)$')] + [string] $Noise, + + [ValidateRange(1, 100)] + [int] $Top + ) + + Find-Dotnet + + try { + Push-Location -Path "$PSScriptRoot/dotnet-tools/ResultsComparer" + $savedOFS = $OFS; $OFS = $null + + $runArgs = @() + if ($Noise) { $runArgs += "--noise $Noise" } + if ($Top -gt 0) { $runArgs += "--top $Top" } + + dotnet run -c Release --base $BaseResultPath --diff $DiffResultPath --threshold $Threshold "$runArgs" + } + finally { + $OFS = $savedOFS + Pop-Location + } +} + +Export-ModuleMember -Function 'Start-Benchmarking', 'Compare-BenchmarkResult' diff --git a/test/powershell/Host/Base-Directory.Tests.ps1 b/test/powershell/Host/Base-Directory.Tests.ps1 index a55af971f09..203d214e937 100644 --- a/test/powershell/Host/Base-Directory.Tests.ps1 +++ b/test/powershell/Host/Base-Directory.Tests.ps1 @@ -44,7 +44,7 @@ Describe "Configuration file locations" -tags "CI","Slow" { } It @ItArgs "PSModulePath should contain the correct path" { - $env:PSModulePath = "" + $env:PSModulePath = $null $actual = & $powershell -noprofile -c `$env:PSModulePath $actual | Should -Match ([regex]::Escape($expectedModule)) } @@ -94,7 +94,7 @@ Describe "Configuration file locations" -tags "CI","Slow" { } It @ItArgs "PSModulePath should respect XDG_DATA_HOME" { - $env:PSModulePath = "" + $env:PSModulePath = $null $env:XDG_DATA_HOME = $TestDrive $expected = [IO.Path]::Combine($TestDrive, "powershell", "Modules") $actual = & $powershell -noprofile -c `$env:PSModulePath diff --git a/test/powershell/Host/ConsoleHost.Tests.ps1 b/test/powershell/Host/ConsoleHost.Tests.ps1 index 390b461fb90..735c0a39682 100644 --- a/test/powershell/Host/ConsoleHost.Tests.ps1 +++ b/test/powershell/Host/ConsoleHost.Tests.ps1 @@ -24,6 +24,7 @@ Describe 'minishell for native executables' -Tag 'CI' { } It 'gets the error stream from minishell' { + $PSNativeCommandUseErrorActionPreference = $false $output = & $powershell -noprofile { Write-Error 'foo' } 2>&1 ($output | Measure-Object).Count | Should -Be 1 $output | Should -BeOfType System.Management.Automation.ErrorRecord @@ -92,6 +93,10 @@ Describe "ConsoleHost unit tests" -tags "Feature" { } It "Clear-Host does not injects data into PowerShell output stream" { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "ARM64 runs in non-interactively mode and Clear-Host does not work." + } + & { Clear-Host; 'hi' } | Should -BeExactly 'hi' } @@ -147,21 +152,32 @@ Describe "ConsoleHost unit tests" -tags "Feature" { } It "-File should be default parameter" { - Set-Content -Path $testdrive/test -Value "'hello'" - $observed = & $powershell -NoProfile $testdrive/test + Set-Content -Path $testdrive/test.ps1 -Value "'hello'" + $observed = & $powershell -NoProfile $testdrive/test.ps1 $observed | Should -Be "hello" } - It "-File accepts scripts with and without .ps1 extension: " -TestCases @( - @{Filename="test.ps1"}, - @{Filename="test"} - ) { - param($Filename) + It "-File accepts scripts with .ps1 extension" { + $Filename = 'test.ps1' Set-Content -Path $testdrive/$Filename -Value "'hello'" $observed = & $powershell -NoProfile -File $testdrive/$Filename $observed | Should -Be "hello" } + It "-File accepts scripts without .ps1 extension to support shebang" -Skip:($IsWindows) { + $Filename = 'test.xxx' + Set-Content -Path $testdrive/$Filename -Value "'hello'" + $observed = & $powershell -NoProfile -File $testdrive/$Filename + $observed | Should -Be "hello" + } + + It "-File should fail for script without .ps1 extension" -Skip:(!$IsWindows) { + $Filename = 'test.xxx' + Set-Content -Path $testdrive/$Filename -Value "'hello'" + & $powershell -NoProfile -File $testdrive/$Filename 2>&1 $null + $LASTEXITCODE | Should -Be 64 + } + It "-File should pass additional arguments to script" { Set-Content -Path $testdrive/script.ps1 -Value 'foreach($arg in $args){$arg}' $observed = & $powershell -NoProfile $testdrive/script.ps1 foo bar @@ -208,11 +224,8 @@ Describe "ConsoleHost unit tests" -tags "Feature" { $observed | Should -Be $BoolValue } - It "-File '' should return exit code from script" -TestCases @( - @{Filename = "test.ps1"}, - @{Filename = "test"} - ) { - param($Filename) + It "-File should return exit code from script" { + $Filename = 'test.ps1' Set-Content -Path $testdrive/$Filename -Value 'exit 123' & $powershell $testdrive/$Filename $LASTEXITCODE | Should -Be 123 @@ -235,11 +248,16 @@ Describe "ConsoleHost unit tests" -tags "Feature" { $observed | Should -BeExactly "h-llo" } - It "Empty command should fail" { - & $powershell -noprofile -c '' + It "Missing command should fail" { + & $powershell -noprofile -c $LASTEXITCODE | Should -Be 64 } + It "Empty space command should succeed on non-Windows" -skip:$IsWindows { + & $powershell -noprofile -c '' | Should -BeNullOrEmpty + $LASTEXITCODE | Should -Be 0 + } + It "Whitespace command should succeed" { & $powershell -noprofile -c ' ' | Should -BeNullOrEmpty $LASTEXITCODE | Should -Be 0 @@ -270,7 +288,7 @@ export $envVarName='$guid' } It "Doesn't run the login profile when -Login not used" { - $result = & $powershell -Command "`$env:$envVarName" + $result = & $powershell -noprofile -Command "`$env:$envVarName" $result | Should -BeNullOrEmpty $LASTEXITCODE | Should -Be 0 } @@ -368,8 +386,48 @@ export $envVarName='$guid' } } + Context "-SettingsFile Commandline switch set 'PSModulePath'" { + + BeforeAll { + $CustomSettingsFile = Join-Path -Path $TestDrive -ChildPath 'powershell.test.json' + $mPath1 = Join-Path $PSHOME 'Modules' + $mPath2 = Join-Path $TestDrive 'NonExist' + $pathSep = [System.IO.Path]::PathSeparator + + ## Use multiple paths in the setting. + $ModulePath = "${mPath1}${pathSep}${mPath2}".Replace('\', "\\") + Set-Content -Path $CustomSettingsfile -Value "{`"Microsoft.PowerShell:ExecutionPolicy`":`"Unrestricted`", `"PSModulePath`": `"$ModulePath`" }" -ErrorAction Stop + } + + It "Verify PowerShell PSModulePath should contain paths from config file" { + $psModulePath = & $powershell -NoProfile -SettingsFile $CustomSettingsFile -Command '$env:PSModulePath' + + ## $mPath1 already exists in the value of env PSModulePath, so it won't be added again. + $index = $psModulePath.IndexOf("${mPath1}${pathSep}", [System.StringComparison]::OrdinalIgnoreCase) + $index | Should -BeGreaterThan 0 + $index += $mPath1.Length + $psModulePath.IndexOf($mPath1, $index, [System.StringComparison]::OrdinalIgnoreCase) | Should -BeExactly -1 + + ## $mPath2 should be added at the index position 0. + $psModulePath.StartsWith("${mPath2}${pathSep}", [System.StringComparison]::OrdinalIgnoreCase) | Should -BeTrue + } + } + Context "Pipe to/from powershell" { - $p = [PSCustomObject]@{X=10;Y=20} + BeforeAll { + if ($null -ne $PSStyle) { + $outputRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'plaintext' + } + + $p = [PSCustomObject]@{X=10;Y=20} + } + + AfterAll { + if ($null -ne $PSStyle) { + $PSStyle.OutputRendering = $outputRendering + } + } It "xml input" { $p | & $powershell -noprofile { $input | ForEach-Object {$a = 0} { $a += $_.X + $_.Y } { $a } } | Should -Be 30 @@ -388,20 +446,42 @@ export $envVarName='$guid' It "text output" { # Join (multiple lines) and remove whitespace (we don't care about spacing) to verify we converted to string (by generating a table) - -join (& $powershell -noprofile -outputFormat text { [PSCustomObject]@{X=10;Y=20} }) -replace "\s","" | Should -Be "XY--1020" + -join (& $powershell -noprofile -outputFormat text { $PSStyle.OutputRendering = 'PlainText'; [PSCustomObject]@{X=10;Y=20} }) -replace "\s","" | Should -Be "XY--1020" } It "errors are in text if error is redirected, encoded command, non-interactive, and outputformat specified" { $p = [Diagnostics.Process]::new() $p.StartInfo.FileName = "pwsh" - $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('$ErrorView="NormalView";throw "boom"')) + $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes('throw "boom"')) $p.StartInfo.Arguments = "-EncodedCommand $encoded -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -OutputFormat text" $p.StartInfo.UseShellExecute = $false $p.StartInfo.RedirectStandardError = $true $p.Start() | Out-Null $out = $p.StandardError.ReadToEnd() $out | Should -Not -BeNullOrEmpty - $out.Split([Environment]::NewLine)[0] | Should -BeExactly "boom" + $out = $out.Split([Environment]::NewLine)[0] + [System.Management.Automation.Internal.StringDecorated]::new($out).ToString("PlainText") | Should -BeExactly "Exception: boom" + } + + It "Progress is not emitted when stdout is redirected" { + $ps = [powershell]::Create() + $null = $ps.AddScript('$a = & ([Environment]::ProcessPath) -Command "Write-Progress -Activity progress"; $a') + $actual = $ps.Invoke() + + $ps.HadErrors | Should -BeFalse + $actual | Should -BeNullOrEmpty + $ps.Streams.Progress | Should -BeNullOrEmpty + } + + It "Progress is still emitted with redireciton with XML output" { + $ps = [powershell]::Create() + $null = $ps.AddScript('$a = & ([Environment]::ProcessPath) -OutputFormat xml -Command "Write-Progress -Activity progress"; $a') + $actual = $ps.Invoke() + + $ps.HadErrors | Should -BeFalse + $actual | Should -BeNullOrEmpty + $ps.Streams.Progress.Count | Should -Be 1 + $ps.Streams.Progress[0].Activity | Should -Be progress } } @@ -465,7 +545,15 @@ export $envVarName='$guid' } Context "Redirected standard input for 'interactive' use" { - $nl = [Environment]::Newline + BeforeAll { + $nl = [Environment]::Newline + $oldColor = $env:NO_COLOR + $env:NO_COLOR = 1 + } + + AfterAll { + $env:NO_COLOR = $oldColor + } # All of the following tests replace the prompt (either via an initial command or interactively) # so that we can read StandardOutput and reliably know exactly what the prompt is. @@ -560,6 +648,8 @@ foo It "Redirected input w/ nested prompt" -Pending:($IsWindows) { $si = NewProcessStartInfo "-noprofile -noexit -c ""`$function:prompt = { 'PS' + ('>'*(`$NestedPromptLevel+1)) + ' ' }""" -RedirectStdIn $process = RunPowerShell $si + $process.StandardInput.Write("`$PSStyle.OutputRendering='plaintext'`n") + $null = $process.StandardOutput.ReadLine() $process.StandardInput.Write("`$Host.EnterNestedPrompt()`n") $process.StandardOutput.ReadLine() | Should -Be "PS> `$Host.EnterNestedPrompt()" $process.StandardInput.Write("exit`n") @@ -638,6 +728,20 @@ namespace StackTest { It "Should start if HOME is not defined" -Skip:($IsWindows) { bash -c "unset HOME;$powershell -c '1+1'" | Should -BeExactly 2 } + + It "Same user should use the same temporary HOME directory for different sessions" -Skip:($IsWindows) { + $results = bash -c @" +unset HOME; +$powershell -c '[System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::DEFAULT)'; +$powershell -c '[System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::DEFAULT)'; +"@ + $results | Should -HaveCount 2 + $results[0] | Should -BeExactly $results[1] + + $tempHomeName = "pwsh-{0}-98288ff9-5712-4a14-9a11-23693b9cd91a" -f [System.Environment]::UserName + $defaultPath = Join-Path -Path ([System.IO.Path]::GetTempPath()) -ChildPath "$tempHomeName/.config/powershell" + $results[0] | Should -BeExactly $defaultPath + } } Context "PATH environment variable" { @@ -646,7 +750,7 @@ namespace StackTest { } It "powershell starts if PATH is not set" -Skip:($IsWindows) { - bash -c "unset PATH;$powershell -c '1+1'" | Should -BeExactly 2 + bash -c "unset PATH;$powershell -nop -c '1+1'" | Should -BeExactly 2 } } @@ -756,6 +860,8 @@ namespace StackTest { Context "ApartmentState WPF tests" -Tag Slow { It "WPF requires STA and will work" -Skip:(!$IsWindows -or [System.Management.Automation.Platform]::IsNanoServer) { + Set-ItResult -Pending -Because "Disabled due to issue - https://github.com/dotnet/wpf/issues/11651 in .NET 11 Preview 5" + Add-Type -AssemblyName presentationframework $xaml = [xml]@" @@ -807,6 +913,92 @@ namespace StackTest { $LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter } } + + Context "Startup banner text tests" -Tag Slow { + BeforeAll { + $outputPath = "Temp:\StartupBannerTest-Output-${Pid}.txt" + $inputPath = "Temp:\StartupBannerTest-Input.txt" + "exit" > $inputPath + + # Not testing update notification banner text here + $oldPowerShellUpdateCheck = $env:POWERSHELL_UPDATECHECK + $env:POWERSHELL_UPDATECHECK = "Off" + + # Set TERM to "dumb" to avoid DECCKM codes in the output + $oldTERM = $env:TERM + $env:TERM = "dumb" + + $escPwd = [regex]::Escape($pwd) + $expectedPromptPattern = "^PS ${escPwd}> exit`$" + + $spArgs = @{ + FilePath = $powershell + ArgumentList = @("-NoProfile") + RedirectStandardInput = $inputPath + RedirectStandardOutput = $outputPath + WorkingDirectory = $pwd + PassThru = $true + NoNewWindow = $true + UseNewEnvironment = $false + } + } + AfterAll { + $env:TERM = $oldTERM + $env:POWERSHELL_UPDATECHECK = $oldPowerShellUpdateCheck + + Remove-Item $inputPath -Force -ErrorAction Ignore + Remove-Item $outputPath -Force -ErrorAction Ignore + } + BeforeEach { + Remove-Item $outputPath -Force -ErrorAction Ignore + } + It "Displays expected startup banner text by default" { + $process = Start-Process @spArgs + Wait-UntilTrue -sb { $process.HasExited } -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 250 | Should -BeTrue + + $out = @(Get-Content $outputPath) + $out.Count | Should -Be 2 + $out[0] | Should -BeExactly "PowerShell $($PSVersionTable.GitCommitId)" + $out[1] | Should -MatchExactly $expectedPromptPattern + } + It "Displays only the prompt with -NoLogo" { + $spArgs["ArgumentList"] += "-NoLogo" + $process = Start-Process @spArgs + Wait-UntilTrue -sb { $process.HasExited } -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 250 | Should -BeTrue + + $out = @(Get-Content $outputPath) + $out.Count | Should -Be 1 + $out[0] | Should -MatchExactly $expectedPromptPattern + } + } + + Context 'CommandWithArgs tests' { + It 'Should be able to run a pipeline with arguments using ' -TestCases @( + @{ param = '-commandwithargs' } + @{ param = '-cwa' } + ){ + param($param) + $out = pwsh -nologo -noprofile $param '$args | % { "[$_]" }' '$fun' '@times' + $out.Count | Should -Be 2 -Because ($out | Out-String) + $out[0] | Should -BeExactly '[$fun]' + $out[1] | Should -BeExactly '[@times]' + } + + It 'Should be able to handle boolean switch: ' -TestCases @( + @{ param = '-switch:$true'; expected = 'True'} + @{ param = '-switch:$false'; expected = 'False'} + ){ + param($param, $expected) + $out = pwsh -nologo -noprofile -cwa 'param([switch]$switch) $switch.IsPresent' $param + $out | Should -Be $expected + } + } + + It 'Errors for invalid ExecutionPolicy string' { + $out = pwsh -nologo -noprofile -executionpolicy NonExistingExecutionPolicy -c 'exit 0' 2>&1 + $out | Should -Not -BeNullOrEmpty + $LASTEXITCODE | Should -Be $ExitCodeBadCommandLineParameter + } } Describe "WindowStyle argument" -Tag Feature { @@ -822,7 +1014,12 @@ public static WINDOWPLACEMENT GetPlacement(IntPtr hwnd) { WINDOWPLACEMENT placement = new WINDOWPLACEMENT(); placement.length = Marshal.SizeOf(placement); - GetWindowPlacement(hwnd, ref placement); + + if (!GetWindowPlacement(hwnd, ref placement)) + { + throw new System.ComponentModel.Win32Exception(); + } + return placement; } @@ -858,13 +1055,17 @@ public enum ShowWindowCommands : int $global:PSDefaultParameterValues = $defaultParamValues } - It "-WindowStyle should work on Windows" -TestCases @( + It "-WindowStyle should work on Windows" -Pending -TestCases @( @{WindowStyle="Normal"}, @{WindowStyle="Minimized"}, @{WindowStyle="Maximized"} # hidden doesn't work in CI/Server Core ) { param ($WindowStyle) + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "All windows are showing up as hidden or ARM64" + } + try { $ps = Start-Process $powershell -ArgumentList "-WindowStyle $WindowStyle -noexit -interactive" -PassThru $startTime = Get-Date @@ -998,8 +1199,57 @@ Describe 'Pwsh startup and PATH' -Tag CI { } Describe 'Console host name' -Tag CI { - It 'Name is pwsh' -Pending { - # waiting on https://github.com/dotnet/runtime/issues/33673 + It 'Name is pwsh' { (Get-Process -Id $PID).Name | Should -BeExactly 'pwsh' } } + +Describe 'TERM env var' -Tag CI { + BeforeAll { + $oldTERM = $env:TERM + } + + AfterAll { + $env:TERM = $oldTERM + } + + It 'TERM = "dumb"' { + $env:TERM = 'dumb' + pwsh -noprofile -command '$Host.UI.SupportsVirtualTerminal' | Should -BeExactly 'False' + } + + It 'TERM = ""' -TestCases @( + @{ term = "xterm-mono" } + @{ term = "xtermm" } + ) { + param ($term) + + $env:TERM = $term + pwsh -noprofile -command '$PSStyle.OutputRendering' | Should -BeExactly 'PlainText' + } + + It 'NO_COLOR' { + try { + $env:NO_COLOR = 1 + pwsh -noprofile -command '$PSStyle.OutputRendering' | Should -BeExactly 'PlainText' + } + finally { + $env:NO_COLOR = $null + } + } + + It 'No_COLOR should be respected for redirected output' { + $psi = [System.Diagnostics.ProcessStartInfo] @{ + FileName = 'pwsh' + # Pass a command that succeeds and normally produces colored output, and one that produces error output. + Arguments = '-NoProfile -Command Get-Item .; Get-Content \nosuch123' + # Redirect (capture) both stdout and stderr. + RedirectStandardOutput = $true + RedirectStandardError = $true + } + $psi.Environment.Add('NO_COLOR', 1) + ($ps = [System.Diagnostics.Process]::Start($psi)).WaitForExit() + $ps.StandardOutput.ReadToEnd() | Should -Not -Contain '\e' + $ps.StandardError.ReadToEnd() | Should -Not -Contain '\e' + } +} diff --git a/test/powershell/Host/HostUtilities.Tests.ps1 b/test/powershell/Host/HostUtilities.Tests.ps1 index a886891080b..e151a2cfc2b 100644 --- a/test/powershell/Host/HostUtilities.Tests.ps1 +++ b/test/powershell/Host/HostUtilities.Tests.ps1 @@ -35,10 +35,13 @@ Describe "InvokeOnRunspace method as nested command" -tags "Feature" { Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAdminOnWindows" { BeforeAll { + $skipTest = (Test-IsWinWow64) -or !$IsWindows - if ($IsWindows) { - $script:remoteRunspace = New-RemoteRunspace + if ($skipTest) { + return } + + $script:remoteRunspace = New-RemoteRunspace } AfterAll { @@ -48,7 +51,7 @@ Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAd } } - It "Method should successfully invoke command on remote runspace" -Skip:(!$IsWindows) { + It "Method should successfully invoke command on remote runspace" -Skip:$skipTest { $command = [System.Management.Automation.PSCommand]::new() $command.AddScript('"Hello!"') @@ -59,7 +62,7 @@ Describe "InvokeOnRunspace method on remote runspace" -tags "Feature","RequireAd } } -Describe 'PromptForCredential' { +Describe 'PromptForCredential' -Tags "CI" { BeforeAll { [System.Management.Automation.Internal.InternalTestHooks]::SetTestHook('NoPromptForPassword', $true) } @@ -78,3 +81,18 @@ Describe 'PromptForCredential' { $out.UserName | Should -BeExactly 'myDomain\myUser' } } + +Describe 'PushRunspaceLocalFailure' -Tags 'CI' { + It 'Should throw an exception when pushing a local runspace' { + $runspace = [RunspaceFactory]::CreateRunspace() + try { + $runspace.Open() + $exc = { $Host.PushRunspace($runspace) } | Should -Throw -PassThru + $exc.Exception.InnerException | Should -BeOfType ([System.ArgumentException]) + [string]$exc | Should -BeLike "*PushRunspace can only push a remote runspace. (Parameter 'runspace')*" + } + finally { + $runspace.Dispose() + } + } +} diff --git a/test/powershell/Host/Logging.Tests.ps1 b/test/powershell/Host/Logging.Tests.ps1 index 5159d46551f..53798dc1c3c 100644 --- a/test/powershell/Host/Logging.Tests.ps1 +++ b/test/powershell/Host/Logging.Tests.ps1 @@ -43,6 +43,29 @@ enum LogKeyword ManagedPlugin = 0x100 } +# mac log command can emit json, so just use that +# we need to deconstruct the eventmessage to get the event id +# we also need to filter out the non-default messages +function Get-MacOsSyslogItems { + param ([int]$processId, [string]$logId) + $logArgs = "show", "--process", "$processId", "--style", "json" + log $logArgs | + ConvertFrom-Json | + Where-Object { $_.category -eq "$logId" -and $_.messageType -eq "Default" } | + ForEach-Object { + $s = $_.eventMessage.IndexOf('[') + 1 + $e = $_.EventMessage.IndexOf(']') + $l = $e - $s + if ($l -gt 0) { + $eventId = $_.eventMessage.SubString($s, $l) + } + else { + $eventId = "unknown" + } + $_ | Add-Member -MemberType NoteProperty -Name EventId -Value $eventId -PassThru + } +} + <# .SYNOPSIS Creates a powershell.config.json file with syslog settings @@ -188,7 +211,9 @@ Creating Scriptblock text \(1 of 1\):#012{0}(⏎|#012)*ScriptBlock ID: [0-9a-z\- } } - It 'Verifies scriptblock logging' -Skip:(!$IsSupportedEnvironment) { + # Skip test as it is failing in PowerShell CI on Linux platform. + # Tracking Issue: https://github.com/PowerShell/PowerShell/issues/17092 + It 'Verifies scriptblock logging' -Skip <#-Skip:(!$IsSupportedEnvironment)#> { $configFile = WriteLogSettings -LogId $logId -ScriptBlockLogging -LogLevel Verbose $script = @' $PID @@ -213,11 +238,13 @@ $PID # Verify we log that we are the script to create the scriptblock $createdEvents[1].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f (Get-RegEx -SimpleMatch $Script.Replace([System.Environment]::NewLine,"⏎"))) - # Verify we log that we are excuting the created scriptblock + # Verify we log that we are executing the created scriptblock $createdEvents[2].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f "Write\-Verbose 'testheader123' ;Write\-verbose 'after'") } - It 'Verifies scriptblock logging with null character' -Skip:(!$IsSupportedEnvironment) { + # Skip test as it is failing in PowerShell CI on Linux platform. + # Tracking Issue: https://github.com/PowerShell/PowerShell/issues/17092 + It 'Verifies scriptblock logging with null character' -Skip <#-Skip:(!$IsSupportedEnvironment)#> { $configFile = WriteLogSettings -LogId $logId -ScriptBlockLogging -LogLevel Verbose $script = @' $PID @@ -242,18 +269,21 @@ $PID # Verify we log that we are the script to create the scriptblock $createdEvents[1].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f (Get-RegEx -SimpleMatch $Script.Replace([System.Environment]::NewLine,"⏎"))) - # Verify we log that we are excuting the created scriptblock + # Verify we log that we are executing the created scriptblock $createdEvents[2].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f "Write\-Verbose 'testheader123␀' ;Write\-verbose 'after'") } It 'Verifies logging level filtering works' -Skip:(!$IsSupportedEnvironment) { $configFile = WriteLogSettings -LogId $logId -LogLevel Warning - & $powershell -NoProfile -SettingsFile $configFile -Command '$env:PSModulePath | out-null' + $result = & $powershell -NoProfile -SettingsFile $configFile -Command '$PID' + $result | Should -Not -BeNullOrEmpty # by default, PowerShell only logs informational events on startup. With Level = Warning, nothing should - # have been logged. - $items = Get-PSSysLog -Path $SyslogFile -Id $logId -Tail 100 -TotalCount 1 - $items | Should -Be $null + # have been logged. We'll collect all the syslog entries and look for $PID (there should be none). + $items = Get-PSSysLog -Path $SyslogFile + @($items).Count | Should -BeGreaterThan 0 + $logs = $items | Where-Object { $_.ProcessId -eq $result } + $logs | Should -BeNullOrEmpty } } @@ -262,6 +292,9 @@ Describe 'Basic os_log tests on MacOS' -Tag @('CI','RequireSudoOnUnix') { [bool] $IsSupportedEnvironment = $IsMacOS [bool] $persistenceEnabled = $false + $currentWarningPreference = $WarningPreference + $WarningPreference = "SilentlyContinue" + if ($IsSupportedEnvironment) { # Check the current state. @@ -299,6 +332,7 @@ Path:.* } AfterAll { + $WarningPreference = $currentWarningPreference if ($IsSupportedEnvironment -and !$persistenceEnabled) { # disable persistence if it wasn't enabled @@ -306,26 +340,19 @@ Path:.* } } - It 'Verifies basic logging with no customizations' -Skip:(!$IsSupportedEnvironment) { + It 'Verifies basic logging with no customizations' -Skip:(!$IsMacOS) { try { + $timeString = [DateTime]::Now.ToString('yyyy-MM-dd HH:mm:ss') $configFile = WriteLogSettings -LogId $logId + copy-item $configFile /tmp/pwshtest.config.json $testPid = & $powershell -NoProfile -SettingsFile $configFile -Command '$PID' - - Export-PSOsLog -After $after -LogPid $testPid -TimeoutInMilliseconds 30000 -IntervalInMilliseconds 3000 -MinimumCount 3 | - Set-Content -Path $contentFile - $items = @(Get-PSOsLog -Path $contentFile -Id $logId -After $after -TotalCount 3 -Verbose) + $items = Get-MacOsSyslogItems -processId $testPid -logId $logId $items | Should -Not -Be $null $items.Count | Should -BeGreaterThan 2 - $items[0].EventId | Should -BeExactly 'Perftrack_ConsoleStartupStart:PowershellConsoleStartup.WinStart.Informational' - $items[1].EventId | Should -BeExactly 'NamedPipeIPC_ServerListenerStarted:NamedPipe.Open.Informational' - $items[2].EventId | Should -BeExactly 'Perftrack_ConsoleStartupStop:PowershellConsoleStartup.WinStop.Informational' - # if there are more items than expected... - if ($items.Count -gt 3) - { - # Force reporting of the first unexpected item to help diagnosis - $items[3] | Should -Be $null - } + $items.EventId | Should -Contain 'Perftrack_ConsoleStartupStart:PowershellConsoleStartup.WinStart.Informational' + $items.EventId | Should -Contain 'NamedPipeIPC_ServerListenerStarted:NamedPipe.Open.Informational' + $items.EventId | Should -Contain 'Perftrack_ConsoleStartupStop:PowershellConsoleStartup.WinStop.Informational' } catch { if (Test-Path $contentFile) { @@ -335,7 +362,7 @@ Path:.* } } - It 'Verifies scriptblock logging' -Skip:(!$IsSupportedEnvironment) { + It 'Verifies scriptblock logging' -Skip:(!$IsMacOS) { try { $script = @' $PID @@ -346,24 +373,23 @@ $PID $testScriptPath = Join-Path -Path $TestDrive -ChildPath $testFileName $script | Out-File -FilePath $testScriptPath -Force $testPid = & $powershell -NoProfile -SettingsFile $configFile -Command $testScriptPath - - Export-PSOsLog -After $after -LogPid $testPid -TimeoutInMilliseconds 30000 -IntervalInMilliseconds 3000 -MinimumCount 17 | - Set-Content -Path $contentFile - $items = @(Get-PSOsLog -Path $contentFile -Id $logId -After $after -Verbose) + $items = Get-MacOsSyslogItems -processId $testPid -logId $logId $items | Should -Not -Be $null $items.Count | Should -BeGreaterThan 2 $createdEvents = $items | Where-Object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} $createdEvents.Count | Should -BeGreaterOrEqual 3 + $createdEvents | ConvertTo-Json | set-content /tmp/createdEvents.json + # Verify we log that we are executing a file - $createdEvents[0].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f ".*/$testFileName") + $createdEvents[0].EventMessage | Should -Match $testFileName # Verify we log that we are the script to create the scriptblock - $createdEvents[1].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f (Get-RegEx -SimpleMatch $Script)) + $createdEvents[1].EventMessage | Should -Match (Get-RegEx -SimpleMatch $Script) - # Verify we log that we are excuting the created scriptblock - $createdEvents[2].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f "Write\-Verbose 'testheader123' ;Write\-verbose 'after'") + # Verify we log that we are executing the created scriptblock + $createdEvents[2].EventMessage | Should -Match "Write-Verbose 'testheader123' ;Write-verbose 'after'" } catch { if (Test-Path $contentFile) { @@ -373,35 +399,28 @@ $PID } } - It 'Verifies scriptblock logging with null character' -Skip:(!$IsSupportedEnvironment) { + It 'Verifies scriptblock logging with null character' -Skip:(!$IsMacOS) { try { $script = @' $PID & ([scriptblock]::create("Write-Verbose 'testheader123$([char]0x0000)' ;Write-verbose 'after'")) '@ $configFile = WriteLogSettings -ScriptBlockLogging -LogId $logId -LogLevel Verbose - $testFileName = 'test01.ps1' + $testFileName = 'test02.ps1' $testScriptPath = Join-Path -Path $TestDrive -ChildPath $testFileName $script | Out-File -FilePath $testScriptPath -Force - $testPid = & $powershell -NoProfile -SettingsFile $configFile -Command $testScriptPath + $testPid = & $powershell -NoProfile -SettingsFile $configFile -Command $testScriptPath | Select-Object -First 1 - Export-PSOsLog -After $after -LogPid $testPid -TimeoutInMilliseconds 30000 -IntervalInMilliseconds 3000 -MinimumCount 17 | - Set-Content -Path $contentFile - $items = @(Get-PSOsLog -Path $contentFile -Id $logId -After $after -Verbose) + $items = Get-MacOsSyslogItems -processId $testPid -logId $logId + $items | convertto-json | set-content /tmp/items.json - $items | Should -Not -Be $null - $items.Count | Should -BeGreaterThan 2 $createdEvents = $items | Where-Object {$_.EventId -eq 'ScriptBlock_Compile_Detail:ExecuteCommand.Create.Verbose'} - $createdEvents.Count | Should -BeGreaterOrEqual 3 # Verify we log that we are executing a file - $createdEvents[0].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f ".*/$testFileName") + $createdEvents[0].EventMessage | Should -Match $testFileName - # Verify we log that we are the script to create the scriptblock - $createdEvents[1].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f (Get-RegEx -SimpleMatch $Script)) - - # Verify we log that we are excuting the created scriptblock - $createdEvents[2].Message | Should -Match ($scriptBlockCreatedRegExTemplate -f "Write\-Verbose 'testheader123␀' ;Write\-verbose 'after'") + # Verify we log the null in the message + $createdEvents[1].EventMessage | Should -Match "Write-Verbose 'testheader123\`$\(\[char\]0x0000\)' ;Write-verbose 'after'" } catch { if (Test-Path $contentFile) { @@ -411,25 +430,13 @@ $PID } } - # This is pending because it results in false postitives (-Skip:(!$IsSupportedEnvironment) ) - It 'Verifies logging level filtering works' -Pending { - try { - $configFile = WriteLogSettings -LogId $logId -LogLevel Warning - $testPid = & $powershell -NoLogo -NoProfile -SettingsFile $configFile -Command '$PID' - - Export-PSOsLog -After $after -LogPid $testPid | - Set-Content -Path $contentFile - # by default, powershell startup should only logs informational events. - # With Level = Warning, nothing should be logged. - $items = Get-PSOsLog -Path $contentFile -Id $logId -After $after -TotalCount 3 - $items | Should -Be $null - } - catch { - if (Test-Path $contentFile) { - Send-VstsLogFile -Path $contentFile - } - throw - } + # this is now specific to MacOS + It 'Verifies logging level filtering works' -skip:(!$IsMacOs) { + $configFile = WriteLogSettings -LogId $logId -LogLevel Warning + $testPid = & $powershell -NoLogo -NoProfile -SettingsFile $configFile -Command '$PID' + + $items = Get-MacOsSyslogItems -processId $testPid -logId $logId + $items | Should -Be $null -Because ("{0} Warning event logs were found" -f @($items).Count) } } @@ -437,6 +444,10 @@ Describe 'Basic EventLog tests on Windows' -Tag @('CI','RequireAdminOnWindows') BeforeAll { [bool] $IsSupportedEnvironment = $IsWindows [string] $powershell = Join-Path -Path $PSHOME -ChildPath 'pwsh' + + $currentWarningPreference = $WarningPreference + $WarningPreference = "SilentlyContinue" + $scriptBlockLoggingCases = @( @{ name = 'normal script block' @@ -456,6 +467,10 @@ Describe 'Basic EventLog tests on Windows' -Tag @('CI','RequireAdminOnWindows') } } + AfterAll { + $WarningPreference = $currentWarningPreference + } + BeforeEach { if ($IsSupportedEnvironment) { diff --git a/test/powershell/Host/PSVersionTable.Tests.ps1 b/test/powershell/Host/PSVersionTable.Tests.ps1 index e691b7661be..777ccb6c132 100644 --- a/test/powershell/Host/PSVersionTable.Tests.ps1 +++ b/test/powershell/Host/PSVersionTable.Tests.ps1 @@ -3,6 +3,7 @@ Describe "PSVersionTable" -Tags "CI" { BeforeAll { + Set-StrictMode -Version 3 $sma = Get-Item (Join-Path $PSHOME "System.Management.Automation.dll") $formattedVersion = $sma.VersionInfo.ProductVersion @@ -22,10 +23,6 @@ Describe "PSVersionTable" -Tags "CI" { $expectedGitCommitIdPattern = "^$mainVersionPattern$" $unexpectectGitCommitIdPattern = $fullVersionPattern } - - $powerShellVersions = "1.0", "2.0", "3.0", "4.0", "5.0", "5.1", "6.0", "6.1", "6.2", "7.0", "7.1", "7.2" - $powerShellCompatibleVersions = $PSVersionTable.PSCompatibleVersions | - ForEach-Object {$_.ToString(2).SubString(0,3)} } It "Should have version table entries" { @@ -163,15 +160,31 @@ Describe "PSVersionTable" -Tags "CI" { } } - It "Verify PSCompatibleVersions has an entry for all known versions of PowerShell" { - foreach ($version in $powerShellVersions) { - $version | Should -BeIn $powerShellCompatibleVersions + Context "PSCompatibleVersions property" { + It "Is of type System.Version[]" { + Should -ActualValue $PSVersionTable.PSCompatibleVersions -BeOfType System.Version[] + } + + It "Is sorted in ascending order" { + $array = $PSVersionTable.PSCompatibleVersions + [array]::Sort($array) + + $PSVersionTable.PSCompatibleVersions | Should -Be $array } - } - It "Verify PSCompatibleVersions has no unknown PowerShell entries" { - foreach ($version in $powerShellCompatibleVersions) { - $version | Should -BeIn $powerShellVersions + It "Has no unexpected items present" { + $expectedItems = @( + [version]::new(1, 0) + [version]::new(2, 0) + [version]::new(3, 0) + [version]::new(4, 0) + [version]::new(5, 0) + [version]::new(5, 1) + [version]::new(6, 0) + [version]::new(7, 0) + ) + + Compare-Object $expectedItems $PSVersionTable.PSCompatibleVersions | Should -Be $null } } } diff --git a/test/powershell/Host/ScreenReader.Tests.ps1 b/test/powershell/Host/ScreenReader.Tests.ps1 deleted file mode 100644 index 35f86459861..00000000000 --- a/test/powershell/Host/ScreenReader.Tests.ps1 +++ /dev/null @@ -1,54 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. - -Describe "Validate start of console host" -Tag CI { - BeforeAll { - if (-not $IsWindows) { - return - } - - $csharp_source = @' - using System; - using System.Runtime.InteropServices; - - public class ScreenReaderTestUtility { - private const uint SPI_SETSCREENREADER = 0x0047; - - [DllImport("user32.dll", SetLastError = true)] - [return: MarshalAs(UnmanagedType.Bool)] - private static extern bool SystemParametersInfo(uint uiAction, uint uiParam, IntPtr pvParam, uint fWinIni); - - public static bool ActivateScreenReader() { - return SystemParametersInfo(SPI_SETSCREENREADER, 1u, IntPtr.Zero, 0); - } - - public static bool DeactivateScreenReader() { - return SystemParametersInfo(SPI_SETSCREENREADER, 0u, IntPtr.Zero, 0); - } - } -'@ - $utilType = "ScreenReaderTestUtility" -as [type] - if (-not $utilType) { - $utilType = Add-Type -TypeDefinition $csharp_source -PassThru - } - - ## Make the screen reader status active. - $utilType::ActivateScreenReader() - } - - AfterAll { - if ($IsWindows) { - ## Make the screen reader status in-active. - $utilType::DeactivateScreenReader() - } - } - - It "PSReadLine should not be auto-loaded when screen reader status is active" -Skip:(-not $IsWindows) { - $output = & "$PSHOME/pwsh" -noprofile -noexit -c "Get-Module PSReadLine; exit" - $output.Length | Should -BeExactly 2 - - ## The warning message about screen reader should be returned, but the PSReadLine module should not be loaded. - $output[0] | Should -BeLike "Warning:*'Import-Module PSReadLine'." - $output[1] | Should -BeExactly ([string]::Empty) - } -} diff --git a/test/powershell/Host/Startup.Tests.ps1 b/test/powershell/Host/Startup.Tests.ps1 index 6ce9dfc463d..35c22fefe58 100644 --- a/test/powershell/Host/Startup.Tests.ps1 +++ b/test/powershell/Host/Startup.Tests.ps1 @@ -7,7 +7,6 @@ Describe "Validate start of console host" -Tag CI { 'Microsoft.ApplicationInsights.dll' 'Microsoft.Management.Infrastructure.dll' 'Microsoft.PowerShell.ConsoleHost.dll' - 'Microsoft.PowerShell.Security.dll' 'Microsoft.Win32.Primitives.dll' 'Microsoft.Win32.Registry.dll' 'netstandard.dll' @@ -15,7 +14,6 @@ Describe "Validate start of console host" -Tag CI { 'pwsh.dll' 'System.Collections.Concurrent.dll' 'System.Collections.dll' - 'System.Collections.NonGeneric.dll' 'System.Collections.Specialized.dll' 'System.ComponentModel.dll' 'System.ComponentModel.Primitives.dll' @@ -26,7 +24,6 @@ Describe "Validate start of console host" -Tag CI { 'System.Diagnostics.TraceSource.dll' 'System.Diagnostics.Tracing.dll' 'System.IO.FileSystem.AccessControl.dll' - 'System.IO.FileSystem.dll' 'System.IO.FileSystem.DriveInfo.dll' 'System.IO.Pipes.dll' 'System.Linq.dll' @@ -36,6 +33,7 @@ Describe "Validate start of console host" -Tag CI { 'System.Net.Mail.dll' 'System.Net.NetworkInformation.dll' 'System.Net.Primitives.dll' + 'System.Numerics.Vectors.dll' 'System.ObjectModel.dll' 'System.Private.CoreLib.dll' 'System.Private.Uri.dll' @@ -45,15 +43,14 @@ Describe "Validate start of console host" -Tag CI { 'System.Reflection.Primitives.dll' 'System.Runtime.dll' 'System.Runtime.InteropServices.dll' - 'System.Runtime.InteropServices.RuntimeInformation.dll' 'System.Runtime.Loader.dll' 'System.Runtime.Numerics.dll' 'System.Runtime.Serialization.Formatters.dll' 'System.Runtime.Serialization.Primitives.dll' 'System.Security.AccessControl.dll' - 'System.Security.Cryptography.Encoding.dll' - 'System.Security.Cryptography.X509Certificates.dll' + 'System.Security.Cryptography.dll' 'System.Security.Principal.Windows.dll' + 'System.Text.Encoding.CodePages.dll' 'System.Text.Encoding.Extensions.dll' 'System.Text.RegularExpressions.dll' 'System.Threading.dll' @@ -66,16 +63,15 @@ Describe "Validate start of console host" -Tag CI { if ($IsWindows) { $allowedAssemblies += @( 'Microsoft.PowerShell.CoreCLR.Eventing.dll' - 'System.Diagnostics.FileVersionInfo.dll' 'System.DirectoryServices.dll' 'System.Management.dll' 'System.Security.Claims.dll' - 'System.Security.Cryptography.Primitives.dll' 'System.Threading.Overlapped.dll' ) } else { $allowedAssemblies += @( + 'System.Diagnostics.DiagnosticSource.dll' 'System.Net.Sockets.dll' ) } @@ -90,7 +86,7 @@ Describe "Validate start of console host" -Tag CI { Remove-Item $profileDataFile -Force } - $loadedAssemblies = & "$PSHOME/pwsh" -noprofile -command '([System.AppDomain]::CurrentDomain.GetAssemblies()).manifestmodule | Where-Object { $_.Name -notlike ""<*>"" } | ForEach-Object { $_.Name }' + $loadedAssemblies = & "$PSHOME/pwsh" -noprofile -command '([System.AppDomain]::CurrentDomain.GetAssemblies()).manifestmodule | Where-Object { $_.Name -notlike "<*>" } | ForEach-Object { $_.Name }' } It "No new assemblies are loaded" { diff --git a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 index 78be093a5bb..2280d141ac3 100644 --- a/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/BugFix.Tests.ps1 @@ -28,10 +28,9 @@ Describe "Tab completion bug fix" -Tags "CI" { It "Issue#1345 - 'Import-Module -n' should work" { $cmd = "Import-Module -n" $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length - $result.CompletionMatches | Should -HaveCount 3 + $result.CompletionMatches | Should -HaveCount 2 $result.CompletionMatches[0].CompletionText | Should -BeExactly "-Name" $result.CompletionMatches[1].CompletionText | Should -BeExactly "-NoClobber" - $result.CompletionMatches[2].CompletionText | Should -BeExactly "-NoOverwrite" } It "Issue#11227 - [CompletionCompleters]::CompleteVariable and [CompletionCompleters]::CompleteType should work" { @@ -44,6 +43,28 @@ Describe "Tab completion bug fix" -Tags "CI" { $result[0].CompletionText | Should -BeExactly '$ErrorActionPreference' } + It "Issue#24756 - Wildcard completions should not return early due to missing results in one container" -Skip:(!$IsWindows) { + try + { + $keys = New-Item -Path @( + 'HKCU:\AB1' + 'HKCU:\AB2' + 'HKCU:\AB2\Test' + ) + + $res = TabExpansion2 -inputScript 'Get-ChildItem -Path HKCU:\AB?\' + $res.CompletionMatches.Count | Should -Be 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "HKCU:\AB2\Test" + } + finally + { + if ($keys) + { + Remove-Item -Path HKCU:\AB? -Recurse -ErrorAction SilentlyContinue + } + } + } + Context "Issue#3416 - 'Select-Object'" { BeforeAll { $DatetimeProperties = @((Get-Date).psobject.baseobject.psobject.properties) | Sort-Object -Property Name @@ -85,8 +106,193 @@ Describe "Tab completion bug fix" -Tags "CI" { $result.CurrentMatchIndex | Should -Be -1 $result.ReplacementIndex | Should -Be 40 $result.ReplacementLength | Should -Be 0 - $result.CompletionMatches[0].CompletionText | Should -BeExactly 'Expression' - $result.CompletionMatches[1].CompletionText | Should -BeExactly 'Ascending' - $result.CompletionMatches[2].CompletionText | Should -BeExactly 'Descending' + $result.CompletionMatches[0].CompletionText | Should -BeExactly 'Ascending' + $result.CompletionMatches[1].CompletionText | Should -BeExactly 'Descending' + } + + It "Issue#19912 - Tab completion should not crash" { + $ISS = [initialsessionstate]::CreateDefault() + $Runspace = [runspacefactory]::CreateRunspace($ISS) + $Runspace.Open() + $OldRunspace = [runspace]::DefaultRunspace + try + { + [runspace]::DefaultRunspace = $Runspace + {[System.Management.Automation.CommandCompletion]::CompleteInput('Get-', 3, $null)} | Should -Not -Throw + } + finally + { + [runspace]::DefaultRunspace = $OldRunspace + $Runspace.Dispose() + } + } + + It "Issue#26277 - [CompletionCompleters]::CompleteFilename('') should work" { + $testDir = Join-Path $TestDrive "TempTestDir" + $file1 = Join-Path $testDir "abc.ps1" + $file2 = Join-Path $testDir "def.py" + + New-Item -ItemType Directory -Path $testDir > $null + New-Item -ItemType File -Path $file1 > $null + New-Item -ItemType File -Path $file2 > $null + + try { + Push-Location -Path $testDir + $result = [System.Management.Automation.CompletionCompleters]::CompleteFilename("") + $result | Should -Not -Be $null + $result | Measure-Object | ForEach-Object -MemberName Count | Should -Be 2 + + $item1, $item2 = @($result) + $item1.ListItemText | Should -BeExactly 'abc.ps1' + $item2.ListItemText | Should -BeExactly 'def.py' + } finally { + Pop-Location + } + } + + Context 'Native CLI argument completion' { + BeforeAll { + $testDir = Join-Path $TestDrive "TempTestDir" + $file1 = Join-Path $testDir "abc.ps1" + $file2 = Join-Path $testDir "def.py" + + New-Item -ItemType Directory -Path $testDir > $null + New-Item -ItemType File -Path $file1 > $null + New-Item -ItemType File -Path $file2 > $null + + $dirSep = [System.IO.Path]::DirectorySeparatorChar + $relative_name_abc = ".${dirSep}abc.ps1" + $relative_name_def = ".${dirSep}def.py" + } + + AfterAll { + ## Unregister the completer for 'ping' to avoid affecting other tests. + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock $null + } + + It 'Completer script block returning nothing should fall back to file name completion' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches | Should -Not -BeNullOrEmpty + $result.CompletionMatches.Count | Should -Be 2 + $result.CompletionMatches[0].CompletionText | Should -BeExactly $relative_name_abc + $result.CompletionMatches[1].CompletionText | Should -BeExactly $relative_name_def + } finally { + Pop-Location + } + } + + It 'Completer script block returning $null should suppress default completion fallback' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + return $null + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + ## This call should not throw, and should suppress the default file name completion fallback, returning no results. + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches.Count | Should -Be 0 + } finally { + Pop-Location + } + } + + It 'Completer script block returning empty string should suppress default completion fallback' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + return '' + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + ## This call should not throw, and should suppress the default file name completion fallback, returning no results. + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches.Count | Should -Be 0 + } finally { + Pop-Location + } + } + + It 'Completer script block returning empty-string-only array should fall back to default completion' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + return '', '' + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + ## This call should not throw, and should fall back to the default completion. + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches.Count | Should -Be 2 + $result.CompletionMatches[0].CompletionText | Should -BeExactly $relative_name_abc + $result.CompletionMatches[1].CompletionText | Should -BeExactly $relative_name_def + } finally { + Pop-Location + } + } + + It 'Completer script block returning null-value-only array should fall back to default completion' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + return $null, $null + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + ## This call should not throw, and should fall back to the default completion. + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches.Count | Should -Be 2 + $result.CompletionMatches[0].CompletionText | Should -BeExactly $relative_name_abc + $result.CompletionMatches[1].CompletionText | Should -BeExactly $relative_name_def + } finally { + Pop-Location + } + } + + It 'Completer script block returning a single string works as expected' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + return 'hello' + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches.Count | Should -Be 1 + $result.CompletionMatches[0].CompletionText | Should -BeExactly "hello" + } finally { + Pop-Location + } + } + + It 'Completer script block returning an array that contains non-empty-or-null strings works as expected' { + register-ArgumentCompleter -Native -CommandName ping -ScriptBlock { + param($WordToComplete, $CommandAst, $CursorPosition) + return '', 'hello', $null, 'world' + } + + try { + Push-Location -Path $testDir + $cmd = "ping " + $result = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length + $result.CompletionMatches.Count | Should -Be 2 + $result.CompletionMatches[0].CompletionText | Should -BeExactly "hello" + $result.CompletionMatches[1].CompletionText | Should -BeExactly "world" + } finally { + Pop-Location + } + } } } diff --git a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 index 77667306aed..f8762a63929 100644 --- a/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 +++ b/test/powershell/Host/TabCompletion/TabCompletion.Tests.ps1 @@ -23,11 +23,77 @@ Describe "TabCompletion" -Tags CI { $res | Should -BeExactly 'Test-AbbreviatedFunctionExpansion' } + It 'Should complete module by shortname' { + $res = TabExpansion2 -inputScript 'Get-Module -ListAvailable -Name Host' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Microsoft.PowerShell.Host' + } + It 'Should complete native exe' -Skip:(!$IsWindows) { $res = TabExpansion2 -inputScript 'notep' -cursorColumn 'notep'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'notepad.exe' } + It 'Should not include duplicate command results' { + $OldModulePath = $env:PSModulePath + $tempDir = Join-Path -Path $TestDrive -ChildPath "TempPsModuleDir" + $ModuleDirs = @( + Join-Path $tempDir "TestModule1\1.0" + Join-Path $tempDir "TestModule1\1.1" + Join-Path $tempDir "TestModule2\1.0" + ) + try + { + foreach ($Dir in $ModuleDirs) + { + $NewDir = New-Item -Path $Dir -ItemType Directory -Force + $ModuleName = $NewDir.Parent.Name + Set-Content -Value 'MyTestFunction{}' -LiteralPath "$($NewDir.FullName)\$ModuleName.psm1" + New-ModuleManifest -Path "$($NewDir.FullName)\$ModuleName.psd1" -RootModule "$ModuleName.psm1" -FunctionsToExport "MyTestFunction" -ModuleVersion $NewDir.Name + } + + $env:PSModulePath += [System.IO.Path]::PathSeparator + $tempDir + $Res = TabExpansion2 -inputScript MyTestFunction + $Res.CompletionMatches.Count | Should -Be 2 + $SortedMatches = $Res.CompletionMatches.CompletionText | Sort-Object + $SortedMatches[0] | Should -Be "TestModule1\MyTestFunction" + $SortedMatches[1] | Should -Be "TestModule2\MyTestFunction" + } + finally + { + $env:PSModulePath = $OldModulePath + Remove-Item -LiteralPath $ModuleDirs -Recurse -Force + } + } + + It 'Should not include duplicate module results' { + $OldModulePath = $env:PSModulePath + $tempDir = Join-Path -Path $TestDrive -ChildPath "TempPsModuleDir" + try + { + $ModuleDirs = @( + Join-Path $tempDir "TestModule1\1.0" + Join-Path $tempDir "TestModule1\1.1" + ) + foreach ($Dir in $ModuleDirs) + { + $NewDir = New-Item -Path $Dir -ItemType Directory -Force + $ModuleName = $NewDir.Parent.Name + Set-Content -Value 'MyTestFunction{}' -LiteralPath "$($NewDir.FullName)\$ModuleName.psm1" + New-ModuleManifest -Path "$($NewDir.FullName)\$ModuleName.psd1" -RootModule "$ModuleName.psm1" -FunctionsToExport "MyTestFunction" -ModuleVersion $NewDir.Name + } + + $env:PSModulePath += [System.IO.Path]::PathSeparator + $tempDir + $Res = TabExpansion2 -inputScript 'Import-Module -Name TestModule' + $Res.CompletionMatches.Count | Should -Be 1 + $Res.CompletionMatches[0].CompletionText | Should -Be TestModule1 + } + finally + { + $env:PSModulePath = $OldModulePath + Remove-Item -LiteralPath $ModuleDirs -Recurse -Force + } + } + It 'Should complete dotnet method' { $res = TabExpansion2 -inputScript '(1).ToSt' -cursorColumn '(1).ToSt'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ToString(' @@ -43,6 +109,22 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CompareTo(' } + It 'should complete generic type parameters for static methods' { + $script = '[array]::Empty[pscu' + + $results = TabExpansion2 -inputScript $script -cursorColumn $script.Length + $results.CompletionMatches.CompletionText | Should -Contain 'pscustomobject' + } + + It 'should complete generic type parameters for instance methods' { + $script = ' + $dict = [System.Collections.Concurrent.ConcurrentDictionary[string, int]]::new() + $dict.AddOrUpdate[pscu' + + $results = TabExpansion2 -inputScript $script -cursorColumn $script.Length + $results.CompletionMatches.CompletionText | Should -Contain 'pscustomobject' + } + It 'Should complete Magic foreach' { $res = TabExpansion2 -inputScript '(1..10).Fo' -cursorColumn '(1..10).Fo'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'ForEach(' @@ -58,6 +140,356 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly 'pscustomobject' } + It 'Should complete foreach variable' { + $res = TabExpansion2 -inputScript 'foreach ($CurrentItem in 1..10){$CurrentIt' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$CurrentItem' + } + + It 'Should complete variables set with an attribute' { + $res = TabExpansion2 -inputScript '[ValidateNotNull()]$Var1 = 1; $Var' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1' + } + + It 'Should use the first type constraint in a variable assignment in the tooltip' { + $res = TabExpansion2 -inputScript '[int] [string] $Var1 = 1; $Var' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1' + $res.CompletionMatches[0].ToolTip | Should -BeExactly '[int]$Var1' + } + + It 'Should not complete parameter name' { + $res = TabExpansion2 -inputScript 'param($P' + $res.CompletionMatches.Count | Should -Be 0 + } + + It 'Should complete variable in default value of a parameter' { + $res = TabExpansion2 -inputScript 'param($PS = $P' + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + } + + It 'Should complete variable with description and value ' -TestCases @( + @{ Value = 1; Expected = '[int]$VariableWithDescription - Variable description' } + @{ Value = 'string'; Expected = '[string]$VariableWithDescription - Variable description' } + @{ Value = $null; Expected = 'VariableWithDescription - Variable description' } + ) { + param ($Value, $Expected) + + New-Variable -Name VariableWithDescription -Value $Value -Description 'Variable description' -Force + $res = TabExpansion2 -inputScript '$VariableWithDescription' + $res.CompletionMatches.Count | Should -Be 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$VariableWithDescription' + $res.CompletionMatches[0].ToolTip | Should -BeExactly $Expected + } + + It 'Should complete environment variable' { + try { + $env:PWSH_TEST_1 = 'value 1' + $env:PWSH_TEST_2 = 'value 2' + + $res = TabExpansion2 -inputScript '$env:PWSH_TEST_' + $res.CompletionMatches.Count | Should -Be 2 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$env:PWSH_TEST_1' + $res.CompletionMatches[0].ListItemText | Should -BeExactly 'PWSH_TEST_1' + $res.CompletionMatches[0].ToolTip | Should -BeExactly 'PWSH_TEST_1' + $res.CompletionMatches[1].CompletionText | Should -BeExactly '$env:PWSH_TEST_2' + $res.CompletionMatches[1].ListItemText | Should -BeExactly 'PWSH_TEST_2' + $res.CompletionMatches[1].ToolTip | Should -BeExactly 'PWSH_TEST_2' + } + finally { + $env:PWSH_TEST_1 = $null + $env:PWSH_TEST_2 = $null + } + } + + It 'Should complete function variable' { + try { + Function Test-PwshTest1 {} + Function Test-PwshTest2 {} + + $res = TabExpansion2 -inputScript '${function:Test-PwshTest' + $res.CompletionMatches.Count | Should -Be 2 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '${function:Test-PwshTest1}' + $res.CompletionMatches[0].ListItemText | Should -BeExactly 'Test-PwshTest1' + $res.CompletionMatches[0].ToolTip | Should -BeExactly 'Test-PwshTest1' + $res.CompletionMatches[1].CompletionText | Should -BeExactly '${function:Test-PwshTest2}' + $res.CompletionMatches[1].ListItemText | Should -BeExactly 'Test-PwshTest2' + $res.CompletionMatches[1].ToolTip | Should -BeExactly 'Test-PwshTest2' + } + finally { + Remove-Item function:Test-PwshTest1 -ErrorAction SilentlyContinue + Remove-Item function:Test-PwshTest1 -ErrorAction SilentlyContinue + } + } + + It 'Should complete scoped variable with description and value ' -TestCases @( + @{ Value = 1; Expected = '[int]$VariableWithDescription - Variable description' } + @{ Value = 'string'; Expected = '[string]$VariableWithDescription - Variable description' } + @{ Value = $null; Expected = 'VariableWithDescription - Variable description' } + ) { + param ($Value, $Expected) + + New-Variable -Name VariableWithDescription -Value $Value -Description 'Variable description' -Force + $res = TabExpansion2 -inputScript '$local:VariableWithDescription' + $res.CompletionMatches.Count | Should -Be 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$local:VariableWithDescription' + $res.CompletionMatches[0].ToolTip | Should -BeExactly $Expected + } + + It 'Should not complete property name in class definition' { + $res = TabExpansion2 -inputScript 'class X {$P' + $res.CompletionMatches.Count | Should -Be 0 + } + + foreach ($Operator in [System.Management.Automation.CompletionCompleters]::CompleteOperator("")) + { + It "Should complete $($Operator.CompletionText)" { + $res = TabExpansion2 -inputScript "'' $($Operator.CompletionText)" -cursorColumn ($Operator.CompletionText.Length + 3) + $res.CompletionMatches[0].CompletionText | Should -BeExactly $Operator.CompletionText + } + } + + context CustomProviderTests { + BeforeAll { + $testModulePath = Join-Path $TestDrive "ReproModule" + New-Item -Path $testModulePath -ItemType Directory > $null + + New-ModuleManifest -Path "$testModulePath/ReproModule.psd1" -RootModule 'testmodule.dll' + + $testBinaryModulePath = Join-Path $testModulePath "testmodule.dll" + $binaryModule = @' +using System; +using System.Linq; +using System.Management.Automation; +using System.Management.Automation.Provider; + +namespace BugRepro +{ + public class IntItemInfo + { + public string Name; + public IntItemInfo(string name) => Name = name; + } + + [CmdletProvider("Int", ProviderCapabilities.None)] + public class IntProvider : NavigationCmdletProvider + { + public static string[] ToChunks(string path) => path.Split("/", StringSplitOptions.RemoveEmptyEntries); + + protected string _ChildName(string path) + { + var name = ToChunks(path).LastOrDefault(); + return name ?? string.Empty; + } + + protected string Normalize(string path) => string.Join("/", ToChunks(path)); + + protected override string GetChildName(string path) + { + var name = _ChildName(path); + // if (!IsItemContainer(path)) { return string.Empty; } + return name; + } + + protected override bool IsValidPath(string path) => int.TryParse(GetChildName(path), out int _); + + protected override bool IsItemContainer(string path) + { + var name = _ChildName(path); + if (!int.TryParse(name, out int value)) + { + return false; + } + if (ToChunks(path).Count() > 3) + { + return false; + } + return value % 2 == 0; + } + + protected override bool ItemExists(string path) + { + foreach (var chunk in ToChunks(path)) + { + if (!int.TryParse(chunk, out int value)) + { + return false; + } + if (value < 0 || value > 9) + { + return false; + } + } + return true; + } + + protected override void GetItem(string path) + { + var name = GetChildName(path); + if (!int.TryParse(name, out int _)) + { + return; + } + WriteItemObject(new IntItemInfo(name), path, IsItemContainer(path)); + } + protected override bool HasChildItems(string path) => IsItemContainer(path); + + protected override void GetChildItems(string path, bool recurse) + { + if (!IsItemContainer(path)) { GetItem(path); return; } + + for (var i = 0; i <= 9; i++) + { + var _path = $"{Normalize(path)}/{i}"; + if (recurse) + { + GetChildItems(_path, recurse); + } + else + { + GetItem(_path); + } + } + } + } +} +'@ + Add-Type -OutputAssembly $testBinaryModulePath -TypeDefinition $binaryModule + + $pwsh = "$PSHOME\pwsh" + } + + It "Should not complete invalid items when a provider path returns itself instead of its children" { + $result = & $pwsh -NoProfile -Command "Import-Module -Name $testModulePath; (TabExpansion2 'Get-ChildItem Int::/2/3/').CompletionMatches.Count" + $result | Should -BeExactly "0" + } + } + + It 'should complete index expression for ' -TestCases @( + @{ + Intent = 'Hashtable with no user input' + Expected = "'PSVersion'" + TestString = '$PSVersionTable[^' + } + @{ + Intent = 'Hashtable with partial input' + Expected = "'PSVersion'" + TestString = '$PSVersionTable[ PSvers^' + } + @{ + Intent = 'Hashtable with partial quoted input' + Expected = "'PSVersion'" + TestString = '$PSVersionTable["PSvers^' + } + @{ + Intent = 'Hashtable from Ast' + Expected = "'Hello'" + TestString = '$Table = @{Hello = "World"};$Table[^' + } + @{ + Intent = 'Hashtable with cursor on new line' + Expected = "'Hello'" + TestString = @' +$Table = @{Hello = "World"} +$Table[ +^ +'@ + } + ) -Test { + param($Expected, $TestString) + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches[0].CompletionText | Should -BeExactly $Expected + } + + it 'should add quotes when completing hashtable key from Ast with member syntax' -Test { + $res = TabExpansion2 -inputScript '$Table = @{"Hello World" = "World"};$Table.' + $res.CompletionMatches.CompletionText | Where-Object {$_ -eq "'Hello World'"} | Should -BeExactly "'Hello World'" + } + + It '' -TestCases @( + @{ + Intent = 'Complete member with space between dot and cursor' + Expected = 'value__' + TestString = '[System.Management.Automation.ActionPreference]::Break. ^' + } + @{ + Intent = 'Complete member when cursor is in-between existing members and spaces' + Expected = 'value__' + TestString = '[System.Management.Automation.ActionPreference]::Break. ^ ToString()' + } + @{ + Intent = 'Complete static member with space between colons and cursor' + Expected = 'Break' + TestString = '[System.Management.Automation.ActionPreference]:: ^' + } + @{ + Intent = 'Complete static member with new line between colons and cursor' + Expected = 'Break' + TestString = @' +[System.Management.Automation.ActionPreference]:: +^ +'@ + } + @{ + Intent = 'Complete static member with partial input and incomplete input at end of line' + Expected = 'Break' + TestString = '[System.Management.Automation.ActionPreference]:: Brea^. value__.' + } + @{ + Intent = 'Complete static member with partial input and valid input at end of line' + Expected = 'Break' + TestString = '[System.Management.Automation.ActionPreference]:: Brea^. value__' + } + @{ + Intent = 'Complete member with new line between colons and cursor' + Expected = 'value__' + TestString = '[System.Management.Automation.ActionPreference]::Break. ^ ToString()' + } + @{ + Intent = 'Complete type with incomplete expression input at end of line' + Expected = 'System.Management.Automation.ActionPreference' + TestString = '[System.Management.Automation.ActionPreference^]::' + } + @{ + Intent = 'Complete member inside switch expression' + Expected = 'Length' + TestString = @' +switch ($x) +{ + 'RandomString'.^ + {} +} +'@ + } + @{ + Intent = 'Complete member in commandast' + Expected = 'Length' + TestString = 'ls "".^' + } + ){ + param($Expected, $TestString) + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches[0].CompletionText | Should -BeExactly $Expected + } + + It 'Should Complete and replace existing member with space in front of cursor and cursor in front of word' { + $TestString = '[System.Management.Automation.ActionPreference]:: ^Break' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.ReplacementIndex | Should -BeExactly $CursorIndex + $res.ReplacementLength | Should -Be 5 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Break' + } + + It 'Complete and replace existing member with colons in front of cursor and cursor in front of word' { + $TestString = '[System.Management.Automation.ActionPreference]::^Break' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.ReplacementIndex | Should -BeExactly $CursorIndex + $res.ReplacementLength | Should -Be 5 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Break' + } + It 'Should complete namespaces' { $res = TabExpansion2 -inputScript 'using namespace Sys' -cursorColumn 'using namespace Sys'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'System' @@ -118,15 +550,144 @@ Describe "TabCompletion" -Tags CI { $completionText -join ' ' | Should -BeExactly 'Ascending Descending Expression' } - It 'Should complete New-Object hashtable' { - class X { - $A - $B - $C + It 'Should complete variable assigned in other scriptblock' { + $res = TabExpansion2 -inputScript 'ForEach-Object -Begin {$Test1 = "Hello"} -Process {$Test' + $res.CompletionMatches[0].CompletionText | Should -Be '$Test1' + } + + It 'Should complete variable assigned in an array of scriptblocks' { + $res = TabExpansion2 -inputScript 'ForEach-Object -Process @({"Block1"},{$Test1="Hello"});$Test' + $res.CompletionMatches[0].CompletionText | Should -Be '$Test1' + } + + It 'Should not complete variable assigned in an ampersand executed scriptblock' { + $res = TabExpansion2 -inputScript '& {$AmpeersandVarCompletionTest = "Hello"};$AmpeersandVarCompletionTes' + $res.CompletionMatches.Count | Should -Be 0 + } + + It 'Should complete variable assigned in command redirection to variable' { + $res = TabExpansion2 -inputScript 'New-Guid 1>variable:Redir1 2>variable:Redir2 3>variable:Redir3 4>variable:Redir4 5>variable:Redir5 6>variable:Redir6; $Redir' + $res.CompletionMatches[0].CompletionText | Should -Be '$Redir1' + $res.CompletionMatches[1].CompletionText | Should -Be '$Redir2' + $res.CompletionMatches[1].ToolTip | Should -Be '[ErrorRecord]$Redir2' + $res.CompletionMatches[2].CompletionText | Should -Be '$Redir3' + $res.CompletionMatches[2].ToolTip | Should -Be '[WarningRecord]$Redir3' + $res.CompletionMatches[3].CompletionText | Should -Be '$Redir4' + $res.CompletionMatches[3].ToolTip | Should -Be '[VerboseRecord]$Redir4' + $res.CompletionMatches[4].CompletionText | Should -Be '$Redir5' + $res.CompletionMatches[4].ToolTip | Should -Be '[DebugRecord]$Redir5' + $res.CompletionMatches[5].CompletionText | Should -Be '$Redir6' + $res.CompletionMatches[5].ToolTip | Should -Be '[InformationRecord]$Redir6' + } + + context TypeConstructionWithHashtable { + BeforeAll { + class RandomTestType { + $A + $B + $C + } + function RandomTestTypeClassTestCompletion([RandomTestType]$Param1){} + Class LevelOneClass { + [LevelTwoClass] $Property1 + } + class LevelTwoClass { + [string] $Property2 + } + function LevelOneClassTestCompletion([LevelOneClass[]]$Param1){} + Add-Type -TypeDefinition 'public interface IRandomInterfaceTest{string DemoProperty { get; set; }}' + function functionWithInterfaceParam ([IRandomInterfaceTest]$Param1){} } - $res = TabExpansion2 -inputScript 'New-Object -TypeName X -Property @{ ' -cursorColumn 'New-Object -TypeName X -Property @{ '.Length - $res.CompletionMatches | Should -HaveCount 3 - $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' + It 'Should complete New-Object hashtable' { + $res = TabExpansion2 -inputScript 'New-Object -TypeName RandomTestType -Property @{ ' + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' + } + + It 'Complete hashtable key without duplicate keys' { + $TestString = '[RandomTestType]@{A="";^}' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches | Should -HaveCount 2 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'B C' + } + + It 'Complete hashtable key on empty line after key/value pair' { + $TestString = @' +[RandomTestType]@{ + B="" + ^ +} +'@ + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches | Should -HaveCount 2 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A C' + } + + It 'Should complete class properties for typed variable declaration with hashtable' { + $res = TabExpansion2 -inputScript '[RandomTestType]$TestVar = @{' + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' + } + + It 'Should complete class properties for typed command parameter with hashtable input' { + $res = TabExpansion2 -inputScript 'RandomTestTypeClassTestCompletion -Param1 @{' + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'A B C' + } + + It 'Should complete class properties for nested hashtable' { + $res = TabExpansion2 -inputScript '[LevelOneClass]@{Property1=@{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property2' + } + + It 'Should complete class properties for underlying type in array parameter' { + $res = TabExpansion2 -inputScript 'LevelOneClassTestCompletion @{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property1' + } + + It 'Should complete class properties for new class assignment to property' { + $res = TabExpansion2 -inputScript '$Var=[LevelOneClass]::new();$Var.Property1=@{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Property2' + } + + It 'Should not complete class properties from class with constructor that takes arguments' { + $res = TabExpansion2 -inputScript 'class ClassWithCustomConstructor {ClassWithCustomConstructor ($Param){}$A};[ClassWithCustomConstructor]@{' + $res.CompletionMatches[0].CompletionText | Should -BeNullOrEmpty + } + + It 'Should complete class properties for function with an interface type' { + $res = TabExpansion2 -inputScript 'functionWithInterfaceParam -Param1 @{' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'DemoProperty' + } + } + + It 'Complete hashtable keys for Get-WinEvent FilterHashtable' -Skip:(!$IsWindows) { + $TestString = 'Get-WinEvent -FilterHashtable @{^' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches | Should -HaveCount 11 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'LogName ProviderName Path Keywords ID Level StartTime EndTime UserID Data SuppressHashFilter' + } + + It 'Complete hashtable keys for Get-WinEvent SuppressHashFilter' -Skip:(!$IsWindows) { + $TestString = 'Get-WinEvent -FilterHashtable @{SuppressHashFilter=@{' + $res = TabExpansion2 -inputScript $TestString + $res.CompletionMatches | Should -HaveCount 10 + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'LogName ProviderName Path Keywords ID Level StartTime EndTime UserID Data' + } + + It 'Complete hashtable keys for hashtable in array of arguments' { + $res = TabExpansion2 -inputScript 'Get-ChildItem | Format-Table -Property Attributes,@{' + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly 'Expression FormatString Label Width Alignment' + } + + It 'Complete hashtable keys for a hashtable used for splatting' { + $TestString = '$GetChildItemParams=@{^};Get-ChildItem @GetChildItemParams -Force -Recurse' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Path' } It 'Should complete "Get-Process -Id " with Id and name in tooltip' { @@ -146,11 +707,25 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches.Count | Should -BeGreaterThan 0 } - It 'Should complete keyword' -Skip { + It 'Should complete keyword with partial input' { $res = TabExpansion2 -inputScript 'using nam' -cursorColumn 'using nam'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly 'namespace' } + It 'Should complete keyword with no input' { + $res = TabExpansion2 -inputScript 'using ' -cursorColumn 'using '.Length + $res.CompletionMatches.CompletionText | Should -BeExactly 'assembly','module','namespace','type' + } + + It 'Should complete keyword with no input after line continuation' { + $InputScript = @' +using ` + +'@ + $res = TabExpansion2 -inputScript $InputScript -cursorColumn $InputScript.Length + $res.CompletionMatches.CompletionText | Should -BeExactly 'assembly','module','namespace','type' + } + It 'Should first suggest -Full and then -Functionality when using Get-Help -Fu' -Skip { $res = TabExpansion2 -inputScript 'Get-Help -Fu' -cursorColumn 'Get-Help -Fu'.Length $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Full' @@ -163,6 +738,32 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[1].CompletionText | Should -BeExactly '-Functionality' } + It 'Should not remove braces when completing variable with braces' { + $Text = '"Hello${psversiont}World"' + $res = TabExpansion2 -inputScript $Text -cursorColumn $Text.IndexOf('p') + $res.CompletionMatches[0].CompletionText | Should -BeExactly '${PSVersionTable}' + } + + It 'Should work for property assignment of enum type:' { + $res = TabExpansion2 -inputScript '$psstyle.Progress.View="Clas' + $res.CompletionMatches[0].CompletionText | Should -Be '"Classic"' + } + + It 'Should work for variable assignment of enum type with type inference' { + $res = TabExpansion2 -inputScript '[System.Management.Automation.ProgressView]$MyUnassignedVar = $psstyle.Progress.View; $MyUnassignedVar = "Class' + $res.CompletionMatches[0].CompletionText | Should -Be '"Classic"' + } + + It 'Should work for property assignment of enum type with type inference with PowerShell class' { + $res = TabExpansion2 -inputScript 'enum Animals{Cat= 0;Dog= 1};class AnimalTestClass{[Animals] $Prop1};$Test1 = [AnimalTestClass]::new();$Test1.Prop1 = "C' + $res.CompletionMatches[0].CompletionText | Should -Be '"Cat"' + } + + It 'Should work for variable assignment with type inference of PowerShell Enum' { + $res = TabExpansion2 -inputScript 'enum Animals{Cat= 0;Dog= 1}; [Animals]$TestVar1 = "D' + $res.CompletionMatches[0].CompletionText | Should -Be '"Dog"' + } + It 'Should work for variable assignment of enum type: ' -TestCases @( @{ inputStr = '$ErrorActionPreference = '; filter = ''; doubleQuotes = $false } @{ inputStr = '$ErrorActionPreference='; filter = ''; doubleQuotes = $false } @@ -194,117 +795,1146 @@ Describe "TabCompletion" -Tags CI { $expected = '' } - $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - if ($res.CompletionMatches.Count -gt 0) { - $actual = [string]::Join(",",$res.CompletionMatches.completiontext) - } - else { - $actual = '' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + if ($res.CompletionMatches.Count -gt 0) { + $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + } + else { + $actual = '' + } + + $actual | Should -BeExactly $expected + } + + It 'Should work for variable assignment of custom enum: ' -TestCases @( + @{ inputStr = '[Animal]$c="g'; expected = '"Giraffe"','"Goose"' } + @{ inputStr = '[Animal]$c='; expected = "'Duck'","'Giraffe'","'Goose'","'Horse'" } + @{ inputStr = '$script:test = "g'; expected = '"Giraffe"','"Goose"' } + @{ inputStr = '$script:test='; expected = "'Duck'","'Giraffe'","'Goose'","'Horse'" } + @{ inputStr = '$script:test = "x'; expected = @() } + ){ + param($inputStr, $expected) + + enum Animal { Duck; Goose; Horse; Giraffe } + [Animal]$script:test = 'Duck' + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + if ($res.CompletionMatches.Count -gt 0) { + $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + } + else { + $actual = '' + } + + $actual | Should -BeExactly ([string]::Join(",",$expected)) + } + + It 'Should work for assignment of variable with validateset of strings: ' -TestCases @( + @{ inputStr = '$test='; expected = "'a'","'aa'","'aab'","'b'"; doubleQuotes = $false } + @{ inputStr = '$test="a'; expected = "'a'","'aa'","'aab'"; doubleQuotes = $true } + @{ inputStr = '$test = "aa'; expected = "'aa'","'aab'"; doubleQuotes = $true } + @{ inputStr = '$test=''aab'; expected = "'aab'"; doubleQuotes = $false } + @{ inputStr = '$test="c'; expected = ''; doubleQuotes = $true } + ){ + param($inputStr, $expected, $doubleQuotes) + + [ValidateSet('a','aa','aab','b')][string]$test = 'b' + + $expected = [string]::Join(",",$expected) + if ($doubleQuotes) { + $expected = $expected.Replace("'", """") + } + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + if ($res.CompletionMatches.Count -gt 0) { + $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + } + else { + $actual = '' + } + + $actual | Should -BeExactly $expected + } + + It 'Should work for assignment of variable with validateset of int: ' -TestCases @( + @{ inputStr = '$test='; expected = 2,3,11,112 } + @{ inputStr = '$test = 1'; expected = 11,112 } + @{ inputStr = '$test =11'; expected = 11,112 } + @{ inputStr = '$test =4'; expected = @() } + ){ + param($inputStr, $expected) + + [ValidateSet(2,3,11,112)][int]$test = 2 + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + if ($res.CompletionMatches.Count -gt 0) { + $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + } + else { + $actual = '' + } + + $actual | Should -BeExactly ([string]::Join(",",$expected)) + } + + It 'Should work for assignment of variable with validateset of strings: ' -TestCases @( + @{ inputStr = '[validateset("a","aa","aab","b")][string]$test='; expected = "'a'","'aa'","'aab'","'b'"; doubleQuotes = $false } + @{ inputStr = '[validateset("a","aa","aab","b")][string]$test="a'; expected = "'a'","'aa'","'aab'"; doubleQuotes = $true } + @{ inputStr = '[validateset("a","aa","aab","b")][string]$test = "aa'; expected = "'aa'","'aab'"; doubleQuotes = $true } + @{ inputStr = '[validateset("a","aa","aab","b")][string]$test=''aab'; expected = "'aab'"; doubleQuotes = $false } + @{ inputStr = '[validateset("a","aa","aab","b")][string]$test=''c'; expected = ''; doubleQuotes = $false } + ){ + param($inputStr, $expected, $doubleQuotes) + + $expected = [string]::Join(",",$expected) + if ($doubleQuotes) { + $expected = $expected.Replace("'", """") + } + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + if ($res.CompletionMatches.Count -gt 0) { + $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + } + else { + $actual = '' + } + + $actual | Should -BeExactly $expected + } + + It 'ForEach-Object member completion results should include methods' { + $res = TabExpansion2 -inputScript '1..10 | ForEach-Object -MemberName ' + $res.CompletionMatches.CompletionText | Should -Contain "GetType" + } + + It 'Should complete variable member inferred from command inside scriptblock' { + $res = TabExpansion2 -inputScript '& {(New-Guid).' + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + } + + It 'Should not complete void instance members' { + $res = TabExpansion2 -inputScript '([void]("")).' + $res.CompletionMatches | Should -BeNullOrEmpty + } + + It 'Should complete custom constructor from class using the AST' { + $res = TabExpansion2 -inputScript 'class ConstructorTestClass{ConstructorTestClass ([string] $s){}};[ConstructorTestClass]::' + $res.CompletionMatches | Should -HaveCount 3 + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText -join ' ' | Should -BeExactly 'Equals( new( ReferenceEquals(' + } + + It 'Should complete variables assigned inside do while loop' { + $TestString = 'do{$Var1 = 1; $Var^ }while ($true)' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1' + } + + It 'Should complete variables assigned inside do until loop' { + $TestString = 'do{$Var1 = 1; $Var^ }until ($null = Get-ChildItem)' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Var1' + } + + It 'Should show multiple constructors in the tooltip' { + $res = TabExpansion2 -inputScript 'class ConstructorTestClass{ConstructorTestClass ([string] $s){}ConstructorTestClass ([int] $i){}ConstructorTestClass ([int] $i, [bool]$b){}};[ConstructorTestClass]::new' + $res.CompletionMatches | Should -HaveCount 1 + $completionText = $res.CompletionMatches.ToolTip + $completionText.replace("`r`n", [System.Environment]::NewLine).trim() + + $expected = @' +ConstructorTestClass(string s) +ConstructorTestClass(int i) +ConstructorTestClass(int i, bool b) +'@ + $expected.replace("`r`n", [System.Environment]::NewLine).trim() + $completionText.replace("`r`n", [System.Environment]::NewLine).trim() | Should -BeExactly $expected + } + + It 'Should complete parameter in param block' { + $res = TabExpansion2 -inputScript 'Param($Param1=(Get-ChildItem -))' -cursorColumn 30 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Path' + } + + It 'Should complete member in param block' { + $res = TabExpansion2 -inputScript 'Param($Param1=($PSVersionTable.))' -cursorColumn 31 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Count' + } + + It 'Should complete attribute argument in param block' { + $res = TabExpansion2 -inputScript 'Param([Parameter()]$Param1)' -cursorColumn 17 + $names = [Parameter].GetProperties() | Where-Object CanWrite | ForEach-Object Name + + $diffs = Compare-Object -ReferenceObject $res.CompletionMatches.CompletionText -DifferenceObject $names + $diffs | Should -BeNullOrEmpty + } + + It 'Should complete attribute argument in incomplete param block' { + $res = TabExpansion2 -inputScript 'param([ValidatePattern(' + $Expected = ([ValidatePattern].GetProperties() | Where-Object {$_.CanWrite}).Name -join ',' + $res.CompletionMatches.CompletionText -join ',' | Should -BeExactly $Expected + } + + It 'Should complete attribute argument in incomplete param block on new line' { + $TestString = @' +param([ValidatePattern( +^)]) +'@ + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $Expected = ([ValidatePattern].GetProperties() | Where-Object {$_.CanWrite}).Name -join ',' + $res.CompletionMatches.CompletionText -join ',' | Should -BeExactly $Expected + } + + It 'Should complete attribute argument with partially written name in incomplete param block' { + $TestString = 'param([ValidatePattern(op^)]' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Options' + } + + It 'Should complete attribute argument for incomplete standalone attribute' { + $res = TabExpansion2 -inputScript '[ValidatePattern(' + $Expected = ([ValidatePattern].GetProperties() | Where-Object {$_.CanWrite}).Name -join ',' + $res.CompletionMatches.CompletionText -join ',' | Should -BeExactly $Expected + } + + It 'Should complete argument for second parameter' { + $res = TabExpansion2 -inputScript 'Get-ChildItem -Path $HOME -ErrorAction ' + $res.CompletionMatches[0].CompletionText | Should -BeExactly Break + } + + It 'Should complete argument with validateset attribute after comma' { + $TestString = 'function Test-ValidateSet{Param([ValidateSet("Cat","Dog")]$Param1,$Param2)};Test-ValidateSet -Param1 Dog, -Param2' + $res = TabExpansion2 -inputScript $TestString -cursorColumn ($TestString.LastIndexOf(',') + 1) + $res.CompletionMatches[0].CompletionText | Should -BeExactly Cat + } + + It 'Should complete cim ETS member added by shortname' -Skip:(!$IsWindows -or (Test-IsWinServer2012R2) -or (Test-IsWindows2016)) { + $res = TabExpansion2 -inputScript '(Get-NetFirewallRule).Nam' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Name' + } + + It 'Should complete variable assigned with Data statement' { + $TestString = 'data MyDataVar {"Hello"};$MyDatav' + $res = TabExpansion2 -inputScript $TestString + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$MyDataVar' + } + + It 'Should complete global variable without scope' { + $res = TabExpansion2 -inputScript '$Global:MyTestVar = "Hello";$MyTestV' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$MyTestVar' + } + + It 'Should complete previously assigned variable in using: scope' { + $res = TabExpansion2 -inputScript '$MyTestVar = "Hello";$Using:MyTestv' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$Using:MyTestVar' + } + + it 'Should complete "Value" parameter value in "Where-Object" for Enum property with no input' { + $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -eq ' + $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias + } + + it 'Should complete "Value" parameter value in "Where-Object" for Enum property with partial input' { + $res = TabExpansion2 -inputScript 'Get-Command | where-Object CommandType -ne Ali' + $res.CompletionMatches[0].CompletionText | Should -BeExactly Alias + } + + it 'Should complete the right hand side of a comparison operator when left is an Enum with no input' { + $res = TabExpansion2 -inputScript 'Get-Command | Where-Object -FilterScript {$_.CommandType -like ' + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'" + } + + it 'Should complete the right hand side of a comparison operator when left is an Enum with partial input' { + $TempVar = Get-Command + $res = TabExpansion2 -inputScript '$tempVar[0].CommandType -notlike "Ali"' + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'" + } + + it 'Should complete the right hand side of a comparison operator when left is an Enum when cursor is on a newline' { + $res = TabExpansion2 -inputScript "Get-Command | Where-Object -FilterScript {`$_.CommandType -like`n" + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Alias'" + } + + it 'Should complete provider dynamic parameters with quoted path' { + $Script = if ($IsWindows) + { + 'Get-ChildItem -Path "C:\" -Director' + } + else + { + 'Get-ChildItem -Path "/" -Director' + } + $res = TabExpansion2 -inputScript $Script + $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Directory' + } + + it 'Should complete dynamic parameters while providing values to non-string parameters' { + $res = TabExpansion2 -inputScript 'Get-Content -Path $HOME -Verbose:$false -' + $res.CompletionMatches.CompletionText | Should -Contain '-Raw' + } + + It 'Should enumerate types when completing member names for Select-Object' { + $TestString = '"Hello","World" | select-object ' + $res = TabExpansion2 -inputScript $TestString + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Length' + } + + It 'Should complete psobject members for variable' { + $TestVar = Get-Command Get-Command | Select-Object CommandType + $res = TabExpansion2 -inputScript '$TestVar | ForEach-Object {$_.commandtype' + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'CommandType' + } + + It 'Should not complete variables that appear after the cursor' { + $TestString = '$TestVar1 = 1; $TestVar^ ; $TestVar2 = 2' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$TestVar1' + } + + It 'Should not complete pipeline variables outside the pipeline' { + $TestString = 'Get-ChildItem -PipelineVariable TestVar1;$TestVar^' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches | Should -HaveCount 0 + } + + It 'Should complete pipeline variables inside the pipeline' { + $TestString = 'Get-ChildItem -PipelineVariable TestVar1 | ForEach-Object -Process {$TestVar^}' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$TestVar1' + } + + It 'Should complete variable assigned in ParenExpression' { + $res = TabExpansion2 -inputScript '($ParenVar) = 1; $ParenVa' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$ParenVar' + } + + It 'Should complete variable assigned in ArrayLiteral' { + $res = TabExpansion2 -inputScript '$DemoVar1, $DemoVar2 = 1..10; $DemoVar' + $res.CompletionMatches[0].CompletionText | Should -BeExactly '$DemoVar1' + $res.CompletionMatches[1].CompletionText | Should -BeExactly '$DemoVar2' + } + + It 'Should include parameter help message in tool tip - SingleMatch ' -TestCases @( + @{ SingleMatch = $true } + @{ SingleMatch = $false } + ) { + param ($SingleMatch) + + Function Test-Function { + param ( + [Parameter(HelpMessage = 'Some help message')] + $ParamWithHelp, + + $ParamWithoutHelp + ) + } + + $expected = '[Object] ParamWithHelp - Some help message' + + if ($SingleMatch) { + $Script = 'Test-Function -ParamWithHelp' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches + } + else { + $Script = 'Test-Function -' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-ParamWithHelp' + } + + $res.Count | Should -Be 1 + $res.CompletionText | Should -BeExactly '-ParamWithHelp' + $res.ToolTip | Should -BeExactly $expected + } + + It 'Should include parameter help resource message in tool tip - SingleMatch ' -TestCases @( + @{ SingleMatch = $true } + @{ SingleMatch = $false } + ) { + param ($SingleMatch) + + $expected = '`[string`] Activity - *' + + if ($SingleMatch) { + $Script = 'Write-Progress -Activity' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches + } + else { + $Script = 'Write-Progress -' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-Activity' + } + + $res.Count | Should -Be 1 + $res.CompletionText | Should -BeExactly '-Activity' + $res.ToolTip | Should -BeLikeExactly $expected + } + + It 'Should skip empty parameter HelpMessage with multiple parameters - SingleMatch ' -TestCases @( + @{ SingleMatch = $true } + @{ SingleMatch = $false } + ) { + param ($SingleMatch) + + Function Test-Function { + [CmdletBinding(DefaultParameterSetName = 'SetWithoutHelp')] + param ( + [Parameter(ParameterSetName = 'SetWithHelp', HelpMessage = 'Help Message')] + [Parameter(ParameterSetName = 'SetWithoutHelp')] + [string] + $ParamWithHelp, + + [Parameter(ParameterSetName = 'SetWithHelp')] + [switch] + $ParamWithoutHelp + ) + } + + $expected = '[string] ParamWithHelp - Help Message' + + if ($SingleMatch) { + $Script = 'Test-Function -ParamWithHelp' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches + } + else { + $Script = 'Test-Function -' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-ParamWithHelp' + } + + $res.Count | Should -Be 1 + $res.CompletionText | Should -BeExactly '-ParamWithHelp' + $res.ToolTip | Should -BeExactly $expected + } + + It 'Should retrieve help message from dynamic parameter' { + Function Test-Function { + [CmdletBinding()] + param () + dynamicparam { + $attr = [System.Management.Automation.ParameterAttribute]@{ + HelpMessage = "Howdy partner" + } + $attrCollection = [System.Collections.ObjectModel.Collection[System.Attribute]]::new() + $attrCollection.Add($attr) + + $dynParam = [System.Management.Automation.RuntimeDefinedParameter]::new('DynamicParam', [string], $attrCollection) + + $paramDictionary = [System.Management.Automation.RuntimeDefinedParameterDictionary]::new() + $paramDictionary.Add('DynamicParam', $dynParam) + $paramDictionary + } + + end {} + } + + $expected = '[string] DynamicParam - Howdy partner' + $Script = 'Test-Function -' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches | Where-Object CompletionText -eq '-DynamicParam' + $res.Count | Should -Be 1 + $res.CompletionText | Should -BeExactly '-DynamicParam' + $res.ToolTip | Should -BeExactly $expected + } + + It 'Should have type and name for parameter without help message' { + Function Test-Function { + param ( + [Parameter()] + $WithParamAttribute, + + $WithoutParamAttribute + ) + } + + $Script = 'Test-Function -' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches | + Where-Object CompletionText -in '-WithParamAttribute', '-WithoutParamAttribute' | + Sort-Object CompletionText + $res.Count | Should -Be 2 + + $res.CompletionText[0] | Should -BeExactly '-WithoutParamAttribute' + $res.ToolTip[0] | Should -BeExactly '[Object] WithoutParamAttribute' + + $res.CompletionText[1] | Should -BeExactly '-WithParamAttribute' + $res.ToolTip[1] | Should -BeExactly '[Object] WithParamAttribute' + } + + It 'Should ignore errors when faling to get HelpMessage resource' { + Function Test-Function { + param ( + [Parameter(HelpMessageBaseName="invalid", HelpMessageResourceId="SomeId")] + $InvalidHelpParam + ) + } + + $expected = '[Object] InvalidHelpParam' + $Script = 'Test-Function -InvalidHelpParam' + $res = (TabExpansion2 -inputScript $Script).CompletionMatches + $res.Count | Should -Be 1 + $res.CompletionText | Should -BeExactly '-InvalidHelpParam' + $res.ToolTip | Should -BeExactly $expected + } + + Context 'Start-Process -Verb parameter completion' { + BeforeAll { + function GetProcessInfoVerbs([string]$path, [switch]$singleQuote, [switch]$doubleQuote) { + $verbs = (New-Object -TypeName System.Diagnostics.ProcessStartInfo -ArgumentList $path).Verbs + + if ($singleQuote) { + return ($verbs | ForEach-Object { "'$_'" }) + } + elseif ($doubleQuote) { + return ($verbs | ForEach-Object { """$_""" }) + } + + return $verbs + } + + $cmdPath = Join-Path -Path $TestDrive -ChildPath 'test.cmd' + $cmdVerbs = GetProcessInfoVerbs -Path $cmdPath + $cmdVerbsSingleQuote = GetProcessInfoVerbs -Path $cmdPath -SingleQuote + $cmdVerbsDoubleQuote = GetProcessInfoVerbs -Path $cmdPath -DoubleQuote + $exePath = Join-Path -Path $TestDrive -ChildPath 'test.exe' + $exeVerbs = GetProcessInfoVerbs -Path $exePath + $exeVerbsStartingWithRun = $exeVerbs | Where-Object { $_ -like 'run*' } + $exeVerbsSingleQuote = GetProcessInfoVerbs -Path $exePath -SingleQuote + $exeVerbsStartingWithRunSingleQuote = $exeVerbsSingleQuote | Where-Object { $_ -like "'run*" } + $exeVerbsDoubleQuote = GetProcessInfoVerbs -Path $exePath -DoubleQuote + $exeVerbsStartingWithRunDoubleQuote = $exeVerbsDoubleQuote | Where-Object { $_ -like """run*" } + $powerShellExeWithNoExtension = 'powershell' + $txtPath = Join-Path -Path $TestDrive -ChildPath 'test.txt' + $txtVerbs = GetProcessInfoVerbs -Path $txtPath + $wavPath = Join-Path -Path $TestDrive -ChildPath 'test.wav' + $wavVerbs = GetProcessInfoVerbs -Path $wavPath + $docxPath = Join-Path -Path $TestDrive -ChildPath 'test.docx' + $docxVerbs = GetProcessInfoVerbs -Path $docxPath + $fileWithNoExtensionPath = Join-Path -Path $TestDrive -ChildPath 'test' + $fileWithNoExtensionVerbs = GetProcessInfoVerbs -Path $fileWithNoExtensionPath + } + + It "Should complete Verb parameter for ''" -Skip:(!([System.Management.Automation.Platform]::IsWindowsDesktop)) -TestCases @( + @{ TextInput = 'Start-Process -Verb '; ExpectedVerbs = '' } + @{ TextInput = "Start-Process -FilePath $cmdPath -Verb "; ExpectedVerbs = $cmdVerbs -join ' ' } + @{ TextInput = "Start-Process -FilePath $cmdPath -Verb '"; ExpectedVerbs = $cmdVerbsSingleQuote -join ' ' } + @{ TextInput = "Start-Process -FilePath $cmdPath -Verb """; ExpectedVerbs = $cmdVerbsDoubleQuote -join ' ' } + @{ TextInput = "Start-Process -FilePath $exePath -Verb "; ExpectedVerbs = $exeVerbs -join ' ' } + @{ TextInput = "Start-Process -FilePath $exePath -Verb run"; ExpectedVerbs = $exeVerbsStartingWithRun -join ' ' } + @{ TextInput = "Start-Process -FilePath $exePath -Verb 'run"; ExpectedVerbs = $exeVerbsStartingWithRunSingleQuote -join ' ' } + @{ TextInput = "Start-Process -FilePath $exePath -Verb ""run"; ExpectedVerbs = $exeVerbsStartingWithRunDoubleQuote -join ' ' } + @{ TextInput = "Start-Process -FilePath $powerShellExeWithNoExtension -Verb "; ExpectedVerbs = $exeVerbs -join ' ' } + @{ TextInput = "Start-Process -FilePath $txtPath -Verb "; ExpectedVerbs = $txtVerbs -join ' ' } + @{ TextInput = "Start-Process -FilePath $wavPath -Verb "; ExpectedVerbs = $wavVerbs -join ' ' } + @{ TextInput = "Start-Process -FilePath $docxPath -Verb "; ExpectedVerbs = $docxVerbs -join ' ' } + @{ TextInput = "Start-Process -FilePath $fileWithNoExtensionPath -Verb "; ExpectedVerbs = $fileWithNoExtensionVerbs -join ' ' } + ) { + param($TextInput, $ExpectedVerbs) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText -join ' ' | Should -BeExactly $ExpectedVerbs + } + } + + Context 'Scope parameter completion' { + BeforeAll { + $allScopes = 'Global Local Script' + $allScopesSingleQuote = "'Global' 'Local' 'Script'" + $allScopesDoubleQuote = """Global"" ""Local"" ""Script""" + $globalScope = 'Global' + $globalScopeSingleQuote = "'Global'" + $globalScopeDoubleQuote = """Global""" + $localScope = 'Local' + $localScopeSingleQuote = "'Local'" + $localScopeDoubleQuote = """Local""" + $scriptScope = 'Script' + $scriptScopeSingleQuote = "'Script'" + $scriptScopeDoubleQuote = """Script""" + $allScopeCommands = 'Clear-Variable', 'Export-Alias', 'Get-Alias', 'Get-PSDrive', 'Get-Variable', 'Import-Alias', 'New-Alias', 'New-PSDrive', 'New-Variable', 'Remove-Alias', 'Remove-PSDrive', 'Remove-Variable', 'Set-Alias', 'Set-Variable' + } + + It "Should complete '' for ''" -TestCases @( + @{ Commands = $allScopeCommands; ParameterInput = "-Scope "; ExpectedScopes = $allScopes } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope '"; ExpectedScopes = $allScopesSingleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope """; ExpectedScopes = $allScopesDoubleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope G"; ExpectedScopes = $globalScope } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope 'G"; ExpectedScopes = $globalScopeSingleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope ""G"; ExpectedScopes = $globalScopeDoubleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope Lo"; ExpectedScopes = $localScope } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope 'Lo"; ExpectedScopes = $localScopeSingleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope ""Lo"; ExpectedScopes = $localScopeDoubleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope Scr"; ExpectedScopes = $scriptScope } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope 'Scr"; ExpectedScopes = $scriptScopeSingleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope ""Scr"; ExpectedScopes = $scriptScopeDoubleQuote } + @{ Commands = $allScopeCommands; ParameterInput = "-Scope NonExistentScope"; ExpectedScopes = '' } + ) { + param($Commands, $ParameterInput, $ExpectedScopes) + foreach ($command in $Commands) { + $joinedCommand = "$command $ParameterInput" + $res = TabExpansion2 -inputScript $joinedCommand -cursorColumn $joinedCommand.Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText -join ' ' | Should -BeExactly $ExpectedScopes + } + } + } + + Context 'Get-Verb & Get-Command -Verb parameter completion' { + BeforeAll { + $allVerbs = 'Add Approve Assert Backup Block Build Checkpoint Clear Close Compare Complete Compress Confirm Connect Convert ConvertFrom ConvertTo Copy Debug Deny Deploy Disable Disconnect Dismount Edit Enable Enter Exit Expand Export Find Format Get Grant Group Hide Import Initialize Install Invoke Join Limit Lock Measure Merge Mount Move New Open Optimize Out Ping Pop Protect Publish Push Read Receive Redo Register Remove Rename Repair Request Reset Resize Resolve Restart Restore Resume Revoke Save Search Select Send Set Show Skip Split Start Step Stop Submit Suspend Switch Sync Test Trace Unblock Undo Uninstall Unlock Unprotect Unpublish Unregister Update Use Wait Watch Write' + $allVerbsSingleQuote = "'Add' 'Approve' 'Assert' 'Backup' 'Block' 'Build' 'Checkpoint' 'Clear' 'Close' 'Compare' 'Complete' 'Compress' 'Confirm' 'Connect' 'Convert' 'ConvertFrom' 'ConvertTo' 'Copy' 'Debug' 'Deny' 'Deploy' 'Disable' 'Disconnect' 'Dismount' 'Edit' 'Enable' 'Enter' 'Exit' 'Expand' 'Export' 'Find' 'Format' 'Get' 'Grant' 'Group' 'Hide' 'Import' 'Initialize' 'Install' 'Invoke' 'Join' 'Limit' 'Lock' 'Measure' 'Merge' 'Mount' 'Move' 'New' 'Open' 'Optimize' 'Out' 'Ping' 'Pop' 'Protect' 'Publish' 'Push' 'Read' 'Receive' 'Redo' 'Register' 'Remove' 'Rename' 'Repair' 'Request' 'Reset' 'Resize' 'Resolve' 'Restart' 'Restore' 'Resume' 'Revoke' 'Save' 'Search' 'Select' 'Send' 'Set' 'Show' 'Skip' 'Split' 'Start' 'Step' 'Stop' 'Submit' 'Suspend' 'Switch' 'Sync' 'Test' 'Trace' 'Unblock' 'Undo' 'Uninstall' 'Unlock' 'Unprotect' 'Unpublish' 'Unregister' 'Update' 'Use' 'Wait' 'Watch' 'Write'" + $allVerbsDoubleQuote = """Add"" ""Approve"" ""Assert"" ""Backup"" ""Block"" ""Build"" ""Checkpoint"" ""Clear"" ""Close"" ""Compare"" ""Complete"" ""Compress"" ""Confirm"" ""Connect"" ""Convert"" ""ConvertFrom"" ""ConvertTo"" ""Copy"" ""Debug"" ""Deny"" ""Deploy"" ""Disable"" ""Disconnect"" ""Dismount"" ""Edit"" ""Enable"" ""Enter"" ""Exit"" ""Expand"" ""Export"" ""Find"" ""Format"" ""Get"" ""Grant"" ""Group"" ""Hide"" ""Import"" ""Initialize"" ""Install"" ""Invoke"" ""Join"" ""Limit"" ""Lock"" ""Measure"" ""Merge"" ""Mount"" ""Move"" ""New"" ""Open"" ""Optimize"" ""Out"" ""Ping"" ""Pop"" ""Protect"" ""Publish"" ""Push"" ""Read"" ""Receive"" ""Redo"" ""Register"" ""Remove"" ""Rename"" ""Repair"" ""Request"" ""Reset"" ""Resize"" ""Resolve"" ""Restart"" ""Restore"" ""Resume"" ""Revoke"" ""Save"" ""Search"" ""Select"" ""Send"" ""Set"" ""Show"" ""Skip"" ""Split"" ""Start"" ""Step"" ""Stop"" ""Submit"" ""Suspend"" ""Switch"" ""Sync"" ""Test"" ""Trace"" ""Unblock"" ""Undo"" ""Uninstall"" ""Unlock"" ""Unprotect"" ""Unpublish"" ""Unregister"" ""Update"" ""Use"" ""Wait"" ""Watch"" ""Write""" + $verbsStartingWithRe = 'Read Receive Redo Register Remove Rename Repair Request Reset Resize Resolve Restart Restore Resume Revoke' + $verbsStartingWithEx = 'Exit Expand Export' + $verbsStartingWithConv = 'Convert ConvertFrom ConvertTo' + $lifeCycleVerbsStartingWithRe = 'Register Request Restart Resume' + $lifeCycleVerbsStartingWithReSingleQuote = "'Register' 'Request' 'Restart' 'Resume'" + $lifeCycleVerbsStartingWithReDoubleQuote = """Register"" ""Request"" ""Restart"" ""Resume""" + $dataVerbsStartingwithEx = 'Expand Export' + $lifeCycleAndCommmonVerbsStartingWithRe = 'Redo Register Remove Rename Request Reset Resize Restart Resume' + $allLifeCycleAndCommonVerbs = 'Add Approve Assert Build Clear Close Complete Confirm Copy Deny Deploy Disable Enable Enter Exit Find Format Get Hide Install Invoke Join Lock Move New Open Optimize Pop Push Redo Register Remove Rename Request Reset Resize Restart Resume Search Select Set Show Skip Split Start Step Stop Submit Suspend Switch Undo Uninstall Unlock Unregister Wait Watch' + $allJsonVerbs = 'ConvertFrom ConvertTo Test' + $jsonVerbsStartingWithConv = 'ConvertFrom ConvertTo' + $jsonVerbsStartingWithConvSingleQuote = "'ConvertFrom' 'ConvertTo'" + $jsonVerbsStartingWithConvDoubleQuote = """ConvertFrom"" ""ConvertTo""" + $allJsonAndJobVerbs = 'ConvertFrom ConvertTo Debug Get Receive Remove Start Stop Test Wait' + $jsonAndJobVerbsStartingWithSt = 'Start Stop' + $allObjectVerbs = 'Compare ForEach Group Measure New Select Sort Tee Where' + $utilityModuleObjectVerbs = 'Compare Group Measure New Select Sort Tee' + $utilityModuleObjectVerbsStartingWithS = 'Select Sort' + $utilityModuleObjectVerbsStartingWithSSingleQuote = "'Select' 'Sort'" + $utilityModuleObjectVerbsStartingWithSDoubleQuote = """Select"" ""Sort""" + $utilityModuleObjectVerbsStartingWithS + $coreModuleObjectVerbs = 'ForEach Where' + } + + It "Should complete Verb parameter for ''" -TestCases @( + @{ TextInput = 'Get-Verb -Verb '; ExpectedVerbs = $allVerbs } + @{ TextInput = "Get-Verb -Verb '"; ExpectedVerbs = $allVerbsSingleQuote } + @{ TextInput = "Get-Verb -Verb """; ExpectedVerbs = $allVerbsDoubleQuote } + @{ TextInput = 'Get-Verb -Group Lifecycle, Common -Verb '; ExpectedVerbs = $allLifeCycleAndCommonVerbs } + @{ TextInput = 'Get-Verb -Verb Re'; ExpectedVerbs = $verbsStartingWithRe } + @{ TextInput = 'Get-Verb -Group Lifecycle -Verb Re'; ExpectedVerbs = $lifeCycleVerbsStartingWithRe } + @{ TextInput = "Get-Verb -Group Lifecycle -Verb 'Re"; ExpectedVerbs = $lifeCycleVerbsStartingWithReSingleQuote } + @{ TextInput = "Get-Verb -Group Lifecycle -Verb ""Re"; ExpectedVerbs = $lifeCycleVerbsStartingWithReDoubleQuote } + @{ TextInput = 'Get-Verb -Group Lifecycle -Verb Re'; ExpectedVerbs = $lifeCycleVerbsStartingWithRe } + @{ TextInput = 'Get-Verb -Group Lifecycle, Common -Verb Re'; ExpectedVerbs = $lifeCycleAndCommmonVerbsStartingWithRe } + @{ TextInput = 'Get-Verb -Verb Ex'; ExpectedVerbs = $verbsStartingWithEx } + @{ TextInput = 'Get-Verb -Group Data -Verb Ex'; ExpectedVerbs = $dataVerbsStartingwithEx } + @{ TextInput = 'Get-Verb -Group NonExistentGroup -Verb '; ExpectedVerbs = '' } + @{ TextInput = 'Get-Verb -Verb Conv'; ExpectedVerbs = $verbsStartingWithConv } + @{ TextInput = 'Get-Command -Verb '; ExpectedVerbs = $allVerbs } + @{ TextInput = 'Get-Command -Verb Re'; ExpectedVerbs = $verbsStartingWithRe } + @{ TextInput = 'Get-Command -Verb Ex'; ExpectedVerbs = $verbsStartingWithEx } + @{ TextInput = 'Get-Command -Verb Conv'; ExpectedVerbs = $verbsStartingWithConv } + @{ TextInput = 'Get-Command -Noun Json -Verb '; ExpectedVerbs = $allJsonVerbs } + @{ TextInput = 'Get-Command -Noun Json -Verb Conv'; ExpectedVerbs = $jsonVerbsStartingWithConv } + @{ TextInput = "Get-Command -Noun Json -Verb 'Conv"; ExpectedVerbs = $jsonVerbsStartingWithConvSingleQuote } + @{ TextInput = "Get-Command -Noun Json -Verb ""Conv"; ExpectedVerbs = $jsonVerbsStartingWithConvDoubleQuote } + @{ TextInput = 'Get-Command -Noun Json, Job -Verb '; ExpectedVerbs = $allJsonAndJobVerbs } + @{ TextInput = 'Get-Command -Noun Json, Job -Verb St'; ExpectedVerbs = $jsonAndJobVerbsStartingWithSt } + @{ TextInput = 'Get-Command -Noun NonExistentNoun -Verb '; ExpectedVerbs = '' } + @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Utility,Microsoft.PowerShell.Core -Verb '; ExpectedVerbs = $allObjectVerbs } + @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb '; ExpectedVerbs = $utilityModuleObjectVerbs } + @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb S'; ExpectedVerbs = $utilityModuleObjectVerbsStartingWithS } + @{ TextInput = "Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb 'S"; ExpectedVerbs = $utilityModuleObjectVerbsStartingWithSSingleQuote } + @{ TextInput = "Get-Command -Noun Object -Module Microsoft.PowerShell.Utility -Verb ""S"; ExpectedVerbs = $utilityModuleObjectVerbsStartingWithSDoubleQuote } + @{ TextInput = 'Get-Command -Noun Object -Module Microsoft.PowerShell.Core -Verb '; ExpectedVerbs = $coreModuleObjectVerbs } + ) { + param($TextInput, $ExpectedVerbs) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText -join ' ' | Should -BeExactly $ExpectedVerbs + } + } + + Context 'StrictMode Version parameter completion' { + BeforeAll { + $allStrictModeVersions = '1.0 2.0 3.0 Latest' + $allStrictModeVersionsSingleQuote = "'1.0' '2.0' '3.0' 'Latest'" + $allStrictModeVersionsDoubleQuote = """1.0"" ""2.0"" ""3.0"" ""Latest""" + $versionOne = '1.0' + $versionTwo = '2.0' + $versionThree = '3.0' + $latestVersion = 'Latest' + $latestVersionSingleQuote = "'Latest'" + $latestVersionDoubleQuote = """Latest""" + } + + It "Should complete Version for ''" -TestCases @( + @{ TextInput = "Set-StrictMode -Version "; ExpectedVersions = $allStrictModeVersions } + @{ TextInput = "Set-StrictMode -Version '"; ExpectedVersions = $allStrictModeVersionsSingleQuote } + @{ TextInput = "Set-StrictMode -Version """; ExpectedVersions = $allStrictModeVersionsDoubleQuote } + @{ TextInput = "Set-StrictMode -Version 1"; ExpectedVersions = $versionOne } + @{ TextInput = "Set-StrictMode -Version 2"; ExpectedVersions = $versionTwo } + @{ TextInput = "Set-StrictMode -Version 3"; ExpectedVersions = $versionThree } + @{ TextInput = "Set-StrictMode -Version Lat"; ExpectedVersions = $latestVersion } + @{ TextInput = "Set-StrictMode -Version 'Lat"; ExpectedVersions = $latestVersionSingleQuote } + @{ TextInput = "Set-StrictMode -Version ""Lat"; ExpectedVersions = $latestVersionDoubleQuote } + @{ TextInput = "Set-StrictMode -Version NonExistentVersion"; ExpectedVersions = '' } + ) { + param($TextInput, $ExpectedVersions) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText -join ' ' | Should -BeExactly $ExpectedVersions + } + } + + Context 'Help Module parameter completion' { + BeforeAll { + $utilityModule = 'Microsoft.PowerShell.Utility' + $managementModule = 'Microsoft.PowerShell.Management' + $allMicrosoftPowerShellModules = (Get-Module -Name Microsoft.PowerShell* -ListAvailable).Name + Import-Module -Name $allMicrosoftPowerShellModules -ErrorAction SilentlyContinue + $allMicrosoftPowerShellModules = ($allMicrosoftPowerShellModules | Sort-Object -Unique) -join ' ' + } + + It "Should complete Module for ''" -TestCases @( + @{ TextInput = "Save-Help -Module Microsoft.PowerShell.U"; ExpectedModules = $utilityModule } + @{ TextInput = "Update-Help -Module Microsoft.PowerShell.U"; ExpectedModules = $utilityModule } + @{ TextInput = "Save-Help -Module Microsoft.PowerShell.Man"; ExpectedModules = $managementModule } + @{ TextInput = "Update-Help -Module Microsoft.PowerShell.Man"; ExpectedModules = $managementModule } + @{ TextInput = "Save-Help -Module Microsoft.Powershell"; ExpectedModules = $allMicrosoftPowerShellModules } + @{ TextInput = "Update-Help -Module Microsoft.PowerShell"; ExpectedModules = $allMicrosoftPowerShellModules } + @{ TextInput = "Save-Help -Module NonExistentModulePrefix"; ExpectedModules = '' } + @{ TextInput = "Update-Help -Module NonExistentModulePrefix"; ExpectedModules = '' } + ) { + param($TextInput, $ExpectedModules) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object -Unique + $completionText -join ' ' | Should -BeExactly $ExpectedModules + } + } + + Context 'New-ItemProperty -PropertyType parameter completion' { + BeforeAll { + if ($IsWindows) { + $allRegistryValueKinds = 'String ExpandString Binary DWord MultiString QWord Unknown' + $allRegistryValueKindsWithQuotes = "'String' 'ExpandString' 'Binary' 'DWord' 'MultiString' 'QWord' 'Unknown'" + $dwordValueKind = 'DWord' + $qwordValueKind = 'QWord' + $binaryValueKind = 'Binary' + $multiStringValueKind = 'MultiString' + $registryPath = "HKCU:\test1\sub" + New-Item -Path $registryPath -Force + $registryLiteralPath = "HKCU:\test2\*\sub" + New-Item -Path $registryLiteralPath -Force + $fileSystemPath = "TestDrive:\test1.txt" + New-Item -Path $fileSystemPath -Force + $fileSystemLiteralPathDir = "TestDrive:\[]" + $fileSystemLiteralPath = "$fileSystemLiteralPathDir\test2.txt" + New-Item -Path $fileSystemLiteralPath -Force + } + } + + It "Should complete Property Type for ''" -Skip:(!$IsWindows) -TestCases @( + # -Path completions + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType "; ExpectedPropertyTypes = $allRegistryValueKinds } + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType d"; ExpectedPropertyTypes = $dwordValueKind } + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType q"; ExpectedPropertyTypes = $qwordValueKind } + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType bin"; ExpectedPropertyTypes = $binaryValueKind } + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType multi"; ExpectedPropertyTypes = $multiStringValueKind } + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType invalidproptype"; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -Path $fileSystemPath -PropertyType "; ExpectedPropertyTypes = '' } + + # -LiteralPath completions + @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType "; ExpectedPropertyTypes = $allRegistryValueKinds } + @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType d"; ExpectedPropertyTypes = $dwordValueKind } + @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType q"; ExpectedPropertyTypes = $qwordValueKind } + @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType bin"; ExpectedPropertyTypes = $binaryValueKind } + @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType multi"; ExpectedPropertyTypes = $multiStringValueKind } + @{ TextInput = "New-ItemProperty -LiteralPath $registryLiteralPath -PropertyType invalidproptype"; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -LiteralPath $fileSystemLiteralPath -PropertyType "; ExpectedPropertyTypes = '' } + + # All of these should return no completion since they don't specify -Path/-LiteralPath + @{ TextInput = "New-ItemProperty -PropertyType "; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -PropertyType d"; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -PropertyType q"; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -PropertyType bin"; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -PropertyType multi"; ExpectedPropertyTypes = '' } + @{ TextInput = "New-ItemProperty -PropertyType invalidproptype"; ExpectedPropertyTypes = '' } + + # All of these should return completion even with quotes included + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType '"; ExpectedPropertyTypes = $allRegistryValueKindsWithQuotes } + @{ TextInput = "New-ItemProperty -Path $registryPath -PropertyType 'bin"; ExpectedPropertyTypes = "'$binaryValueKind'" } + ) { + param($TextInput, $ExpectedPropertyTypes) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly $ExpectedPropertyTypes + + foreach ($match in $res.CompletionMatches) { + $completionText = $match.CompletionText.Replace("""", "").Replace("'", "") + $listItemText = $match.ListItemText + $completionText | Should -BeExactly $listItemText + $match.ToolTip | Should -Not -BeNullOrEmpty + } + } + + It "Test fallback to provider of current location if no path specified" -Skip:(!$IsWindows) { + try { + Push-Location HKCU:\ + $textInput = "New-ItemProperty -PropertyType " + $res = TabExpansion2 -inputScript $textInput -cursorColumn $textInput.Length + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly $allRegistryValueKinds + } + finally { + Pop-Location + } } - $actual | Should -BeExactly $expected + AfterAll { + if ($IsWindows) { + Remove-Item -Path $registryPath -Force + Remove-Item -LiteralPath $registryLiteralPath -Force + Remove-Item -Path $fileSystemPath -Force + Remove-Item -LiteralPath $fileSystemLiteralPathDir -Recurse -Force + } + } } - It 'Should work for variable assignment of custom enum: ' -TestCases @( - @{ inputStr = '[Animal]$c="g'; expected = '"Giraffe"','"Goose"' } - @{ inputStr = '[Animal]$c='; expected = "'Duck'","'Giraffe'","'Goose'","'Horse'" } - @{ inputStr = '$script:test = "g'; expected = '"Giraffe"','"Goose"' } - @{ inputStr = '$script:test='; expected = "'Duck'","'Giraffe'","'Goose'","'Horse'" } - @{ inputStr = '$script:test = "x'; expected = @() } - ){ - param($inputStr, $expected) + Context 'Get-Command -Noun parameter completion' { + BeforeAll { + function GetModuleCommandNouns( + [string]$Module, + [string]$Verb, + [switch]$SingleQuote, + [switch]$DoubleQuote) + { - enum Animal { Duck; Goose; Horse; Giraffe } - [Animal]$script:test = 'Duck' + $commandParams = @{} - $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - if ($res.CompletionMatches.Count -gt 0) { - $actual = [string]::Join(",",$res.CompletionMatches.completiontext) - } - else { - $actual = '' - } + if ($PSBoundParameters.ContainsKey('Module')) { + $commandParams['Module'] = $Module + } - $actual | Should -BeExactly ([string]::Join(",",$expected)) - } + if ($PSBoundParameters.ContainsKey('Verb')) { + $commandParams['Verb'] = $Verb + } - It 'Should work for assignment of variable with validateset of strings: ' -TestCases @( - @{ inputStr = '$test='; expected = "'a'","'aa'","'aab'","'b'"; doubleQuotes = $false } - @{ inputStr = '$test="a'; expected = "'a'","'aa'","'aab'"; doubleQuotes = $true } - @{ inputStr = '$test = "aa'; expected = "'aa'","'aab'"; doubleQuotes = $true } - @{ inputStr = '$test=''aab'; expected = "'aab'"; doubleQuotes = $false } - @{ inputStr = '$test="c'; expected = ''; doubleQuotes = $true } - ){ - param($inputStr, $expected, $doubleQuotes) + $nouns = (Get-Command @commandParams).Noun - [ValidateSet('a','aa','aab','b')][string]$test = 'b' + if ($SingleQuote) { + return ($nouns | ForEach-Object { "'$_'" }) + } + elseif ($DoubleQuote) { + return ($nouns | ForEach-Object { """$_""" }) + } - $expected = [string]::Join(",",$expected) - if ($doubleQuotes) { - $expected = $expected.Replace("'", """") + return $nouns + } + + $utilityModuleName = 'Microsoft.PowerShell.Utility' + + $allUtilityCommandNouns = GetModuleCommandNouns -Module $utilityModuleName + $allUtilityCommandNounsSingleQuote = GetModuleCommandNouns -Module $utilityModuleName -SingleQuote + $allUtilityCommandNounsDoubleQuote = GetModuleCommandNouns -Module $utilityModuleName -DoubleQuote + $utilityCommandNounsStartingWithF = $allUtilityCommandNouns | Where-Object { $_ -like 'F*'} + $utilityCommandNounsStartingWithFSingleQuote = $allUtilityCommandNounsSingleQuote | Where-Object { $_ -like "'F*"} + $utilityCommandNounsStartingWithFDoubleQuote = $allUtilityCommandNounsDoubleQuote | Where-Object { $_ -like """F*"} + + $allUtilityCommandNounsWithConvertToVerb = GetModuleCommandNouns -Module $utilityModuleName -Verb 'ConvertTo' + $allUtilityCommandNounsWithConvertToVerbSingleQuote = GetModuleCommandNouns -Module $utilityModuleName -SingleQuote -Verb 'ConvertTo' + $allUtilityCommandNounsWithConvertToVerbDoubleQuote = GetModuleCommandNouns -Module $utilityModuleName -DoubleQuote -Verb 'ConvertTo' + $utilityCommandNounsWithConvertToVerb = $allUtilityCommandNounsWithConvertToVerb | Where-Object { $_ -in 'CliXml', 'Csv', 'Html', 'Json', 'Xml' } + $utilityCommandNounsWithConvertToVerbSingleQuote = $allUtilityCommandNounsWithConvertToVerbSingleQuote | Where-Object { $_ -in "'CliXml'", "'Csv'", "'Html'", "'Json'", "'Xml'" } + $utilityCommandNounsWithConvertToVerbDoubleQuote = $allUtilityCommandNounsWithConvertToVerbDoubleQuote | Where-Object { $_ -in """CliXml""", """Csv""", """Html""", """Json""", """Xml""" } + $utilityCommandNounsWithConvertToVerbStartingWithC = $allUtilityCommandNounsWithConvertToVerb | Where-Object { $_ -in 'CliXml', 'Csv' } + $utilityCommandNounsWithConvertToVerbStartingWithCSingleQuote = $allUtilityCommandNounsWithConvertToVerbSingleQuote | Where-Object { $_ -in "'CliXml'", "'Csv'" } + $utilityCommandNounsWithConvertToVerbStartingWithCDoubleQuote = $allUtilityCommandNounsWithConvertToVerbDoubleQuote | Where-Object { $_ -in """CliXml""", """Csv""" } } - $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - if ($res.CompletionMatches.Count -gt 0) { - $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + It "Should complete Noun for ''" -TestCases @( + @{ TextInput = "Get-Command -Module $utilityModuleName -Noun "; ExpectedNouns = $allUtilityCommandNouns } + @{ TextInput = "Get-Command -Module $utilityModuleName -Noun '"; ExpectedNouns = $allUtilityCommandNounsSingleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Noun """; ExpectedNouns = $allUtilityCommandNounsDoubleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Noun F"; ExpectedNouns = $utilityCommandNounsStartingWithF } + @{ TextInput = "Get-Command -Module $utilityModuleName -Noun 'F"; ExpectedNouns = $utilityCommandNounsStartingWithFSingleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Noun ""F"; ExpectedNouns = $utilityCommandNounsStartingWithFDoubleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun "; ExpectedNouns = $utilityCommandNounsWithConvertToVerb } + @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun '"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbSingleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun """; ExpectedNouns = $utilityCommandNounsWithConvertToVerbDoubleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun C"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbStartingWithC } + @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun 'C"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbStartingWithCSingleQuote } + @{ TextInput = "Get-Command -Module $utilityModuleName -Verb ConvertTo -Noun ""C"; ExpectedNouns = $utilityCommandNounsWithConvertToVerbStartingWithCDoubleQuote } + ) { + param($TextInput, $ExpectedNouns) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText + + # Avoid using Sort-Object -Unique because it generates different order than SortedSet on MacOS/Linux + $sortedSetExpectedNouns = [System.Collections.Generic.SortedSet[string]]::new([System.StringComparer]::OrdinalIgnoreCase) + foreach ($noun in $ExpectedNouns) + { + $sortedSetExpectedNouns.Add($noun) | Out-Null + } + + $completionText -join ' ' | Should -BeExactly ($sortedSetExpectedNouns -join ' ') } - else { - $actual = '' + } + + Context "Get-ExperimentalFeature -Name parameter completion" { + BeforeAll { + function GetExperimentalFeatureNames([switch]$SingleQuote, [switch]$DoubleQuote) { + $features = (Get-ExperimentalFeature).Name + + if ($SingleQuote) { + return ($features | ForEach-Object { "'$_'" }) + } + elseif ($DoubleQuote) { + return ($features | ForEach-Object { """$_""" }) + } + + return $features + } + + $allExperimentalFeatures = GetExperimentalFeatureNames + $allExperimentalFeaturesSingleQuote = GetExperimentalFeatureNames -SingleQuote + $allExperimentalFeaturesDoubleQuote = GetExperimentalFeatureNames -DoubleQuote + $experimentalFeaturesStartingWithPS = $allExperimentalFeatures | Where-Object { $_ -like 'PS*'} + $experimentalFeaturesStartingWithPSSingleQuote = $allExperimentalFeaturesSingleQuote | Where-Object { $_ -like "'PS*" } + $experimentalFeaturesStartingWithPSDoubleQuote = $allExperimentalFeaturesDoubleQuote | Where-Object { $_ -like """PS*" } } - $actual | Should -BeExactly $expected + It "Should complete Name for ''" -TestCases @( + @{ TextInput = "Get-ExperimentalFeature -Name "; ExpectedExperimentalFeatureNames = $allExperimentalFeatures } + @{ TextInput = "Get-ExperimentalFeature -Name '"; ExpectedExperimentalFeatureNames = $allExperimentalFeaturesSingleQuote } + @{ TextInput = "Get-ExperimentalFeature -Name """; ExpectedExperimentalFeatureNames = $allExperimentalFeaturesDoubleQuote } + @{ TextInput = "Get-ExperimentalFeature -Name PS"; ExpectedExperimentalFeatureNames = $experimentalFeaturesStartingWithPS } + @{ TextInput = "Get-ExperimentalFeature -Name 'PS"; ExpectedExperimentalFeatureNames = $experimentalFeaturesStartingWithPSSingleQuote } + @{ TextInput = "Get-ExperimentalFeature -Name ""PS"; ExpectedExperimentalFeatureNames = $experimentalFeaturesStartingWithPSDoubleQuote } + ) { + param($TextInput, $ExpectedExperimentalFeatureNames) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly (($ExpectedExperimentalFeatureNames | Sort-Object -Unique) -join ' ') + } } - It 'Should work for assignment of variable with validateset of int: ' -TestCases @( - @{ inputStr = '$test='; expected = 2,3,11,112 } - @{ inputStr = '$test = 1'; expected = 11,112 } - @{ inputStr = '$test =11'; expected = 11,112 } - @{ inputStr = '$test =4'; expected = @() } - ){ - param($inputStr, $expected) + Context "Join-String -Separator & -FormatString parameter completion" { + BeforeAll { + if ($IsWindows) { + $allSeparators = "',' ', ' ';' '; ' ""``r``n"" '-' ' '" + $allFormatStrings = "'[{0}]' '{0:N2}' ""``r``n ```${0}"" ""``r``n [string] ```${0}""" + $newlineSeparator = """``r``n""" + $newlineFormatStrings = """``r``n ```${0}"" ""``r``n [string] ```${0}""" + } + else { + $allSeparators = "',' ', ' ';' '; ' ""``n"" '-' ' '" + $allFormatStrings = "'[{0}]' '{0:N2}' ""``n ```${0}"" ""``n [string] ```${0}""" + $newlineSeparator = """``n""" + $newlineFormatStrings = """``n ```${0}"" ""``n [string] ```${0}""" + } - [ValidateSet(2,3,11,112)][int]$test = 2 + $commaSeparators = "',' ', '" + $semiColonSeparators = "';' '; '" + + $squareBracketFormatString = "'[{0}]'" + $curlyBraceFormatString = "'{0:N2}'" + } - $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - if ($res.CompletionMatches.Count -gt 0) { - $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + It "Should complete for ''" -TestCases @( + @{ TextInput = "Join-String -Separator "; Expected = $allSeparators } + @{ TextInput = "Join-String -Separator '"; Expected = $allSeparators } + @{ TextInput = "Join-String -Separator """; Expected = $allSeparators.Replace("'", """") } + @{ TextInput = "Join-String -Separator ',"; Expected = $commaSeparators } + @{ TextInput = "Join-String -Separator "","; Expected = $commaSeparators.Replace("'", """") } + @{ TextInput = "Join-String -Separator ';"; Expected = $semiColonSeparators } + @{ TextInput = "Join-String -Separator "";"; Expected = $semiColonSeparators.Replace("'", """") } + @{ TextInput = "Join-String -FormatString "; Expected = $allFormatStrings } + @{ TextInput = "Join-String -FormatString '"; Expected = $allFormatStrings } + @{ TextInput = "Join-String -FormatString """; Expected = $allFormatStrings.Replace("'", """") } + @{ TextInput = "Join-String -FormatString ["; Expected = $squareBracketFormatString } + @{ TextInput = "Join-String -FormatString '["; Expected = $squareBracketFormatString } + @{ TextInput = "Join-String -FormatString ""["; Expected = $squareBracketFormatString.Replace("'", """") } + @{ TextInput = "Join-String -FormatString '{"; Expected = $curlyBraceFormatString } + @{ TextInput = "Join-String -FormatString ""{"; Expected = $curlyBraceFormatString.Replace("'", """") } + ) { + param($TextInput, $Expected) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly $Expected + + foreach ($match in $res.CompletionMatches) { + $toolTip = $match.ToolTip.Replace("""", "").Replace("'", "") + $completionText = $match.CompletionText.Replace("""", "").Replace("'", "") + $listItemText = $match.ListItemText + $toolTip.StartsWith($completionText) | Should -BeTrue + $toolTip.EndsWith($listItemText) | Should -BeTrue + } } - else { - $actual = '' + + It "Should complete for ''" -Skip:(!$IsWindows) -TestCases @( + @{ TextInput = "Join-String -Separator '``"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator ""``"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator '``r"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator ""``r"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator '``r``"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator ""``r``"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -FormatString '``"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString ""``"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString '``r"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString ""``r"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString '``r``"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString ""``r``"; Expected = $newlineFormatStrings } + ) { + param($TextInput, $Expected) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly $Expected + + foreach ($match in $res.CompletionMatches) { + $toolTip = $match.ToolTip.Replace("""", "").Replace("'", "") + $completionText = $match.CompletionText.Replace("""", "").Replace("'", "") + $listItemText = $match.ListItemText + $toolTip.StartsWith($completionText) | Should -BeTrue + $toolTip.EndsWith($listItemText) | Should -BeTrue + } } - $actual | Should -BeExactly ([string]::Join(",",$expected)) + It "Should complete for ''" -Skip:($IsWindows) -TestCases @( + @{ TextInput = "Join-String -Separator '``"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator ""``"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator '``n"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -Separator ""``n"; Expected = $newlineSeparator } + @{ TextInput = "Join-String -FormatString '``"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString ""``"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString '``n"; Expected = $newlineFormatStrings } + @{ TextInput = "Join-String -FormatString ""``n"; Expected = $newlineFormatStrings } + ) { + param($TextInput, $Expected) + $res = TabExpansion2 -inputScript $TextInput -cursorColumn $TextInput.Length + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly $Expected + + foreach ($match in $res.CompletionMatches) { + $toolTip = $match.ToolTip.Replace("""", "").Replace("'", "") + $completionText = $match.CompletionText.Replace("""", "").Replace("'", "") + $listItemText = $match.ListItemText + $toolTip.StartsWith($completionText) | Should -BeTrue + $toolTip.EndsWith($listItemText) | Should -BeTrue + } + } } - It 'Should work for assignment of variable with validateset of strings: ' -TestCases @( - @{ inputStr = '[validateset("a","aa","aab","b")][string]$test='; expected = "'a'","'aa'","'aab'","'b'"; doubleQuotes = $false } - @{ inputStr = '[validateset("a","aa","aab","b")][string]$test="a'; expected = "'a'","'aa'","'aab'"; doubleQuotes = $true } - @{ inputStr = '[validateset("a","aa","aab","b")][string]$test = "aa'; expected = "'aa'","'aab'"; doubleQuotes = $true } - @{ inputStr = '[validateset("a","aa","aab","b")][string]$test=''aab'; expected = "'aab'"; doubleQuotes = $false } - @{ inputStr = '[validateset("a","aa","aab","b")][string]$test=''c'; expected = ''; doubleQuotes = $false } - ){ - param($inputStr, $expected, $doubleQuotes) + Context "Format cmdlet's View paramter completion" { + BeforeAll { + $viewDefinition = @' + + + + + R A M + + System.Diagnostics.Process + + + + + + 40 + Center + + + + 40 + Center + + + + 40 + Center + + + + + + + Center + Name + + + Center + PagedMemorySize + + + Center + PeakWorkingSet + + + + + + + + +'@ - $expected = [string]::Join(",",$expected) - if ($doubleQuotes) { - $expected = $expected.Replace("'", """") - } + $tempViewFile = Join-Path -Path $TestDrive -ChildPath 'processViewDefinition.ps1xml' + Set-Content -LiteralPath $tempViewFile -Value $viewDefinition -Force - $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length - if ($res.CompletionMatches.Count -gt 0) { - $actual = [string]::Join(",",$res.CompletionMatches.completiontext) + $ps = [PowerShell]::Create() + $null = $ps.AddScript("Update-FormatData -AppendPath $tempViewFile") + $ps.Invoke() + $ps.HadErrors | Should -BeFalse + $ps.Commands.Clear() + + Remove-Item -LiteralPath $tempViewFile -Force -ErrorAction SilentlyContinue } - else { - $actual = '' + + It 'Should complete Get-ChildItem | -View' -TestCases ( + @{ cmd = 'Format-Table'; expected = "children childrenWithHardlink$(if (!$IsWindows) { ' childrenWithUnixStat' })" }, + @{ cmd = 'Format-List'; expected = 'children' }, + @{ cmd = 'Format-Wide'; expected = 'children' }, + @{ cmd = 'Format-Custom'; expected = '' } + ) { + param($cmd, $expected) + + # The completion is based on OutputTypeAttribute() of the cmdlet. + $res = TabExpansion2 -inputScript "Get-ChildItem | $cmd -View " -cursorColumn "Get-ChildItem | $cmd -View ".Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText -join ' ' | Should -BeExactly $expected } - $actual | Should -BeExactly $expected + It 'Should complete $processList = Get-Process; $processList | ' -TestCases ( + @{ cmd = 'Format-Table -View '; expected = "'R A M'", "Priority", "process", "ProcessModule", "ProcessWithUserName", "StartTime" }, + @{ cmd = 'Format-List -View '; expected = '' }, + @{ cmd = 'Format-Wide -View '; expected = 'process' }, + @{ cmd = 'Format-Custom -View '; expected = '' }, + @{ cmd = 'Format-Table -View S'; expected = "StartTime" }, + @{ cmd = "Format-Table -View 'S"; expected = "'StartTime'" }, + @{ cmd = "Format-Table -View R"; expected = "'R A M'" } + ) { + param($cmd, $expected) + + $null = $ps.AddScript({ + param ($cmd) + $processList = Get-Process + $res = TabExpansion2 -inputScript "`$processList | $cmd" -cursorColumn "`$processList | $cmd".Length + $completionText = $res.CompletionMatches.CompletionText | Sort-Object + $completionText + }).AddArgument($cmd) + + $result = $ps.Invoke() + $ps.Commands.Clear() + $expected = ($expected | Sort-Object) -join ' ' + $result -join ' ' | Should -BeExactly $expected + } } Context NativeCommand { BeforeAll { - $nativeCommand = (Get-Command -CommandType Application -TotalCount 1).Name + ## Find a native command that is not 'pwsh'. We will use 'pwsh' for fallback completer tests later. + $nativeCommand = Get-Command -CommandType Application -TotalCount 2 | + Where-Object Name -NotLike pwsh* | + Select-Object -First 1 } + It 'Completes native commands with -' { Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock { param($wordToComplete, $ast, $cursorColumn) @@ -368,6 +1998,52 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches.CompletionText | Should -BeExactly "-option" } + + It 'Covers an arbitrary unbound native command with -t' { + ## Register a completer for $nativeCommand. + Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock { + param($wordToComplete, $ast, $cursorColumn) + if ($wordToComplete -eq '-t') { + return "-terminal" + } + } + + ## Register a fallback native command completer. + Register-ArgumentCompleter -NativeFallback -ScriptBlock { + param($wordToComplete, $ast, $cursorColumn) + if ($wordToComplete -eq '-t') { + return "-testing" + } + } + + ## The specific completer will be used if it exists. + $line = "$nativeCommand -t" + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches.CompletionText | Should -BeExactly "-terminal" + + ## Otherwise, the fallback completer will kick in. + $line = "pwsh -t" + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches.CompletionText | Should -BeExactly "-testing" + + ## Remove the completer for $nativeCommand. + Register-ArgumentCompleter -Native -CommandName $nativeCommand -ScriptBlock $null + + ## The fallback completer will be used for $nativeCommand. + $line = "$nativeCommand -t" + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches.CompletionText | Should -BeExactly "-testing" + + ## Remove the fallback completer for $nativeCommand. + Register-ArgumentCompleter -NativeFallback -ScriptBlock $null + + ## The fallback completer will be used for $nativeCommand. + $res = TabExpansion2 -inputScript $line -cursorColumn $line.Length + $res.CompletionMatches | Should -HaveCount 0 + } } It 'Should complete "Export-Counter -FileFormat" with available output formats' -Pending { @@ -377,6 +2053,92 @@ Describe "TabCompletion" -Tags CI { $completionText -join ' ' | Should -BeExactly 'blg csv tsv' } + it 'Should include positionally bound parameters when completing in front of parameter value' { + $TestString = 'Get-ChildItem -^ $HOME' + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches.CompletionText | Should -Contain "-Path" + } + + it 'Should find the closest positional parameter match' { + $TestString = @' +function Verb-Noun +{ + Param + ( + [Parameter(Position = 0)] + [string] + $Param1, + [Parameter(Position = 1)] + [System.Management.Automation.ActionPreference] + $Param2 + ) +} +Verb-Noun -Param1 Hello ^ +'@ + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -inputScript $TestString.Remove($CursorIndex, 1) -cursorColumn $CursorIndex + $res.CompletionMatches[0].CompletionText | Should -Be "Break" + } + + it 'Should complete command with an empty arrayexpression element' { + $res = TabExpansion2 -inputScript 'Get-ChildItem @()' -cursorColumn 1 + $res.CompletionMatches[0].CompletionText | Should -Be "Get-ChildItem" + } + + it 'Should not complete TabExpansion2 variables' { + $res = TabExpansion2 -inputScript '$' -cursorColumn 1 + $res.CompletionMatches.CompletionText | Should -Not -Contain '$positionOfCursor' + } + + it 'Should prefer the default parameterset when completing positional parameters' { + $ScriptInput = 'Get-ChildItem | Where-Object ' + $res = TabExpansion2 -inputScript $ScriptInput -cursorColumn $ScriptInput.Length + $res.CompletionMatches[0].CompletionText | Should -Be "Attributes" + } + + it 'Should complete base class members of types without type definition AST' { + $res = TabExpansion2 -inputScript @' +class InheritedClassTest : System.Attribute +{ + [void] TestMethod() + { + $this. +'@ + $res.CompletionMatches.CompletionText | Should -Contain 'TypeId' + } + + it 'Should not complete parameter aliases if the real parameter is in the completion results' { + $res = TabExpansion2 -inputScript 'Get-ChildItem -p' + $res.CompletionMatches.CompletionText | Should -Not -Contain '-proga' + $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction' + } + + it 'Should not complete parameter aliases if the real parameter is in the completion results (Non ambiguous parameters)' { + $res = TabExpansion2 -inputScript 'Get-ChildItem -prog' + $res.CompletionMatches.CompletionText | Should -Not -Contain '-proga' + $res.CompletionMatches.CompletionText | Should -Contain '-ProgressAction' + } + + It 'Should complete dynamic parameters with partial input' { + # See issue: #19498 + try + { + Push-Location function: + $res = TabExpansion2 -inputScript 'Get-ChildItem -LiteralPath $PSHOME -Fi' + $res.CompletionMatches[1].CompletionText | Should -Be '-File' + } + finally + { + Pop-Location + } + } + it 'Should complete enum class members for Enums in script text' { + $res = TabExpansion2 -inputScript 'enum Test1 {Val1};([Test1]"").' + $res.CompletionMatches.CompletionText[0] | Should -Be 'value__' + $res.CompletionMatches.CompletionText | Should -Contain 'HasFlag(' + } + Context "Script name completion" { BeforeAll { Setup -f 'install-powershell.ps1' -Content "" @@ -422,6 +2184,36 @@ Describe "TabCompletion" -Tags CI { } } + Context "Script parameter completion" { + BeforeAll { + Setup -File -Path 'ModuleReqTest.ps1' -Content @' +#requires -Modules ThisModuleDoesNotExist +param ($Param1) +'@ + Setup -File -Path 'AdminReqTest.ps1' -Content @' +#requires -RunAsAdministrator +param ($Param1) +'@ + Push-Location ${TestDrive}\ + } + + AfterAll { + Pop-Location + } + + It "Input should successfully complete script parameter for script with failed script requirements" { + $res = TabExpansion2 -inputScript '.\ModuleReqTest.ps1 -' + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Param1' + } + + It "Input should successfully complete script parameter for admin script while not elevated" { + $res = TabExpansion2 -inputScript '.\AdminReqTest.ps1 -' + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches[0].CompletionText | Should -BeExactly '-Param1' + } + } + Context "File name completion" { BeforeAll { $tempDir = Join-Path -Path $TestDrive -ChildPath "baseDir" @@ -572,12 +2364,166 @@ Describe "TabCompletion" -Tags CI { $expected = ($expected | Sort-Object -CaseSensitive | ForEach-Object { "./$_" }) -join ":" } + + It "PSScriptRoot path completion when AST extent has file identity" { + $scriptText = '"$PSScriptRoot\BugFix.Tests"' + $tokens = $null + $scriptAst = [System.Management.Automation.Language.Parser]::ParseInput( + $scriptText, + $PSCommandPath, + [ref] $tokens, + [ref] $null) + + $cursorPosition = $scriptAst.Extent.StartScriptPosition. + GetType(). + GetMethod('CloneWithNewOffset', [System.Reflection.BindingFlags]'NonPublic, Instance'). + Invoke($scriptAst.Extent.StartScriptPosition, @($scriptText.Length - 1)) + + $res = TabExpansion2 -ast $scriptAst -tokens $tokens -positionOfCursor $cursorPosition + $res.CompletionMatches | Should -HaveCount 1 + $expectedPath = Join-Path $PSScriptRoot -ChildPath BugFix.Tests.ps1 + $res.CompletionMatches[0].CompletionText | Should -Be "`"$expectedPath`"" + } + + It "Relative path completion for using statement when AST extent has file identity" -TestCases @( + @{UsingKind = "module"; ExpectedFileName = 'UsingFileCompletionModuleTest.psm1'} + @{UsingKind = "assembly";ExpectedFileName = 'UsingFileCompletionAssemblyTest.dll'} + ) -test { + param($UsingKind, $ExpectedFileName) + $scriptText = "using $UsingKind .\UsingFileCompletion" + $tokens = $null + $scriptAst = [System.Management.Automation.Language.Parser]::ParseInput( + $scriptText, + (Join-Path -Path $tempDir -ChildPath ScriptInEditor.ps1), + [ref] $tokens, + [ref] $null) + + $cursorPosition = $scriptAst.Extent.StartScriptPosition. + GetType(). + GetMethod('CloneWithNewOffset', [System.Reflection.BindingFlags]'NonPublic, Instance'). + Invoke($scriptAst.Extent.StartScriptPosition, @($scriptText.Length - 1)) + + Push-Location -LiteralPath $PSHOME + $TestFile = Join-Path -Path $tempDir -ChildPath $ExpectedFileName + $null = New-Item -Path $TestFile + $res = TabExpansion2 -ast $scriptAst -tokens $tokens -positionOfCursor $cursorPosition + Pop-Location + + $ExpectedPath = Join-Path -Path '.\' -ChildPath $ExpectedFileName + $res.CompletionMatches.CompletionText | Where-Object {$_ -Like "*$ExpectedFileName"} | Should -Be $ExpectedPath + } + + It "Should handle '~' in completiontext when it's used to refer to home in input" { + $res = TabExpansion2 -inputScript "~$separator" + # select the first answer which does not have a space in the completion (those completions look like & '3D Objects') + $observedResult = $res.CompletionMatches.Where({$_.CompletionText.IndexOf("&") -eq -1})[0].CompletionText + $completedText = $res.CompletionMatches.CompletionText -join "," + if ($IsWindows) { + $observedResult | Should -BeLike "$home$separator*" -Because "$completedText" + } else { + $observedResult | Should -BeLike "~$separator*" -Because "$completedText" + } + } + + It "Should use '~' as relative filter text when not followed by separator" { + $TempDirName = "~TempDir" + $TempDirPath = Join-Path -Path $TestDrive -ChildPath "~TempDir" + $TempDir = New-Item -Path $TempDirPath -ItemType Directory -Force + Push-Location -Path $TestDrive + $res = TabExpansion2 -inputScript ~ + $res.CompletionMatches[0].CompletionText | Should -Be ".${separator}${TempDirName}" + } + + It 'Escapes backtick properly for path: ' -TestCases @( + @{LiteralPath = 'BacktickTest['; BacktickSingle = 1; BacktickDouble = 2; LiteralBacktickSingle = 0; LiteralBacktickDouble = 0} + @{LiteralPath = 'BacktickTest`['; BacktickSingle = 3; BacktickDouble = 6; LiteralBacktickSingle = 1; LiteralBacktickDouble = 2} + @{LiteralPath = 'BacktickTest``['; BacktickSingle = 5; BacktickDouble = 10; LiteralBacktickSingle = 2; LiteralBacktickDouble = 4} + @{LiteralPath = 'BacktickTest$'; BacktickSingle = 0; BacktickDouble = 1; LiteralBacktickSingle = 0; LiteralBacktickDouble = 1} + @{LiteralPath = 'BacktickTest`$'; BacktickSingle = 2; BacktickDouble = 3; LiteralBacktickSingle = 1; LiteralBacktickDouble = 3} + @{LiteralPath = 'BacktickTest``$'; BacktickSingle = 4; BacktickDouble = 7; LiteralBacktickSingle = 2; LiteralBacktickDouble = 5} + ) { + param($LiteralPath, $BacktickSingle, $BacktickDouble, $LiteralBacktickSingle, $LiteralBacktickDouble) + $NewPath = Join-Path -Path $TestDrive -ChildPath $LiteralPath + $null = New-Item -Path $NewPath -Force + Push-Location $TestDrive + + $InputText = "Get-ChildItem -Path {0}.${separator}BacktickTest" + $InputTextLiteral = "Get-ChildItem -LiteralPath {0}.${separator}BacktickTest" + + $Text = (TabExpansion2 -inputScript ($InputText -f "'")).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $BacktickSingle + + $Text = (TabExpansion2 -inputScript ($InputText -f '"')).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $BacktickDouble + + $Text = (TabExpansion2 -inputScript ($InputTextLiteral -f "'")).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $LiteralBacktickSingle + + $Text = (TabExpansion2 -inputScript ($InputTextLiteral -f '"')).CompletionMatches[0].CompletionText + $Text.Length - $Text.Replace('`','').Length | Should -Be $LiteralBacktickDouble + + Remove-Item -LiteralPath $LiteralPath + } + + It "Should add single quotes if there are double quotes in bare word file path" { + $BadQuote = [char]8220 + $TestFile1 = Join-Path -Path $TestDrive -ChildPath "Test1${BadQuote}File" + $null = New-Item -Path $TestFile1 -Force + $res = TabExpansion2 -inputScript "Get-ChildItem -Path $TestDrive\" + ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be "'$TestFile1'" + Remove-Item -LiteralPath $TestFile1 -Force + } + + It "Should escape double quote if the input string uses double quotes" { + $BadQuote = [char]8220 + $TestFile1 = Join-Path -Path $TestDrive -ChildPath "Test1${BadQuote}File" + $null = New-Item -Path $TestFile1 -Force + $res = TabExpansion2 -inputScript "Get-ChildItem -Path `"$TestDrive\" + $Expected = "`"$($TestFile1.Insert($TestFile1.LastIndexOf($BadQuote), '`'))`"" + ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be $Expected + Remove-Item -LiteralPath $TestFile1 -Force + } + + It "Should escape single quotes in file paths" { + $SingleQuote = "'" + $TestFile1 = Join-Path -Path $TestDrive -ChildPath "Test1${SingleQuote}File" + $null = New-Item -Path $TestFile1 -Force + # Regardless if the input string was singlequoted or not, we expect to add surrounding single quotes and + # escape the single quote in the file path with another singlequote. + $Expected = "'$($TestFile1.Insert($TestFile1.LastIndexOf($SingleQuote), "'"))'" + + $res = TabExpansion2 -inputScript "Get-ChildItem -Path '$TestDrive\" + ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be $Expected + + $res = TabExpansion2 -inputScript "Get-ChildItem -Path $TestDrive\" + ($res.CompletionMatches | Where-Object ListItemText -Like "Test1?File").CompletionText | Should -Be $Expected + + Remove-Item -LiteralPath $TestFile1 -Force + } + } + + It 'Should correct slashes in UNC path completion' -Skip:(!$IsWindows) { + $Res = TabExpansion2 -inputScript 'Get-ChildItem //localhost/c$/Windows' + $Res.CompletionMatches[0].CompletionText | Should -Be "'\\localhost\c$\Windows'" + } + + It 'Should keep custom drive names when completing file paths' { + $TempDriveName = "asdf" + $null = New-PSDrive -Name $TempDriveName -PSProvider FileSystem -Root $HOME + + $completions = (TabExpansion2 -inputScript "${TempDriveName}:\") + # select the first answer which does not have a space in the completion (those completions look like & '3D Objects') + $observedResult = $completions.CompletionMatches.Where({$_.CompletionText.IndexOf("&") -eq -1})[0].CompletionText + $completedText = $completions.CompletionMatches.CompletionText -join "," + + $observedResult | Should -BeLike "${TempDriveName}:*" -Because "$completionText" + Remove-PSDrive -Name $TempDriveName } Context "Cmdlet name completion" { BeforeAll { $testCases = @( - @{ inputStr = "get-c*item"; expected = "Get-ChildItem" } + @{ inputStr = "get-ch*item"; expected = "Get-ChildItem" } @{ inputStr = "set-alia?"; expected = "Set-Alias" } @{ inputStr = "s*-alias"; expected = "Set-Alias" } @{ inputStr = "se*-alias"; expected = "Set-Alias" } @@ -627,7 +2573,7 @@ Describe "TabCompletion" -Tags CI { @{ inputStr = '[math].G'; expected = 'GenericParameterAttributes'; setup = $null } @{ inputStr = '[Environment+specialfolder]::App'; expected = 'ApplicationData'; setup = $null } @{ inputStr = 'icm {get-pro'; expected = 'Get-Process'; setup = $null } - @{ inputStr = 'write-ouput (get-pro'; expected = 'Get-Process'; setup = $null } + @{ inputStr = 'write-output (get-pro'; expected = 'Get-Process'; setup = $null } @{ inputStr = 'iex "get-pro'; expected = '"Get-Process"'; setup = $null } @{ inputStr = '$variab'; expected = '$variableA'; setup = { $variableB = 2; $variableA = 1 } } @{ inputStr = 'a -'; expected = '-keys'; setup = { function a {param($keys) $a} } } @@ -677,6 +2623,7 @@ Describe "TabCompletion" -Tags CI { @{ inputStr = 'gmo Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null } @{ inputStr = 'rmo Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null } @{ inputStr = 'gcm -Module Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null } + @{ inputStr = 'gcm -ExcludeModule Microsoft.PowerShell.U'; expected = 'Microsoft.PowerShell.Utility'; setup = $null } @{ inputStr = 'gmo -list PackageM'; expected = 'PackageManagement'; setup = $null } @{ inputStr = 'gcm -Module PackageManagement Find-Pac'; expected = 'Find-Package'; setup = $null } @{ inputStr = 'ipmo PackageM'; expected = 'PackageManagement'; setup = $null } @@ -698,7 +2645,7 @@ Describe "TabCompletion" -Tags CI { ## if $PSHOME contains a space tabcompletion adds ' around the path @{ inputStr = 'cd $PSHOME\Modu'; expected = if($PSHOME.Contains(' ')) { "'$(Join-Path $PSHOME 'Modules')'" } else { Join-Path $PSHOME 'Modules' }; setup = $null } @{ inputStr = 'cd "$PSHOME\Modu"'; expected = "`"$(Join-Path $PSHOME 'Modules')`""; setup = $null } - @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" } else { Join-Path $PSHOME 'System.Management.Automation.dll'; Setup = $null }} + @{ inputStr = '$PSHOME\System.Management.Au'; expected = if($PSHOME.Contains(' ')) { "`& '$(Join-Path $PSHOME 'System.Management.Automation.dll')'" } else { Join-Path $PSHOME 'System.Management.Automation.dll'}; Setup = $null } @{ inputStr = '"$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null } @{ inputStr = '& "$PSHOME\System.Management.Au"'; expected = "`"$(Join-Path $PSHOME 'System.Management.Automation.dll')`""; setup = $null } ## tab completion AST-based tests @@ -713,7 +2660,7 @@ Describe "TabCompletion" -Tags CI { @{ inputStr = '[System.Management.Automation.Runspaces.runspacef'; expected = 'System.Management.Automation.Runspaces.RunspaceFactory'; setup = $null } @{ inputStr = '[specialfol'; expected = 'System.Environment+SpecialFolder'; setup = $null } ## tab completion for variable names in '{}' - @{ inputStr = '${PSDefault'; expected = '$PSDefaultParameterValues'; setup = $null } + @{ inputStr = '${PSDefault'; expected = '${PSDefaultParameterValues}'; setup = $null } ) } @@ -727,17 +2674,30 @@ Describe "TabCompletion" -Tags CI { } It "Tab completion UNC path" -Skip:(!$IsWindows) { - $homeDrive = $env:HOMEDRIVE.Replace(":", "$") - $beforeTab = "\\localhost\$homeDrive\wind" - $afterTab = "& '\\localhost\$homeDrive\Windows'" + $beforeTab = "\\localhost\ADMIN$\boo" + $afterTab = "& '\\localhost\ADMIN$\Boot'" + $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab + } + + It "Tab completion UNC path with forward slashes" -Skip:(!$IsWindows) { + $beforeTab = "//localhost/admin" + # it is expected that tab completion turns forward slashes into backslashes + $afterTab = "\\localhost\ADMIN$" $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab } + It "Tab completion UNC path with filesystem provider" -Skip:(!$IsWindows) { + $res = TabExpansion2 -inputScript 'Filesystem::\\localhost\admin' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Filesystem::\\localhost\ADMIN$' + } + It "Tab completion for registry" -Skip:(!$IsWindows) { $beforeTab = 'registry::HKEY_l' - $afterTab = 'registry::HKEY_LOCAL_MACHINE' + $afterTab = 'Registry::HKEY_LOCAL_MACHINE' $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab @@ -745,7 +2705,7 @@ Describe "TabCompletion" -Tags CI { It "Tab completion for wsman provider" -Skip:(!$IsWindows) { $beforeTab = 'wsman::localh' - $afterTab = 'wsman::localhost' + $afterTab = 'WSMan::localhost' $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab @@ -758,7 +2718,7 @@ Describe "TabCompletion" -Tags CI { New-Item -ItemType Directory -Path "$tempFolder/helloworld" > $null $tempFolder | Should -Exist $beforeTab = 'filesystem::{0}hello' -f $tempFolder - $afterTab = 'filesystem::{0}helloworld' -f $tempFolder + $afterTab = 'FileSystem::{0}helloworld' -f $tempFolder $res = TabExpansion2 -inputScript $beforeTab -cursorColumn $beforeTab.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -BeExactly $afterTab @@ -836,6 +2796,21 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[1].CompletionText | Should -BeExactly 'dog' } + It "Tab completion for validateSet attribute takes precedence over enums" { + function foo { param([ValidateSet('DarkBlue','DarkCyan')][ConsoleColor]$p) } + $inputStr = "foo " + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 2 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'DarkBlue' + $res.CompletionMatches[1].CompletionText | Should -BeExactly 'DarkCyan' + } + + It "Tab completion for attribute type" { + $inputStr = '[validateset()]$var1' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn 2 + $res.CompletionMatches.CompletionText | Should -Contain 'ValidateSet' + } + It "Tab completion for ArgumentCompleter when AST is passed to CompleteInput" { $scriptBl = { function Test-Completion { @@ -869,11 +2844,51 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches | Should -HaveCount 16 $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Black' - $inputStr = "baz Black " + $inputStr = "baz Black " + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 2 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'cat' + $res.CompletionMatches[1].CompletionText | Should -BeExactly 'dog' + } + + It "Tab completion for enum members after colon with space" -TestCases @( + @{ Space = 0 } + @{ Space = 1 } + ) { + param ($Space) + $inputStr = "Get-Command -Type:$(' ' * $Space)Al" $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches | Should -HaveCount 2 - $res.CompletionMatches[0].CompletionText | Should -BeExactly 'cat' - $res.CompletionMatches[1].CompletionText | Should -BeExactly 'dog' + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Alias' + $res.CompletionMatches[1].CompletionText | Should -BeExactly 'All' + } + + It "Tab completion for enum members between colon with space and space with value" -TestCases @( + @{ LeftSpace = 0; RightSpace = 0 } + @{ LeftSpace = 0; RightSpace = 1 } + @{ LeftSpace = 1; RightSpace = 0 } + @{ LeftSpace = 1; RightSpace = 1 } + ) { + param ($LeftSpace, $RightSpace) + $inputStrEndsWithCursor = "Get-Command -Type:$(' ' * $LeftSpace)" + $inputStr = $inputStrEndsWithCursor + "$(' ' * $RightSpace)Alias" + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStrEndsWithCursor.Length + $expectedArray = [enum]::GetNames([System.Management.Automation.CommandTypes]) | Sort-Object + $res.CompletionMatches.CompletionText | Should -Be $expectedArray + } + + It "Tab completion for enum members between comma with space and space with parameter" -TestCases @( + @{ LeftSpace = 0; RightSpace = 0 } + @{ LeftSpace = 0; RightSpace = 1 } + @{ LeftSpace = 1; RightSpace = 0 } + @{ LeftSpace = 1; RightSpace = 1 } + ) { + param ($LeftSpace, $RightSpace) + $inputStrEndsWithCursor = "Get-Command -Type Alias,$(' ' * $LeftSpace)" + $inputStr = $inputStrEndsWithCursor + "$(' ' * $RightSpace)-All" + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStrEndsWithCursor.Length + $expectedArray = [enum]::GetNames([System.Management.Automation.CommandTypes]) | Sort-Object + $res.CompletionMatches.CompletionText | Should -Be $expectedArray } It "Tab completion for enum members after comma" { @@ -884,6 +2899,36 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Configuration' } + It 'Tab completion for enum parameter is filtered against ' -TestCases @( + @{ Name = 'ValidateRange with enum-values'; Attribute = '[ValidateRange([System.ConsoleColor]::Blue, [System.ConsoleColor]::Cyan)]' } + @{ Name = 'ValidateRange with int-values'; Attribute = '[ValidateRange(9, 11)]' } + @{ Name = 'multiple ValidateRange-attributes'; Attribute = '[ValidateRange([System.ConsoleColor]::Blue, [System.ConsoleColor]::Cyan)][ValidateRange([System.ConsoleColor]::Gray, [System.ConsoleColor]::Red)]' } + ) { + param($Name, $Attribute) + $functionDefinition = 'param ( {0}[consolecolor]$color )' -f $Attribute + Set-Item -Path function:baz -Value $functionDefinition + $inputStr = 'baz -color ' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 3 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Blue' + $res.CompletionMatches[1].CompletionText | Should -BeExactly 'Cyan' + $res.CompletionMatches[2].CompletionText | Should -BeExactly 'Green' + } + + It 'Tab completion for enum parameter is filtered with ValidateRange using rangekind' { + $functionDefinition = 'param ( [ValidateRange([System.Management.Automation.ValidateRangeKind]::NonPositive)][consolecolor]$color )' -f $Attribute + Set-Item -Path function:baz -Value $functionDefinition + $inputStr = 'baz -color ' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Black' # 0 = NonPositive + } + + It 'Tab completion of $_ inside incomplete switch condition' { + $res = TabExpansion2 -inputScript 'Get-PSDrive | Sort-Object -Property {switch ($_.nam' + $res.CompletionMatches[0].CompletionText | Should -Be 'Name' + } + It "Test [CommandCompletion]::GetNextResult" { $inputStr = "Get-Command -Type Alias,c" $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length @@ -908,6 +2953,75 @@ Describe "TabCompletion" -Tags CI { $res.CompletionMatches[0].CompletionText | Should -BeExactly "Test history completion" } + It "Test #requires parameter completion" { + $res = TabExpansion2 -inputScript "#requires -" -cursorColumn 11 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "Modules" + } + + It "Test #requires parameter value completion" { + $res = TabExpansion2 -inputScript "#requires -PSEdition " -cursorColumn 21 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "Core" + } + + It "Test no completion after #requires -RunAsAdministrator" { + $res = TabExpansion2 -inputScript "#requires -RunAsAdministrator -" -cursorColumn 31 + $res.CompletionMatches | Should -HaveCount 0 + } + + It "Test no suggestions for already existing parameters in #requires" { + $res = TabExpansion2 -inputScript "#requires -Modules -" -cursorColumn 20 + $res.CompletionMatches.CompletionText | Should -Not -Contain "Modules" + } + + It "Test module completion in #requires without quotes" { + $res = TabExpansion2 -inputScript "#requires -Modules P" -cursorColumn 20 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches.CompletionText | Should -Contain "Pester" + } + + It "Test module completion in #requires with quotes" { + $res = TabExpansion2 -inputScript '#requires -Modules "' -cursorColumn 20 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches.CompletionText | Should -Contain "Pester" + } + + It "Test module completion in #requires with multiple modules" { + $res = TabExpansion2 -inputScript "#requires -Modules Pester," -cursorColumn 26 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches.CompletionText | Should -Contain "Pester" + } + + It "Test hashtable key completion in #requires statement for modules" { + $res = TabExpansion2 -inputScript "#requires -Modules @{" + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "GUID" + } + + It "Test no suggestions for already existing hashtable keys in #requires statement for modules" { + $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="Pester";' -cursorColumn 41 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches.CompletionText | Should -Not -Contain "ModuleName" + } + + It "Test no suggestions for mutually exclusive hashtable keys in #requires statement for modules" { + $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="Pester";RequiredVersion="1.0";' -cursorColumn 63 + $res.CompletionMatches.CompletionText | Should -BeExactly "GUID" + } + + It "Test no suggestions for RequiredVersion key in #requires statement when ModuleVersion is specified" { + $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="Pester";ModuleVersion="1.0";' -cursorColumn 61 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches.CompletionText | Should -Not -Contain "RequiredVersion" + } + + It "Test module completion in #requires statement for hashtables" { + $res = TabExpansion2 -inputScript '#requires -Modules @{ModuleName="p' -cursorColumn 34 + $res.CompletionMatches.Count | Should -BeGreaterThan 0 + $res.CompletionMatches.CompletionText | Should -Contain "Pester" + } + It "Test Attribute member completion" { $inputStr = "function bar { [parameter(]param() }" $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf('(') + 1) @@ -915,14 +3029,63 @@ Describe "TabCompletion" -Tags CI { $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Position" $entry.CompletionText | Should -BeExactly "Position" } + It "Test Attribute member completion multiple members" { $inputStr = "function bar { [parameter(Position,]param() }" $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf(',') + 1) - $res.CompletionMatches | Should -HaveCount 10 + $res.CompletionMatches | Should -HaveCount 9 $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Mandatory" $entry.CompletionText | Should -BeExactly "Mandatory" } + It "Should complete member in attribute argument value" { + $inputStr = '[ValidateRange(1,[int]::Maxva^)]$a' + $CursorIndex = $inputStr.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $inputStr.Remove($CursorIndex, 1) + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "MaxValue" + } + + It "Test Attribute scriptblock completion" { + $inputStr = '[ValidateScript({Get-Child})]$Test=ls' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn ($inputStr.IndexOf('}')) + $res.CompletionMatches | Should -HaveCount 1 + $entry = $res.CompletionMatches | Where-Object CompletionText -EQ "Get-ChildItem" + $entry.CompletionText | Should -BeExactly "Get-ChildItem" + } + + It '' -TestCases @( + @{ + Intent = 'Complete attribute members on empty line' + Expected = @('Position','ParameterSetName','Mandatory','ValueFromPipeline','ValueFromPipelineByPropertyName','ValueFromRemainingArguments','HelpMessage','HelpMessageBaseName','HelpMessageResourceId','DontShow') + TestString = @' +function bar { [parameter( + + +^ + + )]param() } +'@ + } + @{ + Intent = 'Complete attribute members on empty line with preceding member' + Expected = @('Position','ParameterSetName','Mandatory','ValueFromPipeline','ValueFromPipelineByPropertyName','ValueFromRemainingArguments','HelpMessage','HelpMessageBaseName','HelpMessageResourceId','DontShow') + TestString = @' +function bar { [parameter( +Mandatory, + +^ + + )]param() } +'@ + } + ){ + param($Expected, $TestString) + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches[0].CompletionText | Should -BeIn $Expected + } + It "Test completion with line continuation" { $inputStr = @' dir -Recurse ` @@ -950,8 +3113,99 @@ dir -Recurse ` It "Test completion with exact match" { $inputStr = 'get-content -wa' $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 3 + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Wait,-WarningAction,-WarningVariable" + } + + It "Test completion with splatted variable" { + $inputStr = 'Get-Content @Splat -P' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 4 + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-Path,-PipelineVariable,-ProgressAction,-PSPath" + } + + It "Test completion for HttpVersion parameter name" { + $inputStr = 'Invoke-WebRequest -HttpV' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "-HttpVersion" + } + + It "Test completion for HttpVersion parameter" { + $inputStr = 'Invoke-WebRequest -HttpVersion ' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches | Should -HaveCount 4 - [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "-wa,-Wait,-WarningAction,-WarningVariable" + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "1.0,1.1,2.0,3.0" + } + + It "Test completion for HttpVersion parameter with input" { + $inputStr = 'Invoke-WebRequest -HttpVersion 1' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -HaveCount 2 + [string]::Join(',', ($res.CompletionMatches.completiontext | Sort-Object)) | Should -BeExactly "1.0,1.1" + } + + It 'Should complete Select-Object properties without duplicates' { + $res = TabExpansion2 -inputScript '$PSVersionTable | Select-Object -Property Count,' + $res.CompletionMatches.CompletionText | Should -Not -Contain "Count" + } + + It '' -TestCases @( + @{ + Intent = 'Complete loop labels with no input' + Expected = 'Outer','Inner' + TestString = ':Outer while ($true){:Inner while ($true){ break ^ }}' + } + @{ + Intent = 'Complete loop labels that are accessible' + Expected = 'Outer' + TestString = ':Outer do {:Inner while ($true){ break } continue ^ } until ($false)' + } + @{ + Intent = 'Complete loop labels with partial input' + Expected = 'Outer' + TestString = ':Outer do {:Inner while ($true){ break } continue o^ut } while ($true)' + } + @{ + Intent = 'Complete loop label for incomplete switch' + Expected = 'Outer' + TestString = ':Outer switch ($x){"randomValue"{ continue ^' + } + @{ + Intent = 'Complete loop label for incomplete do loop' + Expected = 'Outer' + TestString = ':Outer do {:Inner while ($true){ break } continue ^' + } + @{ + Intent = 'Complete loop label for incomplete for loop' + Expected = 'forLoop' + TestString = ':forLoop for ($i = 0; $i -lt $SomeCollection.Count; $i++) {continue ^' + } + @{ + Intent = 'Complete loop label for incomplete while loop' + Expected = 'WhileLoop' + TestString = ':WhileLoop while ($true){ break ^' + } + @{ + Intent = 'Complete loop label for incomplete foreach loop' + Expected = 'foreachLoop' + TestString = ':foreachLoop foreach ($x in $y) { break ^' + } + @{ + Intent = 'Not Complete loop labels with colon' + Expected = $null + TestString = ':Outer foreach ($x in $y){:Inner for ($i = 0; $i -lt $X.Count; $i++){ break :O^}}' + } + @{ + Intent = 'Not Complete loop labels if cursor is in front of existing label' + Expected = $null + TestString = ':Outer switch ($x){"Value1"{break ^ Outer}}' + } + ){ + param($Expected, $TestString) + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches.CompletionText | Should -BeExactly $Expected } } @@ -970,7 +3224,7 @@ dir -Recurse ` } It "Test complete module file name" { - $inputStr = "using module test" + $inputStr = "using module testm" $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches | Should -HaveCount 1 $res.CompletionMatches[0].CompletionText | Should -BeExactly ".${separator}testModule.psm1" @@ -1022,6 +3276,21 @@ dir -Recurse ` $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected } + It "Tab completion for file array element between comma with space and space with parameter" -TestCases @( + @{ LeftSpace = 0; RightSpace = 0 } + @{ LeftSpace = 0; RightSpace = 1 } + @{ LeftSpace = 1; RightSpace = 0 } + @{ LeftSpace = 1; RightSpace = 1 } + ) { + param ($LeftSpace, $RightSpace) + $inputStrEndsWithCursor = "dir .\commaA.txt,$(' ' * $LeftSpace)" + $inputStr = $inputStrEndsWithCursor + "$(' ' * $RightSpace)-File" + $expected = ".${separator}commaA.txt" + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStrEndsWithCursor.Length + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected + } + It "Test comma with Enum array element" { $inputStr = "gcm -CommandType Cmdlet," $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length @@ -1112,31 +3381,6 @@ dir -Recurse ` } } - Context "User-overridden TabExpansion implementations" { - It "Override TabExpansion with function" { - function TabExpansion ($line, $lastword) { - "Overridden-TabExpansion-Function" - } - - $inputStr = '$PID.' - $res = [System.Management.Automation.CommandCompletion]::CompleteInput($inputStr, $inputst.Length, $null) - $res.CompletionMatches | Should -HaveCount 1 - $res.CompletionMatches[0].CompletionText | Should -BeExactly 'Overridden-TabExpansion-Function' - } - - It "Override TabExpansion with alias" { - function OverrideTabExpansion ($line, $lastword) { - "Overridden-TabExpansion-Alias" - } - Set-Alias -Name TabExpansion -Value OverrideTabExpansion - - $inputStr = '$PID.' - $res = [System.Management.Automation.CommandCompletion]::CompleteInput($inputStr, $inputst.Length, $null) - $res.CompletionMatches | Should -HaveCount 1 - $res.CompletionMatches[0].CompletionText | Should -BeExactly "Overridden-TabExpansion-Alias" - } - } - Context "No tab completion tests" { BeforeAll { $testCases = @( @@ -1152,6 +3396,13 @@ dir -Recurse ` $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches | Should -BeNullOrEmpty } + + It "A single dash should not complete to anything" { + function test-{} + $inputStr = 'git -' + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches | Should -BeNullOrEmpty + } } Context "Tab completion error tests" { @@ -1176,6 +3427,14 @@ dir -Recurse ` param($inputStr, $expected) $inputStr | Should -Throw -ErrorId $expected } + + It "Should not throw errors in tab completion with empty input string" { + {[System.Management.Automation.CommandCompletion]::CompleteInput("", 0, $null)} | Should -Not -Throw + } + + It "Should not throw errors in tab completion with empty input ast" { + {[System.Management.Automation.CommandCompletion]::CompleteInput({}.Ast, @(), {}.Ast.Extent.StartScriptPosition, $null)} | Should -Not -Throw + } } Context "DSC tab completion tests" { @@ -1213,6 +3472,11 @@ dir -Recurse ` It "Input '' should successfully complete" -TestCases $testCases -Skip:(!$IsWindows) { param($inputStr, $expected) + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "TBD" + } + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -BeExactly $expected @@ -1247,6 +3511,18 @@ dir -Recurse ` @{ inputStr = '[Microsoft.Management.Infrastructure.CimClass]$c = $null; $c.CimClassNam'; expected = 'CimClassName' } @{ inputStr = '[Microsoft.Management.Infrastructure.CimClass]$c = $null; $c.CimClassName.Substrin'; expected = 'Substring(' } @{ inputStr = 'Get-CimInstance -ClassName Win32_Process | %{ $_.ExecutableP'; expected = 'ExecutablePath' } + @{ inputStr = 'Get-CimInstance -ClassName Win32_Process | Invoke-CimMethod -MethodName SetPriority -Arguments @{'; expected = 'Priority' } + @{ inputStr = 'Get-CimInstance -ClassName Win32_Service | Invoke-CimMethod -MethodName Change -Arguments @{d'; expected = 'DesktopInteract' } + @{ inputStr = 'Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments @{'; expected = 'CommandLine' } + @{ inputStr = 'New-CimInstance Win32_Environment -Property @{'; expected = 'Caption' } + @{ inputStr = 'Get-CimInstance Win32_Environment | Set-CimInstance -Property @{'; expected = 'Name' } + @{ inputStr = 'Set-CimInstance -Namespace root/CIMV'; expected = 'root/CIMV2' } + @{ inputStr = 'Get-CimInstance Win32_Process -Property '; expected = 'Caption' } + @{ inputStr = 'Get-CimInstance Win32_Process -Property Caption,'; expected = 'Description' } + ) + $FailCases = @( + @{ inputStr = "Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments " } + @{ inputStr = "New-CimInstance Win32_Process -Property " } ) } @@ -1257,26 +3533,37 @@ dir -Recurse ` $res.CompletionMatches.Count | Should -BeGreaterThan 0 $res.CompletionMatches[0].CompletionText | Should -Be $expected } + + It "CIM cmdlet input '' should not successfully complete" -TestCases $FailCases -Skip:(!$IsWindows) { + param($inputStr) + + $res = TabExpansion2 -inputScript $inputStr -cursorColumn $inputStr.Length + $res.CompletionMatches[0].ResultType | should -Not -Be 'Property' + } } Context "Module cmdlet completion tests" { It "ArugmentCompleter for PSEdition should work for ''" -TestCases @( @{cmd = "Get-Module -PSEdition "; expected = "Desktop", "Core"} + @{cmd = "Get-Module -PSEdition '"; expected = "'Desktop'", "'Core'"} + @{cmd = "Get-Module -PSEdition """; expected = """Desktop""", """Core"""} + @{cmd = "Get-Module -PSEdition 'Desk"; expected = "'Desktop'"} + @{cmd = "Get-Module -PSEdition ""Desk"; expected = """Desktop"""} + @{cmd = "Get-Module -PSEdition Co"; expected = "Core"} + @{cmd = "Get-Module -PSEdition 'Co"; expected = "'Core'"} + @{cmd = "Get-Module -PSEdition ""Co"; expected = """Core"""} ) { param($cmd, $expected) $res = TabExpansion2 -inputScript $cmd -cursorColumn $cmd.Length - $res.CompletionMatches | Should -HaveCount $expected.Count - $completionOptions = "" - foreach ($completion in $res.CompletionMatches) { - $completionOptions += $completion.ListItemText - } - $completionOptions | Should -BeExactly ([string]::Join("", $expected)) + $completionText = $res.CompletionMatches.CompletionText + $completionText -join ' ' | Should -BeExactly ($expected -join ' ') } } Context "Tab completion help test" { BeforeAll { - if ([System.Management.Automation.Platform]::IsWindows) { + New-Item -ItemType File (Join-Path ${TESTDRIVE} "pwsh.xml") + if ($IsWindows) { $userHelpRoot = Join-Path $HOME "Documents/PowerShell/Help/" } else { $userModulesRoot = [System.Management.Automation.Platform]::SelectProductNameForDirectory([System.Management.Automation.Platform+XDG_Type]::USER_MODULES) @@ -1285,29 +3572,331 @@ dir -Recurse ` } It 'Should complete about help topic' { - $aboutHelpPathUserScope = Join-Path $userHelpRoot (Get-Culture).Name - $aboutHelpPathAllUsersScope = Join-Path $PSHOME (Get-Culture).Name + $helpName = "about_Splatting" + $helpFileName = "${helpName}.help.txt" + $inputScript = "get-help about_spla" + $culture = "en-US" + $aboutHelpPathUserScope = Join-Path $userHelpRoot $culture + $aboutHelpPathAllUsersScope = Join-Path $PSHOME $culture + $expectedCompletionCount = 0 ## If help content does not exist, tab completion will not work. So update it first. - $userScopeHelp = Test-Path (Join-Path $aboutHelpPathUserScope "about_Splatting.help.txt") - $allUserScopeHelp = Test-Path (Join-Path $aboutHelpPathAllUsersScope "about_Splatting.help.txt") - if ((-not $userScopeHelp) -and (-not $aboutHelpPathAllUsersScope)) { + $userHelpPath = Join-Path $aboutHelpPathUserScope $helpFileName + $userScopeHelp = Test-Path $userHelpPath + if ($userScopeHelp) { + $expectedCompletionCount++ + } else { Update-Help -Force -ErrorAction SilentlyContinue -Scope 'CurrentUser' + if (Test-Path $userHelpPath) { + $expectedCompletionCount++ + } + } + + $allUserScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersScope $helpFileName) + if ($allUserScopeHelpPath) { + $expectedCompletionCount++ + } + + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $inputScript.Length + $res.CompletionMatches | Should -HaveCount $expectedCompletionCount + $res.CompletionMatches[0].CompletionText | Should -BeExactly $helpName + } + + It 'Should complete about help topic regardless of culture' { + try + { + ## Save original culture and temporarily set it to da-DK because there's no localized help for da-DK. + $OriginalCulture = [cultureinfo]::CurrentCulture + $defaultCulture = "en-US" + $culture = "da-DK" + [cultureinfo]::CurrentCulture = $culture + $helpName = "about_Splatting" + $helpFileName = "${helpName}.help.txt" + + $aboutHelpPathUserScope = Join-Path $userHelpRoot $culture + $aboutHelpPathAllUsersScope = Join-Path $PSHOME $culture + $expectedCompletionCount = 0 + + ## If help content does not exist, tab completion will not work. So update it first. + $userHelpPath = Join-Path $aboutHelpPathUserScope $helpFileName + $userScopeHelp = Test-Path $userHelpPath + if ($userScopeHelp) { + $expectedCompletionCount++ + } + else { Update-Help -Force -ErrorAction SilentlyContinue -Scope 'CurrentUser' + if (Test-Path $userHelpPath) { + $expectedCompletionCount++ + } + else { + $aboutHelpPathUserScope = Join-Path $userHelpRoot $defaultCulture + $aboutHelpPathAllUsersScope = Join-Path $PSHOME $defaultCulture + $userHelpDefaultPath = Join-Path $aboutHelpPathUserScope $helpFileName + $userDefaultScopeHelp = Test-Path $userHelpDefaultPath + + if ($userDefaultScopeHelp) { + $expectedCompletionCount++ + } + } + } + + $allUserScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersScope $helpFileName) + if ($allUserScopeHelpPath) { + $expectedCompletionCount++ + } + else { + $aboutHelpPathAllUsersDefaultScope = Join-Path $PSHOME $defaultCulture + $allUsersDefaultScopeHelpPath = Test-Path (Join-Path $aboutHelpPathAllUsersDefaultScope $helpFileName) + + if ($allUsersDefaultScopeHelpPath) { + $expectedCompletionCount++ + } + } + + $res = TabExpansion2 -inputScript 'get-help about_spla' -cursorColumn 'get-help about_spla'.Length + $res.CompletionMatches | Should -HaveCount $expectedCompletionCount + $res.CompletionMatches[0].CompletionText | Should -BeExactly $helpName + } + finally + { + [cultureinfo]::CurrentCulture = $OriginalCulture + } + } + It '' -TestCases @( + @{ + Intent = 'Complete help keywords with minimal input' + Expected = @( + "COMPONENT", + "DESCRIPTION", + "EXAMPLE", + "EXTERNALHELP", + "FORWARDHELPCATEGORY", + "FORWARDHELPTARGETNAME", + "FUNCTIONALITY", + "INPUTS", + "LINK", + "NOTES", + "OUTPUTS", + "PARAMETER", + "REMOTEHELPRUNSPACE", + "ROLE", + "SYNOPSIS" + ) + TestString = @' +<# +.^ +#> +'@ + } + @{ + Intent = 'Complete help keywords without duplicates' + Expected = $null + TestString = @' +<# +.SYNOPSIS +.S^ +#> +'@ + } + @{ + Intent = 'Complete help keywords with allowed duplicates' + Expected = 'PARAMETER' + TestString = @' +<# +.PARAMETER +.Paramet^ +#> +'@ + } + @{ + Intent = 'Complete help keyword FORWARDHELPTARGETNAME argument' + Expected = 'Get-ChildItem' + TestString = @' +<# +.FORWARDHELPTARGETNAME Get-Child^ +#> +'@ + } + @{ + Intent = 'Complete help keyword FORWARDHELPCATEGORY argument' + Expected = 'Cmdlet' + TestString = @' +<# +.FORWARDHELPCATEGORY C^ +#> +'@ + } + @{ + Intent = 'Complete help keyword REMOTEHELPRUNSPACE argument' + Expected = 'PSEdition' + TestString = @' +<# +.REMOTEHELPRUNSPACE PSEditi^ +#> +'@ + } + @{ + Intent = 'Complete help keyword EXTERNALHELP argument' + Expected = Join-Path $TESTDRIVE "pwsh.xml" + TestString = @" +<# +.EXTERNALHELP $TESTDRIVE\pwsh.^ +#> +"@ + } + @{ + Intent = 'Complete help keyword PARAMETER argument for script' + Expected = 'Param1' + TestString = @' +<# +.PARAMETER ^ +#> +param($Param1) +'@ + } + @{ + Intent = 'Complete help keyword PARAMETER argument for function with help inside' + Expected = 'param2' + TestString = @' +function MyFunction ($param1, $param2) +{ +<# +.PARAMETER param1 +.PARAMETER ^ +#> +} +'@ + } + @{ + Intent = 'Complete help keyword PARAMETER argument for function with help before it' + Expected = 'param1','param2' + TestString = @' +<# +.PARAMETER ^ +#> +function MyFunction ($param1, $param2) +{ +} +'@ + } + @{ + Intent = 'Complete help keyword PARAMETER argument for advanced function with help inside' + Expected = 'Param1' + TestString = @' +function Verb-Noun +{ +<# +.PARAMETER ^ +#> + [CmdletBinding()] + Param + ( + $Param1 + ) + + Begin + { + } + Process + { + } + End + { + } +} +'@ + } + @{ + Intent = 'Complete help keyword PARAMETER argument for nested function with help before it' + Expected = 'param3','param4' + TestString = @' +function MyFunction ($param1, $param2) +{ + <# + .PARAMETER ^ + #> + function MyFunction2 ($param3, $param4) + { + } +} +'@ } + @{ + Intent = 'Complete help keyword PARAMETER argument for function inside advanced function' + Expected = 'param1','param2' + TestString = @' +function Verb-Noun +{ + Param + ( + [Parameter()] + [string[]] + $ParamA + ) + Begin + { + <# + .Parameter ^ + #> + function MyFunction ($param1, $param2) + { + } + } +} +'@ + } + @{ + Intent = 'Not complete help keyword PARAMETER argument if following function is too far away' + Expected = $null + TestString = @' +<# +.PARAMETER ^ +#> + + +function MyFunction ($param1, $param2) +{ +} +'@ + } + ){ + param($Expected, $TestString) + $CursorIndex = $TestString.IndexOf('^') + $res = TabExpansion2 -cursorColumn $CursorIndex -inputScript $TestString.Remove($CursorIndex, 1) + $res.CompletionMatches.CompletionText | Should -BeExactly $Expected + } + } - # If help content is present on both scopes, expect 2 or else expect 1 completion. - $expectedCompletions = if ($userScopeHelp -and $allUserScopeHelp) { 2 } else { 1 } + It 'Should complete module specification keys in using module statement' { + $res = TabExpansion2 -inputScript 'using module @{' + $res.CompletionMatches.CompletionText -join ' ' | Should -BeExactly "GUID MaximumVersion ModuleName ModuleVersion RequiredVersion" + $res.CompletionMatches[0].ToolTip | Should -Not -Be $res.CompletionMatches[0].CompletionText + } + + It 'Should not fallback to file completion when completing typenames' { + $Text = '[abcdefghijklmnopqrstuvwxyz]' + $res = TabExpansion2 -inputScript $Text -cursorColumn ($Text.Length - 1) + $res.CompletionMatches | Should -HaveCount 0 + } +} - $res = TabExpansion2 -inputScript 'get-help about_spla' -cursorColumn 'get-help about_spla'.Length - $res.CompletionMatches | Should -HaveCount $expectedCompletions - $res.CompletionMatches[0].CompletionText | Should -BeExactly 'about_Splatting' +Describe "TabCompletion elevated tests" -Tags CI, RequireAdminOnWindows { + It "Tab completion UNC path with spaces" -Skip:(!$IsWindows) { + $Share = New-SmbShare -Temporary -ReadAccess (whoami.exe) -Path C:\ -Name "Test Share" + $res = TabExpansion2 -inputScript '\\localhost\test' + $res.CompletionMatches[0].CompletionText | Should -BeExactly "& '\\localhost\Test Share'" + if ($null -ne $Share) + { + Remove-SmbShare -InputObject $Share -Force -Confirm:$false } } } Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminOnWindows { BeforeAll { - if ($IsWindows) { + $skipTest = -not $IsWindows + $pendingTest = $IsWindows -and (Test-IsWinWow64) + + if (-not $skipTest -and -not $pendingTest) { $session = New-RemoteSession $powershell = [powershell]::Create() $powershell.Runspace = $session.Runspace @@ -1325,11 +3914,16 @@ Describe "Tab completion tests with remote Runspace" -Tags Feature,RequireAdminO ) } else { $defaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["It:Skip"] = $true + + if ($skipTest) { + $PSDefaultParameterValues["It:Skip"] = $true + } elseif ($pendingTest) { + $PSDefaultParameterValues["It:Pending"] = $true + } } } AfterAll { - if ($IsWindows) { + if (-not $skipTest -and -not $pendingTest) { Remove-PSSession $session $powershell.Dispose() } else { @@ -1397,7 +3991,7 @@ Describe "WSMan Config Provider tab complete tests" -Tags Feature,RequireAdminOn @{path = "localhost\plugin"; parameter = "-ru"; expected = "RunAsCredential"}, @{path = "localhost\plugin"; parameter = "-us"; expected = "UseSharedProcess"}, @{path = "localhost\plugin"; parameter = "-au"; expected = "AutoRestart"}, - @{path = "localhost\plugin"; parameter = "-pr"; expected = "ProcessIdleTimeoutSec"}, + @{path = "localhost\plugin"; parameter = "-proc"; expected = "ProcessIdleTimeoutSec"}, @{path = "localhost\Plugin\microsoft.powershell\Resources\"; parameter = "-re"; expected = "ResourceUri"}, @{path = "localhost\Plugin\microsoft.powershell\Resources\"; parameter = "-ca"; expected = "Capability"} ) { @@ -1418,4 +4012,185 @@ Describe "WSMan Config Provider tab complete tests" -Tags Feature,RequireAdminOn # https://github.com/PowerShell/PowerShell/issues/4744 # TODO: move to test cases above once working } + + Context "Tab completion for switch cases on `$PSBoundParameters.Keys" { + It "Should complete parameter names in switch case for `$PSBoundParameters.Keys" { + $inputScript = @" +function Test-Func { + param( + [string]`$Param1, + [string]`$Param2, + [int]`$Count + ) + switch (`$PSBoundParameters.Keys) { + P + } +} +"@ + $cursorPosition = $inputScript.IndexOf("P", $inputScript.IndexOf("Keys)")) + 1 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 2 + $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object + $completionTexts[0] | Should -BeExactly "Param1" + $completionTexts[1] | Should -BeExactly "Param2" + } + + It "Should complete all parameter names when prefix matches single param" { + $inputScript = @" +function Test-Func { + param( + [string]`$Name, + [int]`$Value + ) + switch (`$PSBoundParameters.Keys) { + N + } +} +"@ + $cursorPosition = $inputScript.IndexOf("N", $inputScript.IndexOf("Keys)")) + 1 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "Name" + } + + It "Should complete parameter names in scriptblock param" { + $inputScript = @" +`$sb = { + param( + [string]`$ScriptParam1, + [string]`$ScriptParam2 + ) + switch (`$PSBoundParameters.Keys) { + S + } +} +"@ + $cursorPosition = $inputScript.IndexOf("S", $inputScript.IndexOf("Keys)")) + 1 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 2 + $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object + $completionTexts[0] | Should -BeExactly "ScriptParam1" + $completionTexts[1] | Should -BeExactly "ScriptParam2" + } + } + + Context "Tab completion for `$PSBoundParameters access patterns" { + It "Should complete parameter names for ContainsKey method" { + $inputScript = @" +function Test-Func { + param([string]`$Param1, [string]`$Param2, [int]`$Count) + if (`$PSBoundParameters.ContainsKey('P')) { } +} +"@ + $cursorPosition = $inputScript.IndexOf("'P'") + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 2 + $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object + $completionTexts[0] | Should -BeExactly "'Param1'" + $completionTexts[1] | Should -BeExactly "'Param2'" + } + + It "Should complete parameter names for indexer access" { + $inputScript = @" +function Test-Func { + param([string]`$Param1, [string]`$Param2, [int]`$Count) + `$value = `$PSBoundParameters['P'] +} +"@ + $cursorPosition = $inputScript.IndexOf("'P'") + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 2 + $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object + $completionTexts[0] | Should -BeExactly "'Param1'" + $completionTexts[1] | Should -BeExactly "'Param2'" + } + + It "Should complete parameter names for Remove method" { + $inputScript = @" +function Test-Func { + param([string]`$Param1, [string]`$Param2, [int]`$Count) + `$PSBoundParameters.Remove('C') +} +"@ + $cursorPosition = $inputScript.IndexOf("'C'") + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 1 + $res.CompletionMatches[0].CompletionText | Should -BeExactly "'Count'" + } + + It "Should complete with double quotes when using double-quoted string" { + $inputScript = @" +function Test-Func { + param([string]`$Param1, [string]`$Param2) + if (`$PSBoundParameters.ContainsKey("P")) { } +} +"@ + $cursorPosition = $inputScript.IndexOf('"P"') + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + $res.CompletionMatches | Should -HaveCount 2 + $completionTexts = $res.CompletionMatches.CompletionText | Sort-Object + $completionTexts[0] | Should -BeExactly '"Param1"' + $completionTexts[1] | Should -BeExactly '"Param2"' + } + + It "Should not complete for non-PSBoundParameters variable with indexer" { + $inputScript = @" +function Test-Func { + param([string]`$Param1) + `$hash = @{} + `$value = `$hash['P'] +} +"@ + $cursorPosition = $inputScript.IndexOf("'P'") + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + # Should not return Param1 as completion + $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq "'Param1'" } + $paramCompletion | Should -BeNullOrEmpty + } + + It "Should not complete for non-PSBoundParameters variable with ContainsKey" { + $inputScript = @" +function Test-Func { + param([string]`$Param1) + `$hash = @{} + if (`$hash.ContainsKey('P')) { } +} +"@ + $cursorPosition = $inputScript.IndexOf("'P'") + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + # Should not return Param1 as completion + $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq "'Param1'" } + $paramCompletion | Should -BeNullOrEmpty + } + + It "Should not complete for non-PSBoundParameters variable with Remove" { + $inputScript = @" +function Test-Func { + param([string]`$Param1) + `$hash = @{} + `$hash.Remove('P') +} +"@ + $cursorPosition = $inputScript.IndexOf("'P'") + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + # Should not return Param1 as completion + $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq "'Param1'" } + $paramCompletion | Should -BeNullOrEmpty + } + + It "Should not complete for non-PSBoundParameters variable with double quotes" { + $inputScript = @" +function Test-Func { + param([string]`$Param1) + `$hash = @{} + if (`$hash.ContainsKey("P")) { } +} +"@ + $cursorPosition = $inputScript.IndexOf('"P"') + 2 + $res = TabExpansion2 -inputScript $inputScript -cursorColumn $cursorPosition + # Should not return Param1 as completion + $paramCompletion = $res.CompletionMatches | Where-Object { $_.CompletionText -eq '"Param1"' } + $paramCompletion | Should -BeNullOrEmpty + } + } } diff --git a/test/powershell/Installer/WindowsInstaller.Tests.ps1 b/test/powershell/Installer/WindowsInstaller.Tests.ps1 deleted file mode 100644 index 66bd08e74f5..00000000000 --- a/test/powershell/Installer/WindowsInstaller.Tests.ps1 +++ /dev/null @@ -1,39 +0,0 @@ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -Describe "Windows Installer" -Tags "Scenario" { - - BeforeAll { - $skipTest = -not $IsWindows - $preRequisitesLink = 'https://aka.ms/pscore6-prereq' - $linkCheckTestCases = @( - @{ Name = "Universal C Runtime"; Url = $preRequisitesLink } - @{ Name = "WMF 4.0"; Url = "https://www.microsoft.com/download/details.aspx?id=40855" } - @{ Name = "WMF 5.0"; Url = "https://www.microsoft.com/download/details.aspx?id=50395" } - @{ Name = "WMF 5.1"; Url = "https://www.microsoft.com/download/details.aspx?id=54616" } - ) - } - - It "WiX (Windows Installer XML) file contains pre-requisites link $preRequisitesLink" -Skip:$skipTest { - $wixProductFile = Join-Path -Path $PSScriptRoot -ChildPath "..\..\..\assets\wix\Product.wxs" - (Get-Content $wixProductFile -Raw).Contains($preRequisitesLink) | Should -BeTrue - } - - ## Running 'Invoke-WebRequest' with WMF download URLs has been failing intermittently, - ## because sometimes the URLs lead to a 'this download is no longer available' page. - ## We use a retry logic here. Retry for 5 times with 1 second interval. - # It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -Skip:$skipTest { - It "Pre-Requisistes link for '' is reachable: " -TestCases $linkCheckTestCases -Pending { - param ($Url) - - foreach ($i in 1..5) { - try { - $result = Invoke-WebRequest $Url -UseBasicParsing - break; - } catch { - Start-Sleep -Seconds 1 - } - } - - $result | Should -Not -Be $null - } -} diff --git a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 index 9bef836e19b..6674697ca2f 100644 --- a/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 +++ b/test/powershell/Language/Classes/Scripting.Classes.BasicParsing.Tests.ps1 @@ -682,6 +682,19 @@ Describe 'ScriptScopeAccessFromClassMethod' -Tags "CI" { } Describe 'Hidden Members Test ' -Tags "CI" { + BeforeAll { + if ($null -ne $PSStyle) { + $outputRendering = $PSStyle.OutputRendering + $PSStyle.OutputRendering = 'plaintext' + } + } + + AfterAll { + if ($null -ne $PSStyle) { + $PSStyle.OutputRendering = $outputRendering + } + } + class C1 { [int]$visibleX @@ -820,7 +833,7 @@ class Derived : Base [Derived]::new().foo() '@) - $iss = [System.Management.Automation.Runspaces.initialsessionstate]::CreateDefault2() + $iss = [initialsessionstate]::CreateDefault2() $iss.Commands.Add($ssfe) $ps = [powershell]::Create($iss) @@ -916,7 +929,7 @@ class A : Foo.Bar return [A]::new() '@) - $iss = [System.Management.Automation.Runspaces.initialsessionstate]::CreateDefault() + $iss = [initialsessionstate]::CreateDefault() $iss.Commands.Add($ssfe) $ps = [powershell]::Create($iss) diff --git a/test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 b/test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 new file mode 100644 index 00000000000..bc08db2a063 --- /dev/null +++ b/test/powershell/Language/Classes/Scripting.Classes.NoRunspaceAffinity.Tests.ps1 @@ -0,0 +1,52 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe "Class can be defined without Runspace affinity" -Tags "CI" { + + It "Applying the 'NoRunspaceAffinity' attribute make the class not affiliate with a particular Runspace/SessionState" { + [NoRunspaceAffinity()] + class NoAffinity { + [string] $Name; + [int] $RunspaceId; + + NoAffinity() { + $this.RunspaceId = [runspace]::DefaultRunspace.Id + } + + static [int] Echo() { + return [runspace]::DefaultRunspace.Id + } + + [int] SetAndEcho([string] $value) { + $this.Name = $value + return [runspace]::DefaultRunspace.Id + } + } + + $t = [NoAffinity] + $o = [NoAffinity]::new() + + ## Running directly should use the current Runspace/SessionState. + $t::Echo() | Should -Be $Host.Runspace.Id + $o.RunspaceId | Should -Be $Host.Runspace.Id + $o.SetAndEcho('Blue') | Should -Be $Host.Runspace.Id + $o.Name | Should -Be 'Blue' + + ## Running in a new Runspace should use that Runspace and its current SessionState. + try { + $ps = [powershell]::Create() + $ps.AddScript('function CallEcho($type) { $type::Echo() }').Invoke() > $null; $ps.Commands.Clear() + $ps.AddScript('function CallSetAndEcho($obj) { $obj.SetAndEcho(''Hello world'') }').Invoke() > $null; $ps.Commands.Clear() + $ps.AddScript('function GetName($obj) { $obj.Name }').Invoke() > $null; $ps.Commands.Clear() + $ps.AddScript('function NewObj($type) { $type::new().RunspaceId }').Invoke() > $null; $ps.Commands.Clear() + + $ps.AddCommand('CallEcho').AddArgument($t).Invoke() | Should -Be $ps.Runspace.Id; $ps.Commands.Clear() + $ps.AddCommand('CallSetAndEcho').AddArgument($o).Invoke() | Should -Be $ps.Runspace.Id; $ps.Commands.Clear() + $ps.AddCommand('GetName').AddArgument($o).Invoke() | Should -Be 'Hello world'; $ps.Commands.Clear() + $ps.AddCommand('NewObj').AddArgument($t).Invoke() | Should -Be $ps.Runspace.Id; $ps.Commands.Clear() + } + finally { + $ps.Dispose() + } + } +} diff --git a/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 b/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 index cf304d5918e..6b24b8b6ce0 100644 --- a/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.Classes.inheritance.tests.ps1 @@ -80,6 +80,49 @@ Describe 'Classes inheritance syntax' -Tags "CI" { $getter.Attributes -band [System.Reflection.MethodAttributes]::Virtual | Should -Be ([System.Reflection.MethodAttributes]::Virtual) } + It 'can implement .NET interface static properties' { + Add-Type -TypeDefinition @' +public interface IInterfaceWithStaticAbstractProperty +{ + static abstract int Getter { get; } + static abstract int Setter { get; set; } +} + +public static class InterfaceStaticAbstractPropertyTest +{ + public static int GetGetter() where T : IInterfaceWithStaticAbstractProperty + => T.Getter; + + public static int GetSetter() where T : IInterfaceWithStaticAbstractProperty + => T.Setter; + + public static int SetSetter(int value) where T : IInterfaceWithStaticAbstractProperty + => T.Setter = value; +} +'@ + + $C1 = Invoke-Expression @' +class ClassWithStaticAbstractInterface : IInterfaceWithStaticAbstractProperty { + static [int]$Getter = 1 + static [int]$Setter = 2 +} + +[ClassWithStaticAbstractInterface] +'@ + + $C1::Getter | Should -Be 1 + $C1::Getter | Should -BeOfType ([int]) + $C1::Setter | Should -Be 2 + $C1::Setter | Should -BeOfType ([int]) + $C1::Setter = 3 + $C1::Setter | Should -Be 3 + + [InterfaceStaticAbstractPropertyTest]::GetGetter[ClassWithStaticAbstractInterface]() | Should -Be 1 + [InterfaceStaticAbstractPropertyTest]::GetSetter[ClassWithStaticAbstractInterface]() | Should -Be 3 + [InterfaceStaticAbstractPropertyTest]::SetSetter[ClassWithStaticAbstractInterface](4) + [InterfaceStaticAbstractPropertyTest]::GetSetter[ClassWithStaticAbstractInterface]() | Should -Be 4 + } + It 'allows use of defined later type as a property type' { class A { static [B]$b } class B : A {} @@ -628,3 +671,253 @@ class Derived : Base $sb.Invoke() | Should -Be 200 } } + +Describe 'Base type has abstract properties' -Tags "CI" { + It 'can derive from `FileSystemInfo`' { + ## FileSystemInfo has 3 abstract members that a derived type needs to implement + ## - public abstract bool Exists { get; } + ## - public abstract string Name { get; } + ## - public abstract void Delete (); + + class myFileSystemInfo : System.IO.FileSystemInfo + { + [string] $Name + [bool] $Exists + + myFileSystemInfo([string]$path) + { + # ctor + $this.Name = $path + $this.Exists = $true + } + + [void] Delete() + { + } + } + + $myFile = [myFileSystemInfo]::new('Hello') + $myFile.Name | Should -Be 'Hello' + $myFile.Exists | Should -BeTrue + } + + It 'deriving from `FileSystemInfo` will fail when the abstract property `Exists` is not implemented' { + $script = [scriptblock]::Create('class WillFail : System.IO.FileSystemInfo { [string] $Name }') + $failure = $null + try { + & $script + } catch { + $failure = $_ + } + + $failure | Should -Not -BeNullOrEmpty + $failure.FullyQualifiedErrorId | Should -BeExactly "TypeCreationError" + $failure.Exception.Message | Should -BeLike "*'get_Exists'*" + } +} + +Describe 'Classes inheritance with protected and protected internal members in base class' -Tags 'CI' { + + BeforeAll { + Set-StrictMode -Version 3 + $c1DefinitionProtectedInternal = @' + public class C1ProtectedInternal + { + protected internal string InstanceField = "C1_InstanceField"; + protected internal string InstanceProperty { get; set; } = "C1_InstanceProperty"; + protected internal string InstanceMethod() { return "C1_InstanceMethod"; } + + protected internal virtual string VirtualProperty1 { get; set; } = "C1_VirtualProperty1"; + protected internal virtual string VirtualProperty2 { get; set; } = "C1_VirtualProperty2"; + protected internal virtual string VirtualMethod1() { return "C1_VirtualMethod1"; } + protected internal virtual string VirtualMethod2() { return "C1_VirtualMethod2"; } + + public string CtorUsed { get; set; } + public C1ProtectedInternal() { CtorUsed = "default ctor"; } + protected internal C1ProtectedInternal(string p1) { CtorUsed = "C1_ctor_1args:" + p1; } + } +'@ + $c2DefinitionProtectedInternal = @' + class C2ProtectedInternal : C1ProtectedInternal { + C2ProtectedInternal() : base() { $this.VirtualProperty2 = 'C2_VirtualProperty2' } + C2ProtectedInternal([string]$p1) : base($p1) { $this.VirtualProperty2 = 'C2_VirtualProperty2' } + + [string]GetInstanceField() { return $this.InstanceField } + [string]SetInstanceField([string]$value) { $this.InstanceField = $value; return $this.InstanceField } + [string]GetInstanceProperty() { return $this.InstanceProperty } + [string]SetInstanceProperty([string]$value) { $this.InstanceProperty = $value; return $this.InstanceProperty } + [string]CallInstanceMethod() { return $this.InstanceMethod() } + + [string]GetVirtualProperty1() { return $this.VirtualProperty1 } + [string]SetVirtualProperty1([string]$value) { $this.VirtualProperty1 = $value; return $this.VirtualProperty1 } + [string]CallVirtualMethod1() { return $this.VirtualMethod1() } + + [string]$VirtualProperty2 + [string]VirtualMethod2() { return 'C2_VirtualMethod2' } + # Note: Overriding a virtual property in a derived PowerShell class prevents access to the + # base property via simple typecast ([base]$this).VirtualProperty2. + [string]GetVirtualProperty2() { return $this.VirtualProperty2 } + [string]SetVirtualProperty2([string]$value) { $this.VirtualProperty2 = $value; return $this.VirtualProperty2 } + [string]CallVirtualMethod2Base() { return ([C1ProtectedInternal]$this).VirtualMethod2() } + [string]CallVirtualMethod2Derived() { return $this.VirtualMethod2() } + + [string]GetInstanceMemberDynamic([string]$name) { return $this.$name } + [string]SetInstanceMemberDynamic([string]$name, [string]$value) { $this.$name = $value; return $this.$name } + [string]CallInstanceMemberDynamic([string]$name) { return $this.$name() } + } + + [C2ProtectedInternal] +'@ + + Add-Type -TypeDefinition $c1DefinitionProtectedInternal + Add-Type -TypeDefinition (($c1DefinitionProtectedInternal -creplace 'C1ProtectedInternal', 'C1Protected') -creplace 'protected internal', 'protected') + + $testCases = @( + @{ accessType = 'protected'; derivedType = Invoke-Expression ($c2DefinitionProtectedInternal -creplace 'ProtectedInternal', 'Protected') } + @{ accessType = 'protected internal'; derivedType = Invoke-Expression $c2DefinitionProtectedInternal } + ) + } + + AfterAll { + Set-StrictMode -Off + } + + Context 'Derived class can access instance base class members' { + + It 'can call protected internal .NET method Object.MemberwiseClone()' { + class CNetMethod { + [string]$Foo + [object]CloneIt() { return $this.MemberwiseClone() } + } + $c1 = [CNetMethod]::new() + $c1.Foo = 'bar' + $c2 = $c1.CloneIt() + $c2.Foo | Should -Be 'bar' + } + + It 'can call base ctor' -TestCases $testCases { + param($derivedType) + $derivedType::new('foo').CtorUsed | Should -Be 'C1_ctor_1args:foo' + } + + It 'can access base field' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.GetInstanceField() | Should -Be 'C1_InstanceField' + $c2.SetInstanceField('foo_InstanceField') | Should -Be 'foo_InstanceField' + } + + It 'can access base property' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.GetInstanceProperty() | Should -Be 'C1_InstanceProperty' + $c2.SetInstanceProperty('foo_InstanceProperty') | Should -Be 'foo_InstanceProperty' + } + + It 'can call base method' -TestCases $testCases { + param($derivedType) + $derivedType::new().CallInstanceMethod() | Should -Be 'C1_InstanceMethod' + } + + It 'can access virtual base property' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.GetVirtualProperty1() | Should -Be 'C1_VirtualProperty1' + $c2.SetVirtualProperty1('foo_VirtualProperty1') | Should -Be 'foo_VirtualProperty1' + } + + It 'can call virtual base method' -TestCases $testCases { + param($derivedType) + $derivedType::new().CallVirtualMethod1() | Should -Be 'C1_VirtualMethod1' + } + } + + Context 'Derived class can override virtual base class members' { + + It 'can override virtual base property' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.GetVirtualProperty2() | Should -Be 'C2_VirtualProperty2' + $c2.SetVirtualProperty2('foo_VirtualProperty2') | Should -Be 'foo_VirtualProperty2' + } + + It 'can override virtual base method' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.CallVirtualMethod2Base() | Should -Be 'C1_VirtualMethod2' + $c2.CallVirtualMethod2Derived() | Should -Be 'C2_VirtualMethod2' + } + } + + Context 'Derived class can access instance base class members dynamically' { + + It 'can access base fields and properties' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.GetInstanceMemberDynamic('InstanceField') | Should -Be 'C1_InstanceField' + $c2.GetInstanceMemberDynamic('InstanceProperty') | Should -Be 'C1_InstanceProperty' + $c2.GetInstanceMemberDynamic('VirtualProperty1') | Should -Be 'C1_VirtualProperty1' + $c2.SetInstanceMemberDynamic('InstanceField', 'foo1') | Should -Be 'foo1' + $c2.SetInstanceMemberDynamic('InstanceProperty', 'foo2') | Should -Be 'foo2' + $c2.SetInstanceMemberDynamic('VirtualProperty1', 'foo3') | Should -Be 'foo3' + } + + It 'can call base methods' -TestCases $testCases { + param($derivedType) + $c2 = $derivedType::new() + $c2.CallInstanceMemberDynamic('InstanceMethod') | Should -Be 'C1_InstanceMethod' + $c2.CallInstanceMemberDynamic('VirtualMethod1') | Should -Be 'C1_VirtualMethod1' + } + } + + Context 'Base class members are not accessible outside class scope' { + + BeforeAll { + $instanceTest = { + $c2 = $derivedType::new() + { $null = $c2.InstanceField } | Should -Throw -ErrorId 'PropertyNotFoundStrict' + { $null = $c2.InstanceProperty } | Should -Throw -ErrorId 'PropertyNotFoundStrict' + { $null = $c2.VirtualProperty1 } | Should -Throw -ErrorId 'PropertyNotFoundStrict' + { $c2.InstanceField = 'foo' } | Should -Throw -ErrorId 'PropertyAssignmentException' + { $c2.InstanceProperty = 'foo' } | Should -Throw -ErrorId 'PropertyAssignmentException' + { $c2.VirtualProperty1 = 'foo' } | Should -Throw -ErrorId 'PropertyAssignmentException' + { $derivedType::new().InstanceMethod() } | Should -Throw -ErrorId 'MethodNotFound' + { $derivedType::new().VirtualMethod1() } | Should -Throw -ErrorId 'MethodNotFound' + foreach ($name in @('InstanceField', 'InstanceProperty', 'VirtualProperty1')) { + { $null = $c2.$name } | Should -Throw -ErrorId 'PropertyNotFoundStrict' + { $c2.$name = 'foo' } | Should -Throw -ErrorId 'PropertyAssignmentException' + } + foreach ($name in @('InstanceMethod', 'VirtualMethod1')) { + { $c2.$name() } | Should -Throw -ErrorId 'MethodNotFound' + } + } + $c3UnrelatedType = Invoke-Expression @" + class C3Unrelated { + [void]RunInstanceTest([type]`$derivedType) { $instanceTest } + } + [C3Unrelated] +"@ + $negativeTestCases = $testCases.ForEach({ + $item = $_.Clone() + $item['scopeType'] = 'null scope' + $item['classScope'] = $null + $item + $item = $_.Clone() + $item['scopeType'] = 'unrelated class scope' + $item['classScope'] = $c3UnrelatedType + $item + }) + } + + It 'cannot access instance base members in ' -TestCases $negativeTestCases { + param($derivedType, $classScope) + if ($null -eq $classScope) { + $instanceTest.Invoke() + } + else { + $c3 = $classScope::new() + $c3.RunInstanceTest($derivedType) + } + } + } +} diff --git a/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 b/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 index fb3778463da..d4e86e341b1 100644 --- a/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 +++ b/test/powershell/Language/Classes/scripting.Classes.using.tests.ps1 @@ -417,7 +417,7 @@ function foo() '@ # resolve name to absolute path $scriptToProcessPath = (Get-ChildItem $scriptToProcessPath).FullName - $iss = [System.Management.Automation.Runspaces.initialsessionstate]::CreateDefault() + $iss = [initialsessionstate]::CreateDefault() $iss.StartupScripts.Add($scriptToProcessPath) $ps = [powershell]::Create($iss) diff --git a/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 b/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 index 02d49c4435c..42426b8279a 100644 --- a/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 +++ b/test/powershell/Language/Interop/DotNet/DotNetInterop.Tests.ps1 @@ -121,7 +121,7 @@ namespace DotNetInterop } It "Calling constructor of a ByRef-like type via dotnet adapter should fail gracefully - " -TestCases @( - @{ Number = 1; Script = { [System.Span[string]]::new.Invoke("abc") } } + @{ Number = 1; Script = { [System.Span[string]]::new.Invoke([ref]$null) } } @{ Number = 2; Script = { [DotNetInterop.MyByRefLikeType]::new.Invoke(2) } } ) { param($Script) diff --git a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 index 76069143327..ddc6498eb6d 100644 --- a/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ComparisonOperator.Tests.ps1 @@ -82,6 +82,21 @@ Describe "ComparisonOperator" -Tag "CI" { param($lhs, $operator, $rhs) Invoke-Expression "$lhs $operator $rhs" | Should -BeFalse } + + It "Should be for backtick comparison " -TestCases @( + @{ lhs = 'abc`def'; operator = '-like'; rhs = 'abc`def'; result = $false } + @{ lhs = 'abc`def'; operator = '-like'; rhs = 'abc``def'; result = $true } + @{ lhs = 'abc`def'; operator = '-like'; rhs = 'abc````def'; result = $false } + @{ lhs = 'abc``def'; operator = '-like'; rhs = 'abc````def'; result = $true } + @{ lhs = 'abc`def'; operator = '-like'; rhs = [WildcardPattern]::Escape('abc`def'); result = $true } + @{ lhs = 'abc`def'; operator = '-like'; rhs = [WildcardPattern]::Escape('abc``def'); result = $false } + @{ lhs = 'abc``def'; operator = '-like'; rhs = [WildcardPattern]::Escape('abc``def'); result = $true } + @{ lhs = 'abc``def'; operator = '-like'; rhs = [WildcardPattern]::Escape('abc````def'); result = $false } + ) { + param($lhs, $operator, $rhs, $result) + $expression = "'$lhs' $operator '$rhs'" + Invoke-Expression $expression | Should -Be $result + } } Describe "Bytewise Operator" -Tag "CI" { diff --git a/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 b/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 index e2e54c32170..15340dd18e6 100644 --- a/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/PipelineChainOperator.Tests.ps1 @@ -47,7 +47,7 @@ Describe "Experimental Feature: && and || operators - Feature-Enabled" -Tag CI { @{ Statement = 'testexe -returncode -1 || testexe -returncode -2 && testexe -echoargs "A"'; Output = @('-1', '-2') } @{ Statement = 'testexe -returncode -1 || testexe -returncode -2 || testexe -echoargs "B"'; Output = @('-1', '-2', 'Arg 0 is ') } - # Native command and succesful cmdlet + # Native command and successful cmdlet @{ Statement = 'Test-SuccessfulCommand && testexe -returncode 0'; Output = @('SUCCESS', '0') } @{ Statement = 'testexe -returncode 0 && Test-SuccessfulCommand'; Output = @('0', 'SUCCESS') } @{ Statement = 'Test-SuccessfulCommand && testexe -returncode 1'; Output = @('SUCCESS', '1') } diff --git a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 index b72779f59c4..074351d3414 100644 --- a/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 +++ b/test/powershell/Language/Operators/ReplaceOperator.Tests.ps1 @@ -85,24 +85,13 @@ Describe "Replace Operator" -Tags CI { Describe "Culture-invariance tests for -split and -replace" -Tags CI { BeforeAll { - $skipTest = -not [ExperimentalFeature]::IsEnabled("PSCultureInvariantReplaceOperator") - if ($skipTest) { - Write-Verbose "Test Suite Skipped. The test suite requires the experimental feature 'PSCultureInvariantReplaceOperator' to be enabled." -Verbose - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - $PSDefaultParameterValues["it:skip"] = $true - } else { - $prevCulture = [cultureinfo]::CurrentCulture - # The French culture uses "," as the decimal mark. - [cultureinfo]::CurrentCulture = 'fr' - } + $prevCulture = [cultureinfo]::CurrentCulture + # The French culture uses "," as the decimal mark. + [cultureinfo]::CurrentCulture = 'fr' } AfterAll { - if ($skipTest) { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - } else { - [cultureinfo]::CurrentCulture = $prevCulture - } + [cultureinfo]::CurrentCulture = $prevCulture } It "-split: LHS stringification is not culture-sensitive" { diff --git a/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 b/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 index cef1861f807..009def56758 100644 --- a/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 +++ b/test/powershell/Language/Parser/AutomaticVariables.Tests.ps1 @@ -2,16 +2,15 @@ # Licensed under the MIT License. Describe 'Automatic variable $input' -Tags "CI" { - # Skip on hold for discussion on https://github.com/PowerShell/PowerShell/issues/1563 # $input type in advanced functions - It '$input Type should be enumerator' -Skip { + It '$input Type should be arraylist and object array' { function from_begin { [cmdletbinding()]param() begin { Write-Output -NoEnumerate $input } } function from_process { [cmdletbinding()]param() process { Write-Output -NoEnumerate $input } } function from_end { [cmdletbinding()]param() end { Write-Output -NoEnumerate $input } } - (from_begin) -is [System.Collections.IEnumerator] | Should -BeTrue - (from_process) -is [System.Collections.IEnumerator] | Should -BeTrue - (from_end) -is [System.Collections.IEnumerator] | Should -BeTrue + (from_begin) -is [System.Collections.ArrayList] | Should -BeTrue + (from_process) -is [System.Collections.ArrayList] | Should -BeTrue + (from_end) -is [System.Object[]] | Should -BeTrue } It 'Empty $input really is empty' { diff --git a/test/powershell/Language/Parser/BNotOperator.Tests.ps1 b/test/powershell/Language/Parser/BNotOperator.Tests.ps1 index eb6dd934e30..41930766dc6 100644 --- a/test/powershell/Language/Parser/BNotOperator.Tests.ps1 +++ b/test/powershell/Language/Parser/BNotOperator.Tests.ps1 @@ -12,7 +12,7 @@ $ns = [Guid]::NewGuid() -replace '-','' $typeDefinition = "namespace ns_$ns`n{" -$enumTypeNames = foreach ($baseType in $baseTypes.Keys) +foreach ($baseType in $baseTypes.Keys) { $baseTypeName = $baseTypes[$baseType] $typeDefinition += @" @@ -24,14 +24,12 @@ $enumTypeNames = foreach ($baseType in $baseTypes.Keys) Max = $($baseType::MaxValue) } "@ - - "ns_$ns.E_$baseTypeName" } $typeDefinition += "`n}" -Write-Verbose $typeDefinition -Add-Type $typeDefinition +Write-Verbose $typeDefinition -verbose +$enumTypeNames = Add-Type $typeDefinition -Pass Describe "bnot on enums" -Tags "CI" { foreach ($enumType in [type[]]$enumTypeNames) diff --git a/test/powershell/Language/Parser/Conversions.Tests.ps1 b/test/powershell/Language/Parser/Conversions.Tests.ps1 index bfeeddc4f1a..f6874b1db93 100644 --- a/test/powershell/Language/Parser/Conversions.Tests.ps1 +++ b/test/powershell/Language/Parser/Conversions.Tests.ps1 @@ -78,6 +78,14 @@ Describe 'conversion syntax' -Tags "CI" { $result -join ";" | Should -Be ($Elements -join ";") } } + + It 'Should not convert invalid strings to type name using -as operator' { + 'int]whatever' -as [type] | Should -Be $null + } + + It 'Should not convert invalid strings to type name using left-hand side operator' { + {[Type] 'int]whatever'} | Should -Throw + } } Describe "Type resolution should prefer assemblies in powershell assembly cache" -Tags "Feature" { @@ -526,7 +534,7 @@ Describe 'method conversion' -Tags 'CI' { } Describe 'float/double precision when converting to string' -Tags "CI" { - It "-to-[string] conversion in PowerShell should use the precision specifier " -TestCases @( + It "-to-[string] conversion in PowerShell should use the precision specifier ()" -TestCases @( @{ SourceType = [double]; Format = "G15"; ValueScript = { 1.1 * 3 }; StringConversionResult = "3.3"; ToStringResult = "3.3000000000000003" } @{ SourceType = [double]; Format = "G15"; ValueScript = { 1.1 * 6 }; StringConversionResult = "6.6"; ToStringResult = "6.6000000000000005" } @{ SourceType = [double]; Format = "G15"; ValueScript = { [System.Math]::E }; StringConversionResult = [System.Math]::E.ToString("G15"); ToStringResult = [System.Math]::E.ToString() } diff --git a/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 b/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 index 3c9edd43915..3514f389718 100644 --- a/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 +++ b/test/powershell/Language/Parser/ExtensibleCompletion.Tests.ps1 @@ -175,6 +175,77 @@ function TestFunction ) } + +class NumberCompleter : IArgumentCompleter +{ + + [int] $From + [int] $To + [int] $Step + + NumberCompleter([int] $from, [int] $to, [int] $step) + { + if ($from -gt $to) { + throw [ArgumentOutOfRangeException]::new("from") + } + $this.From = $from + $this.To = $to + $this.Step = if($step -lt 1) { 1 } else { $step } + } + + [IEnumerable[CompletionResult]] CompleteArgument( + [string] $CommandName, + [string] $parameterName, + [string] $wordToComplete, + [CommandAst] $commandAst, + [IDictionary] $fakeBoundParameters) + { + $resultList = [List[CompletionResult]]::new() + $local:to = $this.To + for ($i = $this.From; $i -le $to; $i += $this.Step) { + if ($i.ToString().StartsWith($wordToComplete, [System.StringComparison]::Ordinal)) { + $num = $i.ToString() + $resultList.Add([CompletionResult]::new($num, $num, "ParameterValue", $num)) + } + } + + return $resultList + } +} + +class NumberCompletionAttribute : ArgumentCompleterAttribute, IArgumentCompleterFactory +{ + [int] $From + [int] $To + [int] $Step + + NumberCompletionAttribute([int] $from, [int] $to) + { + $this.From = $from + $this.To = $to + $this.Step = 1 + } + + [IArgumentCompleter] Create() { return [NumberCompleter]::new($this.From, $this.To, $this.Step) } +} + +function FactoryCompletionAdd { + param( + [NumberCompletion(0, 50, Step = 5)] + [int] $Number + ) +} + +Describe "Factory based extensible completion" -Tags "CI" { + @{ + ExpectedResults = @( + @{CompletionText = "5"; ResultType = "ParameterValue" } + @{CompletionText = "50"; ResultType = "ParameterValue" } + ) + TestInput = 'FactoryCompletionAdd -Number 5' + } | Get-CompletionTestCaseData | Test-Completions +} + Describe "Script block based extensible completion" -Tags "CI" { @{ ExpectedResults = @( diff --git a/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 b/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 index f28b6801389..a9641951473 100644 --- a/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 +++ b/test/powershell/Language/Parser/MethodInvocation.Tests.ps1 @@ -1,10 +1,270 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -if ( $IsCoreCLR ) { - return + +Describe 'Generic Method invocation' -Tags 'CI' { + + BeforeAll { + $EmptyArrayCases = @( + @{ + Script = '[Array]::Empty[string]()' + ExpectedType = [string[]] + } + @{ + Script = '[Array]::Empty[System.Collections.Generic.Dictionary[System.Numerics.BigInteger, System.Collections.Generic.List[string[,]]]]()' + ExpectedType = [System.Collections.Generic.Dictionary[System.Numerics.BigInteger, System.Collections.Generic.List[string[, ]]][]] + } + ) + + $IndexingAProperty = @( + @{ + Script = '[object]::Property[[type]]' + IndexType = 'System.Management.Automation.Language.TypeExpressionAst' + IndexString = '[type]' + } + @{ + Script = '$object.IPSubnet[[Array]::IndexOf($_.IPAddress, $_.IPAddress[0])]' + IndexType = 'System.Management.Automation.Language.InvokeMemberExpressionAst' + IndexString = '[Array]::IndexOf($_.IPAddress, $_.IPAddress[0])' + } + @{ + Script = @' + [IPAddress]::Parse( + $_.IPSubnet[ + [Array]::IndexOf($_.IPAddress, $_.IPAddress[0]) + ] + ) +'@ + IndexType = 'System.Management.Automation.Language.InvokeMemberExpressionAst' + IndexString = '[Array]::IndexOf($_.IPAddress, $_.IPAddress[0])' + } + @{ + Script = @' + [IPAddress]::Parse( + $_.IPSubnet[ + ([Array]::IndexOf($_.IPAddress, $_.IPAddress[0])) + ] + ) +'@ + IndexType = 'System.Management.Automation.Language.ParenExpressionAst' + IndexString = '([Array]::IndexOf($_.IPAddress, $_.IPAddress[0]))' + } + ) + + $ExpectedParseErrors = @( + @{ + Script = '$object.Method[incompl' + ExpectedErrors = @('EndSquareBracketExpectedAtEndOfType') + ErrorCount = 1 + } + @{ + Script = '[type]::Member[incompl' + ExpectedErrors = @('EndSquareBracketExpectedAtEndOfType') + ErrorCount = 1 + } + @{ + Script = '$object.Method[Type1[Type2' + ExpectedErrors = @('EndSquareBracketExpectedAtEndOfAttribute','EndSquareBracketExpectedAtEndOfType') + ErrorCount = 2 + } + @{ + Script = '[array]::empty[type]]()' + ExpectedErrors = @('MissingArrayIndexExpression', 'UnexpectedToken', 'ExpectedExpression') + ErrorCount = 3 + } + @{ + Script = '$object.Method[type,]()' + ExpectedErrors = @('MissingTypename') + ErrorCount = 1 + } + @{ + Script = '$object.Method[]()' + ExpectedErrors = @('MissingArrayIndexExpression', 'UnexpectedToken', 'ExpectedExpression') + ErrorCount = 3 + } + @{ + Script = '$object.Method[,]()' + ExpectedErrors = @('MissingExpressionAfterOperator', 'UnexpectedToken', 'ExpectedExpression') + ErrorCount = 3 + } + @{ + Script = '$object.Method[,type]()' + ExpectedErrors = @('MissingExpressionAfterOperator', 'UnexpectedToken', 'ExpectedExpression') + ErrorCount = 3 + } + @{ + Script = '$object.Method[type()' + ExpectedErrors = @('EndSquareBracketExpectedAtEndOfType', 'UnexpectedToken', 'ExpectedExpression') + ErrorCount = 3 + } + @{ + Script = '$object.Method[type)' + ExpectedErrors = @('EndSquareBracketExpectedAtEndOfType', 'UnexpectedToken') + ErrorCount = 2 + } + @{ + Script = '$object.Method[[type]]()' + ExpectedErrors = @('UnexpectedToken', 'ExpectedExpression') + ErrorCount = 2 + } + @{ + Script = '[Array]::Empty[[type]]()' + ExpectedErrors = @('UnexpectedToken', 'ExpectedExpression') + ErrorCount = 2 + } + @{ + Script = '$object.Property[type]' + ExpectedErrors = @('MissingArrayIndexExpression', 'UnexpectedToken') + ErrorCount = 2 + } + ) + } + + It 'does not throw a parse error for " + +'@ + } + @{ + Command = "cscript.exe" + Filename = "test.vbs" + ExpectedResults = @( + "Argument 0 is: " + "Argument 1 is: " + "Argument 2 is: " + "Argument 3 is: " + ) + Script = @' +for i = 0 to wScript.arguments.count - 1 + wscript.echo "Argument " & i & " is: <" & (wScript.arguments(i)) & ">" +next +'@ + } + @{ + Command = "cscript" + Filename = "test.js" + ExpectedResults = @( + "Argument 0 is: " + "Argument 1 is: " + "Argument 2 is: " + "Argument 3 is: " + ) + Script = @' +for(i = 0; i < WScript.Arguments.Count(); i++) { + WScript.echo("Argument " + i + " is: <" + WScript.Arguments(i) + ">"); +} +'@ + } + @{ + Command = "" + Filename = "test.bat" + ExpectedResults = @( + "Argument 1 is: " + "Argument 2 is: " + "Argument 3 is: <""ab cd"">" + "Argument 4 is: <""a'b c'd"">" + ) + Script = @' +@echo off +echo Argument 1 is: ^<%1^> +echo Argument 2 is: ^<%2^> +echo Argument 3 is: ^<%3^> +echo Argument 4 is: ^<%4^> +'@ + } + @{ + Command = "" + Filename = "test.cmd" + ExpectedResults = @( + "Argument 1 is: " + "Argument 2 is: " + "Argument 3 is: <""ab cd"">" + "Argument 4 is: <""a'b c'd"">" + ) + Script = @' +@echo off +echo Argument 1 is: ^<%1^> +echo Argument 2 is: ^<%2^> +echo Argument 3 is: ^<%3^> +echo Argument 4 is: ^<%4^> +'@ + } + ) - It "Should handle PowerShell arrays with or without spaces correctly: " -TestCases @( - @{arguments = "1,2"; expected = @("1,2")} - @{arguments = "1,2,3"; expected = @("1,2,3")} - @{arguments = "1, 2"; expected = "1,", "2"} - @{arguments = "1 ,2"; expected = "1", ",2"} - @{arguments = "1 , 2"; expected = "1", ",", "2"} - @{arguments = "1, 2,3"; expected = "1,", "2,3"} - @{arguments = "1 ,2,3"; expected = "1", ",2,3"} - @{arguments = "1 , 2,3"; expected = "1", ",", "2,3"} - ) { - param($arguments, $expected) - $lines = @(Invoke-Expression "testexe -echoargs $arguments") - $lines.Count | Should -Be $expected.Count - for ($i = 0; $i -lt $expected.Count; $i++) { - $lines[$i] | Should -BeExactly "Arg $i is <$($expected[$i])>" + # determine whether we should skip the tests we just defined + # doing it in this order ensures that the test output will show each skipped test + $skipTests = -not $IsWindows + if ($skipTests) { + return } + + # save the passing style + $passingStyle = $PSNativeCommandArgumentPassing + # explicitely set the passing style to Windows + $PSNativeCommandArgumentPassing = "Windows" } -} -Describe 'PSPath to native commands' { - BeforeAll { - $featureEnabled = $EnabledExperimentalFeatures.Contains('PSNativePSPathResolution') - $originalDefaultParameterValues = $PSDefaultParameterValues.Clone() - - $PSDefaultParameterValues["it:skip"] = (-not $featureEnabled) - - if ($IsWindows) { - $cmd = "cmd" - $cmdArg1 = "/c" - $cmdArg2 = "type" - $dir = "cmd" - $dirArg1 = "/c" - $dirArg2 = "dir" + It "Invoking '' is compatible with PowerShell 5" -TestCases $testCases -Skip:$($skipTests) { + param ( $Command, $Arguments, $Filename, $Script, $ExpectedResults ) + cscript //h:cscript //nologo //s + $a = 'a"b c"d' + $scriptPath = Join-Path $TESTDRIVE $Filename + $Script | out-file -encoding ASCII $scriptPath + if ($Command) { + $results = & $Command $scriptPath $a 'a"b c"d' a"b c"d "a'b c'd" 2> "${TESTDRIVE}/error.txt" } else { - $cmd = "cat" - $dir = "ls" + $results = & $scriptPath $a 'a"b c"d' a"b c"d "a'b c'd" 2> "${TESTDRIVE}/error.txt" } - - Set-Content -Path testdrive:/test.txt -Value 'Hello' - Set-Content -Path "testdrive:/test file.txt" -Value 'Hello' - Set-Content -Path "env:/test var" -Value 'Hello' - $filePath = Join-Path -Path ~ -ChildPath (New-Guid) - Set-Content -Path $filePath -Value 'Home' - $complexDriveName = 'My test! ;+drive' - New-PSDrive -Name $complexDriveName -Root $testdrive -PSProvider FileSystem + $errorContent = Get-Content "${TESTDRIVE}/error.txt" -ErrorAction Ignore + $errorContent | Should -BeNullOrEmpty + $results.Count | Should -Be 4 + $results[0] | Should -Be $ExpectedResults[0] + $results[1] | Should -Be $ExpectedResults[1] + $results[2] | Should -Be $ExpectedResults[2] + $results[3] | Should -Be $ExpectedResults[3] } +} - AfterAll { - $global:PSDefaultParameterValues = $originalDefaultParameterValues - Remove-Item -Path "env:/test var" - Remove-Item -Path $filePath - Remove-PSDrive -Name $complexDriveName +Describe "Will error correctly if an attempt to set variable to improper value" -tags "CI" { + It "will error when setting variable incorrectly" { + { $global:PSNativeCommandArgumentPassing = "zzz" } | Should -Throw -ExceptionType System.Management.Automation.ArgumentTransformationMetadataException } +} - It 'PSPath with ~/path works' { - $out = & $cmd $cmdArg1 $cmdArg2 $filePath - $LASTEXITCODE | Should -Be 0 - $out | Should -BeExactly 'Home' +Describe "find.exe uses legacy behavior on Windows" -Tag 'CI' { + BeforeAll { + $currentSetting = $PSNativeCommandArgumentPassing + $PSNativeCommandArgumentPassing = "Windows" + $testCases = @{ pattern = "" }, + @{ pattern = "blat" }, + @{ pattern = "bl at" } } - - It 'PSPath with ~ works' { - $out = & $dir $dirArg1 $dirArg2 ~ - $LASTEXITCODE | Should -Be 0 - $out | Should -Not -BeNullOrEmpty + AfterAll { + $PSNativeCommandArgumentPassing = $currentSetting } + It "The pattern '' is used properly by find.exe" -skip:(! $IsWindows) -testCases $testCases { + param ($pattern) + $expr = "'foo' | find.exe --% /v ""$pattern""" + $result = Invoke-Expression $expr + $result | Should -Be 'foo' + } +} - It 'PSPath that is file system path works with native commands: ' -TestCases @( - @{ path = "testdrive:/test.txt" } - @{ path = "testdrive:/test file.txt" } - ){ - param($path) +foreach ( $argumentListValue in "Standard","Legacy","Windows" ) { + $PSNativeCommandArgumentPassing = $argumentListValue + Describe "Native Command Arguments (${PSNativeCommandArgumentPassing})" -tags "CI" { + # When passing arguments to native commands, quoted segments that contain + # spaces need to be quoted with '"' characters when they are passed to the + # native command (or to bash or sh on Linux). + # + # This test checks that the proper quoting is occuring by passing arguments + # to the testexe native command and looking at how it got the arguments. + It "Should handle quoted spaces correctly (ArgumentList=${PSNativeCommandArgumentPassing})" { + $a = 'a"b c"d' + $lines = testexe -echoargs $a 'a"b c"d' a"b c"d "a'b c'd" + $lines.Count | Should -Be 4 + if ($PSNativeCommandArgumentPassing -ne "Legacy") { + $lines[0] | Should -BeExactly 'Arg 0 is ' + $lines[1] | Should -BeExactly 'Arg 1 is ' + } + else { + $lines[0] | Should -BeExactly 'Arg 0 is ' + $lines[1] | Should -BeExactly 'Arg 1 is ' + } + $lines[2] | Should -BeExactly 'Arg 2 is ' + $lines[3] | Should -BeExactly 'Arg 3 is ' + } - $out = & $cmd $cmdArg1 $cmdArg2 "$path" - $LASTEXITCODE | Should -Be 0 - $out | Should -BeExactly 'Hello' - } + # In order to pass '"' characters so they are actually part of command line + # arguments for native commands, they need to be escaped with a '\' (this + # is in addition to the '`' escaping needed inside '"' quoted strings in + # PowerShell). + # + # This functionality was broken in PowerShell 5.0 and 5.1, so this test + # will fail on those versions unless the fix is backported to them. + # + # This test checks that the proper quoting and escaping is occurring by + # passing arguments with escaped quotes to the testexe native command and + # looking at how it got the arguments. + It "Should handle spaces between escaped quotes (ArgumentList=${PSNativeCommandArgumentPassing})" { + $lines = testexe -echoargs 'a\"b c\"d' "a\`"b c\`"d" + $lines.Count | Should -Be 2 + if ($PSNativeCommandArgumentPassing -ne "Legacy") { + $lines[0] | Should -BeExactly 'Arg 0 is ' + $lines[1] | Should -BeExactly 'Arg 1 is ' + } + else { + $lines[0] | Should -BeExactly 'Arg 0 is ' + $lines[1] | Should -BeExactly 'Arg 1 is ' + } + } - It 'PSPath passed with single quotes should be treated as literal' { - $out = & $cmd $cmdArg1 $cmdArg2 'testdrive:/test.txt' - $LASTEXITCODE | Should -Not -Be 0 - $out | Should -BeNullOrEmpty - } + It "Should correctly quote paths with spaces (ArgumentList=${PSNativeCommandArgumentPassing}): " -TestCases @( + @{arguments = "'.\test 1\' `".\test 2\`"" ; expected = @(".\test 1\",".\test 2\")}, + @{arguments = "'.\test 1\\\' `".\test 2\\`""; expected = @(".\test 1\\\",".\test 2\\")} + ) { + param($arguments, $expected) + $lines = Invoke-Expression "testexe -echoargs $arguments" + $lines.Count | Should -Be $expected.Count + for ($i = 0; $i -lt $lines.Count; $i++) { + $lines[$i] | Should -BeExactly "Arg $i is <$($expected[$i])>" + } + } - It 'PSPath that is not a file system path fails with native commands: ' -TestCases @( - @{ path = "env:/PSModulePath" } - @{ path = "env:/test var" } - ){ - param($path) + It "Should handle arguments that include commas without spaces (windbg example)" { + $lines = testexe -echoargs -k com:port=\\devbox\pipe\debug,pipe,resets=0,reconnect + $lines.Count | Should -Be 2 + $lines[0] | Should -BeExactly "Arg 0 is <-k>" + $lines[1] | Should -BeExactly "Arg 1 is " + } - $out = & $cmd $cmdArg1 $cmdArg2 "$path" - $LASTEXITCODE | Should -Not -Be 0 - $out | Should -BeNullOrEmpty - } + It "Should handle when the ':' is the parameter value" { + $lines = testexe -echoargs awk -F: '{print $1}' + $lines.Count | Should -Be 3 + $lines[0] | Should -BeExactly 'Arg 0 is ' + $lines[1] | Should -BeExactly 'Arg 1 is <-F:>' + $lines[2] | Should -BeExactly 'Arg 2 is <{print $1}>' + } - It 'Relative PSPath works' { - New-Item -Path $testdrive -Name TestFolder -ItemType Directory -ErrorAction Stop - $cwd = Get-Location - Set-Content -Path (Join-Path -Path $testdrive -ChildPath 'TestFolder' -AdditionalChildPath 'test.txt') -Value 'hello' - Set-Location -Path (Join-Path -Path $testdrive -ChildPath 'TestFolder') - Set-Location -Path $cwd - $out = & $cmd $cmdArg1 $cmdArg2 "TestDrive:test.txt" - $LASTEXITCODE | Should -Be 0 - $out | Should -BeExactly 'Hello' - } + It "Should handle DOS style arguments" { + $lines = testexe -echoargs /arg1 /c:"a string" + $lines.Count | Should -Be 2 + $lines[0] | Should -BeExactly "Arg 0 is " + $lines[1] | Should -BeExactly "Arg 1 is " + } + + It "Should handle PowerShell arrays with or without spaces correctly (ArgumentList=${PSNativeCommandArgumentPassing}): " -TestCases @( + @{arguments = "1,2"; expected = @("1,2")} + @{arguments = "1,2,3"; expected = @("1,2,3")} + @{arguments = "1, 2"; expected = "1,", "2"} + @{arguments = "1 ,2"; expected = "1", ",2"} + @{arguments = "1 , 2"; expected = "1", ",", "2"} + @{arguments = "1, 2,3"; expected = "1,", "2,3"} + @{arguments = "1 ,2,3"; expected = "1", ",2,3"} + @{arguments = "1 , 2,3"; expected = "1", ",", "2,3"} + ) { + param($arguments, $expected) + $lines = @(Invoke-Expression "testexe -echoargs $arguments") + $lines.Count | Should -Be $expected.Count + for ($i = 0; $i -lt $expected.Count; $i++) { + $lines[$i] | Should -BeExactly "Arg $i is <$($expected[$i])>" + } + } + + It "Should handle empty args correctly (ArgumentList=${PSNativeCommandArgumentPassing})" { + if ($PSNativeCommandArgumentPassing -eq 'Legacy') { + $expectedLines = 2 + } + else { + $expectedLines = 3 + } - It 'Complex PSDrive name works' { - $out = & $cmd $cmdArg1 $cmdArg2 "${complexDriveName}:/test.txt" - $LASTEXITCODE | Should -Be 0 - $out | Should -BeExactly 'Hello' + $lines = testexe -echoargs 1 '' 2 + $lines.Count | Should -Be $expectedLines + $lines[0] | Should -BeExactly 'Arg 0 is <1>' + + if ($expectedLines -eq 2) { + $lines[1] | Should -BeExactly 'Arg 1 is <2>' + } + else { + $lines[1] | Should -BeExactly 'Arg 1 is <>' + $lines[2] | Should -BeExactly 'Arg 2 is <2>' + } + + } + + It 'Should treat a PSPath as literal' { + $lines = testexe -echoargs temp:/foo + $lines.Count | Should -Be 1 + $lines | Should -BeExactly 'Arg 0 is ' + } } } diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandPathUpdate.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandPathUpdate.Tests.ps1 new file mode 100644 index 00000000000..ff90500ac83 --- /dev/null +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandPathUpdate.Tests.ps1 @@ -0,0 +1,373 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +## The "Path Update" feature is only available on Windows. +## Skip the test suite on Unix platforms. +if (-not $IsWindows) { + return; +} + +function GetEnvPathLiteralValue { + param( + [System.EnvironmentVariableTarget] $Target + ) + + if ($Target -eq 'User') { + $regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment') + } elseif ($Target -eq 'Machine') { + $regKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment') + } else { + return [PSCustomObject]@{ Kind = $null; Value = $env:Path } + } + + try { + $kind = $regKey.GetValueKind('Path') + $value = $regKey.GetValue('Path', $null, [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames) + + return [PSCustomObject]@{ + Kind = $kind + Value = $value + } + } + finally { + ${regKey}?.Dispose() + } +} + +function RestoreEnvPath { + param( + [System.EnvironmentVariableTarget] $Target, + [Microsoft.Win32.RegistryValueKind] $ValueKind, + [string] $LiteralValue + ) + + ## Open the registry key with 'write' access. + if ($Target -eq 'User') { + $regKey = [Microsoft.Win32.Registry]::CurrentUser.OpenSubKey('Environment', $true) + } elseif ($Target -eq 'Machine') { + $regKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true) + } else { + ## Ignore value kind when restoring the in-proc env Path. + $env:Path = $LiteralValue + return + } + + try { + $regKey.SetValue('Path', $LiteralValue, $ValueKind) + } finally { + ${regKey}?.Dispose() + } +} + +function UpdatePackageManager { + param( + [Parameter(ParameterSetName = 'Add')] + [switch] $Add, + + [Parameter(ParameterSetName = 'Remove')] + [switch] $Remove, + + [string] $Name + ) + + $regKeyPath = 'HKLM:\Software\Microsoft\Command Processor\KnownPackageManagers' + $keyExists = Test-Path -Path $regKeyPath + if (-not $keyExists) { + Write-Host -ForegroundColor Cyan "The registry key 'KnownPackageManagers' doesn't exist." + } + + $subKeyPath = "$regKeyPath\$Name" + if ($Add) { + $null = New-Item $subKeyPath -Force -ErrorAction Stop + } + elseif ($Remove -and $keyExists) { + Remove-Item $subKeyPath -Recurse -Force -ErrorAction Stop + } +} + +Describe "Path update for package managers" -tags @('CI', 'RequireAdminOnWindows') { + + It "Path update is off for an executable that is not registered" { + try { + $oldUserPath = GetEnvPathLiteralValue -Target 'User' + $oldSysPath = GetEnvPathLiteralValue -Target 'Machine' + $oldProcPath = $env:Path + + testexe -updateuserandsystempath + + $newUserPath = GetEnvPathLiteralValue -Target 'User' + $newUserPath.Kind | Should -Be $oldUserPath.Kind -Because "Value kind should not be changed" + $newUserPath.Value | Should -BeLike "$($oldUserPath.Value)*X:\not-exist-user-path" -Because "'testexe -updateuserandsystempath' should append 'X:\not-exist-user-path' to the User Path." + + $newSysPath = GetEnvPathLiteralValue -Target 'Machine' + $newSysPath.Kind | Should -Be $oldSysPath.Kind -Because "Value kind should not be changed" + $newSysPath.Value | Should -BeLike "X:\not-exist-sys-path*$($oldSysPath.Value)" -Because "'testexe -updateuserandsystempath' should prepend 'X:\not-exist-sys-path' to the System Path." + + $newProcPath = $env:Path + $newProcPath | Should -Be $oldProcPath -Because "'testexe -updateuserpath' doesn't change the Process Path and the executable 'testexe' is not in the package manager list." + } + finally { + if ($oldUserPath -ne $null) { + RestoreEnvPath -Target 'User' -ValueKind $oldUserPath.Kind -LiteralValue $oldUserPath.Value + } + + if ($oldSysPath -ne $null) { + RestoreEnvPath -Target 'Machine' -ValueKind $oldSysPath.Kind -LiteralValue $oldSysPath.Value + } + } + } + + ## Add the executable name without extension to the list of package managers. + Context "Add 'testexe' to the list and test 'Path Update'" { + BeforeAll { + UpdatePackageManager -Add -Name 'testexe' + } + + AfterAll { + UpdatePackageManager -Remove -Name 'testexe' + } + + It "Test when only User Path is changed" { + try { + $oldUserPath = GetEnvPathLiteralValue -Target 'User' + + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## New item 'X:\not-exist-user-path' will be appended to User Path. + testexe -updateuserpath + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath.Length | Should -BeGreaterThan $oldProcPath.Length -Because "Path should be updated. The new path item added to 'User Path' should be appended to 'Process Path'." + $newProcPath.IndexOf($oldProcPath) | Should -Be 0 -Because "Path should be updated. The new path item added to 'User Path' should be appended to 'Process Path'." + + $newItem = $newProcPath.SubString($oldProcPath.Length) + if ($oldProcPath.EndsWith(';')) { + $newItem | Should -Be 'X:\not-exist-user-path' + } + else { + $newItem | Should -Be ';X:\not-exist-user-path' + } + } + finally { + if ($oldUserPath -ne $null) { + RestoreEnvPath -Target 'User' -ValueKind $oldUserPath.Kind -LiteralValue $oldUserPath.Value + } + } + } + + It "Test when only System Path is changed" { + try { + $oldSysPath = GetEnvPathLiteralValue -Target 'Machine' + + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## New item 'X:\not-exist-sys-path' will be prepended to System Path. + testexe -updatesystempath > $null + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath.Length | Should -BeGreaterThan $oldProcPath.Length -Because "Path should be updated. The new path item added to 'System Path' should be appended to 'Process Path'." + $newProcPath.IndexOf($oldProcPath) | Should -Be 0 -Because "Path should be updated. The new path item added to 'System Path' should be appended to 'Process Path'." + + $newItem = $newProcPath.SubString($oldProcPath.Length) + if ($oldProcPath.EndsWith(';')) { + $newItem | Should -Be 'X:\not-exist-sys-path' + } + else { + $newItem | Should -Be ';X:\not-exist-sys-path' + } + } + finally { + if ($oldSysPath -ne $null) { + RestoreEnvPath -Target 'Machine' -ValueKind $oldSysPath.Kind -LiteralValue $oldSysPath.Value + } + } + } + + It "Test when both User and System Paths are changed" { + try { + $oldUserPath = GetEnvPathLiteralValue -Target 'User' + $oldSysPath = GetEnvPathLiteralValue -Target 'Machine' + + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## New item 'X:\not-exist-user-path' will be appended to User Path. + ## New item 'X:\not-exist-sys-path' will be prepended to System Path. + $null = testexe -updateuserandsystempath + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath.Length | Should -BeGreaterThan $oldProcPath.Length -Because "Path should be updated. The new path items should be appended to 'Process Path'." + $newProcPath.IndexOf($oldProcPath) | Should -Be 0 -Because "Path should be updated. The new path items should be appended to 'Process Path'." + + $newItem = $newProcPath.SubString($oldProcPath.Length) + if ($oldProcPath.EndsWith(';')) { + $newItem | Should -Be 'X:\not-exist-user-path;X:\not-exist-sys-path' + } + else { + $newItem | Should -Be ';X:\not-exist-user-path;X:\not-exist-sys-path' + } + } + finally { + if ($oldUserPath -ne $null) { + RestoreEnvPath -Target 'User' -ValueKind $oldUserPath.Kind -LiteralValue $oldUserPath.Value + } + + if ($oldSysPath -ne $null) { + RestoreEnvPath -Target 'Machine' -ValueKind $oldSysPath.Kind -LiteralValue $oldSysPath.Value + } + } + } + + It "Test when neither User nor System Path is changed" { + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## Print help message and exit. + testexe -h > $null + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath | Should -Be $oldProcPath -Because "'testexe -h' doesn't change the env Path." + } + } + + ## Add the executable name with extension to the list of package managers. + Context "Add 'testexe.exe' to the list and test 'Path Update'" { + BeforeAll { + UpdatePackageManager -Add -Name 'testexe.exe' + } + + AfterAll { + UpdatePackageManager -Remove -Name 'testexe.exe' + } + + It "Test when only User Path is changed" { + try { + $oldUserPath = GetEnvPathLiteralValue -Target 'User' + + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## New item 'X:\not-exist-user-path' will be appended to User Path. + testexe -updateuserpath + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath.Length | Should -BeGreaterThan $oldProcPath.Length -Because "Path should be updated. The new path item added to 'User Path' should be appended to 'Process Path'." + $newProcPath.IndexOf($oldProcPath) | Should -Be 0 -Because "Path should be updated. The new path item added to 'User Path' should be appended to 'Process Path'." + + $newItem = $newProcPath.SubString($oldProcPath.Length) + if ($oldProcPath.EndsWith(';')) { + $newItem | Should -Be 'X:\not-exist-user-path' + } + else { + $newItem | Should -Be ';X:\not-exist-user-path' + } + } + finally { + if ($oldUserPath -ne $null) { + RestoreEnvPath -Target 'User' -ValueKind $oldUserPath.Kind -LiteralValue $oldUserPath.Value + } + } + } + + It "Test when only System Path is changed" { + try { + $oldSysPath = GetEnvPathLiteralValue -Target 'Machine' + + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## New item 'X:\not-exist-sys-path' will be prepended to System Path. + testexe -updatesystempath > $null + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath.Length | Should -BeGreaterThan $oldProcPath.Length -Because "Path should be updated. The new path item added to 'System Path' should be appended to 'Process Path'." + $newProcPath.IndexOf($oldProcPath) | Should -Be 0 -Because "Path should be updated. The new path item added to 'System Path' should be appended to 'Process Path'." + + $newItem = $newProcPath.SubString($oldProcPath.Length) + if ($oldProcPath.EndsWith(';')) { + $newItem | Should -Be 'X:\not-exist-sys-path' + } + else { + $newItem | Should -Be ';X:\not-exist-sys-path' + } + } + finally { + if ($oldSysPath -ne $null) { + RestoreEnvPath -Target 'Machine' -ValueKind $oldSysPath.Kind -LiteralValue $oldSysPath.Value + } + } + } + + It "Test when both User and System Paths are changed" { + try { + $oldUserPath = GetEnvPathLiteralValue -Target 'User' + $oldSysPath = GetEnvPathLiteralValue -Target 'Machine' + + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## New item 'X:\not-exist-user-path' will be appended to User Path. + ## New item 'X:\not-exist-sys-path' will be prepended to System Path. + $null = testexe -updateuserandsystempath + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath.Length | Should -BeGreaterThan $oldProcPath.Length -Because "Path should be updated. The new path items should be appended to 'Process Path'." + $newProcPath.IndexOf($oldProcPath) | Should -Be 0 -Because "Path should be updated. The new path items should be appended to 'Process Path'." + + $newItem = $newProcPath.SubString($oldProcPath.Length) + if ($oldProcPath.EndsWith(';')) { + $newItem | Should -Be 'X:\not-exist-user-path;X:\not-exist-sys-path' + } + else { + $newItem | Should -Be ';X:\not-exist-user-path;X:\not-exist-sys-path' + } + } + finally { + if ($oldUserPath -ne $null) { + RestoreEnvPath -Target 'User' -ValueKind $oldUserPath.Kind -LiteralValue $oldUserPath.Value + } + + if ($oldSysPath -ne $null) { + RestoreEnvPath -Target 'Machine' -ValueKind $oldSysPath.Kind -LiteralValue $oldSysPath.Value + } + } + } + + It "Test when neither User nor System Path is changed" { + $oldProcPath, $newProcPath = pwsh -noprofile -c { + $oldPath = $env:Path + + ## Print help message and exit. + testexe -h > $null + + $newPath = $env:Path + $oldPath, $newPath + } + + $newProcPath | Should -Be $oldProcPath -Because "'testexe -h' doesn't change the env Path." + } + } +} diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 index 95eb59857ae..542f1724303 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeCommandProcessor.Tests.ps1 @@ -43,6 +43,62 @@ Describe 'native commands with pipeline' -tags 'Feature' { $result[0] | Should -Match "pwsh" } } + + It 'native command should be killed when pipeline is disposed' -Skip:($IsWindows) { + $yes = (Get-Process 'yes' -ErrorAction Ignore).Count + yes | Select-Object -First 2 + # wait a little to be sure that the process is ended + Start-Sleep -Milliseconds 500 + (Get-Process 'yes' -ErrorAction Ignore).Count | Should -Be $yes + } + + It 'native command should still execute if the current working directory no longer exists with command: ' -Skip:($IsWindows) -TestCases @( + @{ command = 'ps' } + @{ command = 'start-process ps -nonewwindow'} + ){ + param($command) + + $wd = New-Item testdrive:/tmp -ItemType directory + $lock = New-Item testdrive:/lock -ItemType file + $script = @" + while (`$null -ne (Get-Item "$lock" -ErrorAction Ignore)) { + Start-Sleep -Seconds 1 + } + + try { + `$out = $command + } + catch { + `$null = Set-Content -Path "$testdrive/error" -Value (`$_ | Out-String) + } + + `$null = Set-Content -Path "$testdrive/out" -Value `$out +"@ + + $pwsh = Start-Process -FilePath "${PSHOME}/pwsh" -WorkingDirectory $wd -ArgumentList @('-noprofile','-command',$script) + + Remove-Item -Path $wd -Force + Remove-Item $lock + $start = Get-Date + + try { + while ($null -eq (Get-Item "$testdrive/error" -ErrorAction Ignore) -and $null -eq (Get-Item "$testdrive/out" -ErrorAction Ignore)) { + if (((Get-Date) - $start).TotalSeconds -gt 60) { + throw "Timeout" + } + + Start-Sleep -Seconds 1 + } + } + finally { + $pwsh | Stop-Process -Force -ErrorAction Ignore + } + + $err = Get-Item -Path "$testdrive/error" -ErrorAction Ignore + $err | Should -BeNullOrEmpty -Because $err + $out = Get-Item -Path "$testdrive/out" -ErrorAction Ignore + $out | Should -Not -BeNullOrEmpty + } } Describe "Native Command Processor" -tags "Feature" { @@ -89,6 +145,10 @@ Describe "Native Command Processor" -tags "Feature" { } It "Should not block running Windows executables" -Skip:(!$IsWindows -or !(Get-Command notepad.exe)) { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "Needs investigation" + } + function FindNewNotepad { Get-Process -Name notepad -ErrorAction Ignore | Where-Object { $_.Id -NotIn $dontKill } @@ -141,7 +201,7 @@ Describe "Native Command Processor" -tags "Feature" { } } - It '$ErrorActionPreference does not apply to redirected stderr output' -Skip:(!$EnabledExperimentalFeatures.Contains('PSNotApplyErrorActionToStderr')) { + It '$ErrorActionPreference does not apply to redirected stderr output' { pwsh -noprofile -command '$ErrorActionPreference = ''Stop''; testexe -stderr stop 2>$null; ''hello''; $error; $?' | Should -BeExactly 'hello','True' } @@ -153,6 +213,12 @@ Describe "Native Command Processor" -tags "Feature" { Wait-UntilTrue -sb { (Get-Process mmc).Count -gt 0 } -TimeoutInMilliseconds 5000 -IntervalInMilliseconds 1000 | Should -BeTrue Get-Process mmc | Stop-Process } + + It 'Can redirect stdout and stderr to different files' { + testexe -stderrandout testing > $TestDrive/stdout.txt 2> $TestDrive/stderr.txt + Get-Content $TestDrive/stdout.txt | Should -Be testing + Get-Content $TestDrive/stderr.txt | Should -Be gnitset + } } Describe "Open a text file with NativeCommandProcessor" -tags @("Feature", "RequireAdminOnWindows") { @@ -246,3 +312,93 @@ Categories=Application; { $dllFile = "$PSHOME\System.Management.Automation.dll"; & $dllFile } | Should -Throw -ErrorId "NativeCommandFailed" } } + +Describe "Run native command from a mounted FAT-format VHD" -tags @("Feature", "RequireAdminOnWindows") { + BeforeAll { + if (-not $IsWindows) { + return; + } + else { + $storageModule = Get-Module -Name 'Storage' -ListAvailable -ErrorAction SilentlyContinue + + if (-not $storageModule) { + Write-Verbose -Verbose "Storage module is not available." + return; + } + } + + $vhdx = Join-Path -Path $TestDrive -ChildPath ncp.vhdx + + if (Test-Path -Path $vhdx) { + Remove-item -Path $vhdx -Force + } + + $create_vhdx = Join-Path -Path $TestDrive -ChildPath 'create_vhdx.txt' + + Set-Content -Path $create_vhdx -Force -Value @" + create vdisk file="$vhdx" maximum=20 type=fixed + select vdisk file="$vhdx" + attach vdisk + convert mbr + create partition primary + format fs=fat + assign letter="T" + detach vdisk +"@ + + diskpart.exe /s $create_vhdx + Mount-DiskImage -ImagePath $vhdx > $null + + Copy-Item "$env:WinDir\System32\whoami.exe" "T:\whoami.exe" + } + + AfterAll { + if ($IsWindows) { + $storageModule = Get-Module -Name 'Storage' -ListAvailable -ErrorAction SilentlyContinue + + if (-not $storageModule) { + Write-Verbose -Verbose "Storage module is not available." + return; + } + + Dismount-DiskImage -ImagePath $vhdx + Remove-Item $vhdx, $create_vhdx -Force + } + } + + It "Should run 'whoami.exe' from FAT file system without error" -Skip:(!$IsWindows) { + if ((Test-IsWinServer2012R2) -or (Test-IsWindows2016)) { + Set-ItResult -Pending -Because "Marking as pending since whomai.exe is not found on T:\ on 2012R2 and 2016 after copying to VHD" + return + } + + $expected = & "$env:WinDir\System32\whoami.exe" + $result = T:\whoami.exe + $result | Should -BeExactly $expected + } +} + +Describe "Native application invocation and getting cursor position" -Tags 'CI' { + It "Invoking a native application should not collect the cursor position" -Skip:($IsWindows) { + $expectCmd = Get-Command expect -Type Application -ErrorAction Ignore + $dateCmd = Get-Command date -Type Application -ErrorAction Ignore + # if date or expect are missing mark the test as pending + # test setup will need to ensure that these programs are present. + $missing = @() + if ($null -eq $expectCmd) { + $missing += "expect" + } + if ($null -eq $dateCmd) { + $missing += "date" + } + if ($missing.count -ne 0) { + $message = "missing command(s) {0}" -f ($missing -join ", ") + Set-ItResult -Pending -Because $message + } + + $powershell = Join-Path -Path $PSHOME -ChildPath "pwsh" + $commandString = "spawn $powershell -nopro -c /bin/date; expect eof" + [string]$result = expect -c $commandString + $result.IndexOf("`e[6n") | Should -Be -1 -Because $result.replace("`e","``e").replace("`u{7}","") + } +} diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 index 59702938375..53ed45fe4da 100644 --- a/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 +++ b/test/powershell/Language/Scripting/NativeExecution/NativeStreams.Tests.ps1 @@ -12,9 +12,9 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' { $error.Clear() $command = [string]::Join('', @( - '[Console]::Error.Write(\"foo`n`nbar`n`nbaz\"); ', - '[Console]::Error.Write(\"middle\"); ', - '[Console]::Error.Write(\"foo`n`nbar`n`nbaz\")' + '[Console]::Error.Write("foo`n`nbar`n`nbaz"); ', + '[Console]::Error.Write("middle"); ', + '[Console]::Error.Write("foo`n`nbar`n`nbaz")' )) $out = & $powershell -noprofile -command $command 2>&1 @@ -53,7 +53,11 @@ Describe "Native streams behavior with PowerShell" -Tags 'CI' { ($out | Out-String).Replace("`r", '') | Should -BeExactly "foo`n`nbar`n`nbazmiddlefoo`n`nbar`n`nbaz`n" } - It 'does not get truncated or split when redirected' { + It 'Does not get truncated or split when redirected' { + if (Test-IsWindowsArm64) { + Set-ItResult -Pending -Because "IOException: The handle is invalid." + } + $longtext = "0123456789" while ($longtext.Length -lt [console]::WindowWidth) { $longtext += $longtext diff --git a/test/powershell/Language/Scripting/NativeExecution/NativeWindowsTildeExpansion.Tests.ps1 b/test/powershell/Language/Scripting/NativeExecution/NativeWindowsTildeExpansion.Tests.ps1 new file mode 100644 index 00000000000..3a478607c08 --- /dev/null +++ b/test/powershell/Language/Scripting/NativeExecution/NativeWindowsTildeExpansion.Tests.ps1 @@ -0,0 +1,32 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'Native Windows tilde expansion tests' -tags "CI" { + BeforeAll { + $originalDefaultParams = $PSDefaultParameterValues.Clone() + $PSDefaultParameterValues["it:skip"] = -Not $IsWindows + } + + AfterAll { + $global:PSDefaultParameterValues = $originalDefaultParams + } + + # Test ~ expansion + It 'Tilde should be replaced by the filesystem provider home directory' { + cmd /c echo ~ | Should -BeExactly ($ExecutionContext.SessionState.Provider.Get("FileSystem").Home) + } + # Test ~ expansion with a path fragment (e.g. ~/foo) + It '~/foo should be replaced by the /foo' { + cmd /c echo ~/foo | Should -BeExactly "$($ExecutionContext.SessionState.Provider.Get("FileSystem").Home)/foo" + cmd /c echo ~\foo | Should -BeExactly "$($ExecutionContext.SessionState.Provider.Get("FileSystem").Home)\foo" + } + + It '~ should not be replaced when quoted' { + cmd /c echo '~' | Should -BeExactly '~' + cmd /c echo "~" | Should -BeExactly '~' + cmd /c echo '~/foo' | Should -BeExactly '~/foo' + cmd /c echo "~/foo" | Should -BeExactly '~/foo' + cmd /c echo '~\foo' | Should -BeExactly '~\foo' + cmd /c echo "~\foo" | Should -BeExactly '~\foo' + } +} diff --git a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 index 95d62071ad1..8177adab219 100644 --- a/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 +++ b/test/powershell/Language/Scripting/ParameterBinding.Tests.ps1 @@ -170,6 +170,19 @@ Describe "Tests for parameter binding" -Tags "CI" { ( get-foo -b b a c d ) -join ',' | Should -BeExactly 'a,c,d' } + It 'Too many parameter sets defined' { + $scriptblock = { + param($numSets=1) + $parameters = (1..($numSets) | ForEach-Object { "[Parameter(parametersetname='set$_')]`$a$_" }) -join ', ' + $body = "param($parameters) 'working'" + $sb = [scriptblock]::Create($body) + & $sb -a1 123 + } + + & $scriptblock -numSets 32 | Should -Be 'working' + { & $scriptblock -numSets 33 } | Should -Throw -ErrorId 'ParsingTooManyParameterSets' + } + It 'Default parameter set with value from remaining arguments case 1' { function get-foo { diff --git a/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 b/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 new file mode 100644 index 00000000000..04993c80a9f --- /dev/null +++ b/test/powershell/Language/Scripting/PipelineBehaviour.Tests.ps1 @@ -0,0 +1,625 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +Describe 'Function Pipeline Behaviour' -Tag 'CI' { + + BeforeAll { + $filePath = "$TestDrive\output.txt" + if (Test-Path $filePath) { + Remove-Item $filePath -Force + } + } + + Context "'Clean' block runs when any other named blocks run" { + + AfterEach { + if (Test-Path $filePath) { + Remove-Item $filePath -Force + } + } + + It "'Clean' block executes only if at least one of the other named blocks executed" { + ## The 'Clean' block is for cleanup purpose. When none of other named blocks execute, + ## there is no point to execute the 'Clean' block, so it will be skipped in this case. + function test-1 { + clean { 'clean-redirected-output' > $filePath } + } + + function test-2 { + End { 'end' } + clean { 'clean-redirected-output' > $filePath } + } + + ## The 'Clean' block is skipped. + test-1 | Should -BeNullOrEmpty + Test-Path -Path $filePath | Should -BeFalse + + ## The 'Clean' block runs. + test-2 | Should -BeExactly 'end' + Test-Path -Path $filePath | Should -BeTrue + Get-Content $filePath | Should -BeExactly 'clean-redirected-output' + } + + It "'Clean' block is skipped when the command doesn't run due to no input from upstream command" { + function test-1 ([switch] $WriteOutput) { + Process { + if ($WriteOutput) { + Write-Output 'process' + } else { + Write-Verbose -Verbose 'process' + } + } + } + + function test-2 { + Process { Write-Output "test-2: $_" } + clean { Write-Warning 'test-2-clean-warning' } + } + + ## No output from 'test-1.Process', so 'test-2.Process' didn't run, and thus 'test-2.Clean' was skipped. + test-1 | test-2 *>&1 | Should -BeNullOrEmpty + + ## Output from 'test-1.Process' would trigger 'test-2.Process' to run, and thus 'test-2.Clean' would run. + $output = test-1 -WriteOutput | test-2 *>&1 + $output | Should -Be @('test-2: process', 'test-2-clean-warning') + } + + It "'Clean' block is skipped when the command doesn't run due to terminating error from upstream Process block" { + function test-1 ([switch] $ThrowException) { + Process { + if ($ThrowException) { + throw 'process' + } else { + Write-Output 'process' + } + } + } + + function test-2 { + Process { Write-Output "test-2: $_" } + clean { 'clean-redirected-output' > $filePath } + } + + $failure = $null + try { test-1 -ThrowException | test-2 } catch { $failure = $_ } + $failure | Should -Not -BeNullOrEmpty + $failure.Exception.Message | Should -BeExactly 'process' + ## 'test-2' didn't run because 'test-1' throws terminating exception, so 'test-2.Clean' didn't run either. + Test-Path -Path $filePath | Should -BeFalse + + test-1 | test-2 | Should -BeExactly 'test-2: process' + Test-Path -Path $filePath | Should -BeTrue + Get-Content $filePath | Should -BeExactly 'clean-redirected-output' + } + + It "'Clean' block is skipped when the command doesn't run due to terminating error from upstream Begin block" { + function test-1 { + Begin { throw 'begin' } + End { 'end' } + } + + function test-2 { + Begin { 'begin' } + Process { Write-Output "test-2: $_" } + clean { 'clean-redirected-output' > $filePath } + } + + $failure = $null + try { test-1 | test-2 } catch { $failure = $_ } + $failure | Should -Not -BeNullOrEmpty + $failure.Exception.Message | Should -BeExactly 'begin' + ## 'test-2' didn't run because 'test-1' throws terminating exception, so 'test-2.Clean' didn't run either. + Test-Path -Path $filePath | Should -BeFalse + } + + It "'Clean' block runs when '' runs" -TestCases @( + @{ Script = { [CmdletBinding()]param() begin { 'output' } clean { Write-Warning 'clean-warning' } }; BlockName = 'Begin' } + @{ Script = { [CmdletBinding()]param() process { 'output' } clean { Write-Warning 'clean-warning' } }; BlockName = 'Process' } + @{ Script = { [CmdletBinding()]param() end { 'output' } clean { Write-Warning 'clean-warning' } }; BlockName = 'End' } + ) { + param($Script, $BlockName) + + & $Script -WarningVariable wv | Should -BeExactly 'output' + $wv | Should -BeExactly 'clean-warning' + } + + It "'Clean' block runs when '' throws terminating error" -TestCases @( + @{ Script = { [CmdletBinding()]param() begin { throw 'failure' } clean { Write-Warning 'clean-warning' } }; BlockName = 'Begin' } + @{ Script = { [CmdletBinding()]param() process { throw 'failure' } clean { Write-Warning 'clean-warning' } }; BlockName = 'Process' } + @{ Script = { [CmdletBinding()]param() end { throw 'failure' } clean { Write-Warning 'clean-warning' } }; BlockName = 'End' } + ) { + param($Script, $BlockName) + + $failure = $null + try { & $Script -WarningVariable wv } catch { $failure = $_ } + $failure | Should -Not -BeNullOrEmpty + $failure.Exception.Message | Should -BeExactly 'failure' + $wv | Should -BeExactly 'clean-warning' + } + + It "'Clean' block runs in pipeline - simple function" { + function test-1 { + param([switch] $EmitError) + process { + if ($EmitError) { + throw 'test-1-process-error' + } else { + Write-Output 'test-1' + } + } + + clean { 'test-1-clean' >> $filePath } + } + + function test-2 { + begin { Write-Verbose -Verbose 'test-2-begin' } + process { $_ } + clean { 'test-2-clean' >> $filePath } + } + + function test-3 { + end { Write-Verbose -Verbose 'test-3-end' } + clean { 'test-3-clean' >> $filePath } + } + + ## All command will run, so all 'Clean' blocks will run + test-1 | test-2 | test-3 + Test-Path $filePath | Should -BeTrue + $content = Get-Content $filePath + $content | Should -Be @('test-1-clean', 'test-2-clean', 'test-3-clean') + + $failure = $null + Remove-Item $filePath -Force + try { + test-1 -EmitError | test-2 | test-3 + } catch { + $failure = $_ + } + + ## Exception is thrown from 'test-1.Process'. By that time, the 'test-2.Begin' has run, + ## so 'test-2.Clean' will run. However, 'test-3.End' won't run, so 'test-3.Clean' won't run. + $failure | Should -Not -BeNullOrEmpty + $failure.Exception.Message | Should -BeExactly 'test-1-process-error' + Test-Path $filePath | Should -BeTrue + $content = Get-Content $filePath + $content | Should -Be @('test-1-clean', 'test-2-clean') + } + + It "'Clean' block runs in pipeline - advanced function" { + function test-1 { + [CmdletBinding()] + param([switch] $EmitError) + process { + if ($EmitError) { + throw 'test-1-process-error' + } else { + Write-Output 'test-1' + } + } + + clean { 'test-1-clean' >> $filePath } + } + + function test-2 { + [CmdletBinding()] + param( + [Parameter(ValueFromPipeline)] + $pipeInput + ) + + begin { Write-Verbose -Verbose 'test-2-begin' } + process { $pipeInput } + clean { 'test-2-clean' >> $filePath } + } + + function test-3 { + [CmdletBinding()] + param( + [Parameter(ValueFromPipeline)] + $pipeInput + ) + + end { Write-Verbose -Verbose 'test-3-end' } + clean { 'test-3-clean' >> $filePath } + } + + ## All command will run, so all 'Clean' blocks will run + test-1 | test-2 | test-3 + Test-Path $filePath | Should -BeTrue + $content = Get-Content $filePath + $content | Should -Be @('test-1-clean', 'test-2-clean', 'test-3-clean') + + + $failure = $null + Remove-Item $filePath -Force + ## Exception will be thrown from 'test-1.Process'. By that time, the 'test-2.Begin' has run, + ## so 'test-2.Clean' will run. However, 'test-3.End' won't run, so 'test-3.Clean' won't run. + try { + test-1 -EmitError | test-2 | test-3 + } catch { + $failure = $_ + } + $failure | Should -Not -BeNullOrEmpty + $failure.Exception.Message | Should -BeExactly 'test-1-process-error' + Test-Path $filePath | Should -BeTrue + $content = Get-Content $filePath + $content | Should -Be @('test-1-clean', 'test-2-clean') + } + + It 'does not execute End {} if the pipeline is halted during Process {}' { + # We don't need Should -Not -Throw as if this reaches end{} and throws the test will fail anyway. + 1..10 | + & { + begin { "BEGIN" } + process { "PROCESS $_" } + end { "END"; throw "This should not be reached." } + } | + Select-Object -First 3 | + Should -Be @( "BEGIN", "PROCESS 1", "PROCESS 2" ) + } + + It "still executes 'Clean' block if the pipeline is halted" { + 1..10 | + & { + process { $_ } + clean { "Clean block hit" > $filePath } + } | + Select-Object -First 1 | + Should -Be 1 + + Test-Path $filePath | Should -BeTrue + Get-Content $filePath | Should -BeExactly 'Clean block hit' + } + + It "Select-Object in pipeline" { + function bar { + process { 'bar_' + $_ } end { 'bar_end' } clean { 'bar_clean' > $filePath } + } + + function zoo { + process { 'zoo_' + $_ } end { 'zoo_end' } clean { 'zoo_clean' >> $filePath } + } + + 1..10 | bar | Select-Object -First 2 | zoo | Should -Be @('zoo_bar_1', 'zoo_bar_2', 'zoo_end') + Test-Path $filePath | Should -BeTrue + $content = Get-Content $filePath + $content | Should -Be @('bar_clean', 'zoo_clean') + } + } + + Context 'Streams from Named Blocks' { + + It 'Permits output from named block: